Communitygithub.com

agent-payment-x402

为AI智能体添加x402支付执行能力,支持按任务预算、支出控制和自托管钱包。适用于智能体需要自行支付并管理预算的场景。

agent-payment-x402 是什么?

agent-payment-x402 是一项为 AI 智能体提供策略化支付执行能力的技能。它基于 x402 HTTP 支付协议和 MCP 工具,使智能体能够为外部服务、API 或其他智能体进行支付,同时保持非托管钱包的安全性,避免了资金池化带来的风险。该技能支持两种主要集成路径:对于 Base 等多链网络,使用 agentwallet-sdk 作为 MCP 支付服务器并配合严格支出策略;对于 X Layer,则需使用 OKX Agent Payments Protocol。技能内置了按任务预算、按会话预算、白名单接收方和速率限制等完整支出控制策略,并采用 ERC-4337 智能账户管理密钥,确保智能体只能在预设策略范围内操作。支持 Claude Code 等智能体框架通过 MCP 工具调用,并提供详细的 TypeScript 集成示例,包括预算预检查、失败封闭等最佳实践。

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

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

智能体支付执行 (x402)

为 AI 智能体启用策略化支付,内置支出控制。使用 x402 HTTP 支付协议和 MCP 工具,使智能体能够为外部服务、API 或其他智能体进行支付,无需承担托管风险。

何时使用

当你的智能体需要:支付 API 调用、购买服务、与其他智能体结算、强制执行按任务支出限制,或管理非托管钱包时使用。与 cost-aware-llm-pipeline 和 security-review 技能自然搭配。

决策树

根据你的智能体是购买付费 API 的访问权限还是为他人提供 API 收费,选择集成路径:

需求推荐路径
智能体支付 Base 或其它 agentwallet 支持链上的 402 付费 API使用 agentwallet-sdk 作为 MCP 支付服务器,并设置严格支出策略
智能体支付 X Layer 上的 402 付费 API使用 okx/onchainos-skills 中的 OKX Agent Payments Protocol;okx-x402-payment 是已弃用的旧别名
TypeScript API 向智能体收费使用 OKX Payments TypeScript 卖家 SDK 文档(集成 Express、Hono、Fastify 或 Next.js)
Go API 向智能体收费使用 OKX Payments Go 卖家 SDK 文档(集成 Gin、Echo 或 net/http)
Rust API 向智能体收费使用 OKX Payments Rust 卖家 SDK 文档(集成 Axum)
Java API 向智能体收费使用 OKX Payments Java 卖家 SDK 文档(集成 Spring Boot 2/3、Java EE 或 Jakarta)
Python API 向智能体收费在实现前请检查当前 OKX Payments 仓库;Python 卖家指南可能不可用

支持的网络

  • agentwallet-sdk:在生产环境前,使用包文档确认当前网络覆盖范围。Base Sepolia 是最安全的开发默认选择;Base 主网是原始技能指定的生产路径。
  • OKX Payments / X Layer:当前卖家文档针对 X Layer(eip155:196)和 USDT0 结算。在生成生产代码前请获取最新 SDK 文档,因为支付包和协调者行为可能快速变化。

工作原理

x402 协议

x402 将 HTTP 402(需要付款)扩展为机器可协商的流程。当服务器返回 402 时,智能体的支付工具会协商价格、检查预算、签署交易,并在编排器设置的策略和确认边界内仅重试一次。

支出控制

每次支付工具调用都会强制执行 SpendingPolicy:

  • 按任务预算 — 单个智能体动作的最大支出
  • 按会话预算 — 整个会话的累计限制
  • 白名单接收方 — 限制智能体可以支付的地址/服务
  • 速率限制 — 每分钟/小时的最大交易数量

非托管钱包

智能体通过 ERC-4337 智能账户持有自己的密钥。编排器在委托前设置策略;智能体只能在边界内支出。无资金池化,无托管风险。

MCP 集成

支付层暴露标准 MCP 工具,可无缝接入任何 Claude Code 或智能体框架设置。

安全注意事项:始终锁定包版本。此工具管理私钥 — 未锁定的 npx 安装会引入供应链风险。

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

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

可用工具(智能体可调用)

工具用途
get_balance检查智能体钱包余额
send_payment向地址或 ENS 发送付款
check_spending查询剩余预算
list_transactions所有支付的审计追踪

注意:支出策略由编排器在委托给智能体之前设置 — 而非智能体自身。这可以防止智能体提升自己的支出限制。在你的编排层或任务前钩子中通过 set_policy 配置策略,切勿将其暴露为智能体可调用的工具。

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

此路径用于 X Layer 的 x402、多方支付 (MPP)、会话支付、收费和智能体对智能体 (A2A) 收费流程。

对于买方侧智能体流程:

  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 配置前安装包 — npx 不带 -y 会在非交互式环境中提示确认,导致服务器挂起: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. 在委托给智能体前设置支出策略。
  //    始终验证成功 — 静默失败意味着没有激活任何控制措施。
  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);
}

// Pre-tool 钩子:四种不同错误路径下的失败封闭预算执行。
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;
});

最佳实践

  • 委托前设置预算:在启动子智能体时,通过编排层附加 SpendingPolicy。切勿允许智能体无限制支出。
  • 锁定依赖:始终在 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/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

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.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

api-connector-builder

Build a new API connector or provider by matching the target repo

相关技能