Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
fix(mcp): sanitize MCPTool name for LLM provider compatibility (#1787)
qbc9bac81cb8330
diff --git a/src/agentscope/mcp/_mcp_client.py b/src/agentscope/mcp/_mcp_client.pyindex 3438baccc..688e6e27b 100644--- a/src/agentscope/mcp/_mcp_client.py+++ b/src/agentscope/mcp/_mcp_client.py@@ -1,5 +1,6 @@# -*- coding: utf-8 -*-"""Unified MCP client implementation for AgentScope."""+import refrom contextlib import AsyncExitStack, _AsyncGeneratorContextManagerfrom typing import Any, TYPE_CHECKING@@ -115,6 +116,15 @@ class MCPClient(BaseModel):def model_post_init(self, __context: Any) -> None:"""Validate configuration and initialize client."""+ # MCP name is used to compose model-facing tool names+ # (mcp__{name}__{tool}), which must match ^[a-zA-Z0-9_-]+$.+ if not re.fullmatch(r"[a-zA-Z0-9_-]+", self.name):+ raise ValueError(+ f"MCPClient name '{self.name}' contains characters not "+ f"allowed by LLM providers (only [a-zA-Z0-9_-] are "+ f"permitted). Please rename it.",+ )+# STDIO MCP must be statefulif self.mcp_config.type == "stdio_mcp" and not self.is_stateful:raise ValueError(diff --git a/src/agentscope/tool/_adapters.py b/src/agentscope/tool/_adapters.pyindex cbd23a130..65990238f 100644--- a/src/agentscope/tool/_adapters.py+++ b/src/agentscope/tool/_adapters.py@@ -2,6 +2,7 @@"""Adapters to convert functions and MCP tools to ToolProtocol."""import inspectimport json+import refrom contextlib import _AsyncGeneratorContextManagerfrom datetime import timedeltafrom typing import Callable, Any, AsyncGenerator, Generator@@ -199,7 +200,22 @@ class MCPTool(ToolBase):The timeout in seconds for tool execution."""self.mcp_name = mcp_name- self.name = f"mcp__{self.mcp_name}__{tool.name}"++ # LLM providers enforce ^[a-zA-Z0-9_-]+$ on tool names.+ # mcp_name is validated in MCPClient.model_post_init;+ # tool.name comes from the MCP server and may contain dots,+ # colons, etc. — replace illegal chars with "x" (not "_")+ # to avoid collisions with the "__" separator.+ # self._tool.name retains the original for server-side calls.+ sanitized_tool = re.sub(r"[^a-zA-Z0-9_-]", "x", tool.name)+ self.name = f"mcp__{mcp_name}__{sanitized_tool}"+ if sanitized_tool != tool.name:+ logger.debug(+ "MCP tool name sanitized: '%s' -> '%s'.",+ tool.name,+ self.name,+ )+self.description = tool.description or ""# Preserve the full inputSchema (including $defs, anyOf, oneOf, etc.)diff --git a/tests/service_inbox_middleware_test.py b/tests/service_inbox_middleware_test.pyindex 731ffbc8d..e1a9cd1f6 100644--- a/tests/service_inbox_middleware_test.py+++ b/tests/service_inbox_middleware_test.py@@ -273,6 +273,7 @@ class TestInboxMiddlewareInjection(IsolatedAsyncioTestCase):"type": "HINT_BLOCK","id": AnyString(),"created_at": AnyString(),+ "metadata": {},"reply_id": agent.state.reply_id,"block_id": hint.id,"source": "tester",@@ -392,6 +393,7 @@ class TestInboxMiddlewareYieldsHintBlockEvents(IsolatedAsyncioTestCase):"type": "HINT_BLOCK","id": AnyString(),"created_at": AnyString(),+ "metadata": {},"reply_id": "rid-evt","block_id": h1.id,"source": "alice",@@ -401,6 +403,7 @@ class TestInboxMiddlewareYieldsHintBlockEvents(IsolatedAsyncioTestCase):"type": "HINT_BLOCK","id": AnyString(),"created_at": AnyString(),+ "metadata": {},"reply_id": "rid-evt","block_id": h2.id,"source": "bob",@@ -441,6 +444,7 @@ class TestInboxMiddlewareDelegatesDownstream(IsolatedAsyncioTestCase):"type": "HINT_BLOCK","id": AnyString(),"created_at": AnyString(),+ "metadata": {},"reply_id": "rid","block_id": hint.id,"source": "x",