Skip to content

非公式本サイトは非公式の日本語ドキュメントであり、Cloudflare 公式サイトではありません。最新情報はdevelopers.cloudflare.comをご確認ください。

MCP ツールの課金

最終更新 Markdown で表示Agent セットアップ

Agents SDK は paidTool を提供します。tool の差し替えとして使え、x402 の支払い要件を追加します。クライアントはツール呼び出しごとに支払い、同じサーバーで無料ツールと有料ツールを混在できます。

セットアップ

課金したいツールには、McpServerwithX402 でラップし、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 支払いファシリテーターの 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 を使い、テスト用 USDC は Circle faucet から取得します。

完成した動作例は GitHub の x402-mcp を参照してください。

関連

役に立ちましたか?