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
|
|
@ -1,4 +1,5 @@
|
|||
//! Buffer commands: `buffer.get`, `buffer.edit`, `buffer.close`.
|
||||
//! Buffer commands: `buffer.get`, `buffer.edit`, `buffer.close`,
|
||||
//! `buffer.list`.
|
||||
//!
|
||||
//! Edits use UTF-16 code unit offsets, as CodeMirror and LSP do, and follow
|
||||
//! CodeMirror's change-set semantics: every `{from, to}` of a batch refers
|
||||
|
|
@ -222,3 +223,37 @@ impl Command for Close {
|
|||
Ok(Outcome::value(Value::Null))
|
||||
}
|
||||
}
|
||||
|
||||
/// `buffer.list`: the open buffers without their text, for agents (MCP
|
||||
/// resources) that need to know which files are open.
|
||||
pub struct List;
|
||||
|
||||
impl Command for List {
|
||||
fn spec(&self) -> &CommandSpec {
|
||||
&CommandSpec {
|
||||
id: "buffer.list",
|
||||
label: "List Buffers",
|
||||
menu_path: None,
|
||||
default_shortcut: None,
|
||||
params: "none; returns [{ id, path, version, dirty }] ordered by id, empty without a project",
|
||||
}
|
||||
}
|
||||
|
||||
fn run(&self, state: &mut State, _params: Value) -> Result<Outcome, EngineError> {
|
||||
let list: Vec<Value> = state
|
||||
.buffers
|
||||
.ids()
|
||||
.into_iter()
|
||||
.filter_map(|id| {
|
||||
let open = state.buffers.get(id)?;
|
||||
Some(json!({
|
||||
"id": id,
|
||||
"path": path_string(&open.path),
|
||||
"version": open.version,
|
||||
"dirty": open.dirty(),
|
||||
}))
|
||||
})
|
||||
.collect();
|
||||
Ok(Outcome::value(Value::Array(list)))
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -52,5 +52,6 @@ pub fn register_builtins(registry: &mut Registry) -> Result<(), EngineError> {
|
|||
registry.register(Box::new(syntax::OutlineCommand))?;
|
||||
registry.register(Box::new(toolchain::Status))?;
|
||||
registry.register(Box::new(toolchain::DownloadPhpactor))?;
|
||||
registry.register(Box::new(buffer::List))?;
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -388,6 +388,7 @@ mod tests {
|
|||
"buffer.close",
|
||||
"buffer.edit",
|
||||
"buffer.get",
|
||||
"buffer.list",
|
||||
"file.open",
|
||||
"file.save",
|
||||
"file.saveAll",
|
||||
|
|
|
|||
|
|
@ -529,3 +529,29 @@ fn a_panicking_command_leaves_open_buffers_intact() {
|
|||
assert_eq!(got["dirty"], true);
|
||||
run(&mut engine, "file.save", json!({"id": id}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn buffer_list_names_open_buffers_without_text() {
|
||||
let mut engine = Engine::new().unwrap();
|
||||
assert_eq!(
|
||||
run(&mut engine, "buffer.list", Value::Null).value,
|
||||
json!([])
|
||||
);
|
||||
let (_dir, mut engine, _) = open_project(&[("a.php", b"a"), ("src/b.php", b"b")]);
|
||||
let (a, _) = open_file(&mut engine, "a.php");
|
||||
let (b, _) = open_file(&mut engine, "src/b.php");
|
||||
run(
|
||||
&mut engine,
|
||||
"buffer.edit",
|
||||
json!({"id": b, "baseVersion": 1, "edits": [{"from": 0, "to": 0, "insert": "!"}]}),
|
||||
);
|
||||
let out = run(&mut engine, "buffer.list", json!({}));
|
||||
assert_eq!(
|
||||
out.value,
|
||||
json!([
|
||||
{"id": a, "path": "a.php", "version": 1, "dirty": false},
|
||||
{"id": b, "path": "src/b.php", "version": 2, "dirty": true},
|
||||
])
|
||||
);
|
||||
assert!(out.events.is_empty());
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,6 +12,14 @@ publish.workspace = true
|
|||
layer = 5
|
||||
|
||||
[dependencies]
|
||||
lutra-engine.workspace = true
|
||||
serde_json = "1.0.154"
|
||||
|
||||
[dev-dependencies]
|
||||
lutra-control.workspace = true
|
||||
lutra-testkit.workspace = true
|
||||
proptest.workspace = true
|
||||
tempfile.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
|
|
|||
130
crates/mcp/src/encoding.rs
Normal file
130
crates/mcp/src/encoding.rs
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
//! Small encoders the server needs: base64 for image content and the
|
||||
//! percent-encoding of buffer paths in `lutra://buffer/` resource URIs.
|
||||
|
||||
/// The scheme and authority of buffer resources.
|
||||
pub const BUFFER_URI_PREFIX: &str = "lutra://buffer/";
|
||||
|
||||
/// The standard base64 alphabet.
|
||||
const BASE64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
|
||||
/// Encodes `bytes` as standard base64 with padding.
|
||||
pub fn base64(bytes: &[u8]) -> String {
|
||||
let mut out = String::with_capacity(bytes.len().div_ceil(3).saturating_mul(4));
|
||||
let symbol =
|
||||
|index: u32| char::from(BASE64.get((index & 63) as usize).copied().unwrap_or(b'A'));
|
||||
for chunk in bytes.chunks(3) {
|
||||
let b = |i: usize| u32::from(chunk.get(i).copied().unwrap_or(0));
|
||||
let n = (b(0) << 16) | (b(1) << 8) | b(2);
|
||||
out.push(symbol(n >> 18));
|
||||
out.push(symbol(n >> 12));
|
||||
out.push(if chunk.len() > 1 { symbol(n >> 6) } else { '=' });
|
||||
out.push(if chunk.len() > 2 { symbol(n) } else { '=' });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether `b` stays as it is in a path segment of a buffer URI
|
||||
/// (RFC 3986 unreserved characters).
|
||||
fn unreserved(b: u8) -> bool {
|
||||
b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~')
|
||||
}
|
||||
|
||||
/// The resource URI of the buffer with project-relative `path`
|
||||
/// (`/`-separated): every byte outside the unreserved set is
|
||||
/// percent-encoded, slashes stay.
|
||||
pub fn buffer_uri(path: &str) -> String {
|
||||
let mut uri = String::from(BUFFER_URI_PREFIX);
|
||||
for b in path.bytes() {
|
||||
if unreserved(b) || b == b'/' {
|
||||
uri.push(char::from(b));
|
||||
} else {
|
||||
uri.push_str(&format!("%{b:02X}"));
|
||||
}
|
||||
}
|
||||
uri
|
||||
}
|
||||
|
||||
/// The project-relative path named by a buffer resource URI.
|
||||
///
|
||||
/// # Returns
|
||||
/// `None` for another scheme, an empty path, a bad percent escape, or a
|
||||
/// path that is not UTF-8.
|
||||
pub fn buffer_path(uri: &str) -> Option<String> {
|
||||
let encoded = uri.strip_prefix(BUFFER_URI_PREFIX)?;
|
||||
if encoded.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut bytes = Vec::with_capacity(encoded.len());
|
||||
let mut rest = encoded.bytes();
|
||||
while let Some(b) = rest.next() {
|
||||
if b == b'%' {
|
||||
let hi = hex(rest.next()?)?;
|
||||
let lo = hex(rest.next()?)?;
|
||||
bytes.push((hi << 4) | lo);
|
||||
} else {
|
||||
bytes.push(b);
|
||||
}
|
||||
}
|
||||
String::from_utf8(bytes).ok()
|
||||
}
|
||||
|
||||
/// The value of one hex digit.
|
||||
fn hex(b: u8) -> Option<u8> {
|
||||
char::from(b)
|
||||
.to_digit(16)
|
||||
.and_then(|d| u8::try_from(d).ok())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use proptest::prelude::*;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn encodes_base64() {
|
||||
assert_eq!(base64(b""), "");
|
||||
assert_eq!(base64(b"f"), "Zg==");
|
||||
assert_eq!(base64(b"fo"), "Zm8=");
|
||||
assert_eq!(base64(b"foo"), "Zm9v");
|
||||
assert_eq!(base64(b"foobar"), "Zm9vYmFy");
|
||||
assert_eq!(base64(&[0xff, 0xfe, 0x00]), "//4A");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encodes_buffer_uris() {
|
||||
assert_eq!(buffer_uri("src/a.php"), "lutra://buffer/src/a.php");
|
||||
assert_eq!(
|
||||
buffer_uri("my dir/ä#?.php"),
|
||||
"lutra://buffer/my%20dir/%C3%A4%23%3F.php"
|
||||
);
|
||||
assert_eq!(
|
||||
buffer_path("lutra://buffer/my%20dir/%c3%a4.php").as_deref(),
|
||||
Some("my dir/ä.php")
|
||||
);
|
||||
assert_eq!(buffer_path("lutra://buffer/"), None);
|
||||
assert_eq!(buffer_path("file:///a.php"), None);
|
||||
assert_eq!(buffer_path("lutra://buffer/%zz"), None);
|
||||
assert_eq!(buffer_path("lutra://buffer/%4"), None);
|
||||
assert_eq!(buffer_path("lutra://buffer/%ff"), None);
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#[test]
|
||||
fn buffer_uris_round_trip(path in "[^\\x00]{1,40}") {
|
||||
prop_assert_eq!(buffer_path(&buffer_uri(&path)), Some(path));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn buffer_path_never_panics(uri in ".{0,60}") {
|
||||
let _ = buffer_path(&uri);
|
||||
let _ = buffer_path(&format!("{BUFFER_URI_PREFIX}{uri}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn base64_has_the_right_length(bytes in proptest::collection::vec(any::<u8>(), 0..100)) {
|
||||
let text = base64(&bytes);
|
||||
prop_assert_eq!(text.len(), bytes.len().div_ceil(3) * 4);
|
||||
}
|
||||
}
|
||||
}
|
||||
311
crates/mcp/src/events.rs
Normal file
311
crates/mcp/src/events.rs
Normal file
|
|
@ -0,0 +1,311 @@
|
|||
//! The recent-event buffer behind the `get_events` tool.
|
||||
//!
|
||||
//! A pump thread holds its own control connection subscribed to engine
|
||||
//! events (`events.subscribe`) and appends every event to a ring of the
|
||||
//! last [`CAPACITY`] events, each numbered with a sequence number that
|
||||
//! only grows. `get_events {since}` returns the events after `since`, so
|
||||
//! an agent polls without missing or repeating events while it keeps up.
|
||||
//! Events the ring dropped, or that were missed while the subscription
|
||||
//! was down, are reported as a gap instead of being silently skipped.
|
||||
//!
|
||||
//! Events are untrusted: an event whose JSON is larger than
|
||||
//! [`MAX_EVENT_BYTES`] is replaced by its kind and `truncated: true`.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::remote::{CallError, Connector};
|
||||
|
||||
/// The control method that subscribes a connection to engine events.
|
||||
const SUBSCRIBE: &str = "events.subscribe";
|
||||
|
||||
/// Events kept in the ring.
|
||||
pub const CAPACITY: usize = 1000;
|
||||
|
||||
/// Largest event kept whole, in bytes of JSON.
|
||||
pub const MAX_EVENT_BYTES: usize = 16 * 1024;
|
||||
|
||||
/// How long the pump waits for one event before it checks whether it
|
||||
/// should stop.
|
||||
const PUMP_TICK: Duration = Duration::from_millis(250);
|
||||
|
||||
/// Pause before the pump connects again after losing its connection.
|
||||
const RECONNECT_PAUSE: Duration = Duration::from_millis(500);
|
||||
|
||||
/// The ring and its bookkeeping.
|
||||
#[derive(Debug, Default)]
|
||||
struct Ring {
|
||||
/// `(seq, event)`, oldest first.
|
||||
events: VecDeque<(u64, Value)>,
|
||||
/// The sequence number of the newest event; 0 before the first.
|
||||
latest: u64,
|
||||
/// For each outage of the subscription, the sequence number the next
|
||||
/// event got: events may be missing just before it.
|
||||
gaps: VecDeque<u64>,
|
||||
/// Whether the pump currently has a live subscription.
|
||||
subscribed: bool,
|
||||
}
|
||||
|
||||
/// The shared event buffer.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct EventLog {
|
||||
/// The ring.
|
||||
ring: Mutex<Ring>,
|
||||
/// Signalled when an event arrives.
|
||||
arrived: Condvar,
|
||||
}
|
||||
|
||||
/// What `get_events` returns.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Page {
|
||||
/// `(seq, event)` in order.
|
||||
pub events: Vec<(u64, Value)>,
|
||||
/// The newest sequence number known; pass it as `since` next time.
|
||||
pub latest: u64,
|
||||
/// Whether events after `since` were lost: dropped from the ring, or
|
||||
/// missed while the subscription was down.
|
||||
pub missed: bool,
|
||||
/// Whether events are being received right now.
|
||||
pub subscribed: bool,
|
||||
}
|
||||
|
||||
impl EventLog {
|
||||
/// Locks the ring; a poisoned lock is still usable because every
|
||||
/// update leaves the ring consistent.
|
||||
fn lock(&self) -> MutexGuard<'_, Ring> {
|
||||
self.ring.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// Appends one event, dropping the oldest when the ring is full.
|
||||
pub fn push(&self, event: Value) {
|
||||
let event = cap(event);
|
||||
let mut ring = self.lock();
|
||||
ring.latest = ring.latest.saturating_add(1);
|
||||
let seq = ring.latest;
|
||||
if ring.events.len() >= CAPACITY {
|
||||
ring.events.pop_front();
|
||||
}
|
||||
ring.events.push_back((seq, event));
|
||||
drop(ring);
|
||||
self.arrived.notify_all();
|
||||
}
|
||||
|
||||
/// Records whether the subscription is live. Going down marks a gap
|
||||
/// before the next event.
|
||||
pub fn set_subscribed(&self, subscribed: bool) {
|
||||
let mut ring = self.lock();
|
||||
if ring.subscribed && !subscribed {
|
||||
let next = ring.latest.saturating_add(1);
|
||||
if ring.gaps.len() >= CAPACITY {
|
||||
ring.gaps.pop_front();
|
||||
}
|
||||
ring.gaps.push_back(next);
|
||||
}
|
||||
ring.subscribed = subscribed;
|
||||
}
|
||||
|
||||
/// The events after `since` matching `kinds` (all if empty), at most
|
||||
/// `max`. If none match yet, waits up to `wait` for one to arrive.
|
||||
pub fn page(&self, since: u64, max: usize, kinds: &[String], wait: Duration) -> Page {
|
||||
let deadline = Instant::now() + wait;
|
||||
let mut ring = self.lock();
|
||||
loop {
|
||||
let page = select(&ring, since, max, kinds);
|
||||
let left = deadline.saturating_duration_since(Instant::now());
|
||||
if !page.events.is_empty() || left.is_zero() {
|
||||
return page;
|
||||
}
|
||||
ring = self
|
||||
.arrived
|
||||
.wait_timeout(ring, left)
|
||||
.map(|(guard, _)| guard)
|
||||
.unwrap_or_else(|e| e.into_inner().0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds a page from the ring.
|
||||
fn select(ring: &Ring, since: u64, max: usize, kinds: &[String]) -> Page {
|
||||
let oldest = ring
|
||||
.events
|
||||
.front()
|
||||
.map_or(ring.latest.saturating_add(1), |(seq, _)| *seq);
|
||||
let dropped = since.saturating_add(1) < oldest && since < ring.latest;
|
||||
let outage = ring.gaps.iter().any(|gap| *gap > since);
|
||||
let wanted = |event: &Value| {
|
||||
kinds.is_empty()
|
||||
|| event
|
||||
.get("kind")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|kind| kinds.iter().any(|k| k == kind))
|
||||
};
|
||||
let events: Vec<(u64, Value)> = ring
|
||||
.events
|
||||
.iter()
|
||||
.filter(|(seq, event)| *seq > since && wanted(event))
|
||||
.take(max)
|
||||
.cloned()
|
||||
.collect();
|
||||
let latest = match events.last() {
|
||||
Some((seq, _)) if events.len() >= max => *seq,
|
||||
_ => ring.latest,
|
||||
};
|
||||
Page {
|
||||
events,
|
||||
latest,
|
||||
missed: dropped || outage,
|
||||
subscribed: ring.subscribed,
|
||||
}
|
||||
}
|
||||
|
||||
/// Replaces an event larger than [`MAX_EVENT_BYTES`] by its kind.
|
||||
fn cap(event: Value) -> Value {
|
||||
let size = serde_json::to_string(&event).map_or(usize::MAX, |text| text.len());
|
||||
if size <= MAX_EVENT_BYTES {
|
||||
return event;
|
||||
}
|
||||
let kind = event.get("kind").cloned().unwrap_or(Value::Null);
|
||||
json!({ "kind": kind, "truncated": true, "bytes": size })
|
||||
}
|
||||
|
||||
/// The pump thread's handle; dropping it stops the thread at its next
|
||||
/// tick.
|
||||
#[derive(Debug)]
|
||||
pub struct Pump {
|
||||
/// Set to stop the thread.
|
||||
stop: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl Drop for Pump {
|
||||
fn drop(&mut self) {
|
||||
self.stop.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts the pump: connects without starting Lutra, subscribes and
|
||||
/// appends events to `log` until the handle is dropped. A lost connection
|
||||
/// is retried every [`RECONNECT_PAUSE`].
|
||||
///
|
||||
/// # Errors
|
||||
/// If the thread cannot be spawned.
|
||||
pub fn start(connector: Arc<dyn Connector>, log: Arc<EventLog>) -> std::io::Result<Pump> {
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let flag = stop.clone();
|
||||
thread::Builder::new()
|
||||
.name("lutra-mcp-events".into())
|
||||
.spawn(move || pump(connector.as_ref(), &log, &flag))?;
|
||||
Ok(Pump { stop })
|
||||
}
|
||||
|
||||
/// The pump loop.
|
||||
fn pump(connector: &dyn Connector, log: &EventLog, stop: &AtomicBool) {
|
||||
while !stop.load(Ordering::Relaxed) {
|
||||
let mut connection = match connector.connect(false) {
|
||||
Ok(connection) => connection,
|
||||
Err(_) => {
|
||||
thread::sleep(RECONNECT_PAUSE);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if connection.request(SUBSCRIBE, Value::Null).is_err() {
|
||||
thread::sleep(RECONNECT_PAUSE);
|
||||
continue;
|
||||
}
|
||||
log.set_subscribed(true);
|
||||
while !stop.load(Ordering::Relaxed) {
|
||||
match connection.next_event(PUMP_TICK) {
|
||||
Ok(Some(event)) => {
|
||||
if event.get("kind").and_then(Value::as_str) == Some("subscriptionLost") {
|
||||
break;
|
||||
}
|
||||
log.push(event);
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(CallError::Lost(_) | CallError::Remote { .. }) => break,
|
||||
}
|
||||
}
|
||||
log.set_subscribed(false);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn kinds(page: &Page) -> Vec<u64> {
|
||||
page.events.iter().map(|(seq, _)| *seq).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pages_follow_sequence_numbers() {
|
||||
let log = EventLog::default();
|
||||
log.set_subscribed(true);
|
||||
for i in 0..5 {
|
||||
log.push(json!({"kind": if i % 2 == 0 { "a" } else { "b" }, "i": i}));
|
||||
}
|
||||
let page = log.page(0, 100, &[], Duration::ZERO);
|
||||
assert_eq!(kinds(&page), vec![1, 2, 3, 4, 5]);
|
||||
assert_eq!(page.latest, 5);
|
||||
assert!(!page.missed);
|
||||
assert!(page.subscribed);
|
||||
let page = log.page(3, 100, &[], Duration::ZERO);
|
||||
assert_eq!(kinds(&page), vec![4, 5]);
|
||||
let page = log.page(0, 2, &[], Duration::ZERO);
|
||||
assert_eq!(kinds(&page), vec![1, 2]);
|
||||
assert_eq!(
|
||||
page.latest, 2,
|
||||
"the next page starts after the last one returned"
|
||||
);
|
||||
let page = log.page(0, 100, &["b".to_string()], Duration::ZERO);
|
||||
assert_eq!(kinds(&page), vec![2, 4]);
|
||||
assert_eq!(page.latest, 5);
|
||||
assert!(log.page(5, 100, &[], Duration::ZERO).events.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reports_dropped_and_missed_events() {
|
||||
let log = EventLog::default();
|
||||
log.set_subscribed(true);
|
||||
for _ in 0..CAPACITY + 10 {
|
||||
log.push(json!({"kind": "x"}));
|
||||
}
|
||||
let page = log.page(0, 5, &[], Duration::ZERO);
|
||||
assert_eq!(page.events.first().map(|(seq, _)| *seq), Some(11));
|
||||
assert!(page.missed);
|
||||
assert!(!log.page(20, 5, &[], Duration::ZERO).missed);
|
||||
let latest = log.page(0, CAPACITY, &[], Duration::ZERO).latest;
|
||||
log.set_subscribed(false);
|
||||
log.set_subscribed(true);
|
||||
log.push(json!({"kind": "y"}));
|
||||
let page = log.page(latest, 5, &[], Duration::ZERO);
|
||||
assert!(page.missed, "an outage after `since` is reported");
|
||||
assert!(!log.page(latest + 1, 5, &[], Duration::ZERO).missed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn caps_large_events() {
|
||||
let log = EventLog::default();
|
||||
log.push(json!({"kind": "big", "text": "x".repeat(MAX_EVENT_BYTES)}));
|
||||
let page = log.page(0, 1, &[], Duration::ZERO);
|
||||
assert_eq!(page.events[0].1["kind"], "big");
|
||||
assert_eq!(page.events[0].1["truncated"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn waits_for_an_event() {
|
||||
let log = Arc::new(EventLog::default());
|
||||
let writer = log.clone();
|
||||
let handle = thread::spawn(move || {
|
||||
thread::sleep(Duration::from_millis(50));
|
||||
writer.push(json!({"kind": "late"}));
|
||||
});
|
||||
let page = log.page(0, 10, &[], Duration::from_secs(10));
|
||||
handle.join().unwrap();
|
||||
assert_eq!(page.events.len(), 1);
|
||||
}
|
||||
}
|
||||
230
crates/mcp/src/jsonrpc.rs
Normal file
230
crates/mcp/src/jsonrpc.rs
Normal file
|
|
@ -0,0 +1,230 @@
|
|||
//! JSON-RPC 2.0 messages as MCP uses them on stdio: one message per line,
|
||||
//! no batches.
|
||||
//!
|
||||
//! Every line is untrusted. [`parse`] turns any input into an
|
||||
//! [`Incoming`] message or a ready error response and never panics; the
|
||||
//! response helpers always produce one valid line.
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
/// Standard JSON-RPC error codes and the MCP codes Lutra emits.
|
||||
pub mod codes {
|
||||
/// The line is not valid JSON.
|
||||
pub const PARSE_ERROR: i64 = -32700;
|
||||
/// The JSON is not a valid request.
|
||||
pub const INVALID_REQUEST: i64 = -32600;
|
||||
/// No such method.
|
||||
pub const METHOD_NOT_FOUND: i64 = -32601;
|
||||
/// Bad params, an unknown tool or resource, or missing request
|
||||
/// metadata.
|
||||
pub const INVALID_PARAMS: i64 = -32602;
|
||||
/// The server failed.
|
||||
pub const INTERNAL_ERROR: i64 = -32603;
|
||||
/// The request names a protocol version the server does not support
|
||||
/// (MCP 2026-07-28).
|
||||
pub const UNSUPPORTED_PROTOCOL_VERSION: i64 = -32022;
|
||||
}
|
||||
|
||||
/// One message read from the client.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Incoming {
|
||||
/// A request, which gets exactly one response.
|
||||
Request {
|
||||
/// The id: a number or a string.
|
||||
id: Value,
|
||||
/// The method name.
|
||||
method: String,
|
||||
/// The params object; empty if absent.
|
||||
params: Map<String, Value>,
|
||||
},
|
||||
/// A notification, which gets no response.
|
||||
Notification {
|
||||
/// The method name.
|
||||
method: String,
|
||||
},
|
||||
/// A response to a request of ours; Lutra sends none, so it is
|
||||
/// ignored.
|
||||
Response,
|
||||
}
|
||||
|
||||
/// Parses one line.
|
||||
///
|
||||
/// # Errors
|
||||
/// The error response line to send back: a parse error for invalid
|
||||
/// JSON, invalid request for anything that is not a single JSON-RPC 2.0
|
||||
/// message, invalid params for params that are not an object.
|
||||
pub fn parse(line: &str) -> Result<Incoming, String> {
|
||||
let value: Value = serde_json::from_str(line)
|
||||
.map_err(|e| error(&Value::Null, codes::PARSE_ERROR, &e.to_string(), None))?;
|
||||
let Value::Object(mut object) = value else {
|
||||
return Err(error(
|
||||
&Value::Null,
|
||||
codes::INVALID_REQUEST,
|
||||
"a message must be one JSON object (batches are not supported)",
|
||||
None,
|
||||
));
|
||||
};
|
||||
let id = object.remove("id");
|
||||
let id_ok = matches!(id, Some(Value::Number(_) | Value::String(_)));
|
||||
let echo = if id_ok {
|
||||
id.clone().unwrap_or(Value::Null)
|
||||
} else {
|
||||
Value::Null
|
||||
};
|
||||
if object.get("jsonrpc").and_then(Value::as_str) != Some("2.0") {
|
||||
return Err(error(
|
||||
&echo,
|
||||
codes::INVALID_REQUEST,
|
||||
"jsonrpc must be \"2.0\"",
|
||||
None,
|
||||
));
|
||||
}
|
||||
let method = match object.remove("method") {
|
||||
Some(Value::String(method)) => method,
|
||||
Some(_) => {
|
||||
return Err(error(
|
||||
&echo,
|
||||
codes::INVALID_REQUEST,
|
||||
"method must be a string",
|
||||
None,
|
||||
));
|
||||
}
|
||||
None if object.contains_key("result") || object.contains_key("error") => {
|
||||
return Ok(Incoming::Response);
|
||||
}
|
||||
None => {
|
||||
return Err(error(&echo, codes::INVALID_REQUEST, "missing method", None));
|
||||
}
|
||||
};
|
||||
let params = match object.remove("params") {
|
||||
None | Some(Value::Null) => Map::new(),
|
||||
Some(Value::Object(params)) => params,
|
||||
Some(_) => {
|
||||
if id.is_none() {
|
||||
return Ok(Incoming::Notification { method });
|
||||
}
|
||||
return Err(error(
|
||||
&echo,
|
||||
codes::INVALID_PARAMS,
|
||||
"params must be an object",
|
||||
None,
|
||||
));
|
||||
}
|
||||
};
|
||||
match id {
|
||||
None => Ok(Incoming::Notification { method }),
|
||||
Some(_) if !id_ok => Err(error(
|
||||
&Value::Null,
|
||||
codes::INVALID_REQUEST,
|
||||
"the id must be a number or a string",
|
||||
None,
|
||||
)),
|
||||
Some(id) => Ok(Incoming::Request { id, method, params }),
|
||||
}
|
||||
}
|
||||
|
||||
/// A success response line.
|
||||
pub fn result(id: &Value, result: Value) -> String {
|
||||
encode(&json!({ "jsonrpc": "2.0", "id": id, "result": result }))
|
||||
}
|
||||
|
||||
/// An error response line, with optional `data`.
|
||||
pub fn error(id: &Value, code: i64, message: &str, data: Option<Value>) -> String {
|
||||
let mut error = json!({ "code": code, "message": message });
|
||||
if let (Some(data), Some(object)) = (data, error.as_object_mut()) {
|
||||
object.insert("data".into(), data);
|
||||
}
|
||||
encode(&json!({ "jsonrpc": "2.0", "id": id, "error": error }))
|
||||
}
|
||||
|
||||
/// Serialises a message as one line. serde_json escapes control
|
||||
/// characters inside strings, so the line has no embedded newline.
|
||||
fn encode(message: &Value) -> String {
|
||||
serde_json::to_string(message).unwrap_or_else(|_| {
|
||||
String::from(
|
||||
r#"{"jsonrpc":"2.0","id":null,"error":{"code":-32603,"message":"cannot encode the response"}}"#,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn err_code(line: &str) -> (Value, i64) {
|
||||
let response: Value = serde_json::from_str(&parse(line).unwrap_err()).unwrap();
|
||||
(
|
||||
response["id"].clone(),
|
||||
response["error"]["code"].as_i64().unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_requests_and_notifications() {
|
||||
let m = parse(r#"{"jsonrpc":"2.0","id":7,"method":"tools/list"}"#).unwrap();
|
||||
assert_eq!(
|
||||
m,
|
||||
Incoming::Request {
|
||||
id: json!(7),
|
||||
method: "tools/list".into(),
|
||||
params: Map::new()
|
||||
}
|
||||
);
|
||||
let m = parse(r#"{"jsonrpc":"2.0","id":"a","method":"x","params":{"k":1}}"#).unwrap();
|
||||
let Incoming::Request { id, params, .. } = m else {
|
||||
panic!()
|
||||
};
|
||||
assert_eq!(id, json!("a"));
|
||||
assert_eq!(params["k"], 1);
|
||||
assert_eq!(
|
||||
parse(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#).unwrap(),
|
||||
Incoming::Notification {
|
||||
method: "notifications/initialized".into()
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
parse(r#"{"jsonrpc":"2.0","id":1,"result":{}}"#).unwrap(),
|
||||
Incoming::Response
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_bad_messages() {
|
||||
assert_eq!(err_code("{"), (Value::Null, codes::PARSE_ERROR));
|
||||
assert_eq!(err_code("[]"), (Value::Null, codes::INVALID_REQUEST));
|
||||
assert_eq!(
|
||||
err_code(r#"{"id":1,"method":"x"}"#),
|
||||
(json!(1), codes::INVALID_REQUEST)
|
||||
);
|
||||
assert_eq!(
|
||||
err_code(r#"{"jsonrpc":"2.0","id":null,"method":"x"}"#),
|
||||
(Value::Null, codes::INVALID_REQUEST)
|
||||
);
|
||||
assert_eq!(
|
||||
err_code(r#"{"jsonrpc":"2.0","id":{},"method":"x"}"#),
|
||||
(Value::Null, codes::INVALID_REQUEST)
|
||||
);
|
||||
assert_eq!(
|
||||
err_code(r#"{"jsonrpc":"2.0","id":2,"method":5}"#),
|
||||
(json!(2), codes::INVALID_REQUEST)
|
||||
);
|
||||
assert_eq!(
|
||||
err_code(r#"{"jsonrpc":"2.0","id":3,"method":"x","params":[1]}"#),
|
||||
(json!(3), codes::INVALID_PARAMS)
|
||||
);
|
||||
assert_eq!(
|
||||
err_code(r#"{"jsonrpc":"2.0","id":4}"#),
|
||||
(json!(4), codes::INVALID_REQUEST)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn responses_are_single_lines() {
|
||||
let line = result(&json!(1), json!({"text": "a\nb"}));
|
||||
assert!(!line.contains('\n'));
|
||||
let line = error(&json!("x"), codes::INTERNAL_ERROR, "a\nb", Some(json!(1)));
|
||||
assert!(!line.contains('\n'));
|
||||
let value: Value = serde_json::from_str(&line).unwrap();
|
||||
assert_eq!(value["error"]["data"], 1);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,3 +1,25 @@
|
|||
//! MCP server of Lutra (layer L5).
|
||||
//!
|
||||
//! Exposes the engine commands as Model Context Protocol tools over stdio.
|
||||
//! `lutra mcp` speaks the Model Context Protocol over stdio so that
|
||||
//! agents can drive Lutra: JSON-RPC 2.0, one message per line
|
||||
//! ([`jsonrpc`]), served by [`server::Server`] in both the modern
|
||||
//! (2026-07-28, per-request metadata) and the legacy (`initialize`) era.
|
||||
//! The tools are generic over the command registry (D16): see [`tools`].
|
||||
//! Resources are the open buffers. Recent engine events are kept by
|
||||
//! [`events`].
|
||||
//!
|
||||
//! The crate does not open sockets or start processes itself: the `lutra`
|
||||
//! CLI implements [`remote::Connector`] with the control channel client
|
||||
//! and the single-instance rendezvous (`lutra_control::client`).
|
||||
//! Everything read from stdin or from Lutra is untrusted, capped and
|
||||
//! never panics.
|
||||
|
||||
pub mod encoding;
|
||||
pub mod events;
|
||||
pub mod jsonrpc;
|
||||
pub mod remote;
|
||||
pub mod server;
|
||||
pub mod tools;
|
||||
|
||||
pub use remote::{CallError, Connection, Connector};
|
||||
pub use server::Server;
|
||||
|
|
|
|||
84
crates/mcp/src/remote.rs
Normal file
84
crates/mcp/src/remote.rs
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
//! The connection to a running Lutra, as the MCP server sees it.
|
||||
//!
|
||||
//! The server does not know how Lutra is reached: the `lutra` CLI (layer
|
||||
//! L6) implements [`Connector`] on top of the control channel client and
|
||||
//! the single-instance rendezvous file, and tests implement it with a
|
||||
//! test backend. That keeps this crate free of sockets and process
|
||||
//! launching.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
/// Error code of a failure to reach Lutra or of a lost connection.
|
||||
pub const UNAVAILABLE: &str = "unavailable";
|
||||
|
||||
/// Why a call to Lutra failed.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum CallError {
|
||||
/// Lutra answered with an error: the engine's or the control
|
||||
/// channel's code and message.
|
||||
Remote {
|
||||
/// Stable code, e.g. `disabled` or `invalid_params`.
|
||||
code: String,
|
||||
/// Human-readable message.
|
||||
message: String,
|
||||
},
|
||||
/// The connection failed or was lost, or Lutra sent something that is
|
||||
/// not a protocol line. The next call connects again.
|
||||
Lost(String),
|
||||
}
|
||||
|
||||
impl CallError {
|
||||
/// The stable code: the remote code, or [`UNAVAILABLE`].
|
||||
pub fn code(&self) -> &str {
|
||||
match self {
|
||||
Self::Remote { code, .. } => code,
|
||||
Self::Lost(_) => UNAVAILABLE,
|
||||
}
|
||||
}
|
||||
|
||||
/// The message.
|
||||
pub fn message(&self) -> &str {
|
||||
match self {
|
||||
Self::Remote { message, .. } | Self::Lost(message) => message,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for CallError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}: {}", self.code(), self.message())
|
||||
}
|
||||
}
|
||||
|
||||
/// One authenticated connection to the control channel.
|
||||
pub trait Connection: Send {
|
||||
/// Sends one control request (`engine.execute`, `ui.screenshot`, …)
|
||||
/// and waits for its result.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`CallError::Remote`] for an error answer, [`CallError::Lost`] if
|
||||
/// the connection failed.
|
||||
fn request(&mut self, method: &str, params: Value) -> Result<Value, CallError>;
|
||||
|
||||
/// The next event (the object inside `{"event": ...}`) after
|
||||
/// `events.subscribe`, waiting at most `timeout`.
|
||||
///
|
||||
/// # Returns
|
||||
/// `Ok(None)` if none arrived in time.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`CallError::Lost`] if the connection failed.
|
||||
fn next_event(&mut self, timeout: Duration) -> Result<Option<Value>, CallError>;
|
||||
}
|
||||
|
||||
/// Opens connections to Lutra.
|
||||
pub trait Connector: Send + Sync {
|
||||
/// Connects to the running Lutra. With `start`, a Lutra that is not
|
||||
/// running is started first.
|
||||
///
|
||||
/// # Errors
|
||||
/// A message saying why Lutra cannot be reached.
|
||||
fn connect(&self, start: bool) -> Result<Box<dyn Connection>, String>;
|
||||
}
|
||||
489
crates/mcp/src/server.rs
Normal file
489
crates/mcp/src/server.rs
Normal file
|
|
@ -0,0 +1,489 @@
|
|||
//! The MCP server: protocol versions, methods, resources and the stdio
|
||||
//! loop.
|
||||
//!
|
||||
//! Lutra serves both eras of MCP on one stdio process:
|
||||
//! - **Modern** (2026-07-28): every request carries its protocol version
|
||||
//! and client capabilities in `_meta`; there is no handshake.
|
||||
//! `server/discover` reports the versions and capabilities, results
|
||||
//! carry `resultType: "complete"` and the server info in `_meta`, and an
|
||||
//! unsupported version gets `UnsupportedProtocolVersion` (-32022).
|
||||
//! - **Legacy** (2025-11-25 back to 2024-11-05): the client starts with
|
||||
//! `initialize`; the server answers with the client's version if it
|
||||
//! knows it, else its newest legacy version.
|
||||
//!
|
||||
//! A request with neither modern metadata nor a prior `initialize` is
|
||||
//! served with legacy result shapes, which is what simple scripts expect.
|
||||
//!
|
||||
//! Methods: `server/discover`, `initialize`, `ping`, `tools/list`,
|
||||
//! `tools/call`, `resources/list`, `resources/read`,
|
||||
//! `resources/templates/list`. Notifications (`notifications/initialized`,
|
||||
//! `notifications/cancelled`, …) are accepted and need no answer. Lists
|
||||
//! are returned whole; a `cursor` is ignored.
|
||||
//!
|
||||
//! Resources are the open buffers, `lutra://buffer/<project-relative
|
||||
//! path>` (see [`crate::encoding::buffer_uri`]), read with their unsaved
|
||||
//! changes.
|
||||
//!
|
||||
//! The connection to Lutra is made on the first call that needs it, so
|
||||
//! listing tools never starts Lutra. Before each use the connection is
|
||||
//! pinged; a dead one is replaced (which starts Lutra again if it quit).
|
||||
//! Every request runs under [`lutra_engine::guard`], so a bug answers with
|
||||
//! an internal error instead of ending the process.
|
||||
|
||||
use std::io::{self, BufRead, Write};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use lutra_engine::guard;
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::encoding::{buffer_path, buffer_uri};
|
||||
use crate::events::{self, EventLog, Pump};
|
||||
use crate::jsonrpc::{self, Incoming, codes};
|
||||
use crate::remote::{CallError, Connection, Connector};
|
||||
use crate::tools::{self, Host};
|
||||
|
||||
/// The modern protocol versions, newest first.
|
||||
pub const MODERN_VERSIONS: &[&str] = &["2026-07-28"];
|
||||
|
||||
/// The legacy (handshake) protocol versions, newest first.
|
||||
pub const LEGACY_VERSIONS: &[&str] = &["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"];
|
||||
|
||||
/// `_meta` key of the request's protocol version.
|
||||
pub const META_PROTOCOL_VERSION: &str = "io.modelcontextprotocol/protocolVersion";
|
||||
|
||||
/// `_meta` key of the client's capabilities.
|
||||
pub const META_CLIENT_CAPABILITIES: &str = "io.modelcontextprotocol/clientCapabilities";
|
||||
|
||||
/// `_meta` key of the server info in results.
|
||||
pub const META_SERVER_INFO: &str = "io.modelcontextprotocol/serverInfo";
|
||||
|
||||
/// Largest message line read from stdin, newline excluded.
|
||||
pub const MAX_LINE_BYTES: usize = 16 * 1024 * 1024;
|
||||
|
||||
/// Counter for temporary screenshot names, unique within the process.
|
||||
static SHOTS: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
/// Control method used to check that a connection is alive.
|
||||
const APP_PING: &str = "app.ping";
|
||||
|
||||
/// Guidance for the model, sent with `initialize` and `server/discover`.
|
||||
pub const INSTRUCTIONS: &str = "Lutra is a PHP IDE. Every action is a command: call list_commands to see them with their params, then execute_command {command, params}. Typical flow: project.open {path}, file.open {path}, buffer.edit {id, baseVersion, edits} with UTF-16 offsets, file.save {id}. read_buffer returns the current text of an open file, screenshot shows the window, get_events returns what changed (pass latest as since next time). app.quit needs confirm: true; only use it when the user asks to close Lutra.";
|
||||
|
||||
/// Every supported version, modern first.
|
||||
fn all_versions() -> Vec<&'static str> {
|
||||
MODERN_VERSIONS
|
||||
.iter()
|
||||
.chain(LEGACY_VERSIONS)
|
||||
.copied()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The server's name and version.
|
||||
fn server_info() -> Value {
|
||||
json!({ "name": "lutra", "title": "Lutra", "version": env!("CARGO_PKG_VERSION") })
|
||||
}
|
||||
|
||||
/// The server's capabilities.
|
||||
fn capabilities() -> Value {
|
||||
json!({ "tools": { "listChanged": false }, "resources": {} })
|
||||
}
|
||||
|
||||
/// A failed request: a JSON-RPC error.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
struct Failure {
|
||||
/// Error code.
|
||||
code: i64,
|
||||
/// Message.
|
||||
message: String,
|
||||
/// Extra data.
|
||||
data: Option<Value>,
|
||||
}
|
||||
|
||||
impl Failure {
|
||||
/// A failure without data.
|
||||
fn new(code: i64, message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
code,
|
||||
message: message.into(),
|
||||
data: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A failure with data.
|
||||
fn with_data(code: i64, message: impl Into<String>, data: Value) -> Self {
|
||||
Self {
|
||||
code,
|
||||
message: message.into(),
|
||||
data: Some(data),
|
||||
}
|
||||
}
|
||||
|
||||
/// Lutra could not answer a resources request.
|
||||
fn from_call(e: &CallError) -> Self {
|
||||
Self::with_data(
|
||||
codes::INTERNAL_ERROR,
|
||||
e.to_string(),
|
||||
json!({ "code": e.code() }),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// The MCP server state for one stdio process.
|
||||
pub struct Server {
|
||||
/// Opens connections to Lutra.
|
||||
connector: Arc<dyn Connector>,
|
||||
/// The request connection, once made.
|
||||
connection: Option<Box<dyn Connection>>,
|
||||
/// Recent events.
|
||||
events: Arc<EventLog>,
|
||||
/// The event pump, started with the first connection.
|
||||
pump: Option<Pump>,
|
||||
/// The legacy version negotiated by `initialize`.
|
||||
legacy: Option<String>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Server {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Server")
|
||||
.field("connected", &self.connection.is_some())
|
||||
.field("legacy", &self.legacy)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl Server {
|
||||
/// A server that reaches Lutra through `connector`.
|
||||
pub fn new(connector: Arc<dyn Connector>) -> Self {
|
||||
Self {
|
||||
connector,
|
||||
connection: None,
|
||||
events: Arc::new(EventLog::default()),
|
||||
pump: None,
|
||||
legacy: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads messages from `input` until it ends and writes the responses
|
||||
/// to `output`, one line each. Blank lines are skipped; a line over
|
||||
/// [`MAX_LINE_BYTES`] or not UTF-8 gets a parse error.
|
||||
///
|
||||
/// # Errors
|
||||
/// Only I/O errors of `input` or `output`.
|
||||
pub fn serve(&mut self, mut input: impl BufRead, mut output: impl Write) -> io::Result<()> {
|
||||
let mut line = Vec::new();
|
||||
loop {
|
||||
line.clear();
|
||||
let limit = u64::try_from(MAX_LINE_BYTES)
|
||||
.unwrap_or(u64::MAX)
|
||||
.saturating_add(1);
|
||||
let read = io::Read::take(input.by_ref(), limit).read_until(b'\n', &mut line)?;
|
||||
if read == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
let response = if line.last() != Some(&b'\n') && line.len() > MAX_LINE_BYTES {
|
||||
skip_line(&mut input)?;
|
||||
Some(jsonrpc::error(
|
||||
&Value::Null,
|
||||
codes::PARSE_ERROR,
|
||||
&format!("a message is longer than {MAX_LINE_BYTES} bytes"),
|
||||
None,
|
||||
))
|
||||
} else {
|
||||
match std::str::from_utf8(&line) {
|
||||
Ok(text) if text.trim().is_empty() => None,
|
||||
Ok(text) => self.handle_line(text.trim()),
|
||||
Err(_) => Some(jsonrpc::error(
|
||||
&Value::Null,
|
||||
codes::PARSE_ERROR,
|
||||
"a message is not UTF-8",
|
||||
None,
|
||||
)),
|
||||
}
|
||||
};
|
||||
if let Some(response) = response {
|
||||
output.write_all(response.as_bytes())?;
|
||||
output.write_all(b"\n")?;
|
||||
output.flush()?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Answers one message line.
|
||||
///
|
||||
/// # Returns
|
||||
/// The response line, or `None` for a notification or a response.
|
||||
pub fn handle_line(&mut self, line: &str) -> Option<String> {
|
||||
let (id, method, params) = match jsonrpc::parse(line) {
|
||||
Ok(Incoming::Request { id, method, params }) => (id, method, params),
|
||||
Ok(Incoming::Notification { .. } | Incoming::Response) => return None,
|
||||
Err(response) => return Some(response),
|
||||
};
|
||||
let outcome = guard::run(|| Ok(self.handle_request(&method, ¶ms)));
|
||||
Some(match outcome {
|
||||
Ok(Ok(result)) => jsonrpc::result(&id, result),
|
||||
Ok(Err(failure)) => jsonrpc::error(&id, failure.code, &failure.message, failure.data),
|
||||
Err(panic) => jsonrpc::error(&id, codes::INTERNAL_ERROR, &panic.to_string(), None),
|
||||
})
|
||||
}
|
||||
|
||||
/// Checks the protocol metadata, runs the method and shapes the
|
||||
/// result for the era of the request.
|
||||
fn handle_request(
|
||||
&mut self,
|
||||
method: &str,
|
||||
params: &Map<String, Value>,
|
||||
) -> Result<Value, Failure> {
|
||||
let modern = modern_request(params)?;
|
||||
let mut result = match method {
|
||||
"server/discover" => Ok(json!({
|
||||
"supportedVersions": all_versions(),
|
||||
"capabilities": capabilities(),
|
||||
"instructions": INSTRUCTIONS,
|
||||
})),
|
||||
"initialize" => Ok(self.initialize(params)),
|
||||
"ping" => Ok(json!({})),
|
||||
"tools/list" => Ok(json!({ "tools": tools::definitions() })),
|
||||
"tools/call" => self.call_tool(params),
|
||||
"resources/list" => self.list_resources(),
|
||||
"resources/read" => self.read_resource(params),
|
||||
"resources/templates/list" => Ok(json!({ "resourceTemplates": [] })),
|
||||
other => Err(Failure::new(
|
||||
codes::METHOD_NOT_FOUND,
|
||||
format!("method not found: {other}"),
|
||||
)),
|
||||
}?;
|
||||
if (modern || method == "server/discover")
|
||||
&& let Some(object) = result.as_object_mut()
|
||||
{
|
||||
object.insert("resultType".into(), json!("complete"));
|
||||
object.insert("_meta".into(), json!({ META_SERVER_INFO: server_info() }));
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// `initialize` (legacy): picks the version and describes the server.
|
||||
fn initialize(&mut self, params: &Map<String, Value>) -> Value {
|
||||
let requested = params.get("protocolVersion").and_then(Value::as_str);
|
||||
let version = requested
|
||||
.and_then(|v| LEGACY_VERSIONS.iter().find(|known| **known == v))
|
||||
.or(LEGACY_VERSIONS.first())
|
||||
.copied()
|
||||
.unwrap_or_default();
|
||||
self.legacy = Some(version.to_string());
|
||||
json!({
|
||||
"protocolVersion": version,
|
||||
"capabilities": capabilities(),
|
||||
"serverInfo": server_info(),
|
||||
"instructions": INSTRUCTIONS,
|
||||
})
|
||||
}
|
||||
|
||||
/// `tools/call`.
|
||||
fn call_tool(&mut self, params: &Map<String, Value>) -> Result<Value, Failure> {
|
||||
let name = params
|
||||
.get("name")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| Failure::new(codes::INVALID_PARAMS, "tools/call needs a name"))?;
|
||||
if !tools::exists(name) {
|
||||
return Err(Failure::new(
|
||||
codes::INVALID_PARAMS,
|
||||
format!("Unknown tool: {name}"),
|
||||
));
|
||||
}
|
||||
let empty = Map::new();
|
||||
let args = match params.get("arguments") {
|
||||
None | Some(Value::Null) => &empty,
|
||||
Some(Value::Object(args)) => args,
|
||||
Some(_) => {
|
||||
return Err(Failure::new(
|
||||
codes::INVALID_PARAMS,
|
||||
"arguments must be an object",
|
||||
));
|
||||
}
|
||||
};
|
||||
Ok(tools::call(self, name, args))
|
||||
}
|
||||
|
||||
/// `resources/list`: one resource per open buffer.
|
||||
fn list_resources(&mut self) -> Result<Value, Failure> {
|
||||
let buffers = tools::open_buffers(self).map_err(|e| Failure::from_call(&e))?;
|
||||
let resources: Vec<Value> = buffers
|
||||
.iter()
|
||||
.map(|b| {
|
||||
let mut resource = json!({
|
||||
"uri": buffer_uri(&b.path),
|
||||
"name": b.path,
|
||||
"mimeType": mime_type(&b.path),
|
||||
});
|
||||
if b.dirty
|
||||
&& let Some(object) = resource.as_object_mut()
|
||||
{
|
||||
object.insert(
|
||||
"description".into(),
|
||||
json!("Open buffer with unsaved changes"),
|
||||
);
|
||||
}
|
||||
resource
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({ "resources": resources }))
|
||||
}
|
||||
|
||||
/// `resources/read`: the current text of an open buffer.
|
||||
fn read_resource(&mut self, params: &Map<String, Value>) -> Result<Value, Failure> {
|
||||
let uri = params
|
||||
.get("uri")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| Failure::new(codes::INVALID_PARAMS, "resources/read needs a uri"))?;
|
||||
let not_found = || {
|
||||
Failure::with_data(
|
||||
codes::INVALID_PARAMS,
|
||||
"Resource not found",
|
||||
json!({ "uri": uri }),
|
||||
)
|
||||
};
|
||||
let path = buffer_path(uri).ok_or_else(not_found)?;
|
||||
let buffers = tools::open_buffers(self).map_err(|e| Failure::from_call(&e))?;
|
||||
let id = buffers
|
||||
.iter()
|
||||
.find(|b| b.path == path)
|
||||
.map(|b| b.id)
|
||||
.ok_or_else(not_found)?;
|
||||
let buffer = match tools::buffer_text(self, id) {
|
||||
Ok(buffer) => buffer,
|
||||
Err(CallError::Remote { .. }) => return Err(not_found()),
|
||||
Err(e) => return Err(Failure::from_call(&e)),
|
||||
};
|
||||
let text = buffer
|
||||
.get("text")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default();
|
||||
Ok(json!({
|
||||
"contents": [{ "uri": uri, "mimeType": mime_type(&path), "text": text }]
|
||||
}))
|
||||
}
|
||||
|
||||
/// The request connection, made (and Lutra started) if there is none
|
||||
/// or the old one no longer answers a ping. Starts the event pump with
|
||||
/// the first connection.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`CallError::Lost`] if Lutra cannot be reached.
|
||||
fn connection(&mut self) -> Result<&mut Box<dyn Connection>, CallError> {
|
||||
let alive = match self.connection.as_mut() {
|
||||
Some(connection) => connection.request(APP_PING, Value::Null).is_ok(),
|
||||
None => false,
|
||||
};
|
||||
if !alive {
|
||||
self.connection = None;
|
||||
let connection = self.connector.connect(true).map_err(CallError::Lost)?;
|
||||
self.connection = Some(connection);
|
||||
}
|
||||
if self.pump.is_none() {
|
||||
self.pump = events::start(self.connector.clone(), self.events.clone()).ok();
|
||||
}
|
||||
self.connection
|
||||
.as_mut()
|
||||
.ok_or_else(|| CallError::Lost("no connection to Lutra".into()))
|
||||
}
|
||||
}
|
||||
|
||||
impl Host for Server {
|
||||
fn call(&mut self, method: &str, params: Value) -> Result<Value, CallError> {
|
||||
let result = self.connection()?.request(method, params);
|
||||
if matches!(result, Err(CallError::Lost(_))) {
|
||||
self.connection = None;
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn events(&mut self) -> Result<&EventLog, CallError> {
|
||||
self.connection()?;
|
||||
Ok(&self.events)
|
||||
}
|
||||
|
||||
fn temp_png(&mut self) -> PathBuf {
|
||||
let shot = SHOTS.fetch_add(1, Ordering::Relaxed);
|
||||
std::env::temp_dir().join(format!("lutra-mcp-{}-{shot}.png", std::process::id()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a request uses the modern protocol, judged by its `_meta`.
|
||||
///
|
||||
/// # Errors
|
||||
/// `UnsupportedProtocolVersion` for a version the server does not serve
|
||||
/// per request, invalid params for a malformed version or missing client
|
||||
/// capabilities.
|
||||
fn modern_request(params: &Map<String, Value>) -> Result<bool, Failure> {
|
||||
let Some(meta) = params.get("_meta").and_then(Value::as_object) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let Some(version) = meta.get(META_PROTOCOL_VERSION) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let Some(version) = version.as_str() else {
|
||||
return Err(Failure::new(
|
||||
codes::INVALID_PARAMS,
|
||||
format!("{META_PROTOCOL_VERSION} must be a string"),
|
||||
));
|
||||
};
|
||||
if !MODERN_VERSIONS.contains(&version) {
|
||||
return Err(Failure::with_data(
|
||||
codes::UNSUPPORTED_PROTOCOL_VERSION,
|
||||
"Unsupported protocol version",
|
||||
json!({ "supported": all_versions(), "requested": version }),
|
||||
));
|
||||
}
|
||||
if !meta
|
||||
.get(META_CLIENT_CAPABILITIES)
|
||||
.is_some_and(Value::is_object)
|
||||
{
|
||||
return Err(Failure::new(
|
||||
codes::INVALID_PARAMS,
|
||||
format!("_meta needs {META_CLIENT_CAPABILITIES}"),
|
||||
));
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// The MIME type of a buffer from its file extension.
|
||||
pub fn mime_type(path: &str) -> &'static str {
|
||||
let extension = path
|
||||
.rsplit_once('.')
|
||||
.map(|(_, ext)| ext.to_ascii_lowercase())
|
||||
.unwrap_or_default();
|
||||
match extension.as_str() {
|
||||
"php" | "phtml" | "inc" => "text/x-php",
|
||||
"json" => "application/json",
|
||||
"md" => "text/markdown",
|
||||
"js" | "mjs" | "cjs" => "text/javascript",
|
||||
"ts" => "text/x-typescript",
|
||||
"html" | "htm" => "text/html",
|
||||
"css" => "text/css",
|
||||
"xml" => "application/xml",
|
||||
"yml" | "yaml" => "application/yaml",
|
||||
_ => "text/plain",
|
||||
}
|
||||
}
|
||||
|
||||
/// Discards the rest of an overlong line, up to and including its
|
||||
/// newline.
|
||||
///
|
||||
/// # Errors
|
||||
/// Read errors.
|
||||
fn skip_line(input: &mut impl BufRead) -> io::Result<()> {
|
||||
loop {
|
||||
let available = input.fill_buf()?;
|
||||
if available.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(end) = available.iter().position(|b| *b == b'\n') {
|
||||
input.consume(end.saturating_add(1));
|
||||
return Ok(());
|
||||
}
|
||||
let len = available.len();
|
||||
input.consume(len);
|
||||
}
|
||||
}
|
||||
595
crates/mcp/src/tools.rs
Normal file
595
crates/mcp/src/tools.rs
Normal file
|
|
@ -0,0 +1,595 @@
|
|||
//! The MCP tools (D16): generic access to every command plus a few
|
||||
//! helpers agents need.
|
||||
//!
|
||||
//! - `list_commands {filter?, enabledOnly?}`: the command registry with
|
||||
//! params docs and enabled state (engine and UI commands).
|
||||
//! - `execute_command {command, params?, confirm?}`: runs any command;
|
||||
//! `app.quit` is refused unless `confirm` is `true`.
|
||||
//! - `screenshot {path?}`: a PNG of the main window as image content.
|
||||
//! - `read_buffer {path | id}`: the text of an open buffer, unsaved
|
||||
//! changes included.
|
||||
//! - `get_events {since?, max?, kinds?, waitMs?}`: recent engine events.
|
||||
//!
|
||||
//! Arguments are untrusted and checked here; a bad argument, an engine
|
||||
//! error or an unreachable Lutra is a tool error (`isError: true`) whose
|
||||
//! text starts with the stable code, so the model can correct itself.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::encoding::base64;
|
||||
use crate::events::{CAPACITY, EventLog};
|
||||
use crate::remote::CallError;
|
||||
|
||||
/// Control method that runs an engine command.
|
||||
pub const ENGINE_EXECUTE: &str = "engine.execute";
|
||||
/// Control method that lists the commands.
|
||||
pub const ENGINE_LIST_COMMANDS: &str = "engine.listCommands";
|
||||
/// Control method that writes a screenshot.
|
||||
pub const UI_SCREENSHOT: &str = "ui.screenshot";
|
||||
|
||||
/// The command that needs `confirm: true`.
|
||||
pub const QUIT_COMMAND: &str = "app.quit";
|
||||
|
||||
/// Largest screenshot read back, in bytes.
|
||||
pub const MAX_IMAGE_BYTES: u64 = 32 * 1024 * 1024;
|
||||
|
||||
/// Most text `read_buffer` returns, in bytes; longer texts are cut at a
|
||||
/// character boundary and marked `truncated`.
|
||||
pub const MAX_TEXT_BYTES: usize = 4 * 1024 * 1024;
|
||||
|
||||
/// Default and largest `max` of `get_events`.
|
||||
const DEFAULT_EVENTS: u64 = 100;
|
||||
|
||||
/// Largest `waitMs` of `get_events`.
|
||||
const MAX_WAIT_MS: u64 = 30_000;
|
||||
|
||||
/// Most `kinds` in one `get_events` call.
|
||||
const MAX_KINDS: usize = 64;
|
||||
|
||||
/// Tool error code for bad arguments.
|
||||
const INVALID_ARGUMENTS: &str = "invalid_params";
|
||||
|
||||
/// What a tool needs from the server.
|
||||
pub trait Host {
|
||||
/// Sends a control request to Lutra, connecting (and starting Lutra)
|
||||
/// if needed.
|
||||
///
|
||||
/// # Errors
|
||||
/// The remote error or the connection failure.
|
||||
fn call(&mut self, method: &str, params: Value) -> Result<Value, CallError>;
|
||||
|
||||
/// The event buffer, after making sure the event pump runs.
|
||||
///
|
||||
/// # Errors
|
||||
/// If Lutra cannot be reached.
|
||||
fn events(&mut self) -> Result<&EventLog, CallError>;
|
||||
|
||||
/// A fresh temporary path for a screenshot.
|
||||
fn temp_png(&mut self) -> PathBuf;
|
||||
}
|
||||
|
||||
/// A tool failure the model can act on.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ToolError {
|
||||
/// Stable code: an engine or control code, `invalid_params`,
|
||||
/// `confirmation_required`, `not_open` or `unavailable`.
|
||||
pub code: String,
|
||||
/// Message.
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl ToolError {
|
||||
/// A tool error.
|
||||
fn new(code: &str, message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
code: code.to_string(),
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A bad-arguments error.
|
||||
fn arguments(message: impl Into<String>) -> Self {
|
||||
Self::new(INVALID_ARGUMENTS, message)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<CallError> for ToolError {
|
||||
fn from(e: CallError) -> Self {
|
||||
Self::new(e.code(), e.message())
|
||||
}
|
||||
}
|
||||
|
||||
/// The tool definitions for `tools/list`, in a fixed order.
|
||||
pub fn definitions() -> Vec<Value> {
|
||||
vec![
|
||||
json!({
|
||||
"name": "list_commands",
|
||||
"title": "List Lutra commands",
|
||||
"description": "Lists every Lutra command (engine and UI commands) with its id, label, menu path, default shortcut, params documentation and whether it is enabled right now. Run them with execute_command.",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"filter": { "type": "string", "description": "Only commands whose id or label contains this text (case-insensitive)" },
|
||||
"enabledOnly": { "type": "boolean", "description": "Only commands that can run right now" }
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"annotations": { "readOnlyHint": true, "openWorldHint": false }
|
||||
}),
|
||||
json!({
|
||||
"name": "execute_command",
|
||||
"title": "Run a Lutra command",
|
||||
"description": "Runs a Lutra command by id with its params object, exactly as a menu, shortcut or the command palette would, and returns its result. Examples: project.open {path}, file.open {path}, buffer.edit {id, baseVersion, edits}, file.save {id}, search.find {query}. UI commands (tool windows, panels, editor.reveal) work while the window is open. Errors carry the engine's code (unknown_command, disabled, invalid_params, stale_version, unsaved_changes, failed). app.quit is refused unless confirm is true.",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"command": { "type": "string", "description": "Command id, e.g. file.open" },
|
||||
"params": { "type": "object", "description": "The command's params as documented by list_commands; omit for none" },
|
||||
"confirm": { "type": "boolean", "description": "Must be true to run app.quit, which closes Lutra" }
|
||||
},
|
||||
"required": ["command"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"annotations": { "destructiveHint": true, "openWorldHint": false }
|
||||
}),
|
||||
json!({
|
||||
"name": "screenshot",
|
||||
"title": "Screenshot of Lutra",
|
||||
"description": "Captures the Lutra main window as a PNG image. With path, the PNG is also kept at that path.",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"path": { "type": "string", "description": "Where to keep the PNG (optional)" }
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"annotations": { "readOnlyHint": true, "openWorldHint": false }
|
||||
}),
|
||||
json!({
|
||||
"name": "read_buffer",
|
||||
"title": "Read an open buffer",
|
||||
"description": "Returns the current text of a file open in Lutra, including unsaved changes, with its buffer id, version (for buffer.edit's baseVersion), dirty flag and line ending. Name it by project-relative path or by buffer id. Texts over 4 MiB are cut and marked truncated.",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"path": { "type": "string", "description": "Project-relative path (an absolute path inside the project works too)" },
|
||||
"id": { "type": "integer", "minimum": 0, "description": "Buffer id" }
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"annotations": { "readOnlyHint": true, "openWorldHint": false }
|
||||
}),
|
||||
json!({
|
||||
"name": "get_events",
|
||||
"title": "Recent Lutra events",
|
||||
"description": "Returns engine events (bufferOpened, bufferChanged, dirtyChanged, notification, searchResults, indexReady, uiCommand, …) received since this MCP server first connected, numbered by seq. Pass the returned latest as since on the next call to get only newer events; missed is true if events after since were lost. The last 1000 events are kept.",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"since": { "type": "integer", "minimum": 0, "description": "Only events with a larger seq (default 0)" },
|
||||
"max": { "type": "integer", "minimum": 1, "maximum": 1000, "description": "Most events to return (default 100)" },
|
||||
"kinds": { "type": "array", "items": { "type": "string" }, "description": "Only these event kinds" },
|
||||
"waitMs": { "type": "integer", "minimum": 0, "maximum": 30000, "description": "If no event matches yet, wait up to this long for one (default 0)" }
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"annotations": { "readOnlyHint": true, "openWorldHint": false }
|
||||
}),
|
||||
]
|
||||
}
|
||||
|
||||
/// Whether `name` is a tool.
|
||||
pub fn exists(name: &str) -> bool {
|
||||
matches!(
|
||||
name,
|
||||
"list_commands" | "execute_command" | "screenshot" | "read_buffer" | "get_events"
|
||||
)
|
||||
}
|
||||
|
||||
/// Runs tool `name` and builds its `tools/call` result. Unknown names
|
||||
/// must be rejected by the caller with [`exists`] first.
|
||||
pub fn call(host: &mut dyn Host, name: &str, args: &Map<String, Value>) -> Value {
|
||||
let outcome = match name {
|
||||
"list_commands" => list_commands(host, args),
|
||||
"execute_command" => execute_command(host, args),
|
||||
"screenshot" => screenshot(host, args),
|
||||
"read_buffer" => read_buffer(host, args),
|
||||
"get_events" => get_events(host, args),
|
||||
other => Err(ToolError::new("unknown_tool", format!("no tool {other}"))),
|
||||
};
|
||||
match outcome {
|
||||
Ok(result) => result,
|
||||
Err(e) => json!({
|
||||
"content": [{ "type": "text", "text": format!("{}: {}", e.code, e.message) }],
|
||||
"structuredContent": { "error": { "code": e.code, "message": e.message } },
|
||||
"isError": true
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// A successful result with `structured` also given as JSON text.
|
||||
fn structured(structured: Value) -> Value {
|
||||
let text = serde_json::to_string(&structured).unwrap_or_default();
|
||||
json!({
|
||||
"content": [{ "type": "text", "text": text }],
|
||||
"structuredContent": structured,
|
||||
"isError": false
|
||||
})
|
||||
}
|
||||
|
||||
/// Fails on argument names outside `allowed`.
|
||||
fn only(args: &Map<String, Value>, allowed: &[&str]) -> Result<(), ToolError> {
|
||||
match args.keys().find(|k| !allowed.contains(&k.as_str())) {
|
||||
Some(key) => Err(ToolError::arguments(format!(
|
||||
"unknown argument {key}; allowed: {}",
|
||||
allowed.join(", ")
|
||||
))),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// An optional string argument.
|
||||
fn string<'a>(args: &'a Map<String, Value>, key: &str) -> Result<Option<&'a str>, ToolError> {
|
||||
match args.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::String(s)) => Ok(Some(s)),
|
||||
Some(_) => Err(ToolError::arguments(format!("{key} must be a string"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// An optional boolean argument.
|
||||
fn boolean(args: &Map<String, Value>, key: &str) -> Result<Option<bool>, ToolError> {
|
||||
match args.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::Bool(b)) => Ok(Some(*b)),
|
||||
Some(_) => Err(ToolError::arguments(format!("{key} must be a boolean"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// An optional non-negative integer argument no larger than `max`.
|
||||
fn integer(args: &Map<String, Value>, key: &str, max: u64) -> Result<Option<u64>, ToolError> {
|
||||
match args.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(value) => match value.as_u64() {
|
||||
Some(n) if n <= max => Ok(Some(n)),
|
||||
_ => Err(ToolError::arguments(format!(
|
||||
"{key} must be an integer from 0 to {max}"
|
||||
))),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// `list_commands`.
|
||||
fn list_commands(host: &mut dyn Host, args: &Map<String, Value>) -> Result<Value, ToolError> {
|
||||
only(args, &["filter", "enabledOnly"])?;
|
||||
let filter = string(args, "filter")?.map(str::to_lowercase);
|
||||
let enabled_only = boolean(args, "enabledOnly")?.unwrap_or(false);
|
||||
let list = host.call(ENGINE_LIST_COMMANDS, Value::Null)?;
|
||||
let Value::Array(list) = list else {
|
||||
return Err(ToolError::new(
|
||||
"failed",
|
||||
"engine.listCommands did not return a list",
|
||||
));
|
||||
};
|
||||
let field = |command: &Value, key: &str| {
|
||||
command
|
||||
.get(key)
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default()
|
||||
.to_lowercase()
|
||||
};
|
||||
let commands: Vec<Value> = list
|
||||
.into_iter()
|
||||
.filter(|command| {
|
||||
filter.as_deref().is_none_or(|filter| {
|
||||
field(command, "id").contains(filter) || field(command, "label").contains(filter)
|
||||
})
|
||||
})
|
||||
.filter(|command| {
|
||||
!enabled_only || command.get("enabled").and_then(Value::as_bool) == Some(true)
|
||||
})
|
||||
.collect();
|
||||
Ok(structured(json!({ "commands": commands })))
|
||||
}
|
||||
|
||||
/// `execute_command`.
|
||||
fn execute_command(host: &mut dyn Host, args: &Map<String, Value>) -> Result<Value, ToolError> {
|
||||
only(args, &["command", "params", "confirm"])?;
|
||||
let command = string(args, "command")?
|
||||
.filter(|c| !c.is_empty())
|
||||
.ok_or_else(|| ToolError::arguments("command is required"))?;
|
||||
let params = match args.get("params") {
|
||||
None | Some(Value::Null) => Value::Null,
|
||||
Some(params @ Value::Object(_)) => params.clone(),
|
||||
Some(_) => return Err(ToolError::arguments("params must be an object")),
|
||||
};
|
||||
let confirm = boolean(args, "confirm")?.unwrap_or(false);
|
||||
if command == QUIT_COMMAND && !confirm {
|
||||
return Err(ToolError::new(
|
||||
"confirmation_required",
|
||||
"app.quit closes Lutra; call it again with confirm: true if the user wants that",
|
||||
));
|
||||
}
|
||||
let result = host.call(
|
||||
ENGINE_EXECUTE,
|
||||
json!({ "command": command, "params": params }),
|
||||
)?;
|
||||
Ok(structured(json!({ "result": result })))
|
||||
}
|
||||
|
||||
/// `screenshot`.
|
||||
fn screenshot(host: &mut dyn Host, args: &Map<String, Value>) -> Result<Value, ToolError> {
|
||||
only(args, &["path"])?;
|
||||
let kept = match string(args, "path")? {
|
||||
Some("") => return Err(ToolError::arguments("path must not be empty")),
|
||||
Some(path) => Some(
|
||||
std::path::absolute(path)
|
||||
.map_err(|e| ToolError::arguments(format!("bad path {path}: {e}")))?,
|
||||
),
|
||||
None => None,
|
||||
};
|
||||
let path = kept.clone().unwrap_or_else(|| host.temp_png());
|
||||
let shot = host
|
||||
.call(UI_SCREENSHOT, json!({ "path": path }))
|
||||
.map_err(ToolError::from)
|
||||
.and_then(|_| read_png(&path));
|
||||
if kept.is_none() {
|
||||
remove_temp(&path);
|
||||
}
|
||||
let png = shot?;
|
||||
let mut content =
|
||||
vec![json!({ "type": "image", "data": base64(&png), "mimeType": "image/png" })];
|
||||
if let Some(kept) = &kept {
|
||||
content.push(json!({ "type": "text", "text": format!("Saved to {}", kept.display()) }));
|
||||
}
|
||||
Ok(json!({ "content": content, "isError": false }))
|
||||
}
|
||||
|
||||
/// Deletes a temporary screenshot. A failure only leaves a file in the
|
||||
/// temporary folder, which the system cleans, so it is ignored.
|
||||
fn remove_temp(path: &Path) {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
|
||||
/// Reads a PNG written by Lutra, capped at [`MAX_IMAGE_BYTES`].
|
||||
///
|
||||
/// # Errors
|
||||
/// `screenshot_failed` if it cannot be read, is too large or is not a PNG.
|
||||
fn read_png(path: &Path) -> Result<Vec<u8>, ToolError> {
|
||||
use std::io::Read;
|
||||
let failed = |why: String| ToolError::new("screenshot_failed", why);
|
||||
let file = std::fs::File::open(path)
|
||||
.map_err(|e| failed(format!("cannot read {}: {e}", path.display())))?;
|
||||
let mut bytes = Vec::new();
|
||||
file.take(MAX_IMAGE_BYTES + 1)
|
||||
.read_to_end(&mut bytes)
|
||||
.map_err(|e| failed(format!("cannot read {}: {e}", path.display())))?;
|
||||
if bytes.len() as u64 > MAX_IMAGE_BYTES {
|
||||
return Err(failed(format!(
|
||||
"the screenshot is larger than {MAX_IMAGE_BYTES} bytes"
|
||||
)));
|
||||
}
|
||||
if !bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
|
||||
return Err(failed("the screenshot is not a PNG".into()));
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// One entry of `buffer.list`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct OpenBuffer {
|
||||
/// Buffer id.
|
||||
pub id: u64,
|
||||
/// Project-relative path with `/` separators.
|
||||
pub path: String,
|
||||
/// Whether it has unsaved changes.
|
||||
pub dirty: bool,
|
||||
}
|
||||
|
||||
/// The open buffers (`buffer.list`); entries without an id or a path are
|
||||
/// skipped.
|
||||
///
|
||||
/// # Errors
|
||||
/// The call's error.
|
||||
pub fn open_buffers(host: &mut dyn Host) -> Result<Vec<OpenBuffer>, CallError> {
|
||||
let list = host.call(
|
||||
ENGINE_EXECUTE,
|
||||
json!({ "command": "buffer.list", "params": null }),
|
||||
)?;
|
||||
let entries = list.as_array().map(Vec::as_slice).unwrap_or_default();
|
||||
Ok(entries
|
||||
.iter()
|
||||
.filter_map(|entry| {
|
||||
Some(OpenBuffer {
|
||||
id: entry.get("id")?.as_u64()?,
|
||||
path: entry.get("path")?.as_str()?.to_string(),
|
||||
dirty: entry.get("dirty").and_then(Value::as_bool).unwrap_or(false),
|
||||
})
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Finds the buffer for `wanted`: the same project-relative path
|
||||
/// (backslashes count as slashes, a leading `./` is ignored), or else the
|
||||
/// longest buffer path that `wanted` ends with after a `/` (an absolute
|
||||
/// path inside the project).
|
||||
pub fn find_buffer<'a>(buffers: &'a [OpenBuffer], wanted: &str) -> Option<&'a OpenBuffer> {
|
||||
let normal = wanted.replace('\\', "/");
|
||||
let normal = normal.strip_prefix("./").unwrap_or(&normal);
|
||||
buffers.iter().find(|b| b.path == normal).or_else(|| {
|
||||
buffers
|
||||
.iter()
|
||||
.filter(|b| {
|
||||
normal
|
||||
.strip_suffix(b.path.as_str())
|
||||
.is_some_and(|head| head.ends_with('/'))
|
||||
})
|
||||
.max_by_key(|b| b.path.len())
|
||||
})
|
||||
}
|
||||
|
||||
/// The text of a buffer (`buffer.get`).
|
||||
///
|
||||
/// # Errors
|
||||
/// The call's error.
|
||||
pub fn buffer_text(host: &mut dyn Host, id: u64) -> Result<Value, CallError> {
|
||||
host.call(
|
||||
ENGINE_EXECUTE,
|
||||
json!({ "command": "buffer.get", "params": { "id": id } }),
|
||||
)
|
||||
}
|
||||
|
||||
/// `read_buffer`.
|
||||
fn read_buffer(host: &mut dyn Host, args: &Map<String, Value>) -> Result<Value, ToolError> {
|
||||
only(args, &["path", "id"])?;
|
||||
let path = string(args, "path")?;
|
||||
let id = integer(args, "id", u64::MAX)?;
|
||||
let id = match (path, id) {
|
||||
(Some(_), Some(_)) | (None, None) => {
|
||||
return Err(ToolError::arguments("give either path or id"));
|
||||
}
|
||||
(None, Some(id)) => id,
|
||||
(Some(path), None) => {
|
||||
let buffers = open_buffers(host)?;
|
||||
find_buffer(&buffers, path).map(|b| b.id).ok_or_else(|| {
|
||||
ToolError::new(
|
||||
"not_open",
|
||||
format!(
|
||||
"{path} is not open in Lutra; open it with execute_command file.open {{path}}"
|
||||
),
|
||||
)
|
||||
})?
|
||||
}
|
||||
};
|
||||
let buffer = buffer_text(host, id)?;
|
||||
let text = buffer
|
||||
.get("text")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default();
|
||||
let (text, truncated) = cut(text, MAX_TEXT_BYTES);
|
||||
let meta = json!({
|
||||
"id": buffer.get("id"),
|
||||
"path": buffer.get("path"),
|
||||
"version": buffer.get("version"),
|
||||
"dirty": buffer.get("dirty"),
|
||||
"lineEnding": buffer.get("lineEnding"),
|
||||
"truncated": truncated,
|
||||
});
|
||||
Ok(json!({
|
||||
"content": [
|
||||
{ "type": "text", "text": serde_json::to_string(&meta).unwrap_or_default() },
|
||||
{ "type": "text", "text": text }
|
||||
],
|
||||
"structuredContent": meta,
|
||||
"isError": false
|
||||
}))
|
||||
}
|
||||
|
||||
/// `text` cut to at most `max` bytes at a character boundary, and whether
|
||||
/// it was cut.
|
||||
pub fn cut(text: &str, max: usize) -> (&str, bool) {
|
||||
if text.len() <= max {
|
||||
return (text, false);
|
||||
}
|
||||
let mut end = max;
|
||||
while end > 0 && !text.is_char_boundary(end) {
|
||||
end -= 1;
|
||||
}
|
||||
(text.get(..end).unwrap_or_default(), true)
|
||||
}
|
||||
|
||||
/// `get_events`.
|
||||
fn get_events(host: &mut dyn Host, args: &Map<String, Value>) -> Result<Value, ToolError> {
|
||||
only(args, &["since", "max", "kinds", "waitMs"])?;
|
||||
let since = integer(args, "since", u64::MAX)?.unwrap_or(0);
|
||||
let max = integer(args, "max", CAPACITY as u64)?.unwrap_or(DEFAULT_EVENTS);
|
||||
if max == 0 {
|
||||
return Err(ToolError::arguments("max must be at least 1"));
|
||||
}
|
||||
let wait = integer(args, "waitMs", MAX_WAIT_MS)?.unwrap_or(0);
|
||||
let kinds = match args.get("kinds") {
|
||||
None | Some(Value::Null) => Vec::new(),
|
||||
Some(Value::Array(kinds)) if kinds.len() <= MAX_KINDS => kinds
|
||||
.iter()
|
||||
.map(|k| k.as_str().map(str::to_string))
|
||||
.collect::<Option<Vec<_>>>()
|
||||
.ok_or_else(|| ToolError::arguments("kinds must be strings"))?,
|
||||
Some(_) => {
|
||||
return Err(ToolError::arguments(format!(
|
||||
"kinds must be a list of at most {MAX_KINDS} strings"
|
||||
)));
|
||||
}
|
||||
};
|
||||
let log = host.events()?;
|
||||
let page = log.page(
|
||||
since,
|
||||
usize::try_from(max).unwrap_or(CAPACITY),
|
||||
&kinds,
|
||||
Duration::from_millis(wait),
|
||||
);
|
||||
let events: Vec<Value> = page
|
||||
.events
|
||||
.into_iter()
|
||||
.map(|(seq, event)| json!({ "seq": seq, "event": event }))
|
||||
.collect();
|
||||
Ok(structured(json!({
|
||||
"events": events,
|
||||
"latest": page.latest,
|
||||
"missed": page.missed,
|
||||
"subscribed": page.subscribed,
|
||||
})))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn buffers() -> Vec<OpenBuffer> {
|
||||
["a.php", "src/a.php", "src/sub/a.php"]
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, p)| OpenBuffer {
|
||||
id: i as u64 + 1,
|
||||
path: (*p).into(),
|
||||
dirty: false,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_buffers_by_path() {
|
||||
let b = buffers();
|
||||
let id = |p: &str| find_buffer(&b, p).map(|b| b.id);
|
||||
assert_eq!(id("a.php"), Some(1));
|
||||
assert_eq!(id("./src/a.php"), Some(2));
|
||||
assert_eq!(id(r"src\sub\a.php"), Some(3));
|
||||
assert_eq!(id("/home/me/project/src/sub/a.php"), Some(3));
|
||||
assert_eq!(id(r"C:\p\src\a.php"), Some(2));
|
||||
assert_eq!(id("/p/x.php"), None);
|
||||
assert_eq!(id("xa.php"), None);
|
||||
assert_eq!(id(""), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cuts_at_character_boundaries() {
|
||||
assert_eq!(cut("abc", 5), ("abc", false));
|
||||
assert_eq!(cut("abc", 2), ("ab", true));
|
||||
assert_eq!(cut("aäb", 2), ("a", true));
|
||||
assert_eq!(cut("ä", 1), ("", true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_definition_is_a_tool() {
|
||||
let defs = definitions();
|
||||
assert_eq!(defs.len(), 5);
|
||||
for def in defs {
|
||||
let name = def["name"].as_str().unwrap();
|
||||
assert!(exists(name), "{name}");
|
||||
assert_eq!(def["inputSchema"]["type"], "object");
|
||||
}
|
||||
assert!(!exists("nope"));
|
||||
}
|
||||
}
|
||||
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