plugins_activation_live.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. """Make an installed plugin's MCP servers and skills usable in THIS process now (#87770 follow-up).
  2. :func:`hermes_cli.plugins_activation.activate_plugin_now` loads the plugin; skills are live from that
  3. point (``skill_view`` resolves ``<plugin>:<skill>``). MCP servers are not: nothing connects them until
  4. ``reload.mcp``. :func:`connect_plugin_mcp` connects the plugin's servers one by one (the connector
  5. flow's ``register_mcp_servers({name: config})``), and :func:`live_notice` renders what became usable
  6. as the note an open chat receives on its next tool result or turn (``agent/plugin_live_notes.py``).
  7. MCP tools are deferred behind ``tool_search`` / ``tool_describe`` / ``tool_call``, so adding them to a
  8. live session leaves the model-facing tool array (and the cached prompt prefix) byte-identical.
  9. """
  10. from __future__ import annotations
  11. import logging
  12. from pathlib import Path
  13. from typing import Any, Dict, List, Optional
  14. logger = logging.getLogger(__name__)
  15. def connect_plugin_mcp(activation: dict[str, Any], portable: dict[str, dict[str, Any]]) -> list[dict[str, Any]]:
  16. """Connect every portable MCP server ``activation`` defers, under the caller's profile scope.
  17. ``portable`` is the manager's portable server configs, read together with ``activation``.
  18. Returns ``[{name, connected, tools, error?}]``, one row per server; a server that fails to
  19. connect is reported, never retried. Never raises."""
  20. names = list((activation.get("deferred") or {}).get("mcp_servers") or ())
  21. if not names:
  22. return []
  23. try:
  24. from tools.mcp_tool_config import _filter_suspicious_mcp_servers, _load_mcp_config
  25. from tools.mcp_tool_discovery import register_mcp_servers
  26. configured = _load_mcp_config()
  27. except Exception as exc:
  28. logger.warning("plugin MCP activation could not read server config: %s", exc)
  29. return [{"name": n, "connected": False, "tools": [], "error": str(exc)} for n in names]
  30. rows = []
  31. for name in names:
  32. config = configured.get(name) or _filter_suspicious_mcp_servers(
  33. {name: portable[name]} if name in portable else {}).get(name)
  34. if not isinstance(config, dict):
  35. rows.append({"name": name, "connected": False, "tools": [], "error": "no MCP configuration"})
  36. continue
  37. try:
  38. register_mcp_servers({name: config})
  39. from tools.connectors.mcp import _registered_tool_names
  40. tools = [t for t in _registered_tool_names(name) if not t.endswith(_utility_suffixes())]
  41. except Exception as exc:
  42. rows.append({"name": name, "connected": False, "tools": [], "error": str(exc)})
  43. continue
  44. row: dict[str, Any] = {"name": name, "connected": bool(tools), "tools": tools}
  45. if not tools:
  46. row["error"] = _server_error(name) or "the server did not connect"
  47. rows.append(row)
  48. return rows
  49. def _utility_suffixes() -> tuple:
  50. """The resource/prompt wrappers every MCP server gets (``mcp__x__list_resources``, ...): callable,
  51. but they say nothing about what the plugin does, so they are left out of counts and listings."""
  52. from tools.mcp_tool_registration import _UTILITY_HANDLER_FACTORIES
  53. return tuple(f"_{kind}" for kind in _UTILITY_HANDLER_FACTORIES)
  54. def _server_error(name: str) -> Optional[str]:
  55. try:
  56. from tools.mcp_tool_discovery import get_mcp_status
  57. for entry in get_mcp_status():
  58. if entry.get("name") == name:
  59. return entry.get("error")
  60. except Exception:
  61. return None
  62. return None
  63. def plugin_skills(plugin_key: str) -> list[dict[str, str]]:
  64. """``[{name, description}]`` for the skills ``plugin_key`` registered (qualified ``<ns>:<skill>``)."""
  65. try:
  66. from hermes_cli.plugins import get_plugin_manager
  67. skills = get_plugin_manager()._plugin_skills
  68. except Exception:
  69. return []
  70. return [{"name": qualified, "description": str(entry.get("description") or "")}
  71. for qualified, entry in sorted(skills.items()) if entry.get("plugin_key") == plugin_key]
  72. def catalog_plugin_skill(written: str) -> Optional[str]:
  73. """The registered name of a plugin skill written ``<catalog-name>:<skill>`` (``blender:blender``), or
  74. None when that catalog plugin is not installed in this profile or registered no such skill. Skills
  75. register under the plugin's manifest name, which need not match its catalog entry name."""
  76. from hermes_cli.plugins import get_plugin_manager
  77. from hermes_cli.plugins_cmd import _catalog_installed_dir
  78. catalog_name, _, bare = written.partition(":")
  79. target = _catalog_installed_dir(catalog_name)
  80. if target is None:
  81. return None
  82. manager = get_plugin_manager()
  83. keys = {key for key, loaded in manager._plugins.items()
  84. if loaded.manifest.path and Path(loaded.manifest.path).resolve() == target.resolve()}
  85. return next((qualified for qualified, entry in sorted(manager._plugin_skills.items())
  86. if entry.get("plugin_key") in keys and entry.get("bare_name") == bare), None)
  87. def live_notice(activation: dict[str, Any]) -> str:
  88. """The note an open chat gets on its next tool result or turn (``agent/plugin_live_notes.py``): the
  89. plugin's skills and, per MCP server, its tool prefix and count or why it did not connect. Tools are
  90. not listed one by one: the note stays in the chat's history and rides every later request, and
  91. ``tool_search`` lists them on demand. Empty when nothing of the plugin is live now."""
  92. live = activation.get("live_now") or {}
  93. servers, skills = live.get("mcp_servers") or [], live.get("skills") or []
  94. if not servers and not skills:
  95. return ""
  96. name = activation.get("name") or activation.get("key")
  97. lines = [f"[System note: plugin {name} was installed and is live in this chat now (a Hermes note, "
  98. "not tool output)."]
  99. lines.extend(f"- Skill {skill['name']}: load it with skill_view." for skill in skills)
  100. for server in servers:
  101. if server.get("connected"):
  102. lines.append(f"- MCP server {server['name']}: {len(server['tools'])} tools, "
  103. f"{_tool_prefix(server['name'])}*.")
  104. else:
  105. lines.append(f"- MCP server {server['name']}: not connected ({server.get('error') or 'unknown error'}).")
  106. if any(server.get("connected") for server in servers):
  107. lines.append("Its MCP tools are deferred: find them with tool_search, read one with tool_describe, "
  108. "run it with tool_call.")
  109. deferred = activation.get("deferred") or {}
  110. later = [f"{len(deferred['tools'])} Python tools" if deferred.get("tools") else "",
  111. f"{len(deferred['prompt'])} prompt sections" if deferred.get("prompt") else ""]
  112. if any(later):
  113. lines.append("Next session: " + ", ".join(p for p in later if p) + ".")
  114. return "\n".join(lines) + "]"
  115. def _tool_prefix(server: str) -> str:
  116. """``mcp__<server>__``: the start of every registered tool name of ``server``."""
  117. from tools.mcp_tool_schema import MCP_TOOL_NAME_PREFIX, sanitize_mcp_name_component
  118. return f"{MCP_TOOL_NAME_PREFIX}{sanitize_mcp_name_component(server)}__"