Skip to content

Win32 fixes #723

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 19 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
9a797c2
Add Windows-specific test for process creation to prevent hanging
DanielAvdar May 13, 2025
1fba897
Merge branch 'modelcontextprotocol:main' into #552
DanielAvdar May 13, 2025
2f25562
Merge branch 'main' into #552
DanielAvdar May 13, 2025
0ec5bc0
Merge branch 'main' into #552
DanielAvdar May 14, 2025
289281b
Merge branch 'main' into #552
DanielAvdar May 14, 2025
7a84ecb
Fix Windows hang in test by properly using stdio_client
DanielAvdar May 14, 2025
90f2cc1
Update timeout in test_552_windows_hang.py and handle additional exce…
DanielAvdar May 14, 2025
8c6fc2a
Update error assertions in test_552_windows_hang to check for expecte…
DanielAvdar May 14, 2025
bd6cc71
Add version check for asyncio.timeout in Windows-specific test
DanielAvdar May 14, 2025
fb09415
Merge branch 'main' into #552
DanielAvdar May 15, 2025
8ba9b5e
Merge branch 'main' into #552
DanielAvdar May 15, 2025
d1a76ad
Refactor stdio client to modularize transport and parameters
DanielAvdar May 15, 2025
4aab29a
Merge branch 'main' into win32-fixes
DanielAvdar May 15, 2025
947a37a
Refactor test to use parameterized arguments.
DanielAvdar May 15, 2025
a5b53cf
Merge branch 'main' into #552
DanielAvdar May 15, 2025
8e0e369
Refactor stdio client to modularize transport and parameters
DanielAvdar May 15, 2025
ac6950f
Merge remote-tracking branch 'origin/win32-fixes' into win32-fixes
DanielAvdar May 15, 2025
606a499
Disable stdout reader task initialization in transport.py
DanielAvdar May 16, 2025
8c42202
Handle ProcessLookupError in win32.py to ensure process termination
DanielAvdar May 16, 2025
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
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ dev = [
"pytest-xdist>=3.6.1",
"pytest-examples>=0.0.14",
"pytest-pretty>=1.2.0",
"pytest-cov>=6.1.1",
]
docs = [
"mkdocs>=1.6.1",
Expand Down
222 changes: 11 additions & 211 deletions src/mcp/client/stdio/__init__.py
Original file line number Diff line number Diff line change
@@ -1,222 +1,22 @@
import os
import sys
from contextlib import asynccontextmanager
from pathlib import Path
from typing import Literal, TextIO
from typing import TextIO

import anyio
import anyio.lowlevel
from anyio.streams.memory import MemoryObjectReceiveStream, MemoryObjectSendStream
from anyio.streams.text import TextReceiveStream
from pydantic import BaseModel, Field

import mcp.types as types
from mcp.shared.message import SessionMessage

from .win32 import (
create_windows_process,
get_windows_executable_command,
terminate_windows_process,
)

# Environment variables to inherit by default
DEFAULT_INHERITED_ENV_VARS = (
[
"APPDATA",
"HOMEDRIVE",
"HOMEPATH",
"LOCALAPPDATA",
"PATH",
"PROCESSOR_ARCHITECTURE",
"SYSTEMDRIVE",
"SYSTEMROOT",
"TEMP",
"USERNAME",
"USERPROFILE",
]
if sys.platform == "win32"
else ["HOME", "LOGNAME", "PATH", "SHELL", "TERM", "USER"]
)


def get_default_environment() -> dict[str, str]:
"""
Returns a default environment object including only environment variables deemed
safe to inherit.
"""
env: dict[str, str] = {}

for key in DEFAULT_INHERITED_ENV_VARS:
value = os.environ.get(key)
if value is None:
continue

if value.startswith("()"):
# Skip functions, which are a security risk
continue

env[key] = value

return env


class StdioServerParameters(BaseModel):
command: str
"""The executable to run to start the server."""

args: list[str] = Field(default_factory=list)
"""Command line arguments to pass to the executable."""

env: dict[str, str] | None = None
"""
The environment to use when spawning the process.

If not specified, the result of get_default_environment() will be used.
"""

cwd: str | Path | None = None
"""The working directory to use when spawning the process."""

encoding: str = "utf-8"
"""
The text encoding used when sending/receiving messages to the server

defaults to utf-8
"""

encoding_error_handler: Literal["strict", "ignore", "replace"] = "strict"
"""
The text encoding error handler.

See https://docs.python.org/3/library/codecs.html#codec-base-classes for
explanations of possible values
"""
# Import from the new files
from .parameters import StdioServerParameters
from .transport import StdioClientTransport


@asynccontextmanager
async def stdio_client(server: StdioServerParameters, errlog: TextIO = sys.stderr):
"""
Client transport for stdio: this will connect to a server by spawning a
process and communicating with it over stdin/stdout.
Client transport for stdio: connects to a server by spawning a process
and communicating with it over stdin/stdout, managed by StdioClientTransport.
"""
read_stream: MemoryObjectReceiveStream[SessionMessage | Exception]
read_stream_writer: MemoryObjectSendStream[SessionMessage | Exception]

write_stream: MemoryObjectSendStream[SessionMessage]
write_stream_reader: MemoryObjectReceiveStream[SessionMessage]

read_stream_writer, read_stream = anyio.create_memory_object_stream(0)
write_stream, write_stream_reader = anyio.create_memory_object_stream(0)

command = _get_executable_command(server.command)

# Open process with stderr piped for capture
process = await _create_platform_compatible_process(
command=command,
args=server.args,
env=(
{**get_default_environment(), **server.env}
if server.env is not None
else get_default_environment()
),
errlog=errlog,
cwd=server.cwd,
)

async def stdout_reader():
assert process.stdout, "Opened process is missing stdout"

try:
async with read_stream_writer:
buffer = ""
async for chunk in TextReceiveStream(
process.stdout,
encoding=server.encoding,
errors=server.encoding_error_handler,
):
lines = (buffer + chunk).split("\n")
buffer = lines.pop()

for line in lines:
try:
message = types.JSONRPCMessage.model_validate_json(line)
except Exception as exc:
await read_stream_writer.send(exc)
continue

session_message = SessionMessage(message)
await read_stream_writer.send(session_message)
except anyio.ClosedResourceError:
await anyio.lowlevel.checkpoint()

async def stdin_writer():
assert process.stdin, "Opened process is missing stdin"
transport = StdioClientTransport(server_params=server, errlog=errlog)
async with transport as streams:
yield streams

try:
async with write_stream_reader:
async for session_message in write_stream_reader:
json = session_message.message.model_dump_json(
by_alias=True, exclude_none=True
)
await process.stdin.send(
(json + "\n").encode(
encoding=server.encoding,
errors=server.encoding_error_handler,
)
)
except anyio.ClosedResourceError:
await anyio.lowlevel.checkpoint()

async with (
anyio.create_task_group() as tg,
process,
):
tg.start_soon(stdout_reader)
tg.start_soon(stdin_writer)
try:
yield read_stream, write_stream
finally:
# Clean up process to prevent any dangling orphaned processes
if sys.platform == "win32":
await terminate_windows_process(process)
else:
process.terminate()
await read_stream.aclose()
await write_stream.aclose()


def _get_executable_command(command: str) -> str:
"""
Get the correct executable command normalized for the current platform.

Args:
command: Base command (e.g., 'uvx', 'npx')

Returns:
str: Platform-appropriate command
"""
if sys.platform == "win32":
return get_windows_executable_command(command)
else:
return command


async def _create_platform_compatible_process(
command: str,
args: list[str],
env: dict[str, str] | None = None,
errlog: TextIO = sys.stderr,
cwd: Path | str | None = None,
):
"""
Creates a subprocess in a platform-compatible way.
Returns a process handle.
"""
if sys.platform == "win32":
process = await create_windows_process(command, args, env, errlog, cwd)
else:
process = await anyio.open_process(
[command, *args], env=env, stderr=errlog, cwd=cwd
)

return process
# Ensure __all__ or exports are updated if this was a public API change, though
# stdio_client itself remains the primary public entry point from this file.
78 changes: 78 additions & 0 deletions src/mcp/client/stdio/parameters.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import os
import sys
from pathlib import Path
from typing import Literal

from pydantic import BaseModel, Field

# Environment variables to inherit by default
DEFAULT_INHERITED_ENV_VARS = (
[
"APPDATA",
"HOMEDRIVE",
"HOMEPATH",
"LOCALAPPDATA",
"PATH",
"PROCESSOR_ARCHITECTURE",
"SYSTEMDRIVE",
"SYSTEMROOT",
"TEMP",
"USERNAME",
"USERPROFILE",
]
if sys.platform == "win32"
else ["HOME", "LOGNAME", "PATH", "SHELL", "TERM", "USER"]
)


def get_default_environment() -> dict[str, str]:
"""Returns a default environment object including only environment variables deemed
safe to inherit.
"""
env: dict[str, str] = {}

for key in DEFAULT_INHERITED_ENV_VARS:
value = os.environ.get(key)
if value is None:
continue

if value.startswith("()"):
# Skip functions, which are a security risk
continue

env[key] = value

return env


class StdioServerParameters(BaseModel):
command: str
"""The executable to run to start the server."""

args: list[str] = Field(default_factory=list)
"""Command line arguments to pass to the executable."""

env: dict[str, str] | None = None
"""
The environment to use when spawning the process.

If not specified, the result of get_default_environment() will be used.
"""

cwd: str | Path | None = None
"""The working directory to use when spawning the process."""

encoding: str = "utf-8"
"""
The text encoding used when sending/receiving messages to the server

defaults to utf-8
"""

encoding_error_handler: Literal["strict", "ignore", "replace"] = "strict"
"""
The text encoding error handler.

See https://docs.python.org/3/library/codecs.html#codec-base-classes for
explanations of possible values
"""
Loading
Loading