Skip to content

The agent that grows with you

fix(gateway): a reload naming the revision the session holds is not refused

qbyc14952a93fa1
diff --git a/gateway/session_ancillary.py b/gateway/session_ancillary.py
index 28f2a313c52..29af104e17d 100644
--- a/gateway/session_ancillary.py
+++ b/gateway/session_ancillary.py
@@ -257,7 +257,8 @@ async def reload_mcp(connection, ref, params):
session's MCP servers then change as a new policy generation when it is idle (``session``: applied,
unchanged or busy); other sessions take theirs when next attached. A configured server that did not
connect is named: a refusal when nothing took effect (no server registered or removed, no session
- generation), else ``unavailable`` beside the success."""
+ generation), else ``unavailable`` beside the success. A call naming ``rev``, the revision the session
+ already holds, is that same nothing-left-to-load, answered as success with ``loaded_rev``."""
if set(params) - {'session_id', 'confirm', 'rev', 'profile'}:
raise RuntimeStoreError('invalid_params')
if 'session:control' not in connection.actor.capabilities:
@@ -279,7 +280,12 @@ async def reload_mcp(connection, ref, params):
multiplex = bool(getattr(runner.config, 'multiplex_profiles', False))
runner._mcp_reload_refresh_cached_agents(multiplex, served_profile_name(connection.authority.profile_id))
session = await _commit_session_mcp(connection, ref, params)
- if failed and session != 'applied' and not (result.get('removed') or result['added']):
+ held_rev = await asyncio.to_thread(_held_mcp_rev, connection, ref) if params.get('rev') else ''
+ # Refuse only a reload whose own work did not take effect: a call that names the revision the session
+ # already holds has nothing left to load, and refusing it leaves a client that acknowledges on
+ # ``reloaded`` retrying a parked server at poll rate with no way to close the handshake (#141769).
+ if (failed and session != 'applied' and not (result.get('removed') or result['added'])
+ and params.get('rev') != held_rev):
raise RuntimeStoreError('mcp_servers_unavailable', field='mcp_servers',
detail=f'did not connect: {", ".join(failed)}')
changed = ', '.join(f'{k}: {", ".join(v)}' for k, v in result.items() if v) or 'no server changes'
@@ -290,9 +296,26 @@ async def reload_mcp(connection, ref, params):
selected = {'session_servers': await asyncio.to_thread(_session_servers, connection.authority, ref.session_id,
ready)} if session else {}
return {'status': 'reloaded', 'message': f'MCP servers reconciled ({changed}){note}{unavailable}',
+ **({'loaded_rev': held_rev} if held_rev else {}),
**({'session': session} if session else {}), **({'unavailable': failed} if failed else {}), **selected}
+def _held_mcp_rev(connection, ref):
+ """The ``mcp_rev`` this session's committed policy already holds — the value ``config.get mtime`` shipped
+ the client — or ``''`` when the call names no live local session."""
+ sid = getattr(ref, 'session_id', None)
+ live = connection.authority.sessions.get(sid) if sid else None
+ if live is None or live.source is None:
+ return ''
+ from pathlib import Path
+ from gateway.run import _profile_runtime_scope
+ from gateway.session_config import mcp_revision
+ from gateway.session_policy import policy_for_source
+ from hermes_cli.config import load_config
+ with _profile_runtime_scope(Path(connection.authority.profile_id)):
+ return mcp_revision(policy_for_source(connection.authority.runner, live.source), load_config())
+
+
def _session_servers(authority, sid, ready):
"""The profile MCP servers the session's committed policy runs (its toolsets name them) that are *ready*
(live or lazy): a server connected for the profile is not one a chat with ``no_mcp``, an explicit pick or
diff --git a/gateway/session_config.py b/gateway/session_config.py
index b2fae77f9cb..13b009d43d1 100644
--- a/gateway/session_config.py
+++ b/gateway/session_config.py
@@ -33,6 +33,16 @@ def _authorize(connection, ref, params):
return None
+def mcp_revision(policy, cfg) -> str:
+ """``mcp_rev``: the MCP-relevant sections a client polls (``config.get mtime``) and names back on
+ ``reload.mcp``. Read from the session's frozen policy when it has one — a live config edit is not an
+ MCP reload request, it reaches a chat as a committed generation — so the value a client is told to load
+ is the value the session already holds."""
+ return hashlib.sha256(json.dumps({k: (policy.config() if policy else cfg).get(k)
+ for k in ('mcp', 'mcp_servers', 'tools')},
+ sort_keys=True).encode()).hexdigest()[:12]
+
+
def _client_config(cfg):
# Native full-config consumers are presentation-only. Do not export provider,
# MCP, plugin or terminal configuration (which can contain arbitrary secrets).
@@ -85,10 +95,7 @@ async def config_get(connection, ref, params):
'mtime': lambda: {'mtime': (home / 'config.yaml').stat().st_mtime
if (home / 'config.yaml').exists() else 0,
# Frozen tool policy is not a live MCP reload request.
- 'mcp_rev': hashlib.sha256(json.dumps({
- k: (policy.config() if policy else cfg).get(k)
- for k in ('mcp', 'mcp_servers', 'tools')},
- sort_keys=True).encode()).hexdigest()[:12]},
+ 'mcp_rev': mcp_revision(policy, cfg)},
'reasoning': lambda: _reasoning(agent, policy, cfg, connection, ref),
'fast': lambda: _fast(connection, ref, policy, agent, cfg),
'skin': lambda: {'value': display.get('skin', 'default')},
diff --git a/tests/gateway/test_mcp_reload_held_revision.py b/tests/gateway/test_mcp_reload_held_revision.py
new file mode 100644
index 00000000000..899e308ed51
--- /dev/null
+++ b/tests/gateway/test_mcp_reload_held_revision.py
@@ -0,0 +1,73 @@
+"""A ``reload.mcp`` that names the revision the calling session already holds has nothing left to load:
+it answers the success shape (naming the configured server that is down) instead of the named refusal, so
+a client that only advances its accepted revision on ``status: reloaded`` can acknowledge it (#141769).
+
+The refusal stays for a caller that names no revision, and for one that names a revision the session does
+not hold: those still describe a reload whose work did not take effect.
+"""
+import json
+from types import SimpleNamespace
+
+import pytest
+
+from tests.gateway.test_session_resume_config_refresh import _call, _connect, _owner_authority
+
+CONFIG = ('model: {default: m1, provider: custom, base_url: "http://127.0.0.1:9/v1"}\n'
+ 'platform_toolsets: {cli: [terminal]}\nterminal: {backend: local}\n'
+ 'mcp_servers: {old: {command: old-mcp}}\n')
+
+
+def _home(monkeypatch):
+ from gateway import run
+ from hermes_constants import get_hermes_home
+ home = get_hermes_home()
+ home.mkdir(parents=True, exist_ok=True)
+ (home / 'config.yaml').write_text(CONFIG)
+ monkeypatch.setattr(run, '_hermes_home', home)
+ return home
+
+
+def _reloaded_profile(authority, monkeypatch):
+ """reload.mcp's profile side: the owner's reconcile has nothing to add or remove, and one configured
+ server is down — the state after a gateway restart whose TUI re-attached."""
+ authority.runner.config = SimpleNamespace(multiplex_profiles=False)
+ authority.runner._mcp_reload_refresh_cached_agents = lambda multiplex, profile: None
+ monkeypatch.setattr('gateway.session_authorities.served_profile_name', lambda profile_id: 'default')
+ monkeypatch.setattr('tools.mcp_tool_discovery.reconcile_mcp_servers_with_config',
+ lambda: {'removed': [], 'added': [], 'pending': []})
+ monkeypatch.setattr('tools.mcp_tool_discovery.mcp_servers_not_connected', lambda: ['parked'])
+ monkeypatch.setattr('tools.mcp_tool_discovery.mcp_servers_ready', lambda: ['old'])
+
+
+def _refusal(reply):
+ assert 'result' not in reply, reply
+ return json.dumps(reply['error'])
+
+
+async def test_a_reload_naming_the_revision_the_session_holds_is_not_refused(tmp_path, monkeypatch):
+ home = _home(monkeypatch)
+ monkeypatch.setattr('gateway.session_policy.launch_key', lambda authority, policy: None)
+ store, authority = await _owner_authority(home)
+ _reloaded_profile(authority, monkeypatch)
+ owner = _connect(authority)
+ try:
+ sid = (await _call(owner, 'session.create', request_id='a', source='cli', cwd=str(tmp_path)))['session_id']
+ rev = (await _call(owner, 'config.get', key='mtime', session_id=sid))['mcp_rev']
+ assert rev and rev != 'deadbeefcafe'
+ # The revision the poller was told to load is the one this session already holds: the acknowledged
+ # handshake must close, and the down server is named beside the success instead of replacing it.
+ result = await _call(owner, 'reload.mcp', session_id=sid, confirm=True, rev=rev)
+ assert result['status'] == 'reloaded' and result['unavailable'] == ['parked'], result
+ assert result['loaded_rev'] == rev and result['session'] == 'unchanged', result
+ assert 'did not connect: parked' in result['message'], result
+ # A client that names no revision describes a reload whose own work did not take effect: refused.
+ assert 'parked' in _refusal(await owner.dispatch(
+ {'id': 2, 'method': 'reload.mcp', 'params': {'session_id': sid, 'confirm': True}}))
+ # A revision this session does not hold is still a reload that has work left to do: refused.
+ assert 'parked' in _refusal(await owner.dispatch(
+ {'id': 3, 'method': 'reload.mcp',
+ 'params': {'session_id': sid, 'confirm': True, 'rev': 'deadbeefcafe'}}))
+ finally:
+ await owner.close()
+ store.close_all_db_handles()