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

为 MCP 工具收费

Agents SDK 提供了 paidTool,作为 tool 的直接替代品,增加了 x402 付款要求。客户端按工具调用付费,你可以在同一个服务器中混合使用免费和付费工具。

配置

withX402 包装你的 McpServer,并对要收费的工具使用 paidTool:

TypeScript


import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";

import { McpAgent } from "agents/mcp";

import { withX402, type X402Config } from "agents/x402";

import { z } from "zod";


const X402_CONFIG: X402Config = {

  network: "base",

  recipient: "0xYourWalletAddress",

  facilitator: { url: "https://x402.org/facilitator" }, // Payment facilitator URL

  // To learn more about facilitators: https://docs.x402.org/core-concepts/facilitator

};


export class PaidMCP extends McpAgent<Env> {

  server = withX402(

    new McpServer({ name: "PaidMCP", version: "1.0.0" }),

    X402_CONFIG,

  );


  async init() {

    // Paid tool — $0.01 per call

    this.server.paidTool(

      "square",

      "Squares a number",

      0.01, // USD

      { number: z.number() },

      {},

      async ({ number }) => {

        return { content: [{ type: "text", text: String(number ** 2) }] };

      },

    );


    // Free tool

    this.server.tool(

      "echo",

      "Echo a message",

      { message: z.string() },

      async ({ message }) => {

        return { content: [{ type: "text", text: message }] };

      },

    );

  }

}


Explain Code

配置项

字段描述
network生产环境用 base,测试环境用 base-sepolia
recipient接收付款的钱包地址
facilitator付款 facilitator 的 URL(使用 https://x402.org/facilitator)

paidTool 签名

TypeScript


this.server.paidTool(

  name, // Tool name

  description, // Tool description

  price, // Price in USD (e.g., 0.01)

  inputSchema, // Zod schema for inputs

  annotations, // MCP annotations

  handler, // Async function that executes the tool

);


当客户端调用付费工具但未付款时,服务器会返回 402 并附带付款要求。客户端通过 x402 完成付款后,带着付款凭证重试,然后获得结果。

测试

使用 base-sepolia 网络,并从 Circle faucet ↗ 获取测试 USDC。

完整可运行的示例参见 GitHub 上的 x402-mcp ↗

相关内容