python-sdk icon indicating copy to clipboard operation
python-sdk copied to clipboard

Using transport="stdio" closes real stdio, causing ValueError after server exits

Open hyn0027 opened this issue 10 months ago • 11 comments

Initial Checks

  • [x] I confirm that I'm using the latest version of MCP Python SDK
  • [x] I confirm that I searched for my issue in https://github.com/modelcontextprotocol/python-sdk/issues before opening this issue

Description

Hi! I ran into an issue where running the server with transport="stdio" causes subsequent stdio operations to fail after the server exits.

Minimal reproduction

from mcp.server.fastmcp import FastMCP

mcp = FastMCP("Demo")
mcp.run(transport="stdio")
print("?")

When using Ctrl+D to exit the server, the final print raises:

Traceback (most recent call last):
  File "...", line 5, in <module>
    print("?")
ValueError: I/O operation on closed file.

I’m not sure if this is intended behavior though.

Likely cause

In stdio.py, stdio is wrapped like this: https://github.com/modelcontextprotocol/python-sdk/blob/5301298225968ce0fa8ae62870f950709da14dc6/src/mcp/server/stdio.py#L44-L47

When these wrappers are closed, they also close the sys.stdin.buffer / sys.stdout.buffer.

Proposed fix

    if not stdin:
        stdin_fd = os.dup(sys.stdin.fileno())
        stdin_bin = os.fdopen(stdin_fd, "rb", closefd=True)
        stdin = anyio.wrap_file(TextIOWrapper(stdin_bin, encoding="utf-8"))
    if not stdout:
        stdout_fd = os.dup(sys.stdout.fileno())
        stdout_bin = os.fdopen(stdout_fd, "wb", closefd=True)
        stdout = anyio.wrap_file(TextIOWrapper(stdout_bin, encoding="utf-8"))

Python & MCP Python SDK

Python 3.10.15
mcp==1.25.0

hyn0027 avatar Jan 22 '26 23:01 hyn0027

I can reproduce this on main; root cause is TextIOWrapper closing sys.stdin.buffer/sys.stdout.buffer due to auto garbage collection. os.dup() adds another pointer to the underlying resource and ensures that the stdio process doesn't prematurely get GC'd. Happy to put up a PR if this is up for grabs.

adityuhkapoor avatar Feb 12 '26 02:02 adityuhkapoor

Hi, PR #2040 is ready for review, all CI green and regression test is included. The fix uses os.dup() to give TextIOWrapper its own file descriptor so closing it doesn't kill process stdio. @Kludex

adityuhkapoor avatar Feb 17 '26 21:02 adityuhkapoor

Hi, I’d like to work on this issue if it’s still available. I’m planning to put together a small fix in src/mcp/server/stdio.py with tests in tests/server/test_stdio.py.

GitAashishG avatar Apr 26 '26 05:04 GitAashishG

I'd like to help with this if it's still needed. I see several open PRs (#2040, #3090, …). Happy to:

  1. wait / review an existing PR, or
  2. take a different good-first-issue if this one is already covered. Please let me know which is preferred.

sherlocklovercn avatar Jul 24 '26 03:07 sherlocklovercn

Reliability note for long-running MCP stdio servers:

If transport="stdio" closes the process's real stdin/stdout, any parent that still expects to log, receive protocol frames, or reuse the same pipes will see a hard ValueError after the server exits — often misread as a model failure rather than a transport lifecycle bug.

Fail-closed pattern:

  1. Isolate MCP stdio to dedicated pipes (never the parent process stdio).
  2. On shutdown, emit a terminal event {stage: "mcp_stdio", status: "closed"} before tearing down pipes.
  3. Expected-vs-actual test: start server, exchange one request, exit cleanly, assert parent logging still works and no unhandled ValueError.

Pure free diagnostic notes — no product pitch.

IgorGanapolsky avatar Jul 24 '26 18:07 IgorGanapolsky

Verified and reproduced on Python 3.12 (Linux x86_64) with mcp==1.25.0.

Root Cause: anyio.wrap_file(TextIOWrapper(sys.stdin.buffer)) closes the underlying buffer upon aclose(), causing subsequent sys.stdout or sys.stdin operations to raise ValueError: I/O operation on closed file.

Portability Note for os.dup(): While os.dup(sys.stdin.fileno()) resolves basic TTY/pipe closures, it raises io.UnsupportedOperation on Windows GUI applications (pythonw), frozen executables, or custom in-memory streams (io.BytesIO) that lack a native OS file descriptor.

Recommended Fix: Using a non-closing stream proxy wrapper around process-owned streams ensures process handles remain open across Linux, macOS, and Windows without requiring a native OS fileno().

Note: Acknowledging existing open PRs #2040, #2734, and #3090 tracking this issue.

camirian avatar Jul 30 '26 23:07 camirian

I'd like to work on this. The proposed approach looks right: duplicating the fds before wrapping them prevents the async wrappers from closing the process's real stdin/stdout when the server exits. I'll open a PR with the server-side fix and a regression test shortly.

RahilOp avatar Aug 07 '26 02:08 RahilOp

Actually, I see there are already open PRs addressing this (#2040, #2734, #3090). I'll step back from this one to avoid a duplicate and pick a different MCP issue. Thanks!

RahilOp avatar Aug 07 '26 02:08 RahilOp

Current main appears to have addressed this now. src/mcp/server/stdio.py uses _UnownedTextWrapper, whose close() detaches instead of closing the process-owned buffer, and the fd-claim path duplicates/diverts/restores stdio explicitly. The inline comment also references issue #1933 and PR #3117. That should cover the original TextIOWrapper lifecycle failure without relying solely on os.dup() being available for every custom stream. If there isn't a remaining reproduction against current main, this issue looks closable.

yashkhou avatar Sep 28 '26 18:09 yashkhou

I can fix this.

Closing the process’s real stdin/stdout when transport="stdio" tears down leaves later prints/input raising ValueError. I will track where the stdio transport closes the underlying streams, stop closing the process-owned fds (only the transport wrappers), and add a regression test that runs a stdio server then writes to stdout after exit without error.

Will open a PR once the repro is green locally.

HarshXAI avatar Sep 29 '26 17:09 HarshXAI

Hi maintainers,

I verified that the original stdio stream-closure bug has been fixed on main through #3117, but it still reproduces on the latest v1 release (mcp==1.30.0).

I've prepared a minimal backport targeting v1.x that prevents the underlying process-owned stdin/stdout buffers from being closed, along with a regression test.

The regression test fails before the fix and passes afterward. The relevant tests also pass, apart from an unrelated permission test failure caused by running as root.

I understand that maintenance of v1.x is limited to security and critical fixes. Would this backport be considered in scope for the branch? If so, I'd be happy to submit a PR for review.

Implementation: https://github.com/dr1Mohamad/python-sdk/commit/c6dffe8ac47b9efc60b1f539c936b32a4ee08fd4

AI tools were used to assist with this contribution.

Thanks!

mohamad-alakkad avatar Nov 07 '26 13:11 mohamad-alakkad