Communitygithub.com

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

AIエージェントにx402支払い実行機能を追加します。タスクごとの予算、支出制御、非カストディアルウォレットを提供します。Baseはagentwallet-sdk、X LayerはOKX Payments / OKX Agent Payments Protocolをサポートします。エージェントが自分で支払いを行い、タスクごとの予算、支出制御、非カストディアルウォレットが必要な場合に使用します。

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

このスキルは、AIエージェントがポリシーに基づいた支払いを実行できるようにするための包括的なソリューションです。x402 HTTP支払いプロトコルとMCPツールを利用して、エージェントがカストディアルリスクなしに外部サービス、API、他のエージェントへの支払いを行えるようにします。主な機能として、タスクごとの予算、セッションごとの累積制限、許可リストによる受取人制限、レート制限などの支出制御メカニズムを備えています。また、ERC-4337スマートアカウントを使用した非カストディアルウォレットをサポートし、エージェントが自身の秘密鍵を保持します。このスキルは、Baseネットワークではagentwallet-sdk、X LayerではOKX Agent Payments Protocolを介して動作し、Claude Codeや他のエージェントハーネスと統合するためのMCPサーバーを提供します。

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

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

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

ドキュメント

エージェント支払い実行 (x402) は何をしますか?

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

使用するタイミング

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

決定木

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

ニーズ推奨パス
エージェントがBaseまたはagentwallet-sdkがサポートする他のチェーン上の402ゲートAPIに支払う厳格な支出ポリシーと共にagentwallet-sdkをMCP支払いサーバーとして使用
エージェントが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 を使用して、何がなぜ使われたかを記録します。
  • フェイルクローズド: 支払いツールに到達できない場合は、有料アクションをブロックします — 計測なしのアクセスにフォールバックしないでください。
  • セキュリティレビューと組み合わせる: 支払いツールは高権限です。シェルアクセスと同じ注意を払ってください。
  • まずテストネットでテストする: 開発には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

関連スキル