Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion docs/client/transports.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,10 @@ Describe the process with `StdioServerParameters` and hand it to `Client`:

Entering the block spawns the process. Leaving it shuts the subprocess down: close stdin, wait, kill if it lingers. You never clean it up yourself.

The child's stderr goes to yours. To send it somewhere else, build the transport yourself with `stdio_client` (from `mcp`) and pass that instead: `Client(stdio_client(server, errlog=log_file))`.
The child's stderr goes to the current `sys.stderr`, including the output stream in a Jupyter notebook.
To send it elsewhere, pass a text stream to `stdio_client` (from `mcp`), as in `Client(stdio_client(server, errlog=log_file))`.
When the client forwards stderr to a Python stream such as a notebook stream or `io.StringIO`,
it decodes the output using the server's `encoding` and `encoding_error_handler`.

!!! warning
The child does **not** inherit your environment. It gets a minimal allow-list (`HOME`, `LOGNAME`,
Expand Down
88 changes: 78 additions & 10 deletions src/mcp/client/stdio.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
"""stdio client transport.

Runs an MCP server as a subprocess and exchanges newline-delimited JSON-RPC
messages with it over stdin/stdout. Two pipe tasks bridge the server's pipes
to the session's in-memory streams; shutdown follows the MCP spec sequence
messages with it over stdin/stdout. Pipe tasks bridge the server's pipes to
the session's in-memory streams. Shutdown follows the MCP spec sequence
(close stdin, wait, then kill the process tree) inside a cancellation shield
with every wait bounded, so a cancelled caller can neither leak a live server
process nor hang on one.
"""

import codecs
import logging
import os
import subprocess
import sys
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager, suppress
Expand All @@ -20,7 +22,7 @@
import anyio.lowlevel
import anyio.to_thread
import mcp_types as types
from anyio.abc import AsyncResource, Process
from anyio.abc import AsyncResource, ByteReceiveStream, Process
from anyio.streams.text import TextReceiveStream
from pydantic import BaseModel, Field

Expand Down Expand Up @@ -69,6 +71,9 @@
# Time for the writer to flush accepted messages before stdin closes.
_WRITER_FLUSH_TIMEOUT = 0.5

# Time to deliver remaining stderr after the server exits.
_STDERR_DRAIN_TIMEOUT = 0.5

# How often to poll returncode while waiting for the process to die.
_EXIT_POLL_INTERVAL = 0.01

Expand Down Expand Up @@ -113,21 +118,25 @@ class StdioServerParameters(BaseModel):

@asynccontextmanager
async def stdio_client(
server: StdioServerParameters, errlog: TextIO = sys.stderr
server: StdioServerParameters, errlog: TextIO | None = None
) -> AsyncGenerator[TransportStreams, None]:
"""Spawns an MCP server subprocess and connects to it over stdin/stdout.

The server's stderr is sent to `errlog`, defaulting to the current `sys.stderr`.

Raises:
OSError: If the server process cannot be spawned.
ValueError: If the spawn parameters are invalid (embedded NUL bytes).
"""
command = await _get_executable_command(server.command)
errlog = sys.stderr if errlog is None else errlog
stderr = _stderr_redirect(errlog)

process = await _create_platform_compatible_process(
command=command,
args=server.args,
env=get_default_environment() | (server.env or {}),
errlog=errlog,
errlog=stderr,
cwd=server.cwd,
)

Expand All @@ -138,6 +147,19 @@ async def stdio_client(

shutting_down = False
writer_done = anyio.Event()
stderr_done = anyio.Event() if stderr == subprocess.PIPE else None
stderr_scope = anyio.CancelScope(shield=True) if stderr_done is not None else None

async def stderr_reader() -> None:
assert (
errlog is not None and process.stderr is not None and stderr_done is not None and stderr_scope is not None
)
# Keep draining while caller cancellation closes stdin and stops the server.
try:
with stderr_scope:
await _forward_stderr(process.stderr, errlog, server)
finally:
stderr_done.set()

async def stdout_reader() -> None:
assert process.stdout, "Opened process is missing stdout"
Expand Down Expand Up @@ -193,29 +215,70 @@ async def shutdown() -> None:
await writer_done.wait()
if flush_scope.cancelled_caught:
await anyio.lowlevel.cancel_shielded_checkpoint() # resync coverage on 3.11 (gh-106749)
await _stop_server_process(process)
await _stop_server_process(process, stderr_done)
await _aclose_all(read_stream, write_stream, read_stream_writer, write_stream_reader)
# One pass so unblocked tasks exit via their except paths before the cancel.
await anyio.lowlevel.checkpoint()

async with anyio.create_task_group() as tg:
tg.start_soon(stdout_reader)
tg.start_soon(stdin_writer)
if stderr_done is not None:
tg.start_soon(stderr_reader)
try:
yield read_stream, write_stream
finally:
shutting_down = True
# Shutdown must finish even under caller cancellation, or the server
# process would leak; every wait inside is bounded. (Native
# task.cancel() and the fallback's worker threads can still defeat it.)
with anyio.CancelScope(shield=True):
await shutdown()
try:
with anyio.CancelScope(shield=True):
await shutdown()
finally:
if stderr_scope is not None:
stderr_scope.cancel()
# Unstick pipe tasks a kill survivor's open pipe end could still block.
tg.cancel_scope.cancel()
# The cancel lands via throw(); one yield resyncs 3.11 coverage (gh-106749).
await anyio.lowlevel.cancel_shielded_checkpoint()


def _stderr_redirect(errlog: TextIO | None) -> int | None:
if errlog is None:
return None
# OutStream.fileno() can point to the original terminal and bypass the notebook.
outstream = getattr(sys.modules.get("ipykernel.iostream"), "OutStream", None)
if isinstance(outstream, type) and isinstance(errlog, outstream):
return subprocess.PIPE
try:
fd = errlog.fileno()
except (AttributeError, OSError, ValueError):
return subprocess.PIPE
return fd if fd >= 0 else subprocess.PIPE


async def _forward_stderr(stderr: ByteReceiveStream, errlog: TextIO, server: StdioServerParameters) -> None:
def write(chunk: bytes) -> None:
if text := decoder.decode(chunk, final=not chunk):
errlog.write(text)
errlog.flush()

with suppress(anyio.ClosedResourceError, anyio.BrokenResourceError, ConnectionError):
try:
decoder = codecs.getincrementaldecoder(server.encoding)(errors=server.encoding_error_handler)
async for chunk in stderr:
await anyio.to_thread.run_sync(write, chunk, abandon_on_cancel=True)
await anyio.to_thread.run_sync(write, b"", abandon_on_cancel=True)
except (LookupError, OSError, ValueError):
# The logger can also be configured to write to the failed destination.
with suppress(OSError, ValueError):
logger.exception("Forwarding the MCP server's stderr failed")
# A failed destination must not leave the child blocked on a full pipe.
async for _ in stderr:
pass


def _parse_line(line: str) -> SessionMessage | Exception:
"""Parses one stdout line, returning parse errors as values for the session to surface."""
try:
Expand Down Expand Up @@ -246,7 +309,7 @@ async def _drain_stdout(process: ServerProcess) -> None:
await process.stdout.receive()


async def _stop_server_process(process: ServerProcess) -> None:
async def _stop_server_process(process: ServerProcess, stderr_done: anyio.Event | None = None) -> None:
"""Closes stdin, waits out the grace period, then kills the whole tree.

The escalation order is spec text; timeouts and tree-wide scope are SDK policy:
Expand All @@ -263,6 +326,11 @@ async def _stop_server_process(process: ServerProcess) -> None:

# Reaps surviving Windows job members now, not at GC; no-op on POSIX.
close_process_job(process)
if stderr_done is not None:
assert process.stderr is not None
with anyio.move_on_after(_STDERR_DRAIN_TIMEOUT):
await stderr_done.wait()
await _close_pipe(process.stderr)
# A kill survivor can hold the stdout pipe open; poison the reader anyway.
await _close_pipe(process.stdout)
_close_subprocess_transport(process)
Expand Down Expand Up @@ -330,7 +398,7 @@ async def _create_platform_compatible_process(
command: str,
args: list[str],
env: dict[str, str] | None = None,
errlog: TextIO = sys.stderr,
errlog: TextIO | int | None = sys.stderr,
cwd: Path | str | None = None,
) -> ServerProcess:
"""Spawns the server in its own kill scope.
Expand Down
58 changes: 53 additions & 5 deletions src/mcp/os/win32/utilities.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
"""Windows-specific functionality for stdio transport operations."""

import logging
import os
import shutil
import subprocess
import sys
import weakref
from contextlib import suppress
from io import FileIO
from pathlib import Path
from typing import BinaryIO, TextIO, TypeAlias, cast

import anyio
from anyio.abc import Process
from anyio.abc import ByteReceiveStream, Process
from anyio.streams.file import FileReadStream, FileWriteStream

logger = logging.getLogger(__name__)
Expand All @@ -23,6 +25,8 @@
import win32api
import win32con
import win32job
import win32pipe
import winerror
else:
# Type stubs for non-Windows platforms
win32api = None
Expand Down Expand Up @@ -51,7 +55,7 @@ def rebind_std_handle_to_fd(fd: int) -> None:
raise OSError(f"SetStdHandle failed for fd {fd}") from exc


# How often FallbackProcess polls the underlying Popen for exit.
# How often the Popen fallback polls for exit or pending pipe data.
_EXIT_POLL_INTERVAL = 0.01

# Job Object handle per spawned process, for tree termination at shutdown.
Expand Down Expand Up @@ -81,6 +85,46 @@ def get_windows_executable_command(command: str) -> str:
return command # path probing failed (permissions, broken symlinks)


class _FallbackStderr(ByteReceiveStream):
"""Reads the fallback stderr pipe without parking a worker in a blocking read."""

def __init__(self, pipe: FileIO) -> None:
self._pipe = pipe
if sys.platform != "win32":
os.set_blocking(pipe.fileno(), False)

def _read_nowait(self, max_bytes: int) -> bytes | None:
if sys.platform == "win32":
handle = msvcrt.get_osfhandle(self._pipe.fileno())
try:
_, pending, _ = win32pipe.PeekNamedPipe(handle, 0)
except pywintypes.error as exc:
if exc.winerror == winerror.ERROR_BROKEN_PIPE:
return b""
raise anyio.BrokenResourceError from exc
if not pending:
return None
max_bytes = min(max_bytes, pending)
return self._pipe.read(max_bytes)

async def receive(self, max_bytes: int = 65536) -> bytes:
if max_bytes < 1:
raise ValueError("max_bytes must be a positive integer")
try:
while (chunk := self._read_nowait(max_bytes)) is None:
await anyio.sleep(_EXIT_POLL_INTERVAL)
except ValueError:
raise anyio.ClosedResourceError from None
except OSError as exc:
raise anyio.BrokenResourceError from exc
if not chunk:
raise anyio.EndOfStream
return chunk

async def aclose(self) -> None:
self._pipe.close()


class FallbackProcess:
"""Async wrapper around subprocess.Popen for SelectorEventLoop.

Expand All @@ -92,9 +136,13 @@ def __init__(self, popen_obj: subprocess.Popen[bytes]) -> None:
self.popen: subprocess.Popen[bytes] = popen_obj
stdin = popen_obj.stdin
stdout = popen_obj.stdout
stderr = popen_obj.stderr

self.stdin = FileWriteStream(cast(BinaryIO, stdin)) if stdin else None
self.stdout = FileReadStream(cast(BinaryIO, stdout)) if stdout else None
# Popen uses FileIO for pipes when bufsize=0.
assert stderr is None or isinstance(stderr, FileIO)
self.stderr = _FallbackStderr(stderr) if stderr is not None else None

async def wait(self) -> int:
"""Waits for exit by polling the Popen.
Expand Down Expand Up @@ -137,7 +185,7 @@ async def create_windows_process(
command: str,
args: list[str],
env: dict[str, str] | None = None,
errlog: TextIO | None = sys.stderr,
errlog: TextIO | int | None = sys.stderr,
cwd: Path | str | None = None,
) -> Process | FallbackProcess:
"""Creates a subprocess with Job Object support for tree termination.
Expand All @@ -150,7 +198,7 @@ async def create_windows_process(
(see the inline note below).

Returns:
Process | FallbackProcess: The spawned process with async stdin/stdout streams.
Process | FallbackProcess: The spawned process with async streams for its pipes.
"""
try:
process = await anyio.open_process(
Expand All @@ -177,7 +225,7 @@ async def _create_windows_fallback_process(
command: str,
args: list[str],
env: dict[str, str] | None = None,
errlog: TextIO | None = sys.stderr,
errlog: TextIO | int | None = sys.stderr,
cwd: Path | str | None = None,
) -> FallbackProcess:
"""Spawns via subprocess.Popen and wraps it in FallbackProcess."""
Expand Down
Loading
Loading