AI agent과 유료 API 사이에서 결제 게이트웨이 역할을 수행하여, AI agent의 지출 정책 및 예산을 관리합니다.
다른 이름 Hellotravisss/agentpay, agentpay-gateway
- 스타
- 0
- Tools
- —
- 다운로드, 30일
- —
- 최신 버전
- 0.9.0
- 마지막 커밋
- 2026년 10월 29일
- 라이선스
- MIT
agentpay MCP란?
AI agent과 유료 API 사이에서 결제 게이트웨이 역할을 수행하여, AI agent의 지출 정책 및 예산을 관리합니다.
프로젝트 README에서 생성된 요약
agentpay MCP server 정보
agentpay는 민감한 지갑 자격 증명을 노출하지 않고 AI agent의 금융 거래를 관리하도록 설계된 중립적 결제 게이트웨이입니다. 자율형 agent와 x402 스타일 API 또는 Alipay와 같은 유료 서비스 사이에서 엄격한 지출 정책을 집행합니다. 결제 요청을 가로채어 비용 및 정책 선호도에 따라 선호하는 결제 수단으로 트랜잭션을 라우팅하는 동시에, 모든 지출이 정의된 예산 범위 내에서 이루어지도록 보장합니다.
개발자는 Node.js를 사용하여 이를 셀프 호스팅 서비스로 배포할 수 있습니다. Claude 또는 Cursor와 같은 AI 클라이언트가 paid_fetch 및 check_budget과 같은 도구를 사용하여 게이트웨이와 상호작용할 수 있도록 MCP server를 제공합니다. 이 시스템은 모든 트랜잭션을 트랜잭션당 한도, 일일 또는 월간 예산, 수취인 차단 목록과 대조하여 확인하는 deny-by-default 정책 모델을 사용합니다. 모든 금융 결정은 추가 전용(append-only) 감사 로그에 기록되며, 대규모 결제는 내장된 관리자 대시보드를 통해 사람의 승인을 기다리도록 보류할 수 있습니다.
활용 사례
- 1엄격한 Agent 지출 한도 적용개발자는 기본 통화로 일일 최대 예산을 설정하여 Agent가 여러 결제 수단에서 과도하게 지출하는 것을 방지할 수 있습니다.
- 2안전한 Agent 결제 관리실제 디지털 지갑이나 키에 대한 접근 권한을 Agent에게 부여하지 않고도 Agent가 유료 API에 접근할 수 있도록 허용할 수 있습니다.
- 3Human-in-the-loop 감독 구현고액 트랜잭션을 일시 중지하고 사람이 수동으로 승인하거나 거부할 수 있도록 시스템을 구성할 수 있습니다.
프로젝트의 README를 바탕으로 작성되었습니다. 모든 활용 사례는 해당 내용의 인용문과 대조하여 확인합니다.
agentpay MCP 설치 방법
형식 확인: 2026년 11월 10일Cursor에 추가Goose에 추가Claude Code에 agentpay MCP 설치
$ claude mcp add --env 'AGENTPAY_API_KEY=<YOUR_AGENTPAY_API_KEY>' agentpay -- npx -y agentpay-gatewayCursor에 agentpay MCP 설치
~/.cursor/mcp.json
{
"mcpServers": {
"agentpay": {
"command": "npx",
"args": [
"-y",
"agentpay-gateway"
],
"env": {
"AGENTPAY_API_KEY": "<YOUR_AGENTPAY_API_KEY>"
}
}
}
}VS Code에 agentpay MCP 설치
.vscode/mcp.json
{
"servers": {
"agentpay": {
"type": "stdio",
"command": "npx",
"args": [
"-y",
"agentpay-gateway"
],
"env": {
"AGENTPAY_API_KEY": "<YOUR_AGENTPAY_API_KEY>"
}
}
}
}VS Code CLI에 agentpay MCP 설치
$ code --add-mcp '{"name":"agentpay","type":"stdio","command":"npx","args":["-y","agentpay-gateway"],"env":{"AGENTPAY_API_KEY":"<YOUR_AGENTPAY_API_KEY>"}}'Claude Desktop에 agentpay MCP 설치
claude_desktop_config.json
{
"mcpServers": {
"agentpay": {
"command": "npx",
"args": [
"-y",
"agentpay-gateway"
],
"env": {
"AGENTPAY_API_KEY": "<YOUR_AGENTPAY_API_KEY>"
}
}
}
}Codex에 agentpay MCP 설치
$ codex mcp add agentpay --env 'AGENTPAY_API_KEY=<YOUR_AGENTPAY_API_KEY>' -- npx -y agentpay-gatewayCodex config.toml에 agentpay MCP 설치
~/.codex/config.toml
[mcp_servers.agentpay] command = "npx" args = ["-y", "agentpay-gateway"] [mcp_servers.agentpay.env] AGENTPAY_API_KEY = "<YOUR_AGENTPAY_API_KEY>"
Gemini CLI에 agentpay MCP 설치
$ gemini mcp add -s user -e 'AGENTPAY_API_KEY=<YOUR_AGENTPAY_API_KEY>' agentpay npx -- -y agentpay-gatewayGemini settings.json에 agentpay MCP 설치
~/.gemini/settings.json
{
"mcpServers": {
"agentpay": {
"command": "npx",
"args": [
"-y",
"agentpay-gateway"
],
"env": {
"AGENTPAY_API_KEY": "<YOUR_AGENTPAY_API_KEY>"
}
}
}
}구성
AGENTPAY_API_KEY비밀Agent key from POST /admin/keys
AGENTPAY_URLagentpay gateway URL
LEDGER_FILEX402_PRIVATE_KEY
| 이름 | 설명 | 유형 |
|---|---|---|
| AGENTPAY_API_KEY | Agent key from POST /admin/keys | 비밀 |
| AGENTPAY_URL | agentpay gateway URL | |
| LEDGER_FILE | — | |
| X402_PRIVATE_KEY | — |
자동 검사
2026년 11월 14일에 실행됨전체 보고서 →자동 검사를 통과했습니다. 이는 보안 감사가 아닙니다. 코드를 직접 읽고 서버에 필요한 최소한의 권한만 부여하십시오. 검사 방식
- 소스 저장소 연결 및 접근 가능hellotravisss/agentpay is public and reachablegithub.com/hellotravisss/agentpay ↗통과
- 패키지가 이 저장소를 소스로 명시agentpay-gateway names hellotravisss/agentpay as sourcenpmjs.com/package/agentpay-gateway ↗통과
- 빌드 출처(Sigstore 증명)No build attestation published for this release검사되지 않음
- 오픈 소스 라이선스 (OSI)MITspdx.org/licenses/MIT.html ↗통과
- 최근 1년 내 커밋 또는 릴리스Last commit or release 2026-10-29github.com/hellotravisss/agentpay ↗통과
- OpenSSF Scorecard검사되지 않음
- 패키지 이름이 인기 패키지와 유사하지 않음No popular package one edit away from agentpay-gateway통과
- 패키지 및 해당 종속성에 중요한 보안 권고 없음14 resolved dependencies checked; no critical advisoryosv.dev ↗통과
- 모델에 대한 숨겨진 지침 없음0 tool descriptions and the README read; no override phrases, credential paths or hidden characters통과
- 파괴적인 도구에 라벨 표시됨검사되지 않음
- 원격 엔드포인트가 MCP 핸드셰이크에 응답검사되지 않음
README
GitHub에서 보기agentpay
A cross-rail spend-policy gateway for AI agent payments. It sits between your agents and anything that charges them money — x402-style paid APIs, Alipay/WeChat-style agent payments, whatever comes next — and answers the question every company deploying paying agents will have to answer:
"How do I let my agent spend money — across several payment rails — without giving it my wallets?"
Agents never hold payment credentials. They call paid resources through the gateway, which:
- intercepts the
402 Payment Requiredhandshake and collects every payment option the merchant accepts, - routes to one rail (agent's rail preference first, ties broken by cheapest cost in the policy's base currency),
- checks the payment against that agent's spend policy — budgets and caps are denominated in one base currency and enforced across all rails and currencies via exact FX conversion,
- executes approved payments on the chosen rail,
- retries the request with the payment proof and returns the unlocked response,
- writes every decision — denials included — to an append-only audit log.
┌────────────────────────────────────────────────┐ ─▶ paid API (x402, USDC)
agent ──HTTP──▶ │ gateway │
(no keys, no wallet) │ policy ─ fx ─ router ─ ledger ─ audit ─ rails │ ─▶ paid API (Alipay, CNY)
└────────────────────────────────────────────────┘ ─▶ ...
For how it's built and why — design principles, the full 402 request lifecycle, and where the simple parts grow — see docs/ARCHITECTURE.md.
Where it fits — the neutral layer
The platforms are racing to let agents spend, and each is building a closed loop: Alipay's ACT delegated-payment protocol, WeChat Pay's isolated "AI card" with user-set authorization scope and spend limits, x402 for crypto-native APIs. Every platform wants agents spending inside its wallet, on its rail — and the design they keep converging on (a wallet isolated from your real account, scoped authorization, per-spend limits, big payments held for confirmation, a full audit trail) is exactly the control surface this project is built around. The thesis is no longer speculative; it's where the giants are pointing their capex.
But a company running real agents doesn't get to live in one loop. Its agents pay an x402 API in USDC, a vendor in CNY, the next thing in whatever ships next quarter — and no single platform gives it one neutral view across all of them: one base-currency budget, one audit trail, one policy, one place where the agent never holds a credential. The more these closed loops fragment, the more that spanning layer is missing.
That layer is agentpay. It sits above the rails — x402, Alipay, WeChat, mock — behind a two-method interface (rails/rail.ts), so budget, policy, FX, routing, and audit are written once and every rail plugs in underneath. It's rail-neutral and self-hosted by design: the value is precisely the part no platform racing to own its own loop will build for you.
Quick start
npx agentpay-gateway # gateway on http://127.0.0.1:4020, dashboard at /admin (mock rails)
From source:
npm install
npm test # 110 tests: money, FX, policy, x402 v1+v2, MCP, persistence, approvals, security, e2e
npm run demo # walkthrough: 2 rails, 2 currencies, 1 unified USD budget, human-in-the-loop
npm run dev # start the gateway on :4020 (dashboard at http://localhost:4020/admin)
The demo runs a merchant that accepts USDC (x402-style) or CNY (Alipay-style); two agents with different rail preferences get routed differently, and one USD budget governs both — a 0.36 CNY purchase consumes ~0.0504 USD of it. Per-transaction caps, payee blocklists, budget exhaustion, the per-rail spend breakdown, and the audit trail are all shown.
Install as an agent skill
There's a ready-to-install agent skill in skill/ — a step-by-step runbook an AI assistant (Claude Code, OpenClaw, …) follows to set agentpay up for you: install + self-test, write a deny-by-default policy, launch the gateway, reroute the agent's paid calls through /proxy, then operate it (spend, audit, approvals, live policy edits) and harden for production. It bundles policy templates and a troubleshooting + API reference. Point your assistant at skill/SKILL.md, or install it from a skill marketplace.
Use from Claude / Cursor (MCP)
Try it in two minutes: npx -p agentpay-gateway agentpay-demo starts a gateway (mock money) plus a toy paid API. Ready-made agents for the Claude Agent SDK, Vercel AI SDK, OpenAI Agents SDK and LangChain are in examples/.
Give an MCP agent a budget it cannot exceed. The agentpay-mcp server holds only
the agent's gateway API key — the wallet and the limits stay in the gateway. Unlike
honor-system budget tools, the agent is never asked to check its budget; a payment
over the limit simply isn't signed.
{
"mcpServers": {
"agentpay": {
"command": "npx",
"args": ["-y", "-p", "agentpay-gateway", "agentpay-mcp"],
"env": { "AGENTPAY_URL": "http://127.0.0.1:4020", "AGENTPAY_API_KEY": "<key from POST /admin/keys>" }
}
}
}
Tools: paid_fetch(url, method?, body?) — fetch any URL; the gateway pays x402/402
within policy. Denials and approval holds come back as tool errors the model can
explain. check_budget() — spent today/this month vs limits (via the agent-scoped
GET /v1/budget, which shows an agent only its own numbers).
Policies
Policies are deny-by-default: an agent with no policy entry cannot spend at all. See policies/example.json:
{
"fxRates": { "USDC:USD": "1", "CNY:USD": "0.14" }, // directional pairs, exact decimals
"defaults": { "currency": "USD", "perTransactionMax": "1.00", "dailyBudget": "10.00" },
"agents": [
{
"agentId": "research-bot",
"enabled": true,
"currency": "USD", // base currency for ALL limits below
"railPreference": ["alipay-act", "x402"], // routing order when merchants accept several rails
"perTransactionMax": "0.25", // cap on any single payment, in base currency
"dailyBudget": "0.15", // UTC calendar day, across all rails/currencies
"monthlyBudget": "3.00", // UTC calendar month
"maxTransactionsPerDay": 200,
"requireApprovalOver": "0.50", // hold payments >= this for human review (base ccy)
"payeeBlocklist": ["merchant-shady"]
// or "payeeAllowlist": [...] to whitelist instead
}
]
}
All money is exact decimal (bigint micro-units, 6 dp — USDC precision); FX conversions round up so budgets are enforced conservatively. No floats anywhere near amounts. Payments in a currency with no configured rate to the base currency are denied (no_fx_rate).
API
| Endpoint | Purpose |
|---|---|
ANY /proxy?url=<target> |
Proxy a request; routes + pays on 402 if policy allows. Identify the agent via Authorization: Bearer <api key> (when keys are configured) or X-Agent-Id. |
GET /admin |
Web dashboard (single self-contained page) — live spend, pending approvals with approve/reject buttons, the audit trail, and inline policy editing. |
GET /admin/policy |
The full live policy config. |
GET /admin/agents |
Configured agents with their resolved limits. |
PUT /admin/agents/:id |
Create or replace an agent's policy (validated). Takes effect on the next request; written back to the policy file. |
DELETE /admin/agents/:id |
Remove an agent (reverts to deny-by-default). |
GET /admin/keys · POST /admin/keys · DELETE /admin/keys/:id |
Multi-tenant API keys: list, mint (secret returned once), revoke. |
GET /admin/spend/:agentId |
Unified spend vs. limits in the base currency, plus a per-rail breakdown in native currencies. |
GET /admin/audit?agent=&limit= |
Audit trail of every allow/deny/failure/hold. |
GET /admin/approvals?status= |
List payments held for human review (filter pending/approved/rejected). |
POST /admin/approvals/:id |
Decide a held payment: body { "decision": "approve" | "reject" }. |
GET /healthz |
Liveness. |
Successful paid responses carry X-Gateway-Payment-Id, X-Gateway-Rail, and X-Gateway-Payment-Amount headers. Denials return 403 with the violated rule id (per_transaction_max, daily_budget, payee_blocklisted, no_fx_rate, approval_rejected, ...) so the agent can explain itself or back off.
Human-in-the-loop approvals
Set requireApprovalOver on an agent and any policy-approved payment at or above that base-currency amount is held instead of executed: the proxy returns 202 with an approvalId rather than paying. An operator approves or rejects via POST /admin/approvals/:id; the agent's retry then executes (approved) or is denied with approval_rejected. Each approval is single-use, so it unlocks exactly one payment. Budgets are still re-checked at execution time on the retry.
Persistence
By default the ledger, audit log, and approvals live in memory. Point any of them at a file to make state survive restarts — .sqlite selects a transactional SQLite backend (Node's built-in node:sqlite, no extra dependency), anything else is append-only JSONL:
LEDGER_FILE=./ledger.sqlite AUDIT_FILE=./audit.jsonl APPROVALS_FILE=./approvals.sqlite APIKEYS_FILE=./keys.sqlite npm run dev
Live FX rates
FixedRateProvider is fine for static pairs; CachingRateProvider wraps any async rate source (a RateFetcher, default httpRateFetcher hits exchangerate.host) with a TTL and a hard staleness limit. Past that limit a cached rate is refused (no_fx_rate) rather than used — a payment is never priced on a stale rate. Stablecoin pegs can be pinned so they never expire or fetch.
Editing policies (live)
Policies change at runtime — no restart. The PolicyManager owns the live config; every decision reads through it, so an edit takes effect on the next request. Two ways in, kept in sync:
- Admin API / dashboard —
PUT/DELETE /admin/agents/:id(the dashboard's edit pencils and "add agent" button drive these). Each edit is validated, audited aspolicy_changed, and written back to the policy file. - The file itself —
npm run devwatches the policy file and hot-reloads out-of-band edits. The write-back and the watcher don't fight:reload()no-ops when the file is byte-identical to the in-memory state, so a self-write doesn't trigger a reload loop. (fxRatesare built once at startup and not hot-reloaded.)
Multi-tenant API keys
Agents authenticate with Authorization: Bearer <key>. Keys are minted per agent (an agent can hold several, for rotation) via POST /admin/keys or the dashboard — the raw secret is returned exactly once; only its SHA-256 hash is stored, so a leaked store yields no usable credentials. Keys support an optional expiry and can be revoked instantly (DELETE /admin/keys/:id); both are audited (apikey_created / apikey_revoked).
By default a valid Bearer key authenticates and X-Agent-Id still works (convenient for local dev). Set REQUIRE_API_KEY=1 (or requireApiKey: true) to reject X-Agent-Id so only a valid key authenticates. Persist keys across restarts with APIKEYS_FILE=./keys.sqlite.
Payment rails
Rails implement one interface (src/rails/rail.ts): supports(network) + pay(ctx) -> receipt. Adding a rail never touches policy, FX, or routing code. Included:
MockRail— instant in-process settlement; instantiate several to simulate a multi-rail deployment.X402Rail— adapter for Coinbase's x402 protocol, with a real client-side payment implementation:createEip3009Signerproduces signed EIP-3009transferWithAuthorizationpayloads for USDC on Base / Base Sepolia. Speaks both x402 v1 and v2: v1 (X-PAYMENT, body requirements) and v2 (PAYMENT-REQUIRED/PAYMENT-SIGNATURE/PAYMENT-RESPONSEheaders, CAIP-2 networks likeeip155:84532, atomicamount, the chosen requirement echoed verbatim asaccepted). Permit2-only requirements are refused rather than mis-signed. Signing is fully offline; the merchant's facilitator settles on-chain. Verified two ways: signatures are checked cryptographically in the test suite, and the rail has settled a real payment on Base Sepolia end to end (see below).AlipayActRail— adapter shaped for Alipay's agent-payment stack (AI付 under the ACT delegation model); bring your merchant integration viaexecutePayment.
Credentials live inside the rail callbacks you supply — the gateway core never touches keys. Planned: Google AP2.
Buying a real x402 resource on Base Sepolia
This has been run for real: the gateway settled 0.01 USDC on Base Sepolia through Coinbase's hosted testnet facilitator from a wallet holding zero ETH (the facilitator pays gas — x402 is gasless for the payer). On-chain proof: 0x3108b5…54ff9d (x402 v1). x402 v2 was then settled the same way against Coinbase's official @x402/express 2.27 merchant: 0x8c0256…f668c5.
To reproduce — public testnet endpoints come and go, so the reliable path is a local x402 merchant:
# 1. fund a throwaway wallet with testnet USDC: https://faucet.circle.com (Base Sepolia)
# 2. run a local x402 merchant settling on base-sepolia (official middleware + hosted facilitator)
mkdir x402-merchant && cd x402-merchant && npm init -y && npm i x402-express express
cat > server.mjs <<'JS'
import express from "express";
import { paymentMiddleware } from "x402-express";
const app = express();
app.use(paymentMiddleware("0xYourMerchantAddress", { // any address — it just receives the USDC
"/premium": { price: "$0.01", network: "base-sepolia", config: { description: "x402 test" } },
}));
app.get("/premium", (_q, r) => r.json({ message: "unlocked by a real on-chain payment" }));
app.listen(4021, () => console.log("merchant on http://localhost:4021/premium"));
JS
node server.mjs
# 3. buy it through the gateway (signs EIP-3009 offline, facilitator settles on-chain)
X402_PRIVATE_KEY=0x... TARGET_URL=http://localhost:4021/premium npx tsx demo/x402-live.ts
Or point TARGET_URL at any live x402 resource that settles on base-sepolia.
Security
It moves money, so the control plane is hardened, not just the math:
- Admin API auth — set
ADMIN_TOKENand every/admin/*data/mutation endpoint requires it (Authorization: BearerorX-Admin-Token, constant-time compared). Unset, the admin API is open, so the CLI binds127.0.0.1by default (override withHOST) and warns at startup. The dashboard carries the token (seed it once via/admin#token=…). - SSRF guard —
/proxyrefuses targets that resolve to private/loopback/link-local ranges (incl. the169.254.169.254cloud-metadata IP) by default. The guard runs at connect time via a pinned DNS lookup and is re-applied to every redirect hop, so neither DNS rebinding nor a redirect-to-internal can slip past. Opt in withallowPrivateTargetsonly for local testing. - x402 asset allowlist — the signer refuses to sign an EIP-3009 authorization for any token not on a per-network allowlist (default: canonical USDC), so a malicious
402can't trick the wallet into authorizing a transfer of a different, more valuable token. Authorization validity is clamped (maxAuthorizationSeconds). - No double-spend under concurrency — the decide→execute→record window is serialized per agent, so concurrent payments can't both pass the budget check before either is recorded.
- DoS limits — 1 MiB request-body cap (
413), 30 s upstream fetch timeout, and the upstream response is streamed (not buffered whole into memory). - Money integrity — exact
bigintarithmetic (no floats), API keys stored only as SHA-256 hashes (raw secret shown once), and the upstreamAuthorizationheader is never forwarded.
Deploy checklist: set ADMIN_TOKEN, enable REQUIRE_API_KEY=1, keep allowPrivateTargets off, and put the gateway behind TLS. Full threat model, hardening list, and checklist in docs/SECURITY.md.
Status & roadmap
This is an MVP. The policy engine, FX layer, cross-rail router, ledger, audit log, approvals, persistence, and 402 proxy flow are tested and working end to end against mock rails; the x402 rail has settled a real payment on Base Sepolia. Done since the first cut:
- Live FX rate provider with caching and staleness limits (
CachingRateProvider) - Persistent storage beyond JSONL — transactional SQLite via
node:sqlite - Human-in-the-loop approvals ("hold payments over $X for review")
- Web dashboard for spend + audit + approvals + policy editing (
GET /admin) - Policy hot-reload and an admin API for editing policies
- Multi-tenant API key management (hashed keys, mint/revoke, per-key expiry)
- End-to-end x402 v2 settlement against the official v2 merchant — 0.01 USDC on Base Sepolia
- End-to-end x402 settlement against a live facilitator — 0.01 USDC settled on Base Sepolia (reproduce: above)
Not yet built:
- Real Alipay AI付/ACT settlement (requires merchant onboarding)
agentpay MCP 질문
agentpay MCP를 Claude Code에 추가하려면 어떻게 하나요?
터미널에서 claude mcp add --env 'AGENTPAY_API_KEY=<YOUR_AGENTPAY_API_KEY>' agentpay -- npx -y agentpay-gateway를 실행합니다. 모든 프로젝트에서 사용할 수 있게 하려면 --scope user를 추가합니다.
agentpay MCP를 Cursor에 추가하려면 어떻게 하나요?
~/.cursor/mcp.json를 열고 mcpServers 아래에 서버를 추가합니다. 위 설치 섹션에 표시된 Cursor 구성을 사용합니다.
agentpay가 지갑을 어떻게 보호하나요?
Agent는 결제 자격 증명이나 지갑을 보유하지 않습니다. 자격 증명을 보유하고 정책을 집행하는 게이트웨이를 통해 유료 리소스를 호출합니다.
Agent의 지출 한도를 설정할 수 있나요?
네, 모든 결제 수단에 적용되는 기본 통화 기준의 트랜잭션당 최대 금액, 일일 예산, 월간 예산을 정의할 수 있습니다.
결제 금액이 일정 수준을 초과하면 어떻게 되나요?
결제가 자동으로 실행되는 대신 사람이 직접 검토할 수 있도록 임계값을 설정할 수 있습니다.
다양한 통화를 지원하나요?
네, 여러 결제 수단과 통화를 지원하며, FX 환산을 통해 단일 기본 통화 예산 내에서 관리합니다.