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.
This commit is contained in:
0xbyt4
2026-03-02 21:34:21 +03:00
parent aa2ecaef29
commit 593c549bc4

View File

@@ -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")