x402-mcp

x402-mcp

A hybrid MCP server that integrates x402 payment protocol, providing tools to manage cryptocurrency payments and dynamically create HTTP endpoints protected by payments.

Category
Visit Server

README

x402-mcp

A TypeScript MCP (Model Context Protocol) Server with Express.js integration for the x402 Payment Protocol.

Overview

This is a hybrid MCP server that combines:

  • MCP Server: Provides tools to interact with the x402 payment protocol through the Model Context Protocol
  • Express HTTP Server: Creates payment-protected HTTP endpoints using x402 payment middleware

This allows AI assistants and MCP clients to both manage x402 payments AND dynamically create HTTP endpoints protected by cryptocurrency payments. Built with TypeScript, the official MCP SDK, and x402-express middleware.

Features

šŸ”§ MCP Tools for Payment Management

  • x402_create_payment_request: Create a new payment request with specified price and details
  • x402_check_payment_status: Check the status of an existing payment request
  • x402_get_config: Get the current x402 configuration (payment address, network, facilitator URL)
  • x402_list_networks: List available networks for x402 payments

🌐 MCP Tools for Express Endpoint Management

  • x402_create_protected_endpoint: Dynamically create HTTP endpoints protected by x402 payment middleware
  • x402_list_protected_endpoints: List all protected endpoints on the Express server
  • x402_get_express_server_status: Get Express server status (running state, port, endpoint count)
  • x402_update_endpoint_price: Update the price for an existing protected endpoint

āš™ļø Configuration

  • Payment Address: 0x243E0B615BfEa0f315109b8b415e3D6b9c3131F7
  • Network: Base Sepolia (testnet) - change to "base" for mainnet
  • Payment Token: USDC (stablecoin)
  • Facilitator URL: https://x402.org/facilitator (testnet)
  • Express Port: 4021

Installation

npm install

Development

Run the server in development mode with hot reload:

npm run dev

Build

Compile TypeScript to JavaScript:

npm run build

Production

Run the compiled server:

npm start

Architecture

This is a hybrid server that runs two servers simultaneously:

ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│                      x402-mcp Process                        │
ā”œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¤
│                                                              │
│  ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”  ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”ā”‚
│  │   MCP Server (stdio)     │  │  Express HTTP Server     ││
│  │                          │  │  (Port 4021)             ││
│  │  • Tool Management       │  │                          ││
│  │  • Payment Requests      │  │  • Payment Middleware    ││
│  │  • Endpoint Management   │  │  • Protected Routes      ││
│  │  • Configuration         │  │  • Health Check          ││
│  ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜  ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜ā”‚
│                                                              │
│              Both use X402_CONFIG shared state               │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
                              │
                              ā–¼
                    x402 Facilitator
                 (Payment Verification)

Key Components

  1. MCP Server: Communicates via stdio, provides tools to AI assistants
  2. Express Server: HTTP server with x402 payment middleware
  3. ExpressServerManager: Manages Express lifecycle and protected endpoints
  4. X402Handler: Handles manual payment request creation and tracking
  5. x402-express Middleware: Intercepts HTTP requests, enforces payments

Project Structure

x402-mcp/
ā”œā”€ā”€ src/
│   └── index.ts          # Main implementation (MCP + Express hybrid)
ā”œā”€ā”€ dist/                 # Compiled JavaScript output
ā”œā”€ā”€ package.json          # Dependencies and scripts
ā”œā”€ā”€ tsconfig.json         # TypeScript configuration
ā”œā”€ā”€ .gitignore           # Git ignore rules
└── README.md            # This file

Usage with MCP Clients

Configuration

Add this server to your MCP client configuration (e.g., Claude Desktop):

{
  "mcpServers": {
    "x402-mcp": {
      "command": "node",
      "args": ["/path/to/x402-mcp/dist/index.js"]
    }
  }
}

For development:

{
  "mcpServers": {
    "x402-mcp": {
      "command": "npm",
      "args": ["run", "dev"],
      "cwd": "/path/to/x402-mcp"
    }
  }
}

Example Tool Calls

Create a Protected HTTP Endpoint

{
  "name": "x402_create_protected_endpoint",
  "arguments": {
    "path": "/weather",
    "method": "GET",
    "price": "$0.001",
    "description": "Get current weather data for any location",
    "responseData": {
      "weather": "sunny",
      "temperature": 72,
      "humidity": 45
    },
    "inputSchema": {
      "type": "object",
      "properties": {
        "location": {
          "type": "string",
          "description": "City name"
        }
      }
    },
    "outputSchema": {
      "type": "object",
      "properties": {
        "weather": { "type": "string" },
        "temperature": { "type": "number" },
        "humidity": { "type": "number" }
      }
    }
  }
}

Response:

{
  "success": true,
  "message": "Protected endpoint created successfully",
  "data": {
    "endpoint": "GET /weather",
    "url": "http://localhost:4021/weather",
    "price": "$0.001",
    "description": "Get current weather data for any location",
    "network": "base-sepolia",
    "payTo": "0x243E0B615BfEa0f315109b8b415e3D6b9c3131F7"
  }
}

Now when someone accesses http://localhost:4021/weather without payment, they'll receive a 402 Payment Required response with payment instructions!

Create Payment Request

{
  "name": "x402_create_payment_request",
  "arguments": {
    "price": "$0.50",
    "description": "Access to premium API endpoint",
    "resource": "/api/premium/data",
    "maxTimeoutSeconds": 120
  }
}

Response:

{
  "success": true,
  "message": "Payment request created successfully",
  "data": {
    "paymentId": "x402_1234567890_abc123",
    "paymentUrl": "https://x402.org/facilitator/pay?id=...",
    "price": "$0.50",
    "network": "base-sepolia",
    "payTo": "0x243E0B615BfEa0f315109b8b415e3D6b9c3131F7",
    "description": "Access to premium API endpoint",
    "expiresAt": "2024-01-01T12:02:00.000Z"
  }
}

List All Protected Endpoints

{
  "name": "x402_list_protected_endpoints",
  "arguments": {}
}

Response:

{
  "success": true,
  "message": "Found 1 protected endpoint(s)",
  "data": [
    {
      "method": "GET",
      "path": "/weather",
      "price": "$0.001",
      "description": "Get current weather data for any location",
      "url": "http://localhost:4021/weather"
    }
  ]
}

Get Express Server Status

{
  "name": "x402_get_express_server_status",
  "arguments": {}
}

Response:

{
  "success": true,
  "message": "Express server is running",
  "data": {
    "isRunning": true,
    "port": 4021,
    "network": "base-sepolia",
    "payTo": "0x243E0B615BfEa0f315109b8b415e3D6b9c3131F7",
    "facilitatorUrl": "https://x402.org/facilitator",
    "endpointCount": 1,
    "endpoints": [...]
  }
}

Check Payment Status

{
  "name": "x402_check_payment_status",
  "arguments": {
    "paymentId": "x402_1234567890_abc123"
  }
}

Response:

{
  "success": true,
  "data": {
    "paymentId": "x402_1234567890_abc123",
    "status": "pending",
    "paid": false,
    "price": "$0.50",
    "network": "base-sepolia",
    "createdAt": "2024-01-01T12:00:00.000Z",
    "expiresAt": "2024-01-01T12:02:00.000Z"
  }
}

Get Configuration

{
  "name": "x402_get_config",
  "arguments": {}
}

Response:

{
  "success": true,
  "message": "Current x402 configuration",
  "data": {
    "payTo": "0x243E0B615BfEa0f315109b8b415e3D6b9c3131F7",
    "network": "base-sepolia",
    "facilitatorUrl": "https://x402.org/facilitator"
  }
}

List Networks

{
  "name": "x402_list_networks",
  "arguments": {}
}

Response:

{
  "success": true,
  "message": "Available networks for x402 payments",
  "data": [
    {
      "name": "base",
      "displayName": "Base Mainnet",
      "chainId": 8453,
      "currency": "ETH",
      "stablecoin": "USDC",
      "isMainnet": true
    },
    {
      "name": "base-sepolia",
      "displayName": "Base Sepolia Testnet",
      "chainId": 84532,
      "currency": "ETH",
      "stablecoin": "USDC",
      "isMainnet": false
    },
    {
      "name": "avalanche",
      "displayName": "Avalanche C-Chain",
      "chainId": 43114,
      "currency": "AVAX",
      "stablecoin": "USDC",
      "isMainnet": true
    },
    {
      "name": "solana",
      "displayName": "Solana Mainnet",
      "chainId": null,
      "currency": "SOL",
      "stablecoin": "USDC",
      "isMainnet": true
    }
  ]
}

Error Handling

The server includes comprehensive error handling:

  • Payment not found: Returns error when checking status of non-existent payment
  • Invalid payment status: Prevents operations on payments in wrong state
  • Expired payments: Automatically marks pending payments as expired
  • Invalid arguments: Validates using Zod schemas with detailed error messages

Technology Stack

  • TypeScript: Type-safe development
  • Node.js: Runtime environment
  • MCP SDK: Official Model Context Protocol SDK
  • x402-express: x402 Payment Protocol integration
  • Zod: Runtime type validation

How x402 Protocol Works

The x402 protocol is a standard for HTTP-based cryptocurrency payments. This hybrid MCP server provides two complementary approaches:

Approach 1: Express Middleware (Recommended)

This is the standard x402 flow using Express middleware:

  1. Create Protected Endpoint: Use x402_create_protected_endpoint to dynamically create an HTTP endpoint
  2. Client Makes Request: When a client accesses the endpoint without payment, they receive HTTP 402 Payment Required
  3. Payment Instructions: The 402 response includes payment details (amount, address, network) in the response body
  4. Client Pays: Client submits payment transaction on the blockchain
  5. Retry with Proof: Client retries the request with X-PAYMENT header containing cryptographic proof of payment
  6. Middleware Verifies: x402 middleware verifies the payment via the facilitator
  7. Access Granted: If valid, the endpoint returns the protected content

Approach 2: Manual Payment Requests

For custom payment flows:

  1. Call x402_create_payment_request with price and details
  2. Server returns a payment URL and unique payment ID
  3. User completes payment through the payment URL
  4. Call x402_check_payment_status to verify payment completion
  5. Grant access to resource once payment is confirmed

Network Support

  • Base (mainnet) and Base Sepolia (testnet)
  • Avalanche C-Chain (mainnet) and Avalanche Fuji (testnet)
  • Solana (mainnet) and Solana Devnet (testnet)
  • All payments processed in USDC stablecoin

Use Cases

  • AI API Monetization: Charge for expensive AI model inference calls
  • Content Paywalls: Gate premium content behind cryptocurrency payments
  • Micro-transactions: Enable small payments for individual API calls (as low as $0.001)
  • Resource Access Control: Manage access to computational resources
  • Dynamic API Marketplaces: AI agents can discover and pay for APIs automatically
  • Pay-per-use Services: Weather data, stock prices, translation APIs, etc.

Running on Mainnet

To accept real payments on mainnet, you need to make a few changes:

1. Set up CDP API Keys

  1. Sign up at cdp.coinbase.com
  2. Create a new project and generate API credentials
  3. Set environment variables:
    export CDP_API_KEY_ID=your-api-key-id
    export CDP_API_KEY_SECRET=your-api-key-secret
    

2. Update Configuration in src/index.ts

// Uncomment the facilitator import
import { facilitator } from "@coinbase/x402";

const X402_CONFIG = {
  payTo: "0xYourMainnetAddress", // Your real mainnet wallet address
  network: "base" as const, // Change from "base-sepolia" to "base"
  facilitatorUrl: "https://x402.org/facilitator", // Not used for mainnet
  expressPort: 4021,
};

3. Update Express Middleware to Use CDP Facilitator

In the applyPaymentMiddleware() method:

private applyPaymentMiddleware() {
  if (Object.keys(this.routeConfigs).length > 0) {
    this.app.use(paymentMiddleware(
      X402_CONFIG.payTo,
      this.routeConfigs,
      facilitator // Use CDP facilitator instead of testnet URL
    ));
  }
}

Customization

Testnet Configuration (Current)

const X402_CONFIG = {
  payTo: "0xYourAddress", // Your receiving wallet address
  network: "base-sepolia" as const, // or "avalanche-fuji", "solana-devnet"
  facilitatorUrl: "https://x402.org/facilitator",
  expressPort: 4021,
};

Mainnet Configuration

const X402_CONFIG = {
  payTo: "0xYourAddress", // Your receiving wallet address
  network: "base" as const, // or "avalanche", "solana"
  facilitatorUrl: "https://x402.org/facilitator",
  expressPort: 4021,
};

Note: When you specify prices like "$0.50", the x402 protocol automatically processes payments in USDC on the selected network.

Resources

License

MIT

Recommended Servers

playwright-mcp

playwright-mcp

A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.

Official
Featured
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.

Official
Featured
Local
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.

Official
Featured
Local
TypeScript
VeyraX MCP

VeyraX MCP

Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.

Official
Featured
Local
graphlit-mcp-server

graphlit-mcp-server

The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.

Official
Featured
TypeScript
Kagi MCP Server

Kagi MCP Server

An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.

Official
Featured
Python
E2B

E2B

Using MCP to run code via e2b.

Official
Featured
Neon Database

Neon Database

MCP server for interacting with Neon Management API and databases

Official
Featured
Exa Search

Exa Search

A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.

Official
Featured
Qdrant Server

Qdrant Server

This repository is an example of how to create a MCP server for Qdrant, a vector search engine.

Official
Featured