diff --git a/Cargo.lock b/Cargo.lock index 9a4de2e07d..69e74d98e2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1356,6 +1356,14 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-jsonrpc" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=fbb2d4b299d87191a79444c6e4e02d69d9325059#fbb2d4b299d87191a79444c6e4e02d69d9325059" +dependencies = [ + "serde_json", +] + [[package]] name = "craft-keymap" version = "0.1.0" @@ -1394,6 +1402,14 @@ dependencies = [ "serde", ] +[[package]] +name = "craft-mcp-server" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=fbb2d4b299d87191a79444c6e4e02d69d9325059#fbb2d4b299d87191a79444c6e4e02d69d9325059" +dependencies = [ + "serde_json", +] + [[package]] name = "craft-menu" version = "0.1.0" @@ -4882,6 +4898,8 @@ dependencies = [ "craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)", "craft-docx", "craft-image-codecs", + "craft-jsonrpc", + "craft-mcp-server", "craft-prc", "craft-wordmodel 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)", "flate2", diff --git a/Cargo.toml b/Cargo.toml index 9becf77a2b..fc6231cd16 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -51,6 +51,9 @@ craft-wordmodel = { git = "https://github.com/storytold/craft-libs", version = " craft-pptx = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "010702ee9b030844c852939095b1da0d0656a890" } craft-drawingml = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "010702ee9b030844c852939095b1da0d0656a890" } craft-opc = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e2dc681a3" } +# Shared MCP stdio framing and JSON-RPC 2.0 envelopes (storytold/craft-libs#778). +craft-mcp-server = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "fbb2d4b299d87191a79444c6e4e02d69d9325059" } +craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "fbb2d4b299d87191a79444c6e4e02d69d9325059" } # internal pdfcraft-geom = { path = "crates/geom", version = "0.21.0" } pdfcraft-filters = { path = "crates/filters", version = "0.21.0" } diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml index 9e9efaee9b..5c40f45469 100644 --- a/crates/automation/Cargo.toml +++ b/crates/automation/Cargo.toml @@ -20,12 +20,14 @@ serde_json = { workspace = true } sha2 = "0.11" tempfile = "3.27" base64 = { version = "0.23", optional = true } +craft-jsonrpc = { workspace = true, optional = true } +craft-mcp-server = { workspace = true, optional = true } [features] default = ["mcp"] # The MCP server module. Opt-in at run time either way; disable to leave it out of the build. -mcp = ["dep:base64"] +mcp = ["dep:base64", "dep:craft-jsonrpc", "dep:craft-mcp-server"] [dev-dependencies] # Synthetic printer profiles for the app-managed print colour tests. diff --git a/crates/automation/src/mcp.rs b/crates/automation/src/mcp.rs index b033871867..5bc4489166 100644 --- a/crates/automation/src/mcp.rs +++ b/crates/automation/src/mcp.rs @@ -14,15 +14,16 @@ use std::io::{BufRead, Write}; use base64::Engine as _; +use craft_jsonrpc::{RpcError, error_response, process_legacy}; +use craft_mcp_server::{Incoming, read_message}; use serde_json::{Value, json}; use crate::{Automation, Content, ToolError}; /// Protocol revisions we speak, newest first. -pub const PROTOCOL_VERSIONS: &[&str] = &["2025-06-18", "2025-03-26", "2024-11-05"]; +pub use craft_mcp_server::SUPPORTED_VERSIONS as PROTOCOL_VERSIONS; const PARSE_ERROR: i64 = -32700; -const INVALID_REQUEST: i64 = -32600; const METHOD_NOT_FOUND: i64 = -32601; const INVALID_PARAMS: i64 = -32602; const INTERNAL_ERROR: i64 = -32603; @@ -88,61 +89,43 @@ impl McpServer { /// Serve until `input` reaches end of file. pub fn serve(&mut self, mut input: impl BufRead, mut output: impl Write) -> std::io::Result<()> { - let mut buf = Vec::new(); - loop { - match read_line_limited(&mut input, &mut buf, MAX_LINE_BYTES)? { - LineRead::End => return Ok(()), - LineRead::TooLong => { - drain_line(&mut input)?; - buf.clear(); - buf.shrink_to(64 * 1024); - let reply = error(Value::Null, INVALID_REQUEST, &format!("request line exceeds {MAX_LINE_BYTES} bytes")); - writeln!(output, "{reply}")?; - output.flush()?; - continue; - } - LineRead::Line => {} - } - let reply = match std::str::from_utf8(&buf) { - Ok(line) if line.trim().is_empty() => None, - Ok(line) => self.handle_line(line), - Err(e) => Some(error(Value::Null, PARSE_ERROR, &format!("parse error: {e}")).to_string()), + while let Some(incoming) = read_message(&mut input, MAX_LINE_BYTES)? { + let reply = match incoming { + Incoming::Line(line) => self.handle_line(&line), + Incoming::Refused(reply) => Some(reply), }; - if buf.capacity() > 64 * 1024 { - buf.clear(); - buf.shrink_to(64 * 1024); - } if let Some(reply) = reply { - writeln!(output, "{reply}")?; + output.write_all(reply.as_bytes())?; + output.write_all(b"\n")?; output.flush()?; } } + Ok(()) } /// Handle one JSON-RPC message; returns the serialized reply, if one is due. pub fn handle_line(&mut self, line: &str) -> Option { + let line = line.trim(); + if line.is_empty() { + return None; + } let reply = match serde_json::from_str::(line) { Ok(msg) => self.handle(&msg), - Err(e) => Some(error(Value::Null, PARSE_ERROR, &format!("parse error: {e}"))), + Err(e) => Some(error_response(Value::Null, RpcError::new(PARSE_ERROR, format!("parse error: {e}")))), }; reply.map(|r| r.to_string()) } /// Handle one parsed message. Notifications (no `id`) get no reply. pub fn handle(&mut self, msg: &Value) -> Option { - let Some(obj) = msg.as_object() else { return Some(error(Value::Null, INVALID_REQUEST, "expected a JSON-RPC request object")) }; - let id = obj.get("id").cloned(); - let Some(method) = obj.get("method").and_then(Value::as_str) else { - // A response to something we sent (we send no requests) or garbage. - return id.map(|id| error(id, INVALID_REQUEST, "missing method")); - }; - let params = obj.get("params").cloned().unwrap_or(Value::Null); - let id = id?; // notifications/initialized, notifications/cancelled, …: nothing to answer - let result = guarded_dispatch(method, || self.dispatch(method, ¶ms)); - Some(match result { - Ok(result) => json!({ "jsonrpc": "2.0", "id": id, "result": result }), - Err((code, message)) => error(id, code, &message), - }) + process_legacy( + msg, + |req| { + let params = req.params.cloned().unwrap_or(Value::Null); + guarded_dispatch(req.method, || self.dispatch(req.method, ¶ms)).map_err(|(code, message)| RpcError::new(code, message)) + }, + |_| {}, + ) } fn dispatch(&mut self, method: &str, params: &Value) -> Result { @@ -345,53 +328,6 @@ fn unwrap_tool_call(args: &Value) -> Result<(String, Value), String> { Ok((name.to_owned(), inner)) } -/// What [`read_line_limited`] found. -#[derive(Debug, PartialEq, Eq)] -enum LineRead { - /// A line, now in the buffer (newline and a trailing `\r` stripped). - Line, - /// End of stream. - End, - /// The line is longer than the limit; at most `max + 1` bytes of it were read. - TooLong, -} - -/// Read one `\n`-terminated line of at most `max` bytes into `buf`. -fn read_line_limited(reader: &mut impl BufRead, buf: &mut Vec, max: usize) -> std::io::Result { - use std::io::Read as _; - buf.clear(); - // `take` bounds what is buffered for one line: never more than `max + 1` bytes. - let limit = u64::try_from(max).unwrap_or(u64::MAX).saturating_add(1); - if reader.take(limit).read_until(b'\n', buf)? == 0 { - return Ok(LineRead::End); - } - if buf.last() == Some(&b'\n') { - buf.pop(); - if buf.last() == Some(&b'\r') { - buf.pop(); - } - return Ok(LineRead::Line); - } - // No newline: either the limit was passed, or this is a last line before end of stream. - Ok(if buf.len() > max { LineRead::TooLong } else { LineRead::Line }) -} - -/// Discard the rest of an overlong line up to `\n` or end of stream without buffering it. -fn drain_line(reader: &mut impl BufRead) -> std::io::Result<()> { - loop { - let chunk = reader.fill_buf()?; - if chunk.is_empty() { - return Ok(()); - } - if let Some(pos) = chunk.iter().position(|&b| b == b'\n') { - reader.consume(pos + 1); - return Ok(()); - } - let len = chunk.len(); - reader.consume(len); - } -} - /// Last-resort boundary shared by every tools/call route, including compact dispatch. fn guarded_tool(f: impl FnOnce() -> Result) -> Result { pdfcraft_engine::guard(f).unwrap_or_else(|message| Ok(tool_error(&format!("internal error: {message}")))) @@ -547,10 +483,6 @@ impl McpServer { } } -fn error(id: Value, code: i64, message: &str) -> Value { - json!({ "jsonrpc": "2.0", "id": id, "error": { "code": code, "message": message } }) -} - fn tool_json(t: &crate::ToolDef) -> Value { json!({ "name": t.name, @@ -614,27 +546,6 @@ mod tests { assert_eq!(ok["resources"], json!([])); } - #[test] - fn read_line_limited_and_drain_line_respect_boundaries() { - use super::{LineRead, drain_line, read_line_limited}; - let mut buf = Vec::new(); - let mut input: &[u8] = b"aaaaaaaaaa\nbb\r\ncc"; - assert_eq!(read_line_limited(&mut input, &mut buf, 10).unwrap(), LineRead::Line); - assert_eq!(buf, b"aaaaaaaaaa", "a line exactly at the limit is accepted"); - assert_eq!(read_line_limited(&mut input, &mut buf, 10).unwrap(), LineRead::Line); - assert_eq!(buf, b"bb", "CRLF is stripped"); - assert_eq!(read_line_limited(&mut input, &mut buf, 10).unwrap(), LineRead::Line); - assert_eq!(buf, b"cc", "a last line without a newline is still read"); - assert_eq!(read_line_limited(&mut input, &mut buf, 10).unwrap(), LineRead::End); - - let mut overlong: &[u8] = b"0123456789abcdef\nafter\n"; - assert_eq!(read_line_limited(&mut overlong, &mut buf, 10).unwrap(), LineRead::TooLong); - assert_eq!(buf.len(), 11, "at most max + 1 bytes are buffered"); - drain_line(&mut overlong).unwrap(); - assert_eq!(read_line_limited(&mut overlong, &mut buf, 10).unwrap(), LineRead::Line); - assert_eq!(buf, b"after", "the next line after an overlong line is read cleanly"); - } - #[test] fn serve_answers_non_utf8_and_overlong_lines_and_keeps_serving() { let init = json!({