René's URL Explorer Experiment


Title: OAuthClientProvider._initialize() breaks transparent refresh: missing update_token_expiry + missing oauth_metadata load · Issue #3250 · modelcontextprotocol/python-sdk · GitHub

Open Graph Title: OAuthClientProvider._initialize() breaks transparent refresh: missing update_token_expiry + missing oauth_metadata load · Issue #3250 · modelcontextprotocol/python-sdk

X Title: OAuthClientProvider._initialize() breaks transparent refresh: missing update_token_expiry + missing oauth_metadata load · Issue #3250 · modelcontextprotocol/python-sdk

Description: Two bugs in OAuthClientProvider._initialize() combine to break transparent token refresh Summary When a client process restarts (or any time OAuthClientProvider is reconstructed), the SDK fails to transparently refresh expired access_tok...

Open Graph Description: Two bugs in OAuthClientProvider._initialize() combine to break transparent token refresh Summary When a client process restarts (or any time OAuthClientProvider is reconstructed), the SDK fails to ...

X Description: Two bugs in OAuthClientProvider._initialize() combine to break transparent token refresh Summary When a client process restarts (or any time OAuthClientProvider is reconstructed), the SDK fails to ...

Opengraph URL: https://github.com/modelcontextprotocol/python-sdk/issues/3250

X: @github

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"OAuthClientProvider._initialize() breaks transparent refresh: missing update_token_expiry + missing oauth_metadata load","articleBody":"## Two bugs in `OAuthClientProvider._initialize()` combine to break transparent token refresh\n\n### Summary\n\nWhen a client process restarts (or any time `OAuthClientProvider` is reconstructed), the SDK fails to transparently refresh expired access_tokens even when a valid `refresh_token` is on disk and the IdP would happily exchange it. Users are forced through an interactive OAuth re-auth on every process restart — even when the refresh_token is still valid for up to 15 days per the IdP's policy.\n\nThis affects every MCP server that issues short-lived access_tokens (~15 min) with longer-lived refresh_tokens — Fold MCP, Notion, GitHub PAT-rotated OAuth, any Hydra-style server, etc. — i.e. **the entire modern OAuth ecosystem**. The symptom is indistinguishable from the server revoking the refresh_token.\n\n### Bug 1: `_initialize()` doesn't compute `token_expiry_time`\n\n`_initialize()` loads `current_tokens` from storage but never calls `context.update_token_expiry(token)`. So `context.token_expiry_time` stays `None`.\n\nThen `is_token_valid()`:\n\n```python\ndef is_token_valid(self) -> bool:\n    return bool(\n        self.current_tokens\n        and self.current_tokens.access_token\n        and (not self.token_expiry_time or time.time() \u003c= self.token_expiry_time)\n    )\n```\n\nWhen `token_expiry_time is None`, the second clause is `not None or …` = `True`, so the function **unconditionally returns True** regardless of whether the access_token is expired by 1 second or 1 hour.\n\nThe refresh-on-expiry guard in `async_auth_flow`:\n\n```python\nif not self.context.is_token_valid() and self.context.can_refresh_token():\n    refresh_request = await self._refresh_token()\n    …\n```\n\n…never fires. Expired access_tokens are sent on every request, the server returns 401, and the user lands in the full-re-auth branch (`async_auth_flow` lines 514+) which forces interactive login.\n\nThis same fix is **already applied on the write path**: `set_tokens()` (the function called after a successful refresh) **does** call `update_token_expiry()`, and there's even a comment in `set_tokens` referencing \"Fix A … OAuthTokens.expiresAt persistence\" that describes the pattern. The read path (`_initialize`) just doesn't do the same thing.\n\n### Bug 2: `_refresh_token()` builds the wrong endpoint URL when `oauth_metadata` isn't loaded\n\n`_refresh_token()` picks the token endpoint like this:\n\n```python\nif self.context.oauth_metadata and self.context.oauth_metadata.token_endpoint:\n    token_url = str(self.context.oauth_metadata.token_endpoint)  # pragma: no cover\nelse:\n    auth_base_url = self.context.get_authorization_base_url(self.context.server_url)\n    token_url = urljoin(auth_base_url, \"/token\")\n```\n\nFor a server like `https://mcp.fold.money/mcp`, the fallback path produces `https://mcp.fold.money/token` — **404**. The correct endpoint for Hydra-style servers is `https://mcp.fold.money/oauth/token`.\n\n`oauth_metadata` is normally populated via server discovery during the 401-handling flow (after a 401). But the refresh-on-expiry path runs **before** any 401 — it proactively refreshes when the token is expired, with no 401 yet. So `oauth_metadata` is never populated, and refresh fails silently with 404. The user then sees the 401 → re-auth loop as if the refresh_token itself were invalid.\n\nThe fix is for `_initialize()` to also load `oauth_metadata` from storage (e.g., via `storage.load_oauth_metadata()`, which the reference `HermesTokenStorage` implementation already provides).\n\n### Reproduction\n\nAny MCP client using `OAuthClientProvider` against an IdP with ~15 min access_tokens and a Hydra-style token endpoint.\n\n```python\nimport asyncio, httpx\nfrom mcp.client.auth.oauth2 import OAuthClientProvider\nfrom mcp.shared.auth import OAuthClientMetadata, OAuthToken, OAuthClientInformationFull\n\n# Suppose these came from persistent storage (Hermes's HermesTokenStorage\n# or any conforming storage impl):\nclient_info = OAuthClientInformationFull.model_validate(client_info_dict)\ncurrent_tokens = OAuthToken.model_validate({\n    \"access_token\": \"...\", \"token_type\": \"Bearer\", \"expires_in\": 900,\n    \"refresh_token\": \"...\", \"scope\": \"mcp:read\",\n})\n\nclass _Storage:\n    async def get_tokens(self): return current_tokens\n    async def set_tokens(self, t): current_tokens = t  # in-memory for repro\n    async def get_client_info(self): return client_info\n\nprovider = OAuthClientProvider(\n    server_url=\"https://mcp.fold.money/mcp\",\n    client_metadata=OAuthClientMetadata(...),\n    storage=_Storage(),\n)\nawait provider._initialize()\nprint(provider.context.is_token_valid())  # → True, even if access_token is expired\nprint(provider.context.token_expiry_time) # → None (Bug 1)\n\n# Now suppose we manually trigger the refresh (mimicking async_auth_flow):\nimport time\n# Force expires_in = 0 in the loaded token (the way HermesTokenStorage does it):\n# …\n\n# Refresh URL points to /token, not /oauth/token (Bug 2):\nreq = await provider._refresh_token()\nprint(req.url)  # → \"https://mcp.fold.money/token\" (404), not \"/oauth/token\"\n```\n\n### Fix\n\nIn `src/mcp/client/auth/oauth2.py`, modify `OAuthClientProvider._initialize()`:\n\n```python\nasync def _initialize(self) -> None:\n    \"\"\"Load stored tokens and client info.\"\"\"\n    import asyncio as _asyncio\n    self.context.current_tokens = await self.context.storage.get_tokens()\n    self.context.client_info = await self.context.storage.get_client_info()\n    # Fix bug 1: compute absolute expiry from the loaded token's\n    # `expires_in`, mirroring what set_tokens() does on the write path.\n    if self.context.current_tokens is not None:\n        self.context.update_token_expiry(self.context.current_tokens)\n    # Fix bug 2: load oauth_metadata if the storage supports it, so\n    # _refresh_token() can find the correct token_endpoint without\n    # having to wait for server discovery.\n    loader = getattr(self.context.storage, \"load_oauth_metadata\", None)\n    if callable(loader):\n        try:\n            meta = loader()\n            if _asyncio.iscoroutine(meta):\n                meta = await meta\n            if meta is not None:\n                self.context.oauth_metadata = meta  # type: ignore[assignment]\n        except Exception:\n            pass\n    self._initialized = True\n```\n\nThe reference storage (`HermesTokenStorage` in some downstream clients like `hermes-agent`) already implements `load_oauth_metadata()` returning `OAuthMetadata.model_validate(\u003ccontents of {server}.meta.json>)`. For SDK-provided storage classes that don't yet implement this, the `getattr` guard makes the second fix a no-op — bug 2 only manifests for downstream storage classes that already populate `.meta.json`.\n\n### Live verification\n\nPatched locally against `mcp==1.28.1` on macOS (Hermes agent 0.20.0). 16-minute live repro against `https://mcp.fold.money`:\n\n1. Login via OAuth → fresh token, mtime T0.\n2. Wait 15 min past access_token expiry → token on disk is stale, mtime still T0 (SDK never touched file).\n3. Make MCP call with forced-expired access_token + fresh refresh_token.\n4. **Without the fix**: SDK sends expired token, gets 401, falls through to re-auth (browser prompt).\n5. **With the fix**: SDK calls `https://mcp.fold.money/oauth/token` with `grant_type=refresh_token`, gets HTTP 200 with fresh rotated pair, writes back to disk. MCP call returns real data (verified: `get_total_balance` → ₹146,656.35 across 4 accounts).\n\n### AI disclosure\n\nDrafted with AI assistance (GPT-class model). The bug analysis, code path tracing, fix design, and live verification were all done by a human reviewer who understood every line. The fix itself is 12 lines, two of which mirror the existing `set_tokens` write-path logic.","author":{"url":"https://github.com/draesthetic","@type":"Person","name":"draesthetic"},"datePublished":"2026-08-04T19:35:00Z","url":"https://github.com/modelcontextprotocol/python-sdk/issues/3250"}

react-profiling0
react-import-mapreact,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322
route-pattern/_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format)
route-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:14ad103a-5354-611d-5f16-b68e5c3c5db1
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-idE9A0:296654:142F32C:1AF6FCE:6B012DB8
html-safe-nonced3bd132e40fdd7e54d714b297465d1a96bf20c1d692df1925cf2493e007cf1b6
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJFOUEwOjI5NjY1NDoxNDJGMzJDOjFBRjZGQ0U6NkIwMTJEQjgiLCJ2aXNpdG9yX2lkIjoiMzMzNDQ0NjEyODg4NzMxMTgwMCIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9
visitor-hmac6b9855552a9a897b055b25f9a5586ca8f974e76117d4071376760c5c6f78fef2
hovercard-subject-tagissue:5064197173
github-keyboard-shortcutsrepository,issues,copilot
google-site-verificationApib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I
octolytics-urlhttps://collector.github.com/github/collect
analytics-location///voltron/issues_fragments/issue_layout
fb:app_id1401488693436528
apple-itunes-appapp-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/modelcontextprotocol/python-sdk/3250/issue_layout
twitter:imagehttps://opengraph.githubassets.com/5d2963f1e210213dfb2740f3338b869a3a43b24dae154d30887ae1d989956818/modelcontextprotocol/python-sdk/issues/3250
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/5d2963f1e210213dfb2740f3338b869a3a43b24dae154d30887ae1d989956818/modelcontextprotocol/python-sdk/issues/3250
og:image:altTwo bugs in OAuthClientProvider._initialize() combine to break transparent token refresh Summary When a client process restarts (or any time OAuthClientProvider is reconstructed), the SDK fails to ...
og:image:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernamedraesthetic
hostnamegithub.com
expected-hostnamegithub.com
Nonecc5dfdd32f62ebd3223cab3af3aa2b268d3605218237326a48a99d1efd89495c
turbo-cache-controlno-preview
go-importgithub.com/modelcontextprotocol/python-sdk git https://github.com/modelcontextprotocol/python-sdk.git
octolytics-dimension-user_id182288589
octolytics-dimension-user_loginmodelcontextprotocol
octolytics-dimension-repository_id862584018
octolytics-dimension-repository_nwomodelcontextprotocol/python-sdk
octolytics-dimension-repository_publictrue
octolytics-dimension-repository_is_forkfalse
octolytics-dimension-repository_network_root_id862584018
octolytics-dimension-repository_network_root_nwomodelcontextprotocol/python-sdk
turbo-body-classeslogged-out env-production page-responsive
disable-turbofalse
browser-stats-urlhttps://api.github.com/_private/browser/stats
browser-errors-urlhttps://api.github.com/_private/browser/errors
release8c77c9e8439031ad54c75a250694842892f693e1
ui-targetfull
theme-color#1e2327
color-schemelight dark
react-app-nameissues

Links:

Skip to contenthttps://github.com/modelcontextprotocol/python-sdk/issues/3250#start-of-content
https://github.com/
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fmodelcontextprotocol%2Fpython-sdk%2Fissues%2F3250
GitHubRepository hosting, code review, and collaborationhttps://github.com/platform
CopilotAI coding agent for tasks, projects, and automated workhttps://github.com/features/copilot
ActionsCI/CD and automationhttps://github.com/features/actions
Code QualityQuality analysis, fixes, and enforcementhttps://github.com/features/code-quality
CodespacesCloud development environmentshttps://github.com/features/codespaces
Code SecurityVulnerability detection and remediationhttps://github.com/security/advanced-security/code-security
Secret ProtectionSecret scanning and leak preventionhttps://github.com/security/advanced-security/secret-protection
All Featureshttps://github.com/features
Documentationhttps://docs.github.com/en
Traininghttps://learn.github.com/skills
Certificationshttps://learn.github.com/credentials
Build with Copilothttps://github.com/features/ai
Customize Copilothttps://docs.github.com/en/copilot/how-tos/copilot-on-github/customize-copilot/customize-copilot-overview
Integrationshttps://github.com/marketplace
Trending reposhttps://github.com/trending
GitHub Sponsorshttps://github.com/open-source/sponsors
Developer articleshttps://github.com/resources/articles
ChangelogYour source for the latest features, improvements, and fixes across GitHub products, all in one place.https://github.blog/changelog/
Enterpriseshttps://github.com/enterprise
Teamhttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
Healthcarehttps://github.com/solutions/industry/healthcare
Financial serviceshttps://github.com/solutions/industry/financial-services
Manufacturinghttps://github.com/solutions/industry/manufacturing
Governmenthttps://github.com/solutions/industry/government
See all industrieshttps://github.com/solutions/industry
Why GitHubhttps://github.com/why-github
Customer Storieshttps://github.com/customer-stories
Business insightshttps://github.com/solutions/executive-insights
Trust Centerhttps://github.com/trust-center
GitHub Advanced SecurityEnterprise-grade code securityhttps://github.com/security/advanced-security
Copilot for businessEnterprise-grade AI featureshttps://github.com/features/copilot/copilot-business
Premium SupportEnterprise-grade 24/7 supporthttps://github.com/enterprise/premium-support
Documentationhttps://docs.github.com/en
Resource centerhttps://github.com/resources
Bloghttps://github.blog/
Events & webinarshttps://github.com/resources/events
Community Forumhttps://github.com/orgs/community/discussions
Customer Storieshttps://github.com/customer-stories
Integrationshttps://github.com/marketplace
Customer supporthttps://help.github.com/
Traininghttps://learn.github.com/skills
GitHub Statushttps://www.githubstatus.com/
Abouthttps://github.com/about
Partnershttps://github.com/partners
Changeloghttps://github.blog/changelog/
GitHub UniverseThe event for developers, by developers — talks, workshops, and what’s next for GitHub.https://githubuniverse.com/
Pricinghttps://github.com/pricing
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fmodelcontextprotocol%2Fpython-sdk%2Fissues%2F3250
Sign uphttps://github.com/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-name%3E%2F%3Crepo-name%3E%2Fvoltron%2Fissues_fragments%2Fissue_layout&source=header-repo&source_repo=modelcontextprotocol%2Fpython-sdk
Reloadhttps://github.com/modelcontextprotocol/python-sdk/issues/3250
Reloadhttps://github.com/modelcontextprotocol/python-sdk/issues/3250
Reloadhttps://github.com/modelcontextprotocol/python-sdk/issues/3250
modelcontextprotocolhttps://github.com/modelcontextprotocol
python-sdkhttps://github.com/modelcontextprotocol/python-sdk
Codehttps://github.com/modelcontextprotocol/python-sdk
Issues315 (315)https://github.com/modelcontextprotocol/python-sdk/issues
Pull requests112 (112)https://github.com/modelcontextprotocol/python-sdk/pulls
Actionshttps://github.com/modelcontextprotocol/python-sdk/actions
Projectshttps://github.com/modelcontextprotocol/python-sdk/projects
Security and quality12 (12)https://github.com/modelcontextprotocol/python-sdk/security
Insightshttps://github.com/modelcontextprotocol/python-sdk/insights
https://github.com/modelcontextprotocol/python-sdk
New issuehttps://github.com/login?return_to=https://github.com/modelcontextprotocol/python-sdk/issues/3250
New issuehttps://github.com/login?return_to=https://github.com/modelcontextprotocol/python-sdk/issues/3250
#3263https://github.com/modelcontextprotocol/python-sdk/pull/3263
OAuthClientProvider._initialize() breaks transparent refresh: missing update_token_expiry + missing oauth_metadata loadhttps://github.com/modelcontextprotocol/python-sdk/issues/3250#top
#3263https://github.com/modelcontextprotocol/python-sdk/pull/3263
P1Significant bug affecting many users, highly requested featurehttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22P1%22
bugSomething isn't workinghttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22bug%22
v1Affects the v1.x maintenance linehttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22v1%22
v2Affects the v2 line (2.x on main)https://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22v2%22
https://github.com/draesthetic
draesthetichttps://github.com/draesthetic
on Aug 4, 2026https://github.com/modelcontextprotocol/python-sdk/issues/3250#issue-5064197173
maxisbeyhttps://github.com/maxisbey
v2Affects the v2 line (2.x on main)https://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22v2%22
P3Nice to haves, rare edge caseshttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22P3%22
P1Significant bug affecting many users, highly requested featurehttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22P1%22
P3Nice to haves, rare edge caseshttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22P3%22
on Aug 11, 2026https://github.com/modelcontextprotocol/python-sdk/issues/3250#event-29288238275
maxisbeyhttps://github.com/maxisbey
on Aug 18, 2026https://github.com/modelcontextprotocol/python-sdk/issues/3250#event-29619254368
OAuth client: refresh before re-authorizing, and discover before refr…https://github.com/modelcontextprotocol/python-sdk/commit/2bc618ab6de57dcb6ae08181d2e40ddd77cdd49a
2bc618ahttps://github.com/modelcontextprotocol/python-sdk/commit/2bc618ab6de57dcb6ae08181d2e40ddd77cdd49a
maxisbeyhttps://github.com/maxisbey
v1Affects the v1.x maintenance linehttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22v1%22
on Aug 18, 2026https://github.com/modelcontextprotocol/python-sdk/issues/3250#event-29625156021
claudehttps://github.com/apps/claude
bugSomething isn't workinghttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22bug%22
on Oct 8, 2026https://github.com/modelcontextprotocol/python-sdk/issues/3250#event-32781077085
https://github.com/finly-ai-dev
finly-ai-devhttps://github.com/finly-ai-dev
on Oct 11, 2026https://github.com/modelcontextprotocol/python-sdk/issues/3250#issuecomment-6109304114
Sign up for freehttps://github.com/signup?return_to=https://github.com/modelcontextprotocol/python-sdk/issues/3250
Sign in to commenthttps://github.com/login?return_to=https://github.com/modelcontextprotocol/python-sdk/issues/3250
P1Significant bug affecting many users, highly requested featurehttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22P1%22
bugSomething isn't workinghttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22bug%22
v1Affects the v1.x maintenance linehttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22v1%22
v2Affects the v2 line (2.x on main)https://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22v2%22
https://github.com
Termshttps://docs.github.com/site-policy/github-terms/github-terms-of-service
Privacyhttps://docs.github.com/site-policy/privacy-policies/github-privacy-statement
Securityhttps://github.com/security
Statushttps://www.githubstatus.com/
Communityhttps://github.community/
Docshttps://docs.github.com/
Contacthttps://support.github.com?tags=dotcom-footer

Viewport: width=device-width


URLs of crawlers that visited me.