Skip to content

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

fix(server): serve Mcp-Param validation from a wire-schema cache (#5666)

akushonkamencb0a1387ad06
diff --git a/fastmcp_slim/fastmcp/server/low_level.py b/fastmcp_slim/fastmcp/server/low_level.py
index b0760741c..f27f07463 100644
--- a/fastmcp_slim/fastmcp/server/low_level.py
+++ b/fastmcp_slim/fastmcp/server/low_level.py
@@ -458,6 +458,25 @@ class LowLevelServer(_Server[LifespanResultT]):
# Store a weak reference to FastMCP to avoid circular references
self._fastmcp_ref: weakref.ref[FastMCP] = weakref.ref(fastmcp)
+ # The SDK validates Mcp-Param-* headers on `tools/call` against the
+ # called tool's input schema. Without this sync hook the SDK falls back
+ # to a full `tools/list` per call β€” running every FastMCP list
+ # middleware and provider enumeration on each tool invocation (#5652).
+ # FastMCP tool resolution is async, so the hook serves FastMCP's
+ # wire-schema cache (seeded at registration, refreshed on every
+ # `tools/list`) instead of resolving through providers here.
+ def _get_tool_input_schema(name: str) -> dict[str, Any] | None:
+ # A bound method would hold a strong reference back to the
+ # FastMCP instance and recreate the cycle the weakref above
+ # exists to avoid; resolve through the weakref instead and
+ # fail open (no validation) if the server is gone.
+ resolved = self._fastmcp_ref()
+ if resolved is None:
+ return None
+ return resolved._get_tool_input_schema(name)
+
+ self.get_tool_input_schema = _get_tool_input_schema
+
# FastMCP servers support notifications for all components. v2 derives
# capabilities from registered handlers + protocol_version, but legacy
# clients still read NotificationOptions at create_initialization_options
diff --git a/fastmcp_slim/fastmcp/server/mixins/mcp_operations.py b/fastmcp_slim/fastmcp/server/mixins/mcp_operations.py
index aad306575..fc6b43310 100644
--- a/fastmcp_slim/fastmcp/server/mixins/mcp_operations.py
+++ b/fastmcp_slim/fastmcp/server/mixins/mcp_operations.py
@@ -148,6 +148,24 @@ class MCPOperationsMixin:
list(await self.list_tools()), lambda t: t.name
)
sdk_tools = [tool.to_mcp_tool(name=tool.name) for tool in tools]
+ # Refresh the Mcp-Param schema cache (served to the SDK's
+ # `get_tool_input_schema` hook, mcp>=2.3) from the full visible
+ # set, pre-pagination: these are the authoritative wire schemas,
+ # including proxied and mounted tools. Merged in place with
+ # `update` (never `clear`) β€” the dict is shared with
+ # _SchemaCacheLocalProvider and single server-wide, so an
+ # auth-scoped listing of one client must not evict the schemas
+ # another (differently authorized) client validated against. The
+ # cache may therefore hold a superset of any one client's listing;
+ # a stale entry can only appear for tools removed remotely between
+ # listings, and a miss stays fail-open.
+ self._wire_input_schemas.update(
+ {
+ sdk_tool.name: sdk_tool.input_schema
+ for sdk_tool in sdk_tools
+ if sdk_tool.input_schema is not None
+ }
+ )
cursor = params.cursor if params else None
page, next_cursor = _apply_pagination(
sdk_tools, cursor, self._list_page_size
diff --git a/fastmcp_slim/fastmcp/server/server.py b/fastmcp_slim/fastmcp/server/server.py
index c08007314..569b72637 100644
--- a/fastmcp_slim/fastmcp/server/server.py
+++ b/fastmcp_slim/fastmcp/server/server.py
@@ -102,7 +102,11 @@ from fastmcp.server.transforms import (
ToolTransform,
Transform,
)
-from fastmcp.server.transforms.visibility import apply_session_transforms, is_enabled
+from fastmcp.server.transforms.visibility import (
+ Visibility,
+ apply_session_transforms,
+ is_enabled,
+)
from fastmcp.settings import DuplicateBehavior as DuplicateBehaviorSetting
from fastmcp.tools.base import Tool, ToolResult
from fastmcp.tools.function_tool import FunctionTool
@@ -308,6 +312,93 @@ def _lifespan_proxy(
return wrap
+class _SchemaCacheLocalProvider(LocalProvider):
+ """LocalProvider that mirrors registered tools into FastMCP's wire-schema
+ cache, so the SDK's `get_tool_input_schema` hook (Mcp-Param header
+ validation, mcp>=2.3) can resolve locally-registered tools before the first
+ `tools/list`. The cache dict is owned by the FastMCP server and shared by
+ reference; listings merge into it by value (`update`, never `clear`), so an
+ auth-scoped listing cannot drop another principal's cached schemas."""
+
+ def __init__(
+ self,
+ schema_cache: dict[str, dict[str, Any]],
+ server_transforms: list[Transform] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ super().__init__(**kwargs)
+ self._schema_cache = schema_cache
+ # The owning FastMCP's server-level transform list, shared by
+ # reference so transforms added after construction are visible.
+ self._server_transforms = (
+ server_transforms if server_transforms is not None else []
+ )
+
+ def _seed_schema(self, name: str, candidates: list[Tool]) -> None:
+ """Seed the wire-schema cache for `name` from the tool dispatch and
+ `tools/list` would actually serve: the highest version by the same
+ PEP 440-aware `version_sort_key` used by `_get_tool` and
+ `dedupe_with_versions`. When a transform is installed, the wire schema
+ is only computed on the listing path, so seeding is skipped entirely
+ (and any entry dropped): a miss fails open, a wrong entry (e.g. a
+ pre-transform schema) fails closed (#5666 review)."""
+ transforms = [
+ t
+ for t in (*self._server_transforms, *self._transforms)
+ if not isinstance(t, Visibility)
+ ]
+ if transforms:
+ self._schema_cache.pop(name, None)
+ return
+ latest = max(candidates, key=version_sort_key)
+ try:
+ schema = latest.to_mcp_tool(name=latest.name).input_schema
+ except Exception:
+ # Seeding must never break registration; a missing entry only
+ # means the tool is not header-validated until the next listing.
+ return
+ if isinstance(schema, dict):
+ self._schema_cache[name] = schema
+
+ def add_transform(self, transform: Transform) -> None:
+ super().add_transform(transform)
+ # Entries seeded before this transform are pre-transform schemas.
+ if not isinstance(transform, Visibility):
+ self._schema_cache.clear()
+
+ def add_tool(self, tool: Tool | Callable[..., Any]) -> Tool:
+ added = super().add_tool(tool)
+ # Seed from the version dispatch serves, not necessarily the one just
+ # added: registering an older version after a newer one must not
+ # replace the newer version's schema in the cache.
+ same_name = [
+ component
+ for component in self._components.values()
+ if isinstance(component, Tool) and component.name == added.name
+ ]
+ self._seed_schema(added.name, same_name or [added])
+ return added
+
+ def remove_tool(self, name: str, version: str | None = None) -> None:
+ super().remove_tool(name, version=version)
+ # Evict only when no version of the tool remains: a version-scoped
+ # removal can leave other versions live under the same logical name,
+ # in which case re-seed from the surviving tool instead. A stale schema
+ # would let Mcp-Param header validation reject calls for a tool that
+ # no longer exists (or no longer has this schema) until the next
+ # listing; a miss is fail-open, so dropping the entry is always the
+ # safe direction.
+ surviving = [
+ component
+ for component in self._components.values()
+ if isinstance(component, Tool) and component.name == name
+ ]
+ if not surviving:
+ self._schema_cache.pop(name, None)
+ return
+ self._seed_schema(name, surviving)
+
+
class StateValue(FastMCPBaseModel):
"""Wrapper for stored context state values."""
@@ -371,9 +462,19 @@ class FastMCP(
self._state_storage: AsyncKeyValue | None = session_state_store
self.__state_store: PydanticAdapter[StateValue] | None = None
+ # Wire-format input schemas, keyed by tool name. Shared by reference
+ # with _SchemaCacheLocalProvider (seeded on local tool registration)
+ # and served to the SDK's `get_tool_input_schema` hook (mcp>=2.3, see
+ # LowLevelServer) so Mcp-Param header validation on `tools/call` does
+ # not fall back to a full `tools/list` per call (#5652). Refreshed in
+ # place from every `tools/list` response.
+ self._wire_input_schemas: dict[str, dict[str, Any]] = {}
+
# Create LocalProvider for local components
- self._local_provider: LocalProvider = LocalProvider(
- on_duplicate=self._on_duplicate
+ self._local_provider: LocalProvider = _SchemaCacheLocalProvider(
+ schema_cache=self._wire_input_schemas,
+ server_transforms=self._transforms,
+ on_duplicate=self._on_duplicate,
)
for t in transforms or []:
@@ -823,6 +924,11 @@ class FastMCP(
```
"""
self._transforms.append(transform)
+ # Schemas seeded before this transform existed are pre-transform and
+ # would fail closed on Mcp-Param validation; drop them so the next
+ # `tools/list` (which applies the transform) repopulates the cache.
+ if not isinstance(transform, Visibility):
+ self._wire_input_schemas.clear()
async def list_tools(self, *, run_middleware: bool = True) -> Sequence[Tool]:
"""List all enabled tools from providers.
@@ -1855,6 +1961,27 @@ class FastMCP(
"""
return self._local_provider.add_tool(tool)
+ def _get_tool_input_schema(self, name: str) -> dict[str, Any] | None:
+ """Synchronous lookup served to the SDK's `get_tool_input_schema` hook
+ (Mcp-Param header validation on `tools/call`, mcp>=2.3).
+
+ Returns the tool's wire input schema from the cache seeded by local
+ tool registration and refreshed by every `tools/list` response. FastMCP
+ tool resolution is async (providers, middleware, proxies) and cannot
+ run inside this sync hook, so a cache miss returns None β€” which the SDK
+ treats as fail-open, skipping header validation for that call exactly
+ as it does when a `tools/list` listing fails.
+
+ A stale hit fails closed: listings merge into the cache without pruning,
+ and a mounted or proxied server's own registrations do not reach this
+ server's cache, so an entry for a mounted or proxied tool that was
+ removed or changed upstream keeps validating against the old schema
+ until the next `tools/list` on this server. The cache is keyed by name
+ and holds the highest version's schema, so version-pinned calls are
+ validated against that schema too.
+ """
+ return self._wire_input_schemas.get(name)
+
@overload
def tool(
self,
diff --git a/tests/server/test_mcp_param_schema_cache.py b/tests/server/test_mcp_param_schema_cache.py
new file mode 100644
index 000000000..b1364f8e6
--- /dev/null
+++ b/tests/server/test_mcp_param_schema_cache.py
@@ -0,0 +1,375 @@
+"""Wire-schema cache behind the SDK's `get_tool_input_schema` hook (mcp>=2.3).
+
+Every argument-bearing `tools/call` made the SDK fall back to running the
+server's full `tools/list` handler β€” all `on_list_tools` middleware, provider
+enumeration, and request logging β€” just to find one tool's input schema
+(#5652). FastMCP now serves the sync hook from a wire-schema cache: local tool
+registration seeds it, and every `tools/list` response refreshes it (which also
+covers proxied and mounted tools).
+"""
+
+import json
+from typing import Annotated
+
+from pydantic import Field
+from starlette.testclient import TestClient
+
+from fastmcp import Client, FastMCP
+from fastmcp.server.middleware import Middleware
+from fastmcp.server.transforms.tool_transform import ToolTransform
+from fastmcp.tools import Tool
+from fastmcp.tools.tool_transform import (
+ ArgTransform,
+ ArgTransformConfig,
+ ToolTransformConfig,
+)
+
+# A parameter carrying an Mcp-Param header annotation, as the SDK's
+# validate_mcp_param_headers reads it out of the wire input schema.
+HDR = Annotated[str, Field(json_schema_extra={"x-mcp-header": "Region"})]
+
+
+def _hook(server: FastMCP):
+ return server._mcp_server.get_tool_input_schema
+
+
+def test_hook_installed():
+ server = FastMCP("t")
+
+ assert callable(_hook(server))
+ # Unknown tools must not raise from the hook.
+ assert _hook(server)("no-such-tool") is None
+
+
+async def test_local_tool_available_before_any_listing():
+ server = FastMCP("t")
+
+ @server.tool
+ def echo(text: str) -> str:
+ return text
+
+ schema = _hook(server)("echo")
+
+ assert schema is not None
+ assert "text" in schema["properties"]
+
+
+async def test_transformed_schema_is_served():
+ server = FastMCP("t")
+
+ def add(old_x: int, old_y: int) -> int:
+ return old_x + old_y
+
+ base = Tool.from_function(add, name="add")
+ renamed = Tool.from_tool(
+ base,
+ transform_args={
+ "old_x": ArgTransform(name="x"),
+ "old_y": ArgTransform(name="y"),
+ },
+ )
+ server.add_tool(renamed)
+
+ schema = _hook(server)("add")
+
+ assert schema is not None
+ # The renamed (wire) parameters, not the original ones.
+ assert set(schema["properties"]) == {"x", "y"}
+
+
+async def test_listing_covers_mounted_tools():
+ nested = FastMCP("nested")
+
+ @nested.tool
+ def remote(x: int) -> int:
+ return x
+
+ server = FastMCP("main")
+ server.mount(nested, namespace="nested")
+
+ # Mounted tools resolve asynchronously, so they can only enter the cache
+ # through a listing.
+ assert _hook(server)("nested_remote") is None
+
+ async with Client(server) as client:
+ tools = await client.list_tools()
+
+ assert [tool.name for tool in tools] == ["nested_remote"]
+ schema = _hook(server)("nested_remote")
+ assert schema is not None
+ assert "x" in schema["properties"]
+
+
+async def test_listing_refresh_replaces_stale_entries():
+ server = FastMCP("t")
+
+ @server.tool
+ def keep(text: str) -> str:
+ return text
+
+ temp = Tool.from_function(lambda: "temp", name="temp")
+ server.add_tool(temp)
+ assert _hook(server)("temp") is not None
+
+ server._local_provider.remove_tool("temp")
+
+ # Removal evicts the cache entry immediately, not only after the next
+ # listing β€” a stale schema could otherwise keep header-validating a tool
+ # that no longer exists.
+ assert _hook(server)("temp") is None
+ assert _hook(server)("keep") is not None
+
+ async with Client(server) as client:
+ await client.list_tools()
+
+ # The removal evicted "temp" and the listing (which cannot see it anymore)
+ # merges without resurrecting it, so it stays out.
+ assert _hook(server)("temp") is None
+ assert _hook(server)("keep") is not None
+
+
+def test_tools_call_does_not_run_list_middleware():
+ listings = 0
+
+ class CountListings(Middleware):
+ async def on_list_tools(self, context, call_next):
+ nonlocal listings
+ listings += 1
+ return await call_next(context)
+
+ server = FastMCP("demo")
+ server.add_middleware(CountListings())
+
+ @server.tool
+ def echo(text: str) -> str:
+ return text
+
+ app = server.http_app(stateless_http=True)
+ with TestClient(app) as client:
+ response = client.post(
+ "/mcp",
+ json={
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "tools/call",
+ "params": {
+ "name": "echo",
+ "arguments": {"text": "hi"},
+ "_meta": {
+ "io.modelcontextprotocol/protocolVersion": "2026-07-28",
+ "io.modelcontextprotocol/clientCapabilities": {},
+ },
+ },
+ },
+ headers={
+ "Accept": "application/json, text/event-stream",
+ "MCP-Protocol-Version": "2026-07-28",
+ "Mcp-Method": "tools/call",
+ "Mcp-Name": "echo",
+ },
+ )
+ assert response.status_code == 200, response.text[:300]
+ assert "hi" in response.text
+
+ # The argument-bearing call must not have run the tools/list handler.
+ assert listings == 0
+
+
+async def test_auth_scoped_listing_does_not_evict_other_schemas():
+ """An auth-filtered `tools/list` must not clear other principals' schemas.
+
+ The cache is one shared server-wide dict: a listing visible to only one
+ client (here: middleware filtering the catalog) merges into it instead of
+ replacing it, so another client's already-cached schema keeps validating
+ Mcp-Param headers instead of silently fail-opening (#5666 review).
+ """
+
+ server = FastMCP("t")
+
+ @server.tool
+ def alpha(x: int) -> int:
+ return x
+
+ @server.tool
+ def beta(y: int) -> int:
+ return y
+
+ class OnlyBeta(Middleware):
+ async def on_list_tools(self, context, call_next):
+ return [tool for tool in await call_next(context) if tool.name == "beta"]
+
+ server.add_middleware(OnlyBeta())
+
+ async with Client(server) as client:
+ listed = await client.list_tools()
+
+ assert [tool.name for tool in listed] == ["beta"]
+ # The scoped listing serves beta but must not evict alpha's schema.
+ assert _hook(server)("beta") is not None
+ assert _hook(server)("alpha") is not None
+ assert "x" in _hook(server)("alpha")["properties"]
+
+
+async def test_version_scoped_removal_keeps_surviving_version():
+ """Evicting on remove_tool must not go further than the removed version."""
+
+ server = FastMCP("t")
+ server.add_tool(Tool.from_function(lambda: "v1", name="dup", version="1.0"))
+ server.add_tool(Tool.from_function(lambda: "v2", name="dup", version="2.0"))
+
+ schema = _hook(server)("dup")
+ assert schema is not None
+
+ # Removing one version re-seeds the cache from the surviving version
+ # instead of evacuating the logical name.
+ server._local_provider.remove_tool("dup", version="2.0")
+ schema = _hook(server)("dup")
+ assert schema is not None
+
+ # Removing the last version evicts the entry entirely.
+ server._local_provider.remove_tool("dup", version="1.0")
+ assert _hook(server)("dup") is None
+
+
+async def test_seed_serves_highest_version_not_last_registered():
+ """Regression (#5666 review repro 1): registering an older version after
+ a newer one must not seed the older version's schema. Dispatch serves the
+ highest version, so the cache must hold that version's schema β€” a cached
+ `x-mcp-header` annotation from the wrong version fails closed (HTTP 400)
+ on calls main accepts."""
+
+ def v2(region: str) -> str:
+ return f"v2:{region}"
+
+ def v1(region: HDR) -> str:
+ return f"v1:{region}"
+
+ server = FastMCP("t")
+ server.add_tool(Tool.from_function(v2, name="t", version="2.0"))
+ server.add_tool(Tool.from_function(v1, name="t", version="1.0"))
+
+ schema = _hook(server)("t")
+
+ # v2 (the highest version, and the one dispatch runs) has no header
+ # annotation; seeding v1's schema would demand Mcp-Param-Region.
+ assert schema is not None
+ assert "x-mcp-header" not in json.dumps(schema)
+
+
+async def test_reseed_after_removal_sorts_versions_semantically():
+ """Regression (#5666 review repro 2): re-seeding after a version-scoped
+ removal must pick the surviving version the way dispatch does (PEP 440),
+ not lexicographic string order where "9" > "10"."""
+
+ def v9(region: HDR) -> str:
+ return f"v9:{region}"
+
+ def v10(region: str) -> str:
+ return f"v10:{region}"
+
+ def v11(region: str) -> str:
+ return f"v11:{region}"
+
+ server = FastMCP("t")
+ server.add_tool(Tool.from_function(v9, name="t", version="9"))
+ server.add_tool(Tool.from_function(v10, name="t", version="10"))
+ server.add_tool(Tool.from_function(v11, name="t", version="11"))
+
+ # Removing the highest version re-seeds from v10 (plain), not v9 (which
+ # carries the header annotation and would fail closed).
+ server._local_provider.remove_tool("t", version="11")
+
+ schema = _hook(server)("t")
+
+ assert schema is not None
+ assert "x-mcp-header" not in json.dumps(schema)
+
+
+async def test_seed_skipped_when_server_transform_rewrites_schema():
+ """Regression (#5666 review repro 3): with a server-level ToolTransform
+ renaming arguments, the pre-transform schema must not be seeded. The
+ cache entry is dropped instead; the next tools/list (which applies the
+ transform) is the only writer, and until then a miss fails open."""
+
+ def f(region: HDR) -> str:
+ return f"region:{region}"
+
+ server = FastMCP(
+ "t",
+ transforms=[
+ ToolTransform(
+ {
+ "t": ToolTransformConfig(
+ arguments={"region": ArgTransformConfig(name="area")}
+ )
+ }
+ )
+ ],
+ )
+ server.add_tool(Tool.from_function(f, name="t"))
+
+ # No seeded entry: the transform-aware wire schema is only known after a
+ # listing. A stale pre-transform entry would reject calls carrying
+ # Mcp-Param-Region even though the wire argument is now "area".
+ assert _hook(server)("t") is None
+
+ async with Client(server) as client:
+ tools = await client.list_tools()
+
+ assert [tool.name for tool in tools] == ["t"]
+ schema = _hook(server)("t")
+ assert schema is not None
+ assert set(schema["properties"]) == {"area"}
+
+
+async def test_add_transform_drops_schemas_seeded_before_it():
+ """A decorator tool seeds its pre-transform schema; a transform added
+ afterwards renames the annotated argument. The seeded entry must be
+ dropped so calls carrying the header are not rejected against a schema
+ the tool no longer has."""
+ server = FastMCP("t")
+
+ @server.tool
+ def t(region: HDR) -> str:
+ return f"region:{region}"
+
+ assert _hook(server)("t") is not None
+
+ server.add_transform(
+ ToolTransform(
+ {
+ "t": ToolTransformConfig(
+ arguments={"region": ArgTransformConfig(name="area")}
+ )
+ }
+ )
+ )
+
+ assert _hook(server)("t") is None
+
+ async with Client(server) as client:
+ await client.list_tools()
+
+ schema = _hook(server)("t")
+ assert schema is not None
+ assert set(schema["properties"]) == {"area"}
+
+
+async def test_provider_add_transform_drops_seeded_schemas():
+ server = FastMCP("t")
+
+ @server.tool
+ def t(region: HDR) -> str:
+ return f"region:{region}"
+
+ server._local_provider.add_transform(
+ ToolTransform(
+ {
+ "t": ToolTransformConfig(
+ arguments={"region": ArgTransformConfig(name="area")}
+ )
+ }
+ )
+ )
+
+ assert _hook(server)("t") is None