x402 Protocol Explained — How AI Agents Pay Each Other
When two software agents need to exchange value, they hit a wall the web has carried unused for thirty years. HTTP defines a status code, 402 Payment Required, that was reserved early and then left mostly idle because the web had no native settlement layer. Humans paid with credit cards in a browser, not with a status code. The x402 protocol is the attempt to wake that code up and give machines a clean way to settle a charge before a request proceeds. This post explains what x402 is, why ai agent payments need a pay-per-call standard, how escrow with lock, release, and refund actually works, and how nano-empire-tollbooth implements an x402 hook you can wire into your own mesh. This is informational and not financial advice.
What HTTP 402 Was, and What x402 Makes It
HTTP 402 has always meant the same thing on paper: the server will not fulfill this request until payment is settled. The problem was the missing second half. A 402 with no agreed format for "here is the price" and "here is the proof I paid" is just a closed door with no handle. For human traffic that gap was filled by redirecting to a checkout page. That works for a person with a card. It does not work for an autonomous agent that needs to decide, pay, and continue inside a single programmatic loop.
The x402 model fills the gap with a small, predictable handshake on top of plain HTTP. A caller requests a resource. The server responds with 402 and a machine-readable quote: the amount, the asset, and where to send proof. The caller settles the charge and retries the request carrying that proof. The server verifies and serves the result. No browser, no OAuth dance, no subscription portal. The price is discoverable, the payment is per call, and the proof travels with the request. That is the entire shape of http 402 reborn for the machine economy.
Why Agents Need a Pay-Per-Call Settlement Standard
Traditional billing was built around people and accounts. You sign up once, store a card, and the provider charges you on a cycle. An agent that discovers a tool at runtime has none of that context. It does not have an account on every service it might call, it cannot fill in a checkout form, and it will not wait for a human to approve a subscription. It needs to learn a price, decide if the call is worth it, pay exactly for that call, and move on in milliseconds.
This is why pay per call is the natural unit for agent settlement. Each request is a discrete, priced event. There is no recurring relationship to manage, no entitlement table to sync, and no idle subscription to forget about. When an agent calls a function that returns a real result, value moves. When it does not, nothing moves. For a deeper look at why this layer is becoming foundational, see why AI agents need payment rails. If you want to see how this compares with card-based billing built for humans, the Stripe vs Nano Empire comparison lays out the tradeoffs, and our post on Stripe vs an agent payment SDK goes further on the developer experience.
How Escrow Works: Lock, Release, Refund
A pay-per-call charge has a failure problem. If the caller pays and then the downstream function errors, the caller paid for nothing. If the function runs first and the caller never pays, the provider gave away work. Escrow solves both by splitting settlement into three steps tied to the lifecycle of the request.
- Lock. When the call begins, the toll amount is locked in escrow. The funds are committed but not yet delivered to the provider.
- Release. When the function returns successfully, the locked amount is released to the provider. The work was done, so the value moves.
- Refund. When the function fails or is rejected, the locked amount is refunded to the caller. No result, no charge.
This lifecycle also gives you budget control. Before a charge is even locked, the booth can check a per-agent daily cap and reject the call if the source agent is over budget. That stops a runaway agent from burning a month of spend in an afternoon, because the limit is enforced at the moment of the charge rather than discovered on an invoice later. Every lock, release, refund, and rejection is written to an append-only JSONL ledger, one JSON object per event, so the whole history is auditable after the fact.
How nano-empire-tollbooth Implements an x402 Hook
nano-empire-tollbooth is a Python package that puts this entire model behind one decorator. You attach @monetize(price_usd=...) to any function and every call is metered, logged, and settled through the escrow lifecycle described above. It runs on Python 3.9+, it is MIT licensed, and the first 100 calls run free in paper mode so you can validate the flow before any real money is involved.
Install it from PyPI:
terminalpip install nano-empire-tollbooth
The simplest path is the decorator. Here a single line turns a plain function into a priced, x402-settled call:
pythonfrom nano_empire_tollbooth import monetize
@monetize(price_usd=0.01)
def summarize(text: str) -> str:
"""Summarize a document. Priced per call, settled via the tollbooth."""
sentences = text.split(". ")
if len(sentences) <= 3:
return text
return ". ".join(sentences[:3]) + "."
print(summarize("Long document text. Many sentences here. And more after that. ..."))
Every call is locked, the function runs, and on a clean return the toll is released. If the function raises, the toll is refunded. The first 100 calls run in paper mode, which exercises the full code path and writes the ledger without moving real money, so paper and live use the same logic.
For a mesh router, you wire the booth in directly so you control the lock, release, and refund around your own dispatch. You can also plug in an x402 verifier that confirms a payment before a charge is allowed to settle. The verifier is just a function that returns true or false, so you can back it with any gateway or chain you already use.
pythonfrom nano_empire_tollbooth import Tollbooth, TollboothConfig
config = TollboothConfig(
toll_per_message_usd=0.001, # default per-call rate
paper_mode=False, # live settlement
max_daily_toll_per_agent=10.0, # per-agent daily cap
)
booth = Tollbooth(config)
# Optional x402 hook: verify payment before settlement
async def my_x402_verifier(wallet, signature, amount_usd):
# call your payment gateway, on-chain program, or invoice service
return True # or False to reject the charge
booth.set_x402_verifier(my_x402_verifier)
# In your A2A router dispatch loop
async def route_message(task_id, source_agent, target_agent, payload):
record = await booth.charge(task_id, source_agent, target_agent)
if record.status.name == "FAILED": # over cap or x402 rejected
return {"error": "agent over budget"}
try:
result = await target_agent.handle(task_id, payload)
await booth.release(task_id) # success -> release escrow
return result
except Exception:
await booth.refund(task_id) # failure -> refund escrow
raise
The numbers above are illustrative. The point is the structure: a charge locks escrow, an x402 verifier can gate it, success releases it, and failure refunds it, with every step landing in the ledger. You can test all of this without writing any payment code by using the Tollbooth Simulator, and the quickstart guide walks through the first call end to end.
Where This Goes Next
The web reserved 402 because someone expected a day when requests would carry payment as naturally as they carry headers. For human traffic that day never quite arrived, because people pay in browsers, not in status codes. For agents the calculus is different. An agent that can read a price, settle a charge, and verify a receipt inside one loop turns every useful function into a discrete priced service. That is the practical meaning of the machine economy: not a grand new currency, but a boring, reliable way for one program to pay another for one unit of work.
The x402 model gives that exchange a shape, and escrow gives it safety, so a failed call costs nobody. nano-empire-tollbooth packages both into a decorator and a router hook you can adopt incrementally, starting in free paper mode and moving to live settlement when you are ready. If you are building agents that need to pay or get paid, the agent-to-agent payments walkthrough is a good next read, and the Nano Empire AI landing page has the full picture. This is informational and not financial advice.
Wire x402 settlement into your agents.
Install from PyPI and run the full escrow lifecycle in free paper mode. No credit card required to start, 100 free calls included.