Skip to content

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

Reuse the stdio session after a cancelled startup (#6243)

nate nowack150a1c763fe8
diff --git a/fastmcp_slim/fastmcp/client/transports/stdio.py b/fastmcp_slim/fastmcp/client/transports/stdio.py
index 2550ec47b..3c1d33447 100644
--- a/fastmcp_slim/fastmcp/client/transports/stdio.py
+++ b/fastmcp_slim/fastmcp/client/transports/stdio.py
@@ -67,6 +67,7 @@ class StdioTransport(ClientTransport):
self.log_file = log_file
self._session: ClientSession | None = None
+ self._session_future: asyncio.Future[ClientSession] | None = None
self._session_options: TransportOptions | None = None
self._session_read_timeout: float | None = None
self._active_sessions = 0
@@ -144,41 +145,50 @@ class StdioTransport(ClientTransport):
):
await self.disconnect()
- if self._connect_task is not None:
- return
-
- session_future: asyncio.Future[ClientSession] = asyncio.Future()
-
- # Recorded before the connect completes: while it is in flight the
- # session already belongs to these options, and a concurrent caller
- # comparing against an unset value would read it as a mismatch and
- # tear down the connection being established.
- self._session_options = options
- self._session_read_timeout = session_kwargs.get("read_timeout_seconds")
-
- # start the connection task
- self._connect_task = asyncio.create_task(
- _stdio_transport_connect_task(
- command=self.command,
- args=self.args,
- env=self.env,
- cwd=self.cwd,
- log_file=self.log_file,
- # TODO(ty): remove when ty supports Unpack[TypedDict] inference
- session_kwargs=session_kwargs, # type: ignore[arg-type]
- transport_options=options,
- ready_event=self._ready_event,
- stop_event=self._stop_event,
- session_future=session_future,
+ # Preserve the established connect() return value when a ready
+ # keep-alive session is reused. connect_session() yields _session.
+ if self._session is not None:
+ return None
+
+ session_future: asyncio.Future[ClientSession] | None = self._session_future
+ if self._connect_task is None:
+ session_future = asyncio.Future()
+ self._session_future = session_future
+
+ # Recorded before the connect completes: while it is in flight
+ # the session already belongs to these options, and a
+ # concurrent caller comparing against an unset value would read
+ # it as a mismatch and tear down the connection being established.
+ self._session_options = options
+ self._session_read_timeout = session_kwargs.get("read_timeout_seconds")
+
+ # Start the connection task.
+ self._connect_task = asyncio.create_task(
+ _stdio_transport_connect_task(
+ command=self.command,
+ args=self.args,
+ env=self.env,
+ cwd=self.cwd,
+ log_file=self.log_file,
+ # TODO(ty): remove when ty supports Unpack[TypedDict] inference
+ session_kwargs=session_kwargs, # type: ignore[arg-type]
+ transport_options=options,
+ ready_event=self._ready_event,
+ stop_event=self._stop_event,
+ session_future=session_future,
+ )
)
- )
+
+ if session_future is None:
+ raise RuntimeError("Stdio connection has no session future")
# wait for the client to be ready before returning
await self._ready_event.wait()
# Check if connect task completed with an exception (early failure)
- if self._connect_task.done():
- exception = self._connect_task.exception()
+ connect_task = self._connect_task
+ if connect_task is not None and connect_task.done():
+ exception = connect_task.exception()
if exception is not None:
raise exception
@@ -210,6 +220,7 @@ class StdioTransport(ClientTransport):
# reset variables and events for potential future reconnects
self._connect_task = None
self._session = None
+ self._session_future = None
self._session_options = None
self._session_read_timeout = None
self._stop_event = anyio.Event()
diff --git a/tests/client/client/test_session.py b/tests/client/client/test_session.py
index 861171ec9..8dbc2a249 100644
--- a/tests/client/client/test_session.py
+++ b/tests/client/client/test_session.py
@@ -3,7 +3,7 @@
import asyncio
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
-from typing import Any
+from typing import Any, cast
import httpx2
import pytest
@@ -257,6 +257,7 @@ class TestKeepAliveSessionsRespectClientOptions:
task = asyncio.create_task(never_finishes())
transport._connect_task = task
+ transport._session = cast(ClientSession, object())
transport._session_options = options
async def fake_disconnect():
diff --git a/tests/client/test_stdio.py b/tests/client/test_stdio.py
index 6a29834da..e78265327 100644
--- a/tests/client/test_stdio.py
+++ b/tests/client/test_stdio.py
@@ -1,5 +1,7 @@
import asyncio
+import contextlib
import gc
+import importlib
import inspect
import os
import time
@@ -274,6 +276,56 @@ class TestKeepAlive:
assert client.transport.keep_alive is True
+ async def test_cancelled_initial_connect_can_reuse_starting_session(
+ self, stdio_script, monkeypatch
+ ):
+ stdio_module = importlib.import_module("fastmcp.client.transports.stdio")
+ original_stdio_client = stdio_module.stdio_client
+ stdio_entered = asyncio.Event()
+ release_stdio = asyncio.Event()
+
+ @contextlib.asynccontextmanager
+ async def gated_stdio_client(*args, **kwargs):
+ async with original_stdio_client(*args, **kwargs) as streams:
+ stdio_entered.set()
+ await release_stdio.wait()
+ yield streams
+
+ monkeypatch.setattr(stdio_module, "stdio_client", gated_stdio_client)
+ transport = PythonStdioTransport(script_path=stdio_script)
+ first_enter = asyncio.create_task(transport.connect_session().__aenter__())
+ retry_context = None
+ retry_enter = None
+
+ try:
+ await asyncio.wait_for(stdio_entered.wait(), timeout=5)
+ first_enter.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await first_enter
+
+ retry_context = transport.connect_session()
+ retry_enter = asyncio.create_task(retry_context.__aenter__())
+ await asyncio.sleep(0)
+ retry_waited_for_startup = not retry_enter.done()
+
+ release_stdio.set()
+ session = await asyncio.wait_for(retry_enter, timeout=5)
+ assert retry_waited_for_startup
+ assert session is not None
+ assert (await session.list_tools()).tools
+ finally:
+ release_stdio.set()
+ if not first_enter.done():
+ first_enter.cancel()
+ await asyncio.gather(first_enter, return_exceptions=True)
+ if retry_enter is not None:
+ if not retry_enter.done():
+ await asyncio.gather(retry_enter, return_exceptions=True)
+ if not retry_enter.cancelled() and retry_enter.exception() is None:
+ assert retry_context is not None
+ await retry_context.__aexit__(None, None, None)
+ await transport.disconnect()
+
async def test_keep_alive_set_false(self):
client = Client(
transport=StdioTransport(command="python", args=[""], keep_alive=False)