π The fast, Pythonic way to build MCP servers and clients.
Reconnect StdioTransport when reused on a different event loop (#6425)
nate nowacke636d2275391
diff --git a/docs/clients/transports.mdx b/docs/clients/transports.mdxindex 3ee779359..3de9de3f4 100644--- a/docs/clients/transports.mdx+++ b/docs/clients/transports.mdx@@ -114,6 +114,8 @@ For complete isolation between connections, disable session persistence:transport = StdioTransport(command="python", args=["server.py"], keep_alive=False)```+A persisted session belongs to the event loop that created it, so reuse from a different loop transparently starts a fresh subprocess instead. Sharing one transport between loops still works, but only reuses the subprocess within a single loop β and it raises if two loops try to hold overlapping sessions on the same transport, which needs one transport per loop. The old subprocess is shut down on the loop that started it, so that loop must still be running or already closed: if it is stopped but still open (as after `loop.run_until_complete(...)`), reuse from another loop raises until you close the client on the original loop.+## HTTP Transport<VersionBadge version="2.3.0" />diff --git a/fastmcp_slim/fastmcp/client/transports/stdio.py b/fastmcp_slim/fastmcp/client/transports/stdio.pyindex 3c1d33447..c31080a48 100644--- a/fastmcp_slim/fastmcp/client/transports/stdio.py+++ b/fastmcp_slim/fastmcp/client/transports/stdio.py@@ -83,6 +83,10 @@ class StdioTransport(ClientTransport):transport_options: TransportOptions | None = None,**session_kwargs: Unpack[SessionKwargs],) -> AsyncGenerator[ClientSession, None]:+ # Checked before the cleanup below takes effect: a context refused here+ # never acquired the connection, so it must not tear down the one+ # another loop is still using.+ self._refuse_foreign_loop_in_use()try:await self.connect(transport_options=transport_options, **session_kwargs)self._active_sessions += 1@@ -103,10 +107,19 @@ class StdioTransport(ClientTransport):**session_kwargs: Unpack[SessionKwargs],) -> ClientSession | None:options = transport_options or TransportOptions()+ self._refuse_foreign_loop_in_use()# Serialized so concurrent callers can't each decide to replace the# session and race to spawn competing subprocesses.async with self._connect_lock:+ # An idle connection left by another loop is rebuilt on this one.+ connect_task = self._connect_task+ if (+ connect_task is not None+ and connect_task.get_loop() is not asyncio.get_running_loop()+ ):+ await self.disconnect()+# A kept-alive session was built for one client's options; handing it# to a client that wants different ones would silently give it the# first client's behavior. Rebuild it when it's idle; refuse when@@ -195,17 +208,77 @@ class StdioTransport(ClientTransport):self._session = await session_futurereturn self._session+ def _refuse_foreign_loop_in_use(self) -> None:+ """Refuse a connection while another event loop is using this one.++ The connection task and the session's streams belong to the event loop+ that created them. A session reused from another loop never sees its+ responses, so the initialize handshake would hang. Refuse while another+ loop is using or establishing the connection, before waiting on the+ lock: the lock is bound to one loop and cannot arbitrate between loops.+ """+ connect_task = self._connect_task+ foreign_loop = (+ connect_task is not None+ and connect_task.get_loop() is not asyncio.get_running_loop()+ )+ if foreign_loop and (self._active_sessions or self._connect_lock.locked()):+ raise RuntimeError(+ "This stdio transport has a live session bound to a different "+ "event loop and another client is still using it. Sharing one "+ "transport across event loops with overlapping sessions is not "+ "supported; give each loop its own transport."+ )+async def disconnect(self):if self._connect_task is None:return+ connect_task = self._connect_task+ owning_loop = connect_task.get_loop()++ # The task can only be signalled and awaited from the loop that owns+ # it. From any other loop, run the teardown there and wait for it. A+ # closed loop has already cancelled the task, so there is nothing left+ # to stop.+ if owning_loop is not asyncio.get_running_loop():+ if owning_loop.is_closed():+ self._reset()+ return++ # A stopped loop can't run the teardown until something runs it+ # again, and forgetting the connection now would leave its+ # subprocess alive with nothing able to stop it. Keep the+ # connection and refuse, so the owner can still close it there.+ if not owning_loop.is_running():+ raise RuntimeError(+ "This stdio transport's connection belongs to an event loop "+ "that is stopped but not closed, so it can't be shut down "+ "from this loop. Close the client on the loop that opened "+ "it, or close that loop, before using it from another loop."+ )++ stop_event = self._stop_event++ async def stop_on_owning_loop() -> None:+ stop_event.set()+ await asyncio.wait({connect_task})++ # Scheduling raises if the loop closed since the check above; its+ # shutdown cancelled the task, so the teardown is done either way.+ with contextlib.suppress(RuntimeError):+ await asyncio.wrap_future(+ asyncio.run_coroutine_threadsafe(stop_on_owning_loop(), owning_loop)+ )+ self._reset()+ return+# signal the connection task to stopself._stop_event.set()# Wait without propagating the connection task's cancellation into# this caller. Cancellation of this wait therefore still belongs to# the caller and must propagate normally.- connect_task = self._connect_taskawait asyncio.wait({connect_task})try:_ = connect_task.result()@@ -217,7 +290,10 @@ class StdioTransport(ClientTransport):exc_info=True,)- # reset variables and events for potential future reconnects+ self._reset()++ def _reset(self) -> None:+ """Clear connection state and events so a future connect starts fresh."""self._connect_task = Noneself._session = Noneself._session_future = Nonediff --git a/tests/client/test_stdio.py b/tests/client/test_stdio.pyindex 893483013..94f38a0d1 100644--- a/tests/client/test_stdio.py+++ b/tests/client/test_stdio.py@@ -472,6 +472,99 @@ class TestKeepAlive:assert pid1 != pid2+ # https://github.com/PrefectHQ/fastmcp/issues/4471+ @pytest.mark.timeout(30)+ async def test_keep_alive_reconnects_on_a_different_event_loop(self, stdio_script):+ """A kept-alive connection belongs to the loop that created it.++ Reusing the transport from a second, concurrently-alive loop has to+ spawn a fresh subprocess: the first loop's session never sees its+ responses on the second loop, so reusing it would hang the initialize+ handshake instead of connecting.+ """+ client = Client(transport=PythonStdioTransport(script_path=stdio_script))++ async with client:+ result1 = await client.call_tool("pid")+ pid1: int = result1.data++ async def reuse() -> int:+ async with client:+ result = await client.call_tool("pid")+ return int(result.data)++ def reuse_on_new_loop() -> int:+ # Bounded so a reused foreign-loop session fails as a timeout here+ # rather than hanging the suite.+ return asyncio.run(asyncio.wait_for(reuse(), timeout=10))++ # Off-thread, so this test's loop stays running while the second one+ # connects: only the owning loop can tear the old connection down.+ pid2 = await asyncio.to_thread(reuse_on_new_loop)++ assert pid2 != pid1+ await wait_for_process_exit(pid1)++ # The second loop is closed by now; closing from this one must still+ # succeed rather than fail on a task it cannot await.+ await client.close()++ @pytest.mark.timeout(30)+ def test_stopped_owning_loop_keeps_the_connection(self, stdio_script):+ """A stopped loop can't run the teardown, so the connection stays its.++ Moving to another loop would otherwise forget a subprocess that nothing+ could stop anymore. The move is refused instead, and the owning loop+ can still close it.+ """+ client = Client(transport=PythonStdioTransport(script_path=stdio_script))++ async def use() -> int:+ async with client:+ result = await client.call_tool("pid")+ return int(result.data)++ def use_on_new_loop() -> int:+ return asyncio.run(asyncio.wait_for(use(), timeout=10))++ loop_a = asyncio.new_event_loop()+ try:+ pid1 = loop_a.run_until_complete(use())++ with pytest.raises(RuntimeError, match="stopped but not closed"):+ use_on_new_loop()+ assert psutil.pid_exists(pid1)++ # The transport owns the subprocess; the client keeps the refused+ # connect's error and would re-raise it on close().+ loop_a.run_until_complete(client.transport.close())+ loop_a.run_until_complete(wait_for_process_exit(pid1))+ finally:+ loop_a.close()++ @pytest.mark.timeout(30)+ @pytest.mark.parametrize("keep_alive", [True, False])+ async def test_refuses_a_different_event_loop_while_in_use(+ self, stdio_script, keep_alive+ ):+ transport = PythonStdioTransport(+ script_path=stdio_script, keep_alive=keep_alive+ )++ def connect_on_new_loop() -> None:+ async def connect() -> None:+ async with transport.connect_session():+ pass++ asyncio.run(asyncio.wait_for(connect(), timeout=10))++ async with transport.connect_session() as session:+ with pytest.raises(RuntimeError, match="different event loop"):+ await asyncio.to_thread(connect_on_new_loop)+ assert (await session.list_tools()).tools++ await transport.close()+async def test_keep_alive_starts_new_session_if_manually_closed(self, stdio_script):client = Client(transport=PythonStdioTransport(script_path=stdio_script))assert client.transport.keep_alive is True