The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(mcp): publish the identity of the inputs the transport connects with
John Paul Soliva6d8d565a7cac
diff --git a/tests/tools/test_mcp_shared_connection_resolved_identity.py b/tests/tools/test_mcp_shared_connection_resolved_identity.pyindex d2658b13b50..6d5cca3d179 100644--- a/tests/tools/test_mcp_shared_connection_resolved_identity.py+++ b/tests/tools/test_mcp_shared_connection_resolved_identity.py@@ -202,3 +202,45 @@ def test_profile_whose_runtime_file_names_another_endpoint_does_not_adopt(two_prdeclaration.unregister("svc")assert adoptable == {"default": True, "worker": False}+++def test_published_identity_describes_the_endpoint_the_live_session_connected_to(monkeypatch):+ """The runtime file rotates from endpoint A to B on every read: the identity published with+ the live session must describe the endpoint the transport actually connected with."""+ from tools import mcp_tool, mcp_tool_transport+ from tools.mcp_tool import MCPServerTask+ from tools.mcp_tool_registration import _resolved_identity++ endpoints = iter([("http://127.0.0.1:4101", {"Authorization": "Bearer token-a"}),+ ("http://127.0.0.1:4102", {"Authorization": "Bearer token-b"})])+ last: list = []++ def rotating(_name):+ last[:] = [next(endpoints, last[0] if last else None)]+ return last[0]++ monkeypatch.setattr(mcp_tool_transport, "_live_endpoint", rotating)+ monkeypatch.setattr(mcp_tool, "_MCP_HTTP_AVAILABLE", True)+ monkeypatch.setattr(mcp_tool, "_MCP_NEW_HTTP", True)+ live: dict = {}++ class _Task(MCPServerTask):+ async def _prepare_run(self, config):+ self._config = config+ return True++ def _streamable_http_transport(self, url, headers, *_rest):+ live["url"] = url+ return None++ async def _serve_transport(self, _transport, _label, _timeout):+ live["published"] = self._resolved_identity+ self._shutdown_event.set()+ return "shutdown"++ config = {"url": "http://127.0.0.1:9/mcp"}+ asyncio.run(asyncio.wait_for(_Task("svc").run(config), timeout=5))++ monkeypatch.setattr(mcp_tool_transport, "_live_endpoint", lambda _name: last[0])+ assert live["url"] == last[0][0]+ assert live["published"] == _resolved_identity("svc", config)diff --git a/tools/mcp_tool_registration.py b/tools/mcp_tool_registration.pyindex dc4f77fbb60..33dad5c36de 100644--- a/tools/mcp_tool_registration.py+++ b/tools/mcp_tool_registration.py@@ -428,41 +428,38 @@ def _auth_type(config: dict) -> str:return (config.get("auth") or "").lower().strip()+def _identity_digest(resolved: list) -> str:+ """Only the hash of a connection's resolved inputs is kept: they carry secrets."""+ return hashlib.sha256(json.dumps(resolved, sort_keys=True, default=str).encode()).hexdigest()++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 the way the transport resolves it: a stdio child's executable (bare+ CURRENT profile's scope by the transport's own resolvers: a stdio child's executable (bare``npx``/``node`` may resolve under the profile's home), env (external secret-source values) anddefault cwd; an HTTP connection's URL and headers after a ``server_json`` live endpoint and- ``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+ ``identity_header`` (``value_from: profile``). The transport publishes the digest of the very+ inputs each attempt connects with; an adopter recomputes it here."""from tools.mcp_tool_errors import _apply_identity_header- from tools.mcp_tool_transport import LiveEndpointUnavailable, _live_endpoint+ from tools.mcp_tool_transport import LiveEndpointUnavailable, _http_endpoint, _stdio_launchif "url" in config:- url, headers = config["url"], dict(config.get("headers") or {})try:- live = _live_endpoint(server_name)+ url, headers = _http_endpoint(server_name, config)except LiveEndpointUnavailable: # the transport cannot connect either; never equal to a live one- live = (None, {})- if live is not None:- url, live_headers = live- headers.update(live_headers)- resolved: Any = [url, _apply_identity_header(server_name, config, headers)]- else:- command, env = config.get("command"), _config._build_safe_env(config.get("env"))- if command: # the transport refuses a command-less stdio config before resolving anything- command, env = _config._resolve_stdio_command(command, env)- cwd = config.get("cwd")- resolved = [command, env, cwd if cwd is not None else resolve_context_cwd() or None]- return hashlib.sha256(json.dumps(resolved, sort_keys=True, default=str).encode()).hexdigest()+ return ""+ return _identity_digest([url, _apply_identity_header(server_name, config, headers)])+ if not config.get("command"): # the transport refuses it before resolving anything+ return ""+ return _identity_digest(list(_stdio_launch(config)))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: OAuthtokens 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."""+ identity header and the default cwd resolve per profile, so the adopter's resolution must hash+ to what the owner connected with. Within one profile the connection is the profile's: its+ default cwd resolves in the connection task's own context, never per session."""if _connection_identity(getattr(server, "_config", {}) or {}) != _connection_identity(config):return Falseif not cross_profile:diff --git a/tools/mcp_tool_server_run.py b/tools/mcp_tool_server_run.pyindex aec22f501f9..64b49599ac6 100644--- a/tools/mcp_tool_server_run.py+++ b/tools/mcp_tool_server_run.py@@ -342,8 +342,7 @@ class MCPServerRunMixin:config = self._refresh_remote_config(config)rebuild = Truerun_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)+ self._resolved_identity = None # the transport publishes the inputs it connects withif not await self._on_clean_return(await run_transport(config), budget):breakexcept asyncio.CancelledError:diff --git a/tools/mcp_tool_transport.py b/tools/mcp_tool_transport.pyindex 6ebcd85c604..490eea57f66 100644--- a/tools/mcp_tool_transport.py+++ b/tools/mcp_tool_transport.py@@ -111,6 +111,30 @@ def _live_endpoint(server_name: str) -> Optional[tuple[str, dict]]:return endpoint.url, headers+def _http_endpoint(server_name: str, config: dict) -> tuple[str, dict]:+ """URL + configured headers, overlaid by a ``server_json`` live endpoint's URL and bearer."""+ url, headers = config["url"], dict(config.get("headers") or {})+ live = _live_endpoint(server_name)+ if live is not None:+ url, live_headers = live+ headers.update(live_headers)+ return url, headers+++def _stdio_launch(config: dict) -> tuple:+ """(command, env, cwd) a stdio child is spawned with, resolved in the current profile's scope."""+ command, env = _config._resolve_stdio_command(config["command"], _config._build_safe_env(config.get("env")))+ # A stdio child inherits this process's cwd when none is configured. Hosted sessions (ACP,+ # gateway) pin a logical cwd via agent.runtime_cwd; without it the child resolves relative+ # paths against the daemon's launch dir, not the session workspace. Explicit config always+ # wins; an existing session/TERMINAL_CWD anchor becomes the default; else native (None).+ # The resolved default is fixed for the connection's lifetime.+ cwd = config.get("cwd")+ if cwd is None:+ cwd = _runtime_cwd.resolve_context_cwd() or None+ return command, env, cwd++class MCPServerTransportMixin:"""Methods of :class:`tools.mcp_tool.MCPServerTask` (mixed in; relies on its attributes)."""@@ -316,16 +340,11 @@ class MCPServerTransportMixin:command = config.get("command")if not command:raise ValueError(f"MCP server '{self.name}' has no 'command' in config")- command, safe_env = _config._resolve_stdio_command(command, _config._build_safe_env(config.get("env")))+ command, safe_env, stdio_cwd = _stdio_launch(config)+ # Hash the inputs this attempt spawns with, never a second resolution of them.+ self._resolved_identity = _registration._identity_digest([command, safe_env, stdio_cwd])# OSV malware preflight, then the cached-npx swap (ordering enforced there).command, args = await _core._preflight_stdio_command(self.name, command, config.get("args", []))- # A stdio child inherits this process's cwd when none is configured. Hosted sessions (ACP,- # gateway) pin a logical cwd via agent.runtime_cwd; without it the child resolves relative- # paths against the daemon's launch dir, not the session workspace. Explicit config always- # wins; an existing session/TERMINAL_CWD anchor becomes the default; else native (None).- stdio_cwd = config.get("cwd")- if stdio_cwd is None:- stdio_cwd = _runtime_cwd.resolve_context_cwd() or Noneserver_params = _core.StdioServerParameters(command=command, args=args, env=safe_env or None, cwd=stdio_cwd,# Windows pipes can split non-UTF-8 bytes at chunk boundaries; substitute, don't raise.@@ -528,18 +547,16 @@ class MCPServerTransportMixin:raise ImportError(f"MCP server '{self.name}' requires HTTP transport but ""mcp.client.streamable_http is not available. ""Upgrade the mcp package to get HTTP support.")- url = config["url"]- headers = dict(config.get("headers") or {})- live = _live_endpoint(self.name)- if live is not None:- url, live_headers = live- headers.update(live_headers)+ url, headers = _http_endpoint(self.name, config)logger.debug("MCP server '%s': connecting to %s", self.name, url)self._http_rejection = {} # last 4xx/5xx the owned client saw this attempt (recorder hook)# Agent Plugins v1 strict_redirect_headers: configured headers MUST NOT follow a cross-origin# redirect — capture their names BEFORE client-generated headers are merged in.configured_header_names = {key.lower() for key in headers}headers = _apply_identity_header(self.name, config, headers) # explicit same-name headers win+ # Hash the endpoint this attempt connects to: a second read of the runtime file could+ # publish another endpoint's identity alongside this session.+ self._resolved_identity = _registration._identity_digest([url, headers])# Seed MCP-Protocol-Version (user override wins) from the HANDSHAKE version, not the latest: a# 2026-07-28 header routes the handshake-era ``initialize()`` onto the envelope ladder, which rejects it.if not any(key.lower() == "mcp-protocol-version" for key in headers):