Paiement x402 pour agents IA

VérifiéPrudence

Ajoutez des paiements x402 aux agents IA avec budgets par tâche, contrôles de dépenses et portefeuilles non-custodiaux. Prend en charge Base et X Layer.

Spar Skills Guide Bot
Data & IAAvancé
26/08/2026
Claude CodeCursorWindsurf
#x402#agent-payments#mcp#spending-controls#non-custodial-wallets

Recommandé pour

Synthèse automatique

Ce skill explique comment ajouter l'exécution de paiements x402 à des agents IA via des serveurs MCP, avec des budgets par tâche, des contrôles de dépenses et des portefeuilles non custodiaux sur Base ou X Layer.

Points forts

  • Arbre de décision clair qui oriente vers le bon chemin d'intégration selon que l'agent paie une API 402 ou facture des agents
  • Politique de dépenses explicite : budget par tâche, budget par session, bénéficiaires autorisés et limitation de débit
  • Frontière d'autorité bien posée : toute installation, écriture, appel réseau ou paiement exige une autorisation explicite de l'utilisateur
  • Distingue les références externes (agentwallet-sdk, okx/onchainos-skills) des skills locales et signale les alias obsolètes

Limites

  • Ne fournit pas de code d'implémentation complet : il renvoie vers des SDK et dépôts externes dont la couverture réseau et les packages évoluent vite
  • Aucun guide vendeur Python confirmé, et le support multi-chaînes doit être vérifié dans la documentation avant la production
  • L'application réelle des limites de dépense dépend de l'orchestrateur hôte et des outils MCP configurés, pas du skill seul
Quand l'utiliser

À utiliser lorsqu'un agent doit payer un appel d'API protégé par un 402, régler un service ou un autre agent, ou opérer un portefeuille non custodial sous limites de dépense.

Quand l'éviter

À éviter si vous cherchez du code de paiement prêt à l'emploi ou si votre agent n'a aucun besoin d'effets financiers externes, car le skill reste un guide d'orientation et de politique.

Analyse de sécurité

Prudence
Score qualité85/100

The skill describes payment tooling with private key management and network installs, which are powerful but legitimate for its stated purpose. It includes explicit safety guidance, policy controls, and confirmation requirements, but the financial and supply-chain risks warrant caution.

Points d'attention
  • •Instructs use of npx to install agentwallet-sdk@6.0.0 which manages private keys; supply-chain risk exists if the package or version is compromised, though the version is pinned.
  • •Enables payment execution and non-custodial wallet management, which can lead to financial loss if policies are misconfigured or the agent is tricked.
  • •References external repositories and recommends fetching current SDK docs, potentially introducing unverified code into the workflow.
  • •Provides MCP configuration examples that users might copy directly without implementing the required orchestrator-side policy enforcement.
Comment cette analyse est faite

Exemples

Paid API call on Base
Configure an MCP payment server using agentwallet-sdk so my agent can pay a 402-gated API on Base Sepolia, with a 0.05 USDC per-task budget and a 1 USDC per-session cap.
X Layer settlement
My agent needs to settle a payment with another agent on X Layer — walk me through the OKX Agent Payments Protocol path, including the current endpoint and USDT0 settlement details.
Charge agents for my API
I have an Express API in TypeScript and want to charge agents per request via x402 — show me how the OKX Payments seller SDK flow works and what I need before writing code.

name: agent-payment-x402 description: Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. origin: community

Agent Payment Execution (x402)

Runtime and authority boundary

Treat target-specific paths, slash commands, hooks, routers, model tiers, SHIP, or auto-fix behavior in this Skill as guidance for an external target system or runtime only if the user explicitly requests that target. For the current OMP session, this Skill does not route, hook, command, gate, control, grant permission, or decide completion; inspection, planning, and read-only review authorize no mutation. Any installation, configuration, file write, command, network call, upload, publication, payment, mutation, or other external effect requires explicit user authorization for the exact target and effect plus current native permission. Preserve fail-closed safety rules inside authorized target work; target safety is not an OMP gate or completion condition.

agentwallet-sdk, okx/onchainos-skills, and their nested guide names are external ecosystem package or repository references, not local OMP Skill URIs. Do not load them as Skills unless the current host exposes an exact matching Skill URI; otherwise consult them only as authorized external sources.

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.

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.

Decision Tree

Choose the integration path based on whether your agent is buying access to a paid API or charging others for one:

| Need | Recommended path | |------|------------------| | Agent pays a 402-gated API on Base or another agentwallet-supported chain | Use agentwallet-sdk as an MCP payment server with strict spending policy | | Agent pays a 402-gated API on X Layer | Use OKX Agent Payments Protocol from okx/onchainos-skills; okx-x402-payment is a deprecated legacy alias | | TypeScript API charges agents | Use OKX Payments TypeScript seller SDK docs for Express, Hono, Fastify, or Next.js | | Go API charges agents | Use OKX Payments Go seller SDK docs for Gin, Echo, or net/http | | Rust API charges agents | Use OKX Payments Rust seller SDK docs for Axum | | Java API charges agents | Use OKX Payments Java seller SDK docs for Spring Boot 2/3, Java EE, or Jakarta | | Python API charges agents | Check the current OKX Payments repository before implementation; a Python seller guide may not be available |

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.

How It Works

x402 Protocol

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.

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

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.

MCP Integration

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.

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

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

Available Tools (agent-callable)

| Tool | Purpose | |------|---------| | 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.

Option 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:

| Runtime | Current 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.

Examples

Budget enforcement in an MCP client

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

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;
});

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.

Production Reference

Du fichier au premier essai

Le téléchargement contient exactement le contenu affiché sur cette fiche. Cette copie peut différer de la dernière version du dépôt source.

Consulter la source et ses fichiers annexes

Ce téléchargement contient uniquement SKILL.md. Les scripts, références, modèles et dépendances éventuels ne sont pas inclus. Récupérez les fichiers nécessaires depuis la source en conservant leur arborescence avant de poursuivre.

1. Télécharger le fichier

Télécharger SKILL.md

Depuis la racine d’un projet de test, enregistrez le fichier sous .skill-downloads/agent-payment-execution-x402-mt9mgmsw/SKILL.md, ou utilisez la commande suivante. Ce dossier sert à examiner la skill avant son installation.

Commande pour macOS/Linux ou WSL : un shell POSIX et curl sont nécessaires. Sous Windows sans WSL, utilisez le bouton de téléchargement et créez le dossier manuellement.

mkdir -p '.skill-downloads/agent-payment-execution-x402-mt9mgmsw' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/agent-payment-execution-x402-mt9mgmsw/download' --output '.skill-downloads/agent-payment-execution-x402-mt9mgmsw/SKILL.md.part' && mv '.skill-downloads/agent-payment-execution-x402-mt9mgmsw/SKILL.md.part' '.skill-downloads/agent-payment-execution-x402-mt9mgmsw/SKILL.md'

2. Vérifier les prérequis

Lisez SKILL.md avant de l’utiliser. Si le fichier cite des scripts ou services externes, examinez-les et préparez les accès nécessaires dans votre environnement de test.

Aucune section de prérequis reconnue dans ce fichier. Cela ne signifie pas qu’il est autonome : les bibliothèques, outils et accès peuvent être cités ailleurs dans le contenu ou dans le dépôt source.

Les plateformes de la fiche sont des indications du catalogue. Les chemins ci-dessous suivent la documentation des outils ; ils ne prouvent pas que cette skill y a été exécutée. Aucune version minimale de ces outils n’est attestée pour cette fiche.

3. Charger la skill

Après vérification, copiez le dossier complet dans le projet avec l’une des commandes ci-dessous, puis ouvrez une nouvelle session de l’outil. La commande s’arrête si un dossier du même nom existe déjà : comparez les fichiers avant de le remplacer.

Claude Code
test -f '.skill-downloads/agent-payment-execution-x402-mt9mgmsw/SKILL.md' && test -s '.skill-downloads/agent-payment-execution-x402-mt9mgmsw/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/agent-payment-x402' && cp -R '.skill-downloads/agent-payment-execution-x402-mt9mgmsw' '.claude/skills/agent-payment-x402'

Cursor
test -f '.skill-downloads/agent-payment-execution-x402-mt9mgmsw/SKILL.md' && test -s '.skill-downloads/agent-payment-execution-x402-mt9mgmsw/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/agent-payment-x402' && cp -R '.skill-downloads/agent-payment-execution-x402-mt9mgmsw' '.cursor/skills/agent-payment-x402'

OpenSkills

OpenSkills doit déjà être installé. La procédure locale install/read est contrôlée avec OpenSkills 1.5.0, qui exige Node.js ≥ 20.6.0. Aucun slug du catalogue n’est résolu automatiquement.

Installation officielle d’OpenSkills
openskills install './.skill-downloads/agent-payment-execution-x402-mt9mgmsw'

openskills read 'agent-payment-execution-x402-mt9mgmsw'

La lecture doit afficher le contenu du fichier installé et son dossier de base. Elle ne lance ni la skill ni ses dépendances.

Pour un agent qui lit AGENTS.md, synchronisez ensuite l’index. Cette commande modifie AGENTS.md : relisez le diff avant de l’utiliser.

openskills sync

Mode manuel ou autre outil : joignez SKILL.md à une conversation, ou ouvrez-le dans un agent capable de lire les fichiers. Ajoutez les ressources annexes nécessaires. Il n’existe pas de dossier universel reconnu par tous les outils.

4. Faire un premier essai

Utilisez une entrée courte et fictive : un endpoint d’API, un petit document ou un brief d’interface. Dans une nouvelle conversation, joignez le fichier ou donnez son chemin à l’agent, puis adaptez cette demande :

Lis .skill-downloads/agent-payment-execution-x402-mt9mgmsw/SKILL.md et applique ses instructions à cet exemple : [décrire une entrée de test]. Indique les fichiers, dépendances ou accès qui manquent. Produis le résultat demandé par la skill sans inventer de données ni exécuter de script non examiné.

Résultat attendu : une sortie correspondant aux instructions de la skill, ou une liste précise des prérequis manquants. Une simple confirmation de lecture ne valide pas le premier usage. Si une ressource externe est indisponible, ce parcours reste à tester.

Skills similaires