Communitygithub.com

agent-payment-x402

為 AI Agent 新增 x402 支付執行功能,支援每項任務預算、支出控管與非託管錢包。可透過 agentwallet-sdk 用於 Base 鏈,或透過 OKX Payments / OKX Agent Payments Protocol 用於 X Layer。當 Agent 需要自行支付某項費用,且需要任務級預算、支出控管及非託管錢包時使用。

agent-payment-x402 是什麼?

Agent Payment Execution (x402) 是一項為 AI Agent 提供政策控制支付能力的技能,內建支出控管機制。它基於 x402 HTTP 支付協議與 MCP 工具,讓 Agent 能夠支付外部服務、API 或其他 Agent,而無需承擔資金託管風險。該技能支援 Base 鏈(透過 agentwallet-sdk)與 X Layer(透過 OKX Agent Payments Protocol),並提供詳細的決策樹,幫助開發者根據不同的支付場景選擇合適的整合路徑。其核心功能包括:非託管的 ERC-4337 智慧帳戶錢包、基於 SpendingPolicy 的多層級預算控制(任務級、會話級、白名單收款方、交易速率限制),以及標準化的 MCP 工具(get_balance、send_payment、check_spending、list_transactions)。開發者可以在 Claude Code 或其他 Agent 框架中輕鬆整合這些工具,並透過嚴格的預算設定與失敗封閉(fail-closed)模式確保安全。支援完整的買方與賣方流程,包含 TypeScript、Go、Rust、Java 等多種語言的 SDK 文件參考。

相容平台✓Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/agent-payment-x402

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

Agent 支付執行 (x402)

讓 AI Agent 能夠執行受政策約束的支付,並內建支出控管功能。使用 x402 HTTP 支付協議與 MCP 工具,使 Agent 在無託管風險下,支付外部服務、API 或其他 Agent。

使用時機

當您的 Agent 需要:支付 API 呼叫費用、購買服務、與其他 Agent 結算、強制執行任務級支出上限,或管理非託管錢包時,即可使用此技能。此技能與 cost-aware-llm-pipeline 和 security-review 技能搭配使用效果最佳。

決策樹

根據您的 Agent 是要購買付費 API 的存取權,還是向其他 Agent 收取費用,選擇不同的整合路徑:

需求建議路徑
Agent 在 Base 或其他 agentwallet 支援的鏈上支付 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 賣方指南

支援的網路

  • agentwallet-sdk:使用官方套件文件確認生產環境前的當前網路覆蓋範圍。Base Sepolia 是最安全的開發預設值;而 Base 主網則是原始技能指定的正式路徑。
  • OKX Payments / X Layer:目前的賣方文件以 X Layer(eip155:196)及 USDT0 結算為目標。產生正式程式碼前,請先取得最新的 SDK 文件,因為支付套件和促進者行為可能快速變動。

運作方式

x402 協議

x402 將 HTTP 402(需要付款)擴展為機器可協商的流程。當伺服器回傳 402 狀態碼時,Agent 的支付工具會協商價格、檢查預算、簽署交易,並僅在協調器設定的政策與確認邊界內重試。

支出控管

每個支付工具呼叫都會強制執行 SpendingPolicy:

  • 任務級預算 — 單一 Agent 動作的最大花費
  • 會話級預算 — 整個會話的累積上限
  • 白名單收款方 — 限制 Agent 可支付的位址/服務
  • 速率限制 — 每分鐘/每小時的最大交易數

非託管錢包

Agent 透過 ERC-4337 智慧帳戶持有自己的金鑰。協調器在委派前設定政策;Agent 只能在範圍內花費。無共用資金,無託管風險。

MCP 整合

支付層提供標準的 MCP 工具,可插入任何 Claude Code 或 Agent 框架設定。

安全性注意事項:務必鎖定套件版本。此工具管理私鑰 — 未鎖定的 npx 安裝將帶來供應鏈風險。

選項 A:agentwallet-sdk(Base / 多鏈)

{
  "mcpServers": {
    "agentpay": {
      "command": "npx",
      "args": ["[email protected]"]
    }
  }
}

可用工具(Agent 可呼叫)

工具用途
get_balance檢查 Agent 錢包餘額
send_payment向地址或 ENS 發送支付
check_spending查詢剩餘預算
list_transactions所有支付的審計追蹤

注意:支出政策由協調器在委派給 Agent 之前設定 — 而不是由 Agent 本身設定。這可防止 Agent 自行提高支出上限。請在您的協調層或任務前掛鉤中,透過 set_policy 設定政策,切勿將其設為 Agent 可呼叫的工具。

選項 B:OKX Agent Payments Protocol(X Layer)

針對 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 流程,請在產生程式碼前,先取得最新的語言特定指南:

執行環境目前指南
TypeScripthttps://raw.githubusercontent.com/okx/payments/main/typescript/SELLER.md
Gohttps://raw.githubusercontent.com/okx/payments/main/go/x402/SELLER.md
Rusthttps://raw.githubusercontent.com/okx/payments/main/rust/x402/SELLER.md
Javahttps://raw.githubusercontent.com/okx/payments/main/java/SELLER.md

請勿直接複製舊版文件中的範例,而應檢查目前的 OKX 儲存庫。目前的 OKX 指南使用 okx-agent-payments-protocol 作為調度器,且 Java 賣方文件現已可用。

範例

在 MCP 用戶端中執行預算控管

在建構呼叫 agentpay MCP 伺服器的協調器時,請在分派付費工具呼叫前強制執行預算。

先決條件:在新增 MCP 設定前,請先安裝套件 — 在非互動式環境中,未使用 -y 的 npx 會提示確認,導致伺服器掛起:npm install -g [email protected]

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: ["[email protected]"],
    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;
});

最佳實踐

  • 委派前設定預算:在生成子 Agent 時,透過您的協調層附加 SpendingPolicy。切勿讓 Agent 擁有無限花費權限。
  • 鎖定依賴項目:在 MCP 設定中始終指定確切版本(例如 [email protected])。在部署到正式環境前,驗證套件的完整性。
  • 審計追蹤:在任務後掛鉤中使用 list_transactions 記錄花費內容及原因。
  • 失敗封閉:如果支付工具無法連線,請封鎖付費操作 — 不要回退到無計量存取。
  • 與 security-review 搭配使用:支付工具屬於高權限操作。請比照 Shell 存取權限進行審查。
  • 先在測試網路上測試:使用 Base Sepolia 進行開發;正式環境再切換至 Base 主網。

正式環境參考

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

相關技能