Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
fix(mcp): preserve $defs in MCPTool input schema and strip titles recursively (#1595)
qbceefa53210fdb
diff --git a/src/agentscope/tool/_adapters.py b/src/agentscope/tool/_adapters.pyindex c2dc51c97..eeba19efc 100644--- a/src/agentscope/tool/_adapters.py+++ b/src/agentscope/tool/_adapters.py@@ -161,12 +161,15 @@ class MCPTool(ToolBase):self.name = f"mcp__{self.mcp_name}__{tool.name}"self.description = tool.description or ""- # Extract input schema- self.input_schema = {- "type": "object",- "properties": tool.inputSchema.get("properties", {}),- "required": tool.inputSchema.get("required", []),- }+ # Preserve the full inputSchema (including $defs, anyOf, oneOf, etc.)+ # rather than only copying "properties" and "required", which would+ # silently drop any nested type definitions that the LLM needs to+ # resolve $ref pointers.+ _schema = dict(tool.inputSchema) if tool.inputSchema else {}+ _schema.setdefault("type", "object")+ _schema.setdefault("properties", {})+ _schema.setdefault("required", [])+ self.input_schema = _schema# By defaultself.is_concurrency_safe = Falsediff --git a/src/agentscope/tool/_utils.py b/src/agentscope/tool/_utils.pyindex 3d98b0211..5d6a410f8 100644--- a/src/agentscope/tool/_utils.py+++ b/src/agentscope/tool/_utils.py@@ -29,9 +29,16 @@ def _remove_title_field(schema: dict) -> dict:schema["additionalProperties"],dict,):- _remove_title_field(- schema["additionalProperties"],- )+ _remove_title_field(schema["additionalProperties"])++ # $defs — referenced sub-schemas, e.g. Pydantic models used as parameter+ # types generate "$defs": {"SubModel": {"title": "SubModel", ...}}.+ # These titles are auto-generated noise just like property titles, and+ # should be removed for the same reason.+ if "$defs" in schema and isinstance(schema["$defs"], dict):+ for def_schema in schema["$defs"].values():+ if isinstance(def_schema, dict):+ _remove_title_field(def_schema)return schemadiff --git a/tests/mcp_sse_client_test.py b/tests/mcp_sse_client_test.pyindex d5ca92ce0..9d3970d87 100644--- a/tests/mcp_sse_client_test.py+++ b/tests/mcp_sse_client_test.py@@ -6,6 +6,7 @@ from multiprocessing import Processfrom unittest.async_case import IsolatedAsyncioTestCasefrom mcp.server import FastMCP+from pydantic import BaseModelfrom agentscope.mcp import MCPClient, HttpMCPConfigfrom agentscope.message import ToolCallBlock@@ -32,6 +33,36 @@ def setup_server() -> None:sse_server.run(transport="sse")+# ---------------------------------------------------------------------------+# Server / tool definitions for $defs preservation test+# ---------------------------------------------------------------------------+++class _ItemConfig(BaseModel):+ """Config sub-model to generate $defs in the MCP inputSchema."""++ key: str+ count: int+++async def tool_with_model(name: str, config: _ItemConfig) -> str:+ """A tool whose parameter uses a Pydantic sub-model.++ Args:+ name: Item name.+ config: Item configuration.+ """+ return f"name={name}, key={config.key}, count={config.count}"+++def setup_defs_server() -> None:+ """Set up an SSE MCP server that exposes a tool with Pydantic+ sub-models."""+ server = FastMCP("DefsSSE", port=8005)+ server.tool()(tool_with_model)+ server.run(transport="sse")++class SseMCPClientTest(IsolatedAsyncioTestCase):"""Test class for MCP server functionality."""@@ -246,3 +277,99 @@ class SseMCPClientTest(IsolatedAsyncioTestCase):await stateful_client.close()self.assertFalse(stateful_client.is_connected)+++class SseSchemaDefsPreservationTest(IsolatedAsyncioTestCase):+ """End-to-end tests for $defs preservation in MCP tool schemas.++ These tests start a real FastMCP server that exposes a tool whose+ parameter is a Pydantic sub-model. FastMCP generates an inputSchema with+ ``$defs`` for the sub-model. We verify that the schema returned by+ ``Toolkit.get_function_schemas()`` preserves those ``$defs`` and that+ Pydantic-generated ``title`` fields inside ``$defs`` are stripped.+ """++ async def asyncSetUp(self) -> None:+ """Start the $defs test server."""+ self.port = 8005+ self.process = Process(target=setup_defs_server)+ self.process.start()+ await asyncio.sleep(10)++ self.schemas = [+ {+ "type": "function",+ "function": {+ "name": "mcp__test_defs_client__tool_with_model",+ "description": "A tool whose parameter uses a "+ "Pydantic sub-model.\n\n Args:\n "+ "name: Item name.\n "+ "config: Item configuration.\n ",+ "parameters": {+ "$defs": {+ "_ItemConfig": {+ "description": "Config sub-model to "+ "generate $defs in the "+ "MCP inputSchema.",+ "properties": {+ "key": {"type": "string"},+ "count": {"type": "integer"},+ },+ "required": ["key", "count"],+ "type": "object",+ },+ },+ "properties": {+ "name": {"type": "string"},+ "config": {"$ref": "#/$defs/_ItemConfig"},+ },+ "required": ["name", "config"],+ "type": "object",+ },+ },+ },+ ]++ async def asyncTearDown(self) -> None:+ """Stop the $defs test server."""+ while self.process.is_alive():+ self.process.terminate()+ await asyncio.sleep(5)++ async def test_defs_preserved_and_titles_stripped(self) -> None:+ """$defs from Pydantic sub-model parameters must survive the full+ pipeline.++ Failure scenario (before fix):+ MCPTool.__init__ only copied ``properties`` and ``required``,+ so ``$defs._ItemConfig`` was silently dropped. The LLM would+ receive a schema where ``config`` had an unresolvable+ ``$ref: "#/$defs/_ItemConfig"``.++ Expected behaviour (after fix):+ - ``MCPTool.input_schema`` contains ``$defs._ItemConfig``+ - ``Toolkit.get_function_schemas()`` output contains ``$defs``+ with the ref resolved and Pydantic titles stripped.+ """+ client = MCPClient(+ name="test_defs_client",+ is_stateful=False,+ mcp_config=HttpMCPConfig(+ type="http_mcp",+ url=f"http://127.0.0.1:{self.port}/sse",+ ),+ )++ mcp_tool = await client.get_tool("tool_with_model")++ # 1. input_schema must preserve $defs+ self.assertIn(+ "$defs",+ mcp_tool.input_schema,+ "MCPTool.input_schema must preserve $defs from inputSchema",+ )++ # 2. get_function_schemas() must preserve $defs and strip titles+ toolkit = Toolkit(tools=[mcp_tool])+ schemas = toolkit.get_function_schemas()+ self.assertListEqual(schemas, self.schemas)diff --git a/tests/toolkit_test.py b/tests/toolkit_test.pyindex a35c717fa..449748411 100644--- a/tests/toolkit_test.py+++ b/tests/toolkit_test.py@@ -3,6 +3,7 @@"""Toolkit test case."""import jsonfrom typing import Any, AsyncGenerator, Generator+from unittest import TestCasefrom unittest.async_case import IsolatedAsyncioTestCasefrom utils import AnyString@@ -1026,3 +1027,72 @@ The tool instructions are a collection of suggestions, rules and notifications a"state": "success",},)+++class RemoveTitleFieldTest(TestCase):+ """Unit tests for _remove_title_field."""++ def setUp(self) -> None:+ from agentscope.tool._utils import _remove_title_field++ self.fn = _remove_title_field++ def test_removes_top_level_title(self) -> None:+ """The top level title field must be removed."""+ schema = {"title": "Root", "type": "object", "properties": {}}+ self.fn(schema)+ self.assertNotIn("title", schema)++ def test_removes_property_titles(self) -> None:+ """Titles inside properties must be removed."""+ schema: dict[str, Any] = {+ "type": "object",+ "properties": {+ "name": {"title": "Name", "type": "string"},+ },+ }+ self.fn(schema)+ self.assertNotIn("title", schema["properties"]["name"])++ def test_removes_defs_titles(self) -> None:+ """Titles inside $defs must be recursively stripped."""+ schema: dict[str, Any] = {+ "type": "object",+ "properties": {"x": {"$ref": "#/$defs/MyModel"}},+ "$defs": {+ "MyModel": {+ "title": "MyModel",+ "type": "object",+ "properties": {+ "val": {"title": "Val", "type": "string"},+ },+ },+ },+ }+ self.fn(schema)++ self.assertDictEqual(+ schema,+ {+ "type": "object",+ "properties": {"x": {"$ref": "#/$defs/MyModel"}},+ "$defs": {+ "MyModel": {+ "type": "object",+ "properties": {+ "val": {"type": "string"},+ },+ },+ },+ },+ )++ def test_does_not_mutate_non_dict_defs(self) -> None:+ """Boolean schema values inside $defs should not raise."""+ schema: dict[str, Any] = {+ "type": "object",+ "properties": {},+ "$defs": {"AlwaysTrue": True},+ }+ self.fn(schema)+ self.assertEqual(schema["$defs"]["AlwaysTrue"], True)