"""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