MCP Apps Human Approval Nonces, Elicitation Limits & Silent Agent Auth/Refusal Traps
Why OAuth Bearer tokens cannot prove human-in-the-loop consent, undocumented MCP Apps iframe traps, cryptographic card nonces, and four silent agent runtime vulnerabilities.
- 01MCP OAuth/Bearer authentication only proves which user signed in—never whether the human or the LLM invoked
approve_paymentorapprove_email. - 02Stateless HTTP MCP servers cannot inspect client capabilities to know if a host renders MCP Apps (
ui://), and built-in card action runners let the chat model click approval cards unless all chat-callable actions are stripped. - 03True human-in-the-loop gates combine a short-lived CSPRNG/HMAC nonce rendered exclusively inside the visual MCP App iframe (never in tool JSON
content) with an out-of-band signed URL and blank-reasonrejection. - 04Production harnesses must explicitly defend against tokenless retry fallbacks, false
SUCCEEDEDexits on expired JWTs, attacker-initiated PKCE OAuth phishing, and refusal hints that trigger destructive workarounds.
1. Why MCP Tool Authentication Fails to Prove Human Approval (HITL)
The most pervasive security flaw in enterprise Model Context Protocol (MCP) deployments is conflating session principal authentication with physical human intent verification. An OAuth 2.1 or OIDC Bearer token proves only which human user authenticated the transport session—it provides zero cryptographic distinction between a tool call initiated by the human at the keyboard and an autonomous tool call synthesized by the LLM running inside that user’s session.
Whenever a two-phase mutation workflow exposes both stage_payment and approve_payment (or draft_email and approve_email) as standard MCP tools in tools/list, the LLM calls stage_payment in Turn 1, reads the returned draft_id from the JSON tool result, and autonomously invokes approve_payment({ draft_id }) in Turn 2 using the exact same user Bearer token. Because the server sees a valid finance-director JWT on both calls, RBAC passes cleanly while human oversight is completely bypassed.
- Ambient Authority Inside the Agent Loop: Because the agent harness inherits the signed-in user’s credentials, every autonomous LLM tool invocation carries the full authority of the human principal.
- Unverifiable Client Tool Prompts: Host-side "Allow tool execution?" dialogs are purely client-side UX preferences. Once a user clicks "Always allow for this server" or runs through an API harness, the MCP server receives identical JSON-RPC frames.
- Audit Trail Forgery via Optional
reasonFields: Leaving an approvalreasonparameter optional or acceptingreason: ""allows the model either to pass empty strings or to hallucinate plausible-sounding compliance justifications into your immutable audit log.
If every argument required to invoke approve_* (draft_id, confirm: true, reason) can be derived or synthesized by the LLM from prior tool outputs, you do not have a Human-in-the-Loop gate—you merely have a two-turn prompt speedbump.
2. Empirical Comparison: MCP Elicitation vs. MCP Apps vs. Out-of-Band Magic Links
Teams building human-in-the-loop write gates on MCP typically evaluate three mechanisms: MCP Elicitation (elicitation/create), MCP Apps (ui:// resources bound via _meta.ui.resourceUri), and out-of-band signed approval links. Empirical testing across desktop, CLI, mobile, and background harnesses reveals critical blind spots in relying on any single protocol primitive.
MCP Elicitation lacks universal local desktop client support across major MCP hosts and fails outright over headless, asynchronous, or stateless channels without persistent server-to-client RPC. MCP Apps delivers rich sandboxed UI cards inside chat, but introduces two undocumented production traps alongside strict iframe execution constraints:
- Trap A — Client Capability Blindness Over Stateless Streamable HTTP: On stateless Streamable HTTP transports, an MCP server handling
tools/callcannot reliably inspect or trust client capability negotiation state to know whether the calling host actually rendersMCP AppsUI cards. Rejecting non-card clients locks out CLI, mobile, and headless users; assuming the card rendered leaves text-only users stranded. - Trap B — Host UI Card Action Runners Letting the Model Click "Approve": Certain MCP hosts wire interactive card actions into built-in UI card action runners (
ui/messageor model-visible card action bindings). Unless all chat-callable actions are completely stripped from the approval card, the chat model itself can invoke the card’s approve action autonomously! - Sandboxed Iframe Operational Constraints:
MCP Appsiframes execute inside anopaque origin(nullorigin sandbox), possess no server-to-app push channel (status updates require clientpostMessagepolling only while the card stays mounted and open), and enforce no CPU or memory quotas against runaway iframe scripts.
| Evaluation Dimension | MCP Elicitation (elicitation/create) | Standalone MCP Apps Card (ui://) | Hybrid: Nonce-Bearing MCP App + Out-of-Band Signed Link |
|---|---|---|---|
| Desktop, CLI & Mobile Host Reach | Low; unsupported across several popular local desktop & CLI hosts | Partial; stateless HTTP server cannot verify whether host renders ui:// | Universal; visual card on desktop + signed URL fallback on CLI/mobile |
| Autonomous LLM Self-Approval Resistance | Moderate (relies entirely on host enforcing a blocking human modal) | Vulnerable unless all chat-callable card actions are stripped | Cryptographic; CSPRNG nonce excluded from tool JSON content |
| Async / Headless Workflow Compatibility | Fails; requires live bidirectional interactive session | Fails; no server-to-app push once card unmounts | Full; signed portal/Slack/email approval URL survives session disconnect |
| Runtime Isolation & Resource Governance | Host-rendered JSON Schema form | Opaque origin iframe; postMessage polling only; zero CPU/RAM quotas | Server-verified SSO principal + constant-time single-use HMAC + audit trail |
3. The Cryptographic One-Time Card Nonce & Blank-Reason Guard Pattern
To guarantee a human physically reviewed the staged mutation without locking out CLI or mobile users, combine visual-only one-time cryptographic nonces inside MCP Apps with an out-of-band signed approval URL.
When the LLM calls stage_supplier_payment, the server generates a short-lived (e.g., 5-minute TTL) CSPRNG human verification code bound via HMAC-SHA256 to (stage_id, caller_sub, canonical_payload_hash). Crucially, this nonce is never placed inside the MCP tool’s JSON content or structuredContent. It is rendered solely as read-only visual HTML inside the ui://approvals/{id} iframe (with zero chat-callable buttons/actions) alongside a signed out-of-band approval portal link.
Because the LLM cannot inspect the opaque origin iframe DOM, it cannot read the verification code. Either the human reads the code off the visual card and provides it—or clicks the out-of-band signed URL directly. Simultaneously, rejecting blank reason: "" strings on confirm_supplier_payment prevents silent boilerplate submissions and forces desktop hosts to prompt the human for an explicit audit justification.
import { randomBytes, createHmac, timingSafeEqual } from 'node:crypto';
interface StagedMutation {
stageId: string;
actorSub: string;
payloadHash: string;
nonceHmac: Buffer;
expiresAtMs: number;
consumed: boolean;
}
function issueHumanNonce(stageId: string, actorSub: string, payloadHash: string, secret: string) {
// 10-hex-char CSPRNG code shown ONLY inside visual UI / out-of-band portal
const humanCode = randomBytes(5).toString('hex').toUpperCase();
const nonceHmac = createHmac('sha256', secret)
.update(`${stageId}:${actorSub}:${payloadHash}:${humanCode}`)
.digest();
return { humanCode, nonceHmac };
}
// PHASE 1: Stage mutation — NEVER return humanCode in JSON content or structuredContent!
export async function stageSupplierPayment(args: { supplierId: string; amountUsd: number }, ctx: { sub: string }) {
const stageId = `stg_${randomBytes(8).toString('hex')}`;
const payloadHash = createHmac('sha256', 'domain-canonical')
.update(JSON.stringify({ supplierId: args.supplierId, amountUsd: args.amountUsd }))
.digest('hex');
const { humanCode, nonceHmac } = issueHumanNonce(stageId, ctx.sub, payloadHash, process.env.HITL_SECRET!);
await approvalStore.save({
stageId,
actorSub: ctx.sub,
payloadHash,
nonceHmac,
expiresAtMs: Date.now() + 5 * 60_000,
consumed: false,
});
// Strip ALL chat-callable actions from the MCP App HTML card; render purely visual summary + nonce
await uiResourceCache.put(`ui://approvals/${stageId}`, {
html: renderActionlessApprovalCardHtml({ stageId, amountUsd: args.amountUsd, humanCode }),
});
return {
content: [
{
type: 'text',
text: `Payment staged (${stageId}). Ask the user for the 10-character code shown on the approval card, or have them approve via the out-of-band link.`,
},
],
_meta: {
ui: { resourceUri: `ui://approvals/${stageId}` },
outOfBandApprovalUrl: `https://approve.internal.example/hitl/${stageId}`,
},
};
}
// PHASE 2: Confirm mutation — Reject blank reason: "" and verify single-use HMAC in constant time
export async function confirmSupplierPayment(
args: { stageId: string; humanVerificationCode: string; reason: string },
ctx: { sub: string },
) {
const cleanReason = (args.reason ?? '').trim();
if (cleanReason.length < 10) {
throw new Error('INVALID_AUDIT_REASON: Approval reason cannot be blank; provide an explicit human justification (>= 10 chars).');
}
const record: StagedMutation | null = await approvalStore.getForUpdate(args.stageId);
if (!record || record.consumed || Date.now() > record.expiresAtMs) {
throw new Error('APPROVAL_EXPIRED_OR_CONSUMED: Staged mutation expired or was already executed.');
}
if (record.actorSub !== ctx.sub) {
throw new Error('PRINCIPAL_MISMATCH: Approving principal must match staging principal or authorized delegate.');
}
const candidateHmac = createHmac('sha256', process.env.HITL_SECRET!)
.update(`${record.stageId}:${ctx.sub}:${record.payloadHash}:${args.humanVerificationCode.trim().toUpperCase()}`)
.digest();
if (candidateHmac.length !== record.nonceHmac.length || !timingSafeEqual(candidateHmac, record.nonceHmac)) {
throw new Error('INVALID_HUMAN_NONCE: Verification code mismatch.');
}
await approvalStore.markConsumed(record.stageId, { reason: cleanReason, verifiedAt: new Date().toISOString() });
return executeIdempotentErpPayment(record.stageId);
}4. Four Silent Production Auth & Refusal Vulnerabilities in Agent Runtimes
Real-world red-team audits of managed MCP agent runtimes show that catastrophic failures rarely break encryption—instead, they exploit subtle interactions between HTTP retry middleware, batch exit codes, OAuth redirect flows, and LLM goal-seeking behavior on refusal messages:
- 1. Tokenless Retry Fallback: Several managed agent runtimes and HTTP tool wrappers respond to a
401 Unauthorizedor403 Forbiddenon a Bearer-authenticated MCP request by automatically retrying the identical call without anAuthorizationheader. If your MCP server falls back to a demo, local-dev, or default anonymous workspace identity whenAuthorizationis omitted, the rejected call silently succeeds under the fallback identity! Defense: Strictly ban anonymous/default fallback principals on every authenticated endpoint—missingAuthorizationmust unconditionally return401. - 2. False
SUCCEEDEDBackground Runs on Mid-Job Auth Expiry: Whenmcp_authentication_failed_errorfires or a 1-hour OIDC JWT expires at minute 46 of an unattended intake job, the LLM reads the tool error, replies politely in prose ("I cannot access the server right now due to an authentication issue"), and terminates cleanly with exit code0. The workflow scheduler marks the runSUCCEEDED, silently dropping intake documents for 45+ minutes without paging anyone! Defense: Enforce deterministic harness post-condition gates that inspect tool-error telemetry, proactively refresh tokens before expiry, and force a non-zero exit code whenever authentication faults occur. - 3. Why PKCE Alone Fails Attacker-Initiated MCP OAuth Phishing: OAuth 2.1 PKCE (
code_challenge/code_verifier) proves only that the party redeeming the authorization code is the same party that started the OAuth flow. If an attacker initiates an MCP OAuth flow on their own client (owningcode_verifier) and sends the resulting authorization URL to a victim employee, PKCE passes cleanly once the victim approves! Defense: Enforce strict pre-registeredredirect_uriallowlists (banning unverified dynamic tunnels/callbacks), RFC 8707resourceindicators, and strict JWTaudvalidation. - 4. Refusal Hints Triggering Destructive Workarounds & Contact-Mutation Privilege Escalation: Returning helpful refusal hints such as "Cannot proceed while X is active; to proceed, first archive X" causes goal-directed agents to treat the error message as instructions and autonomously archive live records! Similarly, restricting outbound email tools to "verified entity contacts only" fails if the agent also holds
update_entity: the agent simply callsupdate_entityto overwrite or append an attacker/unverified address onto the entity first, then callssend_emailcleanly! Defense: Never include destructive prerequisite recipes inside refusal messages, and isolate master-data mutation (update_entity) from outbound action eligibility (send_email) across capability graphs.
Whenever an outbound or financial guardrail relies on mutable entity state (e.g., "only email verified contacts on the customer record"), mutating that entity inside an agent session must taint and suspend auto-execution eligibility until out-of-band human verification completes.
Frequently Asked Technical Questions
If every MCP request carries a per-user OAuth 2.1 Bearer token, why can the server not trust approve_payment calls?
Because OAuth 2.1 authenticates the session principal, not which actor inside the session triggered the JSON-RPC frame. The LLM shares the user’s Bearer token for every tool call in tools/list. Without a secret withheld from the LLM’s JSON context—such as a visual-only MCP App nonce or out-of-band signed URL—the model can call stage_payment and approve_payment back-to-back on its own.
Why not rely exclusively on MCP Elicitation (elicitation/create) for human approvals?
MCP Elicitation is not universally supported across local desktop, CLI, and mobile MCP clients, and it cannot function over stateless HTTP batch pipelines or asynchronous background runs where no interactive client socket is attached. Pairing actionless MCP Apps visual nonces with out-of-band signed approval links covers every client topology.
Why must all chat-callable actions be stripped from an MCP Apps approval card?
Hosts with built-in UI card action runners expose interactive card actions back to the chat model so the assistant can drive UI workflows. If an "Approve" button on the card remains callable through that bridge, the LLM can trigger the card action directly without waiting for a human click.
How do we stop unattended background agents from exiting 0 (SUCCEEDED) when MCP auth tokens expire mid-run?
Never derive batch job health from whether the LLM finished generating a final assistant message. Wrap the agent loop in a deterministic harness gate that tracks mcp_authentication_failed_error and HTTP 401/403 tool events, refreshes short-lived JWTs ahead of TTL expiry, and forces a non-zero process exit code if any unrecovered auth failure occurred.
Glossary Concepts Referenced in This Guide
UPDATE/INSERT statements on ERP/CRM databases, requiring typed action proposals validated against preconditions and approved by a named human role.Agent = Model + Harness) responsible for tool-calling loops, context compaction, retries, sandboxing, and execution traces.Free to reference in engineering docs, ADRs, articles, and course syllabi with attribution.
[MCP Apps Human Approval Nonces, Elicitation Limits & Silent Agent Auth/Refusal Traps — Ontoloji.org](https://ontoloji.org/en/guides/mcp-apps-human-approval-nonce-elicitation-and-refusal-traps)