DEV Community

Cover image for Building an x402-native AI agent with AgentKit — what I learned
Mario Semper
Mario Semper

Posted on

Building an x402-native AI agent with AgentKit — what I learned

Spent the last two weeks wiring Coinbase AgentKit into an x402 payment flow. Here's what worked, what didn't, and a working example.

Why x402: AI agents can't handle API keys. They need to authenticate, pay, and retry — autonomously. x402 (HTTP 402 Payment Required) gives them exactly that. No accounts, no secrets, no human in the loop.

What I built: An agent that calls a payment verification API using USDC on-chain, no pre-registration. The whole integration is about 50 lines of code:

The agent hits the API, gets a 402, the MCP client pays with the Smart Account wallet, retries, and the call completes. All automatic.

What tripped me up

AgentKit's wallet is a Smart Account, not an EOA. The x402 client needs to know that — some libraries assume externally-owned accounts and break silently when they get a 4337-style address. Worth double-checking your client-side x402 handler if you see weird signature failures.

The 402 → pay → retry loop needs idempotency. First implementation doubled a payment because the retry fired before the first transaction confirmed. Add a nonce or a short debounce, or use an SDK that handles this for you (MCP SDK does, plain fetch doesn't).

MCP clients handle x402 automatically — but only with Streamable HTTP transport. If you're still on stdio or SSE transport, you'll need to wrap the request yourself. The newer transports have the retry logic built in.

Gas matters more than you think on Ethereum mainnet. At $0.05 per call, mainnet gas can eat the entire payment margin. Base is the sweet spot — fast, cheap, and AgentKit is native there. Arbitrum, Optimism, Polygon also work if your use case needs them.

Full working example

Repo with everything: github.com/masem-at/paywatcher-agentkit-example

README walks through setup end-to-end. TypeScript, Coinbase AgentKit SDK, @modelcontextprotocol/sdk. Works on Base by default, but supports 5 EVM chains out of the box.

Happy to answer questions in the comments — especially if you're hitting the Smart Account / x402 client edge case, that one took me a day to debug.

Top comments (0)