From 55f903dc4c6886928194d9a49881fe53baee48b0 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 16:41:43 -0500 Subject: [PATCH] mcp: delegate stdio framing and protocol constants to craft-mcp-server (refs storytold/craft-libs#778) (#2261) --- Cargo.lock | 9 ++++++ Cargo.toml | 2 ++ crates/mcp/Cargo.toml | 1 + crates/mcp/src/server.rs | 61 ++++++---------------------------------- crates/mcp/src/tests.rs | 2 +- 5 files changed, 21 insertions(+), 54 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8f19374f8..0633e3e29 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1017,6 +1017,14 @@ dependencies = [ "writeable", ] +[[package]] +name = "craft-mcp-server" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bc186ca719958fcce3b6ee24794277eabed14609#bc186ca719958fcce3b6ee24794277eabed14609" +dependencies = [ + "serde_json", +] + [[package]] name = "craft-media" version = "0.1.0" @@ -1384,6 +1392,7 @@ dependencies = [ name = "deckcraft-mcp" version = "0.19.0" dependencies = [ + "craft-mcp-server", "deckcraft-engine", "deckcraft-render", "log", diff --git a/Cargo.toml b/Cargo.toml index ac5d567ac..aeceec4e5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,6 +21,8 @@ craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "ea24422ae9 # Isolated table XML writer; existing DrawingML model/readers keep their revision. craft-drawingml-table = { package = "craft-drawingml", git = "https://github.com/storytold/craft-libs", rev = "cff5af869dbf6926801c9ac63a927d155202ba3b" } craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "44d83fa8f635333dcb3c231f87381387a1f5631b", version = "0.1.0" } +# Shared MCP stdio framing and protocol constants (craft-libs#778). +craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "bc186ca719958fcce3b6ee24794277eabed14609", version = "0.1.0" } # internal deckcraft-geom = { path = "crates/geom" } deckcraft-color = { path = "crates/color" } diff --git a/crates/mcp/Cargo.toml b/crates/mcp/Cargo.toml index ab2efad44..3b9e1254f 100644 --- a/crates/mcp/Cargo.toml +++ b/crates/mcp/Cargo.toml @@ -9,6 +9,7 @@ description = "DeckCraft MCP server: JSON-RPC 2.0 over stdio, driving a running workspace = true [dependencies] +craft-mcp-server = { workspace = true } deckcraft-engine = { workspace = true } deckcraft-render = { workspace = true } serde_json = { workspace = true } diff --git a/crates/mcp/src/server.rs b/crates/mcp/src/server.rs index d28f184ff..2b7a0f99e 100644 --- a/crates/mcp/src/server.rs +++ b/crates/mcp/src/server.rs @@ -1,16 +1,14 @@ //! JSON-RPC 2.0 framing and the MCP lifecycle / tools / resources methods. -use std::io::{self, BufRead, Write}; +use std::io::{BufRead, Write}; +pub use craft_mcp_server::PROTOCOL_VERSION; +use craft_mcp_server::{Incoming, SUPPORTED_VERSIONS, read_message, response}; use serde_json::{Value, json}; use crate::backend::Backend; use crate::tools::{call_tool, tool_definitions}; -/// The MCP revision we implement. -pub const PROTOCOL_VERSION: &str = "2025-06-18"; -const SUPPORTED_VERSIONS: &[&str] = &[PROTOCOL_VERSION, "2025-03-26", "2024-11-05"]; - const PARSE_ERROR: i64 = -32700; const INVALID_REQUEST: i64 = -32600; const METHOD_NOT_FOUND: i64 = -32601; @@ -45,10 +43,6 @@ pub struct Server { initialized: bool, } -fn response(id: Value, result: Value) -> Value { - json!({"jsonrpc": "2.0", "id": id, "result": result}) -} - fn error(id: Value, code: i64, message: impl Into) -> Value { json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message.into()}}) } @@ -69,15 +63,11 @@ impl Server { /// Serve newline-delimited JSON-RPC until `input` closes. Logs go to stderr only (stdout is /// the protocol stream). - pub fn serve(&mut self, input: impl BufRead, mut output: impl Write) -> std::io::Result<()> { - let mut input = input; - while let Some(frame) = read_frame(&mut input)? { - let reply = match frame { - Frame::Complete(bytes) => match std::str::from_utf8(&bytes) { - Ok(line) => self.handle_line(line), - Err(_) => Some(error(Value::Null, PARSE_ERROR, "request frame is not valid UTF-8").to_string()), - }, - Frame::TooLarge => Some(error(Value::Null, INVALID_REQUEST, "request frame exceeds 16 MiB").to_string()), + pub fn serve(&mut self, mut input: impl BufRead, mut output: impl Write) -> std::io::Result<()> { + while let Some(incoming) = read_message(&mut input, MAX_FRAME_BYTES)? { + let reply = match incoming { + Incoming::Line(line) => self.handle_line(&line), + Incoming::Refused(reply) => Some(reply), }; if let Some(reply) = reply { output.write_all(reply.as_bytes())?; @@ -207,38 +197,3 @@ impl Server { } } } - -enum Frame { - Complete(Vec), - TooLarge, -} - -/// Read through one newline while retaining no more than the documented frame budget. -fn read_frame(input: &mut impl BufRead) -> io::Result> { - let mut bytes = Vec::new(); - let mut too_large = false; - loop { - let available = input.fill_buf()?; - if available.is_empty() { - if bytes.is_empty() && !too_large { - return Ok(None); - } - return Ok(Some(if too_large { Frame::TooLarge } else { Frame::Complete(bytes) })); - } - let count = available.iter().position(|byte| *byte == b'\n').map_or(available.len(), |i| i + 1); - if !too_large { - let remaining = MAX_FRAME_BYTES.saturating_sub(bytes.len()); - if count > remaining { - too_large = true; - bytes.clear(); - } else { - bytes.extend_from_slice(&available[..count]); - } - } - let ended = available[count - 1] == b'\n'; - input.consume(count); - if ended { - return Ok(Some(if too_large { Frame::TooLarge } else { Frame::Complete(bytes) })); - } - } -} diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 665591872..3ae5e656c 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -20,7 +20,7 @@ fn oversized_stdio_frame_is_drained_before_the_next_request() { let replies: Vec = std::str::from_utf8(&output).unwrap().lines().map(|line| serde_json::from_str(line).unwrap()).collect(); assert_eq!(replies.len(), 2); assert_eq!(replies[0]["error"]["code"], -32600); - assert!(replies[0]["error"]["message"].as_str().unwrap().contains("16 MiB")); + assert!(replies[0]["error"]["message"].as_str().unwrap().contains("too large")); assert_eq!(replies[1]["id"], 1); assert_eq!(replies[1]["result"]["serverInfo"]["name"], "deckcraft"); }