From cfecebbcfb175b84165ed769c04e8ecae0dc74f1 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Thu, 1 Oct 2026 21:40:12 -0400 Subject: [PATCH] Headless JSON-lines server and MCP command_batch crates/automation/src/rpc.rs: a headless session behind the control protocol's envelope (engine.execute, doc.*, session.list, batch), on stdio or loopback TCP. MCP gains command_batch (headless and bridge). Co-Authored-By: Claude Opus 5.5 --- crates/automation/src/lib.rs | 3 + crates/automation/src/rpc.rs | 349 ++++++++++++++++++++++++++++++++ crates/automation/src/server.rs | 49 ++++- crates/automation/tests/mcp.rs | 25 +++ docs/control-protocol.md | 30 +++ docs/development.md | 5 +- 6 files changed, 459 insertions(+), 2 deletions(-) create mode 100644 crates/automation/src/rpc.rs diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs index ba0631b444..8787257960 100644 --- a/crates/automation/src/lib.rs +++ b/crates/automation/src/lib.rs @@ -8,6 +8,8 @@ //! app over the JSON-lines control protocol (`docs/control-protocol.md`), so //! agents can also inspect, screenshot and click the live UI. //! * [`Headless`]: the synchronous session + file I/O core, shared with the CLI. +//! * [`rpc`]: a headless JSON-lines server (stdio or loopback TCP) with the +//! control protocol's envelope, used by `photocraft-cli serve`. //! * [`files`]: open/save any supported format, `.pcraft` natively. //! //! L6, no UI-toolkit dependencies. @@ -16,6 +18,7 @@ pub mod bridge; pub mod files; pub mod headless; +pub mod rpc; pub mod server; pub use bridge::BridgeClient; diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs new file mode 100644 index 0000000000..a3ce06abdb --- /dev/null +++ b/crates/automation/src/rpc.rs @@ -0,0 +1,349 @@ +//! Headless JSON-lines server: the control protocol's envelope +//! (`{"id","method","params"}` → `{"id","ok","result"|"error"}`) over a +//! [`Headless`] session, so scripts and agents can keep one editing session +//! open without MCP or the GUI. `photocraft-cli serve` runs it on stdio or a +//! loopback TCP port. +//! +//! Methods (camelCase params): +//! - `engine.execute {command, params?}` / `engine.commands {filter?}` +//! - `session.list`, `doc.open {path}`, `doc.new {…file.new params}`, +//! `doc.save {path?, format?, quality?, index?}`, `doc.inspect {index?}`, +//! `doc.render {index?, maxSide?, path?}` (writes a PNG to `path`, else +//! returns it base64-encoded), `doc.select {index}`, `doc.close {index?}` +//! - `batch {steps: [{command, params?} | {method, params?}], stopOnError?}` +//! - `methods`: this list. + +use std::io::{BufRead, Write}; +use std::net::TcpListener; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; + +use base64::Engine as _; +use serde_json::{Value, json}; + +use crate::{AutomationError, Headless}; + +/// Method names served by [`Headless::handle`]. +pub const METHODS: &[&str] = &[ + "engine.execute", + "engine.commands", + "session.list", + "doc.open", + "doc.new", + "doc.save", + "doc.inspect", + "doc.render", + "doc.select", + "doc.close", + "batch", + "methods", +]; + +fn bad(msg: impl Into) -> AutomationError { + AutomationError::BadRequest(msg.into()) +} + +fn index_of(p: &Value) -> Option { + p.get("index").and_then(Value::as_u64).map(|i| i as usize) +} + +fn str_of<'a>(p: &'a Value, k: &str) -> Option<&'a str> { + p.get(k).and_then(Value::as_str) +} + +impl Headless { + /// Dispatch one request. Unknown methods and bad params are errors, never panics. + pub fn handle(&mut self, method: &str, params: Value) -> Result { + let p = if params.is_null() { json!({}) } else { params }; + match method { + "engine.execute" => { + let id = + str_of(&p, "command").ok_or_else(|| bad("engine.execute needs `command`"))?; + self.command_run(id, p.get("params").cloned().unwrap_or(Value::Null)) + } + "engine.commands" => { + let all = self.command_list(); + Ok(match str_of(&p, "filter").map(str::to_lowercase) { + None => all, + Some(n) => Value::Array( + all.as_array() + .into_iter() + .flatten() + .filter(|c| { + let hay = format!( + "{} {}", + c["id"].as_str().unwrap_or(""), + c["label"].as_str().unwrap_or("") + ); + hay.to_lowercase().contains(&n) + }) + .cloned() + .collect(), + ), + }) + } + "session.list" => Ok(self.session_list()), + "doc.open" => { + let path = str_of(&p, "path").ok_or_else(|| bad("doc.open needs `path`"))?; + self.open(&PathBuf::from(path)) + } + "doc.new" => self.command_run("file.new", p), + "doc.save" => { + let mut opts = photocraft_io::ExportOptions::default(); + if let Some(q) = p.get("quality").and_then(Value::as_u64) { + opts.encode.jpeg_quality = q.clamp(1, 100) as u8; + } + let path = str_of(&p, "path").map(PathBuf::from); + self.save(index_of(&p), path.as_deref(), str_of(&p, "format"), &opts) + } + "doc.inspect" => self.inspect(index_of(&p)), + "doc.render" => { + let max = p.get("maxSide").and_then(Value::as_u64).unwrap_or(1024) as u32; + let png = self.render_png(index_of(&p), max)?; + match str_of(&p, "path") { + Some(path) => { + std::fs::write(path, &png) + .map_err(|e| AutomationError::Io(e.to_string()))?; + Ok(json!({"path": path, "bytes": png.len()})) + } + None => Ok(json!({ + "mime": "image/png", + "base64": base64::engine::general_purpose::STANDARD.encode(&png), + })), + } + } + "doc.select" => { + let i = index_of(&p).ok_or_else(|| bad("doc.select needs `index`"))?; + self.select(i) + } + "doc.close" => self.close(index_of(&p)), + "batch" => self.batch(&p), + "methods" => Ok(json!(METHODS)), + other => Err(bad(format!("unknown method `{other}` (try `methods`)"))), + } + } + + /// Run `steps` in order. Each step is `{command, params?}` (an engine command) or + /// `{method, params?}` (any [`METHODS`] entry). Stops at the first error unless + /// `stopOnError` is false; the reply lists every step's result. + pub fn batch(&mut self, p: &Value) -> Result { + let steps = p + .get("steps") + .and_then(Value::as_array) + .ok_or_else(|| bad("batch needs `steps`"))?; + let stop = p + .get("stopOnError") + .and_then(Value::as_bool) + .unwrap_or(true); + let mut results = Vec::with_capacity(steps.len()); + let mut failed = 0usize; + for (i, s) in steps.iter().enumerate() { + let params = s.get("params").cloned().unwrap_or(Value::Null); + let r = if let Some(c) = str_of(s, "command") { + self.command_run(c, params) + } else if let Some(m) = str_of(s, "method") { + if m == "batch" { + Err(bad("nested batch")) + } else { + self.handle(m, params) + } + } else { + Err(bad(format!("step {i} needs `command` or `method`"))) + }; + match r { + Ok(v) => results.push(json!({"ok": true, "result": v})), + Err(e) => { + failed += 1; + results.push(json!({"ok": false, "error": e.to_string()})); + if stop { + break; + } + } + } + } + Ok(json!({"completed": results.len() - failed, "failed": failed, "results": results})) + } +} + +/// Answer one request line. Malformed JSON gets an error reply with `id: null`. +pub fn respond(h: &Mutex, line: &str) -> Value { + let req: Value = match serde_json::from_str(line) { + Ok(v) => v, + Err(e) => return json!({"id": null, "ok": false, "error": format!("bad JSON: {e}")}), + }; + let id = req.get("id").cloned().unwrap_or(Value::Null); + let Some(method) = req.get("method").and_then(Value::as_str) else { + return json!({"id": id, "ok": false, "error": "missing `method`"}); + }; + let params = req.get("params").cloned().unwrap_or(Value::Null); + let r = match h.lock() { + Ok(mut g) => g.handle(method, params), + Err(_) => Err(AutomationError::Other("session lock poisoned".into())), + }; + match r { + Ok(v) => json!({"id": id, "ok": true, "result": v}), + Err(e) => json!({"id": id, "ok": false, "error": e.to_string()}), + } +} + +/// Serve JSON lines from `r` to `w` until EOF. Blank lines are ignored. +pub fn serve_lines(h: &Mutex, r: impl BufRead, mut w: impl Write) -> std::io::Result<()> { + for line in r.lines() { + let line = line?; + if line.trim().is_empty() { + continue; + } + let reply = respond(h, &line); + writeln!(w, "{reply}")?; + w.flush()?; + } + Ok(()) +} + +/// Serve on a loopback TCP address (one thread per connection, one shared session). +/// Refuses non-loopback addresses. +pub fn serve_tcp( + addr: &str, + h: Arc>, + ready: impl FnOnce(std::net::SocketAddr), +) -> Result<(), AutomationError> { + let listener = + TcpListener::bind(addr).map_err(|e| AutomationError::Io(format!("bind {addr}: {e}")))?; + let local = listener + .local_addr() + .map_err(|e| AutomationError::Io(e.to_string()))?; + if !local.ip().is_loopback() { + return Err(bad(format!("{addr} is not a loopback address"))); + } + ready(local); + for stream in listener.incoming() { + let Ok(stream) = stream else { continue }; + let h = h.clone(); + std::thread::spawn(move || { + let Ok(read) = stream.try_clone() else { return }; + let _ = serve_lines(&h, std::io::BufReader::new(read), stream); + }); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn session() -> Mutex { + Mutex::new(Headless::new()) + } + + #[test] + fn lines_round_trip_and_errors() { + let h = session(); + let input = concat!( + r#"{"id":1,"method":"doc.new","params":{"width":64,"height":32,"background":"white"}}"#, + "\n", + "\n", + r#"{"id":2,"method":"engine.execute","params":{"command":"layer.new.layer","params":{"name":"Ink"}}}"#, + "\n", + r#"{"id":3,"method":"doc.inspect"}"#, + "\n", + r#"{"id":4,"method":"nope"}"#, + "\n", + "not json\n", + ); + let mut out = Vec::new(); + serve_lines(&h, input.as_bytes(), &mut out).unwrap(); + let replies: Vec = String::from_utf8(out) + .unwrap() + .lines() + .map(|l| serde_json::from_str(l).unwrap()) + .collect(); + assert_eq!(replies.len(), 5); + assert!(replies[0]["ok"].as_bool().unwrap()); + assert_eq!(replies[1]["id"], 2); + assert!(replies[2]["result"].to_string().contains("Ink")); + assert!(!replies[3]["ok"].as_bool().unwrap()); + assert!( + replies[3]["error"] + .as_str() + .unwrap() + .contains("unknown method") + ); + assert_eq!(replies[4]["id"], Value::Null); + } + + #[test] + fn batch_stops_on_error_unless_told_not_to() { + let h = session(); + let mut g = h.lock().unwrap(); + g.handle("doc.new", json!({"width": 16, "height": 16})) + .unwrap(); + let steps = json!([ + {"command": "layer.new.layer", "params": {"name": "A"}}, + {"command": "no.such.command"}, + {"command": "layer.new.layer", "params": {"name": "B"}}, + {"method": "doc.inspect"} + ]); + let r = g.handle("batch", json!({"steps": steps})).unwrap(); + assert_eq!(r["completed"], 1); + assert_eq!(r["failed"], 1); + assert_eq!(r["results"].as_array().unwrap().len(), 2); + let r = g + .handle("batch", json!({"steps": steps, "stopOnError": false})) + .unwrap(); + assert_eq!(r["completed"], 3); + let insp = &r["results"][3]["result"]; + assert!(insp.to_string().contains("\"B\"")); + } + + #[test] + fn render_to_file_and_base64() { + let h = session(); + let mut g = h.lock().unwrap(); + g.handle( + "doc.new", + json!({"width": 40, "height": 20, "background": "black"}), + ) + .unwrap(); + let b = g.handle("doc.render", json!({"maxSide": 10})).unwrap(); + let png = base64::engine::general_purpose::STANDARD + .decode(b["base64"].as_str().unwrap()) + .unwrap(); + let img = photocraft_codecs::decode(&png).unwrap(); + assert_eq!(img.dimensions(), (10, 5)); + let path = std::env::temp_dir().join(format!("pc-rpc-{}.png", std::process::id())); + let r = g + .handle( + "doc.render", + json!({"path": path.to_string_lossy(), "maxSide": 0}), + ) + .unwrap(); + assert!(r["bytes"].as_u64().unwrap() > 0); + assert_eq!( + photocraft_codecs::decode(&std::fs::read(&path).unwrap()) + .unwrap() + .dimensions(), + (40, 20) + ); + let _ = std::fs::remove_file(path); + } + + #[test] + fn tcp_serves_loopback() { + use std::io::{BufReader, Write as _}; + let h = Arc::new(Mutex::new(Headless::new())); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let _ = serve_tcp("127.0.0.1:0", h, move |a| tx.send(a).unwrap()); + }); + let addr = rx.recv().unwrap(); + let mut s = std::net::TcpStream::connect(addr).unwrap(); + writeln!(s, r#"{{"id":"a","method":"methods"}}"#).unwrap(); + let mut line = String::new(); + BufReader::new(s.try_clone().unwrap()) + .read_line(&mut line) + .unwrap(); + let v: Value = serde_json::from_str(&line).unwrap(); + assert_eq!(v["id"], "a"); + assert!(v["result"].as_array().unwrap().iter().any(|m| m == "batch")); + } +} diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index 9cb40a103c..be42e89d41 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -115,6 +115,15 @@ pub struct RunParams { pub params: Option, } +#[derive(Debug, Deserialize, JsonSchema)] +pub struct BatchParams { + /// Commands to run in order: `[{"id": "layer.new.layer", "params": {"name": "Ink"}}, …]`. + pub steps: Vec, + /// Stop at the first failing step (default true). + #[serde(default)] + pub stop_on_error: Option, +} + #[derive(Debug, Deserialize, JsonSchema)] pub struct PointerParams { /// Events in document coordinates: `[{"kind":"down|move|up","x":..,"y":..,"pressure":..}]`. @@ -489,6 +498,44 @@ impl PhotocraftMcp { .await } + #[tool( + description = "Run several engine commands in one call (fewer round trips). Returns {completed, failed, \ + results:[{ok, result|error}]}; stops at the first error unless stop_on_error is false." + )] + async fn command_batch( + &self, + Parameters(p): Parameters, + ) -> Result { + let stop = p.stop_on_error.unwrap_or(true); + let steps: Vec = p + .steps + .into_iter() + .map(|s| json!({"command": s.id, "params": s.params.unwrap_or_else(|| json!({}))})) + .collect(); + let args = json!({"steps": steps, "stopOnError": stop}); + if let Some(r) = self.headless_op(move |h| h.batch(&args)).await { + return to_result(r); + } + let b = self.bridge_client().expect("bridge"); + let mut results = Vec::new(); + let mut failed = 0; + for s in &steps { + match b.call("engine.execute", s.clone()).await { + Ok(v) => results.push(json!({"ok": true, "result": v})), + Err(e) => { + failed += 1; + results.push(json!({"ok": false, "error": e.to_string()})); + if stop { + break; + } + } + } + } + Ok(ok_json( + &json!({"completed": results.len() - failed, "failed": failed, "results": results}), + )) + } + // ----- live-GUI tools (bridge mode) ----- #[tool( @@ -615,7 +662,7 @@ impl PhotocraftMcp { } } -#[tool_handler(router = self.tool_router, name = "photocraft", instructions = "Photocraft image editor. Every edit is an engine command: call `command_list` to discover ids and parameter docs, then `command_run`. Use `doc_open`/`doc_new` first, `doc_inspect` for the layer tree, `doc_render_preview` to see the result, and `doc_save` (.pcraft is lossless native; .psd/.png/.jpg/.tif… export). In bridge mode the `ui_*` tools drive the live app (inspect, screenshot, pointer, menus).")] +#[tool_handler(router = self.tool_router, name = "photocraft", instructions = "Photocraft image editor. Every edit is an engine command: call `command_list` to discover ids and parameter docs, then `command_run` (or `command_batch` for several at once). Use `doc_open`/`doc_new` first, `doc_inspect` for the layer tree, `doc_render_preview` to see the result, and `doc_save` (.pcraft is lossless native; .psd/.png/.jpg/.tif… export). In bridge mode the `ui_*` tools drive the live app (inspect, screenshot, pointer, menus).")] impl ServerHandler for PhotocraftMcp {} /// Used by the render helper in tests and the CLI. diff --git a/crates/automation/tests/mcp.rs b/crates/automation/tests/mcp.rs index a7b1fc1db3..7841d44cf5 100644 --- a/crates/automation/tests/mcp.rs +++ b/crates/automation/tests/mcp.rs @@ -78,6 +78,7 @@ async fn lists_expected_tools() { "doc_close", "command_list", "command_run", + "command_batch", "ui_inspect", "ui_screenshot", "ui_pointer", @@ -409,3 +410,27 @@ async fn bridge_reports_unreachable_app() { assert!(text(&r).contains("--control"), "{}", text(&r)); client.cancel().await.unwrap(); } + +#[tokio::test(flavor = "multi_thread")] +async fn command_batch_runs_steps_in_order() { + let client = connect(PhotocraftMcp::headless()).await; + json_of(&call(&client, "doc_new", json!({"width": 32, "height": 32})).await); + let r = json_of( + &call( + &client, + "command_batch", + json!({"steps": [ + {"id": "layer.new.layer", "params": {"name": "One"}}, + {"id": "layer.new.layer", "params": {"name": "Two"}}, + {"id": "no.such.command"}, + {"id": "layer.new.layer", "params": {"name": "Three"}} + ]}), + ) + .await, + ); + assert_eq!(r["completed"], 2); + assert_eq!(r["failed"], 1); + let doc = json_of(&call(&client, "doc_inspect", json!({})).await).to_string(); + assert!(doc.contains("\"Two\"") && !doc.contains("\"Three\"")); + client.cancel().await.unwrap(); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index ce1f0e50b6..3e00a13bf4 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -125,3 +125,33 @@ How each MCP tool maps onto control methods in bridge mode: `doc_select` and `doc_close` work only in headless mode. The `ui_*` tools and `control_call` work only in bridge mode; in headless mode they return a tool error that explains how to start bridge mode. **Security note:** the control port has no authentication. Any local process can drive the app. Only enable `--control` when you need it. A token handshake is planned (architecture §12). + +## Headless server + +`photocraft-cli serve` keeps one headless engine session (no window, no GPU) and answers the same +JSON-lines envelope on stdio, or on `127.0.0.1:` with `--port ` (loopback only; each +connection shares the session). It is the fastest way for a script or agent to make many edits: +no MCP framing, no app start-up per command. Implementation: `crates/automation/src/rpc.rs`. + +| Method | Params | +|---|---| +| `engine.execute` | `{command, params?}`: any engine command | +| `engine.commands` | `{filter?}`: registry with params docs and enablement | +| `session.list` | open documents and the active index | +| `doc.open` / `doc.new` | `{path}` / `file.new` params | +| `doc.save` | `{path?, format?, quality?, index?}` (`.pcraft` native, else export by extension) | +| `doc.inspect` | `{index?}`: same JSON as `document.inspect` | +| `doc.render` | `{index?, maxSide? (1024; 0 = full), path?}`: PNG to `path`, else `{mime, base64}` | +| `doc.select` / `doc.close` | `{index}` / `{index?}` | +| `batch` | `{steps: [{command, params?} \| {method, params?}], stopOnError? (true)}` → `{completed, failed, results}` | +| `methods` | the list above | + +```sh +printf '%s\n' \ + '{"id":1,"method":"doc.open","params":{"path":"/abs/in.jpg"}}' \ + '{"id":2,"method":"batch","params":{"steps":[{"command":"image.adjustments.invert"},{"command":"filter.blur.gaussianBlur","params":{"radius":3}}]}}' \ + '{"id":3,"method":"doc.save","params":{"path":"/abs/out.png"}}' | photocraft-cli serve +``` + +The MCP server has the same batching as the `command_batch` tool (`{steps:[{id, params}], stop_on_error}`), +in headless and bridge mode. diff --git a/docs/development.md b/docs/development.md index b0b6a55555..136f995b12 100644 --- a/docs/development.md +++ b/docs/development.md @@ -92,7 +92,7 @@ Tools: - `session_list` - `doc_open`, `doc_new`, `doc_save`, `doc_export`, `doc_inspect`, `doc_render_preview` (returns a PNG image), `doc_select`, `doc_close` -- `command_list`, `command_run` +- `command_list`, `command_run`, `command_batch` (several commands per call) - bridge only: `ui_inspect`, `ui_screenshot`, `ui_pointer`, `ui_menu_invoke`, `ui_set`, `control_call` Claude Code (`.mcp.json` in the repo root, or `claude mcp add`): @@ -124,6 +124,9 @@ screenshot. `crates/automation/tests/agent_tasks.rs` is the reference: ten reali (title card, colour grade, undo/redo, editable smart blur, masks, saved selections, align, layer export, resize/crop, CMYK + native save) driven purely over MCP. +Without MCP, `photocraft-cli serve [--port N]` keeps a headless session open and answers JSON lines +(see `docs/control-protocol.md#headless-server`). + A typical agent loop: 1. `doc_open {path}`