adk-tool 3.0.0

Tool system for Rust Agent Development Kit (ADK-Rust) agents (FunctionTool, MCP, Google Search)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
//! Checks a tool call's arguments against the tool's parameters schema before the tool runs.
//!
//! A model's arguments are only as good as its reading of the schema. Deserializing them with
//! serde drops keys the type does not declare and ignores the schema's constraints (`minimum`,
//! `maxLength`, `pattern`, ...), so a call the model believes was honoured can run with
//! different meaning. [`ToolArgumentValidator`] rejects such a call with an
//! [`TOOL_INVALID_ARGUMENTS_CODE`] error, whose message reaches the model so it can correct the
//! call; the tool does not run. The `#[tool]` macro applies it to every generated tool.

use std::collections::HashSet;

use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result, TOOL_INVALID_ARGUMENTS_CODE};
use serde_json::{Map, Value};

/// The most schema violations listed in one invalid-arguments error.
const MAX_REPORTED_VIOLATIONS: usize = 8;

/// The most characters of one violation message; a message quotes the offending value.
const MAX_VIOLATION_CHARS: usize = 200;

/// The error code for a tool whose parameters schema does not compile.
pub const TOOL_INVALID_PARAMETERS_SCHEMA_CODE: &str = "tool.invalid_parameters_schema";

/// Validates tool-call arguments against a JSON Schema.
///
/// Compile it once per schema and call [`validate`](Self::validate) in
/// [`Tool::execute`](adk_core::Tool::execute) before acting on the arguments. Pair it with
/// [`close_object_schemas`] to reject keys the schema does not declare.
///
/// # Example
///
/// ```rust
/// use adk_tool::{TOOL_INVALID_ARGUMENTS_CODE, ToolArgumentValidator};
/// use serde_json::json;
///
/// let validator = ToolArgumentValidator::new(&json!({
///     "type": "object",
///     "properties": { "count": { "type": "integer", "minimum": 1, "maximum": 10 } },
///     "required": ["count"],
///     "additionalProperties": false
/// }))?;
///
/// assert!(validator.validate("book", &json!({ "count": 3 })).is_ok());
/// let err = validator.validate("book", &json!({ "count": 50, "dry_run": true })).unwrap_err();
/// assert_eq!(err.code, TOOL_INVALID_ARGUMENTS_CODE);
/// assert!(err.message.contains("/count"));
/// assert!(err.message.contains("dry_run"));
/// # Ok::<(), adk_tool::AdkError>(())
/// ```
pub struct ToolArgumentValidator {
    validator: jsonschema::Validator,
}

impl std::fmt::Debug for ToolArgumentValidator {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ToolArgumentValidator").finish_non_exhaustive()
    }
}

impl ToolArgumentValidator {
    /// Compiles `schema`. The draft follows its `$schema` keyword, defaulting to 2020-12.
    ///
    /// `format` is treated as an annotation, as the 2020-12 draft specifies, so a value's
    /// format is left to the tool's own deserialization.
    ///
    /// # Errors
    ///
    /// Returns an error with code [`TOOL_INVALID_PARAMETERS_SCHEMA_CODE`] when `schema` is not a
    /// valid JSON Schema.
    pub fn new(schema: &Value) -> Result<Self> {
        let validator = jsonschema::validator_for(schema).map_err(|error| {
            AdkError::new(
                ErrorComponent::Tool,
                ErrorCategory::Internal,
                TOOL_INVALID_PARAMETERS_SCHEMA_CODE,
                format!(
                    "the tool's parameters schema does not compile: {error}. Fix the schema the \
                     tool declares."
                ),
            )
        })?;
        Ok(Self { validator })
    }

    /// Checks `args` against the schema.
    ///
    /// # Errors
    ///
    /// Returns an [`ErrorCategory::InvalidInput`] error with code
    /// [`TOOL_INVALID_ARGUMENTS_CODE`] that lists each violation by its JSON pointer, such as
    /// `/count: 50 is greater than the maximum of 10`. An agent shows this message to the model.
    pub fn validate(&self, tool_name: &str, args: &Value) -> Result<()> {
        let mut violations = Vec::new();
        let mut total = 0usize;
        for error in self.validator.iter_errors(args) {
            total += 1;
            if violations.len() == MAX_REPORTED_VIOLATIONS {
                continue;
            }
            let path = error.instance_path().as_str();
            let location = if path.is_empty() { "arguments" } else { path };
            violations.push(format!("{location}: {}", truncate(&error.to_string())));
        }
        if total == 0 {
            return Ok(());
        }
        if total > violations.len() {
            violations.push(format!("and {} more", total - violations.len()));
        }
        Err(AdkError::new(
            ErrorComponent::Tool,
            ErrorCategory::InvalidInput,
            TOOL_INVALID_ARGUMENTS_CODE,
            format!(
                "invalid arguments for '{tool_name}': {}. Correct the arguments to match the \
                 tool's parameters schema and call it again.",
                violations.join("; ")
            ),
        ))
    }
}

fn truncate(message: &str) -> String {
    match message.char_indices().nth(MAX_VIOLATION_CHARS) {
        Some((end, _)) => format!("{}…", &message[..end]),
        None => message.to_string(),
    }
}

/// The argument check a builder tool compiles from its parameters type.
pub(crate) struct ArgumentCheck {
    /// The type's JSON Schema, for reading integral floats as integers.
    schema: Value,
    /// The same schema with its objects closed, or why it did not compile.
    validator: std::result::Result<ToolArgumentValidator, String>,
}

impl ArgumentCheck {
    /// Compiles the check for `T`.
    ///
    /// Built from the standard schema of `T`, which keeps `null` for an `Option` field where
    /// the model-facing OpenAPI form says `nullable`.
    pub(crate) fn for_type<T: schemars::JsonSchema>() -> Self {
        let schema = serde_json::to_value(schemars::schema_for!(T)).unwrap_or_default();
        let mut closed = schema.clone();
        close_object_schemas(&mut closed);
        let validator = ToolArgumentValidator::new(&closed).map_err(|error| error.message);
        Self { schema, validator }
    }

    /// Reads integral floats at integer fields as integers, then, unless `lenient`, checks
    /// `args` against the schema.
    pub(crate) fn apply(&self, tool_name: &str, lenient: bool, args: &mut Value) -> Result<()> {
        coerce_integral_floats(&self.schema, args);
        if lenient {
            return Ok(());
        }
        match &self.validator {
            Ok(validator) => validator.validate(tool_name, args),
            Err(message) => Err(AdkError::new(
                ErrorComponent::Tool,
                ErrorCategory::Internal,
                TOOL_INVALID_PARAMETERS_SCHEMA_CODE,
                message.clone(),
            )),
        }
    }
}

/// Largest magnitude below which every integer is exactly representable as an `f64`.
const EXACT_F64_INTEGERS: f64 = 9_007_199_254_740_992.0;

/// Rewrites each integral float in `args` at a position `schema` types as an integer, so
/// `3.0` becomes `3`.
///
/// Some models write every number with a decimal point. JSON Schema counts `3.0` as an
/// integer, but serde's integer types reject it, so without this the call fails after it
/// passed validation. Follows `properties`, `additionalProperties`, `items`,
/// `prefixItems`, `allOf`/`anyOf`/`oneOf` and local `$ref`s; a float with a fraction, or
/// one too large to be an exact integer, is left as it is.
///
/// # Example
///
/// ```rust
/// use adk_tool::coerce_integral_floats;
/// use serde_json::json;
///
/// let schema = json!({
///     "type": "object",
///     "properties": { "count": { "type": "integer" }, "ratio": { "type": "number" } }
/// });
/// let mut args = json!({ "count": 3.0, "ratio": 2.0 });
/// coerce_integral_floats(&schema, &mut args);
/// assert_eq!(args, json!({ "count": 3, "ratio": 2.0 }));
/// ```
pub fn coerce_integral_floats(schema: &Value, args: &mut Value) {
    coerce_at(schema, schema, args, 0);
}

fn coerce_at(root: &Value, schema: &Value, value: &mut Value, depth: usize) {
    // Deep enough for any argument document; stops a `$ref` cycle.
    if depth > 64 {
        return;
    }
    let Some(obj) = schema.as_object() else {
        return;
    };
    if let Some(target) = obj
        .get("$ref")
        .and_then(Value::as_str)
        .and_then(|reference| reference.strip_prefix('#'))
        .and_then(|pointer| root.pointer(pointer))
    {
        coerce_at(root, target, value, depth + 1);
    }
    let integer_only = match obj.get("type") {
        Some(Value::String(kind)) => kind == "integer",
        Some(Value::Array(kinds)) => {
            kinds.iter().any(|kind| kind == "integer") && !kinds.iter().any(|kind| kind == "number")
        }
        _ => false,
    };
    match value {
        Value::Number(number) if integer_only && number.is_f64() => {
            if let Some(float) = number.as_f64()
                && float.fract() == 0.0
                && float.abs() < EXACT_F64_INTEGERS
            {
                // The guard above keeps both casts exact.
                *value =
                    if float < 0.0 { Value::from(float as i64) } else { Value::from(float as u64) };
            }
        }
        Value::Object(members) => {
            let properties = obj.get("properties").and_then(Value::as_object);
            for (name, member) in members.iter_mut() {
                match properties.and_then(|properties| properties.get(name)) {
                    Some(sub) => coerce_at(root, sub, member, depth + 1),
                    None => {
                        if let Some(sub @ Value::Object(_)) = obj.get("additionalProperties") {
                            coerce_at(root, sub, member, depth + 1);
                        }
                    }
                }
            }
        }
        Value::Array(items) => {
            let prefix =
                obj.get("prefixItems").and_then(Value::as_array).map_or(&[][..], Vec::as_slice);
            for (index, item) in items.iter_mut().enumerate() {
                match prefix.get(index) {
                    Some(sub) => coerce_at(root, sub, item, depth + 1),
                    None => {
                        if let Some(sub @ Value::Object(_)) = obj.get("items") {
                            coerce_at(root, sub, item, depth + 1);
                        }
                    }
                }
            }
        }
        _ => {}
    }
    for keyword in ["allOf", "anyOf", "oneOf"] {
        if let Some(Value::Array(branches)) = obj.get(keyword) {
            for branch in branches {
                coerce_at(root, branch, value, depth + 1);
            }
        }
    }
}

/// Sets `additionalProperties: false` on each object schema in `schema` that declares all of its
/// fields, so a validator rejects keys the schema does not name.
///
/// An object schema declares all of its fields when it lists `properties`, says nothing about
/// `additionalProperties`, `patternProperties` or `unevaluatedProperties`, and has no `$ref`,
/// `allOf`, `anyOf`, `oneOf` or `if` beside its `properties` that could add more. Schemas that
/// describe part of an object are left open: `allOf` branches, `if`/`then`/`else`, `not`,
/// `dependentSchemas`, the `anyOf`/`oneOf` branches of an object that has `properties` of its
/// own (a flattened enum), and definitions an `allOf` branch references.
///
/// # Example
///
/// ```rust
/// use adk_tool::close_object_schemas;
/// use serde_json::json;
///
/// let mut schema = json!({
///     "type": "object",
///     "properties": { "address": { "$ref": "#/$defs/Address" } },
///     "$defs": {
///         "Address": { "type": "object", "properties": { "city": { "type": "string" } } }
///     }
/// });
/// close_object_schemas(&mut schema);
/// assert_eq!(schema["additionalProperties"], false);
/// assert_eq!(schema["$defs"]["Address"]["additionalProperties"], false);
/// ```
pub fn close_object_schemas(schema: &mut Value) {
    let mut partial_definitions = HashSet::new();
    collect_all_of_references(schema, &mut partial_definitions);
    close(schema, true, &partial_definitions);
}

const COMBINATORS: [&str; 3] = ["allOf", "anyOf", "oneOf"];

fn close(schema: &mut Value, complete: bool, partial_definitions: &HashSet<String>) {
    let Some(obj) = schema.as_object_mut() else {
        return;
    };
    let has_properties = obj.get("properties").is_some_and(Value::is_object);
    let extendable = ["additionalProperties", "patternProperties", "unevaluatedProperties"]
        .iter()
        .chain(&["$ref", "if"])
        .chain(&COMBINATORS)
        .any(|keyword| obj.contains_key(*keyword));
    if complete && has_properties && !extendable {
        obj.insert("additionalProperties".to_string(), Value::Bool(false));
    }

    for keyword in ["properties", "patternProperties"] {
        if let Some(Value::Object(children)) = obj.get_mut(keyword) {
            children.values_mut().for_each(|child| close(child, true, partial_definitions));
        }
    }
    for keyword in ["$defs", "definitions"] {
        if let Some(Value::Object(definitions)) = obj.get_mut(keyword) {
            for (name, definition) in definitions.iter_mut() {
                close(definition, !partial_definitions.contains(name), partial_definitions);
            }
        }
    }
    for keyword in ["items", "additionalProperties", "unevaluatedProperties", "contains"] {
        match obj.get_mut(keyword) {
            Some(child @ Value::Object(_)) => close(child, true, partial_definitions),
            Some(Value::Array(children)) => {
                children.iter_mut().for_each(|child| close(child, true, partial_definitions));
            }
            _ => {}
        }
    }
    if let Some(Value::Array(children)) = obj.get_mut("prefixItems") {
        children.iter_mut().for_each(|child| close(child, true, partial_definitions));
    }
    for keyword in COMBINATORS {
        // A branch is a whole value only under `anyOf`/`oneOf` of an object with no fields of its own.
        let branch_complete = keyword != "allOf" && !has_properties;
        if let Some(Value::Array(branches)) = obj.get_mut(keyword) {
            for branch in branches {
                close(branch, branch_complete, partial_definitions);
            }
        }
    }
    for keyword in ["not", "if", "then", "else"] {
        if let Some(child) = obj.get_mut(keyword) {
            close(child, false, partial_definitions);
        }
    }
    if let Some(Value::Object(children)) = obj.get_mut("dependentSchemas") {
        children.values_mut().for_each(|child| close(child, false, partial_definitions));
    }
}

/// Records the definition names that `allOf` branches reference, which describe part of an object.
fn collect_all_of_references(schema: &Value, names: &mut HashSet<String>) {
    match schema {
        Value::Object(obj) => {
            if let Some(Value::Array(branches)) = obj.get("allOf") {
                for branch in branches {
                    if let Some(name) = branch.get("$ref").and_then(Value::as_str).and_then(|r| {
                        r.strip_prefix("#/$defs/").or_else(|| r.strip_prefix("#/definitions/"))
                    }) {
                        names.insert(name.to_string());
                    }
                }
            }
            obj.values().for_each(|child| collect_all_of_references(child, names));
        }
        Value::Array(children) => {
            children.iter().for_each(|child| collect_all_of_references(child, names));
        }
        _ => {}
    }
}

/// Reduces a schema generated for a `#[tool]` argument type to the form sent to the model.
///
/// Removes the root `$schema` and `title`, and reduces nullable types that some providers
/// reject: `{"type": ["string", "null"]}` becomes `{"type": "string"}`, and an `anyOf` of one
/// schema and `null` becomes that schema. Validation uses the schema before this reduction, so a
/// model may still send `null` for an optional field.
///
/// # Example
///
/// ```rust
/// use adk_tool::model_facing_schema;
/// use serde_json::json;
///
/// let schema = model_facing_schema(json!({
///     "$schema": "https://json-schema.org/draft/2020-12/schema",
///     "title": "Args",
///     "type": "object",
///     "properties": { "note": { "type": ["string", "null"] } }
/// }));
/// assert_eq!(schema, json!({
///     "type": "object",
///     "properties": { "note": { "type": "string" } }
/// }));
/// ```
pub fn model_facing_schema(mut schema: Value) -> Value {
    if let Some(obj) = schema.as_object_mut() {
        obj.remove("$schema");
        obj.remove("title");
    }
    simplify_nullable(&mut schema);
    schema
}

fn simplify_nullable(schema: &mut Value) {
    match schema {
        Value::Object(map) => {
            if let Some(Value::Array(types)) = map.get("type") {
                let non_null: Vec<_> =
                    types.iter().filter(|t| t.as_str() != Some("null")).cloned().collect();
                if let [only] = non_null.as_slice() {
                    map.insert("type".to_string(), only.clone());
                }
            }
            if let Some(Value::Array(any_of)) = map.remove("anyOf") {
                merge_first_non_null(map, &any_of);
            }
            map.values_mut().for_each(simplify_nullable);
        }
        Value::Array(items) => items.iter_mut().for_each(simplify_nullable),
        _ => {}
    }
}

fn merge_first_non_null(map: &mut Map<String, Value>, any_of: &[Value]) {
    let variant = any_of
        .iter()
        .filter_map(Value::as_object)
        .find(|variant| variant.get("type").and_then(Value::as_str) != Some("null"));
    if let Some(variant) = variant {
        for (key, value) in variant {
            map.insert(key.clone(), value.clone());
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn closed(mut schema: Value) -> Value {
        close_object_schemas(&mut schema);
        schema
    }

    #[test]
    fn closes_complete_objects_and_their_definitions() {
        let schema = closed(json!({
            "type": "object",
            "properties": {
                "address": { "$ref": "#/$defs/Address", "description": "where" },
                "tags": { "type": "array", "items": { "type": "object", "properties": { "k": {} } } }
            },
            "$defs": { "Address": { "type": "object", "properties": { "city": {} } } }
        }));
        assert_eq!(schema["additionalProperties"], false);
        assert_eq!(schema["$defs"]["Address"]["additionalProperties"], false);
        assert_eq!(schema["properties"]["tags"]["items"]["additionalProperties"], false);
        // The `$ref` node itself takes its fields from the definition.
        assert!(schema["properties"]["address"].get("additionalProperties").is_none());
    }

    #[test]
    fn leaves_declared_and_open_ended_objects_alone() {
        let schema = closed(json!({
            "type": "object",
            "properties": {
                "open": { "type": "object", "properties": { "a": {} }, "additionalProperties": true },
                "map": { "type": "object", "additionalProperties": { "type": "string" } },
                "free": { "type": "object" }
            }
        }));
        assert_eq!(schema["properties"]["open"]["additionalProperties"], true);
        assert_eq!(
            schema["properties"]["map"]["additionalProperties"],
            json!({ "type": "string" })
        );
        assert!(schema["properties"]["free"].get("additionalProperties").is_none());
    }

    #[test]
    fn leaves_partial_schemas_open() {
        // A flattened enum: the branches only name the variant's own fields.
        let flattened = closed(json!({
            "type": "object",
            "properties": { "name": {} },
            "oneOf": [
                { "type": "object", "properties": { "a": {} } },
                { "type": "object", "properties": { "b": {} } }
            ]
        }));
        assert!(flattened.get("additionalProperties").is_none());
        assert!(flattened["oneOf"][0].get("additionalProperties").is_none());

        let composed = closed(json!({
            "allOf": [
                { "$ref": "#/$defs/Base" },
                { "type": "object", "properties": { "extra": {} } }
            ],
            "if": { "properties": { "kind": { "const": "x" } } },
            "$defs": { "Base": { "type": "object", "properties": { "id": {} } } }
        }));
        assert!(composed["allOf"][1].get("additionalProperties").is_none());
        assert!(composed["if"].get("additionalProperties").is_none());
        assert!(composed["$defs"]["Base"].get("additionalProperties").is_none());
    }

    #[test]
    fn closes_whole_value_branches_of_a_tagged_enum() {
        let schema = closed(json!({
            "oneOf": [
                { "type": "object", "properties": { "kind": { "const": "a" }, "a": {} } },
                { "type": "null" }
            ]
        }));
        assert_eq!(schema["oneOf"][0]["additionalProperties"], false);
    }

    #[test]
    fn validation_lists_every_violation_by_pointer() {
        let validator = ToolArgumentValidator::new(&closed(json!({
            "type": "object",
            "properties": {
                "count": { "type": "integer", "minimum": 1, "maximum": 10 },
                "room": { "type": "string", "pattern": "^[A-Z][0-9]$" },
                "address": { "$ref": "#/$defs/Address" },
                "note": { "type": ["string", "null"] }
            },
            "required": ["count", "room"],
            "$defs": { "Address": { "type": "object", "properties": { "city": { "type": "string" } } } }
        })))
        .unwrap();

        assert!(
            validator.validate("book", &json!({ "count": 2, "room": "A1", "note": null })).is_ok()
        );
        let err = validator
            .validate(
                "book",
                &json!({ "count": 50, "room": "lobby", "dry_run": true, "address": { "zip": "1" } }),
            )
            .unwrap_err();
        assert_eq!(err.code, TOOL_INVALID_ARGUMENTS_CODE);
        assert_eq!(err.category, ErrorCategory::InvalidInput);
        for expected in
            ["'book'", "/count: 50", "/room:", "arguments: ", "dry_run", "/address:", "zip"]
        {
            assert!(err.message.contains(expected), "{expected} missing from {}", err.message);
        }
    }

    #[test]
    fn long_violation_lists_are_capped() {
        let properties: Map<String, Value> =
            (0..12).map(|i| (format!("f{i}"), json!({ "type": "integer" }))).collect();
        let validator =
            ToolArgumentValidator::new(&json!({ "type": "object", "properties": properties }))
                .unwrap();
        let args: Map<String, Value> =
            (0..12).map(|i| (format!("f{i}"), json!("x".repeat(500)))).collect();
        let err = validator.validate("t", &Value::Object(args)).unwrap_err();
        assert!(err.message.contains("and 4 more"), "{}", err.message);
        assert!(err.message.len() < 8 * (MAX_VIOLATION_CHARS + 16) + 200, "{}", err.message);
    }

    #[test]
    fn an_invalid_schema_is_reported() {
        let err = ToolArgumentValidator::new(&json!({ "type": 12 })).unwrap_err();
        assert_eq!(err.code, TOOL_INVALID_PARAMETERS_SCHEMA_CODE);
    }

    #[test]
    fn model_facing_schema_reduces_nullable_types() {
        let schema = model_facing_schema(json!({
            "$schema": "x",
            "title": "T",
            "properties": {
                "a": { "anyOf": [{ "$ref": "#/$defs/A" }, { "type": "null" }], "description": "d" },
                "b": { "type": ["integer", "null"] }
            }
        }));
        assert_eq!(
            schema,
            json!({
                "properties": {
                    "a": { "$ref": "#/$defs/A", "description": "d" },
                    "b": { "type": "integer" }
                }
            })
        );
    }

    #[test]
    fn integral_floats_become_integers_only_where_the_schema_says_integer() {
        let schema = json!({
            "type": "object",
            "properties": {
                "count": { "type": "integer" },
                "maybe": { "type": ["integer", "null"] },
                "ratio": { "type": "number" },
                "seats": { "type": "array", "items": { "$ref": "#/$defs/Seat" } },
                "pick": { "anyOf": [{ "type": "integer" }, { "type": "string" }] },
                "extra": { "type": "object", "additionalProperties": { "type": "integer" } }
            },
            "$defs": {
                "Seat": { "type": "object", "properties": { "row": { "type": "integer" } } }
            }
        });
        let mut args = json!({
            "count": 3.0,
            "maybe": -2.0,
            "ratio": 2.0,
            "seats": [{ "row": 7.0 }, { "row": 7.5 }],
            "pick": 4.0,
            "extra": { "a": 1.0 },
            "undeclared": 5.0
        });

        coerce_integral_floats(&schema, &mut args);

        assert_eq!(
            args,
            json!({
                "count": 3,
                "maybe": -2,
                "ratio": 2.0,
                "seats": [{ "row": 7 }, { "row": 7.5 }],
                "pick": 4,
                "extra": { "a": 1 },
                "undeclared": 5.0
            })
        );
    }

    #[test]
    fn floats_beyond_exact_integers_are_left_alone() {
        let schema = json!({ "type": "integer" });
        let mut args = json!(1.0e300);
        coerce_integral_floats(&schema, &mut args);
        assert_eq!(args, json!(1.0e300));
    }
}