8# Agent Payment Execution (x402)
9
10Enable AI agents to make policy-gated payments with built-in spending controls. Uses the x402 HTTP payment protocol and MCP tools so agents can pay for external services, APIs, or other agents without custodial risk.
11
12## When to Use
13
14Use when: your agent needs to pay for an API call, purchase a service, settle with another agent, enforce per-task spending limits, or manage a non-custodial wallet. Pairs naturally with cost-aware-llm-pipeline and security-review skills.
15
16## Decision Tree
17
18Choose the integration path based on whether your agent is buying access to a paid API or charging others for one:
19
20| Need | Recommended path |
21|------|------------------|
22| Agent pays a 402-gated API on Base or another agentwallet-supported chain | Use agentwallet-sdk as an MCP payment server with strict spending policy |
23| Agent pays a 402-gated API on X Layer | Use OKX Agent Payments Protocol from okx/onchainos-skills; okx-x402-payment is a deprecated legacy alias |
24| TypeScript API charges agents | Use OKX Payments TypeScript seller SDK docs for Express, Hono, Fastify, or Next.js |
25| Go API charges agents | Use OKX Payments Go seller SDK docs for Gin, Echo, or net/http |
26| Rust API charges agents | Use OKX Payments Rust seller SDK docs for Axum |
27| Java API charges agents | Use OKX Payments Java seller SDK docs for Spring Boot 2/3, Java EE, or Jakarta |
28| Python API charges agents | Check the current OKX Payments repository before implementation; a Python seller guide may not be available |
29
30## Supported Networks
31
32- agentwallet-sdk: use the package docs to confirm current network coverage before production. Base Sepolia is the safest development default; Base mainnet is the production path called out by the original skill.
33- OKX Payments / X Layer: current seller docs target X Layer (eip155:196) and USDT0 settlement. Fetch current SDK docs before generating production code because payment packages and facilitator behavior can change quickly.
34
35## How It Works
36
37### x402 Protocol
38x402 extends HTTP 402 (Payment Required) into a machine-negotiable flow. When a server returns 402, the agent's payment tool negotiates price, checks budget, signs a transaction, and retries only inside the policy and confirmation boundary set by the orchestrator.
39
40### Spending Controls
41Every payment tool call enforces a SpendingPolicy:
42- **Per-task budget** — max spend for a single agent action
43- **Per-session budget** — cumulative limit across an entire session
44- **Allowlisted recipients** — restrict which addresses/services the agent can pay
45- **Rate limits** — max transactions per minute/hour
46
47### Non-Custodial Wallets
48Agents hold their own keys via ERC-4337 smart accounts. The orchestrator sets policy before delegation; the agent can only spend within bounds. No pooled funds, no custodial risk.
49
50## MCP Integration
51
52The payment layer exposes standard MCP tools that slot into any Claude Code or agent harness setup.
53
54> **Security note**: Always pin the package version. This tool manages private keys — unpinned npx installs introduce supply-chain risk.
55
56### Option A: agentwallet-sdk (Base / multi-chain)
57
58```json
59{
60 "mcpServers": {
61 "agentpay": {
62 "command": "npx",
63 "args": ["agentwallet-sdk@6.0.0"]
64 }
65 }
66}
67```
68
69### Available Tools (agent-callable)
70
71| Tool | Purpose |
72|------|---------|
73| get_balance | Check agent wallet balance |
74| send_payment | Send payment to address or ENS |
75| check_spending | Query remaining budget |
76| list_transactions | Audit trail of all payments |
77
78> **Note**: Spending policy is set by the **orchestrator** before delegating to the agent — not by the agent itself. This prevents agents from escalating their own spending limits. Configure policy via set_policy in your orchestration layer or pre-task hook, never as an agent-callable tool.
79
80### Option B: OKX Agent Payments Protocol (X Layer)
81
82Use this path for X Layer x402, Multi-Party Payment (MPP), session payment, charge, and A2A charge flows.
83
84For buyer-side agent flows:
85
861. Install or reference the current okx/onchainos-skills repository.
872. Use skills/okx-agent-payments-protocol/SKILL.md as the dispatcher.
883. Treat skills/okx-x402-payment/SKILL.md as a deprecated compatibility alias, not as the canonical skill.
894. Require explicit user confirmation before wallet status checks or payment actions. Do not hide payment execution behind a generic tool call.
90
91For seller-side API flows, fetch the latest language-specific guide before generating code:
92
93| Runtime | Current guide |
94|---------|---------------|
95| TypeScript | https://raw.githubusercontent.com/okx/payments/main/typescript/SELLER.md |
96| Go | https://raw.githubusercontent.com/okx/payments/main/go/x402/SELLER.md |
97| Rust | https://raw.githubusercontent.com/okx/payments/main/rust/x402/SELLER.md |
98| Java | https://raw.githubusercontent.com/okx/payments/main/java/SELLER.md |
99
100Do not copy examples from older docs without checking the current OKX repository. Current OKX guidance uses okx-agent-payments-protocol as the dispatcher, and Java seller docs are now available.
101
102## Examples
103
104### Budget enforcement in an MCP client
105
106When building an orchestrator that calls the agentpay MCP server, enforce budgets before dispatching paid tool calls.
107
108> **Prerequisites**: Install the package before adding the MCP config — npx without -y will prompt for confirmation in non-interactive environments, causing the server to hang: npm install -g agentwallet-sdk@6.0.0
109
110```typescript
111import { Client } from "@modelcontextprotocol/sdk/client/index.js";
112import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
113
114async function main() {
115 // 1. Validate credentials before constructing the transport.
116 // A missing key must fail immediately — never let the subprocess start without auth.
117 const walletKey = process.env.WALLET_PRIVATE_KEY;
118 if (!walletKey) {
119 throw new Error("WALLET_PRIVATE_KEY is not set — refusing to start payment server");
120 }
121
122 // Connect to the agentpay MCP server via stdio transport.
123 // Whitelist only the env vars the server needs — never forward all of process.env
124 // to a third-party subprocess that manages private keys.
125 const transport = new StdioClientTransport({
126 command: "npx",
127 args: ["agentwallet-sdk@6.0.0"],
128 env: {
129 PATH: process.env.PATH ?? "",
130 NODE_ENV: process.env.NODE_ENV ?? "production",
131 WALLET_PRIVATE_KEY: walletKey,
132 },
133 });
134 const agentpay = new Client({ name: "orchestrator", version: "1.0.0" });
135 await agentpay.connect(transport);
136
137 // 2. Set spending policy before delegating to the agent.
138 // Always verify success — a silent failure means no controls are active.
139 const policyResult = await agentpay.callTool({
140 name: "set_policy",
141 arguments: {
142 per_task_budget: 0.50,
143 per_session_budget: 5.00,
144 allowlisted_recipients: ["api.example.com"],
145 },
146 });
147 if (policyResult.isError) {
148 throw new Error(
149 Failed to set spending policy — do not delegate: ${JSON.stringify(policyResult.content)}
150 );
151 }
152
153 // 3. Use preToolCheck before any paid action
154 await preToolCheck(agentpay, 0.01);
155}
156
157// Pre-tool hook: fail-closed budget enforcement with four distinct error paths.
158async function preToolCheck(agentpay: Client, apiCost: number): Promise<void> {
159 // Path 1: Reject invalid input (NaN/Infinity bypass the < comparison)
160 if (!Number.isFinite(apiCost) || apiCost < 0) {
161 throw new Error(Invalid apiCost: ${apiCost} — action blocked);
162 }
163
164 // Path 2: Transport/connectivity failure
165 let result;
166 try {
167 result = await agentpay.callTool({ name: "check_spending" });
168 } catch (err) {
169 throw new Error(Payment service unreachable — action blocked: ${err});
170 }
171
172 // Path 3: Tool returned an error (e.g., auth failure, wallet not initialised)
173 if (result.isError) {
174 throw new Error(
175 check_spending failed — action blocked: ${JSON.stringify(result.content)}
176 );
177 }
178
179 // Path 4: Parse and validate the response shape
180 let remaining: number;
181 try {
182 const parsed = JSON.parse(
183 (result.content as Array<{ text: string }>)[0].text
184 );
185 if (!Number.isFinite(parsed?.remaining)) {
186 throw new TypeError("missing or non-finite 'remaining' field");
187 }
188 remaining = parsed.remaining;
189 } catch (err) {
190 throw new Error(
191 check_spending returned unexpected format — action blocked: ${err}
192 );
193 }
194
195 // Path 5: Budget exceeded
196 if (remaining < apiCost) {
197 throw new Error(
198 Budget exceeded: need $${apiCost} but only $${remaining} remaining
199 );
200 }
201}
202
203main().catch((err) => {
204 console.error(err);
205 process.exitCode = 1;
206});
207```
208
209## Best Practices
210
211- **Set budgets before delegation**: When spawning sub-agents, attach a SpendingPolicy via your orchestration layer. Never give an agent unlimited spend.
212- **Pin your dependencies**: Always specify an exact version in your MCP config (e.g., agentwallet-sdk@6.0.0). Verify package integrity before deploying to production.
213- **Audit trails**: Use list_transactions in post-task hooks to log what was spent and why.
214- **Fail closed**: If the payment tool is unreachable, block the paid action — don't fall back to unmetered access.
215- **Pair with security-review**: Payment tools are high-privilege. Apply the same scrutiny as shell access.
216- **Test with testnets first**: Use Base Sepolia for development; switch to Base mainnet for production.
217
218## Production Reference
219
220- **npm**: [agentwallet-sdk](https://www.npmjs.com/package/agentwallet-sdk)
221- **Merged into NVIDIA NeMo Agent Toolkit**: [PR #17](https://github.com/NVIDIA/NeMo-Agent-Toolkit-Examples/pull/17) — x402 payment tool for NVIDIA's agent examples
222- **Protocol spec**: [x402.org](https://x402.org)
223- **OKX Payments SDKs**: [okx/payments](https://github.com/okx/payments) — TypeScript, Go, Rust, and Java seller integrations for X Layer x402
224- **OKX Agent Payments Protocol skill**: [okx/onchainos-skills](https://github.com/okx/onchainos-skills/tree/main/skills/okx-agent-payments-protocol)
225- **OKX Payments overview**: [web3.okx.com/onchainos/dev-docs/payments/overview](https://web3.okx.com/onchainos/dev-docs/payments/overview)
226