| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
When running the MCP server with transport='stdio', closing the server would also close the process's real stdin/stdout handles. This caused ValueError when trying to use stdio after the server exits. The issue was that wrapping sys.stdin.buffer/sys.stdout.buffer with TextIOWrapper causes the underlying buffer to be closed when the wrapper is garbage collected, even if we don't use a context manager. Fix: Use os.dup() to duplicate the file descriptors before wrapping. When the duplicated descriptors are closed, the original stdin/stdout remain intact and usable. Fallback: For streams without a fileno() (e.g., BytesIO in tests), we fall back to wrapping them directly (previous behavior). Fixes #1933
|
Thanks for your contribution! Closing this in favour of #2040 as that predates this PR. |
Sorry, something went wrong.
| Back | FazBrowse Home | New Git URL |
Summary
Fixes #1933
When running the MCP server with transport='stdio', closing the server would also close the process's real stdin/stdout handles. This caused a ValueError: I/O operation on closed file when trying to use stdio after the server exits.
Problem
The issue was that wrapping sys.stdin.buffer/sys.stdout.buffer with TextIOWrapper causes the underlying buffer to be closed when the wrapper is garbage collected, even if we don't use a context manager. The old comment said "Purposely not using context managers for these, as we don't want to close standard process handles" but this didn't prevent the closing.
Solution
Use os.dup() to duplicate the file descriptors before wrapping. When the duplicated descriptors are closed (along with the TextIOWrapper), the original stdin/stdout remain intact and usable.
For streams without a fileno() (e.g., BytesIO in tests), we fall back to wrapping them directly (previous behavior).
Test Plan
Added a regression test test_stdio_server_does_not_close_real_stdio that:
All existing tests continue to pass.
Reproduction (from issue)