ai-sdk-x402
v0.1.1
Published
Community x402 payment package for Vercel AI SDK — call pay-per-call APIs with automatic USDC settlement
Maintainers
Readme
ai-sdk-x402
Community x402 package for Vercel AI SDK — call pay-per-call APIs from AI tools with automatic USDC settlement.
⚠️ This is a community package — not an official Vercel product. It bridges the x402 protocol (HTTP 402 Payment Required for machine payments) with the Vercel AI SDK tool system.
What is x402?
x402 is an open protocol that uses HTTP 402 (Payment Required) to let AI agents pay for API calls in USDC at request time — no API keys, no subscriptions, no pre-funding. An agent discovers an endpoint, calls it, gets a 402 with payment details, settles in USDC, and retries. The whole flow takes under 2 seconds on Base L2.
Quick Start
npm install ai-sdk-x402Environment
# Optional: set your wallet for automatic payment
export X402_WALLET=0xYourAddress
# Optional: custom facilitator (default: minia2a.uk)
export X402_FACILITATOR=https://minia2a.ukStandalone Usage
import { x402 } from 'ai-sdk-x402';
// Call a free endpoint (5 free trials per IP)
const time = await x402.call('https://minia2a.uk/x402/time');
console.log(time.result);
// → { utc: '2026-08-09T13:00:00.000Z', unix: 1764000000, ms: 1764000000000, iso: '...', timezone: 'UTC' }
console.log(time.trial);
// → { remaining: 4, max: 5 }AI SDK Tool
import { x402Tool } from 'ai-sdk-x402';
import { generateText } from 'ai';
import { openai } from '@ai-sdk/openai';
const { text } = await generateText({
model: openai('gpt-4o'),
tools: {
getTime: x402Tool({
endpoint: 'https://minia2a.uk/x402/time',
description: 'Get the current UTC time with millisecond precision',
}),
},
prompt: 'What time is it in UTC right now?',
});
console.log(text);
// → "The current UTC time is 2026-08-09T13:00:00.000Z"With Zod Parameters
import { z } from 'zod';
import { x402Tool } from 'ai-sdk-x402';
const tools = {
getCryptoPrice: x402Tool({
endpoint: 'https://minia2a.uk/x402/crypto-price',
description: 'Get current price of a cryptocurrency',
parameters: z.object({
symbol: z.string().describe('Token symbol, e.g. BTC, ETH, SOL'),
}),
}),
searchWeb: x402Tool({
endpoint: 'https://minia2a.uk/x402/web-search',
description: 'Search the web',
parameters: z.object({
q: z.string().describe('Search query'),
}),
}),
};Paid Calls
When an endpoint requires payment (beyond free trials):
import { X402Client } from 'ai-sdk-x402';
const client = new X402Client({ wallet: '0xYourWalletAddress' });
const result = await client.call('https://minia2a.uk/x402/premium-endpoint', {
// Payment is automatic — the client handles 402 → pay → retry
});
console.log(result.receipt);
// → { txHash: '0x...', amountCents: 5, chain: 'base' }How It Works
AI SDK Tool calls endpoint
│
▼
GET /x402/endpoint
│
┌────┴────┐
│ │
200 402 Payment Required
│ │
▼ ▼
Return Extract payment details
result from 402 response
│
▼
POST /api/v1/pay
(USDC settlement on Base)
│
▼
Retry GET with wallet
│
▼
200 → Return resultDiscovery
Find available x402 endpoints from a marketplace:
import { x402 } from 'ai-sdk-x402';
const catalog = await x402.discover();
console.log(`${catalog.total} services available`);
catalog.services.slice(0, 5).forEach(s => {
console.log(` ${s.name} — ${s.priceCents}¢ — ${s.trialsRemaining} trials left`);
});All Tools in One Go
import { x402Tools } from 'ai-sdk-x402';
const tools = x402Tools({
getTime: { endpoint: 'https://minia2a.uk/x402/time', description: 'Get UTC time' },
searchWeb: { endpoint: 'https://minia2a.uk/x402/web-search', description: 'Search the web' },
getGasPrice: { endpoint: 'https://minia2a.uk/x402/gas', description: 'Get Ethereum gas price' },
});
// Pass directly to generateText / streamText
const { text } = await generateText({ model, tools, prompt: '...' });API Reference
X402Client
| Method | Description |
|--------|-------------|
| call<T>(url, opts?) | Call an x402 endpoint, handling 402 payment flow |
| discover(url?) | List available services from a marketplace |
x402Tool(config)
| Option | Type | Description |
|--------|------|-------------|
| endpoint | string | Full URL of the x402 endpoint |
| description | string | Human-readable description for the AI model |
| parameters | ZodSchema | (optional) Zod schema for tool parameters |
| wallet | string | (optional) Wallet address override |
| transform | (res) => unknown | (optional) Transform response before returning to model |
Error Handling
import { X402Error } from 'ai-sdk-x402';
try {
await x402.call('https://minia2a.uk/x402/broken');
} catch (err) {
if (err instanceof X402Error) {
console.log(err.code); // 'TRIALS_EXHAUSTED' | 'WALLET_REQUIRED' | 'PAYMENT_FAILED' | ...
console.log(err.retryable); // true for timeout/network, false for terminal errors
}
}Supported Marketplaces
Any x402-compatible facilitator works. Tested with:
- minia2a.uk — 326+ services, trial-first, open marketplace
Set via X402_FACILITATOR env var or { facilitator } config.
Contributing
This is a community package. Issues and PRs welcome at github.com/minia2a/ai-sdk-x402.
License
MIT — use it, fork it, build on it.
