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:
danny 2026-10-19 18:20:57 +02:00
parent 51eba0b3cb
commit 0e56c22b66
24 changed files with 3055 additions and 18 deletions

View file

@ -17,6 +17,7 @@ path = "src/main.rs"
[dependencies]
lutra-control.workspace = true
lutra-mcp.workspace = true
serde_json = "1.0.154"
[dev-dependencies]

View file

@ -7,8 +7,11 @@ use std::ffi::OsString;
/// Usage text for `--help`.
pub const USAGE: &str = "usage: lutra [--wait] [PATH[:LINE[:COLUMN]]]...
lutra mcp [--port PORT] [--no-start]
Opens folders and files in the running Lutra, or starts it.
Opens folders and files in the running Lutra, or starts it. `lutra mcp`
serves the Model Context Protocol on stdio for agents (lutra mcp --help);
open a file named mcp as ./mcp.
PATH a folder becomes the project; a file opens in a tab
:LINE[:COLUMN] moves the cursor there (1-based)

View file

@ -2,13 +2,15 @@
//!
//! `lutra [--wait] [PATH[:LINE[:COLUMN]]]...` opens folders and files in
//! the running Lutra, or starts it, through the single-instance rendezvous
//! file (see `lutra_control::rendezvous`). Later milestones add the diff
//! viewer, `lutra mcp`, `lutra perf` and `lutra bench`.
//! file (see `lutra_control::rendezvous`). `lutra mcp` serves the Model
//! Context Protocol on stdio (see [`mcp`]). Later milestones add the diff
//! viewer, `lutra perf` and `lutra bench`.
//!
//! Exit codes: 0 ok, 1 error, 2 bad usage.
mod args;
mod launch;
mod mcp;
mod open;
use std::process::ExitCode;
@ -17,7 +19,11 @@ use crate::open::Failure;
/// Parses the arguments and runs the command.
fn main() -> ExitCode {
let args = match args::parse(std::env::args_os().skip(1)) {
let mut raw = std::env::args_os().skip(1).peekable();
if raw.peek().is_some_and(|first| first == "mcp") {
return run_mcp(raw.skip(1).collect());
}
let args = match args::parse(raw) {
Ok(args) => args,
Err(message) => return usage_error(&message),
};
@ -39,6 +45,40 @@ fn main() -> ExitCode {
}
}
/// Runs `lutra mcp` with the arguments after `mcp`.
fn run_mcp(raw: Vec<std::ffi::OsString>) -> ExitCode {
let args: Result<Vec<String>, _> = raw
.into_iter()
.map(std::ffi::OsString::into_string)
.collect();
let options = match args
.map_err(|arg| format!("argument {arg:?} is not valid Unicode"))
.and_then(|args| mcp::parse(&args))
{
Ok(options) => options,
Err(message) => {
eprintln!(
"lutra: {message}
{}",
mcp::USAGE
);
return ExitCode::from(2);
}
};
if options.help {
println!("{}", mcp::USAGE);
return ExitCode::SUCCESS;
}
match mcp::run(&options) {
Ok(()) => ExitCode::SUCCESS,
Err(Failure::Usage(message) | Failure::Error(message)) => {
eprintln!("lutra: {message}");
ExitCode::FAILURE
}
}
}
/// Prints a usage error and returns exit code 2.
fn usage_error(message: &str) -> ExitCode {
eprintln!("lutra: {message}\n\n{}", args::USAGE);

190
apps/lutra-cli/src/mcp.rs Normal file
View file

@ -0,0 +1,190 @@
//! `lutra mcp [--port PORT] [--no-start]`: the MCP server on stdio.
//!
//! The server itself is `lutra_mcp::Server`; this module connects it to
//! Lutra. By default it reaches the running instance through the
//! single-instance rendezvous file (token-authenticated) and starts Lutra
//! when none runs, exactly as `lutra PATH` does. `--port PORT` uses an
//! open `--control PORT` channel instead (development and live checks),
//! and `--no-start` never starts Lutra.
use std::io;
use std::path::PathBuf;
use std::time::Duration;
use lutra_control::client::{self, Client, ClientError};
use lutra_control::rendezvous;
use lutra_mcp::{CallError, Connection, Connector, Server};
use serde_json::Value;
use crate::launch;
use crate::open::Failure;
/// Usage text of `lutra mcp`.
pub const USAGE: &str = "usage: lutra mcp [--port PORT] [--no-start]
Serves the Model Context Protocol on stdin/stdout for agents, e.g.
claude mcp add lutra -- lutra mcp
--port PORT use the --control PORT channel instead of the running
instance's rendezvous file
--no-start do not start Lutra when it is not running
Tools: list_commands, execute_command, screenshot, read_buffer,
get_events. Resources: the open buffers (lutra://buffer/PATH).";
/// Options of `lutra mcp`.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Options {
/// The `--control` port to use instead of the rendezvous file.
pub port: Option<u16>,
/// Whether Lutra may be started.
pub start: bool,
/// `--help` was given.
pub help: bool,
}
/// Parses the arguments after `mcp`.
///
/// # Errors
/// A message for an unknown argument or a bad port.
pub fn parse(args: &[String]) -> Result<Options, String> {
let mut options = Options {
start: true,
..Options::default()
};
let mut args = args.iter();
while let Some(arg) = args.next() {
match arg.as_str() {
"--port" => {
let port = args.next().ok_or("--port needs a port number")?;
options.port = Some(
port.parse::<u16>()
.ok()
.filter(|p| *p != 0)
.ok_or_else(|| format!("{port} is not a port number"))?,
);
}
"--no-start" => options.start = false,
"--help" | "-h" => options.help = true,
other => return Err(format!("unknown argument {other} for lutra mcp")),
}
}
Ok(options)
}
/// Runs the server on stdin and stdout until stdin closes.
///
/// # Errors
/// [`Failure::Error`] for a missing data directory or an I/O error on
/// stdin or stdout.
pub fn run(options: &Options) -> Result<(), Failure> {
let target = match options.port {
Some(port) => Target::Port(port),
None => Target::Rendezvous(
rendezvous::dir()
.ok_or_else(|| Failure::Error("cannot find the Lutra data directory".into()))?,
),
};
let connector = ControlConnector {
target,
start: options.start,
};
let mut server = Server::new(std::sync::Arc::new(connector));
let stdin = io::stdin().lock();
let stdout = io::stdout().lock();
server
.serve(stdin, stdout)
.map_err(|e| Failure::Error(format!("mcp: {e}")))
}
/// Where Lutra listens.
#[derive(Debug, Clone)]
enum Target {
/// The instance named by the rendezvous file in this directory.
Rendezvous(PathBuf),
/// An open `--control` port.
Port(u16),
}
/// Connects to Lutra through the control channel.
#[derive(Debug)]
struct ControlConnector {
/// Where to connect.
target: Target,
/// Whether a missing Lutra may be started.
start: bool,
}
impl Connector for ControlConnector {
fn connect(&self, start: bool) -> Result<Box<dyn Connection>, String> {
let client = match &self.target {
Target::Port(port) => Client::connect(*port, client::DEFAULT_TIMEOUT)
.map_err(|e| format!("Lutra does not answer on control port {port}: {e}"))?,
Target::Rendezvous(dir) => match client::connect_live(dir, client::DEFAULT_TIMEOUT) {
Ok((_, client)) => client,
Err(why) if start && self.start => {
let desktop = launch::find_desktop()
.map_err(|e| format!("{why}, and it cannot be started: {e}"))?;
launch::start(&desktop, dir)?
}
Err(why) => return Err(why.to_string()),
},
};
Ok(Box::new(ControlConnection { client }))
}
}
/// A control channel client as an MCP connection.
#[derive(Debug)]
struct ControlConnection {
/// The client.
client: Client,
}
/// Maps a client error: an error answer stays remote, anything else means
/// the connection is gone.
fn call_error(error: ClientError) -> CallError {
match error {
ClientError::Remote { code, message } => CallError::Remote { code, message },
other => CallError::Lost(other.to_string()),
}
}
impl Connection for ControlConnection {
fn request(&mut self, method: &str, params: Value) -> Result<Value, CallError> {
self.client.request(method, params).map_err(call_error)
}
fn next_event(&mut self, timeout: Duration) -> Result<Option<Value>, CallError> {
self.client.next_event(Some(timeout)).map_err(call_error)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn p(args: &[&str]) -> Result<Options, String> {
parse(&args.iter().map(|s| (*s).to_string()).collect::<Vec<_>>())
}
#[test]
fn parses_options() {
assert_eq!(
p(&[]).unwrap(),
Options {
port: None,
start: true,
help: false
}
);
let o = p(&["--port", "7938", "--no-start"]).unwrap();
assert_eq!(o.port, Some(7938));
assert!(!o.start);
assert!(p(&["-h"]).unwrap().help);
assert!(p(&["--port"]).is_err());
assert!(p(&["--port", "0"]).is_err());
assert!(p(&["--port", "70000"]).is_err());
assert!(p(&["file.php"]).is_err());
}
}

167
apps/lutra-cli/tests/mcp.rs Normal file
View file

@ -0,0 +1,167 @@
//! `lutra mcp` end to end: the binary on stdio against a test backend
//! that claims a temporary rendezvous directory.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
use std::io::{BufRead, BufReader, Write};
use std::path::Path;
use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};
use std::sync::Arc;
use lutra_control::rendezvous::{self, Instance};
use lutra_testkit::EngineBackend;
use serde_json::{Value, json};
fn claim(dir: &Path) -> Arc<EngineBackend> {
let backend = Arc::new(EngineBackend::new());
let token = rendezvous::new_token().unwrap();
let server = lutra_control::start_with_token(0, backend.clone(), &token).unwrap();
rendezvous::write(
dir,
&Instance {
port: server.local_addr().port(),
token,
pid: std::process::id(),
version: "test".into(),
},
)
.unwrap();
backend
}
struct Mcp {
child: Child,
stdin: ChildStdin,
stdout: BufReader<ChildStdout>,
}
impl Mcp {
fn start(dir: &Path, args: &[&str]) -> Self {
let mut child = Command::new(env!("CARGO_BIN_EXE_lutra"))
.arg("mcp")
.args(args)
.env(rendezvous::DIR_ENV, dir)
.env("LUTRA_DESKTOP", dir.join("no-such-desktop"))
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.unwrap();
let stdin = child.stdin.take().unwrap();
let stdout = BufReader::new(child.stdout.take().unwrap());
Self {
child,
stdin,
stdout,
}
}
fn send(&mut self, message: Value) {
writeln!(self.stdin, "{message}").unwrap();
self.stdin.flush().unwrap();
}
fn receive(&mut self) -> Value {
let mut line = String::new();
self.stdout.read_line(&mut line).unwrap();
serde_json::from_str(&line).unwrap()
}
fn ask(&mut self, id: u64, method: &str, params: Value) -> Value {
self.send(json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}));
let response = self.receive();
assert_eq!(response["id"], id);
response
}
fn finish(self) -> std::process::ExitStatus {
let Self {
mut child, stdin, ..
} = self;
drop(stdin);
child.wait().unwrap()
}
}
#[test]
fn drives_lutra_over_stdio() {
let dir = tempfile::tempdir().unwrap();
let project = dir.path().join("project");
std::fs::create_dir_all(&project).unwrap();
std::fs::write(project.join("a.php"), "<?php\n").unwrap();
let backend = claim(dir.path());
let mut mcp = Mcp::start(dir.path(), &[]);
let init = mcp.ask(
1,
"initialize",
json!({"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "e2e", "version": "1"}}),
);
assert_eq!(init["result"]["protocolVersion"], "2025-06-18");
mcp.send(json!({"jsonrpc": "2.0", "method": "notifications/initialized"}));
let tools = mcp.ask(2, "tools/list", json!({}));
assert_eq!(tools["result"]["tools"].as_array().unwrap().len(), 5);
let call = |mcp: &mut Mcp, id: u64, name: &str, args: Value| {
let r = mcp.ask(id, "tools/call", json!({"name": name, "arguments": args}));
assert_eq!(r["result"]["isError"], false, "{r}");
r["result"].clone()
};
call(
&mut mcp,
3,
"execute_command",
json!({"command": "project.open", "params": {"path": project}}),
);
call(
&mut mcp,
4,
"execute_command",
json!({"command": "file.open", "params": {"path": "a.php"}}),
);
let read = call(&mut mcp, 5, "read_buffer", json!({"path": "a.php"}));
assert_eq!(read["content"][1]["text"], "<?php\n");
let resources = mcp.ask(6, "resources/list", json!({}));
assert_eq!(
resources["result"]["resources"][0]["uri"],
"lutra://buffer/a.php"
);
assert_eq!(
backend.engine.lock().unwrap().state().buffers.ids().len(),
1
);
assert!(mcp.finish().success(), "stdin closed: clean exit");
}
#[test]
fn reports_a_missing_lutra_as_a_tool_error() {
let dir = tempfile::tempdir().unwrap();
let mut mcp = Mcp::start(dir.path(), &["--no-start"]);
let r = mcp.ask(
1,
"tools/call",
json!({"name": "list_commands", "arguments": {}}),
);
assert_eq!(r["result"]["isError"], true);
assert_eq!(
r["result"]["structuredContent"]["error"]["code"],
"unavailable"
);
assert!(mcp.finish().success());
}
#[test]
fn usage_errors_exit_with_two() {
let out = Command::new(env!("CARGO_BIN_EXE_lutra"))
.args(["mcp", "--bogus"])
.output()
.unwrap();
assert_eq!(out.status.code(), Some(2));
let out = Command::new(env!("CARGO_BIN_EXE_lutra"))
.args(["mcp", "--help"])
.output()
.unwrap();
assert_eq!(out.status.code(), Some(0));
assert!(String::from_utf8_lossy(&out.stdout).contains("claude mcp add"));
}