skills-templates/x402/SKILL.md
x402 open payment standard for HTTP-native crypto payments. Use for API monetization, AI agent payments, micropayments, and integrating USDC payments into web services using HTTP 402 status code.
npx skillsauth add enuno/claude-command-and-control x402Install this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
The open payment standard that enables services to charge for access to their APIs and content directly over HTTP using the 402 Payment Required status code. Developed by Coinbase as an open standard and backed by the x402 Foundation (co-founded with Cloudflare), x402 enables crypto-native payments without accounts or traditional payment processors.
x402 activates the long-reserved HTTP 402 "Payment Required" status code for programmatic cryptocurrency transactions. Key characteristics:
Ecosystem Partners: AWS, Anthropic, Circle, NEAR, Cloudflare
Current Scale (as of 2025):
This skill should be triggered when:
Comprehensive TypeScript/JavaScript:
# Full installation (all packages)
npm install @x402/core @x402/evm @x402/svm @x402/axios @x402/fetch \
@x402/express @x402/hono @x402/next @x402/paywall @x402/extensions
Seller (Node.js):
# Express
npm install @x402/express @x402/core @x402/evm
# Next.js
npm install @x402/next @x402/core @x402/evm
# Hono (Cloudflare Workers)
npm install @x402/hono @x402/core @x402/evm
Buyer (Node.js):
# Minimal Fetch client
npm install @x402/core @x402/evm @x402/svm @x402/fetch
# Axios client
npm install @x402/core @x402/evm @x402/axios
Cloudflare Agents SDK:
# For Cloudflare Workers with x402 support
npm install @cloudflare/agents
Go:
go get github.com/coinbase/x402/go
Python:
pip install x402
Payments MCP (AI Agents):
# Interactive installation
npx @coinbase/payments-mcp
# Auto-configure for specific client
npx @coinbase/payments-mcp --client claude --auto-config
npx @coinbase/payments-mcp --client claude-code --auto-config
npx @coinbase/payments-mcp --client codex --auto-config
npx @coinbase/payments-mcp --client gemini --auto-config
x402-mcp (Vercel AI SDK):
npm install x402-mcp
| Package | Purpose |
|---------|---------|
| @x402/core | Core protocol types and utilities |
| @x402/evm | Ethereum/Base chain support (EIP-3009) |
| @x402/svm | Solana chain support |
| @x402/fetch | Fetch API wrapper with payment |
| @x402/axios | Axios wrapper with payment |
| @x402/express | Express.js middleware |
| @x402/hono | Hono framework middleware |
| @x402/next | Next.js integration |
| @x402/paywall | Paywall utilities |
| @x402/extensions | Additional protocol extensions |
| @coinbase/payments-mcp | AI agent payments for Claude, Gemini, Codex |
| x402-mcp | Vercel AI SDK MCP integration |
| Network | Identifier |
|---------|------------|
| Base Mainnet | eip155:8453 |
| Base Sepolia (Testnet) | eip155:84532 |
| Solana Mainnet | solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp |
| Solana Devnet | solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1 |
| Environment | URL |
|-------------|-----|
| Testnet | https://x402.org/facilitator |
| Mainnet (CDP) | https://api.cdp.coinbase.com/platform/v2/x402 |
┌────────┐ ┌────────┐ ┌─────────────┐
│ Client │ │ Server │ │ Facilitator │
└────┬───┘ └────┬───┘ └──────┬──────┘
│ │ │
│ 1. GET /paid-resource │ │
│─────────────────────────────> │
│ │ │
│ 2. 402 Payment Required │ │
│ PAYMENT-REQUIRED: {...} │ │
│<───────────────────────────── │
│ │ │
│ 3. Sign payment payload │ │
│ (wallet signature) │ │
│ │ │
│ 4. GET /paid-resource │ │
│ PAYMENT-SIGNATURE: {...} │ │
│─────────────────────────────> │
│ │ │
│ │ 5. POST /verify │
│ │─────────────────────────────────>
│ │ │
│ │ 6. Verification result │
│ │<─────────────────────────────────
│ │ │
│ │ 7. POST /settle │
│ │─────────────────────────────────>
│ │ │
│ │ 8. Settlement confirmation │
│ │<─────────────────────────────────
│ │ │
│ 9. 200 OK + Resource │ │
│ PAYMENT-RESPONSE: {...} │ │
│<───────────────────────────── │
│ │ │
Simplified Flow:
import express from "express";
import { paymentMiddleware } from "@x402/express";
import { x402Server } from "@x402/core/server";
import { registerExactEvmScheme } from "@x402/evm/exact/server";
const app = express();
const server = new x402Server();
registerExactEvmScheme(server);
app.use(paymentMiddleware(server, {
facilitatorUrl: "https://x402.org/facilitator",
routes: {
"/api/paid-endpoint": {
price: "$0.01", // USD price
network: "eip155:84532", // Base Sepolia
recipient: "0xYourWalletAddress"
}
}
}));
app.get("/api/paid-endpoint", (req, res) => {
res.json({ data: "Premium content" });
});
import { wrapFetchWithPayment } from "@x402/fetch";
import { x402Client } from "@x402/core/client";
import { registerExactEvmScheme } from "@x402/evm/exact/client";
import { privateKeyToAccount } from "viem/accounts";
// Create wallet signer
const signer = privateKeyToAccount(process.env.EVM_PRIVATE_KEY as `0x${string}`);
// Setup x402 client
const client = new x402Client();
registerExactEvmScheme(client, { signer });
// Wrap fetch with payment handling
const fetchWithPayment = wrapFetchWithPayment(fetch, client);
// Make paid request (handles 402 automatically)
const response = await fetchWithPayment("https://api.example.com/paid-endpoint");
const data = await response.json();
import { registerExactEvmScheme } from "@x402/evm/exact/client";
import { registerExactSvmScheme } from "@x402/svm/exact/client";
const client = new x402Client();
registerExactEvmScheme(client, { signer: evmSigner });
registerExactSvmScheme(client, { signer: svmSigner });
| Header | Direction | Purpose |
|--------|-----------|---------|
| PAYMENT-REQUIRED | Server → Client | Payment requirements (Base64 JSON) |
| PAYMENT-SIGNATURE | Client → Server | Signed payment payload (Base64 JSON) |
| PAYMENT-RESPONSE | Server → Client | Settlement confirmation (Base64 JSON) |
{
"x402Version": 2,
"accepts": [
{
"scheme": "exact",
"network": "eip155:8453",
"maxAmountRequired": "10000",
"asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
"recipient": "0x...",
"extra": {
"name": "USDC",
"decimals": 6
}
}
],
"timeout": 300,
"description": "Access to premium API",
"mimeType": "application/json"
}
{
"x402Version": 2,
"scheme": "exact",
"network": "eip155:8453",
"payload": {
"signature": "0x...",
"authorization": {
"from": "0xBuyerWallet",
"to": "0xSellerWallet",
"value": "10000",
"validAfter": 0,
"validBefore": 1700000000,
"nonce": "0x..."
}
}
}
{
"x402Version": 2,
"scheme": "exact",
"network": "eip155:8453",
"transactionHash": "0x...",
"settlementTimestamp": 1700000000,
"status": "settled"
}
This skill includes comprehensive documentation in references/:
x402 activates the previously reserved HTTP 402 Payment Required status code for API-native cryptocurrency payments. It enables:
Client (Buyer): Initiates requests, signs payments with crypto wallet Server (Seller): Enforces payment requirements, delivers resources Facilitator: Verifies payments, handles blockchain settlement (optional but recommended)
| Asset | Network | Contract Address |
|-------|---------|------------------|
| USDC | Base Mainnet | 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913 |
| USDC | Base Sepolia | 0x036CbD53842c5426634e7929541eC2318f3dCF7e |
| USDC | Solana Mainnet | EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v |
Fee Structure: CDP facilitator offers zero-fee USDC settlement on Base
exact (Primary):
transferWithAuthorization for EVM chainsdeferred (Cloudflare Proposal):
escrow (Proposed):
The Coinbase Developer Platform (CDP) hosts the primary x402 facilitator with fee-free USDC settlement.
Base URL: https://api.cdp.coinbase.com/platform/v2/x402
Endpoints:
| Endpoint | Method | Auth | Description |
|----------|--------|------|-------------|
| /verify | POST | Required | Verify payment payload (~100ms) |
| /settle | POST | Required | Submit to blockchain (~2s on Base) |
| /discovery/resources | GET | Optional | Query x402 Bazaar |
Verify Request:
{
"x402Version": 1,
"paymentPayload": {
"scheme": "exact",
"network": "eip155:8453",
"payload": { /* signed authorization */ }
},
"paymentRequirements": {
"scheme": "exact",
"network": "eip155:8453",
"payTo": "0xRecipient",
"maxAmountRequired": "1000000",
"resource": "/api/endpoint"
}
}
Verify Response:
{ "isValid": true, "invalidReason": null }
Settle Response:
{ "success": true, "txID": "0x1234..." }
Bazaar Discovery:
curl "https://api.cdp.coinbase.com/platform/v2/x402/discovery/resources?limit=10"
Authentication:
# Environment variables for CDP API
CDP_API_KEY_ID=your_key_id
CDP_API_KEY_SECRET=your_key_secret
Support multiple blockchains on the same endpoint:
app.use(paymentMiddleware(server, {
facilitatorUrl: "https://api.cdp.coinbase.com/platform/v2/x402",
routes: {
"GET /weather": {
accepts: [
{
scheme: "exact",
price: "$0.001",
network: "eip155:8453", // Base mainnet (EVM)
payTo: "0xYourEvmAddress",
},
{
scheme: "exact",
price: "$0.001",
network: "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp", // Solana mainnet
payTo: "YourSolanaAddress",
},
],
description: "Weather data",
},
},
}));
import { x402ResourceServer, FacilitatorClient } from "@x402/core";
import { ExactEvmScheme } from "@x402/evm/exact/server";
import { ExactSvmScheme } from "@x402/svm/exact/server";
const facilitatorClient = new FacilitatorClient(FACILITATOR_URL);
const resourceServer = new x402ResourceServer(facilitatorClient)
.register("eip155:*", new ExactEvmScheme()) // All EVM chains
.register("solana:*", new ExactSvmScheme()); // All Solana chains
app.use(paymentMiddleware(server, {
facilitatorUrl: "https://api.cdp.coinbase.com/platform/v2/x402",
routes: {
"/api/weather": {
price: "$0.001",
network: "eip155:8453",
recipient: "0xYourWallet",
extensions: {
bazaar: {
discoverable: true,
category: "weather",
tags: ["forecast", "api"]
}
}
}
}
}));
const response = await fetch(
"https://api.cdp.coinbase.com/platform/v2/x402/discovery/resources"
);
const services = await response.json();
import (
"github.com/coinbase/x402/go/pkg/x402"
"github.com/coinbase/x402/go/pkg/middleware"
)
server := x402.NewServer()
evmscheme.RegisterExactEvmScheme(server)
config := middleware.Config{
FacilitatorURL: "https://x402.org/facilitator",
Routes: map[string]middleware.RouteConfig{
"/api/data": {
Price: "0.01",
Network: "eip155:84532",
Recipient: "0xYourWallet",
},
},
}
handler := middleware.PaymentMiddleware(server, config)(yourHandler)
import (
"github.com/coinbase/x402/go/pkg/x402"
evmsigners "github.com/coinbase/x402/go/pkg/evm/signers"
)
signer, _ := evmsigners.NewClientSignerFromPrivateKey(os.Getenv("EVM_PRIVATE_KEY"))
client := x402.NewClient()
evmscheme.RegisterExactEvmScheme(client, signer)
httpClient := x402http.WrapHTTPClientWithPayment(http.DefaultClient, client)
resp, _ := httpClient.Get("https://api.example.com/paid-endpoint")
Cloudflare has embedded x402 directly into its Agents SDK and MCP infrastructure, enabling AI agents to pay per use for data access, tool execution, or inference APIs.
Transform any MCP server to support paid tools:
import { McpServer } from "@cloudflare/agents";
import { withX402 } from "@cloudflare/agents/x402";
import { z } from "zod";
const X402_CONFIG = {
network: "base-sepolia",
recipient: "0xYourWalletAddress",
facilitatorUrl: "https://x402.org/facilitator"
};
// Wrap MCP server with x402 payment support
const server = withX402(
new McpServer({ name: "PaidMCP", version: "1.0.0" }),
X402_CONFIG
);
Define tools with USD pricing:
// Paid tool - costs $0.01 per call
server.paidTool(
"square", // Tool name
"Squares a number", // Description
0.01, // Price in USD
{ number: z.number() }, // Input schema
{}, // Options
async ({ number }) => {
return {
content: [{ type: "text", text: String(number ** 2) }]
};
}
);
// Free tool in same server
server.tool(
"greet",
"Says hello",
{ name: z.string() },
async ({ name }) => {
return {
content: [{ type: "text", text: `Hello, ${name}!` }]
};
}
);
Enable agents to pay for tools:
import { withX402Client } from "@cloudflare/agents/x402";
import { privateKeyToAccount } from "viem/accounts";
const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);
// With human confirmation callback
const client = withX402Client(mcpClient, {
account,
onPaymentRequired: async (paymentInfo) => {
// Show user the payment amount and get approval
const approved = await askUserForApproval(paymentInfo);
return approved;
}
});
// Or automatic payment (no confirmation)
const autoPayClient = withX402Client(mcpClient, {
account,
onPaymentRequired: null // Pay automatically
});
Use x402-axios within MCP tool implementations:
import { withPaymentInterceptor } from "x402-axios";
import { privateKeyToAccount } from "viem/accounts";
import axios from "axios";
const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);
const client = withPaymentInterceptor(
axios.create({ baseURL: "https://paid-api.example.com" }),
account
);
// MCP tool that calls paid external API
server.tool(
"get-weather-data",
"Get weather data from the paid API",
{},
async () => {
const res = await client.get("/weather");
return {
content: [{ type: "text", text: JSON.stringify(res.data) }]
};
}
);
Gate specific endpoints in a Worker:
import { paymentMiddleware } from "@x402/hono";
import { Hono } from "hono";
const app = new Hono();
// Apply payment middleware
app.use("/api/premium/*", paymentMiddleware({
facilitatorUrl: "https://x402.org/facilitator",
routes: {
"/api/premium/data": {
price: "$0.01",
network: "base-sepolia",
recipient: "0xYourWallet"
}
}
}));
// Free endpoint
app.get("/api/free", (c) => c.json({ message: "Free data" }));
// Paid endpoint (protected by middleware)
app.get("/api/premium/data", (c) => c.json({ data: "Premium content" }));
export default app;
Coinbase's Payments MCP is the easiest way to enable AI agents (Claude, Gemini, Codex) with x402 payment capabilities. It combines wallets, onramps, and payments into a single solution requiring no API keys.
# Interactive setup (prompts for client)
npx @coinbase/payments-mcp
# Auto-configure for Claude Desktop
npx @coinbase/payments-mcp --client claude --auto-config
# Auto-configure for Claude Code
npx @coinbase/payments-mcp --client claude-code --auto-config
# Check status
npx @coinbase/payments-mcp status
| Client | Auto-Config | Command |
|--------|-------------|---------|
| Claude Desktop | Yes | --client claude |
| Claude Code | Yes | --client claude-code |
| Codex CLI | Yes | --client codex |
| Gemini CLI | Yes | --client gemini |
| Cherry Studio | Yes | - |
| Other | Manual | --client other |
{
"mcpServers": {
"payments-mcp": {
"command": "node",
"args": ["/Users/your-home-dir/.payments-mcp/bundle.js"]
}
}
}
Agents have isolated wallets with explicit funding limits. No access to your main wallet, and impossible to accumulate unexpected charges.
Vercel's x402-mcp integrates x402 payments with MCP servers and the AI SDK.
import { createPaidMcpHandler } from "x402-mcp";
import z from "zod";
const handler = createPaidMcpHandler(
(server) => {
server.paidTool(
"premium_analysis",
{ price: 0.01 }, // $0.01 per call
{ data: z.string() },
async (args) => {
const result = await analyzeData(args.data);
return { content: [{ type: "text", text: result }] };
}
);
},
{ recipient: process.env.WALLET_ADDRESS }
);
export { handler as GET, handler as POST };
import { experimental_createMCPClient as createMCPClient } from "ai";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import { withPayment } from "x402-mcp";
const mcpClient = await createMCPClient({
transport: new StreamableHTTPClientTransport(url),
}).then((client) => withPayment(client, { account }));
const tools = await mcpClient.tools();
x402 was designed from the ground up to enable autonomous AI agent payments:
// AI Agent with x402 payment capability
import { x402Client } from "@x402/core/client";
import { wrapFetchWithPayment } from "@x402/fetch";
async function agentWorkflow(query: string) {
// 1. Discover relevant services from Bazaar
const services = await fetch(
"https://api.cdp.coinbase.com/platform/v2/x402/discovery/resources"
).then(r => r.json());
// 2. Find service matching query
const service = services.resources.find(s =>
s.description.toLowerCase().includes(query.toLowerCase())
);
// 3. Make paid request (automatic 402 handling)
const client = new x402Client();
registerExactEvmScheme(client, { signer });
const fetchWithPayment = wrapFetchWithPayment(fetch, client);
return await fetchWithPayment(service.url).then(r => r.json());
}
Claude and other AI assistants can make payments through MCP servers:
// Claude Desktop config: ~/.config/claude/claude_desktop_config.json
{
"mcpServers": {
"x402-payments": {
"command": "node",
"args": ["/path/to/mcp-server/index.js"],
"env": {
"EVM_PRIVATE_KEY": "0x...",
"RESOURCE_SERVER_URL": "https://api.example.com"
}
}
}
}
const DAILY_LIMIT = 1.00; // $1.00 USD
let dailySpend = 0;
async function makePayment(amount: number) {
if (dailySpend + amount > DAILY_LIMIT) {
throw new Error("Daily spending limit exceeded");
}
dailySpend += amount;
// ... proceed with payment
}
validAfter and validBefore bounds prevent reuse| Code | Description |
|------|-------------|
| INVALID_SIGNATURE | Payment signature verification failed |
| INSUFFICIENT_FUNDS | Payer wallet has insufficient balance |
| EXPIRED_AUTHORIZATION | Payment validity window has passed |
| INVALID_NETWORK | Unsupported network identifier |
| INVALID_SCHEME | Unsupported payment scheme |
| ALREADY_USED | Payment authorization already settled |
| AMOUNT_MISMATCH | Payment amount doesn't match requirement |
| RECIPIENT_MISMATCH | Payment recipient doesn't match requirement |
import { X402Error } from "@x402/core";
try {
const response = await fetchWithPayment(url);
} catch (error) {
if (error instanceof X402Error) {
switch (error.code) {
case 'INSUFFICIENT_FUNDS':
console.error('Add USDC to wallet on correct network');
break;
case 'SCHEME_NOT_REGISTERED':
console.error('Register payment scheme first');
break;
case 'EXPIRED_AUTHORIZATION':
console.error('Payment timed out, retry with fresh payload');
break;
default:
console.error('Payment error:', error.message);
}
}
throw error;
}
https://x402.org/facilitatoreip155:84532 (Base Sepolia)PAYMENT-REQUIRED headerPAYMENT-RESPONSE headerThe x402 Foundation was established by Coinbase and Cloudflare to promote adoption of the x402 protocol as an open standard for internet-native payments. Goals include:
tools
MemPalace local-first AI memory system. Use when setting up persistent memory for Claude Code sessions, mining project files or conversation transcripts, querying past context, configuring MCP tools, managing the knowledge graph, or troubleshooting palace operations.
tools
LangSmith Python SDK — trace, evaluate, and monitor LLM applications. Covers @traceable decorator, trace context manager, Client API, evaluate() / aevaluate(), comparative evaluation, custom evaluators, dataset management, prompt caching, ASGI middleware, and pytest plugin.
development
LangGraph (Python) — build stateful, controllable agent graphs with checkpointing, streaming, persistence, interrupts, fault tolerance, and durable execution. Covers both Graph API (StateGraph) and Functional API (@entrypoint/@task).
development
LangGraph Graph API (Python) — build explicit DAG agent workflows with StateGraph, typed state, nodes, edges, Command routing, Send fan-out, checkpointers, interrupts, and streaming. Use when you need explicit control flow and graph topology.