Communitygithub.com

agent-payment-x402

AI 에이전트에 x402 결제 실행 기능을 추가합니다. 작업별 예산, 지출 제어, 비수탁 지갑을 제공합니다. 에이전트가 스스로 비용을 지불해야 하고 작업별 예산, 지출 제어 및 비수탁 지갑이 필요할 때 사용합니다.

agent-payment-x402란 무엇인가요?

이 스킬은 AI 에이전트가 x402 HTTP 결제 프로토콜과 MCP 도구를 사용하여 정책 기반 지불을 실행할 수 있도록 지원합니다. 에이전트가 외부 API, 서비스 또는 다른 에이전트에게 비용을 지불해야 할 때, 작업별 예산, 세션별 예산, 허용 목록 수신자, 속도 제한 등 다양한 지출 제어 기능을 통해 안전하게 결제를 처리합니다. Base 네트워크에서는 agentwallet-sdk를, X Layer에서는 OKX Payments / OKX Agent Payments Protocol을 지원하며, ERC-4337 스마트 계정을 기반으로 하는 비수탁 지갑을 사용하여 에이전트가 자체 키를 보유하고 정해진 범위 내에서만 지출할 수 있도록 합니다. 오케스트레이터는 위임 전에 지출 정책을 설정하며, 에이전트는 이 범위를 벗어날 수 없습니다. 보안을 위해 패키지 버전을 고정하고, 결제 도구가 응답하지 않을 경우 작업을 차단하는 fail-closed 방식을 권장합니다.

지원 대상✓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-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를 적용합니다:

  • 작업별 예산 — 단일 에이전트 작업의 최대 지출액
  • 세션별 예산 — 전체 세션의 누적 한도
  • 허용 목록 수신자 — 에이전트가 지불할 수 있는 주소/서비스 제한
  • 속도 제한 — 분/시간당 최대 트랜잭션 수

비수탁 지갑

에이전트는 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 구성을 추가하기 전에 패키지를 설치하세요 — -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. 에이전트에 위임하기 전에 지출 정책을 설정합니다.
  //    항상 성공을 확인하세요 — 무음 실패는 제어 기능이 활성화되지 않았음을 의미합니다.
  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);
}

// 사전 도구 훅: 네 가지 별개의 오류 경로가 있는 fail-closed 예산 적용.
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를 사용하여 지출된 내용과 이유를 기록하세요.
  • Fail-closed: 결제 도구에 연결할 수 없으면 유료 작업을 차단하세요 — 측정되지 않은 액세스로 폴백하지 마세요.
  • 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.

관련 스킬