Title: Clients Using Storage Face Deadlock on Token Refresh for SSE · Issue #1326 · modelcontextprotocol/python-sdk · GitHub
Open Graph Title: Clients Using Storage Face Deadlock on Token Refresh for SSE · Issue #1326 · modelcontextprotocol/python-sdk
X Title: Clients Using Storage Face Deadlock on Token Refresh for SSE · Issue #1326 · modelcontextprotocol/python-sdk
Description: Initial Checks I confirm that I'm using the latest version of MCP Python SDK I confirm that I searched for my issue in https://github.com/modelcontextprotocol/python-sdk/issues before opening this issue Description tldr: in calls to an S...
Open Graph Description: Initial Checks I confirm that I'm using the latest version of MCP Python SDK I confirm that I searched for my issue in https://github.com/modelcontextprotocol/python-sdk/issues before opening this ...
X Description: Initial Checks I confirm that I'm using the latest version of MCP Python SDK I confirm that I searched for my issue in https://github.com/modelcontextprotocol/python-sdk/issues before opening t...
Opengraph URL: https://github.com/modelcontextprotocol/python-sdk/issues/1326
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Clients Using Storage Face Deadlock on Token Refresh for SSE","articleBody":"### Initial Checks\n\n- [x] I confirm that I'm using the latest version of MCP Python SDK\n- [x] I confirm that I searched for my issue in https://github.com/modelcontextprotocol/python-sdk/issues before opening this issue\n\n### Description\n\n#### tldr: in calls to an SSE server (like Atlassian) there is an infinite hang druing a request, caused by a deadlock; the deadlock occurs when token refresh yields a request in the middle of the client.stream method that is trying to monitor SSE events, not field requests\n\n### Resulting Behavior - After tokens expire or after a new instance is re-built from storage, the SSE server will not work until full token-clearing and re-auth\n\nAs long as a token refresh attempt is not made, the server will work. \n\nThere are two circumstances when a refresh attempt is made, causing the SSE call to hang:\n1. Tokens expire during a working SSE session\n2. When a Client uses a stale token from storage\n\n### Source of failure for each scenario\n\n**Failure Mode**\n1. `OAuthClientProvider` lazy loads and is passed into `aconnect_sse()` without having checked refresh\n2. The `OAuthClientProvider.async_auth_flow()` generator enters the refresh logic\n3. It yields a refresh request and waits for a response (line ~544 in auth.py)\n4. `aconnect_sse()` uses `client.stream()` which is trying to open an SSE connection\n5. There's no response mechanism - SSE expects to start streaming events, not handle a token refresh request\n6. DEADLOCK: Auth generator waiting for refresh response that will never come\n\n**Temporary Success**\n- First request in `aconnect_sse()` uses `client.stream()` yield 401 which sends everything back out of the SSE context\n- `OAuthClientProvider` is able to perform full re-auth\n- When next sent to `aconnect_sse()` fresh auth headers are availble and SSE stream succeeds\n- SSE is long-lived so works for as long as tokens don't need refresh\n\n### Root cause\n\nIn /mcp/client/sse.py, this call with `aconnect_sse` hangs infinitely.\n\n```python\nasync with anyio.create_task_group() as tg:\n try:\n logger.debug(f\"Connecting to SSE endpoint: {remove_request_params(url)}\")\n async with httpx_client_factory(\n headers=headers, auth=auth, timeout=httpx.Timeout(timeout, read=sse_read_timeout)\n ) as client:\n async with aconnect_sse( #\u003c======================== This hangs indefinitely with a 200 response\n client,\n \"GET\",\n url,\n ) as event_source:\n event_source.response.raise_for_status()\n\n```\n\nThis is because `OAuthClientProvider`, which is attached to the client, on token refresh, tries to yield when in the middle of `client.stream` here:\n```python\n if not self.context.is_token_valid() and self.context.can_refresh_token():\n # Try to refresh token\n refresh_request = await self._refresh_token()\n refresh_response = yield refresh_request. #\u003c======================== Causes client.stream() to hang\n\n if not await self._handle_refresh_response(refresh_response):\n # Refresh failed, need full re-authentication\n self._initialized = False\n```\nOther yields in the broader method occur after the stream got a 401 and so are not in the same context.\n\n### The Fix - Force token refresh check outside of the stream context\n\nAny fix needs to remove the `OAuthClientProvider` from `client` before calling `aconnect_sse`. That way it won't yield the refresh request.\n\nThere is probably a more elgant/direct approach but the below worked. I had to create a separate client to avoid some lock conflict.\n\n```python\nasync with anyio.create_task_group() as tg:\n try:\n logger.debug(f\"Connecting to SSE endpoint: {remove_request_params(url)}\")\n async with httpx_client_factory(\n headers=headers, auth=auth, timeout=httpx.Timeout(timeout, read=sse_read_timeout)\n ) as client:\n \n #----- Start of fix -------\n auth_headers = {}\n if auth:\n # Initialize auth to load stored tokens\n if hasattr(auth, '_initialize') and not getattr(auth, '_initialized', False):\n await auth._initialize()\n\n # Check if tokens need refresh\n if hasattr(auth, 'context') and auth.context:\n # Check if token is expired or needs refresh\n if not auth.context.is_token_valid() and auth.context.can_refresh_token():\n logger.debug(\"Token needs refresh before SSE connection\")\n\n # Use a separate client for refresh to avoid lock issues\n async with httpx.AsyncClient() as refresh_client:\n # Create a dummy request to trigger the refresh flow\n dummy_request = httpx.Request(\"GET\", url)\n\n # Run the auth flow to refresh tokens\n auth_gen = auth.async_auth_flow(dummy_request)\n try:\n # Start the generator\n refresh_request = await auth_gen.asend(None)\n\n # Execute the refresh request\n refresh_response = await refresh_client.request(\n refresh_request.method,\n refresh_request.url,\n data=refresh_request.content,\n headers=refresh_request.headers,\n )\n\n # Send response back to generator\n await auth_gen.asend(refresh_response)\n logger.debug(\"Token refreshed successfully before SSE connection\")\n except StopAsyncIteration:\n # Normal completion of auth flow\n pass\n except Exception as e:\n logger.error(f\"Failed to refresh token before SSE: {e}\")\n\n # Extract the token after potential refresh\n if auth.context.current_tokens and auth.context.current_tokens.access_token:\n token = auth.context.current_tokens.access_token\n auth_headers['Authorization'] = f\"Bearer {token}\"\n\n # CRITICAL: Remove auth from client to prevent generator interference\n client.auth = None\n #----- Resume existing code -------\n async with aconnect_sse(\n client,\n \"GET\",\n url,\n headers=auth_headers, #\u003c============================== Must add this too\n ) as event_source:\n event_source.response.raise_for_status()\n```\n\nSince you removed auth from the client, you have to insert the headers later for the POST call as well:\n\n```python\n async def post_writer(endpoint_url: str):\n try:\n async with write_stream_reader:\n async for session_message in write_stream_reader:\n logger.debug(f\"Sending client message: {session_message}\")\n response = await client.post(\n endpoint_url,\n json=session_message.message.model_dump(\n by_alias=True,\n mode=\"json\",\n exclude_none=True,\n ),\n headers=auth_headers, #\u003c======================== Cause client.stream() to hang\n```\n\n\n### Example Code\n\n```Python\n\n```\n\n### Python & MCP Python SDK\n\n```Text\n1.12.4 (but same code as current version)\n```","author":{"url":"https://github.com/Norcim133","@type":"Person","name":"Norcim133"},"datePublished":"2025-08-30T22:09:04Z","url":"https://github.com/modelcontextprotocol/python-sdk/issues/1326"}
| 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:2a92569b-9e93-116d-f577-bed925095525 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | AAC2:FC5BE:14D33B3:1BAB380:6B0130ED |
| html-safe-nonce | b8e8a2e44e999a1106f7935a07e6e11dc76fea6499418d58312f3bfbf6d9bff3 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJBQUMyOkZDNUJFOjE0RDMzQjM6MUJBQjM4MDo2QjAxMzBFRCIsInZpc2l0b3JfaWQiOiI4ODM0MjMxNDIzMDU4NjUzNDIxIiwicmVnaW9uX2VkZ2UiOiJpYWQiLCJyZWdpb25fcmVuZGVyIjoiaWFkIn0= |
| visitor-hmac | bfd905dcd266c1b3865c13889401e4e1cfef50d2a5a4074812b0ffb80e03f4d7 |
| hovercard-subject-tag | issue:3369550896 |
| 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/1326/issue_layout |
| twitter:image | https://opengraph.githubassets.com/afe0556e687ea4a57d6281e4c64338dd7c1f7e259b0da29b885c5d1258b89ef7/modelcontextprotocol/python-sdk/issues/1326 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/afe0556e687ea4a57d6281e4c64338dd7c1f7e259b0da29b885c5d1258b89ef7/modelcontextprotocol/python-sdk/issues/1326 |
| og:image:alt | Initial Checks I confirm that I'm using the latest version of MCP Python SDK I confirm that I searched for my issue in https://github.com/modelcontextprotocol/python-sdk/issues before opening this ... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | Norcim133 |
| 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