Title: ClosedResourceError + 'Unexpected ASGI message ... after response already completed' race in _handle_post_request notification path (streamable-http) · Issue #3641 · modelcontextprotocol/python-sdk · GitHub
Open Graph Title: ClosedResourceError + 'Unexpected ASGI message ... after response already completed' race in _handle_post_request notification path (streamable-http) · Issue #3641 · modelcontextprotocol/python-sdk
X Title: ClosedResourceError + 'Unexpected ASGI message ... after response already completed' race in _handle_post_request notification path (streamable-http) · Issue #3641 · modelcontextprotocol/python-sdk
Description: Bug: RuntimeError: Unexpected ASGI message 'http.response.start' sent, after response already completed following ClosedResourceError in _handle_post_request notification/response path Environment mcp: 2.1.1 starlette: 1.6.0 uvicorn: 0.5...
Open Graph Description: Bug: RuntimeError: Unexpected ASGI message 'http.response.start' sent, after response already completed following ClosedResourceError in _handle_post_request notification/response path Environment ...
X Description: Bug: RuntimeError: Unexpected ASGI message 'http.response.start' sent, after response already completed following ClosedResourceError in _handle_post_request notification/response path Envi...
Opengraph URL: https://github.com/modelcontextprotocol/python-sdk/issues/3641
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"ClosedResourceError + 'Unexpected ASGI message ... after response already completed' race in _handle_post_request notification path (streamable-http)","articleBody":"# Bug: `RuntimeError: Unexpected ASGI message 'http.response.start' sent, after response already completed` following `ClosedResourceError` in `_handle_post_request` notification/response path\n\n## Environment\n\n- `mcp`: 2.1.1\n- `starlette`: 1.6.0\n- `uvicorn`: 0.52.4\n- `anyio`: 4.14.2\n- Python: 3.13.14\n- OS: macOS 27.0.0 (Darwin, arm64)\n- Server: `basic-memory` 0.23.2 (FastMCP-based), `streamable-http` transport, stateful (not `stateless_http`), single uvicorn worker, run as a long-lived local service (launchd) on `127.0.0.1`.\n\n## Description\n\nOur server logs this pair of exceptions every 1-2 hours of normal multi-client usage (several unrelated local MCP clients making tool calls concurrently against the same long-running session). Each occurrence is almost always transient — the server keeps serving the next request fine within milliseconds — but on one occasion it coincided with the server task group getting wedged: the process stayed alive and listening, but stopped responding to any further request, accumulating CPU in a runnable state until we force-restarted it. I can't yet prove the wedge and this exception pair are causally linked (vs. coincidental timing), but I haven't found another candidate in the logs for that incident, so I'm reporting the reproducible half of it (the exception pair) and flagging the wedge as a possible consequence.\n\n### The two paired exceptions (always appear together, in this order)\n\n**1.** In `_handle_post_request`'s notification/response branch (around `streamable_http.py:588`, `await writer.send(session_message)`):\n\n```\nError handling POST request\nTraceback (most recent call last):\n File \".../mcp/server/streamable_http.py\", line 588, in _handle_post_request\n await writer.send(session_message)\n ...\n raise ClosedResourceError\nanyio.ClosedResourceError\n```\n\n**2.** Immediately after (same request, different connection, usually 1-4 seconds later):\n\n```\nERROR: Exception in ASGI application\nTraceback (most recent call last):\n File \".../mcp/server/streamable_http.py\", line 588, in _handle_post_request\n await writer.send(session_message)\n ...\n raise RuntimeError(f\"Unexpected ASGI message '{message['type']}' sent, after response already completed.\")\nRuntimeError: Unexpected ASGI message 'http.response.start' sent, after response already completed.\n```\n\n### Where this sits relative to known issues\n\nThis looks related to, but distinct from, the previously-reported/fixed races in this area:\n\n- #1363 / #1384 — message-router `ClosedResourceError` from early request validation failure. Already fixed and present in our installed `mcp` 2.1.1 (we checked: `except anyio.ClosedResourceError` guards are present in the message router).\n- #2064 / #2072 — `ClosedResourceError` from `send_log_message()` in the *error recovery* path after a client disconnect. Different code path (ours is the success/notification path, not error logging).\n- #2328 / #2334 — `respond()`-after-cancel assertion race, backported for v1.x. Different symptom (`AssertionError`, not a double ASGI response).\n\nOurs happens on the **notification/response branch** at line 588 — the code path that:\n1. Immediately sends a `202 Accepted` HTTP response for a non-`JSONRPCRequest` message (notification or response), then\n2. Forwards the message to `writer` for the session's message router to process.\n\nThe second exception (`Unexpected ASGI message 'http.response.start' sent, after response already completed`) implies something tried to start an ASGI response a second time on a connection that had already fully completed its response — i.e., there appear to be two handlers (or one handler re-entered) racing on the same underlying ASGI `send` callable, not just a stream that was already closed.\n\n## Hypothesis\n\nWith several concurrent clients attached to the same session, two POST requests can race such that:\n- Request A completes its `202 Accepted` response and returns.\n- Something tied to request A's scope/send (session teardown, or a delayed completion callback from the message router on the same `writer`) fires again afterward and tries to write `http.response.start` through the same (now-closed, already-completed) ASGI `send`, producing the `RuntimeError`.\n- The reactor appears to mix up these fast-fail paths tightly enough that it can spin instead of cleanly terminating, which is consistent with what we saw during the wedge (sustained CPU, no response to new requests, had to be killed externally).\n\nI don't have a minimal repro yet — this only shows up under organic concurrent load against a long-running stateful session, not in a quick scripted test. Happy to help instrument/reproduce if a maintainer can point at the likely callback path (e.g. is there a completion/cancel callback registered per-request that isn't being cancelled/unregistered when the `202` response path returns early?).\n\n## Impact\n\n- Usually harmless (logged, swallowed, next request succeeds).\n- At least once, coincided with the whole server task group wedging (high CPU, unresponsive, required external restart). Severity assessment is tentative since causation isn't proven, but flagging given the potential for a hang in a long-running server.\n\n## What we've done in the meantime\n\nRunning a watchdog that health-checks the MCP endpoint and does a bounded, backoff-limited restart (not an unconditional restart loop) with alerting if it doesn't recover after a few attempts.\n","author":{"url":"https://github.com/djbclark","@type":"Person","name":"djbclark"},"datePublished":"2026-10-03T18:56:43Z","url":"https://github.com/modelcontextprotocol/python-sdk/issues/3641"}
| 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:509750ee-bb38-acae-30aa-08679144a00d |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | 8F44:BEE52:BD3B5:F9E59:6B00B9A9 |
| html-safe-nonce | 02b1205755d82eed2ab76ffe6e46a6e450626eba306f32fb1d36f8b8b95f2d37 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI4RjQ0OkJFRTUyOkJEM0I1OkY5RTU5OjZCMDBCOUE5IiwidmlzaXRvcl9pZCI6Ijc1NDM0Njg4MzU3ODE3ODYwMjUiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | 7fea9535aa1c6cc8463664e9c11ef9fea8df2b912748d315a424f77505726561 |
| hovercard-subject-tag | issue:5692599098 |
| 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/3641/issue_layout |
| twitter:image | https://opengraph.githubassets.com/20687777978dd150ad76b584fdc22b00a6491c4108c1fb807ffb751b8a82cafd/modelcontextprotocol/python-sdk/issues/3641 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/20687777978dd150ad76b584fdc22b00a6491c4108c1fb807ffb751b8a82cafd/modelcontextprotocol/python-sdk/issues/3641 |
| og:image:alt | Bug: RuntimeError: Unexpected ASGI message 'http.response.start' sent, after response already completed following ClosedResourceError in _handle_post_request notification/response path Environment ... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | djbclark |
| 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