René's URL Explorer Experiment


Title: Race Condition in StreamableHTTP Transport Causes ClosedResourceError · Issue #1363 · modelcontextprotocol/python-sdk · GitHub

Open Graph Title: Race Condition in StreamableHTTP Transport Causes ClosedResourceError · Issue #1363 · modelcontextprotocol/python-sdk

X Title: Race Condition in StreamableHTTP Transport Causes ClosedResourceError · Issue #1363 · 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 Race Condition in Stre...

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/1363

X: @github

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Race Condition in StreamableHTTP Transport Causes ClosedResourceError","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# Race Condition in StreamableHTTP Transport Causes ClosedResourceError\n\n## Description\n\nStarting from v1.12.0, MCP servers in HTTP Streamable mode experience a race condition that causes `ClosedResourceError` exceptions when requests fail validation early (e.g., due to incorrect Accept headers). This issue is particularly noticeable with fast-failing requests and can be reproduced consistently.\n\n## Root Cause Analysis\n\n**NOTE: All code references are based on `v1.14.0` with `anyio==4.10.0`.**\n\n### Execution Flow\n\n1. **Transport Setup**: In `streamable_http_manager.py` line 171, `connect()` is called, which internally creates a `message_router` task\n2. **Message Router**: The `message_router` enters an `async for write_stream_reader` loop (line 831 in `streamable_http.py`)\n3. **Checkpoint Yield**: The `write_stream_reader` implementation in `anyio.streams.memory.py` line 109 calls `checkpoint()` in the `receive()` function, yielding control\n4. **Request Handling**: `handle_request()` processes the HTTP request\n5. **Early Return**: If validation fails (e.g., incorrect Accept headers in `_handle_post_request` at line 323 in `streamable_http.py`), the request returns immediately\n6. **Transport Termination**: Back in `streamable_http_manager.py` line 193, `http_transport.terminate()` is called, closing all streams including `write_stream_reader`\n7. **Race Condition**: The `message_router` task may still be in the `checkpoint()` yield and hasn't returned to check the stream state\n8. **Error**: When the `message_router` resumes, it continues to `receive_nowait()` and encounters a closed stream, raising `ClosedResourceError` in line 93\n\n### Code Locations\n\n- **Issue trigger**: `streamable_http.py:323` - Early return on validation failure\n- **Stream creation**: `streamable_http_manager.py:171` - `connect()` call\n- **Message router**: `streamable_http.py:831` - `async for write_stream_reader`\n- **Stream termination**: `streamable_http_manager.py:193` - `terminate()` call\n- **Error source**: `memory.py:93` - `ClosedResourceError` in `receive_nowait()`\n\n## Reproduction Steps\n\n1. Start an MCP server in HTTP Streamable mode\n2. Send a POST request with incorrect `Accept` headers (missing either `application/json` or `text/event-stream`)\n3. The request will fail validation and return quickly\n4. Observe the `ClosedResourceError` in the server logs\n\n### Example Request\n```bash\ncurl -X POST http://localhost:8000/mcp \\\n  -H \"Content-Type: application/json\" \\\n  -H \"Accept: application/json\" \\\n  -d '{\"jsonrpc\": \"2.0\", \"method\": \"initialize\", \"id\": 1}'\n```\n\n## Error Stack Trace\n\n```\n15:37:00 - mcp.server.streamable_http - ERROR - Error in message router\nTraceback (most recent call last):\n  File \"/data/test_project/.venv/lib/python3.10/site-packages/mcp/server/streamable_http.py\", line 831, in message_router\n    async for session_message in write_stream_reader:\n  File \"/data/test_project/.venv/lib/python3.10/site-packages/anyio/abc/_streams.py\", line 41, in __anext__\n    return await self.receive()\n  File \"/data/test_project/.venv/lib/python3.10/site-packages/anyio/streams/memory.py\", line 111, in receive\n    return self.receive_nowait()\n  File \"/data/test_project/.venv/lib/python3.10/site-packages/anyio/streams/memory.py\", line 93, in receive_nowait\n    raise ClosedResourceError\nanyio.ClosedResourceError\n```\n\n## Workaround\n\nAdding a small delay before the early return can mitigate the race condition:\n\n```python\n# In streamable_http.py around line 321\nimport asyncio\nawait asyncio.sleep(0.1)  # Allow message_router to complete checkpoint\n```\n\n## Expected Behavior\n\nThe server should handle early request failures gracefully without raising `ClosedResourceError` exceptions in the message router.\n\n\n## Impact\n\nThis issue affects the reliability of MCP servers in HTTP Streamable mode, particularly when clients send malformed requests or when network conditions cause rapid request/response cycles.\n\n## Proposed Solution\n\nThis issue occurs due to differences in checkpoint handling logic between anyio and the coroutine scheduler being used, combined with the forced checkpoint operation in receive (the reason for this is unclear - if anyone understands, please help supplement, thank you), and further combined with receive_nowait's internal closed state checking causing application exceptions. This is not an exception of the MCP SDK itself.\n\nHowever, to address this issue, there can be two solution approaches:\n\n1. **Approach One**: Add exception handling for `anyio.ClosedResourceError` in the message router loop:\n   ```python\n   try:\n       async for session_message in write_stream_reader:\n           # ... existing code ...\n   except anyio.ClosedResourceError:\n       # Simply ignore the error, or optionally add a warning log\n       # (though the warning log may not be particularly helpful)\n       pass\n   ```\n   This approach directly handles the race condition by catching and ignoring the expected exception.\n\n2. **Approach Two**: Add explicit delays in request validation functions like `_handle_post_request`:\n   ```python\n   async def _handle_post_request(self, scope: Scope, request: Request, receive: Receive, send: Send) -> None:\n       # ... existing code ...\n       \n       if not (has_json and has_sse):\n           response = self._create_error_response(\n               (\"Not Acceptable: Client must accept both application/json and text/event-stream\"),\n               HTTPStatus.NOT_ACCEPTABLE,\n           )\n           await response(scope, receive, send)\n           await asyncio.sleep(0.1)  # Allow message_router to complete checkpoint\n           return\n\n       # Validate Content-Type\n       if not self._check_content_type(request):\n           response = self._create_error_response(\n               \"Unsupported Media Type: Content-Type must be application/json\",\n               HTTPStatus.UNSUPPORTED_MEDIA_TYPE,\n           )\n           await response(scope, receive, send)\n           await asyncio.sleep(0.1)  # Allow message_router to complete checkpoint\n           return\n   ```\n   This approach makes the request handling more complex and harder to understand, but it prevents future issues where automatic closing of `write_stream_reader` might be ignored in version updates.\n\n3. **Approach Three**: Looking forward to other solutions that may provide better approaches to handle this race condition.\n\n## Related Issues\n\nThis issue is related to the broader problem described in #1190, where MCP servers in HTTP Streamable mode are broken starting from v1.12.0.\n\n\n### Example Code\n\n```Python\n\n```\n\n### Python & MCP Python SDK\n\n```Text\npython==3.12.0\nmcp==1.14.0\n```","author":{"url":"https://github.com/Edison-A-N","@type":"Person","name":"Edison-A-N"},"datePublished":"2025-09-13T08:08:13Z","url":"https://github.com/modelcontextprotocol/python-sdk/issues/1363"}

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:25ac98b0-acd2-e98d-f80d-013cad30f5fd
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-idB194:3E5C2:16EA0:1E61E:6B00B743
html-safe-nonce407710927ae464cfd4539e65281c92723094f5c9d5aee35060b1d14c52d95430
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJCMTk0OjNFNUMyOjE2RUEwOjFFNjFFOjZCMDBCNzQzIiwidmlzaXRvcl9pZCI6IjQ2MjczMjY4NzgwNzAzODg1NDciLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ==
visitor-hmaceb66b540353786acc45d5917ad6073dcabdd2b442458ac5a1c2a6a0e39bcae89
hovercard-subject-tagissue:3412857280
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/1363/issue_layout
twitter:imagehttps://opengraph.githubassets.com/bd1a2b74157cf07b5bf6f37bdd6bbf8ce3346abc64bf1f9c9ba983da37b6e47e/modelcontextprotocol/python-sdk/issues/1363
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/bd1a2b74157cf07b5bf6f37bdd6bbf8ce3346abc64bf1f9c9ba983da37b6e47e/modelcontextprotocol/python-sdk/issues/1363
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:usernameEdison-A-N
hostnamegithub.com
expected-hostnamegithub.com
None1d07c25977adfc5ff6acb0a962a9bc168c07afbda6fef765f9761c350c2ae4a2
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
release5429cbfc6aca8c7b9a086a3c8f47400346f38cc9
ui-targetfull
theme-color#1e2327
color-schemelight dark
react-app-nameissues

Links:

Skip to contenthttps://github.com/modelcontextprotocol/python-sdk/issues/1363#start-of-content
https://github.com/
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fmodelcontextprotocol%2Fpython-sdk%2Fissues%2F1363
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%2F1363
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/1363
Reloadhttps://github.com/modelcontextprotocol/python-sdk/issues/1363
Reloadhttps://github.com/modelcontextprotocol/python-sdk/issues/1363
modelcontextprotocolhttps://github.com/modelcontextprotocol
python-sdkhttps://github.com/modelcontextprotocol/python-sdk
Codehttps://github.com/modelcontextprotocol/python-sdk
Issues308 (308)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/1363
New issuehttps://github.com/login?return_to=https://github.com/modelcontextprotocol/python-sdk/issues/1363
#1384https://github.com/modelcontextprotocol/python-sdk/pull/1384
Race Condition in StreamableHTTP Transport Causes ClosedResourceErrorhttps://github.com/modelcontextprotocol/python-sdk/issues/1363#top
#1384https://github.com/modelcontextprotocol/python-sdk/pull/1384
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
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
HTTP Transport Edge Caseshttps://github.com/modelcontextprotocol/python-sdk/milestone/18
https://github.com/Edison-A-N
Edison-A-Nhttps://github.com/Edison-A-N
on Sep 13, 2025https://github.com/modelcontextprotocol/python-sdk/issues/1363#issue-3412857280
https://github.com/modelcontextprotocol/python-sdk/issueshttps://github.com/modelcontextprotocol/python-sdk/issues
#1190https://github.com/modelcontextprotocol/python-sdk/issues/1190
maxisbeyhttps://github.com/maxisbey
bugSomething isn't workinghttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22bug%22
on Sep 22, 2025https://github.com/modelcontextprotocol/python-sdk/issues/1363#event-19839606517
felixweinbergerhttps://github.com/felixweinberger
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
P0Broken core functionality, security issues, critical missing featurehttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22P0%22
on Oct 3, 2025https://github.com/modelcontextprotocol/python-sdk/issues/1363#event-20078827485
felixweinbergerhttps://github.com/felixweinberger
HTTP Transport Edge Caseshttps://github.com/modelcontextprotocol/python-sdk/milestone/18
on Oct 3, 2025https://github.com/modelcontextprotocol/python-sdk/issues/1363#event-20078862243
https://github.com/felixweinberger
felixweinbergerhttps://github.com/felixweinberger
on Oct 3, 2025https://github.com/modelcontextprotocol/python-sdk/issues/1363#issuecomment-3365233119
@Edison-A-Nhttps://github.com/Edison-A-N
fix: handle ClosedResourceError in StreamableHTTP message router #1384https://github.com/modelcontextprotocol/python-sdk/pull/1384
https://github.com/ofek
ofekhttps://github.com/ofek
on Oct 21, 2025https://github.com/modelcontextprotocol/python-sdk/issues/1363#issuecomment-3428814517
https://github.com/ofek
ofekhttps://github.com/ofek
on Oct 21, 2025https://github.com/modelcontextprotocol/python-sdk/issues/1363#issuecomment-3429063013
#1190 (comment)https://github.com/modelcontextprotocol/python-sdk/issues/1190#issuecomment-3429054580
felixweinbergerhttps://github.com/felixweinberger
2025-11-25 Implementationhttps://github.com/orgs/modelcontextprotocol/projects/26
on Oct 30, 2025https://github.com/modelcontextprotocol/python-sdk/issues/1363#event-20608389898
felixweinbergerhttps://github.com/felixweinberger
2025-11-25 Implementationhttps://github.com/orgs/modelcontextprotocol/projects/26
on Oct 30, 2025https://github.com/modelcontextprotocol/python-sdk/issues/1363
felixweinbergerhttps://github.com/felixweinberger
2025-11-25 Implementationhttps://github.com/orgs/modelcontextprotocol/projects/26
on Oct 30, 2025https://github.com/modelcontextprotocol/python-sdk/issues/1363
https://github.com/vemonet
vemonethttps://github.com/vemonet
on Nov 13, 2025https://github.com/modelcontextprotocol/python-sdk/issues/1363#issuecomment-3528724197
maxisbeyhttps://github.com/maxisbey
duplicatehttps://github.com/modelcontextprotocol/python-sdk/issues?q=is%3Aissue%20state%3Aclosed%20archived%3Afalse%20reason%3Aduplicate
on Dec 2, 2025https://github.com/modelcontextprotocol/python-sdk/issues/1363#event-21307587084
github-project-automationhttps://github.com/apps/github-project-automation
2025-11-25 Implementationhttps://github.com/orgs/modelcontextprotocol/projects/26
on Dec 2, 2025https://github.com/modelcontextprotocol/python-sdk/issues/1363
https://github.com/maxisbey
maxisbeyhttps://github.com/maxisbey
on Dec 2, 2025https://github.com/modelcontextprotocol/python-sdk/issues/1363#issuecomment-3602344077
#1190https://github.com/modelcontextprotocol/python-sdk/issues/1190
#1190https://github.com/modelcontextprotocol/python-sdk/issues/1190
Kludexhttps://github.com/Kludex
completedhttps://github.com/modelcontextprotocol/python-sdk/issues?q=is%3Aissue%20state%3Aclosed%20archived%3Afalse%20reason%3Acompleted
#1384https://github.com/modelcontextprotocol/python-sdk/pull/1384
on Dec 4, 2025https://github.com/modelcontextprotocol/python-sdk/issues/1363#event-21355571850
felixweinbergerhttps://github.com/felixweinberger
P1Significant bug affecting many users, highly requested featurehttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22P1%22
P0Broken core functionality, security issues, critical missing featurehttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22P0%22
on Feb 23, 2026https://github.com/modelcontextprotocol/python-sdk/issues/1363#event-23007113665
Sign up for freehttps://github.com/signup?return_to=https://github.com/modelcontextprotocol/python-sdk/issues/1363
Sign in to commenthttps://github.com/login?return_to=https://github.com/modelcontextprotocol/python-sdk/issues/1363
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
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
2025-11-25 ImplementationClosedhttps://github.com/orgs/modelcontextprotocol/projects/26
HTTP Transport Edge CasesNo due datehttps://github.com/modelcontextprotocol/python-sdk/milestone/18
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.