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
//! File upload tests through the portable MCP server.

use std::collections::{BTreeMap, BTreeSet};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};

use futures::StreamExt;
use serde_json::{Value, json};
use web_time::SystemTime;

use super::*;
use crate::cli::Cli;
use crate::command::{CommandContext, CommandDef, CommandHandler};
use crate::mcp::{
    McpDiscovery, McpHttpBody, McpHttpConfig, McpHttpRequest, McpHttpServer, McpServeOptions,
    McpToolFilter,
};
use crate::output::CommandResult;

const MODERN: &str = "2026-07-28";
const KEY: &[u8] = b"0123456789abcdef0123456789abcdef";

#[test]
fn base64_matches_rfc_4648_vectors() {
    for (plain, encoded) in [
        ("", ""),
        ("f", "Zg=="),
        ("fo", "Zm8="),
        ("foo", "Zm9v"),
        ("foob", "Zm9vYg=="),
        ("fooba", "Zm9vYmE="),
        ("foobar", "Zm9vYmFy"),
    ] {
        assert_eq!(encode_base64(plain.as_bytes()), encoded);
        assert_eq!(decode_base64(encoded).unwrap(), plain.as_bytes());
    }
    assert!(decode_base64("Zm9vYg").is_none(), "padding is required");
    assert!(
        decode_base64("Zm9vYh==").is_none(),
        "trailing bits must be zero"
    );
    assert!(
        decode_base64("Zm9v_-==").is_none(),
        "url-safe letters are not base64"
    );
    assert_eq!(encode_base64url(&[0xfb, 0xff]), "-_8");
    assert_eq!(decode_base64url("-_8").unwrap(), [0xfb, 0xff]);
}

#[test]
fn hmac_matches_rfc_4231_case_2() {
    let mac = hmac_sha256(b"Jefe", b"what do ya want for nothing?");
    let hex: String = mac.iter().map(|byte| format!("{byte:02x}")).collect();
    assert_eq!(
        hex,
        "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"
    );
}

#[test]
fn canonical_arguments_compare_numbers_by_value() {
    let one = arguments_digest(&serde_json::from_str::<Value>(r#"{"b":1,"a":[10]}"#).unwrap());
    let same = arguments_digest(&serde_json::from_str::<Value>(r#"{"a":[1e1],"b":1.0}"#).unwrap());
    let other = arguments_digest(&serde_json::from_str::<Value>(r#"{"a":[10],"b":2}"#).unwrap());
    assert_eq!(one, same);
    assert_ne!(one, other);
    assert_eq!(canonical_number("0.0"), "0");
    assert_eq!(canonical_number("-120"), "-12e1");
}

#[test]
fn media_ranges_match_type_essence() {
    let accept = vec!["image/*".to_string(), "application/pdf".to_string()];
    assert!(accepts(&accept, "image/PNG"));
    assert!(accepts(&accept, "application/pdf; charset=binary"));
    assert!(!accepts(&accept, "text/plain"));
    assert!(!accepts(&accept, "imagefoo"));
}

/// In-memory staging: a client "transfer" writes bytes under the handle.
#[derive(Default)]
struct Staging {
    staged: Mutex<BTreeMap<String, Vec<u8>>>,
    consumed: Mutex<BTreeSet<String>>,
    issued: AtomicUsize,
}

impl Staging {
    fn put(&self, target: &Value, bytes: &[u8]) {
        let handle = target["url"]
            .as_str()
            .unwrap()
            .rsplit('/')
            .next()
            .unwrap()
            .to_string();
        self.staged.lock().unwrap().insert(handle, bytes.to_vec());
    }
}

#[async_trait::async_trait]
impl FileStaging for Staging {
    async fn issue(&self, file: &FileInput, _expires: SystemTime) -> Result<StagedTarget, String> {
        let handle = format!("{}-{}", file.id, self.issued.fetch_add(1, Ordering::SeqCst));
        Ok(StagedTarget {
            target: UploadTarget {
                url: Some(format!("https://uploads.example/{handle}")),
                credentials: "omit".into(),
                ..UploadTarget::default()
            },
            handle,
        })
    }

    async fn confirm(&self, handle: &str, _file: &FileInput) -> Result<Option<Vec<u8>>, String> {
        Ok(self.staged.lock().unwrap().get(handle).cloned())
    }

    async fn consume(&self, state_id: &str, _expires: SystemTime) -> Result<bool, String> {
        Ok(self.consumed.lock().unwrap().insert(state_id.to_string()))
    }
}

/// Reads its `upload` file and reports the bytes; asks for input when
/// `ask` is true and no answer has arrived.
struct ReadsFile {
    runs: Arc<AtomicUsize>,
}

#[async_trait::async_trait]
impl CommandHandler for ReadsFile {
    async fn run(&self, ctx: CommandContext) -> CommandResult {
        self.runs.fetch_add(1, Ordering::SeqCst);
        let mcp = ctx.mcp.clone();
        if ctx.options["ask"] == json!(true)
            && mcp.as_ref().is_none_or(|mcp| mcp.input_responses.is_none())
        {
            return CommandResult::InputRequired {
                input_requests: BTreeMap::from([(
                    "roots".to_string(),
                    json!({ "method": "roots/list", "params": {} }),
                )]),
                request_state: Some("inner-state".to_string()),
                meta: BTreeMap::new(),
            };
        }
        let file = match FileInput::from_value(&ctx.options["upload"]).and_then(|file| file.bytes())
        {
            Ok(bytes) => bytes,
            Err(message) => {
                return CommandResult::Ok {
                    data: json!({ "error": message }),
                    cta: None,
                    exit_code: None,
                };
            }
        };
        CommandResult::Ok {
            data: json!({
                "text": String::from_utf8_lossy(&file),
                "state": mcp.and_then(|mcp| mcp.request_state),
            }),
            cta: None,
            exit_code: None,
        }
    }
}

struct Fixture {
    server: McpHttpServer,
    staging: Arc<Staging>,
    runs: Arc<AtomicUsize>,
}

fn fixture(staging: bool, discovery: McpDiscovery) -> Fixture {
    let runs = Arc::new(AtomicUsize::new(0));
    let store = Arc::new(Staging::default());
    let command = CommandDef::build("ingest", ReadsFile { runs: runs.clone() })
        .description("Reads an uploaded file")
        .mcp_input_schema(json!({
            "type": "object",
            "properties": {
                "upload": file_schema(&["text/*"], Some(64), false),
                "ask": { "type": "boolean" }
            },
            "required": ["upload"]
        }))
        .done();
    let cli = Cli::create("files").command("ingest", command);
    let server = McpHttpServer::new(
        &cli,
        &McpServeOptions {
            tools: McpToolFilter {
                discovery,
                ..Default::default()
            },
            ..Default::default()
        },
        McpHttpConfig {
            files: Some(McpFilesOptions {
                max_inline_bytes: 32,
                staging: staging.then(|| store.clone() as Arc<dyn FileStaging>),
                signing_key: KEY.to_vec(),
                ..McpFilesOptions::default()
            }),
            task_spawner: None,
            ..McpHttpConfig::default()
        },
    )
    .unwrap();
    Fixture {
        server,
        staging: store,
        runs,
    }
}

fn capabilities(upload: bool, download: bool) -> Value {
    let mut files = serde_json::Map::new();
    if upload {
        files.insert("upload".into(), json!({}));
    }
    if download {
        files.insert("download".into(), json!({}));
    }
    json!({ "extensions": { FILES_EXTENSION: files } })
}

async fn call(server: &McpHttpServer, params: Value) -> Value {
    send(server, "tools/call", params).await
}

async fn send(server: &McpHttpServer, method: &str, params: Value) -> Value {
    let request = McpHttpRequest {
        method: "POST".into(),
        path: "/mcp".into(),
        headers: vec![
            ("host".into(), "localhost".into()),
            ("content-type".into(), "application/json".into()),
            (
                "accept".into(),
                "application/json, text/event-stream".into(),
            ),
            ("mcp-protocol-version".into(), MODERN.into()),
            ("mcp-method".into(), method.into()),
            (
                "mcp-name".into(),
                params["name"].as_str().unwrap_or_default().into(),
            ),
        ],
        body: serde_json::to_vec(&json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": method,
            "params": params,
        }))
        .unwrap(),
    };
    let response = server.handle(request).await;
    match response.body {
        McpHttpBody::Full(body) => serde_json::from_slice(&body).unwrap(),
        McpHttpBody::EventStream(mut stream) => {
            let mut last = Value::Null;
            while let Some(event) = stream.next().await {
                let payload = event
                    .strip_prefix("data: ")
                    .and_then(|event| event.strip_suffix("\n\n"))
                    .unwrap();
                last = serde_json::from_str(payload).unwrap();
            }
            last
        }
        #[allow(unreachable_patterns, reason = "future body kinds")]
        _ => panic!("unexpected body"),
    }
}

/// The command's data, carried as JSON text without an output schema.
fn output(reply: &Value) -> Value {
    reply["result"]["content"][0]["text"]
        .as_str()
        .and_then(|text| serde_json::from_str(text).ok())
        .unwrap_or(Value::Null)
}

trait Pipe {
    fn pipe(&self, f: fn(&Value) -> Value) -> Value;
}

impl Pipe for Value {
    fn pipe(&self, f: fn(&Value) -> Value) -> Value {
        f(self)
    }
}

fn params(arguments: Value, capabilities: Value) -> Value {
    json!({
        "name": "ingest",
        "arguments": arguments,
        "_meta": {
            "io.modelcontextprotocol/protocolVersion": MODERN,
            "io.modelcontextprotocol/clientCapabilities": capabilities,
        }
    })
}

fn pending(bytes: &[u8]) -> Value {
    serde_json::to_value(FileInput::metadata(
        "doc",
        Some("a.txt".into()),
        "text/plain",
        bytes,
    ))
    .unwrap()
}

#[test]
fn discover_advertises_upload_and_inline_limit() {
    futures::executor::block_on(async {
        let Fixture { server, .. } = fixture(true, McpDiscovery::Direct);
        let body = send(
            &server,
            "server/discover",
            json!({ "_meta": {
                "io.modelcontextprotocol/protocolVersion": MODERN,
                "io.modelcontextprotocol/clientCapabilities": {}
            } }),
        )
        .await;
        assert_eq!(
            body["result"]["capabilities"]["extensions"][FILES_EXTENSION],
            json!({ "upload": {}, "maxInlineBytes": 32 }),
            "{body}"
        );
    });
}

#[test]
fn inline_files_reach_the_command_checked() {
    futures::executor::block_on(async {
        let Fixture { server, runs, .. } = fixture(false, McpDiscovery::Direct);
        let file = FileInput::inline("doc", None, "text/plain", b"hello");
        let reply = call(&server, params(json!({ "upload": file }), json!({}))).await;
        assert_eq!(reply.pipe(output)["text"], "hello", "{reply}");

        let mut wrong =
            serde_json::to_value(FileInput::inline("doc", None, "text/plain", b"hello")).unwrap();
        wrong["digest"] = serde_json::to_value(FileDigest::sha256(b"other")).unwrap();
        let reply = call(&server, params(json!({ "upload": wrong }), json!({}))).await;
        assert_eq!(reply["result"]["isError"], true, "{reply}");

        let mut short =
            serde_json::to_value(FileInput::inline("doc", None, "text/plain", b"hello")).unwrap();
        short["size"] = json!(4);
        let reply = call(&server, params(json!({ "upload": short }), json!({}))).await;
        assert_eq!(reply["result"]["isError"], true, "{reply}");

        let mut nulled =
            serde_json::to_value(FileInput::inline("doc", None, "text/plain", b"hello")).unwrap();
        nulled["data"] = Value::Null;
        let reply = call(&server, params(json!({ "upload": nulled }), json!({}))).await;
        assert_eq!(reply["result"]["isError"], true, "{reply}");

        let large = FileInput::inline("doc", None, "text/plain", &[b'a'; 40]);
        let reply = call(&server, params(json!({ "upload": large }), json!({}))).await;
        assert_eq!(reply["result"]["isError"], true, "inline limit: {reply}");

        let image = FileInput::inline("doc", None, "image/png", b"png");
        let reply = call(&server, params(json!({ "upload": image }), json!({}))).await;
        assert_eq!(reply["result"]["isError"], true, "accept: {reply}");

        assert_eq!(runs.load(Ordering::SeqCst), 1, "only the valid call ran");

        let reply = call(
            &server,
            params(json!({ "upload": pending(b"hello") }), json!({})),
        )
        .await;
        assert_eq!(reply["result"]["isError"], true, "no staging: {reply}");
        assert_eq!(runs.load(Ordering::SeqCst), 1);
    });
}

#[test]
fn duplicate_file_ids_are_rejected() {
    futures::executor::block_on(async {
        let runs = Arc::new(AtomicUsize::new(0));
        let command = CommandDef::build("ingest", ReadsFile { runs: runs.clone() })
            .mcp_input_schema(json!({
                "type": "object",
                "properties": {
                    "upload": file_schema(&[], None, false),
                    "files": { "type": "array", "items": file_schema(&[], None, false) }
                }
            }))
            .done();
        let cli = Cli::create("files").command("ingest", command);
        let server = McpHttpServer::new(
            &cli,
            &McpServeOptions {
                tools: McpToolFilter {
                    discovery: McpDiscovery::Direct,
                    ..Default::default()
                },
                ..Default::default()
            },
            McpHttpConfig {
                files: Some(McpFilesOptions::default()),
                task_spawner: None,
                ..McpHttpConfig::default()
            },
        )
        .unwrap();
        let file = FileInput::inline("same", None, "text/plain", b"a");
        let reply = call(
            &server,
            params(json!({ "upload": file, "files": [file] }), json!({})),
        )
        .await;
        assert_eq!(reply["result"]["isError"], true, "{reply}");
        assert_eq!(runs.load(Ordering::SeqCst), 0);
    });
}

#[test]
fn out_of_band_upload_requires_the_declared_capability() {
    futures::executor::block_on(async {
        let Fixture { server, runs, .. } = fixture(true, McpDiscovery::Direct);
        let reply = call(
            &server,
            params(json!({ "upload": pending(b"hello") }), json!({})),
        )
        .await;
        assert_eq!(reply["error"]["code"], -32021, "{reply}");
        assert_eq!(
            reply["error"]["data"]["requiredCapabilities"]["extensions"][FILES_EXTENSION],
            json!({ "upload": {} })
        );
        assert_eq!(runs.load(Ordering::SeqCst), 0);
    });
}

#[test]
fn out_of_band_upload_round_trips_once() {
    futures::executor::block_on(async {
        let Fixture {
            server,
            staging,
            runs,
        } = fixture(true, McpDiscovery::Direct);
        let arguments = json!({ "upload": pending(b"hello out of band") });
        let first = call(
            &server,
            params(arguments.clone(), capabilities(true, false)),
        )
        .await;
        let result = &first["result"];
        assert_eq!(result["resultType"], "upload_required", "{first}");
        let uploads = result["uploads"].as_array().unwrap();
        assert_eq!(uploads.len(), 1);
        assert_eq!(uploads[0]["fileId"], "doc");
        let state = result["requestState"].as_str().unwrap().to_string();
        assert_eq!(runs.load(Ordering::SeqCst), 0);

        let mut retry = params(arguments.clone(), capabilities(true, false));
        retry["requestState"] = json!(state);

        // Bytes that have not arrived leave the state unconsumed.
        let early = call(&server, retry.clone()).await;
        assert_eq!(early["result"]["isError"], true, "{early}");
        assert_eq!(runs.load(Ordering::SeqCst), 0);

        // Different bytes fail the digest check.
        staging.put(&uploads[0], b"HELLO OUT OF BAND");
        let wrong = call(&server, retry.clone()).await;
        assert_eq!(wrong["result"]["isError"], true, "{wrong}");

        staging.put(&uploads[0], b"hello out of band");
        let done = call(&server, retry.clone()).await;
        assert_eq!(done.pipe(output)["text"], "hello out of band", "{done}");
        assert_eq!(done.pipe(output)["state"], Value::Null);
        assert_eq!(runs.load(Ordering::SeqCst), 1);

        let replay = call(&server, retry).await;
        assert_eq!(replay["error"]["code"], -32602, "consumed: {replay}");
        assert_eq!(runs.load(Ordering::SeqCst), 1);
    });
}

#[test]
fn request_state_binds_arguments_and_signature() {
    futures::executor::block_on(async {
        let Fixture {
            server,
            staging,
            runs,
        } = fixture(true, McpDiscovery::Direct);
        let arguments = json!({ "upload": pending(b"bound") });
        let first = call(
            &server,
            params(arguments.clone(), capabilities(true, false)),
        )
        .await;
        let state = first["result"]["requestState"]
            .as_str()
            .unwrap()
            .to_string();
        staging.put(&first["result"]["uploads"][0], b"bound");

        let mut changed = params(
            json!({ "upload": pending(b"bound"), "ask": false }),
            capabilities(true, false),
        );
        changed["requestState"] = json!(state);
        let reply = call(&server, changed).await;
        assert_eq!(reply["error"]["code"], -32602, "arguments: {reply}");

        let mut tampered_state = state.clone();
        let last = tampered_state.pop().unwrap();
        tampered_state.push(if last == 'A' { 'B' } else { 'A' });
        let mut tampered = params(arguments.clone(), capabilities(true, false));
        tampered["requestState"] = json!(tampered_state);
        let reply = call(&server, tampered).await;
        assert_eq!(reply["error"]["code"], -32602, "signature: {reply}");

        assert_eq!(runs.load(Ordering::SeqCst), 0);

        // Same arguments with reordered members and an equal number still match.
        let mut reordered = params(arguments, capabilities(true, false));
        reordered["requestState"] = json!(state);
        let reply = call(&server, reordered).await;
        assert_eq!(reply.pipe(output)["text"], "bound", "{reply}");
    });
}

#[test]
fn later_input_requests_keep_the_file_binding() {
    futures::executor::block_on(async {
        let Fixture {
            server,
            staging,
            runs,
        } = fixture(true, McpDiscovery::Direct);
        let arguments = json!({ "upload": pending(b"ask"), "ask": true });
        let first = call(
            &server,
            params(arguments.clone(), capabilities(true, false)),
        )
        .await;
        staging.put(&first["result"]["uploads"][0], b"ask");
        let mut retry = params(arguments.clone(), capabilities(true, false));
        retry["requestState"] = first["result"]["requestState"].clone();
        let second = call(&server, retry).await;
        assert_eq!(second["result"]["resultType"], "input_required", "{second}");
        let wrapped = second["result"]["requestState"].as_str().unwrap();
        assert!(wrapped.starts_with(STATE_PREFIX), "{wrapped}");
        assert_ne!(json!(wrapped), first["result"]["requestState"]);

        let mut answer = params(arguments, capabilities(true, false));
        answer["requestState"] = json!(wrapped);
        answer["inputResponses"] = json!({ "roots": { "roots": [] } });
        let third = call(&server, answer.clone()).await;
        assert_eq!(third.pipe(output)["text"], "ask", "{third}");
        assert_eq!(third.pipe(output)["state"], "inner-state");
        assert_eq!(runs.load(Ordering::SeqCst), 2);
        let replay = call(&server, answer).await;
        assert_eq!(replay["error"]["code"], -32602, "{replay}");
    });
}

#[test]
fn progressive_calls_check_nested_file_arguments() {
    futures::executor::block_on(async {
        let Fixture {
            server,
            staging,
            runs,
        } = fixture(true, McpDiscovery::Progressive);
        let execute = |state: Option<&str>| {
            let mut params = json!({
                "name": "call_write_tool",
                "arguments": { "name": "ingest", "arguments": { "upload": pending(b"nested") } },
                "_meta": {
                    "io.modelcontextprotocol/protocolVersion": MODERN,
                    "io.modelcontextprotocol/clientCapabilities": capabilities(true, false),
                }
            });
            if let Some(state) = state {
                params["requestState"] = json!(state);
            }
            params
        };
        let first = call(&server, execute(None)).await;
        assert_eq!(first["result"]["resultType"], "upload_required", "{first}");
        staging.put(&first["result"]["uploads"][0], b"nested");
        let done = call(&server, execute(first["result"]["requestState"].as_str())).await;
        assert_eq!(done.pipe(output)["text"], "nested", "{done}");
        assert_eq!(runs.load(Ordering::SeqCst), 1);
    });
}

#[test]
fn downloads_are_removed_unless_declared() {
    let mut result = json!({
        "content": [],
        "_meta": downloads_meta(&[DownloadTarget {
            url: Some("https://downloads.example/report".into()),
            mime_type: "text/plain".into(),
            size: 6,
            credentials: "omit".into(),
            ..DownloadTarget::default()
        }])
    });
    let options = McpFilesOptions::default();
    let mut kept = result.clone();
    options.finish(
        &mut kept,
        None,
        Declared {
            upload: false,
            download: true,
        },
    );
    assert!(kept["_meta"][FILES_EXTENSION]["downloads"].is_array());
    options.finish(&mut result, None, Declared::default());
    assert!(result.get("_meta").is_none(), "{result}");
}

#[test]
fn unknown_revisions_disable_the_extension() {
    let declared = Declared::from_capabilities(Some(&json!({
        "extensions": { FILES_EXTENSION: { "upload": {}, "revision": "2099-01-01" } }
    })));
    assert_eq!(declared, Declared::default());
    assert!(Declared::from_capabilities(Some(&capabilities(true, true))).download);
}