From 244d7e02f65c060cb92d47e4ccda2df1f9fbb96f Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Fri, 6 Nov 2026 21:57:09 -0700 Subject: [PATCH] feat(cli): MCP server (anicraft-cli mcp) for AI assistants over the command registry --- AGENTS.md | 2 +- CHANGELOG.md | 4 + README.md | 3 +- crates/cli/src/lib.rs | 15 +- crates/cli/src/mcp.rs | 318 ++++++++++++++++++++++++++++++++++++++++++ docs/mcp.md | 56 ++++++++ docs/roadmap.md | 4 +- 7 files changed, 396 insertions(+), 6 deletions(-) create mode 100644 crates/cli/src/mcp.rs create mode 100644 docs/mcp.md diff --git a/AGENTS.md b/AGENTS.md index cbc67a0b..cdd93cbe 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,7 +14,7 @@ crates/render L2 CPU oracle renderer (coverage accumulation, paints, strokes, crates/xfl L2 XFL/FLA import: own XML + zip readers, edges → paths (ADR 0009) crates/svg L2 SVG import: shapes, groups, use, styles, transforms, gradients → shapes crates/engine L3 Session, undo (with gesture coalescing), command registry, .anicraft format -crates/cli L4 anicraft-cli: info/render/render-seq/commands/exec/run/new/serve +crates/cli L4 anicraft-cli: info/render/render-seq/commands/exec/run/new/serve/mcp src/ L5 egui shell (app, menus, stage, timeline, panels, theme) ``` diff --git a/CHANGELOG.md b/CHANGELOG.md index 8303d41f..b9c1ee57 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +* **AniCraft for AI assistants** (`anicraft-cli mcp`): a Model Context Protocol server, so an + assistant can open a document, draw, animate, look at frames and export, through the same + commands as the app, with undo and the same "are you sure" rules. See `docs/mcp.md`. + * **Images in Animate documents.** Opening a `.fla` or XFL now brings its bitmaps into the Library, with bitmap instances on the stage and bitmap fills on shapes (placed, scaled and tiled as in the file). Images are read when the document keeps them as PNG or JPEG (XFL diff --git a/README.md b/README.md index 8ea00003..1fec2c7a 100644 --- a/README.md +++ b/README.md @@ -135,6 +135,7 @@ cargo run -p anicraft-cli -- gif --sample --out animation.gif --fps 24 cargo run -p anicraft-cli -- commands # the registry as JSON cargo run -p anicraft-cli -- exec --sample draw.rect '{"x":10,"y":10,"w":80,"h":40}' --save out.anicraft cargo run -p anicraft-cli -- serve --sample # JSON-lines on stdin/stdout +cargo run -p anicraft-cli -- mcp --sample # MCP server for AI assistants (docs/mcp.md) ``` The `serve` protocol accepts one JSON request per line: @@ -159,7 +160,7 @@ crates/render L2 CPU oracle renderer (coverage accumulation, paints, strokes, crates/xfl L2 XFL/FLA import: own XML + zip readers, edges → paths (ADR 0009) crates/svg L2 SVG import: shapes, groups, use, styles, transforms, gradients → shapes crates/engine L3 Session, undo (with gesture coalescing), command registry, .anicraft format -crates/cli L4 anicraft-cli: info/render/render-seq/commands/exec/run/new/serve +crates/cli L4 anicraft-cli: info/render/render-seq/commands/exec/run/new/serve/mcp src/ L5 egui shell (app, menus, stage, timeline, panels, theme) ``` diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index 21a7a17f..c03c9e95 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -1,7 +1,9 @@ -//! AniCraft headless front end: argument parsing and the JSON-lines `serve` loop. -//! Every operation goes through the engine's command registry. +//! AniCraft headless front end: argument parsing, the JSON-lines `serve` loop and the MCP +//! server (`mcp`). Every operation goes through the engine's command registry. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod mcp; + use anicraft_engine::{Session, commands, format}; use serde_json::{Value, json}; use std::io::{BufRead, Write}; @@ -23,6 +25,8 @@ USAGE: anicraft-cli bench [--layers N] [--shapes N] [--frames N] performance probe (use --release) anicraft-cli serve [file|--sample] JSON-lines on stdin/stdout: {\"id\":1,\"cmd\":\"draw.rect\",\"params\":{\"x\":10,\"y\":10,\"w\":50,\"h\":50}} + anicraft-cli mcp [file|--sample] Model Context Protocol server on stdin/stdout, + for AI assistants (see docs/mcp.md) Frames on the command line are 1-based, as in the timeline."; @@ -193,6 +197,13 @@ pub fn run(argv: &[String]) -> Result { serve(&mut s, stdin.lock(), &mut stdout).map_err(|e| e.to_string())?; Ok(String::new()) } + "mcp" => { + let mut s = open_session(src)?; + let stdin = std::io::stdin(); + let mut stdout = std::io::stdout(); + mcp::serve(&mut s, stdin.lock(), &mut stdout).map_err(|e| e.to_string())?; + Ok(String::new()) + } other => Err(format!("unknown subcommand '{other}'\n\n{USAGE}")), } } diff --git a/crates/cli/src/mcp.rs b/crates/cli/src/mcp.rs new file mode 100644 index 00000000..44e3543e --- /dev/null +++ b/crates/cli/src/mcp.rs @@ -0,0 +1,318 @@ +//! `anicraft-cli mcp`: a Model Context Protocol server on stdin/stdout. +//! +//! The transport is MCP's stdio transport: JSON-RPC 2.0 messages, one per line. AI assistants +//! (any MCP client) get a handful of tools over the engine's command registry rather than one +//! tool per command: list the commands, run one or a batch, read the document, and look at a +//! frame as a picture. Everything still goes through `Session::execute`, so undo, validation +//! and the confirmation tiers (ADR 0004: `"confirm": true` before irreversible loss) apply to +//! an assistant exactly as to the app. + +use anicraft_engine::{Session, commands}; +use serde_json::{Value, json}; +use std::io::{BufRead, Write}; + +/// Protocol revisions this server speaks, newest first. +const PROTOCOLS: &[&str] = &["2025-06-18", "2025-03-26", "2024-11-05"]; + +/// Longest edge of a frame picture, in pixels (keeps replies small). +const MAX_PICTURE_EDGE: f32 = 2048.0; + +/// Most steps in one `anicraft_run_script` call. +const MAX_STEPS: usize = 10_000; + +const INSTRUCTIONS: &str = "AniCraft is a 2D animation studio. Every edit is a command: call \ +anicraft_commands to find one (filter by words such as 'tween' or 'export'), then anicraft_run \ +with its id and params, or anicraft_run_script for several in order. Frames in params are \ +0-based. Commands act on the current scene, layer, frame and selection, which anicraft_document \ +reports. Use anicraft_render to see a frame. Edits can be undone with edit.undo. Commands that \ +would lose work or replace a file refuse until params include \"confirm\": true; ask the person \ +before confirming."; + +fn tools() -> Value { + json!([ + { + "name": "anicraft_commands", + "title": "List AniCraft commands", + "description": "Lists the commands anicraft_run accepts: id, label, menu, shortcut, a summary of their params, and whether they change the document. Optionally only those whose id or label contains `filter`.", + "inputSchema": {"type": "object", "properties": {"filter": {"type": "string", "description": "Words to look for in the id or label, e.g. \"tween\" or \"export\"."}}}, + "annotations": {"readOnlyHint": true, "openWorldHint": false} + }, + { + "name": "anicraft_run", + "title": "Run an AniCraft command", + "description": "Runs one command (see anicraft_commands) with its params and returns its result, plus the document revision and current frame. Commands that would lose work or replace a file need \"confirm\": true in params.", + "inputSchema": { + "type": "object", + "properties": { + "command": {"type": "string", "description": "Command id, e.g. \"draw.rect\"."}, + "params": {"type": "object", "description": "The command's params, e.g. {\"x\": 10, \"y\": 10, \"w\": 50, \"h\": 50}."} + }, + "required": ["command"] + }, + "annotations": {"readOnlyHint": false, "destructiveHint": true, "idempotentHint": false, "openWorldHint": false} + }, + { + "name": "anicraft_run_script", + "title": "Run several AniCraft commands", + "description": "Runs commands in order and returns each result. Stops at the first error and says which step failed; the steps before it stay done (undo them with edit.undo).", + "inputSchema": { + "type": "object", + "properties": { + "steps": { + "type": "array", + "items": {"type": "object", "properties": {"command": {"type": "string"}, "params": {"type": "object"}}, "required": ["command"]} + } + }, + "required": ["steps"] + }, + "annotations": {"readOnlyHint": false, "destructiveHint": true, "idempotentHint": false, "openWorldHint": false} + }, + { + "name": "anicraft_document", + "title": "Describe the document", + "description": "The open document: stage size and frame rate, scenes, the current scene's layers and keyframes, library symbols, and the current scene, frame, layer and selection.", + "inputSchema": {"type": "object", "properties": {}}, + "annotations": {"readOnlyHint": true, "openWorldHint": false} + }, + { + "name": "anicraft_render", + "title": "Look at a frame", + "description": "A frame of the current scene as a PNG picture, exactly as exported. `frame` is 0-based (default: the current frame); `scale` defaults to 0.5 of the stage size.", + "inputSchema": { + "type": "object", + "properties": { + "frame": {"type": "integer", "minimum": 0}, + "scale": {"type": "number", "exclusiveMinimum": 0, "maximum": 4} + } + }, + "annotations": {"readOnlyHint": true, "openWorldHint": false} + } + ]) +} + +/// A JSON-RPC error object. +fn error(id: Value, code: i64, message: impl Into) -> Value { + json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message.into()}}) +} + +fn text_result(v: &Value, is_error: bool) -> Value { + let text = if let Value::String(s) = v { s.clone() } else { serde_json::to_string_pretty(v).unwrap_or_default() }; + json!({"content": [{"type": "text", "text": text}], "isError": is_error}) +} + +/// Runs one tool. Tool failures are results with `isError` (so the assistant can read and +/// correct them); only malformed calls are protocol errors. +fn call_tool(s: &mut Session, name: &str, args: &Value) -> Result { + let run = |s: &mut Session, step: &Value| -> Result { + let id = step.get("command").and_then(Value::as_str).ok_or("missing \"command\"")?; + let params = step.get("params").cloned().unwrap_or_else(|| json!({})); + if !params.is_object() { + return Err(format!("{id}: \"params\" must be an object")); + } + s.execute(id, ¶ms).map_err(|e| format!("{id}: {e}")) + }; + Ok(match name { + "anicraft_commands" => { + let filter = args.get("filter").and_then(Value::as_str).unwrap_or("").to_lowercase(); + let words: Vec<&str> = filter.split_whitespace().collect(); + let list: Vec = commands() + .iter() + .filter(|c| { + let hay = format!("{} {}", c.id, c.label).to_lowercase(); + words.iter().all(|w| hay.contains(w)) + }) + .map(|c| c.to_json()) + .collect(); + text_result(&Value::Array(list), false) + } + "anicraft_run" => match run(s, args) { + Ok(v) => text_result(&json!({"result": v, "revision": s.revision, "frame": s.frame, "scene": s.scene}), false), + Err(e) => text_result(&Value::String(e), true), + }, + "anicraft_run_script" => { + let steps = args.get("steps").and_then(Value::as_array).ok_or("\"steps\" must be an array")?; + if steps.len() > MAX_STEPS { + return Err(format!("at most {MAX_STEPS} steps per call")); + } + let mut results = Vec::with_capacity(steps.len()); + for (i, step) in steps.iter().enumerate() { + match run(s, step) { + Ok(v) => results.push(v), + Err(e) => return Ok(text_result(&json!({"failed_step": i + 1, "error": e, "done": results}), true)), + } + } + text_result(&json!({"results": results, "revision": s.revision, "frame": s.frame}), false) + } + "anicraft_document" => text_result(&s.info(), false), + "anicraft_render" => { + let frame = match args.get("frame") { + None | Some(Value::Null) => s.frame, + Some(v) => v.as_u64().and_then(|f| u32::try_from(f).ok()).ok_or("\"frame\" must be a whole number from 0")?, + }; + if frame >= s.frame_count() { + return Ok(text_result(&Value::String(format!("frame {frame} is past the end: the scene has {} frames (0 to {})", s.frame_count(), s.frame_count().saturating_sub(1))), true)); + } + let stage = s.doc.stage; + let largest = stage.width.max(stage.height).max(1) as f32; + let scale = match args.get("scale") { + None | Some(Value::Null) => 0.5, + Some(v) => v.as_f64().filter(|x| x.is_finite() && *x > 0.0 && *x <= 4.0).ok_or("\"scale\" must be a number above 0, up to 4")? as f32, + }; + let scale = scale.min(MAX_PICTURE_EDGE / largest); + let movie_frame = s.doc.scene_start(s.scene).saturating_add(frame); + let png = anicraft_render::render_frame(&s.doc, movie_frame, scale).and_then(|p| p.encode_png()).map_err(|e| e.to_string())?; + json!({ + "content": [ + {"type": "image", "data": anicraft_doc::base64_encode(&png), "mimeType": "image/png"}, + {"type": "text", "text": format!("Frame {frame} of scene {} at {:.0}% ({}×{} stage).", s.scene, scale * 100.0, stage.width, stage.height)} + ], + "isError": false + }) + } + other => return Err(format!("unknown tool '{other}'")), + }) +} + +/// Answers one JSON-RPC message; `None` for notifications (and responses), which get no reply. +pub fn handle(s: &mut Session, line: &str) -> Option { + let msg: Value = match serde_json::from_str(line.trim_start_matches('\u{feff}')) { + Ok(v) => v, + Err(e) => return Some(error(Value::Null, -32700, format!("parse error: {e}"))), + }; + if !msg.is_object() { + return Some(error(Value::Null, -32600, "expected a JSON-RPC request object")); + } + let method = msg.get("method").and_then(Value::as_str); + let Some(id) = msg.get("id").cloned().filter(|v| !v.is_null()) else { + // Notifications (`notifications/initialized`, `notifications/cancelled`) and replies to + // requests we never send: nothing to answer. + return None; + }; + let Some(method) = method else { return Some(error(id, -32600, "missing \"method\"")) }; + let params = msg.get("params").cloned().unwrap_or_else(|| json!({})); + let result = match method { + "initialize" => { + let asked = params.get("protocolVersion").and_then(Value::as_str).unwrap_or(""); + let version = PROTOCOLS.iter().find(|v| **v == asked).copied().unwrap_or(PROTOCOLS[0]); + json!({ + "protocolVersion": version, + "capabilities": {"tools": {"listChanged": false}}, + "serverInfo": {"name": "anicraft", "title": "AniCraft", "version": env!("CARGO_PKG_VERSION")}, + "instructions": INSTRUCTIONS + }) + } + "ping" => json!({}), + "tools/list" => json!({"tools": tools()}), + "tools/call" => { + let Some(name) = params.get("name").and_then(Value::as_str) else { return Some(error(id, -32602, "tools/call needs a tool \"name\"")) }; + let args = params.get("arguments").cloned().unwrap_or_else(|| json!({})); + match call_tool(s, name, &args) { + Ok(v) => v, + Err(e) => return Some(error(id, -32602, e)), + } + } + other => return Some(error(id, -32601, format!("method not found: {other}"))), + }; + Some(json!({"jsonrpc": "2.0", "id": id, "result": result})) +} + +/// The stdio loop: one message per line in, one reply per line out, until stdin closes. +/// Nothing but protocol messages is written to `out` (logs would corrupt the stream). +pub fn serve(s: &mut Session, input: R, out: &mut W) -> std::io::Result<()> { + for line in input.lines() { + let line = line?; + if line.trim().is_empty() { + continue; + } + if let Some(reply) = handle(s, &line) { + writeln!(out, "{reply}")?; + out.flush()?; + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn call(s: &mut Session, id: u64, method: &str, params: Value) -> Value { + handle(s, &json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}).to_string()).unwrap() + } + + fn tool(s: &mut Session, name: &str, args: Value) -> Value { + call(s, 9, "tools/call", json!({"name": name, "arguments": args}))["result"].clone() + } + + fn text(result: &Value) -> Value { + serde_json::from_str(result["content"][0]["text"].as_str().unwrap()).unwrap_or_else(|_| result["content"][0]["text"].clone()) + } + + #[test] + fn handshake_lists_tools_and_ignores_notifications() { + let mut s = Session::default(); + let init = call(&mut s, 1, "initialize", json!({"protocolVersion": "2025-03-26", "capabilities": {}, "clientInfo": {"name": "t", "version": "1"}})); + assert_eq!(init["result"]["protocolVersion"], "2025-03-26", "a version we speak is echoed"); + assert_eq!(init["result"]["serverInfo"]["name"], "anicraft"); + let newer = call(&mut s, 2, "initialize", json!({"protocolVersion": "2099-01-01"})); + assert_eq!(newer["result"]["protocolVersion"], PROTOCOLS[0], "otherwise our newest"); + assert!(handle(&mut s, r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#).is_none()); + assert_eq!(call(&mut s, 3, "ping", json!({}))["result"], json!({})); + let names: Vec = call(&mut s, 4, "tools/list", json!({}))["result"]["tools"].as_array().unwrap().iter().map(|t| t["name"].as_str().unwrap().to_string()).collect(); + assert_eq!(names, ["anicraft_commands", "anicraft_run", "anicraft_run_script", "anicraft_document", "anicraft_render"]); + // Protocol errors carry JSON-RPC codes. + assert_eq!(call(&mut s, 5, "nope", json!({}))["error"]["code"], -32601); + assert_eq!(handle(&mut s, "{oops").unwrap()["error"]["code"], -32700); + assert_eq!(call(&mut s, 6, "tools/call", json!({"name": "nope"}))["error"]["code"], -32602); + } + + #[test] + fn tools_drive_the_engine() { + let mut s = Session::default(); + let found = text(&tool(&mut s, "anicraft_commands", json!({"filter": "shape tween"}))); + assert!(found.as_array().unwrap().iter().any(|c| c["id"] == "timeline.create_shape_tween"), "{found}"); + let r = tool(&mut s, "anicraft_run", json!({"command": "draw.rect", "params": {"x": 10, "y": 10, "w": 50, "h": 40, "fill": "#ff0000"}})); + assert_eq!(r["isError"], false); + assert_eq!(s.visible_elements().len(), 1); + // A failing command is a tool result the assistant can read, not a protocol error. + let bad = tool(&mut s, "anicraft_run", json!({"command": "draw.rect", "params": {"x": "left"}})); + assert_eq!(bad["isError"], true); + assert!(bad["content"][0]["text"].as_str().unwrap().starts_with("draw.rect:")); + // Scripts run in order and stop at the first failure. + let script = tool(&mut s, "anicraft_run_script", json!({"steps": [ + {"command": "draw.ellipse", "params": {"x": 100, "y": 10, "w": 30, "h": 30}}, + {"command": "no.such"}, + {"command": "draw.ellipse", "params": {"x": 200, "y": 10, "w": 30, "h": 30}} + ]})); + assert_eq!(script["isError"], true); + assert_eq!(text(&script)["failed_step"], 2); + assert_eq!(s.visible_elements().len(), 2, "the step before the failure stays done"); + // Confirmation tiers apply: discarding unsaved work needs "confirm". + assert_eq!(tool(&mut s, "anicraft_run", json!({"command": "file.new"}))["isError"], true); + let doc = text(&tool(&mut s, "anicraft_document", json!({}))); + assert_eq!(doc["stage"]["width"], s.doc.stage.width); + } + + #[test] + fn render_returns_a_png_picture() { + let mut s = Session::new(anicraft_doc::sample::demo()); + let r = tool(&mut s, "anicraft_render", json!({"frame": 3, "scale": 0.25})); + assert_eq!(r["content"][0]["type"], "image"); + assert_eq!(r["content"][0]["mimeType"], "image/png"); + assert!(r["content"][0]["data"].as_str().unwrap().starts_with("iVBORw0KGgo"), "base64 of the PNG signature"); + assert_eq!(tool(&mut s, "anicraft_render", json!({"frame": 1_000_000}))["isError"], true); + assert_eq!(call(&mut s, 7, "tools/call", json!({"name": "anicraft_render", "arguments": {"scale": -1}}))["error"]["code"], -32602); + } + + #[test] + fn stdio_loop_answers_requests_only() { + let mut s = Session::default(); + let input = b"\xef\xbb\xbf{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"ping\"}\n\n{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}\n{\"jsonrpc\":\"2.0\",\"id\":\"b\",\"method\":\"tools/list\"}\n"; + let mut out = Vec::new(); + serve(&mut s, &input[..], &mut out).unwrap(); + let lines: Vec = String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect(); + assert_eq!(lines.len(), 2); + assert_eq!(lines[0]["id"], 1); + assert_eq!(lines[1]["id"], "b"); + } +} diff --git a/docs/mcp.md b/docs/mcp.md new file mode 100644 index 00000000..ce1a3be1 --- /dev/null +++ b/docs/mcp.md @@ -0,0 +1,56 @@ +# AniCraft for AI assistants (MCP) + +`anicraft-cli mcp` is a [Model Context Protocol](https://modelcontextprotocol.io) server. Any +MCP client (an AI assistant, an editor, a script) can then open a document, draw, animate, +look at frames and export through the same commands the app uses. + +```sh +anicraft-cli mcp # a new, empty document +anicraft-cli mcp scene.anicraft # open a document +anicraft-cli mcp --sample # the sample animation +``` + +The server talks MCP's stdio transport: JSON-RPC 2.0, one message per line on stdin and stdout. +It speaks protocol revisions 2025-06-18, 2025-03-26 and 2024-11-05. + +## Connecting a client + +Most clients take a server entry like this one (use the full path to `anicraft-cli`): + +```json +{ + "mcpServers": { + "anicraft": { + "command": "/path/to/anicraft-cli", + "args": ["mcp", "/path/to/scene.anicraft"] + } + } +} +``` + +## Tools + +| Tool | What it does | +|---|---| +| `anicraft_commands` | Lists the commands (id, label, menu, shortcut, params), optionally filtered by words such as `tween` or `export`. | +| `anicraft_run` | Runs one command with its params. | +| `anicraft_run_script` | Runs several commands in order; stops at the first error and says which step failed. | +| `anicraft_document` | Describes the document: stage, scenes, layers and keyframes, library, and the current scene, frame, layer and selection. | +| `anicraft_render` | Returns a frame of the current scene as a PNG picture, exactly as exported. | + +The assistant sees one tool per job, not one per command: the command list is long and grows +with every release, and `anicraft_commands` lets it find what it needs. Frames in params are +0-based, as everywhere in the engine (the CLI's own `--frame` flags are 1-based, as in the +timeline). + +## Safety + +* Everything runs through the engine's commands, so params are checked and every edit can be + undone with `edit.undo`. +* Commands that would lose unsaved work or replace a file refuse until their params include + `"confirm": true` (ADR 0004). The server's instructions ask the assistant to check with you + before confirming. +* Commands read and write files with your permissions, at the paths the assistant gives (open, + save, import, export), as with the CLI. Only connect clients you trust with those files. +* A failing command comes back as a tool result marked as an error, so the assistant can read + the message and try again; it never stops the server. diff --git a/docs/roadmap.md b/docs/roadmap.md index 112b0763..cc477578 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -12,7 +12,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | Rendering | CPU oracle with analytic AA, non-zero/even-odd, solid + linear/radial gradients, round-join strokes. **Mask clipping**: the display list carries nested clips; a clip is the anti-aliased union of its mask fills (strokes and opacity ignored), intersected with any enclosing clip, computed once per render band; an empty mask hides everything under it. **Group alpha**: a symbol instance below full opacity is a group in the display list; each render band composites the group's run of ops into its own buffer (nested groups stack) and blends it once at the group's alpha, so overlaps don't show through; SVG export writes ``. **Bitmaps**: `Paint::Bitmap` fills (once or tiled) with bilinear sampling in premultiplied space, colour effects per sample; PNG/JPEG import to stage (a rectangle of the image's size); stored in the document as PNG (base64 in `.anicraft`), decoded once on first use; SVG export embeds each image once as a pattern. No GPU path, filters or text yet. | | Timeline | **Frame selection**: click, Shift-click or drag across frames and layers; F5/Shift+F5, F6/F7 and Shift+F6 (keys, buttons and right-click menu) act on the whole selection; drag selected keyframes left or right to move them, and up or down onto other layers (the source keeps empty frames, as in Animate) (with a drop outline; one undo step; keys they land on are replaced, and spans fill the frames left behind); removing or clearing selected frames that hold artwork asks first. **Cut/Copy/Paste Frames** (Ctrl+Alt+X/C/V, and plain Ctrl+X/C/V after clicking the timeline): own clipboard, copies cut exactly at the selection edges (mid-tween state kept), paste inserts like Animate, several layers paste onto the layers below (missing ones are created), fresh element ids, symbols travel with them. **Span length by dragging its end** (resize cursor, live outline with the length in frames and seconds; later frames move with it). Headless: `layers`/`count` on the frame commands, `timeline.move_keyframes`, `timeline.cut_frames/copy_frames/paste_frames`. Layers (show/lock/outline), keyframes, blank keyframes, insert/remove frames, classic tweens with 8 easing presets + curve preview, **shape tweens** (morph between any two shapes: segments made cubic, subpaths paired by size and grown from or shrunk to a point when counts differ, segment counts equalized by subdivision, windings matched and start points aligned; amber spans; classic ⇄ shape keeps the easing), auto-key when editing inside a tween, frame labels, symbol nesting: graphics keep step with their timeline (loop, play once, single frame, first frame; set in Properties), movie clips loop their own timeline from when the instance appears (continuous across keyframes holding the same instance), buttons show their Up frame, onion skin (±2 frames), looping playback. **Mask layers**: right-click a layer › Mask turns it into a mask over the layer below (Masked adds more layers to it); masked layers are indented under a stencil icon; the mask applies on the stage and in every export alike, and while the mask layer is unlocked its edge shows in the layer colour so it can be picked and reshaped; masked-away parts cannot be picked; layers moved in under a mask join it, moved out leave it, and a mask moves with its whole group; masks inside symbols nest. Headless: `layer.toggle_mask`, `layer.set_type`. **Scenes** (ADR 0011): the movie is an ordered list of scenes, each its own timeline, edited one at a time (scene menu on the edit bar, Insert › Scene, Modify › Scene, Shift+PageUp/PageDown); add, duplicate (fresh ids), rename, reorder and remove (asks when the scene has artwork; undoable); PNG-sequence and GIF exports play every scene in order. **Layer folders**: nestable folders (depth ≤ 16) holding layers and masks through `Layer.parent`, one invariant (`Timeline::repair_masks`: a child sits below its parent inside the parent's unbroken run; broken links fall back to the nearest valid ancestor); hiding or locking a folder hides or locks its contents (rendering, picking, drawing); folders open and close on the timeline (view state); layers move in and out with Up/Down, a folder moves with its contents; deleting a folder deletes its contents (asks first). No motion editor yet; **motion guides**: guided layers (children of a guide through `Layer.parent`) have their classic tweens follow the guide's first path by arc length, from the point nearest each start keyframe to the point nearest its end (`geom::walk::PathWalk`), optionally orienting to the path; guide artwork is listed for picking and editing, drawn on the stage as a line, and never rendered or exported. | | Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. No brush or merge drawing yet. | -| Headless | CLI: info, render, render-seq, **gif**, commands, exec, run, serve (JSON-lines). No MCP yet. | +| Headless | CLI: info, render, render-seq, **gif**, commands, exec, run, serve (JSON-lines). **MCP server** (`anicraft-cli mcp`, `docs/mcp.md`): stdio JSON-RPC, protocol 2025-06-18 (and 2025-03-26, 2024-11-05); five tools over the command registry (list, run, run a script, describe the document, render a frame as a PNG picture); confirmation tiers and undo apply as in the app. | | Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. Every scene comes across. **Bitmaps**: library items whose image is in the package as PNG or JPEG (the original in `LIBRARY/`, else the `bin/` data file when it is PNG or JPEG), instances, and bitmap fills with their matrix (twips scale removed; repeating unless clipped); Animate's own bitmap encodings are not public and are reported, not decoded. No text, motion tweens or shape hints from XFL yet; **Import to Stage (Ctrl+R) for SVG drawings**: editable shapes on a new layer at the playhead, with groups, use and symbols, transforms, viewBox, styles, opacity and gradients; unsupported parts are reported. **Sprite sheet export**: movie frames on one PNG grid (parallel render, columns/padding/scale, transparent or stage background) with a "JSON hash" frame map (rectangles, sizes, per-frame durations). **Video export**: WebM (VP9) or MP4 (H.264) by streaming raw frames, in order and rendered in parallel batches, to the user's own ffmpeg (no encoder bundled; ffmpeg from a parameter, `ANICRAFT_FFMPEG` or the PATH; argument lists, never a shell). No Lottie yet. | | Tests | 133 tests (adds point editing, closed-path anchors, curve fitting, pen/pencil/subselection commands, the Pen's path data, frame ranges, keyframe moves, range confirmations, frame selection and the frame clipboard): unit, analytic render, band/determinism, robustness fuzz over all commands, round trip (v1 and v2 files), structural sharing and history budget, render-service equivalence, confirmations, clipboard, transforms and align, GIF decode and timing, free-transform maths, UI-guideline enforcement, CLI. | | Ease of use & safety | **Visual language** (ADR 0008, revised): graphite palette, corners by role (square structure, softened controls, rounder menus and dialogs with soft depth), borders only between layout regions, flat buttons with a visible focus ring, vibrant timeline blocks (mint artwork, violet tweens), sentence-case headings, **collapsible sections with rules** (Preferences, Properties, dock, shortcut sheet), **Lucide icons** stroked as vectors via a new full SVG path reader; click targets ≥ 28 px (tools 40, rows 28, toggles 24); palette contrast, target sizes and "no raw colours or radii" are enforced by tests. Product principles written (`docs/product-principles.md`). Tiered destructive-action confirmations, enforced in the engine (ADR 0004). Unsaved-changes guard on close/new/open. Overwrite checks for saves and exports. "Ctrl+Z to undo" hints. Command palette (Ctrl+K). Shortcut sheet (F1). Right-click menus on stage, frames and layers. Save As (Ctrl+Shift+S). **Shortcut editor** (F1): every menu command, tool and view key can be rebound, given extra keys or unbound; recording asks before taking a key from another action, reserved keys (palette, editor, Preferences, quit, play, Esc, Space, Tab) stay fixed, per-action and global reset; only the changes are saved in preferences, so untouched actions follow new defaults; menus, tooltips and the palette show the keys in effect. | @@ -26,7 +26,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a |---|---|---| | **M0** | Foundations *(this version)* | Workspace + layering; document model; timeline evaluation with classic tweens and easing; CPU oracle renderer; command registry with undo; `.anicraft`; CLI render + JSON-lines; egui shell with stage, tools, timeline, properties, library; `--screenshot`. | | **M1** | Authoring core ✅ *(v0.1.0)* | ~~Free transform tool with handles~~ ✅; ~~subselection and Bézier point editing~~ ✅; ~~Pen and Pencil~~ ✅; ~~Paint bucket / Ink bottle~~ ✅; ~~copy/paste~~ ✅, ~~duplicate, arrange~~ ✅, ~~align~~ ✅ (commands and menus; and the dock's Align panel ✅); ~~onion skin~~ ✅ (basic); ~~frame selection ranges in the timeline (multi-frame insert/remove/move keyframes by drag)~~ ✅ (including between layers); ~~PNG sequence + animated GIF export~~ ✅; ~~keyboard shortcut map editor~~ ✅. | -| **M2** | Model at scale | ~~`Arc` structural sharing (O(changed) undo)~~ done early (ADR 0001); ~~scenes~~ ✅ (ADR 0011); ~~layer folders~~ ✅, ~~guide and motion-guide layers~~ ✅; ~~mask layers~~ ✅; ~~Movie Clip and Button behaviours~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅ (shape hints still to do); motion tween + Motion Editor curves; MCP server; perf budgets (criterion) with CI enforcement; ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). | +| **M2** | Model at scale | ~~`Arc` structural sharing (O(changed) undo)~~ done early (ADR 0001); ~~scenes~~ ✅ (ADR 0011); ~~layer folders~~ ✅, ~~guide and motion-guide layers~~ ✅; ~~mask layers~~ ✅; ~~Movie Clip and Button behaviours~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅ (shape hints still to do); motion tween + Motion Editor curves; ~~MCP server~~ ✅; perf budgets (criterion) with CI enforcement; ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). | | **M3** | GPU stage | wgpu renderer (sparse-strip coverage, tile binning, gradient ramps in a texture atlas) behind a feature flag; per-pixel parity tests vs the CPU oracle; becomes the default stage renderer once parity ≤ 1/255 mean error; 4K playback at 60 fps for 1,000 shapes. | | **M4** | Interchange *(in progress)* | **XFL import** (DOMDocument.xml, symbols, edges/fill styles decoded from the public format descriptions) with a corpus of self-authored files: first slice ✅ (see Files above); ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; Lottie export; ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅. | | **M5** | Rich media | Text engine (shaping via rustybuzz, glyph atlas); ~~bitmap import and bitmap fills~~ ✅; audio layers (symphonia + cpal), waveform display, stream sync; filters (blur, drop shadow, glow, colour matrix) and blend modes on Movie Clips. |