Lutra/apps/lutra-cli/src/mcp.rs
danny 0e56c22b66 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>
2026-10-20 20:43:12 +02:00

190 lines
6.1 KiB
Rust

//! `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());
}
}