1use std::collections::HashSet;
11
12use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result, TOOL_INVALID_ARGUMENTS_CODE};
13use serde_json::{Map, Value};
14
15const MAX_REPORTED_VIOLATIONS: usize = 8;
17
18const MAX_VIOLATION_CHARS: usize = 200;
20
21pub const TOOL_INVALID_PARAMETERS_SCHEMA_CODE: &str = "tool.invalid_parameters_schema";
23
24pub struct ToolArgumentValidator {
51 validator: jsonschema::Validator,
52}
53
54impl std::fmt::Debug for ToolArgumentValidator {
55 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56 f.debug_struct("ToolArgumentValidator").finish_non_exhaustive()
57 }
58}
59
60impl ToolArgumentValidator {
61 pub fn new(schema: &Value) -> Result<Self> {
71 let validator = jsonschema::validator_for(schema).map_err(|error| {
72 AdkError::new(
73 ErrorComponent::Tool,
74 ErrorCategory::Internal,
75 TOOL_INVALID_PARAMETERS_SCHEMA_CODE,
76 format!(
77 "the tool's parameters schema does not compile: {error}. Fix the schema the \
78 tool declares."
79 ),
80 )
81 })?;
82 Ok(Self { validator })
83 }
84
85 pub fn validate(&self, tool_name: &str, args: &Value) -> Result<()> {
93 let mut violations = Vec::new();
94 let mut total = 0usize;
95 for error in self.validator.iter_errors(args) {
96 total += 1;
97 if violations.len() == MAX_REPORTED_VIOLATIONS {
98 continue;
99 }
100 let path = error.instance_path().as_str();
101 let location = if path.is_empty() { "arguments" } else { path };
102 violations.push(format!("{location}: {}", truncate(&error.to_string())));
103 }
104 if total == 0 {
105 return Ok(());
106 }
107 if total > violations.len() {
108 violations.push(format!("and {} more", total - violations.len()));
109 }
110 Err(AdkError::new(
111 ErrorComponent::Tool,
112 ErrorCategory::InvalidInput,
113 TOOL_INVALID_ARGUMENTS_CODE,
114 format!(
115 "invalid arguments for '{tool_name}': {}. Correct the arguments to match the \
116 tool's parameters schema and call it again.",
117 violations.join("; ")
118 ),
119 ))
120 }
121}
122
123fn truncate(message: &str) -> String {
124 match message.char_indices().nth(MAX_VIOLATION_CHARS) {
125 Some((end, _)) => format!("{}…", &message[..end]),
126 None => message.to_string(),
127 }
128}
129
130pub(crate) struct ArgumentCheck {
132 schema: Value,
134 validator: std::result::Result<ToolArgumentValidator, String>,
136}
137
138impl ArgumentCheck {
139 pub(crate) fn for_type<T: schemars::JsonSchema>() -> Self {
144 let schema = serde_json::to_value(schemars::schema_for!(T)).unwrap_or_default();
145 let mut closed = schema.clone();
146 close_object_schemas(&mut closed);
147 let validator = ToolArgumentValidator::new(&closed).map_err(|error| error.message);
148 Self { schema, validator }
149 }
150
151 pub(crate) fn apply(&self, tool_name: &str, lenient: bool, args: &mut Value) -> Result<()> {
154 coerce_integral_floats(&self.schema, args);
155 if lenient {
156 return Ok(());
157 }
158 match &self.validator {
159 Ok(validator) => validator.validate(tool_name, args),
160 Err(message) => Err(AdkError::new(
161 ErrorComponent::Tool,
162 ErrorCategory::Internal,
163 TOOL_INVALID_PARAMETERS_SCHEMA_CODE,
164 message.clone(),
165 )),
166 }
167 }
168}
169
170const EXACT_F64_INTEGERS: f64 = 9_007_199_254_740_992.0;
172
173pub fn coerce_integral_floats(schema: &Value, args: &mut Value) {
197 coerce_at(schema, schema, args, 0);
198}
199
200fn coerce_at(root: &Value, schema: &Value, value: &mut Value, depth: usize) {
201 if depth > 64 {
203 return;
204 }
205 let Some(obj) = schema.as_object() else {
206 return;
207 };
208 if let Some(target) = obj
209 .get("$ref")
210 .and_then(Value::as_str)
211 .and_then(|reference| reference.strip_prefix('#'))
212 .and_then(|pointer| root.pointer(pointer))
213 {
214 coerce_at(root, target, value, depth + 1);
215 }
216 let integer_only = match obj.get("type") {
217 Some(Value::String(kind)) => kind == "integer",
218 Some(Value::Array(kinds)) => {
219 kinds.iter().any(|kind| kind == "integer") && !kinds.iter().any(|kind| kind == "number")
220 }
221 _ => false,
222 };
223 match value {
224 Value::Number(number) if integer_only && number.is_f64() => {
225 if let Some(float) = number.as_f64()
226 && float.fract() == 0.0
227 && float.abs() < EXACT_F64_INTEGERS
228 {
229 *value =
231 if float < 0.0 { Value::from(float as i64) } else { Value::from(float as u64) };
232 }
233 }
234 Value::Object(members) => {
235 let properties = obj.get("properties").and_then(Value::as_object);
236 for (name, member) in members.iter_mut() {
237 match properties.and_then(|properties| properties.get(name)) {
238 Some(sub) => coerce_at(root, sub, member, depth + 1),
239 None => {
240 if let Some(sub @ Value::Object(_)) = obj.get("additionalProperties") {
241 coerce_at(root, sub, member, depth + 1);
242 }
243 }
244 }
245 }
246 }
247 Value::Array(items) => {
248 let prefix =
249 obj.get("prefixItems").and_then(Value::as_array).map_or(&[][..], Vec::as_slice);
250 for (index, item) in items.iter_mut().enumerate() {
251 match prefix.get(index) {
252 Some(sub) => coerce_at(root, sub, item, depth + 1),
253 None => {
254 if let Some(sub @ Value::Object(_)) = obj.get("items") {
255 coerce_at(root, sub, item, depth + 1);
256 }
257 }
258 }
259 }
260 }
261 _ => {}
262 }
263 for keyword in ["allOf", "anyOf", "oneOf"] {
264 if let Some(Value::Array(branches)) = obj.get(keyword) {
265 for branch in branches {
266 coerce_at(root, branch, value, depth + 1);
267 }
268 }
269 }
270}
271
272pub fn close_object_schemas(schema: &mut Value) {
300 let mut partial_definitions = HashSet::new();
301 collect_all_of_references(schema, &mut partial_definitions);
302 close(schema, true, &partial_definitions);
303}
304
305const COMBINATORS: [&str; 3] = ["allOf", "anyOf", "oneOf"];
306
307fn close(schema: &mut Value, complete: bool, partial_definitions: &HashSet<String>) {
308 let Some(obj) = schema.as_object_mut() else {
309 return;
310 };
311 let has_properties = obj.get("properties").is_some_and(Value::is_object);
312 let extendable = ["additionalProperties", "patternProperties", "unevaluatedProperties"]
313 .iter()
314 .chain(&["$ref", "if"])
315 .chain(&COMBINATORS)
316 .any(|keyword| obj.contains_key(*keyword));
317 if complete && has_properties && !extendable {
318 obj.insert("additionalProperties".to_string(), Value::Bool(false));
319 }
320
321 for keyword in ["properties", "patternProperties"] {
322 if let Some(Value::Object(children)) = obj.get_mut(keyword) {
323 children.values_mut().for_each(|child| close(child, true, partial_definitions));
324 }
325 }
326 for keyword in ["$defs", "definitions"] {
327 if let Some(Value::Object(definitions)) = obj.get_mut(keyword) {
328 for (name, definition) in definitions.iter_mut() {
329 close(definition, !partial_definitions.contains(name), partial_definitions);
330 }
331 }
332 }
333 for keyword in ["items", "additionalProperties", "unevaluatedProperties", "contains"] {
334 match obj.get_mut(keyword) {
335 Some(child @ Value::Object(_)) => close(child, true, partial_definitions),
336 Some(Value::Array(children)) => {
337 children.iter_mut().for_each(|child| close(child, true, partial_definitions));
338 }
339 _ => {}
340 }
341 }
342 if let Some(Value::Array(children)) = obj.get_mut("prefixItems") {
343 children.iter_mut().for_each(|child| close(child, true, partial_definitions));
344 }
345 for keyword in COMBINATORS {
346 let branch_complete = keyword != "allOf" && !has_properties;
348 if let Some(Value::Array(branches)) = obj.get_mut(keyword) {
349 for branch in branches {
350 close(branch, branch_complete, partial_definitions);
351 }
352 }
353 }
354 for keyword in ["not", "if", "then", "else"] {
355 if let Some(child) = obj.get_mut(keyword) {
356 close(child, false, partial_definitions);
357 }
358 }
359 if let Some(Value::Object(children)) = obj.get_mut("dependentSchemas") {
360 children.values_mut().for_each(|child| close(child, false, partial_definitions));
361 }
362}
363
364fn collect_all_of_references(schema: &Value, names: &mut HashSet<String>) {
366 match schema {
367 Value::Object(obj) => {
368 if let Some(Value::Array(branches)) = obj.get("allOf") {
369 for branch in branches {
370 if let Some(name) = branch.get("$ref").and_then(Value::as_str).and_then(|r| {
371 r.strip_prefix("#/$defs/").or_else(|| r.strip_prefix("#/definitions/"))
372 }) {
373 names.insert(name.to_string());
374 }
375 }
376 }
377 obj.values().for_each(|child| collect_all_of_references(child, names));
378 }
379 Value::Array(children) => {
380 children.iter().for_each(|child| collect_all_of_references(child, names));
381 }
382 _ => {}
383 }
384}
385
386pub fn model_facing_schema(mut schema: Value) -> Value {
411 if let Some(obj) = schema.as_object_mut() {
412 obj.remove("$schema");
413 obj.remove("title");
414 }
415 simplify_nullable(&mut schema);
416 schema
417}
418
419fn simplify_nullable(schema: &mut Value) {
420 match schema {
421 Value::Object(map) => {
422 if let Some(Value::Array(types)) = map.get("type") {
423 let non_null: Vec<_> =
424 types.iter().filter(|t| t.as_str() != Some("null")).cloned().collect();
425 if let [only] = non_null.as_slice() {
426 map.insert("type".to_string(), only.clone());
427 }
428 }
429 if let Some(Value::Array(any_of)) = map.remove("anyOf") {
430 merge_first_non_null(map, &any_of);
431 }
432 map.values_mut().for_each(simplify_nullable);
433 }
434 Value::Array(items) => items.iter_mut().for_each(simplify_nullable),
435 _ => {}
436 }
437}
438
439fn merge_first_non_null(map: &mut Map<String, Value>, any_of: &[Value]) {
440 let variant = any_of
441 .iter()
442 .filter_map(Value::as_object)
443 .find(|variant| variant.get("type").and_then(Value::as_str) != Some("null"));
444 if let Some(variant) = variant {
445 for (key, value) in variant {
446 map.insert(key.clone(), value.clone());
447 }
448 }
449}
450
451#[cfg(test)]
452mod tests {
453 use super::*;
454 use serde_json::json;
455
456 fn closed(mut schema: Value) -> Value {
457 close_object_schemas(&mut schema);
458 schema
459 }
460
461 #[test]
462 fn closes_complete_objects_and_their_definitions() {
463 let schema = closed(json!({
464 "type": "object",
465 "properties": {
466 "address": { "$ref": "#/$defs/Address", "description": "where" },
467 "tags": { "type": "array", "items": { "type": "object", "properties": { "k": {} } } }
468 },
469 "$defs": { "Address": { "type": "object", "properties": { "city": {} } } }
470 }));
471 assert_eq!(schema["additionalProperties"], false);
472 assert_eq!(schema["$defs"]["Address"]["additionalProperties"], false);
473 assert_eq!(schema["properties"]["tags"]["items"]["additionalProperties"], false);
474 assert!(schema["properties"]["address"].get("additionalProperties").is_none());
476 }
477
478 #[test]
479 fn leaves_declared_and_open_ended_objects_alone() {
480 let schema = closed(json!({
481 "type": "object",
482 "properties": {
483 "open": { "type": "object", "properties": { "a": {} }, "additionalProperties": true },
484 "map": { "type": "object", "additionalProperties": { "type": "string" } },
485 "free": { "type": "object" }
486 }
487 }));
488 assert_eq!(schema["properties"]["open"]["additionalProperties"], true);
489 assert_eq!(
490 schema["properties"]["map"]["additionalProperties"],
491 json!({ "type": "string" })
492 );
493 assert!(schema["properties"]["free"].get("additionalProperties").is_none());
494 }
495
496 #[test]
497 fn leaves_partial_schemas_open() {
498 let flattened = closed(json!({
500 "type": "object",
501 "properties": { "name": {} },
502 "oneOf": [
503 { "type": "object", "properties": { "a": {} } },
504 { "type": "object", "properties": { "b": {} } }
505 ]
506 }));
507 assert!(flattened.get("additionalProperties").is_none());
508 assert!(flattened["oneOf"][0].get("additionalProperties").is_none());
509
510 let composed = closed(json!({
511 "allOf": [
512 { "$ref": "#/$defs/Base" },
513 { "type": "object", "properties": { "extra": {} } }
514 ],
515 "if": { "properties": { "kind": { "const": "x" } } },
516 "$defs": { "Base": { "type": "object", "properties": { "id": {} } } }
517 }));
518 assert!(composed["allOf"][1].get("additionalProperties").is_none());
519 assert!(composed["if"].get("additionalProperties").is_none());
520 assert!(composed["$defs"]["Base"].get("additionalProperties").is_none());
521 }
522
523 #[test]
524 fn closes_whole_value_branches_of_a_tagged_enum() {
525 let schema = closed(json!({
526 "oneOf": [
527 { "type": "object", "properties": { "kind": { "const": "a" }, "a": {} } },
528 { "type": "null" }
529 ]
530 }));
531 assert_eq!(schema["oneOf"][0]["additionalProperties"], false);
532 }
533
534 #[test]
535 fn validation_lists_every_violation_by_pointer() {
536 let validator = ToolArgumentValidator::new(&closed(json!({
537 "type": "object",
538 "properties": {
539 "count": { "type": "integer", "minimum": 1, "maximum": 10 },
540 "room": { "type": "string", "pattern": "^[A-Z][0-9]$" },
541 "address": { "$ref": "#/$defs/Address" },
542 "note": { "type": ["string", "null"] }
543 },
544 "required": ["count", "room"],
545 "$defs": { "Address": { "type": "object", "properties": { "city": { "type": "string" } } } }
546 })))
547 .unwrap();
548
549 assert!(
550 validator.validate("book", &json!({ "count": 2, "room": "A1", "note": null })).is_ok()
551 );
552 let err = validator
553 .validate(
554 "book",
555 &json!({ "count": 50, "room": "lobby", "dry_run": true, "address": { "zip": "1" } }),
556 )
557 .unwrap_err();
558 assert_eq!(err.code, TOOL_INVALID_ARGUMENTS_CODE);
559 assert_eq!(err.category, ErrorCategory::InvalidInput);
560 for expected in
561 ["'book'", "/count: 50", "/room:", "arguments: ", "dry_run", "/address:", "zip"]
562 {
563 assert!(err.message.contains(expected), "{expected} missing from {}", err.message);
564 }
565 }
566
567 #[test]
568 fn long_violation_lists_are_capped() {
569 let properties: Map<String, Value> =
570 (0..12).map(|i| (format!("f{i}"), json!({ "type": "integer" }))).collect();
571 let validator =
572 ToolArgumentValidator::new(&json!({ "type": "object", "properties": properties }))
573 .unwrap();
574 let args: Map<String, Value> =
575 (0..12).map(|i| (format!("f{i}"), json!("x".repeat(500)))).collect();
576 let err = validator.validate("t", &Value::Object(args)).unwrap_err();
577 assert!(err.message.contains("and 4 more"), "{}", err.message);
578 assert!(err.message.len() < 8 * (MAX_VIOLATION_CHARS + 16) + 200, "{}", err.message);
579 }
580
581 #[test]
582 fn an_invalid_schema_is_reported() {
583 let err = ToolArgumentValidator::new(&json!({ "type": 12 })).unwrap_err();
584 assert_eq!(err.code, TOOL_INVALID_PARAMETERS_SCHEMA_CODE);
585 }
586
587 #[test]
588 fn model_facing_schema_reduces_nullable_types() {
589 let schema = model_facing_schema(json!({
590 "$schema": "x",
591 "title": "T",
592 "properties": {
593 "a": { "anyOf": [{ "$ref": "#/$defs/A" }, { "type": "null" }], "description": "d" },
594 "b": { "type": ["integer", "null"] }
595 }
596 }));
597 assert_eq!(
598 schema,
599 json!({
600 "properties": {
601 "a": { "$ref": "#/$defs/A", "description": "d" },
602 "b": { "type": "integer" }
603 }
604 })
605 );
606 }
607
608 #[test]
609 fn integral_floats_become_integers_only_where_the_schema_says_integer() {
610 let schema = json!({
611 "type": "object",
612 "properties": {
613 "count": { "type": "integer" },
614 "maybe": { "type": ["integer", "null"] },
615 "ratio": { "type": "number" },
616 "seats": { "type": "array", "items": { "$ref": "#/$defs/Seat" } },
617 "pick": { "anyOf": [{ "type": "integer" }, { "type": "string" }] },
618 "extra": { "type": "object", "additionalProperties": { "type": "integer" } }
619 },
620 "$defs": {
621 "Seat": { "type": "object", "properties": { "row": { "type": "integer" } } }
622 }
623 });
624 let mut args = json!({
625 "count": 3.0,
626 "maybe": -2.0,
627 "ratio": 2.0,
628 "seats": [{ "row": 7.0 }, { "row": 7.5 }],
629 "pick": 4.0,
630 "extra": { "a": 1.0 },
631 "undeclared": 5.0
632 });
633
634 coerce_integral_floats(&schema, &mut args);
635
636 assert_eq!(
637 args,
638 json!({
639 "count": 3,
640 "maybe": -2,
641 "ratio": 2.0,
642 "seats": [{ "row": 7 }, { "row": 7.5 }],
643 "pick": 4,
644 "extra": { "a": 1 },
645 "undeclared": 5.0
646 })
647 );
648 }
649
650 #[test]
651 fn floats_beyond_exact_integers_are_left_alone() {
652 let schema = json!({ "type": "integer" });
653 let mut args = json!(1.0e300);
654 coerce_integral_floats(&schema, &mut args);
655 assert_eq!(args, json!(1.0e300));
656 }
657}