How to prevent AI agents from taking irreversible actions

By

Updated

Tagged: AI

A practical architecture for AI agents that spend money, deploy code, delete data, or change infrastructure without turning confirmation into a suggestion.

I used an AI agent to buy hostingpicker.dev through the Cloudflare Registrar API. It cost $12.20, the registration went through immediately, and there’s no refund on a domain purchase.

The API call itself was a few lines. What took real work was making sure the agent couldn’t buy the wrong domain, approve its own purchase, reuse an old price, or retry a request that might have already gone through.

Domains are just one example. We’re giving agents tools that can:

  • spend money
  • deploy code
  • delete data
  • change DNS
  • send email to thousands of people
  • create infrastructure
  • publish content

You can’t protect any of those with “always ask me first” in the system prompt. The model may follow it, or it may not, because a prompt is only advice. A safety boundary has to be code the model can’t get around.

I built that boundary for my Cloudflare Domains Toolkit. In this post I want to take it apart and show the parts you can reuse for any irreversible action.

The rule

I started with one sentence:

The agent can search and prepare. A person approves the exact live action.

Everything else in the design comes from that. The agent can suggest domains, check if they’re available, work out the price, and prepare a quote. None of that gives it permission to buy. The purchase needs a separate approval from me, tied to one exact domain and one exact amount. I think the same rule applies when AI agents shop for us.

Confirmation is not a boundary

This tool is unsafe:

async function buyDomain(domain: string) {
  const confirmed = await agentAsksUser(
    `Buy ${domain}?`
  )

  if (confirmed) {
    await cloudflare.register(domain)
  }
}

The problem is that the agent writes the question itself. It can leave out the price, ask before checking the final state, or read “hmm, I guess” as a yes.

On top of that, buyDomain() still accepts any string, so nothing ties your answer to the domain that gets registered. A second call with a different domain goes right through. Your “yes” is just a chat message that approves nothing specific.

Start with the threat model

Before writing any tools, list how the action can go wrong. For a domain purchase:

  1. The agent chooses the wrong domain.
  2. The domain contains confusing Unicode characters.
  3. The displayed price excludes a required multi-year term.
  4. Availability changes after the first check.
  5. The price changes before registration.
  6. One quote is submitted twice.
  7. Two concurrent calls use the same quote.
  8. The request succeeds but the response is lost.
  9. The agent retries and creates another unwanted action.
  10. A broad API token lets the tool change unrelated account state.

Some of these are the model getting it wrong. Others, like a lost response or two concurrent calls, happen even with no AI involved. Your safety boundary has to cover both.

Give the agent narrow capabilities

My Registrar MCP server exposes four tools:

search_domains
check_domain
quote_domain_purchase
purchase_domain

DNS management lives in a separate command-line tool with its own API token. The registration token can’t touch DNS, and the DNS token can’t buy anything.

That’s least privilege, and it also keeps the code simpler. The purchasing server does one thing, uses one credential, and has just one dangerous tool to protect.

What I avoided is a generic tool like this:

cloudflare_api_request(method, path, body)

That looks convenient, but in practice it gives the agent permission to do anything the token allows, and you can’t reason about what it might call. Give the agent tools named after what you want it to accomplish instead of handing it a raw HTTP client.

Separate discovery, preparation, and execution

The four tools split the workflow into three phases:

DiscoveryPreparationHuman approvalExecutionVerification

Discovery is loose: the agent searches, tries ideas, and checks what’s available, and nothing here can spend money. Preparation is where things get strict, validating one exact domain, pricing it, and writing it down as a quote. Execution takes that quote, checks the live state again, asks a person to approve it, and runs that single purchase.

The same split works for other tools too. A deploy tool can inspect the changes, prepare one immutable release, and promote only that release (keeping deploy credentials out of the agent’s working copy, which I covered in How to protect secrets when coding agents deploy your app). A deletion tool can search records, prepare the exact IDs along with the impact of removing them, and then delete only that set.

The server owns policy

The model never decides whether an action is allowed. The server enforces that in code.

For the domain tool, the server requires:

  • plain ASCII domain names
  • one exact registrable domain
  • prices in USD
  • no premium domains
  • a maximum initial charge of $20
  • complete minimum registration term pricing
  • auto-renewal disabled
  • a five-minute quote lifetime

The agent can explain these rules to me, but it can’t change them or talk the server out of them.

The same idea applies to a deploy tool. If production requires a green test suite, the tool checks the test result itself instead of asking the model whether the tests look fine. Models are good at judgment calls, like picking a domain name that reads well, while rules that must always hold belong in plain code.

Represent money without floating point

Cloudflare returns prices as decimal strings, so the server converts them to integer cents right away:

function parseUsd(value: string) {
  const [dollars, cents = ''] = value.split('.')

  return Number(dollars) * 100 +
    Number(cents.padEnd(2, '0'))
}

With that in place, the $20 limit becomes a plain integer:

if (initialChargeCents > 2000) {
  throw new Error('Purchase exceeds the safety limit')
}

That avoids floating-point comparisons around a billable action. The server also calculates the full initial charge up front. Some domain extensions require more than one year, so the first payment can include a registration year plus required renewal years, and the value shown for approval has to match what the provider will charge.

A quote is a temporary decision record

The preparation phase creates a quote:

type PurchaseQuote = {
  id: string
  domain: string
  currency: 'USD'
  registrationCents: number
  renewalCents: number
  years: number
  totalCents: number
  autoRenew: false
  expiresAt: number
  status: 'available' | 'consumed'
}

The quote records every value that matters, and it’s the exact thing you’ll be asked to approve.

The purchase tool doesn’t accept a price or a number of years as free-form input, because then the caller could pass anything. Instead, the caller passes the quote ID and repeats the public values, and the server checks them against its own copy. If anything differs, the purchase stops.

Quotes expire after five minutes and live in memory, so a restart wipes them. That’s fine, since a quote doesn’t reserve anything and only records one short-lived decision.

Recheck external state before approval

Availability and prices can change between creating a quote and running the purchase, so the execution phase asks Cloudflare again:

check availability
check registration price
check renewal price
check minimum term
recalculate complete initial charge

If any value changed, the server rejects the quote and the agent has to prepare a new one. That closes a time-of-check/time-of-use gap: you don’t want someone approving an old $12.20 quote when the live charge is now $120.20.

The order matters here:

prepare quote
wait
recheck live state
show approval
execute immediately

Don’t ask for approval first and refresh the values afterward.

Put approval at the protocol boundary

For the final decision, I use an MCP form-mode elicitation. In the 2026-07-28 MCP protocol, the tool returns an input_required result containing the elicitation. The client shows the form, collects the answer, and retries the original tool call with the response attached.

The wire format changed from the earlier version of the protocol, where the server sent a request to the client, but the important part didn’t change: the MCP client draws the form, not the model.

The server asks the client to show a structured form containing:

  • exact domain
  • exact total charge
  • registration term
  • non-refundable warning
  • auto-renewal state
  • an unchecked approval box

The elicitation response distinguishes three actions:

accept
decline
cancel

The retried call only continues when the answer is accept and the approval box is true. The server checks those returned values itself instead of assuming the form schema took care of it.

If the client can’t show the form, the purchase tool fails. There’s no environment variable or “trusted mode” to skip approval. A client that can’t ask the question doesn’t get to buy domains.

Approval content is part of the security design

A form that just says “Continue?” is useless. I should be able to make the decision from the form alone, without scrolling back through the chat to figure out what the agent is about to do.

The form has to answer these questions:

What will happen?
Which exact resource is affected?
How much will it cost?
Can it be undone?
What happens later?

What goes into “what happens later” depends on the action. For a domain purchase, that includes auto-renewal. For a deployment, it includes the target environment and release identifier, and for a deletion, it covers the count and type of records being removed.

Consume single-use state before waiting

My first implementation marked the quote as used after approval, like this:

const approved = await requestApproval(quote)
quote.status = 'consumed'

That introduces a race condition. Two purchase calls can reach requestApproval() before either one consumes the quote, and the client can end up showing two forms for the same quote.

The fix is small: mark the quote used before you await anything:

quote.status = 'consumed'
const approved = await requestApproval(quote)

If the person declines, the quote stays used and the agent has to prepare a new one. Creating a new quote is free, whereas a single-use quote that can fire twice costs real money.

In a multi-process server, an in-memory assignment isn’t enough, so use an atomic database update instead:

UPDATE purchase_quotes
SET status = 'consumed'
WHERE id = ?
  AND status = 'available';

Only continue when the query updated one row.

An ambiguous result is not a failed result

Imagine the registration request reaches Cloudflare and buys the domain, but the connection drops before the response comes back. The client sees an error, and you have no way to know whether the purchase went through.

Retrying automatically could repeat a billable or destructive action, so the server leaves the quote consumed and reports an ambiguous outcome. Before anyone tries again, a person has to check the account state directly.

This distinction applies to many systems:

explicit rejection → safe to report failure
confirmed success → safe to report success
connection lost after sending → outcome unknown

If the external API supports idempotency keys, use one stable key for the logical action so a retry returns the original result instead of running it a second time. Without idempotency keys, a retry loop only hides the fact that you don’t know what happened.

Verify the result separately

A 200 from the API is a good sign, but the account is the source of truth.

After execution, record:

  • quote ID
  • exact requested action
  • provider request or workflow ID
  • approval time
  • execution time
  • response state
  • verification state

Then query the provider as a separate step after the call returns, rather than folding verification into the success response. Check that a purchased domain appears in the account, that a deployment’s promoted release passes health checks, or that deleted records are gone.

Test the boundary without the real capability

Your policy tests shouldn’t touch production credentials. Put the provider behind a small interface so you can swap it out:

interface RegistrarClient {
  checkDomain(domain: string): Promise<DomainState>
  createRegistration(
    domain: string,
    years: number
  ): Promise<RegistrationResult>
}

With that interface in place, the test suite runs against a fake implementation that can simulate:

  • a price change
  • a domain becoming unavailable
  • a required multi-year term
  • a timeout after receiving the request
  • two concurrent purchase calls
  • a duplicated quote

Write a test for each of those cases.

In my tool, the live purchase came last, after the policy and protocol tests passed. That one real run was the only way to see the MCP client show the approval form at the right moment.

A reusable state machine

You can model the whole action as a state machine:

discovered
    ↓
prepared
    ↓
rechecking
    ↓
awaiting_approval
    ↓
executing
    ↓
confirmed | rejected | outcome_unknown
Fig 1 · 1/6Purchase
discovered · search and check, no charge

Don’t collapse outcome_unknown into rejected, and don’t move from awaiting_approval back to the same prepared capability. Create a fresh decision record instead.

The server handles every valid transition one step at a time, and the model never sets a state directly.

Applying the pattern elsewhere

First, you need to decide which actions require this flow. Most of the time that’s a fixed list in code: deploy, send, delete, pay. When requests arrive as free text, a small classification model like Jev can label them as reversible or irreversible. Treat that label as a safety net that sends more actions to approval, never as a reason to skip it.

If you apply this to a production deployment, the decision record might look like this:

repository
commit SHA
build artifact digest
environment
test result
rollback target

An email campaign uses its own fields:

list ID
recipient count
subject
content digest
scheduled time
unsubscribe configuration

Deleting customer records fits the same pattern:

tenant ID
record IDs
record count
backup state
retention consequence

The fields depend on the action, but the steps don’t change:

  1. Give the agent a narrow capability.
  2. Separate discovery from execution.
  3. Prepare one immutable decision record.
  4. Enforce policy in code.
  5. Recheck changing external state.
  6. Show the exact consequences to a person.
  7. Consume approval capability atomically.
  8. Execute once.
  9. Preserve ambiguous outcomes.
  10. Verify and audit the result.

What approval does not solve

Human approval isn’t a complete security system on its own. People approve the wrong thing all the time, and repeated prompts quickly lead to confirmation fatigue. A compromised MCP client can show misleading details, a compromised server can ignore its own policy, and stolen provider credentials bypass the agent workflow altogether.

You still need other boundaries around it:

  • narrowly scoped credentials
  • hard spending and resource limits
  • provider-side roles
  • separate production accounts
  • audit logs
  • alerts for sensitive actions
  • credential storage outside prompts and source code

Approval only connects one human decision to one prepared action, so it has to sit on top of those other safeguards.

What I took away from this

Just because an agent knows how to call an API doesn’t mean it should. The model is good at exploring options, explaining trade-offs, and preparing the work, while your code decides what’s allowed and a person answers the one question left at the end.

With that split in place, you get useful agent tools without trusting the model as an operator. In this project, the Cloudflare API call was the easy part, and most of the work went into the boundary around it. For the broader list of what I let run alone and what I never do, see things I let coding agents do unattended.

If the process can die before you answer, store the exact proposal so it isn’t lost. I built that in an agent approval flow that survives a restart.

Want me to talk about your product? You can sponsor this site.

Related posts about ai: