//! 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); /// 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 { self.0.execute(command, params) } fn list_commands(&self) -> Vec { 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 { self.0.request(method, params).map_err(call_error) } fn next_event(&mut self, timeout: Duration) -> Result, CallError> { self.0.next_event(Some(timeout)).map_err(call_error) } } impl Connector for Rendezvous { fn connect(&self, _start: bool) -> Result, 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, 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"), " 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"], "= 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" ); }