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
Domain: github.com
{"@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-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:25ac98b0-acd2-e98d-f80d-013cad30f5fd |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | B194:3E5C2:16EA0:1E61E:6B00B743 |
| html-safe-nonce | 407710927ae464cfd4539e65281c92723094f5c9d5aee35060b1d14c52d95430 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJCMTk0OjNFNUMyOjE2RUEwOjFFNjFFOjZCMDBCNzQzIiwidmlzaXRvcl9pZCI6IjQ2MjczMjY4NzgwNzAzODg1NDciLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | eb66b540353786acc45d5917ad6073dcabdd2b442458ac5a1c2a6a0e39bcae89 |
| hovercard-subject-tag | issue:3412857280 |
| 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/1363/issue_layout |
| twitter:image | https://opengraph.githubassets.com/bd1a2b74157cf07b5bf6f37bdd6bbf8ce3346abc64bf1f9c9ba983da37b6e47e/modelcontextprotocol/python-sdk/issues/1363 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/bd1a2b74157cf07b5bf6f37bdd6bbf8ce3346abc64bf1f9c9ba983da37b6e47e/modelcontextprotocol/python-sdk/issues/1363 |
| 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 | Edison-A-N |
| hostname | github.com |
| expected-hostname | github.com |
| None | 1d07c25977adfc5ff6acb0a962a9bc168c07afbda6fef765f9761c350c2ae4a2 |
| 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 | 5429cbfc6aca8c7b9a086a3c8f47400346f38cc9 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width