From 593c549bc466f6e0b8c517320393c16731597c74 Mon Sep 17 00:00:00 2001 From: 0xbyt4 <35742124+0xbyt4@users.noreply.github.com> Date: Mon, 2 Mar 2026 21:34:21 +0300 Subject: [PATCH] fix: make discover_mcp_tools idempotent to prevent duplicate connections When discover_mcp_tools() is called multiple times (e.g. direct call then model_tools import), return existing tool names instead of opening new connections that would orphan the previous ones. --- tools/mcp_tool.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/tools/mcp_tool.py b/tools/mcp_tool.py index 5225d63f7..5cdce4a39 100644 --- a/tools/mcp_tool.py +++ b/tools/mcp_tool.py @@ -361,6 +361,9 @@ def discover_mcp_tools() -> List[str]: Called from ``model_tools._discover_tools()``. Safe to call even when the ``mcp`` package is not installed (returns empty list). + Idempotent: if servers are already connected, returns the existing + tool names without creating duplicate connections. + Returns: List of all registered MCP tool names. """ @@ -368,6 +371,15 @@ def discover_mcp_tools() -> List[str]: logger.debug("MCP SDK not available -- skipping MCP tool discovery") return [] + # Already connected -- return existing tool names (idempotent) + if _servers: + existing: List[str] = [] + for name, server in _servers.items(): + for mcp_tool in server._tools: + schema = _convert_mcp_schema(name, mcp_tool) + existing.append(schema["name"]) + return existing + servers = _load_mcp_config() if not servers: logger.debug("No MCP servers configured")