"""MCP 客戶端:連接外部 MCP 伺服器,把它們的工具自動暴露給 agent。 設定格式與 Claude Desktop / Cursor 相同(在前端「🔌 MCP」裡編輯,存在 Turso): { "mcpServers": { "remote-http": {"url": "https://example.com/mcp", "headers": {"Authorization": "Bearer ${MY_TOKEN}"}}, "remote-sse": {"url": "https://example.com/sse", "transport": "sse"}, "local-stdio": {"command": "npx", "args": ["-y", "@modelcontextprotocol/server-everything"], "env": {}} } } 字串裡的 ${VAR} 會替換成 Space Secrets 裡同名的環境變數,key 不用寫進資料庫。 """ import asyncio import json import logging import os import re from contextlib import AsyncExitStack from mcp import ClientSession, StdioServerParameters from mcp.client.sse import sse_client from mcp.client.stdio import stdio_client from mcp.client.streamable_http import streamablehttp_client from . import config from . import db as store log = logging.getLogger("mcp") DEFAULT_CONFIG = {"mcpServers": {}} _VAR = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}") def _subst(v): if isinstance(v, str): return _VAR.sub(lambda m: os.environ.get(m.group(1), ""), v) if isinstance(v, list): return [_subst(x) for x in v] if isinstance(v, dict): return {k: _subst(x) for k, x in v.items()} return v class MCPConn: def __init__(self, name: str, cfg: dict): self.name, self.cfg = name, _subst(cfg) self.session: ClientSession | None = None self.tools: list = [] self.error: str | None = None self.ready, self.stop = asyncio.Event(), asyncio.Event() self.task: asyncio.Task | None = None async def start(self): self.task = asyncio.create_task(self._run()) try: await asyncio.wait_for(self.ready.wait(), config.MCP_CONNECT_TIMEOUT) except asyncio.TimeoutError: self.error = f"連線逾時({config.MCP_CONNECT_TIMEOUT}s)" self.stop.set() async def _run(self): c = self.cfg try: async with AsyncExitStack() as stack: if c.get("command"): env = {"PATH": os.environ.get("PATH", ""), "HOME": os.environ.get("HOME", "/tmp"), "LANG": "C.UTF-8", **{k: str(v) for k, v in (c.get("env") or {}).items()}} params = StdioServerParameters(command=c["command"], args=c.get("args") or [], env=env, cwd=c.get("cwd")) read, write = await stack.enter_async_context(stdio_client(params)) elif c.get("url"): # 去掉替換後變空的 header(例如 Secret 沒設定) headers = {k: str(v).strip() for k, v in (c.get("headers") or {}).items() if str(v).strip() and str(v).strip().lower() not in ("bearer", "token")} transport = (c.get("transport") or c.get("type") or "").lower() if transport == "sse" or (not transport and c["url"].rstrip("/").endswith("/sse")): read, write = await stack.enter_async_context(sse_client(c["url"], headers=headers)) else: read, write, _ = await stack.enter_async_context( streamablehttp_client(c["url"], headers=headers)) else: raise ValueError("需要 command(stdio)或 url(http/sse)") session = await stack.enter_async_context(ClientSession(read, write)) await session.initialize() self.tools = (await session.list_tools()).tools self.session = session self.ready.set() await self.stop.wait() except Exception as e: # noqa: BLE001 msg = repr(e) if hasattr(e, "exceptions"): # ExceptionGroup msg = "; ".join(repr(x) for x in e.exceptions) self.error = msg[:500] log.warning("MCP %s 失敗: %s", self.name, self.error) finally: self.session = None self.ready.set() async def close(self): self.stop.set() if self.task: try: await asyncio.wait_for(self.task, 10) except Exception: # noqa: BLE001 self.task.cancel() def _convert(res) -> dict: parts = [] for item in res.content or []: t = getattr(item, "type", "") if t == "text": parts.append(item.text) elif t == "image": parts.append(f"[圖片 {getattr(item, 'mimeType', '')}]") elif t == "resource": r = item.resource parts.append(getattr(r, "text", None) or f"[資源 {getattr(r, 'uri', '')}]") else: parts.append(str(item)) out = {"content": "\n".join(parts)} if not parts and getattr(res, "structuredContent", None): out["content"] = json.dumps(res.structuredContent, ensure_ascii=False) if getattr(res, "isError", False): out["is_error"] = True return out class MCPManager: def __init__(self): self.conns: dict[str, MCPConn] = {} self.tool_map: dict[str, tuple[MCPConn, str]] = {} self.schemas: list[dict] = [] self.lock = asyncio.Lock() async def get_config(self) -> dict: raw = await store.get_setting("mcp_config") try: cfg = json.loads(raw) if raw else DEFAULT_CONFIG except json.JSONDecodeError: cfg = DEFAULT_CONFIG return cfg if isinstance(cfg, dict) else DEFAULT_CONFIG async def reload(self): async with self.lock: await self.stop_all() servers = (await self.get_config()).get("mcpServers") or {} conns = [MCPConn(n, c) for n, c in servers.items() if isinstance(c, dict) and not c.get("disabled")] await asyncio.gather(*(c.start() for c in conns)) self.conns = {c.name: c for c in conns} self._rebuild() def _rebuild(self): self.tool_map, self.schemas = {}, [] for c in self.conns.values(): if not c.session: continue for t in c.tools: base = re.sub(r"[^a-zA-Z0-9_-]", "_", f"mcp_{c.name}_{t.name}")[:64] fname, i = base, 2 while fname in self.tool_map: fname, i = f"{base[:60]}_{i}", i + 1 self.tool_map[fname] = (c, t.name) schema = t.inputSchema or {} if schema.get("type") != "object": schema = {"type": "object", "properties": {}} self.schemas.append({"type": "function", "function": { "name": fname, "description": f"[MCP:{c.name}] {(t.description or t.name)[:1000]}", "parameters": schema}}) async def call(self, fname: str, args: dict) -> dict: conn, tname = self.tool_map[fname] if not conn.session: return {"error": f"MCP 伺服器 {conn.name} 已斷線,請在 MCP 設定裡重新連線"} res = await asyncio.wait_for(conn.session.call_tool(tname, args), config.MCP_CALL_TIMEOUT) return _convert(res) def status(self) -> list[dict]: return [{"name": c.name, "connected": c.session is not None, "error": c.error, "tools": [t.name for t in c.tools] if c.session else []} for c in self.conns.values()] async def stop_all(self): await asyncio.gather(*(c.close() for c in self.conns.values()), return_exceptions=True) self.conns, self.tool_map, self.schemas = {}, {}, [] manager = MCPManager()