[v1.x] fix: handle ClosedResourceError when transport closes mid-request by owendevereaux · Pull Request #2334 · modelcontextprotocol/python-sdk
and others added 2 commits
March 22, 2026 17:24Backports fixes from #2306 to v1.x to address issue #2328. When the transport closes while handlers are processing requests (e.g., stdin EOF during a long-running tool call), the server could crash with ClosedResourceError when trying to send a response through the already-closed write stream. This fix: 1. Wraps the message loop in a try/finally that cancels in-flight handlers when the transport closes, preventing them from attempting to respond 2. Catches BrokenResourceError and ClosedResourceError when calling message.respond() and logs instead of crashing 3. Properly re-raises transport-close cancellation to let the task group handle it (vs client-initiated cancellation which already sent a response) 4. Uses list() snapshot when iterating _response_streams in the finally block to avoid 'dictionary changed size during iteration' errors Fixes #2328
This was referenced
Mar 27, 2026This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters