π The fast, Pythonic way to build MCP servers and clients.
add independent client groups (#4904)
nate nowack2a2080c6c787
diff --git a/dev-docs/v4-notes/client-groups.md b/dev-docs/v4-notes/client-groups.mdnew file mode 100644index 000000000..1ccc02bee--- /dev/null+++ b/dev-docs/v4-notes/client-groups.md@@ -0,0 +1,33 @@+---+title: Client Groups+---++**Status: In review (#4904).** `ClientGroup` coordinates independent FastMCP clients β one managed connection per server β with collision-checked tool namespacing and call routing. User-facing usage is documented at [Client Groups](https://gofastmcp.com/clients/client-groups).++## TL;DR++Applications that hand tools from several servers to one agent previously chose between two bad shapes. `Client(config)` composes servers behind an in-process proxy, so every backend shares one negotiated protocol era β one handshake-era backend reconnects every modern backend under the handshake era β and concurrent calls funnel through one frontend session. One `Client` per server keeps each negotiated era, but nothing owns the composition: callers hand-roll namespacing, collision detection, lifecycle, and routing.++`ClientGroup` is the object between those two: a mapping of named clients where each connection negotiates independently, tools are published as `{server}_{tool}`, and calls route back through the client that advertised the tool. It lives at `fastmcp.client.group` β in the main namespace, since the surface is additive and small.++## Motivation++The immediate driver was per-server protocol pinning: agent integrations need `mode="legacy"` on one server and `mode="auto"` on another, which a single aggregate connection cannot express. Namespacing requests (a prefix for a single server's tools) kept arriving alongside it, because the same integrations feed multiple servers' tools to one model.++## Decisions++**Group over kwarg.** A `tool_name_prefix` kwarg on `Client` was fully implemented as a comparison (#4932, closed). It was rejected because a prefix is collision policy, and collision policy belongs with the composition object that detects collisions. It also would have made the stable single-server client present names the server never advertised. The group's dict keys are the namespace; a one-client group is the supported way to get namespacing alone.++**No synthetic frontend.** There is no aggregate session and no protocol translation. `resolve_tool()` returns the server name, the owning `Client`, and the upstream tool name, because tool adapters need to bind per-tool behavior (session-driven input loops, handlers, interceptors) to the real connection. The group never stands between an adapter and the client.++**Invariants over flexibility.** Membership is immutable after construction (routes hold the advertising client and would go stale under mutation). Group entry is race-guarded and connects clients concurrently, unwinding successes on partial failure. A known route only requires its own client to be connected, so one dead server does not fail calls routed to healthy servers; full-fleet connectivity is required only for catalog discovery, which queries everyone.++**Tool-only for now.** Resources have URI-based identity with different collision rules, and prompts a different invocation surface. Expanding beyond tools should follow concrete usage rather than declaring those policies by analogy.++## Performance++Measured against two real local streamable-HTTP servers (ratios are the finding, not the absolute numbers): routed calls through the group are indistinguishable from direct client calls (p50 1.89ms both), while the `Client(config)` proxy adds ~65% per call. Under concurrency the difference compounds β 200 concurrent calls across both servers completed ~6x faster through the group (~145ms vs ~875ms), because the group fans out over independent sessions while the proxy serializes through one. Group entry connects clients concurrently, so entry latency stays roughly one handshake deep instead of growing linearly with server count.++## Relationship to the upstream SDK group++The MCP Python SDK's `ClientSessionGroup` is the prior art. Its `connect_to_server()` owns lifecycle but only speaks the classic handshake; `connect_with_session()` can register an externally negotiated modern session but does not own it. `ClientGroup` combines independent modern negotiation with group-owned lifecycle while keeping calls on the configured FastMCP client surface (auth, tracing, caching, result parsing, progress, multi-round tools).diff --git a/docs/clients/client-groups.mdx b/docs/clients/client-groups.mdxnew file mode 100644index 000000000..f501c9c62--- /dev/null+++ b/docs/clients/client-groups.mdx@@ -0,0 +1,115 @@+---+title: Client Groups+sidebarTitle: Client Groups+icon: layer-group+---++import { VersionBadge } from '/snippets/version-badge.mdx'++<VersionBadge version="4.0.0" />++A `ClientGroup` coordinates several independent FastMCP clients without combining them behind a proxy server. Each client keeps its own connection, negotiated protocol version, capabilities, and handlers. The group adds namespaced tool discovery and routes each call back to the client that advertised the tool.++This differs from passing a multi-server configuration directly to `Client`. `Client(config)` presents one aggregate MCP endpoint and therefore selects one protocol era shared by its proxy chain. A `ClientGroup` retains one MCP connection per configured server, so legacy and modern servers can operate in their native eras at the same time.++## Create a group from clients++Construct the clients explicitly when each server needs its own handlers, authentication, or connection settings:++```python+import asyncio++from fastmcp import Client+from fastmcp.client.group import ClientGroup++legacy_client = Client("legacy_server.py", mode="legacy")+modern_client = Client("https://modern.example.com/mcp", mode="auto")++group = ClientGroup(+ {+ "legacy": legacy_client,+ "modern": modern_client,+ }+)+++async def main() -> None:+ async with group:+ tools = await group.list_tools()+ print([tool.name for tool in tools])++ result = await group.call_tool(+ "modern_get_weather",+ {"city": "Chicago"},+ )+ print(result)+++asyncio.run(main())+```++Tool names are prefixed with the configured client name by default. For example, a `get_weather` tool exposed by the `modern` client becomes `modern_get_weather`.++A group with a single client is a supported way to get namespacing alone: the one server's tools are presented under its configured name, with no other behavior change.++The first routed call loads the tool catalog lazily. After a successful load, unknown tool names fail locally rather than repeating discovery against every server. Call `list_tools()` explicitly to refresh the routes when servers add or remove tools dynamically β the explicit call refreshes past any client-side response cache, so the catalog reflects what every server advertises now.++## Bind tools to their owning client++Tool adapters β code that turns MCP tools into callables for an agent framework β often need more than routed calls: session-driven input loops, handler context, and interceptors must run on the connection that owns the tool. `resolve_tool()` returns that route, so an adapter can discover through the group and still bind each generated tool to its real client:++```python+async with group:+ for tool in await group.list_tools():+ route = await group.resolve_tool(tool.name)+ # route.client is the connected FastMCP client for this tool;+ # route.upstream_name is the name the server itself advertises+ register_agent_tool(tool, client=route.client, name=route.upstream_name)+```++The group aggregates names and detects collisions; it never stands between the adapter and the client, so everything a single `Client` supports keeps working per tool.++## Create a group from configuration++`ClientGroup.from_config` creates one client per server rather than passing the entire configuration through a proxy. A FastMCP-specific `mode` field can select the protocol behavior for each server:++```python+from fastmcp.client.group import ClientGroup++config = {+ "mcpServers": {+ "legacy": {+ "command": "python",+ "args": ["legacy_server.py"],+ "mode": "legacy",+ },+ "modern": {+ "url": "https://modern.example.com/mcp",+ "mode": "auto",+ },+ }+}++group = ClientGroup.from_config(config)+```++Entries without a `mode` use `"auto"` by default.++## Manage connections explicitly++Using the group as a context manager is optional. Applications can own each client connection and use the group only for discovery and routing:++```python+async with legacy_client, modern_client:+ tools = await group.list_tools()+```++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 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.++## Relationship to SDK session groups++The upstream official MCP Python SDK provides `ClientSessionGroup` for aggregating raw `ClientSession` connections, including tools, resources, and prompts. Its `connect_to_server()` path uses the classic `initialize` handshake, so it does not negotiate the modern protocol. Use it when classic sessions, raw SDK results, and dynamic group membership fit the application.++`connect_with_session()` can register a modern session that was connected separately, but the caller must create and keep that client alive because the SDK group does not own sessions registered this way. `ClientGroup` instead manages fully configured FastMCP clients directly. Each client can negotiate its own modern or legacy protocol, and calls continue through that client, preserving its authentication, handlers, caching, tracing, result parsing, and multi-round tool behavior. The API is intentionally narrower and currently aggregates tools only.diff --git a/docs/clients/client.mdx b/docs/clients/client.mdxindex 8ea9e21be..9861ca75d 100644--- a/docs/clients/client.mdx+++ b/docs/clients/client.mdx@@ -121,6 +121,10 @@ async with client:icons = await client.read_resource("weather://weather/icons/sunny")```+<Note>+A multi-server configuration presents one aggregate MCP endpoint. Each entry still configures its own transport, headers, and auth, but every backend shares the outer client's negotiated protocol era, handlers, and client-level policy. To hold several fully independent connections β each with its own protocol `mode` and handlers β see [Client Groups](/clients/client-groups).+</Note>+## Connection LifecycleThe client uses context managers for connection management. When you enter the context, the client establishes a connection and negotiates the protocol era with the server. Metadata returned by either legacy initialization or modern discovery is exposed through the same client properties.@@ -212,7 +216,7 @@ async with Client("https://example.com/mcp", mode="auto") as client:<Note>`mode="auto"` is the default as of FastMCP 4.0. Earlier versions defaulted to `"legacy"`. If a server behaves unexpectedly under discovery, or you depend on the legacy `initialize` result, pin the old behavior with `Client(..., mode="legacy")`.-The SSE transport is legacy-only β it cannot carry the sessionless modern era β so a client connecting over SSE always negotiates the legacy handshake, even under `mode="auto"`. A multi-server config (`MCPConfigTransport` with more than one server) negotiates the best era shared by every connected backend: it stays modern when every backend is modern-capable and reconnects every leg under the handshake era when any backend requires legacy. Pinning `mode="legacy"` or a modern version applies that mode to every backend. All-modern configurations follow normal modern semantics; applications that rely on handshake-era server-initiated sampling or elicitation should pin `mode="legacy"`.+The SSE transport is legacy-only β it cannot carry the sessionless modern era β so a client connecting over SSE always negotiates the legacy handshake, even under `mode="auto"`. A multi-server config (`MCPConfigTransport` with more than one server) negotiates the best era shared by every connected backend: it stays modern when every backend is modern-capable and reconnects every leg under the handshake era when any backend requires legacy. Pinning `mode="legacy"` or a modern version applies that mode to every backend. All-modern configurations follow normal modern semantics; applications that rely on handshake-era server-initiated sampling or elicitation should pin `mode="legacy"`. To keep each server on its own natively negotiated era instead, use one client per server β [Client Groups](/clients/client-groups) coordinate several independent clients under one tool catalog.</Note>## Response cachingdiff --git a/docs/docs.json b/docs/docs.jsonindex 3abd86a72..ab6bc52e6 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -243,6 +243,7 @@"clients/client","clients/client-only-package","clients/transports",+ "clients/client-groups","clients/fastmcp-remote",{"collapsed": true,diff --git a/fastmcp_slim/fastmcp/client/group.py b/fastmcp_slim/fastmcp/client/group.pynew file mode 100644index 000000000..ef214d5e9--- /dev/null+++ b/fastmcp_slim/fastmcp/client/group.py@@ -0,0 +1,264 @@+"""Coordination of independent MCP client connections."""++from __future__ import annotations++import contextlib+import datetime+from collections.abc import Mapping+from dataclasses import dataclass+from types import MappingProxyType, TracebackType+from typing import Any++import anyio+import mcp_types+from mcp.client.caching import CacheMode++from fastmcp.client.client import CallToolResult, Client, ConnectMode+from fastmcp.client.progress import ProgressHandler+from fastmcp.mcp_config import MCPConfig+from fastmcp.utilities.async_utils import gather+++@dataclass(frozen=True)+class ToolRoute:+ """The client and upstream name behind a public group tool name."""++ server_name: str+ client: Client[Any]+ upstream_name: str+++class ClientGroup:+ """Coordinate independent clients without introducing a proxy server.++ Each client retains its own transport, session, capabilities, and protocol+ 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.+ """++ def __init__(self, clients: Mapping[str, Client[Any]]) -> None:+ if not clients:+ raise ValueError("ClientGroup requires at least one client")++ self._clients = dict(clients)+ self._exit_stack: contextlib.AsyncExitStack | None = None+ self._tool_routes: dict[str, ToolRoute] = {}+ self._catalog_loaded = False+ self._route_lock = anyio.Lock()++ @property+ def clients(self) -> Mapping[str, Client[Any]]:+ """The group's clients, keyed by server name.++ Read-only: membership is fixed at construction, since discovered routes+ hold the client that advertised each tool and would silently go stale+ if the mapping were swapped underneath them.+ """+ return MappingProxyType(self._clients)++ @classmethod+ def from_config(+ cls,+ config: MCPConfig | dict[str, Any],+ *,+ default_mode: ConnectMode = "auto",+ ) -> ClientGroup:+ """Create one independent client for each configured server.++ A server entry may include a FastMCP-specific ``mode`` field. It applies+ only to that server; entries without one use ``default_mode``.+ """+ parsed = (+ config if isinstance(config, MCPConfig) else MCPConfig.from_dict(config)+ )+ clients: dict[str, Client[Any]] = {}++ for name, server in parsed.mcpServers.items():+ configured_mode = (server.model_extra or {}).get("mode", default_mode)+ if not isinstance(configured_mode, str):+ raise TypeError(f"Protocol mode for server {name!r} must be a string")+ clients[name] = Client(server.to_transport(), mode=configured_mode)++ return cls(clients)++ @property+ def protocol_versions(self) -> dict[str, str | None]:+ 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")++ # Claim the stack before the first await so a concurrent entry hits the+ # guard above instead of racing past it and overwriting this one.+ stack = contextlib.AsyncExitStack()+ self._exit_stack = stack+ await stack.__aenter__()++ # Connect concurrently: entry latency stays one handshake deep instead+ # of growing linearly with the number of servers. With+ # return_exceptions=True every connection attempt runs to completion,+ # 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+ )+ 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)+ self._exit_stack = None+ await stack.aclose()+ raise errors[0]++ for client in clients:+ stack.push_async_exit(client)++ return self++ async def __aexit__(+ self,+ exc_type: type[BaseException] | None,+ 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++ def _require_connected(self) -> None:+ disconnected = [+ name for name, client in self._clients.items() if not client.is_connected()+ ]+ if disconnected:+ names = ", ".join(repr(name) for name in disconnected)+ raise RuntimeError(f"ClientGroup clients are not connected: {names}")++ def _require_route_connected(self, route: ToolRoute) -> None:+ if not route.client.is_connected():+ raise RuntimeError(+ f"ClientGroup client for server {route.server_name!r} is not connected"+ )++ async def list_tools(+ self, *, cache_mode: CacheMode = "refresh"+ ) -> list[mcp_types.Tool]:+ """List tools from every client with namespaced names.++ An explicit call is the group's catalog-refresh mechanism, so it+ defaults to `cache_mode="refresh"`: a client-side response cache+ (SEP-2549) is repopulated rather than served, and the routes reflect+ what every server advertises now. Pass `cache_mode="use"` to allow+ cache hits when staleness within the server's hint is acceptable.+ """+ self._require_connected()+ tools: list[mcp_types.Tool] = []+ routes: dict[str, ToolRoute] = {}+ clients = list(self._clients.items())+ tool_lists = await gather(+ client.list_tools(cache_mode=cache_mode) for _, client in clients+ )++ for (server_name, client), server_tools in zip(+ clients, tool_lists, strict=True+ ):+ for tool in server_tools:+ public_name = f"{server_name}_{tool.name}"+ if public_name in routes:+ raise ValueError(f"Tool name collision: {public_name!r}")+ routes[public_name] = ToolRoute(+ server_name=server_name,+ client=client,+ upstream_name=tool.name,+ )+ tools.append(tool.model_copy(update={"name": public_name}))++ self._tool_routes = routes+ self._catalog_loaded = True+ return tools++ async def resolve_tool(self, name: str) -> ToolRoute:+ """Resolve a public tool name to its client and upstream identity.++ A known route only requires its own client to be connected; one dead+ server does not couple failures onto calls routed to healthy servers.+ Loading the catalog (the first resolution, or after a refresh) still+ requires every client, since discovery queries them all.+ """+ route = self._tool_routes.get(name)+ if route is not None:+ self._require_route_connected(route)+ return route+ if self._catalog_loaded:+ raise KeyError(+ f"Unknown tool: {name!r}. If servers changed their tools,"+ " call list_tools() to refresh the catalog."+ )++ async with self._route_lock:+ route = self._tool_routes.get(name)+ if route is not None:+ return route+ if not self._catalog_loaded:+ # Lazy cold-start discovery may serve a cached listing; only an+ # explicit list_tools() call promises a refreshed catalog.+ await self.list_tools(cache_mode="use")+ route = self._tool_routes.get(name)++ if route is None:+ raise KeyError(+ f"Unknown tool: {name!r}. If servers changed their tools,"+ " call list_tools() to refresh the catalog."+ )+ return route++ async def call_tool_mcp(+ self,+ name: str,+ arguments: dict[str, Any] | None = None,+ *,+ timeout: datetime.timedelta | float | int | None = None,+ progress_handler: ProgressHandler | None = None,+ meta: dict[str, Any] | None = None,+ ) -> mcp_types.CallToolResult:+ """Call a namespaced tool and return its raw MCP result."""+ route = await self.resolve_tool(name)+ return await route.client.call_tool_mcp(+ route.upstream_name,+ arguments or {},+ timeout=timeout,+ progress_handler=progress_handler,+ meta=meta,+ )++ async def call_tool(+ self,+ name: str,+ arguments: dict[str, Any] | None = None,+ *,+ version: str | None = None,+ timeout: datetime.timedelta | float | int | None = None,+ progress_handler: ProgressHandler | None = None,+ raise_on_error: bool = True,+ meta: dict[str, Any] | None = None,+ ) -> CallToolResult:+ """Call a namespaced tool through the client that advertised it."""+ route = await self.resolve_tool(name)+ return await route.client.call_tool(+ route.upstream_name,+ arguments,+ version=version,+ timeout=timeout,+ progress_handler=progress_handler,+ raise_on_error=raise_on_error,+ meta=meta,+ )diff --git a/fastmcp_slim/fastmcp/client/mixins/tools.py b/fastmcp_slim/fastmcp/client/mixins/tools.pyindex 40db1f21c..caffccd48 100644--- a/fastmcp_slim/fastmcp/client/mixins/tools.py+++ b/fastmcp_slim/fastmcp/client/mixins/tools.py@@ -90,6 +90,8 @@ class ClientToolsMixin:async def list_tools(self: Client,max_pages: int = AUTO_PAGINATION_MAX_PAGES,+ *,+ cache_mode: CacheMode = "use",) -> list[mcp_types.Tool]:"""Retrieve all tools available on the server.@@ -99,6 +101,11 @@ class ClientToolsMixin:Args:max_pages: Maximum number of pages to fetch before raising. Defaults to 250.+ cache_mode: Response-cache behavior for the first page (only active when+ the client was built with a cache and the connection is modern).+ `"use"` (default) serves and stores; `"refresh"` stores without+ serving; `"bypass"` skips the cache. Subsequent cursor pages always+ skip the cache.Returns:list[mcp_types.Tool]: A list of all Tool objects.@@ -112,7 +119,7 @@ class ClientToolsMixin:seen_cursors: set[str] = set()for _ in range(max_pages):- result = await self.list_tools_mcp(cursor=cursor)+ result = await self.list_tools_mcp(cursor=cursor, cache_mode=cache_mode)all_tools.extend(result.tools)if not result.next_cursor:breakdiff --git a/tests/client/group/test_client_group.py b/tests/client/group/test_client_group.pynew file mode 100644index 000000000..bd9cd789e--- /dev/null+++ b/tests/client/group/test_client_group.py@@ -0,0 +1,349 @@+import asyncio+from collections.abc import AsyncIterator+from contextlib import asynccontextmanager+from typing import Any+from unittest.mock import patch++import pytest+from pydantic import ConfigDict++from fastmcp import Client, Context, FastMCP+from fastmcp.client.group import ClientGroup+from fastmcp.client.transports import FastMCPTransport+from fastmcp.mcp_config import MCPConfig, StdioMCPServer+++class LegacyFastMCPTransport(FastMCPTransport):+ legacy_only = True+++class InMemoryServer(StdioMCPServer):+ model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True)++ mcp: FastMCP+ command: str = "in-memory"++ def to_transport(self) -> FastMCPTransport:+ return FastMCPTransport(self.mcp)+++class LegacyInMemoryServer(InMemoryServer):+ def to_transport(self) -> FastMCPTransport:+ return LegacyFastMCPTransport(self.mcp)+++def make_server(name: str) -> FastMCP:+ server = FastMCP(name)++ @server.tool+ async def protocol_era(ctx: Context) -> str:+ request_context = ctx.request_context+ assert request_context is not None+ return request_context.protocol_version++ @server.tool+ def echo(value: str) -> str:+ return f"{name}: {value}"++ return server+++async def test_clients_negotiate_independently():+ legacy = Client(LegacyFastMCPTransport(make_server("legacy")))+ modern = Client(FastMCPTransport(make_server("modern")))+ group = ClientGroup({"old": legacy, "new": modern})++ async with group:+ assert group.protocol_versions == {+ "old": "2025-11-25",+ "new": "2026-07-28",+ }++ tools = await group.list_tools()+ assert {tool.name for tool in tools} == {+ "old_protocol_era",+ "old_echo",+ "new_protocol_era",+ "new_echo",+ }+ route = await group.resolve_tool("new_echo")+ assert route.server_name == "new"+ assert route.client is modern+ assert route.upstream_name == "echo"++ old_era = await group.call_tool("old_protocol_era")+ new_era = await group.call_tool("new_protocol_era")+ echoed = await group.call_tool("new_echo", {"value": "hello"})++ assert old_era.data == "2025-11-25"+ assert new_era.data == "2026-07-28"+ assert echoed.data == "modern: hello"++ assert not legacy.is_connected()+ assert not modern.is_connected()+++async def test_from_config_applies_mode_per_server():+ config = MCPConfig(+ mcpServers={+ "old": InMemoryServer(mcp=make_server("old"), mode="legacy"),+ "new": InMemoryServer(mcp=make_server("new"), mode="auto"),+ }+ )+ group = ClientGroup.from_config(config)++ async with group:+ assert group.protocol_versions == {+ "old": "2025-11-25",+ "new": "2026-07-28",+ }+++async def test_call_tool_populates_routes_lazily():+ group = ClientGroup({"server": Client(make_server("server"))})++ async with group:+ result = await group.call_tool("server_echo", {"value": "hello"})++ assert result.data == "server: hello"+++async def test_concurrent_cold_calls_share_tool_discovery():+ first = Client(make_server("first"))+ second = Client(make_server("second"))+ group = ClientGroup({"first": first, "second": second})++ with (+ patch.object(first, "list_tools", wraps=first.list_tools) as first_list,+ patch.object(second, "list_tools", wraps=second.list_tools) as second_list,+ ):+ async with group:+ results = await asyncio.gather(+ group.call_tool("first_echo", {"value": "one"}),+ group.call_tool("second_echo", {"value": "two"}),+ group.call_tool("first_protocol_era"),+ )++ assert [result.data for result in results] == [+ "first: one",+ "second: two",+ "2026-07-28",+ ]+ assert first_list.call_count == 1+ assert second_list.call_count == 1+++async def test_unknown_tools_do_not_repeat_discovery():+ first = Client(make_server("first"))+ second = Client(make_server("second"))+ group = ClientGroup({"first": first, "second": second})++ with (+ patch.object(first, "list_tools", wraps=first.list_tools) as first_list,+ patch.object(second, "list_tools", wraps=second.list_tools) as second_list,+ ):+ async with group:+ for name in ("missing", "also_missing", "missing"):+ with pytest.raises(KeyError, match=f"Unknown tool: {name!r}"):+ await group.call_tool(name)++ assert first_list.call_count == 1+ assert second_list.call_count == 1+++async def test_callers_can_manage_connections():+ old = Client(LegacyFastMCPTransport(make_server("old")))+ new = Client(FastMCPTransport(make_server("new")))+ group = ClientGroup({"old": old, "new": new})++ async with old, new:+ tools = await group.list_tools()+ result = await group.call_tool("new_echo", {"value": "hello"})++ assert {tool.name for tool in tools} >= {"old_echo", "new_echo"}+ assert result.data == "new: hello"+ assert group.protocol_versions == {+ "old": "2025-11-25",+ "new": "2026-07-28",+ }++ assert not old.is_connected()+ assert not new.is_connected()+++async def test_group_context_does_not_close_caller_owned_client():+ client = Client(make_server("server"))+ group = ClientGroup({"server": client})++ async with client:+ async with group:+ result = await group.call_tool("server_echo", {"value": "hello"})+ assert result.data == "server: hello"++ assert client.is_connected()++ assert not client.is_connected()+++async def test_group_requires_each_client_to_be_connected():+ connected = Client(make_server("connected"))+ disconnected = Client(make_server("disconnected"))+ group = ClientGroup({"connected": connected, "disconnected": disconnected})++ async with connected:+ try:+ await group.list_tools()+ except RuntimeError as exc:+ assert str(exc) == "ClientGroup clients are not connected: 'disconnected'"+ else:+ raise AssertionError("Expected a disconnected-client error")+++async def test_group_keeps_one_connection_per_server():+ lifecycles = {"entered": 0, "exited": 0}++ @asynccontextmanager+ async def lifespan(_server: FastMCP) -> AsyncIterator[dict[str, Any]]:+ lifecycles["entered"] += 1+ try:+ yield {}+ finally:+ lifecycles["exited"] += 1++ server = FastMCP("stateful", lifespan=lifespan)++ @server.tool+ def echo(value: str) -> str:+ return value++ group = ClientGroup({"stateful": Client(server)})+ async with group:+ await group.list_tools()+ await group.call_tool("stateful_echo", {"value": "one"})+ await group.call_tool("stateful_echo", {"value": "two"})+ assert lifecycles == {"entered": 1, "exited": 0}++ assert lifecycles == {"entered": 1, "exited": 1}+++async def test_tool_name_collisions_are_rejected():+ first = FastMCP("first")+ second = FastMCP("second")++ @first.tool(name="b_echo")+ def first_echo() -> str:+ return "first"++ @second.tool(name="echo")+ def second_echo() -> str:+ return "second"++ group = ClientGroup(+ {+ "a": Client(first),+ "a_b": Client(second),+ }+ )++ async with group:+ try:+ await group.list_tools()+ except ValueError as exc:+ assert str(exc) == "Tool name collision: 'a_b_echo'"+ else:+ raise AssertionError("Expected a tool name collision")+++async def test_single_client_group_provides_namespacing_alone():+ group = ClientGroup({"solo": Client(FastMCPTransport(make_server("solo")))})++ async with group:+ tools = await group.list_tools()+ assert sorted(tool.name for tool in tools) == ["solo_echo", "solo_protocol_era"]++ result = await group.call_tool("solo_echo", {"value": "hi"})+ assert result.data == "solo: hi"+++async def test_client_membership_is_immutable():+ group = ClientGroup({"solo": Client(FastMCPTransport(make_server("solo")))})++ with pytest.raises(TypeError):+ group.clients["other"] = Client( # ty: ignore[invalid-assignment]+ FastMCPTransport(make_server("other"))+ )+++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)++ await group.__aexit__(None, None, None)+ assert not client.is_connected()+++async def test_known_route_survives_an_unrelated_dead_client():+ healthy = Client(FastMCPTransport(make_server("healthy")))+ doomed = Client(FastMCPTransport(make_server("doomed")))+ group = ClientGroup({"healthy": healthy, "doomed": doomed})++ async with healthy:+ async with doomed:+ await group.list_tools()+ assert not doomed.is_connected()++ result = await group.call_tool("healthy_echo", {"value": "hi"})+ assert result.data == "healthy: hi"++ with pytest.raises(RuntimeError, match="doomed"):+ await group.call_tool("doomed_echo", {"value": "hi"})+++async def test_partial_connect_failure_unwinds_connected_clients():+ ok = Client(FastMCPTransport(make_server("ok")))+ bad = Client(FastMCPTransport(make_server("bad")))+ group = ClientGroup({"ok": ok, "bad": bad})++ from unittest.mock import AsyncMock++ with patch.object(bad, "__aenter__", AsyncMock(side_effect=RuntimeError("boom"))):+ with pytest.raises(RuntimeError, match="boom"):+ async with group:+ pass++ assert not ok.is_connected()+ assert group._exit_stack is None+++async def test_explicit_list_tools_refreshes_past_client_response_cache():+ """A cache-hinted server must not leave group.list_tools() serving a stale+ catalog: the explicit call is the documented refresh mechanism."""+ server = FastMCP("hinted", cache_ttl=60000)++ @server.tool+ def original() -> str:+ return "original"++ client = Client(FastMCPTransport(server), cache=True)+ group = ClientGroup({"hinted": client})++ async with group:+ tools = await group.list_tools()+ assert [tool.name for tool in tools] == ["hinted_original"]++ @server.tool+ def added() -> str:+ return "added"++ refreshed = await group.list_tools()+ assert {tool.name for tool in refreshed} == {"hinted_original", "hinted_added"}++ result = await group.call_tool("hinted_added")+ assert result.data == "added"diff --git a/tests/server/test_pagination.py b/tests/server/test_pagination.pyindex 89d3ec79e..68791f8b5 100644--- a/tests/server/test_pagination.py+++ b/tests/server/test_pagination.py@@ -263,6 +263,7 @@ class TestPaginationCycleDetection:async def returning_constant_cursor(*,cursor: str | None = None,+ cache_mode: str = "use",) -> mcp_types.ListToolsResult:result = await original(cursor=cursor)result.next_cursor = "stuck"@@ -292,6 +293,7 @@ class TestPaginationCycleDetection:async def returning_constant_cursor(*,cursor: str | None = None,+ cache_mode: str = "use",) -> mcp_types.ListPromptsResult:result = await original(cursor=cursor)result.next_cursor = "stuck"@@ -319,6 +321,7 @@ class TestPaginationCycleDetection:async def returning_constant_cursor(*,cursor: str | None = None,+ cache_mode: str = "use",) -> mcp_types.ListResourcesResult:result = await original(cursor=cursor)result.next_cursor = "stuck"@@ -346,6 +349,7 @@ class TestPaginationCycleDetection:async def returning_constant_cursor(*,cursor: str | None = None,+ cache_mode: str = "use",) -> mcp_types.ListResourceTemplatesResult:result = await original(cursor=cursor)result.next_cursor = "stuck"@@ -375,6 +379,7 @@ class TestPaginationCycleDetection:async def returning_cycling_cursor(*,cursor: str | None = None,+ cache_mode: str = "use",) -> mcp_types.ListToolsResult:nonlocal call_countresult = await original(cursor=cursor)@@ -407,6 +412,7 @@ class TestPaginationCycleDetection:async def returning_empty_cursor(*,cursor: str | None = None,+ cache_mode: str = "use",) -> mcp_types.ListToolsResult:result = await original(cursor=cursor)result.next_cursor = ""@@ -435,6 +441,7 @@ class TestPaginationCycleDetection:async def returning_unique_cursor(*,cursor: str | None = None,+ cache_mode: str = "use",) -> mcp_types.ListToolsResult:nonlocal call_countresult = await original(cursor=cursor)@@ -465,6 +472,7 @@ class TestPaginationCycleDetection:async def returning_unique_cursor(*,cursor: str | None = None,+ cache_mode: str = "use",) -> mcp_types.ListResourcesResult:nonlocal call_countresult = await original(cursor=cursor)@@ -495,6 +503,7 @@ class TestPaginationCycleDetection:async def returning_unique_cursor(*,cursor: str | None = None,+ cache_mode: str = "use",) -> mcp_types.ListPromptsResult:nonlocal call_countresult = await original(cursor=cursor)