Skip to content
Forward Deployed

Forward Deployed

Tool-Using Agent with Safety Controls

Give an agent useful tools while controlling identity, approvals, effects, budgets and recovery outside the model.

Kind
Case study
Level
Core
Sections
5
By
Sourav Banerjee
Last updated
20 Nov 2026

Practise this as a worksheet: Tool-Using Agent with Safety Controls

Report an issue

Case brief

Understand the scenario, task, and constraints.

Let an agent prepare work without granting it authority

An operations team wants an agent to read customer email, query internal systems, update customer relationship management (CRM) records and sometimes issue refunds. Everyone agrees on that feature list and then disagrees about everything else. Operations wants speed. Security wants hard approval gates. The support manager wants routine cases handled without friction. Finance fears money that moves and cannot come back. That disagreement is the design problem.

The useful part of the agent is interpreting a messy request. The dangerous part is letting that interpretation become authority. A customer email is input to interpret, and it may also carry instructions written to manipulate the agent. Tool output is the same: a CRM row or a fetched page can contain hostile text. One injected sentence must never turn into a refund.

So the model proposes one bounded next action, meaning a single small step with stated limits, never "do everything". Deterministic services, which give the same answer for the same input and do not depend on the model's judgement, then take over. A validator checks the tool and its arguments. A policy service answers allow, block or needs a human. A credential broker issues a short-lived token that covers only that action. An idempotent gateway, a write path that turns repeated calls for the same action into one effect, runs it once and writes a receipt. Neither an email nor the model's confidence can authorise a refund.

The planner proposes one step; validation and a policy decision follow; the gateway executes once, a human approves, or the system stops and records, source figure 1.Dark variant: The planner proposes one step; validation and a policy decision follow; the gateway executes once, a human approves, or the system stops and records, source figure 1.
The core loop: the planner proposes one step, the tool and arguments are validated, and the policy decision sends it to the gateway, to a human approver, or to stop-and-record. Source figure 1. Open for full size.

The figure is the whole case in miniature. Every later section adds detail to one of its boxes, and none of them lets the planner skip a box. Writes fail closed, meaning that when a control cannot answer, the write does not happen. Operators can stop work already in flight by revoking tokens and cancelling queues.

Five groups of people meet in this system. The business user delegates inbox and case work. An approver reviews the exact risky payload. Security defines identity, authorisation and audit rules. Each tool and data owner defines supported operations, limits and the revert procedure. Operators monitor, reconcile uncertain actions and stop workflows. Step 1 maps what each of them notices first when the agent fails.

The first release excludes free-form code or shell execution, open-ended tool discovery, unbounded loops, cross-tenant access, self-modifying policy and unrestricted refunds. The case assumes you are comfortable with large language model (LLM) agents and tool calling, authentication and scoped tokens, idempotent APIs and basic cloud architecture.

This is the anchor case for agents that act. Several related prompts keep the same proposal-to-execution boundary and change which control dominates. The table shows where each one lands in this casebook.

Related cases that reuse this boundary, what changes, and where this casebook covers the change.

Related caseWhat changes from this caseWhere it is covered
Enterprise AI assistant over 100+ internal applicationsTool discovery and registry loading at scale; enterprise identity must reach every applicationIntegrating hundreds of applications
Enterprise workflow automation (OpenAI-style practice prompt) and the reported Salesforce prompt on loop, tool interfaces, memory, orchestration and safetyMore orchestration and memory detail, with the same proposal-to-execution boundaryIntegrations and the fifty-minute rehearsal
Slow, looping or timed-out agent, and the "slow and expensive" self-drillStep budgets, cached safe reads, async work, per-tool timeouts and explicit stop conditions dominateDiagnose a slow or looping agent
Incident: refund tool called above the approval thresholdSeparate planner failure from gateway enforcement success; contain risky bulk plansInvestigate the refund near miss

This is an interview design and operating model, not an implemented agent backend. All workload numbers, thresholds and incident records come from the source case and are planning assumptions. Work through the proposal-to-receipt sequence first; the larger tool catalog and wider autonomy only make sense once that boundary holds.

Next: build the answer in interview order.

Start the walkthrough

Design walkthrough

Follow the reasoning from discovery to delivery.

1. Define an autonomy matrix for actions

Open with the disagreement rather than the feature list, and restate the ask as an outcome someone can test: enable useful automation while deterministic controls govern identity, permissions, risk and irreversible effects. A spoken version of that opening, from the source:

"We want an agent that reads email, checks internal systems, updates CRM, and sometimes issues refunds. The useful part is interpreting the request; the dangerous part is letting that interpretation become authority. I'll let the model propose actions, while identity, policy, approval, and an idempotent gateway decide what can actually happen."

Then ask the questions that change what may be built, not the ones that merely sound thorough. Ask which actions are reversible, where money and permission boundaries sit, and whether the agent acts as a user, a service account or a delegated actor. Record what may run, what needs review and what is forbidden. Autonomy differs by action class. A public FAQ lookup and a payment cannot share one enable switch.

The table lists the seven questions that change the controls. Each row pairs the formal question with the plain-language worry behind it and the decision the answer drives.

Discovery questions that determine delegation, approval, authority and incident response.

Question to ask What it's really asking What you then decide
Which actions are reversible, and where is the money or permission boundary? If the agent refunds the wrong person, can we undo it, and at what amount does a human have to say yes? Which steps auto-run, which wait for a person, and which never run. Do not invent a refund threshold.
Does the agent act as the user, a service account, or a delegated actor? If a bad email tricks the agent, whose account takes the damage: the user's, a shared robot, or a narrow "this ticket only" role? How wide the token is, and how much one injected instruction can change.
What can run autonomously, what needs approval, and what is forbidden? Can it write a CRM note on its own, must a manager approve a refund, and is "change payment details" never allowed? The allow / ask a human / never-do-this list, and how far v1 may go.
Which systems own customer, identity, and refund truth? If the agent's todo list says "refunded" but billing says "not refunded," which one do we trust? Read live from CRM, identity, and refund systems. Task state is progress, not money.
What must be logged and retained for an audit or dispute? If a customer later disputes a refund, can you prove exactly what happened, and how long do you keep that proof? Ledger fields (who, proposal, policy, approval, receipt) and how long they are kept.
How can operators stop an in-flight task? If a bad refund loop is already running, how do we stop work already started, not only the next chat? Kill switch must halt new tool calls, cancel queued work, and revoke tokens.
What workload and business outcome matter? How busy is peak, and are we optimising for faster handling or fewer wrong refunds? Planner/tool size, how many approvers you need, and how much autonomy you ship.

Is email untrusted? It is not on the list because the answer is always yes. A message may carry instructions to override policy, exfiltrate data or trigger a tool, and tool output carries the same risk, so the design assumes it rather than asking.

The answers decide more than thresholds. Reversibility and the money boundary decide whether you are building a control system with payment and escalation rules or an assistant with a few tools. The identity question sets blast radius, the amount of damage one mistake can reach: full-record access widens it, while access limited to the fields of one case contains what an injected instruction can change. Audit and retention are design inputs that shape the ledger schema, not something added after launch. The kill-switch question tells the interviewer you expect the system to be stoppable before it is perfect. Finally, whether success means fewer handling minutes, a higher resolution rate, a lower error rate or better satisfaction decides which metric the business inspects, and that metric sets how much autonomy is worth the risk.

Map the people next, because each one defines success differently and notices a different failure first.

Stakeholders, the failure each notices first, what the agent gives them and where approval sits.

UserWorkflowFailure they notice firstWhat the agent gives themApproval needed
Business userDelegates inbox and case work, wants less manual handlingThe agent stalls or does the wrong thing to a customerTriage, drafts, prepared refund cases, closed loops on low-risk casesNone for reads and drafts
ApproverDecides when a risky action is allowedA refund executed without them, or a queue that never drainsAn approval record with reviewer, timestamp, rationale and the exact payloadThey are the approval
Security ownerDefines identity, authorisation and audit rulesA long-lived credential in a prompt, or a tool called on an injected instructionScoped tokens, a policy gate outside the model, a tamper-evident ledgerSigns off on each tool class
Tool and data ownerOwns email, CRM, customer DB, refund serviceTheir system called in unsupported ways, or duplicated writesA declared schema per tool, idempotency keys, per-tool concurrency limitsOwns the revert procedure
OperatorMonitors, retries, escalatesNo way to stop it, no way to explain a decisionKill switch, runbook, replayable decision recordRuns containment

When the interviewer withholds answers, state assumptions ranked by risk. With no approval process defined, assume a conservative human gate on every irreversible action. With retention unspecified, store enough to reconstruct any action and leave the exact period to the customer's dispute and privacy policy. With tenancy unclear, assume strict isolation and a separate authorisation check at every tool boundary. The source's working defaults are that the CRM is the source of truth for customer context, refunds above a threshold require approval, and the agent may draft actions but cannot execute high-risk steps unless the policy engine allows it. Do not invent a permissive refund limit to complete the diagram.

The source grades answers in three tiers, and the difference between them is where authority sits. The weak answer connects the agent to email and CRM and lets it refund when it decides the customer deserves one. The model is the authority, it holds credentials rather than scoped capabilities, and nothing stops an instruction hidden in a ticket. The average answer plans tool calls, checks permissions before each one, requires approval for large refunds, logs everything and adds retries. It still trusts tool output, never bounds loops or spend, and retries without idempotency, which is how one refund quietly becomes two. The strong answer has the planner propose one bounded action, a typed schema validate it, a policy engine return allow, block or needs-approval, a broker mint a token for that single action and an idempotent gateway guarantee one effect. Tool observations are data, and loops, spend, refund amounts and destinations all have hard ceilings.

2. Make safety and performance testable

A requirement the customer cannot test is a preference. "It should be safe" is a preference. "No arbitrary command execution" is a constraint, and only the constraint changes the architecture. Separate three kinds of statement: what the system must do (functional), how safely and how well it must do it (non-functional), and what it must never do (non-goals).

Interviewers often ask for the six functional must-haves cold, and they work as a set:

  1. Separate planning from execution. The model proposes; a separate control layer decides whether any tool call may run.
  2. Validate tool name, arguments, identity and policy against an allowlist, a parameter schema, the caller's identity and the policy rules before anything runs.
  3. Use scoped, short-lived credentials. The agent never holds a broad secret and receives only the minimum for the next approved step.
  4. Require approval for high-risk actions. Refunds, account changes and any irreversible external write cross a human boundary unless the customer accepts a narrower automated threshold.
  5. Make effects idempotent and auditable, so a retry cannot double-refund and every decision leaves a replayable trace.
  6. Stop safely under uncertainty. Poor confidence, a malformed tool response, unclear policy or an inconsistent environment means pause, escalate or fail closed, never improvise.

Three should-haves complete the first usable version: a declared registry with schema and data class for every tool, so an undeclared tool cannot be called; a kill switch that halts autonomous paths without a deploy, tested before launch; and approval captured as a first-class record. The could-haves wait: richer policy expression, adaptive risk scoring, queued multi-step orchestration, replay tooling, operator dashboards, anomaly detection on action patterns and per-tenant policy overlays.

Declare the non-goals out loud, because strong candidates draw a narrower boundary than the prompt suggests: free-form code execution or shell access, open-ended tool discovery, unbounded autonomous loops, automatic refunds without approval thresholds, cross-tenant data access and self-modifying policy logic.

The constraints below are each written so that a test can fail them. The numbers are illustrative interview figures, not measured production demand.

Source example constraints for capacity, latency, security, reliability and operability.

Constraint Stated so it can be tested
Latency Model-planning time budgeted separately from tool time; p95 completion under about 15 seconds for low-risk tasks; approval queue time bounded by an escalation rule, for example 99.5% of approval requests leave the queue within 2 minutes
Availability At 50,000 users and 20 QPS peak, 10 actions per task means roughly 200 tool actions per second. Reads parallelise; writes and approvals do not. Concurrency capped per user, per tool and globally
Cost Hard ceilings on tool calls per task, per-task spend, refund amount and allowable destinations. These are guardrails, not tuning knobs
Security Short-lived, narrowly scoped credentials minted per workflow; the model never holds a reusable API key or admin token. No arbitrary command execution. Tool observations are untrusted input
Audit and compliance A tamper-evident ledger records intent, policy decision, approval and outcome for every action. Every decision is replayable from versioned prompts, policies, proposals and outcomes
Reliability Writes fail closed when the credential broker or policy engine is unavailable; only the lowest-risk reads degrade. A write is never retried without proven idempotency
Operability A rapid global disable for the agent, a tool category, or both, without a deployment cycle

Each requirement has an explicit control point and owning component.

Requirement Control point Component
Separate planning from execution Plan/execute boundary Orchestrator that emits candidate actions but cannot perform them
Validate tool name, arguments, identity, policy Policy gate Authorisation service with schema validation and allowlists
Use scoped short-lived credentials Secret broker Token minting layer with time-limited, least-privilege credentials
Require approval for high-risk actions Human approval flow Review queue with explicit accept/reject and reason capture
Idempotent, auditable effects Action ledger Durable event log and idempotency keys
Stop safely under uncertainty Fail-closed controller Error handler that pauses execution and alerts operators
No arbitrary command execution Execution sandbox Restricted tool adapters only, no shell escape
Bounded autonomous steps and spend Budget governor Step counter, retry cap, spend threshold
Replayable decisions Decision record Versioned prompts, policies, tool proposals, outcomes
Rapid global disable Kill switch Central feature flag or routing gate that stops all agent actions

Two latency details are easy to lose. Planner time and tool time get separate budgets, because a slow model and a slow downstream API need different fixes. The p95 target, the duration that 95% of low-risk tasks finish within, is about fifteen seconds. Human approval has its own rule: the example requires 99.5% of approval requests to leave the queue within two minutes, by decision or escalation. These are service objectives to measure, not proof that human review always finishes in that time. The capacity row is worked through in step 7.

The traceability table above is the proof that every requirement has an owner. If a row has no component, the requirement is a hope. If you are asked "What are the requirements?" in an interview, the source's short version is:

"Functionally, the model proposes one bounded action; policy, approval, a scoped token, and an idempotent gateway decide and execute. Non-functionally, fail closed on writes, bound loops and spend, keep a ledger, and keep a kill switch."

3. Draw the nine components and their boundaries

The LLM is the agent's planner, not its executor. It reads task state and tool results, proposes one bounded action, and can continue only after the policy, approval, gateway and receipt path completes. The whiteboard version of the architecture has seven steps:

  1. Establish delegation. Authenticate the user and determine which actions the user may delegate.
  2. Plan one bounded step. The planner reads task state and proposes one next action within its step and cost budgets.
  3. Validate the tool call. Resolve the tool's typed schema and check arguments, data class and action limits.
  4. Apply policy. Block and record a disallowed action, allow a safe one, or request human approval for the exact payload before it expires.
  5. Grant narrow authority. For an allowed or approved action, the broker issues a short-lived scoped token. Budgets and the kill switch still apply.
  6. Execute once through the gateway. The idempotent gateway calls the target system and prevents a retry from becoming a second side effect.
  7. Close the loop. Store the action receipt in the audit ledger and task state, and continue planning only from the recorded result.
Whiteboard architecture: delegating user, authenticate and authorise, LLM planner with task state, tool registry and typed schema, validation, policy decision, stop and record, approval bound to payload and expiry, scoped token, idempotent gateway, systems of record, receipt and audit ledger, kill switch and budgets, source figure 2.Dark variant: Whiteboard architecture from delegating user through planner, validation, policy, approval, scoped token, idempotent gateway and audit ledger, source figure 2.
The whiteboard architecture: the seven steps above, with task state beside the planner, the stop-and-record exit from policy, and the kill switch and budgets applying across the path. Source figure 2. Open for full size.

Say each boundary as you draw it. The planner can propose. The registry defines legal tool shapes. Validation rejects malformed or over-limit arguments. Policy decides. Approval binds to the exact state. The broker supplies one narrow capability. The gateway is the only write path. A proposal is not proof of execution; the receipt is.

The full design reads the same system as nine components in dependency order, which is the order they have to exist and also the order they fail. The table gives each one's job, the trust boundary it guards and what happens when it is unavailable.

Nine component responsibilities, trust boundaries and failure behaviour.

Component Responsibility Trust boundary Fails how
Agent planner Propose the next bounded action, never execute Model to control plane Degrades: pauses and escalates on low confidence
Task state store Track workflow progress and intermediate results Durable workflow state, not business truth Closed for writes: no state, no continuation
Tool registry Declare allowed tools, schemas, data class, risk label Approved tool catalog Closed: undeclared tool cannot be called
Policy decision point Return allow, block or needs-approval with scopes and a reason Authorisation and risk gate Closed: unavailable means no writes
Credential broker Mint one scoped, short-lived token per approved action Identity and secret boundary Closed for writes; reads degrade only where policy allows a cached path
Approval service Capture human sign-off bound to a snapshot with expiry Human-in-the-loop control Closed: expired approval means re-request
Idempotent execution gateway Exactly one side effect per proposal, replay returns the receipt Execution safety boundary Reconciles: uncertain writes go to a reconciliation state, never blind retry
Audit ledger Intent, decision, approval, outcome, tamper-evident Immutable trace layer Closed: incomplete evidence means stop and escalate
Kill switch Halt autonomous paths without a deploy Operational safety boundary Tested before launch; it is the last layer

The organising split in the full diagram is control plane against data plane. The control plane decides what the agent is allowed to do, under what conditions and with which approvals. The data plane performs the bounded business work once those decisions are made. The model sits entirely inside the control plane's proposal step and never touches the data plane directly. The source draws the decision half and the execution half separately, then the two planes together.

Decision half: user, authentication and delegated authorisation, planner proposes one bounded action, declared tool registry, validate schema before policy, policy decision with block, approval-needed and allow branches, approval bound to snapshot and expiry, credential broker, token for one tenant, workflow, action and expiry, source figure 3.Dark variant: Decision half from user authentication to a credential broker token for one tenant, workflow, action and expiry, source figure 3.
The decision half. Validation runs before policy; the policy decision blocks with a reason, asks for approval bound to a snapshot and expiry, or allows with scopes; only an allowed or approved-and-revalidated action reaches the broker. Source figure 3. Open for full size.
Execution half: scoped token and idempotency key, idempotent execution gateway, CRM, email, refund service and internal data, receipt and side effects, tamper-evident audit ledger; a replay of the same proposal returns the existing receipt, source figure 4.Dark variant: Execution half, where a replay of the same proposal returns the existing receipt, source figure 4.
The execution half. The gateway uses the scoped token and idempotency key, writes the receipt to the tamper-evident ledger, and answers a replay of the same proposal with the existing receipt instead of a second call. Source figure 4. Open for full size.
Control plane containing delegating user, authN/authZ edge, audit ledger request record, agent planner, task state store, tool registry, policy decision point, approval service, kill switch and credential broker; data plane containing the idempotent execution gateway, CRM, email, refund and internal data systems of record and the execution-outcome audit record, source figure 5.Dark variant: Control plane and data plane view of the controlled agent, source figure 5.
Control plane and data plane. Everything that decides, including the planner, sits in the control plane; the data plane holds only the gateway, the systems of record and the outcome record. Source figure 5. Open for full size.

Four trust-boundary sentences are worth saying verbatim. The user boundary ends at authentication. The planner boundary ends at proposing intent, not action. The policy boundary ends at allow, deny or approve. The execution boundary ends at a scoped, logged side effect in a downstream system of record.

Name the systems of record explicitly. The CRM owns customer attributes and a support view of refund history. The refund or payment service owns whether money actually moved; reconcile the CRM view against its transaction receipt. The email system owns transport and inbox state. The internal data source owns account and entitlement data. The task state store owns workflow progress but not business truth. Caches may sit beside the planner or registry for low-risk lookups, but they never become the source of truth for permissions or refunds. Tool outputs stay untrusted data wherever they are stored.

Not every boundary is synchronous. Planning the next action and evaluating policy are synchronous, because a person is waiting on a gating decision. Tool execution can be synchronous for one low-latency action, but bulk and slow steps go through queues. Audit writes can be asynchronous only while the log never falls behind the point where a failure becomes unrecoverable. When risk rises faster than capacity, apply backpressure: if approvers are saturated, slow autonomous execution instead of letting risky actions pile up. Partition work by workflow or account, so all actions for one account share a key and two conflicting refunds cannot run in parallel.

The ledger audits requests, proposals, policy verdicts, approvals and receipts. Monitoring watches denials, unsafe actions, duplicate effects, approval delay and overrides. The kill switch halts new calls, cancels queued work, revokes tokens and marks in-flight work, as step 6 explains.

4. Trace an email-to-refund task

Walk the representative request in order without skipping a handoff: "Read the customer's email, check whether the account qualifies for a refund, update the CRM note, and issue the refund if policy allows." The interviewer should hear where control moves from the model to deterministic services and back.

  1. Authenticate the delegating user. The front door verifies who is asking and what delegation rights they hold. A support agent is not a finance approver.
  2. Plan the bounded next action. The planner picks the next smallest step, such as "retrieve the latest email thread", never the whole workflow.
  3. Resolve the tool schema. The registry returns the exact contract, including field names and data-sensitivity labels.
  4. Validate arguments and data classification for shape, missing fields, dangerous content, the amount, account and destination, and regulated data that changes handling.
  5. Evaluate policy and risk. The policy point compares the action, user role, data class and downstream effect against current policy. A CRM note update may pass; a refund may need approval.
  6. Obtain approval if required, captured as a record bound to the exact payload, tenant, record version, amount and expiry.
  7. Execute with a scoped credential and an idempotency key, so a retry cannot duplicate the refund.
  8. Record the result and decide whether to continue. The ledger stores the input, policy result, approval outcome, tool result and side effects. The planner proposes another bounded step only if the new task state and evidence justify it; otherwise it stops.

The email text read in step 2 is an observation, so it enters task state as data with its provenance, never as an instruction. An approval records reviewer, timestamp, rationale, exact payload, tenant, record version, amount and expiry. The gateway revalidates that snapshot at execution time, so a changed amount or record version invalidates the old approval.

Sequence diagram: authenticate, delegated request, resolve tool schema, validated action with data classification, then either mint scoped credential, execute with idempotency key, record result and side effects, continue or stop; or, for high risk, request human or workflow approval and mint the credential only if approved, source figure 6.Dark variant: Sequence diagram of one request with the high-risk approval branch, source figure 6.
One request as a sequence. The low-risk path mints a credential and executes directly; the alternative branch for high-risk actions requests human or workflow approval first and mints the credential only if approved. Both end in record, then continue or stop. Source figure 6. Open for full size.

The data model follows from the walk, and two of its records must never be conflated: the proposal and the receipt. AgentTask(id, actor, goal, state, step_budget) records progress. ToolDefinition(name, schema, data_class, scopes) describes the legal operation. ActionProposal(id, task_id, tool, args_hash, policy_decision) is a recommendation. PolicyDecision(proposal_id, verdict, scopes, reason) is authority. ActionReceipt(proposal_id, idempotency_key, outcome) records execution. A proposal is not evidence that a side effect occurred.

Canonicalise arguments before hashing, meaning put them in one fixed form (field order, number format, whitespace) so the same logical input always yields the same idempotency seed. A repeated key returns the stored receipt when one exists. Persist the operation before dispatch, reject conflicting arguments for that identity, and distinguish prepared, in-flight, confirmed and uncertain states. If the downstream effect completed before the receipt was saved, reconcile through the same operation key rather than dispatching a new write. The source also ties every refund to a durable business-action identifier built from case, customer and policy decision. That matters because two legitimate refunds with identical arguments are two operations and need distinct identities; this example is our illustration of the source rule.

The gateway, not the planner, owns exactly-once effect semantics, and only within the idempotency contract the downstream system supports. A local cache of completed responses is not enough on its own. A lost response is an unknown outcome that needs reconciliation; neither a prompt nor a generic retry makes it safe.

Schema validation runs before policy evaluation, so malformed or over-limit arguments are rejected before any authorisation logic executes. If the policy point or broker cannot be reached, the write does not proceed.

5. Hold four security controls together

Start security from the hostile case. A message that looks like ordinary customer email is a prompt injection asking the agent to ignore policy, pull a privileged record and issue an unauthorised refund. Do not argue about whether the model understands the instruction. Contain the blast radius, preserve the evidence and keep every irreversible action behind deterministic checks. The model sees information; it does not inherit trust.

Four controls answer almost any "how do you secure an agent with tool access" question, so learn them as a set:

  1. Treat tool observations as untrusted. A CRM response, ticket thread, database row or fetched page can carry hostile instructions. If the model can read it, the model can be manipulated by it, so tool output is never a command, a policy override or an approval signal.
  2. Never give the model broad, long-lived credentials. A broker mints capability tokens tied to one tenant, one workflow, one action type and one expiry window. If the broker is down, writes fail closed.
  3. Validate output before downstream use. The model may propose "refund $5,000", and a $500 task limit rejects it however confident the model sounds. Validation is where policy becomes enforceable.
  4. Bound the dangerous dimensions with hard ceilings on tool calls, per-task spend, maximum refund amount, allowable CRM objects and destinations.

The $5,000 and $500 figures are the source's dollar example for validation. They are separate from the euro-denominated near miss in the deep dives. Typed arguments, required fields, enumerated action types and explicit data classes leave the model less room to invent an action. Restricted adapters expose supported operations without a shell escape.

Blast radius is a design variable along four axes: tenant, region, workflow and dependency. A single-tenant outage beats a cross-tenant incident. A regional backlog beats a global write failure. A failure in the refund workflow should not block email triage, and a broker outage should not take down read-only analytics that can safely degrade.

Defence in depth means no single control carries the load. Policy constrains the model, the action layer validates its output, the broker scopes identity, the gateway tracks idempotency, the ledger preserves evidence and the operator can kill the workflow. If an interviewer asks for the single most important control, name all six. A prompt telling the model to refuse unsafe requests can sit on top of them, but it enforces nothing.

6. Decide how each failure stops or recovers

Design the failure path together with the happy path. Five rules organise every row of the table below:

  1. Reads that support a recommendation may degrade or queue.
  2. Writes that change customer state fail closed when authorisation, validation or identity is uncertain.
  3. Irreversible effects require approval or a second deterministic check.
  4. A write is never retried without proven idempotency.
  5. Incomplete evidence means stop and escalate.

Only explicitly approved, non-sensitive read paths may degrade to cached evidence. An unavailable broker must never trigger use of a broad static secret to keep a demo alive.

Source failure decisions for injection, uncertain execution, stale approval, loops and unavailable controls.

Fails Behaviour
Prompt injection requests an unauthorised tool The illustrated scope violation is rejected by policy evaluation on the proposed action, independently of model judgement. Preserve the message and proposal, then quarantine or review. The model never holds broad credentials. Also test harmful proposals that remain inside the formal allowlist; those require object, purpose, value and approval checks
Tool succeeds but the response is lost If idempotent, reconcile via the idempotency key or transaction record before any retry. If not, move to a reconciliation state, mark the action uncertain, escalate if the final state cannot be confirmed. Never repeat a write blindly
Approval becomes stale before execution Approval is bound to a snapshot: tenant, record version, amount, expiry. If the snapshot no longer matches at execution time, the approval is invalid and is re-requested
Agent loops on the same action Attempt counter, backoff, circuit breaker that opens after repeated failure. N attempts without a state change means stop and escalate
Credential broker is unavailable Writes fail closed. Reads degrade only to a cached, non-sensitive path that policy explicitly allows. Queue the work, notify the operator, keep the evidence. Never fall back to a broad static secret to keep the demo alive
Proposal exceeds the task's refund limit Validator rejects before policy runs, regardless of model confidence
Policy engine unavailable Fail closed for every write. Say this row slowly

The source says to read the policy-engine row slowly, because it is the row candidates most often soften. Now replay the path under the failure that matters most: a malicious instruction arrives inside an email.

Injection replay: user request or email content, agent planner makes a bounded action proposal, tool registry marks content as untrusted, policy decision point blocks scope change, audit ledger records attempted injection, kill switch may disable autonomous tool path; legitimate proposals continue to schema, policy, approval and execution, source figure 7.Dark variant: Injection replay through registry, policy decision point, audit ledger and kill switch, source figure 7.
The injection replay. The planner still produces a bounded proposal; the registry marks the content untrusted, the policy point blocks the scope change, the ledger records the attempt and the kill switch can disable the autonomous path. Source figure 7. Open for full size.

Follow the figure from the top. The planner still extracts a bounded action from the email. The registry marks the email content as untrusted. The policy decision point rejects the illustrated attempt to expand scope. A subtler injection may request a formally allowed action on the wrong customer or for the wrong purpose. Bind the proposal to the authenticated task and intended object, enforce aggregate value and destination limits, and review ambiguous financial intent. An allowlist alone does not establish that the user wanted this particular refund. The ledger records the attempted injection, and if the pattern repeats the kill switch can disable the autonomous tool path. Here the control-plane split becomes concrete: the model may read adversarial content in the data plane, but that content cannot rewrite policy in the control plane.

A successful tool call whose response was lost is an unknown outcome. Query its operation key or transaction record. Return the stored result if confirmed, continue reconciliation if pending, or escalate if the final state is unknowable. Never turn a network timeout into permission to repeat a payment.

A repeated action increments an attempt counter. Cached safe observations, backoff, per-tool circuit breakers and a no-state-change limit prevent loops. A stale approval returns to review. Missing durable evidence stops continuation. Audit may buffer asynchronously only while the system can still recover required intent and outcome. Persist sufficient intent before an irreversible operation.

The kill switch stops new tool calls, cancels queued work, requests token revocation and marks in-flight tasks for rejection where downstream services support it. A self-contained token may remain acceptable until expiry if the resource server does not check revocation state. Measure propagation delay and require the gateway to check a current cancellation or authorisation epoch before each write. A dashboard flag that only blocks new user requests is not enough. Even the full version has limits, which are our qualification rather than the source's: a completed external effect cannot be retracted by a flag, and a downstream API that ignores the in-flight mark needs reconciliation. Document those limits and the downstream revert path.

Before launch the team needs evidence and a runbook. The evidence shows which prompt version ran, which proposals were generated, which validations passed or failed, which approval artifact was attached, which identity token was used and which external calls were made. The runbook tells an operator how to quarantine a workflow, revoke a capability, replay a safe read-only step and reconcile uncertain writes without making things worse. A read-only replay can be safe; replaying a write needs its receipt and idempotency contract. Together they answer, after the fact, what happened, what was allowed, what was blocked and what the recovery path was.

7. Size the work behind each task

One request is not one unit of work. The source planning anchor is 50,000 users, twenty arriving tasks per second (QPS, queries per second) at peak and ten tool actions per task, which is about 200 tool actions per second. Separate three layers of load: how often tasks arrive; how many tool calls, model calls and policy checks each task triggers; and how many of those actions can change records, money or permissions. Iterative planning bursts can create forty to sixty model calls per second, so planner admission, model quota, adapters, approval queues and the ledger each need their own estimate.

Source planning estimates and their resulting bottlenecks.

Estimate Number What it forces
Planning decisions 20 per second at peak; 40 to 60 model calls per second under iterative planning bursts The planner is a queueing problem before it is a throughput problem; size planner and tool adapters separately
Tool actions roughly 200 per second at peak Reads parallelise; writes and approvals do not; concurrency caps must assume worst-case composition
Audit storage ~5 KB decision record and ~20 KB audit trail per task, so 100 KB/s to 400 KB/s About 8.6 GB to 34.6 GB per day of raw append-only data before indexing and replication
Planner compute ~1 second of planner time per task, so about 20 core-seconds per second at peak Reasoned about as a throughput-constrained service with slack for tail latency

The estimate that most affects the design is not CPU. It is the ratio of model time to tool time, plus how irreversible the tool effects are. If planning is fast and tools are slow, invest in async orchestration, caching and queueing. If tool effects are high-risk, invest in policy checks, staged execution and audit logging, even at some cost in latency. If human review is the bottleneck, write clearer escalation rules and reduce the number of ambiguous cases that reach a person.

Derive the risk tier before deciding autonomy. The source's decision aid is Risk = Impact × Likelihood × Irreversibility, used as a qualitative aid, not literal arithmetic.

A proposed action is scored with Risk = Impact x Likelihood x Irreversibility and assigned one of four tiers: fully autonomous, autonomous with preconditions, require human approval, blocked entirely, source figure 8.Dark variant: A proposed action is scored and assigned one of four risk tiers, source figure 8.
Each proposed action gets a risk tier from impact, likelihood and irreversibility: fully autonomous, autonomous with preconditions, require human approval, or blocked entirely. Source figure 8. Open for full size.

Place this case's actions in the four tiers. A low-impact read of a public FAQ can be fully autonomous. A CRM update is partly reversible, yet it still costs something if it misroutes a customer, so it runs with preconditions. A refund may be technically reversible and still meaningfully irreversible through customer dissatisfaction, accounting noise or abuse, so it needs human approval. Some exports and permission changes are blocked entirely.

Show a sensitivity range instead of false precision. The tenfold growth case is the real test: which part breaks first, the planner, the approval queue, a tool adapter, the audit log or the refund service?

Baseline, tenfold growth and tenfold lower-load cases.

Scenario Task peak Internal action pressure Likely design implication
Baseline 20 QPS Moderate Single queue, bounded retries, tight approval gate
10x growth 200 QPS High Partition by tenant or workflow class, add backpressure, move more work async
10x lower 2 QPS Low Simpler deployment may work, but keep safety controls identical

Check the audit arithmetic rather than repeating the range. At twenty tasks per second, the 5 KB decision record alone is 100 KB/s, or about 8.6 GB/day, and the 20 KB audit trail alone is 400 KB/s, or about 34.6 GB/day. The source quotes these as a range. If every task writes both, the raw total is about 500 KB/s, or 43.2 GB/day, before indexing and replication. Plan storage on the larger figure unless the two records are known to overlap.

The source also budgets about one second of planner compute per task, or twenty core-seconds per second under a CPU-service interpretation. Remote model serving must instead be sized by request concurrency, token throughput and provider quota. A one-second API wait is not a one-core compute requirement.

At 200 tasks/s, identify the first saturated component instead of multiplying every server count. Partition by tenant or workflow, add backpressure and move long work to queues returning job IDs. At two tasks/s, simplify deployment while keeping the safety controls identical. Preserve ordering by account for conflicting writes. Parallelise independent authorised reads, while approvals and dependent writes follow state transitions.

Concurrency limits are a safety feature as well as a performance one. Cap per user, so nobody floods the system with parallel tasks; per tool, so a noisy downstream system is not overwhelmed; and globally. Encode value limits too, so many low-risk reads are allowed while the number and total value of refunds in flight stay bounded. A well-designed limit stops one prompt injection from becoming a cascade.

8. Prove the controls before widening autonomy

Two counts gate every expansion of autonomy: unsafe actions and duplicate effects, and the source requires both to be zero. High tool success alongside a rising duplicate-effect count is a deployment blocker, not a product win. A zero count is an operational gate, not proof of zero future risk, so record how much traffic and which attack tests stand behind it. Compare denials, overrides, approval delays and task completion with baselines too, so a nominally safe system does not quietly block every useful task.

The table gives each metric, what it proves, the threshold the source treats as strong, where the evidence comes from and who owns it.

Release metrics, evidence source and accountable owner.

Metric What it proves Strong threshold Dataset / method Owner
Unsafe action count The control boundary held Zero in any sensitive workflow Audit review, incident tickets, rule checks Incident commander / ops lead
Duplicate-effect count Retries and replays cannot double-charge Zero; any occurrence alerts immediately Idempotency logs and reconciliation reports Reliability engineer
Policy denial rate Denials reflect real policy, not a broken prompt Stable against baseline; spikes investigated Policy engine logs Platform / trust-and-safety
Approval rate and delay Human gates protect without stalling the workflow Delay within SLO; rate stable Approval service logs Business operations
Tool success rate Downstream systems are called in supported ways Stable; failures alert when throughput stalls Tool execution telemetry Downstream system owner
Task completion rate Automation finishes work without manual rescue Holds or improves after each expansion Workflow state machine, case closures Product and FDE
Human override rate The agent is earning its place in the queue Low enough to justify the automation Review UI, post-action edits Operations manager

Report four dashboard layers, because the customer is buying workflow improvement under control, not model accuracy. Technical health is tool success, duplicate effects, error rate, queue latency and denial rate. Model quality is task completion, approval rate and delay, and how often a proposed action is later corrected. Adoption is override rate, usage by team and the share of eligible requests routed through the agent. Business outcome is time to resolution, refund cycle time, backlog reduction and the customer key performance indicator (KPI) the workflow exists to move. A healthy service can still fail the business.

Read the layers together, because one number has more than one cause. A denial spike can mean the guardrails are stopping an attack or the schema is too restrictive. An override spike can mean the model underperforms or the policy needs calibration. Inspect examples before changing the gate.

Red-team before granting more power, as a release gate rather than a stunt. Feed the system emails, documents and ticket text with adversarial instructions hidden in legitimate content, and ask whether it can be steered into calling tools it should not, leaking context or skipping approvals. The source's attack families are:

  • indirect injection in emails, CRM records, tickets, database rows and fetched pages;
  • over-broad credentials that turn one manipulated plan into fleet-wide access;
  • unvalidated proposals, such as a confident $5,000 refund against a $500 limit;
  • lost responses that a naive retry turns into a second refund;
  • stale approvals or action loops that authorise the wrong state or retry into a large bill;
  • cross-tenant requests.

The go/no-go for autonomy has three parts: the obvious attack paths were exercised, the policy layer rejected them, and the agent fell back to read-only or human review instead of improvising around the control plane. A passing demo is not evidence that these paths are safe.

Autonomy is earned in phases, and the go/no-go at each phase is a claim about the controls, not about the model. The schedule below is the source's week-by-week version.

Read-only rollout, proven reversibility, human financial review and canary expansion.

Week Gate
0-1 Classify every action by reversibility and financial impact; name the approver for each risky class
1-2 Read-only triage and drafting, no write path at all. Exit when drafts are useful for a defined slice, the policy layer blocks disallowed actions correctly, and every recommendation traces back to inputs and tool calls
2-3 Prove reversibility on a narrow set of CRM writes. Each tool has an owner, a documented revert procedure and an idempotency strategy
3-4 Add write paths only where rollback is demonstrated; every financial action stays behind a human. The gate is "the tool succeeded, the change was logged, the revert path exists, duplicates are under control"
5 Red-team the prompt with hostile tool observations before any additional power
6-8 Canary a small representative slice; watch policy denials, duplicate effects, approval delay and override rate; stop and fix on any of them
After Expand autonomy only where unsafe-action count stays at zero and duplicate effects never appear
Rollout phases: phase 1 read-only draft and classify, phase 2 reversible writes, phase 3 financial actions behind approval, red-team review and canary rollout, expanded autonomy, source figure 9.Dark variant: Rollout phases from read-only drafting to expanded autonomy, source figure 9.
Rollout phases: read-only draft and classify, reversible writes, financial actions behind approval, red-team review and canary, then expanded autonomy. Source figure 9. Open for full size.

The figure compresses the schedule into its phases: read-only drafting and classification, reversible writes, financial actions behind approval, red-team review with a canary, and only then expanded autonomy.

A practical approval gate records reviewer identity, decision timestamp, policy rationale and the exact payload that will execute. An approval that ages out expires rather than executing later. A policy change updates the gate before the next rollout step, not after an incident.

Keep a risk register in which each entry names the risk, its owner, the mitigation, the trigger that fires it and the rollback. Reuse its shape for any de-risking question an interviewer asks. The source fills in three rows.

Source risk register: owner, mitigation, trigger and rollback for the three leading risks.

RiskOwnerMitigationTriggerRollback
Prompt injection causes an unauthorised tool callSecurity reviewerInjection tests, allowlists, policy checks, read-only fallbackAny confirmed unauthorised attemptDisable autonomous tool calls and revert to human review
Duplicate CRM writes after retriesReliability engineerIdempotency keys, reconciliation jobs, replay-safe contractsAny duplicated side effectPause write traffic and drain the queue
Refund approvals stall operationsFinance operations leadApproval service level agreements (SLAs), escalation path, reviewer trainingDelay exceeds target or queue depth climbsNarrow the eligible refund scope or route more to manual handling

The rollout is also a training and support plan. Users need to know what the agent can do, what it will refuse, how approvals work and how to escalate when a result looks wrong. Support needs a runbook for inspecting logs, finding the policy rule that fired and recovering a stuck workflow.

Build the approval service, idempotency layer, policy engine, credential broker and ledger as shared services. Keep the customer-specific pieces, CRM fields, refund rules, routing and thresholds, in configuration and adapters. The durable product asset is the control plane, not any one customer's wiring.

Try the case yourself

Technical deep dives

Examine mechanisms, alternatives, and operational consequences.

Integrating hundreds of applications without loading every tool

This is where the "enterprise assistant over 100+ applications" case joins this one. REST, function calling, Model Context Protocol (MCP) and agent frameworks are layers of one system, not competing technologies, and interviewers check whether you treat them that way.

REST is ideal when the interface is stable, the operations are deterministic and no reasoning is needed. A fixed workflow can call it directly. But a model does not natively understand authentication, endpoint discovery or request schemas, so REST alone never adds up to an assistant.

Function calling lets the model select a declared operation from natural language. The axis that separates it from REST is who decides to make the call: fixed application code, or the model. The wire call can be identical. The cost is not: another REST endpoint is cheap, while another function the model must choose between costs prompt space and selection accuracy. The source uses about twenty functions as a comfortable example and 1,500 functions across 100 applications as a catalog that strains selection and prompt size. These are scenario assumptions, not model-independent limits. Measure tool-selection accuracy, schema-token cost and latency on the actual catalog; maintain discovery metadata as schemas change.

MCP solves discoverability. One server per application advertises its tools and resources, so the assistant asks what is exposed instead of hardcoding schemas. MCP does not replace REST. The captured source describes MCP as JSON-RPC over standard input/output (stdio) or Streamable HTTP, and an MCP server may call REST, SOAP (Simple Object Access Protocol), SQL or a legacy system underneath. A tool protocol standardises access and discovery; it does not grant business permission.

An agent framework earns its place when a request needs multi-step reasoning. "Prepare a renewal report for our top customers and email their managers" means finding customers, retrieving CRM data, generating a report, storing a PDF and sending an email, and no single function coordinates that. A single agent suits one tool, a short workflow and deterministic execution. A multi-agent shape suits planning across many domains with independent specialists. Wrapping "Create a Jira ticket" in an orchestrator would be pure overhead.

Each integration layer has a different job.

Technology Best use
REST API Direct application communication
Function calling Small, deterministic tool execution
MCP Enterprise tool discovery and standardised AI integration
Agent framework Multi-step planning, orchestration, reasoning
Integration layers from top to bottom: agent framework coordinates multi-step decisions; MCP discovers available functions without 1,500 hardcoded schemas; function calling chooses a declared operation; REST, SOAP or SQL performs external execution, source figure 10.Dark variant: Four integration layers from agent framework down to REST, SOAP or SQL execution, source figure 10.
The four layers stacked: the agent framework coordinates, MCP discovers functions without 1,500 hardcoded schemas, function calling chooses one declared operation, and REST, SOAP or SQL executes it. Source figure 10. Open for full size.

Read the stack from the bottom. Execution never moves out of the REST, SOAP or SQL layer; each layer above adds a decision, not a new way to write. That is why the gateway and policy controls from the walkthrough still sit in front of the bottom layer however the call was chosen.

The tool registry is what makes this scale. Loading every MCP server up front does not. The registry sits between the planner and the universe of servers and loads only those relevant to the current task, which keeps the prompt small. In this design it also carries each tool's argument schema, data class and risk label, so the policy point can decide without asking the model. Treat the 1,500-function figure as the source's scenario, not a universal breaking point.

At 500-plus applications and 200,000 employees, the rest of the scaling list is short:

  • cache employee profiles, the org hierarchy and the holiday calendar, within freshness and privacy rules;
  • scale the planner, gateway and LLM routing as stateless horizontal services;
  • set per-user and per-application quotas, with circuit breakers against runaway agents;
  • run long workflows asynchronously and return a job ID;
  • use regional gateways, region-local MCP servers and data-residency controls.

No application trusts the LLM; applications trust enterprise identity. Every request carries the user's identity, an OAuth token, role-based or attribute-based access control (RBAC or ABAC) context and an audit record. The gateway establishes the actor and tenant for the target resource, so the backend does not trust the model directly. For HTTP MCP, validate token audience and use credentials issued for the receiving server. Do not forward an arbitrary incoming bearer token to every downstream application; exchange it or use the approved delegated credential for each target. This identity propagation is the same rule as the credential broker: the model receives context to reason with, never a secret to act with. Task state and audit stay separate from cross-session business truth.

The reported Salesforce prompt asks for the loop, tool interfaces, memory, orchestration and safety in one architecture, and this design answers each part. The loop is propose, validate, decide, execute, record, repeat, with a step budget. Tool interfaces are the registry's typed schemas with data class and risk. Memory is the task state store for workflow progress plus the ledger for what happened, and neither is business truth. Orchestration is the planner choosing one bounded action at a time over a queue partitioned by account. Safety is every layer below the planner.

Diagnose a slow or looping agent

The usual pivot after a good design is "the agent is slow and expensive". On this system the dominant driver is agent steps and tool calls, plus retries after failed or rejected actions. An agent that acts must be bounded before it is optimised, and the bounds already exist in the design: cap the steps, make the common paths deterministic, cache read-only tool results within the request, and let the approval gate stop the loop until a decision arrives. Do not answer by giving the loop a bigger model and a longer budget.

Trace model planning, downstream tool wait and approval delay separately, because each points to a different lever. The table is the source's one-glance version.

Source cost-and-latency pivot with its dominant driver and proof metrics.

Drill field Worked answer
Dominant driver Agent steps and tool calls, plus retries after failed or rejected actions
Cheapest lever first Bound steps per request; deterministic route for known intents; cache read-only tool results within the request; approval gate as the loop breaker
Metric that proves it Steps per request; tool latency; retry count; cost per request
Do not Give the loop a bigger model and a longer budget
60-second line An agent that acts must be bounded before it is optimised. Cap the steps, make the common paths deterministic, and let the approval gate stop the loop

Two production scenarios arrive as the same pivot in different words, and each has its own diagnosis.

"The agent keeps calling tools repeatedly." It repeats a CRM lookup or retrieval until the request times out. Ask which tool repeats, which observation triggers it and whether state is preserved between steps. The likely causes are a poor stopping condition, ambiguous tool descriptions, missing memory, a failed parse or no result cache. Inspect the trace for repeated tool-and-observation pairs and find the missing state transition. Now: set max steps, cache the tool result, improve the schema and add a deterministic route. Later: agent budget tests and trace-based loop detection. Prevent recurrence with unit tests for tool selection and loop prevention. The source's spoken line: "I would treat this as a control-loop bug. The fix is step budgets, better tool routing, cached results, and explicit stopping criteria."

"The tool-calling workflow times out." An external workflow exceeds the response deadline. Ask which tool is slow, whether it can run asynchronously and whether the result is needed immediately. The likely causes are a slow external API, serial calls, no timeout budget or synchronous side effects. Trace the calls and find the critical-path dependency. Now: set per-tool timeouts, parallelise read-only calls, and return a clearly limited partial answer or an async job ID with status. Later: dependency service level agreements (SLAs) and circuit breakers. Prevent recurrence with a workflow design review before adding tools. The spoken line: "A tool timeout is not always an LLM issue. I would redesign slow side effects as async and keep the user informed."

Every strong cost answer follows four verbs in order. Measure, by tracing and attributing cost first. Route, matching the model and path to the risk. Bound, with limits on steps, tokens, timeouts and budgets. Cache safely, with tenant, permission and version in the cache key so one user's cached result never answers another user's request.

Deliver the answer in six moves: frame the business impact, decompose the path, name the largest measured driver, fix it safely, prove it with before-and-after numbers, and prevent recurrence. The proof metrics are steps per task, tool latency, retries, timeouts and cost per task.

When the interviewer wants unit economics, the ratio of model time to tool time decides the lever. When planning is expensive, batch safe reads into one planning pass. When tool calls dominate, cache safe reads and prefetch context. When human time is the cost, improve proposal clarity and risk classification, and tighten the threshold so only high-value cases reach a person. Never bypass a required approval to save time.

Investigate the refund near miss

The incident on this design is a near miss, and the trap is to say there was no problem because the gateway blocked it. Work through it as detect, contain, root cause and prevent.

A retail support assistant may summarise orders, draft replies, check policy and recommend refunds. It may not execute a refund above €250 without manager approval; for those it may only create a proposed refund ticket. On 8 July 2026 a support agent asked it to "handle all delayed VIP shipments from yesterday". The planner selected the refund_customer tool for eighteen orders, several of them above the threshold, including a €740 refund with no approval. The gateway blocked the high-value calls. The three log lines below are the source's trace, kept unchanged.

2026-07-08T16:07:51.119Z level=warn service=agent-planner
  trace_id=trc_tool_9031 request_id=req_retail_22018 tenant_id=shopline
  user_role=support_agent user_intent="handle delayed VIP shipments from yesterday"
  planned_tool_calls=18 selected_tool=refund_customer
  policy_doc_version=refund_policy_v3 planner_model=agent_planner_2026_07

2026-07-08T16:07:51.522Z level=critical service=tool-gateway
  trace_id=trc_tool_9031 tool_call_id=tc_77881 tool=refund_customer
  order_id=ord_884120 customer_tier=vip refund_amount_eur=740.00
  approval_state=missing user_role=support_agent max_allowed_without_approval_eur=250.00
  tool_call_blocked=true block_reason=approval_required policy_decision=deny

2026-07-08T16:07:51.800Z level=warn service=agent-safety-evaluator
  trace_id=trc_tool_9031 event=unsafe_bulk_action_near_miss
  bulk_action=true affected_orders=18 blocked_calls=6 allowed_calls=12
  safer_alternative=create_refund_review_ticket
  planner_policy_compliance_score=0.42

Detect. Read the telemetry line by line. The planner line shows eighteen planned calls to refund_customer under policy refund_policy_v3 and planner model agent_planner_2026_07. The gateway line shows a €740 refund against a €250 no-approval limit, approval state missing, and a deny decision. The safety evaluator line shows six blocked calls, twelve allowed, a safer alternative of create_refund_review_ticket and a planner policy-compliance score of 0.42. Those lines tell two different stories. The gateway's critical line is enforcement working. The evaluator's line is the planner failing.

The source states that no unauthorised money moved. The twelve allowed calls passed the gateway, so they may have executed, and "no unauthorised money moved" is not the same as "no money moved". The trace alone cannot say whether those twelve refunds were legitimate, which is why containment includes auditing them.

Contain immediately: disable bulk refund planning, force all VIP refund actions into review-ticket mode, and add a user confirmation step for financial actions. Then audit the twelve allowed calls to confirm that the smaller refunds were legitimate. Preserve the proposals, policy context, schema and gateway records.

Root cause. The planner prompt agent_planner_2026_07 was deployed to make the agent "more action-oriented". Its examples emphasised completing workflows end to end and omitted bulk-action approval boundaries. The planner over-generalised "handle delayed shipments" into direct refund execution: it retrieved the refund policy and still failed to apply the threshold while planning. The gateway policy was unchanged and blocked correctly. Separate planner failure from enforcement success. This is a near miss, not a completed unauthorised transaction, and it still counts as an incident because the distribution of proposals got worse.

Prevent with defence in depth rather than a prompt edit:

  • risk-aware tool schemas that encode the approval threshold;
  • pre-execution policy simulation, so a planner change is tested against policy before it ships;
  • planner training examples that cover thresholds and bulk actions;
  • a separate action-risk classifier before tool calls;
  • hard enforcement kept in the gateway regardless of planner confidence.

The same pattern applies to account deletion, data export and permission changes. A malicious user can phrase any of them as operational cleanup, which makes this a fraud and unauthorised-action risk, not only a quality bug.

The weak answer is "the tool was blocked, so there is no problem; I would tell the agent to be more careful". The source scorecard rewards four things: reading planned, blocked and allowed calls with role, amount and approval state; separating planner failure from gateway success; auditing the plan, policy context, schema and gateway logs rather than editing the prompt; and naming the fraud and unauthorised-action risk. A spoken version is in the practice answers.

Make trade-offs explicit

Interviewers probe exactly four pairs, and each has a resolved shape: give a little on one side to protect something specific on the other. Flexible interpretation helps turn messy email into useful intent. Deterministic execution limits how that interpretation changes records. Fine-grained scopes add integration work, so scope irreversible effects first and share authorisation wrappers. Human approval adds queue latency, which is acceptable when the alternative grants uncontrolled financial authority. A central gateway provides one enforceable write path, while direct integrations multiply validation and audit responsibilities.

The source's four resolved trade-offs.

Trade-off Resolution
Agent flexibility vs deterministic workflow Flexible interpretation, deterministic execution. The model drafts, the workflow validates; letting the model choose the final action raises variance, audit complexity and blast radius
Fine-grained scopes vs integration burden Optimise scopes around irreversible effects first, then simplify with shared auth patterns and reusable wrappers
Automatic execution vs approval latency Tiered automation: low risk auto-runs, medium risk queues for review, high risk needs explicit approval or a second check. Accept approval latency to protect against irreversible financial harm
Central tool gateway vs direct integrations The gateway is the default, because it is the one place for auth, policy, audit, idempotency and schema validation; direct integrations multiply the places a bad prompt can reach a write API

Source references

MCP 2025-11-25 authorisation requires resource-bound token handling. RFC 7009 describes revocation and propagation limits. The incident logs below remain source-reported teaching evidence, not observed transactions in this review.

The captured case's reference check was dated 27 September 2026. The protocol and tool-selection material is retained as source context rather than a claim about every current provider or implementation.

Apply the decisions

Practice

Attempt the case before revealing the worked reasoning.

Reconstruct the controlled request

On a blank page, trace the email request through identity, proposal, schema, policy, approval, capability, execution and receipt. Then inject a lost refund response and a changed approval snapshot, and say what each component does. This blank-page drill is authored guidance. Answers 1 to 10 below are the source's own self-check questions; answers 11 to 16 turn the source's follow-ups and drills into questions to answer before revealing.

Work through your answer

This local worksheet is a prototype addition. Notes save in this browser. Nothing is submitted or scored.

No notes yet.

Check your reasoning

Reveal the self-assessment rubric

This checklist is an authored addition. Assess what you can explain without reopening the walkthrough.

0 of 7 reasoning checks covered.

Why is "the model refuses" not a security control?

Because the model sees information and does not inherit trust. Any content it reads can manipulate it. Enforcement lives in the policy point, the broker and the gateway, so an injected instruction fails there even if the model is fooled.

What makes a retry safe?

A canonical argument hash as the idempotency seed, a durable business-action identifier, and a gateway that returns the stored receipt for a repeated key instead of calling the tool again. The downstream system must honour that contract or support reconciliation. Without it, do not retry a write; a lost response stays pending until confirmed.

What does an approval bind to, and why?

A snapshot of tenant, record version, amount and expiry, recorded with reviewer, timestamp, rationale and the exact payload. If the record changes before execution, the snapshot no longer matches, the approval is invalid and it is re-requested.

Where does the policy boundary end?

At allow, deny or approve, with scopes and a reason. The execution boundary ends at a scoped, logged side effect in a downstream system of record, which returns a receipt.

Why does validation run before policy?

So malformed or over-limit arguments, such as a $5,000 refund on a $500 task, are rejected before any authorisation logic executes, whatever the model's confidence.

What happens to writes when the credential broker is down?

They fail closed. Only reads with a cached, non-sensitive path that policy explicitly allows may degrade. The work is queued, the operator notified and the evidence kept. Never fall back to a broad static secret.

At what scale does function calling break, and what replaces it?

The source illustrates the problem with 1,500 functions across 100 applications and about twenty as a comfortable smaller catalog. These counts are assumptions to test, not a universal breaking point. MCP provides discovery and a tool registry loads only the servers and tools a task needs, carrying schema, data class, risk and scopes. Treat the count as the source's scenario, not a universal threshold.

Which two counts gate every autonomy expansion?

Unsafe actions and duplicate effects, both zero. Record the traffic and tests behind the zero, because zero observations do not prove future absence.

What is the refund near miss's root cause, and what is its fix?

A planner prompt made "more action-oriented" whose examples omitted bulk-action approval boundaries. The fix is risk-aware schemas that encode the threshold, policy simulation before execution, a separate risk classifier, better planner examples, and enforcement kept in the gateway. Contain first by disabling bulk refund planning and auditing the twelve allowed calls.

What is the first production gate?

That the control plane demonstrably prevents unauthorised actions, duplicate execution and uncontrolled side effects, not that the agent can do everything.

Why not let each tool integrate directly instead of routing every write through one gateway?

One gateway centralises authorisation, policy, validation, audit and idempotency in a single write path. Direct integrations multiply the places a bad prompt can reach a write API, and each one has to reimplement those checks correctly.

When does the agent stop?

On risk, ambiguity, missing state, a stale approval, a policy or broker failure, or a budget ceiling on steps, retries or spend. It pauses, escalates to a human or fails closed; it never improvises around the missing control.

The interviewer challenges your riskiest assumption: what if the email itself is trying to steer the agent into a refund it should not make?

Answer calmly and specifically. The email is untrusted input used only for classification and extraction. The policy engine outside the model decides whether the request is eligible for any write path. The workflow requires a durable action record, plus approval for risky cases. Content that looks like injection or carries conflicting instructions fails closed, and the ledger keeps it as evidence.

The agent keeps calling the same CRM lookup until the request times out. What do you do?

Treat it as a control-loop bug. Ask which tool repeats, what observation triggers it and whether state is preserved. Inspect the trace for the missing state transition. Now: max steps, a cached result, a better schema and a deterministic route. Later: budget tests and trace-based loop detection. Prevent with unit tests for tool selection and loop prevention.

The tool-calling workflow times out because an external system is slow. What do you do?

It is not always an LLM issue. Find the critical-path dependency, set per-tool timeouts, parallelise read-only calls and return a limited partial answer or an async job with status. Redesign slow side effects as async and keep the user informed. Later, add dependency SLAs and circuit breakers; prevent recurrence with a workflow design review before new tools.

Explain the refund near miss in about thirty seconds.

Source spoken answer: "This is a near miss. The gateway prevented loss, but the planner attempted unauthorised high-value refunds. I would inspect the planned calls, policy retrieval, and gateway decisions. Then I would disable bulk refund execution, route VIP refunds to review tickets, encode approval thresholds in the tool schema, add policy simulation before execution, and keep the gateway as a non-bypassable enforcement layer."

Rehearse a fifty-minute design

Organise the sketch around trust boundaries, not the model, and spend minutes where the stakes are: identity, authorisation, duplicate execution and malicious instructions. A weak answer covers prompts, vector search, optical character recognition (OCR), channels and regions all at once. A better one narrows by risk.

The full design's schedule runs as follows. Minutes 0 to 5: open with the customer outcome and the hidden constraint, and invite redirection toward strict safety, lower latency or faster rollout. Minutes 5 to 12: lock scope, meaning what the agent may do versus suggest, which actions are reversible, dollar thresholds, staged CRM updates and stable identifiers. Minutes 12 to 22: the architecture as a control system, where the model plans, policy decides, the gateway executes, the ledger records and a state machine tracks progress. Minutes 22 to 30: the four trade-offs. Minutes 30 to 38: the follow-up drill. Minutes 38 to 44: what to build first, which is read-only, then reversible writes with approval, then low-value automated writes, refunds last. Minutes 44 to 50: the ninety-second decision memo.

Fifty-minute timeline: 0-5 open with customer outcome, 5-12 lock scope, 12-22 architecture as control system, 22-30 defend trade-offs, 30-38 follow-up drill, 38-44 summarise under pressure, 44-50 executive close, source figure 11.Dark variant: Fifty-minute interview timeline in seven blocks, source figure 11.
The fifty-minute timeline. The figure labels the last two blocks "summarise under pressure" and "executive close"; the prose schedule fills them with the build-first plan and the decision memo. Source figure 11. Open for full size.

The shorter interview guide in the source splits the same fifty minutes differently: opening and scope 12, architecture and the one-request walk 10, trade-offs and failure drills 16, rollout and measurement 6, close 6. Either split works if you name the control boundary early and keep the technical detail in reserve for follow-ups.

The follow-ups arrive in a predictable order, and the table holds a prepared answer for each. Answers 11 to 13 in the practice set cover three more: why not direct integrations, when the agent stops, and the riskiest-assumption challenge.

Source follow-ups on credentials, duplicates, hostile email, tool schemas, stopping and containment.

Follow-up Answer
Can the model hold credentials? No. It receives the minimum context to reason, never a long-lived secret. Credentials live in a secrets manager or token broker; the model requests an action and a trusted service mints a constrained token for that exact operation
How do you stop duplicate refunds? Idempotency at the business-action layer, not only the API layer. Every refund carries a durable identifier tied to case, customer and policy decision; before execution the workflow checks whether it completed, is in flight or partially applied, and on retry returns the existing outcome
What if the email contains malicious instructions? Assume it will. Email is untrusted input, never command authority. The model classifies and extracts facts and does not obey embedded instructions about overrides, credentials or approvals. Prompt separation, tool allowlisting, policy outside the model, strict role boundaries
How does the kill switch work mid-task? More than a flag on new requests: halt new tool invocations, cancel queued workflows, revoke or expire delegated tokens, and mark in-flight tasks so downstream services reject completion. The state machine makes the pause point explicit
OpenAI-style practice prompt, an agent that reads incoming requests and performs actions across Salesforce, SAP, Jira and email: "The agent wants to issue a refund. Should it be allowed to do so automatically?" Only below a threshold, only as a delegated actor with a scoped token, only through the idempotent gateway, and only where the revert path is proven. Above the threshold it creates a proposed refund ticket for approval. Assume the model will occasionally be wrong and design so the blast radius is limited
How do tool schemas reduce hallucinated actions? (Tier 2) Typed arguments, enums over free text, required fields, a data-class and risk label per tool, and validation before policy so a malformed proposal never reaches authorisation
How do you sandbox tool execution? Restricted adapters only, no shell escape, per-tool concurrency limits, and a gateway that is the only path to any write API
How do you control cost explosions from runaway tool calls? Step budgets per task, retry caps, a circuit breaker on repeated identical calls, per-user and global concurrency, and a spend ceiling that trips the kill switch
When do you route to a human, and how does auditing drive that? On risk tier, on low confidence, on policy ambiguity, on any inconsistency. The ledger's denial and override rates recalibrate the thresholds
Circuit breakers, rate limits, degradation when the model is unavailable? Per-tool breakers, per-user and per-tool quotas, and degradation to read-only or human-review mode, never to a bigger static credential

Repair the common weak answers on the spot. Talking about the model too long becomes re-centring the control plane. Optimising for elegance becomes acknowledging the cost of fine-grained scopes and approval queues. Assuming email is trustworthy becomes stating untrusted-input handling early. Describing the kill switch as a UI flag becomes tying it to cancellation, token revocation and downstream rejection. Drowning the interviewer in components becomes saying what ships first and what is deferred.

Close with the source's ninety-second decision memo:

"We're building an agent that turns unstructured email into safe operational action, but we are not giving the model unchecked authority. The model handles interpretation and recommendation; deterministic services handle identity, authorisation, idempotency, approvals, audit, and execution. The key trade-off is flexibility versus control: we accept some workflow rigidity so that refunds and CRM writes are gated, logged, and reversible where possible. The first gate is not 'the agent can do everything'; it is that the control plane demonstrably prevents unauthorised actions, duplicate execution, and uncontrolled side effects."

When the whole design has to fit in a summary, the source's two-minute spoken answer, condensed here with its sequence intact, runs: name the disagreement between operations, security and finance; restate the outcome as useful automation under deterministic control of identity, permissions, risk and irreversible effects; say the model interprets and proposes while deterministic systems decide; walk planner, schema validation before policy, policy verdict with scopes, broker token for one workflow and action type, and the idempotent gateway with one side effect however many retries occur; state that tool observations are data, so an injection hidden in a ticket fails at the policy gate; name the ceilings on loops, spend, refund amounts and destinations; and finish with read-only first, proven reversibility before any write path, money behind a human, red-team before more autonomy. Success is fewer handling minutes with zero unauthorised or unreviewed irreversible changes.

The shorter guide's spoken summary is a useful sixty-second version:

"The model interprets requests and proposes one bounded action. A registry and validator check the tool and arguments; deterministic policy returns allow, block, or approval. A broker mints a short-lived scoped token, and an idempotent gateway executes once and writes a receipt. Tool output is untrusted, writes fail closed, and budgets cap loops and spend. I would ship read-only first, add reversible writes with a revert plan, keep money behind human approval, and gate expansion on zero unsafe or duplicate effects."

The lines that carry the round, as the source lists them:

  • "The model proposes; it never decides."
  • "Flexible interpretation, deterministic execution."
  • "Tool output is untrusted data, never instructions."
  • "The model sees information; it does not inherit trust."
  • "No application trusts the LLM. Applications trust enterprise identity."
  • "Validation is where policy becomes enforceable, and it runs before policy does."
  • "A retry without idempotency is how one refund becomes two."
  • "Fail closed on writes. Degrade only the lowest-risk reads. Never fall back to a broad secret to keep the demo alive."
  • "Ceilings on steps, spend, refund amount and destinations are guardrails, not tuning knobs."
  • "The first production gate is that the control plane prevents unauthorised actions, duplicate execution and uncontrolled side effects."

Interviewers also calibrate level. On this design the levels separate on how far the control plane reaches past a single request, not on how well the planner picks tools.

Senior, staff and principal expectations for the controlled agent.

Level Sounds like Missing
Senior The planner proposes one bounded action, the typed schema rejects over-limit arguments before policy runs, and the policy decision point returns allow, block or needs-approval. A broker mints a token for that one action, the idempotent gateway executes once and stores a receipt, and writes fail closed if policy or the broker is down. The operating half: who owns each tool's revert path, how the kill switch stops work already in flight, and what evidence lets autonomy expand.
Staff Gives each tool an owner and a documented revert procedure, binds approvals to tenant, record version, amount and expiry, and makes the kill switch cancel queued work, revoke tokens and mark in-flight tasks. Rolls out read-only first, keeps money behind a human, and gates every expansion on zero unsafe actions and zero duplicate effects. What breaks as workflows and applications multiply: one-off wiring per customer, a registry past 1,500 functions, and planner regressions like the refund near miss that the gateway quietly absorbs.
Principal Makes policy, broker, approval, gateway and ledger one shared control plane, so each new workflow brings only adapters and configuration, the registry loads only task-relevant tools, and identity propagates so no application trusts the LLM. Treats the refund near miss as a shift in the proposal distribution, so policy simulation and a separate action-risk check gate every planner change. The refund threshold, the autonomy tier per action class and how long the ledger is kept depend on the customer's finance policy and dispute rules, so they wait for discovery.

Return to the decisions you could not explain.

Review the essentials

Quick review

Recall the decisions, failure responses, and closing answer.

Recall the proposal-to-receipt contract

One sentence: the model proposes; deterministic systems decide; the idempotent gateway executes once and records a receipt. Name the disagreement between operations, security and finance in the first two minutes, because it is the design problem.

Ask first: which actions are reversible, where the money boundary sits, whose identity the agent acts as, what needs approval, which systems are the record, what audit must keep, how to stop in-flight work and what the peak task and tool load is.

Authenticate, propose one step, resolve a registered tool, validate arguments and data class, evaluate policy, obtain approval if needed, mint a scoped capability, execute with an operation key, persist the receipt and decide whether to continue. Business systems own truth. Workflow state owns progress.

Keep observations untrusted, credentials narrow, proposals validated and dangerous dimensions bounded. Required records are task, tool definition, proposal, policy decision, approval and receipt. Recheck approval snapshot and expiry. Fail writes closed on missing policy, credentials or durable evidence. Reconcile lost responses instead of repeating them.

The source assumes 50,000 users, twenty peak tasks/s, ten actions/task and forty to sixty model calls/s in bursts. At tenfold growth, partition and apply backpressure. Tool and value limits constrain damage as well as load. Large catalogs need task-relevant schema discovery and enterprise identity at every backend.

Read-only comes first, then reversible CRM writes with proven rollback. Money remains reviewed in the pilot. Zero observed unsafe and duplicate effects gate each expansion. Watch denials, overrides, approval delay and business completion together. A kill switch withdraws new authority and pauses work but cannot undo completed effects.

For the near miss, eighteen refunds were planned, six blocked and twelve allowed, and the €740 request exceeded the €250 no-approval limit. Distinguish the planner's unsafe proposals from the gateway's successful denial, and audit the twelve allowed operations as well as the six blocked ones. For slow or looping work, trace, route known intents, bound steps and retries, cache safe reads with tenant, permission and version in the key, and move slow effects to asynchronous jobs. Never extend an unbounded loop to make it more capable.

Policy, broker, approval, gateway and ledger are the reusable control plane; each customer brings adapters and configuration. Final mental model: propose, validate, decide, approve if needed, scope the credential, execute once, record, then stop or repeat within budget.

"I would let the model interpret and propose, keep authority in policy and approval, execute only through a scoped idempotent gateway, and expand autonomy only when unsafe and duplicate effects stay at zero."

Test your recall

Where next

Practise this as a worksheet
Tool-Using Agent with Safety Controls