modelcontextprotocol / modelcontextprotocol/python-sdk
Using transport="stdio" closes real stdio, causing ValueError after server exits
Nessuno ha ancora preso questa issue.
- Lingua principale
- Python
- Stelle
- 24.3k
- Fork
- 4k
- Merge medio
- 1g 1h
- PR unite (30g)
- 31
Descrizione
Initial Checks
- I confirm that I'm using the latest version of MCP Python SDK
- I confirm that I searched for my issue in https://github.com/modelcontextprotocol/python-sdk/issues before opening this issue
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
from mcp.server.fastmcp import FastMCP
mcp = 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:
https://github.com/modelcontextprotocol/python-sdk/blob/5301298225968ce0fa8ae62870f950709da14dc6/src/mcp/server/stdio.py#L44-L47
When these wrappers are closed, they also close the sys.stdin.buffer / sys.stdout.buffer.
Proposed fix
if not stdin:
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"))
if not stdout:
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
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Inizia in src/mcp/server/stdio.py, nella configurazione del wrapper intorno alle righe collegate, quindi esegui la riproduzione minima di FastMCP riportata nell'issue. Conferma che la chiusura dei wrapper stdio non chiuda più gli stream standard reali del processo e verifica che il print finale abbia esito positivo dopo l'uscita del server.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- backend
- Tipo di issue
- Bug
- Difficoltà
- 2/5
- Tempo stimato
- 1-3 ore
- Stato di attività
- Tranquilla
- Chiarezza
- Specificata chiaramente
- Idoneità per principianti
- 68/100