multicast 2.0.0

A declarative CLI framework for Rust with typed commands, agent discovery, HTTP, and MCP
Documentation

Multicast

The CLI framework for humans and agents.

Define a command once. Multicast derives the argument parsing, help, validation, output formatting, JSON Schemas, and every transport from that single definition — so a command you wrote for a terminal is already an MCP tool, an HTTP route, an OpenAPI operation, a skill file an agent can read, a shell completion, and a window.

[dependencies]
multicast = "2.0.0"
schemars = "1"
serde = { version = "1", features = ["derive"] }
tokio = { version = "1", features = ["full"] }

Requires Rust 1.88 or newer. For an existing Incurs installation, see the migration guide.

Quick start

use multicast::cli::Cli;
use multicast::command::{CommandDef, TypedContext, TypedResult};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

#[derive(Deserialize, multicast::Args)]
struct GreetArgs {
    /// Name to greet.
    name: String,
}

#[derive(Deserialize, multicast::Options)]
struct GreetOptions {
    /// Add an exclamation mark.
    excited: bool,
}

#[derive(JsonSchema, Serialize)]
struct GreetOutput {
    message: String,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let greet = CommandDef::typed::<GreetArgs, GreetOptions, (), GreetOutput, _, _>(
        "greet",
        |ctx: TypedContext<GreetArgs, GreetOptions, ()>| async move {
            TypedResult::ok(GreetOutput {
                message: format!(
                    "Hello, {}{}",
                    ctx.args.name,
                    if ctx.options.excited { "!" } else { "." },
                ),
            })
        },
    )
    .description("Greet someone")
    .done();

    Cli::create("greet")
        .version("1.0.0")
        .command("greet", greet)
        .serve()
        .await
}
$ greet greet Ada --excited --json
{
  "message": "Hello, Ada!"
}

Doc comments become descriptions everywhere. CommandDef::typed derives the input schemas from GreetArgs and GreetOptions, and the output schema from GreetOutput. The handler receives validated values whether the call arrived from a terminal, HTTP, or an agent.

What that one definition already gives you

Nothing below needs extra code.

Run this You get
greet --help Help for the CLI and every command
greet greet --schema The command's JSON Schema
greet --llms / --llms-full A manifest written for an agent to read
greet --format json|yaml|toon|jsonl|md The same result in any output format
greet --mcp An MCP server over stdio
greet mcp add Registration with detected MCP clients
greet skills add Agent Skills installed for detected agents
greet completions bash|zsh|fish A shell completion script
greet plugin build --output ./dist A portable Agent Plugins 1.0.0 package (--target claude-code for a Claude Code plugin)
greet --config-schema A schema for the config file format

Output

A command returns TypedResult::ok(value), and the serialized value is the output. Pass --full-output for the {ok, data, meta} envelope when a caller wants timing and command metadata. TypedResult::error(code, message) produces the structured error envelope and a non-zero exit; ok_with_exit_code passes a wrapped subprocess's status through without turning success into a failure; ok_with_cta attaches follow-up commands.

The default format is TOON. Table and CSV are deliberately opt-in, through a separate crate:

multicast-extras = "2.0.0"
use multicast_extras::{CliExtras, ExtraFormat};

let cli = cli.default_extra_format(ExtraFormat::Table);

Feature flags

multicast = { version = "2.0.0", features = ["http", "openapi"] }
Feature Adds
cli (default) Process adapters, signals, and terminal output
toon, tokens (default) TOON output and --token-count / --token-limit
http Axum routes for root and nested commands, plus fetch gateways
openapi Import an OpenAPI 3.x document as commands, and emit one
yaml YAML output
agent-plugins, agent-plugins-mcp Load Agent Plugin packages, with or without MCP transports

MCP clients that support discovery negotiate with server/discover; older clients initialize with their exact standard. Fallback happens only on protocol evidence, never on an authentication, transport, or server failure.

The multicast command-line tool

cargo install multicast-cli     # installs the `multicast` binary
multicast explain               # the Rust authoring reference, by topic
multicast explain typed-commands

Code generation

Point it at a project whose binary exposes --llms-full, and it writes typed helpers for calling that CLI from Rust:

multicast gen --dir ./my-cli --entry my-cli --config-schema
  • src/multicast_generated.rs — typed command modules, argument and option types, CTA renderers, and the embedded manifest
  • incurs.manifest.json — the canonical command manifest
  • config.schema.json — the config file schema, with --config-schema

--output and --json-output override the first two paths. --entry takes a Cargo binary name or a path to an executable.

Agent Plugin packages

Any multicast CLI can package itself:

my-cli plugin build --bundle-cli --output ./dist/my-cli-plugin

The package keeps its layers separate: skills/<name>/SKILL.md for agents to read, mcp.json declaring the tool surface, and bin/my-cli as the executable, all declared by a root plugin.json. Use --plugin-no-mcp for a skills-only package. Add --target claude-code to write a Claude Code plugin and one-plugin marketplace instead (claude plugin marketplace add <dir>).

The multicast binary is also a client for those packages:

multicast plugin install ./dist/my-cli-plugin
multicast plugin validate ./dist/my-cli-plugin --data-dir ~/.local/share/my-cli-plugin
multicast plugin tools    ./dist/my-cli-plugin --data-dir ~/.local/share/my-cli-plugin
multicast plugin call     ./dist/my-cli-plugin my-server_my-tool \
  --arguments '{"name":"Ada"}' --data-dir ~/.local/share/my-cli-plugin
multicast plugin uninstall my-cli [--purge]

Installation validates the package, checks its operating system and architecture, and installs the command into your executable directory, telling you when that directory is not on PATH. Each MCP server connects independently, so one failure does not hide the tools from the others. The data directory you name is created before launch and persists across runs.

See Agent Plugins compatibility for the full behavior and failure-boundary matrix.

Cloudflare Workers

Start with the Cloudflare application guide to generate an independent tool, deploy it, and publish custom durable workflows at runtime without redeploying. The shared adapter handles HTTP/MCP, events, schedules, and recovery; your application supplies tools and authenticated tenant identity.

Every feature runs in a Cloudflare Worker. Build with default-features = false, serve http::build_cli_router_with through the Workers SDK, pass the Worker's variables as the environment, and set a RequestGuard. /mcp is served without an async runtime, and outbound calls go through multicast_mcp_cloudflare::WorkersHttpClient. Commands that install into the local machine (skills add, mcp add, plugin build, --mcp over stdio) answer with a coded error there. extensions/cloudflare/examples/feature-worker exercises every feature under wrangler dev.

OpenTelemetry

Command execution, native and portable MCP servers, the HTTP MCP client, and reverse peer calls emit spans and duration histograms through the host's global OpenTelemetry Rust 0.33 providers. Install your trace provider, meter provider, and text-map propagator before serving the CLI. Multicast does not install an SDK or exporter; without providers, the API is a no-op. The matching API is re-exported as multicast::telemetry::opentelemetry.

Histogram Measures
incurs.command.duration Command execution through completion of streamed output
mcp.client.operation.duration Outbound MCP operation through response or acknowledgement
mcp.server.operation.duration Inbound MCP handler execution

Durations use seconds. MCP client and server spans follow the MCP semantic conventions, including trace context in params._meta, tool and prompt names, and error classification. Existing metadata is preserved. Arguments, results, resource URIs, credentials, and request IDs are excluded from telemetry attributes.

Disable instrumentation for a CLI instance with Cli::create("my-tool").open_telemetry(false). Disable an HTTP MCP client with McpRemoteOptions { open_telemetry: false, ..Default::default() }. Keep your provider handles and flush or shut them down after serving finishes.

For native hosts without an existing SDK, the optional multicast-telemetry crate installs OpenTelemetry 0.33 trace and metric providers with OTLP/HTTP JSON exporters and W3C propagation. Retain its OtlpTelemetry guard, run commands through Cli::run_to, and call shutdown before returning the process exit status. The short-lived CLI example exports both successful and failed commands. Core multicast keeps using the host's providers; the starter is a separate opt-in dependency.

Calling commands without a CLI

Cli::tool_catalog() exposes every MCP-visible command as a transport-neutral Rust API. Calls made through it use the same schemas, middleware, environment fields, config defaults, streaming results, and structured errors as the CLI — it is the boundary MCP, Code Mode, and the desktop application all go through. try_tool_catalog() reports name collisions instead of silently replacing a command.

Code Mode

multicast-codemode lets an agent write a small JavaScript program that calls your tools, instead of making one tool call per step. It provides connector discovery, approval policy, immutable capability snapshots, deterministic replay, cancellation, ordered events, artifact-backed large values, rollback hooks, and bounded durable history. It can wrap a multicast catalog, a remote MCP client, or an authenticated OpenAPI client.

multicast-codemode-local runs those programs in a resource-limited QuickJS runtime, and multicast-codemode-mcp exposes the lifecycle to MCP clients:

Tool Purpose
codemode_search Search tools and snippets, with the declarations needed to call each match
codemode_execute Start a JavaScript execution
codemode_execution Read execution state or an owned artifact
codemode_decide Approve or reject one pending action
codemode_cancel Cancel a running or paused execution

Workflows

multicast-workflows turns Code Mode programs into reusable commands of the CLI that runs them. A CLI author ships workflows in the binary; each one becomes an ordinary command, so it appears in help, skills, and MCP tools. Users and agents promote a completed Code Mode execution to a saved workflow at runtime.

use multicast_workflows::Workflows;

let cli = Workflows::new()
    .shipped(
        "add-three",
        "Add three integers",
        serde_json::json!({
            "type": "object",
            "properties": {
                "a": {"type": "integer"},
                "b": {"type": "integer"},
                "c": {"type": "integer"}
            },
            "required": ["a", "b", "c"],
            "additionalProperties": false
        }),
        "async (input) => {
            const first = await math.sum({ left: input.a, right: input.b });
            return math.sum({ left: first.sum, right: input.c });
        }",
    )
    .attach(cli)?;

Attaching fails when a shipped workflow calls a command the CLI does not have. Input is checked against the workflow's schema before any command runs. Executions are durable: a workflow that reaches a command needing approval exits with code 75 and waits for workflows approve, and an interrupted execution continues with workflows resume. Workflows call the CLI's own commands, not other workflows.

math add-three --a 1 --b 2 --c 3
math workflows exec 'async () => math.sum({ left: 4, right: 5 })'
math workflows save nine --from EXECUTION_ID --description "Adds four and five"
math workflows run nine
math workflows list

Executions and saved workflows live in one SQLite store per CLI under the XDG data directory. See the example.

workflows run and workflows exec accept --result-only: completed workflows return just their chosen logical value, while failures and approval pauses keep their diagnostics and nonzero status. Use global --format json for literal JSON.

Every run is recorded in a run ledger beside the store, tagged with the workflow's version (a digest of its program and input schema). Four read-only commands keep a catalog maintainable without drowning in history:

Command Reports
workflows doctor Only what needs action: saved workflows calling commands the CLI no longer has, versions that keep failing, interrupted runs, and runs awaiting a decision. Each finding names the command that resolves it. Notices (never run, stale after --stale-days, duplicate, lost) need --all. Exits 1 on any error or warning.
workflows stats [NAME] Runs and success rate for the current version, kept apart from earlier versions.
workflows failures [NAME] Failed runs grouped by cause: the executing step plus the error with numbers, identifiers, and quoted text removed. A cause stays active until the workflow next succeeds; --all shows resolved causes.
workflows trace EXECUTION_ID One run's steps, the step where it stopped, its error, console tail, and status timeline. Large values are truncated unless --full.

Check workflow changes offline

Capture a completed run, review its inputs and observed results, and keep the JSON fixture alongside the workflow. The current command schemas, annotations, approval and replay policies, and retry budget become the reviewed baseline.

math add-three --a 1 --b 2 --c 3
math workflows capture add-three --from EXECUTION_ID --input '{"a":1,"b":2,"c":3}' > add-three.json
math workflows check add-three --fixture add-three.json

check runs the current program in a fresh sandbox, supplies the fixture's results, and requires the same ordered command calls, exact arguments, and final result. It never invokes command handlers. A caught unexpected call still fails the check. Changes to a called command's schema or policy require reviewing a new baseline.

Capture requires a completed run of the current program and the same input. Fixtures include full observed values, including stored artifacts, and can contain sensitive data; review or replace those values before committing. Both commands limit a fixture to 16 MiB. A captured result is an observation, so independently verify the expected result before treating it as a regression oracle. Programs that depend on clocks, random values, or external state may need deterministic inputs to pass offline.

Run workflows from events and schedules

Native hosts can use Workflows::attach_with_triggers for durable event admission and interval schedules, with persistent event deduplication, workflow concurrency gates, and deadlines. The host supplies authentication, its HTTP adapter, and the polling lifetime. See trigger delivery and the executable host adapter.

Share explicitly reviewed observations

multicast-observe combines overlapping equivalent reads under host-owned contracts and visibility grants. Mutable reads share only while in flight; bounded completed-result reuse requires an explicit immutable contract and caller freshness limit. No contracts are enabled by default. Each workflow keeps its own execution, approvals, journal, and result projection.

Use the native authority and SDK for local or private HTTPS access, or the Cloudflare protocol adapter for a private service binding. Durable Worker hosts can separately bind current workflow authority across restart and re-resolve credentials before connector calls. Sharing does not authorize commands or cache arbitrary tools, writes, credentials, or workflows.

Terminal applications

multicast-app-ratatui runs a command graph full-screen in a terminal: commands on the left, the selected command's inputs collected from its schema, results below.

use multicast_app_ratatui::TerminalApp;

TerminalApp::from_cli(&cli)?.title("Todo").run()

The installed multicast tool does this for its own commands:

multicast --tui

See its README for the key map and the controls each schema type gets.

Native desktop applications

multicast-app-gpui ships the same command graph as a double-clickable application, for people who will never open a terminal. Commands are listed in a window, each command's inputs are collected from its schema, and every call goes through the tool catalog — so validation, middleware, config defaults, streaming, and cancellation behave exactly as they do on the CLI.

use multicast_app_gpui::DesktopApp;

DesktopApp::from_cli(&cli)?.title("Todo").run()

MacBundle wraps the built executable in a macOS .app that installs by dragging. See its README for the full guide and current limits.

How it fits together

              typed command definitions
                         |
                         v
            shared command graph + schemas
      ______________|____________________________
     |        |        |            |            |
    CLI     HTTP      MCP     tool catalog   generated artifacts
                                   |          |-- OpenAPI
                                   |          |-- Agent Skills
                                   |          |-- shell completions
                                   |          `-- Rust and JSON codegen
                                   |
                                   |-- Code Mode  (local QuickJS, remote executors)
                                   |
                                   `-- native desktop window

Learn more

License

MIT. multicast began as a Rust port of wevm/incur and keeps its command model; the two are now independent.