AI agents are getting smarter — but they still can’t pay for things. Here’s how I built an MCP server that lets Claude, Cursor, and other AI tools call 120+ crypto APIs and pay per call using the x402 protocol.
What is MCP (Model Context Protocol)?
Model Context Protocol (MCP) is an open standard created by Anthropic that lets AI models connect to external tools and data sources. Think of it as USB-C for AI — a universal plug that lets any AI client talk to any tool server.
Before MCP, every AI integration was bespoke. Want Claude to check gas prices? Custom code. Want Cursor to look up ENS names? Another custom integration. MCP standardizes this into a simple pattern:
- MCP Server exposes tools with typed inputs/outputs
- MCP Client (Claude Desktop, Cursor, etc.) discovers and calls those tools
- The AI model decides when to call each tool based on the conversation
User → AI Client → MCP Server → External API
← ←
The key insight: AI agents can now discover and use tools at runtime, without hardcoded integrations.
The Problem: APIs Need Auth, AI Agents Don’t Have Wallets
Traditional APIs require API keys, OAuth tokens, or subscription plans. This creates friction for AI agents:
- Who provisions the API key?
- Who manages the billing account?
- How do you rate-limit an autonomous agent?
What if the API call itself was the payment? No keys, no accounts, no subscriptions — just pay per call.
Enter x402: HTTP-Native Payments
The x402 protocol (created by Coinbase) adds payments directly into HTTP. When a server returns 402 Payment Required, it includes payment details in the response headers. The client pays (in USDC on Base), and the server fulfills the request.
Client → GET /api/fortune
Server → 402 Payment Required
X-Payment: { amount: "0.001", currency: "USDC", network: "base" }
Client → GET /api/fortune + X-Payment-Proof: <signed tx>
Server → 200 OK { fortune: "Your mass adoption is closer than you think..." }
This is perfect for AI agents because:
- No API keys to manage — payment is authorization
- Micro-transactions — $0.001 per call is viable
- Composable — any HTTP client can pay, including AI agents
Building the MCP Server
I built httpay-mcp — an MCP server that exposes 121+ endpoints from httpay.xyz as MCP tools. Here’s how.
Project Setup
mkdir httpay-mcp && cd httpay-mcp
npm init -y
npm install @modelcontextprotocol/sdk zod
npm install -D typescript tsx @types/node
package.json highlights:
{
"name": "httpay-mcp",
"version": "0.1.0",
"type": "module",
"bin": { "httpay-mcp": "./dist/index.js" },
"dependencies": {
"@modelcontextprotocol/sdk": "^1.12.0",
"zod": "^3.25.0"
}
}
Step 1: Define Your Endpoint Catalog
First, I defined every API endpoint as a typed object. Each endpoint has a name, path, description, price, and parameters:
// src/endpoints.ts
export interface EndpointParam {
name: string;
description: string;
required: boolean;
in: "path" | "query";
}
export interface Endpoint {
name: string;
method: "GET";
path: string;
description: string;
price: string;
category: string;
params: EndpointParam[];
}
// Helper to define endpoints concisely
function ep(
category: string,
path: string,
description: string,
price: string,
params: EndpointParam[] = []
): Endpoint {
const name = path
.replace(/^\/api\//, "")
.replace(/\/:[^/]+/g, "")
.replace(/[/-]/g, "_");
return { name, method: "GET", path, description, price, category, params };
}
export const ENDPOINTS: Endpoint[] = [
ep("Fun", "/api/fortune", "Crypto fortune cookie", "$0.001"),
ep("Fun", "/api/roast-my-wallet/:address", "Roast on-chain activity", "$0.002",
[p("address", "Wallet address to roast")]),
ep("Tools", "/api/token-price/:symbol", "Live token price", "$0.005",
[p("symbol", "Token symbol e.g. ETH")]),
// ... 118 more endpoints across Fun, Tools, Analysis, Games, Dev, Novelty
];
The full catalog covers 121 endpoints across 9 categories — everything from crypto fortune cookies ($0.001) to real-time x402 transaction monitoring ($0.05).
Step 2: Create the MCP Server
The core of the MCP server dynamically registers every endpoint as a tool:
// src/index.ts
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import { ENDPOINTS, type Endpoint } from "./endpoints.js";
const server = new McpServer({
name: "httpay",
version: "0.1.0",
});
for (const endpoint of ENDPOINTS) {
// Build Zod schema from endpoint params
const schemaShape: Record<string, z.ZodTypeAny> = {};
for (const param of endpoint.params) {
const field = z.string().describe(param.description);
schemaShape[param.name] = param.required ? field : field.optional();
}
const description = [
endpoint.description,
`Category: ${endpoint.category}`,
`Price: ${endpoint.price}`,
`Endpoint: ${endpoint.method} ${endpoint.path}`,
].join("\n");
server.tool(endpoint.name, description, schemaShape, async (args) => {
const result = await callEndpoint(endpoint, args as Record<string, string>);
return {
content: [{ type: "text" as const, text: result }],
};
});
}
The key pattern: one endpoint definition → one MCP tool. The AI client sees all 121 tools with their descriptions and typed parameters.
Step 3: Handle x402 Payment Flow
The callEndpoint function handles HTTP calls and x402 payment negotiation:
async function callEndpoint(
endpoint: Endpoint,
args: Record<string, string>
): Promise<string> {
const url = buildUrl(endpoint, args);
const response = await fetch(url, {
headers: {
Accept: "application/json",
"User-Agent": "httpay-mcp/0.1.0",
},
});
if (response.status === 402) {
const paymentInfo = await response.text();
return JSON.stringify({
status: 402,
message: "Payment required (x402). Cost: " + endpoint.price,
endpoint: url,
paymentInfo: paymentInfo.substring(0, 2000),
});
}
if (!response.ok) {
return JSON.stringify({
error: true,
status: response.status,
message: await response.text().catch(() => response.statusText),
});
}
const contentType = response.headers.get("content-type") || "";
if (contentType.includes("application/json")) {
return JSON.stringify(await response.json(), null, 2);
}
return await response.text();
}
Step 4: Wire Up the Transport
MCP servers communicate over stdio — the simplest and most universal transport:
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error(`httpay MCP server started with ${ENDPOINTS.length} tools`);
}
main().catch((error) => {
console.error("Fatal error:", error);
process.exit(1);
});
The server reads JSON-RPC messages from stdin and writes responses to stdout. Any MCP client can connect.
Step 5: Configure Claude Desktop
Add the server to your Claude Desktop config (~/Library/Application Support/Claude/claude_desktop_config.json):
{
"mcpServers": {
"httpay": {
"command": "node",
"args": ["/path/to/httpay-mcp/dist/index.js"]
}
}
}
Restart Claude Desktop, and you’ll see 121 new tools available. Ask Claude anything:
"What’s the current gas price on Base?"
→ Claude callsgas_oracletool → returns live gas data"Roast my wallet 0xd8dA6BF..."
→ Claude callsroast_my_walletwith the address → personalized roast
How AI Agents Discover and Pay for APIs
With MCP + x402, the flow for an AI agent becomes:
- Discovery: Agent connects to MCP server, receives tool list with descriptions and pricing
- Selection: Based on user’s request, the agent picks the right tool
- Execution: Agent calls the tool, MCP server hits the x402 API
- Payment: x402 handles micro-payment automatically (USDC on Base)
- Response: Data flows back through MCP to the agent
No API keys. No OAuth. No billing dashboards. The agent just uses the tools and pays for what it uses.
The Bigger Picture
This pattern — MCP for discovery + x402 for payment — could fundamentally change how AI agents interact with the web:
- API developers can monetize without building auth systems
- AI agents can autonomously discover and pay for services
- Users pay only for what they use, at micro-transaction scale
- The market becomes more efficient — any API can be instantly monetizable
Imagine an AI agent that needs weather data, crypto prices, and sentiment analysis. It discovers three MCP servers, calls the cheapest endpoints from each, pays fractions of a cent per call, and synthesizes the result. No accounts created, no subscriptions started.
Try It Yourself
- 🌐 API Marketplace: httpay.xyz — 121+ pay-per-call endpoints
- 🔧 MCP Server: github.com/alfredz0x/httpay-mcp
- 📖 x402 Protocol: x402.org
- 📖 MCP Specification: modelcontextprotocol.io
The combination of MCP and x402 turns every API into an AI-native, pay-per-call service. We’re early, but the infrastructure is here. Start building.
Previously: How to Build Pay-Per-Call APIs with x402 and USDC on Base
Top comments (0)