diff --git a/docs/client/transports.md b/docs/client/transports.md index b41fe51348..d7010286d5 100644 --- a/docs/client/transports.md +++ b/docs/client/transports.md @@ -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`, diff --git a/src/mcp/client/stdio.py b/src/mcp/client/stdio.py index 6a3ad12111..4dceb3fa48 100644 --- a/src/mcp/client/stdio.py +++ b/src/mcp/client/stdio.py @@ -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 @@ -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 @@ -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 @@ -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, ) @@ -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" @@ -193,7 +215,7 @@ 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() @@ -201,6 +223,8 @@ async def shutdown() -> None: 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: @@ -208,14 +232,53 @@ async def shutdown() -> None: # 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: @@ -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: @@ -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) @@ -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. diff --git a/src/mcp/os/win32/utilities.py b/src/mcp/os/win32/utilities.py index 321fda8a66..8d6b3111e5 100644 --- a/src/mcp/os/win32/utilities.py +++ b/src/mcp/os/win32/utilities.py @@ -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__) @@ -23,6 +25,8 @@ import win32api import win32con import win32job + import win32pipe + import winerror else: # Type stubs for non-Windows platforms win32api = None @@ -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. @@ -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. @@ -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. @@ -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. @@ -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( @@ -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.""" diff --git a/tests/client/test_stdio.py b/tests/client/test_stdio.py index b64eb01902..4580d7599f 100644 --- a/tests/client/test_stdio.py +++ b/tests/client/test_stdio.py @@ -9,16 +9,19 @@ import errno import gc +import io import logging import math import os import signal +import subprocess import sys import threading from collections.abc import Callable from contextlib import AsyncExitStack, suppress +from functools import partial from pathlib import Path -from types import SimpleNamespace +from types import ModuleType, SimpleNamespace from typing import TextIO, cast import anyio @@ -1251,7 +1254,7 @@ async def recording_spawn( 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, ) -> anyio.abc.Process | FallbackProcess: process = await _create_platform_compatible_process(command, args, env, errlog, cwd) @@ -1279,6 +1282,191 @@ def _kill_spawn_groups(spawned: list[anyio.abc.Process | FallbackProcess]) -> No os.killpg(process.pid, signal.SIGKILL) +@pytest.mark.anyio +@pytest.mark.parametrize( + "anyio_backend", + [ + "asyncio", + # Trio 0.31 opens its Linux pidfd without encoding= (it never reads text from it). + pytest.param("trio", marks=pytest.mark.filterwarnings("ignore::EncodingWarning:trio._subprocess")), + ], +) +async def test_stderr_is_forwarded_to_a_stream_without_a_fileno(monkeypatch: pytest.MonkeyPatch) -> None: + """A Python-only stderr stream receives the server's final diagnostic on clean exit.""" + spawned = _record_spawned_processes(monkeypatch) + server = StdioServerParameters( + command=sys.executable, + args=["-c", "import sys; sys.stdin.read(); sys.stderr.buffer.write(b' final diagnostic\\n')"], + ) + + with io.StringIO() as errlog, anyio.fail_after(5): + async with stdio_client(server, errlog=errlog): + pass + + assert errlog.getvalue() == " final diagnostic\n" + assert spawned[0].returncode == 0 + + +@pytest.mark.anyio +@pytest.mark.parametrize("fileno_error", [AttributeError, OSError, ValueError, None]) +async def test_stderr_uses_the_current_sys_stderr_when_fileno_fails( + monkeypatch: pytest.MonkeyPatch, fileno_error: type[Exception] | None +) -> None: + """A replacement installed after import receives the subprocess diagnostics.""" + + class Errlog(io.StringIO): + def fileno(self) -> int: + if fileno_error is not None: + raise fileno_error("no file descriptor") + return -1 + + server = StdioServerParameters( + command=sys.executable, + args=["-c", "import sys; sys.stdin.read(); sys.stderr.buffer.write(b'diagnostic')"], + ) + with Errlog() as errlog, anyio.fail_after(5): + monkeypatch.setattr(sys, "stderr", errlog) + async with stdio_client(server): + pass + assert errlog.getvalue() == "diagnostic" + + +@pytest.mark.anyio +@pytest.mark.parametrize("notebook_stream", [False, True]) +async def test_stderr_uses_the_correct_destination_for_streams_with_a_fileno( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, notebook_stream: bool +) -> None: + """A file receives the original bytes and a notebook stream receives Python text.""" + path = tmp_path / "stderr.log" + with path.open("w", encoding="utf-8") as file: + + class OutStream(io.StringIO): + def fileno(self) -> int: + return file.fileno() + + iostream = ModuleType("ipykernel.iostream") + setattr(iostream, "OutStream", OutStream) + monkeypatch.setitem(sys.modules, "ipykernel.iostream", iostream) + server = StdioServerParameters( + command=sys.executable, + args=["-c", "import sys; sys.stdin.read(); sys.stderr.buffer.write(b'caf\\xe9\\n')"], + encoding="latin-1", + ) + + with OutStream() as outstream: + assert outstream.fileno() == file.fileno() + monkeypatch.setattr(sys, "stderr", outstream if notebook_stream else file) + with anyio.fail_after(5): + async with stdio_client(server): + pass + + assert outstream.getvalue() == ("café\n" if notebook_stream else "") + assert path.read_bytes() == (b"" if notebook_stream else b"caf\xe9\n") + + +@pytest.mark.anyio +async def test_popen_fallback_delivers_stderr_and_exits_when_another_writer_holds_the_pipe( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """An inherited stderr writer cannot force the fallback client to wait for EOF.""" + read_fd, write_fd = os.pipe() + finished = anyio.Event() + + async def spawn_fallback( + command: str, args: list[str], env: dict[str, str], errlog: int | None, cwd: Path | str | None + ) -> FallbackProcess: + assert errlog == subprocess.PIPE + # On POSIX Popen blocks in an exec handshake, so start it in a worker. + popen = await anyio.to_thread.run_sync( + partial( + subprocess.Popen, + [command, *args], + env=env, + cwd=cwd, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=stderr_writer, + bufsize=0, + ) + ) + popen.stderr = stderr_reader + return FallbackProcess(popen) + + async def hold_writer_open() -> None: + try: + with anyio.fail_after(5): + await finished.wait() + finally: + stderr_writer.close() + + monkeypatch.setattr(stdio, "_create_platform_compatible_process", spawn_fallback) + server = StdioServerParameters( + command=sys.executable, + args=["-c", "import sys; sys.stdin.read(); sys.stderr.buffer.write(b'fallback diagnostic')"], + ) + with ( + os.fdopen(read_fd, "rb", buffering=0) as stderr_reader, + os.fdopen(write_fd, "wb", buffering=0) as stderr_writer, + io.StringIO() as errlog, + ): + async with anyio.create_task_group() as tg: + tg.start_soon(hold_writer_open) + async with stdio_client(server, errlog=errlog): + pass + finished.set() + assert stderr_reader.closed + assert errlog.getvalue() == "fallback diagnostic" + + +@pytest.mark.anyio +async def test_stderr_uses_inherited_stderr_when_sys_stderr_is_unavailable(monkeypatch: pytest.MonkeyPatch) -> None: + """A process can start on hosts that have no Python stderr stream.""" + spawned = _record_spawned_processes(monkeypatch) + monkeypatch.setattr(sys, "stderr", None) + server = StdioServerParameters(command=sys.executable, args=["-c", "import sys; sys.stdin.read()"]) + with anyio.fail_after(5): + async with stdio_client(server): + pass + assert spawned[0].returncode == 0 + + +@pytest.mark.anyio +async def test_stderr_applies_the_configured_decode_error_handler_at_eof() -> None: + """An incomplete character at EOF is forwarded with the configured replacement.""" + server = StdioServerParameters( + command=sys.executable, + args=["-c", "import sys; sys.stdin.read(); sys.stderr.buffer.write(b'diagnostic: \\xc3')"], + encoding_error_handler="replace", + ) + with io.StringIO() as errlog, anyio.fail_after(5): + async with stdio_client(server, errlog=errlog): + pass + assert errlog.getvalue() == "diagnostic: \ufffd" + + +@pytest.mark.anyio +@pytest.mark.parametrize("closed_logging_handler", [False, True]) +async def test_a_closed_errlog_does_not_stop_stderr_from_draining( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, closed_logging_handler: bool +) -> None: + """A server flushing more than a pipe's capacity still exits if its destination closes.""" + spawned = _record_spawned_processes(monkeypatch) + server = StdioServerParameters( + command=sys.executable, + args=["-c", "import sys; sys.stdin.read(); sys.stderr.buffer.write(b'x' * 2_000_000)"], + ) + with io.StringIO() as errlog, monkeypatch.context() as patch, anyio.fail_after(5): + if closed_logging_handler: + patch.setattr(logging, "raiseExceptions", True) + patch.setattr(stdio.logger, "handlers", [logging.StreamHandler(errlog)]) + patch.setattr(sys, "stderr", errlog) + async with stdio_client(server, errlog=errlog): + errlog.close() + assert spawned[0].returncode == 0 + if not closed_logging_handler: + assert any("Forwarding the MCP server's stderr failed" in record.message for record in caplog.records) + + @pytest.mark.anyio async def test_exiting_the_context_terminates_the_entire_process_tree(monkeypatch: pytest.MonkeyPatch) -> None: """Exiting `stdio_client` kills the server's whole process tree. @@ -1444,8 +1632,8 @@ async def test_a_graceful_exit_with_a_surviving_child_leaks_no_pipe_fds( # prag baseline = set(os.listdir("/proc/self/fd")) # Two interpreter cold starts on a loaded runner; healthy runs take ~0.3s. - with anyio.fail_after(15.0): - async with stdio_client(server_params): + with io.StringIO() as errlog, anyio.fail_after(15.0): + async with stdio_client(server_params, errlog=errlog): stream = await _accept_alive(sock) await stream.aclose() diff --git a/tests/transports/stdio/conftest.py b/tests/transports/stdio/conftest.py index e9601ac6d5..dc283c14ab 100644 --- a/tests/transports/stdio/conftest.py +++ b/tests/transports/stdio/conftest.py @@ -37,7 +37,7 @@ async def recording_spawn( 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, ) -> anyio.abc.Process | FallbackProcess: process = await _create_platform_compatible_process(command, args, env, errlog, cwd) diff --git a/tests/transports/stdio/test_windows.py b/tests/transports/stdio/test_windows.py index 8eb12832da..f3e9e089ca 100644 --- a/tests/transports/stdio/test_windows.py +++ b/tests/transports/stdio/test_windows.py @@ -4,6 +4,7 @@ """ import asyncio +import io import sys from contextlib import AsyncExitStack from pathlib import Path @@ -119,7 +120,7 @@ async def test_a_selector_event_loop_session_uses_the_fallback_process_and_exits ) -> None: """`stdio_client` uses `FallbackProcess` under `SelectorEventLoop`. - This covers clean exit because forced shutdown can strand the fallback reader thread. + This covers clean exit and delivery of stderr to a Python-only stream. """ async with AsyncExitStack() as stack: sock, port = await open_liveness_listener() @@ -130,15 +131,17 @@ async def test_a_selector_event_loop_session_uses_the_fallback_process_and_exits f"s = socket.create_connection(('127.0.0.1', {port}))\n" f"s.sendall(b'alive')\n" f"sys.stdin.read()\n" + f"sys.stderr.buffer.write(b'selector diagnostic')\n" ) server_params = StdioServerParameters(command=sys.executable, args=["-c", server]) # Allow one cold interpreter start on loaded CI. - with anyio.fail_after(10.0): - async with stdio_client(server_params): + with io.StringIO() as errlog, anyio.fail_after(10.0): + async with stdio_client(server_params, errlog=errlog): stream = await accept_alive(sock) stack.push_async_callback(stream.aclose) assert isinstance(spawned_processes[0], FallbackProcess) + assert errlog.getvalue() == "selector diagnostic" await assert_stream_closed(stream) assert spawned_processes[0].returncode == 0