multicast 1.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
//! Exporter-backed controls through public CLI, catalog, and MCP boundaries.
#![cfg(all(feature = "http", not(target_arch = "wasm32")))]

use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};
use std::time::Duration;

use futures::StreamExt;
use multicast::cli::Cli;
use multicast::command::{CommandContext, CommandDef, CommandHandler};
use multicast::mcp::{
    McpDiscovery, McpHttpBody, McpHttpConfig, McpHttpRequest, McpHttpServer, McpRemoteOptions,
    McpServeOptions, McpToolFilter,
};
use multicast::mcp_client::McpHttpClient;
use multicast::output::{CommandResult, StreamRecord};
use multicast::tool::ToolCallOptions;
use opentelemetry::trace::{FutureExt, SpanKind, Status, TraceContextExt, Tracer, TracerProvider};
use opentelemetry::{Context, global};
use opentelemetry_sdk::metrics::data::{AggregatedMetrics, MetricData};
use opentelemetry_sdk::metrics::{InMemoryMetricExporter, PeriodicReader, SdkMeterProvider};
use opentelemetry_sdk::propagation::TraceContextPropagator;
use opentelemetry_sdk::trace::{InMemorySpanExporter, SdkTracerProvider, SpanData};
use serde_json::{Value, json};

const SECRET: &str = "private-payload-946372";

struct Handler {
    kind: &'static str,
    seen: Arc<Mutex<Vec<opentelemetry::trace::SpanContext>>>,
}
#[async_trait::async_trait]
impl CommandHandler for Handler {
    async fn run(&self, _: CommandContext) -> CommandResult {
        let before = Context::current().span().span_context().clone();
        tokio::task::yield_now().await;
        assert_eq!(
            before,
            *Context::current().span().span_context(),
            "context survives an await"
        );
        self.seen.lock().unwrap().push(before);
        match self.kind {
            "failure" => CommandResult::Error {
                code: "EXPECTED_FAILURE".into(),
                message: SECRET.into(),
                retryable: false,
                exit_code: None,
                cta: None,
            },
            "stream" | "stream_error" => {
                let error = self.kind == "stream_error";
                CommandResult::RecordStream(Box::pin(async_stream::stream! {
                    tokio::time::sleep(Duration::from_millis(30)).await;
                    yield StreamRecord::Chunk(json!(SECRET));
                    if error { yield StreamRecord::Error { code: "STREAM_FAILED".into(), message: SECRET.into(), retryable: false, exit_code: None, cta: None }; }
                    else { yield StreamRecord::Ok { cta: None }; }
                }))
            }
            "wait" => std::future::pending().await,
            _ => CommandResult::Ok {
                data: json!({ "secret": SECRET }),
                cta: None,
                exit_code: None,
            },
        }
    }
}
fn cli(enabled: bool, seen: &Arc<Mutex<Vec<opentelemetry::trace::SpanContext>>>) -> Cli {
    let mut cli = Cli::create("observed")
        .open_telemetry(enabled)
        .mcp(McpServeOptions {
            tools: McpToolFilter {
                discovery: McpDiscovery::Direct,
                ..Default::default()
            },
            ..Default::default()
        });
    for name in ["success", "failure", "stream", "stream_error", "wait"] {
        cli = cli.command(
            name,
            CommandDef::build(
                name,
                Handler {
                    kind: name,
                    seen: seen.clone(),
                },
            )
            .done(),
        );
    }
    cli
}
fn attr(span: &SpanData, key: &str) -> Option<String> {
    span.attributes
        .iter()
        .find(|kv| kv.key.as_str() == key)
        .map(|kv| kv.value.to_string())
}
async fn portable(server: &McpHttpServer, message: Value) -> Vec<Value> {
    let response = server
        .handle(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(), "2025-03-26".into()),
            ],
            body: serde_json::to_vec(&message).unwrap(),
        })
        .await;
    assert!(matches!(response.status, 200 | 202), "{response:?}");
    match response.body {
        McpHttpBody::EventStream(mut stream) => {
            let mut values = Vec::new();
            while let Some(chunk) = stream.next().await {
                for line in chunk.lines().filter_map(|l| l.strip_prefix("data: ")) {
                    values.push(serde_json::from_str(line).unwrap());
                }
            }
            values
        }
        McpHttpBody::Full(bytes) => vec![serde_json::from_slice(&bytes).unwrap()],
        McpHttpBody::Empty => Vec::new(),
    }
}

// One test owns the process-global providers; no global-provider races with
// other integration binaries or parallel cases.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn exported_observations_follow_real_execution() {
    let spans = InMemorySpanExporter::default();
    let trace_provider = SdkTracerProvider::builder()
        .with_simple_exporter(spans.clone())
        .build();
    let metrics = InMemoryMetricExporter::default();
    let reader = PeriodicReader::builder(metrics.clone())
        .with_interval(Duration::from_secs(3600))
        .build();
    let meter_provider = SdkMeterProvider::builder().with_reader(reader).build();
    global::set_tracer_provider(trace_provider.clone());
    global::set_meter_provider(meter_provider.clone());
    global::set_text_map_propagator(TraceContextPropagator::new());
    let seen = Arc::new(Mutex::new(Vec::new()));
    let app = cli(true, &seen);

    let root = trace_provider.tracer("host").start("host-operation");
    let root_context = Context::new().with_span(root);
    let root_id = root_context.span().span_context().span_id();
    app.tool_catalog()
        .call("success", BTreeMap::new(), ToolCallOptions::isolated())
        .with_context(root_context.clone())
        .await;
    let command = spans
        .get_finished_spans()
        .unwrap()
        .into_iter()
        .find(|s| s.name == "multicast.command success")
        .unwrap();
    assert_eq!(command.parent_span_id, root_id);
    assert_eq!(command.span_kind, SpanKind::Internal);

    let mut stdout = Vec::new();
    app.serve_to(vec!["failure".into(), "--json".into()], &mut stdout, false)
        .await
        .unwrap();
    assert!(
        String::from_utf8(stdout)
            .unwrap()
            .contains("EXPECTED_FAILURE")
    );
    for name in ["stream", "stream_error"] {
        app.tool_catalog()
            .call(name, BTreeMap::new(), ToolCallOptions::isolated())
            .await;
    }

    // Confirm a dropped active execution records cancellation exactly once.
    let catalog = app.tool_catalog();
    let observed_before = seen.lock().unwrap().len();
    let waiting = tokio::spawn(async move {
        catalog
            .call("wait", BTreeMap::new(), ToolCallOptions::isolated())
            .await
    });
    tokio::time::timeout(Duration::from_secs(5), async {
        while seen.lock().unwrap().len() == observed_before {
            tokio::task::yield_now().await;
        }
    })
    .await
    .unwrap();
    waiting.abort();
    assert!(waiting.await.unwrap_err().is_cancelled());

    let server = McpHttpServer::from_cli(&app, McpHttpConfig::default()).unwrap();
    let remote_trace = "4bf92f3577b34da6a3ce929d0e0e4736";
    let remote_parent = "00f067aa0ba902b7";
    let call = |name: &str, id: i64| json!({ "jsonrpc": "2.0", "id": id, "method": "tools/call", "params": { "name": name, "arguments": {}, "_meta": { "traceparent": format!("00-{remote_trace}-{remote_parent}-01"), "example/keep": true } } });
    assert_eq!(
        portable(&server, call("success", 1))
            .with_context(root_context.clone())
            .await
            .len(),
        1
    );
    let failed = portable(&server, call("failure", 2)).await;
    assert_eq!(failed[0]["result"]["isError"], true);
    portable(
        &server,
        json!({ "jsonrpc": "2.0", "method": "notifications/initialized", "params": { "_meta": { "traceparent": format!("00-{remote_trace}-{remote_parent}-01") } } }),
    )
    .await;
    portable(&server, json!({ "jsonrpc": "2.0", "method": "notifications/message", "params": {"level": "info", "data": SECRET} })).await;

    let captured_meta = Arc::new(Mutex::new(None));
    let captured = captured_meta.clone();
    let peer = multicast::command::McpPeer::new(move |request| {
        *captured.lock().unwrap() = request.meta;
        async { Ok(json!({})) }
    });
    peer.request(multicast::command::McpPeerRequest {
        method: "elicitation/create".into(),
        params: Some(json!({"secret": SECRET})),
        meta: Some(json!({"example/keep": true})),
    })
    .with_context(root_context.clone())
    .await
    .unwrap();
    let meta = captured_meta.lock().unwrap().clone().unwrap();
    assert_eq!(meta["example/keep"], true);
    assert!(
        meta["traceparent"]
            .as_str()
            .unwrap()
            .contains(&root_context.span().span_context().trace_id().to_string())
    );

    for (method, code) in [
        ("roots/list", "-32602"),
        ("sampling/createMessage", "-32603"),
    ] {
        let peer = multicast::command::McpPeer::new(move |_| async move {
            Err(multicast::command::McpPeerError {
                code: code.into(),
                message: SECRET.into(),
                data: None,
            })
        });
        peer.request(multicast::command::McpPeerRequest {
            method: method.into(),
            params: None,
            meta: None,
        })
        .await
        .unwrap_err();
    }

    // Native HTTP uses the same exporters and propagation through real sockets.
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let router = multicast::http::build_cli_router(&app).unwrap();
    let native = tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
    let native_start = spans.get_finished_spans().unwrap().len();
    let client =
        McpHttpClient::connect(&format!("http://{addr}/mcp"), &McpRemoteOptions::default())
            .with_context(root_context.clone())
            .await
            .unwrap();
    let result = client
        .call_tool("success", serde_json::Map::new())
        .with_context(root_context.clone())
        .await
        .unwrap();
    assert_ne!(result.get("isError"), Some(&json!(true)));
    let native_spans = spans.get_finished_spans().unwrap()[native_start..].to_vec();
    let client_span = native_spans
        .iter()
        .find(|s| s.name == "tools/call success" && s.span_kind == SpanKind::Client)
        .unwrap();
    let server_span = native_spans
        .iter()
        .find(|s| s.name == "tools/call success" && s.span_kind == SpanKind::Server)
        .unwrap();
    assert_eq!(client_span.parent_span_id, root_id);
    assert_eq!(
        server_span.parent_span_id,
        client_span.span_context.span_id()
    );
    assert_eq!(
        server_span.span_context.trace_id(),
        client_span.span_context.trace_id()
    );
    native.abort();

    let before = spans.get_finished_spans().unwrap().len();
    let disabled = cli(false, &seen);
    disabled
        .tool_catalog()
        .call("success", BTreeMap::new(), ToolCallOptions::isolated())
        .await;
    let mut stdout = Vec::new();
    disabled
        .serve_to(vec!["success".into(), "--json".into()], &mut stdout, false)
        .await
        .unwrap();
    let disabled_server = McpHttpServer::from_cli(&disabled, McpHttpConfig::default()).unwrap();
    portable(&disabled_server, call("success", 3)).await;
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let router = multicast::http::build_cli_router(&disabled).unwrap();
    let native_disabled = tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
    let options = McpRemoteOptions {
        open_telemetry: false,
        ..Default::default()
    };
    let client = McpHttpClient::connect(&format!("http://{addr}/mcp"), &options)
        .with_context(root_context.clone())
        .await
        .unwrap();
    client
        .call_tool("success", serde_json::Map::new())
        .with_context(root_context.clone())
        .await
        .unwrap();
    native_disabled.abort();
    assert_eq!(
        spans.get_finished_spans().unwrap().len(),
        before,
        "instance opt-out suppresses both protocol and command telemetry"
    );

    let exported = spans.get_finished_spans().unwrap();
    let remote = exported
        .iter()
        .find(|s| {
            s.name == "tools/call success" && s.span_context.trace_id().to_string() == remote_trace
        })
        .unwrap();
    assert_eq!(remote.parent_span_id.to_string(), remote_parent);
    assert_eq!(remote.links.links.len(), 1);
    assert_eq!(remote.links.links[0].span_context.span_id(), root_id);
    let notification = exported
        .iter()
        .find(|s| {
            s.name == "notifications/initialized"
                && s.span_context.trace_id().to_string() == remote_trace
        })
        .unwrap();
    assert_eq!(notification.parent_span_id.to_string(), remote_parent);
    let invalid = exported.iter().find(|s| s.name == "roots/list").unwrap();
    assert_eq!(
        attr(invalid, "rpc.response.status_code").as_deref(),
        Some("-32602")
    );
    assert_eq!(attr(invalid, "error.type"), None);
    assert_eq!(invalid.status, Status::Unset);
    let internal = exported
        .iter()
        .find(|s| s.name == "sampling/createMessage")
        .unwrap();
    assert_eq!(
        attr(internal, "rpc.response.status_code").as_deref(),
        Some("-32603")
    );
    assert_eq!(attr(internal, "error.type").as_deref(), Some("-32603"));
    assert!(matches!(internal.status, Status::Error { .. }));
    assert!(
        exported
            .iter()
            .any(|s| s.name == "notifications/initialized")
    );
    assert!(!exported.iter().any(|s| s.name == "notifications/message"));
    for (name, error) in [
        ("multicast.command failure", "EXPECTED_FAILURE"),
        ("multicast.command stream_error", "STREAM_FAILED"),
        ("multicast.command wait", "cancelled"),
        ("tools/call failure", "tool_error"),
    ] {
        let span = exported.iter().find(|s| s.name == name).unwrap();
        assert_eq!(attr(span, "error.type").as_deref(), Some(error));
        assert!(matches!(span.status, Status::Error { .. }));
    }
    let stream = exported
        .iter()
        .find(|s| s.name == "multicast.command stream")
        .unwrap();
    assert!(
        stream.end_time.duration_since(stream.start_time).unwrap() >= Duration::from_millis(25)
    );
    assert_eq!(
        exported
            .iter()
            .filter(|s| s.name == "multicast.command wait")
            .count(),
        1
    );
    assert!(!format!("{exported:?}").contains(SECRET));

    meter_provider.force_flush().unwrap();
    let metric_batches = metrics.get_finished_metrics().unwrap();
    let mut names = Vec::new();
    let mut command_count = 0;
    let mut failures = BTreeMap::<String, u64>::new();
    for batch in &metric_batches {
        for scope in batch.scope_metrics() {
            for metric in scope.metrics() {
                names.push(metric.name().to_string());
                assert_eq!(metric.unit(), "s");
                let AggregatedMetrics::F64(MetricData::Histogram(hist)) = metric.data() else {
                    panic!("duration histogram")
                };
                for point in hist.data_points() {
                    assert!(point.count() > 0);
                    if metric.name() == "multicast.command.duration" {
                        command_count += point.count();
                    }
                    if let Some(error) = point
                        .attributes()
                        .find(|kv| kv.key.as_str() == "error.type")
                    {
                        *failures.entry(error.value.to_string()).or_default() += point.count();
                    }
                    assert!(
                        point.sum() >= 0.0 && point.sum() < 60.0,
                        "durations use seconds"
                    );
                    assert_eq!(
                        point.bounds().collect::<Vec<_>>(),
                        vec![
                            0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 30.0, 60.0,
                            120.0, 300.0
                        ]
                    );
                    for kv in point.attributes() {
                        assert!(
                            !["jsonrpc.request.id", "mcp.resource.uri"].contains(&kv.key.as_str())
                        );
                    }
                }
            }
        }
    }
    for name in [
        "multicast.command.duration",
        "mcp.client.operation.duration",
        "mcp.server.operation.duration",
    ] {
        assert!(names.iter().any(|n| n == name), "missing {name}");
    }
    // Eight explicitly invoked enabled commands above; all disabled invocations
    // must leave this count unchanged, including calls over real HTTP.
    assert_eq!(command_count, 8);
    for error in [
        "EXPECTED_FAILURE",
        "STREAM_FAILED",
        "cancelled",
        "tool_error",
        "-32603",
    ] {
        assert!(
            failures.get(error).copied().unwrap_or(0) > 0,
            "missing metric error {error}"
        );
    }
    assert!(!failures.contains_key("-32602"));
    assert!(!format!("{metric_batches:?}").contains(SECRET));
    root_context.span().end();
    trace_provider.shutdown().unwrap();
    meter_provider.shutdown().unwrap();
}