Skip to content

The agent that grows with you

fix(gateway): close the review edges on named session.create refusals

Tekniumb51e8b850494
diff --git a/gateway/session_controls.py b/gateway/session_controls.py
index 640a442ef12..d3412405569 100644
--- a/gateway/session_controls.py
+++ b/gateway/session_controls.py
@@ -352,7 +352,7 @@ class AuthorityConnection:
# the frozen request: the policy re-reads the profile's current route every turn.
hidden = params.pop('hidden', False)
if type(hidden) is not bool:
- raise RuntimeStoreError('invalid_params')
+ raise RuntimeStoreError('invalid_params', field='hidden', detail='must be a boolean')
ref = title and resolve_titled_session(self.authority, self.actor, title, missing_ok=True)
if not ref:
skills_prompt = None
diff --git a/gateway/session_local.py b/gateway/session_local.py
index f4aa27d68d5..b6d460e374d 100644
--- a/gateway/session_local.py
+++ b/gateway/session_local.py
@@ -137,7 +137,8 @@ def _bypass_policy(params, *, private_secrets):
from gateway.session_policy import build_policy
from hermes_cli.config_defaults import DEFAULT_CONFIG
if not params.get('model'):
- raise RuntimeStoreError('invalid_params')
+ raise RuntimeStoreError('invalid_params', field='model',
+ detail='a bypass launch has no profile to inherit a model from')
defaults = copy.deepcopy(DEFAULT_CONFIG)
if not isinstance(defaults.get('model'), dict): # code default is the empty string
defaults['model'] = {}
@@ -188,7 +189,8 @@ def stage_local_session(authority, actor, params, *, trusted_policy=None, truste
policy = replace(policy, model=_resolve_gateway_model(policy.config()))
request_id = params.get('request_id', uuid.uuid4().hex)
if not isinstance(request_id, str) or not request_id or len(request_id) > 256:
- raise RuntimeStoreError('invalid_params')
+ raise RuntimeStoreError('invalid_params', field='request_id',
+ detail='must be a non-empty string of at most 256 characters')
from dataclasses import asdict
from gateway.session import SessionEntry
from gateway.session_lifecycle import _now
@@ -201,7 +203,8 @@ def stage_local_session(authority, actor, params, *, trusted_policy=None, truste
saved = local_receipt(authority.db, sid)
original = restore_policy(saved['policy'])
if original.request_json != policy.request_json:
- raise RuntimeStoreError('invalid_params')
+ raise RuntimeStoreError('invalid_params', field='request_id',
+ detail='a resumed request_id must carry the same frozen request')
if original.credential_ref is not None or params.get('api_key') is not None:
import hmac
key = launch_key(authority, original)
@@ -212,7 +215,8 @@ def stage_local_session(authority, actor, params, *, trusted_policy=None, truste
if launch_skills(params) and skills_prompt is None:
# `-s` is rendered off-loop by the RPC handler (render_launch_skills); a caller that
# skipped it must not mint a session silently missing its preload.
- raise RuntimeStoreError('invalid_params')
+ raise RuntimeStoreError('invalid_params', field='skills',
+ detail='the caller must render -s skills before minting the session')
policy = replace(policy, skills_prompt=skills_prompt)
policy = bind_launch_key(authority, sid, policy, params.get("api_key"), config_secrets=private_secrets)
from gateway.session_local_recovery import local_source
diff --git a/gateway/session_local_mcp.py b/gateway/session_local_mcp.py
index 225c91a7fd1..28171041124 100644
--- a/gateway/session_local_mcp.py
+++ b/gateway/session_local_mcp.py
@@ -60,8 +60,14 @@ def validate_servers(servers):
raise ValueError('duplicate server')
names.add(model.name)
except (ValidationError, KeyError, AttributeError, TypeError, ValueError) as exc:
+ # Never the message: pydantic's carries ``input_value=`` and a server's argv may hold a credential.
+ if isinstance(exc, ValidationError):
+ why = '; '.join(f"{'.'.join(map(str, err['loc']))}: {err['type']}"
+ for err in exc.errors(include_input=False))
+ else:
+ why = 'duplicate server' if str(exc) == 'duplicate server' else type(exc).__name__
raise RuntimeStoreError('invalid_params', field='editor.mcp_servers',
- detail=f'unusable server spec: {str(exc)[:120]}') from exc
+ detail=f'unusable server spec: {why}') from exc
def private_editor_request(request, private):
diff --git a/gateway/session_policy.py b/gateway/session_policy.py
index 7f47591c257..e6a3d1c2234 100644
--- a/gateway/session_policy.py
+++ b/gateway/session_policy.py
@@ -37,9 +37,9 @@ def _refuse(field, detail=None):
``reason`` stays the bounded wire code every caller compares as a string; ``field`` and
``detail`` are what tells ~20 different create checks apart, in the client and in the
- gateway log, without a second run to find out which one fired."""
- raise RuntimeStoreError('invalid_params', field=str(field)[:80],
- detail=None if detail is None else str(detail)[:160])
+ gateway log, without a second run to find out which one fired (``RuntimeStoreError`` bounds
+ and flattens both)."""
+ raise RuntimeStoreError('invalid_params', field=field, detail=detail)
@dataclass(frozen=True)
@@ -309,7 +309,7 @@ def build_policy(params, config, *, private_secrets=None, profile_terminal=True,
# pick wins anyway; skipping it here also spares the probe.
named = workspace_posture and source != 'tool' and 'cwd' in params and 'toolsets' not in params
coding_posture = named and _in_coding_workspace(config, source, cwd)
- enabled = _resolve_toolsets(params, config, source, safe_mode, coding_posture)
+ enabled = _resolve_toolsets(params, config, source, safe_mode, coding_posture, bypass=ignore_user_config)
terminal = build_profile_terminal_scope(get_hermes_home()) if profile_terminal else default_terminal_scope()
# The client's launch folder is a path on THIS host: a remote or container backend keeps its own
# configured cwd unless the user picked this folder for the session.
@@ -408,22 +408,30 @@ def _apply_launch_overrides(params, config):
config['agent'].pop('reasoning_overrides', None)
-def _resolve_toolsets(params, config, source, safe_mode, coding_posture=False):
+def _resolve_toolsets(params, config, source, safe_mode, coding_posture=False, bypass=False):
"""Validate explicit toolsets and return the session's enabled toolset set. Without a pick, a
*coding_posture* session runs ``focus_toolsets`` instead of the profile default while the profile
stays on ``focus``; the gateway decides it, never the client."""
- from hermes_cli.tools_config import _get_platform_tools
+ from hermes_cli.tools_config import _get_platform_tools, enabled_mcp_server_names
from hermes_cli.toolset_validation import saved_toolset_resolver
+ from toolsets import validate_toolset
explicit = params.get('toolsets')
if 'toolsets' in params:
if not isinstance(explicit, list):
_refuse('toolsets', f'must be a list of toolset names, got {type(explicit).__name__}')
# The CLI validator's rule: a configured MCP server's toolset registers only after its first
- # connect, so an offline server is inactive, not a typo (#138748, #139154).
- known = saved_toolset_resolver(config)
+ # connect, so an offline server is inactive, not a typo (#138748, #139154). A bypass launch never
+ # reads the profile, so it takes the in-process registry alone.
+ known = validate_toolset if bypass else saved_toolset_resolver(config)
+ configured = config.get('mcp_servers') if isinstance(config.get('mcp_servers'), dict) else {}
+ enabled_servers = enabled_mcp_server_names(config) if configured else set()
for name in explicit:
if not isinstance(name, str) or not known(name):
_refuse('toolsets', f'unknown or invalid toolset name: {name!r}')
+ server = name[4:] if name.startswith('mcp-') and name not in configured else name
+ if server in configured and server not in enabled_servers:
+ # Picking a disabled server must not match nothing and fall through to every enabled one.
+ _refuse('toolsets', f'MCP server {server!r} is disabled in config')
if 'desktop_ui' in explicit and source != 'gui':
_refuse('toolsets', f'desktop_ui is only available on the Desktop, not on {source}')
config.setdefault('platform_toolsets', {})['acp' if source == 'acp' else 'cli'] = explicit
diff --git a/hermes_cli/tools_config.py b/hermes_cli/tools_config.py
index 8b748fa4822..bdf7c7c805e 100644
--- a/hermes_cli/tools_config.py
+++ b/hermes_cli/tools_config.py
@@ -685,9 +685,10 @@ def _merge_mcp_servers(
"""Explicit passthrough entries plus this platform's MCP servers: listed names form an allowlist, else every
globally enabled server (when ``include_default_mcp_servers``); the ``no_mcp`` sentinel disables all."""
enabled_mcp_servers = enabled_mcp_server_names(config)
- # ``mcp-<server>`` names the same server as its bare alias: either spelling selects only that server.
- explicit_passthrough = {ts[4:] if ts.startswith("mcp-") and ts[4:] in enabled_mcp_servers else ts
- for ts in explicit_passthrough}
+ # ``mcp-<server>`` names the same server as its bare alias: either spelling selects only that server
+ # (unless a server is literally named ``mcp-<server>``).
+ explicit_passthrough = {ts[4:] if ts.startswith("mcp-") and ts not in enabled_mcp_servers
+ and ts[4:] in enabled_mcp_servers else ts for ts in explicit_passthrough}
result = explicit_passthrough - enabled_mcp_servers
if "no_mcp" in toolset_names:
return result - {"no_mcp"}
diff --git a/hermes_state_runtime.py b/hermes_state_runtime.py
index 55fccbf3c73..6940b70b068 100644
--- a/hermes_state_runtime.py
+++ b/hermes_state_runtime.py
@@ -20,11 +20,21 @@ class RuntimeStoreError(ValueError):
def __init__(self, reason: str, *, field: str | None = None, detail: str | None = None):
self.reason = reason
- self.field = field
- self.detail = detail
+ self.field = _one_line(field, 80)
+ self.detail = _one_line(detail, 160)
super().__init__(reason)
+def _one_line(value, limit):
+ """A refusal's ``field``/``detail`` as the log line and the client frame carry it: either may hold
+ client text, so whitespace collapses to single spaces, other non-printables drop (no forged log
+ lines), and the length is bounded below the client's frame limit."""
+ if value is None:
+ return None
+ text = ''.join(ch for ch in ' '.join(str(value).split()) if ch.isprintable())
+ return text[:limit] or None
+
+
def _text(value):
if not isinstance(value, str) or not value or len(value) > 1024:
raise RuntimeStoreError('invalid_params')
diff --git a/tests/gateway/test_session_policy_refusal_fields.py b/tests/gateway/test_session_policy_refusal_fields.py
index 9ec357fd642..8b631463b4d 100644
--- a/tests/gateway/test_session_policy_refusal_fields.py
+++ b/tests/gateway/test_session_policy_refusal_fields.py
@@ -50,6 +50,9 @@ def _refusal(params, cfg=None, **kwargs):
({'source': 'acp', 'editor': {'edit_approval_policy': 'always'}}, 'editor.edit_approval_policy'),
({'source': 'acp', 'editor': {'mcp_servers': 'terminal'}}, 'editor.mcp_servers'),
({'source': 'acp', 'editor': {'mcp_servers': [{'type': 'stdio'}]}}, 'editor.mcp_servers'),
+ ({'source': 'acp', 'editor': {'bad\nkey': 1}}, 'editor.bad key'), # client text: one line, no forged log line
+ ({'source': 'cli', 'toolsets': [None]}, 'toolsets'), # a literal None is the bad element
+ ({'source': 'cli', 'toolsets': [False]}, 'toolsets'),
])
def test_every_create_check_names_the_field_it_read(tmp_path, extra, field):
refusal = _refusal({'cwd': str(tmp_path), **extra})
@@ -199,3 +202,46 @@ def test_a_refusal_without_a_named_field_reads_exactly_as_before():
message = agent_init_failure_message(GatewayRPCError('storage_unavailable', 5001,
{'reason': 'storage_unavailable'}))
assert message.count('storage_unavailable') == 1 and '(' not in message
+
+
+def test_a_bypass_launch_without_a_model_names_the_model():
+ """`--ignore-user-config` has no profile to inherit a model from: the refusal says so."""
+ from gateway.session_local import _bypass_policy
+
+ with pytest.raises(RuntimeStoreError) as caught:
+ _bypass_policy({'source': 'cli'}, private_secrets=None)
+ assert (caught.value.field, caught.value.reason) == ('model', 'invalid_params')
+
+
[email protected]('name', ['deadserver', 'mcp-deadserver'])
+def test_an_explicit_pick_of_a_disabled_mcp_server_is_refused_by_name(tmp_path, name):
+ """A disabled server matched no allowlist entry and fell through to every enabled server; main
+ refused it (it never registers), and so does this, by name."""
+ servers = {'deadserver': {'command': str(tmp_path / 'absent'), 'enabled': False},
+ 'other': {'command': str(tmp_path / 'absent')}}
+ refusal = _refusal({'cwd': str(tmp_path), 'toolsets': ['terminal', name]}, {**_CFG, 'mcp_servers': servers})
+ assert refusal.field == 'toolsets' and "'deadserver' is disabled" in refusal.detail
+
+
+def test_a_server_literally_named_mcp_prefix_keeps_its_own_name(tmp_path):
+ servers = {'foo': {'command': str(tmp_path / 'absent')}, 'mcp-foo': {'command': str(tmp_path / 'absent')}}
+ policy = build_policy({'source': 'cli', 'cwd': str(tmp_path), 'toolsets': ['terminal', 'mcp-foo']},
+ {**_CFG, 'mcp_servers': servers})
+ assert 'mcp-foo' in policy.toolsets and 'foo' not in policy.toolsets, policy.toolsets
+
+
+def test_an_unusable_server_spec_never_echoes_its_values(tmp_path):
+ """pydantic's message carries ``input_value=``, and a server's argv may hold a credential."""
+ spec = {'type': 'stdio', 'name': 'x', 'command': 'srv', 'args': '--token=SECRETSECRET', 'env': []}
+ refusal = _refusal({'cwd': str(tmp_path), 'source': 'acp', 'editor': {'mcp_servers': [spec]}})
+ assert refusal.field == 'editor.mcp_servers' and 'args' in refusal.detail
+ assert 'SECRET' not in refusal.detail and '\n' not in refusal.detail
+
+
+def test_a_bypass_launch_never_reads_profile_plugin_state(tmp_path, monkeypatch):
+ def _profile_read(_config):
+ raise AssertionError('a bypass launch read the profile toolset resolver')
+ monkeypatch.setattr('hermes_cli.toolset_validation.saved_toolset_resolver', _profile_read)
+ policy = build_policy({'source': 'cli', 'cwd': str(tmp_path), 'ignore_user_config': True, 'model': 'fixture',
+ 'toolsets': ['terminal']}, dict(_CFG))
+ assert 'terminal' in policy.toolsets