Skip to content

The agent that grows with you

fix(mcp): a profile only adopts a shared connection whose resolved identity matches its own

John Paul Soliva921aa601646e
diff --git a/tests/gateway/test_multiplex_mcp_discovery.py b/tests/gateway/test_multiplex_mcp_discovery.py
index 5da2b4c5842..b58d5de35ee 100644
--- a/tests/gateway/test_multiplex_mcp_discovery.py
+++ b/tests/gateway/test_multiplex_mcp_discovery.py
@@ -174,8 +174,13 @@ async def test_reload_mcp_reports_a_shared_server_to_a_non_owner_profile(
get_or_create_session=MagicMock(side_effect=RuntimeError("skip transcript")),
)
- live_server = SimpleNamespace(session=object(), _config={}, _tools=[], tool_timeout=30,
- initialize_result=None, _registered_tool_names=[])
+ from tools import mcp_tool_registration as _mcp_registration
+ # Premise: both profiles resolve the connection's inputs identically (the reload runs under
+ # the worker's runtime scope, which this fake's owner never had).
+ monkeypatch.setattr(_mcp_registration, "_resolved_identity", lambda *_args: "same-identity")
+ live_server = SimpleNamespace(name="shared", session=object(), _config={}, _tools=[], tool_timeout=30,
+ initialize_result=None, _registered_tool_names=[],
+ _resolved_identity="same-identity")
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)
@@ -244,6 +249,7 @@ def test_shared_server_tools_are_callable_and_removed_on_non_owner_reload(
from tools import mcp_tool
from tools import mcp_tool_config as _mcp_config
from tools import mcp_tool_discovery as _mcp_discovery
+ from tools import mcp_tool_registration as _mcp_registration
from tools.registry import registry
worker_home = tmp_path / "profiles" / "worker"
@@ -268,6 +274,7 @@ def test_shared_server_tools_are_callable_and_removed_on_non_owner_reload(
_registered_tool_names=[],
_config={},
initialize_result=None,
+ _resolved_identity=_mcp_registration._resolved_identity("shared", {}),
)
owner_tool_name = "mcp__shared__echo"
registry.register(
diff --git a/tests/tools/test_mcp_multiplex_connection_keys.py b/tests/tools/test_mcp_multiplex_connection_keys.py
index 940864eade4..7112c4b2e3f 100644
--- a/tests/tools/test_mcp_multiplex_connection_keys.py
+++ b/tests/tools/test_mcp_multiplex_connection_keys.py
@@ -18,8 +18,10 @@ def _tool():
def _server(name, cfg):
+ from tools.mcp_tool_registration import _resolved_identity
return SimpleNamespace(name=name, session=object(), _config=cfg, _tools=[_tool()], tool_timeout=30,
- initialize_result=None, _registered_tool_names=[], _sampling=None)
+ initialize_result=None, _registered_tool_names=[], _sampling=None,
+ _resolved_identity=_resolved_identity(name, cfg))
@pytest.fixture
diff --git a/tests/tools/test_mcp_shared_connection_resolved_identity.py b/tests/tools/test_mcp_shared_connection_resolved_identity.py
new file mode 100644
index 00000000000..6dff8bce76b
--- /dev/null
+++ b/tests/tools/test_mcp_shared_connection_resolved_identity.py
@@ -0,0 +1,150 @@
+"""A multiplexed profile never adopts another profile's live MCP connection when the inputs that
+connection was opened with resolve differently for it: external secret-source env on a stdio
+child, or ``identity_header.value_from: profile`` on HTTP. Both profiles have byte-identical
+``mcp_servers`` config, so only the resolved values tell the identities apart."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import subprocess
+import sys
+import textwrap
+import time
+from pathlib import Path
+
+import pytest
+import yaml
+
+_MODEL = {"default": "x", "provider": "custom", "base_url": "http://127.0.0.1:9/v1"}
+
+_STDIO_SERVER = """
+import os
+from mcp.server import MCPServer
+server = MCPServer("gh")
+
+def whoami() -> str:
+ return "GH_TOKEN=" + str(os.environ.get("GH_TOKEN"))
+
+server.run("stdio")
+"""
+
+_HTTP_SERVER = """
+import asyncio, json, socket, sys
+import uvicorn
+from mcp.server import MCPServer
+log_path, port_path = sys.argv[1], sys.argv[2]
+server = MCPServer("team")
+
+def save_note(text: str) -> str:
+ return "saved"
+
+def recording(app):
+ async def wrapped(scope, receive, send):
+ if scope["type"] == "http" and scope.get("method") == "POST":
+ body = b""
+ while True:
+ event = await receive()
+ body += event.get("body", b"")
+ if not event.get("more_body"):
+ break
+ headers = {k.decode().lower(): v.decode() for k, v in scope["headers"]}
+ try:
+ method = json.loads(body).get("method")
+ except Exception:
+ method = None
+ with open(log_path, "a") as fh:
+ fh.write(json.dumps([method, headers.get("x-hermes-profile")]) + "\\n")
+ replayed = False
+
+ async def replay():
+ nonlocal replayed
+ if replayed:
+ return await receive()
+ replayed = True
+ return {"type": "http.request", "body": body, "more_body": False}
+ return await app(scope, replay, send)
+ return await app(scope, receive, send)
+ return wrapped
+
+sock = socket.socket()
+sock.bind(("127.0.0.1", 0))
+uv = uvicorn.Server(uvicorn.Config(recording(server.streamable_http_app()), log_level="warning"))
+
+async def main():
+ task = asyncio.create_task(uv.serve(sockets=[sock]))
+ while not uv.started:
+ await asyncio.sleep(0.01)
+ open(port_path, "w").write(str(sock.getsockname()[1]))
+ await task
+
+asyncio.run(main())
+"""
+
+
+def two_profile_homes(tmp_path, monkeypatch):
+ """default + worker profile homes under a temp HOME; MCP connections shut down afterwards."""
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HOME", str(tmp_path))
+ default_home = tmp_path / ".hermes"
+ worker_home = default_home / "profiles" / "worker"
+ worker_home.mkdir(parents=True)
+ monkeypatch.setenv("HERMES_HOME", str(default_home))
+ monkeypatch.setenv("NO_PROXY", "*")
+ yield {"default": default_home, "worker": worker_home}
+ from tools.mcp_tool_lifecycle import shutdown_mcp_servers
+ shutdown_mcp_servers()
+
+
+def _discover_and_call(homes: dict, tool: str, args: dict) -> dict:
+ import gateway.run as gateway_run
+ from gateway.config import GatewayConfig
+ from tools.registry import registry
+
+ asyncio.run(gateway_run._discover_gateway_mcp_tools(GatewayConfig(multiplex_profiles=True)))
+ results = {}
+ for name, home in homes.items():
+ with gateway_run._profile_runtime_scope(home):
+ results[name] = json.loads(registry.dispatch(tool, args)).get("result")
+ return results
+
+
+def test_profile_with_other_secret_source_value_gets_its_own_stdio_connection(two_profile_homes, tmp_path):
+ server = tmp_path / "gh_server.py"
+ server.write_text(textwrap.dedent(_STDIO_SERVER))
+ for name, home in two_profile_homes.items():
+ (home / "secrets.env").write_text(f"GH_TOKEN=fake-token-{name}\n")
+ (home / "config.yaml").write_text(yaml.safe_dump({
+ "model": _MODEL,
+ "secrets": {"command": {"enabled": True, "command": f"cat {home / 'secrets.env'}"}},
+ "mcp_servers": {"gh": {"command": sys.executable, "args": [str(server)]}}}))
+
+ results = _discover_and_call(two_profile_homes, "mcp__gh__whoami", {})
+
+ assert results == {"default": "GH_TOKEN=fake-token-default", "worker": "GH_TOKEN=fake-token-worker"}
+
+
+def test_profile_with_other_profile_identity_header_gets_its_own_http_connection(two_profile_homes, tmp_path):
+ log, port_file = tmp_path / "calls.log", tmp_path / "port"
+ script = tmp_path / "team_server.py"
+ script.write_text(_HTTP_SERVER)
+ proc = subprocess.Popen([sys.executable, str(script), str(log), str(port_file)])
+ try:
+ deadline = time.monotonic() + 30
+ while not (port_file.exists() and port_file.read_text()) and time.monotonic() < deadline:
+ time.sleep(0.05)
+ team = {"url": f"http://127.0.0.1:{port_file.read_text()}/mcp",
+ "identity_header": {"name": "X-Hermes-Profile", "value_from": "profile"}}
+ for home in two_profile_homes.values():
+ (home / "config.yaml").write_text(yaml.safe_dump({"model": _MODEL, "mcp_servers": {"team": team}}))
+
+ _discover_and_call(two_profile_homes, "mcp__team__save_note", {"text": "hi"})
+
+ calls = [json.loads(line) for line in log.read_text().splitlines()]
+ assert [profile for method, profile in calls if method == "tools/call"] == ["default", "worker"]
+ finally:
+ proc.terminate()
+ proc.wait(10)
diff --git a/tools/mcp_tool_registration.py b/tools/mcp_tool_registration.py
index 5a16e82201a..70a617d5e4f 100644
--- a/tools/mcp_tool_registration.py
+++ b/tools/mcp_tool_registration.py
@@ -3,6 +3,7 @@ include/exclude filtering, trust-tier metadata capture, utility-tool selection,
resolution and the schema-cache write-through. Both entry points (``_register_server_tools``
live, ``_register_from_cache_sync`` lazy) build ``_Candidate`` records for ``_register_candidates``."""
+import hashlib
import json
import logging
import threading
@@ -427,16 +428,35 @@ def _auth_type(config: dict) -> str:
return (config.get("auth") or "").lower().strip()
-def _same_server_route(server: Any, config: dict, *, cross_profile: bool = False) -> bool:
- """Whether *server* matches *config*, with OAuth connections never reusable across profiles.
+def _resolved_identity(server_name: str, config: dict) -> str:
+ """Digest of what a connection is opened with that the config does not show, resolved in the
+ CURRENT profile's scope: a stdio child's env (external secret-source values) and default cwd,
+ an HTTP connection's headers after ``identity_header`` (``value_from: profile``). The
+ connecting task records it per attempt; an adopter recomputes it. Only the hash is kept."""
+ from agent.runtime_cwd import resolve_context_cwd
+ from tools.mcp_tool_errors import _apply_identity_header
- OAuth credentials live in the owning profile's token storage rather than the static config,
- so identical OAuth configs cannot prove that two profiles authenticate as the same account.
- """
+ if "url" in config:
+ resolved: Any = _apply_identity_header(server_name, config, dict(config.get("headers") or {}))
+ else:
+ cwd = config.get("cwd")
+ resolved = [_config._build_safe_env(config.get("env")), cwd if cwd is not None else resolve_context_cwd()]
+ return hashlib.sha256(json.dumps(resolved, sort_keys=True, default=str).encode()).hexdigest()
+
+
+def _same_server_route(server: Any, config: dict, *, cross_profile: bool = False) -> bool:
+ """Whether *server* matches *config*. Across profiles the static config is not enough: OAuth
+ tokens live in the owner's token store (never reusable), and secret-source env, the profile
+ identity header and the session cwd resolve per profile, so the adopter's resolution must hash
+ to what the owner connected with."""
if _connection_identity(getattr(server, "_config", {}) or {}) != _connection_identity(config):
return False
+ if not cross_profile:
+ return True
# Identities match, so both sides carry the same normalised auth type.
- return not (cross_profile and _auth_type(config) == "oauth")
+ recorded = getattr(server, "_resolved_identity", None)
+ return (_auth_type(config) != "oauth" and recorded is not None
+ and recorded == _resolved_identity(server.name, config))
def register_connected_into_current_scope(servers: dict) -> int:
diff --git a/tools/mcp_tool_server_run.py b/tools/mcp_tool_server_run.py
index db6d7f83fcf..aec22f501f9 100644
--- a/tools/mcp_tool_server_run.py
+++ b/tools/mcp_tool_server_run.py
@@ -342,6 +342,8 @@ class MCPServerRunMixin:
config = self._refresh_remote_config(config)
rebuild = True
run_transport = self._run_http if self._is_http() else self._run_stdio
+ # Resolved in this (owning) profile's scope, as the transport resolves it.
+ self._resolved_identity = _registration._resolved_identity(self.name, config)
if not await self._on_clean_return(await run_transport(config), budget):
break
except asyncio.CancelledError: