M3.8: MCP server lutra mcp
- 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>
This commit is contained in:
parent
51eba0b3cb
commit
0e56c22b66
24 changed files with 3055 additions and 18 deletions
303
crates/mcp/tests/protocol.rs
Normal file
303
crates/mcp/tests/protocol.rs
Normal file
|
|
@ -0,0 +1,303 @@
|
|||
//! 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);
|
||||
}
|
||||
}
|
||||
369
crates/mcp/tests/tcp.rs
Normal file
369
crates/mcp/tests/tcp.rs
Normal file
|
|
@ -0,0 +1,369 @@
|
|||
//! 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"
|
||||
);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue