From c5782129bc5f314b98d808cbda1d9565ae703bea Mon Sep 17 00:00:00 2001 From: Lion Yang Date: Wed, 14 May 2025 01:36:33 +0800 Subject: [PATCH] Fix hanging on streams when stdio_client exiting (#559) --- src/mcp/client/stdio/__init__.py | 2 ++ tests/client/test_stdio.py | 7 +++++++ 2 files changed, 9 insertions(+) diff --git a/src/mcp/client/stdio/__init__.py b/src/mcp/client/stdio/__init__.py index e8be5af..6d815b4 100644 --- a/src/mcp/client/stdio/__init__.py +++ b/src/mcp/client/stdio/__init__.py @@ -181,6 +181,8 @@ async def stdio_client(server: StdioServerParameters, errlog: TextIO = sys.stder await terminate_windows_process(process) else: process.terminate() + await read_stream.aclose() + await write_stream.aclose() def _get_executable_command(command: str) -> str: diff --git a/tests/client/test_stdio.py b/tests/client/test_stdio.py index 523ba19..33d90e7 100644 --- a/tests/client/test_stdio.py +++ b/tests/client/test_stdio.py @@ -9,6 +9,13 @@ from mcp.types import JSONRPCMessage, JSONRPCRequest, JSONRPCResponse tee: str = shutil.which("tee") # type: ignore +@pytest.mark.anyio +@pytest.mark.skipif(tee is None, reason="could not find tee command") +async def test_stdio_context_manager_exiting(): + async with stdio_client(StdioServerParameters(command=tee)) as (_, _): + pass + + @pytest.mark.anyio @pytest.mark.skipif(tee is None, reason="could not find tee command") async def test_stdio_client():