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
View
Interview prep
Sections
4
By
Sourav Banerjee
Last updated
20 Nov 2026

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

Report an issue

Interview view. The case brief, design walkthrough, technical deep dives and quick review, condensed into bullets, tables and lines to say out loud, with interactive diagrams to step through.

Want to go deep? The full casebook has the complete reasoning in prose, the original diagrams, practice questions with worked answers and the sources.

Case brief

The case in one line: the model proposes one bounded action; deterministic services decide, scope, execute once and record a receipt.

30-Second Cheat Sheet

  • The product: an agent that reads customer email, queries internal systems, updates CRM records and sometimes issues refunds.
  • The real problem is a disagreement: operations wants speed, security wants hard approval gates, the support manager wants low friction, finance fears money that can't come back.
  • Useful part vs dangerous part: interpreting a messy request is useful. Letting that interpretation become authority is dangerous.
  • Email and tool output are untrusted: one injected sentence must never turn into a refund.
  • The loop: planner proposes one bounded next action → validator → policy (allow, block or needs a human) → credential broker → idempotent gateway → receipt.
  • Writes fail closed: when a control can't answer, the write doesn't happen.
  • Stoppable: operators halt in-flight work by revoking tokens and cancelling queues.
  • Anchor case for agents that act: related prompts keep the same proposal-to-execution boundary.

1. Let an Agent Prepare Work Without Granting It Authority

The situation

  • An operations team wants an agent to:
    • Read customer email.
    • Query internal systems.
    • Update customer relationship management (CRM) records.
    • Sometimes issue refunds.
  • Everyone agrees on that feature list, then disagrees about everything else.
Group What they want or fear
Operations Speed
Security Hard approval gates
Support manager Routine cases handled without friction
Finance Fears money that moves and can't come back
  • That disagreement is the design problem.

Why the agent is dangerous

  • Useful part: interpreting a messy request.
  • Dangerous part: letting that interpretation become authority.
  • A customer email is input to interpret. 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.

The terms that carry the whole case

Term Meaning
Bounded next action A single small step with stated limits, never "do everything"
Deterministic service Gives the same answer for the same input; doesn't depend on the model's judgement
Validator Checks the tool and its arguments
Policy service Answers allow, block or needs a human
Credential broker Issues a short-lived token that covers only that action
Idempotent gateway A write path that turns repeated calls for the same action into one effect, runs it once and writes a receipt
Fail closed When a control can't answer, the write doesn't happen
  • Neither an email nor the model's confidence can authorise a refund.

The core loop (source figure 1)

planner proposes one step → validate tool and arguments → policy decision

  • Allow → idempotent gateway executes once.

  • Needs a human → human approver.

  • Block → stop and record.

  • The figure is the whole case in miniature. Every later section adds detail to one of its boxes.

  • None of them lets the planner skip a box.

  • Writes fail closed. Operators can stop work already in flight by revoking tokens and cancelling queues.


2. Who Meets in This System

Five groups of people. Step 1 of the walkthrough maps what each notices first when the agent fails.

Group Role
Business user Delegates inbox and case work
Approver Reviews the exact risky payload
Security Defines identity, authorisation and audit rules
Tool and data owner Defines supported operations, limits and the revert procedure
Operator Monitors, reconciles uncertain actions and stops workflows

What the first release excludes

  • Free-form code or shell execution
  • Open-ended tool discovery
  • Unbounded loops
  • Cross-tenant access
  • Self-modifying policy
  • Unrestricted refunds

What it assumes you know

  • Large language model (LLM) agents and tool calling
  • Authentication and scoped tokens
  • Idempotent APIs
  • Basic cloud architecture

  • This is the anchor case for agents that act.
  • Related prompts keep the same proposal-to-execution boundary and change which control dominates.
Related case What changes from this case Where it is covered
Enterprise AI assistant over 100+ internal applications Tool discovery and registry loading at scale; enterprise identity must reach every application Deep dives: integrating hundreds of applications
Enterprise workflow automation (OpenAI-style practice prompt) and the reported Salesforce prompt on loop, tool interfaces, memory, orchestration and safety More orchestration and memory detail, same proposal-to-execution boundary Deep dives: integrations; the fifty-minute rehearsal in the full casebook
Slow, looping or timed-out agent, and the "slow and expensive" self-drill Step budgets, cached safe reads, async work, per-tool timeouts and explicit stop conditions dominate Deep dives: diagnose a slow or looping agent
Incident: refund tool called above the approval threshold Separate planner failure from gateway enforcement success; contain risky bulk plans Deep dives: investigate the refund near miss

The caveat to keep

  • 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.

Quick Recall: Lines to Say in the Interview

  • "The useful part is interpreting the request; the dangerous part is letting that interpretation become authority."
  • "The model proposes one bounded next action, never 'do everything'."
  • "Validator, policy, broker, idempotent gateway, receipt: the planner can't skip a box."
  • "Neither an email nor the model's confidence can authorise a refund."
  • "One injected sentence must never turn into a refund."
  • "Writes fail closed, and operators can revoke tokens and cancel queues mid-flight."
  • "The disagreement between operations, security and finance is the design problem."

Design walkthrough

The goal: useful automation where deterministic controls, not the model, govern identity, permissions, risk and irreversible effects.

30-Second Cheat Sheet

  • Open with the disagreement, not the feature list. Restate the ask as a testable outcome.
  • Autonomy differs by action class: a public FAQ lookup and a payment can't share one enable switch.
  • Six functional must-haves: separate planning from execution, validate, scoped short-lived credentials, approval for high risk, idempotent auditable effects, stop safely under uncertainty.
  • Nine components in dependency order. The gateway is the only write path; a proposal is not proof, the receipt is.
  • Four security controls as a set: untrusted observations, narrow credentials, validated output, bounded dangerous dimensions.
  • Policy engine unavailable → fail closed for every write. Say that row slowly.
  • Sizing: 50,000 users, 20 QPS peak, 10 actions/task ≈ 200 tool actions/s; 40 to 60 model calls/s in bursts.
  • Release gate: unsafe-action count and duplicate-effect count both zero before any autonomy expansion.

Opening line (source's version): "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."


1. Define an Autonomy Matrix for Actions

Open with the disagreement

  • Restate the ask as an outcome someone can test: enable useful automation while deterministic controls govern identity, permissions, risk and irreversible effects.
  • Ask questions that change what may be built, not ones that merely sound thorough.
  • Record what may run, what needs review and what is forbidden.
  • Autonomy differs by action class. A public FAQ lookup and a payment can't share one enable switch.

The seven questions that change the controls

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 must a human say yes? Which steps auto-run, wait for a person or never run. Don't 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 alone, must a manager approve a refund, 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 disputes a refund, can you prove what happened, and how long do you keep the proof? Ledger fields (who, proposal, policy, approval, receipt) and retention
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, how much autonomy you ship

Why "is email untrusted?" isn't on the list

  • The answer is always yes.
  • A message may carry instructions to override policy, exfiltrate data or trigger a tool. Tool output carries the same risk.
  • The design assumes it rather than asking.

What the answers decide

  • Reversibility and the money boundary: a control system with payment and escalation rules, or an assistant with a few tools.
  • The identity question sets blast radius.
    • Full-record access widens it.
    • 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.
  • The success metric (fewer handling minutes, higher resolution rate, lower error rate or better satisfaction) decides which metric the business inspects, and that sets how much autonomy is worth the risk.

Blast radius = the amount of damage one mistake can reach.

Map the people

User Workflow Failure they notice first What the agent gives them Approval needed
Business user Delegates inbox and case work, wants less manual handling The agent stalls or does the wrong thing to a customer Triage, drafts, prepared refund cases, closed loops on low-risk cases None for reads and drafts
Approver Decides when a risky action is allowed A refund executed without them, or a queue that never drains Approval record with reviewer, timestamp, rationale and the exact payload They are the approval
Security owner Defines identity, authorisation and audit rules A long-lived credential in a prompt, or a tool called on an injected instruction Scoped tokens, a policy gate outside the model, a tamper-evident ledger Signs off on each tool class
Tool and data owner Owns email, CRM, customer DB, refund service Their system called in unsupported ways, or duplicated writes Declared schema per tool, idempotency keys, per-tool concurrency limits Owns the revert procedure
Operator Monitors, retries, escalates No way to stop it, no way to explain a decision Kill switch, runbook, replayable decision record Runs containment

When the interviewer withholds answers

State assumptions ranked by risk:

  • No approval process defined → a conservative human gate on every irreversible action.
  • Retention unspecified → store enough to reconstruct any action; the exact period follows the customer's dispute and privacy policy.
  • Tenancy unclear → strict isolation and a separate authorisation check at every tool boundary.
  • The source's working defaults:
    • The CRM is the source of truth for customer context.
    • Refunds above a threshold require approval.
    • The agent may draft actions but can't execute high-risk steps unless the policy engine allows it.
  • Don't invent a permissive refund limit to complete the diagram.

The three answer tiers: where authority sits

Tier What it does Why it falls short (or wins)
Weak Connects the agent to email and CRM and lets it refund when it decides the customer deserves one The model is the authority, holds credentials not scoped capabilities, and nothing stops an instruction hidden in a ticket
Average Plans tool calls, checks permissions before each, requires approval for large refunds, logs everything, adds retries Still trusts tool output, never bounds loops or spend, retries without idempotency: one refund quietly becomes two
Strong Planner proposes one bounded action; typed schema validates; policy returns allow, block or needs-approval; broker mints a token for that single action; idempotent gateway guarantees one effect Tool observations are data; loops, spend, refund amounts and destinations all have hard ceilings

2. Make Safety and Performance Testable

  • A requirement the customer can't test is a preference.
    • "It should be safe" is a preference.
    • "No arbitrary command execution" is a constraint. Only the constraint changes the architecture.
  • Separate three kinds of statement:
    • Functional: what the system must do.
    • Non-functional: how safely and how well.
    • Non-goals: what it must never do.

The six functional must-haves (asked cold, 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; it gets 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 can't 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 → pause, escalate or fail closed. Never improvise.

Should-haves and could-haves

Should-haves (3), for the first usable version:

  • A declared registry with schema and data class for every tool, so an undeclared tool can't be called.
  • A kill switch that halts autonomous paths without a deploy, tested before launch.
  • Approval captured as a first-class record.

Could-haves (wait): richer policy expression, adaptive risk scoring, queued multi-step orchestration, replay tooling, operator dashboards, anomaly detection on action patterns, per-tenant policy overlays.

Non-goals, said out loud

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
  • Self-modifying policy logic

Constraints a test can fail

The numbers are illustrative interview figures, not measured production demand.

Constraint Stated so it can be tested
Latency 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, e.g. 99.5% of approval requests leave the queue within 2 minutes
Availability At 50,000 users and 20 QPS peak, 10 actions per task ≈ 200 tool actions per second. Reads parallelise; writes and approvals don't. Concurrency capped per user, per tool and globally
Cost Hard ceilings on tool calls per task, per-task spend, refund amount and allowable destinations. 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 Tamper-evident ledger records intent, policy decision, approval and outcome for every action. Every decision 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 Rapid global disable for the agent, a tool category, or both, without a deployment cycle

QPS = queries per second. p95 = the duration 95% of low-risk tasks finish within.

Every requirement has a control point and an owner

Requirement Control point Component
Separate planning from execution Plan/execute boundary Orchestrator that emits candidate actions but can't perform them
Validate tool name, arguments, identity, policy Policy gate Authorisation service with schema validation and allowlists
Scoped short-lived credentials Secret broker Token minting layer with time-limited, least-privilege credentials
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
  • If a row has no component, the requirement is a hope.

Two latency details that are easy to lose

  • Planner time and tool time get separate budgets: a slow model and a slow downstream API need different fixes.
  • p95 ≈ 15 seconds for low-risk tasks.
  • Human approval has its own rule: 99.5% of approval requests leave the queue within 2 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.

Spoken answer (source's short version): "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 planner, not the executor.
  • It reads task state and tool results, proposes one bounded action, and continues only after the policy, approval, gateway and receipt path completes.

The whiteboard version: seven steps (source figure 2)

  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; 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 stops a retry becoming a second side effect.
  7. Close the loop. Store the action receipt in the audit ledger and task state; continue planning only from the recorded result.

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.

Nine components in dependency order

  • The order they have to exist, and also the order they fail.
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 can't 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

Control plane vs data plane

  • Control plane: decides what the agent may do, under what conditions and with which approvals.
  • 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 three views:
    • Decision half (figure 3): user → authentication and delegated authorisation → planner proposes one bounded action → declared tool registry → validate schema before policy → policy decision.
      • Block → with a reason.
      • Approval needed → bound to snapshot and expiry.
      • Allow → with scopes.
      • Only an allowed or approved-and-revalidated action reaches the broker → token for one tenant, workflow, action and expiry.
    • Execution half (figure 4): scoped token + idempotency key → idempotent gateway → CRM, email, refund service, internal data → receipt to the tamper-evident ledger. A replay of the same proposal returns the existing receipt instead of a second call.
    • Both planes (figure 5): everything that decides, including the planner, is in the control plane. The data plane holds only the gateway, the systems of record and the outcome record.

Four trust-boundary sentences (say them verbatim)

  1. The user boundary ends at authentication.
  2. The planner boundary ends at proposing intent, not action.
  3. The policy boundary ends at allow, deny or approve.
  4. The execution boundary ends at a scoped, logged side effect in a downstream system of record.

Name the systems of record

System Owns
CRM Customer attributes and a support view of refund history
Refund or payment service Whether money actually moved; reconcile the CRM view against its transaction receipt
Email system Transport and inbox state
Internal data source Account and entitlement data
Task state store Workflow progress, not business truth
  • Caches may sit beside the planner or registry for low-risk lookups. They never become the source of truth for permissions or refunds.
  • Tool outputs stay untrusted data wherever they are stored.

Sync vs async boundaries

  • Synchronous: planning the next action and evaluating policy, because a person is waiting on a gating decision.
  • Tool execution: synchronous for one low-latency action; bulk and slow steps go through queues.
  • Audit writes: async only while the log never falls behind the point where a failure becomes unrecoverable.
  • Backpressure: when risk rises faster than capacity (approvers saturated), slow autonomous execution instead of letting risky actions pile up.
  • Partition by workflow or account: all actions for one account share a key, so two conflicting refunds can't run in parallel.

What watches the system

  • Ledger audits requests, proposals, policy verdicts, approvals and receipts.
  • Monitoring watches denials, unsafe actions, duplicate effects, approval delay and overrides.
  • Kill switch halts new calls, cancels queued work, revokes tokens and marks in-flight work (step 6).

4. Trace an Email-to-Refund Task

The request: "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. Verify who is asking and what delegation rights they hold. A support agent is not a finance approver.
  2. Plan the bounded next action. The smallest next step, e.g. "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: shape, missing fields, dangerous content, the amount, account and destination, and regulated data that changes handling.
  5. Evaluate policy and risk. Compare 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, 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 can't duplicate the refund.
  8. Record the result and decide whether to continue. The ledger stores input, policy result, approval outcome, tool result and side effects. The planner proposes another step only if the new state and evidence justify it; otherwise it stops.
  • The email text read in step 2 is an observation: 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.
  • Source figure 6 draws this as a sequence: the low-risk path mints a credential and executes directly; the high-risk branch requests human or workflow approval and mints the credential only if approved. Both end in record, then continue or stop.

The data model: never conflate proposal and receipt

Record Fields What it is
AgentTask id, actor, goal, state, step_budget Progress
ToolDefinition name, schema, data_class, scopes The legal operation
ActionProposal id, task_id, tool, args_hash, policy_decision A recommendation
PolicyDecision proposal_id, verdict, scopes, reason Authority
ActionReceipt proposal_id, idempotency_key, outcome Execution
  • A proposal is not evidence that a side effect occurred.

Idempotency done properly

  • Canonicalise arguments before hashing: 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.
  • Distinguish prepared, in-flight, confirmed and uncertain states.
  • If the downstream effect completed before the receipt was saved, reconcile through the same operation key, never dispatch a new write.
  • Durable business-action identifier: the source ties every refund to one built from case, customer and policy decision.
    • Two legitimate refunds with identical arguments are two operations and need distinct identities. This example is the casebook's 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 isn't enough on its own.
    • A lost response is an unknown outcome that needs reconciliation. Neither a prompt nor a generic retry makes it safe.

Idempotency key = an identifier that makes repeating the same request produce one effect, not two.

  • Schema validation runs before policy evaluation, so malformed or over-limit arguments are rejected before any authorisation logic runs.
  • If the policy point or broker can't be reached, the write doesn't proceed.

5. Hold Four Security Controls Together

Start from the hostile case

  • A message that looks like ordinary customer email is a prompt injection: ignore policy, pull a privileged record, issue an unauthorised refund.
  • Don't argue about whether the model understands the instruction.
    • Contain the blast radius.
    • Preserve the evidence.
    • Keep every irreversible action behind deterministic checks.
  • The model sees information; it does not inherit trust.

The four controls (learn 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, it can be manipulated by it. 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. Broker down → writes fail closed.
  3. Validate output before downstream use. The model may propose "refund $5,000"; 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.
  • Keep the units separate: $5,000 and $500 are the source's dollar validation example. 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 has four axes

Axis Better failure
Tenant A single-tenant outage beats a cross-tenant incident
Region A regional backlog beats a global write failure
Workflow A refund-workflow failure shouldn't block email triage
Dependency A broker outage shouldn't take down read-only analytics that can safely degrade

Defence in depth: six controls, no single one 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.
  • The operator can kill the workflow.
  • Asked for the single most important control? Name all six.
  • A prompt telling the model to refuse unsafe requests can sit on top, but it enforces nothing.

6. Decide How Each Failure Stops or Recovers

Design the failure path together with the happy path.

Five rules that organise every row

  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 a broad static secret to keep a demo alive.
Fails Behaviour
Prompt injection requests an unauthorised tool The illustrated scope violation is rejected by policy evaluation on the proposed action, independent of model judgement. Preserve message and proposal, then quarantine or review. Model never holds broad credentials. Also test harmful proposals inside the formal allowlist: those need 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 can't be confirmed. Never repeat a write blindly
Approval becomes stale before execution Approval is bound to a snapshot: tenant, record version, amount, expiry. Snapshot mismatch at execution → approval invalid, re-requested
Agent loops on the same action Attempt counter, backoff, circuit breaker that opens after repeated failure. N attempts without a state change → stop and escalate
Credential broker is unavailable Writes fail closed. Reads degrade only to a cached, non-sensitive path policy explicitly allows. Queue the work, notify the operator, keep the evidence. Never fall back to a broad static secret
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
  • Read the policy-engine row slowly: it's the row candidates most often soften.

Replay the injection (source figure 7)

  1. The planner still extracts a bounded action from the email.
  2. The registry marks the email content untrusted.
  3. The policy decision point rejects the illustrated attempt to expand scope.
  4. 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.
    • Review ambiguous financial intent.
    • An allowlist alone doesn't establish that the user wanted this particular refund.
  5. The ledger records the attempted injection. If the pattern repeats, the kill switch can disable the autonomous tool path.
  6. Legitimate proposals continue to schema, policy, approval and execution.
  • The control-plane split made concrete: the model may read adversarial content in the data plane, but that content can't rewrite policy in the control plane.

Lost responses, loops, stale approvals

  • Lost response = unknown outcome. Query the operation key or transaction record.
    • Confirmed → return the stored result.
    • Pending → continue reconciliation.
    • Unknowable → escalate.
    • Never turn a network timeout into permission to repeat a payment.
  • Repeated action → attempt counter. Cached safe observations, backoff, per-tool circuit breakers and a no-state-change limit prevent loops.
  • Stale approval → returns to review.
  • Missing durable evidence → stops continuation.
  • Audit may buffer async only while required intent and outcome are still recoverable. Persist sufficient intent before an irreversible operation.

What the kill switch really does

  • Stops new tool calls, cancels queued work, requests token revocation, marks in-flight tasks for rejection where downstream services support it.
  • A self-contained token may stay acceptable until expiry if the resource server doesn't check revocation state.
    • Measure propagation delay.
    • Require the gateway to check a current cancellation or authorisation epoch before each write.
  • A dashboard flag that only blocks new user requests isn't enough.
  • Limits (the casebook's qualification, not the source's):
    • A completed external effect can't be retracted by a flag.
    • A downstream API that ignores the in-flight mark needs reconciliation.
    • Document those limits and the downstream revert path.

Evidence and runbook before launch

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
  • Which external calls were made

The runbook tells an operator how to:

  • Quarantine a workflow

  • Revoke a capability

  • Replay a safe read-only step

  • 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: what happened, what was allowed, what was blocked, what the recovery path was.


7. Size the Work Behind Each Task

  • One request is not one unit of work.
  • Source planning anchor: 50,000 users, 20 tasks/s (QPS) at peak, 10 tool actions per task ≈ 200 tool actions/s.
  • Three layers of load:
    1. How often tasks arrive.
    2. How many tool calls, model calls and policy checks each task triggers.
    3. How many of those actions can change records, money or permissions.
  • Iterative planning bursts can create 40 to 60 model calls/s. Planner admission, model quota, adapters, approval queues and the ledger each need their own estimate.
Estimate Number What it forces
Planning decisions 20/s at peak; 40 to 60 model calls/s under iterative bursts The planner is a queueing problem before a throughput problem; size planner and tool adapters separately
Tool actions ~200/s at peak Reads parallelise; writes and approvals don't; concurrency caps must assume worst-case composition
Audit storage ~5 KB decision record and ~20 KB audit trail per task → 100 KB/s to 400 KB/s About 8.6 GB to 34.6 GB/day raw append-only data before indexing and replication
Planner compute ~1 s planner time per task → ~20 core-seconds/s at peak A throughput-constrained service with slack for tail latency

The estimate that matters most isn't CPU

  • It's the ratio of model time to tool time, plus how irreversible the tool effects are.
If… Invest in
Planning is fast and tools are slow Async orchestration, caching, queueing
Tool effects are high-risk Policy checks, staged execution, audit logging, even at some latency cost
Human review is the bottleneck Clearer escalation rules; fewer ambiguous cases reaching a person

Derive the risk tier before deciding autonomy (source figure 8)

  • Risk = Impact × Likelihood × Irreversibility. A qualitative aid, not literal arithmetic.
Tier This case's action Why
Fully autonomous Public FAQ read Low impact
Autonomous with preconditions CRM update Partly reversible, but misrouting a customer still costs something
Require human approval Refund Technically reversible, still meaningfully irreversible: customer dissatisfaction, accounting noise, abuse
Blocked entirely Some exports and permission changes Too dangerous to delegate

Sensitivity range, not 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?
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, keep safety controls identical

Check the audit arithmetic

  • At 20 tasks/s:
    • 5 KB decision record alone = 100 KB/s ≈ 8.6 GB/day.
    • 20 KB audit trail alone = 400 KB/s ≈ 34.6 GB/day.
  • The source quotes these as a range.
  • If every task writes both: 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.

Planner compute, read carefully

  • The source budgets ~1 second of planner compute per task → 20 core-seconds per second under a CPU-service interpretation.
  • Remote model serving is sized by request concurrency, token throughput and provider quota instead.
  • A one-second API wait is not a one-core compute requirement.

At 200 tasks/s and at 2 tasks/s

  • 200 tasks/s: find the first saturated component instead of multiplying every server count.
    • Partition by tenant or workflow.
    • Add backpressure.
    • Move long work to queues returning job IDs.
  • 2 tasks/s: simplify deployment, keep the safety controls identical.
  • Always:
    • Preserve ordering by account for conflicting writes.
    • Parallelise independent authorised reads.
    • Approvals and dependent writes follow state transitions.

Concurrency limits are a safety feature

  • Per user: nobody floods the system with parallel tasks.
  • Per tool: a noisy downstream system isn't overwhelmed.
  • Globally.
  • Value limits too: many low-risk reads 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

  • Unsafe actions and duplicate effects. The source requires both to be zero.
  • High tool success with 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. Record how much traffic and which attack tests stand behind it.
  • Compare denials, overrides, approval delays and task completion with baselines, so a nominally safe system doesn't quietly block every useful task.
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 can't 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 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

SLO = service level objective, the target you commit to internally. FDE = Forward Deployed Engineer.

Four dashboard layers

  • The customer is buying workflow improvement under control, not model accuracy.
Layer Measures
Technical health Tool success, duplicate effects, error rate, queue latency, denial rate
Model quality Task completion, approval rate and delay, how often a proposed action is later corrected
Adoption Override rate, usage by team, share of eligible requests routed through the agent
Business outcome Time to resolution, refund cycle time, backlog reduction, the customer KPI the workflow exists to move
  • A healthy service can still fail the business.
  • Read the layers together; one number has more than one cause.
    • A denial spike = guardrails stopping an attack, or a schema too restrictive.
    • An override spike = the model underperforming, or policy needing calibration.
    • Inspect examples before changing the gate.

KPI = key performance indicator.

Red-team as a release gate, not a stunt

  • Feed emails, documents and ticket text with adversarial instructions hidden in legitimate content.
  • Ask: can it be steered into calling tools it shouldn't, leaking context or skipping approvals?
  • The source's attack families:
    • 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.

Go/no-go for autonomy:

  • The obvious attack paths were exercised.

  • The policy layer rejected them.

  • The agent fell back to read-only or human review instead of improvising around the control plane.

  • A passing demo isn't evidence that these paths are safe.

Autonomy is earned in phases

  • Each phase's go/no-go is a claim about the controls, not about the model.
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. Gate: "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
  • Source figure 9 compresses it: read-only draft and classify → reversible writes → financial actions behind approval → red-team review and canary → 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.

Risk register

  • Each entry: risk, owner, mitigation, trigger, rollback. Reuse the shape for any de-risking question.
Risk Owner Mitigation Trigger Rollback
Prompt injection causes an unauthorised tool call Security reviewer Injection tests, allowlists, policy checks, read-only fallback Any confirmed unauthorised attempt Disable autonomous tool calls, revert to human review
Duplicate CRM writes after retries Reliability engineer Idempotency keys, reconciliation jobs, replay-safe contracts Any duplicated side effect Pause write traffic and drain the queue
Refund approvals stall operations Finance operations lead Approval SLAs, escalation path, reviewer training Delay exceeds target or queue depth climbs Narrow eligible refund scope or route more to manual handling

SLA = service level agreement.

Training, support and what to reuse

  • Users need to know what the agent can do, what it refuses, how approvals work, 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.
  • Shared services: approval service, idempotency layer, policy engine, credential broker, ledger.
  • Customer-specific, in configuration and adapters: CRM fields, refund rules, routing, thresholds.
  • The durable product asset is the control plane, not any one customer's wiring.

Quick Recall: Lines to Say in the Interview

  • "The useful part is interpreting the request; the dangerous part is letting that interpretation become authority."
  • "A public FAQ lookup and a payment can't share one enable switch."
  • "The planner can propose. Policy decides. The gateway is the only write path. A proposal is not proof; the receipt is."
  • "Validation runs before policy, so a $5,000 refund on a $500 limit dies before authorisation."
  • "Policy engine unavailable: fail closed for every write."
  • "A lost response is an unknown outcome. Never turn a timeout into permission to repeat a payment."
  • "Twenty tasks a second, ten actions each: about 200 tool actions a second, and the planner is a queueing problem first."
  • "Unsafe actions and duplicate effects both at zero gate every expansion of autonomy."
  • "The durable asset is the control plane, not one customer's wiring."

Technical deep dives

What this part covers: the follow-ups. Integrating hundreds of applications, a slow or looping agent, the refund near miss and the four trade-offs interviewers probe.

30-Second Cheat Sheet

  • REST, function calling, MCP and agent frameworks are layers of one system, not competing technologies.
  • Function calling strains with catalog size: ~20 functions is comfortable; 1,500 across 100 applications strains selection and prompt size. Scenario assumptions, not limits.
  • The tool registry loads only task-relevant servers and carries schema, data class and risk label for policy.
  • No application trusts the LLM; applications trust enterprise identity. Never forward an arbitrary bearer token downstream.
  • Slow and expensive? Bound steps before optimising. Measure, route, bound, cache safely. Never a bigger model and a longer budget.
  • Refund near miss: 18 planned, 6 blocked, 12 allowed, a €740 refund against a €250 limit. Separate planner failure from gateway success.
  • "No unauthorised money moved" ≠ "no money moved": audit the twelve allowed calls.
  • Four trade-offs, each resolved: flexible interpretation, deterministic execution; scope irreversible effects first; accept approval latency; gateway by default.

1. 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. Interviewers check whether you treat them that way.

The four layers

  • REST: ideal when the interface is stable, operations are deterministic and no reasoning is needed. A fixed workflow can call it directly.
    • A model doesn't natively understand authentication, endpoint discovery or request schemas, so REST alone never adds up to an assistant.
  • Function calling: the model selects a declared operation from natural language.
    • The axis that separates it from REST: who decides to make the call, fixed application code or the model. The wire call can be identical.
    • The cost isn't identical: another REST endpoint is cheap; another function the model must choose between costs prompt space and selection accuracy.
    • Source's numbers: about twenty functions as a comfortable example; 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 doesn't replace REST. The captured source describes MCP as JSON-RPC over stdio or Streamable HTTP; 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 doesn't grant business permission.
  • Agent framework: earns its place when a request needs multi-step reasoning.
    • "Prepare a renewal report for our top customers and email their managers" = find customers → retrieve CRM data → generate a report → store a PDF → send an email. No single function coordinates that.
    • Single agent: one tool, a short workflow, deterministic execution.
    • Multi-agent: planning across many domains with independent specialists.
    • Wrapping "Create a Jira ticket" in an orchestrator would be pure overhead.
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

Read the stack from the bottom (source figure 10)

agent framework (coordinates multi-step decisions) → MCP (discovers functions without 1,500 hardcoded schemas) → function calling (chooses one declared operation) → REST, SOAP or SQL (executes)

  • Execution never moves out of the REST, SOAP or SQL layer. Each layer above adds a decision, not a new way to write.
  • That's why the gateway and policy controls still sit in front of the bottom layer, however the call was chosen.

The tool registry makes it scale

  • Loading every MCP server up front doesn't.
  • The registry sits between the planner and the universe of servers and loads only those relevant to the current task, keeping the prompt small.
  • 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

  • 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.
  • Quotas per user and per application, with circuit breakers against runaway agents.
  • Long workflows async, returning a job ID.
  • Regional gateways, region-local MCP servers and data-residency controls.

Identity reaches every backend

  • No application trusts the LLM; applications trust enterprise identity.
  • Every request carries the user's identity, an OAuth token, RBAC or ABAC context and an audit record.
  • The gateway establishes the actor and tenant for the target resource, so the backend doesn't trust the model directly.
  • For HTTP MCP: validate token audience and use credentials issued for the receiving server.
  • Don't forward an arbitrary incoming bearer token to every downstream application. Exchange it, or use the approved delegated credential for each target.
  • 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.

RBAC / ABAC = role-based / attribute-based access control. Token audience = the server a token was issued for; any other server should refuse it.

Answering the reported Salesforce prompt

Part asked This design's answer
Loop Propose, validate, decide, execute, record, repeat, with a step budget
Tool interfaces The registry's typed schemas with data class and risk
Memory Task state store for workflow progress plus the ledger for what happened; neither is business truth
Orchestration The planner choosing one bounded action at a time over a queue partitioned by account
Safety Every layer below the planner

2. Diagnose a Slow or Looping Agent

  • The usual pivot after a good design: "the agent is slow and expensive".
  • Dominant driver: agent steps and tool calls, plus retries after failed or rejected actions.
  • An agent that acts must be bounded before it is optimised. The bounds already exist:
    • Cap the steps.
    • Make the common paths deterministic.
    • Cache read-only tool results within the request.
    • Let the approval gate stop the loop until a decision arrives.
  • Don't answer by giving the loop a bigger model and a longer budget.
  • Trace separately: model planning, downstream tool wait and approval delay. Each points to a different lever.
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, same pivot

"The agent keeps calling tools repeatedly" "The tool-calling workflow times out"
Symptom Repeats a CRM lookup or retrieval until the request times out An external workflow exceeds the response deadline
Ask Which tool repeats, which observation triggers it, is state preserved between steps? Which tool is slow, can it run async, is the result needed immediately?
Likely causes Poor stopping condition, ambiguous tool descriptions, missing memory, failed parse, no result cache Slow external API, serial calls, no timeout budget, synchronous side effects
Investigate Trace for repeated tool-and-observation pairs; find the missing state transition Trace the calls; find the critical-path dependency
Now Max steps, cache the tool result, improve the schema, add a deterministic route Per-tool timeouts, parallelise read-only calls, clearly limited partial answer or async job ID with status
Later Agent budget tests and trace-based loop detection Dependency SLAs and circuit breakers
Prevent Unit tests for tool selection and loop prevention Workflow design review before adding tools

Spoken answer (looping): "I would treat this as a control-loop bug. The fix is step budgets, better tool routing, cached results, and explicit stopping criteria."

  • Spoken answer (timeout): "A tool timeout is not always an LLM issue. I would redesign slow side effects as async and keep the user informed."

Four verbs, in order

  1. Measure: trace and attribute cost first.
  2. Route: match the model and path to the risk.
  3. Bound: limits on steps, tokens, timeouts and budgets.
  4. Cache safely: tenant, permission and version in the cache key, so one user's cached result never answers another's request.

Deliver it in six moves

  1. Frame the business impact.
  2. Decompose the path.
  3. Name the largest measured driver.
  4. Fix it safely.
  5. Prove it with before-and-after numbers.
  6. Prevent recurrence.
  • Proof metrics: steps per task, tool latency, retries, timeouts, cost per task.

Unit economics: the model-to-tool ratio decides the lever

When… Lever
Planning is expensive Batch safe reads into one planning pass
Tool calls dominate Cache safe reads and prefetch context
Human time is the cost Improve proposal clarity and risk classification; tighten the threshold so only high-value cases reach a person
  • Never bypass a required approval to save time.

3. Investigate the Refund Near Miss

  • The trap: saying there was no problem because the gateway blocked it.
  • Work through it as detect → contain → root cause → prevent.

The setup

  • 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 refund_customer for eighteen orders, several above the threshold, including a €740 refund with no approval.
  • The gateway blocked the high-value calls.

The source's trace, 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

Line What it shows Story
Planner (warn) 18 planned calls to refund_customer, policy refund_policy_v3, model agent_planner_2026_07 The plan
Gateway (critical) €740 refund vs €250 no-approval limit, approval_state=missing, policy_decision=deny Enforcement working
Safety evaluator (warn) 6 blocked, 12 allowed, safer alternative create_refund_review_ticket, compliance score 0.42 The planner failing
  • Those lines tell two different stories.
  • The source states that no unauthorised money moved.
  • But the twelve allowed calls passed the gateway, so they may have executed. "No unauthorised money moved" ≠ "no money moved".
  • The trace alone can't say whether those twelve refunds were legitimate, which is why containment includes auditing them.

Contain immediately

  1. Disable bulk refund planning.
  2. Force all VIP refund actions into review-ticket mode.
  3. Add a user confirmation step for financial actions.
  4. Audit the twelve allowed calls to confirm the smaller refunds were legitimate.
  5. Preserve the proposals, policy context, schema and gateway records.

Root cause

  • 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.
  • 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, not 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: a fraud and unauthorised-action risk, not only a quality bug.

How it's graded

  • Weak answer: "the tool was blocked, so there is no problem; I would tell the agent to be more careful".
  • The source scorecard rewards four things:
    1. Reading planned, blocked and allowed calls with role, amount and approval state.
    2. Separating planner failure from gateway success.
    3. Auditing the plan, policy context, schema and gateway logs rather than editing the prompt.
    4. Naming the fraud and unauthorised-action risk.

Spoken answer (from the practice answers in the full casebook): "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."


4. Make Trade-offs Explicit

  • Interviewers probe exactly four pairs. Each has a resolved shape: give a little on one side to protect something specific on the other.
    • Flexible interpretation turns 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: acceptable when the alternative is uncontrolled financial authority.
    • A central gateway gives one enforceable write path; direct integrations multiply validation and audit responsibilities.
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: the one place for auth, policy, audit, idempotency and schema validation. Direct integrations multiply the places a bad prompt can reach a write API

5. Source References


Quick Recall: Lines to Say in the Interview

  • "REST, function calling, MCP and agent frameworks are layers of one system, not competitors."
  • "A tool protocol standardises discovery; it doesn't grant business permission."
  • "No application trusts the LLM; applications trust enterprise identity."
  • "An agent that acts must be bounded before it is optimised."
  • "Measure, route, bound, cache safely, with tenant, permission and version in the key."
  • "A tool timeout is not always an LLM issue."
  • "The gateway prevented loss, but the planner attempted unauthorised high-value refunds."
  • "No unauthorised money moved isn't the same as no money moved: audit the twelve allowed calls."
  • "Flexible interpretation, deterministic execution."

Quick review

One sentence: the model proposes; deterministic systems decide; the idempotent gateway executes once and records a receipt.

30-Second Cheat Sheet

  • Name the disagreement between operations, security and finance in the first two minutes. It is the design problem.
  • Business systems own truth. Workflow state owns progress.
  • Four controls: untrusted observations, narrow credentials, validated proposals, bounded dangerous dimensions.
  • Fail writes closed on missing policy, credentials or durable evidence. Reconcile lost responses, never repeat them.
  • Sizing: 50,000 users, 20 peak tasks/s, 10 actions/task, 40 to 60 model calls/s in bursts.
  • Zero observed unsafe and duplicate effects gate each expansion.
  • Near miss: 18 planned, 6 blocked, 12 allowed, €740 vs a €250 no-approval limit.
  • Reusable control plane: policy, broker, approval, gateway, ledger. Customers bring adapters and configuration.

1. Recall the Proposal-to-Receipt Contract

Ask first

  1. Which actions are reversible?
  2. Where does the money boundary sit?
  3. Whose identity does the agent act as?
  4. What needs approval?
  5. Which systems are the record?
  6. What must audit keep?
  7. How do we stop in-flight work?
  8. What is the peak task and tool load?

The request path

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 → decide whether to continue

  • Business systems own truth. Workflow state owns progress.

Controls and records

  • Keep observations untrusted, credentials narrow, proposals validated, dangerous dimensions bounded.
Required record What it is
Task Progress
Tool definition The legal operation
Proposal A recommendation
Policy decision Authority
Approval Human sign-off bound to a snapshot
Receipt Proof of execution
  • Recheck approval snapshot and expiry.
  • Fail writes closed on missing policy, credentials or durable evidence.
  • Reconcile lost responses instead of repeating them.

Numbers and scale

Item Value
Users 50,000
Peak tasks 20/s
Actions per task 10
Model calls in bursts 40 to 60/s
  • These are the source's assumptions.
  • 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.

Rollout

  • Read-only comes first.
  • Then reversible CRM writes with proven rollback.
  • Money stays 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 can't undo completed effects.

The two pivots

Refund near miss:

  • Eighteen refunds planned, six blocked, twelve allowed.
  • The €740 request exceeded the €250 no-approval limit.
  • Distinguish the planner's unsafe proposals from the gateway's successful denial.
  • Audit the twelve allowed operations as well as the six blocked ones.

Slow or looping work:

  • Trace → route known intents → bound steps and retries → cache safe reads (tenant, permission and version in the key) → move slow effects to async jobs.
  • Never extend an unbounded loop to make it more capable.

Reuse and the final mental model

  • 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 → stop or repeat within budget.

Closing line: "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."


Flashcard Drill


Quick Recall: Lines to Say in the Interview

  • "The model proposes; deterministic systems decide; the gateway executes once and records a receipt."
  • "Business systems own truth; workflow state owns progress."
  • "Fail writes closed on missing policy, credentials or durable evidence."
  • "Reconcile a lost response; never repeat it."
  • "Twenty tasks a second, ten actions each, forty to sixty model calls a second in bursts."
  • "Zero unsafe and zero duplicate effects gate each expansion."
  • "Eighteen planned, six blocked, twelve allowed: audit the twelve."
  • "A kill switch withdraws authority but can't undo completed effects."

Where next

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