Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

从 Agents SDK 发起支付

Agents SDK 内置了一个可以为受 x402 保护的工具付费的 MCP 客户端。你可以在 Agent 中或任何 MCP 客户端连接里使用它。

TypeScript


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 ↗

环境配置

请安全地保存你的私钥:

Terminal window


# Local development (.dev.vars)

MY_PRIVATE_KEY="0x..."


# Production

npx wrangler secret put MY_PRIVATE_KEY


测试时使用 base-sepolia。可在 Circle faucet ↗ 领取测试用 USDC。

相关内容