fastmcp-client 0.11.0

MCP client implementation for FastMCP
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
//! Explicit parameter-header disclosure through the managed OAuth call owner.
//!
//! Reuses the normal core codec, managed credential lifecycle, one-POST dispatch,
//! incremental notifications and request-local cancellation. An annotation in a
//! catalog is never sufficient to enable this API: the host supplies a reviewed
//! plan bound to this resource and tool. Ordinary calls remain header-free.

/// One explicit catalog refresh after a trusted pre-dispatch header rejection.
pub mod repair;

use std::fmt;
use std::sync::Arc;

use asupersync::Cx;
use fastmcp_core::McpRequestCancellation;
use fastmcp_protocol::{CoreRequest, RequestId};

use super::interaction::{ManagedInteraction, ManagedInteractionError, ManagedInteractionLimits};
use super::{
    CoreDecoder, ManagedCoreCall, ManagedCoreError, ManagedCoreLimits, ManagedOAuthSession,
    bounded_wait, call_deadline, prepare,
};
use crate::http_executor::ModernHttpRequest;
use crate::http_executor::parameter_headers::{ReviewedToolHeaders, ToolHeaderDispatchError};

/// Header admission and core transport errors contain no disclosed values.
#[derive(Debug)]
pub enum ManagedToolHeaderError {
    Headers(ToolHeaderDispatchError),
    Core(ManagedCoreError),
}

impl fmt::Display for ManagedToolHeaderError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Headers(error) => fmt::Display::fmt(error, f),
            Self::Core(error) => fmt::Display::fmt(error, f),
        }
    }
}

impl std::error::Error for ManagedToolHeaderError {}
impl From<ToolHeaderDispatchError> for ManagedToolHeaderError {
    fn from(error: ToolHeaderDispatchError) -> Self {
        Self::Headers(error)
    }
}
impl From<ManagedCoreError> for ManagedToolHeaderError {
    fn from(error: ManagedCoreError) -> Self {
        Self::Core(error)
    }
}

// One preparation path is shared by initial calls and explicit continuations.
// It must run before credential acquisition and before consuming retry state.
pub(crate) fn prepare_optional(
    target: &str,
    request: CoreRequest,
    request_id: RequestId,
    limits: ManagedCoreLimits,
    reviewed: Option<&ReviewedToolHeaders>,
) -> Result<(ModernHttpRequest, CoreDecoder), ManagedToolHeaderError> {
    let (wire, decoder) = prepare(target, request, request_id, limits)?;
    let wire = match reviewed {
        Some(reviewed) => wire.with_reviewed_tool_headers(reviewed)?,
        None => wire,
    };
    Ok((wire, decoder))
}

impl ManagedOAuthSession {
    /// Starts an explicitly resumed operation with one immutable header review.
    /// Original arguments are projected on the first POST, every continuation,
    /// and any separately authorized journal recovery. Input answers and opaque
    /// state never become a replacement schema or a source of routing fields.
    pub async fn start_tool_interaction_with_headers(
        &self,
        cx: &Cx,
        request: CoreRequest,
        request_id: RequestId,
        reviewed: Arc<ReviewedToolHeaders>,
        limits: ManagedInteractionLimits,
    ) -> Result<ManagedInteraction, ManagedInteractionError> {
        self.start_tool_interaction_with_headers_and_cancellation(
            cx,
            &McpRequestCancellation::new(),
            request,
            request_id,
            reviewed,
            limits,
        )
        .await
    }

    /// Retains the original cancellation domain, deadline and review across
    /// host pauses. A review grants disclosure only; it does not grant replay
    /// authority or permission to run an input resolver.
    #[allow(clippy::too_many_arguments)]
    pub async fn start_tool_interaction_with_headers_and_cancellation(
        &self,
        cx: &Cx,
        cancellation: &McpRequestCancellation,
        request: CoreRequest,
        request_id: RequestId,
        reviewed: Arc<ReviewedToolHeaders>,
        limits: ManagedInteractionLimits,
    ) -> Result<ManagedInteraction, ManagedInteractionError> {
        self.start_core_interaction_configured(
            cx,
            cancellation,
            request,
            request_id,
            limits,
            Some(reviewed),
        )
        .await
    }

    /// Sends one tools/call with explicitly reviewed schema-derived headers.
    /// All binding, body, field-type and byte checks run before renewal or I/O.
    /// This returns the ordinary incremental core call; an input-required result
    /// does not automatically trigger a continuation or an input resolver.
    pub async fn request_tool_with_headers(
        &self,
        cx: &Cx,
        request: CoreRequest,
        request_id: RequestId,
        reviewed: &ReviewedToolHeaders,
        limits: ManagedCoreLimits,
    ) -> Result<ManagedCoreCall, ManagedToolHeaderError> {
        self.request_tool_with_headers_and_cancellation(
            cx,
            &McpRequestCancellation::new(),
            request,
            request_id,
            reviewed,
            limits,
        )
        .await
    }

    /// Retains one cancellation domain and absolute deadline through preparation,
    /// credential renewal and every response read. No sibling is cancelled and
    /// no side-effecting operation is replayed by this method.
    #[allow(clippy::too_many_arguments)]
    pub async fn request_tool_with_headers_and_cancellation(
        &self,
        cx: &Cx,
        cancellation: &McpRequestCancellation,
        request: CoreRequest,
        request_id: RequestId,
        reviewed: &ReviewedToolHeaders,
        limits: ManagedCoreLimits,
    ) -> Result<ManagedCoreCall, ManagedToolHeaderError> {
        let deadline = call_deadline(cx, cancellation, limits.timeout)?;
        let (wire, decoder) = prepare_optional(
            self.resource().as_str(),
            request,
            request_id,
            limits,
            Some(reviewed),
        )?;
        let response = bounded_wait(cx, cancellation, deadline, async {
            self.execute_with_cancellation(cx, cancellation, &wire)
                .await
                .map_err(ManagedCoreError::from)
        })
        .await?;
        ManagedCoreCall::from_response(response, decoder, cancellation.clone(), deadline)
            .map_err(ManagedToolHeaderError::from)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use fastmcp_core::CanonicalHttpUrl;
    use fastmcp_protocol::protocol_policy::ProtocolEra;
    use fastmcp_protocol::{ClientCapabilities, FinalRequestMeta};
    use serde_json::{Value, json};

    const TARGET: &str = "https://tools.example/mcp";

    fn review() -> ReviewedToolHeaders {
        ReviewedToolHeaders::new(
            CanonicalHttpUrl::parse(TARGET).unwrap(),
            "lookup",
            json!({
                "type":"object", "properties":{"region":{"type":"string","x-mcp-header":"Region"}},
            }),
            |binding| {
                binding.property_path() == ["region".to_owned()]
                    && binding.header_name() == "Mcp-Param-Region"
            },
        )
        .unwrap()
    }

    fn request(method: &str, mut params: Value) -> CoreRequest {
        params["_meta"] =
            serde_json::to_value(FinalRequestMeta::new(ClientCapabilities::default())).unwrap();
        CoreRequest::decode(ProtocolEra::Modern2026, method, Some(&params)).unwrap()
    }

    #[test]
    fn managed_preparation_retains_the_core_decoder_and_exact_parameters() {
        let request = request(
            "tools/call",
            json!({"name":"lookup","arguments":{"region":"eu","private":"body-only"}}),
        );
        let before = request.encode_params().unwrap().unwrap();
        let (wire, decoder) = prepare_optional(
            TARGET,
            request,
            RequestId::Number(17),
            ManagedCoreLimits::default(),
            Some(&review()),
        )
        .unwrap();
        let body: Value = serde_json::from_slice(wire.body()).unwrap();
        assert_eq!(body["params"], before);
        assert_eq!(body["id"], 17);
        assert_eq!(decoder.request_id, RequestId::Number(17));
        assert!(
            wire.headers()
                .iter()
                .any(|(name, value)| name == "Mcp-Param-Region" && value == "eu")
        );
        assert!(
            !wire
                .headers()
                .iter()
                .any(|(_, value)| value.contains("body-only"))
        );
        assert!(
            !wire
                .headers()
                .iter()
                .any(|(name, _)| name == "Authorization")
        );
    }

    #[test]
    fn invalid_binding_type_or_size_fails_during_local_preparation() {
        let review = review();
        for (target, request) in [
            (
                "https://tools.example/other",
                request("tools/call", json!({"name":"lookup"})),
            ),
            (TARGET, request("tools/call", json!({"name":"other"}))),
            (
                TARGET,
                request(
                    "tools/call",
                    json!({"name":"lookup","arguments":{"region":42}}),
                ),
            ),
            (TARGET, request("tools/list", json!({}))),
        ] {
            assert!(
                prepare_optional(
                    target,
                    request,
                    RequestId::Number(17),
                    ManagedCoreLimits::default(),
                    Some(&review)
                )
                .is_err()
            );
        }
        let tiny =
            ManagedCoreLimits::new(1, 1024, 1024, 1, std::time::Duration::from_secs(1)).unwrap();
        assert!(matches!(
            prepare_optional(
                TARGET,
                request("tools/call", json!({"name":"lookup"})),
                RequestId::Number(17),
                tiny,
                Some(&review)
            ),
            Err(ManagedToolHeaderError::Core(
                ManagedCoreError::RequestTooLarge
            ))
        ));
    }

    #[test]
    fn header_opt_in_does_not_activate_extensions_or_change_ordinary_calls() {
        let core = request(
            "tools/call",
            json!({"name":"lookup","arguments":{"region":"eu"}}),
        );
        let (ordinary, _) = prepare_optional(
            TARGET,
            core.clone(),
            RequestId::Number(17),
            ManagedCoreLimits::default(),
            None,
        )
        .unwrap();
        assert!(
            !ordinary
                .headers()
                .iter()
                .any(|(name, _)| name.starts_with("Mcp-Param-"))
        );
        let mut params = core.encode_params().unwrap().unwrap();
        params["_meta"]["io.modelcontextprotocol/clientCapabilities"]["extensions"] =
            json!({"io.modelcontextprotocol/tasks":{}});
        let core =
            CoreRequest::decode(ProtocolEra::Modern2026, "tools/call", Some(&params)).unwrap();
        assert!(matches!(
            prepare_optional(
                TARGET,
                core,
                RequestId::Number(17),
                ManagedCoreLimits::default(),
                Some(&review())
            ),
            Err(ManagedToolHeaderError::Core(
                ManagedCoreError::UnsupportedRequest
            ))
        ));
    }

    fn challenge(
        original: &CoreRequest,
        state: Option<&str>,
    ) -> fastmcp_protocol::InputRequiredResult {
        let mut value = json!({"resultType":"input_required", "inputRequests":{
            "one":{"method":"roots/list"}, "two":{"method":"roots/list"}
        }});
        if let Some(state) = state {
            value["requestState"] = json!(state);
        }
        let result = original.decode_result(&value.to_string()).unwrap();
        super::super::interaction::input_required(&result)
            .unwrap()
            .clone()
    }

    fn continuation_source() -> CoreRequest {
        let original = request(
            "tools/call",
            json!({"name":"lookup", "arguments":{"region":"eu", "private":"body-only"}}),
        );
        let mut params = original.encode_params().unwrap().unwrap();
        params["_meta"]["io.modelcontextprotocol/clientCapabilities"] = json!({"roots":{}});
        CoreRequest::decode(ProtocolEra::Modern2026, "tools/call", Some(&params)).unwrap()
    }

    #[test]
    fn full_and_partial_continuations_project_only_immutable_original_arguments() {
        use super::super::interaction::{InputSelection, continuation_request_selected};
        let original = continuation_source();
        let before = original.encode_params().unwrap().unwrap();
        let input = challenge(&original, Some("  opaque\0  "));
        let review = review();
        for (selection, answers) in [
            (
                InputSelection::Complete,
                json!({"one":{"roots":[]},"two":{"roots":[]}}),
            ),
            (InputSelection::Partial, json!({"two":{"roots":[]}})),
        ] {
            let next = continuation_request_selected(
                &original,
                &input,
                Some(serde_json::from_value(answers.clone()).unwrap()),
                selection,
            )
            .unwrap();
            let (wire, _) = prepare_optional(
                TARGET,
                next,
                RequestId::Number(18),
                ManagedCoreLimits::default(),
                Some(&review),
            )
            .unwrap();
            let encoded: Value = serde_json::from_slice(wire.body()).unwrap();
            assert_eq!(encoded["params"]["arguments"], before["arguments"]);
            assert_eq!(encoded["params"]["_meta"], before["_meta"]);
            assert_eq!(encoded["params"]["inputResponses"], answers);
            assert_eq!(encoded["params"]["requestState"], "  opaque\0  ");
            let fields: Vec<_> = wire
                .headers()
                .into_iter()
                .filter(|(name, _)| name.starts_with("Mcp-Param-"))
                .collect();
            assert_eq!(
                fields,
                vec![("Mcp-Param-Region".to_owned(), "eu".to_owned())]
            );
        }
        assert_eq!(original.encode_params().unwrap().unwrap(), before);
    }

    #[test]
    fn invalid_partial_answers_never_become_a_header_bearing_continuation() {
        use super::super::interaction::{InputSelection, continuation_request_selected};
        let original = continuation_source();
        let before = original.encode_params().unwrap().unwrap();
        for (input, answers) in [
            (challenge(&original, None), json!({"one":{"roots":[]}})),
            (
                challenge(&original, Some("state")),
                json!({"foreign":{"roots":[]}}),
            ),
            (challenge(&original, Some("state")), json!({})),
        ] {
            assert!(
                continuation_request_selected(
                    &original,
                    &input,
                    Some(serde_json::from_value(answers).unwrap()),
                    InputSelection::Partial
                )
                .is_err()
            );
        }
        assert_eq!(original.encode_params().unwrap().unwrap(), before);
    }

    #[test]
    fn reply_recovery_changes_the_rpc_id_but_not_the_projected_headers_or_params() {
        use super::super::interaction::continuation_request;
        let original = continuation_source();
        let input = challenge(&original, Some("journal-state"));
        let answers =
            serde_json::from_value(json!({"one":{"roots":[]},"two":{"roots":[]}})).unwrap();
        let request = continuation_request(&original, &input, Some(answers)).unwrap();
        let review = review();
        let (first, _) = prepare_optional(
            TARGET,
            request.clone(),
            RequestId::Number(18),
            ManagedCoreLimits::default(),
            Some(&review),
        )
        .unwrap();
        let (next, _) = prepare_optional(
            TARGET,
            request,
            RequestId::Number(19),
            ManagedCoreLimits::default(),
            Some(&review),
        )
        .unwrap();
        let first_body: Value = serde_json::from_slice(first.body()).unwrap();
        let next_body: Value = serde_json::from_slice(next.body()).unwrap();
        assert_ne!(first_body["id"], next_body["id"]);
        assert_eq!(first_body["params"], next_body["params"]);
        assert_eq!(first.headers(), next.headers());
    }

    #[test]
    fn state_only_continuation_keeps_absence_and_still_projects_the_original_input() {
        use super::super::interaction::{continuation_request, input_required};
        let original = continuation_source();
        let result = original
            .decode_result(r#"{"resultType":"input_required","requestState":""}"#)
            .unwrap();
        let next = continuation_request(&original, input_required(&result).unwrap(), None).unwrap();
        let (wire, _) = prepare_optional(
            TARGET,
            next,
            RequestId::Number(18),
            ManagedCoreLimits::default(),
            Some(&review()),
        )
        .unwrap();
        let value: Value = serde_json::from_slice(wire.body()).unwrap();
        assert_eq!(value["params"]["requestState"], "");
        assert!(value["params"].get("inputResponses").is_none());
        assert!(
            wire.headers()
                .iter()
                .any(|(name, value)| name == "Mcp-Param-Region" && value == "eu")
        );
    }
}