Communitygithub.com

agent-payment-x402

AIエージェントにx402支払い実行機能を追加します。タスクごとの予算、支出管理、非カストディアルウォレットをサポート。Base(agentwallet-sdk経由)およびX Layer(OKX Payments / OKX Agent Payments Protocol経由)に対応します。エージェントが自ら支払いを行う必要があり、タスクごとの予算、支出管理、非カストディアルウォレットが必要な場合に使用します。

agent-payment-x402 とは?

Agent Payment Execution (x402) は、AIエージェントがポリシーに基づいた支払いを実行できるようにするスキルです。x402 HTTP支払いプロトコルとMCPツールを使用して、エージェントが外部サービス、API、または他のエージェントにカストディアルリスクなしで支払いを行えるようにします。このスキルは、タスクごとの予算、セッションごとの予算、許可された受取人リスト、レート制限などの支出管理機能を提供し、エージェントが設定されたポリシー内でのみ行動できるようにします。主要な統合パスとして、Baseネットワーク向けのagentwallet-sdkと、X Layer向けのOKX Agent Payments Protocolをサポートしており、TypeScript、Go、Rust、Java、Pythonなど複数の言語で販売者側の統合も可能です。非カストディアルウォレット(ERC-4337スマートアカウント)を使用するため、資金をプールしたりカストディアルリスクを負うことなく、安全な支払い実行が実現します。

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

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

エージェント支払い実行 (x402)

AIエージェントがポリシーに基づいた支払いを、組み込みの支出管理機能とともに行えるようにします。x402 HTTP支払いプロトコルとMCPツールを使用するため、エージェントはカストディアルリスクなしで外部サービス、API、または他のエージェントに支払うことができます。

使用するタイミング

エージェントがAPI呼び出しの支払い、サービスの購入、他のエージェントとの決済、タスクごとの支出制限の適用、または非カストディアルウォレットの管理を行う必要がある場合に使用します。cost-aware-llm-pipeline や security-review スキルと自然に組み合わせることができます。

決定木

エージェントが有料APIへのアクセスを購入するのか、自身のAPIに対して他のエージェントに課金するのかに基づいて統合パスを選択します。

ニーズ推奨パス
エージェントがBaseまたは他のagentwallet対応チェーン上の402ゲートAPIに支払う厳格な支出ポリシーを持つMCP支払いサーバーとして agentwallet-sdk を使用
エージェントがX Layer上の402ゲートAPIに支払うokx/onchainos-skills からOKX Agent Payments Protocolを使用( okx-x402-payment は非推奨のレガシーエイリアス)
TypeScript APIがエージェントに課金するExpress、Hono、Fastify、Next.js向けのOKX Payments TypeScript販売者SDKドキュメントを使用
Go APIがエージェントに課金するGin、Echo、net/http 向けのOKX Payments Go販売者SDKドキュメントを使用
Rust APIがエージェントに課金するAxum向けのOKX Payments Rust販売者SDKドキュメントを使用
Java APIがエージェントに課金するSpring Boot 2/3、Java EE、Jakarta向けのOKX Payments Java販売者SDKドキュメントを使用
Python APIがエージェントに課金する実装前に現在のOKX Paymentsリポジトリを確認。Python販売者ガイドが利用できない場合あり

サポートされているネットワーク

  • agentwallet-sdk: パッケージドキュメントを使用して、本番環境の前に現在のネットワークカバレッジを確認してください。Base Sepoliaが最も安全な開発デフォルトです。Baseメインネットは、元のスキルが示す本番パスです。
  • OKX Payments / X Layer: 現在の販売者ドキュメントはX Layer(eip155:196)とUSDT0決済を対象としています。本番コードを生成する前に、最新のSDKドキュメントを取得してください。支払いパッケージとファシリテーターの動作は急速に変更される可能性があります。

仕組み

x402プロトコル

x402は、HTTP 402(Payment Required)を機械がネゴシエーション可能なフローに拡張します。サーバーが 402 を返すと、エージェントの支払いツールが価格をネゴシエートし、予算を確認し、トランザクションに署名し、オーケストレーターによって設定されたポリシーと確認境界内でのみ再試行します。

支出管理

すべての支払いツールの呼び出しは、SpendingPolicy を適用します。

  • タスクごとの予算 — 単一のエージェントアクションの最大支出額
  • セッションごとの予算 — セッション全体の累積制限
  • 許可リストに登録された受取人 — エージェントが支払い可能なアドレス/サービスを制限
  • レート制限 — 1分/1時間あたりの最大トランザクション数

非カストディアルウォレット

エージェントは、ERC-4337スマートアカウントを介して自身の鍵を保持します。オーケストレーターが委任前にポリシーを設定します。エージェントは範囲内でのみ支出できます。資金のプールやカストディアルリスクはありません。

MCP統合

支払いレイヤーは、任意のClaude Codeまたはエージェントハーネス設定に組み込める標準的なMCPツールを公開します。

セキュリティ注意: 常にパッケージバージョンを固定してください。このツールは秘密鍵を管理します。固定されていない 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);
}

// プリツールフック: 4つの異なるエラーパスを持つフェイルクローズドな予算適用。
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と組み合わせる: 支払いツールは高特権です。シェルアクセスと同じ注意を払ってください。
  • 最初にテストネットでテストする: 開発には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.

関連スキル