Skip to content

The agent that grows with you

feat: borrow editor MCP configurations with frozen session manifests

Teknium394f00f694cb
diff --git a/gateway/session_local_editor.py b/gateway/session_local_editor.py
index 21d91cd9cc9..bad74534b05 100644
--- a/gateway/session_local_editor.py
+++ b/gateway/session_local_editor.py
@@ -14,8 +14,8 @@ def validate_editor(source, editor):
or editor.get('edit_approval_policy', 'ask') != 'ask'
or not isinstance(editor.get('mcp_servers', []), list)):
raise RuntimeStoreError('invalid_params')
- if editor.get('mcp_servers'):
- raise RuntimeStoreError('acp_mcp_policy_unavailable')
+ from gateway.session_local_mcp import validate_servers
+ validate_servers(editor.get('mcp_servers', []))
def request_editor_edit(proposal):
diff --git a/gateway/session_local_mcp.py b/gateway/session_local_mcp.py
new file mode 100644
index 00000000000..3c996f65176
--- /dev/null
+++ b/gateway/session_local_mcp.py
@@ -0,0 +1,142 @@
+"""Borrow editor transports for one canonical execution, never for a viewer.
+
+Only a fingerprint and the selected schema manifest are durable. Editors must
+resupply the exact transport specification after owner restart, including argv:
+credentials are not reliably distinguishable from ordinary command arguments.
+"""
+from contextlib import contextmanager
+from dataclasses import replace
+import hashlib
+import hmac
+import json
+
+from hermes_state_runtime import RuntimeStoreError
+
+PRIVATE_KEY = ('editor_mcp',)
+
+
+def _json(value):
+ return json.dumps(value, sort_keys=True, separators=(',', ':'))
+
+
+def fingerprint(servers):
+ return hashlib.sha256(_json(servers).encode()).hexdigest()
+
+
+def validate_servers(servers):
+ from acp.schema import McpServerStdio, McpServerHttp, McpServerSse
+ from pydantic import ValidationError
+ kinds = {'stdio': McpServerStdio, 'http': McpServerHttp, 'sse': McpServerSse}
+ if not isinstance(servers, list) or len(servers) > 16 or len(_json(servers)) > 65536:
+ raise RuntimeStoreError('invalid_params')
+ names = set()
+ try:
+ for spec in servers:
+ kind = spec.get('type', 'stdio')
+ model = kinds[kind].model_validate(spec)
+ if not model.name or model.name in names:
+ raise ValueError('duplicate server')
+ names.add(model.name)
+ except (ValidationError, KeyError, AttributeError, TypeError, ValueError) as exc:
+ raise RuntimeStoreError('invalid_params') from exc
+
+
+def private_editor_request(request, private):
+ editor = request.get('editor') or {}
+ servers = editor.get('mcp_servers') or []
+ if not servers:
+ return
+ if private is None:
+ raise RuntimeStoreError('launch_credentials_unavailable')
+ private[PRIVATE_KEY] = json.loads(_json(servers))
+ request['editor'] = {**editor, 'mcp_servers': {'fingerprint': fingerprint(servers)}}
+
+
+def _configs(scope, servers, cwd):
+ configs = {}
+ prefix = hashlib.sha256(scope.encode()).hexdigest()[:20]
+ for i, spec in enumerate(servers):
+ name = f'editor_{prefix}_{i}'
+ if spec.get('type', 'stdio') == 'stdio':
+ config = {'command': spec['command'], 'args': spec['args'],
+ 'env': {e['name']: e['value'] for e in spec.get('env', [])}, 'cwd': cwd}
+ else:
+ config = {'url': spec['url'], 'headers': {e['name']: e['value'] for e in spec.get('headers', [])}}
+ if spec['type'] == 'sse':
+ config['transport'] = 'sse'
+ # One bounded eager discovery; no lazy or late schema refresh.
+ config.update(connect_timeout=5, tool_timeout=30, lazy=False)
+ configs[name] = config
+ return configs
+
+
+@contextmanager
+def _registered(scope, servers, cwd):
+ from tools.registry import registry, session_tool_scope
+ from tools.mcp_tool_discovery import register_mcp_servers
+ from tools.mcp_tool_lifecycle import shutdown_mcp_servers
+ from tools.mcp_tool import _servers
+ configs = _configs(scope, servers, cwd)
+ with session_tool_scope(scope):
+ try:
+ register_mcp_servers(configs)
+ if any(name not in _servers or _servers[name].session is None for name in configs):
+ raise RuntimeStoreError('acp_mcp_discovery_failed')
+ names = [n for n in registry.get_all_tool_names()
+ if registry.get_toolset_for_tool(n) in {f'mcp-{k}' for k in configs}]
+ yield {n: registry.get_schema(n) for n in sorted(names)}, tuple(f'mcp-{k}' for k in configs)
+ finally:
+ shutdown_mcp_servers(scope=scope)
+
+
+def bind_editor_mcp(authority, sid, policy, servers):
+ if not servers:
+ return policy
+ scope = 'editor-session:' + hashlib.sha256(f'{authority.profile_id}:{sid}'.encode()).hexdigest()
+ with _registered(scope, servers, policy.cwd) as (schemas, toolsets):
+ data = {'scope': scope, 'fingerprint': fingerprint(servers), 'schemas': schemas}
+ policy = replace(policy, editor_mcp_json=_json(data),
+ toolsets=tuple(sorted(set(policy.toolsets) | set(toolsets))))
+ attach_editor_mcp(authority, policy, servers)
+ return policy
+
+
+def attach_editor_mcp(authority, policy, servers):
+ validate_servers(servers)
+ data = json.loads(policy.editor_mcp_json or '{}')
+ if not data or not hmac.compare_digest(data['fingerprint'], fingerprint(servers)):
+ raise RuntimeStoreError('acp_mcp_policy_conflict')
+ borrowed = getattr(authority, '_local_editor_mcp', None)
+ if borrowed is None:
+ borrowed = authority._local_editor_mcp = {}
+ borrowed[data['scope']] = json.loads(_json(servers))
+
+
+def resume_editor_mcp(authority, ref, editor):
+ """Call after ordinary resume authorization, before attaching the viewer."""
+ if editor is None:
+ return
+ from gateway.session_local_editor import validate_editor
+ from gateway.session_policy import policy_for_source
+ policy = policy_for_source(authority.runner, authority.sessions[ref.session_id].source)
+ if policy is None:
+ raise RuntimeStoreError('acp_mcp_policy_conflict')
+ validate_editor(policy.source, editor)
+ servers = editor.get('mcp_servers', [])
+ if servers:
+ attach_editor_mcp(authority, policy, servers)
+
+
+@contextmanager
+def editor_mcp_scope(authority, policy):
+ if not policy.editor_mcp_json:
+ yield
+ return
+ data = json.loads(policy.editor_mcp_json)
+ servers = getattr(authority, '_local_editor_mcp', {}).get(data['scope'])
+ if servers is None:
+ raise RuntimeStoreError('launch_credentials_unavailable')
+ with _registered(data['scope'], servers, policy.cwd) as (schemas, _):
+ if schemas != data['schemas']:
+ raise RuntimeStoreError('acp_mcp_schema_changed')
+ yield
diff --git a/gateway/session_policy.py b/gateway/session_policy.py
index 38f9fbf3a4c..d86d0ab2092 100644
--- a/gateway/session_policy.py
+++ b/gateway/session_policy.py
@@ -23,6 +23,7 @@ class LocalSessionPolicy:
terminal_json: str
credential_ref: str | None = None
config_secret_ref: str | None = None
+ editor_mcp_json: str | None = None
def config(self, authority=None):
config = json.loads(self.config_json)
@@ -131,6 +132,8 @@ def build_policy(params, config, *, private_secrets=None):
terminal['TERMINAL_CWD'] = cwd
request = {k: v for k, v in params.items() if k not in {'request_id', 'api_key'}}
request.setdefault('source', 'cli')
+ from gateway.session_local_mcp import private_editor_request
+ private_editor_request(request, private_secrets)
_extract_config_secrets(config, private_secrets)
_extract_config_secrets(terminal, private_secrets, (None,))
return LocalSessionPolicy(source, SURFACES[source], cwd, model, tuple(sorted(enabled)),
@@ -166,6 +169,9 @@ def bind_launch_key(authority, session_id, policy, api_key, *, config_secrets=No
"""
from dataclasses import replace
import hmac
+ from gateway.session_local_mcp import PRIVATE_KEY, bind_editor_mcp
+ config_secrets = dict(config_secrets or {})
+ policy = bind_editor_mcp(authority, session_id, policy, config_secrets.pop(PRIVATE_KEY, None))
if api_key is None and not config_secrets:
return policy
keys = getattr(authority, '_local_launch_keys', None)
@@ -256,7 +262,8 @@ def policy_scope(policy, *, authority=None):
terminal_token = set_terminal_scope(terminal)
from gateway.session_local_editor import editor_scope
try:
- with editor_scope(policy):
+ from gateway.session_local_mcp import editor_mcp_scope
+ with editor_scope(policy), editor_mcp_scope(authority, policy):
yield
finally:
reset_terminal_scope(terminal_token)
diff --git a/tests/acp/test_session_mcp_policy.py b/tests/acp/test_session_mcp_policy.py
new file mode 100644
index 00000000000..cb4ad1dbd9d
--- /dev/null
+++ b/tests/acp/test_session_mcp_policy.py
@@ -0,0 +1,91 @@
+"""Editor MCP credentials are borrowed and tools are frozen per canonical owner."""
+import concurrent.futures
+from dataclasses import asdict
+import json
+import sys
+from types import SimpleNamespace
+
+import pytest
+
+from gateway.session_policy import build_policy, bind_launch_key, policy_scope, restore_policy
+from hermes_state_runtime import RuntimeStoreError
+
+
+def server_spec(tmp_path):
+ script = tmp_path / 'owned_mcp.py'
+ script.write_text('''import json, os, sys
+for line in sys.stdin:
+ r=json.loads(line); method=r.get('method'); ident=r.get('id')
+ if ident is None: continue
+ if method=='initialize': result={'protocolVersion':r['params']['protocolVersion'],'capabilities':{'tools':{}},'serverInfo':{'name':'owned-peer','version':'1'}}
+ elif method=='tools/list': result={'tools':[{'name':'echo','description':'owned echo','inputSchema':{'type':'object','properties':{}}}]}
+ elif method=='tools/call': result={'content':[{'type':'text','text':os.environ['BORROWED_CREDENTIAL']}]}
+ else: result={}
+ print(json.dumps({'jsonrpc':'2.0','id':ident,'result':result}),flush=True)
+''')
+ return {'name': 'same-editor-name', 'command': sys.executable, 'args': [str(script)],
+ 'env': [{'name': 'BORROWED_CREDENTIAL', 'value': 'PRIVATE_A'}]}
+
+
+def owner():
+ return SimpleNamespace(instance_id='owned', epoch=1, profile_id='owned-profile')
+
+
+def policy(authority, sid, spec, tmp_path):
+ private = {}
+ result = build_policy({'source': 'acp', 'cwd': str(tmp_path), 'model': 'local',
+ 'toolsets': [], 'editor': {'mcp_servers': [spec]}}, {}, private_secrets=private)
+ return bind_launch_key(authority, sid, result, None, config_secrets=private)
+
+
+def test_opposing_editors_freeze_tools_and_release_only_their_session(server_spec, tmp_path):
+ from tools.registry import registry
+ authority = owner()
+ left = policy(authority, 'a', server_spec, tmp_path)
+ other = json.loads(json.dumps(server_spec))
+ other['env'][0]['value'] = 'PRIVATE_B'
+ right = policy(authority, 'b', other, tmp_path)
+ import threading
+ ready = threading.Barrier(2)
+ released = threading.Event()
+ def run(p, marker):
+ with policy_scope(p, authority=authority):
+ names = [n for n in registry.get_all_tool_names() if n.startswith('mcp__')]
+ assert len(names) == 1
+ ready.wait(timeout=20)
+ if marker == 'PRIVATE_B':
+ assert released.wait(20)
+ result = registry.dispatch(names[0], {})
+ assert marker in result
+ if marker == 'PRIVATE_A':
+ released.set()
+ return names
+ with concurrent.futures.ThreadPoolExecutor(2) as pool:
+ a = pool.submit(run, left, 'PRIVATE_A')
+ b = pool.submit(run, right, 'PRIVATE_B')
+ an, bn = a.result(40), b.result(40)
+ assert an != bn
+ assert not any(registry.get_entry(n) for n in an + bn)
+ durable = json.dumps(asdict(left))
+ assert 'PRIVATE_A' not in durable and str(tmp_path / 'owned_mcp.py') not in durable
+
+
+def test_cold_editor_rebind_requires_exact_borrowed_config(server_spec, tmp_path):
+ from gateway.session_local_mcp import attach_editor_mcp
+ from tools.registry import registry
+ original = policy(owner(), 'cold', server_spec, tmp_path)
+ cold = restore_policy(json.loads(json.dumps(asdict(original))))
+ authority = owner()
+ with pytest.raises(RuntimeStoreError, match='launch_credentials_unavailable'):
+ with policy_scope(cold, authority=authority):
+ pass
+ changed = json.loads(json.dumps(server_spec))
+ changed['env'][0]['value'] = 'CHANGED_SECRET'
+ with pytest.raises(RuntimeStoreError, match='acp_mcp_policy_conflict'):
+ attach_editor_mcp(authority, cold, [changed])
+ attach_editor_mcp(authority, cold, [server_spec])
+ with policy_scope(cold, authority=authority):
+ names = [n for n in registry.get_all_tool_names() if n.startswith('mcp__')]
+ assert 'PRIVATE_A' in registry.dispatch(names[0], {})
+ assert cold.toolsets == original.toolsets
diff --git a/tools/mcp_tool_registration.py b/tools/mcp_tool_registration.py
index 10b65b52387..8850234c689 100644
--- a/tools/mcp_tool_registration.py
+++ b/tools/mcp_tool_registration.py
@@ -297,7 +297,7 @@ def _register_server_tools(name: str, server: "MCPServerTask", config: dict) ->
registered = _register_candidates(
name, _resolve_name_collisions(name, candidates),
check_fn=_make_check_fn(name), scope=lambda: _core._server_registry_scope(name), lazy=False)
- if registered:
+ if registered and not (_core._server_registry_scope(name) or '').startswith('editor-session:'):
_write_schema_cache(name, server, config, should_register)
return registered