The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(mcp): trust-gate Session/Always answers now stick per (server, tool)
liuhao1024ce11b6be1af2
diff --git a/tools/approval_prompt.py b/tools/approval_prompt.pyindex ac759553022..ca23aa8340f 100644--- a/tools/approval_prompt.py+++ b/tools/approval_prompt.py@@ -284,15 +284,29 @@ def _consent(choice, unresolved: str) -> str:return unresolved if choice in ("timeout", "cancelled") else "decline"+def _remembered_consent(session_key: str, choice, remember_key: str | None, unresolved: str) -> str:+ """:func:`_consent`, recording a ``session``/``always`` answer under *remember_key*. Without a key+ those scopes were never offered, so a stale or typed broader answer covers this call only."""+ if remember_key is not None:+ from tools import approval as _a+ _a._persist_choice(session_key, choice, [remember_key])+ return _consent(choice, unresolved)++def request_elicitation_consent(message: str, description: str, *,timeout_seconds: int | None = None,- surface: str = "mcp-elicitation", title: str = "Confirm this action?") -> str:+ surface: str = "mcp-elicitation", title: str = "Confirm this action?",+ remember_key: str | None = None) -> str:"""Route an MCP elicitation request to the surface owning the active session:gateway sessions through ``_await_gateway_decision``, CLI/TUI through``prompt_dangerous_approval``. Always fails closed: a missing notify_cb in agateway session, timeouts, and exceptions map to ``"decline"`` so a servertreats them as "user did not approve" rather than retrying or hanging.- Returns ``"accept" | "decline" | "cancel"``."""+ Returns ``"accept" | "decline" | "cancel"``.++ Without *remember_key* the consent covers one call, so every surface offers only+ once/deny. With it, the session and always choices are offered and recorded under+ that approval key; the caller checks ``tools.approval.is_approved`` before asking."""from tools import approval as _atry:session_key = _ctx.get_current_session_key()@@ -303,6 +317,7 @@ def request_elicitation_consent(message: str, description: str, *,# would detach the viewer mid-turn instead of failing closed like the in-process ``-q`` input() path.if _ctx._is_single_query_approval_context():return "decline"+ scoped = remember_key is not None# api_server is an unattended *platform* for the dangerous-command gate, but a live ``/v1/runs`` run# registers an approval notify callback and answers via ``POST /v1/runs/{id}/approval``@@ -323,7 +338,8 @@ def request_elicitation_consent(message: str, description: str, *,decision = _gw._await_gateway_decision(session_key, notify_cb, {"command": message, "description": description,"pattern_key": "mcp_elicitation",- "pattern_keys": ["mcp_elicitation"]}, surface=surface)+ "pattern_keys": ["mcp_elicitation"],+ "allow_session": scoped, "allow_permanent": scoped}, surface=surface)except Exception as exc:logger.error("Elicitation gateway dispatch failed: %s", exc, exc_info=True)return "decline"@@ -331,7 +347,7 @@ def request_elicitation_consent(message: str, description: str, *,return "decline"if not decision.get("resolved") or decision.get("cancelled"):return "cancel" # nobody answered (timeout / prompt withdrawn) — not a user refusal- return _consent(decision.get("choice"), "decline")+ return _remembered_consent(session_key, decision.get("choice"), remember_key, "decline")# Nobody can answer a -q, cron or unattended-platform worker. A `hermes chat -q` turn still has the CLI's# panel callback registered, which would wait the full approval timeout before failing closed.@@ -347,10 +363,9 @@ def request_elicitation_consent(message: str, description: str, *,hook_choice = "cancelled"try:from tools.terminal_tool import _get_approval_callback- # allow_permanent=False: elicitation is a per-call confirmation — no pattern to remember.# Pass the agent thread's panel callback: without it prompt_toolkit fails the prompt closed unseen.choice = prompt_dangerous_approval(message, description, timeout_seconds=timeout_seconds,- allow_permanent=False, title=title,+ allow_permanent=scoped, allow_session=scoped, title=title,approval_callback=_get_approval_callback())hook_choice = choiceexcept Exception as exc:@@ -358,4 +373,4 @@ def request_elicitation_consent(message: str, description: str, *,return "decline"finally:_ctx._fire_approval_hook("post_approval_response", **hook_kwargs, choice=hook_choice)- return _consent(choice, "cancel") # timeout mirrors the gateway's unresolved outcome+ return _remembered_consent(session_key, choice, remember_key, "cancel") # timeout mirrors the gatewaydiff --git a/tools/mcp_tool_handlers.py b/tools/mcp_tool_handlers.pyindex b93fb3b03ea..dbec9f313e1 100644--- a/tools/mcp_tool_handlers.py+++ b/tools/mcp_tool_handlers.py@@ -57,6 +57,19 @@ def _tool_is_read_only(server_name: str, tool_name: str) -> bool:return _core._tool_read_only_hints.get(_resolve_server_key(server_name), {}).get(tool_name) is True+def _trust_approval_key(server_name: str, tool_name: str) -> str:+ """Approval key a session/always answer to the trust gate is kept under: one (server, tool) pair,+ so allowing one write tool never covers the server's others. Session entries are per chat;+ always entries land in the active profile's ``command_allowlist``."""+ return f"mcp:{server_name}/{tool_name}"+++def _trust_granted(server_name: str, tool_name: str) -> bool:+ from tools.approval import is_approved+ from tools.approval_context import get_current_session_key+ return is_approved(get_current_session_key(), _trust_approval_key(server_name, tool_name))++def _trust_gate_check(server_name: str, tool_name: str, booked: Optional[list] = None) -> Optional[str]:"""Approval gate for write-capable tools on ``trust: untrusted`` servers, plus the declared spendlimit on any server. None to proceed, else a ``tool_error``. Fail-closed: approval-system errors@@ -67,7 +80,8 @@ def _trust_gate_check(server_name: str, tool_name: str, booked: Optional[list] =# Trust and costs are the calling profile's own policy (an adopter of a shared connection keeps its own).key = _server_key(server_name)trust = _core._server_trust_levels.get(key, _core._TRUST_FULL)- gated = trust == _core._TRUST_UNTRUSTED and not _tool_is_read_only(server_name, tool_name)+ gated = (trust == _core._TRUST_UNTRUSTED and not _tool_is_read_only(server_name, tool_name)+ and not _trust_granted(server_name, tool_name))charge = Noneif key in _core._server_cost_policies: # no table: not even a session lookup, main's path byte for bytefrom tools.approval_context import get_current_session_key@@ -103,8 +117,12 @@ def _ask_for_call(server_name: str, tool_name: str, charge, booked: Optional[listail = "This tool is write-capable (no readOnlyHint=true annotation) and may modify external state."# The limit notice leads: the messaging gateway's text fallback keeps only the first ~200 characters.message = " ".join([head, *(["This call goes past the chat's spend limit."] if over else []), *extra, tail])+ # Over the limit the answer covers this call only: a remembered trust grant must not+ # pre-approve the next over-limit call.+ remember_key = None if over else _trust_approval_key(server_name, tool_name)+ scope = "once" if over else "once, for this session, or always"description = (f"Server '{server_name}' is configured 'trust: untrusted'. "- f"Approve to run '{tool_name}' once, or deny to block it.")+ f"Approve to run '{tool_name}' {scope}, or deny to block it.")title = f"MCP server '{server_name}' is asking"else:message = " ".join([f"MCP tool '{tool_name}' on server '{server_name}' would take this chat past its "@@ -112,9 +130,11 @@ def _ask_for_call(server_name: str, tool_name: str, charge, booked: Optional[lisdescription = (f"Server '{server_name}' declares a spend limit per chat. Approve to run '{tool_name}' "f"once (every further paid call in this chat asks again), or deny to block it.")title = f"MCP server '{server_name}' spend limit"+ remember_key = Nonetry: # lazy: tools.approval routes the prompt to whichever surface owns the sessionfrom tools.approval_prompt import request_elicitation_consent- answer = request_elicitation_consent(message, description, surface=f"mcp-trust/{server_name}", title=title)+ answer = request_elicitation_consent(message, description, surface=f"mcp-trust/{server_name}", title=title,+ remember_key=remember_key)except Exception as exc:logger.error("MCP trust gate: approval check failed for %s.%s: %s", server_name, tool_name, exc, exc_info=True)if over and charge is not None: