Skip to content

Craft Anything: understand how any software works, and craft your own.

Rust

Help models correct rejected tool argument types (#546)

Afloat888f75b3f16a
diff --git a/Cargo.lock b/Cargo.lock
index 43f9ecef..6669c1d0 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1226,6 +1226,7 @@ dependencies = [
"schemars",
"serde",
"serde_json",
+ "serde_path_to_error",
"sha1",
"sha2",
"tempfile",
@@ -5754,6 +5755,17 @@ dependencies = [
"zmij",
]
+[[package]]
+name = "serde_path_to_error"
+version = "0.1.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"
+dependencies = [
+ "itoa",
+ "serde",
+ "serde_core",
+]
+
[[package]]
name = "serde_repr"
version = "0.1.21"
diff --git a/Cargo.toml b/Cargo.toml
index ea6e986b..be1fcbab 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -29,6 +29,7 @@ craft-anything-testkit = { path = "crates/testkit" }
thiserror = "2"
serde = { version = "1", features = ["derive", "rc"] }
serde_json = "1"
+serde_path_to_error = "0.1"
sha2 = "0.10"
hex = "0.4"
bitflags = { version = "2", features = ["serde"] }
diff --git a/crates/ai/src/tests.rs b/crates/ai/src/tests.rs
index 57eab5e9..e3968a1e 100644
--- a/crates/ai/src/tests.rs
+++ b/crates/ai/src/tests.rs
@@ -597,6 +597,46 @@ fn local_server_without_tools_falls_back_to_react() {
assert!(last["content"].as_str().unwrap().starts_with("Observation:"));
}
+/// #498: return a field-specific error to the model, then accept its corrected call.
+#[test]
+fn a_model_can_correct_an_array_sent_to_a_string_parameter() {
+ let call = |id: &str, input: Value| {
+ chat_sse(&[json!({"choices":[{
+ "delta":{"tool_calls":[{"index":0,"id":id,"type":"function","function":{
+ "name":"core_unknown_add","arguments":input.to_string()
+ }}]},"finish_reason":"tool_calls"
+ }]})])
+ };
+ let (url, seen) = mock(vec![
+ (200, "text/event-stream", call("wrong", json!({"question": ["Where is the loop?"]}))),
+ (200, "text/event-stream", call("corrected", json!({"question": "Where is the loop?"}))),
+ (200, "text/event-stream", chat_sse(&[json!({"choices":[{"delta":{"content":"Recorded."},"finish_reason":"stop"}]})])),
+ ]);
+ let (h, _d) = hub();
+ add(&h, "Local", BackendKind::OpenaiCompatible, &url, None);
+ let mut c = h.start(Some("Local"), true).unwrap();
+ let events = run(&mut c, "Record what remains unknown.");
+ let completed: Vec<_> = events
+ .iter()
+ .filter_map(|event| match event {
+ AgentEvent::ToolFinished { tool, ok, .. } if tool == "core_unknown_add" => Some(*ok),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(completed, vec![false, true]);
+ assert_eq!(h.engine.session().unknowns().count(), 1, "only the corrected call creates a record");
+ let seen = seen.lock().unwrap();
+ assert_eq!(seen.len(), 3);
+ let result = seen[1].body["messages"].as_array().unwrap().last().unwrap();
+ assert_eq!(result["role"], "tool");
+ assert_eq!(result["tool_call_id"], "wrong");
+ let error: Value = serde_json::from_str(result["content"].as_str().unwrap()).unwrap();
+ assert_eq!(error["error"]["code"], "bad_input");
+ assert_eq!(error["error"]["details"]["parameter_path"], "/question");
+ assert!(error["error"]["message"].as_str().unwrap().contains("expected a string"));
+ assert!(error["error"]["remediation"].as_str().unwrap().contains("call the tool again"));
+}
+
#[test]
fn json_text_tool_calls_execute_through_both_protocols() {
for react in [false, true] {
diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml
index 2c201f45..2ef34dbd 100644
--- a/crates/engine/Cargo.toml
+++ b/crates/engine/Cargo.toml
@@ -19,6 +19,7 @@ craft-anything-platform = { workspace = true }
craft-anything-engines = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
+serde_path_to_error = { workspace = true }
schemars = { workspace = true }
bitflags = { workspace = true }
thiserror = { workspace = true }
diff --git a/crates/engine/src/tool.rs b/crates/engine/src/tool.rs
index 350e4849..193ab312 100644
--- a/crates/engine/src/tool.rs
+++ b/crates/engine/src/tool.rs
@@ -305,5 +305,121 @@ pub fn empty_schema() -> Value {
/// Parse tool params; `null` is treated as `{}` so programmatic callers can omit them.
pub fn parse_params<T: DeserializeOwned>(v: Value) -> Result<T, ToolError> {
let v = if v.is_null() { Value::Object(Default::default()) } else { v };
- serde_json::from_value(v).map_err(|e| ToolError::invalid(format!("invalid params: {e}")))
+ serde_path_to_error::deserialize(v).map_err(|error| {
+ let pointer = parameter_pointer(error.path());
+ let location = pointer.as_deref().filter(|p| !p.is_empty()).map(|p| format!(" at {p:?}")).unwrap_or_default();
+ ToolError::invalid(format!("invalid params{location}: {}", error.inner()))
+ .with_remediation("Correct the parameter to match the tool's input schema, then call the tool again.")
+ .with_details(serde_json::json!({"parameter_path": pointer}))
+ })
+}
+
+/// A JSON Pointer to the rejected value, without guessing when Serde cannot locate it.
+fn parameter_pointer(path: &serde_path_to_error::Path) -> Option<String> {
+ const LIMIT: usize = 1024;
+ let mut pointer = String::new();
+ for segment in path {
+ pointer.push('/');
+ match segment {
+ serde_path_to_error::Segment::Map { key } if key.len() <= LIMIT => {
+ pointer.push_str(&key.replace('~', "~0").replace('/', "~1"));
+ }
+ serde_path_to_error::Segment::Seq { index } => pointer.push_str(&index.to_string()),
+ // Enum variants need not be object keys (for example, internally tagged enums).
+ _ => return None,
+ }
+ if pointer.len() > LIMIT {
+ return None;
+ }
+ }
+ Some(pointer)
+}
+
+#[cfg(test)]
+mod parameter_tests {
+ use super::*;
+ use craft_anything_evidence::ErrorCode;
+ use serde_json::json;
+
+ #[derive(Debug, Deserialize, PartialEq)]
+ #[serde(deny_unknown_fields)]
+ struct Question {
+ question: String,
+ #[serde(default)]
+ probes: Vec<String>,
+ }
+
+ #[test]
+ fn an_array_for_a_string_identifies_the_parameter_to_correct() {
+ for input in [json!({"question": ["Where?"]}), json!({"question": ["Where?", "Why?"]})] {
+ let error = parse_params::<Question>(input).unwrap_err();
+ assert_eq!(error.code, ErrorCode::BadInput);
+ assert!(error.message.contains("question") && error.message.contains("expected a string"), "{error:?}");
+ assert_eq!(error.details.as_ref().unwrap()["parameter_path"], "/question");
+ assert!(error.remediation.as_deref().unwrap().contains("call the tool again"));
+ assert!(!error.message.contains("Where?"), "the parameter value is not needed to locate the error");
+ }
+ let valid = parse_params::<Question>(json!({"question": "Where?", "probes": ["inspect"]})).unwrap();
+ assert_eq!(valid, Question { question: "Where?".into(), probes: vec!["inspect".into()] });
+ }
+
+ #[test]
+ fn a_nested_parameter_error_keeps_the_array_index() {
+ let error = parse_params::<Question>(json!({"question": "Where?", "probes": ["inspect", ["trace"]]})).unwrap_err();
+ assert_eq!(error.details.as_ref().unwrap()["parameter_path"], "/probes/1");
+ assert!(error.message.contains("expected a string"), "{error:?}");
+ }
+
+ #[test]
+ fn a_parameter_path_escapes_json_pointer_keys() {
+ #[derive(Debug, Deserialize)]
+ struct Envelope {
+ #[serde(rename = "a~/b")]
+ _questions: Vec<Question>,
+ }
+ let error = parse_params::<Envelope>(json!({"a~/b": [{"question": ["Where?"]}]})).unwrap_err();
+ assert_eq!(error.details.as_ref().unwrap()["parameter_path"], "/a~0~1b/0/question");
+ }
+
+ #[test]
+ fn oversized_parameter_paths_are_not_reported_as_complete_pointers() {
+ let input = json!({"x".repeat(2048): {"question": ["Where?"]}});
+ let error = parse_params::<std::collections::BTreeMap<String, Question>>(input).unwrap_err();
+ assert!(error.details.as_ref().unwrap()["parameter_path"].is_null());
+ assert!(error.message.len() < 200);
+ assert!(error.message.contains("expected a string"));
+ }
+
+ #[test]
+ fn an_enum_path_does_not_guess_a_json_object_location() {
+ #[derive(Debug, Deserialize)]
+ enum Choice {
+ Question(Question),
+ }
+ let error = parse_params::<Choice>(json!({"Question": {"question": ["Where?"]}})).unwrap_err();
+ assert!(error.details.as_ref().unwrap()["parameter_path"].is_null());
+ assert!(error.message.contains("expected a string"));
+ let Choice::Question(valid) = parse_params::<Choice>(json!({"Question": {"question": "Where?"}})).unwrap();
+ assert_eq!(valid.question, "Where?");
+ }
+
+ #[test]
+ fn parameter_defaults_and_strictness_are_preserved() {
+ #[derive(Debug, Default, Deserialize, PartialEq)]
+ struct Defaults {
+ #[serde(default)]
+ count: u32,
+ }
+ assert_eq!(parse_params::<Defaults>(Value::Null).unwrap(), Defaults::default());
+ assert_eq!(parse_params::<Defaults>(json!({"count": 4})).unwrap().count, 4);
+ for input in [json!({"count": -1}), json!({"count": "4"}), json!({"count": u64::MAX})] {
+ let error = parse_params::<Defaults>(input).unwrap_err();
+ assert_eq!(error.details.as_ref().unwrap()["parameter_path"], "/count");
+ }
+ let missing = parse_params::<Question>(json!({"probes": []})).unwrap_err();
+ assert!(missing.message.contains("missing field `question`"));
+ assert_eq!(missing.details.as_ref().unwrap()["parameter_path"], "", "the known location is the parent object, not an invented missing value");
+ let extra = parse_params::<Question>(json!({"question": "Where?", "surprise": true})).unwrap_err();
+ assert!(extra.message.contains("unknown field `surprise`"));
+ }
}
diff --git a/crates/engine/src/tools/session_tools.rs b/crates/engine/src/tools/session_tools.rs
index 94ab331c..37c55d47 100644
--- a/crates/engine/src/tools/session_tools.rs
+++ b/crates/engine/src/tools/session_tools.rs
@@ -689,6 +689,21 @@ mod tests {
assert_eq!(v["result"]["valid"], false, "cites no evidence");
}
+ /// #498: the bad field must be identifiable, and rejected input must not create an unknown.
+ #[test]
+ fn an_unknown_can_be_recorded_after_correcting_its_parameter_type() {
+ let e = Engine::new(crate::testing::session());
+ for caller in [Caller::Agent, Caller::Mcp, Caller::Cli] {
+ let error = e.call("core_unknown_add", json!({"question": ["Where is the loop?"]}), CallOptions::new(caller)).unwrap_err();
+ assert_eq!(error.code, craft_anything_evidence::ErrorCode::BadInput);
+ assert_eq!(error.details.as_ref().unwrap()["parameter_path"], "/question");
+ assert!(error.message.contains("expected a string"));
+ assert_eq!(e.session().unknowns().count(), 0);
+ }
+ e.call("core_unknown_add", json!({"question": "Where is the loop?"}), CallOptions::new(Caller::Agent)).unwrap();
+ assert_eq!(e.session().unknowns().count(), 1);
+ }
+
#[test]
fn project_evidence_is_loaded_in_a_new_session() {
use crate::project::{Project, Purpose};
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 9ba8f746..25c62a97 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -199,8 +199,9 @@ been run live.
- [x] Preserve `length` and `content_filter` stop reasons on native tool-call streams; a parsed
call must not override truncation or refusal and execute tools. Pair other retained
unexecuted calls with results before the conversation continues — PR #544
-- [ ] Accept a tool argument of a near type, such as a list for a string, or answer so the model
- can correct it (#498)
+- [x] Return a rejected tool argument's JSON Pointer when known and guidance to correct the call
+ (#498), keeping schema types strict
+ — commit `0c3ae5cca569`
- [ ] Find how each local server is told its context size and set it, or stop with a plain message
when the prompt won't fit. We assume 24k and send no `num_ctx`, which an OpenAI-style endpoint
may ignore anyway; LM Studio refused a 12.6k prompt on its 8k default (#73)
diff --git a/docs/STATUS.md b/docs/STATUS.md
index f5824289..fdd9b072 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -14,6 +14,7 @@ workspace clippy, layers, fmt and the secret scan of all history were clean. Chi
| Apple app graphs | Selecting a macOS bundle recognises its root-relative `Contents/Info.plist` and retains its service/extension type; nested XPC bundles appear in `services` and as `xpc-service` graph nodes, including their executables when hosted in frameworks | Synthetic inventory tests, including parent-directory and flat bundle layouts, selected services/extensions, framework-hosted service executables, and bare-program controls. Ordinary selected directories with `Contents/Info.plist` need an Apple bundle suffix; archives retain layout-based recognition. Framework libraries and dylibs stay excluded from executables. Real app bundles were not checked for this correction |
| Chinese UI | Simplified (`zh-hans`) and Traditional (`zh-hant`) Chinese in Settings → General → Language; System chooses a supported OS language, otherwise English. Both catalogs cover UI controls and tool titles; translated titles are searchable. Raw tool data, AI text, logs, CLI/MCP and the separate browser viewer keep their original text. See [localisation](localization.md). | Catalog integrity and locale-resolution tests; `cargo xtask i18n-coverage`; isolated UI language-switch test. Platform visual checks are recorded separately. |
| Engine | 298 engine tools (314 with the AI and setup layers') across native, managed, Java, Android, Apple, JS/Electron, web, firmware, packets, databases, game archives and assets; see [tools.md](tools.md) and [tool-status.md](tool-status.md). A saved result can be narrowed without running again (`core_evidence_browse` keeps the rows matching given field values, cut to chosen fields) | A functional audit that ran every tool on real inputs on Windows, plus 600+ unit and integration tests |
+| Tool argument correction | Shared parameter parsing keeps schema types strict and reports the rejected value's JSON Pointer when known, the original type error and guidance to correct the call. Unknown locations are null; a root failure uses the empty pointer | Parser regressions cover string/array mismatches, nested indices, escaped keys, oversized paths, enum locations, defaults and strict fields. Shared engine dispatch is checked for Agent, MCP and CLI callers: rejected arrays create no record, and corrected input creates one. No live Qwen or Ollama build was run for this correction |
| Java class usage | `java_class_users_find` includes the component class of multidimensional object arrays; primitive-array descriptors do not match an unrelated class with the same descriptor letter | Synthetic class files parsed by the built-in reader: one- and two-dimensional allocations, class names beginning with `L`, primitive arrays, hit limits and method filters; formats tests. This correction was not checked with javac output or a JVM |
| Single-file apps and game files | `core_packed_files_list` and `core_packed_files_unpack` read Bun and Node.js single-file programs, .NET single-file apps, PyInstaller and Godot packs through one seam (`formats::packed`); `formats_bytecode_show` reads Python bytecode, `game_unity_code_names_show` Unity IL2CPP metadata, `formats_ai_weights_show` GGUF and safetensors headers. `app_folder_explain` says what an install folder is made with and what to run next | Unit tests with damaged files. Real files: a 279 MB Bun program, Node blobs, PyInstaller programs (Python 3.9, 3.14), .NET 8 single-file apps (macOS, Linux, Windows, compressed), Godot 3.6, 4.3 and 4.5 packs, 214 Python modules against CPython's own reader, a GGUF and a safetensors file, about 25 installed Mac apps. IL2CPP on synthetic files only |
| esbuild module dependencies | Recognised CommonJS and ESM wrappers keep their dependency edges after identifier minification; semantic bindings distinguish shadowed and reused names, and repeated calls produce one edge | 44 JS unit tests pass. New synthetic regressions cover short names, forward declarations, both wrapper kinds, shadowed parameters, reused names, unrelated calls and duplicates. No real minified application was run for this correction; sources above the existing semantic-analysis size limit retain name-based resolution |