Skip to content
Conduit

mcp server

mcp-payments

Agent payment infrastructure MCP server — charge, refund, escrow, subscriptions, webhooks. 69 tools for autonomous agent payments.

nyx-builds/mcp-paymentscommunitylistedunreviewed

Set up

Runs on your computer. Pick your agent and operating system.

Before you start

  • uv (`curl -LsSf https://astral.sh/uv/install.sh | sh`)
~/Library/Application Support/Claude/claude_desktop_config.json
{
  "mcpServers": {
    "nyx-builds-mcp-payments": {
      "command": "uvx",
      "args": [
        "mcp-payments"
      ]
    }
  }
}

same format Cursor, GitHub Copilot CLI, Junie, JetBrains AI Assistant, Augment (Auggie CLI), Factory Droid, Kiro, Devin CLI +12

Values in angle brackets are placeholders. Restart Claude Desktop after editing its config.Claude Desktop docs

README

synced Oct 23, 2026

mcp-payments

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:

  1. Agent requests GET /api/premium
  2. 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"
  }]
}
  1. Agent pays (on-chain USDC) and retries with X-PAYMENT header
  2. Middleware verifies payment → returns resource with X-PAYMENT-RESPONSE settlement 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)

ToolDescription
set_tool_priceSet pricing for an MCP tool
get_tool_priceCheck pricing for a tool
list_tool_pricesList all tool pricing
create_customerRegister a customer/agent
get_customerLook up a customer
top_up_balanceAdd prepaid balance
create_payment_intentCreate intent (x402 compatible)
chargeCharge a customer immediately
fulfill_intentExecute a payment intent
get_paymentGet payment details
verify_paymentVerify payment validity
refund_paymentRefund (full or partial)
get_receiptGenerate signed receipt
list_paymentsList with filters
payment_summaryAnalytics and revenue
create_x402_responseGenerate HTTP 402 requirements
create_escrowHold funds until task completes
release_escrowRelease escrow to payee
refund_escrowRefund escrow to payer
get_escrowCheck escrow status
list_escrowsList/filter escrows
create_splitSplit payment to multiple recipients
get_splitCheck split payment status
verify_x402_paymentVerify an x402 payment header
create_x402_middleware_configGenerate middleware pricing config
record_usageRecord metered usage event
get_usage_summaryGet usage summary
settle_usageSettle accumulated usage
list_usage_eventsList usage events
register_serviceRegister an agent service
publish_servicePublish service to marketplace
search_servicesSearch services
list_servicesList services
get_serviceGet service details
purchase_servicePurchase a service
create_planCreate subscription plan
subscribe_to_planSubscribe to a plan
review_serviceReview a service
list_service_reviewsList service reviews
set_spend_policySet spend limit/policy
check_authorizationCheck if charge is allowed
get_spend_reportGet spending analytics
list_spend_policiesList spend policies
delete_spend_policyDelete a spend policy
open_disputeNEW Open a dispute on an escrow
get_disputeNEW Get dispute details
list_disputesNEW List/filter disputes
submit_evidenceNEW Submit evidence to a dispute
send_dispute_messageNEW Send a message in dispute thread
escalate_disputeNEW Escalate to arbiter review
resolve_disputeNEW Resolve (release/refund/split)
cancel_disputeNEW Cancel (withdraw) a dispute
get_dispute_statsAggregate dispute statistics
configure_retryNEW Configure auto-retry behavior (triggers, strategy, limits)
get_retryNEW Get retry process details + attempt history
list_retriesNEW List/filter retry processes
execute_retryNEW Execute next retry attempt immediately
cancel_retryNEW Cancel an active retry process
process_pending_retriesNEW Sweep all due retries (auto-recovery)
get_retry_statsNEW 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

ProviderTypeStatus
internalLedger-only (prepaid balance)✅ Production-ready
x402Coinbase HTTP-native crypto✅ Protocol support + middleware
stripeFiat via Stripe🔧 Stub (requires API keys)
solanaOn-chain SOL🔧 Stub (requires RPC)
ethereumOn-chain ETH🔧 Stub (requires RPC)
lightningBitcoin 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:

PackageRole
mcp-paymentsPayment execution (this repo)
agent-invoiceBilling & invoicing
agent-ledgerDouble-entry accounting
agent-budgetBudget tracking

License

MIT

↑↓ navigate openesc close