r402-mcp 0.15.0

MCP transport for the x402 payment protocol (official rmcp SDK).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! Client-side MCP auto-pay — Go `X402MCPClient` / `CallPaidTool`.
//!
//! V1 payment paths are intentionally omitted (r402 is V2-only).

use std::future::Future;
use std::sync::Arc;

use r402_core::wire::{PaymentRequired, SettleResponse};
use rmcp::model::{CallToolRequestParams, CallToolResult};
use serde_json::{Map, Value};

use crate::encode::{
    McpPaymentPayload, attach_payment_to_params, extract_payment_required, extract_settle_response,
    is_payment_required_result,
};
use crate::error::{McpClientError, PaymentRequiredError};

/// Minimal tool-call surface (Go `MCPCaller`).
pub trait McpToolCaller: Send + Sync {
    /// Invokes `tools/call`.
    fn call_tool(
        &self,
        params: CallToolRequestParams,
    ) -> impl Future<Output = Result<CallToolResult, String>> + Send;
}

/// Signs a [`PaymentRequired`] into a wire payment payload.
pub trait PaymentSigner: Send + Sync {
    /// Creates a payment for the challenge.
    fn sign_payment(
        &self,
        required: PaymentRequired,
    ) -> impl Future<Output = Result<McpPaymentPayload, String>> + Send;
}

/// Result of a paid tool call (Go `MCPToolCallResult` / `ToolCallResult`).
#[derive(Debug, Clone)]
pub struct PaidToolCallResult {
    /// Underlying MCP tool result.
    pub result: CallToolResult,
    /// Whether a payment was submitted.
    pub payment_made: bool,
    /// Settlement from `_meta`, if present.
    pub payment_response: Option<SettleResponse>,
}

/// Client options (Go `Options`).
#[derive(Debug, Clone, Copy)]
pub struct X402McpClientOptions {
    /// Auto-create payment when challenged (default true).
    pub auto_payment: bool,
}

impl Default for X402McpClientOptions {
    fn default() -> Self {
        Self { auto_payment: true }
    }
}

/// Client hooks (Go hook fields).
#[derive(Clone, Default)]
pub struct ClientHooks {
    /// Can abort or supply a custom payload.
    pub on_payment_required:
        Option<Arc<dyn Fn(PaymentRequiredContext) -> PaymentRequiredHookResult + Send + Sync>>,
    /// Approve/deny auto-pay.
    pub on_payment_requested: Option<Arc<dyn Fn(PaymentRequiredContext) -> bool + Send + Sync>>,
    /// Before signing.
    pub on_before_payment: Option<Arc<dyn Fn(PaymentRequiredContext) + Send + Sync>>,
    /// After paid call returns.
    pub on_after_payment: Option<Arc<dyn Fn(AfterPaymentContext) + Send + Sync>>,
}

impl std::fmt::Debug for ClientHooks {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ClientHooks").finish_non_exhaustive()
    }
}

/// Context for payment-required hooks.
#[derive(Debug, Clone)]
pub struct PaymentRequiredContext {
    /// Tool name.
    pub tool_name: String,
    /// Arguments.
    pub arguments: Map<String, Value>,
    /// Challenge body.
    pub payment_required: PaymentRequired,
}

/// Result of `on_payment_required`.
#[derive(Debug, Clone, Default)]
pub struct PaymentRequiredHookResult {
    /// Abort without paying.
    pub abort: bool,
    /// Optional custom signed payload.
    pub payment: Option<McpPaymentPayload>,
}

/// Context after a paid call.
#[derive(Debug, Clone)]
pub struct AfterPaymentContext {
    /// Tool name.
    pub tool_name: String,
    /// Payload that was submitted.
    pub payment_payload: McpPaymentPayload,
    /// Tool result.
    pub result: CallToolResult,
    /// Settlement if present.
    pub settle_response: Option<SettleResponse>,
}

/// Go `X402MCPClient`.
pub struct X402McpClient<C, S> {
    caller: C,
    signer: S,
    options: X402McpClientOptions,
    hooks: ClientHooks,
}

impl<C, S> std::fmt::Debug for X402McpClient<C, S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("X402McpClient")
            .field("options", &self.options)
            .finish_non_exhaustive()
    }
}

impl<C, S> X402McpClient<C, S>
where
    C: McpToolCaller,
    S: PaymentSigner,
{
    /// Creates a client with default options.
    #[must_use]
    pub fn new(caller: C, signer: S) -> Self {
        Self {
            caller,
            signer,
            options: X402McpClientOptions::default(),
            hooks: ClientHooks::default(),
        }
    }

    /// Sets options.
    #[must_use]
    pub const fn with_options(mut self, options: X402McpClientOptions) -> Self {
        self.options = options;
        self
    }

    /// Sets hooks.
    #[must_use]
    pub fn with_hooks(mut self, hooks: ClientHooks) -> Self {
        self.hooks = hooks;
        self
    }

    /// Go `CallTool` — automatic payment when required.
    ///
    /// # Errors
    ///
    /// Transport, signing, user deny, or persistent 402.
    pub async fn call_tool(
        &self,
        name: impl Into<String>,
        arguments: Option<Map<String, Value>>,
    ) -> Result<PaidToolCallResult, McpClientError> {
        let name = name.into();
        let args = arguments.unwrap_or_default();
        let mut params = CallToolRequestParams::new(name.clone());
        if !args.is_empty() {
            params = params.with_arguments(args.clone());
        }

        let first = self
            .caller
            .call_tool(params.clone())
            .await
            .map_err(McpClientError::Transport)?;

        if !is_payment_required_result(&first) {
            return Ok(PaidToolCallResult {
                payment_response: extract_settle_response(&first),
                result: first,
                payment_made: false,
            });
        }

        let required = extract_payment_required(&first)
            .ok_or_else(|| McpClientError::Payment("missing PaymentRequired body".into()))?;

        let pr_ctx = PaymentRequiredContext {
            tool_name: name.clone(),
            arguments: args,
            payment_required: required.clone(),
        };

        if let Some(ref hook) = self.hooks.on_payment_required {
            let hr = hook(pr_ctx.clone());
            if hr.abort {
                return Err(PaymentRequiredError::new("Payment required", required).into());
            }
            if let Some(payload) = hr.payment {
                return self
                    .call_tool_with_payment(name, params.arguments.clone(), payload)
                    .await;
            }
        }

        if !self.options.auto_payment {
            return Err(PaymentRequiredError::new("Payment required", required).into());
        }

        if let Some(ref requested) = self.hooks.on_payment_requested
            && !requested(pr_ctx.clone())
        {
            return Err(PaymentRequiredError::new("Payment denied by user", required).into());
        }

        if let Some(ref before) = self.hooks.on_before_payment {
            before(pr_ctx);
        }

        let payload = self
            .signer
            .sign_payment(required)
            .await
            .map_err(McpClientError::Payment)?;

        self.call_tool_with_payment(name, params.arguments, payload)
            .await
    }

    /// Go `CallToolWithPayment`.
    ///
    /// # Errors
    ///
    /// Transport failure or still-required payment.
    pub async fn call_tool_with_payment(
        &self,
        name: impl Into<String>,
        arguments: Option<Map<String, Value>>,
        payload: McpPaymentPayload,
    ) -> Result<PaidToolCallResult, McpClientError> {
        let name = name.into();
        let mut params = CallToolRequestParams::new(name.clone());
        if let Some(args) = arguments {
            params = params.with_arguments(args);
        }
        let params = attach_payment_to_params(params, &payload);

        let result = self
            .caller
            .call_tool(params)
            .await
            .map_err(McpClientError::Transport)?;

        if is_payment_required_result(&result) {
            return Err(McpClientError::StillRequired);
        }

        let settle = extract_settle_response(&result);
        if let Some(ref after) = self.hooks.on_after_payment {
            after(AfterPaymentContext {
                tool_name: name,
                payment_payload: payload,
                result: result.clone(),
                settle_response: settle.clone(),
            });
        }

        Ok(PaidToolCallResult {
            payment_response: settle,
            result,
            payment_made: true,
        })
    }

    /// Go `GetToolPaymentRequirements`.
    ///
    /// # Errors
    ///
    /// Transport failures.
    pub async fn get_tool_payment_requirements(
        &self,
        name: impl Into<String>,
        arguments: Option<Map<String, Value>>,
    ) -> Result<Option<PaymentRequired>, McpClientError> {
        let mut params = CallToolRequestParams::new(name.into());
        if let Some(args) = arguments {
            params = params.with_arguments(args);
        }
        let result = self
            .caller
            .call_tool(params)
            .await
            .map_err(McpClientError::Transport)?;
        Ok(extract_payment_required(&result))
    }
}

/// Go `CallPaidTool` free function.
///
/// # Errors
///
/// Same as [`X402McpClient::call_tool`].
pub async fn call_paid_tool<C, S>(
    caller: C,
    signer: S,
    name: impl Into<String>,
    arguments: Option<Map<String, Value>>,
) -> Result<PaidToolCallResult, McpClientError>
where
    C: McpToolCaller,
    S: PaymentSigner,
{
    X402McpClient::new(caller, signer)
        .call_tool(name, arguments)
        .await
}

#[cfg(test)]
mod tests {
    use std::sync::Mutex;

    use r402_core::wire::{PaymentRequirements, ResourceInfo};
    use serde_json::json;

    use super::*;
    use crate::encode::payment_required_tool_result;

    struct MockCaller {
        calls: Mutex<u8>,
    }

    impl McpToolCaller for MockCaller {
        fn call_tool(
            &self,
            params: CallToolRequestParams,
        ) -> impl Future<Output = Result<CallToolResult, String>> + Send {
            std::future::ready(self.handle_call(&params))
        }
    }

    impl MockCaller {
        fn handle_call(&self, params: &CallToolRequestParams) -> Result<CallToolResult, String> {
            let unpaid = params.meta.is_none();
            let mut n = self.calls.lock().map_err(|e| e.to_string())?;
            *n = n.saturating_add(1);
            drop(n);
            if !unpaid {
                return Ok(CallToolResult::success(vec![
                    rmcp::model::ContentBlock::text("ok"),
                ]));
            }
            let network = "eip155:1"
                .parse()
                .map_err(|e| format!("fixture network: {e}"))?;
            let resource = ResourceInfo::new("mcp://tool/demo");
            let req = PaymentRequirements::new(
                "exact".into(),
                network,
                "1".into(),
                "0xa".into(),
                "0xb".into(),
                60,
            );
            let pr = PaymentRequired::new(resource).with_accepts(vec![req]);
            Ok(payment_required_tool_result(&pr))
        }
    }

    struct MockSigner;

    impl PaymentSigner for MockSigner {
        fn sign_payment(
            &self,
            required: PaymentRequired,
        ) -> impl Future<Output = Result<McpPaymentPayload, String>> + Send {
            let result = required
                .accepts
                .into_iter()
                .next()
                .ok_or_else(|| "no accepts".to_owned())
                .map(|accepted| McpPaymentPayload::new(accepted, json!({"s": 1})));
            std::future::ready(result)
        }
    }

    #[tokio::test]
    async fn auto_pays_on_second_call() {
        let client = X402McpClient::new(
            MockCaller {
                calls: Mutex::new(0),
            },
            MockSigner,
        );
        let out = client.call_tool("demo", None).await.unwrap();
        assert!(out.payment_made);
        assert!(!out.result.is_error.unwrap_or(false));
    }

    #[tokio::test]
    async fn auto_payment_disabled_returns_402() {
        let client = X402McpClient::new(
            MockCaller {
                calls: Mutex::new(0),
            },
            MockSigner,
        )
        .with_options(X402McpClientOptions {
            auto_payment: false,
        });
        let err = client.call_tool("demo", None).await.unwrap_err();
        match err {
            McpClientError::PaymentRequired(e) => assert_eq!(e.code, 402),
            other => panic!("expected PaymentRequired, got {other:?}"),
        }
    }
}