The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(acp): gateway owns each session's editor MCP servers
unsupportedpastelsa1de1ceea3c7
diff --git a/acp_adapter/gateway_server.py b/acp_adapter/gateway_server.pyindex a6316dce837..27fa51b0a82 100644--- a/acp_adapter/gateway_server.py+++ b/acp_adapter/gateway_server.py@@ -100,6 +100,12 @@ def _submit_fingerprint(session_id, text, attachments):return session_id, digest.hexdigest()+def _tools_changed_notice(payload):+ """The owner re-froze this session's editor MCP tools (a changed config or changed schemas)."""+ servers = ", ".join(payload.get("mcp_servers") or []) or "none"+ return f"Editor MCP tools changed (servers: {servers}); the new tool list applies from the next turn.\n"++class GatewayACPAgent(acp.Agent):def __init__(self):self._conn = None@@ -321,6 +327,7 @@ class GatewayACPAgent(acp.Agent):async def _resume(self, cwd, held_id, mcp_servers):client = await self._client()from acp_adapter.catalog import logical_session_id+ from hermes_cli.gateway_client import GatewayRPCErrorsession_id = await asyncio.to_thread(logical_session_id, self._home / "state.db", held_id)# The latest load names the id this editor addresses the conversation by.self._aliases = {held: sid for held, sid in self._aliases.items() if sid != session_id}@@ -338,7 +345,15 @@ class GatewayACPAgent(acp.Agent):if "acp-session-mcp-v1" not in descriptor.get("capabilities", []):raise GatewayClientError("acp_mcp_policy_unavailable")resume_params['editor'] = {'mcp_servers': [s.model_dump(by_alias=True) for s in mcp_servers]}- snapshot = await client.rpc("session.resume", session_id=session_id, **resume_params)+ try:+ snapshot = await client.rpc("session.resume", session_id=session_id, **resume_params)+ except GatewayRPCError as exc:+ if str(exc) != "acp_mcp_policy_conflict":+ raise+ # The editor's MCP config changed: the owner re-binds the session's servers (control+ # capability, idle only), as the workspace move above, instead of refusing the thread.+ await self._rebind_editor_mcp(client, session_id, resume_params['editor'])+ snapshot = await client.rpc("session.resume", session_id=session_id, **resume_params)self._snapshots[session_id] = snapshotif 'editor' in resume_params:self._editor_mcp[session_id] = resume_params['editor']@@ -364,6 +379,12 @@ class GatewayACPAgent(acp.Agent):self._mutations.acknowledge(session_id, 'workspace', payload)return await client.rpc("session.info", session_id=session_id)+ async def _rebind_editor_mcp(self, client, session_id, editor):+ """The owner's ``editor_mcp`` mutation: rediscovers *editor*'s servers into the session's policy."""+ self._unacked.pop(session_id, None)+ await self._mutations.apply(client, session_id, 'editor_mcp', editor)+ self._mutations.acknowledge(session_id, 'editor_mcp', editor)+async def load_session(self, cwd, session_id, mcp_servers=None, **kwargs):return LoadSessionResponse(**await self._resume(cwd, session_id, mcp_servers))@@ -412,17 +433,18 @@ class GatewayACPAgent(acp.Agent):session_id = self._aliases.get(session_id, session_id)client = await self._client()info = await client.rpc('session.info', session_id=session_id)- if mcp_servers:- # The branch inherits the parent's borrowed-MCP scope; binding other servers to the child- # (or giving it its own scope) has no owner verb.- raise GatewayClientError('cwd_policy_conflict')+ # The owner binds the child's editor servers under the child's own scope: these, or else a+ # copy of the parent's.+ payload = {'mcp_servers': [s.model_dump(by_alias=True) for s in mcp_servers]} if mcp_servers else {}self._unacked.pop(session_id, None)- result = await self._mutations.apply(client, session_id, 'branch', {})+ result = await self._mutations.apply(client, session_id, 'branch', payload)child = result['branched_session_id']if self._moved(info, cwd):await self._move_workspace(client, child, cwd)self._snapshots[child] = await client.rpc('session.resume', session_id=child)- self._mutations.acknowledge(session_id, 'branch', {})+ if payload or session_id in self._editor_mcp:+ self._editor_mcp[child] = payload or self._editor_mcp[session_id]+ self._mutations.acknowledge(session_id, 'branch', payload)info = self._snapshots[child].get('info') or await client.rpc('session.info', session_id=child)return ForkSessionResponse(session_id=child, **await self._session_fields(child, info, child))@@ -671,7 +693,7 @@ class GatewayACPAgent(acp.Agent):kind, payload = event.get("type"), event.get("payload", {})sid, editor_id = event["session_id"], self._editor_id(event["session_id"])aid = event.get("admission_id")- if kind in {"session.info", "session.updated", "session.usage"}:+ if kind in {"session.info", "session.updated", "session.usage", "session.tools_changed"}:await self._project_session_state(kind, sid, editor_id, payload)returnif kind == "session.replay_gap":@@ -745,6 +767,11 @@ class GatewayACPAgent(acp.Agent):if kind == "session.usage":await self._project_usage(sid, editor_id, payload)return+ if kind == "session.tools_changed":+ if self._conn:+ await self._conn.session_update(session_id=editor_id, update=acp.update_agent_message_text(+ _tools_changed_notice(payload)))+ returnif kind == "session.info" and sid in self._snapshots and "pending" in payload:async with self._changed:self._snapshots[sid]["pending"] = payload["pending"]diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex f5d26473085..a4495f58c21 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -246,6 +246,8 @@ class SessionAuthority:if transport is not None:live.event_stream.fanout.detach(transport)if not live.subscribers:+ from gateway.session_local_mcp import release_editor_mcp+ await asyncio.to_thread(release_editor_mcp, self, [session_id])from gateway.session_acp_lifecycle import (end_idle_acp_session, end_idle_viewer_session, reopen_if_reattached)from gateway.session_runtime_workers import tracked_write@@ -773,6 +775,9 @@ class SessionAuthority:if first is not None and live.source.platform == Platform.LOCAL:from gateway.session_local_recovery import restore_local_sessionrestore_local_session(self, ref.session_id)+ # Editor MCP schema drift re-freezes here, at this admission's start: a turn boundary.+ from gateway.session_local_mcp import refreeze_editor_mcp+ await refreeze_editor_mcp(self, ref, live)if first['request_id'].startswith('hosted:'):from gateway.session_hosted_transport import check_remote_hosted_admissionif not await asyncio.to_thread(check_remote_hosted_admission, self, ref, first):diff --git a/gateway/session_local_mcp.py b/gateway/session_local_mcp.pyindex de81502fa72..54dec630767 100644--- a/gateway/session_local_mcp.py+++ b/gateway/session_local_mcp.py@@ -1,21 +1,32 @@-"""Borrow editor transports for one canonical execution, never for a viewer.+"""Editor MCP servers are session state the gateway owns; an ACP connection only requests them.Only a fingerprint and the selected schema manifest are durable. Editors mustresupply the exact transport specification after owner restart, including argv:credentials are not reliably distinguishable from ordinary command arguments.+A different specification is a ``session.mutate editor_mcp`` (control capability,+revision/generation fenced, idle only), never an implicit swap on attach.++The frozen manifest is part of the session's prompt-cache prefix, so it only changes+at a turn boundary: through that mutation while the session is idle, or through the+re-freeze the drain runs at the start of an admission (``refreeze_editor_mcp``).+Inside an execution it never changes."""+import asynciofrom contextlib import contextmanagerfrom dataclasses import replaceimport hashlibimport hmacimport jsonimport logging+import threading+import uuidfrom hermes_state_runtime import RuntimeStoreErrorlogger = logging.getLogger(__name__)PRIVATE_KEY = ('editor_mcp',)+_HELD_LOCK = threading.Lock()def _json(value):@@ -55,6 +66,25 @@ def private_editor_request(request, private):request['editor'] = {**editor, 'mcp_servers': {'fingerprint': fingerprint(servers)}}+def private_mutation_payload(operation, payload):+ """``(store payload, servers)`` of an ``editor_mcp`` or a ``branch`` naming servers: the list+ stays in owner memory; the receipt digest and every store write see only its fingerprint."""+ if operation == 'editor_mcp':+ if not isinstance(payload, dict) or set(payload) != {'mcp_servers'}:+ raise RuntimeStoreError('invalid_params')+ elif operation != 'branch' or not isinstance(payload, dict) or 'mcp_servers' not in payload:+ return payload, None+ servers = payload['mcp_servers']+ validate_servers(servers)+ servers = json.loads(_json(servers))+ return {**payload, 'mcp_servers': {'fingerprint': fingerprint(servers)}}, servers+++def session_scope(authority, sid):+ """A session's own ledger scope: never shared with another session (a fork included) or profile."""+ return 'editor-session:' + hashlib.sha256(f'{authority.profile_id}:{sid}'.encode()).hexdigest()++def _server_names(scope, servers):"""Index -> ledger name: the editor's own server name (the model sees ``mcp__editor_github_<tag>__x``)plus a per-session tag, so two sessions borrowing same-named servers never adopt one connection."""@@ -71,6 +101,15 @@ def _frozen_names(data, servers):return {i: f'editor_{prefix}_{i}' for i in range(len(servers))}+def _frozen_toolset(data, toolset):+ """Whether *toolset* is one of the editor toolsets frozen in *data* (a manifest or None)."""+ if not data:+ return False+ if 'names' in data:+ return toolset in {f'mcp-{name}' for name in data['names'].values()}+ return toolset.startswith(f"mcp-editor_{hashlib.sha256(data['scope'].encode()).hexdigest()[:20]}_")++def _configs(servers, names, cwd):configs = {}for i, name in names.items():@@ -88,47 +127,126 @@ def _configs(servers, names, cwd):return configs+class _Held:+ """One session scope's editor connections. ``users`` executions borrow them right now; between+ executions they stay connected only while the session has a viewer (``_viewed``)."""++ def __init__(self):+ self.lock = threading.Lock()+ self.users = 0+ self.fingerprint = None+++def _held(authority, scope):+ with _HELD_LOCK:+ table = getattr(authority, '_editor_mcp_held', None)+ if table is None:+ table = authority._editor_mcp_held = {}+ return table.setdefault(scope, _Held())+++def _viewed(authority, scope):+ return any(live.subscribers and session_scope(authority, sid) == scope+ for sid, live in list(getattr(authority, 'sessions', {}).items()))+++def _connected(scope, names):+ from tools.mcp_tool import _servers+ from tools.mcp_tool_scope import _server_key+ # Inside the scope the ledger keys are ``(scope, name)``, never bare names.+ return [i for i, name in names.items()+ if _server_key(name, scope) in _servers and _servers[_server_key(name, scope)].session]+++def _disconnect(held, scope):+ from tools.mcp_tool_lifecycle import shutdown_mcp_servers+ shutdown_mcp_servers(scope=scope)+ held.fingerprint = None++@contextmanager-def _registered(scope, servers, names, cwd, *, partial=False):- """Yield ``(schemas, connected indexes)``. Only ``partial`` (the creation-time selection) may- leave a server out; an execution needs every server its manifest was frozen with."""+def _borrowed(authority, scope, servers, names, cwd, *, partial=False):+ """Yield ``(schemas, connected indexes)`` inside the session's tool scope. Only ``partial`` (a+ selection being frozen) may leave a server out; an execution needs every server its manifest+ was frozen with. A held connection is reused; the last borrower closes it unless a viewer remains."""from tools.registry import registry, session_tool_scopefrom tools.mcp_tool_discovery import register_mcp_servers- from tools.mcp_tool_lifecycle import shutdown_mcp_servers- from tools.mcp_tool import _servers- from tools.mcp_tool_scope import _server_key- configs = _configs(servers, names, cwd)+ held = _held(authority, scope)+ wanted = fingerprint(servers)with session_tool_scope(scope):+ with held.lock:+ if held.fingerprint not in (None, wanted):+ # A committed editor_mcp swapped the credentials: no execution may still run on the old ones.+ if held.users:+ raise RuntimeStoreError('session_busy')+ _disconnect(held, scope)+ connected = _connected(scope, names)+ if len(connected) != len(names):+ register_mcp_servers(_configs(servers, names, cwd))+ connected = _connected(scope, names)+ held.fingerprint = wanted+ held.users += 1try:- register_mcp_servers(configs)- # Inside the scope the ledger keys are ``(scope, name)``, never bare names.- connected = [i for i, name in names.items()- if _server_key(name, scope) in _servers and _servers[_server_key(name, scope)].session]if len(connected) != len(names) and not partial:raise RuntimeStoreError('acp_mcp_discovery_failed')toolsets = {f'mcp-{names[i]}' for i in connected}tools = [n for n in registry.get_all_tool_names() if registry.get_toolset_for_tool(n) in toolsets]yield {n: registry.get_schema(n) for n in sorted(tools)}, connectedfinally:- shutdown_mcp_servers(scope=scope)+ with held.lock:+ held.users -= 1+ if not held.users and not _viewed(authority, scope):+ _disconnect(held, 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()- names = _server_names(scope, servers)- with _registered(scope, servers, names, policy.cwd, partial=True) as (schemas, connected):- # One broken editor server must not refuse the session (main skipped it too): it is left out- # of the frozen selection, so no later execution respawns it.- for i in sorted(set(names) - set(connected)):- logger.warning("Editor MCP server %r failed discovery; session %s continues without it",- servers[i].get('name'), sid)+def release_editor_mcp(authority, session_ids):+ """The last viewer left (or the sessions retired): close their held editor connections. One an+ execution still borrows is closed by that execution when it ends."""+ table = getattr(authority, '_editor_mcp_held', None) or {}+ for sid in session_ids:+ scope = session_scope(authority, sid)+ held = table.get(scope)+ if held is None:+ continue+ with held.lock:+ if not held.users and held.fingerprint is not None and not _viewed(authority, scope):+ _disconnect(held, scope)+++def rebind_editor_mcp(authority, sid, policy, servers):+ """``(policy, manifest changed)``: *policy* with its editor selection freshly discovered from+ *servers* under *sid*'s own scope (blocking). A broken server is left out of the frozen selection+ (main skipped it too), so no later execution respawns it."""+ old = json.loads(policy.editor_mcp_json or 'null')+ toolsets = {name for name in policy.toolsets if not _frozen_toolset(old, name)}+ data = None+ if servers:+ scope = session_scope(authority, sid)+ held = _held(authority, scope)+ with held.lock:+ if held.users:+ raise RuntimeStoreError('session_busy')+ # Fresh discovery: a held connection keeps the schemas it was first frozen with.+ _disconnect(held, scope)+ names = _server_names(scope, servers)+ with _borrowed(authority, scope, servers, names, policy.cwd, partial=True) as (schemas, connected):+ for i in sorted(set(names) - set(connected)):+ logger.warning("Editor MCP server %r failed discovery; session %s continues without it",+ servers[i].get('name'), sid)names = {i: names[i] for i in connected}data = {'scope': scope, 'fingerprint': fingerprint(servers), 'schemas': schemas,'names': {str(i): name for i, name in names.items()}}- policy = replace(policy, editor_mcp_json=_json(data),- toolsets=tuple(sorted(set(policy.toolsets) | {f'mcp-{name}' for name in names.values()})))+ toolsets |= {f'mcp-{name}' for name in names.values()}+ rebound = replace(policy, editor_mcp_json=_json(data) if data else None, toolsets=tuple(sorted(toolsets)))+ changed = ((old or {}).get('schemas', {}) != (data or {}).get('schemas', {})+ or rebound.toolsets != policy.toolsets)+ return rebound, changed+++def bind_editor_mcp(authority, sid, policy, servers):+ if not servers:+ return policy+ policy, _ = rebind_editor_mcp(authority, sid, policy, servers)attach_editor_mcp(authority, policy, servers)return policy@@ -159,6 +277,135 @@ def resume_editor_mcp(authority, ref, editor):attach_editor_mcp(authority, policy, servers)+def install_editor_mcp(authority, sid, servers):+ """After a committed change: *sid*'s borrowed credentials follow its committed policy (memory only)."""+ from gateway.session_policy import restore_policy+ from hermes_state_local import local_receipt+ policy = restore_policy(local_receipt(authority.db, sid)['policy'])+ data = json.loads(policy.editor_mcp_json or '{}')+ borrowed = getattr(authority, '_local_editor_mcp', None)+ if borrowed is None:+ borrowed = authority._local_editor_mcp = {}+ if not data:+ borrowed.pop(session_scope(authority, sid), None)+ elif hmac.compare_digest(data['fingerprint'], fingerprint(servers)):+ borrowed[data['scope']] = json.loads(_json(servers))+++def announce_tools_changed(live, session_id, result):+ """One ``session.tools_changed`` on the session's stream when a change altered the manifest:+ server names and the generation only, never a transport specification."""+ if live is not None and result.get('tools_changed'):+ live.event_stream.publish(session_id, {'mcp_servers': result['mcp_servers'],+ 'execution_generation': result['execution_generation']}, event_type='session.tools_changed')+++async def prepare_editor_mcp(authority, live, payload, prepared, *, servers):+ """``session.mutate editor_mcp``: discover the new list and freeze it into the policy the next+ turn runs under. Equal schemas leave the manifest, and so the prompt-cache prefix, as it was;+ only the fingerprint and the borrowed credentials swap."""+ from gateway.session_mutation_policy import _rebind+ from gateway.session_policy import restore_policy+ receipt = prepared['snapshot']['receipt']+ old = restore_policy(receipt['policy'])+ if old.source != 'acp':+ raise RuntimeStoreError('invalid_params')+ policy, changed = await asyncio.to_thread(rebind_editor_mcp, authority, receipt['session_id'], old, servers)+ names = json.loads(policy.editor_mcp_json or '{}').get('names', {})+ return _rebind(authority, prepared, old, policy, tools_changed=changed,+ mcp_servers=[servers[int(i)]['name'] for i in sorted(names, key=int)])+++async def refreeze_editor_mcp(authority, ref, live):+ """The drain, before it claims the FIFO head (claim gate and mutation lock held, nothing+ executing), re-checks the editor schemas; a drifted manifest is re-frozen through the+ ``editor_mcp`` writer path, so the turn runs on it instead of failing ``acp_mcp_schema_changed``."""+ from gateway.config import Platform+ from gateway.session_local_recovery import local_adapter_map+ # The policy the claim just restored (``restore_local_session``) for this local route.+ adapter = local_adapter_map(authority).get(Platform.LOCAL)+ policy = adapter.policies.get(live.source.chat_id) if adapter is not None else None+ if policy is None or not policy.editor_mcp_json:+ return+ data = json.loads(policy.editor_mcp_json)+ servers = getattr(authority, '_local_editor_mcp', {}).get(data['scope'])+ if servers is None:+ return # the execution reports launch_credentials_unavailable++ def probe():+ names = _frozen_names(data, servers)+ with _borrowed(authority, data['scope'], servers, names, policy.cwd, partial=True) as (schemas, connected):+ return schemas, len(connected) == len(names)+ schemas, complete = await asyncio.to_thread(probe)+ # A server that is down right now is the execution's discovery failure, never a narrowed manifest.+ if not complete or schemas == data['schemas']:+ return+ try:+ await _commit_refreeze(authority, ref, live, servers)+ except RuntimeStoreError:+ # The FIFO must not pause on it: the turn then reports the drift as before.+ logger.warning('Editor MCP schemas of session %s changed; re-freeze failed', ref.session_id, exc_info=True)+++async def _commit_refreeze(authority, ref, live, servers):+ from gateway.session_local import publish_local_policy+ from hermes_state_local import local_receipt+ from hermes_state_runtime import mutate_runtime_session+ owner = await asyncio.to_thread(local_receipt, authority.db, ref.session_id)+ row = await asyncio.to_thread(authority.db.get_session, ref.session_id)+ payload, servers = private_mutation_payload('editor_mcp', {'mcp_servers': servers})+ fields = dict(epoch=authority.epoch, principal_id=owner['principal_id'], session_id=ref.session_id,+ request_id='editor-mcp-refreeze:' + uuid.uuid4().hex, expected_revision=row['runtime_revision'],+ expected_generation=row['runtime_generation'], operation='editor_mcp', payload=payload)+ prepared = await asyncio.to_thread(mutate_runtime_session, authority.db, **fields, _prepare_only=True)+ prepared = await prepare_editor_mcp(authority, live, payload, prepared, servers=servers)+ result = await asyncio.to_thread(mutate_runtime_session, authority.db, **fields, _prepared=prepared)+ install_editor_mcp(authority, ref.session_id, servers)+ publish_local_policy(authority, ref.session_id)+ live.event_stream.publish(ref.session_id, result, event_type='session.updated')+ announce_tools_changed(live, ref.session_id, result)+++def _child_secret_ref(authority, child, parent, policy):+ """A durable config-secret reference names the policy identity, which the child's own editor+ selection changed; the frozen secrets themselves are the parent's."""+ from gateway.session_policy_credentials import PREFIX, config_reference, recover_config_secrets+ if parent.config_secret_ref is None or not parent.config_secret_ref.startswith(PREFIX):+ return policy+ secrets = recover_config_secrets(authority, parent, skip=())+ return replace(policy, config_secret_ref=config_reference(authority, child, policy, secrets))+++async def prepare_branch_editor(authority, ref, servers):+ """``(prepared, servers)`` for a fork of an editor session: the child's selection under its OWN+ scope, from the fork's list or else a copy of the parent's borrowed servers. The child never+ shares the parent's scope or connections. ``(None, None)`` when no editor servers are involved."""+ from gateway.session_policy import restore_policy+ from hermes_state_keys import local_identity+ from hermes_state_local import local_receipt+ try:+ saved = await asyncio.to_thread(local_receipt, authority.db, ref.session_id)+ except RuntimeStoreError:+ return None, None # not a local session: the branch transaction refuses it+ parent = restore_policy(saved['policy'])+ if servers is None:+ if not parent.editor_mcp_json:+ return None, None+ servers = getattr(authority, '_local_editor_mcp', {}).get(json.loads(parent.editor_mcp_json)['scope'])+ if servers is None:+ raise RuntimeStoreError('launch_credentials_unavailable')+ servers = json.loads(_json(servers))+ elif parent.source != 'acp':+ raise RuntimeStoreError('invalid_params')+ request_id = 'branch:' + uuid.uuid4().hex+ child = local_identity(saved['profile_id'], saved['principal_id'], request_id)+ policy, _ = await asyncio.to_thread(rebind_editor_mcp, authority, child, parent, servers)+ policy = _child_secret_ref(authority, child, parent, policy)+ return {'request_id': request_id, 'child': child, 'parent_editor_mcp_json': parent.editor_mcp_json,+ 'editor_mcp_json': policy.editor_mcp_json, 'toolsets': list(policy.toolsets),+ 'config_secret_ref': policy.config_secret_ref}, servers++@contextmanagerdef editor_mcp_scope(authority, policy):if not policy.editor_mcp_json:@@ -168,7 +415,8 @@ def editor_mcp_scope(authority, policy):servers = getattr(authority, '_local_editor_mcp', {}).get(data['scope'])if servers is None:raise RuntimeStoreError('launch_credentials_unavailable')- with _registered(data['scope'], servers, _frozen_names(data, servers), policy.cwd) as (schemas, _):+ with _borrowed(authority, data['scope'], servers, _frozen_names(data, servers), policy.cwd) as (schemas, _):if schemas != data['schemas']:+ # Drift is re-frozen by the drain before a claim; inside an execution the manifest never changes.raise RuntimeStoreError('acp_mcp_schema_changed')yielddiff --git a/gateway/session_mutations.py b/gateway/session_mutations.pyindex f3e6aae83df..7704bb36639 100644--- a/gateway/session_mutations.py+++ b/gateway/session_mutations.py@@ -6,12 +6,13 @@ branch/compress/model still require their own prepared runtime publication."""import asynciofrom contextlib import nullcontext+from functools import partialfrom hermes_state_runtime import RuntimeStoreError, mutate_runtime_session_METADATA = frozenset({'rename', 'archive', 'sidebar'})# Prepared off the commit like model, then published as a new frozen policy.-_POLICY = frozenset({'model', 'reasoning', 'workspace'})+_POLICY = frozenset({'model', 'reasoning', 'workspace', 'editor_mcp'})_FIELDS = frozenset({'session_id', 'request_id', 'expected_revision', 'operation', 'payload'})@@ -104,6 +105,10 @@ async def _mutate_session(authority, actor, ref, params, *, commit_lock=None):operation = params['operation']if not isinstance(operation, str) or (operation in _POLICY and params.get('expected_generation') is None):raise RuntimeStoreError('invalid_params')+ from gateway.session_local_mcp import private_mutation_payload+ # Editor MCP transport specs (credentials) stay in owner memory; the store sees a fingerprint.+ payload, editor_servers = private_mutation_payload(operation, params['payload'])+ params = {**params, 'payload': payload}cold_history = Falseimported_ids = Noneif operation == 'import':@@ -141,7 +146,10 @@ async def _mutate_session(authority, actor, ref, params, *, commit_lock=None):if not authorize_history(conn, actor, ref.session_id, claim=True):raise RuntimeStoreError('permission_denied')- prepared = None+ prepared = branch_editor = None+ if operation == 'branch':+ from gateway.session_local_mcp import prepare_branch_editor+ branch_editor, editor_servers = await prepare_branch_editor(authority, ref, editor_servers)if operation in {*_POLICY, 'compress'}:# Its own BEGIN IMMEDIATE, so off the loop like the commit below.prepared = await asyncio.to_thread(mutate_runtime_session, authority.db, epoch=authority.epoch,@@ -152,7 +160,9 @@ async def _mutate_session(authority, actor, ref, params, *, commit_lock=None):from gateway.session_mutation_model import prepare_modelfrom gateway.session_mutation_compress import prepare_compressfrom gateway.session_mutation_policy import PREPARE- prepare = {'model': prepare_model, 'compress': prepare_compress, **PREPARE}[operation]+ from gateway.session_local_mcp import prepare_editor_mcp+ prepare = {'model': prepare_model, 'compress': prepare_compress, **PREPARE,+ 'editor_mcp': partial(prepare_editor_mcp, servers=editor_servers)}[operation]prepared = await prepare(authority, live, params['payload'], prepared)applied = Falseif prepared.get('status') in {'preview', 'noop', 'confirmation_required'}:@@ -172,7 +182,7 @@ async def _mutate_session(authority, actor, ref, params, *, commit_lock=None):result = await asyncio.to_thread(mutate_runtime_session, authority.db, epoch=authority.epoch,principal_id=actor.subject, session_id=ref.session_id, request_id=params['request_id'],expected_revision=params['expected_revision'], expected_generation=params.get('expected_generation'),- operation=operation, payload=params['payload'], _live_guard=live_guard, _prepared=prepared,+ operation=operation, payload=params['payload'], _live_guard=live_guard, _prepared=branch_editor or prepared,_authorize_write=authorize_write if cold_history or operation == 'import' else None)# Post-commit projections are idempotent reads of the committed receipt, so exact# retries repeat them (like delete's retirement); only the one-shot event is fenced.@@ -185,6 +195,10 @@ async def _mutate_session(authority, actor, ref, params, *, commit_lock=None):note_compression(authority, ref, live)elif operation == 'reset' and applied and live is not None:live.compression_count = 0 # a fresh conversation, as main's /new builds a fresh agent+ if editor_servers is not None and (operation == 'branch' or owns_projection):+ # Before the policy publication below, so no execution sees the policy without them.+ from gateway.session_local_mcp import install_editor_mcp+ install_editor_mcp(authority, result.get('branched_session_id', ref.session_id), editor_servers)if operation not in {*_POLICY, 'reset', 'compress', 'rewind'} or owns_projection:_project_committed(authority, ref, operation, result)if live is not None:@@ -192,6 +206,8 @@ async def _mutate_session(authority, actor, ref, params, *, commit_lock=None):authority.runner._evict_cached_agent(live.route)if applied:live.event_stream.publish(ref.session_id, result, event_type='session.updated')+ from gateway.session_local_mcp import announce_tools_changed+ announce_tools_changed(live, ref.session_id, result)if operation == 'delete':# After the synchronous projections (no yield before retirement), off the loop: the# retired-media owner check is a messages-table pass (exact retries repeat it too).@@ -262,3 +278,5 @@ def retire_live_sessions(authority, session_ids):evict = getattr(authority.runner, '_evict_cached_agent', None)if callable(evict):evict(candidate.route)+ from gateway.session_local_mcp import release_editor_mcp+ release_editor_mcp(authority, session_ids)diff --git a/hermes_state_mutation_branch.py b/hermes_state_mutation_branch.pyindex b95443ba6c0..a61a94470e3 100644--- a/hermes_state_mutation_branch.py+++ b/hermes_state_mutation_branch.py@@ -31,7 +31,22 @@ def _branch_boundary(conn, target, through):return through-def branch_in_transaction(db, conn, session_id, payload):+def _child_policy(policy, child, prepared):+ """The parent's frozen policy, except editor MCP servers: the gateway prepared the child's own+ selection under the child's own scope (gateway/session_local_mcp.py ``prepare_branch_editor``).+ Copying the parent's would share its scope, borrowed credentials and live connections."""+ if prepared is None:+ if policy.get('editor_mcp_json'):+ raise RuntimeStoreError('runtime_coordination_required')+ return policy+ # Prepared against the parent's selection and the child id this commit derives; anything else moved.+ if child != prepared['child'] or policy.get('editor_mcp_json') != prepared['parent_editor_mcp_json']:+ raise RuntimeStoreError('revision_conflict')+ return {**policy, 'editor_mcp_json': prepared['editor_mcp_json'], 'toolsets': prepared['toolsets'],+ 'config_secret_ref': prepared['config_secret_ref']}+++def branch_in_transaction(db, conn, session_id, payload, prepared=None):row = conn.execute('SELECT value FROM state_meta WHERE key=?',(POLICY_PREFIX + session_id,)).fetchone()if row is None:@@ -43,8 +58,9 @@ def branch_in_transaction(db, conn, session_id, payload):from gateway.session import SessionEntry, SessionSourcefrom gateway.config import Platformfrom hermes_state_keys import local_identity, profile_from_session_key- request_id = 'branch:' + uuid.uuid4().hex+ request_id = prepared['request_id'] if prepared else 'branch:' + uuid.uuid4().hexchild = local_identity(saved['profile_id'], saved['principal_id'], request_id)+ policy = _child_policy(saved['policy'], child, prepared)# The child keeps the parent's owning profile: a served secondary's origin names it# (``local_source``), and restore compares the stored origin against that exactly.source = SessionSource(Platform.LOCAL, child, user_id=saved['principal_id'], chat_type='dm',@@ -55,7 +71,6 @@ def branch_in_transaction(db, conn, session_id, payload):now = _now()entry = SessionEntry(route, child, now, now, origin=source, platform=Platform.LOCAL)parent = conn.execute('SELECT * FROM sessions WHERE id=?', (target,)).fetchone()- policy = saved['policy']db._publish_child_session_row(conn, parent, parent_session_id=target,child_session_id=child, source=policy['source'], model=policy['model'],model_config={'_branched_from': target}, system_prompt=None,diff --git a/hermes_state_mutation_prepared.py b/hermes_state_mutation_prepared.pyindex d6fc1df22af..d305fbffd6a 100644--- a/hermes_state_mutation_prepared.py+++ b/hermes_state_mutation_prepared.py@@ -73,5 +73,11 @@ def workspace_in_transaction(db, conn, session_id, payload, prepared):'git_repo_root': git['root'] or None, 'execution_generation': generation}+def editor_mcp_in_transaction(db, conn, session_id, payload, prepared):+ snapshot, generation = _commit_policy(db, conn, session_id, prepared)+ return {session_id, snapshot['target']}, {'tools_changed': prepared['tools_changed'],+ 'mcp_servers': prepared['mcp_servers'], 'execution_generation': generation}++POLICY_HANDLERS = {'model': model_in_transaction, 'reasoning': reasoning_in_transaction,- 'workspace': workspace_in_transaction}+ 'workspace': workspace_in_transaction, 'editor_mcp': editor_mcp_in_transaction}diff --git a/hermes_state_mutations.py b/hermes_state_mutations.pyindex b3e7a71ea3b..73374396f92 100644--- a/hermes_state_mutations.py+++ b/hermes_state_mutations.py@@ -22,6 +22,10 @@ def validate_action(operation, payload):returnif operation == 'workspace' and set(payload) == {'cwd'} and isinstance(payload['cwd'], str) and payload['cwd'].strip():return+ # The editor's MCP servers (gateway/session_local_mcp.py): the owner keeps the list in memory and+ # hands the store only its fingerprint, so no transport credential reaches a receipt.+ if operation == 'editor_mcp' and set(payload) == {'mcp_servers'} and _valid_editor_fingerprint(payload):+ returnif operation == 'compress' and _valid_compress_payload(payload):returnif operation in {'delete', 'reset'} and not payload:@@ -45,7 +49,9 @@ def validate_action(operation, payload):def _valid_branch_payload(payload):# ``through_message_id``: the physical row id of the last message the branch keeps (a stable# boundary, never a visible-message count); absent means the whole active transcript.- if set(payload) - {'title', 'through_message_id'}:+ if set(payload) - {'title', 'through_message_id', 'mcp_servers'}:+ return False+ if 'mcp_servers' in payload and not _valid_editor_fingerprint(payload):return Falseif 'title' in payload and not isinstance(payload['title'], str):return False@@ -53,6 +59,11 @@ def _valid_branch_payload(payload):type(payload['through_message_id']) is int and payload['through_message_id'] > 0)+def _valid_editor_fingerprint(payload):+ servers = payload['mcp_servers']+ return isinstance(servers, dict) and set(servers) == {'fingerprint'} and isinstance(servers['fingerprint'], str)++_COMPRESS_FIELDS = {'focus': str, 'preview': bool, 'partial': bool, 'keep_last': int}@@ -70,13 +81,14 @@ def apply_action(db, conn, session_id, operation, payload, *, prepared=None):if operation == 'compress':from hermes_state_mutation_compress import compress_in_transactionreturn compress_in_transaction(db, conn, session_id, payload, prepared)- if operation in {'model', 'reasoning', 'workspace'}:+ if operation in {'model', 'reasoning', 'workspace', 'editor_mcp'}:from hermes_state_mutation_prepared import POLICY_HANDLERSreturn POLICY_HANDLERS[operation](db, conn, session_id, payload, prepared)+ if operation == 'branch':+ from hermes_state_mutation_branch import branch_in_transaction+ return branch_in_transaction(db, conn, session_id, payload, prepared)from hermes_state_mutation_reset import reset_in_transaction- from hermes_state_mutation_branch import branch_in_transaction- handlers = {'delete': _delete, 'import': _import, 'rewind': _rewind, 'reset': reset_in_transaction,- 'branch': branch_in_transaction}+ handlers = {'delete': _delete, 'import': _import, 'rewind': _rewind, 'reset': reset_in_transaction}if operation in handlers:return handlers[operation](db, conn, session_id, payload)affected = set()diff --git a/tests/acp_adapter/test_gateway_editor_mcp.py b/tests/acp_adapter/test_gateway_editor_mcp.pyindex d7fbf9b1720..ea980db1d98 100644--- a/tests/acp_adapter/test_gateway_editor_mcp.py+++ b/tests/acp_adapter/test_gateway_editor_mcp.py@@ -1,10 +1,17 @@-"""Native ACP stdio through ordinary gateway source, real model and MCP peers."""+"""Native ACP stdio through ordinary gateway source, real model and MCP peers.++The editor's ``mcpServers`` is a request: the owner binds each session's servers under that+session's own scope, changes them only through the fenced ``editor_mcp`` mutation (or a re-freeze+at an admission start), and never writes a transport credential to state.db or events+(#134889 ACP-8, ACP-10, ACP-12).+"""import asynciofrom http.server import BaseHTTPRequestHandlerimport jsonimport osimport reimport signal+import sqlite3import subprocessimport sysimport time@@ -12,6 +19,7 @@ import timeimport psutilimport pytest+from hermes_cli.gateway_client import GatewayRPCErrorfrom tests.acp_adapter.test_gateway_sessions import editor, viewerfrom tests.gateway.test_normal_runtime_boot import controlfrom tests.waiting import async_wait_until@@ -85,6 +93,14 @@ for line in sys.stdin:return spec('A'), spec('B')+def respec(spec, marker, tmp_path):+ """*spec*'s server with another marker, gate and borrowed secret (same name, same tools)."""+ changed = json.loads(json.dumps(spec))+ changed['env'] = [{'name': 'MARKER', 'value': marker}, {'name': 'GATE', 'value': str(tmp_path / marker)},+ {'name': 'BORROWED_TOKEN', 'value': 'opaque-secret-' + marker}]+ return changed++async def initialize(acp):assert 'result' in await acp.rpc('initialize', protocolVersion=1, clientCapabilities={})@@ -126,7 +142,6 @@ async def test_native_opposing_editor_mcp_survives_viewer_exit(daemon, specs, tmfor session_id in (sid, bs):saved = await ws.rpc('session.resume', session_id=session_id)assert 'OWNED_RESULT_' in json.dumps(saved['messages'])- import sqlite3with sqlite3.connect(daemon[0] / 'state.db') as db:dump = '\n'.join(db.iterdump())assert all('opaque-secret-' + marker not in dump for marker in ('A', 'B'))@@ -136,8 +151,10 @@ async def test_native_opposing_editor_mcp_survives_viewer_exit(daemon, specs, tm@pytest.mark.platforms("linux")@pytest.mark.asyncio-async def test_native_cold_editor_rebind_refuses_changed_secret(daemon, specs, tmp_path, model_peer):+async def test_native_cold_editor_rebind_applies_changed_secret(daemon, specs, tmp_path, model_peer):+ """A changed editor config on load is the owner's ``editor_mcp`` rebind, not a refusal (#134889 ACP-10)."""(tmp_path / 'A').touch()+ (tmp_path / 'C').touch()async with editor(daemon, tmp_path) as acp:await initialize(acp)created = await acp.rpc('session/new', cwd=str(tmp_path), mcpServers=[specs[0]])@@ -166,18 +183,152 @@ async def test_native_cold_editor_rebind_refuses_changed_secret(daemon, specs, tcold = home, current, env, rootasync with editor(cold, tmp_path) as acp:await initialize(acp)- changed = json.loads(json.dumps(specs[0]))- changed['env'][-1]['value'] = 'changed-secret'- refused = await acp.rpc('session/load', sessionId=sid, cwd=str(tmp_path), mcpServers=[changed])- assert 'acp_mcp_policy_conflict' in json.dumps(refused), refused- loaded = await acp.rpc('session/load', sessionId=sid, cwd=str(tmp_path), mcpServers=[specs[0]])+ changed = respec(specs[0], 'C', tmp_path)+ loaded = await acp.rpc('session/load', sessionId=sid, cwd=str(tmp_path), mcpServers=[changed])assert 'result' in loaded, loadedacp.frames.clear() # Old replay is not evidence of new execution.assert 'result' in await prompt(acp, sid, 'Use owned echo after restart')- assert 'OWNED_RESULT_A' in json.dumps(acp.frames)+ frames = json.dumps(acp.frames)+ assert 'OWNED_RESULT_C' in frames and 'OWNED_RESULT_A' not in frames+ # Same server, same schemas: the frozen manifest (prompt-cache prefix) did not move.+ assert 'Editor MCP tools changed' not in frames+ assert 'opaque-secret-' not in frames+ with sqlite3.connect(home / 'state.db') as db:+ dump = '\n'.join(db.iterdump())+ assert all('opaque-secret-' + marker not in dump for marker in 'AC')print('ACP_MCP_COLD_RECEIPT=' + json.dumps({'session_id': sid,- 'old_pid': descriptor['pid'], 'new_pid': process.pid, 'changed_secret_refused': True}))+ 'old_pid': descriptor['pid'], 'new_pid': process.pid, 'changed_secret_rebound': True}))finally:if process.poll() is None:process.send_signal(signal.SIGINT)await asyncio.to_thread(process.wait, 20)+++def _policies(home, *session_ids):+ with sqlite3.connect(home / 'state.db') as db:+ rows = [db.execute('SELECT value FROM state_meta WHERE key=?',+ ('gateway.local_policy.v1:' + sid,)).fetchone()[0] for sid in session_ids]+ dump = '\n'.join(db.iterdump())+ assert 'opaque-secret-' not in dump+ return [json.loads(json.loads(row)['policy']['editor_mcp_json'] or 'null') for row in rows]+++def _peers_running(pid):+ return [child for child in psutil.Process(pid).children(recursive=True)+ if any('peer.py' in part for part in child.cmdline())]++[email protected]("linux")+async def test_native_fork_binds_child_editor_mcp_in_its_own_scope(daemon, specs, tmp_path, model_peer):+ for marker in 'AC':+ (tmp_path / marker).write_text('release')+ async with editor(daemon, tmp_path) as acp:+ await initialize(acp)+ created = await acp.rpc('session/new', cwd=str(tmp_path), mcpServers=[specs[0]])+ assert 'result' in created, created+ sid = created['result']['sessionId']+ assert 'result' in await prompt(acp, sid)+ forked = await acp.rpc('session/fork', sessionId=sid, cwd=str(tmp_path),+ mcpServers=[respec(specs[0], 'C', tmp_path)])+ assert 'result' in forked, forked+ child = forked['result']['sessionId']+ acp.frames.clear()+ assert 'result' in await prompt(acp, child)+ frames = json.dumps(acp.frames)+ assert 'OWNED_RESULT_C' in frames and 'OWNED_RESULT_A' not in frames+ # No list: the child gets a copy of the parent's servers, still under its own scope.+ copied = await acp.rpc('session/fork', sessionId=sid, cwd=str(tmp_path), mcpServers=[])+ assert 'result' in copied, copied+ twin = copied['result']['sessionId']+ acp.frames.clear()+ assert 'result' in await prompt(acp, twin)+ assert 'OWNED_RESULT_A' in json.dumps(acp.frames)+ acp.frames.clear()+ assert 'result' in await prompt(acp, sid, 'Use owned echo again')+ frames = json.dumps(acp.frames)+ assert 'OWNED_RESULT_A' in frames and 'OWNED_RESULT_C' not in frames+ assert 'opaque-secret-' not in frames+ parent, forked_policy, twin_policy = _policies(daemon[0], sid, child, twin)+ assert len({parent['scope'], forked_policy['scope'], twin_policy['scope']}) == 3+ assert forked_policy['fingerprint'] != parent['fingerprint'] == twin_policy['fingerprint']++[email protected]("linux")+async def test_native_schema_drift_refreezes_at_the_next_turn(daemon, specs, tmp_path, model_peer):+ (tmp_path / 'A').write_text('release')+ async with editor(daemon, tmp_path) as acp:+ await initialize(acp)+ created = await acp.rpc('session/new', cwd=str(tmp_path), mcpServers=[specs[0]])+ assert 'result' in created, created+ sid = created['result']['sessionId']+ assert 'result' in await prompt(acp, sid)+ # The last viewer left: its connection closes. The server's schema then changes.+ await async_wait_until(lambda: not _peers_running(daemon[1]['pid']), timeout=20,+ what='editor MCP peer released with the last viewer')+ script = tmp_path / 'peer.py'+ script.write_text(script.read_text().replace("'owned echo'", "'drifted echo'"))+ async with editor(daemon, tmp_path) as acp:+ await initialize(acp)+ loaded = await acp.rpc('session/load', sessionId=sid, cwd=str(tmp_path), mcpServers=[specs[0]])+ assert 'result' in loaded, loaded+ acp.frames.clear()+ reply = await prompt(acp, sid, 'Use owned echo after drift')+ assert 'result' in reply, reply+ frames = json.dumps(acp.frames)+ assert 'Editor MCP tools changed (servers: same-name)' in frames+ assert 'OWNED_RESULT_A' in frames and 'opaque-secret-' not in frames+ (frozen,) = _policies(daemon[0], sid)+ assert 'drifted echo' in json.dumps(frozen['schemas'])+++def _completed(ws, frames, marker):+ """Predicate: a ``message.complete`` carrying *marker* arrived (its admission is terminal)."""+ def seen():+ while not ws.events.empty():+ frames.append(ws.events.get_nowait())+ return any(frame['params'].get('type') == 'message.complete' and marker in json.dumps(frame)+ for frame in frames)+ return seen++[email protected]("linux")+async def test_editor_mcp_mutation_is_fenced_idle_only_and_secret_free(daemon, specs, tmp_path, model_peer):+ async with viewer(daemon) as ws:+ created = await ws.rpc('session.create', request_id='editor-owner', source='acp', cwd=str(tmp_path),+ editor={'mcp_servers': [specs[0]], 'edit_approval_policy': 'ask'})+ sid = created['session_id']+ snapshot = await ws.rpc('session.resume', session_id=sid)+ changed = respec(specs[0], 'C', tmp_path)+ base = dict(session_id=sid, operation='editor_mcp', payload={'mcp_servers': [changed]})+ with pytest.raises(GatewayRPCError, match='invalid_params'):+ await ws.rpc('session.mutate', request_id='unfenced', expected_revision=snapshot['revision'], **base)+ with pytest.raises(GatewayRPCError, match='revision_conflict'):+ await ws.rpc('session.mutate', request_id='stale', expected_revision=snapshot['revision'] + 5,+ expected_generation=snapshot['execution_generation'], **base)+ await ws.rpc('prompt.submit', session_id=sid, input_id='busy-turn', text='Use owned echo')+ await async_wait_until(lambda: (tmp_path / 'A.entered').exists(), timeout=25, what='turn inside the MCP tool')+ running = await ws.rpc('session.resume', session_id=sid)+ with pytest.raises(GatewayRPCError, match='session_busy'):+ await ws.rpc('session.mutate', request_id='busy', expected_revision=running['revision'],+ expected_generation=running['execution_generation'], **base)+ (tmp_path / 'A').write_text('release')+ frames = []+ await async_wait_until(_completed(ws, frames, 'OWNED_RESULT_A'), timeout=30, what='first turn settled')+ idle = await ws.rpc('session.resume', session_id=sid)+ fence = dict(expected_revision=idle['revision'], expected_generation=idle['execution_generation'])+ applied = await ws.rpc('session.mutate', request_id='applied', **fence, **base)+ assert applied['tools_changed'] is False and applied['mcp_servers'] == ['same-name']+ assert applied['revision'] > idle['revision']+ assert await ws.rpc('session.mutate', request_id='applied', **fence, **base) == applied+ (tmp_path / 'C').write_text('release')+ await ws.rpc('prompt.submit', session_id=sid, input_id='after-rebind', text='Use owned echo')+ await async_wait_until(_completed(ws, frames, 'OWNED_RESULT_C'), timeout=30, what='rebound turn settled')+ events = json.dumps(frames)+ assert 'OWNED_RESULT_C' in events+ assert 'opaque-secret-' not in events and 'BORROWED_TOKEN' not in events+ from gateway.session_local_mcp import fingerprint+ (frozen,) = _policies(daemon[0], sid)+ assert frozen['fingerprint'] == fingerprint([changed])diff --git a/tests/acp_adapter/test_session_mcp_ownership.py b/tests/acp_adapter/test_session_mcp_ownership.pynew file mode 100644index 00000000000..596fae557ad--- /dev/null+++ b/tests/acp_adapter/test_session_mcp_ownership.py@@ -0,0 +1,121 @@+"""The gateway owns each session's editor MCP servers as session state (#134889 ACP-8/ACP-10).++A changed editor list re-freezes through one owner path (equal schemas keep the manifest), and a+viewed session keeps its connections between executions instead of respawning them per turn.+"""+import asyncio+import json+from types import SimpleNamespace++import pytest++from gateway.session_policy import policy_scope+from hermes_state_runtime import RuntimeStoreError+from tests.acp_adapter.test_session_mcp_policy import owner, policy+++def _editor_servers():+ from tools.mcp_tool import _servers+ return {key: server for key, server in _servers.items() if key[-1].startswith('editor_')}+++def test_changed_credentials_with_equal_schemas_keep_the_manifest(server_spec, tmp_path):+ from gateway.session_local_mcp import attach_editor_mcp, rebind_editor_mcp+ from tools.registry import registry+ authority = owner()+ before = policy(authority, 'rebind', server_spec, tmp_path)+ changed = json.loads(json.dumps(server_spec))+ changed['env'][0]['value'] = 'PRIVATE_B'+ after, tools_changed = rebind_editor_mcp(authority, 'rebind', before, [changed])+ old, new = json.loads(before.editor_mcp_json), json.loads(after.editor_mcp_json)+ # The prompt-cache prefix (tool manifest + toolsets) is byte-stable; only the fingerprint moved.+ assert not tools_changed+ assert new['schemas'] == old['schemas'] and new['names'] == old['names'] and new['scope'] == old['scope']+ assert after.toolsets == before.toolsets+ assert new['fingerprint'] != old['fingerprint']+ assert 'PRIVATE_B' not in after.editor_mcp_json+ attach_editor_mcp(authority, after, [changed])+ with policy_scope(after, authority=authority):+ names = [n for n in registry.get_all_tool_names() if n.startswith('mcp__')]+ assert 'PRIVATE_B' in registry.dispatch(names[0], {})+++def test_changed_schema_is_reported_as_a_manifest_change(server_spec, tmp_path):+ from gateway.session_local_mcp import rebind_editor_mcp+ authority = owner()+ before = policy(authority, 'schema', server_spec, tmp_path)+ script = tmp_path / 'owned_mcp.py'+ script.write_text(script.read_text().replace('owned echo', 'renamed echo'))+ after, tools_changed = rebind_editor_mcp(authority, 'schema', before, [server_spec])+ assert tools_changed+ schemas = json.loads(after.editor_mcp_json)['schemas']+ assert 'renamed echo' in json.dumps(schemas)+ assert after.toolsets == before.toolsets # same server, same ledger name+++def test_viewed_session_keeps_editor_connections_between_executions(server_spec, tmp_path):+ from gateway.session_local_mcp import release_editor_mcp+ authority = owner()+ live = SimpleNamespace(subscribers={'editor': object()})+ authority.sessions = {'viewed': live}+ p = policy(authority, 'viewed', server_spec, tmp_path)+ with policy_scope(p, authority=authority):+ first = _editor_servers()+ assert first, 'a viewed session keeps its editor servers connected after the execution'+ with policy_scope(p, authority=authority):+ assert _editor_servers() == first # the same connection objects: no respawn per turn+ # Another session with the same editor config never adopts these connections.+ authority.sessions['other'] = SimpleNamespace(subscribers={'editor': object()})+ other = policy(authority, 'other', server_spec, tmp_path)+ with policy_scope(other, authority=authority):+ assert set(_editor_servers()) - set(first)+ live.subscribers.clear()+ authority.sessions['other'].subscribers.clear()+ release_editor_mcp(authority, ['viewed', 'other'])+ assert not _editor_servers()+++def test_unviewed_session_releases_editor_connections_after_execution(server_spec, tmp_path):+ authority = owner()+ authority.sessions = {'quiet': SimpleNamespace(subscribers={})}+ p = policy(authority, 'quiet', server_spec, tmp_path)+ with policy_scope(p, authority=authority):+ assert _editor_servers()+ assert not _editor_servers()+++def test_editor_scopes_are_per_session_and_per_profile():+ from gateway.session_local_mcp import session_scope+ one, other = owner(), SimpleNamespace(profile_id='other-profile')+ assert session_scope(one, 'parent') != session_scope(one, 'child')+ assert session_scope(one, 'parent') != session_scope(other, 'parent')++[email protected](('actor_profile', 'capabilities', 'reason'), [+ ('owned-profile', {'session:read', 'session:submit'}, 'permission_denied'),+ ('foreign-profile', {'session:read', 'session:submit', 'session:control'}, 'profile_mismatch'),+])+def test_editor_mcp_change_requires_control_in_the_owning_profile(server_spec, actor_profile, capabilities, reason):+ from gateway.session_contract import Principal, SessionRef+ from gateway.session_mutations import _mutate_session+ authority = owner()+ actor = Principal('viewer', actor_profile, frozenset(capabilities), 'viewer-transport')+ params = {'session_id': 'held', 'request_id': 'r', 'expected_revision': 0, 'expected_generation': 0,+ 'operation': 'editor_mcp', 'payload': {'mcp_servers': [server_spec]}}+ with pytest.raises(RuntimeStoreError, match=reason):+ asyncio.run(_mutate_session(authority, actor, SessionRef('owned-profile', 'held'), params))+ assert not _editor_servers() # refused before any discovery+++def test_store_payload_carries_only_the_fingerprint(server_spec):+ from gateway.session_local_mcp import fingerprint, private_mutation_payload+ from hermes_state_mutations import validate_action+ payload, servers = private_mutation_payload('editor_mcp', {'mcp_servers': [server_spec]})+ assert servers == [server_spec]+ assert payload == {'mcp_servers': {'fingerprint': fingerprint([server_spec])}}+ assert 'PRIVATE_A' not in json.dumps(payload)+ validate_action('editor_mcp', payload)+ with pytest.raises(RuntimeStoreError, match='invalid_params'):+ validate_action('editor_mcp', {'mcp_servers': [server_spec]})+ branch, _ = private_mutation_payload('branch', {'mcp_servers': [server_spec]})+ validate_action('branch', branch)