使用 MCP 服务器支付
本指南展示了如何将启用 x402 的 API 桥接到 MCP 工具,以便 AI 客户端可以通过自然语言提示调用并支付它们。它基于 构建按次付费 API 中的服务器。
您将构建什么
一个 MCP 服务器,它将支持 x402 付费的端点封装为工具。AI 客户端输入自然语言提示,每次工具调用都会触发付费的 x402 请求,并且结算可在 Stablescan 上查看。用户永远不会看到钱包提示。
演示
步骤 1. Claude 中的用户:"提取 ACME Corp 的财务数据并评估信用风险。"
步骤 2. 客户端调用 get_company_financials("ACME")
→ MCP 处理程序:fetchWithPayment("/financials?ticker=ACME")
→ 402 Payment Required → 签署 ERC-3009 → 重试
→ 协调器链上结算 $0.01 USDT0
→ 交易:0x8f3a...aaaa
→ 200 OK { revenue, debt_ratio, cash_flow }
步骤 3. 客户端调用 assess_credit_risk(financials)
→ MCP 处理程序:fetchWithPayment("/credit-risk", POST)
→ 协调器链上结算 $0.05 USDT0
→ 交易:0x9bc4...bbbb
→ 200 OK { score: 72, rating: "moderate" }
步骤 4. Claude 回答:
"ACME Corp 的信用风险评分为 72(中等)。收入稳定,
但债股比率升至 1.8 倍..."两个 tx 值都可以在 https://stablescan.xyz 上看到。
概述
MCP 服务器:// --- MCP Server ---
// 将启用 x402 的 API 桥接到 MCP 工具
tools = {
"get_company_financials": {
handler: (ticker) =>
fetchWithPayment("https://api.example.com/financials?ticker=" + ticker),
},
"assess_credit_risk": {
handler: (financials) =>
fetchWithPayment("https://api.example.com/credit-risk", {
method: "POST",
body: JSON.stringify({ financials }),
}),
},
}─── AI 客户端 ─────────────────────────────────
用户:"提取 ACME Corp 的财务数据并评估其信用风险。"
客户端调用 get_company_financials 工具
→ MCP 服务器发送 x402 付费请求
→ 协调器链上结算 USDT0
→ API 返回财务数据
客户端使用结果调用 assess_credit_risk 工具
→ MCP 服务器发送 x402 付费请求
→ 协调器链上结算 USDT0
→ API 返回风险评估
→ 客户端回复合并结果先决条件
- 运行中的 x402 服务器(请参阅 构建按次付费 API)。
- 兼容 MCP 的 AI 客户端(Claude Desktop、Claude Code 等)。
步骤 1:创建 MCP 服务器
MCP 服务器充当 AI 客户端和支持 x402 的 API 之间的桥梁。每个工具都使用 x402 客户端 SDK 发送付费请求并返回结果。
npm install @modelcontextprotocol/sdk @x402/fetch @x402/evm @tetherto/wdk-wallet-evm// mcp-server.ts
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import WalletManagerEvm from "@tetherto/wdk-wallet-evm";
import { x402Client, wrapFetchWithPayment } from "@x402/fetch";
import { registerExactEvmScheme } from "@x402/evm/exact/client";
import { z } from "zod";
// --- 钱包和 x402 客户端 ---
const account = await new WalletManagerEvm(process.env.SEED_PHRASE!, {
provider: "https://rpc.stable.xyz",
}).getAccount(0);
const client = new x402Client();
registerExactEvmScheme(client, { signer: account });
const fetchWithPayment = wrapFetchWithPayment(fetch, client);
// --- x402 API 基础 URL ---
const API_BASE = process.env.API_BASE || "http://localhost:4021";
// --- MCP 服务器 ---
const server = new McpServer({
name: "x402-payments",
version: "1.0.0",
});
server.tool(
"get_company_financials",
"通过股票代码获取公司财务数据(付费端点,每次调用 $0.01)",
{ ticker: z.string().describe("公司股票代码 (例如 ACME)") },
async ({ ticker }) => {
const response = await fetchWithPayment(`${API_BASE}/financials?ticker=${ticker}`);
const data = await response.json();
return { content: [{ type: "text", text: JSON.stringify(data) }] };
},
);
server.tool(
"assess_credit_risk",
"根据财务数据评估信用风险(付费端点,每次调用 $0.05)",
{ financials: z.string().describe("公司财务数据的 JSON 字符串") },
async ({ financials }) => {
const response = await fetchWithPayment(`${API_BASE}/credit-risk`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: financials,
});
const data = await response.json();
return { content: [{ type: "text", text: JSON.stringify(data) }] };
},
);
server.tool(
"check_balance",
"检查支付钱包的 USDT0 余额",
{},
async () => {
const USDT0_STABLE = "0x779Ded0c9e1022225f8E0630b35a9b54bE713736";
const balance = await account.getTokenBalance(USDT0_STABLE);
const formatted = (Number(balance) / 1e6).toFixed(2);
return {
content: [{ type: "text", text: `钱包余额:${formatted} USDT0` }],
};
},
);
// --- 启动 ---
const transport = new StdioServerTransport();
await server.connect(transport);每个工具处理程序都会调用 fetchWithPayment,它会自动处理完整的 x402 支付周期。AI 客户端只看到工具名称、描述和参数。
步骤 2:配置您的 AI 客户端
将 MCP 服务器添加到您的 AI 客户端配置中。
Claude Desktop (claude_desktop_config.json):
{
"mcpServers": {
"x402-payments": {
"command": "npx",
"args": ["tsx", "/path/to/mcp-server.ts"],
"env": {
"SEED_PHRASE": "您的助记词",
"API_BASE": "https://api.example.com"
}
}
}
}claude mcp add x402-payments -- npx tsx /path/to/mcp-server.ts配置后,重启您的 AI 客户端。工具应该出现在可用工具列表中。
步骤 3:输入提示并使用它
配置后,AI 客户端可以通过用户的提示调用付费 API:
用户:"提取 ACME Corp 的财务数据并评估其信用风险。"
- 客户端调用
get_company_financials("ACME"):通过 x402 支付 $0.01。返回收入、负债率、现金流等。 - 客户端调用
assess_credit_risk(financials):通过 x402 支付 $0.05。返回风险评分、评级、关键因素。 - 客户端回复:"ACME Corp 的信用风险评分为 72(中等)。收入稳定,但债股比率升至 1.8 倍..."
单个工具也可以独立工作:
- "提取 ACME Corp 的财务数据" 调用
get_company_financials($0.01)。 - "评估此数据的信用风险" 调用
assess_credit_risk($0.05)。 - "我还有多少 USDT0?" 调用
check_balance。
用户无需与钱包、签名或支付流程进行交互。MCP 服务器透明地处理每个工具调用的支付。
消费控制
为防止意外消费,请考虑向 MCP 服务器添加控制。
const MAX_PER_CALL = 100_000; // 以基本单位计 $0.10
const MAX_PER_SESSION = 5_000_000; // 以基本单位计 $5.00
let sessionSpent = 0n;
function checkSpendingLimit(amount: bigint) {
if (amount > BigInt(MAX_PER_CALL)) {
throw new Error(`金额超出单次调用上限 ${MAX_PER_CALL / 1e6}`);
}
if (sessionSpent + amount > BigInt(MAX_PER_SESSION)) {
throw new Error(`会话消费上限 ${MAX_PER_SESSION / 1e6} 已达到`);
}
sessionSpent += amount;
}这些限制在服务器端运行。AI 客户端无法修改或绕过它们。
接下来推荐
- 构建按次付费 API:设置此 MCP 服务器桥接的 x402 服务器。
- x402 概念:回顾这些支付背后的结算协议。
- 使用 AI 开发:将 Stable 的文档和运行时 MCP 服务器连接到同一个 AI 客户端。

