The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): reload-plugins connects the enabled plugin's MCP servers now
Teknium15c394d9caf2
diff --git a/gateway/run_plugin_rewire.py b/gateway/run_plugin_rewire.pyindex ac4f7ea6635..429155c3aec 100644--- a/gateway/run_plugin_rewire.py+++ b/gateway/run_plugin_rewire.py@@ -15,6 +15,7 @@ from __future__ import annotationsimport asyncioimport contextlibimport logging+import threadingfrom pathlib import Pathfrom typing import Any, Callable, Dict, Optional@@ -112,6 +113,7 @@ def reload_plugins_verb(runner: Any, loop: asyncio.AbstractEventLoop) -> Callabl# enabling caller asks for the restart that loads it.names = sorted(manager._plugins)activations = activation_summaries(manager) + dependency_blocked_summaries(manager)+ _reconcile_plugin_mcp_servers(runner, requested)try:rewired = asyncio.run_coroutine_threadsafe(_count_adapters(runner, profile_name), loop).result(timeout=5.0)except Exception:@@ -122,6 +124,41 @@ def reload_plugins_verb(runner: Any, loop: asyncio.AbstractEventLoop) -> Callablreturn _handler+# Long enough for a local stdio server to connect, short enough to stay well inside the caller's+# 30 s socket timeout: a slow server keeps connecting in the background after the answer goes out.+_MCP_CONNECT_WAIT_S = 10.0+++def _reconcile_plugin_mcp_servers(runner: Any, home: Path) -> None:+ """Connect the MCP servers a just-enabled plugin declares (and drop a disabled one's) now, so the+ next session's tool list has them. The forced re-discovery only registers their configs; until+ this, the housekeeping reconcile connected them up to a minute later, and every session started in+ that window came up without the plugin's tools. Runs under the same profile scope that chore binds,+ on its own thread so a slow server delays the answer by at most ``_MCP_CONNECT_WAIT_S``."""+ from gateway.run import _profile_runtime_scope+ from gateway.run_turn import GatewayTurnMixin++ multiplex = bool(getattr(getattr(runner, "config", None), "multiplex_profiles", False))++ def _reconcile() -> None:+ from tools.mcp_oauth import suppress_interactive_oauth+ from tools.mcp_tool_discovery import reconcile_mcp_servers_with_config+ scope = _profile_runtime_scope(home) if multiplex else GatewayTurnMixin._standalone_launch_scope()+ try:+ with scope, suppress_interactive_oauth():+ result = reconcile_mcp_servers_with_config()+ except Exception:+ logger.warning("MCP reconcile after reload-plugins failed for %s", home, exc_info=True)+ return+ if result["removed"] or result["added"]:+ logger.info("MCP servers reconciled after reload-plugins (%s): removed=%s added=%s",+ home, result["removed"], result["added"])++ thread = threading.Thread(target=_reconcile, name="reload-plugins-mcp", daemon=True)+ thread.start()+ thread.join(timeout=_MCP_CONNECT_WAIT_S)++async def _count_adapters(runner: Any, profile_name: Optional[str]) -> int:"""Live adapters for the profile; scheduled after the loaded-event callback, so they are re-wired."""if profile_name is None:diff --git a/tests/gateway/test_reload_plugins_connects_mcp.py b/tests/gateway/test_reload_plugins_connects_mcp.pynew file mode 100644index 00000000000..9c4fd957e6c--- /dev/null+++ b/tests/gateway/test_reload_plugins_connects_mcp.py@@ -0,0 +1,80 @@+"""The gateway's ``reload-plugins`` verb connects an enabled plugin's MCP servers before it answers.++``hermes plugins install`` (a "y" at Enable-now, or ``--enable``), ``plugins enable`` and the Desktop+ask the running gateway to reload plugins, then tell the user the plugin's MCP servers apply "next+session". The forced re-discovery only registered the server configs; the servers connected on the+next housekeeping reconcile tick, up to a minute later, so a session started in between had none of+the plugin's MCP tools. Real plugin dir, real stdio MCP server, real registry: no fakes on that path.+"""++from __future__ import annotations++import asyncio+import json+import sys+import threading+from types import SimpleNamespace++import pytest++pytest.importorskip("mcp")++SERVER = '''\+import json, sys+TOOL = {"name": "ping", "description": "Probe tool.", "inputSchema": {"type": "object", "properties": {}}}+for line in sys.stdin:+ msg = json.loads(line) if line.strip() else {}+ rid = msg.get("id")+ if rid is None:+ continue+ method = msg.get("method")+ result = ({"protocolVersion": msg["params"].get("protocolVersion"), "capabilities": {"tools": {}},+ "serverInfo": {"name": "rpprobe", "version": "1"}} if method == "initialize"+ else {"tools": [TOOL]} if method == "tools/list" else {})+ sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": rid, "result": result}) + "\\n")+ sys.stdout.flush()+'''+++def gateway_home(tmp_path, monkeypatch):+ home = tmp_path / "hermes-home"+ plugin = home / "plugins" / "rpprobe"+ plugin.mkdir(parents=True)+ (plugin / "plugin.json").write_text(json.dumps({+ "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",+ "name": "rpprobe", "version": "0.1.0", "description": "reload-plugins MCP probe"}), encoding="utf-8")+ server = plugin / "server.py"+ server.write_text(f"#!{sys.executable}\n{SERVER}", encoding="utf-8")+ server.chmod(0o755)+ (plugin / "mcp.json").write_text(json.dumps({+ "$schema": "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",+ "mcpServers": {"rpprobe": {"type": "stdio", "command": "./server.py", "args": []}}}), encoding="utf-8")+ (home / "config.yaml").write_text("plugins:\n enabled: [rpprobe]\n disabled: []\n", encoding="utf-8")+ monkeypatch.setenv("HERMES_HOME", str(home))+ from hermes_cli import plugins+ from tools.mcp_tool_lifecycle import shutdown_mcp_servers+ plugins._reset_plugin_managers_for_tests()+ loop = asyncio.new_event_loop()+ thread = threading.Thread(target=loop.run_forever, daemon=True)+ thread.start()+ try:+ yield home, loop+ finally:+ shutdown_mcp_servers()+ loop.call_soon_threadsafe(loop.stop)+ thread.join(timeout=5)+ loop.close()+ plugins._reset_plugin_managers_for_tests()+++def test_reload_plugins_answers_with_the_plugins_mcp_tools_already_registered(gateway_home):+ from gateway.run_plugin_rewire import reload_plugins_verb+ from tools.registry import registry+ _home, loop = gateway_home+ runner = SimpleNamespace(config=SimpleNamespace(multiplex_profiles=False), adapters={})++ answer = reload_plugins_verb(runner, loop)({})++ assert answer["reloaded"] is True and "rpprobe" in answer["plugins"]+ assert "mcp__rpprobe__ping" in registry.get_all_tool_names()