DEV Community

tradeit
tradeit

Posted on

I Built an API That AI Agents Pay For — Here's How (x402 + MCP)

What if AI agents could discover your API and pay you in USDC — automatically?

I built a DeFi intelligence API with 6 endpoints. Each call costs $0.005–$0.10. Agents pay USDC on Base L2. No API keys, no subscriptions. Just micropayments.

The Problem

Traditional API monetization doesn't work for AI agents. They can't sign up for accounts, manage API keys, or handle subscriptions. They need to pay per request without human intervention.

x402: HTTP's Missing Payment Layer

x402 is an open standard backed by Coinbase that finally puts a protocol behind HTTP's 402 Payment Required status code:

  1. Agent calls your API → gets 402 with payment details
  2. Agent pays USDC via a facilitator
  3. Agent retries with payment proof → gets data

Under a second, fully automated.

What I Built

Endpoint Price Data
/prices $0.005 Top 30 token prices
/yields $0.02 Yield rates across 3000+ protocols
/funding-rates $0.05 Perp funding rates (Binance, Bybit)
/whales $0.05 Wallet movements >$500K
/rwa-opportunities $0.08 Scored tokenized real-world assets
/signal-summary $0.10 AI-synthesized market snapshot

The Key Code

Gate any endpoint with x402 payments:

// Set price per endpoint
const routeConfig = {
  'GET /prices': {
    accepts: {
      scheme: 'exact',
      price: '$0.005',
      network: 'eip155:8453', // Base L2
      payTo: walletAddress,
    },
  },
};

// One line to gate all paid endpoints
app.use(paymentMiddleware(routeConfig, resourceServer));
Enter fullscreen mode Exit fullscreen mode

Add an MCP manifest so AI agents auto-discover your tools:

// GET /mcp — agents read this to find your tools
{
  name: 'defi-signal-api',
  tools: [{
    name: 'get_prices',
    description: 'Token prices for top 30 assets.',
    x402: { price: '0.005', currency: 'USDC', chain: 'base' },
  }],
}
Enter fullscreen mode Exit fullscreen mode

Claude, ChatGPT, and other LLMs can call these directly.

Build Your Own

I packaged the whole project as a starter kit — full source, 77 tests, one-command Railway deploy, and a customization guide.

Get the x402 API Starter Kit →


Questions? Find me on GitHub.

Top comments (0)