Skip to content

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

Agents SDK から支払う

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

Agents SDK には、x402 で保護されたツールへ支払える MCP クライアントがあります。Agent から、または任意の MCP クライアント接続から使えます。

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 を使います。テスト用 USDC は Circle faucet から取得します。

関連

役に立ちましたか?