Coverage for app / mcp / loader.py: 94%
127 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
1"""
2MCP tool loader — connects to configured MCP servers and returns their tools
3as LangChain StructuredTools for binding to worker agents.
5Server descriptor format (stored on WorkerAgentDefinition.mcp_servers and
6forwarded from svc-core MCPServer rows)::
8 {"name": "github", "transport": "http" | "sse" | "stdio",
9 "url": "https://…", # http / sse
10 "headers": {…}, # optional, http / sse
11 "command": "npx", "args": […], # stdio
12 "env": {…}} # optional, stdio
14Uses ``langchain-mcp-adapters``.
16Availability
17------------
18Both entry points — ``load_mcp_tools`` and ``probe_mcp_server`` — return
19before touching a descriptor while ``app.mcp.MCP_AVAILABLE`` is off, which it
20is in every environment (see that module for why and what turning it on
21needs).
23Reliability
24-----------
25Every server is loaded concurrently under a per-server deadline
26(``settings.mcp_connect_timeout_s``) so one slow or unreachable server can
27never stall agent execution. Failures are contained per server: an
28unreachable or misconfigured server logs a warning and contributes no tools,
29never failing the agent execution.
31Security
32--------
33stdio servers run as subprocesses inside this container, so the launch
34command is validated against ``settings.mcp_stdio_command_allowlist`` (and
35the transport can be disabled wholesale via ``settings.mcp_stdio_enabled``).
36http/sse servers must present an absolute http(s) URL.
38Accuracy
39--------
40Tool names are namespaced on collision: when two servers expose the same
41tool name, the later server's tool is renamed ``<server>__<tool>`` instead
42of being silently dropped, so every configured capability stays callable.
43"""
45from __future__ import annotations
47import asyncio
48import re
49import shlex
50from dataclasses import dataclass, field
51from typing import Any
52from urllib.parse import urlparse
54from app.common.settings import get_settings
55from app.mcp import UNAVAILABLE_MESSAGE, is_available
56from app.util.logger import get_logger
58logger = get_logger(__name__)
60# svc-core historically labels the transport "connection_type"; the MCP
61# adapters call http "streamable_http". Normalise both here.
62_TRANSPORT_ALIASES = {
63 "http": "streamable_http",
64 "streamable_http": "streamable_http",
65 "sse": "sse",
66 "stdio": "stdio",
67}
69# LangChain/OpenAI tool names must match this charset.
70_TOOL_NAME_SAFE = re.compile(r"[^a-zA-Z0-9_-]+")
73class MCPConfigError(ValueError):
74 """A server descriptor failed validation (bad transport, URL, or command)."""
77def _sanitise_name(raw: str, fallback: str) -> str:
78 cleaned = _TOOL_NAME_SAFE.sub("_", raw).strip("_")
79 return cleaned or fallback
82def _to_connection(server: dict[str, Any]) -> dict[str, Any]:
83 """Convert one descriptor to a langchain-mcp-adapters connection dict.
85 Raises MCPConfigError when the descriptor is invalid or violates the
86 deployment's transport policy — callers decide whether that is a warning
87 (agent execution) or a 4xx (probe endpoint).
88 """
89 settings = get_settings()
90 raw_transport = str(
91 server.get("transport") or server.get("connection_type") or ""
92 ).lower()
93 transport = _TRANSPORT_ALIASES.get(raw_transport)
94 config: dict[str, Any] = (
95 server.get("config")
96 or server.get("connection_config")
97 or {k: v for k, v in server.items() if k not in ("name", "transport")}
98 )
100 if transport in ("streamable_http", "sse"):
101 url = str(config.get("url", "")).strip()
102 parsed = urlparse(url)
103 if parsed.scheme not in ("http", "https") or not parsed.netloc:
104 raise MCPConfigError(
105 f"{raw_transport} transport requires an absolute http(s) URL, got {url!r}"
106 )
107 conn: dict[str, Any] = {"transport": transport, "url": url}
108 headers = config.get("headers")
109 if headers:
110 if not isinstance(headers, dict):
111 raise MCPConfigError("headers must be an object of header→value")
112 conn["headers"] = {str(k): str(v) for k, v in headers.items()}
113 return conn
115 if transport == "stdio":
116 if not settings.mcp_stdio_enabled:
117 raise MCPConfigError(
118 "stdio MCP servers are disabled in this deployment "
119 "(mcp_stdio_enabled=false)"
120 )
121 command = str(config.get("command", "")).strip()
122 if not command:
123 raise MCPConfigError("stdio transport requires a command")
124 # Allow "npx something --flag" as a single command string.
125 parts = shlex.split(command)
126 executable = parts[0].rsplit("/", 1)[-1]
127 if executable not in settings.mcp_stdio_command_allowlist:
128 raise MCPConfigError(
129 f"stdio command {executable!r} is not on the allowed launcher list "
130 f"({sorted(settings.mcp_stdio_command_allowlist)})"
131 )
132 args = list(config.get("args") or [])
133 conn = {
134 "transport": "stdio",
135 "command": parts[0],
136 "args": parts[1:] + [str(a) for a in args],
137 }
138 env = config.get("env")
139 if env:
140 if not isinstance(env, dict):
141 raise MCPConfigError("env must be an object of variable→value")
142 conn["env"] = {str(k): str(v) for k, v in env.items()}
143 return conn
145 raise MCPConfigError(
146 f"unknown transport {raw_transport!r} (expected http, sse, or stdio)"
147 )
150async def _load_one(name: str, server: dict[str, Any]) -> list[Any]:
151 """Load tools from a single server under the configured deadline.
153 Returns [] on any failure — per-server isolation is the contract.
154 """
155 settings = get_settings()
156 try:
157 connection = _to_connection(server)
158 except MCPConfigError as exc:
159 logger.warning("[mcp] server %r rejected: %s — skipped", name, exc)
160 return []
162 try:
163 from langchain_mcp_adapters.client import MultiServerMCPClient
165 client = MultiServerMCPClient({name: connection})
166 server_tools = await asyncio.wait_for(
167 client.get_tools(server_name=name),
168 timeout=settings.mcp_connect_timeout_s,
169 )
170 logger.info(
171 "[mcp] server %r provided %d tool(s): %s",
172 name,
173 len(server_tools),
174 [t.name for t in server_tools],
175 )
176 return list(server_tools)
177 except asyncio.TimeoutError:
178 logger.warning(
179 "[mcp] server %r did not respond within %.1fs — skipped",
180 name,
181 settings.mcp_connect_timeout_s,
182 )
183 return []
184 except Exception as exc:
185 logger.warning(
186 "[mcp] could not load tools from server %r (%s) — skipped", name, exc
187 )
188 return []
191def _merge_namespaced(per_server: list[tuple[str, list[Any]]]) -> list[Any]:
192 """Merge tool lists, renaming collisions to ``<server>__<tool>``."""
193 merged: dict[str, Any] = {}
194 for server_name, tools in per_server:
195 safe_server = _sanitise_name(server_name, "mcp")
196 for tool in tools:
197 tool.name = _sanitise_name(str(tool.name), "tool")
198 if tool.name in merged:
199 namespaced = f"{safe_server}__{tool.name}"
200 if namespaced in merged:
201 logger.warning(
202 "[mcp] duplicate tool %r within server %r — dropped",
203 tool.name,
204 server_name,
205 )
206 continue
207 logger.info(
208 "[mcp] tool name collision on %r — exposing server %r's copy as %r",
209 tool.name,
210 server_name,
211 namespaced,
212 )
213 tool.name = namespaced
214 merged[tool.name] = tool
215 return list(merged.values())
218async def load_mcp_tools(servers: list[dict[str, Any]]) -> list[Any]:
219 """Connect to each MCP server concurrently and return the union of tools.
221 Per-server isolation: one bad/slow server logs a warning and is skipped.
222 Returns [] when no servers are configured or the adapter is missing.
223 """
224 if not servers:
225 return []
227 if not is_available():
228 logger.warning(
229 "[mcp] MCP servers are not available — %d server(s) ignored",
230 len(servers),
231 )
232 return []
234 try:
235 import langchain_mcp_adapters # noqa: F401
236 except ImportError:
237 logger.warning(
238 "langchain-mcp-adapters is not installed — %d MCP server(s) ignored",
239 len(servers),
240 )
241 return []
243 names = [str(s.get("name") or f"mcp_{i}") for i, s in enumerate(servers)]
244 results = await asyncio.gather(
245 *(_load_one(name, server) for name, server in zip(names, servers))
246 )
247 return _merge_namespaced(list(zip(names, results)))
250# ---------------------------------------------------------------------------
251# Probe — connection test + tool discovery
252# ---------------------------------------------------------------------------
255@dataclass
256class MCPProbeResult:
257 """Outcome of probing a single MCP server descriptor."""
259 ok: bool
260 tools: list[dict[str, str]] = field(default_factory=list)
261 error: str = ""
264async def probe_mcp_server(server: dict[str, Any]) -> MCPProbeResult:
265 """Connect to one MCP server and report its tools without side effects.
267 Unlike ``load_mcp_tools`` this surfaces the failure reason so users can
268 fix their configuration; validation errors and connection errors both
269 come back as ``ok=False`` with a human-readable message.
270 """
271 if not is_available():
272 return MCPProbeResult(ok=False, error=UNAVAILABLE_MESSAGE)
274 settings = get_settings()
275 name = str(server.get("name") or "probe")
276 try:
277 connection = _to_connection(server)
278 except MCPConfigError as exc:
279 return MCPProbeResult(ok=False, error=str(exc))
281 try:
282 from langchain_mcp_adapters.client import MultiServerMCPClient
283 except ImportError:
284 return MCPProbeResult(
285 ok=False, error="langchain-mcp-adapters is not installed on svc-ai"
286 )
288 try:
289 client = MultiServerMCPClient({name: connection})
290 tools = await asyncio.wait_for(
291 client.get_tools(server_name=name),
292 timeout=settings.mcp_connect_timeout_s,
293 )
294 except asyncio.TimeoutError:
295 return MCPProbeResult(
296 ok=False,
297 error=f"server did not respond within {settings.mcp_connect_timeout_s:.0f}s",
298 )
299 except Exception as exc:
300 return MCPProbeResult(ok=False, error=f"connection failed: {exc}")
302 return MCPProbeResult(
303 ok=True,
304 tools=[
305 {
306 "name": _sanitise_name(str(t.name), "tool"),
307 "description": str(getattr(t, "description", "") or "")[:500],
308 }
309 for t in tools
310 ],
311 )