Guardrails the agent can’t talk its way around
Agents take actions nobody asked for, in the wrong order, past approvals that live in a prompt. Put the checks that matter in code on the path to the side effect, where the model can’t argue with them.
The user asks to refund a damaged item, and the agent also cancels the rest of the order “to save them the trouble.” The agent sends the refund confirmation, then finds out the refund call failed. A reviewer approves “refund $42.50,” the agent re-plans, and a different refund goes out under the same approval.
None of these needs a malicious model. It only needs a helpful one under pressure, or one that read a web page with instructions in it. Anthropic’s system card for Claude Opus 4.6 describes the model as at times overly agentic, taking risky actions without first seeking permission. In computer use tests it kept doing so even when the system prompt actively discouraged it. Assume yours will ignore an explicit instruction sometimes, and build so that it doesn’t matter.
So every rule that matters also runs as code on the path to the side effect. That takes two kinds of control: checks on what the agent plans, and approvals bound to exactly what it does. The examples use a store support agent that issues refunds and emails customers.
Name the failure so you can count it
I call the planning failures off-spec behavior, and I define it narrowly so it can be counted. A run is off-spec if the agent did at least one of these:
- Used the wrong tool: called a tool that doesn’t serve the request, when a correct one existed.
- Acted outside the request: changed something the user didn’t ask to change.
- Did steps in the wrong order: took an action before something it depends on was true.
Each kind has a different cause and a different fix. The usual fix, a longer system prompt, treats all three as one problem and fixes none of them reliably.
Off-spec lives in the trajectory. A run can end with a perfect reply and still contain an action nobody asked for. So label a sample of traces with which kind occurred, count the tags, and fix whichever kind dominates first. Then turn each tag into a CI assertion, so a prompt edit or a model swap that brings one back fails a test. The checks below double as labelers: run them over production traces after the fact and the hand-labeled sample becomes a number you can watch every day.
Wrong tool: schemas help less than you think
Overlapping tools and error messages that steer the model toward a write are covered in the ChatGPT post: fewer visible tools, descriptions that say what not to use them for, and errors that point at reads.
Strict schemas are the other usual fix. Structured outputs scored 100% on OpenAI’s schema-following eval, against under 40% for an older model without it. That guarantees a well-formed call, not the right one, and constrained decoding has a trap. If reason must be one of five enum values and none fits, the model can’t say so. It picks the closest wrong value, confidently. Give every enum that classifies intent an unsupported and an ask_user value, and route on them.
Outside the request: check the plan against the request
Scope creep is hard to catch in review because each extra action is defensible on its own. The fix is to have the agent commit to a plan as data before it acts, then check that plan in code.
The catch is who decides what the request was. If the planner also lists the request’s entities, it will list the order it wants to cancel, and the check passes. So extract the scope in a separate call that sees only the user’s message, with no tools and no tool output, or take it from what the user selected in the UI. The planner gets that scope as read-only input.
{
"scope": {
"entities": ["item:A-1001/2"],
"actions": ["refund"]
},
"plan": [
{ "tool": "check_refund_policy",
"args": { "order": "A-1001" } },
{ "tool": "create_refund",
"args": { "order": "A-1001", "items": ["A-1001/2"] } },
{ "tool": "send_email",
"args": { "order": "A-1001",
"template": "refund_issued" } }
]
}
scope comes from the extractor and is read-only. plan comes from the planner.
Two checks run before anything executes. Every write must target an entity in scope. Entities derived through a short, fixed list of relations (an item derives its order, an order derives its customer) can be read or notified, never written. Without that list, derivation quietly expands to everything the customer owns. Every write must also be an action kind in scope, and implied actions come from a fixed map in code: a refund implies a notification, and nothing implies a cancellation.
This runs in code because the model can’t judge its own scope. Ask the model that proposed the cancellation whether it’s in scope and it usually says yes.
Wrong order: make it unrepresentable
“Always check the policy before refunding” in a prompt gets ignored sometimes. A create_refund that requires a policy_check_id, which only check_refund_policy can mint, can’t succeed out of order.
def create_refund(
order: str,
items: list[str],
policy_check_id: str,
): ...
The tool checks that the ID exists, is fresh, and covers this call: the same items, at or under the amount the check approved. A token that only proves “some check ran on this order” can be reused to refund a different item or a bigger amount. Skip the check and the call fails with an error that names the tool to call first.
Repair, but bounded
Plans fail validation. The model invents an order ID or puts the email before the refund. Send the errors back, let it fix the plan once or twice, then stop and tell the user what couldn’t be done. Send every error at once. A validator that returns only the first one invites oscillation: fix A, trip B, fix B, bring back A.
The nastier failure is the repair that passes. The policy rejects the refund step, so the model deletes the refund and keeps the email. The new plan validates cleanly and tells the customer their refund is on the way. A repaired plan needs a coverage check as well as a validity check: it still does every action in scope, or it says plainly which one it can’t do.
Gate the effect, not the tool
Validation catches bad plans. Approval covers plans that look fine and still need a person. The common setup: create_refund needs approval and everything else runs freely. Then someone adds update_order, and status: "refunded" issues the refund. Or the agent has a general HTTP tool, or a code tool that can import the payments SDK. OWASP calls this Excessive Agency and recommends human approval for high-impact actions, which is right and thin on detail.
Put the gate in the client that holds the credential for the external system. Every path that can move money or reach a customer goes through one function, and that function asks the policy engine. If the agent’s runtime holds the credential, any tool that can reach the network is a bypass, and code execution is the widest one. Take it away from agents that touch customer data, or run it with no credentials and no egress except through gated endpoints. Simon Willison’s lethal trifecta is the test: private data, untrusted content, and a way to send data out. Two outbound paths aren’t tools at all. A chat UI that renders Markdown fetches any image URL the model writes, and the query string can carry whatever it just read, so allowlist the image hosts. And the approved email body itself can carry data out.
Bind the approval to the exact action
The reviewer approves “refund $42.50 to order A-1001.” Too often the system stores approved = true on the run. Now the agent can re-plan after approval and issue a different refund, or the same one twice, and the gate waves both through.
Store the grant against a hash of the canonical action: tool, target and every normalized argument, plus the version of the policy rules for that kind of action. Hash the whole policy version instead and every unrelated policy deploy invalidates every pending approval. Recompute the hash at execution and refuse on a mismatch. Grants are single-use and expire.
action = canonical({
"tool": "create_refund",
"order": "A-1001",
"amount_cents": 4250,
"policy": policy.version_for("refund"),
})
grant = approvals.get(run_id, sha256(action))
if not grant or grant.used or grant.expired(now):
raise NeedsApproval(action)
payments.refund(
order=action["order"],
amount_cents=action["amount_cents"],
idempotency_key=grant.id,
)
grant.mark_used()
Single-use gets hard once crashes enter. Mark the grant used before the call and crash mid-call, and the retry finds a spent grant for a refund that may have landed. Mark it after, and a crash in between lets it run twice. The way out is in the code above: the grant ID is the idempotency key for the external call. A retry under the same grant reaches the payment provider with the same key and gets the first refund back. Keep the grant’s expiry shorter than the provider’s key retention, or that guarantee quietly lapses. And if a retry finds the grant expired, look the refund up by its grant ID before asking a person again, because a fresh grant means a fresh key.
Then deal with time. “Refund every order in yesterday’s failed shipment” is the same string at 4pm and 9am, but the batch can grow overnight. Resolve the action to concrete values before asking (the order IDs and the exact total), approve those, and re-check them at execution. If they drifted, ask again.
Render the approval card from data
If the model writes the approval text, the approval text is an attack surface. An injection doesn’t have to beat the gate. It only has to get the model to describe a harmful action in harmless words. “Send the customer their refund confirmation” can sit on top of a phishing link to an address the customer never gave you.
Render the card from the action’s arguments, in code. The amount is the integer in the call, formatted by your code. The preview is the real recipient and body as plain text, with every link expanded to its real host and the body diffed against the approved template. The model’s explanation can appear below the facts, labeled as the model’s.
The plan helps here too. It records which arguments were fixed before the agent read any untrusted content, so anything filled in later is untrusted by construction, and the card can say so: “recipient taken from an inbound email.”
Ask less so people keep reading
Approval fatigue is a security bug. If every action needs a click, reviewers stop reading by Wednesday. Write a policy that proves most actions safe: refunds under a threshold inside the return window, emails from a template a person already approved, drafts that never leave the system. Auto-approve those with a recorded reason, and the queue gets small enough that people read each card.
That only works if the policy is code with unit tests, not rules in a prompt the model weighs against the user’s request.
Every check is also a place the agent can refuse something reasonable. Put false refusals on the same dashboard as off-spec actions. Tightening a check to cut one raises the other, and you want to see the trade.
Read your framework’s resume rules
Pausing for a person can double a side effect. In LangGraph, interrupt() pauses a node, and on resume the runtime reruns the whole node from the top, the same rule as checkpoints. A node that creates the refund record and then interrupts for approval creates it twice. Resume values are also matched to interrupt() calls by their order within the node, so make one interrupt conditional and every later answer lands on the wrong question. Keep one interrupt per node, with nothing before it that has a side effect, and treat the resume value as untrusted input: an approval for this action hash, from someone allowed to give it.
Fail closed, and keep the agent out of the approval path
The policy service is down: deny. Then decide what the denied action does when it comes back. Resume it automatically and a refund evaluated against hour-old data runs as if nothing happened. Expire it and the customer who heard “we’re processing your refund” never gets one. I send it back through the policy as a new request, re-resolved from scratch, and tell the user it’s delayed.
If any tool can reach the endpoint that grants approvals, the model can approve itself. Keep that endpoint behind a credential the agent’s runtime never holds, and alert on any agent identity that calls it. Decide on purpose, per action class, whether the person who asked for the action can also approve it.
Re-planning costs you a guarantee
Plan-first has a cost: the world changes mid-run. The policy check comes back “partial refund only,” and the plan assumed a full one. The design patterns paper from Beurer-Kellner and colleagues prizes plan-then-execute because tool output can’t add actions to a plan fixed before the agent read it. Google DeepMind’s CaMeL goes further and separates control flow from untrusted data entirely. In the paper’s current version it solved 77% of AgentDojo’s tasks with provable security, against 84% undefended. I’d pay those seven points on any agent that moves money.
If you allow re-planning, the new plan goes through every check the first one did, from scratch, including approval. The new plan was written after the agent read tool output, so the injection guarantee is gone. What’s left is a bound: the scope check limits an injected instruction to in-scope actions on in-scope entities, and the approval card shows a person the exact arguments inside that bound.
I still write the rules into the prompt. A model that knows them makes fewer attempts for the code to catch.
Sources
- Anthropic, Claude Opus 4.6 announcement and system card (February 2026)
- OpenAI, Introducing Structured Outputs in the API (August 2024)
- OWASP, LLM06:2025 Excessive Agency
- Simon Willison, The lethal trifecta for AI agents (June 2025)
- LangChain, LangGraph interrupts
- Beurer-Kellner et al., Design patterns for securing LLM agents against prompt injections (June 2025)
- Debenedetti et al., Defeating prompt injections by design (March 2025)