agent-payment-x402

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Agent Payment Execution (x402)

Agent支付执行(x402)

Enable 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.
让AI Agent能够执行受策略管控的支付操作,内置支出控制功能。借助x402 HTTP支付协议和MCP工具,Agent无需承担托管风险即可为外部服务、API或其他Agent支付费用。

When to Use

适用场景

Use 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.
适用于以下场景:你的Agent需要为API调用付费、购买服务、与其他Agent结算、执行按任务设置的支出限额,或管理非托管钱包。与cost-aware-llm-pipeline和security-review技能搭配使用效果更佳。

Decision Tree

决策树

Choose the integration path based on whether your agent is buying access to a paid API or charging others for one:
NeedRecommended path
Agent pays a 402-gated API on Base or another agentwallet-supported chainUse
agentwallet-sdk
as an MCP payment server with strict spending policy
Agent pays a 402-gated API on X LayerUse OKX Agent Payments Protocol from
okx/onchainos-skills
;
okx-x402-payment
is a deprecated legacy alias
TypeScript API charges agentsUse OKX Payments TypeScript seller SDK docs for Express, Hono, Fastify, or Next.js
Go API charges agentsUse OKX Payments Go seller SDK docs for Gin, Echo, or
net/http
Rust API charges agentsUse OKX Payments Rust seller SDK docs for Axum
Java API charges agentsUse OKX Payments Java seller SDK docs for Spring Boot 2/3, Java EE, or Jakarta
Python API charges agentsCheck the current OKX Payments repository before implementation; a Python seller guide may not be available
根据你的Agent是购买付费API访问权限还是向他人提供收费API,选择对应的集成路径:
需求推荐路径
Agent在Base链或其他agentwallet-sdk支持的链上访问402管控的API使用
agentwallet-sdk
作为MCP支付服务器,并配置严格的支出策略
Agent在X Layer链上访问402管控的API使用
okx/onchainos-skills
中的OKX Agent Payments Protocol;
okx-x402-payment
已废弃,仅作为兼容别名
TypeScript API向Agent收费参考OKX Payments TypeScript卖家SDK文档,支持Express、Hono、Fastify或Next.js
Go API向Agent收费参考OKX Payments Go卖家SDK文档,支持Gin、Echo或
net/http
Rust API向Agent收费参考OKX Payments Rust卖家SDK文档,支持Axum
Java API向Agent收费参考OKX Payments Java卖家SDK文档,支持Spring Boot 2/3、Java EE或Jakarta
Python API向Agent收费实施前请查看OKX Payments当前仓库;Python卖家指南可能尚未提供

Supported Networks

支持的网络

  • 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.
  • 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.
  • agentwallet-sdk
    :上线前请查看包文档确认当前网络覆盖范围。Base Sepolia是最安全的开发默认选项;Base主网是原技能指定的生产环境路径。
  • OKX Payments / X Layer:当前卖家文档针对X Layer(
    eip155:196
    )和USDT0结算。生成生产代码前请获取最新SDK文档,因为支付包和服务商行为可能会快速变化。

How It Works

工作原理

x402 Protocol

x402协议

x402 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.
x402将HTTP 402(需要支付)扩展为可机器协商的流程。当服务器返回
402
时,Agent的支付工具会协商价格、检查预算、签署交易,并仅在编排器设定的策略和确认边界内重试请求。

Spending Controls

支出控制

Every payment tool call enforces a
SpendingPolicy
:
  • Per-task budget — max spend for a single agent action
  • Per-session budget — cumulative limit across an entire session
  • Allowlisted recipients — restrict which addresses/services the agent can pay
  • Rate limits — max transactions per minute/hour
每次支付工具调用都会强制执行
SpendingPolicy
  • 按任务预算 — 单个Agent操作的最高支出
  • 按会话预算 — 整个会话期间的累计限额
  • 收件人白名单 — 限制Agent可支付的地址/服务
  • 速率限制 — 每分钟/每小时的最大交易次数

Non-Custodial Wallets

非托管钱包

Agents 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.
Agent通过ERC-4337智能账户持有自己的密钥。编排器在委托前设置策略;Agent只能在限定范围内支出。无资金池,无托管风险。

MCP Integration

MCP集成

The payment layer exposes standard MCP tools that slot into any Claude Code or agent harness setup.
Security note: Always pin the package version. This tool manages private keys — unpinned
npx
installs introduce supply-chain risk.
支付层提供标准MCP工具,可嵌入任何Claude Code或Agent harness设置中。
安全提示:始终固定包版本。该工具管理私钥 — 未固定版本的
npx
安装会引入供应链风险。

Option A: agentwallet-sdk (Base / multi-chain)

选项A:agentwallet-sdk(Base / 多链)

json
{
  "mcpServers": {
    "agentpay": {
      "command": "npx",
      "args": ["agentwallet-sdk@6.0.0"]
    }
  }
}
json
{
  "mcpServers": {
    "agentpay": {
      "command": "npx",
      "args": ["agentwallet-sdk@6.0.0"]
    }
  }
}

Available Tools (agent-callable)

可用工具(Agent可调用)

ToolPurpose
get_balance
Check agent wallet balance
send_payment
Send payment to address or ENS
check_spending
Query remaining budget
list_transactions
Audit trail of all payments
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.
工具用途
get_balance
检查Agent钱包余额
send_payment
向地址或ENS发送支付
check_spending
查询剩余预算
list_transactions
所有支付的审计追踪
注意:支出策略由编排器在委托给Agent前设置 — 而非Agent自身设置。这可防止Agent自行提升支出限额。请通过编排层或任务前钩子中的
set_policy
配置策略,切勿将其设为Agent可调用工具。

Option B: OKX Agent Payments Protocol (X Layer)

选项B:OKX Agent Payments Protocol(X Layer)

Use this path for X Layer x402, Multi-Party Payment (MPP), session payment, charge, and A2A charge flows.
For buyer-side agent flows:
  1. Install or reference the current
    okx/onchainos-skills
    repository.
  2. Use
    skills/okx-agent-payments-protocol/SKILL.md
    as the dispatcher.
  3. Treat
    skills/okx-x402-payment/SKILL.md
    as a deprecated compatibility alias, not as the canonical skill.
  4. Require explicit user confirmation before wallet status checks or payment actions. Do not hide payment execution behind a generic tool call.
For seller-side API flows, fetch the latest language-specific guide before generating code:
RuntimeCurrent guide
TypeScript
https://raw.githubusercontent.com/okx/payments/main/typescript/SELLER.md
Go
https://raw.githubusercontent.com/okx/payments/main/go/x402/SELLER.md
Rust
https://raw.githubusercontent.com/okx/payments/main/rust/x402/SELLER.md
Java
https://raw.githubusercontent.com/okx/payments/main/java/SELLER.md
Do 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.
适用于X Layer的x402、多方支付(MPP)、会话支付、收费和A2A收费流程。
对于买方侧Agent流程:
  1. 安装或引用当前
    okx/onchainos-skills
    仓库。
  2. 使用
    skills/okx-agent-payments-protocol/SKILL.md
    作为调度器。
  3. skills/okx-x402-payment/SKILL.md
    视为已废弃的兼容别名,而非标准技能。
  4. 在钱包状态检查或支付操作前需获得用户明确确认。切勿将支付执行隐藏在通用工具调用背后。
对于卖方侧API流程,生成代码前请获取最新的语言特定指南:
运行时当前指南
TypeScript
https://raw.githubusercontent.com/okx/payments/main/typescript/SELLER.md
Go
https://raw.githubusercontent.com/okx/payments/main/go/x402/SELLER.md
Rust
https://raw.githubusercontent.com/okx/payments/main/rust/x402/SELLER.md
Java
https://raw.githubusercontent.com/okx/payments/main/java/SELLER.md
不要从旧文档复制示例,需先检查OKX当前仓库。当前OKX指南使用
okx-agent-payments-protocol
作为调度器,且Java卖家文档现已可用。

Examples

示例

Budget enforcement in an MCP client

MCP客户端中的预算强制执行

When building an orchestrator that calls the agentpay MCP server, enforce budgets before dispatching paid tool calls.
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
typescript
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";

async function main() {
  // 1. Validate credentials before constructing the transport.
  //    A missing key must fail immediately — never let the subprocess start without auth.
  const walletKey = process.env.WALLET_PRIVATE_KEY;
  if (!walletKey) {
    throw new Error("WALLET_PRIVATE_KEY is not set — refusing to start payment server");
  }

  // Connect to the agentpay MCP server via stdio transport.
  // Whitelist only the env vars the server needs — never forward all of process.env
  // to a third-party subprocess that manages private keys.
  const transport = new StdioClientTransport({
    command: "npx",
    args: ["agentwallet-sdk@6.0.0"],
    env: {
      PATH: process.env.PATH ?? "",
      NODE_ENV: process.env.NODE_ENV ?? "production",
      WALLET_PRIVATE_KEY: walletKey,
    },
  });
  const agentpay = new Client({ name: "orchestrator", version: "1.0.0" });
  await agentpay.connect(transport);

  // 2. Set spending policy before delegating to the agent.
  //    Always verify success — a silent failure means no controls are active.
  const policyResult = await agentpay.callTool({
    name: "set_policy",
    arguments: {
      per_task_budget: 0.50,
      per_session_budget: 5.00,
      allowlisted_recipients: ["api.example.com"],
    },
  });
  if (policyResult.isError) {
    throw new Error(
      `Failed to set spending policy — do not delegate: ${JSON.stringify(policyResult.content)}`
    );
  }

  // 3. Use preToolCheck before any paid action
  await preToolCheck(agentpay, 0.01);
}

// Pre-tool hook: fail-closed budget enforcement with four distinct error paths.
async function preToolCheck(agentpay: Client, apiCost: number): Promise<void> {
  // Path 1: Reject invalid input (NaN/Infinity bypass the < comparison)
  if (!Number.isFinite(apiCost) || apiCost < 0) {
    throw new Error(`Invalid apiCost: ${apiCost} — action blocked`);
  }

  // Path 2: Transport/connectivity failure
  let result;
  try {
    result = await agentpay.callTool({ name: "check_spending" });
  } catch (err) {
    throw new Error(`Payment service unreachable — action blocked: ${err}`);
  }

  // Path 3: Tool returned an error (e.g., auth failure, wallet not initialised)
  if (result.isError) {
    throw new Error(
      `check_spending failed — action blocked: ${JSON.stringify(result.content)}`
    );
  }

  // Path 4: Parse and validate the response shape
  let remaining: number;
  try {
    const parsed = JSON.parse(
      (result.content as Array<{ text: string }>)[0].text
    );
    if (!Number.isFinite(parsed?.remaining)) {
      throw new TypeError("missing or non-finite 'remaining' field");
    }
    remaining = parsed.remaining;
  } catch (err) {
    throw new Error(
      `check_spending returned unexpected format — action blocked: ${err}`
    );
  }

  // Path 5: Budget exceeded
  if (remaining < apiCost) {
    throw new Error(
      `Budget exceeded: need $${apiCost} but only $${remaining} remaining`
    );
  }
}

main().catch((err) => {
  console.error(err);
  process.exitCode = 1;
});
构建调用agentpay MCP服务器的编排器时,需在调度付费工具调用前强制执行预算。
前提条件:添加MCP配置前请先安装包 — 不带
-y
npx
会在非交互式环境中提示确认,导致服务器挂起:
npm install -g agentwallet-sdk@6.0.0
typescript
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";

async function main() {
  // 1. 在构建传输前验证凭据。
  //    缺少密钥必须立即失败 — 绝不要让子进程在无授权的情况下启动。
  const walletKey = process.env.WALLET_PRIVATE_KEY;
  if (!walletKey) {
    throw new Error("WALLET_PRIVATE_KEY未设置 — 拒绝启动支付服务器");
  }

  // 通过stdio传输连接到agentpay MCP服务器。
  // 仅白名单服务器所需的环境变量 — 绝不要将所有process.env转发
  // 给管理私钥的第三方子进程。
  const transport = new StdioClientTransport({
    command: "npx",
    args: ["agentwallet-sdk@6.0.0"],
    env: {
      PATH: process.env.PATH ?? "",
      NODE_ENV: process.env.NODE_ENV ?? "production",
      WALLET_PRIVATE_KEY: walletKey,
    },
  });
  const agentpay = new Client({ name: "orchestrator", version: "1.0.0" });
  await agentpay.connect(transport);

  // 2. 在委托给Agent前设置支出策略。
  //    始终验证是否成功 — 静默失败意味着没有控制生效。
  const policyResult = await agentpay.callTool({
    name: "set_policy",
    arguments: {
      per_task_budget: 0.50,
      per_session_budget: 5.00,
      allowlisted_recipients: ["api.example.com"],
    },
  });
  if (policyResult.isError) {
    throw new Error(
      `设置支出策略失败 — 请勿委托:${JSON.stringify(policyResult.content)}`
    );
  }

  // 3. 在任何付费操作前使用preToolCheck
  await preToolCheck(agentpay, 0.01);
}

// 工具前钩子:通过四个不同的错误路径实现故障关闭式预算强制执行。
async function preToolCheck(agentpay: Client, apiCost: number): Promise<void> {
  // 路径1:拒绝无效输入(NaN/Infinity会绕过<比较)
  if (!Number.isFinite(apiCost) || apiCost < 0) {
    throw new Error(`无效的apiCost:${apiCost} — 操作已阻止`);
  }

  // 路径2:传输/连接失败
  let result;
  try {
    result = await agentpay.callTool({ name: "check_spending" });
  } catch (err) {
    throw new Error(`支付服务不可达 — 操作已阻止:${err}`);
  }

  // 路径3:工具返回错误(例如,授权失败、钱包未初始化)
  if (result.isError) {
    throw new Error(
      `check_spending失败 — 操作已阻止:${JSON.stringify(result.content)}`
    );
  }

  // 路径4:解析并验证响应格式
  let remaining: number;
  try {
    const parsed = JSON.parse(
      (result.content as Array<{ text: string }>)[0].text
    );
    if (!Number.isFinite(parsed?.remaining)) {
      throw new TypeError("缺少或非有限值的'remaining'字段");
    }
    remaining = parsed.remaining;
  } catch (err) {
    throw new Error(
      `check_spending返回意外格式 — 操作已阻止:${err}`
    );
  }

  // 路径5:预算超支
  if (remaining < apiCost) {
    throw new Error(
      `预算超支:需要$${apiCost},但仅剩$${remaining}`
    );
  }
}

main().catch((err) => {
  console.error(err);
  process.exitCode = 1;
});

Best Practices

最佳实践

  • Set budgets before delegation: When spawning sub-agents, attach a SpendingPolicy via your orchestration layer. Never give an agent unlimited spend.
  • 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.
  • Audit trails: Use
    list_transactions
    in post-task hooks to log what was spent and why.
  • Fail closed: If the payment tool is unreachable, block the paid action — don't fall back to unmetered access.
  • Pair with security-review: Payment tools are high-privilege. Apply the same scrutiny as shell access.
  • Test with testnets first: Use Base Sepolia for development; switch to Base mainnet for production.
  • 委托前设置预算:生成子Agent时,通过编排层附加SpendingPolicy。绝不要赋予Agent无限支出权限。
  • 固定依赖版本:始终在MCP配置中指定确切版本(例如,
    agentwallet-sdk@6.0.0
    )。上线前验证包完整性。
  • 审计追踪:在任务后钩子中使用
    list_transactions
    记录支出明细及原因。
  • 故障关闭:如果支付工具不可达,阻止付费操作 — 不要回退到无计量访问。
  • 搭配security-review:支付工具属于高权限工具。需像对待shell访问一样进行严格审查。
  • 先在测试网测试:开发时使用Base Sepolia;生产环境切换到Base主网。

Production Reference

生产参考