mcp.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. """MCP dashboard routes.
  2. The OAuth flow registry (``_mcp_oauth_flows``) and the worker/helpers stay in
  3. web_server — reached via the late-binding seam so tests that mutate
  4. ``web_server._mcp_oauth_flows`` or monkeypatch its helpers keep working.
  5. """
  6. import asyncio
  7. import hashlib
  8. from contextlib import contextmanager
  9. import re
  10. import secrets
  11. import threading
  12. import time
  13. from typing import Any, Dict, Optional
  14. from fastapi import APIRouter, HTTPException, Request
  15. from fastapi.responses import HTMLResponse
  16. from hermes_cli.web_deps import late
  17. from hermes_cli.web_server_mcp import _mcp_oauth_flows, _mcp_server_summary, _normalize_mcp_server_create
  18. from hermes_cli.web_models import MCPCatalogInstall, MCPEnabledToggle, MCPServerCreate, MCPServersReplace
  19. from hermes_cli.web_routers._common import (
  20. _profile_cli_args, _profile_scope, _spawn_hermes_action, config_write_scope, http_failure,
  21. log as _log, scoped_to_thread,
  22. )
  23. router = APIRouter()
  24. _config_profile_scope = late("_config_profile_scope", "hermes_cli.web_server_profiles")
  25. _require_token = late("_require_token")
  26. _run_dashboard_mcp_oauth = late("_run_dashboard_mcp_oauth", "hermes_cli.web_server_mcp")
  27. load_config = late("load_config", "hermes_cli.config")
  28. save_config = late("save_config", "hermes_cli.config")
  29. save_env_value = late("save_env_value", "hermes_cli.config")
  30. _mcp_oauth_flows_lock = threading.Lock()
  31. _MCP_DASHBOARD_OAUTH_TTL = 15 * 60
  32. _MAX_PENDING_MCP_OAUTH_FLOWS = 8
  33. @contextmanager
  34. def _profile_secret_scope(profile: Optional[str]):
  35. """Home + secret scope for a probe-class request (#109901). ``_config_profile_scope`` now binds
  36. the secret scope itself; this stays the probe/OAuth callers' name. Home-only, NOT
  37. ``_profile_scope``: the body can block for seconds and the latter holds the process-global
  38. skills lock."""
  39. with _config_profile_scope(profile):
  40. yield
  41. def _secret_scoped(profile: Optional[str], fn):
  42. def _run():
  43. with _profile_secret_scope(profile):
  44. return fn()
  45. return _run
  46. def _gc_mcp_oauth_flows() -> None:
  47. cutoff = time.time() - _MCP_DASHBOARD_OAUTH_TTL
  48. with _mcp_oauth_flows_lock:
  49. stale = [fid for fid, flow in _mcp_oauth_flows.items() if getattr(flow, "created_at", 0) < cutoff]
  50. for flow_id in stale:
  51. _mcp_oauth_flows.pop(flow_id, None)
  52. def _mcp_oauth_callback_url(request: Request, server_name: str) -> str:
  53. """Externally reachable callback URL for a dashboard flow."""
  54. from urllib.parse import quote, urlparse, urlunparse
  55. from hermes_cli.dashboard_auth.prefix import prefix_from_request, resolve_public_url
  56. suffix = f"/api/mcp/oauth/callback/{quote(server_name, safe='')}"
  57. public_url = resolve_public_url(request.app.state)
  58. if public_url:
  59. return f"{public_url}{suffix}"
  60. base = urlparse(str(request.base_url))
  61. prefix = prefix_from_request(request)
  62. return urlunparse(base._replace(path=f"{prefix}{suffix}", params="", query="", fragment=""))
  63. def _mcp_install_action_name(name: str) -> str:
  64. """Unique per-entry mcp-install action name (+ registered log file), so a
  65. re-click or a second catalog install doesn't overwrite the first's tracked
  66. process/log while its git clone is still running."""
  67. from hermes_cli.web_server_gateway import _ACTION_LOG_FILES
  68. slug = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")[:48] or "server"
  69. digest = hashlib.sha1(name.encode()).hexdigest()[:8]
  70. action = f"mcp-install-{slug}-{digest}"
  71. _ACTION_LOG_FILES.setdefault(action, f"action-{action}.log")
  72. return action
  73. @router.get("/api/mcp/servers")
  74. async def list_mcp_servers(profile: Optional[str] = None):
  75. from hermes_cli.mcp_config import _get_mcp_servers
  76. def _read():
  77. config_servers = _get_mcp_servers()
  78. from tui_gateway.mcp_rpc_helpers import server_configs_with_sources
  79. return server_configs_with_sources(config_servers)
  80. servers, plugins = await asyncio.to_thread(_secret_scoped(profile, _read))
  81. return {"servers": [
  82. _mcp_server_summary(name, cfg, plugins[name]) for name, cfg in sorted(servers.items())
  83. ]}
  84. @router.post("/api/mcp/servers")
  85. async def add_mcp_server(body: MCPServerCreate, profile: Optional[str] = None):
  86. from hermes_cli.mcp_catalog import record_mcp_install
  87. from hermes_cli.mcp_config import _get_mcp_servers, _save_bearer_auth_token, _save_mcp_server
  88. try:
  89. name, server_config, bearer_token = _normalize_mcp_server_create(body)
  90. except ValueError as exc:
  91. raise HTTPException(status_code=400, detail=str(exc)) from exc
  92. def _save() -> bool:
  93. # _save_mcp_server does its own load→mutate→save; the duplicate-name
  94. # check sits under the same lock span so a concurrent add can't slip
  95. # between check and save.
  96. with config_write_scope(body.profile or profile):
  97. config_servers = _get_mcp_servers()
  98. from tui_gateway.mcp_rpc_helpers import server_configs_with_sources
  99. servers, plugins = server_configs_with_sources(config_servers)
  100. if plugin := plugins.get(name):
  101. raise HTTPException(
  102. status_code=409, detail=f"Server '{name}' is provided by plugin '{plugin}' and cannot be modified",
  103. )
  104. if name in servers:
  105. raise HTTPException(status_code=409, detail=f"Server '{name}' already exists")
  106. if bearer_token is not None:
  107. server_config["headers"] = _save_bearer_auth_token(name, bearer_token)
  108. return _save_mcp_server(name, server_config)
  109. def _run():
  110. saved = _save()
  111. # Outside the config mutation lock: a cold first metric call costs imports + catalog loads.
  112. with _profile_scope(body.profile or profile):
  113. record_mcp_install("url" if server_config.get("url") else "local", None,
  114. "success" if saved else "failed", failure_class=None if saved else "config_rejected")
  115. if not saved:
  116. raise HTTPException(
  117. status_code=400, detail=f"Server '{name}' rejected: suspicious command/args configuration",
  118. )
  119. try:
  120. await asyncio.to_thread(_run)
  121. except HTTPException:
  122. raise
  123. except Exception as exc:
  124. _log.exception("POST /api/mcp/servers failed")
  125. raise HTTPException(status_code=400, detail=str(exc)) from exc
  126. return _mcp_server_summary(name, server_config)
  127. @router.put("/api/mcp/servers")
  128. async def replace_mcp_servers(body: MCPServersReplace, profile: Optional[str] = None):
  129. """Replace the entire ``mcp_servers`` map (the mcp.json editor's save) —
  130. the deep-merging ``/api/config`` can never delete a key or drop an
  131. ``enabled: false``, so removals wouldn't persist through it."""
  132. from hermes_cli.mcp_config import _replace_mcp_servers
  133. def _run():
  134. with config_write_scope(body.profile or profile):
  135. from tui_gateway.mcp_rpc_helpers import server_configs_with_sources
  136. _servers, plugins = server_configs_with_sources({})
  137. for name in body.servers:
  138. if plugin := plugins.get(name):
  139. return False, [f"Server '{name}' is provided by plugin '{plugin}' and cannot be modified"]
  140. return _replace_mcp_servers(body.servers)
  141. ok, issues = await asyncio.to_thread(_run)
  142. if not ok:
  143. raise HTTPException(status_code=400, detail="; ".join(issues))
  144. return {"ok": True}
  145. @router.delete("/api/mcp/servers/{name}")
  146. async def remove_mcp_server(name: str, profile: Optional[str] = None):
  147. from hermes_cli.mcp_config import _get_mcp_servers, _remove_mcp_server
  148. def _run():
  149. with config_write_scope(profile):
  150. config_servers = _get_mcp_servers()
  151. from tui_gateway.mcp_rpc_helpers import server_configs_with_sources
  152. _servers, plugins = server_configs_with_sources(config_servers)
  153. if plugin := plugins.get(name):
  154. raise HTTPException(
  155. status_code=409, detail=f"Server '{name}' is provided by plugin '{plugin}' and cannot be modified",
  156. )
  157. return _remove_mcp_server(name)
  158. if not await asyncio.to_thread(_run):
  159. raise HTTPException(status_code=404, detail=f"Server '{name}' not found")
  160. return {"ok": True}
  161. @router.post("/api/mcp/servers/{name}/test")
  162. async def test_mcp_server(name: str, profile: Optional[str] = None):
  163. """Connect to the server, list its tools, disconnect."""
  164. from hermes_cli.mcp_config import _get_mcp_servers, _oauth_tokens_present, _probe_single_server
  165. def _read():
  166. config_servers = _get_mcp_servers()
  167. from tui_gateway.mcp_rpc_helpers import server_configs_with_sources
  168. return server_configs_with_sources(config_servers)[0]
  169. servers = await asyncio.to_thread(_secret_scoped(profile, _read))
  170. if name not in servers:
  171. raise HTTPException(status_code=404, detail=f"Server '{name}' not found")
  172. details: dict[str, Any] = {}
  173. # An `auth: oauth` server that serves tools/list anonymously would probe OK
  174. # with no token — a false green. Require a token on disk, matching /auth.
  175. needs_oauth_token = servers[name].get("auth") == "oauth"
  176. def _probe():
  177. tools = _probe_single_server(name, servers[name], details=details)
  178. return tools, (_oauth_tokens_present(name) if needs_oauth_token else True)
  179. try: # probe blocks on a dedicated MCP event loop — keep it off the FastAPI loop
  180. tools, token_present = await asyncio.to_thread(_secret_scoped(profile, _probe))
  181. except Exception as exc:
  182. from hermes_cli.mcp_config import redact_mcp_probe_text
  183. return {"ok": False, "error": redact_mcp_probe_text(exc), "tools": []}
  184. if not token_present:
  185. return {"ok": False, "error": "OAuth authentication required — no token found.", "tools": []}
  186. # Optional per-tool schema size (chars) for the desktop's cost overlay;
  187. # failed probes simply omit it.
  188. schema_chars = details.get("schema_chars") or {}
  189. return {
  190. "ok": True,
  191. "tools": [
  192. {
  193. "name": t,
  194. "description": d,
  195. **({"schema_chars": schema_chars[t]} if isinstance(schema_chars.get(t), int) else {}),
  196. }
  197. for t, d in tools
  198. ],
  199. "prompts": details.get("prompts", 0),
  200. "resources": details.get("resources", 0),
  201. }
  202. @router.post("/api/mcp/servers/{name}/auth")
  203. async def auth_mcp_server(name: str, request: Request, profile: Optional[str] = None):
  204. """Start MCP OAuth and hand the authorization URL to the dashboard browser."""
  205. from hermes_cli.mcp_config import _get_mcp_servers
  206. from hermes_constants import get_hermes_home
  207. from tools.mcp_dashboard_oauth import DashboardOAuthFlow, exception_message
  208. _require_token(request)
  209. _gc_mcp_oauth_flows()
  210. def _home() -> str:
  211. return str(get_hermes_home().expanduser().resolve(strict=False))
  212. process_home = _home()
  213. def _read():
  214. with _profile_secret_scope(profile):
  215. config_servers = _get_mcp_servers()
  216. from tui_gateway.mcp_rpc_helpers import server_configs_with_sources
  217. servers, plugins = server_configs_with_sources(config_servers)
  218. return servers, plugins, _home()
  219. servers, plugins, flow_home = await asyncio.to_thread(_read)
  220. if name not in servers:
  221. raise HTTPException(status_code=404, detail=f"Server '{name}' not found")
  222. if plugin := plugins.get(name):
  223. raise HTTPException(status_code=409, detail=f"Server '{name}' is provided by plugin '{plugin}' and cannot be modified")
  224. cfg = dict(servers[name])
  225. if not cfg.get("url"):
  226. raise HTTPException(status_code=400, detail="stdio servers authenticate via env keys, not OAuth")
  227. if cfg.get("headers") and cfg.get("auth") != "oauth":
  228. raise HTTPException(status_code=400, detail="This server uses header/API-key auth, not OAuth")
  229. cfg["auth"] = "oauth"
  230. flow_id = secrets.token_urlsafe(24)
  231. flow = DashboardOAuthFlow(
  232. flow_id=flow_id,
  233. server_name=name,
  234. profile=profile,
  235. hermes_home=flow_home,
  236. redirect_uri=(cfg.get("oauth") or {}).get("redirect_uri") or _mcp_oauth_callback_url(request, name),
  237. reconnect_live=flow_home == process_home,
  238. )
  239. with _mcp_oauth_flows_lock:
  240. live = [f for f in _mcp_oauth_flows.values() if not f.worker_done]
  241. if len(live) >= _MAX_PENDING_MCP_OAUTH_FLOWS:
  242. raise HTTPException(status_code=429, detail="Too many MCP OAuth flows are already in progress")
  243. if any(f.server_name == name and f.hermes_home == flow_home for f in live):
  244. raise HTTPException(status_code=409, detail=f"MCP OAuth for '{name}' is already in progress")
  245. _mcp_oauth_flows[flow_id] = flow
  246. threading.Thread(target=_run_dashboard_mcp_oauth, args=(flow, cfg), daemon=True, name=f"mcp-oauth-{name}").start()
  247. try:
  248. await flow.wait_for_authorization_url(timeout=30)
  249. except Exception as exc:
  250. flow.mark_error(exception_message(exc))
  251. return flow.snapshot()
  252. @router.get("/api/mcp/oauth/flows/{flow_id}")
  253. async def mcp_oauth_flow_status(flow_id: str, request: Request):
  254. _require_token(request)
  255. _gc_mcp_oauth_flows()
  256. flow = _mcp_oauth_flows.get(flow_id)
  257. if flow is None:
  258. raise HTTPException(status_code=404, detail="OAuth flow not found or expired")
  259. snapshot = flow.snapshot()
  260. snapshot["tools"] = flow.tools
  261. return snapshot
  262. @router.delete("/api/mcp/oauth/flows/{flow_id}")
  263. async def cancel_mcp_oauth_flow(flow_id: str, request: Request):
  264. """Cancel an in-flight flow. mark_error unblocks the worker so it frees the
  265. per-server "already in progress" slot — otherwise a renderer that stops
  266. polling leaves the flow squatting until the 300s callback timeout and every
  267. retry 409s. Idempotent: a settled flow is left as-is."""
  268. _require_token(request)
  269. flow = _mcp_oauth_flows.get(flow_id)
  270. if flow is None: # expired/GC'd is the goal state of a cancel — not an error
  271. return {"ok": True, "status": "expired"}
  272. flow.mark_error("Cancelled by user", cancelled=True)
  273. return {"ok": True, "status": flow.snapshot()["status"]}
  274. @router.get("/api/mcp/oauth/callback/{server_name:path}")
  275. async def mcp_oauth_callback(
  276. server_name: str,
  277. code: Optional[str] = None,
  278. state: Optional[str] = None,
  279. error: Optional[str] = None,
  280. iss: Optional[str] = None,
  281. ):
  282. _gc_mcp_oauth_flows()
  283. with _mcp_oauth_flows_lock:
  284. candidates = [
  285. flow for flow in _mcp_oauth_flows.values()
  286. if flow.server_name == server_name and flow.status == "authorization_required"
  287. ]
  288. flow = next(
  289. (c for c in candidates
  290. if c.expected_state is not None and state is not None and secrets.compare_digest(c.expected_state, state)),
  291. None,
  292. )
  293. if flow is None:
  294. return HTMLResponse("<h1>OAuth flow expired</h1><p>Return to Hermes and try again.</p>", status_code=404)
  295. try:
  296. flow.deliver_callback(code=code, state=state, error=error, iss=iss)
  297. except ValueError as exc:
  298. return HTMLResponse(
  299. "<h1>OAuth callback rejected</h1><p>The callback was invalid or already used.</p>",
  300. status_code=409 if "already received" in str(exc) else 400,
  301. )
  302. if error:
  303. return HTMLResponse("<h1>Authorization failed</h1><p>Return to Hermes for details.</p>", status_code=400)
  304. return HTMLResponse("<h1>Authorization received</h1><p>You can close this tab and return to Hermes.</p>")
  305. @router.put("/api/mcp/servers/{name}/enabled")
  306. async def set_mcp_server_enabled(name: str, body: MCPEnabledToggle, profile: Optional[str] = None):
  307. """Toggle ``enabled`` (takes effect on next session/gateway); disabled
  308. servers stay in config so they can be re-enabled without re-entry."""
  309. def _run():
  310. with config_write_scope(body.profile or profile):
  311. cfg = load_config()
  312. from tui_gateway.mcp_rpc_helpers import server_configs_with_sources
  313. _servers, plugins = server_configs_with_sources(cfg.get("mcp_servers") or {})
  314. if plugin := plugins.get(name):
  315. raise HTTPException(
  316. status_code=409, detail=f"Server '{name}' is provided by plugin '{plugin}' and cannot be modified",
  317. )
  318. servers = cfg.get("mcp_servers")
  319. if not isinstance(servers, dict) or name not in servers:
  320. raise HTTPException(status_code=404, detail=f"Server '{name}' not found")
  321. if not isinstance(servers[name], dict):
  322. raise HTTPException(status_code=400, detail="Malformed server config")
  323. servers[name]["enabled"] = bool(body.enabled)
  324. save_config(cfg)
  325. return {"ok": True, "name": name, "enabled": bool(body.enabled)}
  326. return await asyncio.to_thread(_run)
  327. def _catalog_entry_json(entry: Any, installed: bool, enabled: bool) -> dict[str, Any]:
  328. auth = entry.auth
  329. transport = entry.transport
  330. install = entry.install
  331. return {
  332. "name": entry.name,
  333. "description": entry.description,
  334. "connector_slug": entry.connector_slug,
  335. "source": entry.source,
  336. "transport": transport.type,
  337. "auth_type": getattr(auth, "type", "none"),
  338. # Env vars the user must supply (names + prompts only, never values).
  339. "required_env": [
  340. {"name": e.name, "prompt": e.prompt, "required": e.required}
  341. for e in getattr(auth, "env", []) or []
  342. ],
  343. # Transport details surfaced on purpose: the trust model asks users to
  344. # inspect command/args/url + bootstrap before installing.
  345. "command": transport.command,
  346. "args": list(transport.args or []),
  347. "url": transport.url,
  348. # Git bootstrap (present only for entries that clone + build).
  349. "install_url": install.url if install else None,
  350. "install_ref": install.ref if install else None,
  351. "bootstrap": list(install.bootstrap) if install else [],
  352. "default_enabled": list(entry.tools.default_enabled) if entry.tools.default_enabled is not None else None,
  353. "post_install": entry.post_install or "",
  354. # Composer-suggestion triggers (desktop brand pills), only when the
  355. # manifest declares a `suggest` block.
  356. "suggest": {
  357. "keywords": list(entry.suggest.keywords), "hosts": list(entry.suggest.hosts),
  358. "applications": list(getattr(entry.suggest, "applications", [])),
  359. "examples": list(getattr(entry.suggest, "examples", [])),
  360. "requires_app": getattr(entry.suggest, "requires_app", False),
  361. } if entry.suggest else None,
  362. "needs_install": install is not None,
  363. "installed": installed,
  364. "enabled": enabled,
  365. }
  366. @router.get("/api/mcp/catalog")
  367. async def list_mcp_catalog(profile: Optional[str] = None):
  368. """Browse the Nous-approved MCP catalog (optional-mcps/ manifests), each
  369. entry annotated with installed/enabled state for ``profile``."""
  370. with http_failure("mcp_catalog import failed", 500, "Catalog unavailable"):
  371. from hermes_cli import mcp_catalog
  372. entries = []
  373. try:
  374. def _read():
  375. with _profile_scope(profile):
  376. catalog = list(mcp_catalog.list_catalog())
  377. state = {e.name: (mcp_catalog.is_installed(e.name), mcp_catalog.is_enabled(e.name)) for e in catalog}
  378. return catalog, state
  379. catalog_entries, installed_state = await asyncio.to_thread(_read)
  380. for entry in catalog_entries:
  381. installed, enabled = installed_state.get(entry.name, (False, False))
  382. entries.append(_catalog_entry_json(entry, installed, enabled))
  383. except HTTPException: # unknown/invalid profile → 404, not a silently-empty catalog
  384. raise
  385. except Exception:
  386. _log.exception("list_mcp_catalog failed")
  387. diagnostics = []
  388. try:
  389. diagnostics = [{"name": n, "kind": k, "message": m} for (n, k, m) in mcp_catalog.catalog_diagnostics()]
  390. except Exception:
  391. pass
  392. return {"entries": entries, "diagnostics": diagnostics}
  393. @router.post("/api/mcp/catalog/install")
  394. async def install_mcp_catalog_entry(body: MCPCatalogInstall, profile: Optional[str] = None):
  395. """Install a catalog MCP into config.yaml (declared env vars go to .env
  396. first; git-bootstrap entries run via the background CLI action path)."""
  397. from hermes_cli import mcp_catalog
  398. from hermes_cli.config import validate_env_var_name_for_write
  399. name = (body.name or "").strip()
  400. entry = mcp_catalog.get_entry(name)
  401. if entry is None:
  402. raise HTTPException(status_code=404, detail=f"No catalog entry '{name}'")
  403. # Catalog credentials are a closed schema: configuring one MCP must not
  404. # become a generic write primitive for unrelated process environment.
  405. declared_env = {spec.name for spec in (entry.auth.env or [])}
  406. undeclared_env = sorted(set(body.env) - declared_env)
  407. if undeclared_env:
  408. raise HTTPException(
  409. status_code=400,
  410. detail=f"Catalog entry '{name}' does not declare environment variable(s): {', '.join(undeclared_env)}",
  411. )
  412. # Validate the complete map before the first write so a mixed
  413. # valid+invalid request cannot partially persist credentials.
  414. try:
  415. for key in body.env:
  416. validate_env_var_name_for_write(key)
  417. except ValueError as exc:
  418. raise HTTPException(status_code=400, detail=str(exc)) from exc
  419. effective_profile = body.profile or profile
  420. # Secrets are persisted to .env here (before install_entry runs); non-secret
  421. # values ride preloaded_env into install_entry → config.yaml, so .env stays
  422. # secrets-only and nothing re-prompts on a non-TTY server.
  423. if body.env:
  424. def _write_env():
  425. with _profile_scope(effective_profile):
  426. for spec in entry.auth.env or []:
  427. value = (body.env or {}).get(spec.name)
  428. if spec.secret and value:
  429. save_env_value(spec.name, value)
  430. await asyncio.to_thread(_write_env)
  431. # Git-bootstrap entries can take a while to clone — background action so
  432. # the request returns immediately (per-entry action name, see helper).
  433. if entry.install is not None:
  434. action = _mcp_install_action_name(name)
  435. try:
  436. _spawn_hermes_action(_profile_cli_args(effective_profile) + ["mcp", "install", name], action)
  437. except HTTPException:
  438. raise
  439. except Exception as exc:
  440. raise HTTPException(status_code=500, detail=f"Install failed: {exc}")
  441. return {"ok": True, "name": name, "background": True, "action": action}
  442. # No git step — install synchronously; install_entry goes through the
  443. # call-time config/env resolvers so the profile scope covers it.
  444. try:
  445. await scoped_to_thread(
  446. effective_profile,
  447. lambda: mcp_catalog.install_entry(entry, enable=body.enable, preloaded_env=body.env or None),
  448. )
  449. except HTTPException:
  450. raise
  451. except Exception as exc:
  452. _log.exception("install_mcp_catalog_entry failed")
  453. raise HTTPException(status_code=400, detail=str(exc))
  454. return {"ok": True, "name": name, "background": False}