The Complete Guide

The Spend Firewall for AI Agents

An autonomous AI agent with a payment method and no spending limit is one infinite retry loop away from a $12,400 bill. A spend firewall is the control layer that sits in front of every transaction the agent attempts, evaluates it against your rules, and returns approve, block, or flag before a single dollar moves.

The 2am problem. At 2:14am your agent hits a rate-limit and retries a purchase 40 times. At 2:15am it buys compute from a vendor you've never heard of. At 2:31am it tips an API into an overage tier. At 9:03am you wake up and find out from Stripe. Total: $12,400. Every layer of your stack worked exactly as designed — the only thing missing was a guardrail that said "stop."
<5mspre-spend decision latency
6rule types every agent needs
53/53eval scenarios passing
Contents

1. What a spend firewall is

A spend firewall is a deterministic control layer that sits between an autonomous AI agent and any action that would move money — an API call, a compute purchase, a tool-triggered payment, a settlement on agent-commerce rails. Every time the agent wants to spend, it asks the firewall first. The firewall evaluates the proposed transaction against a set of rules you configured and returns one of three decisions, in under 5 milliseconds:

The third outcome — flag — is what makes a spend firewall qualitatively different from a blunt budget cap. A budget cap has two states: under and over. A spend firewall has three: fine, blocked, and "this might be fine but a human should look." That third state is where most real-world autonomous-agent spend decisions actually live — the $2,000 compute purchase from a vendor you've used before but not at 3am, the $500 API top-up that's within budget but unusual, the ad buy that matches your category rules but spikes velocity. A binary cap either blocks all of these (false positives that break your agent's workflow) or allows all of them (the $12,400 morning). A flag routes them to a human.

2. Why budget caps and observability tools fail

The most common objection to a spend firewall is "I already have a budget cap on my LLM provider / gateway / observability tool." This section explains why that isn't enough.

The reactive-vs-pre-spend distinction

Every existing tool that touches AI spend — LiteLLM, Helicone, OpenRouter, Portkey, Langfuse, OpenAI's billing caps, AWS Budgets — is reactive. They count tokens or dollars after a call completes, compare the running total to a threshold, and then either reject the next call or alert you that a threshold has been crossed. The call that crossed the threshold already completed and already cost you money.

A spend firewall is pre-spend. It evaluates the transaction before it fires. The blocked transaction never happens. The flagged transaction is held. This is a categorical difference, not a degree of better — it is the difference between an airbag and a crash report.

The velocity gap

Reactive tools cannot stop the thing that actually causes catastrophic agent spend: a runaway retry loop. A bug, a rate-limit, a transient network error — your agent retries the paid call. Forty times in 90 seconds. Each retry completes, each one costs money, and the daily budget cap only trips after the budget is already gone. A spend firewall's velocity rule detects the retry pattern on the second or third repeat and blocks subsequent attempts — the loop dies before the wallet does.

The merchant gap

No budget cap, no observability tool, and no LLM gateway has a merchant allowlist. They cannot prevent your agent from spending at a vendor you have never approved. A spend firewall can — unknown merchants are blocked by default, and you allowlist the ones you trust.

ApproachStops runaway spendTimingVelocity killMerchant allowlistHuman approval queue
Trust the prompt
Provider budget cap⚠️ Per-provider onlyReactive
LLM gateway (LiteLLM, Portkey)⚠️ Post-callReactive
Observability (Helicone, Langfuse)❌ Alerts onlyReactive
Human babysitterMinutes⚠️ Slow⚠️ Manual
Spend firewall (sipi.bot)<5ms pre-spend

3. The six rule types

A spend firewall enforces six categories of rule. Most deployments only need the first three; the rest handle edge cases that matter in production.

Rule 1 — Per-transaction cap

A hard ceiling on any single spend. Block anything over $500 outright. This is the floor — every autonomous agent should have one, even if it's high. It catches the catastrophic single transaction (the $6,200 GPU rental from an unknown vendor) that no other rule type will catch.

{"rule_type": "per_transaction", "params": {"max_amount": 500}, "action": "BLOCKED"}

Rule 2 — Daily / period total

A rolling budget across all transactions in a window — day, week, month. This catches the death-of-a-thousand-cuts pattern: many small purchases that individually pass every rule but collectively blow the budget. Without it, an agent can spend $1,000 by making 100 $10 purchases, none of which trips a per-transaction cap.

{"rule_type": "daily_total", "params": {"max_amount": 2000}, "action": "BLOCKED"}

Rule 3 — Velocity limit (the runaway-loop killer)

A cap on how many transactions are allowed in a time window. This is the rule that stops the 2am retry loop. If your agent makes more than 10 transactions in an hour, something is wrong — block the 11th. Velocity rules catch bugs, prompt-injection-driven spending, and compromised agents far faster than any amount-based rule, because the pattern of repeated spend is detectable before the amount becomes dangerous.

{"rule_type": "velocity", "params": {"max_count": 10, "window_minutes": 60}, "action": "BLOCKED"}

Rule 4 — Merchant allowlist / blocklist

Only approved vendors go through. An unknown merchant — unknown-gpu.ru, a newly-registered domain, a vendor you've never used — is blocked unless you've allowlisted it. This is your defense against prompt injection that tries to route spend to an attacker-controlled merchant, and against agents that "discover" novel vendors during tool use.

{"rule_type": "merchant_allow", "params": {"allowed": ["openai.com", "anthropic.com", "aws.amazon.com"]}, "action": "BLOCKED"}

Rule 5 — Category limits

Allow, cap, or flag by spend category — compute, SaaS, advertising, data enrichment, payments. Your agent might be allowed to buy unlimited API credits (LLM calls) but capped at $100/day on advertising spend, and blocked entirely from wire transfers. Category rules let you express nuanced spend policy that a single dollar cap cannot.

{"rule_type": "category_limit", "params": {"category": "ads", "max_amount": 100}, "action": "BLOCKED"}

Rule 6 — Time windows

Restrict or flag spend outside expected hours. Block all agent spend between 8pm and 8am. Flag anything on weekends. This catches the single most common runaway pattern — unattended overnight activity — without breaking daytime workflows.

{"rule_type": "time_window", "params": {"allowed_hours": "9-18"}, "action": "FLAGGED"}

4. Architecture: where the firewall sits

A spend firewall is a single HTTP endpoint that your agent calls before any action that would move money. It does not hold your money, it does not process payments, and it does not replace your payment rail. It is a decision API — you ask "should my agent spend $X at merchant Y for category Z?", it answers, and your existing payment infrastructure either proceeds or doesn't.

┌──────────────┐     ┌──────────────┐     ┌──────────────────┐
│  AI Agent    │────▶│  sipi.bot    │────▶│ APPROVED/BLOCK/  │
│ (LangChain,  │     │  evaluate()  │     │ FLAGGED + reason │
│  CrewAI, etc)│     │  <5ms        │     └──────────────────┘
└──────────────┘     └──────────────┘
                            │
                            ▼ if APPROVED
                     ┌──────────────┐
                     │ Your payment │
                     │ rail (Stripe,│
                     │ x402, etc)   │
                     └──────────────┘

This design has three consequences worth stating explicitly:

5. How to deploy one in 5 lines

The fastest path — the hosted endpoint. Sign up, get an API key, call the endpoint before any paid action:

import requests

def before_agent_spends(amount, merchant, category):
    r = requests.post(
        "https://sipi.bot/v1/transactions/evaluate",
        headers={"Authorization": "Bearer YOUR_KEY"},
        json={"amount": amount, "merchant": merchant, "category": category},
    ).json()
    return r["decision"]  # "APPROVED", "BLOCKED", or "FLAGGED"

# in your agent's tool-call path:
if before_agent_spends(6200, "unknown-gpu.ru", "compute") != "APPROVED":
    abort_action()

For self-hosting (free, MIT, runs anywhere with Python 3.9+):

pip install sipi-bot
python -m spendfirewall.api  # serves on :8080

6. Framework integrations

sipi.bot ships native surfaces for every common agent runtime:

RuntimeSurfaceSetup
Claude Code, Cursor, HermesMCP tool (stdio)python -m spendfirewall.mcp_server
Any HTTP-capable runtimeHTTP APIPOST /v1/transactions/evaluate
Shells, CI, cronCLIsipi-guard --amount 500 --merchant X
A2A agent discoveryAgent cardGET /.well-known/agent-card.json
LangChainWrapper5-line client in /integrations
CrewAIWrapper5-line client
OpenAI Agents SDKWrapper5-line client
Vercel AI SDKWrapper5-line client

7. Agent-commerce rails (x402, AP2, AgentKit)

If you are building on agent-payment protocols — x402 (Coinbase), AP2 (Google), or Coinbase AgentKit — the spend firewall is the compliance layer that sits in front of the wallet. The protocol moves the money; the firewall decides whether the move is allowed.

# agent wants to settle a payment via x402
decision = sipibot.evaluate(amount=0.50, merchant="content-provider", category="micropayment")
if decision == "APPROVED":
    x402.settle(payment)  # rail moves the money
elif decision == "FLAGGED":
    route_to_human(payment)

This composition matters because agent-commerce protocols are being designed for speed and autonomy — "the agent pays, the resource is delivered, no human in the loop." That is exactly the design that produces $12,400 mornings. A spend firewall reintroduces the control point without breaking the protocol's latency budget.

8. The audit log and compliance

Every decision the firewall makes — approve, block, or flag — is written to a tamper-evident audit log: an append-only ledger with a content hash chain, so you can verify after the fact that no decision was altered or deleted. For regulated industries (fintech, healthcare, enterprise), this is the difference between "we have agent spend controls" and "we have agent spend controls we can prove to an auditor."

The log records, per decision: the timestamp, the amount, the merchant, the category, the rule that fired (or "within all policies" for approvals), the action taken, and the decision latency. For a flagged transaction that went through the human approval queue, it also records who approved or denied it and when.

9. What a spend firewall is not

The one-sentence summary. A spend firewall is the pre-spend control layer that turns "your agent just spent $12,400 while you slept" into "your agent tried to spend $12,400, we blocked it, and you have a clean log in the morning."

10. Tuning the firewall: from paranoid to permissive

The biggest mistake teams make with a spend firewall is treating the initial rule set as fixed. It is not. A firewall that is too tight blocks legitimate work and gets bypassed ("just this once"); one that is too loose may as well not exist. The goal of the first two weeks of production traffic is to tune, not to lock down.

The tuning loop is mechanical and takes about ten minutes a day:

  1. Review the blocked list daily. Open the dashboard, look at every BLOCKED decision, and read the reason field. If a blocked transaction was legitimate — the agent was supposed to pay that vendor — you have one of three gaps: the merchant is missing from the allowlist, the per-transaction cap is too low, or the velocity limit is tripping on a legitimate burst (not a runaway loop).
  2. Distinguish loops from bursts. A velocity trip on 12 transactions in a minute is a runaway loop if the merchant is the same and the amounts are identical; it is a burst if the merchants differ and the amounts vary. Loops deserve a tighter cap; bursts deserve a higher one.
  3. Walk the per-transaction cap toward the 95th percentile. Pull a week of approved transactions, sort by amount, and set the per-transaction cap just above the 95th-percentile value. This blocks the long tail of outliers without interrupting normal work. The runaway cost calculator does this math for you.
  4. Anchor the approval threshold at ~2× the per-transaction cap. Anything between the cap and 2× the cap should FLAG for human review rather than BLOCK outright — it's unusual but not necessarily wrong, and a human can usually clear the queue in under a minute.

After two weeks, the dashboard's blocked list should be almost entirely genuine threats: unknown merchants, high-risk TLDs, out-of-window spends, and the occasional runaway loop. When you reach that steady state, the firewall has stopped being a control problem and started being an alarm system — which is exactly the goal.

11. Anti-patterns: five ways teams defeat their own firewall

Most agent-spend incidents in production are not engine failures — they are configuration failures, where well-intentioned decisions quietly disabled the protection. These five anti-patterns account for nearly every "but we had a firewall" post-mortem:

1. The emergency bypass that never closed

A legitimate spend is blocked, someone adds a blanket ALLOW rule "just for today," and it is never removed. Within a week the firewall is a pass-through. Fix: every ALLOW rule must have an expiry; treat permanent allows as a code review, not a dashboard click. Use the spend policy template to make the review a written artifact.

2. Trusting the agent's self-reported amount

If the firewall evaluates the amount the agent claims it will spend, a prompt-injected or buggy agent simply reports a smaller number. Fix: the amount must come from the tool call's actual parameters or the merchant's quote response — never from free text the agent generated. This is why sipi.bot's evaluate endpoint takes structured {amount, merchant, category}, not a prompt.

3. Velocity limits set per-agent when agents are spawned on demand

Serverless agent runtimes spin up a fresh agent per task, so a per-agent velocity limit sees only one transaction per identity and never trips. Fix: velocity must be scoped to the workspace (the card or budget), not the agent instance. One workspace-level velocity rule catches a loop no matter how many agents participate in it.

4. No rule for the "unknown merchant" default

If the default action for an unmatched merchant is APPROVED, the firewall protects you from merchants you already know about and nothing else — which is the opposite of the threat model. Fix: default action must be BLOCKED, and the allowlist is how merchants earn their way in. See the merchant allowlist policy.

5. Treating the firewall as a logging tool

Some teams wire up the evaluate call but never enforce the decision — they log it "for visibility" and let the transaction proceed regardless. This gives you a beautiful audit trail of every dollar you lost. Fix: the agent runtime must treat a BLOCKED decision as a hard stop, not a suggestion. If your framework makes that hard, the integration guides show the wiring for LangChain, CrewAI, OpenAI Agents SDK, and the Vercel AI SDK.

This guide is the trunk; the branches below go deeper on each rule type, comparison, and reference. If you're building a real deployment, these are the next reads.

13. Frequently asked questions

What is a spend firewall for AI agents?

A spend firewall is a control layer that sits in front of every transaction an autonomous AI agent attempts and evaluates it against your rules — per-transaction caps, daily totals, velocity limits, merchant allowlists, category limits, and time windows — returning approve, block, or flag before any money moves. Unlike a budget cap, it is pre-spend: the transaction is stopped before it fires, not after.

How is a spend firewall different from an LLM budget cap?

An LLM budget cap fires reactively — after tokens are consumed or after a daily threshold is crossed. A spend firewall evaluates every transaction before a single dollar moves, with velocity limits that kill retry loops and merchant allowlists that budget caps do not provide.

Do I need a spend firewall if I use LangChain or CrewAI?

If your agent can trigger real payments — API calls, compute, tools, transactions — yes. The framework decides what the agent does; the firewall governs what the agent is allowed to spend doing it.

Can an AI agent spend money without my permission?

Yes, if it has access to a payment method and no pre-spend guardrail. Agents that can call paid APIs, buy compute, trigger charges, or settle on agent-commerce rails can spend without per-transaction approval. A spend firewall is what prevents that.

How much does a spend firewall cost?

The open-source core is MIT-licensed and free to self-host forever. The hosted service is flat-rate: $99/month (Team, unlimited evaluations) or $499/month (Business, managed policy). No per-call fees.

Protect your agent with sipi.bot →

Free self-host core (MIT) · Hosted from $99/mo · 53/53 eval scenarios passing

Related