Skip to content

The agent that grows with you

review-fix(mcp): preserve MCP SDK 2 input schemas in the schema-cache write-through (salvaged from #91451 / #102129)

Teknium0c62b297c68b
diff --git a/tests/tools/test_mcp_schema_cache.py b/tests/tools/test_mcp_schema_cache.py
index ebfd4bea751..527b7b30b1f 100644
--- a/tests/tools/test_mcp_schema_cache.py
+++ b/tests/tools/test_mcp_schema_cache.py
@@ -102,3 +102,88 @@ class TestWriteSkip:
# Changed payload → rewrite.
msc.write_cache_entry("srv", "fp2", tools=tools, utility_tools=[])
assert len(saves) == 2
+
+
+class TestWriteThroughPreservesSchema:
+ """Regression: the write-through path must persist real tool parameters.
+
+ ``mcp`` 2.0 renamed ``Tool.inputSchema`` to ``input_schema``, keeping the
+ camelCase spelling only as a *serialization* alias — pydantic aliases do
+ not apply to attribute access, so ``getattr(tool, "inputSchema")`` returns
+ None on 2.x instead of raising. The cache-write path used exactly that
+ bare read, so every entry landed on disk with ``"inputSchema": {}``. A
+ server later registered from that cache (``lazy: true``) was advertised to
+ the model with every parameter stripped, which makes required-argument
+ tools such as zhihu's ``zhida`` (``query`` + ``model`` both required)
+ uncallable.
+
+ These tests drive the live ``_register_server_tools`` write-through with a
+ genuine SDK ``Tool`` so the field-rename is actually exercised — the mock
+ fixtures elsewhere build ``SimpleNamespace`` objects and cannot catch it.
+ (Salvaged from #91451 / #102129.)
+ """
+
+ _SCHEMA = {
+ "type": "object",
+ "properties": {
+ "query": {"type": "string"},
+ "model": {"type": "string"},
+ },
+ "required": ["query", "model"],
+ }
+
+ def _cache_write_through(self, tmp_path, monkeypatch):
+ import json
+ from unittest.mock import MagicMock, patch
+
+ from mcp.types import Tool
+
+ import tools.mcp_tool as mt
+ from tools.registry import ToolRegistry
+
+ monkeypatch.setattr(msc, "_cache_path", lambda: tmp_path / "cache.json")
+ # Registration records per-server state in module globals (lazy tool names, trust
+ # levels, read-only hints...); isolate them so the probe server never leaks into
+ # later tests such as ``discover_mcp_tools() == []`` assertions.
+ for attr in ("_lazy_server_tool_names", "_lazy_server_configs", "_lazy_server_fingerprints",
+ "_mcp_tool_server_names", "_server_trust_levels", "_tool_read_only_hints"):
+ monkeypatch.setattr(mt, attr, {})
+ server = mt.MCPServerTask("probe_srv")
+ server._tools = [
+ Tool(name="zhida", description="知乎直答", inputSchema=self._SCHEMA)
+ ]
+ server.session = MagicMock()
+
+ with patch("tools.registry.registry", ToolRegistry()):
+ registered = mt._register_server_tools("probe_srv", server, {})
+ assert registered, "tool was not registered; write-through never fired"
+ entry = json.loads((tmp_path / "cache.json").read_text(encoding="utf-8"))["probe_srv"]
+ return entry
+
+ def test_cached_schema_keeps_properties(self, tmp_path, monkeypatch):
+ cached = self._cache_write_through(tmp_path, monkeypatch)["tools"][0]["inputSchema"]
+ assert set(cached.get("properties", {})) == {"query", "model"}, (
+ "write-through persisted an empty schema — the SDK field rename "
+ "was read with a bare camelCase getattr"
+ )
+
+ def test_cached_schema_keeps_required(self, tmp_path, monkeypatch):
+ cached = self._cache_write_through(tmp_path, monkeypatch)["tools"][0]["inputSchema"]
+ assert cached.get("required") == ["query", "model"]
+
+ def test_cache_round_trip_reaches_agent_schema(self, tmp_path, monkeypatch):
+ """The whole point of the cache: a lazy server re-advertises params."""
+ from unittest.mock import patch
+
+ import tools.mcp_tool as mt
+ from tools.registry import ToolRegistry
+
+ entry = self._cache_write_through(tmp_path, monkeypatch)
+ lazy_reg = ToolRegistry()
+ with patch("tools.registry.registry", lazy_reg):
+ names = mt._register_from_cache_sync("probe_srv", {}, entry)
+ assert names, "lazy registration produced no tools"
+ schema = lazy_reg.get_schema("mcp__probe_srv__zhida")
+ assert schema is not None, "lazy path did not register the tool"
+ assert set(schema["parameters"].get("properties", {})) == {"query", "model"}
+ assert schema["parameters"].get("required") == ["query", "model"]
diff --git a/tools/mcp_tool_registration.py b/tools/mcp_tool_registration.py
index 17282af067f..35af9bb2892 100644
--- a/tools/mcp_tool_registration.py
+++ b/tools/mcp_tool_registration.py
@@ -7,7 +7,7 @@ import logging
from dataclasses import dataclass
from types import SimpleNamespace
from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Optional
-from tools.mcp_tool_common import _parse_boolish, _core, _resolve_tool_timeout
+from tools.mcp_tool_common import _parse_boolish, _core, _resolve_tool_timeout, mcp_field
from tools.mcp_tool_handlers import (
_make_check_fn, _make_get_prompt_handler, _make_list_prompts_handler,
_make_list_resources_handler, _make_read_resource_handler)
@@ -244,11 +244,21 @@ def _write_schema_cache(name: str, server: "MCPServerTask", config: dict, should
"""Write-through: persist the manifest so the next startup registers this server lazily (no spawn). Never raises."""
try:
from tools.mcp_schema_cache import config_fingerprint, write_cache_entry
- tools_payload = [{
- "name": t.name, "description": t.description or "",
- "inputSchema": t.inputSchema if isinstance(getattr(t, "inputSchema", None), dict) else {},
- "annotations": {"readOnlyHint": _annotation_read_only_hint(t)}, # lazy path trust-gates identically
- } for t in server._tools if should_register(t.name)]
+ tools_payload = []
+ for t in server._tools:
+ if not should_register(t.name):
+ continue
+ # mcp 2.0 renamed every Tool model field to snake_case and left camelCase as a
+ # *serialization* alias only, which pydantic does not apply to attribute access: a bare
+ # camelCase getattr returns None on 2.x instead of raising. That silently wrote an empty
+ # ``inputSchema`` into the schema cache on every write-through, so a ``lazy: true`` server
+ # registered from cache with every parameter stripped. ``mcp_field`` reads both spellings.
+ schema_obj = mcp_field(t, "input_schema", "inputSchema")
+ tools_payload.append({
+ "name": t.name, "description": t.description or "",
+ "inputSchema": schema_obj if isinstance(schema_obj, dict) else {},
+ "annotations": {"readOnlyHint": _annotation_read_only_hint(t)}, # lazy path trust-gates identically
+ })
utility_payload = [{"schema": e["schema"], "handler_key": e["handler_key"]}
for e in _select_utility_schemas(name, server, config)]
cache_meta = getattr(server, "_list_cache_meta", None) or {}