跳转到内容
搜索文档

对 MCP 工具收费

最后更新 查看 MarkdownAgent 设置

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

设置

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

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 }] };
			},
		);
	}
}

配置

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

paidTool 签名

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

相关

这篇文档对您有帮助吗?