Skip to content

Pay from Agents SDK

Last updated View as MarkdownAgent setup

The Agents SDK includes an MCP client that can pay for x402-protected tools. Use it from your Agents or any MCP client connection.

agents/x402 needs @modelcontextprotocol/sdk, which is an optional peer dependency of agents. It does not load the package at runtime, but its types refer to MCP SDK v1. Add the exact version your Agents release expects, such as @modelcontextprotocol/sdk@1.32.1, to your package.json.

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

For a complete working example, see x402-mcp on GitHub ↗︎.

Environment setup

Store your private key securely:

# Local development (.dev.vars)
MY_PRIVATE_KEY="0x..."

# Production
npx wrangler secret put MY_PRIVATE_KEY

Use base-sepolia for testing. Get test USDC from the Circle faucet ↗︎.

Was this helpful?