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
stdio_server: text a tool prints still reaches the client, because sys.stdout is flushed after fd 1 is restored #3821
Since #3117, stdio_server() points fd 1 at stderr while it serves, so that stray output from handlers misses the wire. Text written with print() still reaches the client. It goes into sys.stdout's own buffer, which is block-buffered when stdout is a pipe. That buffer is flushed when the interpreter exits, after stdio_server() has given fd 1 back to the client's pipe. The client then reads the text as a JSON-RPC message.
Reproduction
mcp 2.3.0, Python 3.13.16, macOS 26.3.
importasyncioimportsysfrommcpimportClientSession, StdioServerParametersfrommcp.client.stdioimportstdio_clientfrommcp.server.mcpserverimportMCPServerifsys.argv[1:] == ["server"]:
server=MCPServer("repro")
@server.tool()defnoisy() ->str:
print("stray output from a tool") # e.g. a library that printsreturn"done"server.run("stdio")
else:
asyncdefmain():
params=StdioServerParameters(command=sys.executable, args=[__file__, "server"])
asyncwithstdio_client(params) as (read, write):
asyncwithClientSession(read, write) assession:
awaitsession.initialize()
result=awaitsession.call_tool("noisy", {})
print("result:", result.content[0].text)
asyncio.run(main())
Running python repro.py, the call succeeds, and the client also logs:
pydantic_core._pydantic_core.ValidationError: 1 validation error for union[JSONRPCRequest,JSONRPCNotification,JSONRPCResponse,JSONRPCError]
Invalid JSON: expected value at line 1 column 1 [type=json_invalid, input_value='stray output from a tool', input_type=str]
Cause
While fd 1 is diverted, the printed text never reaches it: it sits in sys.stdout's buffer. The buffer is written out at interpreter exit, when fd 1 is the protocol pipe again. Adding sys.stdout.flush() right after the print() in the tool removes the error, and the text appears on stderr, which confirms this.
Suggestion
Flush sys.stdout before restoring fd 1, so that pending text goes to the diversion. Making sys.stdout line-buffered while serving (sys.stdout.reconfigure(line_buffering=True)) would also send printed text to stderr when it is printed, rather than at exit.
As a workaround we call sys.stdout.reconfigure(line_buffering=True) before server.run("stdio") and flush after each tool.
I looked through the implementation in src/mcp/server/stdio.py and I think I understand the root cause.
The _claim_fd() release callback restores fd 1 without first flushing the original sys.stdout wrapper. Buffered output can therefore be written to the protocol pipe after the descriptor has been restored.
I think a targeted fix would be to flush the captured stdout stream before restoring fd 1, while ensuring descriptor restoration still happens even if flushing fails.
I'd also like to add a regression test in tests/server/test_stdio.py that uses print() without flush=True and verifies that the buffered output reaches stderr rather than the JSON-RPC stream.
Does this approach align with the intended behavior? I'd be interested in contributing the implementation and tests.
AI assistance disclosure: I used ChatGPT to help with initial code-path analysis and drafting. I'll verify the behavior and take responsibility for the implementation.
Testing this against current main surfaced an additional concurrency constraint that any fix here has to respect: the blockbuster detector in tests/conftest.py.
If you only add stream.flush() inside _claim_fd.release(), it executes on the asyncio event loop thread during restore_stdout() in stdio_server()'s teardown, raising blockbuster.blockbuster.BlockingError: Blocking call to io.BufferedWriter.write.
To cleanly flush buffered tool text into the diversion without triggering a BlockingError or corrupting the wire fd:
In stdio_server(), immediately before calling restore_stdout() inside anyio.CancelScope(shield=True), offload the flush:
awaitanyio.to_thread.run_sync(sys.stdout.flush)
This empties the Python-side buffer into the diversion descriptor while fd 1 still redirects there.
Inside _claim_fd.release(), retain a defensive try: stream.flush() except OSError: pass marked # pragma: no cover to cover any synchronous teardown paths.
Verified with test_stdio_server_flushes_unbuffered_stdout_to_diversion_before_restoring_fd1 in tests/server/test_stdio.py. 18/18 server stdio tests pass with 100.00% statement and branch coverage on src/mcp/server/stdio.py, and clean ruff/pyright.
Could a maintainer assign this issue to me so I can open the PR under the intake gate?
Activity
ima-d-ice commentedon Nov 5, 2026
I looked through the implementation in
src/mcp/server/stdio.pyand I think I understand the root cause.The
_claim_fd()release callback restores fd 1 without first flushing the originalsys.stdoutwrapper. Buffered output can therefore be written to the protocol pipe after the descriptor has been restored.I think a targeted fix would be to flush the captured stdout stream before restoring fd 1, while ensuring descriptor restoration still happens even if flushing fails.
I'd also like to add a regression test in
tests/server/test_stdio.pythat usesprint()withoutflush=Trueand verifies that the buffered output reaches stderr rather than the JSON-RPC stream.Does this approach align with the intended behavior? I'd be interested in contributing the implementation and tests.
AI assistance disclosure: I used ChatGPT to help with initial code-path analysis and drafting. I'll verify the behavior and take responsibility for the implementation.
media-ctrl commentedon Nov 5, 2026
JohnnyWilson16 commentedon Nov 6, 2026
Testing this against current
mainsurfaced an additional concurrency constraint that any fix here has to respect: theblockbusterdetector intests/conftest.py.If you only add
stream.flush()inside_claim_fd.release(), it executes on the asyncio event loop thread duringrestore_stdout()instdio_server()'s teardown, raisingblockbuster.blockbuster.BlockingError: Blocking call to io.BufferedWriter.write.To cleanly flush buffered tool text into the diversion without triggering a
BlockingErroror corrupting the wire fd:stdio_server(), immediately before callingrestore_stdout()insideanyio.CancelScope(shield=True), offload the flush:_claim_fd.release(), retain a defensivetry: stream.flush() except OSError: passmarked# pragma: no coverto cover any synchronous teardown paths.Verified with
test_stdio_server_flushes_unbuffered_stdout_to_diversion_before_restoring_fd1intests/server/test_stdio.py. 18/18 server stdio tests pass with 100.00% statement and branch coverage onsrc/mcp/server/stdio.py, and cleanruff/pyright.Could a maintainer assign this issue to me so I can open the PR under the intake gate?
fix(stdio): flush sys.stdout before restoring fd 1 in stdio_server (m…