Title: fix: cancel in-flight handlers when transport closes in server.run() by maxisbey · Pull Request #2306 · modelcontextprotocol/python-sdk · GitHub
Open Graph Title: fix: cancel in-flight handlers when transport closes in server.run() by maxisbey · Pull Request #2306 · modelcontextprotocol/python-sdk
X Title: fix: cancel in-flight handlers when transport closes in server.run() by maxisbey · Pull Request #2306 · modelcontextprotocol/python-sdk
Description: When the transport closes mid-request, server.run() now cancels in-flight handlers instead of waiting for them. Motivation and Context Discovered while investigating #2231. That issue's stated symptom (server survives parent death with no tool running) does not reproduce — stdin EOF propagates cleanly through anyio.wrap_file + TextIOWrapper on all tested Python versions (3.10–3.14). But the investigation surfaced a real adjacent bug: When stdin closes while a tool handler is running, server.run()'s task group joins on the handler rather than cancelling it. The handler eventually finishes, tries to send its response through a _write_stream that _receive_loop already closed, and server.run() crashes with ClosedResourceError wrapped in a triple-nested ExceptionGroup. In practice: a stdio server with a 3-second tool gets SIGTERM'd at 2s by the client's graceful-shutdown escalation (PROCESS_TERMINATION_TIMEOUT), so finally blocks never run. With this fix, the handler gets CancelledError immediately and cleanup runs. This is the same bug class as #2257 (merged last week), which fixed one specific write-after-close in _handle_message. This closes the general case. The existing CancelledError catch in _handle_request (added in #1153 for CancelledNotification) now distinguishes the two cancellation sources via message.cancelled — which checks the responder's own cancel scope, set only by responder.cancel(). TG cancellation is an outer scope and doesn't set it. May help some #526 cases, but the long-lived orphans reported there are more consistent with the client never closing stdin (client-side bug). Go SDK has the same wait-then-crash behavior (conn.go:167); C# fixed it in modelcontextprotocol/csharp-sdk#226. How Has This Been Tested? New test in tests/server/test_cancel_handling.py drives server.run() with raw memory streams (can't use InMemoryTransport — it wraps server.run() in its own finally: tg.cancel_scope.cancel() which masks the bug). Fails with TimeoutError on main, passes with fix. Existing test_server_remains_functional_after_cancel covers the CancelledNotification path unchanged. Verified against real subprocess scenario (Python 3.14, kill -9 parent with tool in progress). Breaking Changes None. Handlers already needed to be cancel-safe for CancelledNotification. Types of changes Bug fix (non-breaking change which fixes an issue) New feature (non-breaking change which adds functionality) Breaking change (fix or feature that would cause existing functionality to change) Documentation update Checklist I have read the MCP Documentation My code follows the repository's style guidelines New and existing tests pass locally I have added appropriate error handling I have added or updated documentation as needed Additional context session.py:108 pragma removed: RequestResponder.__exit__ now sees _completed == False when a handler is cancelled before reaching respond(). Note for reviewers: this also affects streamable HTTP when terminate() fires mid-request (stateless mode after handle_request() returns early, or session DELETE). In-flight tools are now cancelled rather than drained. Since they were previously crashing on the closed write stream anyway, this is strictly better.
Open Graph Description: When the transport closes mid-request, server.run() now cancels in-flight handlers instead of waiting for them. Motivation and Context Discovered while investigating #2231. That issue's stated ...
X Description: When the transport closes mid-request, server.run() now cancels in-flight handlers instead of waiting for them. Motivation and Context Discovered while investigating #2231. That issue's sta...
Opengraph URL: https://github.com/modelcontextprotocol/python-sdk/pull/2306
X: @github
Domain: github.com
| route-pattern | /:user_id/:repository/pull/:id/files(.:format) |
| route-controller | pull_requests |
| route-action | files |
| fetch-nonce | v2:ed08e293-aaf3-731f-47bc-ad916b7ba2e2 |
| current-catalog-service-hash | ae870bc5e265a340912cde392f23dad3671a0a881730ffdadd82f2f57d81641b |
| request-id | 8EDE:314A82:6EE328:90B39B:6A5AE53D |
| html-safe-nonce | 448358101f7fe7fd3bb90a65d9b355a8cd4ab020bb8b58e4f932a64095cb2748 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI4RURFOjMxNEE4Mjo2RUUzMjg6OTBCMzlCOjZBNUFFNTNEIiwidmlzaXRvcl9pZCI6IjY4MTAxNzY4NzA0OTY5MjQ3NyIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | e984cac8a5867a6bde16848c8a29ca0ee72c64f3b8bb1c02b86b2a6e823322d3 |
| hovercard-subject-tag | pull_request:3415641486 |
| github-keyboard-shortcuts | repository,pull-request-list,pull-request-conversation,pull-request-files-changed,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/pull/2306/files |
| twitter:image | https://avatars.githubusercontent.com/u/224885523?s=400&v=4 |
| twitter:card | summary_large_image |
| og:image | https://avatars.githubusercontent.com/u/224885523?s=400&v=4 |
| og:image:alt | When the transport closes mid-request, server.run() now cancels in-flight handlers instead of waiting for them. Motivation and Context Discovered while investigating #2231. That issue's stated ... |
| og:site_name | GitHub |
| og:type | object |
| hostname | github.com |
| expected-hostname | github.com |
| None | 5290d7e14309ad1e76106a9c4237bd1041517e83ea182c8ab756752cb0c6940b |
| turbo-cache-control | no-preview |
| diff-view | unified |
| 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 full-width |
| disable-turbo | true |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 9c975978430e9ad293956f2bbdaf153b1bd84a99 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
Links:
Viewport: width=device-width