multicast 2.0.0

A declarative CLI framework for Rust with typed commands, agent discovery, HTTP, and MCP
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
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
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
//! File uploads and downloads for tools: the experimental
//! `io.modelcontextprotocol/files` extension.
//!
//! This module follows the draft at revision
//! `8a859b8f268926fe4beb84d78565e7cc6f9fa617` of
//! `modelcontextprotocol/experimental-ext-file-uploads` (2026-11-09). The draft
//! is not final; expect breaking changes behind the `mcp-files` feature.
//!
//! A tool marks a file argument with an `x-mcp-file` object schema (see
//! [`file_schema`]). The client sends each file as a [`FileInput`], either
//! inline with base64 `data` or, when the server has a [`FileStaging`] host,
//! out of band: the server answers `upload_required` with one
//! [`UploadTarget`] per file and a signed `requestState`, the client
//! transfers the bytes, and the retry runs the command with the confirmed bytes
//! placed in each file's `data`. A command therefore always sees verified
//! inline input, read with [`FileInput::bytes`].

use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;

use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
use sha2::{Digest, Sha256};
use web_time::{SystemTime, UNIX_EPOCH};

/// Extension identifier in capabilities and result metadata.
pub const FILES_EXTENSION: &str = "io.modelcontextprotocol/files";

/// Schema keyword that marks a file argument.
pub const FILE_SCHEMA_KEYWORD: &str = "x-mcp-file";

/// Default [`McpFilesOptions::max_inline_bytes`]: 1 MiB.
pub const DEFAULT_MAX_INLINE_BYTES: u64 = 1024 * 1024;

/// Default [`McpFilesOptions::state_ttl`]: 15 minutes.
pub const DEFAULT_STATE_TTL: Duration = Duration::from_secs(15 * 60);

#[cfg(test)]
mod tests;

const STATE_PREFIX: &str = "mcf1.";
const MAX_SCHEMA_DEPTH: usize = 64;

/// Builds the object schema of one file argument.
///
/// `accept` lists media types or ranges such as `image/*`; an empty list
/// accepts every type. `max_size` bounds the decoded size in bytes however
/// the file travels. Set `require_digest` when the command needs the server
/// to check a SHA-256 `digest` against the bytes.
pub fn file_schema(accept: &[&str], max_size: Option<u64>, require_digest: bool) -> Value {
    let mut marker = Map::new();
    if !accept.is_empty() {
        marker.insert("accept".into(), json!(accept));
    }
    if let Some(max_size) = max_size {
        marker.insert("maxSize".into(), json!(max_size));
    }
    let mut required = vec!["id", "mimeType", "size"];
    if require_digest {
        required.push("digest");
    }
    json!({
        "type": "object",
        FILE_SCHEMA_KEYWORD: marker,
        "properties": {
            "id": { "type": "string", "minLength": 1, "maxLength": 128 },
            "name": { "type": "string" },
            "mimeType": { "type": "string" },
            "size": { "type": "integer", "minimum": 0 },
            "digest": {
                "type": "object",
                "properties": {
                    "algorithm": { "const": "sha-256" },
                    "value": { "type": "string" }
                },
                "required": ["algorithm", "value"]
            },
            "data": { "type": "string" }
        },
        "required": required
    })
}

/// A SHA-256 digest of a file's bytes.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FileDigest {
    /// Always `sha-256`.
    pub algorithm: String,
    /// Base64url digest without padding.
    pub value: String,
}

impl FileDigest {
    /// Computes the SHA-256 digest of `bytes`.
    pub fn sha256(bytes: &[u8]) -> Self {
        Self {
            algorithm: "sha-256".into(),
            value: encode_base64url(&Sha256::digest(bytes)),
        }
    }
}

/// One file argument, as the client sends it and as a command receives it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FileInput {
    /// Identifier unique within the call, 1 to 128 characters.
    pub id: String,
    /// Original file name, if known.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Media type; `application/octet-stream` when unknown.
    pub mime_type: String,
    /// Decoded size in bytes.
    pub size: u64,
    /// SHA-256 of the bytes, when the sender supplies one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub digest: Option<FileDigest>,
    /// Base64 bytes. Absent for an empty file, or for a file sent out of band.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub data: Option<String>,
}

impl FileInput {
    /// Builds an inline file with its size and digest computed from `bytes`.
    /// An empty file carries no `data`.
    pub fn inline(
        id: impl Into<String>,
        name: Option<String>,
        mime_type: impl Into<String>,
        bytes: &[u8],
    ) -> Self {
        let mut file = Self::metadata(id, name, mime_type, bytes);
        if !bytes.is_empty() {
            file.data = Some(encode_base64(bytes));
        }
        file
    }

    /// Builds a file with its size and digest computed from `bytes` and no
    /// `data`, for an out-of-band transfer.
    pub fn metadata(
        id: impl Into<String>,
        name: Option<String>,
        mime_type: impl Into<String>,
        bytes: &[u8],
    ) -> Self {
        Self {
            id: id.into(),
            name,
            mime_type: mime_type.into(),
            size: bytes.len() as u64,
            digest: Some(FileDigest::sha256(bytes)),
            data: None,
        }
    }

    /// Reads a file argument from a command's arguments.
    pub fn from_value(value: &Value) -> Result<Self, String> {
        serde_json::from_value(value.clone())
            .map_err(|error| format!("invalid file input: {error}"))
    }

    /// Decodes and checks the file's bytes.
    ///
    /// Succeeds only when the decoded length equals `size` and, if a
    /// `digest` is present, the SHA-256 matches. An empty file without
    /// `data` has no bytes.
    pub fn bytes(&self) -> Result<Vec<u8>, String> {
        let bytes = match &self.data {
            Some(data) => decode_base64(data).ok_or("file data is not valid base64")?,
            None if self.size == 0 => Vec::new(),
            None => return Err(format!("file {} has no data", self.id)),
        };
        check_bytes(self, &bytes)?;
        Ok(bytes)
    }
}

/// The form encoding of an [`UploadTarget`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UploadForm {
    /// Fields sent before the file, in order.
    pub fields: Vec<FormField>,
    /// Name of the part that carries the file.
    pub file_field: String,
}

/// One `multipart/form-data` field.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FormField {
    /// Field name.
    pub name: String,
    /// Field value.
    pub value: String,
}

/// Where and how a client sends one file's bytes.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct UploadTarget {
    /// The [`FileInput::id`] this target is for. The server sets it.
    pub file_id: String,
    /// Absolute `https` URL. Exactly one of `url` and `path` is present.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    /// Path under the MCP address.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
    /// `PUT` (the default) or `POST`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub method: Option<String>,
    /// Sends the file as `multipart/form-data`; requires `POST`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub form: Option<UploadForm>,
    /// Headers sent with the transfer.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub headers: Option<BTreeMap<String, String>>,
    /// `omit` when the target carries its own authorization, `include` to
    /// attach the MCP credential.
    pub credentials: String,
    /// RFC 3339 advisory latest start time.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<String>,
    /// Metadata not used for the transfer.
    #[serde(default, rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<Map<String, Value>>,
}

/// A file a result offers for download, listed under the extension's key in
/// the result's `_meta` as `downloads`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct DownloadTarget {
    /// Absolute `https` URL. Exactly one of `url` and `path` is present.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    /// Path under the MCP address.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
    /// Suggested file name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Media type; `application/octet-stream` when unknown.
    pub mime_type: String,
    /// Size in bytes, after any `Content-Encoding` is removed.
    pub size: u64,
    /// SHA-256 of the bytes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub digest: Option<FileDigest>,
    /// Headers sent with the `GET`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub headers: Option<BTreeMap<String, String>>,
    /// `omit` or `include`, as for uploads.
    pub credentials: String,
    /// RFC 3339 advisory latest start time.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<String>,
    /// Metadata not used for the transfer.
    #[serde(default, rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<Map<String, Value>>,
}

/// Builds the `_meta` object that offers `downloads` in a tool result.
pub fn downloads_meta(downloads: &[DownloadTarget]) -> Value {
    json!({ FILES_EXTENSION: { "downloads": downloads } })
}

/// A target the staging host issued for one file.
#[derive(Debug, Clone)]
pub struct StagedTarget {
    /// The target returned to the client. Its `file_id` is overwritten.
    pub target: UploadTarget,
    /// Opaque handle the server binds into `requestState` and later passes to
    /// [`FileStaging::confirm`].
    pub handle: String,
}

/// Host storage for out-of-band uploads.
///
/// The server never stores bytes itself. Each target should write to a
/// staging location, enforce the declared size, accept one write, and stay
/// valid no longer than `expires`. Staged bytes must be kept until `expires`.
#[async_trait::async_trait]
#[allow(
    clippy::double_must_use,
    reason = "async_trait annotates generated futures"
)]
pub trait FileStaging: Send + Sync {
    /// Issues a target for `file`, valid until `expires`.
    async fn issue(&self, file: &FileInput, expires: SystemTime) -> Result<StagedTarget, String>;

    /// Returns the bytes staged under `handle`, or `None` if none arrived.
    /// The server checks size and digest itself.
    async fn confirm(&self, handle: &str, file: &FileInput) -> Result<Option<Vec<u8>>, String>;

    /// Records `state_id` as used, atomically in storage shared by every
    /// server instance. Returns `false` if it was already recorded. The
    /// record must be kept until `expires`.
    async fn consume(&self, state_id: &str, expires: SystemTime) -> Result<bool, String>;
}

/// File upload settings for an MCP server.
#[derive(Clone)]
pub struct McpFilesOptions {
    /// Largest total decoded inline size in one request; `0` accepts no
    /// inline data.
    pub max_inline_bytes: u64,
    /// Storage for out-of-band uploads; `None` accepts files inline only.
    pub staging: Option<Arc<dyn FileStaging>>,
    /// Key that signs `requestState`. Required with `staging`; use at least
    /// 32 random bytes shared by every server instance.
    pub signing_key: Vec<u8>,
    /// Lifetime of each `requestState` and the targets issued under it.
    pub state_ttl: Duration,
}

impl Default for McpFilesOptions {
    fn default() -> Self {
        Self {
            max_inline_bytes: DEFAULT_MAX_INLINE_BYTES,
            staging: None,
            signing_key: Vec::new(),
            state_ttl: DEFAULT_STATE_TTL,
        }
    }
}

impl std::fmt::Debug for McpFilesOptions {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("McpFilesOptions")
            .field("max_inline_bytes", &self.max_inline_bytes)
            .field("staging", &self.staging.is_some())
            .field("state_ttl", &self.state_ttl)
            .finish_non_exhaustive()
    }
}

impl McpFilesOptions {
    /// Checks that out-of-band uploads have a usable signing key.
    pub fn validate(&self) -> Result<(), String> {
        if self.staging.is_some() && self.signing_key.len() < 32 {
            return Err("file staging requires a signing key of at least 32 bytes".into());
        }
        if self.state_ttl.is_zero() {
            return Err("file requestState lifetime must be positive".into());
        }
        Ok(())
    }

    /// The extension settings advertised in `server/discover`.
    pub(crate) fn settings(&self) -> Value {
        let mut settings = Map::new();
        if self.staging.is_some() {
            settings.insert("upload".into(), json!({}));
        }
        if self.max_inline_bytes > 0 {
            settings.insert("maxInlineBytes".into(), json!(self.max_inline_bytes));
        }
        Value::Object(settings)
    }
}

/// What the client declared for this extension in one request.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct Declared {
    pub(crate) upload: bool,
    pub(crate) download: bool,
}

impl Declared {
    pub(crate) fn from_capabilities(capabilities: Option<&Value>) -> Self {
        let settings = capabilities
            .and_then(|capabilities| capabilities.get("extensions"))
            .and_then(|extensions| extensions.get(FILES_EXTENSION))
            .filter(|settings| settings.is_object())
            // A revision this server does not know disables the extension.
            .filter(|settings| settings.get("revision").is_none());
        Self {
            upload: settings
                .is_some_and(|settings| settings.get("upload").is_some_and(Value::is_object)),
            download: settings
                .is_some_and(|settings| settings.get("download").is_some_and(Value::is_object)),
        }
    }
}

/// The outcome of preparing a `tools/call` with file arguments.
pub(crate) enum Prepared {
    /// Run the command with these arguments and this MRTR request state.
    Run {
        arguments: Option<Map<String, Value>>,
        request_state: Option<String>,
        binding: Option<Binding>,
    },
    /// Return this result without running the command.
    Respond(Value),
    /// Answer with this JSON-RPC error.
    Reject(Value),
}

/// The bindings of a staged logical call, carried into later request states.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct Binding {
    tool: String,
    arguments: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    principal: Option<String>,
    files: Vec<StagedFile>,
    expires: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct StagedFile {
    id: String,
    handle: String,
}

#[derive(Debug, Serialize, Deserialize)]
struct State {
    #[serde(flatten)]
    binding: Binding,
    nonce: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    inner: Option<String>,
}

/// The location and constraints of one file argument.
#[derive(Debug, Clone, Default)]
struct Constraints {
    accept: Vec<Vec<String>>,
    max_size: Option<u64>,
    require_digest: bool,
}

type Pointer = Vec<Segment>;

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
enum Segment {
    Key(String),
    Index(usize),
}

pub(crate) struct Call<'a> {
    pub(crate) tool: &'a str,
    pub(crate) schema: &'a Map<String, Value>,
    /// Arguments are nested under `arguments` for a progressive call.
    pub(crate) nested: bool,
    pub(crate) arguments: Option<Map<String, Value>>,
    pub(crate) declared: Declared,
    pub(crate) request_state: Option<String>,
    pub(crate) principal: Option<&'a str>,
    pub(crate) modern: bool,
}

fn missing_capability(capability: &str) -> Value {
    json!({
        "code": -32021,
        "message": format!("request did not declare the {FILES_EXTENSION} {capability} capability"),
        "data": {
            "requiredCapabilities": {
                "extensions": { FILES_EXTENSION: { capability: {} } }
            }
        }
    })
}

fn invalid_state(message: &str) -> Prepared {
    Prepared::Reject(json!({ "code": -32602, "message": message }))
}

/// A `CallToolResult` with `isError`, returned without running the tool.
pub(crate) fn tool_error(message: impl Into<String>) -> Value {
    json!({
        "resultType": "complete",
        "content": [{ "type": "text", "text": message.into() }],
        "isError": true
    })
}

impl McpFilesOptions {
    /// Validates file arguments and decides whether the command may run.
    pub(crate) async fn prepare(&self, call: Call<'_>) -> Prepared {
        let Call {
            tool,
            schema,
            nested,
            mut arguments,
            declared,
            request_state,
            principal,
            modern,
        } = call;
        let target = arguments.as_ref().map(|arguments| {
            if nested {
                arguments.get("arguments").cloned().unwrap_or(Value::Null)
            } else {
                Value::Object(arguments.clone())
            }
        });
        let Some(target) = target else {
            return Prepared::Run {
                arguments,
                request_state,
                binding: None,
            };
        };
        let mut found = BTreeMap::new();
        let root = Value::Object(schema.clone());
        collect_value(&root, &root, &target, &mut Vec::new(), &mut found, 0);
        if found.is_empty() {
            return Prepared::Run {
                arguments,
                request_state,
                binding: None,
            };
        }

        let mut ids = BTreeSet::new();
        let mut inline_total = 0u64;
        let mut pending = Vec::new();
        for (pointer, constraints) in &found {
            let Some(value) = lookup(&target, pointer) else {
                continue;
            };
            let file = match parse_file(value) {
                Ok(file) => file,
                Err(message) => return Prepared::Respond(tool_error(message)),
            };
            if !ids.insert(file.id.clone()) {
                return Prepared::Respond(tool_error(format!("duplicate file id {}", file.id)));
            }
            if let Err(message) = check_metadata(&file, constraints) {
                return Prepared::Respond(tool_error(message));
            }
            match &file.data {
                Some(data) if !(file.size == 0 && data.is_empty()) => {
                    let Some(bytes) = decode_base64(data) else {
                        return Prepared::Respond(tool_error(format!(
                            "file {} data is not valid base64",
                            file.id
                        )));
                    };
                    inline_total = inline_total.saturating_add(bytes.len() as u64);
                    if inline_total > self.max_inline_bytes {
                        return Prepared::Respond(tool_error(format!(
                            "inline file data exceeds {} bytes",
                            self.max_inline_bytes
                        )));
                    }
                    if let Err(message) = check_bytes(&file, &bytes) {
                        return Prepared::Respond(tool_error(message));
                    }
                }
                _ if file.size == 0 => {
                    if let Err(message) = check_bytes(&file, &[]) {
                        return Prepared::Respond(tool_error(message));
                    }
                }
                _ => pending.push((pointer.clone(), file, constraints.clone())),
            }
        }
        if pending.is_empty() {
            return Prepared::Run {
                arguments,
                request_state,
                binding: None,
            };
        }

        if let Some(state) = request_state
            .as_deref()
            .filter(|state| state.starts_with(STATE_PREFIX))
        {
            return self
                .retry(
                    tool,
                    nested,
                    arguments.take().unwrap_or_default(),
                    principal,
                    state,
                    pending,
                )
                .await;
        }
        let Some(staging) = self.staging.as_ref() else {
            return Prepared::Respond(tool_error(
                "this server does not accept files out of band; send the file inline",
            ));
        };
        if !modern {
            return Prepared::Respond(tool_error(
                "out-of-band file uploads require protocol version 2026-07-28",
            ));
        }
        if !declared.upload {
            return Prepared::Reject(missing_capability("upload"));
        }
        if let Err(message) = self.validate() {
            return Prepared::Respond(tool_error(message));
        }
        let expires_at = SystemTime::now() + self.state_ttl;
        let expires = unix_seconds(expires_at);
        let mut uploads = Vec::new();
        let mut files = Vec::new();
        for (_, file, _) in &pending {
            match staging.issue(file, expires_at).await {
                Ok(StagedTarget { mut target, handle }) => {
                    target.file_id = file.id.clone();
                    uploads.push(target);
                    files.push(StagedFile {
                        id: file.id.clone(),
                        handle,
                    });
                }
                Err(message) => {
                    return Prepared::Respond(tool_error(format!(
                        "could not prepare an upload for file {}: {message}",
                        file.id
                    )));
                }
            }
        }
        let binding = Binding {
            tool: tool.to_string(),
            arguments: arguments_digest(&target),
            principal: principal.map(str::to_string),
            files,
            expires,
        };
        Prepared::Respond(json!({
            "resultType": "upload_required",
            "uploads": uploads,
            "requestState": self.sign(&binding, None),
        }))
    }

    async fn retry(
        &self,
        tool: &str,
        nested: bool,
        mut arguments: Map<String, Value>,
        principal: Option<&str>,
        state: &str,
        pending: Vec<(Pointer, FileInput, Constraints)>,
    ) -> Prepared {
        // 1. Verify the requestState.
        let Some(State { binding, inner, .. }) = self.verify(state) else {
            return invalid_state("requestState failed verification");
        };
        if binding.expires <= unix_seconds(SystemTime::now()) {
            return invalid_state("requestState has expired");
        }
        // 2. Check the tool, arguments, and principal it binds.
        let target = if nested {
            arguments.get("arguments").cloned().unwrap_or(Value::Null)
        } else {
            Value::Object(arguments.clone())
        };
        if binding.tool != tool
            || binding.arguments != arguments_digest(&target)
            || binding.principal.as_deref() != principal
        {
            return invalid_state("tool name, arguments, or principal differ from requestState");
        }
        let Some(staging) = self.staging.as_ref() else {
            return invalid_state("requestState failed verification");
        };
        // 3. Confirm each file's bytes with the storage.
        let mut confirmed = Vec::new();
        for (pointer, file, constraints) in pending {
            let Some(staged) = binding.files.iter().find(|staged| staged.id == file.id) else {
                return invalid_state("requestState does not bind every file");
            };
            let bytes = match staging.confirm(&staged.handle, &file).await {
                Ok(Some(bytes)) => bytes,
                Ok(None) => {
                    return Prepared::Respond(tool_error(format!(
                        "file {} has not arrived; the tool did not run",
                        file.id
                    )));
                }
                Err(message) => {
                    return Prepared::Respond(tool_error(format!(
                        "file {} could not be confirmed: {message}; the tool did not run",
                        file.id
                    )));
                }
            };
            if let Err(message) =
                check_bytes(&file, &bytes).and_then(|()| check_metadata(&file, &constraints))
            {
                return Prepared::Respond(tool_error(format!("{message}; the tool did not run")));
            }
            confirmed.push((pointer, bytes));
        }
        // 4. Consume the requestState so a repeated retry cannot run the tool twice.
        let expires_at = UNIX_EPOCH + Duration::from_secs(binding.expires);
        match staging.consume(&state_id(state), expires_at).await {
            Ok(true) => {}
            Ok(false) => return invalid_state("requestState was already used"),
            Err(message) => {
                return Prepared::Respond(tool_error(format!(
                    "requestState could not be recorded: {message}; the tool did not run"
                )));
            }
        }
        // 5. Run with the confirmed bytes inline.
        let mut target = target;
        for (pointer, bytes) in confirmed {
            if let Some(Value::Object(file)) = lookup_mut(&mut target, &pointer) {
                file.insert("data".into(), Value::String(encode_base64(&bytes)));
            }
        }
        let arguments = if nested {
            arguments.insert("arguments".into(), target);
            arguments
        } else {
            match target {
                Value::Object(map) => map,
                _ => Map::new(),
            }
        };
        Prepared::Run {
            arguments: Some(arguments),
            request_state: inner,
            binding: Some(binding),
        }
    }

    /// Adjusts a result of a call that passed through [`Self::prepare`].
    ///
    /// A later `input_required` in a staged call gets a new signed
    /// `requestState` that carries the command's own state, so the retry
    /// that answers it repeats verification and consumption. Downloads are
    /// removed for a request that did not declare `download`.
    pub(crate) fn finish(&self, result: &mut Value, binding: Option<&Binding>, declared: Declared) {
        if let Some(binding) = binding
            && result.get("resultType").and_then(Value::as_str) == Some("input_required")
        {
            let inner = result
                .get("requestState")
                .and_then(Value::as_str)
                .map(str::to_string);
            result["requestState"] = Value::String(self.sign(binding, inner));
        }
        if !declared.download {
            strip_downloads(result);
        }
    }

    fn sign(&self, binding: &Binding, inner: Option<String>) -> String {
        static SEQUENCE: AtomicU64 = AtomicU64::new(0);
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|elapsed| elapsed.as_nanos())
            .unwrap_or_default();
        let nonce = format!("{nanos:x}.{:x}", SEQUENCE.fetch_add(1, Ordering::Relaxed));
        let state = State {
            binding: binding.clone(),
            nonce,
            inner,
        };
        let payload = encode_base64url(&serde_json::to_vec(&state).unwrap_or_default());
        let mac = hmac_sha256(&self.signing_key, payload.as_bytes());
        format!("{STATE_PREFIX}{payload}.{}", encode_base64url(&mac))
    }

    fn verify(&self, state: &str) -> Option<State> {
        if self.signing_key.is_empty() {
            return None;
        }
        let (payload, mac) = state.strip_prefix(STATE_PREFIX)?.split_once('.')?;
        let expected = hmac_sha256(&self.signing_key, payload.as_bytes());
        let mac = decode_base64url(mac)?;
        if !constant_time_eq(&expected, &mac) {
            return None;
        }
        serde_json::from_slice(&decode_base64url(payload)?).ok()
    }
}

/// Removes download targets from a result for a client that cannot use them.
pub(crate) fn strip_downloads(result: &mut Value) {
    if let Some(meta) = result.get_mut("_meta").and_then(Value::as_object_mut)
        && let Some(settings) = meta.get_mut(FILES_EXTENSION).and_then(Value::as_object_mut)
    {
        settings.remove("downloads");
        if settings.is_empty() {
            meta.remove(FILES_EXTENSION);
        }
        if meta.is_empty()
            && let Some(object) = result.as_object_mut()
        {
            object.remove("_meta");
        }
    }
}

fn state_id(state: &str) -> String {
    encode_base64url(&Sha256::digest(state.as_bytes()))
}

fn unix_seconds(time: SystemTime) -> u64 {
    time.duration_since(UNIX_EPOCH)
        .map(|elapsed| elapsed.as_secs())
        .unwrap_or_default()
}

fn parse_file(value: &Value) -> Result<FileInput, String> {
    let object = value
        .as_object()
        .ok_or("a file argument must be an object")?;
    if object.get("data").is_some_and(Value::is_null) {
        return Err("file data is not valid base64".into());
    }
    let file = FileInput::from_value(value)?;
    let length = file.id.chars().count();
    if !(1..=128).contains(&length) {
        return Err("a file id must be 1 to 128 characters".into());
    }
    if let Some(digest) = &file.digest
        && (digest.algorithm != "sha-256"
            || decode_base64url(&digest.value).is_none_or(|value| value.len() != 32))
    {
        return Err(format!("file {} has an unsupported digest", file.id));
    }
    Ok(file)
}

fn check_metadata(file: &FileInput, constraints: &Constraints) -> Result<(), String> {
    if let Some(max_size) = constraints.max_size
        && file.size > max_size
    {
        return Err(format!("file {} is larger than {max_size} bytes", file.id));
    }
    for accept in &constraints.accept {
        if !accepts(accept, &file.mime_type) {
            return Err(format!(
                "file {} has a media type this tool does not accept",
                file.id
            ));
        }
    }
    if constraints.require_digest && file.digest.is_none() {
        return Err(format!("file {} requires a digest", file.id));
    }
    Ok(())
}

fn check_bytes(file: &FileInput, bytes: &[u8]) -> Result<(), String> {
    if bytes.len() as u64 != file.size {
        return Err(format!("file {} does not match its declared size", file.id));
    }
    if let Some(digest) = &file.digest
        && FileDigest::sha256(bytes).value != digest.value
    {
        return Err(format!("file {} does not match its digest", file.id));
    }
    Ok(())
}

fn essence(media_type: &str) -> String {
    media_type
        .split(';')
        .next()
        .unwrap_or_default()
        .trim()
        .to_ascii_lowercase()
}

fn accepts(accept: &[String], media_type: &str) -> bool {
    if accept.is_empty() {
        return true;
    }
    let media_type = essence(media_type);
    let Some((kind, _)) = media_type.split_once('/') else {
        return false;
    };
    accept.iter().any(|pattern| {
        let pattern = essence(pattern);
        pattern == "*/*"
            || pattern == media_type
            || pattern
                .strip_suffix("/*")
                .is_some_and(|range| range == kind)
    })
}

fn resolve<'a>(root: &'a Value, schema: &'a Value) -> &'a Value {
    let mut schema = schema;
    for _ in 0..MAX_SCHEMA_DEPTH {
        let Some(reference) = schema.get("$ref").and_then(Value::as_str) else {
            return schema;
        };
        match reference
            .strip_prefix('#')
            .and_then(|pointer| root.pointer(pointer))
        {
            Some(target) => schema = target,
            None => return schema,
        }
    }
    schema
}

fn collect_value(
    root: &Value,
    schema: &Value,
    value: &Value,
    path: &mut Pointer,
    found: &mut BTreeMap<Pointer, Constraints>,
    depth: usize,
) {
    if depth > MAX_SCHEMA_DEPTH {
        return;
    }
    let schema = resolve(root, schema);
    let Some(object) = schema.as_object() else {
        return;
    };
    if let Some(marker) = object.get(FILE_SCHEMA_KEYWORD).and_then(Value::as_object)
        && value.is_object()
    {
        let entry = found.entry(path.clone()).or_default();
        if let Some(accept) = marker.get("accept").and_then(Value::as_array) {
            entry.accept.push(
                accept
                    .iter()
                    .filter_map(Value::as_str)
                    .map(str::to_string)
                    .collect(),
            );
        }
        if let Some(max_size) = marker.get("maxSize").and_then(Value::as_u64) {
            entry.max_size = Some(
                entry
                    .max_size
                    .map_or(max_size, |current| current.min(max_size)),
            );
        }
        if object
            .get("required")
            .and_then(Value::as_array)
            .is_some_and(|required| required.iter().any(|name| name == "digest"))
        {
            entry.require_digest = true;
        }
        return;
    }
    for keyword in ["allOf", "anyOf", "oneOf"] {
        if let Some(branches) = object.get(keyword).and_then(Value::as_array) {
            for branch in branches {
                collect_value(root, branch, value, path, found, depth + 1);
            }
        }
    }
    match value {
        Value::Object(members) => {
            let properties = object.get("properties").and_then(Value::as_object);
            for (key, member) in members {
                let schema = properties
                    .and_then(|properties| properties.get(key))
                    .or_else(|| {
                        object
                            .get("additionalProperties")
                            .filter(|schema| schema.is_object())
                    });
                if let Some(schema) = schema {
                    path.push(Segment::Key(key.clone()));
                    collect_value(root, schema, member, path, found, depth + 1);
                    path.pop();
                }
            }
        }
        Value::Array(items) => {
            let prefix = object.get("prefixItems").and_then(Value::as_array);
            for (index, item) in items.iter().enumerate() {
                let schema = prefix
                    .and_then(|prefix| prefix.get(index))
                    .or_else(|| object.get("items").filter(|schema| schema.is_object()));
                if let Some(schema) = schema {
                    path.push(Segment::Index(index));
                    collect_value(root, schema, item, path, found, depth + 1);
                    path.pop();
                }
            }
        }
        _ => {}
    }
}

fn lookup<'a>(value: &'a Value, pointer: &[Segment]) -> Option<&'a Value> {
    pointer
        .iter()
        .try_fold(value, |value, segment| match segment {
            Segment::Key(key) => value.get(key),
            Segment::Index(index) => value.get(index),
        })
}

fn lookup_mut<'a>(value: &'a mut Value, pointer: &[Segment]) -> Option<&'a mut Value> {
    pointer
        .iter()
        .try_fold(value, |value, segment| match segment {
            Segment::Key(key) => value.get_mut(key),
            Segment::Index(index) => value.get_mut(index),
        })
}

/// SHA-256 over a canonical form of the arguments: object members sorted, and
/// numbers compared by value, as JSON Schema instance equality requires.
fn arguments_digest(value: &Value) -> String {
    let mut canonical = String::new();
    write_canonical(value, &mut canonical);
    encode_base64url(&Sha256::digest(canonical.as_bytes()))
}

fn write_canonical(value: &Value, out: &mut String) {
    match value {
        Value::Object(members) => {
            out.push('{');
            let sorted: BTreeMap<_, _> = members.iter().collect();
            for (index, (key, member)) in sorted.into_iter().enumerate() {
                if index > 0 {
                    out.push(',');
                }
                out.push_str(&Value::String(key.clone()).to_string());
                out.push(':');
                write_canonical(member, out);
            }
            out.push('}');
        }
        Value::Array(items) => {
            out.push('[');
            for (index, item) in items.iter().enumerate() {
                if index > 0 {
                    out.push(',');
                }
                write_canonical(item, out);
            }
            out.push(']');
        }
        Value::Number(number) => out.push_str(&canonical_number(&number.to_string())),
        other => out.push_str(&other.to_string()),
    }
}

/// Rewrites a JSON number token as sign, digits without leading or trailing
/// zeros, and a decimal exponent, so `1`, `1.0`, and `10e-1` agree.
fn canonical_number(token: &str) -> String {
    let (negative, token) = match token.strip_prefix('-') {
        Some(rest) => (true, rest),
        None => (false, token),
    };
    let (mantissa, exponent) = match token.find(['e', 'E']) {
        Some(index) => (
            &token[..index],
            token[index + 1..].parse::<i64>().unwrap_or(0),
        ),
        None => (token, 0),
    };
    let (integer, fraction) = mantissa.split_once('.').unwrap_or((mantissa, ""));
    let digits = format!("{integer}{fraction}");
    let mut exponent = exponent - fraction.len() as i64;
    let digits = digits.trim_start_matches('0');
    if digits.is_empty() {
        return "0".into();
    }
    let trimmed = digits.trim_end_matches('0');
    exponent += (digits.len() - trimmed.len()) as i64;
    format!("{}{trimmed}e{exponent}", if negative { "-" } else { "" })
}

fn hmac_sha256(key: &[u8], message: &[u8]) -> [u8; 32] {
    let mut block = [0u8; 64];
    if key.len() > 64 {
        block[..32].copy_from_slice(&Sha256::digest(key));
    } else {
        block[..key.len()].copy_from_slice(key);
    }
    let mut inner = Sha256::new();
    inner.update(block.map(|byte| byte ^ 0x36));
    inner.update(message);
    let mut outer = Sha256::new();
    outer.update(block.map(|byte| byte ^ 0x5c));
    outer.update(inner.finalize());
    outer.finalize().into()
}

fn constant_time_eq(left: &[u8], right: &[u8]) -> bool {
    left.len() == right.len()
        && left
            .iter()
            .zip(right)
            .fold(0u8, |difference, (left, right)| difference | (left ^ right))
            == 0
}

const STANDARD: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const URL_SAFE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";

fn encode_with(bytes: &[u8], alphabet: &[u8; 64], pad: bool) -> String {
    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
    for chunk in bytes.chunks(3) {
        let triple = (u32::from(chunk[0]) << 16)
            | (u32::from(*chunk.get(1).unwrap_or(&0)) << 8)
            | u32::from(*chunk.get(2).unwrap_or(&0));
        for index in 0..4 {
            if index <= chunk.len() {
                out.push(char::from(
                    alphabet[((triple >> (18 - 6 * index)) & 63) as usize],
                ));
            } else if pad {
                out.push('=');
            }
        }
    }
    out
}

fn decode_with(input: &str, alphabet: &[u8; 64], padded: bool) -> Option<Vec<u8>> {
    let bytes = input.as_bytes();
    let body = if padded {
        if !bytes.len().is_multiple_of(4) {
            return None;
        }
        let padding = bytes.iter().rev().take_while(|byte| **byte == b'=').count();
        if padding > 2 {
            return None;
        }
        &bytes[..bytes.len() - padding]
    } else {
        bytes
    };
    if body.len() % 4 == 1 {
        return None;
    }
    let mut out = Vec::with_capacity(body.len() * 3 / 4);
    let mut buffer = 0u32;
    let mut bits = 0u32;
    for byte in body {
        let sextet = alphabet.iter().position(|candidate| candidate == byte)? as u32;
        buffer = (buffer << 6) | sextet;
        bits += 6;
        if bits >= 8 {
            bits -= 8;
            out.push((buffer >> bits) as u8);
            buffer &= (1 << bits) - 1;
        }
    }
    // Non-canonical trailing bits make the encoding ambiguous.
    (buffer == 0).then_some(out)
}

/// Encodes bytes as RFC 4648 base64 with padding.
pub fn encode_base64(bytes: &[u8]) -> String {
    encode_with(bytes, STANDARD, true)
}

/// Decodes strict RFC 4648 base64 with padding.
pub fn decode_base64(input: &str) -> Option<Vec<u8>> {
    decode_with(input, STANDARD, true)
}

fn encode_base64url(bytes: &[u8]) -> String {
    encode_with(bytes, URL_SAFE, false)
}

fn decode_base64url(input: &str) -> Option<Vec<u8>> {
    decode_with(input, URL_SAFE, false)
}