Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

stdio: stop an unshared subprocess when its session exits under cancellation (#5215)

nate nowackeb33eee76e43
diff --git a/fastmcp_slim/fastmcp/client/transports/stdio.py b/fastmcp_slim/fastmcp/client/transports/stdio.py
index 38cde685a..9bbe550ba 100644
--- a/fastmcp_slim/fastmcp/client/transports/stdio.py
+++ b/fastmcp_slim/fastmcp/client/transports/stdio.py
@@ -92,10 +92,12 @@ class StdioTransport(ClientTransport):
if not self.keep_alive:
# Other clients may still be using this transport. Serialize
# final cleanup with connect() so a new client cannot acquire
- # the session while it is being disconnected.
- async with self._connect_lock:
- if not self._active_sessions:
- await self.disconnect()
+ # the session while it is being disconnected. Shielded because
+ # an exit caused by cancellation must still stop the subprocess.
+ with anyio.CancelScope(shield=True):
+ async with self._connect_lock:
+ if not self._active_sessions:
+ await self.disconnect()
else:
logger.debug("Stdio transport has keep_alive=True, not disconnecting")
diff --git a/tests/client/test_stdio.py b/tests/client/test_stdio.py
index ecbc369bb..60f080f82 100644
--- a/tests/client/test_stdio.py
+++ b/tests/client/test_stdio.py
@@ -6,6 +6,7 @@ import time
import weakref
from pathlib import Path
+import anyio
import psutil
import pytest
from mcp.shared.exceptions import MCPError
@@ -309,6 +310,20 @@ class TestKeepAlive:
await wait_for_process_exit(pid)
+ async def test_cancelled_scope_still_stops_unshared_subprocess(self, stdio_script):
+ transport = PythonStdioTransport(stdio_script, keep_alive=False)
+ pid: int | None = None
+
+ with anyio.CancelScope() as scope:
+ async with transport.connect_session() as session:
+ result = await session.call_tool("pid", {})
+ pid = int(result.content[0].text) # ty: ignore[unresolved-attribute]
+ scope.cancel()
+
+ assert pid is not None
+ assert transport._connect_task is None
+ await wait_for_process_exit(pid)
+
async def test_cancelled_client_leaves_shared_transport_connected(
self, stdio_script
):