跳转到内容
搜索文档

从 Agents SDK 支付

最后更新 查看 MarkdownAgent 设置

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。从 Circle faucet 获取测试 USDC。

相关

这篇文档对您有帮助吗?