Skip to content

stdio_server: text a tool prints still reaches the client, because sys.stdout is flushed after fd 1 is restored #3821

Open

Description

@fabriziosalmi

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

  1. added
    bugSomething isn't working
    v2Affects the v2 line (2.x on main)
    on Nov 5, 2026
  2. ima-d-ice commented on Nov 5, 2026

    @ima-d-ice

    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.

  3. media-ctrl commented on Nov 5, 2026

    @media-ctrl
  4. JohnnyWilson16 commented on Nov 6, 2026

    @JohnnyWilson16

    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:

    1. In stdio_server(), immediately before calling restore_stdout() inside anyio.CancelScope(shield=True), offload the flush:
      await anyio.to_thread.run_sync(sys.stdout.flush)
      This empties the Python-side buffer into the diversion descriptor while fd 1 still redirects there.
    2. 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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingv2Affects the v2 line (2.x on main)

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions