- 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>
369 lines
12 KiB
Rust
369 lines
12 KiB
Rust
//! The MCP server against a test backend over the real control channel:
|
|
//! a token listener with a rendezvous file, as the desktop app runs it.
|
|
|
|
#![allow(
|
|
clippy::unwrap_used,
|
|
clippy::expect_used,
|
|
clippy::panic,
|
|
clippy::indexing_slicing
|
|
)]
|
|
|
|
use std::path::{Path, PathBuf};
|
|
use std::sync::Arc;
|
|
use std::time::Duration;
|
|
|
|
use lutra_control::client::{self, ClientError};
|
|
use lutra_control::rendezvous::{self, Instance};
|
|
use lutra_control::{Backend, EventSink};
|
|
use lutra_engine::{CommandInfo, Effect, EngineError};
|
|
use lutra_mcp::{CallError, Connection, Connector, Server};
|
|
use lutra_testkit::EngineBackend;
|
|
use serde_json::{Value, json};
|
|
|
|
/// A test backend whose screenshots write a tiny PNG.
|
|
struct Window(Arc<EngineBackend>);
|
|
|
|
/// The smallest PNG header the server accepts, plus filler.
|
|
const PNG: &[u8] = b"\x89PNG\r\n\x1a\nfake image data";
|
|
|
|
impl Backend for Window {
|
|
fn execute(&self, command: &str, params: Value) -> Result<Value, EngineError> {
|
|
self.0.execute(command, params)
|
|
}
|
|
|
|
fn list_commands(&self) -> Vec<CommandInfo> {
|
|
self.0.list_commands()
|
|
}
|
|
|
|
fn screenshot(&self, path: &Path) -> Result<(), String> {
|
|
std::fs::write(path, PNG).map_err(|e| e.to_string())
|
|
}
|
|
|
|
fn subscribe(&self, sink: EventSink) {
|
|
self.0.subscribe(sink);
|
|
}
|
|
}
|
|
|
|
/// Reaches the backend through the rendezvous file in `dir`, like
|
|
/// `lutra mcp` does.
|
|
struct Rendezvous(PathBuf);
|
|
|
|
struct Live(client::Client);
|
|
|
|
fn call_error(e: ClientError) -> CallError {
|
|
match e {
|
|
ClientError::Remote { code, message } => CallError::Remote { code, message },
|
|
other => CallError::Lost(other.to_string()),
|
|
}
|
|
}
|
|
|
|
impl Connection for Live {
|
|
fn request(&mut self, method: &str, params: Value) -> Result<Value, CallError> {
|
|
self.0.request(method, params).map_err(call_error)
|
|
}
|
|
|
|
fn next_event(&mut self, timeout: Duration) -> Result<Option<Value>, CallError> {
|
|
self.0.next_event(Some(timeout)).map_err(call_error)
|
|
}
|
|
}
|
|
|
|
impl Connector for Rendezvous {
|
|
fn connect(&self, _start: bool) -> Result<Box<dyn Connection>, String> {
|
|
let (_, client) =
|
|
client::connect_live(&self.0, Duration::from_secs(5)).map_err(|e| e.to_string())?;
|
|
Ok(Box::new(Live(client)))
|
|
}
|
|
}
|
|
|
|
struct Fixture {
|
|
_dir: tempfile::TempDir,
|
|
project: PathBuf,
|
|
backend: Arc<EngineBackend>,
|
|
server: Server,
|
|
next_id: u64,
|
|
}
|
|
|
|
fn fixture() -> Fixture {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let project = dir.path().join("project");
|
|
std::fs::create_dir_all(project.join("src")).unwrap();
|
|
std::fs::write(project.join("src/a.php"), "<?php\necho 'ä';\n").unwrap();
|
|
std::fs::write(project.join("b c.php"), "<?php\n").unwrap();
|
|
let backend = Arc::new(EngineBackend::new());
|
|
let token = rendezvous::new_token().unwrap();
|
|
let handle =
|
|
lutra_control::start_with_token(0, Arc::new(Window(backend.clone())), &token).unwrap();
|
|
let rdv = dir.path().join("rdv");
|
|
rendezvous::write(
|
|
&rdv,
|
|
&Instance {
|
|
port: handle.local_addr().port(),
|
|
token,
|
|
pid: std::process::id(),
|
|
version: "test".into(),
|
|
},
|
|
)
|
|
.unwrap();
|
|
let server = Server::new(Arc::new(Rendezvous(rdv)));
|
|
Fixture {
|
|
_dir: dir,
|
|
project,
|
|
backend,
|
|
server,
|
|
next_id: 1,
|
|
}
|
|
}
|
|
|
|
impl Fixture {
|
|
fn request(&mut self, method: &str, params: Value) -> Value {
|
|
self.next_id += 1;
|
|
let line =
|
|
json!({"jsonrpc": "2.0", "id": self.next_id, "method": method, "params": params});
|
|
let response: Value =
|
|
serde_json::from_str(&self.server.handle_line(&line.to_string()).unwrap()).unwrap();
|
|
assert_eq!(response["id"], self.next_id);
|
|
response
|
|
}
|
|
|
|
fn tool(&mut self, name: &str, args: Value) -> Value {
|
|
self.request("tools/call", json!({"name": name, "arguments": args}))["result"].clone()
|
|
}
|
|
|
|
fn ok(&mut self, name: &str, args: Value) -> Value {
|
|
let result = self.tool(name, args);
|
|
assert_eq!(result["isError"], false, "{result}");
|
|
result
|
|
}
|
|
|
|
fn execute(&mut self, command: &str, params: Value) -> Value {
|
|
self.ok(
|
|
"execute_command",
|
|
json!({"command": command, "params": params}),
|
|
)["structuredContent"]["result"]
|
|
.clone()
|
|
}
|
|
|
|
fn open_project(&mut self) {
|
|
let path = self.project.display().to_string();
|
|
self.execute("project.open", json!({"path": path}));
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn lists_and_executes_commands() {
|
|
let mut f = fixture();
|
|
let all = f.ok("list_commands", json!({}));
|
|
let commands = all["structuredContent"]["commands"].as_array().unwrap();
|
|
let open = commands.iter().find(|c| c["id"] == "file.open").unwrap();
|
|
assert_eq!(open["enabled"], false);
|
|
assert!(open["params"].as_str().unwrap().contains("path"));
|
|
let text: Value = serde_json::from_str(all["content"][0]["text"].as_str().unwrap()).unwrap();
|
|
assert_eq!(text, all["structuredContent"]);
|
|
|
|
let filtered = f.ok("list_commands", json!({"filter": "BUFFER."}));
|
|
let ids: Vec<&str> = filtered["structuredContent"]["commands"]
|
|
.as_array()
|
|
.unwrap()
|
|
.iter()
|
|
.map(|c| c["id"].as_str().unwrap())
|
|
.collect();
|
|
assert_eq!(
|
|
ids,
|
|
vec!["buffer.close", "buffer.edit", "buffer.get", "buffer.list"]
|
|
);
|
|
let enabled = f.ok("list_commands", json!({"enabledOnly": true}));
|
|
assert!(
|
|
enabled["structuredContent"]["commands"]
|
|
.as_array()
|
|
.unwrap()
|
|
.iter()
|
|
.all(|c| c["enabled"] == true)
|
|
);
|
|
|
|
let err = f.tool(
|
|
"execute_command",
|
|
json!({"command": "file.open", "params": {"path": "src/a.php"}}),
|
|
);
|
|
assert_eq!(err["isError"], true);
|
|
assert_eq!(err["structuredContent"]["error"]["code"], "disabled");
|
|
let err = f.tool("execute_command", json!({"command": "no.such"}));
|
|
assert_eq!(err["structuredContent"]["error"]["code"], "unknown_command");
|
|
|
|
f.open_project();
|
|
let opened = f.execute("file.open", json!({"path": "src/a.php"}));
|
|
assert_eq!(opened["path"], "src/a.php");
|
|
assert_eq!(opened["text"], "<?php\necho 'ä';\n");
|
|
}
|
|
|
|
#[test]
|
|
fn quits_only_with_confirmation() {
|
|
let mut f = fixture();
|
|
let err = f.tool("execute_command", json!({"command": "app.quit"}));
|
|
assert_eq!(
|
|
err["structuredContent"]["error"]["code"],
|
|
"confirmation_required"
|
|
);
|
|
let err = f.tool(
|
|
"execute_command",
|
|
json!({"command": "app.quit", "confirm": false}),
|
|
);
|
|
assert_eq!(err["isError"], true);
|
|
assert!(f.backend.effects.lock().unwrap().is_empty());
|
|
f.ok(
|
|
"execute_command",
|
|
json!({"command": "app.quit", "confirm": true}),
|
|
);
|
|
assert_eq!(*f.backend.effects.lock().unwrap(), vec![Effect::Quit]);
|
|
}
|
|
|
|
#[test]
|
|
fn reads_buffers_and_resources() {
|
|
let mut f = fixture();
|
|
let r = f.request("resources/list", json!({}));
|
|
assert_eq!(r["result"]["resources"], json!([]));
|
|
f.open_project();
|
|
let a = f.execute("file.open", json!({"path": "src/a.php"}));
|
|
f.execute("file.open", json!({"path": "b c.php"}));
|
|
f.execute(
|
|
"buffer.edit",
|
|
json!({"id": a["id"], "baseVersion": 1, "edits": [{"from": 0, "to": 0, "insert": "//x\n"}]}),
|
|
);
|
|
|
|
let read = f.ok("read_buffer", json!({"path": "src/a.php"}));
|
|
assert_eq!(read["structuredContent"]["dirty"], true);
|
|
assert_eq!(read["structuredContent"]["version"], 2);
|
|
assert_eq!(read["structuredContent"]["truncated"], false);
|
|
assert_eq!(read["content"][1]["text"], "//x\n<?php\necho 'ä';\n");
|
|
let absolute = f.project.join("src").join("a.php").display().to_string();
|
|
let read = f.ok("read_buffer", json!({"path": absolute}));
|
|
assert_eq!(read["structuredContent"]["path"], "src/a.php");
|
|
let read = f.ok("read_buffer", json!({"id": a["id"]}));
|
|
assert_eq!(read["structuredContent"]["path"], "src/a.php");
|
|
let err = f.tool("read_buffer", json!({"path": "nope.php"}));
|
|
assert_eq!(err["structuredContent"]["error"]["code"], "not_open");
|
|
let err = f.tool("read_buffer", json!({"id": 999}));
|
|
assert_eq!(err["structuredContent"]["error"]["code"], "failed");
|
|
|
|
let r = f.request("resources/list", json!({}));
|
|
let resources = r["result"]["resources"].as_array().unwrap();
|
|
assert_eq!(resources.len(), 2);
|
|
assert_eq!(resources[0]["uri"], "lutra://buffer/src/a.php");
|
|
assert_eq!(resources[0]["mimeType"], "text/x-php");
|
|
assert!(resources[0]["description"].is_string(), "dirty is noted");
|
|
assert_eq!(resources[1]["uri"], "lutra://buffer/b%20c.php");
|
|
assert_eq!(resources[1]["name"], "b c.php");
|
|
|
|
let r = f.request("resources/read", json!({"uri": "lutra://buffer/b%20c.php"}));
|
|
assert_eq!(r["result"]["contents"][0]["text"], "<?php\n");
|
|
assert_eq!(
|
|
r["result"]["contents"][0]["uri"],
|
|
"lutra://buffer/b%20c.php"
|
|
);
|
|
let r = f.request(
|
|
"resources/read",
|
|
json!({"uri": "lutra://buffer/missing.php"}),
|
|
);
|
|
assert_eq!(r["error"]["code"], -32602);
|
|
}
|
|
|
|
#[test]
|
|
fn takes_screenshots_as_images() {
|
|
let mut f = fixture();
|
|
let shot = f.ok("screenshot", json!({}));
|
|
assert_eq!(shot["content"][0]["type"], "image");
|
|
assert_eq!(shot["content"][0]["mimeType"], "image/png");
|
|
assert_eq!(shot["content"][0]["data"], lutra_mcp::encoding::base64(PNG));
|
|
let kept = f.project.join("shot.png");
|
|
let shot = f.ok("screenshot", json!({"path": kept}));
|
|
assert!(
|
|
shot["content"][1]["text"]
|
|
.as_str()
|
|
.unwrap()
|
|
.contains("shot.png")
|
|
);
|
|
assert_eq!(std::fs::read(&kept).unwrap(), PNG);
|
|
}
|
|
|
|
#[test]
|
|
fn screenshot_failures_are_tool_errors() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let backend = Arc::new(EngineBackend::new());
|
|
let token = rendezvous::new_token().unwrap();
|
|
let handle = lutra_control::start_with_token(0, backend, &token).unwrap();
|
|
rendezvous::write(
|
|
dir.path(),
|
|
&Instance {
|
|
port: handle.local_addr().port(),
|
|
token,
|
|
pid: 1,
|
|
version: "test".into(),
|
|
},
|
|
)
|
|
.unwrap();
|
|
let mut server = Server::new(Arc::new(Rendezvous(dir.path().to_path_buf())));
|
|
let line = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "screenshot"}});
|
|
let r: Value = serde_json::from_str(&server.handle_line(&line.to_string()).unwrap()).unwrap();
|
|
assert_eq!(r["result"]["isError"], true);
|
|
assert_eq!(
|
|
r["result"]["structuredContent"]["error"]["code"],
|
|
"screenshot_failed"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn buffers_events_since_a_sequence_number() {
|
|
let mut f = fixture();
|
|
let first = f.ok("get_events", json!({}));
|
|
assert_eq!(first["structuredContent"]["events"], json!([]));
|
|
let wait_subscribed = |f: &mut Fixture| {
|
|
for _ in 0..100 {
|
|
let page = f.ok("get_events", json!({}));
|
|
if page["structuredContent"]["subscribed"] == true {
|
|
return;
|
|
}
|
|
std::thread::sleep(Duration::from_millis(20));
|
|
}
|
|
panic!("the event pump never subscribed");
|
|
};
|
|
wait_subscribed(&mut f);
|
|
f.open_project();
|
|
f.execute("file.open", json!({"path": "src/a.php"}));
|
|
let page = f.ok(
|
|
"get_events",
|
|
json!({"kinds": ["bufferOpened"], "waitMs": 5000}),
|
|
);
|
|
let events = page["structuredContent"]["events"].as_array().unwrap();
|
|
assert_eq!(events.len(), 1);
|
|
assert_eq!(events[0]["event"]["path"], "src/a.php");
|
|
let latest = page["structuredContent"]["latest"].as_u64().unwrap();
|
|
assert!(latest >= events[0]["seq"].as_u64().unwrap());
|
|
assert_eq!(page["structuredContent"]["missed"], false);
|
|
|
|
let page = f.ok("get_events", json!({"since": latest}));
|
|
assert_eq!(page["structuredContent"]["events"], json!([]));
|
|
let page = f.ok("get_events", json!({"max": 1}));
|
|
assert_eq!(
|
|
page["structuredContent"]["events"]
|
|
.as_array()
|
|
.unwrap()
|
|
.len(),
|
|
1
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn modern_tool_calls_work_over_the_wire() {
|
|
let mut f = fixture();
|
|
let r = f.request(
|
|
"tools/call",
|
|
json!({"name": "list_commands", "arguments": {"filter": "app.quit"}, "_meta": {
|
|
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
|
|
"io.modelcontextprotocol/clientCapabilities": {}
|
|
}}),
|
|
);
|
|
assert_eq!(r["result"]["resultType"], "complete");
|
|
assert_eq!(
|
|
r["result"]["structuredContent"]["commands"][0]["id"],
|
|
"app.quit"
|
|
);
|
|
}
|