René's URL Explorer Experiment


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

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@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-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:2a92569b-9e93-116d-f577-bed925095525
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-idAAC2:FC5BE:14D33B3:1BAB380:6B0130ED
html-safe-nonceb8e8a2e44e999a1106f7935a07e6e11dc76fea6499418d58312f3bfbf6d9bff3
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJBQUMyOkZDNUJFOjE0RDMzQjM6MUJBQjM4MDo2QjAxMzBFRCIsInZpc2l0b3JfaWQiOiI4ODM0MjMxNDIzMDU4NjUzNDIxIiwicmVnaW9uX2VkZ2UiOiJpYWQiLCJyZWdpb25fcmVuZGVyIjoiaWFkIn0=
visitor-hmacbfd905dcd266c1b3865c13889401e4e1cfef50d2a5a4074812b0ffb80e03f4d7
hovercard-subject-tagissue:3369550896
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/1326/issue_layout
twitter:imagehttps://opengraph.githubassets.com/afe0556e687ea4a57d6281e4c64338dd7c1f7e259b0da29b885c5d1258b89ef7/modelcontextprotocol/python-sdk/issues/1326
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/afe0556e687ea4a57d6281e4c64338dd7c1f7e259b0da29b885c5d1258b89ef7/modelcontextprotocol/python-sdk/issues/1326
og:image:altInitial 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:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernameNorcim133
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/1326#start-of-content
https://github.com/
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fmodelcontextprotocol%2Fpython-sdk%2Fissues%2F1326
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%2F1326
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/1326
Reloadhttps://github.com/modelcontextprotocol/python-sdk/issues/1326
Reloadhttps://github.com/modelcontextprotocol/python-sdk/issues/1326
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/1326
New issuehttps://github.com/login?return_to=https://github.com/modelcontextprotocol/python-sdk/issues/1326
Clients Using Storage Face Deadlock on Token Refresh for SSEhttps://github.com/modelcontextprotocol/python-sdk/issues/1326#top
P2Moderate issues affecting some users, edge cases, potentially valuable featurehttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22P2%22
bugSomething isn't workinghttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22bug%22
ready for workEnough information for someone to start working onhttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22ready%20for%20work%22
SSE Transport Issueshttps://github.com/modelcontextprotocol/python-sdk/milestone/20
https://github.com/Norcim133
Norcim133https://github.com/Norcim133
on Aug 30, 2025https://github.com/modelcontextprotocol/python-sdk/issues/1326#issue-3369550896
https://github.com/modelcontextprotocol/python-sdk/issueshttps://github.com/modelcontextprotocol/python-sdk/issues
Norcim133https://github.com/Norcim133
needs confirmationNeeds confirmation that the PR is actually required or needed.https://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22needs%20confirmation%22
on Aug 30, 2025https://github.com/modelcontextprotocol/python-sdk/issues/1326#event-19425819665
https://github.com/someposer
someposerhttps://github.com/someposer
on Sep 3, 2025https://github.com/modelcontextprotocol/python-sdk/issues/1326#issuecomment-3247771844
Simple Auth Client Examplehttps://github.com/modelcontextprotocol/python-sdk/blob/main/examples/clients/simple-auth-client/mcp_simple_auth_client/main.py
https://github.com/delatt
delatthttps://github.com/delatt
on Sep 22, 2025https://github.com/modelcontextprotocol/python-sdk/issues/1326#issuecomment-3317434212
felixweinbergerhttps://github.com/felixweinberger
bugSomething isn't workinghttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22bug%22
ready for workEnough information for someone to start working onhttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22ready%20for%20work%22
P2Moderate issues affecting some users, edge cases, potentially valuable featurehttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22P2%22
needs confirmationNeeds confirmation that the PR is actually required or needed.https://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22needs%20confirmation%22
on Oct 3, 2025https://github.com/modelcontextprotocol/python-sdk/issues/1326#event-20078883583
felixweinbergerhttps://github.com/felixweinberger
SSE Transport Issueshttps://github.com/modelcontextprotocol/python-sdk/milestone/20
on Oct 3, 2025https://github.com/modelcontextprotocol/python-sdk/issues/1326#event-20078888393
pvliesdonkhttps://github.com/pvliesdonk
on Mar 14, 2026https://github.com/modelcontextprotocol/python-sdk/issues/1326#event-23576150445
docs: fix id_token lifetime and document MCP OAuth limitations (#199)https://github.com/pvliesdonk/markdown-vault-mcp/commit/df3948e90ac982b4f818f44caf8cec10ab82de3f
#199https://github.com/pvliesdonk/markdown-vault-mcp/pull/199
df3948ehttps://github.com/pvliesdonk/markdown-vault-mcp/commit/df3948e90ac982b4f818f44caf8cec10ab82de3f
peisukehttps://github.com/peisuke
on May 20, 2026https://github.com/modelcontextprotocol/python-sdk/issues/1326#event-25751423708
Apply optional GET SSE workaround on top of v1.27.0https://github.com/peisuke/python-sdk/commit/fa8d4b2adbdc4101e30d3e22a25ad3fcd33859c7
fa8d4b2https://github.com/peisuke/python-sdk/commit/fa8d4b2adbdc4101e30d3e22a25ad3fcd33859c7
https://github.com/peisuke
peisukehttps://github.com/peisuke
on May 22, 2026https://github.com/modelcontextprotocol/python-sdk/issues/1326#issuecomment-4516515522
https://github.com/alibeg-begow
alibeg-begowhttps://github.com/alibeg-begow
on Aug 7, 2026https://github.com/modelcontextprotocol/python-sdk/issues/1326#issuecomment-5216354654
https://github.com/alibeg-begow/singleflight_authhttps://github.com/alibeg-begow/singleflight_auth
Sign up for freehttps://github.com/signup?return_to=https://github.com/modelcontextprotocol/python-sdk/issues/1326
Sign in to commenthttps://github.com/login?return_to=https://github.com/modelcontextprotocol/python-sdk/issues/1326
P2Moderate issues affecting some users, edge cases, potentially valuable featurehttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22P2%22
bugSomething isn't workinghttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22bug%22
ready for workEnough information for someone to start working onhttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22ready%20for%20work%22
SSE Transport IssuesNo due datehttps://github.com/modelcontextprotocol/python-sdk/milestone/20
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.