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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
//! Portable, observation-only restart checkpoints for already-created Tasks.
//!
//! These bytes are a selection, NOT a credential, execution receipt or replay
//! permit. Restore uses a caller-selected managed login at the exact recorded
//! resource, opens a fresh acknowledged subscription, and reads current Tasks.
//! No saved snapshot, terminal ledger, token, input answer, requestState or
//! creating request is restored. A Task that disappeared or became forbidden
//! remains an ordinary server error; it is never recreated or declared complete.
//!
//! The host owns durable storage, access control and atomic replacement of the
//! bytes. Task IDs and resource URLs can be sensitive even without credentials.
//! Export does not close a watch or acknowledge delivery. Restoring starts a NEW
//! observation budget and may redeliver terminal snapshots; exactly-once effects,
//! missed-event replay and persistence of a remote Task are not implied.

use std::fmt;

use asupersync::Cx;
use fastmcp_core::{CanonicalHttpUrl, McpRequestCancellation};
use fastmcp_protocol::FINAL_PROTOCOL_VERSION;
use fastmcp_protocol::tasks_extension::TaskId;
use serde::{Deserialize, Serialize};

use super::recovery::{
    ManagedTaskRecoveryError, ManagedTaskRecoveryPolicy, RecoveringManagedTaskWatch,
};
use super::{
    BoundedWriter, MAX_WATCH_TASKS, ManagedTaskWatch, ManagedTaskWatchError,
    ManagedTaskWatchPolicy, ManagedTasksClient, WatchState,
};

/// Owner-bound lifecycle records and explicitly protected atomic storage.
pub mod resume;

/// Hard bound checked before JSON parsing and while encoding a checkpoint.
pub const MAX_TASK_WATCH_CHECKPOINT_BYTES: usize = 64 * 1024;
const CHECKPOINT_FORMAT: &str = "fastmcp/task-watch";
const CHECKPOINT_VERSION: u32 = 1;

/// Immutable restart selection. Deliberately not `Deserialize`: all decoding
/// must pass the byte bound, exact format/era and selection admission below.
/// Debug output omits the endpoint and Task IDs.
#[derive(Clone)]
pub struct ManagedTaskWatchCheckpoint {
    resource: CanonicalHttpUrl,
    task_ids: Vec<TaskId>,
}

impl fmt::Debug for ManagedTaskWatchCheckpoint {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ManagedTaskWatchCheckpoint")
            .field("version", &CHECKPOINT_VERSION)
            .field("task_count", &self.task_ids.len())
            .finish_non_exhaustive()
    }
}

// Deserialize the closed typed object directly, not through Value: repeated
// members (including escaped spellings) must not silently become last-wins.
#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
struct CheckpointWire {
    format: String,
    version: u32,
    protocol_version: String,
    resource: String,
    task_ids: Vec<TaskId>,
}

/// Fixed checkpoint diagnostics retain neither saved bytes nor identifiers.
/// Live admission errors preserve their original typed cause.
#[derive(Debug)]
pub enum ManagedTaskCheckpointError {
    TooLarge,
    InvalidDocument,
    UnsupportedFormat,
    UnsupportedProtocol,
    InvalidResource,
    InvalidSelection,
    ResourceMismatch,
    Watch(ManagedTaskWatchError),
    Recovery(ManagedTaskRecoveryError),
}

impl fmt::Display for ManagedTaskCheckpointError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::TooLarge => "Task watch checkpoint byte bound exceeded",
            Self::InvalidDocument => "invalid Task watch checkpoint document",
            Self::UnsupportedFormat => "unsupported Task watch checkpoint format or version",
            Self::UnsupportedProtocol => "unsupported Task watch checkpoint protocol era",
            Self::InvalidResource => "invalid Task watch checkpoint resource",
            Self::InvalidSelection => "invalid Task watch checkpoint selection",
            Self::ResourceMismatch => {
                "Task watch checkpoint does not match the configured resource"
            }
            Self::Watch(_) => "Task watch checkpoint admission failed",
            Self::Recovery(_) => "recovering Task watch checkpoint admission failed",
        })
    }
}

impl std::error::Error for ManagedTaskCheckpointError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Watch(error) => Some(error),
            Self::Recovery(error) => Some(error),
            _ => None,
        }
    }
}
impl From<ManagedTaskWatchError> for ManagedTaskCheckpointError {
    fn from(error: ManagedTaskWatchError) -> Self {
        Self::Watch(error)
    }
}
impl From<ManagedTaskRecoveryError> for ManagedTaskCheckpointError {
    fn from(error: ManagedTaskRecoveryError) -> Self {
        Self::Recovery(error)
    }
}

impl ManagedTaskWatchCheckpoint {
    fn new(
        resource: &CanonicalHttpUrl,
        task_ids: Vec<TaskId>,
    ) -> Result<Self, ManagedTaskCheckpointError> {
        // Reuse the live watch's exact uniqueness, cardinality and encoded
        // selection bounds. The restart policy will separately bound snapshots.
        let state = WatchState::new(task_ids, MAX_WATCH_TASKS)
            .map_err(|_| ManagedTaskCheckpointError::InvalidSelection)?;
        let checkpoint = Self {
            resource: resource.clone(),
            task_ids: state.task_ids,
        };
        checkpoint.encode()?;
        Ok(checkpoint)
    }

    /// Decode one bounded closed-format document. This does not establish
    /// ownership or existence of any Task and performs no network or file I/O.
    pub fn decode(bytes: &[u8]) -> Result<Self, ManagedTaskCheckpointError> {
        if bytes.len() > MAX_TASK_WATCH_CHECKPOINT_BYTES {
            return Err(ManagedTaskCheckpointError::TooLarge);
        }
        // Serde's derived struct visitor also supports positional sequences.
        // The portable format is an object, not an order-dependent tuple.
        if bytes
            .iter()
            .copied()
            .find(|byte| !byte.is_ascii_whitespace())
            != Some(b'{')
        {
            return Err(ManagedTaskCheckpointError::InvalidDocument);
        }
        let wire: CheckpointWire = serde_json::from_slice(bytes)
            .map_err(|_| ManagedTaskCheckpointError::InvalidDocument)?;
        if wire.format != CHECKPOINT_FORMAT || wire.version != CHECKPOINT_VERSION {
            return Err(ManagedTaskCheckpointError::UnsupportedFormat);
        }
        if wire.protocol_version != FINAL_PROTOCOL_VERSION {
            return Err(ManagedTaskCheckpointError::UnsupportedProtocol);
        }
        let resource = CanonicalHttpUrl::parse(&wire.resource)
            .map_err(|_| ManagedTaskCheckpointError::InvalidResource)?;
        if resource.as_str() != wire.resource {
            return Err(ManagedTaskCheckpointError::InvalidResource);
        }
        Self::new(&resource, wire.task_ids)
    }

    /// Encode a complete portable selection for host-owned storage. No runtime
    /// state, deadline, token, client policy or Task contents enters the bytes.
    pub fn encode(&self) -> Result<Vec<u8>, ManagedTaskCheckpointError> {
        let wire = CheckpointWire {
            format: CHECKPOINT_FORMAT.to_owned(),
            version: CHECKPOINT_VERSION,
            protocol_version: FINAL_PROTOCOL_VERSION.to_owned(),
            resource: self.resource.as_str().to_owned(),
            task_ids: self.task_ids.clone(),
        };
        let mut writer = BoundedWriter {
            bytes: Vec::new(),
            maximum: MAX_TASK_WATCH_CHECKPOINT_BYTES,
        };
        serde_json::to_writer(&mut writer, &wire)
            .map_err(|_| ManagedTaskCheckpointError::TooLarge)?;
        Ok(writer.bytes)
    }

    /// Exact, canonical resource to inspect before explicitly choosing a login.
    /// Restore never constructs a client or discovers an endpoint from this URL.
    pub fn resource(&self) -> &CanonicalHttpUrl {
        &self.resource
    }

    /// All originally selected IDs, in reconciliation order. Completed IDs are
    /// not suppressed using untrusted persisted state after a restart.
    pub fn task_ids(&self) -> &[TaskId] {
        &self.task_ids
    }

    fn admit_resource(
        &self,
        resource: &CanonicalHttpUrl,
    ) -> Result<(), ManagedTaskCheckpointError> {
        if self.resource.as_str() != resource.as_str() {
            return Err(ManagedTaskCheckpointError::ResourceMismatch);
        }
        Ok(())
    }
}

impl ManagedTaskWatch {
    /// Export the original selection, including Tasks whose terminal snapshots
    /// were already delivered. Works after close/failure too; it does not revive
    /// the old stream, extend its deadline or grant authority to replay inputs.
    pub fn checkpoint(&self) -> Result<ManagedTaskWatchCheckpoint, ManagedTaskCheckpointError> {
        self.client
            .task_watch_checkpoint(self.state.task_ids.clone())
    }
}

impl ManagedTasksClient {
    /// Prepare restartable observation for known, already-created Task IDs.
    /// Persist this before starting a recovering or input-driving watch when
    /// the host needs to retain the selection independently of that owner.
    /// It is not available for an uncertain creation with no admitted Task ID.
    pub fn task_watch_checkpoint(
        &self,
        task_ids: Vec<TaskId>,
    ) -> Result<ManagedTaskWatchCheckpoint, ManagedTaskCheckpointError> {
        ManagedTaskWatchCheckpoint::new(self.session.resource(), task_ids)
    }

    /// Start a fresh observation from a checkpoint using THIS explicitly
    /// selected managed session. Exact resource equality is checked before
    /// credential acquisition or network access. Current login validity, Tasks
    /// discovery, full subscription acknowledgement and every authorized get
    /// are enforced by the ordinary watch path, never by saved data.
    ///
    /// Supply a new ID prefix and explicit finite observation policy. Old
    /// monotonic deadlines and delivery ledgers are not portable across restart.
    pub async fn resume_task_watch(
        &self,
        cx: &Cx,
        checkpoint: &ManagedTaskWatchCheckpoint,
        id_prefix: String,
        policy: ManagedTaskWatchPolicy,
    ) -> Result<ManagedTaskWatch, ManagedTaskCheckpointError> {
        self.resume_task_watch_with_cancellation(
            cx,
            &McpRequestCancellation::new(),
            checkpoint,
            id_prefix,
            policy,
        )
        .await
    }

    /// Cancellation remains local to observation; no remote cancellation or
    /// mutation is sent while restoring, reading, closing or dropping a watch.
    pub async fn resume_task_watch_with_cancellation(
        &self,
        cx: &Cx,
        cancellation: &McpRequestCancellation,
        checkpoint: &ManagedTaskWatchCheckpoint,
        id_prefix: String,
        policy: ManagedTaskWatchPolicy,
    ) -> Result<ManagedTaskWatch, ManagedTaskCheckpointError> {
        checkpoint.admit_resource(self.session.resource())?;
        Ok(self
            .watch_tasks_with_cancellation(
                cx,
                cancellation,
                checkpoint.task_ids.clone(),
                id_prefix,
                policy,
            )
            .await?)
    }

    /// Restore with the existing bounded, observation-only reconnect policy.
    /// The new finite watch budget spans all reconnects; checkpoint restore is
    /// not an automatic way to reset an exhausted owner's limits.
    pub async fn resume_task_watch_recovering(
        &self,
        cx: &Cx,
        checkpoint: &ManagedTaskWatchCheckpoint,
        id_prefix: String,
        policy: ManagedTaskWatchPolicy,
        recovery: ManagedTaskRecoveryPolicy,
    ) -> Result<RecoveringManagedTaskWatch, ManagedTaskCheckpointError> {
        self.resume_task_watch_recovering_with_cancellation(
            cx,
            &McpRequestCancellation::new(),
            checkpoint,
            id_prefix,
            policy,
            recovery,
        )
        .await
    }

    /// Restored admission, backoff and reconciliation share one caller-owned
    /// cancellation domain and preserve typed recovery/admission diagnostics.
    pub async fn resume_task_watch_recovering_with_cancellation(
        &self,
        cx: &Cx,
        cancellation: &McpRequestCancellation,
        checkpoint: &ManagedTaskWatchCheckpoint,
        id_prefix: String,
        policy: ManagedTaskWatchPolicy,
        recovery: ManagedTaskRecoveryPolicy,
    ) -> Result<RecoveringManagedTaskWatch, ManagedTaskCheckpointError> {
        checkpoint.admit_resource(self.session.resource())?;
        Ok(self
            .watch_tasks_recovering_with_cancellation(
                cx,
                cancellation,
                checkpoint.task_ids.clone(),
                id_prefix,
                policy,
                recovery,
            )
            .await?)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn resource() -> CanonicalHttpUrl {
        CanonicalHttpUrl::parse("https://service.example/mcp").unwrap()
    }
    fn id(value: &str) -> TaskId {
        TaskId::parse(value).unwrap()
    }
    fn document() -> serde_json::Value {
        json!({"format":CHECKPOINT_FORMAT, "version":1, "protocolVersion":FINAL_PROTOCOL_VERSION,
            "resource":"https://service.example/mcp", "taskIds":["second", "first"]})
    }

    #[test]
    fn checkpoint_round_trip_preserves_exact_resource_and_selection_order() {
        let saved =
            ManagedTaskWatchCheckpoint::new(&resource(), vec![id("second"), id("first")]).unwrap();
        let encoded = saved.encode().unwrap();
        assert_eq!(
            serde_json::from_slice::<serde_json::Value>(&encoded).unwrap(),
            document()
        );
        let decoded = ManagedTaskWatchCheckpoint::decode(&encoded).unwrap();
        assert_eq!(decoded.resource(), &resource());
        assert_eq!(decoded.task_ids(), [id("second"), id("first")]);
        assert_eq!(decoded.encode().unwrap(), encoded);
        let debug = format!("{decoded:?}");
        assert!(debug.contains("task_count: 2"));
        for secret in ["service.example", "second", "first"] {
            assert!(!debug.contains(secret));
        }
    }

    #[test]
    fn checkpoint_requires_an_object_even_when_a_sequence_has_all_valid_fields() {
        let object = document().to_string();
        assert!(ManagedTaskWatchCheckpoint::decode(object.as_bytes()).is_ok());
        let sequence = json!([
            CHECKPOINT_FORMAT,
            1,
            FINAL_PROTOCOL_VERSION,
            "https://service.example/mcp",
            ["second", "first"]
        ])
        .to_string();
        assert!(matches!(
            ManagedTaskWatchCheckpoint::decode(sequence.as_bytes()),
            Err(ManagedTaskCheckpointError::InvalidDocument)
        ));
    }

    #[test]
    fn checkpoint_rejects_duplicate_unknown_missing_and_trailing_members() {
        let encoded = document().to_string();
        assert!(ManagedTaskWatchCheckpoint::decode(encoded.as_bytes()).is_ok());
        for suffix in [
            r#", "version":1"#,
            r#", "ver\u0073ion":1"#,
            r#", "taskIds":["second","first"]"#,
            r#", "terminal":[true,true]"#,
            r#", "accessToken":"secret""#,
            r#", "requestState":"secret""#,
        ] {
            let invalid = format!("{}{suffix}}}", &encoded[..encoded.len() - 1]);
            assert!(matches!(
                ManagedTaskWatchCheckpoint::decode(invalid.as_bytes()),
                Err(ManagedTaskCheckpointError::InvalidDocument)
            ));
        }
        for field in [
            "format",
            "version",
            "protocolVersion",
            "resource",
            "taskIds",
        ] {
            let mut missing = document();
            missing.as_object_mut().unwrap().remove(field);
            assert!(matches!(
                ManagedTaskWatchCheckpoint::decode(missing.to_string().as_bytes()),
                Err(ManagedTaskCheckpointError::InvalidDocument)
            ));
        }
        for invalid in [format!("{encoded}{{}}"), "null".to_owned(), "[]".to_owned()] {
            assert!(matches!(
                ManagedTaskWatchCheckpoint::decode(invalid.as_bytes()),
                Err(ManagedTaskCheckpointError::InvalidDocument)
            ));
        }
    }

    #[test]
    fn checkpoint_format_and_era_cannot_select_a_legacy_or_future_path() {
        for (field, value) in [
            ("format", json!("other")),
            ("version", json!(0)),
            ("version", json!(2)),
        ] {
            let mut invalid = document();
            invalid[field] = value;
            assert!(matches!(
                ManagedTaskWatchCheckpoint::decode(invalid.to_string().as_bytes()),
                Err(ManagedTaskCheckpointError::UnsupportedFormat)
            ));
        }
        for era in ["2024-11-05", "2025-11-25", "unknown"] {
            let mut invalid = document();
            invalid["protocolVersion"] = json!(era);
            assert!(matches!(
                ManagedTaskWatchCheckpoint::decode(invalid.to_string().as_bytes()),
                Err(ManagedTaskCheckpointError::UnsupportedProtocol)
            ));
        }
    }

    #[test]
    fn checkpoint_selection_reuses_live_watch_cardinality_and_uniqueness_rules() {
        for count in [1, MAX_WATCH_TASKS] {
            let ids = (0..count).map(|n| id(&format!("task-{n}"))).collect();
            let checkpoint = ManagedTaskWatchCheckpoint::new(&resource(), ids).unwrap();
            assert_eq!(
                ManagedTaskWatchCheckpoint::decode(&checkpoint.encode().unwrap())
                    .unwrap()
                    .task_ids()
                    .len(),
                count
            );
        }
        for ids in [
            vec![],
            vec![id("one"), id("one")],
            (0..=MAX_WATCH_TASKS)
                .map(|n| id(&format!("task-{n}")))
                .collect(),
        ] {
            let mut invalid = document();
            invalid["taskIds"] = json!(ids);
            assert!(matches!(
                ManagedTaskWatchCheckpoint::decode(invalid.to_string().as_bytes()),
                Err(ManagedTaskCheckpointError::InvalidSelection)
            ));
        }
    }

    #[test]
    fn checkpoint_resource_is_canonical_and_restore_checks_the_full_endpoint() {
        let checkpoint = ManagedTaskWatchCheckpoint::new(&resource(), vec![id("one")]).unwrap();
        assert!(checkpoint.admit_resource(&resource()).is_ok());
        for different in [
            "http://service.example/mcp",
            "https://other.example/mcp",
            "https://service.example:444/mcp",
            "https://service.example/other",
            "https://service.example/mcp?tenant=other",
        ] {
            assert!(matches!(
                checkpoint.admit_resource(&CanonicalHttpUrl::parse(different).unwrap()),
                Err(ManagedTaskCheckpointError::ResourceMismatch)
            ));
        }
        for repaired in [
            "https://SERVICE.example/mcp",
            "https://service.example:443/mcp",
            "not-a-url",
        ] {
            let mut invalid = document();
            invalid["resource"] = json!(repaired);
            assert!(matches!(
                ManagedTaskWatchCheckpoint::decode(invalid.to_string().as_bytes()),
                Err(ManagedTaskCheckpointError::InvalidResource)
            ));
        }
    }

    #[test]
    fn checkpoint_byte_limit_is_enforced_before_parsing_without_reflecting_input() {
        let mut bytes = document().to_string().into_bytes();
        bytes.resize(MAX_TASK_WATCH_CHECKPOINT_BYTES, b' ');
        assert!(ManagedTaskWatchCheckpoint::decode(&bytes).is_ok());
        bytes.push(b' ');
        assert!(matches!(
            ManagedTaskWatchCheckpoint::decode(&bytes),
            Err(ManagedTaskCheckpointError::TooLarge)
        ));
        assert!(ManagedTaskWatchCheckpoint::decode(&[0xff]).is_err());
        let error = ManagedTaskWatchCheckpoint::decode(b"secret-not-json").unwrap_err();
        assert!(!format!("{error:?} {error}").contains("secret"));
    }
}