- crates/mcp (L5): JSON-RPC 2.0 over stdio, dual era: MCP 2026-07-28 (per-request _meta, server/discover, -32022) and legacy initialize (2025-11-25, 2025-06-18, 2025-03-26, 2024-11-05). Tools list_commands, execute_command (app.quit only with confirm: true), screenshot (image content), read_buffer, get_events (ring of 1000 events via events.subscribe); resources lutra://buffer/<path> for open buffers. Engine errors become tool errors with the engine code. Lines capped at 16 MiB, guard around every request, parser and tool args fuzzed. - lutra mcp [--port PORT] [--no-start] in apps/lutra-cli: connects through the rendezvous file and token, or starts Lutra. - Engine: read-only buffer.list command. - Tests: protocol units + proptest fuzz, integration over the token listener, stdio end to end. Docs: architecture (MCP), G7, ROADMAP. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
303 lines
11 KiB
Rust
303 lines
11 KiB
Rust
//! The MCP protocol layer without a running Lutra: versions, methods,
|
|
//! errors, the stdio loop and a fuzz of the message parser.
|
|
|
|
#![allow(
|
|
clippy::unwrap_used,
|
|
clippy::expect_used,
|
|
clippy::panic,
|
|
clippy::indexing_slicing
|
|
)]
|
|
|
|
use std::sync::Arc;
|
|
|
|
use lutra_mcp::{Connection, Connector, Server};
|
|
use proptest::prelude::*;
|
|
use serde_json::{Value, json};
|
|
|
|
/// A connector for a Lutra that is not running.
|
|
struct Offline;
|
|
|
|
impl Connector for Offline {
|
|
fn connect(&self, _start: bool) -> Result<Box<dyn Connection>, String> {
|
|
Err("Lutra is not running".into())
|
|
}
|
|
}
|
|
|
|
fn server() -> Server {
|
|
Server::new(Arc::new(Offline))
|
|
}
|
|
|
|
fn ask(server: &mut Server, message: Value) -> Value {
|
|
let line = server.handle_line(&message.to_string()).unwrap();
|
|
assert!(!line.contains('\n'));
|
|
serde_json::from_str(&line).unwrap()
|
|
}
|
|
|
|
fn modern(method: &str, id: u64, mut params: Value) -> Value {
|
|
params["_meta"] = json!({
|
|
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
|
|
"io.modelcontextprotocol/clientCapabilities": {},
|
|
"io.modelcontextprotocol/clientInfo": {"name": "test", "version": "1"}
|
|
});
|
|
json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params})
|
|
}
|
|
|
|
#[test]
|
|
fn legacy_initialize_negotiates_a_version() {
|
|
let mut s = server();
|
|
let r = ask(
|
|
&mut s,
|
|
json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {
|
|
"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "c", "version": "1"}
|
|
}}),
|
|
);
|
|
assert_eq!(r["id"], 1);
|
|
assert_eq!(r["result"]["protocolVersion"], "2025-06-18");
|
|
assert_eq!(r["result"]["serverInfo"]["name"], "lutra");
|
|
assert!(r["result"]["capabilities"]["tools"].is_object());
|
|
assert!(r["result"]["capabilities"]["resources"].is_object());
|
|
assert!(r["result"].get("resultType").is_none());
|
|
let r = ask(
|
|
&mut s,
|
|
json!({"jsonrpc": "2.0", "id": 2, "method": "initialize", "params": {"protocolVersion": "1999-01-01"}}),
|
|
);
|
|
assert_eq!(r["result"]["protocolVersion"], "2025-11-25");
|
|
assert_eq!(
|
|
s.handle_line(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#),
|
|
None
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn modern_requests_carry_their_version() {
|
|
let mut s = server();
|
|
let r = ask(&mut s, modern("server/discover", 1, json!({})));
|
|
let result = &r["result"];
|
|
assert_eq!(result["resultType"], "complete");
|
|
assert_eq!(result["supportedVersions"][0], "2026-07-28");
|
|
assert!(
|
|
result["supportedVersions"]
|
|
.as_array()
|
|
.unwrap()
|
|
.contains(&json!("2025-11-25"))
|
|
);
|
|
assert_eq!(
|
|
result["_meta"]["io.modelcontextprotocol/serverInfo"]["name"],
|
|
"lutra"
|
|
);
|
|
let r = ask(&mut s, modern("tools/list", 2, json!({})));
|
|
assert_eq!(r["result"]["resultType"], "complete");
|
|
assert_eq!(r["result"]["tools"].as_array().unwrap().len(), 5);
|
|
|
|
let mut bad = modern("tools/list", 3, json!({}));
|
|
bad["params"]["_meta"]["io.modelcontextprotocol/protocolVersion"] = json!("1900-01-01");
|
|
let r = ask(&mut s, bad);
|
|
assert_eq!(r["error"]["code"], -32022);
|
|
assert_eq!(r["error"]["data"]["requested"], "1900-01-01");
|
|
assert_eq!(r["error"]["data"]["supported"][0], "2026-07-28");
|
|
|
|
let mut bad = modern("tools/list", 4, json!({}));
|
|
bad["params"]["_meta"]
|
|
.as_object_mut()
|
|
.unwrap()
|
|
.remove("io.modelcontextprotocol/clientCapabilities");
|
|
assert_eq!(ask(&mut s, bad)["error"]["code"], -32602);
|
|
}
|
|
|
|
#[test]
|
|
fn lists_tools_in_a_fixed_order_without_lutra() {
|
|
let mut s = server();
|
|
let r = ask(
|
|
&mut s,
|
|
json!({"jsonrpc": "2.0", "id": 1, "method": "tools/list"}),
|
|
);
|
|
let names: Vec<&str> = r["result"]["tools"]
|
|
.as_array()
|
|
.unwrap()
|
|
.iter()
|
|
.map(|t| t["name"].as_str().unwrap())
|
|
.collect();
|
|
assert_eq!(
|
|
names,
|
|
vec![
|
|
"list_commands",
|
|
"execute_command",
|
|
"screenshot",
|
|
"read_buffer",
|
|
"get_events"
|
|
]
|
|
);
|
|
let r = ask(&mut s, json!({"jsonrpc": "2.0", "id": 2, "method": "ping"}));
|
|
assert_eq!(r["result"], json!({}));
|
|
let r = ask(
|
|
&mut s,
|
|
json!({"jsonrpc": "2.0", "id": 3, "method": "resources/templates/list"}),
|
|
);
|
|
assert_eq!(r["result"]["resourceTemplates"], json!([]));
|
|
}
|
|
|
|
#[test]
|
|
fn reports_protocol_and_tool_errors() {
|
|
let mut s = server();
|
|
let r = ask(&mut s, json!({"jsonrpc": "2.0", "id": 1, "method": "nope"}));
|
|
assert_eq!(r["error"]["code"], -32601);
|
|
let r = ask(
|
|
&mut s,
|
|
json!({"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "nope"}}),
|
|
);
|
|
assert_eq!(r["error"]["code"], -32602);
|
|
let r = ask(
|
|
&mut s,
|
|
json!({"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "list_commands", "arguments": 5}}),
|
|
);
|
|
assert_eq!(r["error"]["code"], -32602);
|
|
|
|
let call = |s: &mut Server, id: u64, name: &str, args: Value| {
|
|
ask(
|
|
s,
|
|
json!({"jsonrpc": "2.0", "id": id, "method": "tools/call", "params": {"name": name, "arguments": args}}),
|
|
)["result"]
|
|
.clone()
|
|
};
|
|
let r = call(&mut s, 4, "list_commands", json!({}));
|
|
assert_eq!(r["isError"], true);
|
|
assert_eq!(r["structuredContent"]["error"]["code"], "unavailable");
|
|
assert!(
|
|
r["content"][0]["text"]
|
|
.as_str()
|
|
.unwrap()
|
|
.starts_with("unavailable: ")
|
|
);
|
|
let r = call(&mut s, 5, "list_commands", json!({"bogus": 1}));
|
|
assert_eq!(r["structuredContent"]["error"]["code"], "invalid_params");
|
|
let r = call(&mut s, 6, "execute_command", json!({"command": "app.quit"}));
|
|
assert_eq!(
|
|
r["structuredContent"]["error"]["code"],
|
|
"confirmation_required"
|
|
);
|
|
let r = call(
|
|
&mut s,
|
|
7,
|
|
"execute_command",
|
|
json!({"command": "app.quit", "confirm": "yes"}),
|
|
);
|
|
assert_eq!(r["structuredContent"]["error"]["code"], "invalid_params");
|
|
let r = call(&mut s, 8, "read_buffer", json!({}));
|
|
assert_eq!(r["structuredContent"]["error"]["code"], "invalid_params");
|
|
let r = call(&mut s, 9, "get_events", json!({"max": 0}));
|
|
assert_eq!(r["structuredContent"]["error"]["code"], "invalid_params");
|
|
let r = call(&mut s, 10, "get_events", json!({"waitMs": 999_999}));
|
|
assert_eq!(r["structuredContent"]["error"]["code"], "invalid_params");
|
|
|
|
let r = ask(
|
|
&mut s,
|
|
json!({"jsonrpc": "2.0", "id": 11, "method": "resources/list"}),
|
|
);
|
|
assert_eq!(r["error"]["code"], -32603);
|
|
let r = ask(
|
|
&mut s,
|
|
json!({"jsonrpc": "2.0", "id": 12, "method": "resources/read", "params": {"uri": "file:///x"}}),
|
|
);
|
|
assert_eq!(r["error"]["code"], -32602);
|
|
assert_eq!(r["error"]["data"]["uri"], "file:///x");
|
|
}
|
|
|
|
#[test]
|
|
fn serves_lines_and_survives_garbage() {
|
|
let mut s = server();
|
|
let long = format!(
|
|
"{{\"x\":\"{}\"}}",
|
|
"a".repeat(lutra_mcp::server::MAX_LINE_BYTES)
|
|
);
|
|
let mut input = Vec::new();
|
|
input.extend_from_slice(b"\r\n \n");
|
|
input.extend_from_slice(long.as_bytes());
|
|
input.push(b'\n');
|
|
input.extend_from_slice(b"\xff\xfe\n");
|
|
input.extend_from_slice(br#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#);
|
|
input.push(b'\n');
|
|
input.extend_from_slice(b"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"ping\"}\r\n");
|
|
input.extend_from_slice(br#"{"jsonrpc":"2.0","id":2,"method":"ping"}"#);
|
|
let mut output = Vec::new();
|
|
s.serve(input.as_slice(), &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(), 4);
|
|
assert_eq!(lines[0]["error"]["code"], -32700);
|
|
assert_eq!(lines[1]["error"]["code"], -32700);
|
|
assert_eq!(lines[2]["id"], 1);
|
|
assert_eq!(lines[3]["id"], 2);
|
|
}
|
|
|
|
/// JSON-ish values that reach deep into the request shape.
|
|
fn message() -> impl Strategy<Value = String> {
|
|
let leaf = prop_oneof![
|
|
Just(json!(null)),
|
|
any::<bool>().prop_map(Value::from),
|
|
any::<i64>().prop_map(Value::from),
|
|
"[a-z/_.]{0,12}".prop_map(Value::from),
|
|
prop_oneof![
|
|
Just("tools/call"),
|
|
Just("resources/read"),
|
|
Just("initialize"),
|
|
Just("server/discover"),
|
|
Just("execute_command"),
|
|
Just("2.0"),
|
|
Just("_meta"),
|
|
Just("lutra://buffer/%zz")
|
|
]
|
|
.prop_map(Value::from),
|
|
];
|
|
let value = leaf.prop_recursive(4, 32, 6, |inner| {
|
|
prop_oneof![
|
|
proptest::collection::vec(inner.clone(), 0..4).prop_map(Value::from),
|
|
proptest::collection::btree_map(
|
|
prop_oneof![
|
|
Just("jsonrpc".to_string()),
|
|
Just("id".to_string()),
|
|
Just("method".to_string()),
|
|
Just("params".to_string()),
|
|
Just("name".to_string()),
|
|
Just("arguments".to_string()),
|
|
Just("uri".to_string()),
|
|
Just("_meta".to_string()),
|
|
Just("io.modelcontextprotocol/protocolVersion".to_string()),
|
|
"[a-z]{1,6}"
|
|
],
|
|
inner,
|
|
0..5
|
|
)
|
|
.prop_map(|m| Value::Object(m.into_iter().collect())),
|
|
]
|
|
});
|
|
prop_oneof![value.prop_map(|v| v.to_string()), ".{0,80}"]
|
|
}
|
|
|
|
proptest! {
|
|
#![proptest_config(ProptestConfig::with_cases(512))]
|
|
|
|
#[test]
|
|
fn never_panics_and_answers_with_one_line(line in message()) {
|
|
let mut s = server();
|
|
if let Some(response) = s.handle_line(&line) {
|
|
prop_assert!(!response.contains('\n'));
|
|
let value: Value = serde_json::from_str(&response).unwrap();
|
|
prop_assert_eq!(&value["jsonrpc"], "2.0");
|
|
prop_assert!(value.get("result").is_some() != value.get("error").is_some());
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn tool_calls_with_any_arguments_never_panic(
|
|
name in prop_oneof![Just("list_commands"), Just("execute_command"), Just("screenshot"), Just("read_buffer"), Just("get_events")],
|
|
args in proptest::collection::btree_map("[a-zA-Z]{1,10}", prop_oneof![Just(json!(null)), any::<i64>().prop_map(Value::from), ".{0,10}".prop_map(Value::from), Just(json!({})), Just(json!([1]))], 0..4),
|
|
) {
|
|
let mut s = server();
|
|
let request = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": name, "arguments": args}});
|
|
let response: Value = serde_json::from_str(&s.handle_line(&request.to_string()).unwrap()).unwrap();
|
|
prop_assert_eq!(&response["result"]["isError"], true);
|
|
}
|
|
}
|