π The fast, Pythonic way to build MCP servers and clients.
Keep shared stdio sessions alive until the last client exits (#5180)
Aurelucienaed1cf340ac5
diff --git a/fastmcp_slim/fastmcp/client/transports/stdio.py b/fastmcp_slim/fastmcp/client/transports/stdio.pyindex 8967934b7..38cde685a 100644--- a/fastmcp_slim/fastmcp/client/transports/stdio.py+++ b/fastmcp_slim/fastmcp/client/transports/stdio.py@@ -90,7 +90,12 @@ class StdioTransport(ClientTransport):self._active_sessions -= 1finally:if not self.keep_alive:- await self.disconnect()+ # 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()else:logger.debug("Stdio transport has keep_alive=True, not disconnecting")diff --git a/tests/client/test_stdio.py b/tests/client/test_stdio.pyindex 09370c62b..ecbc369bb 100644--- a/tests/client/test_stdio.py+++ b/tests/client/test_stdio.py@@ -293,6 +293,49 @@ class TestKeepAlive:await wait_for_process_exit(pid)+ async def test_shared_transport_stays_alive_until_last_client_exits(+ self, stdio_script+ ):+ transport = PythonStdioTransport(stdio_script, keep_alive=False)+ first, second = Client(transport), Client(transport)++ async with first:+ pid = (await first.call_tool("pid")).data+ async with second:+ assert (await second.call_tool("pid")).data == pid++ assert await first.ping()+ assert (await first.call_tool("pid")).data == pid++ await wait_for_process_exit(pid)++ async def test_cancelled_client_leaves_shared_transport_connected(+ self, stdio_script+ ):+ transport = PythonStdioTransport(stdio_script, keep_alive=False)+ connected = asyncio.Event()++ async def cancelled_client():+ async with Client(transport) as client:+ await client.ping()+ connected.set()+ await asyncio.Event().wait()++ async with Client(transport) as client:+ pid = (await client.call_tool("pid")).data+ task = asyncio.create_task(cancelled_client())+ try:+ await connected.wait()+ finally:+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task++ assert await client.ping()+ assert (await client.call_tool("pid")).data == pid++ await wait_for_process_exit(pid)+async def test_keep_alive_false_starts_new_session_across_multiple_calls(self, stdio_script):