You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
BrokenResourceError race condition in stdio_client cleanup when context exits quickly #1960
BrokenResourceError race condition in stdio_client cleanup when context exits quickly
Body
Description
When the stdio_client async context manager exits quickly (before the subprocess has finished outputting data), a race condition occurs between the stdout_reader task and the cleanup code in the finally block, resulting in BrokenResourceError.
Reproduction
This occurs in scenarios where:
A subprocess is spawned via stdio_client
The subprocess starts outputting data (e.g., initialization messages)
The calling code exits the context quickly (e.g., user disconnects)
The finally block closes read_stream_writer while stdout_reader is mid-send
Error
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 242, in send
| self.send_nowait(item)
| File "anyio/streams/memory.py", line 213, in send_nowait
| raise BrokenResourceError
| anyio.BrokenResourceError
+------------------------------------
Root Cause
In mcp/client/stdio/__init__.py, the stdio_client function:
The finally block closes read_stream_writer before the TaskGroup has cancelled its tasks. If stdout_reader is in the middle of await read_stream_writer.send(...), it receives BrokenResourceError.
Suggested Fix
Cancel the TaskGroup's scope before closing the streams:
We're currently serializing MCP lifecycle operations with an asyncio.Lock to prevent overlapping enter/exit operations, which avoids triggering the race condition.
For me this fails consistently on main when the client exits without consuming read_stream.
Traceback excerpt:
ExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception)
...
File ".../src/mcp/client/stdio.py", line 160, in stdout_reader
await read_stream_writer.send(session_message)
...
anyio.BrokenResourceError
I also ran the same script against the branch from #2219, and it exited cleanly there.
I traced through the code in src/mcp/client/stdio/__init__.py on the current main branch. The race condition is straightforward:
Timeline of the bug:
stdio_client yields (read_stream, write_stream) to the caller (line 189)
stdout_reader runs in the task group, reading process stdout and calling await read_stream_writer.send(session_message) (line 162) — this is a zero-buffer memory stream, so send() blocks until a consumer calls receive()
The caller exits the context without consuming read_stream (or exits quickly)
The finally block executes (line 190). It terminates the process, then calls await read_stream_writer.aclose() (line 215)
stdout_reader is still alive inside the task group, blocked on send(). The stream it's sending into just got closed from the other end → BrokenResourceError
The existing except on line 163 only catches ClosedResourceError, not BrokenResourceError, so the exception propagates into the ExceptionGroup
Key distinction:ClosedResourceError is raised when you call .send() on a stream handle that you already closed. BrokenResourceError is raised when the receiving end of the stream is closed. The finally block closes read_stream (the receive end, line 213) and read_stream_writer (the send end, line 215). If stdout_reader is mid-send() when the receive end closes, it gets BrokenResourceError, not ClosedResourceError.
Proposed Fix
The proper fix requires both a structural change and a defensive catch. Either alone is incomplete:
1. Cancel the task group scope before closing streams (structural fix)
finally:
# Cancel background tasks FIRST so they're not racing against stream teardowntg.cancel_scope.cancel()
# MCP spec: stdio shutdown sequence (existing code follows)ifprocess.stdin:
...
Adding tg.cancel_scope.cancel() at the top of the finally block causes anyio to deliver Cancelled to stdout_reader and stdin_writer at their next checkpoint (i.e., the blocked send() call). This ensures the tasks are winding down before the streams are closed.
Same change for stdin_writer. This is defense-in-depth: even with the cancel-first approach, there's a narrow window where the task could be between checkpoints when the stream closes. Catching both error types makes the cleanup fully robust.
Why both are needed
Cancel-first alone: there's still a theoretical window between the cancel signal and the task actually reaching a checkpoint. If a stream close happens in that window, BrokenResourceError still escapes.
Catch-only alone (what PR fix: avoid stdio cleanup BrokenResourceError race #2219 did): it suppresses the symptom but doesn't address the root ordering problem. The tasks still run concurrently with stream teardown, which could cause other subtle issues if anyio's internal invariants change.
How This Prevents the Race Condition
With both changes applied:
finally fires → tg.cancel_scope.cancel() marks all tasks for cancellation
stdout_reader is blocked on send() → anyio delivers Cancelled, the task exits its async with read_stream_writer: block cleanly
Stream .aclose() calls now operate on streams that no active task is using
Even if timing is unlucky, the BrokenResourceError catch prevents any exception from leaking into an ExceptionGroup
Note: PR #2219 was closed because the diff only contained the defensive catch while the description promised the structural reordering. A complete fix should include both changes.
Fix: wrap both read_stream_writer.send(...) call sites in stdout_reader with try/except (ClosedResourceError, BrokenResourceError): return, and widen the outer except to the same union. ClosedResourceError is the sibling class (raised on already-closed streams); BrokenResourceError is the one raised when the receiver is closed during an in-flight send — the exact shape of this shutdown race. No API changes.
Tests:test_stdio_client_exits_cleanly_while_server_still_writing in tests/client/test_stdio.py — spawns a subprocess that emits a burst of JSONRPC notifications, exits the stdio_client context immediately, asserts no ExceptionGroup propagates. Wrapped in anyio.fail_after(5.0) per AGENTS.md. Fails before the patch, passes after.
Repro trigger used to verify: an MCP stdio server that emits a few notifications/message frames on startup (jules-mcp-server in our case), driven by a caller that opens a fresh stdio_client per invocation (mcp2cli). Every tool call used to surface as ExceptionGroup → anyio.BrokenResourceError. After the patch, tool calls return cleanly.
Activity
maxisbey commentedon Feb 10, 2026
Thanks for the detailed analysis! Could you provide a single-file runnable script that reproduces this? Would help us validate and prioritize the fix.
AI Disclaimer
lavish0000 commentedon Mar 6, 2026
I was able to reproduce this locally on current
main(b33c811).I used this minimal script from the repo root:
Run command:
For me this fails consistently on
mainwhen the client exits without consumingread_stream.Traceback excerpt:
I also ran the same script against the branch from #2219, and it exited cleanly there.
weiguangli-io commentedon Mar 9, 2026
Root Cause Analysis
I traced through the code in
src/mcp/client/stdio/__init__.pyon the currentmainbranch. The race condition is straightforward:Timeline of the bug:
stdio_clientyields(read_stream, write_stream)to the caller (line 189)stdout_readerruns in the task group, reading process stdout and callingawait read_stream_writer.send(session_message)(line 162) — this is a zero-buffer memory stream, sosend()blocks until a consumer callsreceive()read_stream(or exits quickly)finallyblock executes (line 190). It terminates the process, then callsawait read_stream_writer.aclose()(line 215)stdout_readeris still alive inside the task group, blocked onsend(). The stream it's sending into just got closed from the other end →BrokenResourceErrorexcepton line 163 only catchesClosedResourceError, notBrokenResourceError, so the exception propagates into theExceptionGroupKey distinction:
ClosedResourceErroris raised when you call.send()on a stream handle that you already closed.BrokenResourceErroris raised when the receiving end of the stream is closed. Thefinallyblock closesread_stream(the receive end, line 213) andread_stream_writer(the send end, line 215). Ifstdout_readeris mid-send()when the receive end closes, it getsBrokenResourceError, notClosedResourceError.Proposed Fix
The proper fix requires both a structural change and a defensive catch. Either alone is incomplete:
1. Cancel the task group scope before closing streams (structural fix)
Adding
tg.cancel_scope.cancel()at the top of thefinallyblock causes anyio to deliverCancelledtostdout_readerandstdin_writerat their next checkpoint (i.e., the blockedsend()call). This ensures the tasks are winding down before the streams are closed.2. Catch
BrokenResourceErroralongsideClosedResourceError(defensive fix)Same change for
stdin_writer. This is defense-in-depth: even with the cancel-first approach, there's a narrow window where the task could be between checkpoints when the stream closes. Catching both error types makes the cleanup fully robust.Why both are needed
BrokenResourceErrorstill escapes.How This Prevents the Race Condition
With both changes applied:
finallyfires →tg.cancel_scope.cancel()marks all tasks for cancellationstdout_readeris blocked onsend()→ anyio deliversCancelled, the task exits itsasync with read_stream_writer:block cleanly.aclose()calls now operate on streams that no active task is usingBrokenResourceErrorcatch prevents any exception from leaking into anExceptionGroupNote: PR #2219 was closed because the diff only contained the defensive catch while the description promised the structural reordering. A complete fix should include both changes.
Fix stdio_client BrokenResourceError race condition during shutdown
ddullah commentedon Apr 15, 2026
Paired PRs with a fix + regression test:
main(V2): fix(stdio): handle BrokenResourceError in stdout_reader race (#1960) #2450v1.x: [v1.x] fix(stdio): handle BrokenResourceError in stdout_reader race (#1960) #2449Fix: wrap both
read_stream_writer.send(...)call sites instdout_readerwithtry/except (ClosedResourceError, BrokenResourceError): return, and widen the outerexceptto the same union.ClosedResourceErroris the sibling class (raised on already-closed streams);BrokenResourceErroris the one raised when the receiver is closed during an in-flight send — the exact shape of this shutdown race. No API changes.Tests:
test_stdio_client_exits_cleanly_while_server_still_writingintests/client/test_stdio.py— spawns a subprocess that emits a burst of JSONRPC notifications, exits thestdio_clientcontext immediately, asserts noExceptionGrouppropagates. Wrapped inanyio.fail_after(5.0)per AGENTS.md. Fails before the patch, passes after.Repro trigger used to verify: an MCP stdio server that emits a few
notifications/messageframes on startup (jules-mcp-serverin our case), driven by a caller that opens a freshstdio_clientper invocation (mcp2cli). Every tool call used to surface asExceptionGroup→anyio.BrokenResourceError. After the patch, tool calls return cleanly.