modelcontextprotocol / modelcontextprotocol/python-sdk
Using transport="stdio" closes real stdio, causing ValueError after server exits
Personne n'a encore pris cette issue.
- Langage dominant
- Python
- Étoiles
- 24.3k
- Forks
- 4k
- Merge moyen
- 1 j 1 h
- PR mergées (30 j)
- 31
Description
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
Guide de contribution
Ouvrir le guide de contribution
Par où commencer
- Lisez l'issue en entier, puis le guide de contribution du projet.
- Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
- Forkez le dépôt et travaillez sur une branche.
- Ouvrez une pull request qui référence le numéro de l'issue.
Piste de recherche
Commencez dans src/mcp/server/stdio.py, autour de la configuration du wrapper aux lignes indiquées, puis exécutez la reproduction minimale de FastMCP fournie dans l’issue. Vérifiez que la fermeture des wrappers stdio ne ferme plus les flux standard réels du processus, et vérifiez que le print final s’exécute correctement après l’arrêt du serveur.
Rédigé par le modèle d'indexation à partir du texte de l'issue.
Évaluation
- Stack technique
- python
- Domaine
- backend
- Type d'issue
- Bug
- Difficulté
- 2/5
- Temps estimé
- 1-3 heures
- Activité
- Calme
- Clarté
- Clairement spécifiée
- Accessibilité débutants
- 68/100