Skip to content

The agent that grows with you

fix(gateway): discover and reload MCP servers per profile under multiplex

Tekniumee0e234a2c0d
diff --git a/gateway/run.py b/gateway/run.py
index c65af2e8aba..862fe4f5b7b 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -2700,6 +2700,33 @@ def load_gateway_config_for_runner() -> "GatewayConfig":
return cfg
+async def _discover_gateway_mcp_tools(config: object) -> None:
+ """Run startup MCP discovery for every profile this gateway serves.
+
+ ``discover_mcp_tools`` reads ``mcp_servers`` from ``get_hermes_home()``'s
+ config, so an unscoped call only ever connects the launch profile's
+ servers (#95518). Under multiplex, run it once per served profile inside
+ that profile's ``_profile_runtime_scope`` and carry the scope into the
+ executor thread with ``copy_context()`` (the same shape as
+ ``_run_in_executor_with_context``). Single-profile gateways keep the one
+ unscoped call.
+ """
+ from tools.mcp_tool import discover_mcp_tools
+
+ loop = asyncio.get_running_loop()
+ if not getattr(config, "multiplex_profiles", False):
+ await loop.run_in_executor(None, discover_mcp_tools)
+ return
+ for profile_name, profile_home in _multiplex_profile_homes(config):
+ try:
+ with _profile_runtime_scope(Path(profile_home)):
+ await loop.run_in_executor(None, copy_context().run, discover_mcp_tools)
+ except Exception:
+ logger.warning(
+ "MCP tool discovery failed for profile '%s'", profile_name, exc_info=True,
+ )
+
+
def _platform_has_bot_credential(platform: "Platform", platform_config: "PlatformConfig") -> bool:
"""Return True when a token-authenticated platform has a usable bot credential.
@@ -3089,6 +3116,7 @@ from gateway.session import (
SessionSource,
SessionContext,
TranscriptReadError,
+ _session_key_namespace,
build_session_context,
build_session_context_prompt,
build_channel_continuity_note,
@@ -26184,25 +26212,53 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew
Split out from ``_handle_reload_mcp_command`` so the confirmation
wrapper can invoke the same path whether the user confirmed via
button, text reply, or has the confirm gate disabled.
+
+ Under multiplex the reload runs inside the requesting profile's
+ runtime scope (entered here when the caller — e.g. a button-confirm
+ callback — did not), and only that profile's servers are torn down
+ and rediscovered (#95518).
"""
- loop = asyncio.get_running_loop()
+ multiplex = bool(getattr(self.config, "multiplex_profiles", False))
+ if multiplex and not get_hermes_home_override():
+ profile_home = self._resolve_profile_home_for_source(event.source)
+ with _profile_runtime_scope(Path(profile_home)):
+ return await self._execute_mcp_reload(event)
try:
from tools.mcp_tool import shutdown_mcp_servers, discover_mcp_tools, _servers, _lock
+ from tools.mcp_tool import _server_scope_keys
+ from tools.registry import registry
+
+ reload_scope = registry.current_scope_key() if multiplex else None
+
+ def _scoped_server_names() -> set:
+ with _lock:
+ return {
+ name for name in _servers
+ if reload_scope is None or _server_scope_keys.get(name) == reload_scope
+ }
# Capture old server names before shutdown
- with _lock:
- old_servers = set(_servers.keys())
+ old_servers = _scoped_server_names()
# Read new config before shutting down, so we know what will be added/removed
# Shutdown existing connections
- await loop.run_in_executor(None, shutdown_mcp_servers)
+ await self._run_in_executor_with_context(
+ lambda: shutdown_mcp_servers(scope=reload_scope)
+ )
# Reconnect by discovering tools (reads config.yaml fresh)
- new_tools = await loop.run_in_executor(None, discover_mcp_tools)
+ new_tools = await self._run_in_executor_with_context(discover_mcp_tools)
# Compute what changed
- with _lock:
- connected_servers = set(_servers.keys())
+ connected_servers = _scoped_server_names()
+ if reload_scope is not None:
+ from tools.mcp_tool import _mcp_tool_server_names
+
+ with _lock:
+ new_tools = [
+ n for n in new_tools
+ if _mcp_tool_server_names.get(n) in connected_servers
+ ]
added = connected_servers - old_servers
removed = old_servers - connected_servers
@@ -26231,8 +26287,17 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew
_cache = getattr(self, "_agent_cache", None)
_cache_lock = getattr(self, "_agent_cache_lock", None)
if _cache_lock is not None and _cache:
+ # Multiplex: only this profile's sessions. Rebuilding
+ # another profile's agent inside this scope would hand it
+ # this profile's tool registry.
+ _ns_prefix = (
+ _session_key_namespace(event.source.profile) + ":"
+ if multiplex else None
+ )
with _cache_lock:
for _sess_key, _entry in list(_cache.items()):
+ if _ns_prefix and not str(_sess_key).startswith(_ns_prefix):
+ continue
try:
_agent = _entry[0] if isinstance(_entry, tuple) else _entry
except Exception:
@@ -34034,9 +34099,7 @@ async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool =
# heartbeats (Discord shard, Telegram polling) until it returned.
# See #16856.
try:
- from tools.mcp_tool import discover_mcp_tools
- _loop = asyncio.get_running_loop()
- await _loop.run_in_executor(None, discover_mcp_tools)
+ await _discover_gateway_mcp_tools(runner.config)
except Exception as e:
logger.debug("MCP tool discovery failed: %s", e)
diff --git a/tests/gateway/test_multiplex_mcp_discovery.py b/tests/gateway/test_multiplex_mcp_discovery.py
new file mode 100644
index 00000000000..633b39b7558
--- /dev/null
+++ b/tests/gateway/test_multiplex_mcp_discovery.py
@@ -0,0 +1,121 @@
+"""Multiplexed gateways discover and reload MCP servers per profile (#95518)."""
+
+from __future__ import annotations
+
+import threading
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import MagicMock
+
+import pytest
+
+from gateway.config import GatewayConfig, Platform
+from gateway.platforms.base import MessageEvent
+from gateway.session import SessionSource
+from hermes_constants import get_hermes_home, hermes_home_key
+
+
+async def test_gateway_boot_discovers_mcp_under_every_profile_home(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ import gateway.run as gateway_run
+ from tools import mcp_tool
+
+ homes = [("default", tmp_path / "default"), ("worker", tmp_path / "worker")]
+ for _name, home in homes:
+ home.mkdir()
+ seen: list[tuple[Path, str]] = []
+
+ def fake_discover() -> list[str]:
+ seen.append((get_hermes_home(), threading.current_thread().name))
+ return []
+
+ monkeypatch.setattr(
+ "hermes_cli.profiles.profiles_to_serve",
+ lambda multiplex, profile_allowlist=None: homes,
+ )
+ monkeypatch.setattr(mcp_tool, "discover_mcp_tools", fake_discover)
+
+ await gateway_run._discover_gateway_mcp_tools(GatewayConfig(multiplex_profiles=True))
+
+ # Ran once per profile, under that profile's home, off the loop thread.
+ assert [home for home, _ in seen] == [home for _, home in homes]
+ assert all(thread != threading.current_thread().name for _, thread in seen)
+
+
+async def test_reload_mcp_only_touches_requesting_profile(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from gateway.run import GatewayRunner
+ from tools import mcp_tool
+
+ worker_home = tmp_path / "profiles" / "worker"
+ worker_home.mkdir(parents=True)
+ worker_scope = hermes_home_key(worker_home)
+
+ runner = GatewayRunner.__new__(GatewayRunner)
+ runner.config = GatewayConfig(multiplex_profiles=True)
+ runner._resolve_profile_home_for_source = MagicMock(return_value=worker_home)
+ runner._agent_cache = {}
+ runner._agent_cache_lock = None
+ runner._async_session_store = SimpleNamespace(
+ get_or_create_session=MagicMock(side_effect=RuntimeError("skip transcript")),
+ )
+
+ monkeypatch.setattr(mcp_tool, "_servers", {"default-srv": object(), "worker-srv": object()})
+ monkeypatch.setattr(
+ mcp_tool, "_server_scope_keys",
+ {"default-srv": hermes_home_key(tmp_path), "worker-srv": worker_scope},
+ )
+ seen: list[tuple] = []
+
+ def fake_shutdown(*, scope=None) -> None:
+ seen.append(("shutdown", scope, get_hermes_home()))
+
+ def fake_discover() -> list[str]:
+ seen.append(("discover", get_hermes_home()))
+ return []
+
+ monkeypatch.setattr(mcp_tool, "shutdown_mcp_servers", fake_shutdown)
+ monkeypatch.setattr(mcp_tool, "discover_mcp_tools", fake_discover)
+
+ event = MessageEvent(
+ text="/reload-mcp", message_id="m1",
+ source=SessionSource(
+ platform=Platform.TELEGRAM, user_id="u1", chat_id="c1",
+ chat_type="dm", profile="worker",
+ ),
+ )
+ result = await runner._execute_mcp_reload(event)
+
+ # Entered worker's scope itself, shut down only worker's servers, and
+ # reported only worker's servers (default's untouched connection is not
+ # "removed").
+ assert seen == [
+ ("shutdown", worker_scope, worker_home),
+ ("discover", worker_home),
+ ]
+ assert "default-srv" not in result
+
+
+def test_deregister_scope_kwarg_targets_overlay_and_keeps_plugin_confinement() -> None:
+ from tools.registry import ToolRegistry
+
+ reg = ToolRegistry()
+ reg.register("mcp__s__t", "mcp-s", {"name": "mcp__s__t", "description": "d"},
+ lambda **kw: None, scope="/home/p1")
+ assert reg.snapshot_registration("mcp__s__t", scope="/home/p1") is not None
+
+ reg.deregister("mcp__s__t") # unscoped: global slot only, overlay untouched
+ assert reg.snapshot_registration("mcp__s__t", scope="/home/p1") is not None
+
+ reg.deregister("mcp__s__t", scope="/home/p1")
+ assert reg.snapshot_registration("mcp__s__t", scope="/home/p1") is None
+
+ # A plugin module may not name another profile's overlay.
+ reg._plugin_module_scopes["hermes_plugins.p"] = {"/home/p1"}
+ reg._caller_module = staticmethod(lambda: "hermes_plugins.p")
+ with pytest.raises(PermissionError):
+ reg.deregister("anything", scope="/home/p2")
diff --git a/tests/tools/test_mcp_lazy_start.py b/tests/tools/test_mcp_lazy_start.py
index 85312c0fc2a..dedb3de115f 100644
--- a/tests/tools/test_mcp_lazy_start.py
+++ b/tests/tools/test_mcp_lazy_start.py
@@ -285,7 +285,7 @@ class TestLazyFirstUseConnect:
patch.object(registry, "deregister") as mock_dereg:
assert mcp._ensure_lazy_server_connected("playwright") is True
- mock_dereg.assert_called_once_with("mcp_playwright_tool_x")
+ mock_dereg.assert_called_once_with("mcp_playwright_tool_x", scope=None)
def test_lazy_connect_failure_records_cooldown(self):
mcp._lazy_server_configs["playwright"] = {"command": "npx", "lazy": True}
diff --git a/tools/mcp_tool.py b/tools/mcp_tool.py
index 7f92122c3f0..dab35f47779 100644
--- a/tools/mcp_tool.py
+++ b/tools/mcp_tool.py
@@ -2807,7 +2807,7 @@ class MCPServerTask:
# is currently owned by another server.
if registry.get_toolset_for_tool(tool_name) != toolset_name:
continue
- registry.deregister(tool_name)
+ registry.deregister(tool_name, scope=_server_registry_scope(self.name))
_forget_mcp_tool_server(tool_name)
# 3. Re-register with the fresh list. The helper may skip names that
@@ -2825,7 +2825,7 @@ class MCPServerTask:
for tool_name in old_tool_names - registered_name_set:
if registry.get_toolset_for_tool(tool_name) != toolset_name:
continue
- registry.deregister(tool_name)
+ registry.deregister(tool_name, scope=_server_registry_scope(self.name))
_forget_mcp_tool_server(tool_name)
self._registered_tool_names = registered_names
@@ -4481,7 +4481,7 @@ class MCPServerTask:
from tools.registry import registry
for tool_name in list(getattr(self, "_registered_tool_names", [])):
- registry.deregister(tool_name)
+ registry.deregister(tool_name, scope=_server_registry_scope(self.name))
_forget_mcp_tool_server(tool_name)
self._registered_tool_names = []
@@ -4509,6 +4509,10 @@ class MCPServerTask:
# ---------------------------------------------------------------------------
_servers: Dict[str, MCPServerTask] = {}
+# Profile registry scope that owns each live connection (None outside
+# multiplex). A multiplexed /reload-mcp tears down only its own profile's
+# servers; process shutdown still takes everything.
+_server_scope_keys: Dict[str, Optional[str]] = {}
_server_connecting: set[str] = set()
_server_connect_errors: Dict[str, str] = {}
# Lazy MCP startup (#56832): servers whose tools were registered from the
@@ -5400,6 +5404,36 @@ _mcp_thread: Optional[threading.Thread] = None
# _parallel_safe_servers, _mcp_tool_server_names, and _stdio_pids.
_lock = threading.Lock()
+
+def _mcp_registry_scope() -> Optional[str]:
+ """Registry scope owning MCP registrations made from the current context.
+
+ Under a profile multiplexer each profile's MCP tools live in that
+ profile's registry overlay (the same overlay its plugins use) so two
+ profiles' servers never share one process-global slot. Single-profile
+ processes keep MCP tools process-global (``None``).
+ """
+ from agent.secret_scope import is_multiplex_active
+
+ if not is_multiplex_active():
+ return None
+ from tools.registry import registry
+
+ return registry.current_scope_key()
+
+
+def _server_registry_scope(name: str) -> Optional[str]:
+ """Scope owning server *name*'s tools: recorded at connect, else current.
+
+ Teardown paths run on the MCP loop (process exit, reconnect exhaustion),
+ which does not carry the discovering profile's context, so the scope
+ captured when the server was adopted into ``_servers`` is authoritative.
+ """
+ if name in _server_scope_keys:
+ return _server_scope_keys[name]
+ return _mcp_registry_scope()
+
+
# ---------------------------------------------------------------------------
# Cross-process MCP discovery guard
# ---------------------------------------------------------------------------
@@ -6131,7 +6165,7 @@ def _ensure_lazy_server_connected(server_name: str) -> bool:
from tools.registry import registry
for tool_name in phantom_names:
- registry.deregister(tool_name)
+ registry.deregister(tool_name, scope=_server_registry_scope(server_name))
_forget_mcp_tool_server(tool_name)
logger.info(
"MCP server '%s': deregistered %d phantom cached tool(s) not "
@@ -7523,6 +7557,7 @@ def _register_server_tools(name: str, server: MCPServerTask, config: dict) -> Li
check_fn=candidate["check_fn"],
is_async=False,
description=candidate["schema"]["description"],
+ scope=_server_registry_scope(name),
)
# The pre-check above is advisory only. Multiple servers connect in
@@ -7680,6 +7715,7 @@ def _register_from_cache_sync(name: str, config: dict, entry: dict) -> List[str]
check_fn=check_fn,
is_async=False,
description=schema["description"],
+ scope=_mcp_registry_scope(),
)
if registry.get_toolset_for_tool(registry_name) != toolset_name:
continue
@@ -7713,6 +7749,7 @@ def _register_from_cache_sync(name: str, config: dict, entry: dict) -> List[str]
check_fn=check_fn,
is_async=False,
description=schema.get("description") or "",
+ scope=_mcp_registry_scope(),
)
if registry.get_toolset_for_tool(util_name) != toolset_name:
continue
@@ -7770,6 +7807,7 @@ async def _discover_and_register_server(name: str, config: dict) -> List[str]:
# self-probe, so adopt it into the registry for shutdown/revival.
with _lock:
_servers[name] = server
+ _server_scope_keys[name] = _mcp_registry_scope()
elif server is not None:
await server.shutdown()
raise
@@ -7780,6 +7818,7 @@ async def _discover_and_register_server(name: str, config: dict) -> List[str]:
_server_connecting.discard(name)
_server_connect_errors.pop(name, None)
_servers[name] = server
+ _server_scope_keys[name] = _mcp_registry_scope()
registered_names = _register_server_tools(name, server, config)
server._registered_tool_names = list(registered_names)
@@ -8511,15 +8550,24 @@ def _reinject_post_build_tools(agent, tools_list: list, name_set: set) -> set:
return staged_engine_names
-def shutdown_mcp_servers():
- """Close all MCP server connections and stop the background loop.
+def shutdown_mcp_servers(*, scope: Optional[str] = None):
+ """Close MCP server connections and stop the background loop.
Each server Task is signalled to exit its ``async with`` block so that
the anyio cancel-scope cleanup happens in the same Task that opened it.
All servers are shut down in parallel via ``asyncio.gather``.
+
+ ``scope`` (a registry scope key) restricts teardown to the servers one
+ multiplexed profile owns — its ``/reload-mcp`` must not kill the other
+ profiles' connections — and leaves the shared loop running when anything
+ else is still connected. Without it every server goes, as before.
"""
with _lock:
- servers_snapshot = list(_servers.values())
+ selected = [
+ name for name in _servers
+ if scope is None or _server_scope_keys.get(name) == scope
+ ]
+ servers_snapshot = [_servers[name] for name in selected]
# Fast path: nothing to shut down. The connect-cooldown maps can still
# be populated here — a server that failed to connect is never recorded
@@ -8531,7 +8579,7 @@ def shutdown_mcp_servers():
with _lock:
_server_connect_retry_after.clear()
_server_connect_failures.clear()
- _stop_mcp_loop()
+ _stop_mcp_loop(only_if_idle=scope is not None)
return
async def _shutdown():
@@ -8545,7 +8593,9 @@ def shutdown_mcp_servers():
"Error closing MCP server '%s': %s", server.name, result,
)
with _lock:
- _servers.clear()
+ for name in selected:
+ _servers.pop(name, None)
+ _server_scope_keys.pop(name, None)
# Drop connect-retry cooldowns too: a full shutdown/restart
# should re-attempt every server immediately, not honour a
# stale per-server backoff from before the restart (#50394).
@@ -8575,7 +8625,7 @@ def shutdown_mcp_servers():
_server_connect_retry_after.clear()
_server_connect_failures.clear()
- _stop_mcp_loop()
+ _stop_mcp_loop(only_if_idle=scope is not None)
def _kill_orphaned_mcp_children(
diff --git a/tools/registry.py b/tools/registry.py
index 7107b3ad316..921f1886671 100644
--- a/tools/registry.py
+++ b/tools/registry.py
@@ -906,13 +906,18 @@ class ToolRegistry:
self._toolset_checks[toolset] = check_fn
self._generation += 1
- def deregister(self, name: str) -> None:
+ def deregister(self, name: str, *, scope: Optional[str] = None) -> None:
"""Remove a tool from the registry.
Also cleans up the toolset check if no other tools remain in the
same toolset. Used by MCP dynamic tool discovery to nuke-and-repave
when a server sends ``notifications/tools/list_changed``.
+ ``scope`` selects a profile overlay explicitly (multiplexed MCP tools
+ live in the owning profile's overlay). Plugin callers keep their own
+ scope and may not name another one; non-plugin callers without
+ ``scope`` keep the historical process-global target.
+
Gated by the same operator opt-in policy ``register(override=True)``
enforces. Without this, a plugin could bypass that gate entirely by
deregistering a tool it doesn't own and then calling plain
@@ -930,14 +935,21 @@ class ToolRegistry:
if caller_owner is not None
else None
)
+ if caller_owner is not None and scope is not None and scope != caller_scope:
+ raise PermissionError(
+ f"Plugin module {caller_mod!r} cannot deregister tools "
+ "outside its own profile scope."
+ )
+ if scope is None:
+ scope = caller_scope
target = (
- self._scoped_tools.get(caller_scope, {})
- if caller_scope is not None
+ self._scoped_tools.get(scope, {})
+ if scope is not None
else self._tools
)
entry = target.get(name)
- if entry is None and caller_scope is not None:
- if name in self._tools:
+ if entry is None and scope is not None:
+ if caller_owner is not None and name in self._tools:
raise PermissionError(
f"Scoped plugin module {caller_mod!r} cannot deregister "
f"process-global tool {name!r}; register a scoped "
@@ -977,13 +989,13 @@ class ToolRegistry:
f"opt-in (allow_tool_override)."
)
del target[name]
- if caller_scope is not None and not target:
- self._scoped_tools.pop(caller_scope, None)
+ if scope is not None and not target:
+ self._scoped_tools.pop(scope, None)
# Drop the toolset check and aliases if this was the last tool in
# that toolset.
toolset_still_exists = any(
e.toolset == entry.toolset
- for e in self._merged_tools(caller_scope).values()
+ for e in self._merged_tools(scope).values()
)
if not toolset_still_exists:
self._toolset_checks.pop(entry.toolset, None)