The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(mcp): remote headers render under the owner's fresh secret scope at connect and every reconnect (#119092, salvage #119097)
teknium1c8756dbd613b
diff --git a/tests/tools/test_mcp_connect_secret_scope.py b/tests/tools/test_mcp_connect_secret_scope.pyindex f40956ee515..7518705afb8 100644--- a/tests/tools/test_mcp_connect_secret_scope.py+++ b/tests/tools/test_mcp_connect_secret_scope.py@@ -5,6 +5,7 @@ Discovery at gateway startup runs outside any per-turn scope. Under multiplexingserver registered zero tools (#113746)."""import asyncio+from contextlib import contextmanagerimport pytest@@ -47,6 +48,7 @@ def spawn_env(monkeypatch):self.name = nameasync def start(self, config):+ captured["config"] = configcaptured["env"] = _build_safe_env(config.get("env"))async def shutdown(self):@@ -121,3 +123,98 @@ def test_connect_scope_install_failure_releases_the_discovery_claim(monkeypatch,discovery._core._connect_server_claim.reset(token)asyncio.run(_run())+++REMOTE = {"url": "https://example.invalid/mcp", "headers": {"Authorization": f"Bearer ${{{TOKEN_NAME}}}"}}+++@contextmanager+def _boot_scope(home):+ """The gateway's boot-time ``_profile_runtime_scope`` shape: home override plus a secret scope+ SNAPSHOT built now — before the profile's secret source may have answered."""+ from agent.secret_scope import build_profile_secret_scope, reset_secret_scope, set_secret_scope+ home_token = set_hermes_home_override(str(home))+ token = set_secret_scope(build_profile_secret_scope(home), profile_home=str(home))+ try:+ yield+ finally:+ reset_secret_scope(token)+ reset_hermes_home_override(home_token)+++def _connect_under_boot_scope(home, config):+ async def _run():+ with _boot_scope(home):+ await discovery._connect_server("demo", dict(config, headers=dict(config["headers"])))+ asyncio.run(_run())+++def test_connect_renders_remote_headers_under_the_owners_fresh_scope(tmp_path, spawn_env, monkeypatch):+ """Red on base (#119092): a caller-bound scope was trusted as-is, so a header rendered under the+ boot-time snapshot — taken before B's secret source answered — went out as the literal+ ``Bearer ${VAR}`` (401) instead of failing closed, and never healed. A→B→A: each home's own+ value, never the other's."""+ monkeypatch.setitem(env_loader._SECRET_SOURCES, TOKEN_NAME, "command")+ monkeypatch.setenv(TOKEN_NAME, "launch-env-value")+ home_a, home_b = tmp_path / "s6probe-a", tmp_path / "s6probe-b"+ for home in (home_a, home_b):+ home.mkdir()+ (home_a / ".env").write_text(f"{TOKEN_NAME}=value-a\n", encoding="utf-8")+ set_multiplex_active(True)+ try:+ _connect_under_boot_scope(home_a, REMOTE)+ assert spawn_env["config"]["headers"]["Authorization"] == "Bearer value-a"++ with pytest.raises(ValueError, match=f"'demo'.*{TOKEN_NAME}"): # B: source not hydrated yet+ _connect_under_boot_scope(home_b, REMOTE)+ (home_b / ".env").write_text(f"{TOKEN_NAME}=value-b\n", encoding="utf-8") # the source answers+ _connect_under_boot_scope(home_b, REMOTE)+ assert spawn_env["config"]["headers"]["Authorization"] == "Bearer value-b"++ _connect_under_boot_scope(home_a, REMOTE)+ assert spawn_env["config"]["headers"]["Authorization"] == "Bearer value-a"+ assert current_secret_scope() is None+ finally:+ set_multiplex_active(False)+++def test_reconnect_rerenders_remote_headers_under_the_owners_fresh_scope(tmp_path, monkeypatch):+ """Red on base (#119092): the run task re-read config.yaml on every rebuild but rendered it under+ its copied connect-time scope snapshot, so a parked server retried the literal ``${VAR}`` header+ forever after the owner's secret source came up."""+ from tools.mcp_tool import MCPServerTask+ monkeypatch.setitem(env_loader._SECRET_SOURCES, TOKEN_NAME, "command")+ home_b = tmp_path / "s6probe-b"+ home_b.mkdir()+ (home_b / "config.yaml").write_text(+ "mcp_servers:\n demo:\n url: https://example.invalid/mcp\n"+ f" headers:\n Authorization: 'Bearer ${{{TOKEN_NAME}}}'\n", encoding="utf-8")+ seen: list = []++ class _Task(MCPServerTask):+ async def _prepare_run(self, config):+ self._config = config+ self._auth_type = ""+ return True++ async def _run_http(self, config):+ seen.append(config["headers"]["Authorization"])+ self._ready.set()+ self.session = object()+ self._session_proven = True+ if len(seen) == 1:+ (home_b / ".env").write_text(f"{TOKEN_NAME}=value-b\n", encoding="utf-8") # the source answers+ return "reconnect"+ self._shutdown_event.set()+ return "shutdown"++ async def _scenario():+ with _boot_scope(home_b): # snapshot taken before B's source answered+ await asyncio.wait_for(_Task("demo").run(dict(REMOTE, headers=dict(REMOTE["headers"]))), timeout=10)++ set_multiplex_active(True)+ try:+ asyncio.run(_scenario())+ finally:+ set_multiplex_active(False)+ assert seen == [f"Bearer ${{{TOKEN_NAME}}}", "Bearer value-b"]diff --git a/tools/mcp_tool_config.py b/tools/mcp_tool_config.pyindex 33330e8510b..01e439a52ee 100644--- a/tools/mcp_tool_config.py+++ b/tools/mcp_tool_config.py@@ -352,6 +352,21 @@ def _interpolate_env_vars(value):return value+def _require_rendered_remote(server_name: str, config: dict) -> dict:+ """*config* back, unless it is a remote server whose ``url`` / ``headers`` still carry a literal+ ``${VAR}`` after rendering: sending that is a guaranteed 401 that reads as a bad credential+ (#119092), so fail closed naming the variable instead."""+ if "url" not in config:+ return config+ values = [config.get("url") or "", *(config.get("headers") or {}).values()]+ unresolved = sorted({m.group(1) for value in values for m in _ENV_VAR_PATTERN.finditer(str(value))})+ if unresolved:+ refs = ", ".join(f"${{{ref}}}" for ref in unresolved)+ raise ValueError(f"MCP server '{server_name}': {refs} in url/headers is not set in this profile's "+ ".env or secret source")+ return config++# (server_name, dotted key path) pairs already warned about: config loads repeat per discovery pass._whitespace_warned: Set[Tuple[str, str]] = set()diff --git a/tools/mcp_tool_discovery.py b/tools/mcp_tool_discovery.pyindex 8952d8f6a8d..a8108f87ac8 100644--- a/tools/mcp_tool_discovery.py+++ b/tools/mcp_tool_discovery.py@@ -67,16 +67,19 @@ def _connect_cooldown_active(server_name: str) -> bool:def _owner_scope_home() -> Optional[Path]:- """The profile home whose secret scope MCP credential reads must resolve under, or None when- the caller is already scoped or this is a single-profile process (scope key ``None``).+ """The profile home whose secret scope MCP credential reads must resolve under, or None for a+ single-profile process (scope key ``None``).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)."""- from agent.secret_scope import current_secret_scope- if current_secret_scope() is not None:- return None+ ambient one, so a served profile is never handed another profile's token (#111151). A scope the+ caller already bound is rebuilt rather than trusted: a bound mapping is a snapshot, and the+ gateway's boot-time one is taken before the profile's external secret source may have answered+ (#119092) — the rebuild retries that hydration (cached once it succeeds)."""scope_key = _core._mcp_registry_scope()- return None if scope_key is None else Path(scope_key)+ if scope_key is None:+ return None+ from agent.secret_scope import current_secret_scope_home+ return Path(current_secret_scope_home() or scope_key)async def _install_owner_secret_scope():@@ -132,12 +135,10 @@ async def _connect_server(name: str, config: dict) -> _core.MCPServerTask:scope_token = Nonetry:scope_token = await _install_owner_secret_scope()- # Config loading may have happened before an external secret source was- # hydrated for this owner (multiplex startup). Unresolved placeholders- # deliberately survive interpolation, so render them again now that the- # owning profile's scope is installed instead of retrying a frozen- # ${VAR} header forever.- config = _config._interpolate_env_vars(config)+ # The config was rendered at load time (a lazy server's at boot): re-render under the+ # owner's fresh scope so a ref left literal before its secret source answered resolves+ # now, and refuse to send one that still does not.+ config = _config._require_rendered_remote(name, _config._interpolate_env_vars(config))await server.start(config)except asyncio.CancelledError:raise # start() already reaps server._task; shutdown() here could swallow the canceldiff --git a/tools/mcp_tool_server_run.py b/tools/mcp_tool_server_run.pyindex 64b49599ac6..1eada9c37b6 100644--- a/tools/mcp_tool_server_run.py+++ b/tools/mcp_tool_server_run.py@@ -339,7 +339,18 @@ class MCPServerRunMixin:while True:try:if rebuild:- config = self._refresh_remote_config(config)+ # Under the owner's FRESH scope: the run task's copied one is the connect-time+ # snapshot, so a header rendered before the profile's secret source answered+ # would re-render to the same literal ${VAR} on every probe (#119092).+ from tools import mcp_tool_config as _config+ from tools.mcp_tool_discovery import _install_owner_secret_scope+ scope_token = await _install_owner_secret_scope()+ try:+ config = _config._require_rendered_remote(self.name, self._refresh_remote_config(config))+ finally:+ if scope_token is not None:+ from agent.secret_scope import reset_secret_scope+ reset_secret_scope(scope_token)rebuild = Truerun_transport = self._run_http if self._is_http() else self._run_stdioself._resolved_identity = None # the transport publishes the inputs it connects with