Skip to main content

chart_live_cli/
lib.rs

1// Copyright 2026 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! `chart-live`: one command line and one MCP server for every chart-live engine.
16//!
17//! ```text
18//! chart-live mermaid render diagram.mmd -o out.svg   # = mermaid-live render ...
19//! chart-live d3 sim chart.d3.js --actions @a.json     # = d3-live sim ...
20//! chart-live mcp                                      # mermaid_live_* and d3_* tools together
21//! ```
22//!
23//! The standalone `mermaid-live` and `d3-live` binaries keep working; this crate only routes.
24
25use std::io::{BufRead, Read, Write};
26
27use serde_json::{json, Value};
28
29const USAGE: &str = "\
30chart-live: Mermaid and D3 charts, natively, everywhere
31
32USAGE:
33  chart-live mermaid <command> ...   (see `chart-live mermaid --help`)
34  chart-live d3 <command> ...        (see `chart-live d3 --help`)
35  chart-live mcp                     (MCP server with mermaid_live_* and d3_* tools)
36  chart-live --version
37";
38
39/// Runs the CLI with `args` (excluding `argv[0]`) and returns the exit code.
40pub fn run(args: &[String], stdin: &mut dyn Read, stdout: &mut dyn Write, stderr: &mut dyn Write) -> i32 {
41    match args.first().map(String::as_str) {
42        Some("mermaid") => mermaid_live_cli::run(&args[1..], stdin, stdout, stderr),
43        Some("d3") => d3_live_cli::run(&args[1..], stdin, stdout, stderr),
44        Some("mcp") => match serve(std::io::BufReader::new(stdin), stdout) {
45            Ok(()) => 0,
46            Err(e) => {
47                let _ = writeln!(stderr, "chart-live: {e}");
48                1
49            }
50        },
51        Some("-V" | "--version" | "version") => {
52            let _ = writeln!(stdout, "chart-live {}", env!("CARGO_PKG_VERSION"));
53            0
54        }
55        None | Some("-h" | "--help" | "help") => {
56            let _ = write!(stdout, "{USAGE}");
57            0
58        }
59        Some(other) => {
60            let _ = writeln!(stderr, "chart-live: unknown command `{other}`\n\n{USAGE}");
61            2
62        }
63    }
64}
65
66type Handler = fn(&Value) -> Option<Value>;
67
68const ENGINES: [(&str, Handler); 2] =
69    [("mermaid_", mermaid_live_cli::mcp::handle), ("d3_", d3_live_cli::mcp::handle)];
70
71fn request(method: &str, params: Value) -> Value {
72    json!({"jsonrpc": "2.0", "id": 0, "method": method, "params": params})
73}
74
75fn merged(method: &str, field: &str) -> Vec<Value> {
76    ENGINES
77        .iter()
78        .filter_map(|(_, h)| h(&request(method, json!({}))))
79        .filter_map(|r| r["result"][field].as_array().cloned())
80        .flatten()
81        .collect()
82}
83
84/// Handles one JSON-RPC message by routing to the engine that owns the tool or prompt.
85pub fn handle(message: &Value) -> Option<Value> {
86    let id = message.get("id").cloned();
87    let method = message.get("method").and_then(Value::as_str).unwrap_or("");
88    let params = message.get("params").cloned().unwrap_or(Value::Null);
89    let reply = |result: Value| Some(json!({"jsonrpc": "2.0", "id": id.clone()?, "result": result}));
90    match method {
91        "initialize" => {
92            let mut version = Value::Null;
93            let mut instructions = Vec::new();
94            for (_, h) in ENGINES {
95                if let Some(r) = h(&request("initialize", params.clone())) {
96                    version = r["result"]["protocolVersion"].clone();
97                    if let Some(i) = r["result"]["instructions"].as_str() {
98                        instructions.push(i.to_string());
99                    }
100                }
101            }
102            reply(json!({
103                "protocolVersion": version,
104                "capabilities": {"tools": {"listChanged": false}, "prompts": {"listChanged": false}},
105                "serverInfo": {"name": "chart-live", "title": "Chart-Live", "version": env!("CARGO_PKG_VERSION")},
106                "instructions": instructions.join("\n\n"),
107            }))
108        }
109        "tools/list" => reply(json!({"tools": merged("tools/list", "tools")})),
110        "prompts/list" => reply(json!({"prompts": merged("prompts/list", "prompts")})),
111        "tools/call" | "prompts/get" => {
112            let name = params.get("name").and_then(Value::as_str).unwrap_or("");
113            let owner = if method == "tools/call" {
114                ENGINES.iter().find(|(prefix, _)| name.starts_with(prefix)).map(|(_, h)| *h)
115            } else {
116                // Prompts are few; ask each engine.
117                ENGINES
118                    .iter()
119                    .find(|(_, h)| h(&request(method, params.clone())).is_some_and(|r| r.get("result").is_some()))
120                    .map(|(_, h)| *h)
121            };
122            match owner {
123                Some(h) => h(message),
124                None => Some(json!({"jsonrpc": "2.0", "id": id?, "error": {"code": -32602, "message": format!("unknown {} `{name}`", if method == "tools/call" { "tool" } else { "prompt" })}})),
125            }
126        }
127        // Every engine answers `ping` and ignores notifications the same way.
128        _ => d3_live_cli::mcp::handle(message),
129    }
130}
131
132/// Serves newline-delimited JSON-RPC 2.0 from `input` to `output`.
133pub fn serve(input: impl BufRead, mut output: impl Write) -> std::io::Result<()> {
134    for line in input.lines() {
135        let line = line?;
136        if line.trim().is_empty() {
137            continue;
138        }
139        let reply = match serde_json::from_str::<Value>(&line) {
140            Ok(Value::Array(batch)) => {
141                let replies: Vec<Value> = batch.iter().filter_map(handle).collect();
142                (!replies.is_empty()).then_some(Value::Array(replies))
143            }
144            Ok(message) => handle(&message),
145            Err(e) => Some(json!({"jsonrpc": "2.0", "id": null, "error": {"code": -32700, "message": format!("parse error: {e}")}})),
146        };
147        if let Some(reply) = reply {
148            writeln!(output, "{reply}")?;
149            output.flush()?;
150        }
151    }
152    Ok(())
153}
154
155#[cfg(test)]
156mod tests {
157    use super::*;
158
159    #[test]
160    fn routes_subcommands_to_each_engine() {
161        let (mut out, mut err) = (Vec::new(), Vec::new());
162        let rc = run(&["d3".into(), "validate".into(), "-".into(), "--json".into()],
163            &mut "svg.append('text').attr('x', 10).attr('y', 20).text('Hi');".as_bytes(), &mut out, &mut err);
164        assert_eq!(rc, 0, "{}", String::from_utf8_lossy(&err));
165        let (mut out2, mut err2) = (Vec::new(), Vec::new());
166        let rc2 = run(&["mermaid".into(), "validate".into(), "-".into()],
167            &mut "flowchart LR\n  A --> B\n".as_bytes(), &mut out2, &mut err2);
168        assert_eq!(rc2, 0, "{}", String::from_utf8_lossy(&err2));
169        assert_eq!(run(&["nope".into()], &mut "".as_bytes(), &mut Vec::new(), &mut Vec::new()), 2);
170    }
171
172    #[test]
173    fn one_mcp_server_lists_and_calls_both_engines() {
174        let reqs = [
175            json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2025-06-18"}}),
176            json!({"jsonrpc": "2.0", "id": 2, "method": "tools/list"}),
177            json!({"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "d3_validate", "arguments": {"code": "svg.append('g');"}}}),
178            json!({"jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": {"name": "mermaid_live_validate", "arguments": {"code": "flowchart LR\n A --> B"}}}),
179            json!({"jsonrpc": "2.0", "id": 5, "method": "tools/call", "params": {"name": "nope"}}),
180            json!({"jsonrpc": "2.0", "method": "notifications/initialized"}),
181            json!({"jsonrpc": "2.0", "id": 6, "method": "ping"}),
182        ];
183        let input: String = reqs.iter().map(|v| format!("{v}\n")).collect();
184        let mut output = Vec::new();
185        serve(input.as_bytes(), &mut output).unwrap();
186        let lines: Vec<Value> = String::from_utf8(output).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect();
187        assert_eq!(lines.len(), 6);
188        assert_eq!(lines[0]["result"]["serverInfo"]["name"], "chart-live");
189        assert!(lines[0]["result"]["instructions"].as_str().unwrap().contains("Mermaid-Live"));
190        let names: Vec<&str> = lines[1]["result"]["tools"].as_array().unwrap().iter().map(|t| t["name"].as_str().unwrap()).collect();
191        assert!(names.contains(&"mermaid_live_render") && names.contains(&"d3_sim"), "{names:?}");
192        assert_eq!(lines[2]["id"], 3);
193        assert!(lines[2]["result"].is_object());
194        assert_eq!(lines[3]["result"]["isError"], false);
195        assert_eq!(lines[4]["error"]["code"], -32602);
196        assert_eq!(lines[5]["id"], 6);
197    }
198}