X402 MCP 模板 🤖💰
用于消费受X402保护的API的生产就绪MCP服务器模板,支持无气体微支付
这个模板提供了创建MCP(模型上下文协议)服务器所需的一切,该服务器能够消费支持X402的API,从而使像Claude这样的AI代理能够无缝地进行基于微支付的API调用。
🤖 机器人 对于人工智能开发者见 CLAUDE.md(文件名,可译为“克劳德文档”或保持原样,具体取决于上下文和使用场景) 关于X402与MCP综合集成文档、支付流程及AI开发指南的全面信息。
✨ 特点/功能
- 🔐 X402 无气体微支付 - EIP-712签名,API使用无手续费
- 🎭 双模式操作 - 演示模式(无钱包)和支付模式(有钱包)
- 🔍 服务发现 - 自动发现X402 API功能
- Claude 桌面版准备就绪 - 与Claude Desktop的无缝集成(或:即插即用集成)
- 📡 兼容MCP Inspector - 使用MCP Inspector进行测试和调试
- 🏭 准备就绪,可投入生产 - 主网(Base)和测试网(Base Sepolia)支持
- 📝 全部使用TypeScript - 具有全面类型的类型安全开发
- ⚡ 自动处理付款 - 自动尝试402次,带有支付授权
🏗️ 建筑
MCP + X402 集成流程
┌─────────────────────────────────────────────────────────────────────┐
│ Claude Desktop / MCP Client │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ User Request: "Search for coffee shops near me" │ │
│ └─────────────────────────────────────────────────────────────────┘ │
│ ↓ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ MCP Protocol: CallTool("search_places", {query: "coffee"}) │ │
│ └─────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────────────┐
│ X402 MCP Server (This Template) │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ Tool Handler: Receives request │ │
│ └─────────────────────────────────────────────────────────────────┘ │
│ ↓ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ X402 Payment Client (x402-axios) │ │
│ │ - EIP-712 signature generation │ │
│ │ - Automatic 402 retry handling │ │
│ │ - Payment authorization │ │
│ └─────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────────────┐
│ X402-Protected API Server │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ 1. First Request: Returns 402 Payment Required │ │
│ │ - Includes payment requirements (price, network, address) │ │
│ └─────────────────────────────────────────────────────────────────┘ │
│ ↓ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ 2. Payment Processing: │ │
│ │ - Verify EIP-712 signature │ │
│ │ - Submit to facilitator │ │
│ │ - Execute USDC transfer (gasless) │ │
│ └─────────────────────────────────────────────────────────────────┘ │
│ ↓ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ 3. Second Request: Payment authorized, returns data │ │
│ └─────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────────────┐
│ Result Returned to Claude │
│ - API response data │
│ - Payment metadata │
│ - Cost information │
└─────────────────────────────────────────────────────────────────────┘要点:
- MCP处理工具协议和与Claude的通信
- x402-axios 自动处理支付协议
- 用户只需持有包含USDC的钱包——无需手动支付步骤
- 所有支付复杂性都被抽象化处理了
📁 项目结构
Template-x402-Mcp/
├── index.ts # Main MCP server implementation
├── package.json # Dependencies and scripts
├── tsconfig.json # TypeScript configuration
├── .env.example # Environment variables template
├── README.md # This file - setup and usage guide
└── CLAUDE.md # AI-friendly X402 + MCP documentation🚀 快速入门
1. 克隆并设置
# Navigate to template directory
cd Template-x402-Mcp
# Install dependencies
npm install
# Copy environment variables
cp .env.example .env2. 配置环境
编辑 .env 文件:
选项A:演示模式(无需支付)
# Leave PRIVATE_KEY empty or with placeholder
PRIVATE_KEY=
# Set your X402 API endpoint
RESOURCE_SERVER_URL=https://places-api.x402hub.xyz
# Network (testnet for demo)
NETWORK=base-sepolia选项B:支付模式(已启用X402)
# Add your wallet private key
PRIVATE_KEY=0x1234567890abcdef...
# Set your X402 API endpoint
RESOURCE_SERVER_URL=https://places-api.x402hub.xyz
# Network: base-sepolia (testnet) or base (mainnet)
NETWORK=base-sepolia3. 自定义您的工具
编辑 index.ts 定义您特定的API工具:
// In ListToolsRequestSchema handler
{
name: "your_custom_tool",
description: "Description of what your tool does",
inputSchema: {
type: "object",
properties: {
// Define your input parameters
param1: {
type: "string",
description: "Parameter description"
}
},
required: ["param1"]
}
}添加工具处理器:
case "your_custom_tool": {
const { param1 } = args as { param1: string };
// Make X402-protected API call
const response = await client.post("/api/your-endpoint", {
param1: param1
});
return {
content: [{
type: "text",
text: JSON.stringify(response.data, null, 2)
}]
};
}4. 构建与测试
# Build TypeScript
npm run build
# Test with MCP Inspector
npm run inspector
# Or test in development mode
npm run dev5. Claude桌面集成
添加到Claude桌面配置中:
macOS(苹果电脑操作系统): ~/Library/Application Support/Claude/claude_desktop_config.json Windows: %APPDATA%\Claude\claude_desktop_config.json
{
"mcpServers": {
"x402-your-api": {
"command": "node",
"args": ["/absolute/path/to/Template-x402-Mcp/build/index.js"],
"env": {
"PRIVATE_KEY": "0x...",
"RESOURCE_SERVER_URL": "https://your-x402-api.example.com",
"NETWORK": "base-sepolia"
}
}
}
}重启Claude桌面版 你的工具将随时可用!
🔑 获取USDC用于测试
测试网(Base Sepolia)
# Use Circle's testnet faucet
# Visit: https://faucet.circle.com/
# Enter your wallet address
# Receive free testnet USDC主网(基础)
通过以下方式在Base网络上购买USDC:
📖 可用工具
内置工具
| 工具 | 描述 | 模式 |
|---|---|---|
example_api_call X402 API调用的模板工具 | 两者 | |
service_info 获取API服务发现元数据 | 两者皆是 | |
health_check 检查API可用性 | 两者均需 |
演示模式返回带有设置说明的示例数据 支付方式实现真正的X402受保护API调用
🎭 演示模式 vs 支付模式
演示模式(无私钥)
特点/功能:
- ✅ 立即可用,无需设置钱包
- ✅ 为所有工具返回示例数据
- ✅ 在回复中显示设置说明
- ✅ 非常适合开发和测试MCP集成
- 无法进行真实的API调用
用例:
- 测试MCP服务器功能
- 开发工具定义
- Claude Desktop 集成测试
- 学习X402协议流程
支付模式(使用私钥)
特点/功能:
- ✅ 实现真正的X402受保护的API调用
- ✅ 自动处理支付(无需手动操作)
- ✅ 无需手续费的USDC转账
- ✅ 准备就绪,可投入生产
- ⚠️ 需要钱包中有USDC余额
用例:
- 生产AI代理部署
- 实际数据消耗
- 付费API访问
- 企业集成
🛠️ 自定义指南
添加新工具
第一步: 在(相应位置)添加工具定义 ListToolsRequestSchema 处理程序/处理器
{
name: "get_data_by_id",
description: "Fetch specific data by ID from X402 API",
inputSchema: {
type: "object",
properties: {
id: {
type: "string",
description: "Unique identifier for the data"
}
},
required: ["id"]
}
}步骤2: 添加工具处理程序到 CallToolRequestSchema 处理程序:
case "get_data_by_id": {
const { id } = args as { id: string };
if (!id?.trim()) {
throw new McpError(ErrorCode.InvalidParams, "ID parameter is required");
}
// Demo mode fallback
if (!paymentEnabled) {
return {
content: [{
type: "text",
text: JSON.stringify({
demo_mode: true,
sample_data: { id, name: "Sample Data" },
setup_instructions: { /* ... */ }
}, null, 2)
}]
};
}
// Payment mode - real API call
const response = await client.get(`/api/data/${id}`);
return {
content: [{
type: "text",
text: JSON.stringify(response.data, null, 2)
}]
};
}更改API终端节点
# In .env file
RESOURCE_SERVER_URL=https://your-new-api.example.com交换网络
# Testnet (Base Sepolia)
NETWORK=base-sepolia
# Mainnet (Base)
NETWORK=base🔍 服务发现
您的MCP服务器会自动从(某个来源)获取X402服务的元数据 /.well-known/x402:
// Automatically called by service_info tool
const response = await axios.get(`${baseURL}/.well-known/x402`);
// Returns:
{
"service": "API Service Name",
"version": "1.0.0",
"payment": {
"protocol": "x402 v1.0",
"price": "$0.001",
"network": "base-sepolia"
},
"endpoints": {
"/api/endpoint": {
"method": "POST",
"description": "...",
"inputSchema": { /* ... */ },
"outputSchema": { /* ... */ }
}
}
}使用此元数据来动态生成工具或为用户提供API文档。
🔐 安全最佳实践
- 永远不要承诺
.env- 使用.env.example作为模板 - 轮换私钥 - 定期更换生产环境的密钥
- 使用独立的钱包 - 测试网/主网的不同地址
- 监控USDC余额 - 跟踪支出并设置提醒
- 验证API响应 - 检查数据完整性和结构
- 错误处理 - 不要在错误信息中暴露敏感信息
- 速率限制 - 如有必要,实施客户端速率限制
📊 监控
检查钱包余额
监控您的USDC余额和支付交易:
- 测试网: Sepolia浏览器(或Sepolia区块浏览器)
- 主网: Base Explorer(可译为“基础浏览器”或根据具体上下文调整为更贴切的名称,如“数据库浏览器”等,但“Base Explorer”本身直接翻译为“基础探索器”或“基础浏览器”也是可行的,具体取决于该术语在特定领域或语境中的常用译法)
服务器日志
# Development mode with logs
npm run dev
# Check payment status
# Logs show: ✅ Payment client initialized, wallet address, networkMCP 检查器
# Test tools interactively
npm run inspector
# Check:
# - Tool definitions are correct
# - Payment mode is active
# - API responses are valid🧪 测试
使用MCP Inspector进行测试
# Start inspector
npm run inspector
# Test tools:
1. Select "service_info" - should return API metadata
2. Select "health_check" - should return API health status
3. Select your custom tools - should work in demo or payment mode使用Claude桌面版进行测试
- 添加到配置中 (见上文关于Claude桌面集成功能的说明)
- 重启Claude桌面版
- 会话测试:
You: Can you check the service info for the X402 API?
Claude: [Uses service_info tool, shows API metadata]
You: Search for coffee shops near me
Claude: [Uses your custom tool, makes payment if enabled]验证支付流程
演示模式:
- 工具返回示例数据
- 回复中包含设置说明
- 无需USDC
支付方式:
- 首次调用触发402响应
- x402-axios 自动重试并进行支付
- USDC已转账(请查看区块链浏览器)
- 返回真实数据
🆘 故障排除
“正在演示模式下运行”
问题私钥未配置或无效
解决方案:
- 检查
.env文件有效PRIVATE_KEY=0x...(66个字符) - 确保私钥不是占位符 ``
- 验证密钥格式:
0x接着是64个十六进制字符
“需要支付:USDC余额不足”
问题钱包中没有足够的USDC(美元稳定币)
解决方案:
- 获取测试网 USDC:https://faucet.circle.com/
- 对于主网,请在Base网络上购买USDC
- 在浏览器中检查余额(链接见上文)
“工具执行失败”
问题API终端或配置问题
解决方案:
- 验证
RESOURCE_SERVER_URL是正确且易于获取的 - 检查API是否支持X402协议
- 使用
health_check用于测试连接性的工具 - 使用
service_info用于验证API配置的工具
MCP服务器未在Claude中显示
问题Claude Desktop 无法检测到 MCP 服务器
解决方案:
- 验证
build/index.js存在:npm run build - 检查Claude Desktop配置是否包含绝对路径
- 完全重启Claude桌面版
- 在Claude Desktop开发者工具中检查日志
📚 资源
📄 许可证
MIT 许可证 - 详情请参阅 LICENSE 文件
🤝 贡献(或:参与贡献)
这是一个模板——请fork它并根据自己的需求进行修改!
- 克隆模板
- 为您的X402 API进行定制
- 部署并共享您的MCP服务器
______________________________________________________________________
使用X402协议+模型上下文协议,用心打造
用您自己的API集成替换此模板,并启用AI代理以消费您的服务! 🚀
