Skip to content

feat: use contextvar to pass process for easier access #513

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

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
9 changes: 9 additions & 0 deletions src/mcp/client/stdio/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import contextvars
import os
import sys
from contextlib import asynccontextmanager
Expand All @@ -6,6 +7,7 @@

import anyio
import anyio.lowlevel
from anyio.abc import Process
from anyio.streams.memory import MemoryObjectReceiveStream, MemoryObjectSendStream
from anyio.streams.text import TextReceiveStream
from pydantic import BaseModel, Field
Expand Down Expand Up @@ -92,6 +94,9 @@ class StdioServerParameters(BaseModel):
"""


PROCESS_VAR: contextvars.ContextVar[Process] = contextvars.ContextVar("process")


@asynccontextmanager
async def stdio_client(server: StdioServerParameters, errlog: TextIO = sys.stderr):
"""
Expand Down Expand Up @@ -169,9 +174,13 @@ async def stdin_writer():
):
tg.start_soon(stdout_reader)
tg.start_soon(stdin_writer)
token = None
try:
token = PROCESS_VAR.set(process)
yield read_stream, write_stream
finally:
if token is not None:
PROCESS_VAR.reset(token)
# Clean up process to prevent any dangling orphaned processes
if sys.platform == "win32":
await terminate_windows_process(process)
Expand Down
6 changes: 5 additions & 1 deletion tests/client/test_stdio.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import pytest

from mcp.client.stdio import StdioServerParameters, stdio_client
from mcp.client.stdio import PROCESS_VAR, StdioServerParameters, stdio_client
from mcp.types import JSONRPCMessage, JSONRPCRequest, JSONRPCResponse

tee: str = shutil.which("tee") # type: ignore
Expand Down Expand Up @@ -34,6 +34,10 @@ async def test_stdio_client():
if len(read_messages) == 2:
break

process = PROCESS_VAR.get()
assert process is not None
assert process.returncode is None

assert len(read_messages) == 2
assert read_messages[0] == JSONRPCMessage(
root=JSONRPCRequest(jsonrpc="2.0", id=1, method="ping")
Expand Down
Loading