Skip to content

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

fix(client): stop validating version-pinned call_tool results against the highest version's schema (#5725)

一片一片c2718fdb9824
diff --git a/fastmcp_slim/fastmcp/client/_version_pin.py b/fastmcp_slim/fastmcp/client/_version_pin.py
new file mode 100644
index 000000000..569c7f0ec
--- /dev/null
+++ b/fastmcp_slim/fastmcp/client/_version_pin.py
@@ -0,0 +1,30 @@
+"""Marks the tool call currently in flight as version-pinned.
+
+A version-pinned call executes a specific version on the server, but the
+session's output-schema cache is keyed by tool name and holds only the schema
+of the version ``tools/list`` advertised (``list_tools`` deduplicates by
+identifier and lists the highest version). When the pinned version is a
+different one, its schema is not advertised on the wire, so result
+revalidation has no correct schema to use for that call, and only for that
+call.
+
+The marker holds the session that made the call rather than a bare flag: with
+an in-memory transport the server handler runs in the caller's context, so a
+bare flag would also exempt an unrelated ``Client`` call made from inside that
+handler.
+"""
+
+from contextvars import ContextVar
+from typing import NamedTuple
+
+
+class PinnedCall(NamedTuple):
+ """The session that made a pinned tool call, and the version it pinned."""
+
+ session: object
+ version: str
+
+
+pinned_call: ContextVar[PinnedCall | None] = ContextVar(
+ "fastmcp_pinned_call", default=None
+)
diff --git a/fastmcp_slim/fastmcp/client/mixins/tools.py b/fastmcp_slim/fastmcp/client/mixins/tools.py
index d0548ed01..e0c657c85 100644
--- a/fastmcp_slim/fastmcp/client/mixins/tools.py
+++ b/fastmcp_slim/fastmcp/client/mixins/tools.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, cast
import mcp_types
@@ -12,6 +13,7 @@ if TYPE_CHECKING:
import datetime
from fastmcp.client.client import CallToolResult, Client
+from fastmcp.client._version_pin import PinnedCall, pinned_call
from fastmcp.client.progress import ProgressHandler
from fastmcp.client.telemetry import client_span
from fastmcp.exceptions import ToolError
@@ -220,23 +222,41 @@ class ClientToolsMixin:
allow_claimed=has_claims,
)
- first = await self._await_with_session_monitoring(_retry(None, None))
- driven = await self._await_with_session_monitoring(
- self._drive_input_required(first, _retry)
+ # A pinned call runs a specific version on the server, but the
+ # session's output-schema cache only holds the listed version's
+ # schema. Mark the call for the duration of the request so the
+ # session can skip revalidation when the pinned version is a
+ # different one; nothing else is affected. (#5721)
+ fastmcp_meta = (meta or {}).get("fastmcp")
+ pinned_version = (
+ fastmcp_meta.get("version") if isinstance(fastmcp_meta, dict) else None
)
- if isinstance(driven, mcp_types.CallToolResult):
- result = driven
- else:
- # A claimed extension result (SEP-2133): resolve it through the
- # owning extension's resolver into an ordinary CallToolResult.
- # Resolution issues further session requests of its own (result
- # validation lists tools; a resolver may make more), so it needs
- # the same session monitoring as the calls above β€” otherwise a
- # transport-level failure can kill the session runner while this
- # await waits forever.
- result = await self._await_with_session_monitoring(
- self._resolve_claimed_result(name, driven, read_timeout_seconds)
+ pin_token = (
+ pinned_call.set(PinnedCall(self.session, str(pinned_version)))
+ if pinned_version is not None
+ else None
+ )
+ try:
+ first = await self._await_with_session_monitoring(_retry(None, None))
+ driven = await self._await_with_session_monitoring(
+ self._drive_input_required(first, _retry)
)
+ if isinstance(driven, mcp_types.CallToolResult):
+ result = driven
+ else:
+ # A claimed extension result (SEP-2133): resolve it through the
+ # owning extension's resolver into an ordinary CallToolResult.
+ # Resolution issues further session requests of its own (result
+ # validation lists tools; a resolver may make more), so it needs
+ # the same session monitoring as the calls above β€” otherwise a
+ # transport-level failure can kill the session runner while this
+ # await waits forever.
+ result = await self._await_with_session_monitoring(
+ self._resolve_claimed_result(name, driven, read_timeout_seconds)
+ )
+ finally:
+ if pin_token is not None:
+ pinned_call.reset(pin_token)
# Reflect tool-level errors on the span so callers see ERROR
# status even though the MCP protocol call itself succeeded.
@@ -256,6 +276,7 @@ class ClientToolsMixin:
name: str,
result: mcp_types.CallToolResult,
raise_on_error: bool = False,
+ pinned_version: str | None = None,
) -> CallToolResult:
"""Parse an mcp_types.CallToolResult into our CallToolResult dataclass.
@@ -263,6 +284,9 @@ class ClientToolsMixin:
name: Tool name (for schema lookup)
result: Raw MCP protocol result
raise_on_error: Whether to raise ToolError on errors
+ pinned_version: The tool version the call requested, if any. A
+ result pinned to a version other than the listed one is not
+ coerced through the cached schema; see the module-level parser.
Returns:
CallToolResult: Parsed result with structured data
@@ -277,6 +301,8 @@ class ClientToolsMixin:
list_tools_fn=self.list_tools,
client_name=self.name,
raise_on_error=raise_on_error,
+ pinned_version=pinned_version,
+ listed_versions=getattr(self.session, "_tool_listed_versions", None),
)
async def call_tool(
@@ -335,7 +361,10 @@ class ClientToolsMixin:
meta=request_meta or None,
)
return await self._parse_call_tool_result(
- name, result, raise_on_error=raise_on_error
+ name,
+ result,
+ raise_on_error=raise_on_error,
+ pinned_version=version,
)
@@ -371,6 +400,8 @@ async def _parse_call_tool_result(
list_tools_fn: Any, # Callable[[], Awaitable[None]]
client_name: str | None = None,
raise_on_error: bool = False,
+ pinned_version: str | None = None,
+ listed_versions: Mapping[str, str | None] | None = None,
) -> CallToolResult:
"""Parse an mcp_types.CallToolResult into our CallToolResult dataclass.
@@ -381,6 +412,11 @@ async def _parse_call_tool_result(
list_tools_fn: Async function to refresh tool schemas if needed
client_name: Optional client name for logging
raise_on_error: Whether to raise ToolError on errors
+ pinned_version: The tool version the call requested, if any.
+ listed_versions: The version each listed tool advertises, keyed by name.
+ The cached schema describes that version only, so a result pinned
+ to any other version (or when the listed version is unknown) is
+ hydrated from ``structured_content`` as it arrived instead.
Returns:
CallToolResult: Parsed result with structured data
@@ -412,20 +448,26 @@ async def _parse_call_tool_result(
if name not in tool_output_schemas:
await list_tools_fn()
- if wrap_from_meta:
- # Meta tells us the result is wrapped β€” unwrap and validate.
- structured_content = result.structured_content.get("result")
- elif name in tool_output_schemas:
+ # The cached schema describes the listed version only. A call
+ # pinned to another version has no advertised schema, so coercing
+ # through the cached one would reject content that is valid for
+ # the version that ran; only the result meta's wrap flag applies.
+ if pinned_version is None or (
+ listed_versions is not None
+ and listed_versions.get(name) == pinned_version
+ ):
output_schema = tool_output_schemas.get(name)
- if output_schema and output_schema.get("x-fastmcp-wrap-result"):
- structured_content = result.structured_content.get("result")
- else:
- structured_content = result.structured_content
+ else:
+ output_schema = None
+
+ if wrap_from_meta or (
+ output_schema and output_schema.get("x-fastmcp-wrap-result")
+ ):
+ structured_content = result.structured_content.get("result")
else:
structured_content = result.structured_content
# Type-validate through the schema if available.
- output_schema = tool_output_schemas.get(name)
if output_schema:
if wrap_from_meta or output_schema.get("x-fastmcp-wrap-result"):
output_schema = _wrapped_result_schema(output_schema)
diff --git a/fastmcp_slim/fastmcp/client/transports/base.py b/fastmcp_slim/fastmcp/client/transports/base.py
index 4324eda8e..057d38785 100644
--- a/fastmcp_slim/fastmcp/client/transports/base.py
+++ b/fastmcp_slim/fastmcp/client/transports/base.py
@@ -18,6 +18,8 @@ from mcp.client.session import (
from mcp.shared._httpx_utils import McpHttpClientFactory
from typing_extensions import TypedDict, Unpack
+from fastmcp.client._version_pin import pinned_call
+
# TypeVar for preserving specific ClientTransport subclass types
ClientTransportT = TypeVar("ClientTransportT", bound="ClientTransport")
@@ -65,6 +67,53 @@ class ClientSessionKwargs(TypedDict, total=False):
result_claims: Mapping[str, Sequence[ResultClaim[Any]]] | None
+class VersionAwareClientSession(ClientSession):
+ """A session that skips output-schema revalidation for mismatched pinned calls.
+
+ ``ClientSession.call_tool`` revalidates a tool's structured content against
+ the output schema the server advertised, looked up by tool *name*. That
+ cache holds only the listed (highest) version's schema, so a call pinned to
+ a different version -- which the server executes as the requested version
+ -- would be checked against a schema that does not describe its result.
+
+ The session records the version each listed tool advertises in
+ ``_meta.fastmcp.version``. A pinned call to that version validates as
+ usual; a pinned call to any other version skips the check, since its schema
+ is not obtainable over the wire. Every unpinned call validates as before.
+ """
+
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ super().__init__(*args, **kwargs)
+ self._tool_listed_versions: dict[str, str | None] = {}
+
+ def _absorb_tool_listing(
+ self, result: mcp_types.ListToolsResult, *, complete: bool
+ ) -> mcp_types.ListToolsResult:
+ result = super()._absorb_tool_listing(result, complete=complete)
+ if complete:
+ self._tool_listed_versions = {}
+ for tool in result.tools:
+ fastmcp_meta = (tool.meta or {}).get("fastmcp")
+ version = (
+ fastmcp_meta.get("version") if isinstance(fastmcp_meta, dict) else None
+ )
+ self._tool_listed_versions[tool.name] = (
+ str(version) if version is not None else None
+ )
+ return result
+
+ async def validate_tool_result(
+ self, name: str, result: mcp_types.CallToolResult
+ ) -> None:
+ pin = pinned_call.get()
+ if pin is not None and pin.session is self:
+ if name not in self._tool_output_schemas:
+ await self.list_tools()
+ if self._tool_listed_versions.get(name) != pin.version:
+ return
+ await super().validate_tool_result(name, result)
+
+
@dataclass(frozen=True)
class TransportOptions:
"""How one client wants its connection built.
@@ -75,9 +124,12 @@ class TransportOptions:
settings must preserve the existing options rather than replace the bundle.
Attributes:
- session_class: The ClientSession class to instantiate. Proxies supply a
- session that skips output-schema validation, since they relay
- results rather than consume them.
+ session_class: The ClientSession class to instantiate. The default
+ skips output-schema validation for a tool call pinned to a version
+ other than the listed one, whose result no advertised schema
+ describes; proxies additionally
+ supply a session that skips it for every result, since they relay
+ rather than consume them.
forward_incoming_headers: Whether to forward eligible inbound HTTP
headers upstream, including authorization. Hop-specific HTTP headers
and MCP transport, routing, and event-stream state are excluded
@@ -94,7 +146,7 @@ class TransportOptions:
client's own session and era.
"""
- session_class: type[ClientSession] = ClientSession
+ session_class: type[ClientSession] = VersionAwareClientSession
forward_incoming_headers: bool = False
backend_mode: str | None = None
diff --git a/fastmcp_tasks/fastmcp_tasks/client.py b/fastmcp_tasks/fastmcp_tasks/client.py
index 64d182309..9937528ff 100644
--- a/fastmcp_tasks/fastmcp_tasks/client.py
+++ b/fastmcp_tasks/fastmcp_tasks/client.py
@@ -405,11 +405,13 @@ class ToolTask:
create_result: ClientCreateTaskResult,
*,
raise_on_error: bool = True,
+ pinned_version: str | None = None,
) -> None:
self._client = client
self._tool_name = tool_name
self._create_result = create_result
self._raise_on_error = raise_on_error
+ self._pinned_version = pinned_version
self._cached_result: FastMCPCallToolResult | None = None
@property
@@ -504,7 +506,10 @@ class ToolTask:
)
parsed = await self._client._parse_call_tool_result(
- self._tool_name, mcp_result, raise_on_error=self._raise_on_error
+ self._tool_name,
+ mcp_result,
+ raise_on_error=self._raise_on_error,
+ pinned_version=self._pinned_version,
)
self._cached_result = parsed
return parsed
@@ -559,7 +564,13 @@ async def call_tool_task(
)
)
if isinstance(raw, ClientCreateTaskResult):
- return ToolTask(client, name, raw, raise_on_error=raise_on_error)
+ return ToolTask(
+ client,
+ name,
+ raw,
+ raise_on_error=raise_on_error,
+ pinned_version=version,
+ )
raise ToolError(
f"Tool {name!r} did not run as a task: the server returned a "
f"{type(raw).__name__} instead of a task. Ensure the tool is declared "
diff --git a/tests/client/client/test_session.py b/tests/client/client/test_session.py
index 1ff7f3390..4a8d1ed67 100644
--- a/tests/client/client/test_session.py
+++ b/tests/client/client/test_session.py
@@ -18,7 +18,10 @@ from fastmcp.client.transports import (
FastMCPTransport,
PythonStdioTransport,
)
-from fastmcp.client.transports.base import TransportOptions
+from fastmcp.client.transports.base import (
+ TransportOptions,
+ VersionAwareClientSession,
+)
class _FailingTransport(ClientTransport):
@@ -326,7 +329,7 @@ class TestCustomSessionClass:
assert built == ["yes"]
- async def test_default_session_class_is_client_session(self):
+ async def test_default_session_class_is_version_aware(self):
server = FastMCP("Server")
@server.tool
@@ -334,7 +337,7 @@ class TestCustomSessionClass:
return "pong"
client = Client(server)
- assert TransportOptions().session_class is ClientSession
+ assert TransportOptions().session_class is VersionAwareClientSession
async with client:
result = await client.call_tool("ping")
diff --git a/tests/client/test_versioned_call_tool_validation.py b/tests/client/test_versioned_call_tool_validation.py
new file mode 100644
index 000000000..cfd58d7ee
--- /dev/null
+++ b/tests/client/test_versioned_call_tool_validation.py
@@ -0,0 +1,203 @@
+"""Result validation for tool calls that pin a version.
+
+`Client.call_tool(name, version=...)` executes that exact version on the
+server. The session's output-schema cache is keyed by tool name and holds only
+the highest version's schema (`list_tools` deduplicates by identifier), so the
+pinned result cannot be checked against it: the client has no schema for the
+version that actually ran.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import datetime
+from dataclasses import dataclass
+
+import pytest
+
+from fastmcp import Client, FastMCP
+
+
+def versioned_server() -> FastMCP:
+ server = FastMCP("versioned")
+
+ @server.tool(name="same", version="1.0")
+ def same_v1() -> int:
+ return 7
+
+ @server.tool(name="same", version="2.0")
+ def same_v2() -> int:
+ return 8
+
+ @server.tool(name="value", version="1.0")
+ def value_v1() -> int:
+ return 7
+
+ @server.tool(name="value", version="2.0")
+ def value_v2() -> str:
+ return "hello"
+
+ @server.tool(name="shape", version="1.0")
+ def shape_v1() -> int:
+ return 7
+
+ @server.tool(name="shape", version="2.0")
+ def shape_v2() -> dict:
+ return {"a": 1}
+
+ return server
+
+
+async def test_pinned_call_returns_its_own_version_result(
+ versioned_server: FastMCP,
+) -> None:
+ """A pinned call is not validated against the highest version's schema."""
+ async with Client(versioned_server) as client:
+ result = await client.call_tool("value", version="1.0")
+
+ assert result.data == 7
+
+
+async def test_pinned_call_hydrates_when_versions_differ_in_shape(
+ versioned_server: FastMCP,
+) -> None:
+ """The highest version's schema does not accept this version's content."""
+ async with Client(versioned_server) as client:
+ result = await client.call_tool("shape", version="1.0")
+
+ assert result.data == 7
+
+
+async def test_pinned_call_with_matching_schemas_is_unchanged(
+ versioned_server: FastMCP,
+) -> None:
+ async with Client(versioned_server) as client:
+ pinned = await client.call_tool("same", version="1.0")
+ highest = await client.call_tool("same")
+
+ assert pinned.data == 7
+ assert highest.data == 8
+
+
+@dataclass
+class Point:
+ x: int
+ y: int
+
+
+async def test_pinned_call_to_the_listed_version_still_hydrates() -> None:
+ """Pinning the version the cached schema describes keeps type coercion."""
+ server = FastMCP("single")
+
+ @server.tool(name="when", version="1.0")
+ def when() -> datetime.datetime:
+ return datetime.datetime(2024, 1, 2, 3, 4, 5)
+
+ @server.tool(name="point", version="1.0")
+ def point() -> Point:
+ return Point(x=1, y=2)
+
+ async with Client(server) as client:
+ pinned_when = await client.call_tool("when", version="1.0")
+ pinned_point = await client.call_tool("point", version="1.0")
+
+ assert pinned_when.data == datetime.datetime(2024, 1, 2, 3, 4, 5)
+ assert pinned_point.data.x == 1
+ assert pinned_point.data.y == 2
+ assert not isinstance(pinned_point.data, dict)
+
+
+async def test_pinned_call_to_the_listed_version_still_validates() -> None:
+ """Pinning the listed version keeps the SDK's result revalidation."""
+ server = FastMCP("liar")
+
+ @server.tool(name="liar", version="1.0")
+ def liar() -> int:
+ """Declares int, returns a string."""
+ return "oops" # type: ignore[return-value] # ty:ignore[invalid-return-type]
+
+ async with Client(server) as client:
+ with pytest.raises(RuntimeError, match="Invalid structured content"):
+ await client.call_tool("liar", version="1.0")
+
+
+async def test_unpinned_call_still_validates_a_non_conforming_result() -> None:
+ """Pinning a version must not turn result validation off in general."""
+ server = FastMCP("liar")
+
+ @server.tool
+ def liar() -> int:
+ """Declares int, returns a string."""
+ return "oops" # type: ignore[return-value] # ty:ignore[invalid-return-type]
+
+ async with Client(server) as client:
+ with pytest.raises(RuntimeError, match="Invalid structured content"):
+ await client.call_tool("liar")
+
+
+async def test_concurrent_pinned_calls_leave_the_schema_cache_intact(
+ versioned_server: FastMCP,
+) -> None:
+ """Pinning is per call: concurrent calls must not disturb the shared cache.
+
+ A pinned call is a property of one request, so it must not be expressed by
+ clearing the session-wide schema entry: two pinned calls in flight would
+ then restore each other's placeholder, and every later unpinned call would
+ skip validation for the rest of the session.
+ """
+ async with Client(versioned_server) as client:
+ await client.list_tools()
+ before = client.session._tool_output_schemas.get("value")
+ assert before is not None
+
+ await asyncio.gather(
+ client.call_tool("value", version="1.0"),
+ client.call_tool("value", version="1.0"),
+ )
+
+ assert client.session._tool_output_schemas.get("value") == before
+
+ # And the cache is still consulted for an ordinary call.
+ result = await client.call_tool("value")
+ assert result.data == "hello"
+
+
+async def test_pinned_call_does_not_exempt_a_nested_client_call() -> None:
+ """The marker is scoped to the session that made the pinned call.
+
+ With the in-memory transport the server handler runs in the caller's
+ context, so a process-wide flag would also exempt an unrelated ``Client``
+ call made from inside that handler. Those still validate.
+ """
+ inner = FastMCP("inner")
+
+ @inner.tool
+ def liar() -> int:
+ """Declares int, returns a string."""
+ return "oops" # type: ignore[return-value] # ty:ignore[invalid-return-type]
+
+ validated: list[bool] = []
+
+ outer = FastMCP("outer")
+
+ @outer.tool(name="probe", version="1.0")
+ async def probe_v1() -> int:
+ async with Client(inner) as nested:
+ try:
+ await nested.call_tool("liar")
+ except RuntimeError:
+ validated.append(True)
+ else:
+ validated.append(False)
+ return 1
+
+ @outer.tool(name="probe", version="2.0")
+ def probe_v2() -> int:
+ return 2
+
+ async with Client(outer) as client:
+ result = await client.call_tool("probe", version="1.0")
+
+ assert result.data == 1
+ assert validated == [True]
diff --git a/tests/tasks/client/test_client_tool_tasks.py b/tests/tasks/client/test_client_tool_tasks.py
index f809b34d0..2a1c5fac9 100644
--- a/tests/tasks/client/test_client_tool_tasks.py
+++ b/tests/tasks/client/test_client_tool_tasks.py
@@ -150,3 +150,27 @@ async def test_required_mode_without_optin_raises_32021():
await client.call_tool("must_task", {"x": 1})
assert excinfo.value.error.code == MISSING_REQUIRED_CLIENT_CAPABILITY
+
+
+async def test_task_handle_carries_the_pinned_call_flag() -> None:
+ """A tasked pinned call keeps its version through the handle.
+
+ `call_tool_task` returns before the result exists, so the flag cannot ride
+ on the request context; the handle carries it to `result()` instead.
+ """
+ mcp = FastMCP("versioned-tasks")
+ mcp.add_extension(TasksExtension())
+
+ @mcp.tool(name="value", version="1.0", task=True)
+ async def value_v1() -> int:
+ return 7
+
+ @mcp.tool(name="value", version="2.0", task=True)
+ async def value_v2() -> str:
+ return "hello"
+
+ async with Client(mcp, mode="auto") as client:
+ task = await call_tool_task(client, "value", version="1.0")
+ result = await task.result()
+
+ assert result.data == 7