Skip to content

The agent that grows with you

fix(mcp): keep trust-gate arguments redacted and legible on every approval surface

teknium184f6e1cd3244
diff --git a/tests/tools/test_mcp_tool_costs.py b/tests/tools/test_mcp_tool_costs.py
index 90fe09b153a..6ae2202a4ed 100644
--- a/tests/tools/test_mcp_tool_costs.py
+++ b/tests/tools/test_mcp_tool_costs.py
@@ -113,6 +113,24 @@ def test_full_trust_asks_only_past_the_limit_and_unattended_refuses_without_disp
assert "used about 140 credits" in result["error"] and session.call_tool.await_count == dispatched
+def test_over_limit_notice_leads_the_untrusted_prompt_and_the_arguments_follow(session):
+ """The gateway's plain-text fallback keeps only the first 200 characters of the prompt, so the
+ spend-limit notice and cost must sit ahead of the call's arguments."""
+ _register(dict(COSTED, spend_limit=30, trust="untrusted"))
+ asked = []
+ token = set_current_session_key("chat-a")
+ try:
+ with patch("tools.approval_prompt.request_elicitation_consent",
+ side_effect=lambda msg, desc, **kw: asked.append(msg) or "decline"):
+ handlers._make_tool_handler("srv", "paid_render", 30.0)({"scene": "castle", "notes": "y" * 3_000})
+ finally:
+ reset_current_session_key(token)
+ head = asked[0][:200]
+ assert "goes past the chat's spend limit" in head and "Costs about 40 credits." in head
+ assert '"scene": "castle"' in asked[0][200:]
+ assert session.call_tool.await_count == 0
+
+
def test_chats_and_profiles_never_share_a_tally(session):
_register(COSTED)
for _ in range(2):
diff --git a/tests/tools/test_mcp_trust_gating.py b/tests/tools/test_mcp_trust_gating.py
index ec82cf2d313..ef724b824a9 100644
--- a/tests/tools/test_mcp_trust_gating.py
+++ b/tests/tools/test_mcp_trust_gating.py
@@ -106,13 +106,19 @@ class TestTrustGateAtCallTime:
assert json.loads(raw) == {"result": "ok"}
fake_session.call_tool.assert_awaited_once()
- def test_approval_card_shows_redacted_bounded_arguments(self, fake_session):
- """The approver sees the exact call payload without exposed secrets."""
+ def test_approval_card_shows_redacted_bounded_arguments(self, fake_session, monkeypatch):
+ """The approver sees the call's arguments, never its secrets (even with redaction turned off
+ for logs), and the card stays inside the smallest messaging cap."""
+ import agent.redact
+ monkeypatch.setattr(agent.redact, "_REDACT_ENABLED", False)
_set_trust("srv", "untrusted")
handler = _mcp_handlers._make_tool_handler("srv", "trigger_build", 30.0)
args = {
"job": "release",
"api_key": "sk-supersecretcredential123456",
+ "db_password": "hunter2-correct-horse-battery",
+ "headers": {"Authorization": "Bearer eyJhbGciOiJIUzI1NiJ9.cGF5bG9hZA.c2lnbmF0dXJl"},
+ "target": "prod\u202e",
"notes": "x" * 5_000,
}
@@ -123,13 +129,15 @@ class TestTrustGateAtCallTime:
handler(args)
message = consent.call_args.args[0]
- assert "```json" in message
assert '"job": "release"' in message
- assert "sk-supersecretcredential123456" not in message
+ for secret in ("sk-supersecretcredential123456", "hunter2-correct-horse-battery",
+ "eyJhbGciOiJIUzI1NiJ9.cGF5bG9hZA.c2lnbmF0dXJl", "\u202e"):
+ assert secret not in message
assert "truncated" in message
- assert len(message) < 3_000
+ assert len(message) < 2_000
fake_session.call_tool.assert_not_awaited()
+
def test_denied_approval_blocks_rpc(self, fake_session):
"""'decline' blocks the call — the RPC must never fire."""
_set_trust("srv", "untrusted")
diff --git a/tools/mcp_tool_handlers.py b/tools/mcp_tool_handlers.py
index 15f16da394f..184ef421d26 100644
--- a/tools/mcp_tool_handlers.py
+++ b/tools/mcp_tool_handlers.py
@@ -73,25 +73,41 @@ def _trust_granted(server_name: str, tool_name: str) -> bool:
_trust_approval_key(server_name, tool_name))
-_TRUST_GATE_ARGUMENTS_MAX_CHARS = 2_048
+# Keeps the whole trust-gate card inside Discord's 2,000-character message cap (the tightest button
+# surface), so the truncation marker is never cut off by the adapter's own fit.
+_TRUST_GATE_ARGUMENTS_MAX_CHARS = 1_200
_TRUST_GATE_ARGUMENTS_TRUNCATION_MARKER = "\n... [arguments truncated]"
+def _mask_secret_fields(value: Any) -> Any:
+ """Mask string values under credential-named fields (``db_password``, ``client_secret``): the text
+ redactor below only catches the field names and token shapes it knows."""
+ from agent.redact import is_secret_field_name
+ if isinstance(value, dict):
+ return {k: "***" if isinstance(v, str) and v and is_secret_field_name(k) else _mask_secret_fields(v)
+ for k, v in value.items()}
+ if isinstance(value, list):
+ return [_mask_secret_fields(v) for v in value]
+ return value
+
+
def _format_trust_gate_arguments(args: dict) -> str:
- """Return redacted, bounded JSON for the user-facing approval card."""
+ """Redacted, bounded JSON of the call's arguments for the approval card. Plain text, no
+ fence: every surface already renders the prompt inside a code block."""
+ import unicodedata
from agent.redact import redact_sensitive_text
- rendered = json.dumps(args, ensure_ascii=False, indent=2, default=str)
- rendered = redact_sensitive_text(rendered)
+ rendered = json.dumps(_mask_secret_fields(args), ensure_ascii=False, indent=2, default=str)
+ # Bidi overrides, invisible format characters and the C1/DEL controls JSON leaves raw could make the
+ # card show something other than what the server receives; render them as escapes.
+ rendered = "".join(ch.encode("unicode_escape").decode()
+ if ch != "\n" and unicodedata.category(ch) in ("Cc", "Cf") else ch for ch in rendered)
+ # force: the approval prompt is a display boundary even with security.redact_secrets off. The CLI
+ # prints it as-is. Redact before truncating so a cut cannot split a secret past its pattern.
+ rendered = redact_sensitive_text(rendered, force=True)
if len(rendered) > _TRUST_GATE_ARGUMENTS_MAX_CHARS:
- prefix_length = (
- _TRUST_GATE_ARGUMENTS_MAX_CHARS
- - len(_TRUST_GATE_ARGUMENTS_TRUNCATION_MARKER)
- )
- rendered = (
- rendered[:prefix_length].rstrip()
- + _TRUST_GATE_ARGUMENTS_TRUNCATION_MARKER
- )
+ keep = _TRUST_GATE_ARGUMENTS_MAX_CHARS - len(_TRUST_GATE_ARGUMENTS_TRUNCATION_MARKER)
+ rendered = rendered[:keep].rstrip() + _TRUST_GATE_ARGUMENTS_TRUNCATION_MARKER
return rendered
@@ -143,8 +159,8 @@ def _ask_for_call(server_name: str, tool_name: str, charge, booked: Optional[lis
tail = "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])
- display_args = _format_trust_gate_arguments(args or {})
- message += f"\n\nArguments:\n```json\n{display_args}\n```"
+ if args: # after the notice and cost lines, which must stay in the text fallback's first ~200 characters
+ message += f"\n\nArguments:\n{_format_trust_gate_arguments(args)}"
# 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)