tools_config_mcp.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. """MCP tool checklists and the non-interactive ``hermes tools enable|disable|list`` command."""
  2. from __future__ import annotations
  3. from typing import List, Set
  4. from hermes_cli.cli_output import (
  5. print_error as _print_error, print_info as _print_info, print_success as _print_success,
  6. print_warning as _print_warning)
  7. from hermes_cli.colors import Colors, color
  8. from hermes_cli.toolset_scope import (
  9. _TOOLSET_PLATFORM_RESTRICTIONS, toolset_allowed_for_platform as _toolset_allowed_for_platform)
  10. def _mcp_match_filter():
  11. """Runtime name-filter matcher (exact names or fnmatch globs), with a literal fallback.
  12. Must use the SAME semantics as tools/mcp_tool.py registration — a literal ``in`` check renders glob
  13. excludes (e.g. ``*team_member*`` from catalog default_excluded manifests) as if nothing were
  14. excluded."""
  15. try:
  16. from tools.mcp_tool_schema import matches_name_filter
  17. return matches_name_filter
  18. except ImportError: # pragma: no cover — defensive fallback
  19. return lambda tool_name, patterns: tool_name in patterns
  20. def _mcp_preselected(tool_names: list[str], include_set, exclude_set, match) -> set[int]:
  21. """Indices of tools currently enabled: include mode, exclude mode, or all when unfiltered."""
  22. if include_set is not None:
  23. return {i for i, tn in enumerate(tool_names) if match(tn, include_set)}
  24. if exclude_set:
  25. return {i for i, tn in enumerate(tool_names) if not match(tn, exclude_set)}
  26. return set(range(len(tool_names)))
  27. def _apply_mcp_checklist(server_name: str, tools_cfg: dict, tool_names: list[str], chosen: set[int],
  28. include_set, exclude_set, match) -> None:
  29. """Write a checklist result back as ``tools.include`` / ``tools.exclude``."""
  30. exclude_mode = bool(exclude_set) and include_set is None
  31. if len(chosen) == len(tool_names) and not exclude_mode:
  32. # All tools enabled — clear filters so tools the server adds later are auto-enabled.
  33. tools_cfg.pop("exclude", None)
  34. tools_cfg.pop("include", None)
  35. elif exclude_mode:
  36. # Exclude-mode server (catalog default_excluded / hand-written tools.exclude): stay in exclude
  37. # mode — do NOT demote the dynamic filter to a frozen include list. Unchecked tools become literal
  38. # excludes; re-checked literals are dropped; glob patterns are preserved (they intentionally keep
  39. # matching tools the vendor ships later).
  40. old_exclude = sorted(exclude_set or set())
  41. glob_entries = [p for p in old_exclude if "*" in p or "?" in p or "[" in p]
  42. literal_entries = {p for p in old_exclude if p not in glob_entries}
  43. unchecked = {tn for i, tn in enumerate(tool_names) if i not in chosen}
  44. checked = {tool_names[i] for i in chosen}
  45. new_literals = (literal_entries - checked) | {tn for tn in unchecked if not match(tn, set(old_exclude))}
  46. new_exclude = glob_entries + sorted(new_literals)
  47. glob_shadowed = sorted(tn for tn in checked if glob_entries and match(tn, set(glob_entries)))
  48. if glob_shadowed:
  49. _print_warning(
  50. f" {server_name}: {len(glob_shadowed)} re-enabled "
  51. f"tool(s) still match glob exclude pattern(s) "
  52. f"{glob_entries} and stay excluded — edit "
  53. f"mcp_servers.{server_name}.tools.exclude in config.yaml "
  54. "to enable them.")
  55. if new_exclude:
  56. tools_cfg["exclude"] = new_exclude
  57. else:
  58. tools_cfg.pop("exclude", None)
  59. tools_cfg.pop("include", None)
  60. else:
  61. tools_cfg["include"] = [tool_names[i] for i in sorted(chosen)]
  62. tools_cfg.pop("exclude", None) # include-mode now; drop any legacy exclude block
  63. def _configure_mcp_tools_interactive(config: dict):
  64. """Probe each MCP server for its tools, show a per-server curses checklist, and write the result
  65. back as ``tools.exclude`` / ``tools.include`` entries in config.yaml."""
  66. from hermes_cli.curses_ui import curses_checklist
  67. from hermes_cli.tools_config import save_config
  68. mcp_servers = config.get("mcp_servers") or {}
  69. if not mcp_servers:
  70. _print_info("No MCP servers configured.")
  71. return
  72. from tools.mcp_tool_common import mcp_server_enabled
  73. enabled_names = [k for k, v in mcp_servers.items() if isinstance(v, dict) and mcp_server_enabled(v)]
  74. if not enabled_names:
  75. _print_info("All MCP servers are disabled.")
  76. return
  77. print()
  78. print(color(" Discovering tools from MCP servers...", Colors.YELLOW))
  79. print(color(f" Connecting to {len(enabled_names)} server(s): {', '.join(enabled_names)}", Colors.DIM))
  80. try:
  81. from tools.mcp_tool_discovery import probe_mcp_server_tools
  82. server_tools = probe_mcp_server_tools()
  83. except Exception as exc:
  84. _print_error(f"Failed to probe MCP servers: {exc}")
  85. return
  86. if not server_tools:
  87. _print_warning("Could not discover tools from any MCP server.")
  88. _print_info("Check that server commands/URLs are correct and dependencies are installed.")
  89. return
  90. for name in (n for n in enabled_names if n not in server_tools):
  91. _print_warning(f" Could not connect to '{name}'")
  92. total_tools = sum(len(tools) for tools in server_tools.values())
  93. print(color(f" Found {total_tools} tool(s) across {len(server_tools)} server(s)", Colors.GREEN))
  94. print()
  95. any_changes = False
  96. for server_name, tools in server_tools.items():
  97. if not tools:
  98. _print_info(f" {server_name}: no tools found")
  99. continue
  100. tools_cfg = mcp_servers.get(server_name, {}).get("tools") or {}
  101. # ``include: []`` is an explicit block-all whitelist, not "unfiltered" (#12865).
  102. include_raw, exclude_raw = tools_cfg.get("include"), tools_cfg.get("exclude")
  103. include_set = {str(p) for p in include_raw} if isinstance(include_raw, list) else None
  104. exclude_set = {str(p) for p in exclude_raw or []} or None
  105. labels = []
  106. for tool_name, description in tools:
  107. desc_short = description[:70] + "..." if len(description) > 70 else description
  108. labels.append(f"{tool_name} ({desc_short})" if desc_short else tool_name)
  109. match = _mcp_match_filter()
  110. tool_names = [t[0] for t in tools]
  111. pre_selected = _mcp_preselected(tool_names, include_set, exclude_set, match)
  112. chosen = curses_checklist(
  113. f"MCP Server: {server_name} ({len(tools)} tools)", labels, pre_selected, cancel_returns=pre_selected)
  114. if chosen == pre_selected:
  115. _print_info(f" {server_name}: no changes")
  116. continue
  117. tools_cfg = mcp_servers.setdefault(server_name, {}).setdefault("tools", {})
  118. _apply_mcp_checklist(server_name, tools_cfg, tool_names, chosen, include_set, exclude_set, match)
  119. _print_success(f" {server_name}: {len(chosen)} enabled, {len(tools) - len(chosen)} disabled")
  120. any_changes = True
  121. if any_changes:
  122. save_config(config)
  123. print()
  124. print(color(" ✓ MCP tool configuration saved", Colors.GREEN))
  125. else:
  126. print(color(" No changes to MCP tools", Colors.DIM))
  127. def _apply_toolset_change(config: dict, platform: str, toolset_names: list[str], action: str):
  128. """Add or remove built-in toolsets for a platform."""
  129. from hermes_cli.tools_config import _get_platform_tools, _save_platform_tools
  130. enabled = _get_platform_tools(config, platform, include_default_mcp_servers=False)
  131. updated = enabled - set(toolset_names) if action == "disable" else enabled | set(toolset_names)
  132. _save_platform_tools(config, platform, updated)
  133. def _apply_mcp_change(config: dict, targets: list[str], action: str) -> set[str]:
  134. """Add or remove specific MCP tools from a server's exclude list."""
  135. failed_servers: set[str] = set()
  136. mcp_servers = config.get("mcp_servers") or {}
  137. for target in targets:
  138. server_name, tool_name = target.split(":", 1)
  139. if server_name not in mcp_servers:
  140. failed_servers.add(server_name)
  141. continue
  142. tools_cfg = mcp_servers[server_name].setdefault("tools", {})
  143. exclude = list(tools_cfg.get("exclude") or [])
  144. if action != "disable":
  145. exclude = [t for t in exclude if t != tool_name]
  146. elif tool_name not in exclude:
  147. exclude.append(tool_name)
  148. tools_cfg["exclude"] = exclude
  149. return failed_servers
  150. def _print_tools_list(enabled_toolsets: set, mcp_servers: dict, platform: str = "cli", stripped: dict | None = None):
  151. """Print a summary of enabled/disabled toolsets and MCP tool filters. ``stripped`` is
  152. ``tools_config.toolsets_partially_stripped`` output: enabled rows that agent.disabled_toolsets cuts down."""
  153. from hermes_cli.tools_config import CONFIGURABLE_TOOLSETS, _get_effective_configurable_toolsets
  154. effective_all = _get_effective_configurable_toolsets()
  155. effective = [(k, l, d) for (k, l, d) in effective_all if _toolset_allowed_for_platform(k, platform)]
  156. builtin_keys = {ts_key for ts_key, _, _ in CONFIGURABLE_TOOLSETS}
  157. def _print_rows(entries):
  158. for ts_key, label in entries:
  159. status = color("✓ enabled", Colors.GREEN) if ts_key in enabled_toolsets else color("✗ disabled", Colors.RED)
  160. print(f" {status} {ts_key} {color(label, Colors.DIM)}")
  161. if ts_key in (stripped or {}) and ts_key in enabled_toolsets:
  162. tools, by, hint = stripped[ts_key]
  163. print(color(f" ⚠ {', '.join(tools)} removed by agent.disabled_toolsets: {', '.join(by)} ({hint})",
  164. Colors.YELLOW))
  165. print(f"Built-in toolsets ({platform}):")
  166. _print_rows((k, l) for k, l, _ in effective if k in builtin_keys)
  167. plugin_entries = [(k, l) for k, l, _ in effective if k not in builtin_keys]
  168. if plugin_entries:
  169. print()
  170. print(f"Plugin toolsets ({platform}):")
  171. _print_rows(plugin_entries)
  172. if mcp_servers:
  173. print()
  174. print("MCP servers:")
  175. for srv_name, srv_cfg in mcp_servers.items():
  176. tools_cfg = srv_cfg.get("tools") or {}
  177. exclude, include = tools_cfg.get("exclude") or [], tools_cfg.get("include")
  178. if isinstance(include, list):
  179. _print_info(f"{srv_name} [include only: {', '.join(include) or '(none)'}]")
  180. elif exclude:
  181. _print_info(f"{srv_name} [excluded: {color(', '.join(exclude), Colors.YELLOW)}]")
  182. else:
  183. _print_info(f"{srv_name} {color('all tools enabled', Colors.DIM)}")
  184. def _known_tool_platforms() -> set[str]:
  185. """Return built-in plus discovered plugin platform names. Plugin platforms register at runtime, not
  186. in the static CLI display registry, and must be recognized so an active plugin platform can audit
  187. its authority."""
  188. from hermes_cli.tools_config import PLATFORMS
  189. known = set(PLATFORMS)
  190. try:
  191. from hermes_cli.plugins import discover_plugins
  192. from gateway.platform_registry import platform_registry
  193. discover_plugins() # idempotent
  194. known.update(platform_registry.registered_names())
  195. except Exception:
  196. # Plugin discovery is optional: keep the built-in path when a plugin is malformed or deps are missing.
  197. pass
  198. return known
  199. def tools_disable_enable_command(args):
  200. """Enable, disable, or list tools for a platform."""
  201. from hermes_cli.tools_config import CONFIGURABLE_TOOLSETS, _get_platform_tools, _get_plugin_toolset_keys, load_config, save_config
  202. action = args.tools_action
  203. platform = getattr(args, "platform", "cli")
  204. config = load_config()
  205. from hermes_cli.tools_config import PLATFORMS
  206. valid_platforms = PLATFORMS if platform in PLATFORMS else _known_tool_platforms() # built-ins load no plugin
  207. if platform not in valid_platforms:
  208. _print_error(f"Unknown platform '{platform}'. Valid: {', '.join(sorted(valid_platforms))}")
  209. return
  210. if action == "list":
  211. from hermes_cli.tools_config import toolsets_partially_stripped
  212. enabled = _get_platform_tools(config, platform, include_default_mcp_servers=False)
  213. _print_tools_list(enabled, config.get("mcp_servers") or {}, platform, toolsets_partially_stripped(config, enabled))
  214. return
  215. targets: list[str] = args.names
  216. toolset_targets = [t for t in targets if ":" not in t]
  217. mcp_targets = [t for t in targets if ":" in t]
  218. valid_toolsets = {ts_key for ts_key, _, _ in CONFIGURABLE_TOOLSETS} | _get_plugin_toolset_keys()
  219. unknown_toolsets = [t for t in toolset_targets if t not in valid_toolsets]
  220. for name in unknown_toolsets:
  221. _print_error(f"Unknown toolset '{name}'")
  222. # Reject platform-scoped toolsets on platforms that don't allow them.
  223. restricted_targets = [t for t in toolset_targets
  224. if t in valid_toolsets and not _toolset_allowed_for_platform(t, platform)]
  225. for name in restricted_targets:
  226. allowed = sorted(_TOOLSET_PLATFORM_RESTRICTIONS.get(name) or set())
  227. _print_error(f"Toolset '{name}' is not available on platform '{platform}' (only: {', '.join(allowed)})")
  228. rejected = set(unknown_toolsets) | set(restricted_targets)
  229. toolset_targets = [t for t in toolset_targets if t not in rejected]
  230. if toolset_targets:
  231. _apply_toolset_change(config, platform, toolset_targets, action)
  232. failed_servers: set[str] = set()
  233. if mcp_targets:
  234. failed_servers = _apply_mcp_change(config, mcp_targets, action)
  235. for srv in failed_servers:
  236. _print_error(f"MCP server '{srv}' not found in config")
  237. save_config(config)
  238. successful = [t for t in targets
  239. if t not in rejected and (":" not in t or t.split(":")[0] not in failed_servers)]
  240. if successful:
  241. verb = "Disabled" if action == "disable" else "Enabled"
  242. _print_success(f"{verb}: {', '.join(successful)}")