Initial Checks
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
frommcp.server.fastmcpimportFastMCPmcp=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:
| ifnotstdin: |
| stdin=anyio.wrap_file(TextIOWrapper(sys.stdin.buffer, encoding="utf-8")) |
| ifnotstdout: |
| stdout=anyio.wrap_file(TextIOWrapper(sys.stdout.buffer, encoding="utf-8")) |
When these wrappers are closed, they also close the sys.stdin.buffer / sys.stdout.buffer.
Proposed fix
ifnotstdin:
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"))
ifnotstdout:
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
Initial Checks
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
When using
Ctrl+Dto exit the server, the final print raises:I’m not sure if this is intended behavior though.
Likely cause
In stdio.py, stdio is wrapped like this:
python-sdk/src/mcp/server/stdio.py
Lines 44 to 47 in 5301298
When these wrappers are closed, they also close the sys.stdin.buffer / sys.stdout.buffer.
Proposed fix
Python & MCP Python SDK