Description
Summary
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.
import asyncio
import sys
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from mcp.server.mcpserver import MCPServer
if sys.argv[1:] == ["server"]:
server = MCPServer("repro")
@server.tool()
def noisy() -> str:
print("stray output from a tool") # e.g. a library that prints
return "done"
server.run("stdio")
else:
async def main():
params = StdioServerParameters(command=sys.executable, args=[__file__, "server"])
async with stdio_client(params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
result = await session.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.
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…