Skip to main content

multicast_workflows/
serve.rs

1//! One process entry point that gives a CLI workflows and a Code Mode server.
2
3use std::sync::Arc;
4
5use multicast::cli::Cli;
6use multicast_codemode::{CodeMode, MemoryStore, MulticastConnector};
7use multicast_codemode_local::{LocalCodeModeService, LocalExecutor};
8
9use crate::Workflows;
10
11/// The only argument that starts the Code Mode MCP server over stdio.
12pub const CODEMODE_FLAG: &str = "--codemode";
13
14/// Returns whether `argv` (without the program name) requests the Code Mode
15/// server: exactly [`CODEMODE_FLAG`] and nothing else.
16pub fn is_codemode_request(argv: &[String]) -> bool {
17    matches!(argv, [flag] if flag == CODEMODE_FLAG)
18}
19
20/// Starts a Code Mode service whose only connector is the CLI's own commands.
21///
22/// Executions are held in memory, so several agent sessions can each run a
23/// server for the same CLI at once; an execution does not survive its server.
24/// Workflows keep their own durable store.
25pub fn codemode_service(cli: &Cli) -> Result<LocalCodeModeService, String> {
26    codemode_service_with_limits(cli, multicast_codemode::WorkflowLimits::default(), false)
27}
28fn codemode_service_with_limits(
29    cli: &Cli,
30    limits: multicast_codemode::WorkflowLimits,
31    approve_local: bool,
32) -> Result<LocalCodeModeService, String> {
33    limits.check()?;
34    let catalog = cli.try_tool_catalog().map_err(|error| error.to_string())?;
35    let connector = MulticastConnector::new(catalog);
36    // Honor Workflows::approve_local_commands here too, so the stdio Code Mode
37    // server and `workflows exec` agree on which commands pause.
38    let connector = Arc::new(if approve_local {
39        connector.with_policy_resolver(Arc::new(crate::LocalApproval))
40    } else {
41        connector
42    });
43    LocalCodeModeService::spawn(move || {
44        CodeMode::new(
45            Arc::new(MemoryStore::default()),
46            LocalExecutor::default(),
47            vec![connector],
48        )
49        .with_workflow_limits(limits)
50        .expect("validated limits on unshared runtime")
51    })
52}
53
54/// Serves a CLI from process argv with workflows attached.
55///
56/// `cli --codemode` serves the five Code Mode lifecycle tools over stdio,
57/// calling the CLI's commands. Every other invocation attaches the default
58/// [`Workflows`] and runs [`Cli::serve`], so `--mcp`, `--llms`, and ordinary
59/// commands behave as before plus the `workflows` group.
60pub async fn serve(cli: Cli) -> Result<(), Box<dyn std::error::Error>> {
61    serve_attached(cli, Workflows::new()).await
62}
63
64/// Method form of [`serve`], so a CLI's entry point changes one word:
65/// `cli.serve().await` becomes `cli.serve_workflows().await`.
66pub trait ServeWorkflows {
67    /// Serves this CLI as [`serve`] does.
68    fn serve_workflows(
69        self,
70    ) -> impl std::future::Future<Output = Result<(), Box<dyn std::error::Error>>>;
71}
72
73impl ServeWorkflows for Cli {
74    fn serve_workflows(
75        self,
76    ) -> impl std::future::Future<Output = Result<(), Box<dyn std::error::Error>>> {
77        serve(self)
78    }
79}
80
81/// [`serve`] with an author-configured [`Workflows`] builder.
82pub async fn serve_attached(
83    cli: Cli,
84    workflows: Workflows,
85) -> Result<(), Box<dyn std::error::Error>> {
86    let argv: Vec<String> = std::env::args().skip(1).collect();
87    if is_codemode_request(&argv) {
88        let service =
89            codemode_service_with_limits(&cli, workflows.limits.clone(), workflows.approve_local)?;
90        use multicast_codemode::CodeModeService as _;
91        let definitions = workflows
92            .shipped
93            .iter()
94            .map(|w| {
95                (
96                    w.name.clone(),
97                    multicast_codemode::WorkflowDefinition {
98                        source: multicast_codemode::normalize_code(&w.code),
99                        input: w.input_schema.clone(),
100                        output: serde_json::Value::Bool(true),
101                        bindings: serde_json::json!({}),
102                    },
103                )
104            })
105            .collect();
106        service.install_workflows(definitions).await?;
107        multicast_codemode_mcp::serve_stdio_with(
108            Arc::new(service),
109            cli.mcp_serve_options().custom_methods.clone(),
110        )
111        .await?;
112        return Ok(());
113    }
114    workflows.attach(cli)?.serve().await
115}
116
117#[cfg(all(test, feature = "native", not(target_arch = "wasm32")))]
118mod tests {
119    use super::*;
120    use multicast::command::{
121        CommandContext, CommandDef, CommandHandler, McpAnnotations, McpCommandOptions,
122    };
123    use multicast::output::CommandResult;
124    use multicast_codemode::CodeModeService as _;
125
126    struct Act;
127    #[async_trait::async_trait]
128    impl CommandHandler for Act {
129        async fn run(&self, _: CommandContext) -> CommandResult {
130            CommandResult::Ok {
131                data: serde_json::json!(1),
132                exit_code: None,
133                cta: None,
134            }
135        }
136    }
137
138    fn cli() -> Cli {
139        Cli::create("host").command(
140            "act",
141            CommandDef::build("act", Act)
142                .mcp(McpCommandOptions {
143                    annotations: Some(McpAnnotations {
144                        read_only_hint: Some(false),
145                        destructive_hint: Some(true),
146                        ..Default::default()
147                    }),
148                    ..Default::default()
149                })
150                .done(),
151        )
152    }
153
154    async fn act_needs_approval(approve_local: bool) -> bool {
155        let service = codemode_service_with_limits(
156            &cli(),
157            multicast_codemode::WorkflowLimits::default(),
158            approve_local,
159        )
160        .unwrap();
161        let found = service.search("act".into()).await.unwrap();
162        found
163            .results
164            .iter()
165            .find(|r| r.method == "act")
166            .expect("act listed")
167            .requires_approval
168    }
169
170    #[tokio::test]
171    async fn stdio_server_honors_approve_local_commands() {
172        assert!(!act_needs_approval(true).await);
173        assert!(act_needs_approval(false).await);
174    }
175}