Skip to content

fix: preserve stdin/stdout file descriptors after server exits#2244

Open
haroldfabla2-hue wants to merge 1 commit intomodelcontextprotocol:mainfrom
haroldfabla2-hue:fix/stdio-preserve-fd
Open

fix: preserve stdin/stdout file descriptors after server exits#2244
haroldfabla2-hue wants to merge 1 commit intomodelcontextprotocol:mainfrom
haroldfabla2-hue:fix/stdio-preserve-fd

Conversation

@haroldfabla2-hue
Copy link

Description

Using os.dup() to create copies of file descriptors prevents closing the original sys.stdin/sys.stdout when the TextIOWrapper is closed.

Fixes

Fixes #1933

Changes

  • Use os.dup() to create duplicate file descriptors for stdin/stdout
  • Use os.fdopen() with closefd=True to manage the duplicated fd
  • This prevents ValueError: I/O operation on closed file after the server exits

Testing

The fix can be tested by running:

from mcp.server.fastmcp import FastMCP

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

After exiting the server with Ctrl+D, the print should work without errors.

Using os.dup() to create copies of file descriptors prevents closing
the original sys.stdin/sys.stdout when the TextIOWrapper is closed.

Fixes: modelcontextprotocol#1933
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

1 participant