use std::io::{BufRead, Write};
use std::path::Path;
use serde_json::{Value, json};
pub fn serve() -> std::io::Result<()> {
let stdin = std::io::stdin();
let mut reader = std::io::BufReader::new(stdin.lock());
let mut stdout = std::io::stdout().lock();
loop {
let Some(message) = read_message(&mut reader)? else {
return Ok(());
};
if let Some(response) = dispatch(&message) {
write_message(&mut stdout, &response)?;
}
}
}
pub(crate) fn dispatch(message: &Value) -> Option<Value> {
let method = message.get("method")?.as_str()?;
let id = message.get("id").cloned();
match method {
"initialize" => id.map(|id| result(id, initialize_result())),
"notifications/initialized" | "initialized" => None,
"ping" => id.map(|id| result(id, json!({}))),
"tools/list" => id.map(|id| result(id, tools_list())),
"tools/call" => id.map(|id| result(id, tools_call(message.get("params")))),
_ => id.map(|id| error(id, -32601, "method not found")),
}
}
fn initialize_result() -> Value {
json!({
"protocolVersion": "2024-11-05",
"capabilities": { "tools": { "listChanged": false } },
"serverInfo": { "name": "runnables", "version": env!("CARGO_PKG_VERSION") },
"instructions": "list_runnables returns the commands a folder can run. It does not start them."
})
}
fn tools_list() -> Value {
json!({
"tools": [{
"name": "list_runnables",
"description": "Lists what a folder can run: its apps, tests, watchers, simulators, databases and Docker Compose services, with the shell command for each and the one to run by default. Returns the commands. Does not start them.",
"inputSchema": {
"type": "object",
"properties": {
"folder": {
"type": "string",
"description": "Absolute path of the folder to scan."
}
},
"required": ["folder"],
"additionalProperties": false
}
}]
})
}
fn tools_call(params: Option<&Value>) -> Value {
let name = params
.and_then(|params| params.get("name"))
.and_then(|name| name.as_str())
.unwrap_or("");
if name != "list_runnables" {
return tool_error("Unknown tool");
}
let Some(folder) = params
.and_then(|params| params.get("arguments"))
.and_then(|arguments| arguments.get("folder"))
.and_then(|folder| folder.as_str())
else {
return tool_error("folder is required");
};
let report = crate::report(Path::new(folder));
match serde_json::to_string_pretty(&report) {
Ok(text) => json!({
"content": [{ "type": "text", "text": text }],
"isError": false
}),
Err(error) => tool_error(&error.to_string()),
}
}
fn result(id: Value, value: Value) -> Value {
json!({ "jsonrpc": "2.0", "id": id, "result": value })
}
fn error(id: Value, code: i32, message: &str) -> Value {
json!({
"jsonrpc": "2.0",
"id": id,
"error": { "code": code, "message": message }
})
}
fn tool_error(message: &str) -> Value {
json!({
"content": [{ "type": "text", "text": message }],
"isError": true
})
}
fn read_message(reader: &mut impl BufRead) -> std::io::Result<Option<Value>> {
loop {
let mut line = String::new();
if reader.read_line(&mut line)? == 0 {
return Ok(None);
}
let line = line.trim();
if line.is_empty() {
continue;
}
return serde_json::from_str(line)
.map(Some)
.map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error));
}
}
fn write_message(writer: &mut impl Write, message: &Value) -> std::io::Result<()> {
serde_json::to_writer(&mut *writer, message)
.map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
writer.write_all(b"\n")?;
writer.flush()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn list_runnables_returns_the_command_and_starts_nothing() {
let root = std::env::temp_dir().join(format!("edit-run-mcp-{}", std::process::id()));
_ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root).unwrap();
std::fs::write(
root.join("package.json"),
r#"{"name":"shop","scripts":{"dev":"vite"}}"#,
)
.unwrap();
let init = dispatch(&json!({
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {}
}))
.unwrap();
assert_eq!(init["result"]["serverInfo"]["name"], "runnables");
assert!(dispatch(&json!({"jsonrpc":"2.0","method":"notifications/initialized"})).is_none());
let listed = dispatch(&json!({"jsonrpc":"2.0","id":2,"method":"tools/list"})).unwrap();
assert_eq!(listed["result"]["tools"][0]["name"], "list_runnables");
let called = dispatch(&json!({
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "list_runnables",
"arguments": { "folder": root.to_string_lossy() }
}
}))
.unwrap();
_ = std::fs::remove_dir_all(&root);
assert_eq!(called["result"]["isError"], false);
let text = called["result"]["content"][0]["text"].as_str().unwrap();
assert!(text.contains("npm run dev"), "{text}");
assert!(!text.contains("\"pid\""));
}
#[test]
fn messages_round_trip_through_the_stdio_framing() {
let message = json!({"jsonrpc":"2.0","id":1,"method":"ping"});
let mut bytes = Vec::new();
write_message(&mut bytes, &message).unwrap();
assert!(bytes.ends_with(b"\n"));
assert!(!bytes.windows(15).any(|window| window == b"Content-Length"));
let read = read_message(&mut bytes.as_slice()).unwrap().unwrap();
assert_eq!(read, message);
assert!(read_message(&mut &bytes[bytes.len()..]).unwrap().is_none());
}
}