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

@ -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());
}
}