Title: Issue · GitHub
Open Graph Title: Issue · modelcontextprotocol/python-sdk
X Title: Issue · modelcontextprotocol/python-sdk
Description: The official Python SDK for Model Context Protocol servers and clients - Issue · modelcontextprotocol/python-sdk
Open Graph Description: The official Python SDK for Model Context Protocol servers and clients - Issue · modelcontextprotocol/python-sdk
X Description: The official Python SDK for Model Context Protocol servers and clients - Issue · modelcontextprotocol/python-sdk
Opengraph URL: https://github.com/modelcontextprotocol/python-sdk
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"RequestResponder.__exit__ leaks CancelledError on cancelled request, killing the stdio receive loop","articleBody":"## Summary\n\nWhen a client sends `notifications/cancelled` for an in-flight request handled over stdio, the server's receive loop task group dies. The process stays alive but stops reading stdin, so every subsequent request hangs and the client eventually reports `MCP error -32000: Connection closed`. The bug is racy — it reproduces in roughly 40–80% of attempts depending on platform timing.\n\nAffects: `mcp` 1.26.0 and 1.27.1 (latest at time of writing). Confirmed with FastMCP 3.1.x and the in-tree stdio server.\n\n## Reproduction\n\nA standalone subprocess test is in [mlorentedev/hive `tests/test_transport_recovery.py`](https://github.com/mlorentedev/hive/blob/master/tests/test_transport_recovery.py). The relevant flow:\n\n1. `initialize` → ack\n2. `notifications/initialized`\n3. `tools/call id=2`\n4. `notifications/cancelled` for `requestId=2` (within a few ms of step 3)\n5. Receive: `{\"id\": 2, \"error\": {\"code\": 0, \"message\": \"Request cancelled\"}}` ← OK\n6. `tools/call id=3`\n7. **No response.** Server is alive but `proc.stdout.readline()` hangs.\n\n## Root cause\n\n`mcp.shared.session.RequestResponder.__exit__`:\n\n```python\ndef __exit__(self, exc_type, exc_val, exc_tb):\n try:\n if self._completed:\n self._on_complete(self)\n finally:\n self._entered = False\n ...\n self._cancel_scope.__exit__(exc_type, exc_val, exc_tb) # ← (A)\n```\n\nWhen `notifications/cancelled` arrives, `RequestResponder.cancel()` calls `self._cancel_scope.cancel()` and sends the error response. The handler task catches the `CancelledError` in `mcp/server/lowlevel/server.py` (around line 766) and `return`s. The `with responder:` block then exits with `exc_type=None` while the cancel scope is still in cancelled state — at line (A), anyio's `CancelScope.__exit__` re-raises `CancelledError`.\n\nThat exception bubbles up to:\n\n```python\nasync with anyio.create_task_group() as tg:\n async for message in session.incoming_messages:\n tg.start_soon(self._handle_message, ...)\n```\n\n…in `Server._run`. anyio task groups cancel all sibling tasks and propagate the cancellation. The receive loop is one of those sibling tasks, so it dies.\n\n## Suggested fix\n\nSwallow the spurious cancellation when the responder has already sent its response:\n\n```python\ndef __exit__(self, exc_type, exc_val, exc_tb):\n try:\n if self._completed:\n self._on_complete(self)\n finally:\n self._entered = False\n if not self._cancel_scope:\n raise RuntimeError(\"No active cancel scope\")\n try:\n self._cancel_scope.__exit__(exc_type, exc_val, exc_tb)\n except BaseException as exc:\n if self._completed and isinstance(exc, anyio.get_cancelled_exc_class()):\n # cancel() already sent the error response — the scope's\n # re-raised cancellation is spurious.\n return\n raise\n```\n\nMirrors what we ship in [hive `src/hive/_compat.py`](https://github.com/mlorentedev/hive/blob/master/src/hive/_compat.py).\n\n## Workaround used downstream\n\nWe monkey-patch `RequestResponder.__exit__` at import time. The patch is self-gated (only fires when `_completed=True` AND the leaking exception is `anyio.get_cancelled_exc_class()`), so it stays inert once a fix lands upstream.\n\n## Environment\n\n- Reproduced on Windows 11 (`mcp` 1.26.0, 1.27.1) and via Claude Code as the host.\n- Tracked downstream in [mlorentedev/hive#75](https://github.com/mlorentedev/hive/issues/75).\n- Regression test passes 5/5 with the patch applied on Python 3.12; fails 2/5 — 4/5 without it.\n- Python 3.13 appears to have additional uncancel semantics that the patch does not yet fully cover — verification in progress.","author":{"url":"https://github.com/mlorentedev","@type":"Person","name":"mlorentedev"},"datePublished":"2026-05-15T19:52:52.000Z","interactionStatistic":{"@type":"InteractionCounter","interactionType":"https://schema.org/CommentAction","userInteractionCount":4},"url":"https://github.com/2610/python-sdk/issues/2610"}
| route-pattern | /:user_id/:repository/issues/:id(.:format) |
| route-controller | issues |
| route-action | show |
| fetch-nonce | v2:c37da62a-b0b8-6f4e-e36c-c67be7f9d04f |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | E61C:84D9B:56882E:7B991D:6A59E465 |
| html-safe-nonce | a1c2143cf710aa5df1822ef081148453b43aba80253067a4bb0ea5a4101e0ef0 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJFNjFDOjg0RDlCOjU2ODgyRTo3Qjk5MUQ6NkE1OUU0NjUiLCJ2aXNpdG9yX2lkIjoiMTk2MzY4ODE4NjU3MzYxMjEzMyIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | 85c3242447647783ddd82376b77a227e972424bfbd87a0d2e7804afb8befa87e |
| hovercard-subject-tag | repository:862584018 |
| 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/modelcontextprotocol/python-sdk/issues/2610 |
| twitter:image | https://opengraph.githubassets.com/0c85fdcdce59303eecd8e75d43b66bc4c32ef2d2d1f6371b5f07b246412f03a6/modelcontextprotocol/python-sdk |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/0c85fdcdce59303eecd8e75d43b66bc4c32ef2d2d1f6371b5f07b246412f03a6/modelcontextprotocol/python-sdk |
| og:image:alt | The official Python SDK for Model Context Protocol servers and clients - Issue · modelcontextprotocol/python-sdk |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| hostname | github.com |
| expected-hostname | github.com |
| None | ba3976babb66479b1c943a8edc0777d96157da48fadc0161f9ddb219deee8353 |
| turbo-cache-control | no-cache |
| 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