multicast 1.0.0

A declarative CLI framework for Rust with typed commands, agent discovery, HTTP, and MCP
Documentation
//! Built-in command and MCP observability using the host's OpenTelemetry setup.
//!
//! Install global trace and meter providers and a text-map propagator before
//! serving a CLI. Multicast never installs an SDK, exporter, or background runtime.
//! Without providers, the OpenTelemetry API is a no-op. Disable instrumentation
//! for an instance with [`crate::cli::Cli::open_telemetry`].
//!
//! Commands emit `multicast.command` spans and `multicast.command.duration` histograms.
//! MCP operations emit CLIENT/SERVER spans and `mcp.client.operation.duration` or
//! `mcp.server.operation.duration` histograms in seconds. MCP context travels in
//! `params._meta` through the configured global propagator. Arguments, results,
//! resource URIs, credentials, and request IDs are never telemetry attributes.

use std::sync::Arc;

use futures::StreamExt;
use opentelemetry::metrics::Histogram;
use opentelemetry::propagation::{Extractor, Injector};
use opentelemetry::trace::{FutureExt, SpanKind, Status, TraceContextExt, Tracer};
use opentelemetry::{Context, KeyValue, global};
use serde_json::{Map, Value};
use web_time::Instant;

/// OpenTelemetry API version used by Multicast, for host provider configuration.
pub use opentelemetry;

#[derive(Clone)]
struct Disabled;

/// Whether library instrumentation is enabled in the current execution context.
///
/// Integrations must propagate the context across task and thread boundaries to
/// retain an instance's opt-out. This does not indicate whether an SDK is installed.
pub fn is_enabled() -> bool {
    Context::current().get::<Disabled>().is_none()
}

pub(crate) struct Operation {
    context: Context,
    histogram: Option<Histogram<f64>>,
    attributes: Vec<KeyValue>,
    started: Instant,
    complete: bool,
}

impl Operation {
    fn start(
        enabled: bool,
        name: String,
        kind: SpanKind,
        metric: &'static str,
        attributes: Vec<KeyValue>,
        parent: Context,
        link: Option<Context>,
    ) -> Self {
        let enabled = enabled && Context::current().get::<Disabled>().is_none();
        let context = if enabled {
            let tracer = global::tracer("multicast");
            let mut builder = tracer
                .span_builder(name)
                .with_kind(kind)
                .with_attributes(attributes.clone());
            if let Some(link) = link {
                let span = link.span().span_context().clone();
                if span.is_valid() && span != *parent.span().span_context() {
                    builder = builder.with_links(vec![opentelemetry::trace::Link::new(
                        span,
                        Vec::new(),
                        0,
                    )]);
                }
            }
            parent.with_span(tracer.build_with_context(builder, &parent))
        } else {
            Context::current().with_value(Disabled)
        };
        let histogram = enabled.then(|| {
            global::meter("multicast")
                .f64_histogram(metric)
                .with_unit("s")
                .with_description("Operation duration")
                .with_boundaries(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,
                ])
                .build()
        });
        Self {
            context,
            histogram,
            attributes,
            started: Instant::now(),
            complete: false,
        }
    }

    pub(crate) fn context(&self) -> Context {
        self.context.clone()
    }

    fn mcp(
        enabled: bool,
        method: &str,
        params: Option<&Value>,
        version: Option<&str>,
        kind: SpanKind,
        parent: Context,
        link: Option<Context>,
    ) -> Self {
        // Custom methods do not create unbounded metric series.
        let method = match method {
            "initialize"
            | "ping"
            | "server/discover"
            | "tools/list"
            | "tools/call"
            | "prompts/list"
            | "prompts/get"
            | "resources/list"
            | "resources/read"
            | "resources/templates/list"
            | "resources/subscribe"
            | "resources/unsubscribe"
            | "completion/complete"
            | "logging/setLevel"
            | "sampling/createMessage"
            | "elicitation/create"
            | "roots/list"
            | "tasks/get"
            | "tasks/list"
            | "tasks/result"
            | "tasks/cancel"
            | "tasks/update"
            | "subscriptions/listen"
            | "notifications/initialized"
            | "notifications/cancelled"
            | "notifications/progress"
            | "notifications/tools/list_changed"
            | "notifications/prompts/list_changed"
            | "notifications/resources/list_changed"
            | "notifications/resources/updated"
            | "notifications/roots/list_changed"
            | "notifications/tasks/status"
            | "notifications/elicitation/complete"
            | "notifications/message" => method,
            _ => "_OTHER",
        };
        let mut attrs = vec![KeyValue::new("mcp.method.name", method.to_string())];
        let mut name = method.to_string();
        let target = match method {
            "tools/call" => {
                attrs.push(KeyValue::new("gen_ai.operation.name", "execute_tool"));
                Some("gen_ai.tool.name")
            }
            "prompts/get" => Some("gen_ai.prompt.name"),
            _ => None,
        };
        if let Some(key) = target
            && let Some(target) = params.and_then(|p| p.get("name")).and_then(Value::as_str)
        {
            attrs.push(KeyValue::new(key, target.to_string()));
            name.push(' ');
            name.push_str(target);
        }
        if let Some(version) = version {
            attrs.push(KeyValue::new("mcp.protocol.version", version.to_string()));
        }
        let metric = if kind == SpanKind::Client {
            "mcp.client.operation.duration"
        } else {
            "mcp.server.operation.duration"
        };
        // Logging telemetry itself must not recursively generate telemetry.
        Self::start(
            enabled && method != "notifications/message",
            name,
            kind,
            metric,
            attrs,
            parent,
            link,
        )
    }

    pub(crate) fn mcp_server(
        enabled: bool,
        method: &str,
        params: Option<&Value>,
        meta: Option<&Value>,
        version: Option<&str>,
    ) -> Self {
        let parent = global::get_text_map_propagator(|p| {
            p.extract_with_context(&Context::new(), &Meta(meta))
        });
        Self::mcp(
            enabled,
            method,
            params,
            version,
            SpanKind::Server,
            parent,
            Some(Context::current()),
        )
    }

    pub(crate) fn mcp_client(
        enabled: bool,
        method: &str,
        params: Option<&Value>,
        version: Option<&str>,
    ) -> Self {
        Self::mcp(
            enabled,
            method,
            params,
            version,
            SpanKind::Client,
            Context::current(),
            None,
        )
    }

    pub(crate) fn inject(&self, meta: &mut Value) {
        if self.histogram.is_none() {
            return;
        }
        // Preserve all existing metadata and never repair malformed metadata.
        if meta.is_null() {
            let mut injected = Map::new();
            global::get_text_map_propagator(|p| {
                p.inject_context(&self.context, &mut MetaMut(&mut injected))
            });
            if !injected.is_empty() {
                *meta = Value::Object(injected);
            }
            return;
        }
        if let Some(meta) = meta.as_object_mut() {
            global::get_text_map_propagator(|p| {
                p.inject_context(&self.context, &mut MetaMut(meta))
            });
        }
    }

    pub(crate) fn finish(&mut self) {
        self.complete = true;
    }

    pub(crate) fn fail(&mut self, code: impl Into<String>) {
        if self.histogram.is_some() {
            let code = code.into();
            self.context.span().set_status(Status::error(code.clone()));
            self.context
                .span()
                .set_attribute(KeyValue::new("error.type", code.clone()));
            self.attributes.push(KeyValue::new("error.type", code));
        }
        self.complete = true;
    }

    pub(crate) fn rpc_error(&mut self, code: i64) {
        if self.histogram.is_some() {
            let attr = KeyValue::new("rpc.response.status_code", code.to_string());
            self.context.span().set_attribute(attr.clone());
            self.attributes.push(attr);
        }
        if matches!(code, -32700 | -32600 | -32601 | -32602 | -32002) {
            self.finish();
        } else {
            self.fail(code.to_string());
        }
    }

    pub(crate) fn finish_result(&mut self, result: &Value) {
        if result.get("isError").and_then(Value::as_bool) == Some(true) {
            self.fail("tool_error");
        } else {
            self.finish();
        }
    }

    pub(crate) fn finish_jsonrpc(&mut self, response: &Value) {
        if let Some(code) = response.pointer("/error/code").and_then(Value::as_i64) {
            self.rpc_error(code);
        } else if let Some(result) = response.get("result") {
            self.finish_result(result);
        } else {
            self.finish();
        }
    }
}

impl Drop for Operation {
    fn drop(&mut self) {
        if let Some(histogram) = self.histogram.clone() {
            if !self.complete {
                self.fail("cancelled");
            }
            let _guard = self.context.clone().attach();
            histogram.record(self.started.elapsed().as_secs_f64(), &self.attributes);
            self.context.span().end();
        }
    }
}

struct Meta<'a>(Option<&'a Value>);
impl Extractor for Meta<'_> {
    fn get(&self, key: &str) -> Option<&str> {
        self.0?.get(key)?.as_str()
    }
    fn keys(&self) -> Vec<&str> {
        self.0
            .and_then(Value::as_object)
            .map(|m| m.keys().map(String::as_str).collect())
            .unwrap_or_default()
    }
}
struct MetaMut<'a>(&'a mut Map<String, Value>);
impl Injector for MetaMut<'_> {
    fn set(&mut self, key: &str, value: String) {
        self.0.insert(key.to_string(), Value::String(value));
    }
}

pub(crate) async fn command(
    command: Arc<crate::command::CommandDef>,
    options: crate::command::ExecuteOptions,
) -> crate::command::InternalResult {
    use crate::command::InternalResult;
    let attrs = vec![KeyValue::new(
        "multicast.command.name",
        options.path.clone(),
    )];
    let mut operation = Operation::start(
        options.open_telemetry,
        format!("multicast.command {}", options.path),
        SpanKind::Internal,
        "multicast.command.duration",
        attrs,
        Context::current(),
        None,
    );
    let context = operation.context();
    match crate::command::execute_inner(command, options)
        .with_context(context.clone())
        .await
    {
        InternalResult::Stream(mut stream) => {
            InternalResult::Stream(Box::pin(async_stream::stream! {
                while let Some(value) = stream.next().with_context(context.clone()).await { yield value; }
                operation.finish();
            }))
        }
        InternalResult::RecordStream(mut stream) => {
            InternalResult::RecordStream(Box::pin(async_stream::stream! {
                while let Some(record) = stream.next().with_context(context.clone()).await {
                    match &record {
                        crate::output::StreamRecord::Error { code, .. } => operation.fail(code.clone()),
                        crate::output::StreamRecord::Ok { .. } => operation.finish(),
                        _ => {}
                    }
                    yield record;
                }
            }))
        }
        result => {
            match &result {
                InternalResult::Error { code, .. } => operation.fail(code.clone()),
                _ => operation.finish(),
            }
            result
        }
    }
}

#[cfg(not(target_arch = "wasm32"))]
#[derive(Clone)]
pub(crate) struct McpService<S> {
    inner: S,
    enabled: bool,
}

#[cfg(not(target_arch = "wasm32"))]
impl<S> McpService<S> {
    pub(crate) fn new(inner: S, enabled: bool) -> Self {
        Self { inner, enabled }
    }
}

#[cfg(not(target_arch = "wasm32"))]
#[path = "telemetry/native.rs"]
mod native;