mcp_config.py 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175
  1. """MCP Server Management CLI — ``hermes mcp`` subcommand."""
  2. import asyncio
  3. import contextlib
  4. import logging
  5. import os
  6. import re
  7. import time
  8. from typing import Any, Dict, List, Optional, Tuple
  9. from hermes_cli.config import (
  10. cfg_get,
  11. load_config,
  12. save_config,
  13. get_env_value,
  14. save_env_value,
  15. get_hermes_home,
  16. )
  17. from hermes_cli.colors import Colors, color
  18. from hermes_constants import display_hermes_home
  19. from hermes_cli.mcp_security import validate_mcp_server_entry
  20. from tools.mcp_tool_config import _ENV_VAR_PATTERN
  21. from tools.mcp_tool_common import _env_ref_name, mcp_server_enabled
  22. logger = logging.getLogger(__name__)
  23. _ENV_VAR_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
  24. # MCP test/dashboard surfaces must not fingerprint credential header values
  25. # (firstN/lastN is a reusable fragment). Redact by field identity: once a
  26. # recognized credential header key is found, replace its complete associated
  27. # value regardless of scheme, quoting, parameter order, or wire/JSON/Python
  28. # mapping serialization. Header names come from agent.redact so the lists
  29. # cannot drift. The generic redactor then runs with force=True.
  30. _AUTH_SCHEME_PREFIX_RE = re.compile(
  31. r"^(?:Bearer|Basic|Token|Digest)\s+",
  32. re.IGNORECASE,
  33. )
  34. _DIGEST_PARAM_NAMES = (
  35. "username|response|opaque|cnonce|nonce|uri|realm|qop|nc|algorithm"
  36. )
  37. _DIGEST_PARAM = (
  38. rf"(?:{_DIGEST_PARAM_NAMES})\s*=\s*(?:\"[^\"]*\"|'[^']*'|[^\s,]+)"
  39. )
  40. _DIGEST_PARAMS = rf"{_DIGEST_PARAM}(?:\s*,\s*{_DIGEST_PARAM})*"
  41. _PROBE_REDACTION_RES: Optional[tuple[re.Pattern[str], ...]] = None
  42. def _credential_header_names() -> str:
  43. from agent.redact import _SECRET_HEADER_NAMES
  44. return rf"(?:(?:Proxy-)?Authorization|{_SECRET_HEADER_NAMES})"
  45. def _probe_redaction_res() -> tuple[re.Pattern[str], ...]:
  46. global _PROBE_REDACTION_RES
  47. if _PROBE_REDACTION_RES is not None:
  48. return _PROBE_REDACTION_RES
  49. header = _credential_header_names()
  50. # Quoted-key mapping/JSON: {'X-Api-Key': '…'} / {"Authorization": "…"}
  51. mapping = re.compile(
  52. rf"""(['\"])({header})\1(\s*:\s*)(['\"])((?:\\.|(?!\4).)*)\4""",
  53. re.IGNORECASE,
  54. )
  55. unquoted_mapping = re.compile(
  56. rf"""(['\"])({header})\1(\s*:\s*)(?!['\"])([^\s,}}\]]+)""",
  57. re.IGNORECASE,
  58. )
  59. # Bare wire header: Authorization: Digest … / X-Api-Key: token
  60. wire = re.compile(
  61. rf"({header})(\s*:\s*)([^\n\r]+)",
  62. re.IGNORECASE,
  63. )
  64. bare_scheme = re.compile(
  65. rf"\b(Bearer|Basic|Token)(\s+)([^\s\"']+)"
  66. rf"|\b(Digest)(\s+)({_DIGEST_PARAMS})",
  67. re.IGNORECASE,
  68. )
  69. _PROBE_REDACTION_RES = (mapping, unquoted_mapping, wire, bare_scheme)
  70. return _PROBE_REDACTION_RES
  71. def _mask_header_field_value(value: str) -> str:
  72. """Replace a credential header's complete associated value with ``***``.
  73. A leading auth scheme word is kept for debugging; Digest parameters are
  74. part of the field value and are not tokenized.
  75. """
  76. scheme = _AUTH_SCHEME_PREFIX_RE.match(value)
  77. if scheme:
  78. return f"{scheme.group(0)}***"
  79. return "***"
  80. def _sub_mapping_header(match: re.Match[str]) -> str:
  81. return (
  82. f"{match.group(1)}{match.group(2)}{match.group(1)}"
  83. f"{match.group(3)}{match.group(4)}"
  84. f"{_mask_header_field_value(match.group(5))}{match.group(4)}"
  85. )
  86. def _sub_unquoted_mapping_header(match: re.Match[str]) -> str:
  87. return (
  88. f"{match.group(1)}{match.group(2)}{match.group(1)}"
  89. f"{match.group(3)}{_mask_header_field_value(match.group(4))}"
  90. )
  91. def _sub_wire_header(match: re.Match[str]) -> str:
  92. return f"{match.group(1)}{match.group(2)}{_mask_header_field_value(match.group(3))}"
  93. def _sub_bare_scheme(match: re.Match[str]) -> str:
  94. if match.group(1):
  95. return f"{match.group(1)}{match.group(2)}***"
  96. return f"{match.group(4)}{match.group(5)}***"
  97. def redact_mcp_probe_text(text: object) -> str:
  98. """Fully redact MCP probe/display strings before they leave the process.
  99. Recognized credential header fields (Authorization / Proxy-Authorization
  100. and ``agent.redact._SECRET_HEADER_NAMES``) have their complete associated
  101. value replaced with ``***``. Bare Bearer/Basic/Token/Digest spans are
  102. covered the same way. The generic secret redactor then runs with
  103. ``force=True`` as defense in depth.
  104. """
  105. raw = "" if text is None else str(text)
  106. if not raw:
  107. return raw
  108. mapping, unquoted_mapping, wire, bare_scheme = _probe_redaction_res()
  109. redacted = mapping.sub(_sub_mapping_header, raw)
  110. redacted = unquoted_mapping.sub(_sub_unquoted_mapping_header, redacted)
  111. redacted = wire.sub(_sub_wire_header, redacted)
  112. redacted = bare_scheme.sub(_sub_bare_scheme, redacted)
  113. from agent.redact import redact_sensitive_text
  114. return redact_sensitive_text(redacted, force=True)
  115. def _header_value_is_only_env_refs(value: str) -> bool:
  116. """True when every non-scheme span in *value* is a ``${VAR}`` reference."""
  117. leftover = _ENV_VAR_PATTERN.sub("", value)
  118. leftover = _AUTH_SCHEME_PREFIX_RE.sub("", leftover)
  119. return leftover.strip(" \t;,") == ""
  120. def redact_mcp_header_display(name: str, value: object) -> str:
  121. """Fail-closed CLI display for a credential-shaped MCP header.
  122. A value that is only ``${ENV}`` references (optionally with an auth scheme
  123. word) may be shown — it carries no secret. Anything else, including opaque
  124. API keys and mixed template+literal strings, is replaced with ``***``.
  125. ``name`` stays paired with the value so callers cannot drop the header
  126. identity before this policy runs.
  127. """
  128. raw = "" if value is None else str(value)
  129. if raw and _header_value_is_only_env_refs(raw):
  130. return raw
  131. # Pair name+value for the generic redactor, then still fail closed — an
  132. # opaque token with no recognized scheme must not print.
  133. redact_mcp_probe_text(f"{name}: {raw}")
  134. return "***"
  135. def _redact_probe_exception(exc: BaseException) -> Exception:
  136. """Return a raise-able exception whose ``str()`` is safe to print."""
  137. root = _unwrap_exception_group(exc)
  138. safe = redact_mcp_probe_text(root)
  139. if safe == str(root) and isinstance(root, Exception):
  140. return root
  141. try:
  142. rebuilt = type(root)(safe)
  143. if str(rebuilt) == safe and isinstance(rebuilt, Exception):
  144. return rebuilt
  145. except Exception:
  146. pass
  147. return RuntimeError(safe)
  148. _MCP_PRESETS: dict[str, dict[str, Any]] = {
  149. "codex": {"command": "codex", "args": ["mcp-server"]},
  150. }
  151. def _info(text: str): print(color(f" {text}", Colors.DIM))
  152. def _success(text: str): print(color(f" ✓ {text}", Colors.GREEN))
  153. def _warning(text: str): print(color(f" ⚠ {text}", Colors.YELLOW))
  154. def _error(text: str): print(color(f" ✗ {text}", Colors.RED))
  155. def _confirm(question: str, default: bool = True) -> bool:
  156. default_str = "Y/n" if default else "y/N"
  157. try:
  158. val = input(color(f" {question} [{default_str}]: ", Colors.YELLOW)).strip().lower()
  159. except (KeyboardInterrupt, EOFError):
  160. print()
  161. return default
  162. return val in {"y", "yes"} if val else default
  163. def _print_tools(tools: list[tuple[str, str]], width: int, desc_max: int) -> None:
  164. for tool_name, desc in tools:
  165. short = desc[:desc_max] + "..." if len(desc) > desc_max else desc
  166. print(f" {color(tool_name, Colors.GREEN):{width}s} {short}")
  167. def _get_mcp_servers(config: Optional[dict] = None) -> dict[str, dict]:
  168. """Return the ``mcp_servers`` dict from config, or empty dict."""
  169. if config is None:
  170. config = load_config()
  171. servers = config.get("mcp_servers")
  172. return servers if servers and isinstance(servers, dict) else {}
  173. def _tool_filters(cfg: dict) -> tuple[Optional[list], Optional[list]]:
  174. """Return the ``(include, exclude)`` tool lists from a server config; ``None`` = key absent.
  175. An explicit ``include: []`` is a real (block-all) whitelist — the runtime registers nothing
  176. (tools/mcp_tool_registration.py) — so it must not collapse to "no filter" here (#12865).
  177. """
  178. tools_cfg = cfg.get("tools", {})
  179. if not isinstance(tools_cfg, dict):
  180. return None, None
  181. include, exclude = tools_cfg.get("include"), tools_cfg.get("exclude")
  182. return (
  183. include if isinstance(include, list) else None,
  184. exclude if isinstance(exclude, list) else None)
  185. def _save_mcp_server(name: str, server_config: dict, *, literal_paths: Optional[set[tuple[str, ...]]] = None) -> bool:
  186. """Add or update a server entry in config.yaml.
  187. Returns False when a high-signal exfiltration-shaped stdio command is rejected (shell+egress
  188. payloads are blocked rather than whitelisting command families).
  189. """
  190. if literal_paths and any(path[:2] != ("mcp_servers", name) for path in literal_paths):
  191. raise ValueError("Literal paths must belong to the MCP server being saved")
  192. if not _validate_or_warn(name, server_config):
  193. return False
  194. config = load_config()
  195. config.setdefault("mcp_servers", {})[name] = server_config
  196. if literal_paths:
  197. save_config(config, mcp_literal_paths=literal_paths)
  198. else:
  199. save_config(config)
  200. return True
  201. def _validate_or_warn(name: str, server_config: dict) -> bool:
  202. """Print every suspicious-config issue as a warning; True when the entry is clean."""
  203. issues = validate_mcp_server_entry(name, server_config)
  204. for issue in issues:
  205. _warning(issue)
  206. if issues:
  207. _warning(f"Server '{name}' was NOT saved due to suspicious configuration.")
  208. return not issues
  209. def _lookup_server(
  210. name: str, servers: dict[str, dict], available_label: str = "Available servers"
  211. ) -> Optional[dict]:
  212. """Return the named server config, or print the not-found hint and return None."""
  213. if name in servers:
  214. return servers[name]
  215. _error(f"Server '{name}' not found in config.")
  216. if servers:
  217. _info(f"{available_label}: {', '.join(servers)}")
  218. return None
  219. def _remove_mcp_server(name: str) -> bool:
  220. """Remove a server from config.yaml. Returns True if it existed."""
  221. config = load_config()
  222. servers = config.get("mcp_servers") or {}
  223. if name not in servers:
  224. return False
  225. del servers[name]
  226. if not servers:
  227. config.pop("mcp_servers", None)
  228. save_config(config)
  229. return True
  230. def _replace_mcp_servers(servers: dict[str, dict]) -> tuple[bool, list[str]]:
  231. """Replace the WHOLE ``mcp_servers`` map in config.yaml.
  232. Every entry is validated up front; any suspicious entry rejects the whole save (``(False,
  233. issues)``) so a bad paste can't be partially applied. An empty map removes the key entirely.
  234. """
  235. issues: list[str] = []
  236. for name, cfg in servers.items():
  237. if not isinstance(cfg, dict):
  238. issues.append(f"Server '{name}': expected an object")
  239. continue
  240. issues.extend(validate_mcp_server_entry(name, cfg))
  241. if issues:
  242. return False, issues
  243. config = load_config()
  244. if servers:
  245. config["mcp_servers"] = dict(servers)
  246. else:
  247. config.pop("mcp_servers", None)
  248. save_config(config)
  249. return True, []
  250. def _env_key_for_server(name: str) -> str:
  251. """Convert server name to an env-var key like ``MCP_MYSERVER_API_KEY``."""
  252. suffix = re.sub(r"[^A-Za-z0-9_]", "_", name.upper()).strip("_")
  253. return f"MCP_{suffix}_API_KEY"
  254. def _strip_bearer_prefix(token: str) -> str:
  255. """Strip a leading ``Bearer `` from a pasted token.
  256. The header template already stores ``Authorization: Bearer ${MCP_X_API_KEY}``; a token pasted
  257. with its own prefix would send ``Bearer Bearer <jwt>`` and get a 401.
  258. Normalize on save. (#37792)
  259. """
  260. if not isinstance(token, str):
  261. return token
  262. stripped = token.strip()
  263. if stripped[:7].lower() == "bearer ":
  264. return stripped[7:].strip()
  265. return stripped
  266. def _bearer_auth_headers(name: str) -> dict[str, str]:
  267. """Build the persisted Authorization header template for a named MCP server.
  268. The secret lives in the profile's ``.env``; CLI and Dashboard share this so they produce
  269. byte-equivalent config.
  270. """
  271. return {"Authorization": f"Bearer ${{{_env_key_for_server(name)}}}"}
  272. def _save_bearer_auth_token(name: str, token: str) -> dict[str, str]:
  273. """Persist a normalized Bearer token to ``.env`` and return the header template for config.yaml."""
  274. normalized = _strip_bearer_prefix(token)
  275. if not normalized or normalized.lower() == "bearer":
  276. raise ValueError("Bearer token is required")
  277. save_env_value(_env_key_for_server(name), normalized)
  278. return _bearer_auth_headers(name)
  279. def _parse_env_assignments(raw_env: Optional[list[str]]) -> dict[str, str]:
  280. """Parse ``KEY=VALUE`` strings from CLI args into an env dict."""
  281. parsed: dict[str, str] = {}
  282. for item in raw_env or []:
  283. text = str(item or "").strip()
  284. if not text:
  285. continue
  286. if "=" not in text:
  287. raise ValueError(f"Invalid --env value '{text}' (expected KEY=VALUE)")
  288. key, value = text.split("=", 1)
  289. key = key.strip()
  290. if not key:
  291. raise ValueError(f"Invalid --env value '{text}' (missing variable name)")
  292. if not _ENV_VAR_NAME_RE.match(key):
  293. raise ValueError(f"Invalid --env variable name '{key}'")
  294. parsed[key] = value
  295. return parsed
  296. def _apply_mcp_preset(
  297. name: str,
  298. *,
  299. preset_name: Optional[str],
  300. url: Optional[str],
  301. command: Optional[str],
  302. cmd_args: list[str],
  303. server_config: dict[str, Any]) -> tuple[Optional[str], Optional[str], list[str], bool]:
  304. """Apply a known MCP preset when transport details were omitted."""
  305. if not preset_name:
  306. return url, command, cmd_args, False
  307. preset = _MCP_PRESETS.get(preset_name)
  308. if not preset:
  309. raise ValueError(f"Unknown MCP preset: {preset_name}")
  310. if url or command:
  311. return url, command, cmd_args, False
  312. url, command = preset.get("url"), preset.get("command")
  313. cmd_args = list(preset.get("args") or [])
  314. if url:
  315. server_config["url"] = url
  316. if command:
  317. server_config["command"] = command
  318. if cmd_args:
  319. server_config["args"] = cmd_args
  320. return url, command, cmd_args, True
  321. def _resolve_mcp_server_config(config: dict) -> dict:
  322. """Resolve ``${ENV}`` placeholders in a server config before connecting.
  323. Mirrors ``_load_mcp_config()`` in ``tools/mcp_tool.py``; without it the discovery probe sent
  324. literal placeholders in header templates and auth-requiring servers returned 401.
  325. Mirrors ``_load_mcp_config()`` in ``tools/mcp_tool.py``: load ``~/.hermes/.env`` into ``os.environ`` and
  326. recursively interpolate any ``${VAR}`` placeholders. The CLI builds header templates like
  327. ``Authorization: Bearer ${MCP_X_API_KEY}`` but the probe path never resolved them, so the discovery
  328. probe sent the literal placeholder and auth-requiring servers (e.g. n8n) returned 401 — while runtime
  329. tool loading worked because it interpolates. (#37792)
  330. """
  331. from tools.mcp_tool_config import _interpolate_env_vars
  332. from agent.secret_scope import current_secret_scope
  333. if current_secret_scope() is None:
  334. try:
  335. from hermes_cli.env_loader import load_hermes_dotenv
  336. load_hermes_dotenv()
  337. except Exception: # pragma: no cover — defensive
  338. pass
  339. return _interpolate_env_vars(config)
  340. def _probe_single_server(
  341. name: str, config: dict, connect_timeout: Optional[float] = None, *, details: Optional[dict] = None
  342. ) -> list[tuple[str, str]]:
  343. """Temporarily connect to one MCP server, list its tools, disconnect.
  344. Returns ``(tool_name, description)`` tuples; raises on connection failure. ``details`` is an
  345. out-param filled with ``schema_chars``/``prompts``/``resources`` so the return shape stays stable.
  346. """
  347. issues = validate_mcp_server_entry(name, config)
  348. if issues:
  349. rejected = ValueError("; ".join(issues))
  350. rejected.failure_class = "config_rejected" # type: ignore[attr-defined]
  351. raise rejected
  352. from tools.mcp_tool_loop import _ensure_mcp_loop, _run_on_mcp_loop
  353. from tools.mcp_tool_discovery import _connect_server
  354. from tools.mcp_tool_lifecycle import _stop_mcp_loop_if_idle
  355. from tools.mcp_tool_common import _parse_boolish
  356. config = _resolve_mcp_server_config(config)
  357. if connect_timeout is None:
  358. try:
  359. connect_timeout = max(1.0, float(config.get("connect_timeout", 30)))
  360. except (TypeError, ValueError):
  361. connect_timeout = 30.0
  362. # Deep transport code (tools/mcp_tool_transport.py::_negotiate_session) reads its OWN
  363. # session.initialize() bound straight off config["connect_timeout"], independent of the
  364. # `connect_timeout` param above. Callers that extend the param to give a user time to finish
  365. # an OAuth browser flow (e.g. `hermes mcp login`'s 315s) left that inner bound at the
  366. # (unrelated) 60s default, so the still-pending OAuth callback wait got cancelled mid-flow —
  367. # surfacing as a retry that re-opens a second authorization against the same callback port.
  368. config["connect_timeout"] = connect_timeout
  369. _ensure_mcp_loop()
  370. tools_found: list[tuple[str, str]] = []
  371. async def _probe():
  372. from tools import mcp_tool as _core
  373. claimed = []
  374. claim_token = _core._connect_server_claim.set(claimed.append)
  375. if details is not None:
  376. details["initialized"] = False
  377. try:
  378. server = await asyncio.wait_for(_connect_server(name, config), timeout=connect_timeout)
  379. except TimeoutError:
  380. # str(TimeoutError()) is '' — printed verbatim it was a blank "Authentication failed:".
  381. raise TimeoutError(
  382. f"Connecting to MCP server '{name}' timed out after {float(connect_timeout):.0f}s "
  383. "(bounded by connect_timeout; an OAuth login also by oauth.timeout)"
  384. ) from None
  385. finally:
  386. _core._connect_server_claim.reset(claim_token)
  387. if details is not None and claimed:
  388. details["initialized"] = claimed[0].initialize_result is not None
  389. try:
  390. for t in server._tools:
  391. desc = getattr(t, "description", "") or ""
  392. if len(desc) > 80:
  393. desc = desc[:77] + "..."
  394. tools_found.append((t.name, desc))
  395. if details is not None:
  396. # Per-tool registry-schema sizes (the SAME converted schema the agent registers) so
  397. # the desktop can estimate per-call token cost. Best-effort, absent on failure.
  398. try:
  399. import json as _json
  400. from tools.mcp_tool_schema import _convert_mcp_schema
  401. details["schema_chars"] = {
  402. t.name: len(_json.dumps(_convert_mcp_schema(name, t), separators=(",", ":"), default=str))
  403. for t in server._tools
  404. }
  405. except Exception: # pragma: no cover — display-only extra
  406. pass
  407. # Gate capability probes like runtime registration (_select_utility_schemas):
  408. # honour tools.prompts / tools.resources config AND only call a family the server
  409. # advertises — some servers hard-error on unknown prompts/list.
  410. tools_filter = config.get("tools") or {}
  411. advertised_caps = getattr(getattr(server, "initialize_result", None), "capabilities", None)
  412. def _wanted(cap: str) -> bool:
  413. # No capability info captured (legacy fixtures / older servers) => always try.
  414. if not _parse_boolish(tools_filter.get(cap), default=True):
  415. return False
  416. return advertised_caps is None or getattr(advertised_caps, cap, None) is not None
  417. # Best-effort: servers without the capability raise, which just means "0".
  418. if _wanted("prompts"):
  419. try:
  420. details["prompts"] = len((await server.session.list_prompts()).prompts)
  421. except Exception:
  422. pass
  423. if _wanted("resources"):
  424. try:
  425. details["resources"] = len((await server.session.list_resources()).resources)
  426. except Exception:
  427. pass
  428. finally:
  429. await server.shutdown()
  430. try:
  431. _run_on_mcp_loop(_probe(), timeout=connect_timeout + 10)
  432. except BaseException as exc:
  433. redacted = _redact_probe_exception(exc)
  434. # Classified from the ORIGINAL exception: redaction may rebuild it as a RuntimeError.
  435. with contextlib.suppress(Exception):
  436. redacted.failure_class = probe_failure_class(exc) # type: ignore[attr-defined]
  437. raise redacted from None
  438. finally:
  439. _stop_mcp_loop_if_idle()
  440. return tools_found
  441. def _oauth_tokens_present(name: str) -> bool:
  442. """True if an OAuth token file exists for ``name`` (a clean probe alone is not proof of auth)."""
  443. try:
  444. from tools.mcp_oauth import HermesTokenStorage
  445. return HermesTokenStorage(name).has_cached_tokens()
  446. except Exception as exc: # pragma: no cover — defensive
  447. logger.debug("Could not check OAuth tokens for '%s': %s", name, exc)
  448. return True # permissive: don't block a real success
  449. def _unwrap_exception_group(exc: BaseException) -> Exception:
  450. """Extract the root cause from anyio ``ExceptionGroup`` wrappers so e.g. "401 Unauthorized" surfaces."""
  451. while isinstance(exc, BaseExceptionGroup) and exc.exceptions:
  452. exc = exc.exceptions[0]
  453. return exc if isinstance(exc, Exception) else RuntimeError(str(exc))
  454. def _configure_http_auth(
  455. name: str, url: str, auth_type: Optional[str], server_config: dict[str, Any]
  456. ) -> bool:
  457. """OAuth or Bearer-token setup for an HTTP server. False when the user cancelled."""
  458. print()
  459. if auth_type == "oauth":
  460. _info(f"Starting OAuth flow for '{name}'...")
  461. oauth_ok = False
  462. try:
  463. from tools.mcp_oauth_manager import get_manager
  464. if get_manager().get_or_build_provider(name, url, server_config.get("oauth")):
  465. server_config["auth"] = "oauth"
  466. _success("OAuth configured (tokens will be acquired on first connection)")
  467. oauth_ok = True
  468. else:
  469. _warning("OAuth setup failed — MCP SDK auth module not available")
  470. except Exception as exc:
  471. _warning(f"OAuth error: {exc}")
  472. if not oauth_ok:
  473. _info("This server may not support OAuth.")
  474. if not _confirm("Continue without authentication?", default=True):
  475. _info("Cancelled.")
  476. return False
  477. return True
  478. _info(f"Connecting to {url}")
  479. needs_auth = _confirm("Does this server require authentication?", default=True)
  480. if needs_auth and (auth_type == "header" or not auth_type):
  481. env_key = _env_key_for_server(name)
  482. if get_env_value(env_key):
  483. _success(f"{env_key}: already configured")
  484. server_config["headers"] = _bearer_auth_headers(name)
  485. else:
  486. from hermes_cli.cli_output import prompt
  487. api_key = prompt("API key / Bearer token", default="", password=True)
  488. if api_key:
  489. server_config["headers"] = _save_bearer_auth_token(name, api_key)
  490. _success(f"Saved to {display_hermes_home()}/.env as {env_key}")
  491. return True
  492. def _choose_tools(name: str, tools: list[tuple[str, str]], server_config: dict[str, Any]) -> Optional[int]:
  493. """Ask enable-all / select / cancel; returns the enabled-tool count or None when cancelled."""
  494. print()
  495. _success(f"Connected! Found {len(tools)} tool(s) from '{name}':")
  496. print()
  497. _print_tools(tools, 40, 60)
  498. print()
  499. try:
  500. choice = input(
  501. color(f" Enable all {len(tools)} tools? [Y/n/select]: ", Colors.YELLOW)
  502. ).strip().lower()
  503. except (KeyboardInterrupt, EOFError):
  504. print()
  505. _info("Cancelled.")
  506. return None
  507. if choice in {"n", "no"}:
  508. _info("Cancelled — server not saved.")
  509. return None
  510. if choice not in {"s", "select"}:
  511. return len(tools)
  512. from hermes_cli.curses_ui import curses_checklist
  513. labels = [f"{t[0]} — {t[1]}" for t in tools]
  514. chosen = curses_checklist(f"Select tools for '{name}'", labels, set(range(len(tools))))
  515. if not chosen:
  516. _info("No tools selected — server not saved.")
  517. return None
  518. chosen_names = [tools[i][0] for i in sorted(chosen)]
  519. server_config.setdefault("tools", {})["include"] = chosen_names
  520. return len(chosen_names)
  521. def cmd_mcp_add(args):
  522. """Add a new MCP server with discovery-first tool selection."""
  523. name = args.name
  524. url = getattr(args, "url", None)
  525. # --command uses dest="mcp_command" (see hermes_cli/main.py for why the dest is renamed).
  526. command = getattr(args, "mcp_command", None)
  527. cmd_args = getattr(args, "args", None) or []
  528. if cmd_args and cmd_args[0] == "--":
  529. cmd_args = cmd_args[1:]
  530. auth_type = getattr(args, "auth", None)
  531. raw_connect_timeout = getattr(args, "connect_timeout", None)
  532. server_config: dict[str, Any] = {}
  533. try:
  534. explicit_env = _parse_env_assignments(getattr(args, "env", None))
  535. url, command, cmd_args, _preset_applied = _apply_mcp_preset(
  536. name, preset_name=getattr(args, "preset", None), url=url, command=command,
  537. cmd_args=list(cmd_args), server_config=server_config)
  538. except ValueError as exc:
  539. _error(str(exc))
  540. return
  541. if url and explicit_env:
  542. _error("--env is only supported for stdio MCP servers (--command or stdio presets)")
  543. return
  544. if not url and not command:
  545. _error("Must specify --url <endpoint>, --command <cmd>, or --preset <name>")
  546. _info("Examples:")
  547. _info(' hermes mcp add ink --url "https://mcp.ml.ink/mcp"')
  548. _info(' hermes mcp add github --command npx --args @modelcontextprotocol/server-github')
  549. _info(' hermes mcp add myserver --preset mypreset')
  550. return
  551. # Overwriting an existing server is a re-add, not an install; cancels are not recorded either.
  552. fresh = name not in _get_mcp_servers()
  553. if not fresh and not _confirm(
  554. f"Server '{name}' already exists. Overwrite?", default=False
  555. ):
  556. _info("Cancelled.")
  557. return
  558. def _record(saved: bool, failure_class: str = "config_rejected") -> None:
  559. # A save only fails on a suspicious configuration (_save_mcp_server returns False).
  560. if fresh:
  561. from hermes_cli.mcp_catalog import record_mcp_install
  562. record_mcp_install("url" if url else "local", None, "success" if saved else "failed",
  563. failure_class=None if saved else failure_class)
  564. if url:
  565. server_config["url"] = url
  566. else:
  567. server_config["command"] = command
  568. if cmd_args:
  569. server_config["args"] = cmd_args
  570. if explicit_env:
  571. server_config["env"] = explicit_env
  572. if raw_connect_timeout is not None:
  573. server_config["connect_timeout"] = raw_connect_timeout
  574. if not _validate_or_warn(name, server_config):
  575. _record(False)
  576. return
  577. if url and not _configure_http_auth(name, url, auth_type, server_config):
  578. return
  579. print()
  580. print(color(f" Connecting to '{name}'...", Colors.CYAN))
  581. try:
  582. tools = _probe_single_server(name, server_config)
  583. except Exception as exc:
  584. _error(f"Failed to connect: {_probe_failure_reason(exc)}")
  585. _info(_probe_failure_next_step(name, exc))
  586. saved = False
  587. if _confirm("Save config anyway (you can test later)?", default=False):
  588. server_config["enabled"] = False
  589. saved = _save_mcp_server(name, server_config)
  590. if saved:
  591. _success(f"Saved '{name}' to config (disabled)")
  592. _info("Fix the issue, then: hermes mcp test " + name)
  593. _record(saved, probe_failure_class(exc))
  594. return
  595. if not tools:
  596. _warning("Server connected but reported no tools.")
  597. if _confirm("Save config anyway?", default=True):
  598. saved = _save_mcp_server(name, server_config)
  599. _record(saved)
  600. if saved:
  601. _success(f"Saved '{name}' to config")
  602. return
  603. tool_count = _choose_tools(name, tools, server_config)
  604. if tool_count is None:
  605. return
  606. server_config["enabled"] = True
  607. saved = _save_mcp_server(name, server_config)
  608. _record(saved)
  609. if saved:
  610. print()
  611. _success(
  612. f"Saved '{name}' to {display_hermes_home()}/config.yaml ({tool_count}/{len(tools)} tools enabled)"
  613. )
  614. _info("Start a new session to use these tools, or run /reload-mcp to load them into open sessions.")
  615. def cmd_mcp_remove(args):
  616. """Remove an MCP server from config."""
  617. name = args.name
  618. if _lookup_server(name, _get_mcp_servers()) is None:
  619. return
  620. if not _confirm(f"Remove server '{name}'?", default=True):
  621. _info("Cancelled.")
  622. return
  623. _remove_mcp_server(name)
  624. _success(f"Removed '{name}' from config")
  625. # Route OAuth cleanup through MCPOAuthManager so any provider cached in this process (e.g. from
  626. # an earlier `hermes mcp test`) is evicted too.
  627. try:
  628. from tools.mcp_oauth_manager import get_manager
  629. get_manager().remove(name)
  630. _success("Cleaned up OAuth tokens")
  631. except Exception:
  632. pass
  633. def cmd_mcp_list(args=None):
  634. """List all configured MCP servers."""
  635. servers = _get_mcp_servers()
  636. if not servers:
  637. print()
  638. _info("No MCP servers configured.")
  639. print()
  640. _info("Add one with:")
  641. _info(' hermes mcp add <name> --url <endpoint>')
  642. _info(' hermes mcp add <name> --command <cmd> --args <args...>')
  643. print()
  644. return
  645. print()
  646. print(color(" MCP Servers:", Colors.CYAN + Colors.BOLD))
  647. print()
  648. print(f" {'Name':<16} {'Transport':<30} {'Tools':<12} {'Status':<10}")
  649. print(f" {'─' * 16} {'─' * 30} {'─' * 12} {'─' * 10}")
  650. for name, cfg in servers.items():
  651. if "url" in cfg:
  652. transport = cfg["url"]
  653. elif "command" in cfg:
  654. transport = cfg["command"]
  655. cmd_args = cfg.get("args", [])
  656. if isinstance(cmd_args, list) and cmd_args:
  657. transport = f"{transport} {' '.join(str(a) for a in cmd_args[:2])}"
  658. else:
  659. transport = "?"
  660. if len(transport) > 28:
  661. transport = transport[:25] + "..."
  662. include, exclude = _tool_filters(cfg)
  663. if include is not None:
  664. tools_str = f"{len(include)} selected"
  665. elif exclude:
  666. tools_str = f"-{len(exclude)} excluded"
  667. else:
  668. tools_str = "all"
  669. enabled = mcp_server_enabled(cfg)
  670. status = color("✓ enabled", Colors.GREEN) if enabled else color("✗ disabled", Colors.DIM)
  671. print(f" {name:<16} {transport:<30} {tools_str:<12} {status}")
  672. print()
  673. def _probe_failure_reason(exc: BaseException) -> str:
  674. """Plain reason for a failed probe: ``_format_connect_error`` unwraps ExceptionGroups and names a
  675. missing executable; the result is redacted like every other probe string."""
  676. from tools.mcp_tool_errors import _format_connect_error
  677. return redact_mcp_probe_text(_format_connect_error(exc))
  678. def probe_failure_class(exc: BaseException) -> str:
  679. """Extension-install class for a failed MCP probe, from the exception TYPE (the same tests
  680. :func:`_probe_failure_next_step` uses), never its message. Never raises: an exception whose own
  681. attribute hooks raise reads ``connect_failed`` instead of replacing the user's error."""
  682. from hermes_cli.observability.shared_metrics_fields import tagged_failure_class
  683. if tagged := tagged_failure_class(exc):
  684. return tagged
  685. from tools.mcp_tool_errors import InvalidMcpUrlError, _is_auth_error, _iter_exception_nodes, _unwrap_exception_group
  686. from tools.mcp_tool_node_abi import NodeAbiMismatchError
  687. try:
  688. root = _unwrap_exception_group(exc)
  689. if isinstance(root, InvalidMcpUrlError): # the configured URL is not http(s)://host
  690. return "config_invalid"
  691. if _is_auth_error(root) or getattr(getattr(root, "response", None), "status_code", None) in (401, 403):
  692. return "auth_required"
  693. # A missing stdio command (FileNotFoundError) or a native module built for another Node.
  694. if any(isinstance(node, (FileNotFoundError, NodeAbiMismatchError)) for node in _iter_exception_nodes(exc)):
  695. return "server_start_failed"
  696. except Exception: # a hook on the exception raised; the type tests could not finish
  697. logger.debug("MCP probe failure not classified", exc_info=True)
  698. return "connect_failed"
  699. def _probe_failure_next_step(name: str, exc: BaseException) -> str:
  700. """The one command that fixes the common probe failures (sign-in, missing command, everything else)."""
  701. from tools.mcp_tool_errors import _format_connect_error, _is_auth_error, _unwrap_exception_group
  702. from tools.mcp_tool_node_abi import NodeAbiMismatchError
  703. root = _unwrap_exception_group(exc)
  704. if _is_auth_error(root) or getattr(getattr(root, "response", None), "status_code", None) in (401, 403):
  705. return f"The server rejected the sign-in. Run: hermes mcp login {name}"
  706. if isinstance(root, NodeAbiMismatchError):
  707. return f"After rebuilding it under Hermes's Node as above, run: hermes mcp test {name}"
  708. if "missing executable" in _format_connect_error(exc):
  709. return (f"Install that command, or set mcp_servers.{name}.command in {display_hermes_home()}/config.yaml "
  710. "to its full path.")
  711. return f"Check the server is running and the URL/command in its config, then run: hermes mcp test {name}"
  712. def cmd_mcp_test(args):
  713. """Test connection to an MCP server.
  714. Returns the process exit code so health probes and watchdogs can branch on ``$?`` instead of
  715. parsing the output: 0 connected, 1 connection failed, 3 server not in the config (argparse
  716. already owns 2 for usage errors, so "no such server" stays distinguishable from "bad flags").
  717. """
  718. name = args.name
  719. cfg = _lookup_server(name, _get_mcp_servers(), "Available")
  720. if cfg is None:
  721. return 3
  722. print()
  723. print(color(f" Testing '{name}'...", Colors.CYAN))
  724. if "url" in cfg:
  725. _info(f"Transport: HTTP → {cfg['url']}")
  726. else:
  727. _info(f"Transport: stdio → {cfg.get('command', '?')}")
  728. headers = cfg.get("headers", {})
  729. if cfg.get("auth", "") == "oauth":
  730. _info("Auth: OAuth 2.0")
  731. elif headers:
  732. for k, v in headers.items():
  733. if isinstance(v, str) and ("key" in k.lower() or "auth" in k.lower()):
  734. # Keep header identity with the value. A ${ENV} substring is
  735. # not proof the rest of the header is non-secret.
  736. print(f" {k}: {redact_mcp_header_display(k, v)}")
  737. else:
  738. _info("Auth: none")
  739. start = time.monotonic()
  740. try:
  741. tools = _probe_single_server(name, cfg)
  742. except Exception as exc:
  743. elapsed = time.monotonic() - start
  744. _error(f"Connection failed ({elapsed:.1f}s): {_probe_failure_reason(exc)}")
  745. _info(_probe_failure_next_step(name, exc))
  746. return 1
  747. _success(f"Connected ({(time.monotonic() - start) * 1000:.0f}ms)")
  748. _success(f"Tools discovered: {len(tools)}")
  749. if tools:
  750. print()
  751. _print_tools(tools, 36, 55)
  752. print()
  753. return 0
  754. def _reauth_oauth_server(name: str, server_config: dict, *, flow: str | None = None) -> bool:
  755. """Force a fresh OAuth flow for one server. Returns True on success.
  756. Browser login clears cached state and re-probes. Device login replaces state only after
  757. approval. Both verify a token landed. Shared by ``login`` and ``reauth``.
  758. """
  759. url = server_config.get("url")
  760. if not url:
  761. _error(f"Server '{name}' has no URL — not an OAuth-capable server")
  762. return False
  763. if server_config.get("auth") != "oauth":
  764. _error(f"Server '{name}' is not configured for OAuth (auth={server_config.get('auth')})")
  765. _info("Use `hermes mcp remove` + `hermes mcp add` to reconfigure auth.")
  766. return False
  767. oauth_cfg = server_config.get("oauth") or {}
  768. selected_flow = flow or oauth_cfg.get("flow", "browser")
  769. if selected_flow not in {"browser", "device"}:
  770. _error("oauth.flow must be browser or device")
  771. return False
  772. try:
  773. from tools.mcp_oauth_manager import get_manager
  774. if selected_flow == "browser":
  775. # Tokens, client registration and the CIMD refusal go; the cached authorization-server
  776. # metadata stays. A fresh discovery still overwrites it, but when the metadata document
  777. # cannot be re-fetched (WAF-fronted split-host servers) it is the only thing that keeps
  778. # the announced authorize URL off the SDK's `{mcp-origin}/authorize` guess (#115329).
  779. from tools.mcp_oauth import HermesTokenStorage
  780. get_manager().evict(name)
  781. HermesTokenStorage(name).remove(keep_metadata=True)
  782. except Exception as exc:
  783. _warning(f"Could not clear existing OAuth state: {exc}")
  784. print()
  785. _info(f"Starting OAuth flow for '{name}'...")
  786. # The probe triggers the OAuth flow (browser redirect + callback capture). Its bound must outlast
  787. # the oauth.timeout callback window (plus headroom for the token exchange), or a user who raised
  788. # oauth.timeout still gets cut off at the old fixed floor — matching the GUI re-auth path in
  789. # web_server_mcp.py and tui_gateway/mcp_oauth_sessions.py. force_interactive_oauth: `hermes mcp
  790. # login` is explicitly user-initiated even when stdin isn't a TTY (desktop / agent-spawned
  791. # terminals), where _is_interactive() alone would refuse to open a browser.
  792. try:
  793. from tools.mcp_oauth import force_interactive_oauth, login_connect_timeout
  794. if selected_flow == "device":
  795. from tools.mcp_oauth_device import login_device
  796. asyncio.run(login_device(name, url, oauth_cfg))
  797. probe_config = {**server_config, "oauth": {**oauth_cfg, "flow": selected_flow}}
  798. with force_interactive_oauth():
  799. tools = _probe_single_server(
  800. name, probe_config, connect_timeout=login_connect_timeout(probe_config)
  801. )
  802. # A clean probe is NOT proof of authentication: some servers (e.g. Google Drive) serve
  803. # initialize + tools/list without auth, so the flow may have failed (e.g. DCR 400 for
  804. # providers without RFC 7591) while the probe still lists tools. Verify a token landed.
  805. if not _oauth_tokens_present(name):
  806. _warning("Server responded, but no OAuth token was obtained — authentication did not complete.")
  807. print()
  808. _info(
  809. "Some providers (e.g. Google Drive, Atlassian) do not support "
  810. "automatic client registration. For those you must create an "
  811. "OAuth client yourself and add its credentials to config.yaml:"
  812. )
  813. print()
  814. for line in (
  815. "mcp_servers:", f" {name}:", f" url: {url}", " auth: oauth", " oauth:",
  816. ' client_id: "<your-oauth-client-id>"',
  817. ' client_secret: "<your-oauth-client-secret>"',
  818. ):
  819. print(color(f" {line}", Colors.DIM))
  820. print()
  821. _info("Then re-run `hermes mcp login " + name + "`.")
  822. return False
  823. if tools:
  824. _success(f"Authenticated — {len(tools)} tool(s) available")
  825. else:
  826. _success("Authenticated (server reported no tools)")
  827. return True
  828. except Exception as exc:
  829. try:
  830. from tools.mcp_oauth import humanize_oauth_registration_error
  831. humanized = humanize_oauth_registration_error(name, exc, server_url=url)
  832. except Exception:
  833. humanized = None
  834. _error(f"Authentication failed: {redact_mcp_probe_text(humanized or exc)}")
  835. return False
  836. def cmd_mcp_login(args):
  837. """Run an explicit browser or device authorization for an OAuth-based MCP server."""
  838. cfg = _lookup_server(args.name, _get_mcp_servers())
  839. if cfg is not None:
  840. _reauth_oauth_server(args.name, cfg, flow=getattr(args, "flow", None))
  841. def cmd_mcp_reauth(args):
  842. """Re-authenticate one OAuth MCP server, or all of them sequentially.
  843. Serial-by-design: a human can only complete one browser OAuth flow at a time.
  844. This is the self-service fix for the recurring stale-client ritual in GH#36767 (and avoids the startup
  845. popup storm when several servers go stale at once).
  846. """
  847. servers = _get_mcp_servers()
  848. name = getattr(args, "name", None)
  849. if getattr(args, "all", False):
  850. oauth_servers = [(n, c) for n, c in servers.items() if c.get("auth") == "oauth" and c.get("url")]
  851. if not oauth_servers:
  852. _info("No OAuth-based MCP servers found in config.")
  853. return
  854. print()
  855. _info(f"Re-authenticating {len(oauth_servers)} OAuth server(s) one at a time...")
  856. succeeded = 0
  857. for n, c in oauth_servers:
  858. print()
  859. print(color(f" ── {n} ──", Colors.CYAN + Colors.BOLD))
  860. if _reauth_oauth_server(n, c):
  861. succeeded += 1
  862. print()
  863. _success(f"Re-authenticated {succeeded}/{len(oauth_servers)} server(s)")
  864. return
  865. if not name:
  866. _error("Specify a server name, or use --all to re-auth every OAuth server.")
  867. _info("Usage: hermes mcp reauth <name> | hermes mcp reauth --all")
  868. return
  869. cfg = _lookup_server(name, servers)
  870. if cfg is not None:
  871. _reauth_oauth_server(name, cfg)
  872. def _rebuild_exclude_list(
  873. name: str, exclude: list, tool_names: list[str], chosen: set, matches_name_filter
  874. ) -> list[str]:
  875. """New ``tools.exclude`` for an exclude-mode entry after a checklist edit.
  876. Stays in exclude mode rather than demoting the user's dynamic filter to a frozen include list:
  877. newly-unchecked tools are appended as literal excludes, re-checked tools drop their literal
  878. entries, and glob patterns are preserved (they keep excluding future vendor tools by design).
  879. """
  880. old_exclude = [str(p) for p in exclude]
  881. glob_entries = [p for p in old_exclude if "*" in p or "?" in p or "[" in p]
  882. literal_entries = {p for p in old_exclude if p not in glob_entries}
  883. unchecked = {tool_names[i] for i in range(len(tool_names)) if i not in chosen}
  884. checked = {tool_names[i] for i in chosen}
  885. new_literals = (literal_entries - checked) | {
  886. tn for tn in unchecked if not matches_name_filter(tn, set(old_exclude))}
  887. # A re-checked tool still matched by a kept glob can't be enabled without dropping the glob —
  888. # surface that instead of silently ignoring the click or silently freezing the config.
  889. glob_shadowed = sorted(
  890. tn for tn in checked if glob_entries and matches_name_filter(tn, set(glob_entries))
  891. )
  892. if glob_shadowed:
  893. _warning(
  894. f"{len(glob_shadowed)} re-enabled tool(s) still match glob "
  895. f"exclude pattern(s) {glob_entries} and stay excluded: "
  896. f"{', '.join(glob_shadowed[:5])}"
  897. f"{' ...' if len(glob_shadowed) > 5 else ''}. Remove the "
  898. f"pattern from mcp_servers.{name}.tools.exclude in "
  899. "config.yaml to enable them."
  900. )
  901. return glob_entries + sorted(new_literals)
  902. def cmd_mcp_configure(args):
  903. """Reconfigure which tools are enabled for an existing MCP server."""
  904. import sys as _sys
  905. if not _sys.stdin.isatty():
  906. print("Error: 'hermes mcp configure' requires an interactive terminal.", file=_sys.stderr)
  907. _sys.exit(1)
  908. name = args.name
  909. cfg = _lookup_server(name, _get_mcp_servers(), "Available")
  910. if cfg is None:
  911. return
  912. print()
  913. print(color(f" Connecting to '{name}' to discover tools...", Colors.CYAN))
  914. try:
  915. all_tools = _probe_single_server(name, cfg)
  916. except Exception as exc:
  917. _error(f"Failed to connect: {redact_mcp_probe_text(exc)}")
  918. return
  919. if not all_tools:
  920. _warning("Server reports no tools.")
  921. return
  922. include, exclude = _tool_filters(cfg)
  923. tool_names = [t[0] for t in all_tools]
  924. total = len(all_tools)
  925. # Same matching semantics as runtime registration (tools/mcp_tool.py): exact names or globs.
  926. try:
  927. from tools.mcp_tool_schema import matches_name_filter
  928. except ImportError: # pragma: no cover — defensive fallback
  929. def matches_name_filter(tool_name, patterns):
  930. return tool_name in patterns
  931. if include is not None:
  932. pre_selected = {i for i, tn in enumerate(tool_names) if matches_name_filter(tn, {str(p) for p in include})}
  933. elif exclude:
  934. pre_selected = {i for i, tn in enumerate(tool_names) if not matches_name_filter(tn, {str(p) for p in exclude})}
  935. else:
  936. pre_selected = set(range(total))
  937. _info(f"Currently {len(pre_selected)}/{total} tools enabled for '{name}'.")
  938. print()
  939. from hermes_cli.curses_ui import curses_checklist
  940. labels = [f"{t[0]} — {t[1]}" for t in all_tools]
  941. chosen = curses_checklist(f"Select tools for '{name}'", labels, pre_selected)
  942. if chosen == pre_selected:
  943. _info("No changes made.")
  944. return
  945. config = load_config()
  946. server_entry = cfg_get(config, "mcp_servers", name, default={})
  947. exclude_mode = bool(exclude) and include is None
  948. if len(chosen) == total and not exclude_mode:
  949. server_entry.pop("tools", None) # all selected → register all
  950. elif exclude_mode:
  951. new_exclude = _rebuild_exclude_list(name, exclude, tool_names, chosen, matches_name_filter)
  952. if not new_exclude:
  953. server_entry.pop("tools", None)
  954. else:
  955. server_entry.setdefault("tools", {})
  956. server_entry["tools"]["exclude"] = new_exclude
  957. server_entry["tools"].pop("include", None)
  958. else:
  959. server_entry.setdefault("tools", {})
  960. server_entry["tools"]["include"] = [tool_names[i] for i in sorted(chosen)]
  961. server_entry["tools"].pop("exclude", None)
  962. config.setdefault("mcp_servers", {})[name] = server_entry
  963. save_config(config)
  964. _success(f"Updated config: {len(chosen)}/{total} tools enabled")
  965. _info("Run /reload-mcp for changes to take effect.")
  966. _MCP_USAGE = (
  967. "hermes mcp Open the catalog picker (default)",
  968. "hermes mcp catalog List Nous-approved MCPs",
  969. "hermes mcp install <name> Install a catalog MCP",
  970. "hermes mcp add <name> --url <endpoint> Add a custom MCP server",
  971. "hermes mcp add <name> --command <cmd> Add a stdio server",
  972. "hermes mcp add <name> --preset <preset> Add from a known preset",
  973. "hermes mcp remove <name> Remove a server",
  974. "hermes mcp list List configured servers",
  975. "hermes mcp test <name> Test connection",
  976. "hermes mcp configure <name> Toggle tools",
  977. "hermes mcp login <name> Re-authenticate OAuth",
  978. "hermes mcp reauth <name> | --all Re-auth one or all OAuth servers",
  979. )
  980. def mcp_command(args):
  981. """Main dispatcher for ``hermes mcp`` subcommands."""
  982. action = getattr(args, "mcp_action", None)
  983. if action in ("picker", "catalog", "install"):
  984. # Catalog subcommands live in mcp_picker / mcp_catalog; import lazily to keep this module cheap.
  985. from hermes_cli import mcp_picker
  986. if action == "picker":
  987. mcp_picker.run_picker()
  988. elif action == "catalog":
  989. mcp_picker.show_catalog()
  990. else:
  991. import sys as _sys
  992. rc = mcp_picker.install_by_name(getattr(args, "identifier", "") or "")
  993. if rc:
  994. _sys.exit(rc)
  995. return
  996. handler = {
  997. "add": cmd_mcp_add, "remove": cmd_mcp_remove, "rm": cmd_mcp_remove, "list": cmd_mcp_list,
  998. "ls": cmd_mcp_list, "test": cmd_mcp_test, "configure": cmd_mcp_configure,
  999. "config": cmd_mcp_configure, "login": cmd_mcp_login, "reauth": cmd_mcp_reauth,
  1000. }.get(action)
  1001. if handler:
  1002. # A handler's int return is the process exit code (``main()`` exits non-zero on it).
  1003. return handler(args)
  1004. # No subcommand — drop the user into the catalog picker (same UX as `hermes plugin`).
  1005. from hermes_cli.mcp_picker import run_picker
  1006. run_picker()
  1007. print(color(" Commands:", Colors.CYAN))
  1008. for line in _MCP_USAGE:
  1009. _info(line)
  1010. print()