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
Domain: github.com
{"@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-profiling | 0 |
| react-import-map | react,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-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:14ad103a-5354-611d-5f16-b68e5c3c5db1 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | E9A0:296654:142F32C:1AF6FCE:6B012DB8 |
| html-safe-nonce | d3bd132e40fdd7e54d714b297465d1a96bf20c1d692df1925cf2493e007cf1b6 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJFOUEwOjI5NjY1NDoxNDJGMzJDOjFBRjZGQ0U6NkIwMTJEQjgiLCJ2aXNpdG9yX2lkIjoiMzMzNDQ0NjEyODg4NzMxMTgwMCIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | 6b9855552a9a897b055b25f9a5586ca8f974e76117d4071376760c5c6f78fef2 |
| hovercard-subject-tag | issue:5064197173 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/modelcontextprotocol/python-sdk/3250/issue_layout |
| twitter:image | https://opengraph.githubassets.com/5d2963f1e210213dfb2740f3338b869a3a43b24dae154d30887ae1d989956818/modelcontextprotocol/python-sdk/issues/3250 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/5d2963f1e210213dfb2740f3338b869a3a43b24dae154d30887ae1d989956818/modelcontextprotocol/python-sdk/issues/3250 |
| og:image:alt | 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 ... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | draesthetic |
| hostname | github.com |
| expected-hostname | github.com |
| None | cc5dfdd32f62ebd3223cab3af3aa2b268d3605218237326a48a99d1efd89495c |
| turbo-cache-control | no-preview |
| go-import | github.com/modelcontextprotocol/python-sdk git https://github.com/modelcontextprotocol/python-sdk.git |
| octolytics-dimension-user_id | 182288589 |
| octolytics-dimension-user_login | modelcontextprotocol |
| octolytics-dimension-repository_id | 862584018 |
| octolytics-dimension-repository_nwo | modelcontextprotocol/python-sdk |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 862584018 |
| octolytics-dimension-repository_network_root_nwo | modelcontextprotocol/python-sdk |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 8c77c9e8439031ad54c75a250694842892f693e1 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width