SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
MCP list_commands: ask for commands by id prefix or panel, ids and labels only, or a page at a time (#11726) (#11788)
leValdemar196312c2760a25
diff --git a/crates/mcp/src/server.rs b/crates/mcp/src/server.rsindex 0b4662a778..b87cbef621 100644--- a/crates/mcp/src/server.rs+++ b/crates/mcp/src/server.rs@@ -38,7 +38,7 @@ ids, plane axes, worked examples and the known traps of this version; `file: \"SPlan: work the numbers out first (the parameters, the expected volume and bounding box after each stage, the world point you \will use for each edge or face pick). Then build in a few `batch` calls (all-or-nothing; the reply names the failing step; \`save`, `measure` and `set_parameter` can be steps). Use `verbose: false`. Name every feature. `list_commands {\"filter\": word}` \-gives ids and one-line parameter docs (never unfiltered); `describe_command` gives one command's docs and schemas.\n\n\+gives ids and one-line parameter docs (never unfiltered: it also takes prefix, panel, compact: true and limit); `describe_command` gives one command's docs and schemas.\n\n\Routes: a plate, block, boss, standoff or hole is cheapest as a primitive with expression fields (`solid.box`, `solid.cylinder`, \`solid.hole`, `solid.fillet`, `solid.shell`, patterns and mirror), no sketch. Sketch when the profile is not a box or a circle. \Fillet outside edges before shelling, build inside features after the shell, then the holes and cuts through walls. Give a blind \diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rsindex ed7e114db0..54ad7d2b34 100644--- a/crates/mcp/src/tests.rs+++ b/crates/mcp/src/tests.rs@@ -1741,6 +1741,75 @@ fn list_commands_filter_by_a_command_id_matches_ids() {assert!(ids.iter().all(|id| id.contains("sketch.delete")), "{} commands matched: {ids:?}", ids.len());}+/// #11726: `list_commands` narrows by id prefix and by panel, shrinks each entry to id and label+/// or to chosen keys, and pages; with none of these the reply is the whole catalog as before. A+/// batch step narrows the same way, and a bad argument is a tool error that names it.+#[test]+fn list_commands_narrows_by_prefix_panel_fields_and_page() {+ let mut s = server();+ let all = tool(&mut s, "list_commands", json!({}));+ let all = all.as_array().unwrap();+ assert!(all.len() > 100 && all[0].get("params").is_some(), "the whole catalog, every key");+ let ids = |v: &Value| v.as_array().unwrap().iter().map(|c| c["id"].as_str().unwrap().to_string()).collect::<Vec<_>>();+ let sketch = tool(&mut s, "list_commands", json!({"prefix": "SKETCH."}));+ assert!(!ids(&sketch).is_empty() && ids(&sketch).iter().all(|id| id.starts_with("sketch.")), "{:?}", ids(&sketch));+ let want = all.iter().filter(|c| c["id"].as_str().unwrap().starts_with("sketch.")).count();+ assert_eq!(ids(&sketch).len(), want, "every sketch command, not only those on a toolbar");+ let modify = tool(&mut s, "list_commands", json!({"panel": "modify"}));+ assert!(!ids(&modify).is_empty(), "{modify}");+ assert!(+ modify+ .as_array()+ .unwrap()+ .iter()+ .all(|c| c["panel"].as_str().unwrap().eq_ignore_ascii_case("modify") || c["tab"].as_str().unwrap().eq_ignore_ascii_case("modify")),+ "only the whole panel name matches"+ );+ let compact = tool(&mut s, "list_commands", json!({"compact": true}));+ assert_eq!(ids(&compact), ids(&Value::Array(all.clone())), "compact keeps every command");+ assert!(compact.as_array().unwrap().iter().all(|c| c.as_object().unwrap().keys().eq(["id", "label"].iter())), "{}", compact[0]);+ assert!(compact.to_string().len() * 5 < Value::Array(all.clone()).to_string().len(), "compact is far smaller");+ let picked = tool(&mut s, "list_commands", json!({"prefix": "solid.fillet", "fields": ["id", "enabled"], "compact": true}));+ assert_eq!(picked[0], json!({"id": "solid.fillet", "enabled": picked[0]["enabled"]}), "fields wins over compact");+ // Pages: together they are the whole match list, in order.+ let mut paged = Vec::new();+ let mut offset = json!(0);+ while let Some(at) = offset.as_u64() {+ let page = tool(&mut s, "list_commands", json!({"prefix": "sketch.", "compact": true, "limit": 7, "offset": at}));+ assert_eq!(page["total"], want, "{page}");+ assert_eq!(page["offset"], at);+ assert!(page["commands"].as_array().unwrap().len() <= 7);+ paged.extend(ids(&page["commands"]));+ offset = page["next_offset"].clone();+ }+ assert_eq!(paged, ids(&sketch));+ let past = tool(&mut s, "list_commands", json!({"limit": 5, "offset": 1_000_000}));+ assert_eq!((past["commands"].as_array().unwrap().len(), &past["next_offset"]), (0, &Value::Null), "{past}");+ // A batch step narrows as the tool does.+ let r = tool(&mut s, "batch", json!({"commands": [{"command": "list_commands", "params": {"prefix": "sketch.", "compact": true, "limit": 3}}]}));+ let step = r["results"][0].clone();+ assert_eq!(step["commands"].as_array().map(Vec::len), Some(3), "{r}");+ assert_eq!(step["total"], want, "{r}");+ for bad in [+ json!({"limit": 0}),+ json!({"limit": -1}),+ json!({"offset": "x"}),+ json!({"fields": ["nope"]}),+ json!({"fields": "id"}),+ json!({"compact": 1}),+ json!({"prefix": 3}),+ ] {+ // The argument schema refuses a wrong type before the tool runs; the tool refuses the rest.+ let r = raw_tool(&mut s, "list_commands", bad.clone());+ let text = r["result"]["content"][0]["text"].as_str().or(r["error"]["message"].as_str()).unwrap_or_default().to_string();+ assert!(r["result"]["isError"] == json!(true) || r["error"]["code"].is_i64(), "{bad}: {r}");+ let key = bad.as_object().unwrap().keys().next().unwrap().clone();+ assert!(text.contains(&format!("`{key}`")), "{bad}: the error names the argument: {text}");+ let r = raw_tool(&mut s, "batch", json!({"commands": [{"command": "list_commands", "params": bad.clone()}]}));+ assert!(r["result"]["isError"] == json!(true) || r.to_string().contains(&format!("`{key}`")), "{bad} as a step: {r}");+ }+}+/// Compatibility shims (docs/compatibility.md): a design saved before the rename (legacy/// extension and format tag) opens through MCP, and the legacy resource URIs still read.#[test]diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rsindex 08e4ac47fb..056fb70957 100644--- a/crates/mcp/src/tools.rs+++ b/crates/mcp/src/tools.rs@@ -102,8 +102,26 @@ pub fn tool_definitions() -> Vec<Value> {enabled right now. Ids are dotted and lower-case (solid.extrude, sketch.create, \solid.fillet, sketch.inspect, timeline.rollback). Optional case-insensitive \substring `filter` over id, label, tab and panel (not the parameter docs, so a command id \- finds that command rather than every command whose docs mention it).",- obj(json!({"filter": string("Substring to match, e.g. \"sketch\", \"fillet\", \"pattern\"")}), &[]),+ finds that command rather than every command whose docs mention it). Narrow it further with `prefix` \+ (start of the id) and `panel` (a whole panel or tab name); shrink each entry with `compact` (id and label) \+ or `fields`; page it with `limit` and `offset`, which make the reply {commands, total, offset, next_offset}. \+ With none of these the reply is the whole catalog, about 350 KB.",+ obj(+ json!({+ "filter": string("Substring to match, e.g. \"sketch\", \"fillet\", \"pattern\""),+ "prefix": string("Case-insensitive start of the command id, e.g. \"sketch.\""),+ "panel": string("A whole toolbar panel or tab name, case-insensitive, e.g. \"Modify\" or \"SKETCH\""),+ "compact": {"type": "boolean", "description": "Each entry is only {id, label} (default false)"},+ "fields": {+ "type": "array",+ "items": {"type": "string", "enum": COMMAND_FIELDS},+ "description": "Keep only these keys of each entry; overrides `compact`",+ },+ "limit": {"type": "integer", "minimum": 1, "description": "At most this many commands; the reply becomes {commands, total, offset, next_offset}"},+ "offset": {"type": "integer", "minimum": 0, "description": "Skip this many matches first (default 0); with it the reply is paged as with `limit`"},+ }),+ &[],+ ),Effect::ReadOnly,),tool(@@ -146,7 +164,7 @@ pub fn tool_definitions() -> Vec<Value> {"Run commands in order, stopping at the first error. Each step is {command, params}: an engine command id \(as list_commands lists them). A step may also name one of these tools with that tool's arguments as params, \and runs the engine command it stands for: set_parameter (parameters.change; `value` or `expression`), \- list_commands (engine.commands, with `filter`), describe_command (engine.describe), execute ({command, params}), \+ list_commands (engine.commands, narrowed by its arguments), describe_command (engine.describe), execute ({command, params}), \measure (inspect.measure), compare_picture (inspect.compare_picture, numbers only: no overlay PNG), \inspect_design (document.inspect), undo, redo, export, save, open, new_design, crash_reports; screenshot, \body_topology, batch and pending can't be steps. On an error the steps already run are undone (unless \@@ -867,8 +885,9 @@ fn measure_summary_wanted(a: &Map<String, Value>) -> bool {fn dispatch(b: &mut dyn Backend, name: &str, a: &Map<String, Value>) -> Result<Value, String> {match name {"list_commands" => {+ let query = CommandQuery::parse(a)?;let all = b.call("engine.commands", json!({}))?;- Ok(filter_commands(all, str_arg(a, "filter")))+ Ok(query.apply(all))}"describe_command" => {let id = str_arg(a, "id").ok_or("`id` is required")?;@@ -941,11 +960,100 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Map<String, Value>) -> Result<V/// The command catalog filtered by a case-insensitive substring of id, label, panel or tab/// (`list_commands`; not the parameter docs, which name other commands, #269).-fn filter_commands(all: Value, filter: Option<&str>) -> Value {- let Some(f) = filter.map(str::to_lowercase).filter(|f| !f.is_empty()) else { return all };- let hit =- |c: &Value| ["id", "label", "panel", "tab"].iter().any(|k| c.get(*k).and_then(Value::as_str).is_some_and(|s| s.to_lowercase().contains(&f)));- Value::Array(all.as_array().map(|v| v.iter().filter(|c| hit(c)).cloned().collect()).unwrap_or_default())+/// The keys of a `list_commands` entry, which `fields` may keep.+const COMMAND_FIELDS: &[&str] = &["id", "label", "tab", "panel", "icon", "shortcut", "params", "enabled", "disabled_reason", "planned"];++/// How `list_commands` narrows the catalog (#11726): which commands, which keys of each, and+/// which page. The default keeps the whole catalog as it is.+#[derive(Clone, Debug, Default, PartialEq)]+struct CommandQuery {+ filter: Option<String>,+ prefix: Option<String>,+ panel: Option<String>,+ fields: Option<Vec<String>>,+ limit: Option<usize>,+ offset: Option<usize>,+}++impl CommandQuery {+ fn parse(a: &Map<String, Value>) -> Result<Self, String> {+ let text = |k: &str| -> Result<Option<String>, String> {+ match a.get(k) {+ None | Some(Value::Null) => Ok(None),+ Some(Value::String(s)) => Ok(Some(s.to_lowercase()).filter(|s| !s.is_empty())),+ Some(_) => Err(format!("`{k}` must be a string")),+ }+ };+ let count = |k: &str, least: u64| -> Result<Option<usize>, String> {+ match a.get(k) {+ None | Some(Value::Null) => Ok(None),+ Some(v) => v+ .as_u64()+ .filter(|n| *n >= least)+ .map(|n| Some(usize::try_from(n).unwrap_or(usize::MAX)))+ .ok_or_else(|| format!("`{k}` must be a whole number of at least {least}")),+ }+ };+ let compact = match a.get("compact") {+ None | Some(Value::Null) => false,+ Some(v) => v.as_bool().ok_or("`compact` must be true or false")?,+ };+ let fields = match a.get("fields") {+ None | Some(Value::Null) => compact.then(|| vec!["id".to_string(), "label".to_string()]),+ Some(Value::Array(v)) => {+ let mut keep = Vec::new();+ for f in v {+ let name = f.as_str().filter(|n| COMMAND_FIELDS.contains(n)).ok_or_else(|| {+ let shown: String = f.to_string().chars().take(64).collect();+ format!("`fields` takes the entry keys {}; not {shown}", COMMAND_FIELDS.join(", "))+ })?;+ if !keep.iter().any(|k| k == name) {+ keep.push(name.to_string());+ }+ }+ Some(keep)+ }+ Some(_) => return Err("`fields` must be a list of entry keys".into()),+ };+ Ok(Self {+ filter: text("filter")?,+ prefix: text("prefix")?,+ panel: text("panel")?,+ fields,+ limit: count("limit", 1)?,+ offset: count("offset", 0)?,+ })+ }++ fn matches(&self, c: &Value) -> bool {+ let field = |k: &str| c.get(k).and_then(Value::as_str).map(str::to_lowercase).unwrap_or_default();+ self.filter.as_ref().is_none_or(|f| ["id", "label", "panel", "tab"].iter().any(|k| field(k).contains(f.as_str())))+ && self.prefix.as_ref().is_none_or(|p| field("id").starts_with(p.as_str()))+ && self.panel.as_ref().is_none_or(|p| field("panel") == *p || field("tab") == *p)+ }++ /// The catalog narrowed: a list, or `{commands, total, offset, next_offset}` when paged.+ fn apply(&self, all: Value) -> Value {+ let Value::Array(all) = all else { return all };+ let hits: Vec<Value> = all.into_iter().filter(|c| self.matches(c)).collect();+ let total = hits.len();+ let offset = self.offset.unwrap_or(0).min(total);+ let take = self.limit.unwrap_or(usize::MAX);+ let page: Vec<Value> = hits+ .into_iter()+ .skip(offset)+ .take(take)+ .map(|c| match (&self.fields, c) {+ (Some(keep), Value::Object(m)) => Value::Object(m.into_iter().filter(|(k, _)| keep.contains(k)).collect()),+ (_, c) => c,+ })+ .collect();+ if self.limit.is_none() && self.offset.is_none() {+ return Value::Array(page);+ }+ let end = offset + page.len();+ json!({"commands": page, "total": total, "offset": offset, "next_offset": (end < total).then_some(end)})+ }}/// `pending`: the end of a request still running when its call returned (bridged only; a@@ -975,8 +1083,8 @@ fn pending(b: &mut dyn Backend) -> Result<Value, String> {/// How a tool step's result is cut down to what the tool itself would reply.enum Narrow {- /// A `list_commands` step's catalog, filtered as the tool filters it.- Commands(String),+ /// A `list_commands` step's catalog, narrowed as the tool narrows it.+ Commands(CommandQuery),/// A `measure {summary: true}` step's reply, as `measure_summary` shapes it.MeasureSummary,}@@ -984,7 +1092,7 @@ enum Narrow {impl Narrow {fn apply(&self, v: Value) -> Value {match self {- Narrow::Commands(f) => filter_commands(v, Some(f)),+ Narrow::Commands(q) => q.apply(v),Narrow::MeasureSummary => measure_summary(v),}}@@ -1010,7 +1118,10 @@ fn batch_step(step: &Value) -> Result<(String, Value, Option<Narrow>), String> {let a = params.as_object().unwrap_or(&empty);let mapped = |c: &str, p: Value| Ok((c.to_string(), p, None));match command {- "list_commands" => Ok(("engine.commands".into(), json!({}), str_arg(a, "filter").map(|f| Narrow::Commands(f.to_string())))),+ "list_commands" => {+ let query = CommandQuery::parse(a)?;+ Ok(("engine.commands".into(), json!({}), (query != CommandQuery::default()).then_some(Narrow::Commands(query))))+ }"set_parameter" => {let mut p = pick(a, &["name", "unit", "comment"]);p["expression"] = parameter_value(a)?;diff --git a/docs/mcp.md b/docs/mcp.mdindex c8e093f7d8..bcce7120d2 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -289,10 +289,10 @@ The `skill_reference` tool returns these documents from the copies built into So| Tool | Arguments | What it does ||---|---|---|-| `list_commands` | `filter?` | The command catalog: id, label, tab/panel, shortcut, parameter docs, enabled now. `filter` matches id, label, tab and panel. |+| `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`, filtered by `filter` as the tool filters 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}]`, `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 agentcomputes the volume, body count or bounding box a stage should produce before building it;