Agents SDK 包含可支付 x402 保护工具的 MCP 客户端。可在 Agent 或任何 MCP 客户端连接中使用。
import { Agent } from "agents";
import { withX402Client } from "agents/x402";
import { privateKeyToAccount } from "viem/accounts";
export class MyAgent extends Agent {
// Your Agent definitions...
async onStart() {
const { id } = await this.mcp.connect(`${this.env.WORKER_URL}/mcp`);
const account = privateKeyToAccount(this.env.MY_PRIVATE_KEY);
this.x402Client = withX402Client(this.mcp.mcpConnections[id].client, {
network: "base-sepolia",
account,
});
}
onPaymentRequired(paymentRequirements): Promise<boolean> {
// Your human-in-the-loop confirmation flow...
}
async onToolCall(toolName: string, toolArgs: unknown) {
// The first parameter is the confirmation callback.
// Set to `null` for the agent to pay automatically.
return await this.x402Client.callTool(this.onPaymentRequired, {
name: toolName,
arguments: toolArgs,
});
}
}完整工作示例请参阅 GitHub 上的 x402-mcp ↗。
安全存储私钥:
# Local development (.dev.vars)
MY_PRIVATE_KEY="0x..."
# Production
npx wrangler secret put MY_PRIVATE_KEY测试时使用 base-sepolia。从 Circle faucet ↗ 获取测试 USDC。
- 对 MCP 工具收费 — 构建对工具收费的服务器
- 从编码工具支付 — 为 OpenCode 或 Claude Code 添加支付
- Human-in-the-loop 指南 — 实现审批 Workflow