Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

MCP: batch runs the steps of a script file (path) (#5957) (#5959)

SS-ENa1d66c238e86
diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs
index da018266ab..c1fdb8c8fb 100644
--- a/crates/mcp/src/tests.rs
+++ b/crates/mcp/src/tests.rs
@@ -3418,6 +3418,62 @@ fn a_failed_batch_reports_what_really_happened() {
assert_eq!(methods(&b), ["engine.batch"]);
}
+/// #5957: `batch` runs the steps of a script file (`path`), as an array or `{commands}`, as it
+/// runs them sent inline: tool steps, rollback and reply. The file is read within the agent's
+/// folders; one outside them, missing, not JSON or without steps, or `path` with `commands`,
+/// fails before anything runs.
+#[test]
+fn batch_runs_a_script_file() {
+ use solidcraft_engine::io::vfs::PathScope;
+ let base = solidcraft_engine::io::vfs::temp_dir().join(format!("solidcraft-mcp-script-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&base);
+ let (root, out) = (base.join("root"), base.join("out"));
+ std::fs::create_dir_all(&root).unwrap();
+ std::fs::create_dir_all(&out).unwrap();
+ let file = |d: &std::path::Path, name: &str, text: &str| {
+ let p = d.join(name);
+ std::fs::write(&p, text).unwrap();
+ p.to_string_lossy().to_string()
+ };
+ let steps = json!([
+ {"command": "set_parameter", "params": {"name": "w", "value": 20}},
+ {"command": "solid.box", "params": {"length": "w", "width": 10, "height": 10}},
+ ]);
+ let mut s = Server::new(Box::new(Headless::default())).with_path_scope(Some(PathScope::new([root.clone()])));
+ let array = file(&root, "steps.json", &steps.to_string());
+ let r = tool(&mut s, "batch", json!({"path": array}));
+ assert_eq!((&r["completed"], &r["results"][0]["value"]), (&json!(2), &json!(20.0)), "{r}");
+ let bodies = tool(&mut s, "inspect_design", json!({"measure": false}))["bodies"].as_array().map(Vec::len);
+ assert_eq!(bodies, Some(1));
+
+ // `{commands}`, as `solidcraft-cli script` writes it; a failing step rolls the batch back.
+ let script = json!({"commands": [{"command": "solid.box", "params": {"length": 5, "width": 5, "height": 5}}, {"command": "parameters.change", "params": {"name": "h2", "expression": "1 +"}}]});
+ let r = raw_tool(&mut s, "batch", json!({"path": file(&root, "script.json", &script.to_string())}));
+ assert_eq!(r["result"]["isError"], true, "{r}");
+ let body: Value = serde_json::from_str(r["result"]["content"][0]["text"].as_str().unwrap()).unwrap();
+ assert_eq!((&body["failed"]["index"], &body["rolled_back"]), (&json!(1), &json!(true)), "{body}");
+ assert_eq!(tool(&mut s, "inspect_design", json!({"measure": false}))["bodies"].as_array().map(Vec::len), Some(1));
+
+ let outside = file(&out, "steps.json", &steps.to_string());
+ for (args, says) in [
+ (json!({"path": outside}), "outside"),
+ (json!({"path": root.join("missing.json").to_string_lossy()}), "missing.json"),
+ (json!({"path": file(&root, "bad.json", "[{")}), "not JSON"),
+ (json!({"path": file(&root, "empty.json", "[]")}), "no steps"),
+ (json!({"path": file(&root, "odd.json", "{\"steps\": []}")}), "no `commands`"),
+ (json!({"path": array, "commands": steps}), "not both"),
+ (json!({"path": ""}), "must name"),
+ (json!({}), "`commands` must be"),
+ ] {
+ let r = raw_tool(&mut s, "batch", args.clone());
+ assert_eq!(r["result"]["isError"], true, "{args}: {r}");
+ let text = r["result"]["content"][0]["text"].as_str().unwrap_or_default();
+ assert!(text.contains(says), "{args}: {text}");
+ }
+ assert_eq!(tool(&mut s, "inspect_design", json!({"measure": false}))["bodies"].as_array().map(Vec::len), Some(1), "nothing ran");
+ let _ = std::fs::remove_dir_all(&base);
+}
+
/// Batch steps may name the tools an agent knows: `list_commands` and `set_parameter` run as
/// engine.commands (filtered as the tool filters) and parameters.change; tools that can't be
/// steps fail the batch before anything is sent.
diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs
index a7820daad3..2850a8fd43 100644
--- a/crates/mcp/src/tools.rs
+++ b/crates/mcp/src/tools.rs
@@ -12,6 +12,9 @@ use crate::options::Options;
/// Most commands in one `batch` call.
const MAX_BATCH: usize = 10_000;
+
+/// The largest script file `batch` reads (`path`).
+const MAX_SCRIPT_BYTES: usize = 32 << 20;
/// Largest image returned by `screenshot`.
const MAX_IMAGE_BYTES: usize = 32 << 20;
/// Relative tolerance on an expected volume (`expect.tol`) when the call gives none.
@@ -179,9 +182,10 @@ pub fn tool_definitions_with(opts: Options) -> Vec<Value> {
rollback: false), so the batch is all-or-nothing; the reply names the failing step (index from 0), its error, \
every result before it, whether the design really went back (rolled_back), the steps whose changes are in the \
design (applied) and those never sent (not_run). The usual way to build a part: sketch, draw, dimension, \
- finish, extrude, fillet… in one call. Give `expect` {volume_mm3, tol, bodies, bbox} with the numbers you computed \
- beforehand: after the last step the design is measured and compared, so no separate measure call is needed; a \
- mismatch is flagged as an error naming it, and the design is kept as built.",
+ finish, extrude, fillet… in one call. A long one (a polyline of hundreds of points) can be written to a JSON \
+ file and passed as `path` instead of `commands`. Give `expect` {volume_mm3, tol, bodies, bbox} with the numbers \
+ you computed beforehand: after the last step the design is measured and compared, so no separate measure call is \
+ needed; a mismatch is flagged as an error naming it, and the design is kept as built.",
obj(
json!({
"commands": {
@@ -189,6 +193,9 @@ pub fn tool_definitions_with(opts: Options) -> Vec<Value> {
"description": "Steps: [{\"command\": id, \"params\": {...}}, ...]",
"items": {"type": "object", "properties": {"command": {"type": "string"}, "params": {"type": "object"}}, "required": ["command"]},
},
+ "path": string("Instead of `commands`: a JSON file holding the steps, an array or {\"commands\": [...]} (as \
+ `solidcraft-cli run` takes and `solidcraft-cli script` writes), read by this server within the folders the \
+ agent may use; the steps run as if they had been sent here"),
"rollback": {"type": "boolean", "description": "Undo completed steps when one fails (default true)"},
"coalesce_parameters": {"type": "boolean", "description": "Set each run of consecutive plain parameter edits (parameters.change or set_parameter with a name and a value, or changes) together, rebuilding the design once for the run instead of once per edit; a run that is refused goes step by step, naming the refused step. Other steps still see the design up to date. Each step keeps its own result; the run is one undo step (default false)"},
"timings": {"type": "boolean", "description": "Add `timings`: [{index, command, ms}] for every step run (the failing one included) and `total_ms` (default false)"},
@@ -196,7 +203,7 @@ pub fn tool_definitions_with(opts: Options) -> Vec<Value> {
"verbose": {"type": "boolean", "description": "false: a compact reply. Feature steps leave out the full body list (created_bodies, changed_bodies and removed_bodies stay), sketch steps the ids they repeat outside `created` (default true)"},
"expect": expect_schema(),
}),
- &["commands"],
+ &[],
),
Effect::Files,
),
@@ -1359,6 +1366,32 @@ fn inspect_design_compact(b: &mut dyn Backend, a: &Map<String, Value>) -> Result
Ok(d)
}
+/// The steps of the script file `batch` was given as `path` (`None`: it was given `commands`).
+/// A file it can't read, or whose steps aren't a list, fails the batch before anything is sent.
+fn script_file(a: &Map<String, Value>) -> Result<Option<Vec<Value>>, String> {
+ let Some(path) = a.get("path") else { return Ok(None) };
+ let Some(path) = path.as_str().map(str::trim).filter(|p| !p.is_empty()) else {
+ return Err("`path` must name a script file".into());
+ };
+ if a.contains_key("commands") {
+ return Err("give `commands` or `path`, not both".into());
+ }
+ let text = vfs::read_to_string(path, MAX_SCRIPT_BYTES).map_err(|e| format!("script file `{path}`: {e}"))?;
+ let script: Value = serde_json::from_str(&text).map_err(|e| format!("script file `{path}` is not JSON: {e}"))?;
+ let steps = match script {
+ Value::Array(steps) => steps,
+ Value::Object(mut o) => match o.remove("commands") {
+ Some(Value::Array(steps)) => steps,
+ _ => return Err(format!("script file `{path}`: no `commands` array")),
+ },
+ _ => return Err(format!("script file `{path}`: steps must be an array or {{\"commands\": [...]}}")),
+ };
+ if steps.is_empty() {
+ return Err(format!("script file `{path}` has no steps"));
+ }
+ Ok(Some(steps))
+}
+
/// `set_parameter`'s new value: `value` or `expression` (the parameters.change name), one of
/// them, or both when they agree (`50` and `"50"` do).
fn parameter_value(a: &Map<String, Value>) -> Result<Value, String> {
@@ -1466,7 +1499,11 @@ fn atomic_layout_refusal(count: usize, rule: solidcraft_engine::panels::Rule, de
/// The batch itself: its reply and whether it failed.
fn batch_run(b: &mut dyn Backend, a: &Map<String, Value>) -> (Value, bool) {
- let Some(steps) = a.get("commands").and_then(Value::as_array) else {
+ let from_file = match script_file(a) {
+ Ok(f) => f,
+ Err(e) => return (json!(e), true),
+ };
+ let Some(steps) = from_file.as_ref().map_or_else(|| a.get("commands").and_then(Value::as_array), Some) else {
return (json!("`commands` must be an array of {command, params}"), true);
};
if steps.len() > MAX_BATCH {
diff --git a/docs/mcp.md b/docs/mcp.md
index ac060ac1fa..68fe54d191 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -325,7 +325,7 @@ The `skill_reference` tool returns these documents from the copies built into So
| `list_commands` | `filter?`, `prefix?`, `panel?`, `compact?`, `fields?`, `limit?`, `offset?` | The command catalog: id, label, tab/panel, shortcut, parameter docs, enabled now. `filter` matches id, label, tab and panel. `prefix` keeps the ids that start with it (`"sketch."`) and `panel` the commands of one whole toolbar panel or tab (`"Modify"`), both ignoring case. `compact: true` keeps only `id` and `label` of each entry, about an eighth of the size; `fields` keeps the keys it lists instead. `limit` and `offset` page the matches, and the reply becomes `{commands, total, offset, next_offset}` (`next_offset` is null on the last page). With none of these the reply is the whole catalog, about 350 KB. |
| `describe_command` | `id` | One command's parameter docs (`params`) and, for commands with a typed contract (every new command, and more of the older ones as they are converted), the JSON Schemas (2020-12) of its parameters (`input`) and of a successful result (`output`); `null` for the others. The same as `execute` `engine.describe {command}`. |
| `execute` | `command`, `params?`, `verbose?` (default true), `expect?` | Run any command with JSON parameters (`list_commands` shows them). Failures leave the design unchanged. A feature command replies with the feature (`feature`, `name`), every body (`bodies`) and the bodies it created, changed and removed (`created_bodies`, `changed_bodies`, `removed_bodies`). `verbose: false` uses the same compact reply as `batch`. `expect` checks the design after the command, as it does for `batch` (see below). |
-| `batch` | `commands: [{command, params}]`, `rollback?` (default true), `verbose?` (default true), `timings?`, `profile?`, `coalesce_parameters?` (default false), `expect?` | Run steps in order, stop at the first error and undo the completed steps. The reply names the failing step (`failed.index`, `failed.command`, `failed.error`), every result before it, `rolled_back` (true only when the design really went back to where the batch started), `undone`, `applied` (the indices of the steps whose changes are in the design) and `not_run` (the steps never sent). A step may name a tool instead of a command, with that tool's arguments as `params`: `set_parameter` (runs `parameters.change`; `value` or `expression`), `list_commands` (`engine.commands`, narrowed by its arguments as the tool narrows it), `describe_command` (`engine.describe`), `execute` (`{command, params}`), `measure` (`summary: true` summarised as the tool summarises it), `compare_picture` (`inspect.compare_picture`, numbers only: no overlay PNG), `inspect_design` (`document.inspect`: each sketch as its counts, not its full contents, and no joints), `undo`, `redo`, `export`, `save`, `open`, `new_design` and `crash_reports`. `screenshot`, `body_topology` (use `model.edges` and `model.faces`), `batch`, `check_parameters`, `pending`, `running` and `skill_reference` can't be steps, nor can `component.edit_in_place` and `component.finish_edit`, however a step names them, as they go to another design's tab (send them with the `execute` tool on their own): such a batch fails before anything is sent. So does a step the batch would certainly refuse at its turn (#5853): a step without a command, an unknown command id (the error names the closest ids) or, with `--param-check strict`, parameters that break a command's contract. A headless session checks this itself; an app checks it against its own commands when it gets the batch, and a bridged server at `--param-check strict` checks the contracts before it sends the batch. `verbose: false` keeps the reply small in large designs: feature steps leave out the full body list (`created_bodies`, `changed_bodies`, `removed_bodies` stay) and sketch steps the ids they repeat outside `created`. Bridged to an app that has `engine.batch`, the whole batch is one control request (one frame of the app). Older apps, and apps showing the agent cursor, get the steps one by one. `timings: true` adds `timings: [{index, command, ms}]` for every step run, the failing one included, and `total_ms`. `profile: true` also adds each step's `profile: {boolean_ms, tessellate_ms, other_ms}`, its time in kernel booleans, in tessellation and the rest. Steps are timed where they run: in the app when bridged. An app without `engine.batch` is timed step by step, without `profile`. `coalesce_parameters: true` sets each run of consecutive plain parameter edits (`parameters.change` or `set_parameter` with a name and a value, or `changes`) together, so the design rebuilds once per run instead of once per edit. Steps between runs see the design up to date. Each step keeps its own result (`coalesced`: the run's length), and the run is one undo step. The run skips the states between its edits, so an edit refused on its own can go through with the run's later ones. A refused run goes step by step, naming the refused step. |
+| `batch` | `commands: [{command, params}]` or `path` (a script file, see below), `rollback?` (default true), `verbose?` (default true), `timings?`, `profile?`, `coalesce_parameters?` (default false), `expect?` | Run steps in order, stop at the first error and undo the completed steps. The reply names the failing step (`failed.index`, `failed.command`, `failed.error`), every result before it, `rolled_back` (true only when the design really went back to where the batch started), `undone`, `applied` (the indices of the steps whose changes are in the design) and `not_run` (the steps never sent). A step may name a tool instead of a command, with that tool's arguments as `params`: `set_parameter` (runs `parameters.change`; `value` or `expression`), `list_commands` (`engine.commands`, narrowed by its arguments as the tool narrows it), `describe_command` (`engine.describe`), `execute` (`{command, params}`), `measure` (`summary: true` summarised as the tool summarises it), `compare_picture` (`inspect.compare_picture`, numbers only: no overlay PNG), `inspect_design` (`document.inspect`: each sketch as its counts, not its full contents, and no joints), `undo`, `redo`, `export`, `save`, `open`, `new_design` and `crash_reports`. `screenshot`, `body_topology` (use `model.edges` and `model.faces`), `batch`, `check_parameters`, `pending`, `running` and `skill_reference` can't be steps, nor can `component.edit_in_place` and `component.finish_edit`, however a step names them, as they go to another design's tab (send them with the `execute` tool on their own): such a batch fails before anything is sent. So does a step the batch would certainly refuse at its turn (#5853): a step without a command, an unknown command id (the error names the closest ids) or, with `--param-check strict`, parameters that break a command's contract. A headless session checks this itself; an app checks it against its own commands when it gets the batch, and a bridged server at `--param-check strict` checks the contracts before it sends the batch. `verbose: false` keeps the reply small in large designs: feature steps leave out the full body list (`created_bodies`, `changed_bodies`, `removed_bodies` stay) and sketch steps the ids they repeat outside `created`. Bridged to an app that has `engine.batch`, the whole batch is one control request (one frame of the app). Older apps, and apps showing the agent cursor, get the steps one by one. `timings: true` adds `timings: [{index, command, ms}]` for every step run, the failing one included, and `total_ms`. `profile: true` also adds each step's `profile: {boolean_ms, tessellate_ms, other_ms}`, its time in kernel booleans, in tessellation and the rest. Steps are timed where they run: in the app when bridged. An app without `engine.batch` is timed step by step, without `profile`. `coalesce_parameters: true` sets each run of consecutive plain parameter edits (`parameters.change` or `set_parameter` with a name and a value, or `changes`) together, so the design rebuilds once per run instead of once per edit. Steps between runs see the design up to date. Each step keeps its own result (`coalesced`: the run's length), and the run is one undo step. The run skips the states between its edits, so an edit refused on its own can go through with the run's later ones. A refused run goes step by step, naming the refused step. |
**`expect`** on `batch` and `execute` turns the verify step into part of the build. An agent
computes the volume, body count or bounding box a stage should produce before building it;
@@ -441,6 +441,13 @@ however long the history is. Batches that call `file.new` or `doc.open` get the
not its file path. (An older app without checkpoints falls back to undoing as many steps as
the batch added to the undo history.)
+A long batch, such as a polyline of hundreds of points, can be written to a JSON file and run with
+`path` instead of `commands`, so the steps don't have to go through the chat. The file holds an array
+of steps or `{"commands": [...]}`, the format `solidcraft-cli run` takes and `solidcraft-cli script`
+writes. The server reads it (at most 32 MB), within the folders the agent may use, and runs the steps
+as if they had been sent inline: the same tool steps, rollback and reply. `path` and `commands` can't
+both be given, and a file that can't be read, isn't JSON or has no steps fails before anything is sent.
+
## Camera and close-up recipe
The `camera` of `screenshot` (the object `view.apply`, `view.save` and `solidcraft-cli snapshot --camera` take too) is an orbit camera, `{target, yaw, pitch, distance, fov?}`, in millimetres and **radians**. Unlike the `angle` of `solid.move`, a bare number is not degrees here. The eye is at `target + distance * (-sin(yaw) * cos(pitch), -cos(yaw) * cos(pitch), sin(pitch))`, looking at `target` with Z up on the screen. So `yaw: 0, pitch: 0` is the front view: the eye at -Y, looking along +Y, with +X to the right. A yaw of π/2 looks from -X, π from +Y and -π/2 from +X. The pitch is the elevation angle up from the XY plane, and π/2 looks straight down with +X to the right and +Y up; `view.apply` refuses a pitch past ±π/2. A positive `roll` turns the picture clockwise. The app's View angles readout (`view.angle_readout`) shows the same yaw, pitch and roll in degrees. `fov` is the vertical field of view in radians. `0`, or no `fov`, is an orthographic view whose visible half-height is 0.4 × `distance`; with a perspective `fov` the half-height at the target is `distance * tan(fov / 2)`. `inspect.section` removes what lies on the side its normal points to: it keeps the points `p` with `n · p < d`, where `d = n · origin` (`flip: true` keeps the other side). To look into the cut, put the eye on the removed side.