mcp_picker.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. """MCP picker — interactive `hermes mcp picker` (also the default `hermes mcp`)."""
  2. from __future__ import annotations
  3. import sys
  4. from dataclasses import dataclass
  5. from typing import List, Optional
  6. from hermes_cli.colors import Colors
  7. from hermes_cli.cli_output import prompt_yes_no
  8. from hermes_cli.curses_ui import curses_single_select
  9. from hermes_cli.mcp_catalog import (
  10. CatalogEntry, CatalogError, catalog_diagnostics, install_entry, is_enabled, is_installed,
  11. list_catalog, installed_servers, remove_server, server_enabled, uninstall_entry, _say,
  12. )
  13. from hermes_cli.config import load_config, save_config
  14. _STATUS_NOT_INSTALLED = "available"
  15. _STATUS_DISABLED = "installed (disabled)"
  16. _STATUS_ENABLED = "enabled"
  17. _STATUS_CUSTOM_ENABLED = "custom — enabled"
  18. _STATUS_CUSTOM_DISABLED = "custom — disabled"
  19. @dataclass
  20. class _Row:
  21. """A picker row. ``entry`` is set for catalog rows; custom MCPs carry only name/description/status."""
  22. name: str
  23. description: str
  24. status: str
  25. entry: Optional[CatalogEntry] = None # None for non-catalog (custom) rows
  26. @property
  27. def is_custom(self) -> bool:
  28. return self.entry is None
  29. def _build_rows() -> list[_Row]:
  30. """Return catalog rows + any custom (non-catalog) MCPs found in config."""
  31. catalog_entries = list_catalog()
  32. catalog_names = {e.name for e in catalog_entries}
  33. servers = installed_servers()
  34. rows: list[_Row] = []
  35. for entry in catalog_entries:
  36. cfg = servers.get(entry.name)
  37. if entry.name not in servers:
  38. status = _STATUS_NOT_INSTALLED
  39. elif cfg and server_enabled(cfg):
  40. status = _STATUS_ENABLED
  41. else:
  42. status = _STATUS_DISABLED
  43. rows.append(_Row(entry.name, entry.description, status, entry))
  44. # Custom (non-catalog) MCPs: the transport URL/command doubles as the description.
  45. for name, cfg in sorted(servers.items()):
  46. if name in catalog_names:
  47. continue
  48. status = _STATUS_CUSTOM_ENABLED if server_enabled(cfg) else _STATUS_CUSTOM_DISABLED
  49. rows.append(_Row(name, str(cfg.get("url") or cfg.get("command") or "(no transport)"), status))
  50. return rows
  51. def _format_row(row: _Row) -> str:
  52. return f"{row.name:<18} {row.status:<24} {row.description}"
  53. def _enable_disable(name: str, *, enable: bool) -> None:
  54. cfg = load_config()
  55. servers = cfg.get("mcp_servers") or {}
  56. server = servers.get(name)
  57. if not server:
  58. _say(f" '{name}' is not installed.", Colors.RED)
  59. return
  60. server["enabled"] = enable
  61. cfg["mcp_servers"] = servers
  62. save_config(cfg)
  63. _say(
  64. f" ✓ '{name}' {'enabled' if enable else 'disabled'}. "
  65. "Start a new Hermes session for changes to take effect."
  66. )
  67. def _configure_tools(name: str) -> None:
  68. """Open the tool selection checklist for an already-installed MCP."""
  69. from argparse import Namespace
  70. from hermes_cli.mcp_config import cmd_mcp_configure
  71. cmd_mcp_configure(Namespace(name=name))
  72. def _remove_custom(name: str) -> None:
  73. """Remove a non-catalog MCP entry from config.yaml."""
  74. if not is_installed(name):
  75. _say(f" '{name}' is not configured.", Colors.RED)
  76. return
  77. if not prompt_yes_no(f"Remove '{name}' from mcp_servers?", default=False):
  78. return
  79. remove_server(name)
  80. _say(f" ✓ Removed '{name}'")
  81. def _install(entry: CatalogEntry, verb: str) -> bool:
  82. """Install *entry*, printing (not raising) a CatalogError. True on success."""
  83. try:
  84. install_entry(entry, enable=True)
  85. except CatalogError as exc:
  86. _say(f" ✗ {verb} failed: {exc}", Colors.RED)
  87. return False
  88. return True
  89. def _uninstall(name: str) -> None:
  90. if not prompt_yes_no(f"Uninstall '{name}'?", default=False):
  91. return
  92. if uninstall_entry(name):
  93. _say(
  94. f" ✓ Uninstalled '{name}'. "
  95. "Credentials in .env preserved — delete manually if no longer needed."
  96. )
  97. else:
  98. _say(f" '{name}' was not installed", Colors.DIM)
  99. def _run_submenu(title: str, actions: list) -> None:
  100. """Show a single-select of ``(label, callback)`` pairs and run the picked callback."""
  101. choice = curses_single_select(title, [label for label, _ in actions])
  102. if choice is not None:
  103. actions[choice][1]()
  104. def _handle_row(row: _Row) -> None:
  105. """Act on the picked row based on its current status."""
  106. if row.entry and not is_installed(row.name):
  107. _install(row.entry, "install")
  108. return
  109. if row.entry and not is_enabled(row.name):
  110. _enable_disable(row.name, enable=True)
  111. return
  112. if row.is_custom:
  113. enabled = is_enabled(row.name)
  114. _run_submenu(f"Action for '{row.name}' (custom)", [
  115. ("Configure tools (probe server + re-pick)", lambda: _configure_tools(row.name)),
  116. ("Enable" if not enabled else "Disable",
  117. lambda: _enable_disable(row.name, enable=not is_enabled(row.name))),
  118. ("Remove from config", lambda: _remove_custom(row.name))])
  119. return
  120. # Catalog row, installed + enabled
  121. print()
  122. _say(f" '{row.name}' is already enabled.", Colors.DIM)
  123. _run_submenu(f"Action for '{row.name}'", [
  124. ("Configure tools (probe server + re-pick)", lambda: _configure_tools(row.name)),
  125. ("Disable (keep config, stop loading on next session)",
  126. lambda: _enable_disable(row.name, enable=False)),
  127. ("Uninstall (remove config and any cloned files)", lambda: _uninstall(row.name)),
  128. ("Reinstall (re-clone, re-prompt for credentials)",
  129. lambda: _install(row.entry, "reinstall"))])
  130. def _print_rows_text(rows: list[_Row]) -> None:
  131. """Plain-text catalog dump: `hermes mcp catalog` output and the non-curses fallback."""
  132. print()
  133. if not rows:
  134. _say(" No MCPs in the catalog or configured.", Colors.DIM)
  135. print()
  136. return
  137. _say(" MCP Catalog + configured servers:", Colors.CYAN + Colors.BOLD)
  138. print()
  139. print(f" {'Name':<18} {'Status':<24} Description")
  140. print(f" {'-' * 18} {'-' * 24} {'-' * 11}")
  141. for row in rows:
  142. print(f" {_format_row(row)}")
  143. print()
  144. _say(" Install: hermes mcp install <name> Picker: hermes mcp", Colors.DIM)
  145. # Manifest-version warnings: the user's Hermes is too old to install everything listed.
  146. future = [d for d in catalog_diagnostics() if d[1] == "future_manifest"]
  147. if future:
  148. print()
  149. for name, _, _msg in future:
  150. _say(f" ⚠ '{name}' requires a newer Hermes — run `hermes update` to install this entry.", Colors.YELLOW)
  151. print()
  152. print()
  153. def show_catalog() -> None:
  154. """`hermes mcp catalog` — print the curated list + custom servers, no interaction."""
  155. _print_rows_text(_build_rows())
  156. def run_picker() -> None:
  157. """`hermes mcp picker` (and default `hermes mcp`) — interactive selector; re-renders after each
  158. action until ESC/q."""
  159. while True:
  160. rows = _build_rows()
  161. if not rows or not sys.stdin.isatty():
  162. _print_rows_text(rows) # non-interactive: degrade to the text dump
  163. return
  164. idx = curses_single_select(
  165. "MCP Catalog — ↑↓ navigate ENTER act on entry ESC/q quit",
  166. [_format_row(r) for r in rows],
  167. )
  168. if idx is None:
  169. return
  170. _handle_row(rows[idx])
  171. def install_by_name(identifier: str) -> int:
  172. """`hermes mcp install <name>` — non-interactive entry-point."""
  173. from hermes_cli.mcp_catalog import get_entry
  174. entry = get_entry(identifier)
  175. if entry is None:
  176. _say(
  177. f" ✗ '{identifier}' is not in the catalog. Run `hermes mcp catalog` to see available entries.",
  178. Colors.RED,
  179. )
  180. return 1
  181. return 0 if _install(entry, "install") else 1