Command Palette

Search for a command to run...

UnylyUnyly
Весь каталог

R402

БесплатноНе проверен

MCP transport for the x402 payment protocol (official rmcp SDK).

GitHubEmbed

Описание

MCP transport for the x402 payment protocol (official rmcp SDK).

README

R402

Crates.io Docs.rs CI License Rust

Modular Rust SDK for the x402 payment protocol — client signing, server gating, and facilitator settlement over HTTP 402.

r402 is a production-grade, multi-chain implementation of x402 with dual-path ERC-3009 / Permit2 transfers, the exact and upto (usage-based) schemes, composable lifecycle hooks, and built-in deployments across EVM, Solana (SVM), Tron, and Casper.

See also facilitator — a production-ready facilitator server built on r402.

Quick Start

Install

[dependencies]
r402 = { version = "0.15", features = ["evm", "http", "client", "server"] }

Full feature matrix and crate list: crates/README.md.

Protect a Route (Server)

use alloy_primitives::address;
use axum::{Router, routing::get};
use r402_evm::{Eip155Exact, USDC};
use r402_http::server::X402Middleware;

let x402 = X402Middleware::new("https://facilitator.example.com");

let app = Router::new().route(
    "/paid-content",
    get(handler).layer(
        x402.with_price_tag(Eip155Exact::price_tag(
            address!("0xYourPayToAddress"),
            USDC::base().amount(1_000_000u64), // 1 USDC (6 decimals)
        ))
    ),
);

Send Payments (Client)

use alloy_signer_local::PrivateKeySigner;
use r402_evm::Eip155ExactClient;
use r402_http::client::{WithPayments, X402Client};
use std::sync::Arc;

let signer = Arc::new("0x...".parse::<PrivateKeySigner>()?);
let x402 = X402Client::new().register(Eip155ExactClient::new(signer));

let client = reqwest::Client::new().with_payments(x402);

let res = client.get("https://api.example.com/paid").send().await?;

Usage-Based Pricing (upto Scheme)

The upto scheme lets the buyer sign a maximum while the resource server picks the final charge at request time (meter reads, token usage, dynamic tiers). The facilitator settles for any value in [0, max]; a final amount of 0 returns no on-chain transaction.

use alloy_primitives::address;
use axum::{Router, response::IntoResponse, routing::post};
use r402_evm::{Eip155Upto, USDC};
use r402_http::server::{UptoActualAmount, X402Middleware};

async fn meter(/* ... */) -> impl IntoResponse {
    let mut response = "result".into_response();
    // Charge 0.125 USDC for this call.
    response.extensions_mut().insert(UptoActualAmount::new("125000"));
    response
}

let layer = X402Middleware::new("https://facilitator.example.com")
    .with_price_tag(Eip155Upto::price_tag(
        address!("0xYourPayToAddress"),
        USDC::base().amount(1_000_000u64), // up to 1 USDC
    ));
let app = Router::new().route("/meter", post(meter).layer(layer));

Handlers opt in by inserting UptoActualAmount into the response extensions; the middleware patches paymentRequirements.amount before forwarding the settle request. Buyers sign with Eip155UptoClient (shares the Permit2 auto-approve plumbing with Eip155ExactClient).

Note: UptoActualAmount is honoured only by SettlementMode::Sequential. Concurrent and background modes start settlement before the handler returns and therefore charge the signed maximum.

Settlement Modes

X402Middleware supports three settlement strategies, configurable via with_settlement_mode():

Sequential (default)

Verify → execute → settle. The safest mode — on-chain settlement only occurs after the handler succeeds, and the Payment-Response header is included in the same HTTP response.

sequenceDiagram
    participant C as Client
    participant S as Server
    participant F as Facilitator
    participant H as Handler

    C->>S: HTTP Request + Payment-Signature
    S->>F: verify(payment)
    F-->>S: VerifyResponse ✓
    S->>H: execute request
    Note over S,H: Balance verified but NOT locked —<br/>handler executing (variable latency)
    H-->>S: response body
    S->>F: settle(payment)
    Note over S,F: On-chain transfer (2–5 s)
    F-->>S: SettleResponse (tx_hash)
    S-->>C: 200 OK + Payment-Response header

Concurrent

Verify → (settle ∥ execute) → await both. Reduces total latency by overlapping on-chain settlement with handler execution, saving one facilitator round-trip. On handler error the settlement task is detached (fire-and-forget).

sequenceDiagram
    participant C as Client
    participant S as Server
    participant F as Facilitator
    participant H as Handler

    C->>S: HTTP Request + Payment-Signature
    S->>F: verify(payment)
    F-->>S: VerifyResponse ✓
    par settle ∥ execute
        S->>F: settle(payment)
        Note over S,F: On-chain transfer
        F-->>S: SettleResponse (tx_hash)
    and
        S->>H: execute request
        H-->>S: response body
    end
    S-->>C: 200 OK + Payment-Response header

Background

Verify → spawn settle (fire-and-forget) → execute → return. Settlement runs entirely in the background — the response is returned to the client as soon as the handler completes, without waiting for on-chain confirmation. Ideal for streaming responses (SSE, LLM token streams) where the client should start receiving data immediately. Settlement errors are logged but do not propagate to the caller. Trade-off: the Payment-Response header is not attached since settlement may still be in progress when the response is sent.

sequenceDiagram
    participant C as Client
    participant S as Server
    participant F as Facilitator
    participant H as Handler

    C->>S: HTTP Request + Payment-Signature
    S->>F: verify(payment)
    F-->>S: VerifyResponse ✓
    S-)F: settle(payment) [fire-and-forget]
    S->>H: execute request
    H-->>S: response body (or stream)
    S-->>C: 200 OK (no Payment-Response header)
    Note over S,F: Settlement completes asynchronously
    F-)S: SettleResponse (logged)

Comparison

Mode Total latency Safety Payment-Response Best for
Sequential verify + handler + settle Settlement only on handler success ✅ Included Standard request/response APIs
Concurrent verify + max(handler, settle) Settlement may occur on handler failure ✅ Included Latency-sensitive endpoints
Background verify + handler Settlement errors are non-fatal (logged) ❌ Not attached SSE / LLM streaming responses

For full manual control over settlement timing, use the composable Paygate API directly with verify_only() + VerifiedPayment::settle().

Design

  • Four built-in chains — EVM (EIP-155), Solana (SVM), Tron, Casper
  • Schemesexact (all chains) + upto (usage-based, EVM)
  • Transfer methods — ERC-3009 / Permit2 (EVM, Tron); SPL (SVM); CEP-18 auth (Casper)
  • Lifecycle hooksFacilitatorHooks (verify/settle) + ClientHooks (payment creation)
  • Async model — zero async_trait in core — RPITIT / Pin<Box<dyn Future>>
  • Facilitator trait — unified, dyn-compatible Box<dyn Facilitator> across schemes
  • Wire format — V2-only server (CAIP-2 chain IDs, Payment-Signature header)
  • Settlement errors — failed settle returns 402 with structured error
  • Smart wallets — EIP-6492 (counterfactual) + EIP-1271 (deployed) + ERC-2098 (compact)
  • Strict linting — Clippy pedantic + nursery + correctness (deny)

Crates

See crates/README.md for the full crate table, chain matrix, dependency graph, and feature flag reference.

Acknowledgments

License

Licensed under either of:

at your option.

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this project shall be dual-licensed as above, without any additional terms or conditions.


A QuantX open-source project.

QuantX

Code is law. We write both.

from github.com/qntx/r402

Установка R402

У этого сервера нет опубликованного пакета — он собирается из исходников. Открой репозиторий и следуй инструкции в README.

▸ github.com/qntx/r402

FAQ

R402 MCP бесплатный?

Да, R402 MCP бесплатный — установка в пару кликов через Unyly без оплаты.

Нужен ли API-ключ для R402?

Нет, R402 работает без API-ключей и переменных окружения.

R402 — hosted или self-hosted?

Self-hosted: сервер запускается локально на твоей машине командой из раздела установки.

Как установить R402 в Claude Desktop, Claude Code или Cursor?

Открой R402 на unyly.org, выбери вкладку своего клиента (Claude Desktop, Claude Code, Cursor) и нажми Install — конфиг сгенерируется автоматически, без правки JSON.

Похожие MCP

$5

Stripe

Payments, customers, subscriptions

Stripeавтор: Stripe

malamutemayhem/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

malamutemayhemавтор: malamutemayhem

whiteknightonhorse/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

whiteknightonhorseавтор: whiteknightonhorse

trackerfitness729-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

trackerfitness729-jpgавтор: trackerfitness729-jpg

embeddedlayers/mcp-analytics

Statistical analysis, forecasting, and ML for business data (Shopify, Stripe, WooCommerce, eBay, GA4, Search Console). Upload a CSV or connect live data sources

embeddedlayersавтор: embeddedlayers

carrierone/verilexdata-mcp

20 structured datasets (NPI healthcare, SEC filings, OFAC sanctions, crypto whales, Polymarket signals, patents, economic indicators) via x402 pay-per-query wit

carrieroneавтор: carrierone

tipdotmd/tip-md-x402-mcp-server

MCP server for cryptocurrency tipping through AI interfaces using x402 payment protocol and CDP Wallet.

tipdotmdавтор: tipdotmd

laundromatic/shopgraph

Structured product data from the open web — Schema.org + AI extraction for e-commerce enrichment. Pay per call via Stripe. [shopgraph.dev](https://shopgraph.dev

laundromaticавтор: laundromatic

mrslbt/xendit-mcp

Xendit payment gateway for Southeast Asia. Invoices, disbursements, balance checks, and bank transfers across Indonesia, Philippines, Thailand, Vietnam, and Mal

mrslbtавтор: mrslbt

@arbitova/mcp-server

Non-custodial on-chain escrow + AI dispute arbitration for agent-to-agent USDC payments on Base. Seven tools covering the full EscrowV1 contract surface: create

jiayuanliang0716-maxавтор: jiayuanliang0716-max

Compare R402 with

Не уверен что выбрать?

Найди свой стек за 60 секунд

Автор?

Embed-бейдж для README

Похожее

Все в категории finance