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
9
Cargo.lock
generated
9
Cargo.lock
generated
|
|
@ -2565,6 +2565,7 @@ version = "0.0.0"
|
|||
dependencies = [
|
||||
"lutra-control",
|
||||
"lutra-engine",
|
||||
"lutra-mcp",
|
||||
"lutra-testkit",
|
||||
"proptest",
|
||||
"serde_json",
|
||||
|
|
@ -2649,6 +2650,14 @@ dependencies = [
|
|||
[[package]]
|
||||
name = "lutra-mcp"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"lutra-control",
|
||||
"lutra-engine",
|
||||
"lutra-testkit",
|
||||
"proptest",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lutra-search"
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
**Stage: pre-alpha (M2 done)** · next: M3 language server, terminal, CLI and MCP (the MVP); alpha when the six core workflows work end to end (see [docs/roadmap.md › Alpha gate](docs/roadmap.md#alpha-gate))
|
||||
|
||||
> **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-17 · **Change:** minor (M3.7: `lutra` CLI and single instance) · **Target:** JetBrains PhpStorm 2026.x, described from public documentation only
|
||||
> **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-19 · **Change:** minor (M3.8: MCP server) · **Target:** JetBrains PhpStorm 2026.x, described from public documentation only
|
||||
|
||||
Lutra is a clean-room, open-source PHP IDE with a Rust core and a Tauri + Vue interface, targeting the PhpStorm workflow. Agents can drive all of it over MCP, the `lutra` CLI and a JSON control channel. This page is the summary; the evidence is in [`docs/target-app-parity.md`](docs/target-app-parity.md) and the work list in [`docs/gaps.md`](docs/gaps.md).
|
||||
|
||||
|
|
@ -33,9 +33,9 @@ Dimension hours overlap: language, framework and tooling hours are part of the f
|
|||
| Localization (en, de) | 5% | ~38 | [localization-parity.md](docs/localization-parity.md) |
|
||||
| Performance | 0% | ~100 | [gaps.md › G12](docs/gaps.md) |
|
||||
| Stability | 8% | ~95 | [gaps.md › G11](docs/gaps.md) |
|
||||
| Agent automation | 18% (est.) | ~52 | AGENTS.md |
|
||||
| Agent automation | 26% (est.) | ~44 | AGENTS.md |
|
||||
|
||||
Stability 8%: no-panic lints, the engine guard, a fuzzed control protocol and a crash-recovery journal for unsaved buffers (property-tested: random edits, crash, restore) exist; the journal is not yet checked in the running app. Agent automation 10%: the control channel (ping, execute, listCommands, screenshot) works, and since M1.8 it also reaches the frontend's UI commands (opening the palette, toggling the project tree) through the `uiCommand` event; since M3.7 the `lutra` CLI opens folders and files at a line in the running instance (or starts it), `--wait` blocks until the tabs close (usable as `core.editor`), and a token-protected rendezvous file lets local tools find the instance; MCP does not exist yet. Both are estimated. Localization 5% (estimated): every UI string comes from an English catalog enforced by lint; engine messages, the language switch and German are missing. UI/UX fidelity 1% (estimated): light and dark themes switch live and pass a WCAG AA contrast test; the rest of the ui-parity checklist is open.
|
||||
Stability 8%: no-panic lints, the engine guard, a fuzzed control protocol and a crash-recovery journal for unsaved buffers (property-tested: random edits, crash, restore) exist; the journal is not yet checked in the running app. Agent automation 26%: the control channel (ping, execute, listCommands, screenshot) works, and since M1.8 it also reaches the frontend's UI commands (opening the palette, toggling the project tree) through the `uiCommand` event; since M3.7 the `lutra` CLI opens folders and files at a line in the running instance (or starts it), `--wait` blocks until the tabs close (usable as `core.editor`), and a token-protected rendezvous file lets local tools find the instance; since M3.8 `lutra mcp` gives MCP clients such as Claude Code every command (with params docs and the enabled state), screenshots, the text of open buffers (also as resources) and the recent events, with `app.quit` only on explicit confirmation. Missing: change notifications, progress for long commands, the perf and diff subcommands. Both are estimated. Localization 5% (estimated): every UI string comes from an English catalog enforced by lint; engine messages, the language switch and German are missing. UI/UX fidelity 1% (estimated): light and dark themes switch live and pass a WCAG AA contrast test; the rest of the ui-parity checklist is open.
|
||||
|
||||
## Features
|
||||
|
||||
|
|
@ -75,6 +75,7 @@ All hours estimated. Weights, evidence and the missing items per area: [target-a
|
|||
|
||||
| Date | What landed |
|
||||
|---|---|
|
||||
| 2026-10-19 | M3.8: agents can drive Lutra over MCP: `claude mcp add lutra -- lutra mcp`, then Claude can list and run every command, look at the window, read open files including unsaved changes and follow what happens. Closing Lutra needs an explicit confirmation. |
|
||||
| 2026-10-17 | M3.7: the `lutra` command: `lutra src/Kernel.php:42` opens the file at line 42 in the running Lutra or starts it, `lutra .` opens a folder, `lutra --wait FILE` returns when the tab is closed (for `git commit`). Starting Lutra a second time hands the path to the first window. Only your user account can talk to the running instance. |
|
||||
| 2026-10-17 | M2.6: go to any file, class or symbol by name: `Mod+P`, `Mod+Alt+C` and `Mod+T` open one popup with Files, Classes and Symbols tabs (Tab switches); results update as you type with the matched letters marked, library code is labelled, a hint shows while the index is still building, and Enter jumps there. Agents can open it with a query. |
|
||||
| 2026-10-17 | M2.7: a Structure tool window next to Project (new left stripe, `Mod+2`) shows the classes, functions, methods, properties and constants of the active PHP file as a tree that follows tabs and edits; click or Enter jumps to the declaration. The file is reparsed in the background, so big files never stall typing. |
|
||||
|
|
@ -96,6 +97,7 @@ All hours estimated. Weights, evidence and the missing items per area: [target-a
|
|||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-18 | minor | Feature breadth measured against the full PhpStorm help inventory (155 units); M7–M9 added |
|
||||
| 2026-10-19 | minor | M3.8: MCP server; agent automation 18% → 26% (est.) |
|
||||
| 2026-10-17 | minor | M3.7: `lutra` CLI and single instance; agent automation 10% → 18% (est.) |
|
||||
| 2026-10-17 | minor | Cycle C3 review: M2 done (~6.1 h measured), factor 0.14, MVP ~12 h left |
|
||||
| 2026-10-17 | minor | M2.6: Navigation 4% → 10%, feature depth ~3.2% |
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ path = "src/main.rs"
|
|||
|
||||
[dependencies]
|
||||
lutra-control.workspace = true
|
||||
lutra-mcp.workspace = true
|
||||
serde_json = "1.0.154"
|
||||
|
||||
[dev-dependencies]
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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
190
apps/lutra-cli/src/mcp.rs
Normal 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
167
apps/lutra-cli/tests/mcp.rs
Normal 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"));
|
||||
}
|
||||
|
|
@ -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"
|
||||
);
|
||||
}
|
||||
|
|
@ -1,15 +1,15 @@
|
|||
# Architecture
|
||||
|
||||
> **Status:** M0 decisions recorded, M1 workspace, desktop bridge, tabs and editor, message catalog, engine construction, settings, themes, the recovery journal, notifications, UI commands, the palette, the settings dialog, the app icon and the syntax layer documented; M2 highlighting and `editor.reveal`, plus the search backend, the Find tool window, the symbol index, the Structure tool window and the go-to popup; M3 CLI and single instance, LSP client library, toolchain (PHP detection, Phpactor download), the app menu · **Last updated:** 2026-10-19
|
||||
> **Status:** M0 decisions recorded, M1 workspace, desktop bridge, tabs and editor, message catalog, engine construction, settings, themes, the recovery journal, notifications, UI commands, the palette, the settings dialog, the app icon and the syntax layer documented; M2 highlighting and `editor.reveal`, plus the search backend, the Find tool window, the symbol index, the Structure tool window and the go-to popup; M3 CLI and single instance, LSP client library, toolchain (PHP detection, Phpactor download), the app menu, MCP server · **Last updated:** 2026-10-19
|
||||
|
||||
## Overview
|
||||
|
||||
```
|
||||
apps/lutra-desktop (L6) Tauri 2 shell: windows, menus, IPC bridge to the engine
|
||||
ui/ (L6) Vue 3 + TypeScript + Vite frontend, Pinia, CodeMirror 6
|
||||
apps/lutra-cli (L6) the `lutra` command: open, --wait; later diff, mcp, perf, bench
|
||||
apps/lutra-cli (L6) the `lutra` command: open, --wait, mcp; later diff, perf, bench
|
||||
crates/control (L5) JSON-lines control channel (--control PORT)
|
||||
crates/mcp (L5) MCP server over stdio
|
||||
crates/mcp (L5) MCP server over stdio (the CLI supplies the connection)
|
||||
crates/engine (L4) command registry, workspace state, guard, recovery journal, theme tokens
|
||||
crates/lsp (L3) LSP client (Phpactor first), later DAP client
|
||||
crates/terminal (L3) pseudo-terminal sessions (portable-pty)
|
||||
|
|
@ -78,7 +78,25 @@ As built in M0:
|
|||
- **Starting Lutra:** if no instance answers, the CLI starts the desktop detached (`LUTRA_DESKTOP`, else `lutra-desktop` next to `lutra`, else on `PATH`) and polls the rendezvous file for up to 60 s.
|
||||
- **`--wait`:** subscribes before opening, then blocks until every opened file's `bufferClosed` arrived (or `projectClosed`, or the connection ends because Lutra quit). A `subscriptionLost` renews the subscription and checks the remaining ids with `buffer.get`. Folders are not waited for.
|
||||
- **Exit codes:** 0 ok, 1 error (cannot start, open failed, missing path), 2 bad usage (unknown option, line or column 0 or too big, two folders, a positioned folder, non-Unicode argument). Arguments are untrusted; parsing is property-tested.
|
||||
- **Rendezvous API for M3.8 (`lutra mcp`):** `lutra_control::client::connect_live(&rendezvous::dir()?, timeout)` returns the `Instance` and an authenticated `Client`; `Client::request(method, params)`, `execute(command, params)`, `subscribe()`, `next_event(timeout)` (events read while waiting for a response are queued, at most 4096), `open_folder`, `open_file`, `reveal`, `focus`. To start Lutra when none runs, reuse the CLI's `launch` logic (move it into the client if MCP needs it outside the CLI binary). Response lines are capped at 64 MiB.
|
||||
- **Rendezvous API for M3.8 (`lutra mcp`):** `lutra_control::client::connect_live(&rendezvous::dir()?, timeout)` returns the `Instance` and an authenticated `Client`; `Client::request(method, params)`, `execute(command, params)`, `subscribe()`, `next_event(timeout)` (events read while waiting for a response are queued, at most 4096), `open_folder`, `open_file`, `reveal`, `focus`. Response lines are capped at 64 MiB. `lutra mcp` (M3.8) uses this API from the CLI, so the CLI's `launch` logic stayed in the CLI.
|
||||
|
||||
### MCP server (M3.8)
|
||||
|
||||
- **Shape:** `crates/mcp` (L5) holds the protocol, the tools and the event buffer but opens no sockets and starts no processes; it reaches Lutra through the `lutra_mcp::Connector` / `Connection` traits (`request(method, params)`, `next_event(timeout)`). `lutra mcp` in `apps/lutra-cli` (L6) implements them with `lutra_control::client`: the rendezvous file and token by default (starting Lutra like `lutra PATH` when none runs), `--port PORT` for an open `--control` channel, `--no-start` to never start Lutra. Register it with `claude mcp add lutra -- lutra mcp`. No SDK: the official Rust SDK brings an async runtime and schema generators, and the protocol needed here is small.
|
||||
- **Transport:** stdio, one JSON-RPC 2.0 message per line (UTF-8, at most 16 MiB; a longer or non-UTF-8 line gets a parse error and the next line is read). Batches are rejected. stdout carries only MCP messages; the server exits 0 when stdin closes. Every request runs under `lutra_engine::guard`.
|
||||
- **Protocol versions (dual era):** modern **2026-07-28** (stateless: each request carries `_meta` `io.modelcontextprotocol/protocolVersion` and `io.modelcontextprotocol/clientCapabilities`; `server/discover`; results get `resultType: "complete"` and `_meta` `io.modelcontextprotocol/serverInfo`; another version gets `-32022` with `data {supported, requested}`, missing capabilities `-32602`) and legacy **2025-11-25, 2025-06-18, 2025-03-26, 2024-11-05** through `initialize` (the client's version if known, else 2025-11-25). Only the handshake and the result decoration differ; both eras share every method and tool. A request with neither `_meta` nor a prior `initialize` is served with legacy shapes.
|
||||
- **Methods:** `server/discover`, `initialize`, `ping`, `tools/list`, `tools/call`, `resources/list`, `resources/read`, `resources/templates/list` (empty). Notifications are accepted silently; any other method is `-32601`. Capabilities: `tools {listChanged: false}`, `resources {}` (no subscriptions yet). Lists come whole (a cursor is ignored).
|
||||
- **Tools (D16):**
|
||||
- `list_commands {filter?, enabledOnly?}`: `engine.listCommands` (id, label, menu path, shortcut, params doc, enabled, ui).
|
||||
- `execute_command {command, params?, confirm?}`: `engine.execute` for every engine and UI command. **`app.quit` is refused with `confirmation_required` unless `confirm: true`.**
|
||||
- `screenshot {path?}`: `ui.screenshot` into a temporary file (deleted afterwards) or `path`, returned as `image/png` content; at most 32 MiB, PNG signature checked.
|
||||
- `read_buffer {path | id}`: the current text with unsaved changes plus `{id, path, version, dirty, lineEnding, truncated}`; a project-relative or absolute path inside the project; cut at 4 MiB.
|
||||
- `get_events {since?, max?, kinds?, waitMs?}`: see Events below.
|
||||
- Results carry `structuredContent` and the same JSON as text. Bad arguments, engine errors and an unreachable Lutra are tool errors (`isError: true`, text `code: message`, `structuredContent.error {code, message}`) with the engine's code, or `invalid_params`, `confirmation_required`, `not_open`, `screenshot_failed`, `unavailable`. An unknown tool is `-32602`.
|
||||
- **Events:** the first connection starts a pump thread with its own subscribed connection (`events.subscribe`). It keeps the last 1000 events in a ring, numbered by a growing `seq`, each capped at 16 KiB (a bigger one keeps only `kind` and `truncated: true`). `get_events` returns the events after `since` (default 100, at most 1000, optionally only `kinds`, optionally waiting up to `waitMs` ≤ 30 s), `latest` to pass as `since` next time, `missed` when the ring dropped events after `since` or the subscription was down, and `subscribed`. A lost subscription reconnects every 0.5 s without starting Lutra. Events from before the first connection are not seen.
|
||||
- **Resources:** one per open buffer (`buffer.list`), URI `lutra://buffer/<project-relative path>` with every byte outside the RFC 3986 unreserved set (except `/`) percent-encoded, a MIME type from the extension, and a description for unsaved changes. `resources/read` returns the text with unsaved changes; an unknown or closed buffer is `-32602` with `data {uri}`, an unreachable Lutra `-32603`.
|
||||
- **Connection:** made on the first call that needs Lutra (listing tools never starts it) and pinged (`app.ping`) before each use; a dead one is replaced, which starts Lutra again if it quit.
|
||||
- **Tests:** JSON-RPC and protocol units, a proptest fuzz of message lines and tool arguments (no panic, exactly one valid response line), integration against `lutra_testkit::EngineBackend` behind a real token listener (`crates/mcp/tests/tcp.rs`), and the `lutra mcp` binary on stdio (`apps/lutra-cli/tests/mcp.rs`).
|
||||
|
||||
## Frontend ↔ engine
|
||||
|
||||
|
|
@ -89,7 +107,7 @@ Theme tokens are defined in Rust (`lutra_engine::theme`) and rendered as CSS cus
|
|||
### Workspace (M1.3)
|
||||
|
||||
- `State` holds `project: Option<Workspace>` (the `lutra_vfs::Project`, its watcher and the watched directories) and `buffers` (id → `OpenBuffer { buffer: lutra_text::Buffer, path, version, saved_version, bom }`). A buffer is dirty when `version != saved_version`. Ids are never reused.
|
||||
- Commands: `project.open {path, force?}`, `project.close {force?}`, `project.children {dir?}`, `file.open {path}` (returns the existing buffer if the file is already open), `buffer.get {id}`, `buffer.edit {id, baseVersion, edits}`, `file.save {id}` (`Mod+S`), `file.saveAll` (`Mod+Alt+S`), `buffer.close {id, force?}`. Everything except `project.open` is disabled without a project. Paths are project-relative with `/`; absolute paths are accepted when they lie inside the project; `..` escapes are rejected by the VFS.
|
||||
- Commands: `project.open {path, force?}`, `project.close {force?}`, `project.children {dir?}`, `file.open {path}` (returns the existing buffer if the file is already open), `buffer.get {id}`, `buffer.edit {id, baseVersion, edits}`, `file.save {id}` (`Mod+S`), `file.saveAll` (`Mod+Alt+S`), `buffer.close {id, force?}`, `buffer.list` (M3.8: `[{id, path, version, dirty}]` without text, empty without a project). Everything except `project.open` and `buffer.list` is disabled without a project. Paths are project-relative with `/`; absolute paths are accepted when they lie inside the project; `..` escapes are rejected by the VFS.
|
||||
- Edit protocol: `edits` are `{from, to, insert}` in UTF-16 code units, all relative to the text at `baseVersion` (CodeMirror change-set semantics), non-overlapping, applied atomically. A `baseVersion` other than the current version fails with `stale_version` and changes nothing; the client refetches with `buffer.get` and reapplies its pending changes. Each successful batch increments the version by one. Limits: 100,000 edits and 64 MiB inserted per call.
|
||||
- Saving writes `Buffer::save_text` (the file's dominant line ending) atomically through the VFS and keeps a UTF-8 byte order mark.
|
||||
|
||||
|
|
@ -343,6 +361,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
|
|||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-19 | minor | M3.8: MCP server (`lutra mcp`, dual era 2026-07-28 + legacy `initialize`), tools, resources, event buffer; `buffer.list` |
|
||||
| 2026-10-19 | minor | M3.9: app menu (header bar, `menu.open`, grouping by `menuPath`, launcher under the modal rule); menu paths for user commands |
|
||||
| 2026-10-18 | minor | M3.1: toolchain (PHP detection, pinned Phpactor download with SHA-256 check, network access note, D15), `toolchain.status`/`toolchain.downloadPhpactor`, `toolchainChanged`, bool and string settings |
|
||||
| 2026-10-18 | minor | M3.2: LSP client library (`crates/lsp`: framing, supervision and restart, initialize, requests with timeout and cancel, server requests, document sync, fake server tests) |
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Gaps
|
||||
|
||||
> **Status:** M0 closed G1; G2 under way (text buffer, engine buffers, tabs and editor in the app, recovery journal); G3 M1 part done (project tree, palette, settings dialog, themes) plus the app menu (M3.9); G4 under way (tree-sitter outline and folding library, Lezer highlighting, Structure tool window); G5 under way (search backend, Find tool window, symbol index, go-to popup); G6 under way (LSP client library, PHP detection, Phpactor download); G7 under way (`lutra` CLI and single instance); G14 English UI catalog in place · **Last updated:** 2026-10-19
|
||||
> **Status:** M0 closed G1; G2 under way (text buffer, engine buffers, tabs and editor in the app, recovery journal); G3 M1 part done (project tree, palette, settings dialog, themes) plus the app menu (M3.9); G4 under way (tree-sitter outline and folding library, Lezer highlighting, Structure tool window); G5 under way (search backend, Find tool window, symbol index, go-to popup); G6 under way (LSP client library, PHP detection, Phpactor download); G7 under way (`lutra` CLI and single instance, MCP server); G14 English UI catalog in place · **Last updated:** 2026-10-19
|
||||
|
||||
Every known shortfall, ranked. This is the work list: unless the owner gives a task, take the highest open gap. Hours are agent wall-clock hours for one agent, all estimated.
|
||||
|
||||
|
|
@ -12,7 +12,7 @@ Every known shortfall, ranked. This is the work list: unless the owner gives a t
|
|||
| G4 | Syntax and structure: tree-sitter PHP, ~~Lezer highlighting~~ (M2.2: PHP with embedded HTML plus HTML, CSS, JS/TS, JSON, YAML, Markdown; `--lt-syntax-*` tokens; `editor.reveal`), ~~file structure~~ (M2.7: Structure tool window, `syntax.outline`), semantic highlighting, folding in the editor | M2 | ~8 h |
|
||||
| G5 | Search and navigation: find in files, go to file/class/symbol, first index | M2 | ~35 h |
|
||||
| G6 | Language server: completion, diagnostics, definition, hover, rename via Phpactor (~~PHP detection and Phpactor download~~, M3.1) | M3 | ~43 h |
|
||||
| G7 | Terminal, ~~`lutra` CLI and single instance~~ (M3.7: open folders and files at a line, `--wait`, forwarding a second start, token-protected rendezvous), MCP server, files outside the open project (the CLI refuses them; needs out-of-project buffers or a second window), `lutra diff` | M3 | ~30 h |
|
||||
| G7 | Terminal, ~~`lutra` CLI and single instance~~ (M3.7: open folders and files at a line, `--wait`, forwarding a second start, token-protected rendezvous), ~~MCP server~~ (M3.8: `lutra mcp` with list/execute every command, screenshot, read buffer, recent events, open buffers as resources; still missing: resource and tool change notifications, progress for long commands), files outside the open project (the CLI refuses them; needs out-of-project buffers or a second window), `lutra diff` | M3 | ~26 h |
|
||||
| G8 | Git integration | M4 | ~150 h |
|
||||
| G9 | Debugger, test runner, Composer, run configurations | M5 | ~300 h |
|
||||
| G10 | Own indexer, type inference, inspections, refactorings | M6 | ~800 h |
|
||||
|
|
@ -50,6 +50,7 @@ G6 progress: M3.2 landed the LSP client library in `crates/lsp`: JSON-RPC framin
|
|||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-19 | minor | G7: MCP server (M3.8) |
|
||||
| 2026-10-19 | minor | G3: app menu (M3.9) |
|
||||
| 2026-10-18 | minor | G6: PHP detection and pinned Phpactor download (M3.1) |
|
||||
| 2026-10-18 | minor | G6: LSP client library (M3.2) |
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Milestones
|
||||
|
||||
> **Status:** M0 done, M1 done, M2 in progress · **Last updated:** 2026-10-17
|
||||
> **Status:** M0 done, M1 done, M2 in progress · **Last updated:** 2026-10-19
|
||||
|
||||
Hours are agent wall-clock hours for one agent; M0 and M1 so far are measured, the rest estimated. Since cycle C1 (factor 0.07) M1–M3 are scaled ×0.1; M4–M6 keep their first raw estimates (multiply by ~0.1 for the calibrated value).
|
||||
|
||||
|
|
@ -9,7 +9,7 @@ Hours are agent wall-clock hours for one agent; M0 and M1 so far are measured, t
|
|||
| M0 | Foundation: workspace, lints, quality gate, command registry, control channel, empty window | done 2026-10-14 (CI workflow written, not yet run: hosted on Forgejo, runners unknown) | ~2 (measured) |
|
||||
| M1 | Editor and project: open folder, tree, tabs, editor, save, recovery, palette, settings, themes | done 2026-10-16 (M1.1 text, M1.2 VFS, M1.5 tree UI, M1.3 engine workspace, M1.4 desktop bridge, M1.6 tabs and editor, M1.11 message catalog, M1.9a settings backend, M1.10 themes, M1.7 recovery journal, M1.12 notifications, M1.13 C1 follow-ups, M1.8 command palette and keymap, M1.14 app icon, M1.9b settings dialog; C2 live checks pending, gaming mode) | ~5.6 (measured: C1 2.5, C2 3.1) |
|
||||
| M2 | Syntax and search: highlighting, structure, find in files, go to file/class/symbol | done 2026-10-17 (C3: M2.1 tree-sitter syntax, M2.2 highlighting + `editor.reveal`, M2.3 search backend, M2.4 Find tool window, M2.5 symbol index + go-to commands, M2.6 go-to popup, M2.7 Structure tool window) | ~6.1 (measured) |
|
||||
| M3 | LSP, terminal, CLI: completion, diagnostics, go to definition, hover, rename; terminal; `lutra` CLI and MCP — **MVP** | in progress (M3.7 CLI and single instance done) | ~12 |
|
||||
| M3 | LSP, terminal, CLI: completion, diagnostics, go to definition, hover, rename; terminal; `lutra` CLI and MCP — **MVP** | in progress (M3.7 CLI and single instance, M3.8 MCP server done) | ~12 |
|
||||
| M4 | Git: status, diff, commit, branches, log, blame, conflicts | not started | ~150 |
|
||||
| M5 | Debugger (Xdebug via DAP), PHPUnit/Pest runner, Composer, run configurations | not started | ~300 |
|
||||
| M6 | Own indexer and inspections; Symfony, Laravel, Shopware, WordPress support | not started | ~1,100 |
|
||||
|
|
@ -35,6 +35,7 @@ By the raw estimates the alpha gate needs M1–M4 plus cross-platform verificati
|
|||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-18 | minor | M7–M9 added from the full PhpStorm help inventory (155 feature units); raw hours, calibrate ×0.15 |
|
||||
| 2026-10-19 | minor | M3.8 MCP server |
|
||||
| 2026-10-17 | minor | M3.7 CLI and single instance |
|
||||
| 2026-10-17 | minor | M2 done (C3 review), M3 ~12 h at ×0.15 |
|
||||
| 2026-10-17 | minor | M2.6 go-to popup |
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue