M14.1: MCP server + agent CLI

- crates/automation (L5, no egui): hand-rolled JSON-RPC 2.0 MCP server over
  stdio (initialize, ping, tools/list, tools/call); headless backend (in-process
  Session) and bridge backend (desktop control channel). Tools: list_commands,
  execute_command, get_project/comp/layer, get/set_property, add_keyframe,
  render_frame (inline PNG), open/save_project, undo/redo; bridge-only
  screenshot, ui_* and raw control passthrough.
- effectcraft-cli: info, commands, exec, run, props, get, set, render-frame,
  mcp [--bridge PORT]; --json, --project/--demo/--empty, --save/--save-as.
- engine: prop.get, layer.tree node paths + time, Session::resolve_comp,
  render_rgba8, execute_checked (rejects unknown params, lists accepted keys).
- control channel: render.frame; engine.execute runs every engine command
  directly (no dialogs, validated params).
- docs: control-protocol.md, agents.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Brandon Thomas
2026-10-01 21:40:31 -04:00
co-authored by Claude Opus 5.5
parent dee16181fe
commit c672e03160
22 changed files with 2398 additions and 101 deletions
+2 -2
View File
@@ -205,7 +205,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New Composition…",
["Composition"],
Some("Cmd+N"),
"{name?, width?, height?, frameRate?, duration? (s), background? [r,g,b]|#hex, open?}",
"{name?, width?, height?, frameRate?, duration? (s), background? [r,g,b]|#hex, pixelAspect?, open?}",
always,
new_comp
),
@@ -214,7 +214,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Composition Settings…",
["Composition"],
Some("Cmd+K"),
"{comp?, name?, width?, height?, frameRate?, duration?, background?, shutterAngle?, shutterPhase?, motionBlurSamples?}",
"{comp?, name?, width?, height?, frameRate?, duration?, background?, shutterAngle?, shutterPhase?, motionBlurSamples?, pixelAspect?}",
has_comp,
settings
),
+60 -1
View File
@@ -81,6 +81,65 @@ pub fn find(id: &str) -> Option<&'static CommandSpec> {
command_specs().iter().find(|c| c.id == id)
}
// ---------- parameter validation (agents) ----------
/// Top-level keys accepted by a params doc such as `{layers: [id|name|#n], add?, toggle?}` or
/// `{time? (s) | frame? | timecode?}`; `None` when the doc isn't a `{…}` key list.
pub fn accepted_params(doc: &str) -> Option<Vec<String>> {
let body = doc.trim().strip_prefix('{')?;
// Top-level pieces up to the matching close brace, split at `,` and `|`; `:` starts a value.
let (mut keys, mut cur, mut depth, mut in_value) = (Vec::new(), String::new(), 0i32, false);
let push = |cur: &mut String, keys: &mut Vec<String>| {
let k: String = cur.trim().chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '_').collect();
if !k.is_empty() && !keys.contains(&k) {
keys.push(k);
}
cur.clear();
};
for c in body.chars() {
match c {
'{' | '[' | '(' => depth += 1,
']' | ')' => depth -= 1,
'}' if depth == 0 => {
push(&mut cur, &mut keys);
return Some(keys);
}
'}' => depth -= 1,
',' if depth == 0 => {
push(&mut cur, &mut keys);
in_value = false;
}
'|' if depth == 0 && !in_value => push(&mut cur, &mut keys),
':' if depth == 0 => {
push(&mut cur, &mut keys);
in_value = true;
}
_ if depth == 0 && !in_value => cur.push(c),
_ => {}
}
}
None
}
/// Keys every command understands (comp targeting, gesture merging) and accepted aliases.
const ALWAYS_OK: &[&str] = &["comp", "merge"];
const ALIASES: &[(&str, &str)] = &[("layers", "layer"), ("layer", "layers"), ("time", "frame"), ("frameRate", "fps"), ("properties", "property")];
/// Reject unknown top-level parameters (typos, guessed names) with the list of accepted keys.
pub fn check_params(spec: &CommandSpec, params: &Value) -> Result<()> {
let (Some(obj), Some(accepted)) = (params.as_object(), accepted_params(spec.params)) else { return Ok(()) };
let ok = |k: &str| ALWAYS_OK.contains(&k) || accepted.iter().any(|a| a == k || ALIASES.iter().any(|(doc, alias)| doc == a && *alias == k));
let unknown: Vec<&str> = obj.keys().map(String::as_str).filter(|k| !ok(k)).collect();
if unknown.is_empty() {
return Ok(());
}
let list = if accepted.is_empty() { "none".to_string() } else { accepted.join(", ") };
Err(bad(
spec.id,
format!("unknown parameter(s) {}; accepted: {list} (doc: {})", unknown.iter().map(|k| format!("`{k}`")).collect::<Vec<_>>().join(", "), spec.params),
))
}
// ---------- enablement ----------
pub fn always(_: &Session) -> std::result::Result<(), String> {
@@ -182,6 +241,6 @@ pub(crate) fn time_p(s: &Session, p: &Value, comp: Option<&Comp>) -> Tick {
s.time()
}
pub(crate) fn layer_mut<'a>(p: &'a mut effectcraft_project::Project, cid: ItemId, lid: LayerId) -> Result<&'a mut Layer> {
pub(crate) fn layer_mut(p: &mut effectcraft_project::Project, cid: ItemId, lid: LayerId) -> Result<&mut Layer> {
p.comp_mut(cid).ok_or(EngineError::NoComp)?.layer_mut(lid).ok_or(EngineError::Project(effectcraft_project::ProjectError::NoLayer(lid)))
}
+17 -1
View File
@@ -6,7 +6,7 @@ use effectcraft_time::Tick;
use serde_json::{Value, json};
use super::{CommandSpec, b_p, bad, f_p, has_comp, has_keys, has_layers, layer_mut, layer_p, merge_p, str_p};
use crate::{EngineError, KeyRef, Result, Session, cmd};
use crate::{EngineError, KeyRef, Result, Session, cmd, query};
/// Resolve `{layer, path}` (or `{layer, prop: uid}`) to (comp, layer, prop uid).
fn prop_ref(s: &Session, p: &Value, cmd: &str) -> Result<(ItemId, LayerId, Uid)> {
@@ -57,6 +57,21 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
Ok(out)
}
/// Read one property: value at `time` (comp seconds, default the CTI), keyframes and expression.
fn get(s: &mut Session, p: &Value) -> Result<Value> {
let (cid, lid, uid) = prop_ref(s, p, "prop.get")?;
let l = s.project.comp(cid).and_then(|c| c.layer(lid)).ok_or(EngineError::NoComp)?;
let pr = l.props.find(uid).ok_or_else(|| bad("prop.get", "property vanished"))?;
let t = f_p(p, "time").map(Tick::from_seconds_f64).unwrap_or_else(|| s.time());
let keys: Vec<Value> =
pr.keys.iter().map(|k| json!({"time": k.time.seconds(), "value": k.value.to_json(), "in": k.in_interp.label(), "out": k.out_interp.label()})).collect();
Ok(json!({
"layer": lid.0, "uid": pr.uid, "match": pr.match_id, "name": pr.name, "type": pr.value.kind_name(),
"time": t.seconds(), "value": pr.value_at(l.layer_time(t)).to_json(), "animated": !pr.keys.is_empty(),
"keys": keys, "expression": pr.expr.as_ref().map(|e| e.text.clone()),
}))
}
fn toggle_anim(s: &mut Session, p: &Value) -> Result<Value> {
let (cid, lid, uid) = prop_ref(s, p, "prop.toggleAnimation")?;
let on = b_p(p, "value");
@@ -404,6 +419,7 @@ fn convert_expr_to_keys(s: &mut Session, p: &Value) -> Result<Value> {
pub fn specs() -> Vec<CommandSpec> {
vec![
query!("prop.get", "Get Property", "{layer?, path|prop, time? (comp s)}", get),
cmd!("prop.set", "Set Property Value", [], None, "{layer?, path|prop, value, time?, merge?}", has_layers, set),
cmd!("prop.toggleAnimation", "Toggle Stopwatch", [], None, "{layer?, path|prop, value?}", has_layers, toggle_anim),
cmd!("prop.addKey", "Add Keyframe", [], None, "{layer?, path|prop, time?, value?}", has_layers, add_key),
+39 -19
View File
@@ -76,33 +76,51 @@ fn comp_info(s: &mut Session, p: &Value) -> Result<Value> {
}))
}
fn group_json(g: &PropGroup, l: &Layer, t: effectcraft_time::Tick, depth: usize, max_depth: usize) -> Value {
/// The path segment that addresses child `i` of `g` (see `effectcraft_project::parse_path`): the match
/// id (with `#n` when it is not the first sibling matching it), or `#index` when the match id is not
/// path-safe (effects and other ids containing `.`).
fn segment(g: &PropGroup, i: usize) -> String {
let c = &g.children[i];
let m = c.match_id();
if m.is_empty() || m.contains(['/', '.', '#', '@']) || m.parse::<u64>().is_ok() {
return format!("#{}", i + 1);
}
let n = g.children[..i].iter().filter(|x| x.match_id() == m || x.name().eq_ignore_ascii_case(m)).count() + 1;
if n == 1 { m.to_string() } else { format!("{m}#{n}") }
}
fn group_json(g: &PropGroup, path: &str, l: &Layer, t: effectcraft_time::Tick, depth: usize, max_depth: usize) -> Value {
let children: Vec<Value> = if depth >= max_depth {
vec![]
} else {
g.children
.iter()
.map(|c| match c {
Node::Prop(p) => {
let mut o = json!({"uid": p.uid, "match": p.match_id, "name": p.name, "value": p.value_at(l.layer_time(t)).to_json()});
if !p.keys.is_empty() {
o["keys"] = json!(
p.keys
.iter()
.map(|k| json!({"time": k.time.seconds(), "value": k.value.to_json(), "in": k.in_interp.label(), "out": k.out_interp.label()}))
.collect::<Vec<_>>()
);
.enumerate()
.map(|(i, c)| {
let seg = segment(g, i);
let cpath = if path.is_empty() { seg } else { format!("{path}/{seg}") };
match c {
Node::Prop(p) => {
let mut o = json!({"path": cpath, "uid": p.uid, "match": p.match_id, "name": p.name, "type": p.value.kind_name(), "value": p.value_at(l.layer_time(t)).to_json()});
if !p.keys.is_empty() {
o["keys"] = json!(
p.keys
.iter()
.map(|k| json!({"time": k.time.seconds(), "value": k.value.to_json(), "in": k.in_interp.label(), "out": k.out_interp.label()}))
.collect::<Vec<_>>()
);
}
if let Some(e) = &p.expr {
o["expression"] = json!(e.text);
}
o
}
if let Some(e) = &p.expr {
o["expression"] = json!(e.text);
}
o
Node::Group(g) => group_json(g, &cpath, l, t, depth + 1, max_depth),
}
Node::Group(g) => group_json(g, l, t, depth + 1, max_depth),
})
.collect()
};
let mut o = json!({"uid": g.uid, "match": g.match_id, "name": g.name, "enabled": g.enabled, "children": children});
let mut o = json!({"path": path, "uid": g.uid, "match": g.match_id, "name": g.name, "enabled": g.enabled, "children": children});
match &g.kind {
GroupKind::Mask { mode, inverted, .. } => {
o["mask"] = json!({"mode": mode.label(), "inverted": inverted});
@@ -121,8 +139,10 @@ fn layer_tree(s: &mut Session, p: &Value) -> Result<Value> {
let idx = c.index_of(lid).unwrap_or(0);
let l = c.layer(lid).ok_or(EngineError::NoComp)?;
let depth = p.get("depth").and_then(Value::as_u64).unwrap_or(16) as usize;
let t = p.get("time").and_then(Value::as_f64).map(effectcraft_time::Tick::from_seconds_f64).unwrap_or_else(|| s.time());
let mut o = layer_json(l, idx);
o["properties"] = group_json(&l.props, l, s.time(), 0, depth);
o["time"] = json!(t.seconds());
o["properties"] = group_json(&l.props, "", l, t, 0, depth);
Ok(o)
}
@@ -135,7 +155,7 @@ pub fn specs() -> Vec<CommandSpec> {
query!("command.list", "List Commands", "{filter?, enabledOnly?}", list),
query!("project.summary", "Project Summary", "{}", summary),
query!("comp.info", "Composition Info", "{comp?}", comp_info),
query!("layer.tree", "Layer Property Tree", "{layer?, depth?}", layer_tree),
query!("layer.tree", "Layer Property Tree", "{layer?, comp?, depth?, time? (comp s)} → nodes with `path`", layer_tree),
query!("editor.state", "Editor State", "{}", state),
]
}
+27
View File
@@ -181,6 +181,14 @@ impl Session {
Ok(r)
}
/// [`Session::execute`] for agents and scripts (MCP, CLI, control channel): unknown top-level
/// parameters are rejected with the accepted keys instead of being silently ignored.
pub fn execute_checked(&mut self, id: &str, params: Value) -> Result<Value> {
let spec = commands::find(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?;
commands::check_params(spec, &params)?;
self.execute(id, params)
}
pub fn is_enabled(&self, id: &str) -> bool {
commands::find(id).is_some_and(|c| (c.enabled)(self).is_ok())
}
@@ -306,6 +314,25 @@ impl Session {
r.comp_frame(comp, t)
}
/// Resolve a comp reference (item id number or name; `None`/null = the active comp).
pub fn resolve_comp(&self, comp: Option<&Value>) -> Result<ItemId> {
let p = match comp {
Some(v) if !v.is_null() => serde_json::json!({ "comp": v }),
_ => serde_json::json!({}),
};
commands::comp_id(self, &p)
}
/// Render a comp frame (comp time `t`) as opaque 8-bit RGBA over the comp background, scaled
/// so the longest side is at most `max_side` pixels (0 = full size). Returns (width, height, rgba).
pub fn render_rgba8(&self, comp: ItemId, t: Tick, max_side: u32) -> Result<(u32, u32, Vec<u8>)> {
let c = self.project.comp(comp).ok_or(EngineError::NoComp)?;
let long = c.width.max(c.height).max(1) as f64;
let scale = if max_side == 0 { 1.0 } else { (max_side as f64 / long).min(1.0) };
let img = self.render(comp, t, RenderOpts { scale, ..Default::default() });
Ok((img.width, img.height, img.to_rgba8_over(c.background)))
}
/// Replace the whole project (open/new), resetting history and state.
pub fn replace_project(&mut self, mut p: Project, path: Option<String>) {
p.fix_next_id();
+73
View File
@@ -114,3 +114,76 @@ fn time_navigation() {
s.execute("time.set", json!({"frame": 45})).unwrap();
assert_eq!(s.execute("time.step", json!({"frames": 5})).unwrap()["frame"], 50);
}
#[test]
fn prop_get_and_render_rgba8() {
let mut s = Session::default();
s.execute("comp.new", json!({"name": "T", "width": 320, "height": 180, "duration": 2.0})).unwrap();
let l = s.execute("layer.newSolid", json!({"color": "#ff0000"})).unwrap()["layer"].as_u64().unwrap();
s.execute("prop.addKey", json!({"layer": l, "path": "transform/position", "time": 0.0, "value": [0, 0]})).unwrap();
s.execute("prop.addKey", json!({"layer": l, "path": "transform/position", "time": 1.0, "value": [100, 50]})).unwrap();
let v = s.execute("prop.get", json!({"layer": l, "path": "transform/position", "time": 1.0})).unwrap();
assert_eq!(v["animated"], true);
assert_eq!(v["keys"].as_array().unwrap().len(), 2);
assert_eq!(v["value"][0].as_f64().unwrap(), 100.0);
let cid = s.resolve_comp(Some(&json!("T"))).unwrap();
let (w, h, rgba) = s.render_rgba8(cid, effectcraft_time::Tick::ZERO, 160).unwrap();
assert_eq!((w, h), (160, 90));
assert_eq!(rgba.len(), (w * h * 4) as usize);
}
#[test]
fn params_docs_parse() {
use crate::commands::accepted_params;
let k = |d: &str| accepted_params(d).unwrap();
assert_eq!(k("{layers: [id|name|#n], add?, toggle?}"), ["layers", "add", "toggle"]);
assert_eq!(k("{time? (s) | frame? | timecode?}"), ["time", "frame", "timecode"]);
assert_eq!(k("{interpolation?|in?|out?: linear|bezier|hold, autoBezier?}"), ["interpolation", "in", "out", "autoBezier"]);
assert_eq!(k("{keys: [{layer, prop, time}], add?}"), ["keys", "add"]);
assert_eq!(k("{label: Red|Yellow|Aqua|…, layers?}"), ["label", "layers"]);
assert_eq!(k("{name?, background? [r,g,b]|#hex, open?}"), ["name", "background", "open"]);
assert!(k("{}").is_empty());
assert!(accepted_params("free text").is_none());
// Every registered command documents its params as a parseable key list.
for c in crate::command_specs() {
assert!(accepted_params(c.params).is_some(), "{}: {}", c.id, c.params);
}
}
#[test]
fn execute_checked_rejects_unknown_params() {
let mut s = demo();
let e = s.execute_checked("layer.select", json!({"index": 2})).unwrap_err().to_string();
assert!(e.contains("`index`") && e.contains("layers, add, toggle"), "{e}");
s.execute_checked("layer.select", json!({"layers": ["#2"]})).unwrap();
assert_eq!(s.state.selected_layers.len(), 1);
// Aliases and always-accepted keys.
s.execute_checked("layer.select", json!({"layer": "#1", "comp": s.active_comp_id().unwrap().0})).unwrap();
s.execute_checked("time.set", json!({"frame": 3})).unwrap();
assert!(s.execute_checked("edit.undo", json!({"steps": 2})).is_err());
// Non-object params are not validated; the unchecked path stays lenient.
s.execute("layer.select", json!({"layers": ["#1"], "index": 2})).unwrap();
}
#[test]
fn layer_tree_paths_resolve() {
let mut s = demo();
s.execute("effect.apply", json!({"layer": 1, "effect": "Gaussian Blur"})).unwrap();
let comp = s.execute("comp.info", json!({})).unwrap();
let mut checked = 0;
for l in comp["layers"].as_array().unwrap() {
let tree = s.execute("layer.tree", json!({"layer": l["id"]})).unwrap();
let mut stack = vec![tree["properties"].clone()];
while let Some(n) = stack.pop() {
if let Some(ch) = n["children"].as_array() {
stack.extend(ch.iter().cloned());
continue;
}
let path = n["path"].as_str().unwrap();
let got = s.execute("prop.get", json!({"layer": l["id"], "path": path})).unwrap();
assert_eq!(got["uid"], n["uid"], "path {path} on layer {}", l["name"]);
checked += 1;
}
}
assert!(checked > 20, "{checked}");
}