Building an x402-Powered MCP Server: Let AI Agents Pay for Your Tools

tutorial MCP ai-agents · x402 Guide

What if AI Agents Could Pay for Your Developer Tools?

The Model Context Protocol (MCP) is rapidly becoming the standard way AI agents connect to external tools and data sources. Claude, GPT, and other AI assistants already use MCP servers to read files, query databases, call APIs, and more. But here is the missing piece: how do you charge for those tools?

By combining MCP with the x402 payment protocol, you can build tools that AI agents discover, use, and pay for automatically. No API keys. No billing dashboards. No invoices. The agent hits your tool, pays a few cents in USDC, and gets the result. This is how the autonomous AI economy works.

In this tutorial, you will learn exactly how to build an x402 MCP server from scratch. We will also look at a real, live example: the askclaude-mcp npm package, which connects AI agents to AskClaude.shop through MCP with x402 payments built in.

What is MCP (Model Context Protocol)?

MCP is an open standard created by Anthropic that defines how AI agents communicate with external tools and data sources. Think of it as a universal plug system: any AI agent that speaks MCP can connect to any MCP server, regardless of who built either side.

An MCP server exposes tools (functions the agent can call), resources (data the agent can read), and prompts (templates for common tasks). The AI agent discovers what is available, decides what it needs, and calls the appropriate tool.

Here is the key insight: MCP servers are already the interface between AI agents and the outside world. Adding x402 payments to that interface means agents can pay for premium tools the same way they call free ones. The payment becomes invisible plumbing.

Why MCP + x402 Is a Perfect Match

Architecture: How an x402 MCP Server Works

A standard MCP server receives tool calls from AI agents and returns results. An x402 MCP server adds a payment layer between the request and the execution:

┌─────────────┐     MCP Protocol     ┌──────────────────┐     x402 Payment     ┌──────────────┐
│  AI Agent   │ ──────────────────▶  │  x402 MCP Server │ ──────────────────▶  │  Facilitator │
│  (Claude)   │ ◀──────────────────  │  (Your Server)   │ ◀──────────────────  │  (Coinbase)  │
└─────────────┘     Tool Results     └──────────────────┘     Settlement       └──────────────┘

The flow works like this:

  1. AI agent connects to your MCP server and discovers available tools
  2. Agent calls a tool (e.g., ask_claude or analyze_data)
  3. Your server checks for a valid x402 payment header
  4. If no payment: return a 402 response with pricing details
  5. Agent generates a USDC payment authorization and retries
  6. Your server verifies payment via the facilitator, executes the tool, and returns the result
  7. Facilitator settles the USDC on-chain

Step-by-Step: Building Your x402 MCP Server

Prerequisites

Step 1: Initialize the Project

mkdir x402-mcp-server
cd x402-mcp-server
npm init -y
npm install @modelcontextprotocol/sdk express x402-express

The @modelcontextprotocol/sdk package provides the MCP server framework. The x402-express package handles x402 payment verification as Express middleware.

Step 2: Define Your MCP Tools

Create your server entry point. Each tool you define becomes something AI agents can discover and call:

// server.js
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";

const server = new McpServer({
  name: "my-x402-tools",
  version: "1.0.0",
  description: "Premium AI tools — pay per use with x402"
});

// Define a paid tool
server.tool(
  "summarize_document",
  "Summarize any document using advanced AI. Costs $0.01 per request.",
  {
    content: z.string().describe("The document text to summarize"),
    style: z.enum(["brief", "detailed", "bullets"])
      .describe("Summary style")
  },
  async ({ content, style }) => {
    // This is where your tool logic goes
    const summary = await generateSummary(content, style);
    return {
      content: [{ type: "text", text: summary }]
    };
  }
);

// Define another paid tool
server.tool(
  "analyze_sentiment",
  "Analyze sentiment of text. Costs $0.005 per request.",
  {
    text: z.string().describe("Text to analyze")
  },
  async ({ text }) => {
    const result = await analyzeSentiment(text);
    return {
      content: [{ type: "text", text: JSON.stringify(result) }]
    };
  }
);

Step 3: Add the x402 Payment Layer

Now wrap your MCP server with an HTTP transport that enforces x402 payments. This is where the payment verification happens:

// http-server.js
import express from "express";
import { paymentMiddleware } from "x402-express";

const app = express();

// Your wallet address on Base — this is where USDC payments go
const PAYEE_ADDRESS = "0xYourWalletAddress";

// Facilitator URL (Coinbase CDP or UltravioletaDAO)
const FACILITATOR_URL = "https://x402.org/facilitator";

// Define pricing per tool endpoint
const toolPricing = {
  "/tools/summarize_document": "$0.01",
  "/tools/analyze_sentiment": "$0.005"
};

// Apply x402 middleware to paid endpoints
for (const [path, price] of Object.entries(toolPricing)) {
  app.use(path, paymentMiddleware(
    PAYEE_ADDRESS,
    {
      [path]: {
        price: price,
        network: "base-sepolia",   // Use "base" for production
        config: {
          description: `Payment for ${path}`
        }
      }
    },
    FACILITATOR_URL
  ));
}

// Tool execution endpoints
app.post("/tools/summarize_document", async (req, res) => {
  const { content, style } = req.body;
  const summary = await generateSummary(content, style);
  res.json({ result: summary });
});

app.post("/tools/analyze_sentiment", async (req, res) => {
  const { text } = req.body;
  const result = await analyzeSentiment(text);
  res.json({ result });
});

// Free discovery endpoint — agents can see what tools are available
app.get("/tools", (req, res) => {
  res.json({
    tools: [
      {
        name: "summarize_document",
        description: "Summarize any document using advanced AI",
        price: "$0.01 USDC",
        endpoint: "/tools/summarize_document"
      },
      {
        name: "analyze_sentiment",
        description: "Analyze sentiment of text",
        price: "$0.005 USDC",
        endpoint: "/tools/analyze_sentiment"
      }
    ],
    payment: {
      protocol: "x402",
      network: "base",
      currency: "USDC",
      facilitator: FACILITATOR_URL
    }
  });
});

app.listen(4022, () => {
  console.log("x402 MCP Server running on port 4022");
});

Step 4: Create the MCP Configuration File

AI agents need to know how to connect to your server. Create an MCP configuration that clients like Claude Desktop or Claude Code can use:

// mcp-config.json
{
  "mcpServers": {
    "my-x402-tools": {
      "command": "node",
      "args": ["server.js"],
      "env": {
        "X402_SERVER_URL": "https://your-server.com",
        "X402_WALLET_KEY": "your-agent-wallet-private-key"
      }
    }
  }
}

When an agent adds this configuration, it automatically discovers your tools and can start using (and paying for) them immediately.

Step 5: Handle the Payment Flow in the MCP Client

On the agent side, the MCP client needs to handle 402 responses. Here is how a client wrapper handles the payment flow transparently:

// mcp-x402-client.js
import { ethers } from "ethers";

class X402McpClient {
  constructor(serverUrl, walletPrivateKey) {
    this.serverUrl = serverUrl;
    this.wallet = new ethers.Wallet(walletPrivateKey);
  }

  async callTool(toolName, params) {
    // First attempt — will get 402 if payment required
    let response = await fetch(`${this.serverUrl}/tools/${toolName}`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(params)
    });

    if (response.status === 402) {
      // Extract payment requirements
      const paymentDetails = await response.json();

      // Generate x402 payment authorization
      const authorization = await this.createPaymentAuth(paymentDetails);

      // Retry with payment
      response = await fetch(`${this.serverUrl}/tools/${toolName}`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-PAYMENT": authorization
        },
        body: JSON.stringify(params)
      });
    }

    if (!response.ok) {
      throw new Error(`Tool call failed: ${response.statusText}`);
    }

    return await response.json();
  }

  async createPaymentAuth(paymentDetails) {
    const { amount, recipient, validAfter, validBefore } = paymentDetails;

    // Sign EIP-3009 transferWithAuthorization
    const signature = await this.wallet.signTypedData(
      paymentDetails.domain,
      paymentDetails.types,
      paymentDetails.message
    );

    return JSON.stringify({ ...paymentDetails.message, signature });
  }
}

Real-World Example: askclaude-mcp

You do not have to start from scratch. The askclaude-mcp npm package is a live, working example of an x402 MCP server in production. It connects AI agents to AskClaude.shop, which offers 9 paid endpoints including enhanced AI queries, code review, market analysis, and more.

Installing it is one command:

npm install -g askclaude-mcp

Then add it to your Claude Desktop or Claude Code MCP configuration:

{
  "mcpServers": {
    "askclaude": {
      "command": "askclaude-mcp",
      "env": {
        "ASKCLAUDE_WALLET_KEY": "your-wallet-private-key"
      }
    }
  }
}

Once connected, your AI agent can call tools like ask_claude, code_review, or market_analysis. Each call triggers an x402 payment of a few cents, the service processes the request, and the agent gets the result. No signup, no API key, no billing portal.

This is exactly how the x402 MCP server pattern works in production. The package handles all the payment flow internally so the agent experience is seamless.

Monetization Strategies for Your MCP Tools

Building an x402 MCP server opens up several revenue models:

Per-Call Pricing

The simplest model. Each tool invocation costs a fixed amount. Good for stateless operations like text analysis, data lookups, or API aggregation. This is what AskClaude.shop uses, with prices ranging from $0.01 to $0.10 per call depending on the tool.

Tiered Pricing by Complexity

Charge more for expensive operations. A quick sentiment check might cost $0.005, while a full document analysis costs $0.05. You can even inspect the input and price dynamically based on content length or complexity.

Freemium Discovery

Make your tool discovery endpoint free (no x402 payment required) so agents can see what you offer. Then charge for actual tool execution. This lowers the barrier to discovery while still monetizing usage.

Bundle Pricing

Offer a "session" payment that covers multiple tool calls. The agent pays once and gets a token valid for N calls within a time window. This reduces transaction overhead for high-frequency tools.

Deployment and Best Practices

Use HTTPS in Production

x402 payment headers contain signed authorization data. Always serve your MCP server over HTTPS to prevent interception. Use a reverse proxy like Cloudflare or Caddy in front of your Node.js server.

Choose the Right Facilitator

Your choice of x402 facilitator affects settlement speed and fees. Coinbase CDP Facilitator is the most widely used and trusted. UltravioletaDAO offers a decentralized alternative. Both work with the x402-express middleware.

Test on Base Sepolia First

Always test your payment flow on Base Sepolia testnet before going to production. Testnet USDC is free and the payment flow is identical. Switch to mainnet Base by changing the network configuration.

Implement Rate Limiting

Even with x402 payments, implement rate limiting to protect your server from abuse. A paid request is still a request that consumes your compute resources:

import rateLimit from "express-rate-limit";

const limiter = rateLimit({
  windowMs: 60 * 1000,  // 1 minute
  max: 30,               // 30 requests per minute per IP
  message: { error: "Rate limit exceeded. Try again shortly." }
});

app.use("/tools", limiter);

Log Everything

Track every payment and tool invocation. This gives you analytics on which tools are popular, what agents are willing to pay, and where your revenue comes from. It also helps with debugging failed payments.

The Bigger Picture: MCP as the AI Agent App Store

MCP is quickly becoming the "app store" for AI agents. Just as smartphones created a market for mobile apps, MCP is creating a market for AI agent tools. Adding x402 payments to MCP servers turns that market into a real economy.

Today, most MCP servers are free and open source. That is changing. As AI agents handle more complex tasks and operate with real budgets, the demand for premium, reliable, specialized tools will grow. Developers who build high-quality x402 MCP servers now are positioning themselves at the foundation of this emerging market.

The tools are ready. The protocol exists. The agents are already paying. The question is whether you will build the tools they pay for.

Try an x402 MCP Server Right Now

Install the askclaude-mcp package and connect your AI agent to a live x402 service in minutes.

Get askclaude-mcp on npm