π The fast, Pythonic way to build MCP servers and clients.
client: make ClientGroup context reentrant (#4975)
nate nowack5c679ba3dcd6
diff --git a/docs/clients/client-groups.mdx b/docs/clients/client-groups.mdxindex 22864f458..8c41de3cd 100644--- a/docs/clients/client-groups.mdx+++ b/docs/clients/client-groups.mdx@@ -108,6 +108,15 @@ async with legacy_client, modern_client:It is also safe to enter the group inside a client context. FastMCP client contexts are reference counted, so leaving the group does not close a connection still owned by an outer context.+The group's own context is reentrant in the same way. Entering a group that is already connected, whether from a nested block or a concurrent task, reuses the existing connections. The first entry connects every client and the last exit disconnects them, so code that already relies on `Client` being safe to enter more than once can hold a `ClientGroup` the same way:++```python+async with group:+ async with group: # reuses the connections opened above+ await group.call_tool("modern_get_weather", {"city": "Chicago"})+ assert modern_client.is_connected()+```+The group adds no session handling of its own. Each client owns its transport and session exactly as it does standalone, so a legacy stateful session (for example over SSE or stdio) is held open by its client for as long as that client's context is active, whether the group or the caller entered it.## Related: SDK session groupsdiff --git a/fastmcp_slim/fastmcp/client/group.py b/fastmcp_slim/fastmcp/client/group.pyindex ef214d5e9..307aade55 100644--- a/fastmcp_slim/fastmcp/client/group.py+++ b/fastmcp_slim/fastmcp/client/group.py@@ -35,8 +35,11 @@ class ClientGroup:version. The group only combines tool discovery and routes tool calls.Callers may manage the clients' connections themselves or use the group as- a convenience context manager. Entering an already-connected FastMCP client- is safe because client contexts are reference counted.+ a convenience context manager. The group's context is reentrant in the+ same way a client's is: entries are reference counted, the first entry+ connects every client, and the last exit disconnects them. Entering an+ already-connected FastMCP client is likewise safe because client contexts+ are reference counted."""def __init__(self, clients: Mapping[str, Client[Any]]) -> None:@@ -45,6 +48,8 @@ class ClientGroup:self._clients = dict(clients)self._exit_stack: contextlib.AsyncExitStack | None = None+ self._nesting_counter = 0+ self._lifecycle_lock = anyio.Lock()self._tool_routes: dict[str, ToolRoute] = {}self._catalog_loaded = Falseself._route_lock = anyio.Lock()@@ -89,13 +94,14 @@ class ClientGroup:return {name: client.protocol_version for name, client in self._clients.items()}async def __aenter__(self) -> ClientGroup:- if self._exit_stack is not None:- raise RuntimeError("ClientGroup is already connected")+ async with self._lifecycle_lock:+ if self._exit_stack is None:+ self._exit_stack = await self._connect_all()+ self._nesting_counter += 1+ return self- # Claim the stack before the first await so a concurrent entry hits the- # guard above instead of racing past it and overwriting this one.+ async def _connect_all(self) -> contextlib.AsyncExitStack:stack = contextlib.AsyncExitStack()- self._exit_stack = stackawait stack.__aenter__()# Connect concurrently: entry latency stays one handshake deep instead@@ -112,14 +118,12 @@ class ClientGroup:if not isinstance(result, BaseException):with contextlib.suppress(Exception):await client.__aexit__(None, None, None)- self._exit_stack = Noneawait stack.aclose()raise errors[0]for client in clients:stack.push_async_exit(client)-- return self+ return stackasync def __aexit__(self,@@ -127,13 +131,18 @@ class ClientGroup:exc_value: BaseException | None,traceback: TracebackType | None,) -> bool | None:- stack = self._exit_stack- self._exit_stack = None- self._tool_routes.clear()- self._catalog_loaded = False- if stack is not None:- return await stack.__aexit__(exc_type, exc_value, traceback)- return None+ async with self._lifecycle_lock:+ self._nesting_counter = max(0, self._nesting_counter - 1)+ if self._nesting_counter > 0:+ return None++ stack = self._exit_stack+ self._exit_stack = None+ self._tool_routes.clear()+ self._catalog_loaded = False+ if stack is not None:+ return await stack.__aexit__(exc_type, exc_value, traceback)+ return Nonedef _require_connected(self) -> None:disconnected = [diff --git a/tests/client/group/test_client_group.py b/tests/client/group/test_client_group.pyindex bd9cd789e..b79d6f38d 100644--- a/tests/client/group/test_client_group.py+++ b/tests/client/group/test_client_group.py@@ -278,13 +278,14 @@ async def test_concurrent_group_entry_does_not_double_connect():client = Client(FastMCPTransport(make_server("solo")))group = ClientGroup({"solo": client})- results = await asyncio.gather(- group.__aenter__(), group.__aenter__(), return_exceptions=True- )- errors = [r for r in results if isinstance(r, BaseException)]- assert len(errors) == 1- assert isinstance(errors[0], RuntimeError)+ with patch.object(Client, "_connect", wraps=client._connect) as connect:+ await asyncio.gather(group.__aenter__(), group.__aenter__())++ assert connect.call_count == 1+ assert client.is_connected()+ await group.__aexit__(None, None, None)+ assert client.is_connected()await group.__aexit__(None, None, None)assert not client.is_connected()@@ -347,3 +348,74 @@ async def test_explicit_list_tools_refreshes_past_client_response_cache():result = await group.call_tool("hinted_added")assert result.data == "added"+++async def test_group_context_is_reentrant():+ client = Client(make_server("server"))+ group = ClientGroup({"server": client})++ async with group:+ async with group:+ result = await group.call_tool("server_echo", {"value": "inner"})+ assert result.data == "server: inner"++ assert client.is_connected()+ result = await group.call_tool("server_echo", {"value": "outer"})+ assert result.data == "server: outer"++ assert not client.is_connected()+++async def test_concurrent_group_entries_share_one_connection():+ client = Client(make_server("server"))+ group = ClientGroup({"server": client})+ started = asyncio.Event()++ async def hold_open() -> None:+ async with group:+ started.set()+ await asyncio.sleep(0.05)++ async def use_while_held() -> str:+ await started.wait()+ async with group:+ result = await group.call_tool("server_echo", {"value": "shared"})+ return result.data++ with patch.object(Client, "_connect", wraps=client._connect) as connect:+ _, data = await asyncio.gather(hold_open(), use_while_held())++ assert data == "server: shared"+ assert connect.call_count == 1+ assert not client.is_connected()+++async def test_group_reconnects_after_last_exit():+ client = Client(make_server("server"))+ group = ClientGroup({"server": client})++ async with group:+ assert client.is_connected()+ assert not client.is_connected()++ async with group:+ result = await group.call_tool("server_echo", {"value": "again"})+ assert result.data == "server: again"+ assert not client.is_connected()+++async def test_failed_entry_leaves_group_reenterable():+ good = Client(make_server("good"))+ bad = Client(FastMCPTransport(make_server("bad")))+ group = ClientGroup({"good": good, "bad": bad})++ with patch.object(bad, "_connect", side_effect=ConnectionError("down")):+ with pytest.raises(ConnectionError):+ async with group:+ raise AssertionError("group entry should have failed")++ assert not good.is_connected()++ async with group:+ result = await group.call_tool("good_echo", {"value": "recovered"})+ assert result.data == "good: recovered"