From 63df01fe3f18a5b54634c8ab68761b0487aee20f Mon Sep 17 00:00:00 2001 From: eviaaaaa <2278596667@qq.com> Date: Thu, 14 May 2026 15:28:39 +0800 Subject: [PATCH] fix(agent): handle duplicate MCP tool names (#14217) ### What problem does this PR solve? When multiple MCP servers expose tools with the same name, the agent currently registers those tools using their original MCP names. This can lead to two issues: - later MCP tools may overwrite earlier ones in the agent tool map - duplicate function names may be exposed to the LLM This PR fixes duplicate MCP tool-name handling by applying the same indexed naming strategy already used for native agent tools. Native tools are exposed with generated names such as `_` to avoid collisions, and MCP tools now follow the same convention for consistency. Specifically, this PR: - assigns unique indexed function names to MCP tools exposed to the LLM - preserves each MCP tool's original server-side name in an `MCPToolBinding` - dispatches MCP calls using the original MCP tool name while keeping the indexed name in the agent tool map - allows MCP metadata conversion to override only the OpenAI function name without modifying the original MCP tool metadata ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue) ### Validation The validation was performed using two MCP servers. Both servers exposed a tool with the same name: `mcp0`. Both tools take no input parameters. **MCP Server One:** ONE **MCP Server Two:** Second **Before the fix:** When invoking `mcp0`, only the `mcp0` tool from the MCP server injected later could be called successfully. As shown below, both `mcp0` tools were present, but only the later-registered one was actually invokable. Three **After the fix:** Both `mcp0` tools can now be invoked correctly. F six --- agent/component/agent_with_tools.py | 9 ++++++--- agent/tools/base.py | 14 ++++++++------ common/mcp_tool_call_conn.py | 15 +++++++++++---- 3 files changed, 25 insertions(+), 13 deletions(-) diff --git a/agent/component/agent_with_tools.py b/agent/component/agent_with_tools.py index 859064046d..83c3e27e53 100644 --- a/agent/component/agent_with_tools.py +++ b/agent/component/agent_with_tools.py @@ -32,7 +32,7 @@ from api.db.services.llm_service import LLMBundle from api.db.services.mcp_server_service import MCPServerService from api.db.services.tenant_llm_service import TenantLLMService from common.connection_utils import timeout -from common.mcp_tool_call_conn import MCPToolCallSession, mcp_tool_metadata_to_openai_tool +from common.mcp_tool_call_conn import MCPToolBinding, MCPToolCallSession, mcp_tool_metadata_to_openai_tool from rag.prompts.generator import citation_plus, citation_prompt, full_question, kb_prompt, message_fit_in, structured_output_prompt @@ -97,13 +97,16 @@ class Agent(LLM, ToolBase): indexed_meta["function"]["name"] = indexed_name self.tool_meta.append(indexed_meta) + tool_idx = len(self.tools) for mcp in self._param.mcp: _, mcp_server = MCPServerService.get_by_id(mcp["mcp_id"]) custom_header = self._param.custom_header tool_call_session = MCPToolCallSession(mcp_server, mcp_server.variables, custom_header) for tnm, meta in mcp["tools"].items(): - self.tool_meta.append(mcp_tool_metadata_to_openai_tool(meta)) - self.tools[tnm] = tool_call_session + indexed_name = f"{tnm}_{tool_idx}" + tool_idx += 1 + self.tool_meta.append(mcp_tool_metadata_to_openai_tool(meta, function_name=indexed_name)) + self.tools[indexed_name] = MCPToolBinding(tool_call_session, tnm) self.callback = partial(self._canvas.tool_use_callback, id) self.toolcall_session = LLMToolPluginCallSession(self.tools, self.callback) if self.tool_meta: diff --git a/agent/tools/base.py b/agent/tools/base.py index 194b47fcee..dbcb185518 100644 --- a/agent/tools/base.py +++ b/agent/tools/base.py @@ -23,7 +23,7 @@ from typing import TypedDict, List, Any from agent.component.base import ComponentParamBase, ComponentBase from common.misc_utils import hash_str2int from rag.prompts.generator import kb_prompt -from common.mcp_tool_call_conn import MCPToolCallSession, ToolCallSession +from common.mcp_tool_call_conn import MCPToolBinding, MCPToolCallSession, ToolCallSession from timeit import default_timer as timer @@ -52,16 +52,18 @@ class LLMToolPluginCallSession(ToolCallSession): self.tools_map = tools_map self.callback = callback - def tool_call(self, name: str, arguments: dict[str, Any]) -> Any: - return asyncio.run(self.tool_call_async(name, arguments)) + def tool_call(self, name: str, arguments: dict[str, Any], timeout: float | int = 10) -> Any: + return asyncio.run(self.tool_call_async(name, arguments, request_timeout=timeout)) - async def tool_call_async(self, name: str, arguments: dict[str, Any]) -> Any: + async def tool_call_async(self, name: str, arguments: dict[str, Any], request_timeout: float | int = 10) -> Any: assert name in self.tools_map, f"LLM tool {name} does not exist" logging.info(f"[ToolCall] invoke name={name} arguments={str(arguments)[:200]}") st = timer() tool_obj = self.tools_map[name] - if isinstance(tool_obj, MCPToolCallSession): - resp = await thread_pool_exec(tool_obj.tool_call, name, arguments, 60) + if isinstance(tool_obj, MCPToolBinding): + resp = await thread_pool_exec(tool_obj.session.tool_call, tool_obj.original_name, arguments, request_timeout) + elif isinstance(tool_obj, MCPToolCallSession): + resp = await thread_pool_exec(tool_obj.tool_call, name, arguments, request_timeout) elif hasattr(tool_obj, "invoke_async") and asyncio.iscoroutinefunction(tool_obj.invoke_async): resp = await tool_obj.invoke_async(**arguments) else: diff --git a/common/mcp_tool_call_conn.py b/common/mcp_tool_call_conn.py index 95e3581bb0..676978d052 100644 --- a/common/mcp_tool_call_conn.py +++ b/common/mcp_tool_call_conn.py @@ -20,6 +20,7 @@ import threading import weakref from concurrent.futures import ThreadPoolExecutor from concurrent.futures import TimeoutError as FuturesTimeoutError +from dataclasses import dataclass from string import Template from typing import Any, Literal, Protocol @@ -36,7 +37,13 @@ MCPTask = tuple[MCPTaskType, dict[str, Any], asyncio.Queue[Any]] class ToolCallSession(Protocol): - def tool_call(self, name: str, arguments: dict[str, Any]) -> str: ... + def tool_call(self, name: str, arguments: dict[str, Any], timeout: float | int = 10) -> str: ... + + +@dataclass(frozen=True) +class MCPToolBinding: + session: ToolCallSession + original_name: str class MCPToolCallSession(ToolCallSession): @@ -316,12 +323,12 @@ def shutdown_all_mcp_sessions(): logging.info("All MCPToolCallSession instances have been closed.") -def mcp_tool_metadata_to_openai_tool(mcp_tool: Tool | dict) -> dict[str, Any]: +def mcp_tool_metadata_to_openai_tool(mcp_tool: Tool | dict, function_name: str | None = None) -> dict[str, Any]: if isinstance(mcp_tool, dict): return { "type": "function", "function": { - "name": mcp_tool["name"], + "name": function_name or mcp_tool["name"], "description": mcp_tool["description"], "parameters": mcp_tool["inputSchema"], }, @@ -330,7 +337,7 @@ def mcp_tool_metadata_to_openai_tool(mcp_tool: Tool | dict) -> dict[str, Any]: return { "type": "function", "function": { - "name": mcp_tool.name, + "name": function_name or mcp_tool.name, "description": mcp_tool.description, "parameters": mcp_tool.inputSchema, },