r402-mcp
MCP (Model Context Protocol) integration for the x402 payment protocol.
This crate enables paid tool calls in MCP servers and automatic payment handling in MCP clients, following the x402 payment protocol specification.
Features
- Client-side auto-payment —
X402McpClientwraps any MCP caller with automatic 402 payment handling - Server-side payment wrapper —
PaymentWrapperwraps tool handlers with verify → execute → settle lifecycle - Framework-agnostic — Works with any MCP SDK via the
McpCallertrait andserde_json::Value-based types - Lifecycle hooks — Trait-based hooks for both client and server sides
- Payment extraction utilities — Extract/attach payment data from/to MCP
_metafields
Architecture
The crate follows the x402 MCP specification where payment data flows through JSON-RPC _meta fields:
_meta["x402/payment"]— Client → Server: payment payload_meta["x402/payment-response"]— Server → Client: settlement response
Client Flow
- Call tool without payment
- If 402: extract
PaymentRequiredfromstructuredContentorcontent[0].text - Create payment via registered
SchemeClients - Retry with payment in
_meta["x402/payment"] - Extract settlement response from result
_meta
Server Flow
- Extract
x402/paymentfrom request_meta - If missing → return 402 error with
PaymentRequired - Verify payment via
Facilitator - Execute original handler
- Settle payment via
Facilitator - Attach
SettleResponseto result_meta
Usage
Client
use ;
use ClientOptions;
let client = builder
.scheme_client
.auto_payment
.build;
let result = client.call_tool.await?;
if let Some = &result.payment_response
Server
use PaymentWrapper;
use PaymentWrapperConfig;
let wrapper = new;
let result = wrapper.process.await;
Low-level Utilities
use extract;
// Extract payment from meta
let payment = extract_payment_from_meta;
// Attach payment to meta
attach_payment_to_meta;
// Extract payment required from error result
let pr = extract_payment_required_from_result;
Feature Flags
| Feature | Description |
|---|---|
rmcp |
Built-in integration with the official rmcp SDK |
telemetry |
Enables tracing instrumentation |
License
Licensed under either of Apache License, Version 2.0 or MIT license at your option.