Let your agents pay automatically with x402
Full protocol reference, production-ready pay_invoice() for Stripe, USDC on Base, and x402-native rails — plus a live 402 → pay → retry demo you can run right now.
What is x402?
x402 revives HTTP 402 Payment Required. Instead of failing, an API responds with a machine-readable invoice — Stripe checkout, USDC on Base, or any x402-compatible rail. Agents settle it programmatically and retry with X-PAYMENT. No dashboards. No humans.
Native HTTP 402
Standard status code — every client already understands it.
Any payment rail
Stripe cards, USDC on Base, Lightning, or your own settlement layer.
Built for swarms
LangGraph, CrewAI, AutoGen fleets that can't stop to ask a human.
Spec: x402.org · github.com/coinbase/x402 · Coinbase docs
How the flow works
Four steps. The whole thing happens inside your agent's HTTP client.
Agent calls TableCharts
Your agent POSTs JSON, CSV, or a source URL and asks for a live dashboard.
Receives 402 + invoice
If quota is gone, TableCharts returns HTTP 402 with a machine-readable invoice + buy_url.
Agent pays automatically
Settle via Stripe Payment Intent, USDC on Base, or an x402-native wallet.
Retries with X-PAYMENT
Original request replays with X-PAYMENT header and receives dashboard_url + embed_iframe.
Protocol reference
Exact wire format for the 402 response, headers, and error handling.
402 response schema
HTTP/1.1 402 Payment Required
Content-Type: application/json
WWW-Authenticate: x402 realm="tablecharts", invoice_id="inv_9F..."
{
"code": "quota_exhausted",
"message": "Free quota used. Pay to continue.",
"invoice_id": "inv_9F8A2C...",
"amount": "0.99",
"currency": "USD",
"buy_url": "https://tablecharts.co/pricing#topups",
"supported_payment_methods": ["stripe", "usdc-base", "x402"],
"expires_at": 1736899200,
"x402": {
"version": "0.3",
"network": "base",
"asset": "USDC",
"recipient": "0xAbC1234...",
"nonce": "b9f2...",
"max_amount": "0.99"
}
}Body fields
invoice_id— unique, used for idempotencyamount,currency— decimal string + ISO 4217buy_url— human fallback (Stripe hosted checkout)supported_payment_methods— array of railsexpires_at— unix secondsx402— rail-specific settlement details
Error handling
402 twiceafter payment → invalid X-PAYMENT, do not retry429 / 503→ back off usingRetry-Afterexpires_atpassed → discard invoice, request a fresh 402- Timeouts: 30s request, 60s payment settlement
- Cap retries at 4 and set a per-agent spend limit
Headers
| Header | Direction | Description |
|---|---|---|
| WWW-Authenticate | server → client | Sent on 402. Includes scheme (x402) and invoice_id for correlation. |
| X-PAYMENT | client → server | Rail-prefixed settlement proof: stripe:<pi_id>, usdc-base:<base64-eip3009>, or opaque x402 token. |
| X-INVOICE | client → server | Echoes invoice_id so the server can match your payment to the original 402 (idempotent). |
| Idempotency-Key | client → server | Optional. Prevents duplicate paid retries after network errors. |
| Retry-After | server → client | Sent on 429/503. Wait this many seconds before retrying. |
pay_invoice() — three working rails
No more placeholder. Pick the rail your agent has credentials for; the return value is the X-PAYMENT header for the retry.
# pay_invoice() — USDC on Base (Coinbase Smart Wallet / x402 SDK)
# Best for: fully autonomous agent swarms, sub-cent metered calls.
from x402 import Wallet # pip install x402
from decimal import Decimal
wallet = Wallet.from_private_key(os.environ["X402_PRIVATE_KEY"], network="base")
def pay_invoice_usdc(invoice: dict) -> str:
"""Sign and broadcast a USDC transfer that satisfies the invoice."""
x = invoice["x402"]
assert x["asset"] == "USDC" and x["network"] == "base"
tx = wallet.transfer(
to=x["recipient"],
amount=Decimal(invoice["amount"]),
asset="USDC",
nonce=x["nonce"],
expires_at=x["expires_at"],
)
receipt = tx.wait(timeout=30) # exponential backoff internally
if not receipt.ok:
raise RuntimeError(f"USDC settlement failed: {receipt.error}")
# X-PAYMENT for USDC rail: base64(EIP-3009 authorization + tx hash)
return receipt.x_payment_tokenClient examples
Drop-in wrappers for popular agent frameworks and languages. For fuller copy-paste tool nodes with state and billing observability, see the Ready-to-use LangGraph & CrewAI examples in the docs.
import Stripe from "stripe";
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
const ENDPOINT = "https://tablecharts.co/api/generate-dashboard";
async function payInvoiceStripe(invoice: any): Promise<string> {
const intent = await stripe.paymentIntents.create({
amount: Math.round(parseFloat(invoice.amount) * 100),
currency: invoice.currency.toLowerCase(),
payment_method: process.env.STRIPE_PAYMENT_METHOD_ID,
confirm: true, off_session: true,
metadata: { invoice_id: invoice.invoice_id },
});
if (intent.status !== "succeeded") throw new Error("payment failed");
return `stripe:${intent.id}`;
}
export async function generateWithX402(payload: unknown, tries = 4): Promise<any> {
const headers: Record<string, string> = {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.TABLECHARTS_API_KEY}`,
};
for (let i = 0; i < tries; i++) {
const res = await fetch(ENDPOINT, { method: "POST", headers, body: JSON.stringify(payload) });
if (res.status === 402) {
const invoice = await res.json();
headers["X-PAYMENT"] = await payInvoiceStripe(invoice);
headers["X-INVOICE"] = invoice.invoice_id;
continue;
}
if ([429, 502, 503, 504].includes(res.status)) {
await new Promise(r => setTimeout(r, (2 ** i) * 1000));
continue;
}
if (!res.ok) throw new Error(`TableCharts ${res.status}`);
return res.json();
}
throw new Error("x402 retry limit exceeded");
}Try it live — 402 → pay → retry
Simulated end-to-end flow against a protected endpoint. Watch the request, the 402, the payment, and the successful retry.
Request
POST /api/generate-dashboard
{ "data": [{"month":"Jan","revenue":42000}], "title": "Q1 Revenue" }Response
Sandbox mode — test with fake money
Point your agent at the sandbox endpoint to exercise the full 402 → pay → retry loop against Stripe test cards and Base Sepolia USDC — zero real funds spent.
Stripe test mode
Use a test-mode API key and card 4242 4242 4242 4242. Payment Intents settle instantly with no real charge.
TABLECHARTS_API_KEY=tc_test_...
STRIPE_SECRET_KEY=sk_test_...
X402_ENDPOINT=https://sandbox.tablecharts.co/api/generate-dashboardUSDC on Base Sepolia
Grab test USDC from the Circle faucet and point the x402 client at network base-sepolia. Full settlement, no mainnet gas.
Official MCP server + examples
Drop TableCharts into Claude, Cursor, or any MCP client. The repo ships the TypeScript MCP server, Python examples for LangGraph and CrewAI, and sample agent swarms.
npm install -g @tablecharts/mcp-server
# Or use npx directly in your client config:
{
"mcpServers": {
"tablecharts": {
"command": "npx",
"args": ["-y", "@tablecharts/mcp-server"],
"env": { "TABLECHARTS_API_KEY": "tc_live_..." }
}
}
}tablecharts-mcp-server/
├── README.md # Install, env setup, directory submission copy
├── package.json # @tablecharts/mcp-server entrypoint
├── server.json # MCP discovery metadata
├── glama.json # Glama MCP directory metadata
├── tsconfig.json
├── src/
│ └── index.ts # MCP server: generate_dashboard, list_charts, get_chart
├── examples/
│ ├── sales-agent-swarm-with-tablecharts/ # CrewAI swarm
│ └── sales-analysis-swarm-with-tablecharts/ # LangGraph pipeline
└── .github/workflows/
├── triage.yml
└── backfill-triage.ymlWhat's inside
- src/index.ts — MCP server with
generate_dashboard,list_charts, andget_charttools. - examples/sales-agent-swarm-with-tablecharts/ — CrewAI / LangGraph swarm that calls TableCharts end-to-end.
- examples/sales-analysis-swarm-with-tablecharts/ — Ready-to-fork analysis pipeline.
- README.md — Install, env setup, and directory submission copy.
- server.json + glama.json — MCP discovery metadata for catalogs.
Edge cases & advanced guidance
Things that will happen in production. Handle them once, sleep easy after.
Partial & over-payments
USDC transfers can undershoot due to rounding or overshoot when reusing a nonce. Server treats amount ≥ invoice.amount as paid and issues a credit note; amount < invoice.amount returns a fresh 402 with the remainder.
Multi-agent wallet ownership
Use one hot wallet per agent squad with a shared spend cap. Rotate keys via KMS. Log every settlement with the agent's run_id so a runaway loop can be traced and revoked in seconds.
Monitoring & logging
Emit structured logs on every 402 (invoice_id, rail, amount, latency_ms). Track paid_ratio, avg_settle_ms, and 402_after_payment as SLO metrics. Alert if paid_ratio drops below 95%.
Refunds & disputes
Stripe rail: refund via the PaymentIntent — TableCharts credits the quota back automatically on refund.created. USDC rail: refunds are protocol-level — the server sends USDC back to the payer address in x402.refund_address.
Rate limit + 402 combined
429 always wins. If a response carries both quota_exhausted and Retry-After, wait first, then pay. Never double-pay after a timeout — replay with the same X-INVOICE header for idempotency.
Nonce & replay protection
Every invoice nonce is single-use and expires at expires_at. Reusing X-PAYMENT for a different invoice_id returns 402 with code=payment_mismatch. Always tie X-PAYMENT to its X-INVOICE.
x402 vs. other agent payment approaches
Where x402 fits alongside platform billing and custom credit systems.
| Approach | Autonomous top-up | Cross-provider | Payment rails | Settlement latency |
|---|---|---|---|---|
| x402 (HTTP 402) | Yes — protocol-native | Yes — any HTTP API | Stripe · USDC · Lightning · custom | ~2–10s (USDC), instant (Stripe off-session) |
| OpenAI billing | Only for OpenAI APIs | No — OpenAI only | Card on file | N/A (post-paid) |
| Anthropic billing | Only for Anthropic APIs | No — Anthropic only | Card on file | N/A (post-paid) |
| Custom credit system | Requires custom top-up webhook per vendor | No — per vendor | Whatever you build | Depends on impl. |
| L402 (Lightning) | Yes — protocol-native | Yes | Lightning only | ~1s |
x402 sits at the HTTP layer, so it composes with any of the above — you can use OpenAI billing for LLM calls and x402 for downstream tool APIs like TableCharts in the same agent.
Live x402 activity on TableCharts
Rolling 30-day metrics. Refreshed hourly.
Agents paid via x402
unique API keys
Avg. settlement latency
402 → 200 round-trip
Successful paid retries
of 402 responses
USDC vs. Stripe split
% by transaction count
Illustrative metrics — will be wired to a live counter once the public stats endpoint ships.
Benefits
Keep automation running. Turn exhausted quota into revenue.
Revenue without manual checkout
Every exhausted quota event becomes a paid retry instead of a lost run or support ticket.
Agents keep running 24/7
No waiting for a human to top up. The agent pays, retries, and gets back to work.
Works with agent frameworks
Same retry pattern in LangGraph, CrewAI, AutoGen, or any HTTP-capable runtime.
Clear spend control
Cap retries, cap amounts, and only send payment after a valid 402.
First 20 agents get 1 month free
Ship your x402 integration, send agent traffic, and claim a free first month.
Pricing & top-ups
x402 turns depleted quota into a paid path your agent can complete on its own.
START FREE
Test the API and prove the flow before paying.
AUTOMATIC TOP-UP
Per paid dashboard when an agent needs to keep running.
PAID PLANS
Subscriptions and top-ups for higher-volume agent workflows.
Bundles work for agents too. If your agent authenticates with a tc_live_… API key, we consume the account's subscription quota and prepaid bundle credits before charging $0.59 x402. Buy a bundle from /pricing to lower your per-chart cost as low as $0.33.
Integration checklist
Everything you need to ship an x402-enabled agent today.
1. Create an API key
Scoped TableCharts keys so each agent can be tracked and revoked independently.
2. Handle 402 responses
Parse the invoice, pay via x402 or buy_url, retry with X-PAYMENT + X-INVOICE.
3. Return the dashboard
Agent receives dashboard_url and embed_iframe for downstream tools.
4. Run unattended
Set spend caps and retry limits, then let the agent run around the clock.