fix: dup file descriptors in stdio_server to avoid closing real stdin/stdout#2172
Open
giulio-leone wants to merge 2 commits intomodelcontextprotocol:mainfrom
Open
fix: dup file descriptors in stdio_server to avoid closing real stdin/stdout#2172giulio-leone wants to merge 2 commits intomodelcontextprotocol:mainfrom
giulio-leone wants to merge 2 commits intomodelcontextprotocol:mainfrom
Conversation
…/stdout TextIOWrapper(sys.stdin.buffer) shares the underlying fd with sys.stdin. When the wrapper is closed (or garbage-collected) after the server exits, it also closes sys.stdin.buffer, making any subsequent stdio operation raise `ValueError: I/O operation on closed file`. Use `os.dup()` to duplicate the fd before wrapping, so closing the wrapper only closes the duplicate while leaving the original process handles intact. Fixes modelcontextprotocol#1933 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
Running a server with
transport="stdio"closes the realsys.stdin/sys.stdoutwhen the server exits. Any subsequent stdio operation raises:Root Cause
TextIOWrapper(sys.stdin.buffer)shares the underlying file descriptor withsys.stdin. When theTextIOWrapperis closed (or garbage-collected) after the server exits, it also closessys.stdin.buffer, making any subsequent stdio operation fail.Solution
Use
os.dup()to duplicate the file descriptor before wrapping it inTextIOWrapper. Closing the wrapper then only closes the duplicate fd while leaving the original process handles intact.Testing
sys.stdin.fileno()remains valid after closing the duplicated wrapperFixes #1933