Skip to content

stdio client: requests hang forever after the server closes stdout but keeps running #3804

Open

Description

@gowthamrao

Summary

If a stdio server closes its stdout after the handshake but does not exit, every later request from ClientSession waits forever. End-of-file on stdout should end the session and fail pending requests (for example with CONNECTION_CLOSED), as an exited process does. Instead list_tools() (or any call) never returns, unless the caller sets its own timeout.

Reproducer (self-contained: a 15-line raw stdio server written to a temp file)

import asyncio
import os
import sys
import tempfile
import textwrap
import time

from mcp import ClientSession
from mcp.client.stdio import StdioServerParameters, stdio_client

SERVER = textwrap.dedent(
    '''
    import json, os, sys, time
    for raw in sys.stdin:
        msg = json.loads(raw)
        if msg.get("method") == "initialize":
            reply = {"jsonrpc": "2.0", "id": msg["id"], "result": {
                "protocolVersion": msg["params"]["protocolVersion"],
                "capabilities": {"tools": {}},
                "serverInfo": {"name": "closes-stdout", "version": "0"}}}
            sys.stdout.write(json.dumps(reply) + "\n")
            sys.stdout.flush()
            sys.stdout.close()
            os.close(1)
            time.sleep(600)
    '''
)

async def main() -> None:
    path = os.path.join(tempfile.mkdtemp(), "closes_stdout.py")
    with open(path, "w", encoding="utf-8") as handle:
        handle.write(SERVER)
    params = StdioServerParameters(command=sys.executable, args=[path])
    async with stdio_client(params) as (read, write), ClientSession(read, write) as session:
        await session.initialize()
        started = time.monotonic()
        try:
            await asyncio.wait_for(session.list_tools(), timeout=20)
            print("list_tools returned")
        except TimeoutError:
            print(f"list_tools still pending after {time.monotonic() - started:.0f} s (stdout closed, process alive)")

asyncio.run(main())

Output:

list_tools still pending after 20 s (stdout closed, process alive)

Expected vs actual

Expected Actual
After stdout EOF the session ends and pending and later requests fail promptly with a connection-closed error requests wait until the caller's own timeout; with none, forever

A wedged server (stdout closed by a crash in a logging library, a misbehaving wrapper, an fd mix-up) hangs the host application.

Environment

  • mcp 2.0.0, anyio 4.14.2
  • CPython 3.14.10
  • Windows 11. Linux not tried. The stdout_reader → _drain_stdout path in mcp/client/stdio.py is where EOF should end the session.

Workaround

Pass read_timeout_seconds to ClientSession and a per-request read_timeout_seconds on call_tool, so the hang becomes a REQUEST_TIMEOUT.

Activity

  1. yashaskn8 commented on Nov 3, 2026

    @yashaskn8

    Thanks for the detailed report and the self-contained reproducer.

    I looked through the stdio client implementation in v2.0.0 and noticed two things that might help narrow this down.

    First, there's a small escaping issue in the posted reproducer. Since SERVER uses a regular triple-quoted string, the "\n" inside it becomes an actual newline in the generated Python file, causing a SyntaxError. Using a raw string (r'''...''') or escaping it as "\\n" should fix that.

    Second, JSONRPCDispatcher.run() already handles read-stream EOF by closing the dispatcher and resolving pending requests with CONNECTION_CLOSED.

    The part I'd investigate next is the transport boundary in stdio_client.stdout_reader(). The read-stream sender is closed only after _drain_stdout() finishes. If that drain blocks, the session may never receive the EOF signal.

    However, it's also possible that the Windows subprocess pipe never reports EOF to the reader in the first place. Those would require different fixes.

    Could you confirm whether the corrected reproducer still hangs on Windows, whether the child process remains alive, and whether stdout_reader() reaches _drain_stdout()?

    A useful regression test would complete initialization, start a pending list_tools() request, close the server's stdout while leaving the process alive, and verify that both pending and subsequent requests fail with CONNECTION_CLOSED.

    I'd prefer to confirm which part of the transport is blocking before proposing a patch, so we don't accidentally fix only the symptom or regress normal subprocess shutdown. The analysis and proposed tests should be validated against the Windows reproducer before implementation.

    If this analysis aligns with the maintainers' expectations, I'd be happy to take ownership of this issue and work on a fix with appropriate regression tests. Would you be open to assigning it to me?

  2. media-ctrl commented on Nov 4, 2026

    @media-ctrl
  3. sunhouy commented on Nov 5, 2026

    @sunhouy

    I spent a while on this one and have a fix up in #3819, but it is closed by the intake gate since I'm not assigned to the issue. That part is fine, I'm not asking for the assignment here. What might be useful either way is what I found, because it changes the discriminators in the second comment.

    The part I could measure is the reader task. stdout_reader closes the read stream from inside async with read_stream_writer:, but the finally runs _drain_stdout first, and that drain is with anyio.CancelScope(shield=True): while True: await process.stdout.receive(). So when EOF arrives on a server that is still alive, the drain parks on pipes that stay open until the process exits. The read stream is not closed during that window, and nothing else on that path closes it. stdin_writer has the mirror case and closes the stream explicitly with a comment saying it does so "so the server sees the connection end instead of a request hanging forever"; the read side never got the equivalent.

    What I could not do is reproduce the original hang here, which is why I did not touch 2.0.0. On Linux the request fails promptly on main too, and on 2.0.0 from PyPI it also fails rather than hangs in the versions I tried, so the OS difference the issue was filed from is doing work I can't see. Two things would settle it, and both are cheap for whoever still has the 2.0.0 environment:

    • py-spy dump of the client while list_tools is pending. If stdout_reader is sitting in receive() under the shield, it is the drain, not a spin, and the CPU discriminator in the second comment frames the choice the wrong way round: a parked drain looks exactly like an idle loop from outside.
    • Whether the child's fd 1 close surfaces as EOF at all on Windows. If it does not, the drain never gets its first EndOfStream and no fix on the read side helps until that is understood.

    The second comment's question about intent, should a closed stdout end a session whose process is alive, is the one the fix answers with yes, on the grounds that stdin_writer already assumes it in the other direction and that a session which can no longer receive anything has nothing left to offer the caller. If that reading is wrong, the change in #3819 is the wrong shape and the drain should get a timeout instead of the process getting terminated early.

    On testing: with a real server that closes stdout after the handshake and sleeps, list_tools() hangs until the caller's timeout before the change and raises MCPError(-32000, 'Connection closed') immediately after. In tests/client/test_stdio.py the case is pinned with the existing FakeProcess: pytest tests/client tests/shared goes from 1793 to 1794 passed with the same 5 environment failures (blockbuster on os.stat) before and after.

  4. media-ctrl commented on Nov 5, 2026

    @media-ctrl
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 working

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions