Skip to content

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

fix(client): keep stale contexts from closing newer sessions (#6018)

mikade37675d566b
diff --git a/fastmcp_slim/fastmcp/client/client.py b/fastmcp_slim/fastmcp/client/client.py
index 2d40762a2..422cd8c0f 100644
--- a/fastmcp_slim/fastmcp/client/client.py
+++ b/fastmcp_slim/fastmcp/client/client.py
@@ -17,6 +17,7 @@ from collections.abc import (
from contextlib import AsyncExitStack, asynccontextmanager, suppress
from dataclasses import dataclass, field, replace
from pathlib import Path
+from types import TracebackType
from typing import TYPE_CHECKING, Any, Generic, Literal, TypeVar, cast, overload
import anyio
@@ -590,6 +591,12 @@ class Client(
self._disconnect_timeout: float = fastmcp.settings.client_disconnect_timeout
# Session stops handed off by exiting contexts; referenced until done.
self._stoppers: set[asyncio.Task[None]] = set()
+ # Context-manager holds belong to the task that entered them. Keeping
+ # the session task lets an exit from an older connection avoid
+ # decrementing the reference count of a connection opened afterward.
+ self._context_session_tasks: dict[
+ asyncio.Task[Any], list[asyncio.Task[Any]]
+ ] = {}
# Session context management - see class docstring for detailed explanation
self._session_state = ClientSessionState()
@@ -782,6 +789,7 @@ class Client(
# share lifecycle state with the original instance.
new_client._session_state = ClientSessionState()
new_client._transport_options = self._transport_options
+ new_client._context_session_tasks = {}
# Give the clone its own response cache so cached entries are not shared
# across independent sessions, and rebuild the negotiated_version closure
@@ -955,11 +963,68 @@ class Client(
)
return self.initialize_result
+ async def _enter_context(self) -> asyncio.Task[Any]:
+ """Connect and return the session held by this context."""
+ await self._connect()
+ session_task = self._session_state.session_task
+ if session_task is None:
+ raise RuntimeError("Client connected without a session task")
+ return session_task
+
async def __aenter__(self):
- return await self._connect()
+ session_task = await self._enter_context()
+ task = asyncio.current_task()
+ if task is None:
+ raise RuntimeError("Client context entered outside an asyncio task")
+ self._context_session_tasks.setdefault(task, []).append(session_task)
+ return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
- await self._disconnect()
+ task = asyncio.current_task()
+ session_task = None
+ if task is not None:
+ session_tasks = self._context_session_tasks.get(task)
+ if session_tasks:
+ session_task = session_tasks.pop()
+ if not session_tasks:
+ del self._context_session_tasks[task]
+ await self._disconnect(held=session_task)
+
+ async def _exit_context(
+ self,
+ held: asyncio.Task[Any] | None,
+ entered_task: asyncio.Task[Any] | None,
+ exc_type: type[BaseException] | None,
+ exc_val: BaseException | None,
+ exc_tb: TracebackType | None,
+ ) -> bool | None:
+ """Exit a context entered by another task, preserving its session hold."""
+ if entered_task is not None and held is not None:
+ self._remove_context_session(entered_task, held)
+
+ task = asyncio.current_task()
+ if task is None or held is None:
+ return await self.__aexit__(exc_type, exc_val, exc_tb)
+
+ self._context_session_tasks.setdefault(task, []).append(held)
+ try:
+ return await self.__aexit__(exc_type, exc_val, exc_tb)
+ finally:
+ self._remove_context_session(task, held)
+
+ def _remove_context_session(
+ self, task: asyncio.Task[Any], held: asyncio.Task[Any]
+ ) -> None:
+ """Remove one matching context hold from a task's pending exits."""
+ session_tasks = self._context_session_tasks.get(task)
+ if session_tasks is None:
+ return
+ for index in range(len(session_tasks) - 1, -1, -1):
+ if session_tasks[index] is held:
+ del session_tasks[index]
+ break
+ if not session_tasks:
+ del self._context_session_tasks[task]
async def _connect(self):
"""
@@ -1059,7 +1124,9 @@ class Client(
return self
- async def _disconnect(self, force: bool = False):
+ async def _disconnect(
+ self, force: bool = False, held: asyncio.Task[Any] | None = None
+ ):
"""
Disconnect from session using reference counting.
@@ -1079,6 +1146,13 @@ class Client(
await self._stop_session(None, force=True)
return
+ # A context entered before an explicit close owns the old session. If
+ # the client has since reconnected, its exit must not release the new
+ # session's hold. There is no await between this check and the counter
+ # update, so another task cannot replace the session in between.
+ if held is not None and self._session_state.session_task is not held:
+ return
+
# Release this context's hold before any await. A context that exits
# because it was cancelled can be interrupted at every await below, by
# an enclosing anyio scope or by a native cancellation that repeats
diff --git a/fastmcp_slim/fastmcp/client/group.py b/fastmcp_slim/fastmcp/client/group.py
index eddb560b4..18b3f146d 100644
--- a/fastmcp_slim/fastmcp/client/group.py
+++ b/fastmcp_slim/fastmcp/client/group.py
@@ -29,6 +29,20 @@ class ToolRoute:
upstream_name: str
+@dataclass(frozen=True)
+class _EnteredClient:
+ task: asyncio.Task[Any]
+ session_task: asyncio.Task[Any] | None
+
+
+async def _enter_client_context(client: Client[Any]) -> _EnteredClient:
+ await client.__aenter__()
+ task = asyncio.current_task()
+ if task is None:
+ raise RuntimeError("Client group entered outside an asyncio task")
+ return _EnteredClient(task, client._session_state.session_task)
+
+
class ClientGroup:
"""Coordinate independent clients without introducing a proxy server.
@@ -116,19 +130,44 @@ class ClientGroup:
# so on partial failure the successes are known and can be unwound.
clients = list(self._clients.values())
results = await gather(
- (client.__aenter__() for client in clients), return_exceptions=True
+ (_enter_client_context(client) for client in clients),
+ return_exceptions=True,
)
errors = [result for result in results if isinstance(result, BaseException)]
if errors:
for client, result in zip(clients, results, strict=True):
if not isinstance(result, BaseException):
with contextlib.suppress(Exception):
- await client.__aexit__(None, None, None)
+ await client._exit_context(
+ result.session_task,
+ result.task,
+ None,
+ None,
+ None,
+ )
await stack.aclose()
raise errors[0]
- for client in clients:
- stack.push_async_exit(client)
+ for client, result in zip(clients, results, strict=True):
+ assert not isinstance(result, BaseException)
+
+ async def exit_client(
+ exc_type: type[BaseException] | None,
+ exc_value: BaseException | None,
+ traceback: TracebackType | None,
+ *,
+ client: Client[Any] = client,
+ entered: _EnteredClient = result,
+ ) -> bool | None:
+ return await client._exit_context(
+ entered.session_task,
+ entered.task,
+ exc_type,
+ exc_value,
+ traceback,
+ )
+
+ stack.push_async_exit(exit_client)
return stack
async def __aexit__(
diff --git a/tests/client/client/test_client.py b/tests/client/client/test_client.py
index e1cf88d12..d7bbe77fc 100644
--- a/tests/client/client/test_client.py
+++ b/tests/client/client/test_client.py
@@ -507,6 +507,40 @@ async def test_client_nested_context_manager(fastmcp_server):
assert client._session_state.session is None
[email protected]("mode", ["auto", "legacy"])
+async def test_stale_client_context_does_not_disconnect_reconnected_session(
+ fastmcp_server, mode
+):
+ client = Client(fastmcp_server, mode=mode)
+ entered = asyncio.Event()
+ release = asyncio.Event()
+ exited = asyncio.Event()
+
+ async def old_context() -> None:
+ async with client:
+ entered.set()
+ await release.wait()
+ exited.set()
+
+ old_task = asyncio.create_task(old_context())
+ await entered.wait()
+ await client.close()
+
+ try:
+ async with client:
+ first = await client.call_tool("greet", {"name": "World"})
+ assert first.data == "Hello, World!"
+
+ release.set()
+ await exited.wait()
+
+ second = await client.call_tool("greet", {"name": "World"})
+ assert second.data == "Hello, World!"
+ finally:
+ release.set()
+ await old_task
+
+
async def test_client_context_entry_cancelled_starter_cleans_up(fastmcp_server):
connect_started = anyio.Event()
allow_connect = anyio.Event()
diff --git a/tests/client/group/test_client_group.py b/tests/client/group/test_client_group.py
index 039e84656..43195dcbc 100644
--- a/tests/client/group/test_client_group.py
+++ b/tests/client/group/test_client_group.py
@@ -418,6 +418,41 @@ async def test_group_reconnects_after_last_exit():
assert not client.is_connected()
[email protected]("mode", ["auto", "legacy"])
+async def test_stale_group_context_does_not_disconnect_reconnected_session(
+ fastmcp_server, mode
+):
+ client = Client(fastmcp_server, mode=mode)
+ group = ClientGroup({"server": client})
+ entered = asyncio.Event()
+ release = asyncio.Event()
+ exited = asyncio.Event()
+
+ async def old_group_context() -> None:
+ async with group:
+ entered.set()
+ await release.wait()
+ exited.set()
+
+ old_task = asyncio.create_task(old_group_context())
+ await entered.wait()
+ await client.close()
+
+ try:
+ async with client:
+ first = await client.call_tool("greet", {"name": "World"})
+ assert first.data == "Hello, World!"
+
+ release.set()
+ await exited.wait()
+
+ second = await client.call_tool("greet", {"name": "World"})
+ assert second.data == "Hello, World!"
+ finally:
+ release.set()
+ await old_task
+
+
async def test_failed_entry_leaves_group_reenterable():
good = Client(make_server("good"))
bad = Client(FastMCPTransport(make_server("bad")))