fix(stdio): handle BrokenResourceError in stdout_reader race (#1960)#2450
Open
ddullah wants to merge 1 commit intomodelcontextprotocol:mainfrom
Open
Conversation
`stdio_client` has a race: `read_stream_writer.aclose()` in the context's `finally` block can close the receiver while the background `stdout_reader` task is mid-`send`. anyio then raises `BrokenResourceError`, which the outer `except` does not cover (`ClosedResourceError` is the sibling class, raised on already-closed streams, not streams closed during an in-flight send). The exception propagates through the task group as `ExceptionGroup` and fails every caller that exits the context while the subprocess is still writing to stdout. Wrap both `read_stream_writer.send(...)` sites in `try`/`except (ClosedResourceError, BrokenResourceError): return` so `stdout_reader` shuts down cleanly, and widen the outer `except` to the same union for defense in depth. No API changes. Adds `test_stdio_client_exits_cleanly_while_server_still_writing`: spawns a subprocess that emits a burst of JSONRPC notifications, exits the `stdio_client` context immediately, and asserts no exception propagates. Fails before the fix (ExceptionGroup / BrokenResourceError), passes after. Github-Issue:modelcontextprotocol#1960
There was a problem hiding this comment.
Pull request overview
Fixes a shutdown race in stdio_client where the background stdout_reader task could raise anyio.BrokenResourceError (propagating as an ExceptionGroup) if the context exits while an in-flight send() is happening.
Changes:
- Catch
anyio.BrokenResourceError(alongsideClosedResourceError) around bothread_stream_writer.send(...)call sites instdout_reader, plus widen the outer handler. - Add a regression test that exits the
stdio_clientcontext while a subprocess is still producing stdout output, asserting the context exits cleanly.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.
| File | Description |
|---|---|
src/mcp/client/stdio.py |
Makes stdout_reader resilient to stream-closure races by treating ClosedResourceError/BrokenResourceError as a graceful shutdown signal. |
tests/client/test_stdio.py |
Adds a regression test to ensure fast context exit during server output no longer fails via ExceptionGroup/BrokenResourceError. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
This 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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Fixes #1960. Paired with #2449 (the matching
[v1.x]backport).stdio_clienthas a shutdown race:read_stream_writer.aclose()in thecontext's
finallyblock can close the receiver while the backgroundstdout_readertask is mid-send. anyio raisesBrokenResourceError,which the outer
exceptdoes not cover (ClosedResourceErroris thesibling class, raised on already-closed streams, not streams closed
during an in-flight send). The exception propagates through the task
group as
ExceptionGroupand fails every caller that exits the contextwhile the subprocess is still writing to stdout.
Trigger
Any MCP server that writes a burst of output (startup banners, log-level
notifications/messageframes, scheduler init messages, etc.) paired witha caller that opens a short-lived
stdio_clientper invocation. The taskgroup exits before the subprocess drains, and the race fires.
Reproduced against
jules-mcp-server— which emits threenotifications/messageframes on init — driven bymcp2cli. Every toolcall surfaced as:
```
ExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception)
+-+---------------- 1 ----------------
| Traceback (most recent call last):
| File '.../mcp/client/stdio/init.py', line 162, in stdout_reader
| await read_stream_writer.send(session_message)
| File '.../anyio/streams/memory.py', line 213, in send_nowait
| raise BrokenResourceError
| anyio.BrokenResourceError
```
Fix
Wrap both
read_stream_writer.send(...)sites instdout_readerwithtry/except (ClosedResourceError, BrokenResourceError): return, andwiden the outer
exceptto the same union for defense in depth.stdout_readernow shuts down cleanly no matter how abruptly the callerexits the context. No API changes.
Alternative considered
#1960 also suggests
tg.cancel_scope.cancel()before the stream closes infinally. That works but changes shutdown ordering (cancels user-definednotification handlers, etc.). The chosen fix is narrower: treat the
shutdown race as a graceful exit from
stdout_readerspecifically, withoutaltering the task group lifecycle.
Tests
Added
test_stdio_client_exits_cleanly_while_server_still_writingintests/client/test_stdio.py. Spawns a subprocess that writes a thousandvalid JSONRPC notifications, exits the
stdio_clientcontext immediately,asserts no exception propagates. Wrapped in
anyio.fail_after(5.0)perAGENTS.md. Fails before the fix (ExceptionGroup / BrokenResourceError),
passes after.
Closes #1960.