Skip to content

Commit 685115b

Browse files
use closefd=False per review feedback
1 parent d990d43 commit 685115b

1 file changed

Lines changed: 5 additions & 10 deletions

File tree

src/mcp/server/stdio.py

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ async def run_server():
1717
```
1818
"""
1919

20-
import os
2120
import sys
2221
from contextlib import asynccontextmanager
2322
from io import TextIOWrapper
@@ -35,17 +34,13 @@ async def stdio_server(stdin: anyio.AsyncFile[str] | None = None, stdout: anyio.
3534
"""Server transport for stdio: this communicates with an MCP client by reading
3635
from the current process' stdin and writing to stdout.
3736
"""
38-
# Encoding of stdin/stdout as text streams on python is platform-dependent
39-
# (Windows is particularly problematic), so we re-wrap the underlying binary
40-
# stream to ensure UTF-8. We duplicate the file descriptors first so that
41-
# closing the wrapper doesn't close the real process stdio handles.
37+
# Re-wrap the `fd` with `closefd=False` to force UTF-8 (Windows encoding is
38+
# platform-dependant) without taking ownership of process stdio.
4239
if not stdin:
43-
stdin_fd = os.dup(sys.stdin.buffer.fileno())
44-
stdin = anyio.wrap_file(TextIOWrapper(os.fdopen(stdin_fd, "rb"), encoding="utf-8"))
40+
stdin = anyio.wrap_file(TextIOWrapper(open(sys.stdin.fileno(), "rb", closefd=False), encoding="utf-8"))
4541
if not stdout:
46-
stdout_fd = os.dup(sys.stdout.buffer.fileno())
47-
stdout = anyio.wrap_file(TextIOWrapper(os.fdopen(stdout_fd, "wb"), encoding="utf-8"))
48-
42+
stdout = anyio.wrap_file(TextIOWrapper(open(sys.stdout.fileno(), "wb", closefd=False), encoding="utf-8"))
43+
4944
read_stream: MemoryObjectReceiveStream[SessionMessage | Exception]
5045
read_stream_writer: MemoryObjectSendStream[SessionMessage | Exception]
5146

0 commit comments

Comments
 (0)