跳转到内容
本站为社区维护的非官方中文翻译,与 Cloudflare, Inc. 无关联。本站不提供账户登录,请勿在任何非官方站点输入您的 Cloudflare 账户信息。官方文档:developers.cloudflare.com

从 Agents SDK 支付

最后更新 查看 MarkdownAgent 设置

Agents SDK 包含可支付 x402 保护工具的 MCP 客户端。可在 Agent 或任何 MCP 客户端连接中使用。

agents/x402 需要 @modelcontextprotocol/sdk,这是 agents 的可选对等依赖项。它不会在运行时加载该程序包,但其类型引用 MCP SDK v1。请在 package.json 中添加 Agents 版本所需的精确版本,例如 @modelcontextprotocol/[email protected]。

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。

相关

这篇文档对您有帮助吗?