multicast-workflows 2.0.0

Durable Code Mode workflows attached to multicast CLIs as first-party commands
Documentation
//! A math CLI with shipped workflows.
//!
//! ```text
//! workflow_math add-three --a 1 --b 2 --c 3
//! workflow_math sum-and-note --left 2 --right 3     # pauses for approval
//! workflow_math workflows approve EXECUTION_ID
//! workflow_math workflows exec 'async () => math.sum({ left: 4, right: 5 })'
//! workflow_math workflows save nine --from EXECUTION_ID --description "Adds four and five"
//! workflow_math workflows run nine
//! workflow_math --codemode                         # Code Mode MCP server on stdio
//! workflow_math arithmetic --task "Average 3, 5, and 10"   # activate an archetype
//! workflow_math archetypes save adder --summary "Adds" --instructions "Use sum" --tools sum
//! ```
//!
//! Environment:
//! - `MATH_WORKFLOW_STORE` overrides the workflow store location.
//! - `MATH_COMMAND_LOG` appends one line per command invocation to a file.
//! - `MATH_SLOW_MS` sets how long the `slow` command waits.
//! - `MATH_WITHOUT_NOTE` removes the `note` command and the workflow and
//!   archetype that ship with it, as a newer release that dropped a command
//!   would.

use std::io::Write as _;
use std::time::Duration;

use multicast::cli::Cli;
use multicast::command::{
    CommandContext, CommandDef, CommandHandler, McpAnnotations, McpCommandOptions,
};
use multicast::output::CommandResult;
use multicast_workflows::Workflows;
use serde::Deserialize;
use serde_json::json;

/// Appends the command name to `MATH_COMMAND_LOG`, when set.
fn record(command: &str) {
    if let Ok(path) = std::env::var("MATH_COMMAND_LOG")
        && let Ok(mut file) = std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(path)
    {
        let _ = writeln!(file, "{command}");
    }
}

fn ok(data: serde_json::Value) -> CommandResult {
    CommandResult::Ok {
        data,
        cta: None,
        exit_code: None,
    }
}

fn read_only() -> McpCommandOptions {
    McpCommandOptions {
        annotations: Some(McpAnnotations {
            read_only_hint: Some(true),
            destructive_hint: Some(false),
            open_world_hint: Some(false),
            ..McpAnnotations::default()
        }),
        ..McpCommandOptions::default()
    }
}

struct Sum;

#[async_trait::async_trait]
impl CommandHandler for Sum {
    async fn run(&self, context: CommandContext) -> CommandResult {
        record("sum");
        ok(json!({
            "sum": context.options["left"].as_i64().unwrap_or_default()
                + context.options["right"].as_i64().unwrap_or_default()
        }))
    }
}

#[derive(multicast::Options, Deserialize)]
#[allow(dead_code)]
struct SumOptions {
    /// Left operand.
    left: i64,
    /// Right operand.
    right: i64,
}

struct Note;

#[async_trait::async_trait]
impl CommandHandler for Note {
    async fn run(&self, context: CommandContext) -> CommandResult {
        record("note");
        ok(json!({ "noted": context.options["text"] }))
    }
}

#[derive(multicast::Options, Deserialize)]
#[allow(dead_code)]
struct NoteOptions {
    /// Text to record.
    text: String,
}

struct Slow;

#[async_trait::async_trait]
impl CommandHandler for Slow {
    async fn run(&self, _context: CommandContext) -> CommandResult {
        record("slow");
        let millis = std::env::var("MATH_SLOW_MS")
            .ok()
            .and_then(|value| value.parse().ok())
            .unwrap_or(0);
        tokio::time::sleep(Duration::from_millis(millis)).await;
        ok(json!({ "waited": millis }))
    }
}

struct Divide;

#[async_trait::async_trait]
impl CommandHandler for Divide {
    async fn run(&self, context: CommandContext) -> CommandResult {
        record("divide");
        let numerator = context.options["numerator"].as_i64().unwrap_or_default();
        let denominator = context.options["denominator"].as_i64().unwrap_or_default();
        if denominator == 0 {
            return CommandResult::Error {
                code: "DIVISION_BY_ZERO".into(),
                message: format!("Cannot divide {numerator} by zero"),
                retryable: false,
                exit_code: None,
                cta: None,
            };
        }
        ok(json!({ "quotient": numerator / denominator }))
    }
}

#[derive(multicast::Options, Deserialize)]
#[allow(dead_code)]
struct DivideOptions {
    /// Dividend.
    numerator: i64,
    /// Divisor.
    denominator: i64,
}

fn cli() -> (Cli, Workflows) {
    let without_note = std::env::var_os("MATH_WITHOUT_NOTE").is_some();
    let mut cli = Cli::create("math")
        .description("Integer arithmetic with durable workflows")
        .command(
            "sum",
            CommandDef::build("sum", Sum)
                .description("Add two integers")
                .options::<SumOptions>()
                .mcp(read_only())
                .done(),
        )
        .command(
            "divide",
            CommandDef::build("divide", Divide)
                .description("Divide two integers, rounding toward zero")
                .options::<DivideOptions>()
                .mcp(read_only())
                .done(),
        )
        .command(
            "slow",
            CommandDef::build("slow", Slow)
                .description("Wait for MATH_SLOW_MS milliseconds")
                .mcp(read_only())
                .done(),
        );
    if !without_note {
        cli = cli.command(
            "note",
            CommandDef::build("note", Note)
                .description("Record a note")
                .options::<NoteOptions>()
                .done(),
        );
    }
    let pair = json!({
        "type": "object",
        "properties": {
            "left": {"type": "integer", "description": "Left operand"},
            "right": {"type": "integer", "description": "Right operand"}
        },
        "required": ["left", "right"],
        "additionalProperties": false
    });
    let mut workflows = Workflows::new()
        .retry_policy(multicast_codemode::RetryPolicy { max_attempts: 3 })
        .shipped(
            "add-three",
            "Add three integers",
            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 });
            }",
        )
        .shipped(
            "slow-sum",
            "Wait, then add two integers",
            pair.clone(),
            "async (input) => {
                await math.slow({});
                return math.sum(input);
            }",
        )
        .shipped(
            "ratio",
            "Divide the sum of two integers by a third",
            json!({
                "type": "object",
                "properties": {
                    "left": {"type": "integer"},
                    "right": {"type": "integer"},
                    "by": {"type": "integer"}
                },
                "required": ["left", "right", "by"],
                "additionalProperties": false
            }),
            "async (input) => {
                const total = await math.sum({ left: input.left, right: input.right });
                return math.divide({ numerator: total.sum, denominator: input.by });
            }",
        );
    workflows = workflows.archetype(
        "arithmetic",
        "Answer integer arithmetic questions",
        "Break the question into sums and divisions. Prefer a shipped workflow \
         when one matches the whole question; otherwise call sum and divide.",
        ["sum", "divide", "add-three", "ratio"],
    );
    if !without_note {
        workflows = workflows.archetype(
            "bookkeeping",
            "Record arithmetic results as notes",
            "Compute with sum, then record the total with note. \
             Use sum-and-note when both steps are needed.",
            ["sum", "note", "sum-and-note"],
        );
        workflows = workflows.shipped(
            "sum-and-note",
            "Add two integers and record the total as a note",
            pair,
            "async (input) => {
                const total = await math.sum(input);
                await math.note({ text: String(total.sum) });
                return total;
            }",
        );
    }
    if let Ok(path) = std::env::var("MATH_WORKFLOW_STORE") {
        workflows = workflows.store_path(path);
    }
    (cli, workflows)
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let (cli, workflows) = cli();
    multicast_workflows::serve_attached(cli, workflows).await
}