x402-mcp-agent
v0.4.5
Published
MCP server and SDK for autonomous x402 payments
Maintainers
Readme
x402-mcp-agent
Embedded MCP server for autonomous x402 payment handling in LLM applications. Add x402 micropayment capabilities directly to your codebase - your LLM can call the embedded MCP to handle all x402 needs (making x402 calls, handling facilitator and payment settlement, and generating transaction hashes).
Two Ways to Use
1️⃣ Embedded MCP in Your Codebase (Recommended)
Best for: Integrating x402 payments directly into your application with an embedded MCP server.
Add an embedded MCP server to your project that your LLM can call:
npx x402-mcp-agent initThis generates:
- Embedded MCP Server - Add to your codebase, your LLM calls it to handle x402 payments
x402-endpoints.json- Configure your x402 endpointslib/x402/- Payment utilities (logger, config, wallet, types)- Framework-specific API routes (Vite, Next.js, or Express)
How it works: Your LLM calls the embedded MCP server, which automatically handles:
- Making x402 API calls
- Handling facilitator and payment settlement
- Generating transaction hashes
- Returning results with BaseScan links
Supported frameworks: Vite, Next.js, Express, or framework-agnostic TypeScript utilities.
2️⃣ Standalone MCP Server
Best for: Using with Claude Desktop, Claude Code, or other external MCP clients.
Run as a standalone MCP server:
npx x402-mcp-agent serveExposes configured x402 endpoints as MCP tools for autonomous agent access.
Features
- Autonomous Payments: Automatic x402 payment handling using CDP embedded wallets
- Multiple Integration Modes: CLI code generator or MCP server
- Framework Support: Vite, Next.js, Express, or framework-agnostic
- Flexible Configuration: JSON-based endpoint configuration with environment variable support
- Security First: Trust model ensures only approved endpoints can be called
- Multi-Network Support: Works with Base, Base Sepolia, Ethereum, and Sepolia testnets
- Production Ready: Used in production applications with automatic payment retries
Prerequisites
- Node.js >= 18.0.0
- A CDP embedded wallet with USDC balance
CLI Code Generator
Quick Start
# Navigate to your project directory
cd my-ai-app
# Run the CLI to scaffold x402 payment handling
npx x402-mcp-agent init
# Edit the generated x402-endpoints.json to configure your endpoints
# Add your private key to .env
echo "PRIVATE_KEY=0x..." >> .env
# Install dependencies and start using x402 endpoints!
npm iWhat Gets Generated
The CLI creates the following files in your project:
Framework-Agnostic Files (Always Created)
x402-endpoints.json- Configuration file with example endpointslib/x402/payment-logger.ts- Payment logging utilities with BaseScan linkslib/x402/config.ts- Config loader with environment variable interpolationlib/x402/types.ts- TypeScript type definitionslib/x402/wallet.ts- Wallet setup and x402-fetch wrapper utilities
Framework-Specific API Routes
Vite (+ Vercel Functions):
api/x402/proxy.ts- Generic proxy handler for x402 endpoints
Next.js (App Router):
app/api/x402/[endpoint]/route.ts- Dynamic route handler
Express:
routes/x402.ts- Express router with middleware
None (Framework-agnostic):
- Only the shared utilities above (no API routes)
CLI Options
init command (code generator)
npx x402-mcp-agent init [options]
Options:
-f, --framework <type> Specify framework (vite|nextjs|express|none)
--auto-detect Auto-detect framework from package.json (default)
-o, --output-dir <path> Output directory (default: current directory)
--skip-install Skip automatic dependency installation
-h, --help Display helpserve command (MCP server)
npx x402-mcp-agent serve [options]
Options:
-t, --transport <type> Transport type: stdio or sse (default: stdio)
-p, --port <number> Port for SSE transport (default: 8000)
--host <address> Host address for SSE transport (default: 0.0.0.0)
-h, --help Display help
Examples:
npx x402-mcp-agent serve # stdio mode (Claude Desktop)
npx x402-mcp-agent serve --transport sse # SSE mode on port 8000
npx x402-mcp-agent serve --transport sse -p 3000 # SSE mode on port 3000Examples
Vite + React Application
# Auto-detect Vite and generate appropriate files
cd my-vite-app
npx x402-mcp-agent init
# Result:
# ✅ x402-endpoints.json
# ✅ lib/x402/*.ts (utilities)
# ✅ api/x402/proxy.ts (Vercel Function handler)Then use in your React components:
// Call x402 endpoint from your frontend
const response = await fetch('/api/x402/proxy', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
endpointId: 'minifetch_extract_metadata',
params: { url: 'https://example.com' }
})
});
const result = await response.json();
console.log('Data:', result.data);
console.log('Transaction:', result.txHash);
console.log('BaseScan:', `https://basescan.org/tx/${result.txHash}`);Next.js Application
cd my-nextjs-app
npx x402-mcp-agent init --framework nextjs
# Result:
# ✅ x402-endpoints.json
# ✅ lib/x402/*.ts (utilities)
# ✅ app/api/x402/[endpoint]/route.ts (App Router dynamic route)Use in Server Components or API routes:
// app/page.tsx
async function extractMetadata(url: string) {
const response = await fetch('/api/x402/minifetch_extract_metadata', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url })
});
return response.json();
}Express Application
cd my-express-app
npx x402-mcp-agent init --framework express
# Result:
# ✅ x402-endpoints.json
# ✅ lib/x402/*.ts (utilities)
# ✅ routes/x402.ts (Express router)Mount the router in your Express app:
// server.ts
import express from 'express';
import x402Router from './routes/x402.js';
const app = express();
app.use(express.json());
// Mount x402 router
app.use('/api/x402', x402Router);
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
// Now call: POST /api/x402/minifetch_extract_metadataConfiguration
After running the CLI, edit x402-endpoints.json to configure your endpoints:
{
"wallet": {
"provider": "cdp-embedded",
"network": "base",
"privateKey": "${PRIVATE_KEY}"
},
"endpoints": [
{
"id": "minifetch_extract_metadata",
"name": "Extract URL Metadata",
"url": "https://minifetch.com/api/v1/x402/extract/url-metadata",
"method": "GET",
"description": "Fetch and extract HTML metadata from a URL",
"parameters": {
"type": "object",
"properties": {
"url": { "type": "string", "description": "URL to extract" }
},
"required": ["url"]
},
"estimatedCost": "$0.01",
"trusted": true
}
]
}Set your private key in .env:
PRIVATE_KEY="0x..."MCP Server Usage
The MCP server supports two transport modes:
- stdio (default) - For local MCP clients like Claude Desktop
- SSE (Server-Sent Events) - For HTTP-based remote MCP clients like OpenAI Responses API, ChatGPT Connectors, and deployed web apps
Transport Modes
Stdio Transport (Local)
Run locally for Claude Desktop or other local MCP clients:
npx x402-mcp-agent
# or explicitly:
npx x402-mcp-agent serve --transport stdioSSE Transport (Remote HTTP Server)
Run as HTTP server for OpenAI, ChatGPT, and remote MCP clients:
npx x402-mcp-agent serve --transport sse --port 8000Server will start at http://localhost:8000/sse/
Available endpoints:
/sse- MCP SSE connection endpoint/message- MCP message endpoint/health- Health check/- Server info
Deploy to production:
See examples/vercel-deployment/ for deploying to Vercel, or use any Node.js hosting:
# Replit, Railway, etc.
npx x402-mcp-agent serve --transport sse --port 8000 --host 0.0.0.0Then use with OpenAI Responses API:
const response = await openai.responses.create({
model: 'gpt-4o',
input: [{
role: 'user',
content: [{ type: 'input_text', text: 'Extract metadata from example.com' }]
}],
tools: [{
type: 'mcp',
server_url: 'https://your-x402-server.vercel.app/sse/',
allowed_tools: ['minifetch_extract_metadata'],
require_approval: 'never'
}]
});Or add to ChatGPT Connectors:
- Go to ChatGPT Settings → Connectors
- Add new MCP server:
https://your-x402-server.vercel.app/sse/ - ChatGPT will discover your x402 tools automatically
Prerequisites
- An MCP-compatible client (Claude Desktop, Claude Code, OpenAI, ChatGPT, etc.)
Installation
Global Installation
npm i -g x402-mcp-agentOr Use with npx
npx x402-mcp-agentConfiguration
1. Create Configuration Directory
mkdir -p ~/.x402-agent2. Create Endpoint Configuration
Create ~/.x402-agent/endpoints.json:
{
"wallet": {
"provider": "cdp-embedded",
"network": "base",
"privateKey": "${PRIVATE_KEY}"
},
"endpoints": [
{
"id": "minifetch_extract_metadata",
"name": "Extract URL Metadata",
"url": "https://minifetch.com/api/v1/x402/extract/url-metadata",
"method": "GET",
"description": "Fetch and extract HTML metadata from a specified URL. Returns all HTML meta tags, Open Graph tags, Twitter tags, headings, image tags, and response headers. Set includeResponseBody=true to return entire response body as a string. Useful for SEO and AI research projects.",
"category": "web-scraping",
"parameters": {
"type": "object",
"properties": {
"url": {
"type": "string",
"description": "The URL from which to extract HTML metadata"
},
"includeResponseBody": {
"type": "string",
"description": "If set to 'true', includes the full HTML response body as a string in the result"
}
},
"required": ["url"]
},
"estimatedCost": "$0.01",
"trusted": true
}
]
}See config/endpoints.example.json for a complete example with multiple endpoints.
3. Set Environment Variables
Create a .env file or set environment variables:
export PRIVATE_KEY="0x..."
export X402_CONFIG_PATH="~/.x402-agent/endpoints.json" # Optional, defaults to this
export DEBUG="false" # Set to "true" for debug logging4. Configure Your MCP Client
Claude Desktop (macOS)
Edit ~/Library/Application Support/Claude/claude_desktop_config.json:
{
"mcpServers": {
"x402-agent": {
"command": "npx",
"args": ["-y", "x402-mcp-agent"],
"env": {
"PRIVATE_KEY": "0x...",
"X402_CONFIG_PATH": "~/.x402-agent/endpoints.json"
}
}
}
}Claude Code
Edit ~/.claude/settings.json:
{
"mcp": {
"x402-agent": {
"command": "npx x402-mcp-agent",
"env": {
"PRIVATE_KEY": "0x...",
"X402_CONFIG_PATH": "~/.x402-agent/endpoints.json"
}
}
}
}Codex CLI
Edit ~/.codex/config.toml:
[[mcpServers]]
name = "x402-agent"
command = "npx"
args = ["x402-mcp-agent"]
[mcpServers.env]
PRIVATE_KEY = "0x..."
X402_CONFIG_PATH = "~/.x402-agent/endpoints.json"Usage
Once configured, your LLM agent can autonomously use the endpoints:
User: "Extract metadata from https://example.com and tell me about the page"
Agent: [Calls minifetch_extract_metadata tool]
[Payment automatically handled via x402]
[Receives metadata and summarizes]The agent will:
- Discover available tools via
tools/list - Call endpoints via
tools/call - Handle 402 payment responses automatically
- Return results to the user
Production Deployment
Embedded MCP in Your Application (Recommended)
The embedded MCP server runs directly in your application code. Your LLM calls it to handle all x402 needs automatically.
Next.js Example
After running npx x402-mcp-agent init in your Next.js app:
// app/api/chat/route.ts
import { mcpServer } from '@/lib/x402/mcp-server';
import OpenAI from 'openai';
const openai = new OpenAI();
export async function POST(req: Request) {
const { message } = await req.json();
// Initialize MCP server (singleton, only runs once)
if (!mcpServer.isInitialized()) {
await mcpServer.initialize();
}
// Get available x402 tools from embedded MCP
const x402Tools = await mcpServer.listTools();
// Call LLM with x402 tools available
const completion = await openai.chat.completions.create({
model: 'gpt-4',
messages: [{ role: 'user', content: message }],
tools: x402Tools, // Your LLM can now call x402 endpoints
tool_choice: 'auto'
});
// Handle tool calls from LLM
for (const toolCall of completion.choices[0].message.tool_calls || []) {
if (toolCall.type === 'function') {
// Embedded MCP handles payment, facilitator, settlement automatically
const result = await mcpServer.callTool(
toolCall.function.name,
JSON.parse(toolCall.function.arguments)
);
console.log('Result:', result.content);
console.log('Transaction:', result.txHash);
console.log('BaseScan:', `https://basescan.org/tx/${result.txHash}`);
}
}
return Response.json(completion);
}Direct Usage (Any Node.js App)
import { EmbeddedMCPServer } from 'x402-mcp-agent/sdk';
// Create embedded MCP server instance
const server = new EmbeddedMCPServer();
// Initialize with your config
await server.initialize({
configPath: './x402-endpoints.json',
debug: false
});
// List available tools
const tools = await server.listTools();
// Call an x402 endpoint - payment handled automatically
const result = await server.callTool('minifetch_extract_metadata', {
url: 'https://example.com'
});
console.log('Data:', result.content);
console.log('Transaction:', result.txHash);
console.log('BaseScan:', `https://basescan.org/tx/${result.txHash}`);What the embedded MCP handles automatically:
- ✅ Making x402 API calls
- ✅ Handling facilitator logic
- ✅ Payment settlement
- ✅ Transaction hash generation
- ✅ Error handling and retries
Configuration Paths
The server looks for endpoints.json in the following order:
X402_CONFIG_PATHenvironment variable (explicit path)./x402-endpoints.json(project root)./config/endpoints.json(config folder)~/.x402-agent/endpoints.json(user home, fallback)
Production Best Practices
When deploying to production:
- Add x402-endpoints.json to your repo (without secrets - use
${PRIVATE_KEY}template) - Set PRIVATE_KEY as environment variable in your deployment platform
- Run the MCP server as a child process from your backend
- Monitor wallet balance and set up alerts for low USDC
- Use separate wallets for dev/staging/prod environments
Configuration Reference
Wallet Configuration
| Field | Type | Description | Required |
|-------|------|-------------|----------|
| provider | string | Wallet provider (only "cdp-embedded" supported) | Yes |
| network | string | Network: "base", "base-sepolia", "ethereum", "sepolia" | Yes |
| privateKey | string | Private key (hex or ${ENV_VAR}) | Yes |
Endpoint Configuration
| Field | Type | Description | Required |
|-------|------|-------------|----------|
| id | string | Unique identifier (snake_case) | Yes |
| name | string | Human-readable name | Yes |
| url | string | HTTPS URL of x402 endpoint | Yes |
| method | string | HTTP method (GET, POST, PUT, PATCH, DELETE) | Yes |
| description | string | Tool description (min 20 chars) | Yes |
| parameters | object | JSON Schema for parameters | Yes |
| trusted | boolean | Allow autonomous execution | Yes |
| category | string | Endpoint category | No |
| estimatedCost | string | Estimated cost per call | No |
Environment Variables
PRIVATE_KEY: Your CDP wallet private key (required)X402_CONFIG_PATH: Path to endpoints.json (default:~/.x402-agent/endpoints.json)DEBUG: Enable debug logging (default:false)
Development
Build from Source
# Clone the repository
git clone https://github.com/Must-be-Ash/x402-agent-npm.git
cd x402-agent-npm
# Install dependencies
npm install
# Build
npm run build
# Run in development mode
npm run devProject Structure
x402-agent/
├── src/
│ ├── index.ts # Main entry point
│ ├── server.ts # MCP server setup
│ ├── handlers/
│ │ ├── listTools.ts # tools/list handler
│ │ └── callTool.ts # tools/call handler
│ ├── registry/
│ │ ├── types.ts # TypeScript types
│ │ ├── EndpointRegistry.ts
│ │ └── validator.ts # Config validation
│ ├── payment/
│ │ ├── WalletManager.ts # CDP wallet
│ │ └── PaymentHandler.ts # x402 integration
│ └── utils/
│ ├── errors.ts # Error classes
│ ├── logger.ts # Logging
│ └── retry.ts # Retry logic
├── config/
│ └── endpoints.example.json
└── package.jsonTroubleshooting
Server Not Starting
- Check that Node.js >= 18.0.0 is installed:
node --version - Verify PRIVATE_KEY is set correctly
- Check configuration file syntax:
cat ~/.x402-agent/endpoints.json | jq
Endpoints Not Appearing
- Restart your MCP client after configuration changes
- Check server logs for errors (set
DEBUG=true) - Verify
trusted: trueis set in endpoint config
Payment Failures
- Ensure wallet has sufficient USDC balance
- Check network matches endpoint requirements
- Verify private key has correct format (0x...)
Configuration Errors
- Validate JSON syntax
- Ensure all required fields are present
- Check endpoint URLs use HTTPS
- Verify parameter schemas are valid JSON Schema
Security
Trust Model
Only endpoints with "trusted": true can be called autonomously. This prevents:
- Unauthorized spending on unknown endpoints
- Malicious endpoint injection
- Unintended payment execution
Review endpoints carefully before setting trusted: true!
Private Key Safety
✅ DO:
- Use environment variables for private keys (
${PRIVATE_KEY}) - Use separate wallets for dev/staging/prod
- Monitor wallet balance and set up alerts
- Keep private keys in secure secret management systems
- Rotate keys periodically
❌ DON'T:
- Commit private keys to git
- Hardcode private keys in endpoints.json
- Share wallets between different applications
- Use production wallets for testing
Network Security
- All endpoints must use HTTPS
- Configuration files should have restricted permissions:
chmod 600 ~/.x402-agent/endpoints.json
Production Security Checklist
- [ ]
PRIVATE_KEYset as environment variable (not in code) - [ ]
endpoints.jsonuses${PRIVATE_KEY}template - [ ] Wallet has sufficient USDC balance for expected usage
- [ ] Endpoints are marked
trusted: trueonly after verification - [ ] Monitor transaction logs for unexpected payments
- [ ] Set up alerts for low USDC balance
- [ ] Test on testnet (base-sepolia) before production
- [ ] Use separate wallets for different environments
License
Apache-2.0
Contributing
Contributions are welcome! Please open an issue or pull request.
Support
For issues and questions:
- GitHub Issues: https://github.com/Must-be-Ash/x402-agent-npm/issues
- npm Package: https://www.npmjs.com/package/x402-mcp-agent
- Documentation: https://docs.cdp.coinbase.com/x402/
