Title: Bug: AssertionError: Request already responded to — cancellation race in v1.27.0 · Issue #2416 · modelcontextprotocol/python-sdk · GitHub
Open Graph Title: Bug: AssertionError: Request already responded to — cancellation race in v1.27.0 · Issue #2416 · modelcontextprotocol/python-sdk
X Title: Bug: AssertionError: Request already responded to — cancellation race in v1.27.0 · Issue #2416 · 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 Bug: AssertionError: R...
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/2416
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Bug: AssertionError: Request already responded to — cancellation race in v1.27.0","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# Bug: `AssertionError: Request already responded to` — cancellation race in v1.27.0\n\n`AssertionError: Request already responded to` when CancelledNotification arrives after handler completes but before `respond()`\n\n## Description\n\nWhen a client sends a `notifications/cancelled` for a request whose handler has already finished executing but hasn't yet called `message.respond()`, the server crashes with `AssertionError: Request already responded to`.\n\nPR #2334 (v1.27.0) fixed the `ClosedResourceError` crash path by catching `CancelledError` in `_handle_request` and guarding `respond()` against `BrokenResourceError`/`ClosedResourceError`. However, it left a race window between handler completion and `respond()` where a cancellation notification can set `_completed = True` first, causing the assert on line 129 of `session.py` to fire.\n\n## Reproduction scenario\n\n1. Client sends a `tools/call` request with a long-running handler (e.g. polling with 600s timeout)\n2. Handler completes and returns a result\n3. Between the handler's `return` and the `await message.respond(response)` call in `_handle_request`, the client sends `notifications/cancelled` for that same request ID\n4. The cancellation notification handler (`session.py:403-406`) calls `responder.cancel()`, which:\n - Calls `_cancel_scope.cancel()` \n - Sets `_completed = True`\n - Sends an error response `\"Request cancelled\"`\n5. Back in `_handle_request`, execution reaches `await message.respond(response)` at `server.py:800`\n6. `respond()` hits `assert not self._completed` at `session.py:129` → **crash**\n\nThe `cancel_scope.cancel()` only raises `CancelledError` if the task is currently in an `await`. Since the handler already returned, the code path between the handler return and `respond()` is synchronous — no checkpoint where `CancelledError` can be delivered. The `except anyio.get_cancelled_exc_class()` guard at `server.py:773` never fires.\n\n## Stack trace\n\n```\nExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception)\n +-+---------------- 1 ----------------\n | ExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception)\n +-+---------------- 1 ----------------\n | ExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception)\n +-+---------------- 1 ----------------\n | Traceback (most recent call last):\n | File \"mcp/server/lowlevel/server.py\", line 703, in _handle_message\n | await self._handle_request(message, req, session, lifespan_context, raise_exceptions)\n | File \"mcp/server/lowlevel/server.py\", line 800, in _handle_request\n | await message.respond(response)\n | File \"mcp/shared/session.py\", line 129, in respond\n | assert not self._completed, \"Request already responded to\"\n | AssertionError: Request already responded to\n +------------------------------------\n```\n\n## Impact\n\nThis crashes the entire MCP server process, killing all in-flight requests. In our case, the server manages multiple long-running background agents, so a crash loses all active work. The crash is triggered by normal client behavior (user cancels an operation), making it a reliability issue rather than an edge case.\n\n## Related\n\n- #2328 — original ClosedResourceError report\n- #2334 — v1.x fix (covers ClosedResourceError but not this assert race)\n- #2306 — main branch transport-close cancellation\n\n\n### Example Code\n\n```Python\nThe race window in `_handle_request` (`server.py:719`):\n\n\n# Line 770: handler completes, returns response\nresponse = await handler(req)\n\n# ... exception handling ...\n\n# Line 799-800: GAP — between handler return and respond(),\n# a CancelledNotification can arrive on another task and call\n# responder.cancel(), setting _completed = True and sending\n# an error response. No await in this gap means no CancelledError\n# can be delivered.\ntry:\n await message.respond(response) # \u003c-- assert fires here\nexcept (anyio.BrokenResourceError, anyio.ClosedResourceError):\n ...\n\n\nThe `except anyio.get_cancelled_exc_class()` at line 773 correctly handles the case where the cancellation arrives *during* handler execution. But it cannot handle cancellation that arrives *after* the handler returns, because there's no async checkpoint between the handler return and `respond()`.\n\n## Suggested fix\n\nIn `session.py`, change `respond()` to handle the already-completed case gracefully instead of asserting:\n\n\nasync def respond(self, response: SendResultT | ErrorData) -\u003e None:\n if not self._entered:\n raise RuntimeError(\"RequestResponder must be used as a context manager\")\n \n # If already completed (e.g. by a concurrent cancellation), skip silently.\n if self._completed:\n return\n\n if not self.cancelled:\n self._completed = True\n await self._session._send_response(\n request_id=self.request_id, response=response\n )\n\n\nAlternatively, the guard could be added in `_handle_request` before calling `respond()`:\n\n\nif not message._completed:\n try:\n await message.respond(response)\n except (anyio.BrokenResourceError, anyio.ClosedResourceError):\n logger.debug(\"Response for %s dropped - transport closed\", message.request_id)\n\n\nThe first approach (in `respond()` itself) is more robust since it closes the race for all callers.\n```\n\n### Python \u0026 MCP Python SDK\n\n```Text\n- `mcp` 1.27.0\n- Python 3.14\n- anyio (asyncio backend)\n- FastMCP stdio transport\n- Client: Claude Code 2.1.92\n```","author":{"url":"https://github.com/bbarwik","@type":"Person","name":"bbarwik"},"datePublished":"2026-04-09T20:25:05.000Z","interactionStatistic":{"@type":"InteractionCounter","interactionType":"https://schema.org/CommentAction","userInteractionCount":4},"url":"https://github.com/2416/python-sdk/issues/2416"}
| 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:11161776-f5fe-0443-6a87-67f91e006b8e |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | DADE:19C3B6:5A04A8:80429A:6A59E54C |
| html-safe-nonce | 06745d062907936e1e5685a6b0e634c8258b6bc04529fcfdbf69c6c61823854a |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJEQURFOjE5QzNCNjo1QTA0QTg6ODA0MjlBOjZBNTlFNTRDIiwidmlzaXRvcl9pZCI6IjU0NTQ1ODM3MjQzOTc2ODQwNDQiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | 20a76e7404f8359eb5fb21e88e5b2451c54af5649987a77a87fac6eb143cfa5c |
| hovercard-subject-tag | issue:4234724647 |
| 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/2416/issue_layout |
| twitter:image | https://opengraph.githubassets.com/8a0d14b3774ef6eefa3baff2f2615b9cd903240bf8783c0e02beba14dd24bb16/modelcontextprotocol/python-sdk/issues/2416 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/8a0d14b3774ef6eefa3baff2f2615b9cd903240bf8783c0e02beba14dd24bb16/modelcontextprotocol/python-sdk/issues/2416 |
| 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 | bbarwik |
| hostname | github.com |
| expected-hostname | github.com |
| None | ba3976babb66479b1c943a8edc0777d96157da48fadc0161f9ddb219deee8353 |
| 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 | 26f17126414f953984d8ae42f57c0db48e7dbde3 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
Links:
Viewport: width=device-width