Skip to content

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

MCP: check_parameters tries parameter values and puts the design back (refs #3380) (#9910)

froglemonade2c52896436302
diff --git a/crates/mcp/src/server.rs b/crates/mcp/src/server.rs
index 8f9fc4efe6..557b58c3b1 100644
--- a/crates/mcp/src/server.rs
+++ b/crates/mcp/src/server.rs
@@ -34,7 +34,8 @@ and dimension (`sketch.dimension {entities, value}`; values may name parameters)
(`solid.extrude {distance, operation?: new|join|cut|intersect}`, `solid.revolve`, `solid.fillet {edges: [[x,y,z] point on \
edge], radius}`, `solid.chamfer`, patterns, mirror, primitives). Use `batch` for several steps at once, \
`list_commands` for ids and parameter docs, `describe_command` for a command's schemas, `inspect_design` / `measure` to verify, \
-`body_topology` to find edge points, `set_parameter` to drive the design and `screenshot` to look at it. A call whose error \
+`body_topology` to find edge points, `set_parameter` to drive the design, `check_parameters` to try values (volume, errors, \
+cylinder axes) and have them put back, and `screenshot` to look at it. A call whose error \
starts `still running:` was not cancelled: don't send it again; `pending` waits for its result.";
pub struct Server {
diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs
index 6c897500ec..0606837f76 100644
--- a/crates/mcp/src/tests.rs
+++ b/crates/mcp/src/tests.rs
@@ -135,6 +135,7 @@ fn handshake_and_tools_list() {
"measure",
"body_topology",
"set_parameter",
+ "check_parameters",
"screenshot",
"export",
"undo",
@@ -451,6 +452,210 @@ fn set_parameter_takes_value_or_expression() {
assert!(rel(volume(&mut s), 6000.0) < 1e-9);
}
+/// A box whose length is a parameter and a cylinder standing on it at `len / 2`, so a change
+/// of `len` moves the cylinder's axis.
+fn parametric_box_with_cylinder(s: &mut Server) {
+ tool(&mut *s, "set_parameter", json!({"name": "len", "value": "40 mm"}));
+ tool(
+ &mut *s,
+ "batch",
+ json!({"commands": [
+ {"command": "solid.box", "params": {"length": "len", "width": 30, "height": 20, "corner": [0, 0, 0]}},
+ {"command": "solid.cylinder", "params": {"radius": 5, "height": 10, "base": ["len / 2", 15, 20], "operation": "join"}},
+ ]}),
+ );
+}
+
+fn box_with_cylinder_volume(len: f64) -> f64 {
+ len * 30.0 * 20.0 + PI * 25.0 * 10.0
+}
+
+/// `check_parameters` applies the values with one rebuild, reports the new volume, the
+/// features' state and the moved cylinder axis (its two kernel halves as one cylinder), and
+/// puts the design back: the parameter, the volume and the undo history are as before.
+#[test]
+fn check_parameters_tries_values_and_puts_the_design_back() {
+ let mut s = server();
+ parametric_box_with_cylinder(&mut s);
+ assert!(rel(volume(&mut s), box_with_cylinder_volume(40.0)) < 5e-4);
+ let before = tool(&mut s, "inspect_design", json!({"measure": false, "sketches": false}));
+ let r = tool(&mut s, "check_parameters", json!({"set": {"len": "60 mm"}}));
+ assert_eq!(r["restored"], true, "{r}");
+ assert_eq!(r["values"]["len"], 60.0, "{r}");
+ assert!(r["recomputed"].as_u64().unwrap() >= 1, "{r}");
+ let v = r["measure"]["total"]["volume_mm3"].as_f64().unwrap();
+ assert!(rel(v, box_with_cylinder_volume(60.0)) < 5e-4, "{v}");
+ assert_eq!(r["measure"]["body_count"], 1, "{r}");
+ assert!(r["measure"]["bodies"][0]["faces"].as_u64().unwrap() >= 8, "{r}");
+ assert_eq!((&r["errors"], &r["warnings"], &r["parameter_errors"]), (&json!([]), &json!([]), &json!([])), "{r}");
+ let cyl = r["cylinders"].as_array().unwrap();
+ assert_eq!(cyl.len(), 1, "one cylinder, halves merged: {r}");
+ assert_eq!(cyl[0]["body"], "Body1", "{r}");
+ assert!((cyl[0]["radius"].as_f64().unwrap() - 5.0).abs() < 1e-6, "{r}");
+ let origin: Vec<f64> = cyl[0]["origin"].as_array().unwrap().iter().map(|x| x.as_f64().unwrap()).collect();
+ let axis: Vec<f64> = cyl[0]["axis"].as_array().unwrap().iter().map(|x| x.as_f64().unwrap()).collect();
+ assert!((origin[0] - 30.0).abs() < 1e-6 && (origin[1] - 15.0).abs() < 1e-6 && origin[2].abs() < 1e-6, "axis moved to len / 2 = 30: {r}");
+ assert!(axis[0].abs() < 1e-9 && axis[1].abs() < 1e-9 && (axis[2] - 1.0).abs() < 1e-9, "{r}");
+ assert!(!cyl[0]["faces"].as_array().unwrap().is_empty(), "{r}");
+ // The halves' areas add up to the cylinder's (measured on its mesh).
+ assert!(rel(cyl[0]["area"].as_f64().unwrap(), 2.0 * PI * 5.0 * 10.0) < 1e-2, "{r}");
+ // Back as it was: the value, the volume and the undo history (a checkpoint restores it).
+ assert!(rel(volume(&mut s), box_with_cylinder_volume(40.0)) < 5e-4);
+ let after = tool(&mut s, "inspect_design", json!({"measure": false, "sketches": false}));
+ assert!(after["params"].as_array().unwrap().iter().any(|p| p["name"] == "len" && p["value"] == 40.0 && p["expression"] == "40 mm"), "{after}");
+ assert_eq!(after["undo"], before["undo"], "undo depth: {after}");
+ assert_eq!(after["redo"], before["redo"], "{after}");
+ // Only what was asked for.
+ let r = tool(&mut s, "check_parameters", json!({"set": {"len": 50}, "report": ["measure"]}));
+ assert!(rel(r["measure"]["total"]["volume_mm3"].as_f64().unwrap(), box_with_cylinder_volume(50.0)) < 5e-4, "{r}");
+ assert!(r.get("cylinders").is_none() && r.get("errors").is_none(), "{r}");
+ assert_eq!(r["restored"], true, "{r}");
+ assert!(rel(volume(&mut s), box_with_cylinder_volume(40.0)) < 5e-4);
+ // A value that breaks a feature is reported, not kept.
+ let r = tool(&mut s, "check_parameters", json!({"set": {"len": 0}, "report": ["errors"]}));
+ assert!(!r["errors"].as_array().unwrap().is_empty(), "{r}");
+ assert_eq!(r["restored"], true, "{r}");
+ assert!(rel(volume(&mut s), box_with_cylinder_volume(40.0)) < 5e-4);
+ let d = tool(&mut s, "inspect_design", json!({"measure": false, "sketches": false}));
+ assert!(d["timeline"].as_array().unwrap().iter().all(|f| f["error"].is_null()), "{d}");
+}
+
+/// An unknown parameter name, a bad expression or a bad report list is an error that leaves the
+/// design untouched; `set` that is not an object is refused by argument checking; the tool is
+/// annotated as an edit (it changes the design and puts it back) and is not a batch step.
+#[test]
+fn check_parameters_refuses_bad_input_and_changes_nothing() {
+ let mut s = server();
+ parametric_box_with_cylinder(&mut s);
+ let before = tool(&mut s, "inspect_design", json!({"measure": false, "sketches": false}));
+ let r = raw_tool(&mut s, "check_parameters", json!({"set": {"nope": 5}}));
+ assert_eq!(r["result"]["isError"], json!(true), "{r}");
+ let text = r["result"]["content"][0]["text"].as_str().unwrap();
+ assert!(text.contains("`nope`") && text.contains("`len`"), "{text}");
+ let d = tool(&mut s, "inspect_design", json!({"measure": false, "sketches": false}));
+ assert_eq!(d["undo"], before["undo"], "{d}");
+ assert!(d["params"].as_array().unwrap().iter().all(|p| p["name"] != "nope"), "{d}");
+ for args in [json!({"set": "len"}), json!({"set": [["len", 5]]}), json!({"set": 5}), json!({"set": {"len": 5}, "report": "measure"}), json!({})] {
+ let r = raw_tool(&mut s, "check_parameters", args.clone());
+ assert_eq!(r["error"]["code"], -32602, "{args}: {r}");
+ }
+ for (args, hint) in [
+ (json!({"set": {}}), "empty"),
+ (json!({"set": {"len": true}}), "`set.len`"),
+ (json!({"set": {"len": null}}), "`set.len`"),
+ (json!({"set": {"": 5}}), "empty"),
+ (json!({"set": {"len": 5}, "report": ["volume"]}), "measure, cylinders, errors"),
+ (json!({"set": {"len": "1 +"}}), "len"),
+ (json!({"set": {"len": "a = 5"}}), "len"),
+ ] {
+ let r = raw_tool(&mut s, "check_parameters", args.clone());
+ assert_eq!(r["result"]["isError"], json!(true), "{args}: {r}");
+ let text = r["result"]["content"][0]["text"].as_str().unwrap_or_default();
+ assert!(text.contains(hint), "{args}: {text}");
+ }
+ assert!(rel(volume(&mut s), box_with_cylinder_volume(40.0)) < 5e-4);
+ // Untouched: the undo depth and the parameter (the engine's `revision` moves even for a
+ // refused change, so it is not what tells).
+ let d = tool(&mut s, "inspect_design", json!({"measure": false, "sketches": false}));
+ assert_eq!(d["undo"], before["undo"], "{d}");
+ assert!(d["params"].as_array().unwrap().iter().any(|p| p["name"] == "len" && p["expression"] == "40 mm"), "{d}");
+ // Not a batch step: refused before anything runs.
+ let r = raw_tool(&mut s, "batch", json!({"commands": [{"command": "check_parameters", "params": {"set": {"len": 5}}}]}));
+ let body: Value = serde_json::from_str(r["result"]["content"][0]["text"].as_str().unwrap()).unwrap();
+ assert_eq!(body["completed"], 0, "{body}");
+ assert!(body["failed"]["error"].as_str().unwrap().contains("check_parameters"), "{body}");
+ let def = tool_definitions().into_iter().find(|d| d["name"] == "check_parameters").unwrap();
+ assert_eq!(def["inputSchema"]["required"], json!(["set"]), "{def}");
+ assert_eq!(def["annotations"]["readOnlyHint"], false, "{def}");
+ assert_eq!(def["annotations"]["destructiveHint"], false, "{def}");
+}
+
+/// A backend answering from a closure: what `check_parameters` sends, and what it does when an
+/// app has no `parameters.change {changes}` or cannot restore the checkpoint.
+struct Answers {
+ calls: Vec<(String, Value)>,
+ answer: Box<dyn Fn(&str, &Value) -> Result<Value, String>>,
+}
+
+impl crate::backend::Backend for Answers {
+ fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
+ self.calls.push((method.to_string(), params.clone()));
+ (self.answer)(method, &params)
+ }
+ fn has_ui(&self) -> bool {
+ true
+ }
+ fn describe(&self) -> String {
+ "answers".into()
+ }
+}
+
+/// An app without `parameters.change {changes}` gets one change per name; one that cannot
+/// restore the checkpoint makes the call an error that says the values are still in.
+#[test]
+fn check_parameters_falls_back_per_name_and_says_when_the_restore_failed() {
+ let app = |restore_ok: bool| Answers {
+ calls: Vec::new(),
+ answer: Box::new(move |method, p| {
+ let command = p["command"].as_str().unwrap_or_default();
+ match (method, command) {
+ ("engine.execute", "parameters.list") => Err("unknown command `parameters.list`".into()),
+ ("engine.execute", "edit.checkpoint") => Ok(json!({"checkpoint": 3})),
+ ("engine.execute", "edit.restore_checkpoint") if restore_ok => Ok(json!({"checkpoint": 3, "restored": true})),
+ ("engine.execute", "edit.restore_checkpoint") => Err("busy: request 9 is still running".into()),
+ ("engine.execute", "parameters.change") if p["params"].get("changes").is_some() => {
+ Err("parameters.change: `name` is required".into())
+ }
+ ("engine.execute", "parameters.change") => Ok(json!({"name": p["params"]["name"], "value": 7.0, "recomputed": 1})),
+ ("engine.execute", "inspect.measure") => Ok(json!({"body_count": 1, "bodies": [], "total": {"volume_mm3": 12.5}})),
+ ("document.inspect", _) => {
+ Ok(json!({"timeline": [{"id": 1, "name": "Box", "error": null, "warning": "thin"}], "params": [], "bodies": [{"name": "B"}]}))
+ }
+ ("engine.execute", "model.faces") => Ok(json!({"faces": [
+ {"index": 0, "name": "side", "area": 1.0, "cylinder": {"origin": [0, 0, 5], "axis": [0, 0, -1], "radius": 2}},
+ {"index": 1, "name": "side", "area": 1.0, "cylinder": {"origin": [0, 0, -3], "axis": [0, 0, 1], "radius": 2}},
+ {"index": 2, "name": "hole", "area": 1.0, "cylinder": {"origin": [9, 0, 0], "axis": [0, 0, 1], "radius": 2}},
+ {"index": 3, "name": "top", "area": 4.0, "plane_normal": [0, 0, 1]},
+ ]})),
+ (m, c) => Err(format!("unknown method `{m}` ({c})")),
+ }
+ }),
+ };
+ let mut b = app(true);
+ let r = crate::tools::call_tool(&mut b, "check_parameters", &json!({"set": {"a": "1 mm", "b": 2}}));
+ assert_ne!(r["isError"], json!(true), "{r}");
+ let body: Value = serde_json::from_str(r["content"][0]["text"].as_str().unwrap()).unwrap();
+ assert_eq!(body["restored"], true, "{body}");
+ assert_eq!(body["values"], json!({"a": 7.0, "b": 7.0}), "{body}");
+ assert_eq!(body["recomputed"], 2, "{body}");
+ assert_eq!(body["measure"]["total"]["volume_mm3"], 12.5, "{body}");
+ assert_eq!(body["warnings"], json!([{"feature": 1, "name": "Box", "warning": "thin"}]), "{body}");
+ assert_eq!(body["errors"], json!([]), "{body}");
+ // Two halves on one axis, reported with opposite directions and different axis points, are
+ // one cylinder; the hole next to it is another.
+ let cyl = body["cylinders"].as_array().unwrap();
+ assert_eq!(cyl.len(), 2, "{body}");
+ assert_eq!((&cyl[0]["faces"], &cyl[0]["origin"], &cyl[0]["axis"]), (&json!([0, 1]), &json!([0.0, 0.0, 0.0]), &json!([0.0, 0.0, 1.0])), "{body}");
+ assert_eq!((&cyl[1]["faces"], &cyl[1]["origin"], &cyl[1]["name"]), (&json!([2]), &json!([9.0, 0.0, 0.0]), &json!("hole")), "{body}");
+ let changes: Vec<&Value> = b.calls.iter().filter(|(_, p)| p["command"] == "parameters.change").map(|(_, p)| &p["params"]).collect();
+ assert_eq!(changes.len(), 3, "one combined change, then one per name: {changes:?}");
+ assert_eq!(changes[0], &json!({"changes": {"a": "1 mm", "b": 2}}), "{changes:?}");
+ assert_eq!((changes[1]["name"].as_str(), changes[2]["name"].as_str()), (Some("a"), Some("b")), "{changes:?}");
+ let last = b.calls.last().unwrap();
+ assert_eq!(last.1["command"], "edit.restore_checkpoint", "the restore is the last call: {last:?}");
+ assert_eq!(last.1["params"]["checkpoint"], 3, "{last:?}");
+
+ // The restore fails: an error, loudly, with everything that was read.
+ let mut b = app(false);
+ let r = crate::tools::call_tool(&mut b, "check_parameters", &json!({"set": {"a": "1 mm"}, "report": ["measure"]}));
+ assert_eq!(r["isError"], json!(true), "{r}");
+ let body: Value = serde_json::from_str(r["content"][0]["text"].as_str().unwrap()).unwrap();
+ assert_eq!(body["restored"], false, "{body}");
+ assert!(body["restore_error"].as_str().unwrap().contains("still running"), "{body}");
+ assert!(body["note"].as_str().unwrap().contains("STILL HOLDS"), "{body}");
+ assert_eq!(body["measure"]["total"]["volume_mm3"], 12.5, "{body}");
+}
+
/// Design properties (#1015) are set through `execute` and come back in `inspect_design`.
#[test]
fn design_properties_show_in_inspect_design() {
@@ -1912,7 +2117,7 @@ fn tool_annotations_tell_the_whole_truth() {
assert_eq!(hints(name), (true, false, false), "{name}");
}
assert_eq!(hints("new_design"), (false, true, false));
- for name in ["set_parameter", "undo", "redo"] {
+ for name in ["set_parameter", "check_parameters", "undo", "redo"] {
assert_eq!(hints(name), (false, false, false), "{name}");
}
assert!(tools.iter().all(|t| t["annotations"]["readOnlyHint"].is_boolean()), "every tool is annotated");
diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs
index 9a673b1f6c..91b19973ec 100644
--- a/crates/mcp/src/tools.rs
+++ b/crates/mcp/src/tools.rs
@@ -15,6 +15,8 @@ const MAX_BATCH: usize = 10_000;
const MAX_IMAGE_BYTES: usize = 32 << 20;
const VIEWS: &[&str] = &["iso", "home", "front", "back", "top", "bottom", "left", "right", "fit"];
+/// What `check_parameters` can report.
+const REPORTS: &[&str] = &["measure", "cylinders", "errors"];
fn obj(props: Value, required: &[&str]) -> Value {
let mut o = json!({"type": "object", "properties": props, "additionalProperties": false});
@@ -200,6 +202,34 @@ pub fn tool_definitions() -> Vec<Value> {
),
Effect::Edits,
),
+ tool(
+ "check_parameters",
+ "Try parameter values",
+ "Try parameter values without keeping them: set every parameter in `set` with one rebuild, report what `report` \
+ asks for, and put the design back exactly as it was (undo history included). `measure`: volume, bbox, bodies and \
+ faces per body as the measure tool reports them; `errors`: the features that fail or warn and the parameters that \
+ don't evaluate; `cylinders`: every cylindrical face as {body, radius, origin, axis, faces, name}, the halves the \
+ kernel splits one cylinder into merged (origin is the axis point closest to the world origin). The reply ends with \
+ `restored: true`; if the design could not be put back the call is an error with `restored: false` and the values \
+ still applied. An unknown parameter name is an error and nothing changes. Replaces the loop set_parameter, \
+ measure, body_topology, set_parameter back.",
+ obj(
+ json!({
+ "set": {
+ "type": "object",
+ "description": "Values to try, by parameter name: a number (mm) or an expression (\"140 mm\", \"wall * 2\"), as set_parameter's `value`",
+ "additionalProperties": {"type": ["number", "string"]},
+ },
+ "report": {
+ "type": "array",
+ "items": {"type": "string", "enum": REPORTS},
+ "description": "What to report: measure, cylinders, errors (default all three)",
+ },
+ }),
+ &["set"],
+ ),
+ Effect::Edits,
+ ),
tool(
"screenshot",
"Look at the design",
@@ -418,6 +448,7 @@ pub fn call_tool(b: &mut dyn Backend, name: &str, args: &Value) -> Value {
let r = match name {
"screenshot" => return screenshot(b, a),
"batch" => return batch(b, a),
+ "check_parameters" => return check_parameters(b, a),
_ => dispatch(b, name, a),
};
match r {
@@ -646,6 +677,7 @@ fn batch_step(step: &Value) -> Result<(String, Value, Option<String>), String> {
"body_topology" => Err("`body_topology` is a tool, not a command: in a batch use model.edges {body} and model.faces {body}".into()),
"screenshot" => Err("`screenshot` is a tool, not a command: call it after the batch".into()),
"batch" => Err("batches don't nest: put the steps in this batch".into()),
+ "check_parameters" => Err("`check_parameters` is a tool, not a command: call it on its own (it puts the design back itself)".into()),
"pending" => Err("`pending` is a tool, not a command: call it on its own".into()),
"running" => Err("`running` is a tool, not a command: call it on its own".into()),
"skill_reference" => Err("`skill_reference` is a tool, not a command: call it on its own".into()),
@@ -658,6 +690,7 @@ fn batch_step(step: &Value) -> Result<(String, Value, Option<String>), String> {
const TOOL_STEPS: &[&str] = &[
"batch",
"body_topology",
+ "check_parameters",
"crash_reports",
"describe_command",
"execute",
@@ -1015,6 +1048,235 @@ fn compact(mut v: Value) -> Value {
v
}
+/// `check_parameters`: try parameter values and put the design back (#3380). The checkpoint is
+/// taken before anything changes; whatever happens after it, the design is restored, and a
+/// restore that fails is an error saying the values are still in. Every agent session that
+/// changed a parameter to see its effect spent three to five calls on this loop, and one saved
+/// the design with the test values still in it.
+fn check_parameters(b: &mut dyn Backend, a: &Map<String, Value>) -> Value {
+ let (changes, reports) = match check_parameters_args(a) {
+ Ok(x) => x,
+ Err(e) => return text_result(&Value::String(e), true),
+ };
+ // A name the design has no parameter of is refused before the checkpoint, so nothing
+ // changes: `parameters.change` would make one.
+ if let Err(e) = known_parameters(b, &changes) {
+ return text_result(&Value::String(e), true);
+ }
+ let Some(id) = exec(b, "edit.checkpoint", json!({})).ok().and_then(|v| v["checkpoint"].as_u64()) else {
+ let e = "check_parameters: this app has no edit.checkpoint to put the design back with; use set_parameter and measure, and set the values back yourself";
+ return text_result(&json!(e), true);
+ };
+ let outcome = try_parameters(b, &changes, &reports);
+ let restore = exec(b, "edit.restore_checkpoint", json!({"checkpoint": id}));
+ match (outcome, restore) {
+ (Ok(mut reply), Ok(_)) => {
+ reply["restored"] = json!(true);
+ text_result(&reply, false)
+ }
+ (Err(e), Ok(_)) => text_result(&json!({"error": e, "restored": true, "note": "the design is back as it was"}), true),
+ (outcome, Err(restore_error)) => {
+ let mut reply = match outcome {
+ Ok(r) => r,
+ Err(e) => json!({"error": e}),
+ };
+ reply["restored"] = json!(false);
+ reply["restore_error"] = json!(restore_error);
+ reply["note"] = json!(
+ "THE DESIGN STILL HOLDS THE TRIED VALUES: the checkpoint could not be restored. Set them back with set_parameter (or undo) before saving"
+ );
+ text_result(&reply, true)
+ }
+ }
+}
+
+/// `check_parameters`'s arguments, checked before anything is sent: the values to try (a
+/// number or an expression each, as `set_parameter` takes its `value`) and what to report.
+fn check_parameters_args(a: &Map<String, Value>) -> Result<(Map<String, Value>, Vec<&'static str>), String> {
+ let set = a.get("set").and_then(Value::as_object).ok_or("check_parameters: `set` must be an object of parameter name: value")?;
+ if set.is_empty() {
+ return Err("check_parameters: `set` is empty; give at least one parameter name: value".into());
+ }
+ let mut changes = Map::new();
+ for (name, v) in set {
+ let name = name.trim();
+ if name.is_empty() {
+ return Err("check_parameters: a parameter name in `set` is empty".into());
+ }
+ if !matches!(v, Value::Number(_) | Value::String(_)) {
+ let shown: String = name.chars().take(64).collect();
+ return Err(format!("check_parameters: `set.{shown}` must be a number (mm) or an expression, as set_parameter's `value`"));
+ }
+ changes.insert(name.to_string(), v.clone());
+ }
+ let reports = match a.get("report").filter(|r| !r.is_null()) {
+ None => REPORTS.to_vec(),
+ Some(r) => {
+ let items = r.as_array().ok_or("check_parameters: `report` must be an array of measure, cylinders, errors")?;
+ let mut out: Vec<&'static str> = Vec::new();
+ for item in items {
+ let Some(known) = item.as_str().and_then(|s| REPORTS.iter().copied().find(|r| *r == s)) else {
+ return Err(format!("check_parameters: `report` items must be one of {}", REPORTS.join(", ")));
+ };
+ if !out.contains(&known) {
+ out.push(known);
+ }
+ }
+ out
+ }
+ };
+ Ok((changes, reports))
+}
+
+/// Refuse a name the design has no parameter of, before anything changes. An app without
+/// `parameters.list` is not asked; the change itself then tells.
+fn known_parameters(b: &mut dyn Backend, changes: &Map<String, Value>) -> Result<(), String> {
+ let Ok(list) = exec(b, "parameters.list", json!({})) else { return Ok(()) };
+ let Some(rows) = list["parameters"].as_array() else { return Ok(()) };
+ let names: Vec<&str> = rows.iter().filter_map(|r| r["name"].as_str()).collect();
+ let shown = |n: &str| format!("`{}`", n.chars().take(64).collect::<String>());
+ let unknown: Vec<String> = changes.keys().filter(|n| !names.contains(&n.as_str())).map(|n| shown(n)).collect();
+ if unknown.is_empty() {
+ return Ok(());
+ }
+ let user: Vec<String> = rows.iter().filter(|r| r["source"] == "user").filter_map(|r| r["name"].as_str()).take(40).map(shown).collect();
+ let have = if user.is_empty() { "no user parameters".to_string() } else { format!("user parameters {}", user.join(", ")) };
+ Err(format!("check_parameters: no parameter {}; the design has {have} (parameters.list shows every parameter)", unknown.join(", ")))
+}
+
+/// Apply the values and read back what was asked for: what each parameter is now, the
+/// features rebuilt, and the reports.
+fn try_parameters(b: &mut dyn Backend, changes: &Map<String, Value>, reports: &[&str]) -> Result<Value, String> {
+ let (values, recomputed) = apply_parameters(b, changes)?;
+ let mut reply = json!({"set": changes, "values": values, "recomputed": recomputed});
+ // The bodies and each feature's state: one cheap read serves `errors` and `cylinders`.
+ let design = if reports.iter().any(|r| *r != "measure") { Some(b.call("document.inspect", json!({"measure": false}))?) } else { None };
+ for r in reports {
+ match *r {
+ "measure" => reply["measure"] = exec(b, "inspect.measure", json!({}))?,
+ "errors" => {
+ if let Some(d) = &design {
+ let pick = |key: &str| -> Value {
+ let rows = d["timeline"].as_array().into_iter().flatten().filter(|f| !f[key].is_null());
+ Value::Array(rows.map(|f| json!({"feature": f["id"], "name": f["name"], key: f[key]})).collect())
+ };
+ reply["errors"] = pick("error");
+ reply["warnings"] = pick("warning");
+ let params = d["params"].as_array().into_iter().flatten().filter(|p| !p["error"].is_null());
+ reply["parameter_errors"] = Value::Array(params.map(|p| json!({"name": p["name"], "error": p["error"]})).collect());
+ }
+ }
+ "cylinders" => {
+ if let Some(d) = &design {
+ let bodies: Vec<String> =
+ d["bodies"].as_array().into_iter().flatten().filter_map(|body| body["name"].as_str()).map(str::to_string).collect();
+ reply["cylinders"] = Value::Array(cylinders(b, &bodies));
+ }
+ }
+ _ => {}
+ }
+ }
+ Ok(reply)
+}
+
+/// Set the values with one `parameters.change {changes}`, so the design rebuilds once. An app
+/// without `changes` (it asks for `name`, or refuses the key) gets one `parameters.change` per
+/// name instead; any other refusal (an expression that does not evaluate) is the error. Returns
+/// each parameter's value now and the features rebuilt.
+fn apply_parameters(b: &mut dyn Backend, changes: &Map<String, Value>) -> Result<(Map<String, Value>, Value), String> {
+ let combined = solidcraft_engine::batch_params::combined_params(changes);
+ match exec(b, "parameters.change", combined) {
+ Ok(v) => Ok((v["changed"].as_object().cloned().unwrap_or_default(), v["recomputed"].clone())),
+ Err(e) if e.contains("`name`") || e.contains("`changes`") => {
+ let mut values = Map::new();
+ let mut recomputed = 0u64;
+ for (name, expression) in changes {
+ let v = exec(b, "parameters.change", json!({"name": name, "expression": expression}))?;
+ values.insert(name.clone(), v["value"].clone());
+ recomputed += v["recomputed"].as_u64().unwrap_or(0);
+ }
+ Ok((values, json!(recomputed)))
+ }
+ Err(e) => Err(e),
+ }
+}
+
+/// Every cylindrical face of these bodies (`model.faces`), the halves one cylinder is split
+/// into merged.
+fn cylinders(b: &mut dyn Backend, bodies: &[String]) -> Vec<Value> {
+ let mut out = Vec::new();
+ for body in bodies {
+ match exec(b, "model.faces", json!({"body": body})) {
+ Ok(f) => out.extend(merge_cylinders(body, f["faces"].as_array().map(Vec::as_slice).unwrap_or(&[]))),
+ Err(e) => out.push(json!({"body": body, "error": e})),
+ }
+ }
+ out
+}
+
+/// One cylinder of a body: the faces on it (one, or the halves a kernel splits it into).
+struct Cylinder {
+ radius: f64,
+ origin: [f64; 3],
+ axis: [f64; 3],
+ faces: Vec<Value>,
+ name: Value,
+ area: f64,
+}
+
+fn vec3(v: &Value) -> Option<[f64; 3]> {
+ let a = v.as_array()?;
+ match (a.first()?.as_f64(), a.get(1)?.as_f64(), a.get(2)?.as_f64()) {
+ (Some(x), Some(y), Some(z)) if x.is_finite() && y.is_finite() && z.is_finite() => Some([x, y, z]),
+ _ => None,
+ }
+}
+
+fn dot(a: [f64; 3], b: [f64; 3]) -> f64 {
+ a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
+}
+
+/// The cylindrical faces of one body as cylinders: faces with the same radius on the same
+/// axis line are one cylinder, whatever point on the axis and whichever direction each half
+/// reports. The origin is the axis point closest to the world origin and the axis points so
+/// that its first non-zero component is positive, so the same cylinder reads the same whichever
+/// kernel built it.
+fn merge_cylinders(body: &str, faces: &[Value]) -> Vec<Value> {
+ let mut found: Vec<Cylinder> = Vec::new();
+ for f in faces {
+ let c = &f["cylinder"];
+ let (Some(radius), Some(origin), Some(axis)) = (c["radius"].as_f64(), vec3(&c["origin"]), vec3(&c["axis"])) else { continue };
+ let len = dot(axis, axis).sqrt();
+ if !(radius > 0.0) || !radius.is_finite() || !(len > 0.0) {
+ continue;
+ }
+ let mut axis = axis.map(|x| x / len);
+ if axis.iter().find(|x| x.abs() > 1e-9).is_some_and(|x| *x < 0.0) {
+ // A zero component stays 0.0, not -0.0.
+ axis = axis.map(|x| if x.abs() > 1e-9 { -x } else { 0.0 });
+ }
+ let t = dot(origin, axis);
+ let origin = [origin[0] - t * axis[0], origin[1] - t * axis[1], origin[2] - t * axis[2]];
+ let tol = 1e-4 * radius.max(1.0);
+ let area = f["area"].as_f64().unwrap_or(0.0);
+ let same = |k: &Cylinder| {
+ let d = [k.origin[0] - origin[0], k.origin[1] - origin[1], k.origin[2] - origin[2]];
+ (k.radius - radius).abs() <= tol && dot(k.axis, axis) >= 1.0 - 1e-8 && dot(d, d).sqrt() <= tol
+ };
+ match found.iter_mut().find(|k| same(k)) {
+ Some(k) => {
+ k.faces.push(f["index"].clone());
+ k.area += area;
+ }
+ None => found.push(Cylinder { radius, origin, axis, faces: vec![f["index"].clone()], name: f["name"].clone(), area }),
+ }
+ }
+ found
+ .into_iter()
+ .map(|k| json!({"body": body, "radius": k.radius, "origin": k.origin, "axis": k.axis, "faces": k.faces, "name": k.name, "area": k.area}))
+ .collect()
+}
+
static SHOT: AtomicU64 = AtomicU64::new(0);
/// `screenshot`: render or capture to a file, return it as an MCP image content block.
diff --git a/docs/mcp.md b/docs/mcp.md
index 3bd30f84bb..421c6524af 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -153,7 +153,8 @@ file dialogs are never limited.
Each tool says what it may do, for clients that ask before running tools (or auto-approve on
these hints). `list_commands`, `describe_command`, `inspect_design`, `measure`, `body_topology`,
`skill_reference`, `crash_reports`, `pending` and `running` are read-only. `set_parameter`, `undo` and `redo`
-change the design undoably. `new_design` replaces it (destructive). `execute`, `batch`, `open`, `save`, `export` and
+change the design undoably, and so does `check_parameters` (it changes the design and puts it back:
+not read-only, not destructive). `new_design` replaces it (destructive). `execute`, `batch`, `open`, `save`, `export` and
`screenshot` (whose `path` writes a file) can read, write, overwrite or delete files: they are
not read-only, `destructiveHint` and `openWorldHint` are true.
@@ -287,11 +288,12 @@ The `skill_reference` tool returns these documents from the copies built into So
| `list_commands` | `filter?` | The command catalog: id, label, tab/panel, shortcut, parameter docs, enabled now. `filter` matches id, label, tab and panel. |
| `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) | 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`. |
-| `batch` | `commands: [{command, params}]`, `rollback?` (default true), `verbose?` (default true), `timings?`, `profile?`, `coalesce_parameters?` (default false) | 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`, filtered by `filter` as the tool filters it), `describe_command` (`engine.describe`), `execute` (`{command, params}`), `measure`, `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`, `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}]`, `rollback?` (default true), `verbose?` (default true), `timings?`, `profile?`, `coalesce_parameters?` (default false) | 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`, filtered by `filter` as the tool filters it), `describe_command` (`engine.describe`), `execute` (`{command, params}`), `measure`, `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. |
| `inspect_design` | `measure?` (default true), `sketches?` (default true), `joints?` (default true) | Design properties (`metadata`: project, author… and other tools' keys; set them with `execute` `document.metadata.set`), parameters, timeline (type, suppressed, rolled back, error, warning, timing), bodies (volume, area, centre of mass, bbox, face/edge/vertex counts, visible; `removed_later: true` while a sketch is being edited on a rolled-back timeline and a later feature deletes the body, which is then not shown), sketches (curves, points, constraints, profiles, DOF, solve status, visible), joints when the design has any (as `joint.inspect` gives them: each origin's occurrence, component and path, the snap as saved, the feature, face, edge or sketch curve (`sketch: {id, name, curve}`) its persistent names refer to, `resolves` and the `error` when it is lost; kind, offset, angle, flip, values, limits, expressions, motion links; `execute` `joint.inspect {joint}` gives one joint), selection, undo depth. Hide helper sketches, bodies or construction planes with `execute` `browser.visibility` (`{items, visible}` or `{folder, visible}`), and joint glyphs with `{joints: [id or name], visible}` or `{folder: "joints", visible}` (a hidden joint still constrains and drives; `joint.list` reports each joint's `visible`). |
| `measure` | `body?` or `items?` | Area (mm²), bbox, topology counts and `closed` per body. Volume (mm³), volume centre of mass, density and mass are reported only for closed, consistently oriented bodies (null or omitted for open surfaces). Volume/mass totals skip open bodies; `total.open_bodies_skipped` gives their count. Area and topology totals include all bodies. With `items` (one or two selections as `execute` takes them: `face`, `edge`, `vertex`, `sketch_curve`, `profile`), the picked geometry instead: faces and edges need only `type`, `body` and `point`; `index` is optional. See below. |
| `body_topology` | `body` | Edges (index, midpoint, length, ends) and faces (index, name, area, centroid, normal, `point`, and for a cylindrical face its `cylinder`: `origin`, `axis`, `radius`). An edge midpoint is the `[x,y,z]` that picks that edge for fillet and chamfer. A face's `point` lies on it and picks it (its centroid may not: that of a face with a hole is in the hole); a face's `name` picks it for the commands that take faces (`face.delete`, `solid.shell`, `solid.draft`, `solid.offset_face`, `solid.split_face`, `solid.replace_face`, and `face` of `sheet.convert`). |
| `set_parameter` | `name`, `value` or `expression` (number or expression), `unit?`, `comment?` | Create or change a user parameter and recompute. `expression` is another name for `value` (the one `parameters.change` uses): give one of them, or both only when they agree; neither, or two that differ, is an error. Reports `recomputed` (features rebuilt), `restored` (features whose earlier result for the same inputs was reused, e.g. a value set back) and features that now fail. An expression `new_name = expression` renames the parameter as it sets it; in any other tool's expression parameter it adds the user parameter `new_name` and the input uses it (`defined`, `definitions` in the reply). |
+| `check_parameters` | `set: {name: value}` (a number or an expression each, as `set_parameter`'s `value`), `report?` (`measure`, `cylinders`, `errors`; default all three) | Try parameter values without keeping them: one `edit.checkpoint`, every value set in one `parameters.change {changes}` (one rebuild; an app without `changes` gets one change per name), the reports read, then `edit.restore_checkpoint`, so the design, its parameters and its undo history are exactly as before. The reply has `values` (each parameter's value with the tried expressions in), `recomputed`, `measure` (volume, bbox, bodies and faces per body, as the `measure` tool reports them), `errors` and `warnings` (the features that fail or warn: `{feature, name, error}`) with `parameter_errors` (the parameters that don't evaluate), `cylinders` (every cylindrical face of every body as `{body, radius, origin, axis, faces, name, area}`; the halves a kernel splits one cylinder into are one entry, `origin` is the axis point closest to the world origin and `axis` points so that its first non-zero component is positive) and `restored: true`. A name the design has no parameter of, a value that is not a number or a string, an expression that does not evaluate or an unknown report item is an error, and nothing changes. If the checkpoint cannot be restored the call is an error with `restored: false`, `restore_error` and a note that the tried values are still in the design: set them back before saving. Replaces the loop `set_parameter`, `measure`, `body_topology`, `set_parameter` back, which cost every agent session three to five calls and up to 16 s of rebuilds. Not a `batch` step. |
| `screenshot` | `view?` (iso, top, front, back, bottom, left, right, home, fit, or a named view saved with `view.save`), `camera?` (`{target, yaw, pitch, distance, fov?}`, as `view.apply`), `path?`, `width?`, `height?`, `source?` (window, model), `grid?`, `axes?` | A PNG image content block. Headless: a render with the viewport's pipelines on a headless GPU device (see `solidcraft-cli gpu`; with no adapter, the CPU rasterizer, without analysis colours), fitted to the model, or from the named view or camera; the reply's `renderer` says which (`gpu`, `gpu-software`, `cpu`, with a `warning` for `cpu`). Bridged: the app window (default) or a model render with the app's camera; a named view or camera moves the app's viewport there first (`execute` `view.apply` does the same without a screenshot). `grid: false` and `axes: false` leave the ground grid (it lies on Z 0 and cuts through a part that straddles it) and the origin's axes out of a model render; axes hidden with `browser.visibility` stay out whatever `axes` says. Bridged, a screenshot that gives `grid` or `axes` is a model render, which follows the app's Grid and Origin switches for what it does not give; `source: "window"` with either is an error. A window that is minimised or on another macOS Space presents no frame: with no `source` the reply is a model render and says so (`fallback`); `source: "window"` is an error saying why, at once. Agents that don't need the app's chrome can ask for `source: "model"`. |
| `export` | `path`, `format?` (step, 3mf, 3mf-tagged, stl, stla, obj, urdf), `bodies?`, `mesh_prefix?`, `effort?`, `velocity?` | STEP, 3MF or mesh export; URDF writes the whole assembly with its meshes next to it (`docs/urdf.md`). |
| `undo`, `redo` | — | Undo / redo one change. |
diff --git a/skills/solidcraft-modeling/SKILL.md b/skills/solidcraft-modeling/SKILL.md
index 7981bf6fc8..719d5af1fe 100644
--- a/skills/solidcraft-modeling/SKILL.md
+++ b/skills/solidcraft-modeling/SKILL.md
@@ -49,7 +49,7 @@ Work the part out as numbers first. Then build it in a few large `batch` calls,
## Verify
- **Each stage:** run `measure {}` (about 0.9 KB per body) and compare the volume, bbox and face count with your numbers. A cut or hole that leaves the volume unchanged has missed, even though it reported success.
- **Timeline health:** `inspect_design {"measure":false,"sketches":false}` shows each feature's `error` and `warning`.
-- **Parameter test:** run `set_parameter`. Expect `errors: []`, then `measure` again; the COM and bbox should move by the amounts you computed.
+- **Parameter test:** run `set_parameter`. Expect `errors: []`, then `measure` again; the COM and bbox should move by the amounts you computed. To try values without keeping them, `check_parameters {"set": {"L": "140 mm"}}` reports the volume, errors and cylinder axes and puts the design back.
- **Positions:** `measure` does not say where a feature sits.
- On an asymmetric part, check the COM shift you computed.
- On a symmetric part (a mirrored or patterned layout) the COM does not move, so take a top-view screenshot and compare distances in pixels against a known size.