402ok mcp
用于HTTP 402支付要求协议的MCP(模型上下文协议)服务器中间件 XLayer兼容 支持多网络区块链支付。
特性
- 🔥 XLayer兼容 -完全支持OKX XLayer网络,并集成了本地协调器
- ✅ 需要HTTP 402付款 -MCP x402协议的标准实施
- 🌐 多网络支持 -XLayer、Base、Base Sepolia和任何EVM兼容网络
- 🔐 OKX主持人 -XLayer内置OKX签名身份验证
- 🔌 标准协调员 -支持x402.org和其他标准主持人
- 💳 USDC付款 -基于EIP-712签名的USDC转账
- 🎯 付费和免费工具 -在同一服务器中定义付费和免费工具
- ⚡ 完整的生命周期 -自动验证→ 实现→ 稳定流量
为什么选择XLayer?
XLayer是OKX构建的第2层区块链,提供:
- 交易手续费低
- 快速确认时间
- 与OKX生态系统无缝集成
- 本地USDC支持
该中间件提供 一流的XLayer支持 通过优化OKX促进者集成。
安装
npm install 402ok-mcp快速开始
纯JSON-RPC HTTP(无SDK依赖)
MCP只是 基于HTTP的JSON-RPC 2.0。您可以构建一个简单的MCP服务器,而无需 @modelcontextprotocol/sdk:
import express from "express";
const app = express();
app.use(express.json());
// Tool definitions
const tools = [
{
name: "premium_analysis",
description: "AI-powered premium analysis",
inputSchema: {
type: "object",
properties: { query: { type: "string" } },
required: ["query"]
},
price: "0.01", // USDC
handler: async (args: any) => `Analysis result for: ${args.query}`
}
];
// JSON-RPC 2.0 handler
app.post("/mcp", async (req, res) => {
const { jsonrpc, method, params, id } = req.body;
if (jsonrpc !== "2.0") {
return res.json({ jsonrpc: "2.0", error: { code: -32600, message: "Invalid Request" }, id });
}
try {
let result;
switch (method) {
case "initialize":
// MCP handshake
result = {
protocolVersion: "2024-11-05",
capabilities: { tools: {} },
serverInfo: { name: "paid-mcp-server", version: "1.0.0" }
};
break;
case "tools/list":
// List available tools
result = {
tools: tools.map(t => ({
name: t.name,
description: t.description,
inputSchema: t.inputSchema
}))
};
break;
case "tools/call":
// Call a tool
const tool = tools.find(t => t.name === params.name);
if (!tool) {
throw { code: -32601, message: `Tool not found: ${params.name}` };
}
// Check payment (from _meta)
const payment = params._meta?.["x402.payment"];
if (!payment && tool.price) {
// Return 402 payment required
result = {
isError: true,
content: [{
type: "text",
text: JSON.stringify({
x402Version: 1,
error: "_meta.x402.payment is required",
accepts: [{
scheme: "exact",
network: "xlayer",
maxAmountRequired: (parseFloat(tool.price) * 1_000_000).toString(),
payTo: "0xYourWalletAddress",
asset: "0x74b7f16337b8972027f6196a17a631ac6de26d22",
extra: { name: "USD Coin", version: "2" }
}]
})
}]
};
} else {
// Execute tool (with payment verification if needed)
const output = await tool.handler(params.arguments);
result = {
content: [{ type: "text", text: output }]
};
}
break;
case "notifications/initialized":
// Client notification - no response needed
return res.status(204).send();
default:
throw { code: -32601, message: `Method not found: ${method}` };
}
res.json({ jsonrpc: "2.0", result, id });
} catch (error: any) {
res.json({
jsonrpc: "2.0",
error: { code: error.code || -32603, message: error.message },
id
});
}
});
app.listen(3000, () => {
console.log("Pure JSON-RPC MCP server running on http://localhost:3000/mcp");
});JSON-RPC的关键方法:
| 方法 | 说明 |
|---|---|
initialize | 客户端握手,返回服务器功能 |
tools/list | 返回具有模式的可用工具 |
tools/call | 执行工具,参数包括 name, arguments, _meta |
notifications/initialized | 客户端确认初始化(无响应) |
付款流程 _meta:
- 付款已转入
params._meta["x402.payment"]作为base64编码的JSON - 如果缺失,请在回复中返回付款选项
- 如果存在,请验证→ 执行→ 解决
使用SDK(标准传输)
import { createPaidMcpHandler } from "402ok-mcp";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
// Create MCP server with payment support
const server = createPaidMcpHandler(
(mcp) => {
// Define a paid tool
mcp.paidTool(
"premium_analysis",
"Perform premium data analysis",
{
payments: [
{
price: "0.01", // 0.01 USDC
chainId: 196, // XLayer mainnet
token: "0x74b7f16337b8972027f6196a17a631ac6de26d22", // USDC on XLayer
usdcName: "USD Coin",
usdcVersion: "2",
network: "xlayer",
config: {
description: "Premium analysis service"
}
}
]
},
z.object({
data: z.string().describe("Data to analyze")
}),
async (args) => {
// Your tool logic here
const result = await analyzeData(args.data);
return {
content: [{ type: "text", text: result }]
};
}
);
// Define a free tool
mcp.tool(
"basic_info",
"Get basic information (free)",
z.object({
query: z.string()
}),
async (args) => {
return {
content: [{ type: "text", text: `Info for: ${args.query}` }]
};
}
);
},
{ name: "my-paid-mcp-server", version: "1.0.0" },
{
recipient: "0xe8fb62154382af0812539cfe61b48321d8f846a8", // Your wallet
facilitators: {
xlayer: {
url: "https://www.okx.com",
type: "okx",
okxCredentials: {
apiKey: process.env.OKX_API_KEY!,
secretKey: process.env.OKX_SECRET_KEY!,
passphrase: process.env.OKX_PASSPHRASE!
}
}
}
}
);
// Connect via stdio transport
const transport = new StdioServerTransport();
await server.connect(transport);HTTP服务器模式(流式HTTPServerTransport)
部署为基于web的MCP客户端的HTTP服务器:
import express from "express";
import { randomUUID } from "node:crypto";
import { createPaidMcpHandler } from "402ok-mcp";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
import { z } from "zod";
const app = express();
app.use(express.json());
// Store active sessions
const transports: Record = {};
// Server configuration
const serverConfig = {
recipient: "0xe8fb62154382af0812539cfe61b48321d8f846a8",
facilitators: {
xlayer: {
url: "https://www.okx.com",
type: "okx" as const,
okxCredentials: {
apiKey: process.env.OKX_API_KEY!,
secretKey: process.env.OKX_SECRET_KEY!,
passphrase: process.env.OKX_PASSPHRASE!
}
}
}
};
// Tool setup function
const setupTools = (mcp: any) => {
mcp.paidTool(
"premium_analysis",
"AI-powered premium analysis",
{
payments: [{
price: "0.01",
chainId: 196,
token: "0x74b7f16337b8972027f6196a17a631ac6de26d22",
usdcName: "USD Coin",
usdcVersion: "2",
network: "xlayer",
config: { description: "Premium AI analysis" }
}]
},
z.object({ query: z.string() }),
async (args) => {
return { content: [{ type: "text", text: `Analysis: ${args.query}` }] };
}
);
};
// Handle MCP requests
app.post("/mcp", async (req, res) => {
const sessionId = req.headers["mcp-session-id"] as string | undefined;
let transport: StreamableHTTPServerTransport;
if (sessionId && transports[sessionId]) {
// Reuse existing session
transport = transports[sessionId];
} else if (!sessionId && isInitializeRequest(req.body)) {
// New session initialization
transport = new StreamableHTTPServerTransport({
sessionIdGenerator: () => randomUUID(),
onsessioninitialized: (id) => {
transports[id] = transport;
console.log("Session initialized:", id);
},
onsessionclosed: (id) => {
delete transports[id];
console.log("Session closed:", id);
}
});
transport.onclose = () => {
if (transport.sessionId) {
delete transports[transport.sessionId];
}
};
// Create paid MCP server and connect
const server = createPaidMcpHandler(
setupTools,
{ name: "paid-mcp-http-server", version: "1.0.0" },
serverConfig
);
await server.connect(transport);
} else {
res.status(400).json({
jsonrpc: "2.0",
error: { code: -32000, message: "Invalid session" },
id: null
});
return;
}
await transport.handleRequest(req, res, req.body);
});
// Handle SSE for streaming responses
app.get("/mcp", async (req, res) => {
const sessionId = req.headers["mcp-session-id"] as string;
const transport = transports[sessionId];
if (transport) {
await transport.handleRequest(req, res);
} else {
res.status(400).send("Invalid session");
}
});
// Handle session cleanup
app.delete("/mcp", async (req, res) => {
const sessionId = req.headers["mcp-session-id"] as string;
const transport = transports[sessionId];
if (transport) {
await transport.handleRequest(req, res);
} else {
res.status(400).send("Invalid session");
}
});
app.listen(3000, () => {
console.log("Paid MCP HTTP server running on http://localhost:3000/mcp");
});无状态HTTP模式
对于无服务器/边缘部署,请使用无状态模式:
const transport = new StreamableHTTPServerTransport({
sessionIdGenerator: undefined // Disable session management
});多网络设置
允许用户使用XLayer或Base Sepolia付款:
const server = createPaidMcpHandler(
(mcp) => {
mcp.paidTool(
"premium_service",
"Premium service with multi-network payment",
{
payments: [
// Option 1: XLayer (recommended for lower fees)
{
price: "0.1",
chainId: 196,
token: "0x74b7f16337b8972027f6196a17a631ac6de26d22",
usdcName: "USD Coin",
usdcVersion: "2",
network: "xlayer",
config: {
description: "Pay with XLayer (lower fees)"
}
},
// Option 2: Base Sepolia
{
price: "0.1",
chainId: 84532,
token: "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
usdcName: "USDC",
usdcVersion: "2",
network: "base-sepolia",
config: {
description: "Pay with Base Sepolia"
}
}
]
},
z.object({ input: z.string() }),
async (args) => {
return { content: [{ type: "text", text: "Result" }] };
}
);
},
{ name: "multi-network-server", version: "1.0.0" },
{
recipient: "0xe8fb62154382af0812539cfe61b48321d8f846a8",
facilitators: {
xlayer: {
url: "https://www.okx.com",
type: "okx",
okxCredentials: {
apiKey: process.env.OKX_API_KEY!,
secretKey: process.env.OKX_SECRET_KEY!,
passphrase: process.env.OKX_PASSPHRASE!
}
},
"base-sepolia": {
url: "https://x402.org/facilitator",
type: "standard"
}
}
}
);运作原理
- 客户调用MCP工具 → 服务器检查工具是否需要付款
- 未提供付款 → 返回付款选项错误(x402格式)
- 客户签署付款 → 为USDC转账创建EIP-712签名
- 客户端重试
_meta.x402.payment→ 包括已签署的付款 - 服务器验证付款 → 呼叫主持人核实签名
- 服务器执行工具 → 运行工具逻辑
- 服务器结算付款 → 呼叫协调人执行链上转移
- 服务器返回结果 → 包括结算确认
_meta
这一切都是自动发生的!
api参考
createPaidMcpHandler(setupTools, serverInfo, config)
创建具有支付支持的MCP服务器。
参数
- 安装工具
(server: PaidMcpServer) => void-注册工具的功能 - 服务器信息
{ name: string; version: string }-服务器元数据 - 配置
ServerConfig-服务器配置
类型
interface PaymentConfig {
price: string; // Price in USDC (e.g., "0.1")
chainId: number; // Network chain ID
token: string; // USDC token contract address
usdcName: string; // USDC contract name (for EIP-712)
usdcVersion: string; // USDC contract version (for EIP-712)
network: string; // Network name (e.g., "xlayer")
config?: {
description?: string;
metadata?: Record;
};
}
interface ServerConfig {
recipient: string; // Wallet address to receive payments
facilitators: {
[network: string]: FacilitatorConfig;
};
}
interface FacilitatorConfig {
url: string;
type?: "okx" | "standard";
okxCredentials?: {
apiKey: string;
secretKey: string;
passphrase: string;
};
}PaidMcpServer方法
paidTool(name, description, paymentOptions, paramsSchema, callback)
注册一个需要在执行前付款的付费工具。
tool(name, description, paramsSchema, callback)
注册免费工具(无需付款)。
支持的网络
XLayer(推荐)
- 主网:链ID
196 - 测试网:链ID
195 - USDC合同:
0x74b7f16337b8972027f6196a17a631ac6de26d22(主网) - 引导者:具有API认证的OKX主持人
其他网络
- 基础:标准主持人
- 基础Sepolia:标准主持人
- 任何EVM兼容网络 在USDC的支持下
获取OKX凭据
要将XLayer与OKX主持人一起使用:
- 在以下网址创建OKX帐户https://www.okx.com
- 转到API设置
- 创建具有x402权限的API密钥
- 将API密钥、密钥和密码短语复制到您的
.env:
OKX_API_KEY=your_api_key
OKX_SECRET_KEY=your_secret_key
OKX_PASSPHRASE=your_passphrase客户端集成
MCP客户需要处理x402支付流程。当工具返回付款选项错误时:
// Example handling payment in an MCP client
const result = await mcpClient.callTool("premium_analysis", { data: "..." });
if (result.isError) {
const errorData = JSON.parse(result.content[0].text);
if (errorData.error === "_meta.x402.payment is required") {
// Get payment options
const paymentOptions = errorData.accepts;
// User signs payment with their wallet
const signedPayment = await signPayment(paymentOptions[0]);
// Retry with payment
const paidResult = await mcpClient.callTool(
"premium_analysis",
{ data: "..." },
{ _meta: { "x402.payment": signedPayment } }
);
}
}安全
- 所有付款的EIP-712签名验证
- 主持人双重验证(验证+结算)
- 无需直接访问区块链
- 仅在工具执行成功时自动付款结算
- 工具执行失败=无付款结算
许可证
麻省理工学院
链接
-
