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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
//! Bounded complete catalog collection, with optional credential-local caching.
//!
//! The four core catalog methods share cursor handling, per-page protocol
//! admission, and whole-collection budgets. Only cursor changes between pages.
//! A returned collection contains every remaining page or no pages at all;
//! notifications are delivered immediately even when a later page fails.
//!
//! Caching is explicitly enabled with `with_cache_limits`. Each client owns one
//! cache bound to one managed login. Clones share that cache. All encoded request
//! parameters, including metadata, participate in its conservative exact-request
//! identity; this is not the general all-and-only-semantic cache projection.
//! Credentials never enter a cache key. Public peer hints do not enable sharing.
//!
//! Feed notifications received outside these catalog calls to
//! `invalidate_notification`, and call `clear` after a subscription gap or a
//! local policy change. Those operations also fence collections already running.
//! The default policy permits fresh cached pages beside newly fetched pages.
//! `RefreshWholeCatalog` instead rebuilds from the first page after a cache miss
//! or observed invalidation. Rebuilds share all operation budgets and never retry
//! transport, protocol, authorization, or host errors. Neither policy supplies
//! server-side snapshot isolation or gap recovery.
//! Local bearer revocation is checked even on cache-only paths. It cannot recall
//! results already returned, and does not wake an idle socket by itself; caller
//! cancellation, session closure and the response deadlines own those wakes.

use std::collections::HashSet;
use std::fmt;
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::Instant;

use asupersync::Cx;
use fastmcp_core::McpRequestCancellation;
use fastmcp_protocol::{
    CacheScope, CoreRequest, CoreResult, FINAL_PROTOCOL_VERSION, FinalCoreRequest, FinalCoreResult,
    FinalListParams, RequestId, ServerNotification,
};

use super::{
    ManagedCoreError, ManagedCoreEvent, ManagedCoreLimits, ManagedOAuthSession, bounded_wait,
    call_deadline, check_call, prepare,
};
use crate::cache::{
    CachePartitionKey, FinalCacheGeneration, FinalCacheInsert, FinalCacheKey, FinalCacheLookup,
    FinalCacheResultSet, FinalCacheStats, FinalResultCache, MAX_FINAL_CACHE_CAPACITY,
    MAX_FINAL_CACHE_MAX_BYTES, final_cache_hints,
};
use crate::http_auth::BoundBearerCredential;

/// Subscription-driven full-catalog reconciliation with bounded restart policy.
pub mod watch;

/// One budget spanning all pages, notifications, cache hits and host callbacks.
/// `core` supplies the request/frame/cumulative-payload/notification/time bounds.
/// State bytes account encoded IDs and decoded opaque cursors; their counts are
/// independently bounded by `maximum_pages`. Native transport bounds still apply.
#[derive(Clone, Copy, Debug)]
pub struct ManagedCatalogLimits {
    core: ManagedCoreLimits,
    maximum_pages: usize,
    maximum_items: usize,
    maximum_state_bytes: usize,
}

impl Default for ManagedCatalogLimits {
    fn default() -> Self {
        Self {
            core: ManagedCoreLimits::default(),
            maximum_pages: 128,
            maximum_items: 100_000,
            maximum_state_bytes: 1024 * 1024,
        }
    }
}

impl ManagedCatalogLimits {
    pub fn new(
        core: ManagedCoreLimits,
        maximum_pages: usize,
        maximum_items: usize,
        maximum_state_bytes: usize,
    ) -> Result<Self, ManagedCatalogError> {
        if !(1..=1024).contains(&maximum_pages)
            || maximum_items > 1_000_000
            || !(1..=8 * 1024 * 1024).contains(&maximum_state_bytes)
        {
            return Err(ManagedCatalogError::InvalidLimits);
        }
        Ok(Self {
            core,
            maximum_pages,
            maximum_items,
            maximum_state_bytes,
        })
    }
}

/// How a complete catalog may combine cached pages with network responses.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum ManagedCatalogConsistency {
    /// Reuse each fresh page independently. An observed invalidation aborts the
    /// operation; a missing or stale page is fetched with its exact cursor.
    #[default]
    PerPage,
    /// Reuse a wholly cached catalog, or fetch the whole catalog from its first
    /// page. A cache miss after a cached prefix or a concurrent invalidation
    /// discards that traversal and consumes one bounded rebuild. An initial
    /// cache miss starts a fresh traversal without consuming a rebuild.
    ///
    /// The initial request must omit its cursor. Page, item, payload, state,
    /// notification, request-ID and deadline budgets span discarded traversals.
    /// This is a local freshness policy, not an atomic server snapshot.
    RefreshWholeCatalog { maximum_rebuilds: usize },
}

/// Sanitized collection errors do not retain cursors, request IDs, metadata,
/// result contents or host-provided diagnostics.
#[derive(Debug)]
pub enum ManagedCatalogError {
    InvalidLimits,
    NotCatalog,
    InvalidPage,
    PageLimit,
    ItemLimit,
    StateLimit,
    RepeatedCursor,
    CursorNotAllowed,
    RebuildLimit,
    RepeatedRequestId,
    ScopeChanged,
    Invalidated,
    CredentialChanged,
    CredentialRevoked,
    CacheUnavailable,
    AbortedByHost,
    Core(ManagedCoreError),
}

impl fmt::Display for ManagedCatalogError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Core(error) => fmt::Display::fmt(error, f),
            other => f.write_str(match other {
                Self::InvalidLimits => "invalid managed catalog limits",
                Self::NotCatalog => "request is not a modern core catalog list",
                Self::InvalidPage => "catalog result does not match its requested catalog",
                Self::PageLimit => "catalog page limit exceeded",
                Self::ItemLimit => "catalog item limit exceeded",
                Self::StateLimit => "catalog traversal state limit exceeded",
                Self::RepeatedCursor => "catalog peer repeated an opaque cursor",
                Self::CursorNotAllowed => "whole-catalog refresh requires an absent initial cursor",
                Self::RebuildLimit => "catalog refresh rebuild limit exceeded",
                Self::RepeatedRequestId => "catalog request ID was already used in this collection",
                Self::ScopeChanged => "catalog cache scope changed between pages",
                Self::Invalidated => "catalog was invalidated during collection",
                Self::CredentialChanged => "catalog credential changed during collection",
                Self::CredentialRevoked => "catalog credential has been locally revoked",
                Self::CacheUnavailable => "catalog cache state is unavailable",
                Self::AbortedByHost => "catalog collection stopped by the host",
                Self::Core(_) => unreachable!(),
            }),
        }
    }
}
impl std::error::Error for ManagedCatalogError {}
impl From<ManagedCoreError> for ManagedCatalogError {
    fn from(error: ManagedCoreError) -> Self {
        Self::Core(error)
    }
}

/// A fully traversed suffix of one catalog. Starting with an absent cursor
/// collects from the first page; a supplied cursor collects only its suffix.
/// Exact typed pages retain all admitted unknown result members and their wire
/// representation. There is deliberately no synthetic merged result or TTL.
pub struct CollectedCatalog {
    kind: CatalogKind,
    pages: Vec<CoreResult>,
    item_count: usize,
    credential_generation: u64,
    cache_generation: FinalCacheGeneration,
}

impl CollectedCatalog {
    pub fn method(&self) -> &'static str {
        self.kind.method()
    }
    pub fn pages(&self) -> &[CoreResult] {
        &self.pages
    }
    pub fn into_pages(self) -> Vec<CoreResult> {
        self.pages
    }
    pub fn item_count(&self) -> usize {
        self.item_count
    }
    /// Local to this login, not an identity for cross-session result sharing.
    pub fn credential_generation(&self) -> u64 {
        self.credential_generation
    }
}

/// A catalog collector bound immutably to one managed login and limit policy.
/// No background worker, replay of failed requests, or detached fetch is used.
#[derive(Clone)]
pub struct ManagedCatalogClient {
    session: ManagedOAuthSession,
    limits: ManagedCatalogLimits,
    consistency: ManagedCatalogConsistency,
    cache: Arc<Mutex<FinalResultCache>>,
}

impl ManagedCatalogClient {
    /// Creates an uncached collector. The invalidation generation remains active
    /// even while caching is disabled, so notifications still fence collections.
    pub fn new(session: ManagedOAuthSession, limits: ManagedCatalogLimits) -> Self {
        let mut cache = FinalResultCache::default();
        cache.set_enabled(false);
        Self {
            session,
            limits,
            consistency: ManagedCatalogConsistency::default(),
            cache: Arc::new(Mutex::new(cache)),
        }
    }

    /// Selects the collection freshness policy without replacing the shared
    /// cache. Clones keep the policy selected when they were cloned.
    pub fn with_consistency(
        mut self,
        consistency: ManagedCatalogConsistency,
    ) -> Result<Self, ManagedCatalogError> {
        if matches!(consistency, ManagedCatalogConsistency::RefreshWholeCatalog { maximum_rebuilds } if !(1..=16).contains(&maximum_rebuilds))
        {
            return Err(ManagedCatalogError::InvalidLimits);
        }
        self.consistency = consistency;
        Ok(self)
    }

    /// Explicitly enables a fresh bounded cache for this returned client.
    /// Already-created clones keep their existing cache; clones created after
    /// this call share the new cache. The host must propagate external changes.
    pub fn with_cache_limits(
        mut self,
        entries: usize,
        bytes: usize,
    ) -> Result<Self, ManagedCatalogError> {
        if !(1..=MAX_FINAL_CACHE_CAPACITY).contains(&entries)
            || !(1..=MAX_FINAL_CACHE_MAX_BYTES).contains(&bytes)
        {
            return Err(ManagedCatalogError::InvalidLimits);
        }
        self.cache = Arc::new(Mutex::new(FinalResultCache::with_limits(entries, bytes)));
        Ok(self)
    }

    pub fn clear(&self) -> Result<(), ManagedCatalogError> {
        self.cache()?.clear();
        Ok(())
    }

    /// Invalidate before calling the application's notification observer. This
    /// method may also receive validated notifications from a separate listen.
    pub fn invalidate_notification(
        &self,
        notification: &ServerNotification,
    ) -> Result<(), ManagedCatalogError> {
        self.cache()?.invalidate_notification(notification);
        Ok(())
    }

    pub fn cache_stats(&self) -> Result<FinalCacheStats, ManagedCatalogError> {
        Ok(self.cache()?.stats())
    }

    /// Collect every remaining page. The ID supplier runs only for actual POSTs,
    /// never for cache hits. The notification observer is incremental and may
    /// stop the collection; it is called with no cache lock held.
    pub async fn collect<I, O>(
        &self,
        cx: &Cx,
        request: CoreRequest,
        next_id: I,
        observe: O,
    ) -> Result<CollectedCatalog, ManagedCatalogError>
    where
        I: FnMut() -> Result<RequestId, ManagedCatalogError>,
        O: FnMut(Box<ServerNotification>) -> Result<(), ManagedCatalogError>,
    {
        self.collect_with_cancellation(
            cx,
            &McpRequestCancellation::new(),
            request,
            next_id,
            observe,
        )
        .await
    }

    /// One cancellation domain and absolute deadline span the complete operation.
    /// Synchronous callbacks must cooperate; once they return, deadline checks
    /// prevent overdue IDs/notifications from causing a subsequent POST or fill.
    pub async fn collect_with_cancellation<I, O>(
        &self,
        cx: &Cx,
        cancellation: &McpRequestCancellation,
        mut request: CoreRequest,
        mut next_id: I,
        mut observe: O,
    ) -> Result<CollectedCatalog, ManagedCatalogError>
    where
        I: FnMut() -> Result<RequestId, ManagedCatalogError>,
        O: FnMut(Box<ServerNotification>) -> Result<(), ManagedCatalogError>,
    {
        let deadline = call_deadline(cx, cancellation, self.limits.core.timeout)?;
        let kind = CatalogKind::of(&request)?;
        let maximum_rebuilds = match self.consistency {
            ManagedCatalogConsistency::PerPage => None,
            ManagedCatalogConsistency::RefreshWholeCatalog { maximum_rebuilds } => {
                if list_params(&request)?.cursor.is_some() {
                    return Err(ManagedCatalogError::CursorNotAllowed);
                }
                Some(maximum_rebuilds)
            }
        };
        // Reuse the actual RPC preparation boundary before any credential read.
        // The provisional ID does not escape into the transport or ID history.
        let _ = prepare(
            self.session.resource().as_str(),
            request.clone(),
            RequestId::Number(0),
            self.limits.core,
        )?;
        let mut state = Traversal::new(list_params(&request)?.cursor.as_deref(), self.limits)?;
        Box::pin(bounded_wait(cx, cancellation, deadline, async {
            Ok(async {
                let credential = self
                    .session
                    .credential_with_cancellation(cx, cancellation)
                    .await
                    .map_err(ManagedCoreError::from)?;
                require_unrevoked(credential.credential())?;
                let generation = credential.generation();
                let result_set = kind.result_set();
                let mut rebuilds = 0;
                let mut bypass_cache = false;
                loop {
                    let mut cache_generation = self.cache()?.begin_fetch(&result_set);
                    let mut pages = Vec::new();
                    let initial_items = state.items;
                    let mut cache_writes = true;
                    let mut host_failed = false;
                    let attempt = async {
                        loop {
                            check_call(cx, cancellation, deadline)?;
                            require_unrevoked(credential.credential())?;
                            self.require_generation(&result_set, cache_generation)?;
                            if state.pages >= self.limits.maximum_pages {
                                return Err(ManagedCatalogError::PageLimit);
                            }
                            let key =
                                cache_key(self.session.resource().as_str(), &request, generation)?;
                            let lookup = if bypass_cache {
                                FinalCacheLookup::Miss(crate::cache::FinalCacheMiss::Disabled)
                            } else {
                                self.cache()?.lookup(&key)
                            };
                            let (result, receipt, fetched) = match lookup {
                                FinalCacheLookup::Fresh(result) => {
                                    state.pages += 1;
                                    // A replay has no JSON-RPC envelope or notifications;
                                    // charge its complete retained result to the same
                                    // aggregate payload budget used by the RPC decoder.
                                    let bytes = result
                                        .encode()
                                        .map_err(|_| ManagedCatalogError::InvalidPage)?
                                        .len();
                                    state.charge_bytes(bytes, self.limits.core.total_bytes)?;
                                    (result, Instant::now(), false)
                                }
                                FinalCacheLookup::Miss(_) => {
                                    if maximum_rebuilds.is_some() && !bypass_cache {
                                        if !pages.is_empty() {
                                            return Err(ManagedCatalogError::Invalidated);
                                        }
                                        // Start with one fresh result-set generation and
                                        // bypass every remaining cached continuation.
                                        let mut cache = self.cache()?;
                                        if cache.begin_fetch(&result_set) != cache_generation {
                                            return Err(ManagedCatalogError::Invalidated);
                                        }
                                        cache.invalidate_result_set(&result_set);
                                        cache_generation = cache.begin_fetch(&result_set);
                                        bypass_cache = true;
                                    }
                                    state.pages += 1;
                                    let id = next_id().inspect_err(|_| host_failed = true)?;
                                    check_call(cx, cancellation, deadline)?;
                                    // Host callbacks can revoke a shared credential or
                                    // invalidate this catalog without yielding first.
                                    require_unrevoked(credential.credential())?;
                                    self.require_generation(&result_set, cache_generation)?;
                                    state.reserve_id(&id, self.limits.maximum_state_bytes)?;
                                    // This is the existing one-POST core API, not a new
                                    // response parser. Carry its counters across pages.
                                    let mut call =
                                        Box::pin(self.session.request_core_with_cancellation(
                                            cx,
                                            cancellation,
                                            request.clone(),
                                            id,
                                            self.limits.core,
                                        ))
                                        .await?;
                                    if call.credential_generation() != generation {
                                        return Err(ManagedCatalogError::CredentialChanged);
                                    }
                                    call.deadline = deadline;
                                    call.decoder.bytes = state.bytes;
                                    call.decoder.notifications = state.notifications;
                                    let result = loop {
                                        let event = call
                                            .next_event(cx)
                                            .await?
                                            .ok_or(ManagedCatalogError::InvalidPage)?;
                                        state.bytes = call.decoder.bytes;
                                        state.notifications = call.decoder.notifications;
                                        check_call(cx, cancellation, deadline)?;
                                        require_unrevoked(credential.credential())?;
                                        match event {
                                            ManagedCoreEvent::Notification(notification) => {
                                                self.invalidate_notification(&notification)?;
                                                observe(notification)
                                                    .inspect_err(|_| host_failed = true)?;
                                                check_call(cx, cancellation, deadline)?;
                                                require_unrevoked(credential.credential())?;
                                                self.require_generation(
                                                    &result_set,
                                                    cache_generation,
                                                )?;
                                            }
                                            ManagedCoreEvent::Result(result) => break *result,
                                        }
                                    };
                                    (result, Instant::now(), true)
                                }
                            };
                            self.require_generation(&result_set, cache_generation)?;
                            let facts = page_facts(kind, &result)?;
                            let next = state.admit_page(facts, self.limits)?;
                            // Holding one shared cache guard makes the invalidation
                            // comparison and fill indivisible with respect to clears.
                            check_call(cx, cancellation, deadline)?;
                            {
                                let mut cache = self.cache()?;
                                if cache.begin_fetch(&result_set) != cache_generation {
                                    return Err(ManagedCatalogError::Invalidated);
                                }
                                require_unrevoked(credential.credential())?;
                                if state.cache_ambiguous && cache_writes {
                                    if maximum_rebuilds.is_some() && !bypass_cache {
                                        // A cached cycle cannot authorize mixing its
                                        // cached prefix with newly fetched successors.
                                        return Err(ManagedCatalogError::Invalidated);
                                    }
                                    // Repeated opaque cursors still require another
                                    // POST. Their pages share a cache key, so retaining
                                    // or replaying one would invent pagination progress.
                                    cache.invalidate_result_set(&result_set);
                                    cache_generation = cache.begin_fetch(&result_set);
                                    cache_writes = false;
                                    bypass_cache = true;
                                }
                                if fetched && cache.is_enabled() && cache_writes {
                                    if cache.insert_if_current_at(
                                        key,
                                        cache_generation,
                                        result.clone(),
                                        receipt,
                                    ) == FinalCacheInsert::InvalidatedDuringFetch
                                    {
                                        return Err(ManagedCatalogError::Invalidated);
                                    }
                                }
                            }
                            require_unrevoked(credential.credential())?;
                            pages.push(result);
                            let Some(cursor) = next else { break };
                            list_params_mut(&mut request)?.cursor = Some(cursor);
                        }
                        // Verify that a cached collection did not outlive its login or
                        // cross a renewal while callbacks/other page fetches were active.
                        require_unrevoked(credential.credential())?;
                        let current = self
                            .session
                            .credential_with_cancellation(cx, cancellation)
                            .await
                            .map_err(ManagedCoreError::from)?;
                        if current.generation() != generation {
                            return Err(ManagedCatalogError::CredentialChanged);
                        }
                        self.require_generation(&result_set, cache_generation)?;
                        check_call(cx, cancellation, deadline)?;
                        require_unrevoked(credential.credential())?;
                        require_unrevoked(current.credential())?;
                        Ok(CollectedCatalog {
                            kind,
                            pages,
                            item_count: state.items - initial_items,
                            credential_generation: generation,
                            cache_generation,
                        })
                    }
                    .await;
                    match attempt {
                        Err(ManagedCatalogError::Invalidated)
                            if maximum_rebuilds.is_some() && !host_failed =>
                        {
                            check_call(cx, cancellation, deadline)?;
                            require_unrevoked(credential.credential())?;
                            if rebuilds >= maximum_rebuilds.unwrap_or(0) {
                                return Err(ManagedCatalogError::RebuildLimit);
                            }
                            rebuilds += 1;
                            self.cache()?.invalidate_result_set(&result_set);
                            list_params_mut(&mut request)?.cursor = None;
                            state.scope = None;
                            state.cursors.clear();
                            state.cache_ambiguous = false;
                            bypass_cache = true;
                        }
                        result => return result,
                    }
                }
            }
            .await)
        }))
        .await?
    }

    fn cache(&self) -> Result<MutexGuard<'_, FinalResultCache>, ManagedCatalogError> {
        self.cache
            .lock()
            .map_err(|_| ManagedCatalogError::CacheUnavailable)
    }

    fn require_generation(
        &self,
        result_set: &FinalCacheResultSet,
        expected: FinalCacheGeneration,
    ) -> Result<(), ManagedCatalogError> {
        if self.cache()?.begin_fetch(result_set) != expected {
            return Err(ManagedCatalogError::Invalidated);
        }
        Ok(())
    }
}

// A cache hit constructs no Authorization header, so transport-side revocation
// admission alone is insufficient. Read the shared lineage directly without
// allocating a secret-bearing header. A concurrent revoke after the final check
// may follow an already-admitted result; returned data cannot be recalled.
fn require_unrevoked(credential: &BoundBearerCredential) -> Result<(), ManagedCatalogError> {
    if credential.is_revoked() {
        return Err(ManagedCatalogError::CredentialRevoked);
    }
    Ok(())
}

#[derive(Clone, Copy)]
enum CatalogKind {
    Tools,
    Resources,
    Templates,
    Prompts,
}
impl CatalogKind {
    fn of(request: &CoreRequest) -> Result<Self, ManagedCatalogError> {
        match request {
            CoreRequest::Final(FinalCoreRequest::ToolsList(_)) => Ok(Self::Tools),
            CoreRequest::Final(FinalCoreRequest::ResourcesList(_)) => Ok(Self::Resources),
            CoreRequest::Final(FinalCoreRequest::ResourceTemplatesList(_)) => Ok(Self::Templates),
            CoreRequest::Final(FinalCoreRequest::PromptsList(_)) => Ok(Self::Prompts),
            _ => Err(ManagedCatalogError::NotCatalog),
        }
    }
    fn method(self) -> &'static str {
        match self {
            Self::Tools => "tools/list",
            Self::Resources => "resources/list",
            Self::Templates => "resources/templates/list",
            Self::Prompts => "prompts/list",
        }
    }
    fn result_set(self) -> FinalCacheResultSet {
        match self {
            Self::Tools => FinalCacheResultSet::Tools,
            Self::Resources => FinalCacheResultSet::Resources,
            Self::Templates => FinalCacheResultSet::ResourceTemplates,
            Self::Prompts => FinalCacheResultSet::Prompts,
        }
    }
}

fn list_params(request: &CoreRequest) -> Result<&FinalListParams, ManagedCatalogError> {
    match request {
        CoreRequest::Final(
            FinalCoreRequest::ToolsList(params)
            | FinalCoreRequest::ResourcesList(params)
            | FinalCoreRequest::ResourceTemplatesList(params)
            | FinalCoreRequest::PromptsList(params),
        ) => Ok(params),
        _ => Err(ManagedCatalogError::NotCatalog),
    }
}
fn list_params_mut(request: &mut CoreRequest) -> Result<&mut FinalListParams, ManagedCatalogError> {
    match request {
        CoreRequest::Final(
            FinalCoreRequest::ToolsList(params)
            | FinalCoreRequest::ResourcesList(params)
            | FinalCoreRequest::ResourceTemplatesList(params)
            | FinalCoreRequest::PromptsList(params),
        ) => Ok(params),
        _ => Err(ManagedCatalogError::NotCatalog),
    }
}

fn cache_key(
    target: &str,
    request: &CoreRequest,
    generation: u64,
) -> Result<FinalCacheKey, ManagedCatalogError> {
    let kind = CatalogKind::of(request)?;
    let params = request
        .encode_params()
        .map_err(|_| ManagedCoreError::InvalidRequest)?
        .ok_or(ManagedCoreError::InvalidRequest)?;
    let encoded = serde_json::to_string(&params).map_err(|_| ManagedCoreError::InvalidRequest)?;
    Ok(FinalCacheKey::new(
        target,
        FINAL_PROTOCOL_VERSION,
        "included-in-exact-params",
        "core-only",
        kind.method(),
        encoded,
        list_params(request)?.cursor.clone(),
        0,
        0,
        0,
        0,
        CachePartitionKey::new(format!("managed-catalog-generation-{generation}")),
        kind.result_set(),
    ))
}

struct PageFacts<'a> {
    count: usize,
    cursor: Option<&'a str>,
    scope: CacheScope,
}
fn page_facts(
    kind: CatalogKind,
    result: &CoreResult,
) -> Result<PageFacts<'_>, ManagedCatalogError> {
    let (count, cursor) = match (kind, result) {
        (CatalogKind::Tools, CoreResult::Final(FinalCoreResult::ToolsList { result, .. })) => (
            result.payload.tools.len(),
            result.payload.next_cursor.as_deref(),
        ),
        (
            CatalogKind::Resources,
            CoreResult::Final(FinalCoreResult::ResourcesList { result, .. }),
        ) => (
            result.payload.resources.len(),
            result.payload.next_cursor.as_deref(),
        ),
        (
            CatalogKind::Templates,
            CoreResult::Final(FinalCoreResult::ResourceTemplatesList { result, .. }),
        ) => (
            result.payload.resource_templates.len(),
            result.payload.next_cursor.as_deref(),
        ),
        (CatalogKind::Prompts, CoreResult::Final(FinalCoreResult::PromptsList { result, .. })) => (
            result.payload.prompts.len(),
            result.payload.next_cursor.as_deref(),
        ),
        _ => return Err(ManagedCatalogError::InvalidPage),
    };
    let (_, scope) = final_cache_hints(result).ok_or(ManagedCatalogError::InvalidPage)?;
    Ok(PageFacts {
        count,
        cursor,
        scope,
    })
}

#[derive(Default)]
struct Traversal {
    cursors: HashSet<String>,
    cache_ambiguous: bool,
    ids: Vec<RequestId>,
    pages: usize,
    state_bytes: usize,
    items: usize,
    bytes: usize,
    notifications: usize,
    scope: Option<CacheScope>,
}
impl Traversal {
    fn new(
        cursor: Option<&str>,
        limits: ManagedCatalogLimits,
    ) -> Result<Self, ManagedCatalogError> {
        let mut state = Self::default();
        if let Some(cursor) = cursor {
            state.charge_state(cursor.len().saturating_add(1), limits.maximum_state_bytes)?;
            state.cursors.insert(cursor.to_owned());
        }
        Ok(state)
    }
    fn charge_state(&mut self, bytes: usize, maximum: usize) -> Result<(), ManagedCatalogError> {
        if bytes > maximum.saturating_sub(self.state_bytes) {
            return Err(ManagedCatalogError::StateLimit);
        }
        self.state_bytes += bytes;
        Ok(())
    }
    fn reserve_id(&mut self, id: &RequestId, maximum: usize) -> Result<(), ManagedCatalogError> {
        id.validate()
            .map_err(|_| ManagedCoreError::InvalidRequest)?;
        if self.ids.iter().any(|used| used.correlates_with(id)) {
            return Err(ManagedCatalogError::RepeatedRequestId);
        }
        let bytes = serde_json::to_string(id)
            .map_err(|_| ManagedCoreError::InvalidRequest)?
            .len();
        self.charge_state(bytes, maximum)?;
        self.ids.push(id.clone());
        Ok(())
    }
    fn charge_bytes(&mut self, bytes: usize, maximum: usize) -> Result<(), ManagedCatalogError> {
        if bytes > maximum.saturating_sub(self.bytes) {
            return Err(ManagedCoreError::ResponseByteLimit.into());
        }
        self.bytes += bytes;
        Ok(())
    }
    fn admit_page(
        &mut self,
        page: PageFacts<'_>,
        limits: ManagedCatalogLimits,
    ) -> Result<Option<String>, ManagedCatalogError> {
        if self.scope.is_some_and(|scope| scope != page.scope) {
            return Err(ManagedCatalogError::ScopeChanged);
        }
        if page.count > limits.maximum_items.saturating_sub(self.items) {
            return Err(ManagedCatalogError::ItemLimit);
        }
        if let Some(cursor) = page.cursor {
            self.charge_state(cursor.len().saturating_add(1), limits.maximum_state_bytes)?;
            // Equality affects cache eligibility only, never cursor progression
            // or collection termination. All cursor bytes remain opaque.
            self.cache_ambiguous |= !self.cursors.insert(cursor.to_owned());
        }
        self.items += page.count;
        self.scope = Some(page.scope);
        Ok(page.cursor.map(str::to_owned))
    }
}

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

    fn request(method: &str, params: serde_json::Value) -> CoreRequest {
        let mut params = params;
        params["_meta"] =
            serde_json::to_value(FinalRequestMeta::new(ClientCapabilities::default())).unwrap();
        CoreRequest::decode(ProtocolEra::Modern2026, method, Some(&params)).unwrap()
    }
    fn result(request: &CoreRequest, fields: &str) -> CoreResult {
        request
            .decode_result(&format!(
                r#"{{"resultType":"complete","ttlMs":60000,"cacheScope":"private",{fields}}}"#
            ))
            .unwrap()
    }

    #[test]
    fn every_catalog_uses_its_typed_page_and_exact_unknown_members() {
        for (method, field) in [
            ("tools/list", "tools"),
            ("resources/list", "resources"),
            ("resources/templates/list", "resourceTemplates"),
            ("prompts/list", "prompts"),
        ] {
            let request = request(method, json!({"includeTags":["x"],"excludeTags":[]}));
            let result = result(
                &request,
                &format!(
                    r#""{field}":[],"nextCursor":"","x-retained":{{"z":900719925474099312345,"a":1.20e+4}}"#
                ),
            );
            let facts = page_facts(CatalogKind::of(&request).unwrap(), &result).unwrap();
            assert_eq!(facts.count, 0);
            assert_eq!(facts.cursor, Some(""));
            let encoded = result.encode().unwrap();
            assert!(encoded.contains("1.20e+4") && encoded.contains("900719925474099312345"));
        }
    }

    #[test]
    fn cursor_replacement_does_not_change_other_request_identity() {
        let mut request = request(
            "tools/list",
            json!({"includeTags":["a","b"],"excludeTags":[]}),
        );
        let baseline = request.encode_params().unwrap().unwrap();
        list_params_mut(&mut request).unwrap().cursor = Some("  opaque+/%\0  ".to_owned());
        let mut next = request.encode_params().unwrap().unwrap();
        assert_eq!(next["cursor"], "  opaque+/%\0  ");
        next.as_object_mut().unwrap().remove("cursor");
        assert_eq!(next, baseline);
    }

    #[test]
    fn exact_cache_identity_partitions_cursor_metadata_method_and_credential() {
        let mut request = request("tools/list", json!({}));
        let baseline = cache_key("https://mcp.example/mcp", &request, 1).unwrap();
        assert_ne!(
            baseline,
            cache_key("https://mcp.example/mcp", &request, 2).unwrap()
        );
        assert_ne!(
            baseline,
            cache_key("https://other.example/mcp", &request, 1).unwrap()
        );
        list_params_mut(&mut request).unwrap().cursor = Some(String::new());
        assert_ne!(
            baseline,
            cache_key("https://mcp.example/mcp", &request, 1).unwrap()
        );
        let mut params = request.encode_params().unwrap().unwrap();
        params.as_object_mut().unwrap().remove("cursor");
        params["_meta"]["com.example/tenant"] = json!("other");
        let changed =
            CoreRequest::decode(ProtocolEra::Modern2026, "tools/list", Some(&params)).unwrap();
        assert_ne!(
            baseline,
            cache_key("https://mcp.example/mcp", &changed, 1).unwrap()
        );
    }

    #[test]
    fn repeated_empty_cursors_continue_without_granting_cache_replay() {
        let limits = ManagedCatalogLimits::default();
        let mut state = Traversal::new(None, limits).unwrap();
        let page = || PageFacts {
            count: 1,
            cursor: Some(""),
            scope: CacheScope::Private,
        };
        assert_eq!(
            state.admit_page(page(), limits).unwrap(),
            Some(String::new())
        );
        assert!(!state.cache_ambiguous);
        assert_eq!(
            state.admit_page(page(), limits).unwrap(),
            Some(String::new())
        );
        assert_eq!((state.items, state.state_bytes), (2, 2));
        assert!(state.cache_ambiguous);
        let mut suffix = Traversal::new(Some(""), limits).unwrap();
        assert_eq!(
            suffix.admit_page(page(), limits).unwrap(),
            Some(String::new())
        );
        assert!(suffix.cache_ambiguous);
        assert_eq!(
            suffix
                .admit_page(
                    PageFacts {
                        count: 0,
                        cursor: None,
                        scope: CacheScope::Private
                    },
                    limits
                )
                .unwrap(),
            None
        );
    }

    #[test]
    fn repeated_cursor_bytes_still_consume_the_cumulative_state_bound() {
        let mut limits = ManagedCatalogLimits::default();
        limits.maximum_state_bytes = 2;
        let mut state = Traversal::new(Some(""), limits).unwrap();
        let page = || PageFacts {
            count: 0,
            cursor: Some(""),
            scope: CacheScope::Private,
        };
        assert_eq!(
            state.admit_page(page(), limits).unwrap(),
            Some(String::new())
        );
        assert!(matches!(
            state.admit_page(page(), limits),
            Err(ManagedCatalogError::StateLimit)
        ));
        assert_eq!((state.items, state.state_bytes), (0, 2));
    }

    #[test]
    fn failed_scope_item_and_state_admission_preserves_the_previous_page() {
        let mut limits = ManagedCatalogLimits::default();
        limits.maximum_items = 1;
        limits.maximum_state_bytes = 2;
        let mut state = Traversal::new(None, limits).unwrap();
        state
            .admit_page(
                PageFacts {
                    count: 1,
                    cursor: Some("x"),
                    scope: CacheScope::Private,
                },
                limits,
            )
            .unwrap();
        for (count, cursor, scope) in [
            (0, None, CacheScope::Public),
            (1, None, CacheScope::Private),
            (0, Some("y"), CacheScope::Private),
        ] {
            assert!(
                state
                    .admit_page(
                        PageFacts {
                            count,
                            cursor,
                            scope
                        },
                        limits
                    )
                    .is_err()
            );
            assert_eq!((state.items, state.state_bytes), (1, 2));
            assert_eq!(state.cursors.len(), 1);
        }
    }

    #[test]
    fn numeric_request_aliases_are_not_fresh_and_payload_budget_is_cumulative() {
        let mut state = Traversal::default();
        state.reserve_id(&RequestId::Number(2), 100).unwrap();
        let alias: RequestId = serde_json::from_str("2e0").unwrap();
        assert!(matches!(
            state.reserve_id(&alias, 100),
            Err(ManagedCatalogError::RepeatedRequestId)
        ));
        state
            .reserve_id(&RequestId::String("2".to_owned()), 100)
            .unwrap();
        state.charge_bytes(9, 10).unwrap();
        assert!(matches!(
            state.charge_bytes(2, 10),
            Err(ManagedCatalogError::Core(
                ManagedCoreError::ResponseByteLimit
            ))
        ));
        assert_eq!(state.bytes, 9);
    }

    #[test]
    fn shared_cache_fences_all_pages_after_invalidation_and_clear() {
        let request = request("tools/list", json!({}));
        let key = cache_key("https://mcp.example/mcp", &request, 1).unwrap();
        let mut cache = FinalResultCache::default();
        let generation = cache.begin_fetch(key.result_set());
        let result = result(&request, r#""tools":[]"#);
        assert_eq!(
            cache.insert_if_current(key.clone(), generation, result.clone()),
            FinalCacheInsert::Stored
        );
        cache.invalidate_result_set(&FinalCacheResultSet::Tools);
        assert_eq!(
            cache.insert_if_current(key.clone(), generation, result.clone()),
            FinalCacheInsert::InvalidatedDuringFetch
        );
        let generation = cache.begin_fetch(key.result_set());
        cache.clear();
        assert_eq!(
            cache.insert_if_current(key, generation, result),
            FinalCacheInsert::InvalidatedDuringFetch
        );
    }

    #[test]
    fn revoked_lineage_cannot_admit_cached_data_without_an_authorization_header() {
        let resource =
            crate::http_auth::CanonicalHttpUrl::parse("https://mcp.example/mcp").unwrap();
        let credential = BoundBearerCredential::bind(resource, "test-revocation-canary").unwrap();
        let shared = credential.clone();
        assert!(require_unrevoked(&credential).is_ok());
        shared.revoke();
        for credential in [credential, shared] {
            let error = require_unrevoked(&credential).unwrap_err();
            assert!(matches!(error, ManagedCatalogError::CredentialRevoked));
            assert!(!format!("{error:?} {error}").contains("test-revocation-canary"));
        }
    }
}