use std::io::{BufRead, Read, Write};
use serde_json::{json, Value};
const USAGE: &str = "\
chart-live: Mermaid and D3 charts, natively, everywhere
USAGE:
chart-live mermaid <command> ... (see `chart-live mermaid --help`)
chart-live d3 <command> ... (see `chart-live d3 --help`)
chart-live mcp (MCP server with mermaid_live_* and d3_* tools)
chart-live --version
";
pub fn run(args: &[String], stdin: &mut dyn Read, stdout: &mut dyn Write, stderr: &mut dyn Write) -> i32 {
match args.first().map(String::as_str) {
Some("mermaid") => mermaid_live_cli::run(&args[1..], stdin, stdout, stderr),
Some("d3") => d3_live_cli::run(&args[1..], stdin, stdout, stderr),
Some("mcp") => match serve(std::io::BufReader::new(stdin), stdout) {
Ok(()) => 0,
Err(e) => {
let _ = writeln!(stderr, "chart-live: {e}");
1
}
},
Some("-V" | "--version" | "version") => {
let _ = writeln!(stdout, "chart-live {}", env!("CARGO_PKG_VERSION"));
0
}
None | Some("-h" | "--help" | "help") => {
let _ = write!(stdout, "{USAGE}");
0
}
Some(other) => {
let _ = writeln!(stderr, "chart-live: unknown command `{other}`\n\n{USAGE}");
2
}
}
}
type Handler = fn(&Value) -> Option<Value>;
const ENGINES: [(&str, Handler); 2] =
[("mermaid_", mermaid_live_cli::mcp::handle), ("d3_", d3_live_cli::mcp::handle)];
fn request(method: &str, params: Value) -> Value {
json!({"jsonrpc": "2.0", "id": 0, "method": method, "params": params})
}
fn merged(method: &str, field: &str) -> Vec<Value> {
ENGINES
.iter()
.filter_map(|(_, h)| h(&request(method, json!({}))))
.filter_map(|r| r["result"][field].as_array().cloned())
.flatten()
.collect()
}
pub fn handle(message: &Value) -> Option<Value> {
let id = message.get("id").cloned();
let method = message.get("method").and_then(Value::as_str).unwrap_or("");
let params = message.get("params").cloned().unwrap_or(Value::Null);
let reply = |result: Value| Some(json!({"jsonrpc": "2.0", "id": id.clone()?, "result": result}));
match method {
"initialize" => {
let mut version = Value::Null;
let mut instructions = Vec::new();
for (_, h) in ENGINES {
if let Some(r) = h(&request("initialize", params.clone())) {
version = r["result"]["protocolVersion"].clone();
if let Some(i) = r["result"]["instructions"].as_str() {
instructions.push(i.to_string());
}
}
}
reply(json!({
"protocolVersion": version,
"capabilities": {"tools": {"listChanged": false}, "prompts": {"listChanged": false}},
"serverInfo": {"name": "chart-live", "title": "Chart-Live", "version": env!("CARGO_PKG_VERSION")},
"instructions": instructions.join("\n\n"),
}))
}
"tools/list" => reply(json!({"tools": merged("tools/list", "tools")})),
"prompts/list" => reply(json!({"prompts": merged("prompts/list", "prompts")})),
"tools/call" | "prompts/get" => {
let name = params.get("name").and_then(Value::as_str).unwrap_or("");
let owner = if method == "tools/call" {
ENGINES.iter().find(|(prefix, _)| name.starts_with(prefix)).map(|(_, h)| *h)
} else {
ENGINES
.iter()
.find(|(_, h)| h(&request(method, params.clone())).is_some_and(|r| r.get("result").is_some()))
.map(|(_, h)| *h)
};
match owner {
Some(h) => h(message),
None => Some(json!({"jsonrpc": "2.0", "id": id?, "error": {"code": -32602, "message": format!("unknown {} `{name}`", if method == "tools/call" { "tool" } else { "prompt" })}})),
}
}
_ => d3_live_cli::mcp::handle(message),
}
}
pub fn serve(input: impl BufRead, mut output: impl Write) -> std::io::Result<()> {
for line in input.lines() {
let line = line?;
if line.trim().is_empty() {
continue;
}
let reply = match serde_json::from_str::<Value>(&line) {
Ok(Value::Array(batch)) => {
let replies: Vec<Value> = batch.iter().filter_map(handle).collect();
(!replies.is_empty()).then_some(Value::Array(replies))
}
Ok(message) => handle(&message),
Err(e) => Some(json!({"jsonrpc": "2.0", "id": null, "error": {"code": -32700, "message": format!("parse error: {e}")}})),
};
if let Some(reply) = reply {
writeln!(output, "{reply}")?;
output.flush()?;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn routes_subcommands_to_each_engine() {
let (mut out, mut err) = (Vec::new(), Vec::new());
let rc = run(&["d3".into(), "validate".into(), "-".into(), "--json".into()],
&mut "svg.append('text').attr('x', 10).attr('y', 20).text('Hi');".as_bytes(), &mut out, &mut err);
assert_eq!(rc, 0, "{}", String::from_utf8_lossy(&err));
let (mut out2, mut err2) = (Vec::new(), Vec::new());
let rc2 = run(&["mermaid".into(), "validate".into(), "-".into()],
&mut "flowchart LR\n A --> B\n".as_bytes(), &mut out2, &mut err2);
assert_eq!(rc2, 0, "{}", String::from_utf8_lossy(&err2));
assert_eq!(run(&["nope".into()], &mut "".as_bytes(), &mut Vec::new(), &mut Vec::new()), 2);
}
#[test]
fn one_mcp_server_lists_and_calls_both_engines() {
let reqs = [
json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2025-06-18"}}),
json!({"jsonrpc": "2.0", "id": 2, "method": "tools/list"}),
json!({"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "d3_validate", "arguments": {"code": "svg.append('g');"}}}),
json!({"jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": {"name": "mermaid_live_validate", "arguments": {"code": "flowchart LR\n A --> B"}}}),
json!({"jsonrpc": "2.0", "id": 5, "method": "tools/call", "params": {"name": "nope"}}),
json!({"jsonrpc": "2.0", "method": "notifications/initialized"}),
json!({"jsonrpc": "2.0", "id": 6, "method": "ping"}),
];
let input: String = reqs.iter().map(|v| format!("{v}\n")).collect();
let mut output = Vec::new();
serve(input.as_bytes(), &mut output).unwrap();
let lines: Vec<Value> = String::from_utf8(output).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect();
assert_eq!(lines.len(), 6);
assert_eq!(lines[0]["result"]["serverInfo"]["name"], "chart-live");
assert!(lines[0]["result"]["instructions"].as_str().unwrap().contains("Mermaid-Live"));
let names: Vec<&str> = lines[1]["result"]["tools"].as_array().unwrap().iter().map(|t| t["name"].as_str().unwrap()).collect();
assert!(names.contains(&"mermaid_live_render") && names.contains(&"d3_sim"), "{names:?}");
assert_eq!(lines[2]["id"], 3);
assert!(lines[2]["result"].is_object());
assert_eq!(lines[3]["result"]["isError"], false);
assert_eq!(lines[4]["error"]["code"], -32602);
assert_eq!(lines[5]["id"], 6);
}
}