use serde_json::Value;
fn parse_call_object(body: &str) -> Option<(String, Value)> {
let value: Value = serde_json::from_str(body).ok()?;
let name = value.get("name")?.as_str()?.to_string();
let args = value
.get("arguments")
.or_else(|| value.get("parameters"))
.cloned()
.unwrap_or_else(|| Value::Object(Default::default()));
Some((name, args))
}
pub(super) fn extract_fenced_json(text: &str) -> Option<(String, Value)> {
const FENCE_OPEN: &str = "```json";
const FENCE_CLOSE: &str = "```";
let start = text.find(FENCE_OPEN)? + FENCE_OPEN.len();
let rest = &text[start..];
let end = rest.find(FENCE_CLOSE)?;
parse_call_object(rest[..end].trim())
}
pub(super) fn extract_angle_bracket(text: &str) -> Option<(String, Value)> {
const OPEN: &str = "<tool_call>";
const CLOSE: &str = "</tool_call>";
let start = text.find(OPEN)? + OPEN.len();
let rest = &text[start..];
let end = rest.find(CLOSE)?;
parse_call_object(rest[..end].trim())
}
pub(super) fn extract_balanced_json_scan(text: &str) -> Option<(String, Value)> {
let mut search_from = 0usize;
while let Some(rel_start) = text[search_from..].find('{') {
let start = search_from + rel_start;
let Some(end) = find_balanced_end(text, start) else {
break;
};
if let Some(call) = parse_call_object(&text[start..=end]) {
return Some(call);
}
search_from = start + 1;
}
None
}
fn find_balanced_end(text: &str, start: usize) -> Option<usize> {
let mut depth = 0i32;
let mut in_string = false;
let mut escape = false;
for (idx, ch) in text.char_indices() {
if idx < start {
continue;
}
if in_string {
if escape {
escape = false;
} else if ch == '\\' {
escape = true;
} else if ch == '"' {
in_string = false;
}
continue;
}
match ch {
'"' => in_string = true,
'{' => depth += 1,
'}' => {
depth -= 1;
if depth == 0 {
return Some(idx);
}
}
_ => {}
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn fenced_json_extracts_call() {
let text = "Sure, I'll do that.\n```json\n{\"name\": \"bash\", \"arguments\": {\"command\": \"ls\"}}\n```\nDone.";
let (name, args) = extract_fenced_json(text).expect("fenced call");
assert_eq!(name, "bash");
assert_eq!(args, json!({"command": "ls"}));
}
#[test]
fn fenced_json_none_without_fence() {
assert!(extract_fenced_json("just some prose").is_none());
}
#[test]
fn angle_bracket_extracts_call() {
let text =
"<tool_call>{\"name\": \"read_file\", \"arguments\": {\"path\": \"a.rs\"}}</tool_call>";
let (name, args) = extract_angle_bracket(text).expect("angle-bracket call");
assert_eq!(name, "read_file");
assert_eq!(args, json!({"path": "a.rs"}));
}
#[test]
fn angle_bracket_none_without_tags() {
assert!(extract_angle_bracket("no tags here").is_none());
}
#[test]
fn balanced_scan_recovers_call_from_noisy_text() {
let text = "Let me call the tool: {\"name\": \"bash\", \"arguments\": {\"command\": \"echo hi\"}} — running now.";
let (name, args) = extract_balanced_json_scan(text).expect("scanned call");
assert_eq!(name, "bash");
assert_eq!(args, json!({"command": "echo hi"}));
}
#[test]
fn balanced_scan_handles_nested_braces() {
let text = r#"{"name": "write_file", "arguments": {"path": "a.json", "content": "{\"nested\": true}"}}"#;
let (name, args) = extract_balanced_json_scan(text).expect("scanned call");
assert_eq!(name, "write_file");
assert_eq!(args["path"], "a.json");
}
#[test]
fn balanced_scan_skips_non_matching_object_then_finds_real_call() {
let text = r#"Example: {"foo": "bar"} then the real call {"name": "bash", "arguments": {"command": "pwd"}}"#;
let (name, _) = extract_balanced_json_scan(text).expect("scanned call");
assert_eq!(name, "bash");
}
#[test]
fn balanced_scan_none_when_no_object_present() {
assert!(extract_balanced_json_scan("no json here at all").is_none());
}
#[test]
fn parse_call_object_accepts_parameters_alias() {
let (name, args) =
parse_call_object(r#"{"name": "bash", "parameters": {"command": "ls"}}"#)
.expect("parsed call");
assert_eq!(name, "bash");
assert_eq!(args, json!({"command": "ls"}));
}
#[test]
fn parse_call_object_rejects_missing_name() {
assert!(parse_call_object(r#"{"arguments": {}}"#).is_none());
}
}