Lutra/crates/mcp/src/encoding.rs
danny 0e56c22b66 M3.8: MCP server lutra mcp
- crates/mcp (L5): JSON-RPC 2.0 over stdio, dual era: MCP 2026-07-28
  (per-request _meta, server/discover, -32022) and legacy initialize
  (2025-11-25, 2025-06-18, 2025-03-26, 2024-11-05). Tools list_commands,
  execute_command (app.quit only with confirm: true), screenshot (image
  content), read_buffer, get_events (ring of 1000 events via
  events.subscribe); resources lutra://buffer/<path> for open buffers.
  Engine errors become tool errors with the engine code. Lines capped at
  16 MiB, guard around every request, parser and tool args fuzzed.
- lutra mcp [--port PORT] [--no-start] in apps/lutra-cli: connects through
  the rendezvous file and token, or starts Lutra.
- Engine: read-only buffer.list command.
- Tests: protocol units + proptest fuzz, integration over the token
  listener, stdio end to end. Docs: architecture (MCP), G7, ROADMAP.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 20:43:12 +02:00

130 lines
4.2 KiB
Rust

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