fix(mcp): rekeyed launch-profile connections keep their owner and tools

rekey_unscoped_connections moved the bare key but left the owner in
_server_scope_keys as None and the tools in the process-global registry map.
After the switch, status read the server as configured, config pruning and
/reload-mcp (which select by owner == scope) skipped it, and teardown
deregistered from the wrong slot. The owner, the adoption set and the tool
registrations now move to the launch profile's scope with the key.
This commit is contained in:
Teknium
2026-10-20 07:39:37 -07:00
parent 35fba4c843
commit 0319e113c9
3 changed files with 84 additions and 2 deletions

View File

@@ -117,7 +117,10 @@ async def test_default_profiles_mcp_connections_survive_the_flip(standalone_host
with _profile_runtime_scope(home): # the re-wired primary handler's scope
assert check(), "default profile's live MCP server vanished after the flip"
finally:
core._servers.pop(key, None)
for stale in (key, (hermes_constants.hermes_home_key(home), key)):
core._servers.pop(stale, None)
core._server_scope_keys.pop(stale, None)
core._server_tool_scopes.pop(stale, None)
def test_default_cron_fire_and_kanban_tick_after_the_flip_keep_env_injected_credentials(standalone_host):
@@ -246,3 +249,59 @@ async def test_native_named_profile_turn_never_reads_the_launch_env(tmp_path, mo
bot.mkdir(parents=True)
seen = await _native_turn_across_activation(tmp_path, bot)
assert seen[1] == "UnscopedSecretError", seen
@pytest.mark.asyncio
async def test_default_profiles_mcp_server_is_still_owned_after_the_flip(standalone_host):
"""After the switch the default profile's live server reads connected, a config prune and
/reload-mcp (both select by owner) stop it, and its tools leave the registry."""
from tools import mcp_tool as core
from tools.mcp_tool_discovery import _adopt_server, get_mcp_status
from tools.mcp_tool_lifecycle import shutdown_mcp_servers
from tools.mcp_tool_registration import _register_server_tools
from tools.registry import registry
from gateway.run import _profile_runtime_scope
from hermes_constants import hermes_home_key
runner, home = standalone_host
cfg = {"url": "https://mcp.example/gh"}
closed = []
async def _shutdown():
closed.append("github")
tool = types.SimpleNamespace(name="t", description="d", inputSchema={"type": "object", "properties": {}},
annotations=None)
srv = types.SimpleNamespace(name="github", session=object(), _config=cfg, _tools=[tool], tool_timeout=30,
initialize_result=None, _registered_tool_names=[], _sampling=None,
_is_recycled_stdio=lambda: False, shutdown=_shutdown)
_adopt_server("github", srv) # single-profile discovery: bare key, owner None
srv._registered_tool_names = _register_server_tools("github", srv, cfg)
try:
_mkprofile(home, "daily-news-bot")
await runner.reconcile_served_profiles(reason="control-socket")
with _profile_runtime_scope(home):
from tools.mcp_tool import _mcp_registry_scope
scope = _mcp_registry_scope()
assert get_mcp_status({"github": cfg})[0]["status"] == "connected"
assert registry.get_entry("mcp__github__t") is not None
from tools import mcp_tool_loop as loop
loop._ensure_mcp_loop()
try:
shutdown_mcp_servers(scope=scope) # /reload-mcp's teardown for this profile
finally:
loop._stop_mcp_loop()
srv_tools = list(srv._registered_tool_names)
from tools.mcp_tool_registration import _deregister_mcp_tool_all_scopes
for name in srv_tools: # the task's own _deregister_tools on shutdown
_deregister_mcp_tool_all_scopes(srv, name)
assert closed == ["github"], "the reload skipped the default profile's server"
assert (hermes_home_key(home), "github") not in core._servers
assert registry.get_entry("mcp__github__t", scope=hermes_home_key(home)) is None
assert "mcp__github__t" not in registry._tools
finally:
for key in [k for k in core._servers if (k[1] if isinstance(k, tuple) else k) == "github"]:
core._servers.pop(key, None)
core._server_scope_keys.pop(key, None)
core._server_tool_scopes.pop(key, None)
for slot in (None, hermes_home_key(home)):
registry.deregister("mcp__github__t", scope=slot)

View File

@@ -63,7 +63,7 @@ def _resolve_server_key(name: str, scope: Optional[str] = None, *, current: bool
return own
# Ledgers keyed by connection key (``tools.mcp_tool``); ``_server_scope_keys`` keeps its owner value.
# Ledgers keyed by connection key (``tools.mcp_tool``).
_KEYED_LEDGERS = (
"_servers", "_server_scope_keys", "_server_tool_scopes", "_server_connect_errors",
"_lazy_server_configs", "_lazy_server_fingerprints", "_lazy_server_tool_names",
@@ -77,6 +77,7 @@ def rekey_unscoped_connections(scope: str) -> None:
"""Move every bare-name connection under ``(scope, name)``. A single-profile process keys its
connections by bare name; once it starts multiplexing, the launch profile's lookups resolve
``(launch scope, name)``, so without this its live servers read as disconnected until a restart."""
from tools.registry import registry
with _core._lock:
for attr in _KEYED_LEDGERS:
ledger = getattr(_core, attr)
@@ -87,3 +88,15 @@ def rekey_unscoped_connections(scope: str) -> None:
bare = {k for k in keys if isinstance(k, str)}
keys.difference_update(bare)
keys.update((scope, k) for k in bare)
# The owner and the tools follow the key: status, config pruning and /reload-mcp select by
# owner == scope, and teardown deregisters from the owner's overlay, not the global map.
tool_names = []
for key in [k for k, owner in _core._server_scope_keys.items() if owner is None and _key_scope(k) == scope]:
_core._server_scope_keys[key] = scope
tool_names += getattr(_core._servers.get(key), "_registered_tool_names", None) or ()
for key in [k for k in _core._lazy_server_tool_names if _key_scope(k) == scope]:
tool_names += _core._lazy_server_tool_names[key]
for key in set(_core._servers) | set(_core._lazy_server_tool_names):
if _key_scope(key) == scope:
_core._server_tool_scopes.setdefault(key, set()).add(scope)
registry.move_to_scope(tool_names, scope)

View File

@@ -843,6 +843,16 @@ class ToolRegistry:
self._generation += 1
logger.debug("Deregistered tool: %s", name)
def move_to_scope(self, names, scope: str) -> None:
"""Move process-global registrations into *scope*'s overlay (a single-profile process that
starts multiplexing hands its launch profile's MCP tools to that profile's own scope)."""
scope = normalize_scope(scope)
with self._lock:
moved = {name: self._tools.pop(name) for name in names if name in self._tools}
if moved:
self._slot(scope, create=True).update(moved)
self._generation += 1
def restore_registration(
self, name: str, current: ToolEntry, previous: Optional[ToolEntry], *,
scope: Optional[str] = None) -> bool: