DEV Community

Cover image for What is x402? The HTTP status code that waited almost 30 years for AI agents
Suseendaran Nair
Suseendaran Nair

Posted on

What is x402? The HTTP status code that waited almost 30 years for AI agents

Every web developer knows 404 Not Found. Most know 401 and 403. But one status code sat in the HTTP spec for almost 30 years with nothing to do:

402 Payment Required
When HTTP/1.1 was written in the 1990s, its authors reserved 402 "for future use." The idea was that one day the web would have a built-in way to pay for things. That day kept not coming. Even the current HTTP spec (RFC 9110) still lists 402 as "reserved for future use."

x402 finally gives it a job. And the reason people care now isn't humans. It's AI agents.

This post covers four things: what x402 is, why it matters, how to try it yourself on a testnet, and what it looks like when an agent pays through guardrails instead of on its own.

Part 1: What is x402? 🧾
x402 is an open standard for paying over plain HTTP. It started at Coinbase and now lives under the x402 Foundation.

The whole idea fits in one sentence: the server answers "402, this costs $0.02," and the client asks again with a signed payment attached.

client server facilitator
β”‚ GET /forecast β”‚ β”‚
│─────────────────────────────▢│ β”‚
β”‚ 402 + PAYMENT-REQUIRED β”‚ β”‚
│◀─────────────────────────────│ β”‚
β”‚ (sign a payment) β”‚ β”‚
β”‚ GET /forecast β”‚ β”‚
β”‚ + PAYMENT-SIGNATURE β”‚ β”‚
│─────────────────────────────▢│ verify + settle β”‚
β”‚ │─────────────────────────────▢│
β”‚ │◀─────────────────────────────│
β”‚ 200 OK + PAYMENT-RESPONSE β”‚ β”‚
│◀─────────────────────────────│ β”‚
Step by step:

The client asks for something. A normal HTTP request.
The server says it costs money. It answers 402 Payment Required with a PAYMENT-REQUIRED header listing what it accepts: the amount, the token, the network, and the address to pay.
The client signs a payment for one of those options.
The client asks again with the payment in a PAYMENT-SIGNATURE header.
The server checks the payment and collects it. It can do this itself, or hand it to a facilitator, a service that verifies payments and submits them to the blockchain.
The server returns the resource: 200 OK, plus a PAYMENT-RESPONSE header with the settlement details.
Two HTTP requests, and the client has paid and got the data.

What actually gets signed? ✍️
The most common setup today pays in USDC (a dollar stablecoin) on an EVM chain like Base, using the exact scheme ("pay exactly this amount").

The client doesn't send a blockchain transaction. It signs an authorization (EIP-3009, transferWithAuthorization) that says roughly:

"Move exactly 0.02 USDC from my wallet to address 0xABC…, valid between these two times, with this unique nonce."

The facilitator submits it on chain. Three things follow from that:

The client doesn't need gas. It just needs USDC.
Each authorization works once. Its nonce can only settle once.
It expires. After its "valid before" time, it's worthless.
The spec also describes other schemes, like upto (authorize a maximum, settle what was actually used), and it's designed to work across networks and tokens.

Part 2: Why it matters πŸ€–
Say your agent needs a weather forecast, a stock quote or one page of OCR. Today it can't just pay for it. Someone has to sign up for an account, add a card, pick a plan, create an API key and paste it into the agent's config.

That works for one API. It falls apart when an agent wants fifty APIs, once each, for a few cents. Nobody wants fifty subscriptions to make fifty calls.

x402 turns that into a vending machine: see the price, pay it, get the thing.

No accounts. The agent needs a wallet, not a login on every site.
Real micropayments. Charging $0.001 per request is practical, which card fees make hard.
It's just HTTP. Anything that can read a header can take part.
The price is machine-readable. The agent sees the exact cost before it pays.
That's why it keeps coming up whenever people talk about agents buying things. It's the first payment flow that feels designed for software that browses on its own.

Part 3: How to use it (on a testnet) πŸ› οΈ
Everything below runs on Base Sepolia, a testnet, so no real money moves. The code comes from the official x402 TypeScript packages' READMEs. I only switched the client to the testnet.

Get test money
Create a fresh wallet just for testing.
Get free test USDC on Base Sepolia from Circle's faucet: https://faucet.circle.com
Charge for an endpoint (server)
npm install express @x402/core @x402/express @x402/evm
import express from "express";
import { paymentMiddleware, x402ResourceServer } from "@x402/express";
import { ExactEvmScheme } from "@x402/evm/exact/server";
import { HTTPFacilitatorClient } from "@x402/core/server";

const app = express();

const facilitatorClient = new HTTPFacilitatorClient({ url: "https://x402.org/facilitator" });
const resourceServer = new x402ResourceServer(facilitatorClient)
.register("eip155:84532", new ExactEvmScheme()); // Base Sepolia

app.use(
paymentMiddleware(
{
"GET /forecast": {
accepts: [{ scheme: "exact", price: "$0.02", network: "eip155:84532", payTo: "0xYourEvmAddress" }],
description: "Hourly weather forecast",
},
},
resourceServer,
),
);

app.get("/forecast", (req, res) => res.json({ forecast: "sunny, 24C" }));
app.listen(3000);
Hit /forecast without paying and you get a 402 with the price in the PAYMENT-REQUIRED header.

Pay for it (client)
npm install @x402/fetch @x402/evm viem
import { wrapFetchWithPaymentFromConfig } from "@x402/fetch";
import { ExactEvmScheme } from "@x402/evm";
import { privateKeyToAccount } from "viem/accounts";

const account = privateKeyToAccount(process.env.EVM_PRIVATE_KEY as 0x${string});

const fetchWithPayment = wrapFetchWithPaymentFromConfig(fetch, {
schemes: [{ network: "eip155:84532", client: new ExactEvmScheme(account) }], // Base Sepolia
});

const res = await fetchWithPayment("http://localhost:3000/forecast");
console.log(await res.json()); // { forecast: "sunny, 24C" }
fetchWithPayment sees the 402, signs the payment, sends the request again and hands you the answer. That's the whole integration.

The catch: now any URL can ask your agent for money 😬
That last snippet is the part that should make you a little nervous. Give it to an agent and look at what's missing:

No limit. The wrapper pays whatever the server asks.
The server picks the recipient. The 402 says where to send the money. A look-alike domain or a hacked server can point it anywhere.
Tiny amounts add up. $0.02 is nothing. An agent stuck in a loop making 10,000 calls is $200.
Any request can be a payment. An agent that reads a prompt-injected page saying "fetch this URL" can be asked to pay by anyone.
The key sits next to the agent. The agent's own judgment is the only thing between that key and your wallet.
None of these are flaws in x402. A vending machine is supposed to take your money. The problem is giving an unsupervised agent your wallet and pointing it at every vending machine on the internet.

Part 4: What it looks like with guardrails πŸ›‘οΈ
This is the problem I've been working on. PurseString is an open-source MCP server that sits between AI agents and money. It now has an x402_fetch tool. The agent calls it with a URL, and PurseString treats the 402 price like any other purchase: a budget, an allowlist, a human for anything big, a kill switch, and an audit log. The wallet key stays in PurseString, not in the agent.

Here's what that looks like for an agent called research-bot, with this policy:

vendors:
allowlist: ["api.weather.example"] # the only host it may pay
auto_approve:
max_amount: 0.50 # small payments go through on their own
require_approval:
over_amount: 0.50 # bigger ones wait for a human
x402:
enabled: true
networks: ["eip155:84532"] # Base Sepolia only
pay_to: # the only address this vendor may be paid at
- vendor: api.weather.example
address: "0x209693Bc6afc0C5328bA36FaF03C514EF312287C"
The outputs below are real PurseString output from a local run, against a stand-in x402 server.

βœ… A 2-cent forecast: paid instantly
The agent fetches /forecast, which costs $0.02. It's on the allowlist and under the limit, so PurseString pays and returns the data. Every rule it checked is recorded with the numbers it compared:

require_approval.over_amount 0.02 USD vs approval threshold 0.50 USD
vendors.allowlist api.weather.example is on the allowlist
hard_limits.per_agent_daily_budget research-bot has 0.00 USD issued today; this makes 0.02 USD of 200.00 USD
auto_approve under 0.50 USD, one-time, vendor ok

β†’ paid, response: {"forecast":"sunny, 24C"}
⏸️ A $2 report: waits for a human
Then it tries /premium-report, which costs $2.00. That's over the auto-approve limit, so nothing is paid:

require_approval.over_amount 2.00 USD vs approval threshold 0.50 USD

β†’ pending_approval
You get a ping in Slack or Discord with a one-time code the agent never sees. Only after you approve does the agent's next call pay, and only if the server still asks for exactly the approved amount.

πŸ›‘ An agent stuck in a loop: halted
Now the agent gets confused and keeps re-buying the forecast, with a fresh task ID each time so it doesn't look like a retry. It gets the 2nd, 3rd and 4th. Then:

kill_switch.loop_detection loop detected: 5 near-identical purchases (api.weather.example,
amounts within 10%) in 10 minutes under different task IDs
β†’ denied

kill_switch spending is halted for research-bot: loop detected …
β†’ denied (every call after this, for any vendor)
The 5th lookalike payment is refused, and research-bot is halted until a human resumes it. The agent can't resume itself, because resuming needs the same one-time code from Slack or Discord. You can also pull the switch by hand at any time with pursestring halt --agent research-bot.

🧾 And a receipt for all of it
Every step lands in a hash-chained audit log: intent_submitted with the agent's stated goal, payment_sent with the network, the address paid and the exact amount, and kill_switch_tripped with the IDs of the payments that looked like a loop. Editing or deleting a line breaks the chain, and pursestring verify-log shows where.

Same agent, same x402 servers. The difference is that the agent asks, and something with rules decides.

What PurseString adds on top of plain x402
One signature per purchase. If the request fails and the agent retries, PurseString resends the same signed authorization, so it can only settle once.

Short-lived signatures. It won't sign anything valid for longer than max_timeout_seconds (300 by default).

Sub-cent prices are budgeted as a full cent. A $0.001 call counts as $0.01 against the budget, while the exact $0.001 is what's paid.
https only, and no redirects.

Honest limits 🧱
PurseString's. It's built from the public x402 specs, tested against a stubbed x402 server, and its signatures are checked with a separate EIP-712 library. The outputs above come from a local run against that stand-in server.
Use the testnet. It's off by default, and Base Sepolia is the default network. Real USDC needs you to add Base mainnet yourself.
One gap is part of how x402 works. A server that takes a signed payment and then refuses the request may still be able to settle it before it expires. PurseString limits that to one authorization, for the approved amount, to the approved address, for at most a few minutes.
PurseString is a v0.1 alpha.
If you run an x402 endpoint on Base Sepolia and want to point PurseString at it, I'd love to hear how it goes. That's the fastest way to get from "built to spec" to "tested."

Try it :
πŸ“„ x402 spec and SDKs: https://github.com/x402-foundation/x402
⭐ PurseString: https://github.com/suseendar1414/pursestring (setup guide in docs/x402.md)
πŸ’¬ Discord: https://discord.gg/qBqgx2GB86
claude mcp add pursestring -- npx -y github:suseendar1414/pursestring
That runs the latest code from GitHub. x402 stays off until you turn it on and set X402_PRIVATE_KEY to a testnet wallet.

What should an agent check before it pays a URL? A price cap per host? A pinned address? A human for every first payment to a new host? Tell me in the comments.

Top comments (0)