🚀 The fast, Pythonic way to build MCP servers and clients.
Honor per-server MCP config timeouts (#5758)
Atharva Vichare8f0d481ab6d8
diff --git a/docs/clients/client-groups.mdx b/docs/clients/client-groups.mdxindex e2adef623..9f0f3e607 100644--- a/docs/clients/client-groups.mdx+++ b/docs/clients/client-groups.mdx@@ -72,7 +72,7 @@ The group aggregates names and detects collisions; it never stands between the a## 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:+`ClientGroup.from_config` creates one client per server rather than passing the entire configuration through a proxy. Each entry’s `timeout` applies to that client in milliseconds; `0` disables the request timeout. A FastMCP-specific `mode` field can select the protocol behavior for each server:```pythonfrom fastmcp import ClientGroupdiff --git a/docs/clients/transports.mdx b/docs/clients/transports.mdxindex 52b93f050..cc34d8c34 100644--- a/docs/clients/transports.mdx+++ b/docs/clients/transports.mdx@@ -237,6 +237,33 @@ async with client:answer = await client.call_tool("assistant_ask", {"question": "What?"})```+### Per-server Timeouts++Set `timeout` on a server entry to limit how long its requests can wait. Entry timeouts use **milliseconds**, apply to HTTP, SSE, and STDIO servers, and take precedence over the timeout passed to `Client`. An omitted or `null` entry timeout uses the client timeout; `0` disables the timeout for that backend session.++For example, give the weather server 5 seconds and use a 30-second client timeout for entries without their own limit:++```python+from fastmcp import Client++config = {+ "mcpServers": {+ "weather": {+ "url": "https://weather.example.com/mcp",+ "timeout": 5000,+ },+ "assistant": {+ "command": "python",+ "args": ["./assistant.py"],+ },+ }+}++client = Client(config, timeout=30)+```++With multiple servers, the client timeout also limits the entire routed request, so a backend timeout cannot extend that outer limit. Composite clients and configurations with tool transformations or tag filters use backend proxy sessions: a per-call `timeout` cannot extend those sessions' configured limits. `sse_read_timeout` remains a separate setting for the SSE connection.+### Tool TransformationsFastMCP supports tool transformations within the configuration. You can change names, descriptions, tags, and arguments for tools from a server.diff --git a/fastmcp_slim/fastmcp/client/group.py b/fastmcp_slim/fastmcp/client/group.pyindex 22e62857b..eddb560b4 100644--- a/fastmcp_slim/fastmcp/client/group.py+++ b/fastmcp_slim/fastmcp/client/group.py@@ -88,7 +88,10 @@ class ClientGroup: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)+ timeout = server.timeout / 1000 if server.timeout is not None else None+ clients[name] = Client(+ server.to_transport(), mode=configured_mode, timeout=timeout+ )return cls(clients)diff --git a/fastmcp_slim/fastmcp/client/transports/config.py b/fastmcp_slim/fastmcp/client/transports/config.pyindex 4e5b5e9a5..e28c699b1 100644--- a/fastmcp_slim/fastmcp/client/transports/config.py+++ b/fastmcp_slim/fastmcp/client/transports/config.py@@ -135,6 +135,9 @@ class MCPConfigTransport(ClientTransport):) -> AsyncIterator[ClientSession]:# Single server - delegate directly to pre-created transportif len(self.config.mcpServers) == 1:+ config = next(iter(self.config.mcpServers.values()))+ if config.timeout is not None:+ session_kwargs["read_timeout_seconds"] = config.timeout / 1000 or Noneasync with self.transport.connect_session(transport_options=transport_options, **session_kwargs) as session:@@ -358,6 +361,8 @@ class MCPConfigTransport(ClientTransport):client_kwargs["forward_incoming_headers"] = (transport_options.forward_incoming_headers)+ if config.timeout is not None:+ timeout = config.timeout / 1000client = StatefulProxyClient(transport=transport, timeout=timeout, **client_kwargs)diff --git a/fastmcp_slim/fastmcp/mcp_config.py b/fastmcp_slim/fastmcp/mcp_config.pyindex b18ea1a3e..adf01f424 100644--- a/fastmcp_slim/fastmcp/mcp_config.py+++ b/fastmcp_slim/fastmcp/mcp_config.py@@ -140,7 +140,11 @@ class _TransformingMCPServerMixin(BaseModel):transport = cast("ClientTransport", super().to_transport()) # ty: ignore[unresolved-attribute]# The proxy that wraps this client forwards the initialize handshake and# server-initiated features, which require the legacy era.- client = Client(transport=transport, name=client_name, mode="legacy")+ config = cast("MCPServerTypes", self)+ timeout = config.timeout / 1000 if config.timeout is not None else None+ client = Client(+ transport=transport, name=client_name, mode="legacy", timeout=timeout+ )wrapped_mcp_server = create_proxy(client, name=server_name)if self.include_tags is not None:@@ -181,6 +185,8 @@ class StdioMCPServer(BaseModel):"""MCP server configuration for stdio transport.This is the canonical configuration format for MCP servers using stdio transport.+ `timeout` sets the per-request timeout in milliseconds when used in an+ `MCPConfig`. It takes precedence over the client timeout; zero disables it."""# Required fields@@ -230,6 +236,8 @@ class RemoteMCPServer(BaseModel):"""MCP server configuration for HTTP/SSE transport.This is the canonical configuration format for MCP servers using remote transports.+ `timeout` sets the per-request timeout in milliseconds when used in an+ `MCPConfig`. It takes precedence over the client timeout; zero disables it."""# Required fieldsdiff --git a/tests/client/group/test_client_group.py b/tests/client/group/test_client_group.pyindex 4b1a496af..88fba0e86 100644--- a/tests/client/group/test_client_group.py+++ b/tests/client/group/test_client_group.py@@ -6,6 +6,7 @@ from unittest.mock import patchimport anyioimport pytest+from mcp import MCPErrorfrom pydantic import ConfigDictfrom fastmcp import Client, ClientGroup, Context, FastMCP@@ -449,3 +450,28 @@ async def test_exit_under_cancelled_scope_disconnects_members():await anyio.sleep(0.01)assert group._nesting_counter == 0assert group._exit_stack is None++[email protected]("mode", ["legacy", "auto"])[email protected]("timeout", [None, 0, 500])+async def test_from_config_applies_entry_timeout(+ mode: str, timeout: int | None+) -> None:+ server = FastMCP("Timeout")++ @server.tool+ async def slow() -> str:+ await asyncio.sleep(0.7)+ return "completed"++ group = ClientGroup.from_config(+ MCPConfig(mcpServers={"backend": InMemoryServer(mcp=server, timeout=timeout)}),+ default_mode=mode,+ )+ async with group:+ await group.list_tools()+ if timeout:+ with pytest.raises(MCPError, match="timed out"):+ await group.call_tool("backend_slow")+ else:+ assert (await group.call_tool("backend_slow")).data == "completed"diff --git a/tests/client/transports/test_config_timeout.py b/tests/client/transports/test_config_timeout.pynew file mode 100644index 000000000..1425a3583--- /dev/null+++ b/tests/client/transports/test_config_timeout.py@@ -0,0 +1,114 @@+"""Per-server MCP config timeouts reach the sessions that send requests."""++import asyncio+from collections.abc import AsyncIterator+from contextlib import asynccontextmanager+from typing import Any++import pytest+from mcp import ClientSession, MCPError++from fastmcp import Client, FastMCP+from fastmcp.client.transports import (+ FastMCPTransport,+ SSETransport,+ StdioTransport,+ StreamableHttpTransport,+)+from fastmcp.exceptions import ToolError+++def backend_sessions(monkeypatch: pytest.MonkeyPatch) -> list[ClientSession]:+ """Replace external connections while retaining config parsing and routing."""+ server = FastMCP("Timeout backend")++ @server.tool(tags={"public"})+ async def slow(seconds: float = 1) -> str:+ await asyncio.sleep(seconds)+ return "completed"++ sessions: list[ClientSession] = []++ @asynccontextmanager+ async def connect_session(self: Any, **kwargs: Any) -> AsyncIterator[ClientSession]:+ async with FastMCPTransport(server).connect_session(**kwargs) as session:+ sessions.append(session)+ yield session++ for transport_type in (StreamableHttpTransport, SSETransport, StdioTransport):+ monkeypatch.setattr(transport_type, "connect_session", connect_session)+ return sessions++[email protected](params=["http", "sse", "stdio"])+def server_entry(request: pytest.FixtureRequest) -> dict[str, Any]:+ if request.param == "stdio":+ return {"command": "unused"}+ return {"url": "http://example.invalid/mcp", "transport": request.param}++[email protected]("server_count", [1, 2])[email protected]("transformed", [False, True])+async def test_entry_timeout_limits_requests(+ backend_sessions: list[ClientSession],+ server_entry: dict[str, Any],+ server_count: int,+ transformed: bool,+) -> None:+ entry = {**server_entry, "timeout": 500}+ if transformed:+ entry["include_tags"] = ["public"]+ servers = {"limited": entry}+ if server_count == 2:+ servers["unlimited"] = server_entry++ async with Client({"mcpServers": servers}, mode="legacy") as client:+ name = "slow" if server_count == 1 else "limited_slow"+ with pytest.raises((MCPError, ToolError), match="timed out"):+ await client.call_tool(name)++ if server_count == 2:+ result = await client.call_tool("unlimited_slow", {"seconds": 0})+ assert result.data == "completed"++ assert backend_sessions[0]._session_read_timeout_seconds == 0.5+++ ("entry_timeout", "client_timeout", "expected"),+ [+ (None, None, None),+ (None, 3, 3.0),+ (1250, None, 1.25),+ (1250, 3, 1.25),+ (0, 3, None),+ ],+)[email protected]("server_count", [1, 2])+async def test_entry_timeout_defaults_and_units(+ backend_sessions: list[ClientSession],+ server_entry: dict[str, Any],+ entry_timeout: int | None,+ client_timeout: int | None,+ expected: float | None,+ server_count: int,+) -> None:+ servers = {"first": {**server_entry, "timeout": entry_timeout}}+ if server_count == 2:+ servers["second"] = server_entry++ async with Client({"mcpServers": servers}, timeout=client_timeout):+ assert backend_sessions[0]._session_read_timeout_seconds == expected+ if server_count == 2:+ assert backend_sessions[1]._session_read_timeout_seconds == client_timeout+++async def test_single_server_per_call_timeout_overrides_entry(+ backend_sessions: list[ClientSession], server_entry: dict[str, Any]+) -> None:+ config = {"mcpServers": {"only": {**server_entry, "timeout": 500}}}+ async with Client(config) as client:+ result = await client.call_tool("slow", {"seconds": 0.6}, timeout=2)+ assert result.data == "completed"+ assert backend_sessions[0]._session_read_timeout_seconds == 0.5