The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): preserve shared MCP visibility across profile reloads
joaomarcos7107185f5825
diff --git a/gateway/run_turn.py b/gateway/run_turn.pyindex aba2ce11d1f..ae56c08d6cd 100644--- a/gateway/run_turn.py+++ b/gateway/run_turn.py@@ -2271,7 +2271,7 @@ class GatewayTurnMixin:try:from tools.mcp_tool_lifecycle import shutdown_mcp_serversfrom tools.mcp_tool_discovery import discover_mcp_tools- from tools.mcp_tool import _servers, _lock, _server_scope_keys+ from tools.mcp_tool import _servers, _lock, _server_visible_in_scopefrom tools.mcp_tool_agent import reprobe_tool_availabilityfrom tools.registry import registry@@ -2281,7 +2281,7 @@ class GatewayTurnMixin:with _lock:return {name for name in _servers- if reload_scope is None or _server_scope_keys.get(name) == reload_scope+ if _server_visible_in_scope(name, reload_scope)}old_servers = _scoped_server_names()diff --git a/tests/gateway/test_multiplex_mcp_discovery.py b/tests/gateway/test_multiplex_mcp_discovery.pyindex b0b83b696a8..2e39405c69b 100644--- a/tests/gateway/test_multiplex_mcp_discovery.py+++ b/tests/gateway/test_multiplex_mcp_discovery.py@@ -102,6 +102,83 @@ async def test_reload_mcp_only_touches_requesting_profile(assert "default-srv" not in result+async def test_reload_mcp_reports_a_shared_server_to_a_non_owner_profile(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A shared connection remains visible when its peer profile reloads MCP."""+ from gateway.run import GatewayRunner+ from tools import mcp_tool+ from tools import mcp_tool_discovery as _mcp_discovery+ from tools import mcp_tool_lifecycle as _mcp_lifecycle++ worker_home = tmp_path / "profiles" / "worker"+ worker_home.mkdir(parents=True)+ worker_scope = hermes_home_key(worker_home)+ launch_scope = hermes_home_key(tmp_path / "default")++ 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")),+ )++ live_server = SimpleNamespace(session=object(), _config={})+ monkeypatch.setattr(mcp_tool, "_servers", {"shared": live_server})+ monkeypatch.setattr(mcp_tool, "_server_scope_keys", {"shared": launch_scope})+ monkeypatch.setattr(mcp_tool, "_server_tool_scopes", {"shared": {launch_scope}}, raising=False)+ monkeypatch.setattr(mcp_tool, "_server_connecting", set())+ monkeypatch.setattr(mcp_tool, "_server_connect_errors", {})+ monkeypatch.setattr(mcp_tool, "_lazy_server_configs", {})+ monkeypatch.setattr(mcp_tool, "_mcp_registry_scope", lambda: worker_scope)++ def fake_discover() -> list[str]:+ _mcp_discovery._select_new_servers({"shared": {}})+ return ["mcp__shared__tool"]++ monkeypatch.setattr(_mcp_lifecycle, "shutdown_mcp_servers", lambda **_kwargs: None)+ monkeypatch.setattr(_mcp_discovery, "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)++ assert "No MCP servers connected." not in result+ assert "shared" in result+ assert mcp_tool._server_scope_keys["shared"] == launch_scope+ assert mcp_tool._server_tool_scopes["shared"] == {launch_scope, worker_scope}+++def test_scope_visibility_rejects_a_foreign_server_route(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ from tools import mcp_tool+ from tools import mcp_tool_discovery as _mcp_discovery++ worker_scope = hermes_home_key(tmp_path / "worker")+ launch_scope = hermes_home_key(tmp_path / "default")+ live_server = SimpleNamespace(session=object(), _config={"url": "https://default.example/mcp"})+ monkeypatch.setattr(mcp_tool, "_servers", {"shared": live_server})+ monkeypatch.setattr(mcp_tool, "_server_scope_keys", {"shared": launch_scope})+ monkeypatch.setattr(mcp_tool, "_server_tool_scopes", {"shared": {launch_scope}}, raising=False)+ monkeypatch.setattr(mcp_tool, "_server_connecting", set())+ monkeypatch.setattr(mcp_tool, "_server_connect_errors", {})+ monkeypatch.setattr(mcp_tool, "_lazy_server_configs", {})+ monkeypatch.setattr(mcp_tool, "_mcp_registry_scope", lambda: worker_scope)++ _mcp_discovery._select_new_servers({"shared": {"url": "https://worker.example/mcp"}})++ assert mcp_tool._server_tool_scopes["shared"] == {launch_scope}++def test_deregister_scope_kwarg_targets_overlay_and_keeps_plugin_confinement() -> None:from tools.registry import ToolRegistrydiff --git a/tools/mcp_tool.py b/tools/mcp_tool.pyindex 25c324ac4cb..7509aa91157 100644--- a/tools/mcp_tool.py+++ b/tools/mcp_tool.py@@ -401,6 +401,9 @@ _servers: Dict[str, MCPServerTask] = {}# Profile registry scope per live connection (None outside multiplex) so a multiplexed# /reload-mcp tears down only its own profile's servers._server_scope_keys: Dict[str, Optional[str]] = {}+# Registry scopes that have adopted a live server connection. The owning scope above remains+# authoritative for connection teardown; this set preserves visibility for shared connections.+_server_tool_scopes: Dict[str, set] = {}_server_connecting: set[str] = set()_server_connect_errors: Dict[str, str] = {}# Lazy startup: servers registered from the schema cache without connecting; popped on@@ -627,6 +630,14 @@ def _server_registry_scope(name: str) -> Optional[str]:return _mcp_registry_scope()+def _server_visible_in_scope(name: str, scope: Optional[str]) -> bool:+ """Whether a live server is visible from ``scope`` without changing its teardown owner."""+ if scope is None:+ return True+ return (_server_scope_keys.get(name) == scope+ or scope in _server_tool_scopes.get(name, ()))++# Cross-process discovery guard: advisory file lock so gateway + CLI + TUI don't all discover.# See issue #62771._LOCK_UNAVAILABLE: Any = object() # sentinel: locking broken/unavailablediff --git a/tools/mcp_tool_discovery.py b/tools/mcp_tool_discovery.pyindex 71843b01f01..a782d8e78ce 100644--- a/tools/mcp_tool_discovery.py+++ b/tools/mcp_tool_discovery.py@@ -249,6 +249,19 @@ def _select_new_servers(servers: Dict[str, dict]) -> Dict[str, dict]:for srv_name in new_servers:_core._server_scope_keys[srv_name] = current_scope_core._server_connect_errors.pop(srv_name, None)+ # A shared connection can already be owned by another profile. Record the current+ # profile's visibility separately so its scoped reload sees the connection without+ # moving teardown ownership away from the profile that opened it.+ if current_scope is not None:+ from tools.mcp_schema_cache import config_fingerprint+ for srv_name, srv_cfg in servers.items():+ if not _enabled(srv_cfg):+ continue+ server = _core._servers.get(srv_name)+ if (server is not None and getattr(server, "session", None) is not None+ and config_fingerprint(getattr(server, "_config", {}) or {})+ == config_fingerprint(srv_cfg)):+ _core._server_tool_scopes.setdefault(srv_name, set()).add(current_scope)# Track which servers opt-in to parallel tool calls (idempotent).for srv_name, srv_cfg in servers.items():if _parse_boolish(srv_cfg.get("supports_parallel_tool_calls", False), default=False):@@ -468,7 +481,7 @@ def get_mcp_status(configured: Optional[Dict[str, dict]] = None, *, include_runt# Runtime state belongs to the profile that adopted it; under a multiplexer only that# profile's view may show it, and ``include_runtime=False`` hides the launch profile's# servers from a status read scoped to a different profile.- return include_runtime and _core._server_scope_keys.get(name, None) == current_scope+ return include_runtime and _core._server_visible_in_scope(name, current_scope)active_servers = {n: s for n, s in _core._servers.items() if visible(n)}connecting = {n for n in _core._server_connecting if visible(n)}diff --git a/tools/mcp_tool_lifecycle.py b/tools/mcp_tool_lifecycle.pyindex 4bdc6f95810..0cde565f304 100644--- a/tools/mcp_tool_lifecycle.py+++ b/tools/mcp_tool_lifecycle.py@@ -107,6 +107,7 @@ def shutdown_mcp_servers(*, scope: Optional[str] = None):servers_snapshot = [_core._servers[name] for name in selected]selected_status = (set(_core._servers) | set(_core._server_scope_keys)+ | set(_core._server_tool_scopes)| set(_core._server_connecting) | set(_core._server_connect_errors)if scope is None else {name for name, owner in _core._server_scope_keys.items() if owner == scope@@ -118,6 +119,7 @@ def shutdown_mcp_servers(*, scope: Optional[str] = None):for name in selected_status:_core._server_connect_errors.pop(name, None)_core._server_scope_keys.pop(name, None)+ _core._server_tool_scopes.pop(name, None)# Fast path: nothing to shut down. The connect-cooldown maps can still be populated here — a server that# failed to connect is never recorded in ``_servers`` (that is the very premise of the #50394 cooldown),