Skip to content

The agent that grows with you

fix(mcp): connect resolves credentials under the connection owner's profile scope

moep90d34423e4def6
diff --git a/tests/tools/test_mcp_connect_secret_scope.py b/tests/tools/test_mcp_connect_secret_scope.py
new file mode 100644
index 00000000000..8f1e236f55b
--- /dev/null
+++ b/tests/tools/test_mcp_connect_secret_scope.py
@@ -0,0 +1,105 @@
+"""MCP connect resolves credentials under the connection owner's profile secret scope.
+
+Discovery at gateway startup runs outside any per-turn scope. Under multiplexing an unscoped
+``get_secret`` fails closed, so the stdio child-env build raised ``UnscopedSecretError`` and the
+server registered zero tools (#113746).
+"""
+import asyncio
+
+import pytest
+
+from agent.secret_scope import (
+ UnscopedSecretError, current_secret_scope, reset_secret_scope, set_multiplex_active,
+ set_secret_scope,
+)
+from hermes_cli import env_loader
+from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+from tools import mcp_tool_discovery as discovery
+from tools.mcp_tool_config import _build_safe_env
+
+TOKEN_NAME, TOKEN_VALUE = "EXAMPLE_TOKEN", "profile-own-value"
+
+
+def profile_home(tmp_path, monkeypatch):
+ """A profile home whose ``.env`` holds the credential an external source tagged."""
+ home = tmp_path / "profile"
+ home.mkdir()
+ (home / ".env").write_text(f"{TOKEN_NAME}={TOKEN_VALUE}\n")
+
+ # An external secret source (secrets.command / bitwarden / 1password) tags names
+ # process-wide; the VALUE must come from the active profile's scope.
+ monkeypatch.setitem(env_loader._SECRET_SOURCES, TOKEN_NAME, "command")
+
+ home_token = set_hermes_home_override(str(home))
+ set_multiplex_active(True)
+ try:
+ yield home
+ finally:
+ set_multiplex_active(False)
+ reset_hermes_home_override(home_token)
+
+
+def spawn_env(monkeypatch):
+ """Stub server task: ``start()`` builds the stdio child env the way the transport does."""
+ captured = {}
+
+ class _StubServerTask:
+ def __init__(self, name):
+ self.name = name
+
+ async def start(self, config):
+ captured["env"] = _build_safe_env(config.get("env"))
+
+ async def shutdown(self):
+ pass
+
+ # Origin state is read through _core; patch the origin module (see mcp_tool_discovery docstring).
+ monkeypatch.setattr("tools.mcp_tool.MCPServerTask", _StubServerTask)
+ return captured
+
+
+def test_connect_resolves_the_owning_profiles_secret(profile_home, spawn_env):
+ """Red on base: UnscopedSecretError. The child env must carry the profile's own value."""
+ assert current_secret_scope() is None # discovery runs unscoped
+
+ asyncio.run(discovery._connect_server("demo", {"command": "true"}))
+
+ assert spawn_env["env"][TOKEN_NAME] == TOKEN_VALUE
+
+
+def test_connect_does_not_override_an_installed_scope(profile_home, spawn_env):
+ """A caller that already scoped the turn owns the credentials — never re-derive (#111151)."""
+ token = set_secret_scope({TOKEN_NAME: "callers-value"})
+ try:
+ asyncio.run(discovery._connect_server("demo", {"command": "true"}))
+ finally:
+ reset_secret_scope(token)
+
+ assert spawn_env["env"][TOKEN_NAME] == "callers-value"
+
+
+def test_connect_leaves_the_scope_unchanged_for_the_caller(profile_home, spawn_env):
+ """The binding is the run task's, not the caller's: discovery is unscoped again afterwards."""
+ asyncio.run(discovery._connect_server("demo", {"command": "true"}))
+
+ assert current_secret_scope() is None
+
+
+def test_single_profile_process_binds_nothing(tmp_path, monkeypatch, spawn_env):
+ """No multiplexer, no home override: unchanged, and get_secret still reads os.environ."""
+ monkeypatch.setitem(env_loader._SECRET_SOURCES, TOKEN_NAME, "command")
+ monkeypatch.setenv(TOKEN_NAME, "process-env-value")
+ set_multiplex_active(False)
+
+ asyncio.run(discovery._connect_server("demo", {"command": "true"}))
+
+ assert spawn_env["env"][TOKEN_NAME] == "process-env-value"
+ assert current_secret_scope() is None
+
+
+def test_unscoped_build_still_fails_closed_without_the_binding(profile_home):
+ """The underlying guard is intact: the fix installs a scope, it does not widen get_secret."""
+ with pytest.raises(UnscopedSecretError):
+ _build_safe_env(None)
diff --git a/tools/mcp_tool_discovery.py b/tools/mcp_tool_discovery.py
index ae04d44e532..2bda5669dac 100644
--- a/tools/mcp_tool_discovery.py
+++ b/tools/mcp_tool_discovery.py
@@ -8,6 +8,7 @@ from __future__ import annotations
import asyncio
import logging
import time
+from pathlib import Path
from typing import Dict, List, Optional, Tuple
from tools.mcp_tool_common import _core, _parse_boolish
from tools import mcp_tool_config as _config
@@ -48,6 +49,30 @@ def _enabled(cfg: dict) -> bool:
return _parse_boolish(cfg.get("enabled", True), default=True)
+async def _install_owner_secret_scope():
+ """Bind the connection OWNER's profile secret scope when the caller has none; else None.
+
+ ``MCPServerTask.start`` ensure_futures the run task, which copies THIS context, so one
+ binding covers transport bring-up (``_build_safe_env`` stdio child env, ``${VAR}`` refs) and
+ every later revival inside that task; unscoped, those ``get_secret`` reads fail closed under
+ multiplexing and the server parks with zero tools (#113746). The owner is the profile the
+ connection is keyed under (``_mcp_registry_scope()``), never the ambient one, so a served
+ profile is never handed another profile's token (#111151). Scope key ``None`` (single-profile
+ process) binds nothing.
+ """
+ from agent.secret_scope import build_profile_secret_scope, current_secret_scope, set_secret_scope
+ if current_secret_scope() is not None:
+ return None
+ scope_key = _core._mcp_registry_scope()
+ if scope_key is None:
+ return None
+ from hermes_cli.env_loader import hydrate_profile_secret_sources
+ home = Path(scope_key)
+ # Off-loop: an external source runs a helper subprocess (once per home, then cached).
+ await asyncio.to_thread(hydrate_profile_secret_sources, home)
+ return set_secret_scope(build_profile_secret_scope(home))
+
+
async def _connect_server(name: str, config: dict) -> _core.MCPServerTask:
"""Create an MCPServerTask, start it, return once ready (tear down with ``server.shutdown()``
on the same loop). Raises on bad config, missing HTTP support or connect failure."""
@@ -57,6 +82,7 @@ async def _connect_server(name: str, config: dict) -> _core.MCPServerTask:
claim(server)
# The run task copies this context: don't retain the discovery closure for its life.
claim_token = _core._connect_server_claim.set(None) if claim is not None else None
+ scope_token = await _install_owner_secret_scope()
try:
await server.start(config)
except asyncio.CancelledError:
@@ -70,6 +96,9 @@ async def _connect_server(name: str, config: dict) -> _core.MCPServerTask:
logger.debug("MCP server '%s' shutdown during orphan-reap failed: %s", name, shutdown_exc)
raise
finally:
+ if scope_token is not None:
+ from agent.secret_scope import reset_secret_scope
+ reset_secret_scope(scope_token)
if claim_token is not None:
_core._connect_server_claim.reset(claim_token)
return server