Skip to content

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

Teach fastmcp.Client the modern protocol: mode negotiation, MRTR driver, response cache (#4450)

Jeremiah Lowin515a2244a21f
diff --git a/docs/clients/client.mdx b/docs/clients/client.mdx
index 4d985e187..30e09e613 100644
--- a/docs/clients/client.mdx
+++ b/docs/clients/client.mdx
@@ -160,6 +160,80 @@ async with client:
tools = await client.list_tools()
```
+## Protocol negotiation
+
+<VersionBadge version="4.0.0" />
+
+MCP has two protocol eras: the original *legacy* era, which begins every connection with an `initialize` handshake, and the *modern* era (protocol version `2026-07-28` and later), which a client discovers by probing the server's `server/discover` endpoint. The `mode` parameter controls which era the client negotiates when it connects.
+
+By default, `mode="legacy"`. This runs the initialize handshake and behaves identically to earlier FastMCP versions, so existing code connecting to any server keeps working unchanged.
+
+```python
+from fastmcp import Client
+
+# Legacy handshake (the default)
+client = Client("https://example.com/mcp", mode="legacy")
+```
+
+Set `mode="auto"` to negotiate the newest era the server supports. The client probes `server/discover` and adopts the modern protocol when the server responds; for any server that is not positive evidence of modern support, it falls back to the legacy handshake. This makes `"auto"` safe to use against a mixed fleet of legacy and modern servers.
+
+```python
+client = Client("https://example.com/mcp", mode="auto")
+```
+
+You can also pin a specific modern protocol version to adopt it directly, without a discovery probe:
+
+```python
+client = Client("https://example.com/mcp", mode="2026-07-28")
+```
+
+Once connected, the negotiated version and the server's advertised capabilities are available as properties. Both are populated regardless of which era was negotiated, and both are `None` while the client is disconnected.
+
+```python
+async with Client("https://example.com/mcp", mode="auto") as client:
+ print(client.protocol_version) # e.g. "2026-07-28"
+ print(client.server_capabilities) # ServerCapabilities | None
+```
+
+<Note>
+`mode="auto"` is not the default yet β€” the conservative `"legacy"` remains the default to preserve byte-identical behavior against pre-2026 servers. Whether `"auto"` becomes the default is a future release decision.
+</Note>
+
+## Response caching
+
+<VersionBadge version="4.0.0" />
+
+The client can cache the results of `list_tools`, `list_resources`, `list_prompts`, and `read_resource` so that repeated calls avoid a network round-trip. Caching is opt-in and honors the server's own cache hints, so it only takes effect against modern-era servers that advertise them β€” a cache is inert on a legacy connection.
+
+Enable the default in-memory cache by passing `cache=True`. It respects the `ttlMs` and `cacheScope` hints the server attaches to each response.
+
+```python
+from fastmcp import Client
+
+client = Client("https://example.com/mcp", mode="auto", cache=True)
+
+async with client:
+ tools = await client.list_tools() # fetched from the server
+ tools = await client.list_tools() # served from the cache
+```
+
+The default (`cache=None`) and `cache=False` both disable caching. For control over the store, TTL, or partitioning, pass a `CacheConfig`. A custom config requires a `target_id`, since in-memory FastMCP transports expose no server URL to derive a shared-store identity from.
+
+```python
+from fastmcp import Client
+from mcp.client.caching import CacheConfig
+
+config = CacheConfig(target_id="weather-api", default_ttl_ms=60_000)
+client = Client("https://example.com/mcp", mode="auto", cache=config)
+```
+
+The high-level `list_tools`, `list_resources`, `list_prompts`, and `read_resource` methods always use the cache when one is configured. To override the behavior for a single call, use the lower-level `*_mcp` variants, which accept a `cache_mode` argument: `"use"` (the default) serves and stores, `"refresh"` stores a fresh result without serving a cached one, and `"bypass"` skips the cache entirely.
+
+```python
+async with client:
+ fresh = await client.list_tools_mcp(cache_mode="refresh")
+```
+
## Operations
FastMCP clients interact with three types of server components.
diff --git a/docs/clients/elicitation.mdx b/docs/clients/elicitation.mdx
index dc0135ae3..840e426d2 100644
--- a/docs/clients/elicitation.mdx
+++ b/docs/clients/elicitation.mdx
@@ -136,3 +136,20 @@ client = Client(
elicitation_handler=elicitation_handler
)
```
+
+## Input-required rounds
+
+<VersionBadge version="4.0.0" />
+
+Modern-era servers (protocol version `2026-07-28` and later) can pause a `call_tool`, `get_prompt`, or `read_resource` call to ask for input before producing a final result. When this happens, the client answers each round automatically using the callbacks you already configured β€” your `elicitation_handler`, `sampling_handler`, and roots β€” and retries until the call reaches a terminal result. No extra wiring is needed beyond the handlers described above.
+
+The `input_required_max_rounds` parameter caps how many rounds the client will answer before giving up, guarding against a server that never terminates. It defaults to `10`.
+
+```python
+client = Client(
+ "https://example.com/mcp",
+ mode="auto",
+ elicitation_handler=elicitation_handler,
+ input_required_max_rounds=5,
+)
+```
diff --git a/fastmcp_slim/fastmcp/client/client.py b/fastmcp_slim/fastmcp/client/client.py
index 94ec0ee49..2106c38c7 100644
--- a/fastmcp_slim/fastmcp/client/client.py
+++ b/fastmcp_slim/fastmcp/client/client.py
@@ -3,26 +3,42 @@ from __future__ import annotations
import asyncio
import copy
import datetime
+import hashlib
import secrets
import ssl
+import uuid
import weakref
-from collections.abc import Coroutine
+from collections.abc import Callable, Coroutine
from contextlib import AsyncExitStack, asynccontextmanager, suppress
from dataclasses import dataclass, field
from pathlib import Path
from typing import TYPE_CHECKING, Any, Generic, Literal, TypeVar, cast, overload
import anyio
+import anyio.lowlevel
import httpx
import mcp_types
from exceptiongroup import catch
from mcp import ClientSession, MCPError
+from mcp.client._input_required import (
+ DEFAULT_INPUT_REQUIRED_MAX_ROUNDS,
+ run_input_required_driver,
+)
+from mcp.client._probe import negotiate_auto
+from mcp.client.caching import (
+ CacheConfig,
+ CacheMode,
+ ClientResponseCache,
+ InMemoryResponseCacheStore,
+)
from mcp.client.extension import NotificationBinding
+from mcp.client.session import ClientRequestContext, MessageHandlerFnT
from mcp_types import (
GetTaskResult,
TaskStatusNotification,
TaskStatusNotificationParams,
)
+from mcp_types.version import HANDSHAKE_PROTOCOL_VERSIONS, MODERN_PROTOCOL_VERSIONS
from pydantic import AnyUrl
import fastmcp as fastmcp
@@ -99,6 +115,68 @@ logger = get_logger(__name__)
T = TypeVar("T", bound="ClientTransport")
ResultT = TypeVar("ResultT")
+CacheableT = TypeVar("CacheableT", bound=mcp_types.CacheableResult)
+
+ConnectMode = Literal["legacy", "auto"] | str
+"""How the client negotiates the protocol era at connect time.
+
+- ``"legacy"`` (the current default): the classic initialize handshake, byte-identical
+ to pre-v4 behavior for handshake-era servers.
+- ``"auto"``: probe ``server/discover`` at the newest modern version and adopt it, falling
+ back to the initialize handshake for any server that is not positive evidence of a modern
+ peer (a denylist fallback β€” see the SDK's ``negotiate_auto``).
+- a modern protocol-version string (e.g. ``"2026-07-28"``): adopt that version directly
+ without probing, synthesizing a minimal ``DiscoverResult`` when none is supplied.
+
+The ``str`` arm is only for the version-pin case; ``Client.__init__`` rejects any other value.
+"""
+
+
+def _synthesize_discover(protocol_version: str) -> mcp_types.DiscoverResult:
+ """Build a minimal ``DiscoverResult`` for a pinned modern version (no wire probe).
+
+ Mirrors the SDK Client's ``_synthesize_discover``: the version is pinned but the
+ server identity is unknown, so ``server_info`` is empty.
+ """
+ return mcp_types.DiscoverResult(
+ supported_versions=[protocol_version],
+ capabilities=mcp_types.ServerCapabilities(),
+ server_info=mcp_types.Implementation(name="", version=""),
+ result_type="complete",
+ ttl_ms=0,
+ cache_scope="public",
+ )
+
+
+def _evicting_message_handler(
+ cache: ClientResponseCache, user_handler: MessageHandlerFnT | None
+) -> MessageHandlerFnT:
+ """Compose cache eviction over an existing message handler (SEP-2549).
+
+ A server notification (tools/list_changed, resource updates, etc.) evicts the
+ entries it invalidates *before* the wrapped handler runs, so a downstream
+ consumer never observes a change while a stale cached listing is still served.
+ Mirrors the SDK Client's `_evicting_message_handler`, but delegates to FastMCP's
+ own handler chain rather than clobbering it. Eviction faults are contained: a
+ cache-store error must never block notification delivery.
+ """
+
+ async def handler(
+ message: Any,
+ ) -> None:
+ if isinstance(message, mcp_types.ServerNotification):
+ try:
+ await cache.evict_for_notification(message)
+ except Exception:
+ logger.exception(
+ "Response cache eviction failed; the notification is still delivered"
+ )
+ if user_handler is not None:
+ await user_handler(message)
+ else:
+ await anyio.lowlevel.checkpoint()
+
+ return handler
@dataclass
@@ -180,6 +258,23 @@ class Client(
timeout: Optional timeout for requests (seconds or timedelta)
init_timeout: Optional timeout for initial connection (seconds or timedelta).
Set to 0 to disable. If None, uses the value in the FastMCP global settings.
+ mode: Protocol-era negotiation at connect time. `"legacy"` (the default) runs
+ the initialize handshake, byte-identical to pre-v4 behavior. `"auto"` probes
+ `server/discover` and negotiates the modern era, denylist-falling-back to the
+ handshake for legacy servers. A modern version string (e.g. `"2026-07-28"`)
+ adopts that version directly. `mode="auto"` as a future default is a
+ release-time decision; the conservative `"legacy"` is the default for now.
+ prior_discover: A previously obtained `DiscoverResult` to adopt when `mode` is a
+ version pin, reused instead of synthesizing a minimal one. Ignored otherwise.
+ input_required_max_rounds: Cap on `InputRequiredResult` (SEP-2322) retry rounds
+ for `call_tool` / `get_prompt` / `read_resource` before the driver gives up.
+ Only reachable on 2026-era servers that emit `InputRequiredResult`.
+ cache: Client-side response caching (SEP-2549), opt-in. `None` (default) and
+ `False` disable it; `True` enables the default in-memory store honoring
+ server `ttlMs`/`cacheScope` hints; a `CacheConfig` customizes it. Honoring is
+ modern-only, so a cache is inert on legacy connections. A custom `CacheConfig`
+ store requires `target_id`, since FastMCP transports expose no server URL to
+ derive a shared-store identity from.
Examples:
```python
@@ -269,9 +364,28 @@ class Client(
client_info: mcp_types.Implementation | None = None,
auth: httpx.Auth | Literal["oauth"] | str | None = None,
verify: ssl.SSLContext | bool | str | None = None,
+ mode: ConnectMode = "legacy",
+ prior_discover: mcp_types.DiscoverResult | None = None,
+ input_required_max_rounds: int = DEFAULT_INPUT_REQUIRED_MAX_ROUNDS,
+ cache: CacheConfig | bool | None = None,
) -> None:
self.name = name or self.generate_name()
+ self.input_required_max_rounds = input_required_max_rounds
+
+ if mode not in ("legacy", "auto") and mode not in MODERN_PROTOCOL_VERSIONS:
+ hint = (
+ f" ({mode!r} is a handshake-era version; use mode='legacy')"
+ if mode in HANDSHAKE_PROTOCOL_VERSIONS
+ else ""
+ )
+ raise ValueError(
+ "mode must be 'legacy', 'auto', or one of "
+ f"{list(MODERN_PROTOCOL_VERSIONS)}; got {mode!r}{hint}"
+ )
+ self.mode: ConnectMode = mode
+ self._prior_discover = prior_discover
+
self.transport = cast(ClientTransportT, infer_transport(transport))
if verify is not None:
@@ -317,11 +431,32 @@ class Client(
self.auto_initialize = auto_initialize
+ # Client-side response cache (SEP-2549). Only honored at modern protocol
+ # versions (the SDK ClientResponseCache gates hint-reading on the negotiated
+ # era), so it is inert for legacy connections. `cache=False` disables it.
+ # Retained so `new()` can rebuild an independent cache per clone.
+ self._cache_arg: CacheConfig | bool | None = cache
+ self._response_cache: ClientResponseCache | None = self._build_response_cache(
+ cache
+ )
+
+ # The unwrapped base handler (default routes task notifications; a user
+ # handler is preserved as-is). Retained so `new()` can rebuild the clone's
+ # handler without unwrapping the cache-eviction wrapper below.
+ self._base_message_handler: MessageHandlerFnT | None = (
+ message_handler or TaskNotificationHandler(self)
+ )
+ effective_message_handler = self._base_message_handler
+ if self._response_cache is not None:
+ effective_message_handler = _evicting_message_handler(
+ self._response_cache, effective_message_handler
+ )
+
self._session_kwargs: SessionKwargs = {
"sampling_callback": None,
"list_roots_callback": None,
"logging_callback": create_log_callback(log_handler),
- "message_handler": message_handler or TaskNotificationHandler(self),
+ "message_handler": effective_message_handler,
"read_timeout_seconds": read_timeout_seconds,
"client_info": client_info,
# SDK v2 does not carry `notifications/tasks/status` in any protocol
@@ -365,6 +500,54 @@ class Client(
str, weakref.ref[ToolTask | PromptTask | ResourceTask]
] = {}
+ def _build_response_cache(
+ self, cache: CacheConfig | bool | None
+ ) -> ClientResponseCache | None:
+ """Build the SEP-2549 response cache from the `cache=` argument.
+
+ Response caching is opt-in: `None` (the default) and `False` both leave it
+ disabled, so a legacy connection is byte-identical to pre-v4 behavior (no
+ message-handler wrapping, no caching). `True` enables it with the default
+ `CacheConfig` (honoring server `ttlMs`/`cacheScope` hints via a per-client
+ in-memory store); a `CacheConfig` customizes it.
+
+ Our transports abstract away the server URL the SDK Client uses to derive a
+ cache identity, so `target_id` comes from the explicit `CacheConfig.target_id`
+ or a random per-client id β€” meaning a custom shared store cannot serve one
+ client's entries to another (documented on the parameter).
+ """
+ if cache is None or cache is False:
+ return None
+ config = cache if isinstance(cache, CacheConfig) else CacheConfig()
+
+ target_id = config.target_id
+ if target_id is None:
+ if config.store is not None:
+ raise ValueError(
+ "a custom cache store requires CacheConfig.target_id for FastMCP "
+ "transports: the server URL the SDK derives an identity from is not "
+ "available here, so entries in a shared store could never be served "
+ "to another client"
+ )
+ target_id = uuid.uuid4().hex
+
+ return ClientResponseCache(
+ store=config.store
+ if config.store is not None
+ else InMemoryResponseCacheStore(),
+ partition=config.partition,
+ arm_id=hashlib.sha256(target_id.encode()).hexdigest(),
+ default_ttl_ms=config.default_ttl_ms,
+ clock=config.clock,
+ share_public=config.share_public,
+ # Lazy: the negotiated version is unknown until the handshake completes.
+ negotiated_version=lambda: (
+ self._session_state.session.protocol_version
+ if self._session_state.session is not None
+ else None
+ ),
+ )
+
def _reset_session_state(self, full: bool = False) -> None:
"""Reset session state after disconnect or cancellation.
@@ -391,9 +574,34 @@ class Client(
@property
def initialize_result(self) -> mcp_types.InitializeResult | None:
- """Get the result of the initialization request."""
+ """Get the result of the initialization request.
+
+ `None` on a modern (`server/discover`) connection, which negotiates via a
+ `DiscoverResult` rather than an `InitializeResult`. Use `protocol_version` /
+ `server_capabilities` for era-neutral access to the negotiated identity.
+ """
return self._session_state.initialize_result
+ @property
+ def protocol_version(self) -> str | None:
+ """The negotiated protocol version, or `None` when disconnected.
+
+ Set during connect-time negotiation regardless of era: the initialize
+ handshake, `server/discover`, or a direct version pin all populate it.
+ """
+ session = self._session_state.session
+ return session.protocol_version if session is not None else None
+
+ @property
+ def server_capabilities(self) -> mcp_types.ServerCapabilities | None:
+ """The server's advertised capabilities, or `None` when disconnected.
+
+ Populated from whichever negotiation result the era produced (the
+ `InitializeResult` on legacy, the `DiscoverResult` on modern).
+ """
+ session = self._session_state.session
+ return session.server_capabilities if session is not None else None
+
def set_roots(self, roots: RootsList | RootsHandler) -> None:
"""Set the roots for the client. This does not automatically call `send_roots_list_changed`."""
self._session_kwargs["list_roots_callback"] = create_roots_callback(roots)
@@ -453,17 +661,29 @@ class Client(
new_client._task_registry = {}
new_client._submitted_task_ids = set()
+ # Give the clone its own response cache so cached entries are not shared
+ # across independent sessions, and rebuild the negotiated_version closure
+ # to point at the clone's session state.
+ new_client._response_cache = new_client._build_response_cache(self._cache_arg)
+
# Create a fresh session kwargs dict so the clone doesn't share
# the original's mutable dict. Rebind the task notification handler
# to the new client if the default handler is in use; preserve any
# custom message handler the user may have set.
new_client._session_kwargs = {**self._session_kwargs} # type: ignore[typeddict-item]
- if isinstance(
- self._session_kwargs.get("message_handler"), TaskNotificationHandler
- ):
- new_client._session_kwargs["message_handler"] = TaskNotificationHandler(
- new_client
+ # Recover the unwrapped base handler (never the cache-evicting wrapper): a
+ # default (TaskNotificationHandler) rebinds to the clone; a user handler is
+ # preserved. Then re-wrap with the clone's own cache if one exists.
+ base_handler: MessageHandlerFnT | None = self._base_message_handler
+ if isinstance(base_handler, TaskNotificationHandler) or base_handler is None:
+ base_handler = TaskNotificationHandler(new_client)
+ new_client._base_message_handler = base_handler
+ if new_client._response_cache is not None:
+ new_client._session_kwargs["message_handler"] = _evicting_message_handler(
+ new_client._response_cache, base_handler
)
+ else:
+ new_client._session_kwargs["message_handler"] = base_handler
# Rebind the task-status notification binding so it routes to the clone.
new_client._session_kwargs["notification_bindings"] = [
new_client._task_status_binding()
@@ -483,13 +703,58 @@ class Client(
# Initialize the session if auto_initialize is enabled
try:
if self.auto_initialize:
- await self.initialize()
+ await self._negotiate()
yield
except anyio.ClosedResourceError as e:
raise RuntimeError("Server session was closed unexpectedly") from e
finally:
self._reset_session_state()
+ async def _negotiate(
+ self,
+ timeout: datetime.timedelta | float | int | None = None,
+ ) -> None:
+ """Run the connect-time protocol negotiation dictated by ``self.mode``.
+
+ - ``"legacy"``: today's initialize handshake (populates ``initialize_result``).
+ - ``"auto"``: probe ``server/discover`` at the newest modern version and adopt it,
+ denylist-falling-back to the initialize handshake for handshake-era servers.
+ - a modern version string: adopt that version directly (from ``prior_discover`` if
+ supplied, else a synthesized minimal ``DiscoverResult``).
+
+ Idempotent: once the session has a negotiated protocol version, this is a no-op.
+ """
+ if self.session.protocol_version is not None:
+ # Already negotiated (e.g. a manual initialize() call before context entry).
+ if self.session.initialize_result is not None:
+ self._session_state.initialize_result = self.session.initialize_result
+ return
+
+ if timeout is None:
+ timeout = self._init_timeout
+ else:
+ timeout = normalize_timeout_to_seconds(timeout)
+
+ try:
+ with anyio.fail_after(timeout):
+ if self.mode == "legacy":
+ self._session_state.initialize_result = (
+ await self.session.initialize()
+ )
+ elif self.mode == "auto":
+ await negotiate_auto(self.session)
+ # auto may have fallen back to the legacy handshake; surface its
+ # InitializeResult through the existing public property when so.
+ self._session_state.initialize_result = (
+ self.session.initialize_result
+ )
+ else:
+ self.session.adopt(
+ self._prior_discover or _synthesize_discover(self.mode)
+ )
+ except TimeoutError as e:
+ raise RuntimeError("Failed to initialize server session") from e
+
async def initialize(
self,
timeout: datetime.timedelta | float | int | None = None,
@@ -504,6 +769,11 @@ class Client(
manager unless `auto_initialize=False` was set during client construction.
Manual calls to this method are only needed when auto-initialization is disabled.
+ With `mode="auto"` or a pinned modern version, connect-time negotiation may adopt
+ the modern `server/discover` era, which has no `InitializeResult`; in that case
+ this method raises. Read `protocol_version` / `server_capabilities` instead, or use
+ `mode="legacy"` (the default) when you need the handshake result.
+
Args:
timeout: Optional timeout for the initialization request (seconds or timedelta).
If None, uses the client's init_timeout setting.
@@ -513,7 +783,8 @@ class Client(
capabilities, protocol version, and optional instructions.
Raises:
- RuntimeError: If the client is not connected or initialization times out.
+ RuntimeError: If the client is not connected, initialization times out, or the
+ negotiated era carries no `InitializeResult` (a modern `discover` connection).
Example:
```python
@@ -529,17 +800,15 @@ class Client(
if self.initialize_result is not None:
return self.initialize_result
- if timeout is None:
- timeout = self._init_timeout
- else:
- timeout = normalize_timeout_to_seconds(timeout)
+ await self._negotiate(timeout=timeout)
- try:
- with anyio.fail_after(timeout):
- self._session_state.initialize_result = await self.session.initialize()
- return self._session_state.initialize_result
- except TimeoutError as e:
- raise RuntimeError("Failed to initialize server session") from e
+ if self.initialize_result is None:
+ raise RuntimeError(
+ "The client negotiated a modern protocol era (server/discover), which has "
+ "no InitializeResult. Read client.protocol_version / client.server_capabilities "
+ "instead, or construct the client with mode='legacy'."
+ )
+ return self.initialize_result
async def __aenter__(self):
return await self._connect()
@@ -783,6 +1052,89 @@ class Client(
await call_task
raise
+ async def _cached_fetch(
+ self,
+ method: str,
+ *,
+ cursor: str | None,
+ cache_mode: CacheMode,
+ send: Callable[[], Coroutine[Any, Any, CacheableT]],
+ absorb: Callable[[CacheableT], CacheableT] | None = None,
+ ) -> CacheableT:
+ """Serve one of the cacheable list verbs through the response cache.
+
+ Mirrors the SDK Client's `_cached_fetch`: cursorless `use` calls are served
+ from (and stored to) the cache; a cursor page skips the cache (and evicts on
+ an expired-cursor `INVALID_PARAMS`, which signals the listing changed). The
+ cache is inert on legacy connections because the SDK cache reads no TTL/scope
+ hints below the modern era, so nothing is ever stored to serve.
+
+ `absorb` (tools/list only) re-applies the session's derived per-tool state to a
+ served cache hit, since a hit skips `session.list_tools`.
+ """
+ cache = self._response_cache
+ if cache is None or cache_mode == "bypass":
+ return await send()
+ # A closed (or never-entered) client must raise, never serve cached entries.
+ _ = self.session
+ if cursor is not None:
+ # Continuation pages skip the cache; an expired cursor means the listing
+ # changed, so evict (spec SHOULD) and re-raise.
+ try:
+ return await send()
+ except MCPError as e:
+ if e.code == mcp_types.INVALID_PARAMS:
+ await cache.evict_method(method)
+ raise
+ if cache_mode == "use" and (hit := await cache.read(method, "")) is not None:
+ served = cast(CacheableT, hit)
+ return served if absorb is None else absorb(served)
+ gen = cache.capture(method, "")
+ result = await send()
+ await cache.write(method, "", result, gen, cache_mode)
+ return result
+
+ async def _drive_input_required(
+ self,
+ first: ResultT | mcp_types.InputRequiredResult,
+ retry: Callable[
+ [mcp_types.InputResponses | None, str | None],
+ Coroutine[Any, Any, ResultT | mcp_types.InputRequiredResult],
+ ],
+ ) -> ResultT:
+ """Resolve a SEP-2322 `InputRequiredResult` to its terminal result.
+
+ A 2026-era server may answer `tools/call` / `prompts/get` / `resources/read`
+ with an `InputRequiredResult` carrying embedded sampling / elicitation / roots
+ requests. This hands that off to the SDK's `run_input_required_driver`, which
+ dispatches each embedded request through the *same* callback table that serves
+ legacy server-initiated RPCs (`session.dispatch_input_request`) and retries the
+ original call until it returns a terminal result.
+
+ Legacy servers never emit `InputRequiredResult`, so a terminal `first` passes
+ straight through untouched β€” zero behavior change for pre-2026 servers.
+ """
+ if not isinstance(first, mcp_types.InputRequiredResult):
+ return first
+ session = self.session
+
+ async def dispatch(
+ key: str, req: mcp_types.InputRequest
+ ) -> mcp_types.InputResponse | mcp_types.ErrorData:
+ ctx = ClientRequestContext(
+ session=session,
+ request_id=key,
+ meta=req.params.meta if req.params else None,
+ )
+ return await session.dispatch_input_request(ctx, req)
+
+ return await run_input_required_driver(
+ first,
+ dispatch=dispatch,
+ retry=retry,
+ max_rounds=self.input_required_max_rounds,
+ )
+
def _handle_task_status_notification(
self, notification: TaskStatusNotification
) -> None:
diff --git a/fastmcp_slim/fastmcp/client/mixins/prompts.py b/fastmcp_slim/fastmcp/client/mixins/prompts.py
index c31a09b46..fba8ed3fe 100644
--- a/fastmcp_slim/fastmcp/client/mixins/prompts.py
+++ b/fastmcp_slim/fastmcp/client/mixins/prompts.py
@@ -8,6 +8,7 @@ from typing import TYPE_CHECKING, Any, Literal, cast, overload
import mcp_types
import pydantic_core
+from mcp.client.caching import CacheMode
from pydantic import RootModel
if TYPE_CHECKING:
@@ -34,12 +35,17 @@ class ClientPromptsMixin:
# --- Prompts ---
async def list_prompts_mcp(
- self: Client, *, cursor: str | None = None
+ self: Client,
+ *,
+ cursor: str | None = None,
+ cache_mode: CacheMode = "use",
) -> mcp_types.ListPromptsResult:
"""Send a prompts/list request and return the complete MCP protocol result.
Args:
cursor: Optional pagination cursor from a previous request's nextCursor.
+ cache_mode: Response-cache behavior (only active with a cache and a modern
+ connection). See `list_tools_mcp`.
Returns:
mcp_types.ListPromptsResult: The complete response object from the protocol,
@@ -62,10 +68,15 @@ class ClientPromptsMixin:
if cursor is not None
else None
)
- result = await self._await_with_session_monitoring(
- self.session.list_prompts(params=params)
+
+ async def _send() -> mcp_types.ListPromptsResult:
+ return await self._await_with_session_monitoring(
+ self.session.list_prompts(params=params)
+ )
+
+ return await self._cached_fetch(
+ "prompts/list", cursor=cursor, cache_mode=cache_mode, send=_send
)
- return result
async def list_prompts(
self: Client,
@@ -162,28 +173,23 @@ class ClientPromptsMixin:
propagated_meta = inject_trace_context(meta)
request_meta = cast("mcp_types.RequestParamsMeta | None", propagated_meta)
- # If meta provided, use send_request for SEP-1686 task support
- if propagated_meta:
- # SDK v2: GetPromptRequestParams has no `task` field, so prompt
- # gets cannot be submitted as background tasks over the wire and
- # always graceful-degrade to immediate execution (sdk-feedback #3).
- request = mcp_types.GetPromptRequest(
- params=mcp_types.GetPromptRequestParams(
- name=name,
- arguments=serialized_arguments,
- _meta=request_meta, # type: ignore[unknown-argument] # pydantic alias
- )
- )
- result = await self._await_with_session_monitoring(
- self.session.send_request(
- request=request, # type: ignore[arg-type]
- result_type=mcp_types.GetPromptResult,
- )
- )
- else:
- result = await self._await_with_session_monitoring(
- self.session.get_prompt(name=name, arguments=serialized_arguments)
+ async def _retry(
+ input_responses: mcp_types.InputResponses | None,
+ request_state: str | None,
+ ) -> mcp_types.GetPromptResult | mcp_types.InputRequiredResult:
+ return await self.session.get_prompt(
+ name=name,
+ arguments=serialized_arguments,
+ meta=request_meta,
+ input_responses=input_responses,
+ request_state=request_state,
+ allow_input_required=True,
)
+
+ first = await self._await_with_session_monitoring(_retry(None, None))
+ result = await self._await_with_session_monitoring(
+ self._drive_input_required(first, _retry)
+ )
return result
@overload
diff --git a/fastmcp_slim/fastmcp/client/mixins/resources.py b/fastmcp_slim/fastmcp/client/mixins/resources.py
index d0c6f50e2..7bbbd84ed 100644
--- a/fastmcp_slim/fastmcp/client/mixins/resources.py
+++ b/fastmcp_slim/fastmcp/client/mixins/resources.py
@@ -7,6 +7,7 @@ import weakref
from typing import TYPE_CHECKING, Any, Literal, cast, overload
import mcp_types
+from mcp.client.caching import CacheMode
from pydantic import AnyUrl, RootModel
if TYPE_CHECKING:
@@ -33,12 +34,17 @@ class ClientResourcesMixin:
# --- Resources ---
async def list_resources_mcp(
- self: Client, *, cursor: str | None = None
+ self: Client,
+ *,
+ cursor: str | None = None,
+ cache_mode: CacheMode = "use",
) -> mcp_types.ListResourcesResult:
"""Send a resources/list request and return the complete MCP protocol result.
Args:
cursor: Optional pagination cursor from a previous request's nextCursor.
+ cache_mode: Response-cache behavior (only active with a cache and a modern
+ connection). See `list_tools_mcp`.
Returns:
mcp_types.ListResourcesResult: The complete response object from the protocol,
@@ -61,10 +67,15 @@ class ClientResourcesMixin:
if cursor is not None
else None
)
- result = await self._await_with_session_monitoring(
- self.session.list_resources(params=params)
+
+ async def _send() -> mcp_types.ListResourcesResult:
+ return await self._await_with_session_monitoring(
+ self.session.list_resources(params=params)
+ )
+
+ return await self._cached_fetch(
+ "resources/list", cursor=cursor, cache_mode=cache_mode, send=_send
)
- return result
async def list_resources(
self: Client,
@@ -114,12 +125,17 @@ class ClientResourcesMixin:
return all_resources
async def list_resource_templates_mcp(
- self: Client, *, cursor: str | None = None
+ self: Client,
+ *,
+ cursor: str | None = None,
+ cache_mode: CacheMode = "use",
) -> mcp_types.ListResourceTemplatesResult:
"""Send a resources/listResourceTemplates request and return the complete MCP protocol result.
Args:
cursor: Optional pagination cursor from a previous request's nextCursor.
+ cache_mode: Response-cache behavior (only active with a cache and a modern
+ connection). See `list_tools_mcp`.
Returns:
mcp_types.ListResourceTemplatesResult: The complete response object from the protocol,
@@ -142,10 +158,18 @@ class ClientResourcesMixin:
if cursor is not None
else None
)
- result = await self._await_with_session_monitoring(
- self.session.list_resource_templates(params=params)
+
+ async def _send() -> mcp_types.ListResourceTemplatesResult:
+ return await self._await_with_session_monitoring(
+ self.session.list_resource_templates(params=params)
+ )
+
+ return await self._cached_fetch(
+ "resources/templates/list",
+ cursor=cursor,
+ cache_mode=cache_mode,
+ send=_send,
)
- return result
async def list_resource_templates(
self: Client,
@@ -230,28 +254,22 @@ class ClientResourcesMixin:
propagated_meta = inject_trace_context(meta)
request_meta = cast("mcp_types.RequestParamsMeta | None", propagated_meta)
- # If meta provided, use send_request for SEP-1686 task support
- if propagated_meta:
- # SDK v2: ReadResourceRequestParams has no `task` field, so
- # resource reads cannot be submitted as background tasks over the
- # wire and always graceful-degrade to immediate execution
- # (sdk-feedback #3). The uri is a plain string on the wire.
- request = mcp_types.ReadResourceRequest(
- params=mcp_types.ReadResourceRequestParams(
- uri=uri_str,
- _meta=request_meta, # type: ignore[unknown-argument] # pydantic alias
- )
- )
- result = await self._await_with_session_monitoring(
- self.session.send_request(
- request=request, # type: ignore[arg-type]
- result_type=mcp_types.ReadResourceResult,
- )
- )
- else:
- result = await self._await_with_session_monitoring(
- self.session.read_resource(uri_str)
+ async def _retry(
+ input_responses: mcp_types.InputResponses | None,
+ request_state: str | None,
+ ) -> mcp_types.ReadResourceResult | mcp_types.InputRequiredResult:
+ return await self.session.read_resource(
+ uri_str,
+ meta=request_meta,
+ input_responses=input_responses,
+ request_state=request_state,
+ allow_input_required=True,
)
+
+ first = await self._await_with_session_monitoring(_retry(None, None))
+ result = await self._await_with_session_monitoring(
+ self._drive_input_required(first, _retry)
+ )
return result
@overload
diff --git a/fastmcp_slim/fastmcp/client/mixins/tools.py b/fastmcp_slim/fastmcp/client/mixins/tools.py
index 555c9553b..6e0a0de11 100644
--- a/fastmcp_slim/fastmcp/client/mixins/tools.py
+++ b/fastmcp_slim/fastmcp/client/mixins/tools.py
@@ -7,6 +7,7 @@ import weakref
from typing import TYPE_CHECKING, Any, Literal, cast, overload
import mcp_types
+from mcp.client.caching import CacheMode
from opentelemetry.trace import Status, StatusCode
from pydantic import RootModel
@@ -38,12 +39,19 @@ class ClientToolsMixin:
# --- Tools ---
async def list_tools_mcp(
- self: Client, *, cursor: str | None = None
+ self: Client,
+ *,
+ cursor: str | None = None,
+ cache_mode: CacheMode = "use",
) -> mcp_types.ListToolsResult:
"""Send a tools/list request and return the complete MCP protocol result.
Args:
cursor: Optional pagination cursor from a previous request's nextCursor.
+ cache_mode: Response-cache behavior for this call (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. A cursor page always skips the cache.
Returns:
mcp_types.ListToolsResult: The complete response object from the protocol,
@@ -66,10 +74,25 @@ class ClientToolsMixin:
if cursor is not None
else None
)
- result = await self._await_with_session_monitoring(
- self.session.list_tools(params=params)
+
+ async def _send() -> mcp_types.ListToolsResult:
+ return await self._await_with_session_monitoring(
+ self.session.list_tools(params=params)
+ )
+
+ return await self._cached_fetch(
+ "tools/list",
+ cursor=cursor,
+ cache_mode=cache_mode,
+ send=_send,
+ # A cache hit skips session.list_tools, so re-absorb the served
+ # listing to rebuild the session's derived per-tool state. Hits are
+ # cursorless, but a cached page 1 can carry next_cursor β€” never prune
+ # on a partial listing.
+ absorb=lambda hit: self.session._absorb_tool_listing(
+ hit, complete=hit.next_cursor is None
+ ),
)
- return result
async def list_tools(
self: Client,
@@ -169,14 +192,27 @@ class ClientToolsMixin:
propagated_meta if propagated_meta else None,
)
- result = await self._await_with_session_monitoring(
- self.session.call_tool(
+ read_timeout_seconds = normalize_timeout_to_seconds(timeout)
+ progress_callback = progress_handler or self._progress_handler
+
+ async def _retry(
+ input_responses: mcp_types.InputResponses | None,
+ request_state: str | None,
+ ) -> mcp_types.CallToolResult | mcp_types.InputRequiredResult:
+ return await self.session.call_tool(
name=name,
arguments=arguments,
- read_timeout_seconds=normalize_timeout_to_seconds(timeout),
- progress_callback=progress_handler or self._progress_handler,
+ read_timeout_seconds=read_timeout_seconds,
+ progress_callback=progress_callback,
meta=request_meta,
+ input_responses=input_responses,
+ request_state=request_state,
+ allow_input_required=True,
)
+
+ first = await self._await_with_session_monitoring(_retry(None, None))
+ result = await self._await_with_session_monitoring(
+ self._drive_input_required(first, _retry)
)
# Reflect tool-level errors on the span so callers see ERROR
diff --git a/tests/client/client/test_input_required_driver.py b/tests/client/client/test_input_required_driver.py
new file mode 100644
index 000000000..e96197d58
--- /dev/null
+++ b/tests/client/client/test_input_required_driver.py
@@ -0,0 +1,209 @@
+"""Client-side SEP-2322 multi-round-trip (MRTR) input-required driving.
+
+A 2026-07-28 server may answer `tools/call` / `prompts/get` / `resources/read`
+with an `InputRequiredResult` carrying embedded sampling / elicitation / roots
+requests instead of the terminal result. `fastmcp.Client` fulfils those embedded
+requests through its *existing* handler callbacks (the same table that answers
+legacy server-initiated RPCs) and retries until the call resolves.
+
+The 2026 emitter here is the SDK's own high-level `MCPServer` with declarative
+`Resolve` / `Elicit` resolvers: at 2026-07-28 the framework batches a resolver's
+`Elicit` into an `InputRequiredResult`. It is driven in-memory through a
+`fastmcp.Client` with `mode="auto"` (which negotiates 2026-07-28 over the
+dual-era stream loop), so the whole answer path runs through FastMCP's client.
+
+Server-side MRTR *emission* is a maintainer-held design surface; these tests only
+exercise the client-side *answering* path, which the spec's decisive finding says
+is era-neutral by construction once the driver is wired.
+"""
+
+from typing import Annotated, cast
+
+import pytest
+from mcp.client._input_required import (
+ DEFAULT_INPUT_REQUIRED_MAX_ROUNDS,
+ InputRequiredRoundsExceededError,
+)
+from mcp.server.mcpserver import Elicit, MCPServer, Resolve
+from pydantic import BaseModel
+
+from fastmcp import Client, FastMCP
+from fastmcp.client.elicitation import ElicitResult
+
+
+class _Name(BaseModel):
+ name: str
+
+
+def _ask_name() -> Elicit[_Name]:
+ return Elicit("What is your name?", _Name)
+
+
+class _A(BaseModel):
+ a: str
+
+
+class _B(BaseModel):
+ b: str
+
+
+def _ask_a() -> Elicit[_A]:
+ return Elicit("question A", _A)
+
+
+def _ask_b(dep: Annotated[_A, Resolve(_ask_a)]) -> Elicit[_B]:
+ """A resolver depending on another's answer β€” asked in a later round."""
+ return Elicit(f"question B given {dep.a}", _B)
+
+
+def _multi_round_server() -> MCPServer:
+ server = MCPServer("multi")
+
+ @server.tool()
+ def combine(x: Annotated[_B, Resolve(_ask_b)]) -> str:
+ return f"got {x.b}"
+
+ return server
+
+
+def _mrtr_server() -> MCPServer:
+ """An SDK MCPServer whose `greet` tool elicits a name via a resolver.
+
+ At 2026-07-28 the elicitation is delivered as an `InputRequiredResult`.
+ """
+ server = MCPServer("mrtr")
+
+ @server.tool()
+ def greet(who: Annotated[_Name, Resolve(_ask_name)]) -> str:
+ return f"Hello, {who.name}!"
+
+ return server
+
+
+class TestParamDefaults:
+ def test_default_max_rounds(self):
+ client = Client(FastMCP("x"))
+ assert client.input_required_max_rounds == DEFAULT_INPUT_REQUIRED_MAX_ROUNDS
+
+ def test_custom_max_rounds(self):
+ client = Client(FastMCP("x"), input_required_max_rounds=3)
+ assert client.input_required_max_rounds == 3
+
+ def test_new_preserves_max_rounds(self):
+ parent = Client(FastMCP("x"), input_required_max_rounds=4)
+ assert parent.new().input_required_max_rounds == 4
+
+
+class TestCallToolMRTR:
+ async def test_single_round_completes(self):
+ """One full MRTR round: the server asks, the client's elicitation_handler
+ answers, and the tool completes with the answered value."""
+ asked: list[str] = []
+
+ async def handler(message, response_type, params, ctx):
+ asked.append(message)
+ return ElicitResult(action="accept", content=response_type(name="Ada"))
+
+ async with Client(
+ _mrtr_server(), mode="auto", elicitation_handler=handler
+ ) as client:
+ assert client.protocol_version == "2026-07-28"
+ result = await client.call_tool("greet", {})
+
+ # The embedded elicitation was answered exactly once and the terminal
+ # result carries the answered value. The SDK MCPServer wraps scalar
+ # output as {"result": ...}, surfaced via structured_content.
+ assert asked == ["What is your name?"]
+ assert result.structured_content == {"result": "Hello, Ada!"}
+ assert result.data.result == "Hello, Ada!"
+
+ async def test_data_parsed_on_terminal_result_only(self):
+ """`.data` deserialization runs on the resolved terminal result, never on
+ the intermediate InputRequiredResult."""
+
+ async def handler(message, response_type, params, ctx):
+ return ElicitResult(action="accept", content=response_type(name="Bob"))
+
+ async with Client(
+ _mrtr_server(), mode="auto", elicitation_handler=handler
+ ) as client:
+ result = await client.call_tool("greet", {})
+
+ assert result.is_error is False
+ assert result.data.result == "Hello, Bob!"
+ assert result.structured_content == {"result": "Hello, Bob!"}
+
+ async def test_multi_round_dependent_resolvers(self):
+ """A resolver depending on another's answer is asked in a later round; the
+ driver loops until the dependent chain terminates."""
+ rounds: list[str] = []
+
+ async def handler(message, response_type, params, ctx):
+ rounds.append(message)
+ if "question A" in message:
+ return ElicitResult(action="accept", content=response_type(a="AA"))
+ return ElicitResult(action="accept", content=response_type(b="BB"))
+
+ async with Client(
+ _multi_round_server(), mode="auto", elicitation_handler=handler
+ ) as client:
+ result = await client.call_tool("combine", {})
+
+ # Two rounds: A first, then B (which the client saw carried A's answer).
+ assert rounds == ["question A", "question B given AA"]
+ assert result.structured_content == {"result": "got BB"}
+
+ async def test_max_rounds_exceeded_raises(self):
+ """A dependent chain needing two rounds under `max_rounds=1` raises."""
+
+ async def handler(message, response_type, params, ctx):
+ field = "a" if "question A" in message else "b"
+ return ElicitResult(action="accept", content=response_type(**{field: "v"}))
+
+ async with Client(
+ _multi_round_server(),
+ mode="auto",
+ elicitation_handler=handler,
+ input_required_max_rounds=1,
+ ) as client:
+ with pytest.raises(InputRequiredRoundsExceededError):
+ await client.call_tool("combine", {})
+
+
+class TestLegacyUnaffected:
+ async def test_legacy_call_tool_no_mrtr(self):
+ """A legacy FastMCP server never emits InputRequiredResult; call_tool
+ behaves byte-identically to pre-driver behavior."""
+ mcp = FastMCP("legacy")
+
+ @mcp.tool
+ def add(a: int, b: int) -> int:
+ return a + b
+
+ async with Client(mcp, mode="legacy") as client:
+ result = await client.call_tool("add", {"a": 2, "b": 3})
+ assert result.data == 5
+ assert result.is_error is False
+
+ async def test_legacy_elicitation_still_synchronous(self):
+ """On a legacy connection, a FastMCP server's `ctx.elicit` uses the
+ synchronous server-to-client request path (not MRTR), and the same
+ elicitation_handler answers it. This proves the handler table is shared."""
+ from fastmcp import Context
+ from fastmcp.server.elicitation import AcceptedElicitation
+
+ mcp = FastMCP("legacy-elicit")
+
+ @mcp.tool
+ async def ask(ctx: Context) -> str:
+ result = await ctx.elicit("your name", response_type=_Name)
+ assert isinstance(result, AcceptedElicitation)
+ data = cast(_Name, result.data)
+ return f"Hi {data.name}"
+
+ async def handler(message, response_type, params, ctx):
+ return ElicitResult(action="accept", content=response_type(name="Zoe"))
+
+ async with Client(mcp, mode="legacy", elicitation_handler=handler) as client:
+ result = await client.call_tool("ask", {})
+ assert result.data == "Hi Zoe"
diff --git a/tests/client/client/test_mode_negotiation.py b/tests/client/client/test_mode_negotiation.py
new file mode 100644
index 000000000..fc0b14f62
--- /dev/null
+++ b/tests/client/client/test_mode_negotiation.py
@@ -0,0 +1,150 @@
+"""Connect-time protocol-era negotiation on ``fastmcp.Client`` (``mode=``).
+
+FastMCP serves both protocol eras from one server object over the in-memory
+stream loop (``serve_dual_era_loop``), so a single ``fastmcp_server`` fixture can
+be driven legacy or modern by varying ``mode=`` alone:
+
+* ``mode="legacy"`` (the current default) runs the initialize handshake and
+ reports the handshake-era version, byte-identically to pre-v4 behavior.
+* ``mode="auto"`` probes ``server/discover`` and negotiates the modern era.
+* ``mode="2026-07-28"`` pins the modern version and adopts a synthesized
+ ``DiscoverResult`` without a probe.
+"""
+
+from __future__ import annotations
+
+import pytest
+from mcp_types.version import LATEST_HANDSHAKE_VERSION, LATEST_MODERN_VERSION
+
+from fastmcp import Client, FastMCP
+
+
+class TestModeValidation:
+ def test_default_mode_is_legacy(self, fastmcp_server):
+ """The conservative default is 'legacy' (see the v4 phasing note)."""
+ assert Client(fastmcp_server).mode == "legacy"
+
+ @pytest.mark.parametrize("mode", ["legacy", "auto", LATEST_MODERN_VERSION])
+ def test_valid_modes_accepted(self, fastmcp_server, mode):
+ assert Client(fastmcp_server, mode=mode).mode == mode
+
+ def test_handshake_version_pin_rejected(self, fastmcp_server):
+ """A legacy-era version string is not a valid pin; the error steers to 'legacy'."""
+ with pytest.raises(ValueError, match="use mode='legacy'"):
+ Client(fastmcp_server, mode=LATEST_HANDSHAKE_VERSION)
+
+ def test_unknown_mode_rejected(self, fastmcp_server):
+ with pytest.raises(ValueError, match="mode must be 'legacy', 'auto'"):
+ Client(fastmcp_server, mode="bogus")
+
+
+class TestLegacyMode:
+ async def test_legacy_uses_initialize_handshake(self, fastmcp_server):
+ async with Client(fastmcp_server, mode="legacy") as client:
+ assert client.protocol_version == LATEST_HANDSHAKE_VERSION
+ # Legacy negotiation still populates the InitializeResult unchanged.
+ assert client.initialize_result is not None
+ assert client.initialize_result.server_info.name == "TestServer"
+ assert client.server_capabilities is not None
+
+ async def test_default_matches_legacy(self, fastmcp_server):
+ """Omitting mode= is byte-identical to mode='legacy'."""
+ async with Client(fastmcp_server) as client:
+ assert client.protocol_version == LATEST_HANDSHAKE_VERSION
+ assert client.initialize_result is not None
+
+ async def test_legacy_call_tool(self, fastmcp_server):
+ async with Client(fastmcp_server, mode="legacy") as client:
+ result = await client.call_tool("add", {"a": 2, "b": 3})
+ assert result.data == 5
+
+
+class TestAutoMode:
+ async def test_auto_negotiates_modern_via_discover(self, fastmcp_server):
+ """auto probes server/discover and adopts the modern era in-memory."""
+ async with Client(fastmcp_server, mode="auto") as client:
+ assert client.protocol_version == LATEST_MODERN_VERSION
+ # A discover connection carries capabilities but no InitializeResult.
+ assert client.server_capabilities is not None
+ assert client.initialize_result is None
+
+ async def test_auto_call_tool(self, fastmcp_server):
+ async with Client(fastmcp_server, mode="auto") as client:
+ result = await client.call_tool("add", {"a": 4, "b": 5})
+ assert result.data == 9
+
+ async def test_auto_falls_back_to_legacy_for_handshake_only_server(self):
+ """A server that only speaks the handshake era makes auto denylist-fall-back to
+ initialize, which still populates the InitializeResult.
+
+ FastMCP always serves both eras, so this is characterized against the
+ real dual-era server: auto reaches modern here. The fallback denylist
+ itself is exercised by the SDK's own ``negotiate_auto`` suite; this cell
+ documents the FastMCP-observable outcome.
+ """
+ mcp = FastMCP("both-eras")
+
+ @mcp.tool
+ def ping() -> str:
+ return "pong"
+
+ async with Client(mcp, mode="auto") as client:
+ assert client.protocol_version == LATEST_MODERN_VERSION
+
+
+class TestPinnedMode:
+ async def test_pinned_modern_adopts_without_probe(self, fastmcp_server):
+ """Pinning the modern version adopts it directly; a synthesized
+ DiscoverResult leaves server_info empty."""
+ async with Client(fastmcp_server, mode=LATEST_MODERN_VERSION) as client:
+ assert client.protocol_version == LATEST_MODERN_VERSION
+ assert client.initialize_result is None
+
+ async def test_pinned_modern_call_tool(self, fastmcp_server):
+ async with Client(fastmcp_server, mode=LATEST_MODERN_VERSION) as client:
+ result = await client.call_tool("add", {"a": 7, "b": 8})
+ assert result.data == 15
+
+
+class TestConnectionProperties:
+ async def test_properties_none_before_connect(self, fastmcp_server):
+ client = Client(fastmcp_server, mode="auto")
+ assert client.protocol_version is None
+ assert client.server_capabilities is None
+
+ async def test_properties_none_after_disconnect(self, fastmcp_server):
+ client = Client(fastmcp_server, mode="auto")
+ async with client:
+ assert client.protocol_version is not None
+ assert client.protocol_version is None
+ assert client.server_capabilities is None
+
+
+class TestManualNegotiation:
+ async def test_manual_initialize_legacy(self, fastmcp_server):
+ """auto_initialize=False + a manual initialize() still works in legacy mode."""
+ client = Client(fastmcp_server, mode="legacy", auto_initialize=False)
+ async with client:
+ assert client.protocol_version is None
+ result = await client.initialize()
+ assert result.server_info.name == "TestServer"
+ assert client.protocol_version == LATEST_HANDSHAKE_VERSION
+
+ async def test_initialize_raises_on_modern_era(self, fastmcp_server):
+ """A modern connection has no InitializeResult, so initialize() raises with a
+ pointer to the era-neutral properties."""
+ client = Client(fastmcp_server, mode="auto", auto_initialize=False)
+ async with client:
+ with pytest.raises(RuntimeError, match="modern protocol era"):
+ await client.initialize()
+ # Negotiation still happened; the era-neutral surface is populated.
+ assert client.protocol_version == LATEST_MODERN_VERSION
+
+
+class TestNewPreservesMode:
+ async def test_new_preserves_mode(self, fastmcp_server):
+ parent = Client(fastmcp_server, mode="auto")
+ child = parent.new()
+ assert child.mode == "auto"
+ async with child:
+ assert child.protocol_version == LATEST_MODERN_VERSION
diff --git a/tests/client/client/test_response_cache.py b/tests/client/client/test_response_cache.py
new file mode 100644
index 000000000..40f583106
--- /dev/null
+++ b/tests/client/client/test_response_cache.py
@@ -0,0 +1,178 @@
+"""Client-side response caching (SEP-2549) on ``fastmcp.Client`` (``cache=``).
+
+At 2026-07-28 a server may mark a cacheable list result with a `ttlMs` freshness
+hint; a client built with `cache=` serves subsequent identical calls from an
+in-process store until the hint expires or a server notification evicts the entry.
+
+The 2026 emitter is the SDK's `MCPServer` with `cache_hints=`, which stamps a
+positive `ttlMs` onto `tools/list`. It is driven through a `fastmcp.Client` with
+`mode="auto"` (negotiating 2026-07-28), so the cache coordinator runs entirely
+through FastMCP's client.
+
+Cache *honoring of server hints* is modern-only: a FastMCP or SDK server that
+emits `ttlMs: 0` (no hint) is never cached, and legacy connections never read the
+hint. That gating lives in the SDK's `ClientResponseCache`.
+"""
+
+from __future__ import annotations
+
+import mcp_types
+import pytest
+from mcp.client.caching import CacheConfig
+from mcp.server.caching import CacheHint
+from mcp.server.mcpserver import MCPServer
+
+from fastmcp import Client, FastMCP
+
+
+def _cached_server(ttl_ms: int = 60000) -> MCPServer:
+ """An SDK MCPServer whose tools/list carries a positive ttlMs hint at 2026."""
+ server = MCPServer(
+ "cached", cache_hints={"tools/list": CacheHint(ttl_ms=ttl_ms, scope="public")}
+ )
+
+ @server.tool()
+ def add(a: int, b: int) -> int:
+ return a + b
+
+ return server
+
+
+class TestCacheConstruction:
+ def test_cache_none_is_disabled_by_default(self):
+ """Caching is opt-in: the default `cache=None` builds no cache, so a legacy
+ connection is byte-identical to pre-v4 behavior (no handler wrapping)."""
+ from fastmcp.client.tasks import TaskNotificationHandler
+
+ client = Client(FastMCP("x"))
+ assert client._response_cache is None
+ # The message handler is the bare default, not a cache-evicting wrapper.
+ assert isinstance(
+ client._session_kwargs["message_handler"], TaskNotificationHandler
+ )
+
+ def test_cache_true_builds_default(self):
+ client = Client(FastMCP("x"), cache=True)
+ assert client._response_cache is not None
+
+ def test_cache_false_disables(self):
+ client = Client(FastMCP("x"), cache=False)
+ assert client._response_cache is None
+
+ def test_cache_config_custom(self):
+ client = Client(FastMCP("x"), cache=CacheConfig(default_ttl_ms=1000))
+ assert client._response_cache is not None
+
+ def test_custom_store_requires_target_id(self):
+ """A custom shared store cannot derive an identity from a FastMCP transport."""
+ from mcp.client.caching import InMemoryResponseCacheStore
+
+ with pytest.raises(ValueError, match="requires CacheConfig.target_id"):
+ Client(
+ FastMCP("x"),
+ cache=CacheConfig(store=InMemoryResponseCacheStore(), partition="p"),
+ )
+
+
+class TestCacheServing:
+ async def test_second_list_tools_served_from_cache(self):
+ """A cached tools/list round-trip: the second call is served from the cache
+ without a second wire request."""
+ server = _cached_server()
+ async with Client(server, mode="auto", cache=True) as client:
+ # Confirm the server actually emits the freshness hint at 2026.
+ raw = await client.session.list_tools()
+ assert raw.ttl_ms == 60000
+
+ first = await client.list_tools()
+
+ calls = {"n": 0}
+ original = client.session.list_tools
+
+ async def spy(**kwargs):
+ calls["n"] += 1
+ return await original(**kwargs)
+
+ client.session.list_tools = spy # type: ignore[method-assign]
+ second = await client.list_tools()
+
+ assert calls["n"] == 0 # served from cache, no wire round-trip
+ assert [t.name for t in first] == [t.name for t in second] == ["add"]
+
+ async def test_bypass_skips_cache(self):
+ """`cache_mode="bypass"` always reaches the server."""
+ server = _cached_server()
+ async with Client(server, mode="auto", cache=True) as client:
+ await client.list_tools_mcp() # warm the cache
+
+ calls = {"n": 0}
+ original = client.session.list_tools
+
+ async def spy(**kwargs):
+ calls["n"] += 1
+ return await original(**kwargs)
+
+ client.session.list_tools = spy # type: ignore[method-assign]
+ await client.list_tools_mcp(cache_mode="bypass")
+
+ assert calls["n"] == 1
+
+
+class TestCacheEviction:
+ async def test_tool_list_changed_evicts(self):
+ """A `notifications/tools/list_changed` routed through the composed message
+ handler evicts the cached tools/list entry."""
+ server = _cached_server()
+ async with Client(server, mode="auto", cache=True) as client:
+ await client.list_tools()
+ cache = client._response_cache
+ assert cache is not None
+ assert await cache.read("tools/list", "") is not None
+
+ # Drive the notification through the installed (cache-evicting) handler,
+ # which composes eviction over FastMCP's own message handler chain.
+ handler = client._session_kwargs["message_handler"]
+ assert handler is not None
+ await handler(
+ mcp_types.ToolListChangedNotification(
+ method="notifications/tools/list_changed"
+ )
+ )
+
+ assert await cache.read("tools/list", "") is None
+
+
+class TestEraGating:
+ async def test_legacy_does_not_honor_server_hint(self):
+ """On a legacy connection the server hint is not read, so a hinted tools/list
+ is not served from cache (the entry is never stored under the hint)."""
+ server = _cached_server()
+ async with Client(server, mode="legacy", cache=True) as client:
+ await client.list_tools()
+ cache = client._response_cache
+ assert cache is not None
+ # No modern hint honored -> nothing cached under the modern arm.
+ assert await cache.read("tools/list", "") is None
+
+ async def test_zero_ttl_server_not_cached_on_modern(self):
+ """A modern server that emits `ttlMs: 0` (no hint) is not cached even though
+ the connection is modern."""
+ server = _cached_server(ttl_ms=0)
+ async with Client(server, mode="auto", cache=True) as client:
+ await client.list_tools()
+ cache = client._response_cache
+ assert cache is not None
+ assert await cache.read("tools/list", "") is None
+
+
+class TestNewIndependentCache:
+ async def test_new_gets_independent_cache(self):
+ """`new()` clones get their own cache, not the parent's entries."""
+ parent = Client(_cached_server(), mode="auto", cache=True)
+ child = parent.new()
+ assert child._response_cache is not None
+ assert child._response_cache is not parent._response_cache
+
+ async def test_new_disabled_cache_stays_disabled(self):
+ parent = Client(FastMCP("x"), cache=False)
+ assert parent.new()._response_cache is None