x402

Pay-per-use AgentMail with the x402 payment protocol

Getting started

x402 is an open payment protocol that enables HTTP-native payments. By integrating x402 with AgentMail, your agents can pay for API usage directly over HTTP without managing API keys or subscriptions.

Base URLs

To authenticate with x402 instead of an API key, you must use the x402-specific base URLs below. These replace the default AgentMail base URLs and route requests through the x402 payment layer.

ProtocolURL
HTTPx402.api.agentmail.to
WebSocketx402.ws.agentmail.to

Prerequisites

  • An EVM-compatible wallet with funds (e.g., USDC on Base)
  • Node.js installed

Install dependencies

$npm install agentmail @x402/fetch @x402/evm viem

Quickstart

TypeScript
1import { privateKeyToAccount } from "viem/accounts";
2import { x402Client } from "@x402/fetch";
3import { ExactEvmScheme } from "@x402/evm/exact/client";
4
5import { AgentMailClient } from "agentmail";
6
7
8// Setup x402 client
9
10const PRIVATE_KEY = "0x...";
11
12const signer = privateKeyToAccount(PRIVATE_KEY);
13
14const x402 = new x402Client();
15x402.register("eip155:*", new ExactEvmScheme(signer));
16
17
18// Setup AgentMail client
19
20export const client = new AgentMailClient({ x402 });
21
22
23// Create inbox
24
25const inboxRes = await client.inboxes.create({
26 username: `x402-${Date.now()}`,
27});
28console.log("Created inbox: ", inboxRes.inboxId);
29
30
31// Subscribe to inbox
32
33const socket = await client.websockets.connect();
34console.log("Connected to websocket");
35
36socket.on("message", async (event) => {
37 if (event.type === "subscribed") {
38 console.log("Subscribed to", event.inboxIds);
39 } else if (event.type === "event" && event.eventType === "message.received") {
40 console.log("Received message from: ", event.message.from);
41 }
42});
43
44socket.sendSubscribe({
45 type: "subscribe",
46 inboxIds: [inboxRes.inboxId],
47});

How it works

When you pass an x402 client to AgentMailClient, the SDK automatically handles payment negotiation for each API request. If the server responds with a 402 Payment Required status, the x402 client signs a payment using your wallet and retries the request with the payment attached.

This means your agent can use the full AgentMail API (inboxes, messages, threads, attachments) without needing a traditional API key. Payment happens per-request over HTTP.

Resources