From 3bca787213af0949801a0dab96d0657aa023b99b Mon Sep 17 00:00:00 2001 From: raykholo Date: Fri, 23 Oct 2026 13:44:07 +0000 Subject: [PATCH] MCP tools: unknown command ids suggest the closest ids (#4846) (#4915) * claim: #4846 * MCP tools: unknown command ids suggest the closest ids (#4846) An unknown command id in `execute` or `batch` now lists up to three closest ids, and an id with parameters packed into it says to pass them in `params`. --- crates/mcp/src/tests.rs | 36 +++++++++++++++++++++ crates/mcp/src/tools.rs | 72 +++++++++++++++++++++++++++++++++++++++-- 2 files changed, 106 insertions(+), 2 deletions(-) diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 9fb35f362..dd664b40f 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -602,6 +602,42 @@ fn unknown_tools_and_bad_arguments_are_clean_errors() { assert_eq!(serde_json::from_str::(&both).unwrap().as_array().unwrap().len(), 1); } +#[test] +fn tool_unknown_command_errors_suggest_close_ids() { + let mut s = server(); + for id in ["solid.bxo", "SOLID_BOX", "solid-box", "solid box", "madeup.box"] { + for name in ["execute", "batch"] { + let step = json!({"command": id}); + let args = if name == "batch" { json!({"commands": [step]}) } else { step }; + let r = raw_tool(&mut s, name, args); + assert_eq!(r["result"]["isError"], true, "{r}"); + let text = r["result"]["content"][0]["text"].as_str().unwrap(); + assert!(text.contains("closest: `solid.box`"), "{text}"); + } + } + let r = raw_tool(&mut s, "execute", json!({"command": "solid.box"})); + let text = r["result"]["content"][0]["text"].as_str().unwrap(); + assert!(text.contains("solid.box") && text.contains("length"), "{text}"); +} + +#[test] +fn tool_unknown_command_errors_explain_packed_params() { + let mut s = server(); + for id in ["solid.cube {side: 20}", "solid.box(20)"] { + for name in ["execute", "batch"] { + let step = json!({"command": id}); + let args = if name == "batch" { json!({"commands": [step]}) } else { step }; + let r = raw_tool(&mut s, name, args); + assert_eq!(r["result"]["isError"], true, "{r}"); + assert!(r["result"]["content"][0]["text"].as_str().unwrap().contains("command ids have no parameters; pass them in `params`"), "{r}"); + } + } + let reply = json!({"completed": 0, "results": [], "failed": {"index": 0, "command": "solid.cube {side: 20}", "error": "unknown command `solid.cube {side: 20}`"}, "undone": 0}); + let (_, body, error) = recorded_batch(Ok(reply), json!({"commands": [{"command": "solid.cube {side: 20}"}]})); + assert!(error); + assert!(body["failed"]["error"].as_str().unwrap().contains("command ids have no parameters; pass them in `params`"), "{body}"); +} + fn hostile_values() -> Vec { vec![ Value::Null, diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index e464adf53..6f21fd120 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -402,7 +402,65 @@ pub fn call_tool(b: &mut dyn Backend, name: &str, args: &Value) -> Value { } fn exec(b: &mut dyn Backend, command: &str, params: Value) -> Result { - b.call("engine.execute", json!({"command": command, "params": params})) + b.call("engine.execute", json!({"command": command, "params": params})).map_err(|error| command_error(command, error)) +} + +/// Enrich an unknown-id error without retrying or changing the command that was requested. +fn command_error(command: &str, error: String) -> String { + if !error.starts_with(&format!("unknown command `{command}`")) { + return error; + } + // Bound the quadratic comparison work, including for direct callers without a line cap. + if command.len() > 128 { + return error; + } + let id = command.split(['{', '(']).next().unwrap_or(command).trim(); + let packed = id != command.trim(); + let normalize = |s: &str| s.chars().filter(char::is_ascii_alphanumeric).map(|c| c.to_ascii_lowercase()).collect::(); + let normalized = normalize(id); + if normalized.is_empty() { + return error; + } + let words: Vec<_> = id.split(|c: char| !c.is_ascii_alphanumeric()).filter(|s| !s.is_empty()).collect(); + let mut closest: Vec<_> = solidcraft_engine::command_specs() + .into_iter() + .filter_map(|spec| { + let candidate = normalize(spec.id); + let distance = command_distance(&normalized, &candidate); + let shared = spec.id.split('.').filter(|word| words.iter().any(|w| w.eq_ignore_ascii_case(word))).count(); + (distance <= (normalized.len() / 4).max(2) || shared > 0).then_some(( + normalized != candidate, + distance, + std::cmp::Reverse(shared), + spec.id, + )) + }) + .collect(); + closest.sort_unstable(); + let hints: Vec<_> = closest.iter().take(3).map(|(_, _, _, id)| format!("`{id}`")).collect(); + let mut message = format!("unknown command `{command}`"); + if !hints.is_empty() { + message.push_str(&format!("; closest: {}", hints.join(", "))); + } + if packed { + message.push_str("; command ids have no parameters; pass them in `params`"); + } + message +} + +fn command_distance(a: &str, b: &str) -> usize { + let mut row: Vec = (1..=b.len()).collect(); + for (i, ca) in a.bytes().enumerate() { + let mut diagonal = i; + let mut left = i + 1; + for (cell, cb) in row.iter_mut().zip(b.bytes()) { + let next = (diagonal + usize::from(ca != cb)).min(*cell + 1).min(left + 1); + diagonal = *cell; + *cell = next; + left = next; + } + } + row.last().copied().unwrap_or(a.len()) } fn pick(a: &Map, keys: &[&str]) -> Value { @@ -582,7 +640,17 @@ fn batch(b: &mut dyn Backend, a: &Map) -> Value { } if params.to_string().len() + 64 * 1024 <= solidcraft_engine::MAX_LINE { match b.call("engine.batch", params) { - Ok(r) => return batch_reply(&r, rollback, verbose), + Ok(mut r) => { + if let Some(failed) = r.get_mut("failed") + && let (Some(command), Some(error)) = (failed.get("command").and_then(Value::as_str), failed.get("error").and_then(Value::as_str)) + { + let error = command_error(command, error.to_string()); + if let Some(failed) = failed.as_object_mut() { + failed.insert("error".into(), Value::String(error)); + } + } + return batch_reply(&r, rollback, verbose); + } // Older apps and the headless session, or the app wants the steps one by one. Err(e) if e.starts_with("unknown method") || e.starts_with("engine.batch unavailable") => {} // Never sent: no app to send it to.