Payments
FreeNot checkedAgent payment infrastructure MCP server — charge, refund, escrow, subscriptions, webhooks. 69 tools for autonomous agent payments.
About
Agent payment infrastructure MCP server — charge, refund, escrow, subscriptions, webhooks. 69 tools for autonomous agent payments.
README
Payment execution layer for AI agents. MCP server + CLI. Charge, refund, escrow, split payments, x402 billing middleware, and verify transactions for autonomous agents.
Python 3.10+ License: MIT Tests 454 tests MCP x402 Version
Why?
The MCP ecosystem has no payment layer. Agents can call tools, read resources, and generate prompts — but they can't pay for premium tools, get charged for their usage, or verify payments programmatically. As agents start transacting with each other, they also need trust mechanisms — escrow for task completion, split payments for multi-party settlement, and billing middleware to monetize MCP endpoints via the x402 HTTP 402 protocol.
mcp-payments fills this gap:
- 🔧 MCP-native — pricing is part of tool discovery
- 💸 Multi-provider — internal ledger, Stripe (fiat), x402 (crypto), on-chain
- 🔄 Payment Retry & Auto-Recovery (NEW v0.8.0) — self-healing payments: failed charges auto-retry with configurable backoff, auto top-up, and failure classification
- 🛒 Service Marketplace Registry (v0.5.0) — agents discover, purchase, and provision paid services in one flow
- 📊 Usage metering (v0.4.0) — record, aggregate, and settle metered billing (per-call, per-token, per-second)
- 🔗 x402 billing middleware (v0.3.0) — enforce HTTP 402 payments on any ASGI app
- 📊 Full lifecycle — pricing → intent → charge → verify → refund → receipt
- 🔒 Escrow — hold funds until a task between agents completes
- ✂️ Split payments — distribute one charge to multiple recipients
- 🏪 Suite-compatible — works with agent-invoice, agent-ledger, agent-budget
Quick Start
pip install mcp-payments
Set tool pricing
mcp-payments price my-premium-tool 50 --model per_use --free-tier 10
# 10 free calls, then $0.50 per use
Register a customer and charge
mcp-payments register --name "My Agent" --wallet 0xABC...
mcp-payments top-up cus_xxx 10000 # $100.00 in cents
mcp-payments charge cus_xxx 50 --tool my-premium-tool
Generate x402 payment requirements
mcp-payments x402 0.01 --resource-url https://api.example.com/premium \
--merchant-wallet 0x123...
Service Marketplace Registry (NEW v0.5.0)
The first unified discovery + payment layer for AI agents. Providers list services; agents search, see in-line pricing, purchase, and get provisioning credentials — all through one MCP server.
This closes the loop that competitors are building piecemeal: Rail402 does discovery, piprail does x402 SDK, agent-discovery-mcp does ERC-8004. mcp-payments unifies all of it.
from mcp_payments.engine import PaymentEngine
engine = PaymentEngine()
# 1. Provider registers a service
svc = engine.register_service(
name="Web Search API",
slug="web-search",
provider_customer_id=provider.id,
description="Full-text web search for agents",
category="search",
tags=["search", "web", "research"],
price_per_call=5, # 5 cents per query
free_tier_limit=10,
endpoint_url="https://api.example.com/v1/search",
mcp_server_url="https://mcp.example.com/search",
)
engine.publish_service(svc.id)
# 2. Agent discovers via search
results = engine.search_services("web search")
# → Returns services with in-line pricing, ratings, endpoint info
# 3. Agent purchases — discover → pay → provision in one call
access = engine.purchase_service(svc.id, customer_id=buyer.id)
# → {access_granted: True, endpoint_url: "...", payment_id: "pay_...", ...}
# 4. Agent leaves a verified review
engine.review_service(svc.id, customer_id=buyer.id, rating=5, comment="Fast and accurate")
# → verified=True (auto-checked against payment history)
# 5. Subscription plans
plan = engine.create_plan(svc.id, "Pro", price_cents=1000, included_calls=1000)
engine.subscribe_to_plan(plan.id, customer_id=buyer.id)
MCP tools added (10 new): register_service, publish_service, search_services, list_services, get_service, purchase_service, create_plan, subscribe_to_plan, review_service, list_service_reviews
x402 Billing Middleware (v0.3.0)
Enforce HTTP 402 payments on any ASGI app (FastAPI, Starlette). Agents that request a paid endpoint receive a 402 Payment Required with x402 payment requirements. When they retry with a valid X-PAYMENT header, the middleware verifies the payment and returns the resource.
from mcp_payments.middleware import X402Middleware, PricingRule
from fastapi import FastAPI
app = FastAPI()
# Define pricing rules for different endpoints
pricing_rules = [
PricingRule(method="GET", path="/api/premium", amount=0.01, description="Premium data"),
PricingRule(method="POST", path="/api/analyze", amount=0.05, description="AI analysis"),
]
app.add_middleware(
X402Middleware,
merchant_wallet="0x742d35Cc6634C0532925a3b844Bc9e7595f0bAe1",
pricing_rules=pricing_rules,
)
How it works:
- Agent requests
GET /api/premium - Middleware returns
402 Payment Required:
{
"x402Version": 1,
"accepts": [{
"scheme": "exact",
"network": "base-sepolia",
"asset": "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7235",
"amount": "10000",
"pay_to": "0x742d...",
"resource": "/api/premium",
"description": "Premium data"
}]
}
- Agent pays (on-chain USDC) and retries with
X-PAYMENTheader - Middleware verifies payment → returns resource with
X-PAYMENT-RESPONSEsettlement confirmation
Features:
- Static or dynamic pricing per endpoint
- Optional API key bypass via
check_fn - HMAC signature verification for signed payments
- Facilitator client for on-chain verification (or simulate mode for testing)
- Path prefix stripping for versioned APIs
MCP Tools (60 available)
| Tool | Description |
|---|---|
set_tool_price |
Set pricing for an MCP tool |
get_tool_price |
Check pricing for a tool |
list_tool_prices |
List all tool pricing |
create_customer |
Register a customer/agent |
get_customer |
Look up a customer |
top_up_balance |
Add prepaid balance |
create_payment_intent |
Create intent (x402 compatible) |
charge |
Charge a customer immediately |
fulfill_intent |
Execute a payment intent |
get_payment |
Get payment details |
verify_payment |
Verify payment validity |
refund_payment |
Refund (full or partial) |
get_receipt |
Generate signed receipt |
list_payments |
List with filters |
payment_summary |
Analytics and revenue |
create_x402_response |
Generate HTTP 402 requirements |
create_escrow |
Hold funds until task completes |
release_escrow |
Release escrow to payee |
refund_escrow |
Refund escrow to payer |
get_escrow |
Check escrow status |
list_escrows |
List/filter escrows |
create_split |
Split payment to multiple recipients |
get_split |
Check split payment status |
verify_x402_payment |
Verify an x402 payment header |
create_x402_middleware_config |
Generate middleware pricing config |
record_usage |
Record metered usage event |
get_usage_summary |
Get usage summary |
settle_usage |
Settle accumulated usage |
list_usage_events |
List usage events |
register_service |
Register an agent service |
publish_service |
Publish service to marketplace |
search_services |
Search services |
list_services |
List services |
get_service |
Get service details |
purchase_service |
Purchase a service |
create_plan |
Create subscription plan |
subscribe_to_plan |
Subscribe to a plan |
review_service |
Review a service |
list_service_reviews |
List service reviews |
set_spend_policy |
Set spend limit/policy |
check_authorization |
Check if charge is allowed |
get_spend_report |
Get spending analytics |
list_spend_policies |
List spend policies |
delete_spend_policy |
Delete a spend policy |
open_dispute |
NEW Open a dispute on an escrow |
get_dispute |
NEW Get dispute details |
list_disputes |
NEW List/filter disputes |
submit_evidence |
NEW Submit evidence to a dispute |
send_dispute_message |
NEW Send a message in dispute thread |
escalate_dispute |
NEW Escalate to arbiter review |
resolve_dispute |
NEW Resolve (release/refund/split) |
cancel_dispute |
NEW Cancel (withdraw) a dispute |
get_dispute_stats |
Aggregate dispute statistics |
configure_retry |
NEW Configure auto-retry behavior (triggers, strategy, limits) |
get_retry |
NEW Get retry process details + attempt history |
list_retries |
NEW List/filter retry processes |
execute_retry |
NEW Execute next retry attempt immediately |
cancel_retry |
NEW Cancel an active retry process |
process_pending_retries |
NEW Sweep all due retries (auto-recovery) |
get_retry_stats |
NEW Aggregate retry statistics (recovery rate, etc.) |
Payment Retry & Auto-Recovery (v0.8.0)
Self-healing payments for autonomous agents
When agents operate autonomously, payment failures are inevitable — insufficient balance, provider timeouts, rate limits. Without retry logic, a transient failure kills the entire agent workflow. mcp-payments now has a complete retry & auto-recovery layer: failed charges are automatically retried with configurable backoff strategies, and an auto top-up hook can replenish balance before the next attempt.
Lifecycle: charge fails → retry created → attempts scheduled → succeeded | exhausted | cancelled
charge() fails → maybe_create_retry() → attempts scheduled (fixed/exponential/linear backoff)
│ │
└── auto_top_up (optional) ──────────────────┘
│
process_pending_retries() ←── sweep due retries ←──────────┘
from mcp_payments.engine import PaymentEngine
engine = PaymentEngine()
# Configure retry behavior for a customer
config = engine.configure_retry(
customer_id=customer.id,
triggers=["insufficient_balance", "provider_timeout", "rate_limited"],
max_attempts=5,
strategy="exponential", # fixed | exponential | linear
base_delay_seconds=30,
max_delay_seconds=3600, # cap at 1 hour
auto_top_up=True, # auto-replenish balance before retry
auto_top_up_amount=5000, # $50.00
)
# Now any charge failure matching a trigger auto-creates a retry process
payment = engine.charge(customer.id, amount=500, tool="premium-api")
# If this fails with insufficient_balance, a PaymentRetry is created automatically
# Manual control
retry = engine.get_retry(retry_id)
engine.execute_retry(retry_id) # run next attempt now
engine.pause_retry(retry_id) # pause scheduled retries
engine.resume_retry(retry_id) # resume
engine.cancel_retry(retry_id) # stop retrying
# Auto-recovery sweep — call on cron/interval
processed = engine.process_pending_retries() # all due retries across all customers
# Monitor health
stats = engine.get_retry_stats()
# → {total_retries, active, succeeded, exhausted, recovery_rate, amount_recovered, ...}
Failure classification: Insufficient balance, provider timeout, rate limit, network error, declined. Each maps to configurable triggers — retry only what's recoverable.
Backoff strategies:
- fixed — same delay every attempt
- exponential — delay doubles each attempt (default)
- linear — delay increases by base each attempt
Config resolution: Customer-specific config overrides global default. Most-restrictive-wins when multiple configs apply.
Dispute Resolution (v0.7.0)
Agent accountability for escrow transactions
When an agent-to-agent deal goes wrong, the binary release/refund isn't enough. Parties need a structured process: file a dispute, submit evidence, communicate, and get an arbiter decision. This is the backend infrastructure that internet-court-skill (1.3k⭐) proves agents want.
Lifecycle: opened → responded → under_review → resolved_*
open_dispute → submit_evidence → send_dispute_message → escalate → resolve
(payer/payee) (both parties) (negotiation) (arbiter) (release/refund/split)
from mcp_payments.engine import PaymentEngine
engine = PaymentEngine()
# Payer files a dispute: "The agent didn't deliver"
dispute = engine.open_dispute(
escrow_id=escrow.id,
filed_by="payer",
reason="Task not completed — report never delivered",
category="non_delivery",
expires_in_seconds=86400, # auto-resolve in 24h
)
# Payer submits evidence
engine.submit_evidence(
dispute_id=dispute.id,
submitted_by=payer.id,
content="No report received by deadline",
evidence_url="https://example.com/empty-inbox.png",
evidence_type="screenshot",
)
# Payee responds
engine.submit_evidence(
dispute_id=dispute.id,
submitted_by=payee.id,
content="Report delivered — see attached receipt",
evidence_url="https://example.com/delivery-receipt.pdf",
evidence_type="receipt",
)
# Status transitions: opened → responded
# Negotiate
engine.send_dispute_message(dispute.id, payee.id, "I'll redo it with more detail")
# Escalate if unresolved
engine.escalate_dispute(dispute.id)
# Arbiter resolves: split 60/40 (partial delivery)
engine.resolve_dispute(
dispute_id=dispute.id,
outcome="split",
resolved_by=arbiter.id,
split_percentage=60, # 60% back to payer, 40% to payee
resolution="Partial quality — 60% refund",
)
Resolution outcomes:
- release — funds released to payee (payer was wrong)
- refund — funds returned to payer (payee was wrong)
- split — funds divided by percentage (partial fault)
Auto-expiry: Disputes that expire without resolution are auto-resolved:
- No response from counterparty → refund payer
- Responded but unresolved → 50/50 split
Categories: non_delivery, poor_quality, fraud, overcharge, non_payment, general
Escrow & Split Payments (v0.2.0)
Escrow — agent-to-agent trust
Agent A funds escrow → Agent B performs a task → Agent A releases the funds. If the task isn't done, Agent A refunds. If escrow expires, funds auto-refund.
from mcp_payments.engine import PaymentEngine
engine = PaymentEngine()
payer = engine.create_customer(name="Payer Agent")
payee = engine.create_customer(name="Worker Agent")
engine.top_up_balance(payer.id, 10000)
# Hold $5 in escrow for a task
escrow = engine.create_escrow(
payer_customer_id=payer.id,
payee_customer_id=payee.id,
amount=500,
task_description="Summarize 10 articles",
expires_in_seconds=86400, # auto-refund in 24h
)
# When the task is done, release
engine.release_escrow(escrow.id)
# Or if not done: engine.refund_escrow(escrow.id, reason="not completed")
Split payments — multi-recipient settlement
Distribute one charge across multiple recipients — perfect for marketplaces, platform fees, and revenue sharing.
# Charge $10, split $7 to provider, $2 platform, $1 referrer
split = engine.create_split(
payer_customer_id=payer.id,
shares=[
{"customer_id": provider.id, "amount": 7.00, "label": "provider"},
{"customer_id": platform.id, "amount": 2.00, "label": "platform_fee"},
{"customer_id": referrer.id, "amount": 1.00, "label": "referral"},
],
)
# Each recipient is credited instantly (auto_settle=True by default)
Pricing Models
- fixed — One-time payment
- per_use — Charge per tool invocation
- per_token — Charge per token processed
- tiered — Volume-based pricing
- subscription — Recurring payment
- dynamic — Market-driven pricing
Payment Providers
| Provider | Type | Status |
|---|---|---|
internal |
Ledger-only (prepaid balance) | ✅ Production-ready |
x402 |
Coinbase HTTP-native crypto | ✅ Protocol support + middleware |
stripe |
Fiat via Stripe | 🔧 Stub (requires API keys) |
solana |
On-chain SOL | 🔧 Stub (requires RPC) |
ethereum |
On-chain ETH | 🔧 Stub (requires RPC) |
lightning |
Bitcoin Lightning | 🔧 Stub |
Architecture
mcp-payments/
├── src/mcp_payments/
│ ├── models.py # Pydantic models (Payment, Customer, Price, Escrow, etc.)
│ ├── engine.py # Payment processing engine (charge, escrow, split)
│ ├── middleware.py # x402 billing middleware (NEW v0.3.0)
│ ├── storage.py # JSON-backed storage (swap to SQL for production)
│ ├── server/ # MCP server (60 tools)
│ └── cli/ # CLI interface
├── tests/ # Comprehensive test suite (454 tests)
└── docs/ # Documentation
Suite
This is part of the agent financial infrastructure suite:
| Package | Role |
|---|---|
| mcp-payments | Payment execution (this repo) |
| agent-invoice | Billing & invoicing |
| agent-ledger | Double-entry accounting |
| agent-budget | Budget tracking |
License
MIT
Installing Payments
This server has no published package — it is built from source. Open the repository and follow its README.
▸ github.com/nyx-builds/mcp-paymentsFAQ
Is Payments MCP free?
Yes, Payments MCP is free — one-click install via Unyly at no cost.
Does Payments need an API key?
No, Payments runs without API keys or environment variables.
Is Payments hosted or self-hosted?
Self-hosted: the server runs locally on your machine via the install command above.
How do I install Payments in Claude Desktop, Claude Code or Cursor?
Open Payments on unyly.org, pick your client tab (Claude Desktop, Claude Code, Cursor) and press Install — the config is generated automatically, no JSON editing.
Related MCPs
Stripe
Payments, customers, subscriptions
by Stripemalamutemayhem/unclick-agent-native-endpoints
110+ tools for AI agents spanning social media, finance, gaming, music, AU-specific services, and utilities. Zero-config local tools plus platform connectors. n
by malamutemayhemwhiteknightonhorse/APIbase
Unified API hub for AI agents with 56+ tools across travel (Amadeus, Sabre), prediction markets (Polymarket), crypto, and weather. Pay-per-call via x402 micropa
by whiteknightonhorsetrackerfitness729-jpg/sitelauncher-mcp-server
Deploy live HTTPS websites in seconds. Instant subdomains ($1 USDC) or custom .xyz domains ($10 USDC) on Base chain. Templates for crypto tokens and AI agent pr
Compare Payments with
Not sure what to pick?
Find your stack in 60 seconds
Author?
Embed badge for your README
Browse similar
All finance MCPs
