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
//! One-shot repair of a trusted, pre-dispatch tool-header rejection.
//!
//! A missing reply is not evidence that a tool did not execute. This module
//! creates repair custody only from a complete, strictly admitted HTTP 400 JSON
//! error with code -32020 and the exact attempted request ID, received through
//! the managed session for an independently trusted endpoint. A 200 error, an
//! opaque body, a redirect, malformed data, or interrupted I/O never qualifies.
//!
//! The host explicitly consumes that custody to refresh the complete uncached
//! catalog, approve the new definition and every disclosed path, and send the
//! original invocation once with a fresh ID. There is no third tool attempt,
//! automatic input resolution, durable recovery, or mutation of old tool handles.

use std::collections::HashSet;
use std::fmt;
use std::io::{self, Write};
use std::sync::Arc;

/// Caller-driven continuations with repair policy fixed before the first POST.
pub mod interaction;

use asupersync::{Cx, types::Time};
use fastmcp_core::{CanonicalHttpUrl, McpRequestCancellation};
use fastmcp_protocol::http_headers::ParameterHeaderBinding;
use fastmcp_protocol::protocol_policy::ProtocolEra;
use fastmcp_protocol::{
    CoreRequest, CoreResult, FINAL_CLIENT_CAPABILITIES_META_KEY, FINAL_PROTOCOL_VERSION,
    FINAL_PROTOCOL_VERSION_META_KEY, FinalCoreRequest, FinalCoreResult, FinalTool,
    HEADER_MISMATCH_ERROR_CODE, JsonInteger, RequestId, decode_strict_jsonrpc_response,
};
use serde_json::json;

use super::super::catalog::{ManagedCatalogClient, ManagedCatalogError, ManagedCatalogLimits};
use super::super::check_call;
use super::super::interaction::{
    ManagedInteraction, ManagedInteractionError, ManagedInteractionLimits,
};
use super::{
    ManagedCoreCall, ManagedCoreError, ManagedCoreLimits, ManagedOAuthSession,
    ManagedToolHeaderError, ReviewedToolHeaders, ToolHeaderDispatchError, bounded_wait,
    call_deadline, prepare_optional,
};
use crate::http_executor::ModernHttpErrorBodyAdmission;

const MAX_REPAIR_PAGES: usize = 64;
const MAX_REPAIR_TOOLS: usize = 4096;
const MAX_REPAIR_ID_BYTES: usize = 64 * 1024;

/// Trusted deployment configuration, never a server-advertised retry hint.
///
/// Construct only when the endpoint guarantees that HTTP 400/-32020 is emitted
/// before any tool handler, continuation consumption, or application effect.
/// This client verifies the wire response, not the remote implementation. A
/// misconfigured or dishonest endpoint can repeat effects. TLS authenticity,
/// an idempotent annotation, or the error code alone does not prove this contract.
pub struct ToolHeaderRepairContract {
    resource: CanonicalHttpUrl,
}

impl ToolHeaderRepairContract {
    pub fn for_configured_endpoint(
        resource: CanonicalHttpUrl,
    ) -> Result<Self, ToolHeaderRepairError> {
        if resource.scheme() != "https" || resource.has_userinfo() || resource.fragment().is_some()
        {
            return Err(ToolHeaderRepairError::InvalidContract);
        }
        Ok(Self { resource })
    }

    fn admit_endpoint(&self, resource: &CanonicalHttpUrl) -> Result<(), ToolHeaderRepairError> {
        if &self.resource != resource {
            return Err(ToolHeaderRepairError::EndpointMismatch);
        }
        Ok(())
    }
}

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

/// A single lifetime and response-byte budget spanning rejection, refresh and retry.
///
/// The entire `catalog_bytes` allowance is conservatively charged to the final
/// call, even when the catalog uses less. The original rejection is charged at
/// its actual byte size. Configuration leaves room for both full tool frames,
/// so repair cannot start a side effect with no remaining reply capacity.
#[derive(Clone, Copy, Debug)]
pub struct ToolHeaderRepairLimits {
    core: ManagedCoreLimits,
    catalog_bytes: usize,
    catalog_pages: usize,
    catalog_tools: usize,
}

impl Default for ToolHeaderRepairLimits {
    fn default() -> Self {
        Self {
            core: ManagedCoreLimits::default(),
            catalog_bytes: 4 * 1024 * 1024,
            catalog_pages: 16,
            catalog_tools: 1024,
        }
    }
}

impl ToolHeaderRepairLimits {
    pub fn new(
        core: ManagedCoreLimits,
        catalog_bytes: usize,
        catalog_pages: usize,
        catalog_tools: usize,
    ) -> Result<Self, ToolHeaderRepairError> {
        if !(1..=32 * 1024 * 1024).contains(&catalog_bytes)
            || !(1..=MAX_REPAIR_PAGES).contains(&catalog_pages)
            || !(1..=MAX_REPAIR_TOOLS).contains(&catalog_tools)
            || core
                .frame_bytes
                .checked_mul(2)
                .and_then(|n| n.checked_add(catalog_bytes))
                .is_none_or(|n| n > core.total_bytes)
        {
            return Err(ToolHeaderRepairError::InvalidLimits);
        }
        Ok(Self {
            core,
            catalog_bytes,
            catalog_pages,
            catalog_tools,
        })
    }

    fn catalog(self) -> Result<ManagedCatalogLimits, ManagedCatalogError> {
        let mut core = self.core;
        core.frame_bytes = core.frame_bytes.min(self.catalog_bytes);
        core.total_bytes = self.catalog_bytes;
        // Refresh has no observer side effects and accepts no notifications.
        // Observed catalog mutation therefore refuses the whole replacement.
        core.notifications = 0;
        ManagedCatalogLimits::new(
            core,
            self.catalog_pages,
            self.catalog_tools,
            MAX_REPAIR_ID_BYTES,
        )
    }

    fn retry_charge(self, rejected_bytes: usize) -> Result<usize, ManagedCoreError> {
        let charged = rejected_bytes
            .checked_add(self.catalog_bytes)
            .ok_or(ManagedCoreError::ResponseByteLimit)?;
        if self.core.frame_bytes > self.core.total_bytes.saturating_sub(charged) {
            return Err(ManagedCoreError::ResponseByteLimit);
        }
        Ok(charged)
    }
}

/// Fixed diagnostics contain no peer error messages, names, schemas or values.
#[derive(Debug)]
pub enum ToolHeaderRepairError {
    InvalidContract,
    EndpointMismatch,
    InvalidLimits,
    InitialToolCallRequired,
    ToolUnavailable,
    DuplicateTool,
    DefinitionDeclined,
    Interaction(ManagedInteractionError),
    Headers(ToolHeaderDispatchError),
    Catalog(ManagedCatalogError),
    Core(ManagedCoreError),
}

impl fmt::Display for ToolHeaderRepairError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::InvalidContract => "invalid configured tool-header repair contract",
            Self::EndpointMismatch => "tool-header repair contract names another endpoint",
            Self::InvalidLimits => "invalid tool-header repair limits",
            Self::InitialToolCallRequired => "header repair requires an initial modern tool call",
            Self::ToolUnavailable => "refreshed catalog no longer contains the requested tool",
            Self::DuplicateTool => "refreshed catalog contains duplicate tool names",
            Self::DefinitionDeclined => "host declined the refreshed tool definition",
            Self::Interaction(error) => return error.fmt(f),
            Self::Headers(error) => return error.fmt(f),
            Self::Catalog(error) => return error.fmt(f),
            Self::Core(error) => return error.fmt(f),
        })
    }
}

impl std::error::Error for ToolHeaderRepairError {}
impl From<ManagedInteractionError> for ToolHeaderRepairError {
    fn from(error: ManagedInteractionError) -> Self {
        Self::Interaction(error)
    }
}
impl From<ManagedCoreError> for ToolHeaderRepairError {
    fn from(error: ManagedCoreError) -> Self {
        Self::Core(error)
    }
}
impl From<ManagedCatalogError> for ToolHeaderRepairError {
    fn from(error: ManagedCatalogError) -> Self {
        Self::Catalog(error)
    }
}
impl From<ToolHeaderDispatchError> for ToolHeaderRepairError {
    fn from(error: ToolHeaderDispatchError) -> Self {
        Self::Headers(error)
    }
}
impl From<ManagedToolHeaderError> for ToolHeaderRepairError {
    fn from(error: ManagedToolHeaderError) -> Self {
        match error {
            ManagedToolHeaderError::Headers(error) => Self::Headers(error),
            ManagedToolHeaderError::Core(error) => Self::Core(error),
        }
    }
}

/// Success owns the ordinary incremental core call. Only `Rejected` permits
/// the separate, explicit refresh action; dropping it sends nothing further.
#[must_use = "drive the call or explicitly decide whether to repair its rejection"]
#[expect(
    clippy::large_enum_variant,
    reason = "returned once per call and moved immediately; boxing buys nothing on this path"
)]
pub enum ToolHeaderRepairOutcome {
    Call(ManagedCoreCall),
    Rejected(RejectedToolHeaders),
}

/// Unforgeable, non-Clone custody of one actual pre-dispatch rejection.
/// No response bytes or error message are retained. The host cannot replace
/// the invocation, resource, login, cancellation domain or original deadline.
pub struct RejectedToolHeaders {
    session: ManagedOAuthSession,
    original: CoreRequest,
    tool_name: String,
    cancellation: McpRequestCancellation,
    deadline: Time,
    limits: ToolHeaderRepairLimits,
    ids: IdLedger,
    rejected_bytes: usize,
}

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

impl ManagedOAuthSession {
    /// Attempts one initial tool call under an explicitly trusted rejection contract.
    /// This is the core header API: projection does not apply whole-instance
    /// input validation, so annotated nulls remain body data with no mirror.
    /// It does not replace or silently refresh a schema-bound `ManagedToolClient`.
    #[allow(clippy::too_many_arguments)]
    pub async fn request_tool_with_header_repair(
        &self,
        cx: &Cx,
        request: CoreRequest,
        request_id: RequestId,
        reviewed: &ReviewedToolHeaders,
        contract: ToolHeaderRepairContract,
        limits: ToolHeaderRepairLimits,
    ) -> Result<ToolHeaderRepairOutcome, ToolHeaderRepairError> {
        Box::pin(self.request_tool_with_header_repair_and_cancellation(
            cx,
            &McpRequestCancellation::new(),
            request,
            request_id,
            reviewed,
            contract,
            limits,
        ))
        .await
    }

    /// No HTTP/network/authorization failure triggers a refresh. Only a full
    /// correlated HTTP 400 JSON -32020 response yields single-use repair custody.
    #[allow(clippy::too_many_arguments)]
    pub async fn request_tool_with_header_repair_and_cancellation(
        &self,
        cx: &Cx,
        cancellation: &McpRequestCancellation,
        request: CoreRequest,
        request_id: RequestId,
        reviewed: &ReviewedToolHeaders,
        contract: ToolHeaderRepairContract,
        limits: ToolHeaderRepairLimits,
    ) -> Result<ToolHeaderRepairOutcome, ToolHeaderRepairError> {
        let deadline = call_deadline(cx, cancellation, limits.core.timeout)?;
        contract.admit_endpoint(self.resource())?;
        admit_initial(&request)?;
        let mut ids = IdLedger::default();
        ids.reserve(&request_id)?;
        let (wire, decoder) = prepare_optional(
            self.resource().as_str(),
            request.clone(),
            request_id.clone(),
            limits.core,
            Some(reviewed),
        )?;
        let response = Box::pin(bounded_wait(cx, cancellation, deadline, async {
            self.execute_with_cancellation(cx, cancellation, &wire)
                .await
                .map_err(ManagedCoreError::from)
        }))
        .await?;
        if response.metadata().status() == 200 {
            return Ok(ToolHeaderRepairOutcome::Call(
                ManagedCoreCall::from_response(response, decoder, cancellation.clone(), deadline)?,
            ));
        }
        admit_rejection_head(
            response.metadata().status(),
            response.metadata().error_body_admission(),
        )?;
        let frame = Box::pin(bounded_wait(cx, cancellation, deadline, async {
            response
                .read_to_end(cx, limits.core.frame_bytes)
                .await
                .map_err(ManagedCoreError::from)
        }))
        .await?;
        admit_rejection_body(&frame, &request_id, limits.core.frame_bytes)?;
        check_call(cx, cancellation, deadline)?;
        Ok(ToolHeaderRepairOutcome::Rejected(RejectedToolHeaders {
            session: self.clone(),
            original: request,
            tool_name: reviewed.tool_name().to_owned(),
            cancellation: cancellation.clone(),
            deadline,
            limits,
            ids,
            rejected_bytes: frame.len(),
        }))
    }
}

impl RejectedToolHeaders {
    /// Refreshes the entire uncached tools catalog and explicitly retries once.
    /// `approve` must authorize the changed definition, including the same
    /// original arguments' use with it. `review` separately approves every new
    /// header binding. Even an unannotated replacement needs definition approval.
    /// Both callbacks are synchronous host code and must cooperate.
    ///
    /// The ID supplier covers every catalog page and the one retry. IDs cannot
    /// alias the rejected request or any earlier page. All invocation parameters
    /// are retained exactly; only its RPC ID and reviewed mirrors change.
    /// Catalog pages retain the invocation's admitted client capabilities, but
    /// not its progress token or private observation metadata. A capability-
    /// dependent catalog must not be refreshed under a different client view.
    /// A second rejection, interrupted retry, callback error, cancellation, or
    /// dropped future is terminal. No further repair owner is returned.
    ///
    /// Returns the ordinary core call, including incremental notifications and
    /// typed input-required results. It grants no automatic continuation/replay
    /// permission and does not mutate or resurrect previously invalidated tools.
    pub async fn refresh_and_retry<I, A, R>(
        self,
        cx: &Cx,
        next_id: I,
        approve: A,
        review: R,
    ) -> Result<ManagedCoreCall, ToolHeaderRepairError>
    where
        I: FnMut() -> Result<RequestId, ManagedCatalogError>,
        A: FnOnce(&FinalTool) -> bool,
        R: FnMut(&ParameterHeaderBinding) -> bool,
    {
        Ok(Box::pin(self.refresh_owned(cx, next_id, approve, review))
            .await?
            .into_call())
    }

    /// Performs the same one-shot repair, retaining its successful retry as a
    /// resumable operation before reading any response event. This is an
    /// ownership handoff, not a second invocation. The first event may be a
    /// notification, a complete result, or an input-required challenge.
    ///
    /// Explicit continuation/answer limits cannot enlarge the original core
    /// byte, notification, or time budgets. All rejected-call, catalog-page and
    /// retry IDs remain reserved. Every later round reuses the approved schema
    /// projection and immutable arguments. No input resolver runs automatically.
    #[allow(clippy::too_many_arguments)]
    pub async fn refresh_and_start_interaction<I, A, R>(
        self,
        cx: &Cx,
        maximum_continuations: usize,
        maximum_input_responses: usize,
        next_id: I,
        approve: A,
        review: R,
    ) -> Result<ManagedInteraction, ToolHeaderRepairError>
    where
        I: FnMut() -> Result<RequestId, ManagedCatalogError>,
        A: FnOnce(&FinalTool) -> bool,
        R: FnMut(&ParameterHeaderBinding) -> bool,
    {
        self.admit_interaction_limits(maximum_continuations, maximum_input_responses)?;
        Box::pin(self.refresh_owned(cx, next_id, approve, review))
            .await?
            .into_interaction(cx, maximum_continuations, maximum_input_responses)
    }

    pub(crate) fn admit_interaction_limits(
        &self,
        continuations: usize,
        responses: usize,
    ) -> Result<(), ToolHeaderRepairError> {
        ManagedInteractionLimits::new(self.limits.core, continuations, responses)?;
        Ok(())
    }

    // Only this path can construct RepairedToolCall: it owns the actual retry
    // body together with the complete history and freshly reviewed projection.
    pub(crate) async fn refresh_owned<I, A, R>(
        mut self,
        cx: &Cx,
        mut next_id: I,
        approve: A,
        mut review: R,
    ) -> Result<RepairedToolCall, ToolHeaderRepairError>
    where
        I: FnMut() -> Result<RequestId, ManagedCatalogError>,
        A: FnOnce(&FinalTool) -> bool,
        R: FnMut(&ParameterHeaderBinding) -> bool,
    {
        // A caller may narrow the original budget when authorizing repair.
        // Retain that narrower bound in the returned call, not only in this
        // method's temporary wait, so later reads cannot regain the old time.
        self.deadline = cx
            .budget()
            .deadline
            .map_or(self.deadline, |parent| parent.min(self.deadline));
        check_call(cx, &self.cancellation, self.deadline)?;
        let charged = self.limits.retry_charge(self.rejected_bytes)?;
        let collector = ManagedCatalogClient::new(self.session.clone(), self.limits.catalog()?);
        let list = repair_catalog_request(&self.original)?;
        Box::pin(bounded_wait(cx, &self.cancellation, self.deadline, async {
            Ok(async {
                let catalog = Box::pin(collector.collect_with_cancellation(
                    cx,
                    &self.cancellation,
                    list,
                    || {
                        let id = next_id()?;
                        self.ids.reserve(&id)?;
                        Ok(id)
                    },
                    |_| Err(ManagedCatalogError::AbortedByHost),
                ))
                .await?;
                check_call(cx, &self.cancellation, self.deadline)?;
                let tool = select_tool(
                    catalog.into_pages(),
                    &self.tool_name,
                    self.limits.catalog_tools,
                )?;
                let reviewed = approve_replacement(
                    cx,
                    &self.cancellation,
                    self.deadline,
                    self.session.resource(),
                    &tool,
                    approve,
                    &mut review,
                )?;
                check_call(cx, &self.cancellation, self.deadline)?;
                let id = next_id()?;
                self.ids.reserve(&id)?;
                check_call(cx, &self.cancellation, self.deadline)?;
                let (wire, mut decoder) = prepare_optional(
                    self.session.resource().as_str(),
                    self.original,
                    id,
                    self.limits.core,
                    Some(&reviewed),
                )?;
                decoder.resume_usage(charged, 0)?;
                check_call(cx, &self.cancellation, self.deadline)?;
                let response = Box::pin(self.session.execute_with_cancellation(
                    cx,
                    &self.cancellation,
                    &wire,
                ))
                .await
                .map_err(ManagedCoreError::from)?;
                check_call(cx, &self.cancellation, self.deadline)?;
                // Intentionally NOT the repair entrypoint: a second 400 can
                // only fail. Returned reads retain the original absolute bound.
                let call = ManagedCoreCall::from_response(
                    response,
                    decoder,
                    self.cancellation.clone(),
                    self.deadline,
                )?;
                Ok(RepairedToolCall {
                    call,
                    session: self.session.clone(),
                    reviewed: Arc::new(reviewed),
                    ids: self.ids.ids,
                })
            }
            .await)
        }))
        .await?
    }
}

// Not public and not Clone: no caller can attach fabricated history or a new
// disclosure review to an already-dispatched request, or split its ownership.
pub(crate) struct RepairedToolCall {
    call: ManagedCoreCall,
    session: ManagedOAuthSession,
    reviewed: Arc<ReviewedToolHeaders>,
    ids: Vec<RequestId>,
}

impl RepairedToolCall {
    pub(crate) fn into_call(self) -> ManagedCoreCall {
        self.call
    }

    pub(crate) fn into_interaction(
        self,
        cx: &Cx,
        continuations: usize,
        responses: usize,
    ) -> Result<ManagedInteraction, ToolHeaderRepairError> {
        Ok(ManagedInteraction::from_repaired_call(
            cx,
            self.session,
            self.call,
            self.reviewed,
            self.ids,
            continuations,
            responses,
        )?)
    }
}

// Preserve the admitted capability view on every page without forwarding the
// tool call's observation fields. Re-decoding through ClientCapabilities would
// be a second projection and could discard open capability members; reuse the
// already-admitted encoded object instead. The core preparation boundary still
// refuses nonempty extension advertisements before any request is dispatched.
fn repair_catalog_request(original: &CoreRequest) -> Result<CoreRequest, ToolHeaderRepairError> {
    admit_initial(original)?;
    let params = original
        .encode_params()
        .map_err(|_| ManagedCoreError::InvalidRequest)?
        .ok_or(ManagedCoreError::InvalidRequest)?;
    let capabilities = params
        .get("_meta")
        .and_then(|meta| meta.get(FINAL_CLIENT_CAPABILITIES_META_KEY))
        .and_then(serde_json::Value::as_object)
        .ok_or(ManagedCoreError::InvalidRequest)?;
    CoreRequest::decode(
        ProtocolEra::Modern2026,
        "tools/list",
        Some(&json!({
            "_meta": {
                (FINAL_PROTOCOL_VERSION_META_KEY): FINAL_PROTOCOL_VERSION,
                (FINAL_CLIENT_CAPABILITIES_META_KEY): capabilities,
            },
        })),
    )
    .map_err(|_| ManagedCoreError::InvalidRequest.into())
}

fn admit_initial(request: &CoreRequest) -> Result<(), ToolHeaderRepairError> {
    match request {
        CoreRequest::Final(FinalCoreRequest::ToolsCall(params))
            if params.request_state.is_none() && params.input_responses.is_none() =>
        {
            Ok(())
        }
        _ => Err(ToolHeaderRepairError::InitialToolCallRequired),
    }
}

fn admit_rejection_head(
    status: u16,
    admission: Option<ModernHttpErrorBodyAdmission>,
) -> Result<(), ManagedCoreError> {
    if status != 400 || admission != Some(ModernHttpErrorBodyAdmission::JsonRpcError) {
        return Err(ManagedCoreError::HttpStatus { status });
    }
    Ok(())
}

fn admit_rejection_body(
    frame: &[u8],
    id: &RequestId,
    maximum: usize,
) -> Result<(), ManagedCoreError> {
    let admitted = decode_strict_jsonrpc_response(frame, maximum)
        .map_err(|_| ManagedCoreError::InvalidResponse)?;
    let response = admitted.response();
    if !response
        .id
        .as_ref()
        .is_some_and(|received| received.correlates_with(id))
    {
        return Err(ManagedCoreError::ResponseIdMismatch);
    }
    let error = response
        .error
        .as_ref()
        .ok_or(ManagedCoreError::InvalidResponse)?;
    if error.code != JsonInteger::from(HEADER_MISMATCH_ERROR_CODE) {
        return Err(ManagedCoreError::Remote {
            code: error.code.clone(),
        });
    }
    Ok(())
}

fn select_tool(
    pages: Vec<CoreResult>,
    name: &str,
    maximum: usize,
) -> Result<FinalTool, ToolHeaderRepairError> {
    let mut names = HashSet::new();
    let mut selected = None;
    for page in pages {
        let CoreResult::Final(FinalCoreResult::ToolsList { result, .. }) = page else {
            return Err(ManagedCatalogError::InvalidPage.into());
        };
        for tool in result.payload.tools {
            if names.len() >= maximum {
                return Err(ManagedCatalogError::ItemLimit.into());
            }
            if !names.insert(tool.name.clone()) {
                return Err(ToolHeaderRepairError::DuplicateTool);
            }
            if tool.name == name {
                selected = Some(tool);
            }
        }
    }
    selected.ok_or(ToolHeaderRepairError::ToolUnavailable)
}

#[allow(clippy::too_many_arguments)]
fn approve_replacement<A, R>(
    cx: &Cx,
    cancellation: &McpRequestCancellation,
    deadline: Time,
    resource: &CanonicalHttpUrl,
    tool: &FinalTool,
    approve: A,
    review: &mut R,
) -> Result<ReviewedToolHeaders, ToolHeaderRepairError>
where
    A: FnOnce(&FinalTool) -> bool,
    R: FnMut(&ParameterHeaderBinding) -> bool,
{
    check_call(cx, cancellation, deadline)?;
    let approved = approve(tool);
    check_call(cx, cancellation, deadline)?;
    if !approved {
        return Err(ToolHeaderRepairError::DefinitionDeclined);
    }
    let reviewed = ReviewedToolHeaders::new(
        resource.clone(),
        tool.name.clone(),
        tool.input_schema.clone(),
        |binding| {
            if check_call(cx, cancellation, deadline).is_err() {
                return false;
            }
            let approved = review(binding);
            approved && check_call(cx, cancellation, deadline).is_ok()
        },
    );
    // Cancellation/deadline errors take precedence over a callback's denial.
    check_call(cx, cancellation, deadline)?;
    reviewed.map_err(ToolHeaderRepairError::from)
}

#[derive(Default)]
struct IdLedger {
    ids: Vec<RequestId>,
    bytes: usize,
}

impl IdLedger {
    fn reserve(&mut self, id: &RequestId) -> Result<(), ManagedCatalogError> {
        id.validate()
            .map_err(|_| ManagedCoreError::InvalidRequest)?;
        if self.ids.iter().any(|used| used.correlates_with(id)) {
            return Err(ManagedCatalogError::RepeatedRequestId);
        }
        if self.ids.len() >= MAX_REPAIR_PAGES + 2 {
            return Err(ManagedCatalogError::StateLimit);
        }
        let mut counter = IdBytes(self.bytes);
        serde_json::to_writer(&mut counter, id).map_err(|_| ManagedCatalogError::StateLimit)?;
        self.ids.push(id.clone());
        self.bytes = counter.0;
        Ok(())
    }
}

struct IdBytes(usize);
impl Write for IdBytes {
    fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
        if bytes.len() > MAX_REPAIR_ID_BYTES.saturating_sub(self.0) {
            return Err(io::Error::other("tool-header repair ID budget"));
        }
        self.0 += bytes.len();
        Ok(bytes.len())
    }
    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

#[cfg(test)]
mod tests;