web_server_mcp.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. """MCP dashboard helpers: create-payload normalisation, env redaction/summary, dashboard-driven MCP OAuth worker.
  2. Wraps the same config layer the CLI uses (hermes_cli.mcp_config); stdio ``env``
  3. secrets are redacted on read.
  4. """
  5. import threading
  6. from pathlib import Path
  7. from typing import TYPE_CHECKING, Any, Dict, Optional
  8. if TYPE_CHECKING: # pragma: no cover - annotation only
  9. from tools.mcp_dashboard_oauth import DashboardOAuthFlow
  10. from hermes_cli.config import redact_key
  11. from hermes_cli.web_models import MCPServerCreate
  12. def _normalize_mcp_server_create(body: MCPServerCreate) -> tuple[str, dict[str, Any], Optional[str]]:
  13. """Validate a Dashboard MCP create request and build its safe config.
  14. The returned config never contains the Bearer token; callers persist it via
  15. the shared Bearer helper once inside the intended profile scope. Shared by
  16. the MCP page and the Profile Builder so both enforce one transport/auth contract.
  17. """
  18. from hermes_cli.mcp_config import _bearer_auth_headers, _strip_bearer_prefix
  19. from hermes_cli.mcp_security import validate_mcp_server_entry
  20. name = (body.name or "").strip()
  21. if not name:
  22. raise ValueError("Server name is required")
  23. url = (body.url or "").strip()
  24. command = (body.command or "").strip()
  25. auth = (body.auth or "none").strip().lower()
  26. bearer_token = body.bearer_token.get_secret_value() if body.bearer_token is not None else None
  27. if bool(url) == bool(command):
  28. raise ValueError("Provide exactly one of URL (HTTP/SSE) or command (stdio)")
  29. if auth not in {"none", "header", "oauth"}:
  30. raise ValueError(f"Unsupported auth mode: {auth}")
  31. server_config: dict[str, Any] = {}
  32. if url:
  33. if body.args:
  34. raise ValueError("Arguments are only supported for stdio MCP servers")
  35. if body.env:
  36. raise ValueError("Environment variables are only supported for stdio MCP servers")
  37. if auth == "header":
  38. normalized = _strip_bearer_prefix(bearer_token) if bearer_token else ""
  39. if not normalized or normalized.lower() == "bearer":
  40. raise ValueError("Bearer token is required")
  41. server_config["headers"] = _bearer_auth_headers(name)
  42. elif body.bearer_token is not None:
  43. raise ValueError("Bearer token requires header authentication")
  44. server_config["url"] = url
  45. if auth == "oauth":
  46. server_config["auth"] = "oauth"
  47. else:
  48. if auth != "none" or body.bearer_token is not None:
  49. raise ValueError("HTTP authentication is not supported for stdio MCP servers")
  50. server_config["command"] = command
  51. if body.args:
  52. server_config["args"] = list(body.args)
  53. if body.env:
  54. server_config["env"] = dict(body.env)
  55. issues = validate_mcp_server_entry(name, server_config)
  56. if issues:
  57. raise ValueError(f"Server '{name}' rejected: {'; '.join(issues)}")
  58. return name, server_config, bearer_token
  59. def _redact_mcp_env(env: dict[str, Any]) -> dict[str, str]:
  60. """Mask secret-shaped MCP env values for read responses."""
  61. out: dict[str, str] = {}
  62. for k, v in (env or {}).items():
  63. try:
  64. out[str(k)] = redact_key(str(v)) if v else ""
  65. except Exception:
  66. out[str(k)] = "***"
  67. return out
  68. def _mcp_server_summary(name: str, cfg: dict[str, Any], plugin: str | None = None) -> dict[str, Any]:
  69. from tools.mcp_tool_common import mcp_server_enabled
  70. transport = "http" if cfg.get("url") else ("stdio" if cfg.get("command") else "unknown")
  71. auth = cfg.get("auth")
  72. headers = cfg.get("headers") or {}
  73. if not auth and isinstance(headers, dict) and any(str(key).lower() == "authorization" for key in headers):
  74. auth = "header"
  75. return {
  76. "name": name,
  77. "transport": transport,
  78. "url": cfg.get("url"),
  79. "command": cfg.get("command"),
  80. "args": list(cfg.get("args") or []),
  81. "env": _redact_mcp_env(cfg.get("env") or {}),
  82. "auth": auth,
  83. "enabled": mcp_server_enabled(cfg),
  84. # Tool selection: list of enabled tool names, or None = all.
  85. "tools": cfg.get("tools"),
  86. "source": "plugin" if plugin is not None else "config",
  87. "plugin": plugin,
  88. }
  89. _mcp_oauth_flows: "dict[str, DashboardOAuthFlow]" = {}
  90. _mcp_oauth_transactions: dict[tuple[str, str], threading.Lock] = {}
  91. _mcp_oauth_transactions_lock = threading.Lock()
  92. def _mcp_oauth_transaction(flow) -> threading.Lock:
  93. key = (flow.hermes_home, flow.server_name)
  94. with _mcp_oauth_transactions_lock:
  95. return _mcp_oauth_transactions.setdefault(key, threading.Lock())
  96. def _run_dashboard_mcp_oauth(flow, cfg: dict) -> None:
  97. """Run the normal MCP probe with dashboard redirect/callback handlers."""
  98. from hermes_cli.mcp_config import _oauth_tokens_present, _probe_single_server, _save_mcp_server
  99. try:
  100. from agent.secret_scope import build_profile_secret_scope, reset_secret_scope, set_secret_scope
  101. from hermes_constants import reset_hermes_home_override, set_hermes_home_override
  102. from tools.mcp_dashboard_oauth import dashboard_oauth_flow
  103. from tools.mcp_oauth import HermesTokenStorage, force_interactive_oauth, login_connect_timeout
  104. from tools.mcp_oauth_manager import get_manager
  105. home_token = secret_token = None
  106. try:
  107. home_token = set_hermes_home_override(flow.hermes_home)
  108. secret_token = set_secret_scope(
  109. build_profile_secret_scope(Path(flow.hermes_home)), profile_home=flow.hermes_home)
  110. transaction = _mcp_oauth_transaction(flow)
  111. with transaction, force_interactive_oauth(), dashboard_oauth_flow(flow):
  112. manager = get_manager()
  113. storage = HermesTokenStorage(flow.server_name)
  114. backup = storage.snapshot()
  115. previous_entry = None
  116. try:
  117. previous_entry = manager.remove(flow.server_name, hermes_home=flow.hermes_home)
  118. tools = _probe_single_server(
  119. flow.server_name, cfg, connect_timeout=login_connect_timeout(cfg)
  120. )
  121. if not _oauth_tokens_present(flow.server_name):
  122. raise RuntimeError(
  123. "The server responded, but no OAuth token was obtained — "
  124. "this provider may require a manually-registered OAuth client."
  125. )
  126. _save_mcp_server(flow.server_name, cfg)
  127. flow.tools = [{"name": t, "description": d} for t, d in tools]
  128. flow.mark_approved()
  129. if flow.reconnect_live:
  130. from tools.mcp_tool_loop import reconnect_mcp_server
  131. reconnect_mcp_server(flow.server_name)
  132. except Exception:
  133. storage.restore(backup, only_if_absent=True)
  134. manager.restore_entry(flow.server_name, previous_entry, hermes_home=flow.hermes_home)
  135. raise
  136. finally:
  137. if secret_token is not None:
  138. reset_secret_scope(secret_token)
  139. if home_token is not None:
  140. reset_hermes_home_override(home_token)
  141. except Exception as exc:
  142. from tools.mcp_dashboard_oauth import exception_message
  143. msg = exception_message(exc)
  144. # Providers gating RFC 7591 registration to pre-approved clients 403 the
  145. # register call before any auth URL exists; say so, not "403 Forbidden".
  146. try:
  147. from tools.mcp_oauth import humanize_oauth_registration_error
  148. humanized = humanize_oauth_registration_error(
  149. flow.server_name, exc, server_url=cfg.get("url") if isinstance(cfg, dict) else None
  150. )
  151. if humanized:
  152. msg = humanized
  153. except Exception:
  154. pass
  155. flow.mark_error(msg)
  156. finally:
  157. flow.mark_worker_done()