Skip to main content

adk_tool/
arguments.rs

1//! Checks a tool call's arguments against the tool's parameters schema before the tool runs.
2//!
3//! A model's arguments are only as good as its reading of the schema. Deserializing them with
4//! serde drops keys the type does not declare and ignores the schema's constraints (`minimum`,
5//! `maxLength`, `pattern`, ...), so a call the model believes was honoured can run with
6//! different meaning. [`ToolArgumentValidator`] rejects such a call with an
7//! [`TOOL_INVALID_ARGUMENTS_CODE`] error, whose message reaches the model so it can correct the
8//! call; the tool does not run. The `#[tool]` macro applies it to every generated tool.
9
10use std::collections::HashSet;
11
12use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result, TOOL_INVALID_ARGUMENTS_CODE};
13use serde_json::{Map, Value};
14
15/// The most schema violations listed in one invalid-arguments error.
16const MAX_REPORTED_VIOLATIONS: usize = 8;
17
18/// The most characters of one violation message; a message quotes the offending value.
19const MAX_VIOLATION_CHARS: usize = 200;
20
21/// The error code for a tool whose parameters schema does not compile.
22pub const TOOL_INVALID_PARAMETERS_SCHEMA_CODE: &str = "tool.invalid_parameters_schema";
23
24/// Validates tool-call arguments against a JSON Schema.
25///
26/// Compile it once per schema and call [`validate`](Self::validate) in
27/// [`Tool::execute`](adk_core::Tool::execute) before acting on the arguments. Pair it with
28/// [`close_object_schemas`] to reject keys the schema does not declare.
29///
30/// # Example
31///
32/// ```rust
33/// use adk_tool::{TOOL_INVALID_ARGUMENTS_CODE, ToolArgumentValidator};
34/// use serde_json::json;
35///
36/// let validator = ToolArgumentValidator::new(&json!({
37///     "type": "object",
38///     "properties": { "count": { "type": "integer", "minimum": 1, "maximum": 10 } },
39///     "required": ["count"],
40///     "additionalProperties": false
41/// }))?;
42///
43/// assert!(validator.validate("book", &json!({ "count": 3 })).is_ok());
44/// let err = validator.validate("book", &json!({ "count": 50, "dry_run": true })).unwrap_err();
45/// assert_eq!(err.code, TOOL_INVALID_ARGUMENTS_CODE);
46/// assert!(err.message.contains("/count"));
47/// assert!(err.message.contains("dry_run"));
48/// # Ok::<(), adk_tool::AdkError>(())
49/// ```
50pub 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    /// Compiles `schema`. The draft follows its `$schema` keyword, defaulting to 2020-12.
62    ///
63    /// `format` is treated as an annotation, as the 2020-12 draft specifies, so a value's
64    /// format is left to the tool's own deserialization.
65    ///
66    /// # Errors
67    ///
68    /// Returns an error with code [`TOOL_INVALID_PARAMETERS_SCHEMA_CODE`] when `schema` is not a
69    /// valid JSON Schema.
70    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    /// Checks `args` against the schema.
86    ///
87    /// # Errors
88    ///
89    /// Returns an [`ErrorCategory::InvalidInput`] error with code
90    /// [`TOOL_INVALID_ARGUMENTS_CODE`] that lists each violation by its JSON pointer, such as
91    /// `/count: 50 is greater than the maximum of 10`. An agent shows this message to the model.
92    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
130/// The argument check a builder tool compiles from its parameters type.
131pub(crate) struct ArgumentCheck {
132    /// The type's JSON Schema, for reading integral floats as integers.
133    schema: Value,
134    /// The same schema with its objects closed, or why it did not compile.
135    validator: std::result::Result<ToolArgumentValidator, String>,
136}
137
138impl ArgumentCheck {
139    /// Compiles the check for `T`.
140    ///
141    /// Built from the standard schema of `T`, which keeps `null` for an `Option` field where
142    /// the model-facing OpenAPI form says `nullable`.
143    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    /// Reads integral floats at integer fields as integers, then, unless `lenient`, checks
152    /// `args` against the schema.
153    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
170/// Largest magnitude below which every integer is exactly representable as an `f64`.
171const EXACT_F64_INTEGERS: f64 = 9_007_199_254_740_992.0;
172
173/// Rewrites each integral float in `args` at a position `schema` types as an integer, so
174/// `3.0` becomes `3`.
175///
176/// Some models write every number with a decimal point. JSON Schema counts `3.0` as an
177/// integer, but serde's integer types reject it, so without this the call fails after it
178/// passed validation. Follows `properties`, `additionalProperties`, `items`,
179/// `prefixItems`, `allOf`/`anyOf`/`oneOf` and local `$ref`s; a float with a fraction, or
180/// one too large to be an exact integer, is left as it is.
181///
182/// # Example
183///
184/// ```rust
185/// use adk_tool::coerce_integral_floats;
186/// use serde_json::json;
187///
188/// let schema = json!({
189///     "type": "object",
190///     "properties": { "count": { "type": "integer" }, "ratio": { "type": "number" } }
191/// });
192/// let mut args = json!({ "count": 3.0, "ratio": 2.0 });
193/// coerce_integral_floats(&schema, &mut args);
194/// assert_eq!(args, json!({ "count": 3, "ratio": 2.0 }));
195/// ```
196pub 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    // Deep enough for any argument document; stops a `$ref` cycle.
202    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                // The guard above keeps both casts exact.
230                *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
272/// Sets `additionalProperties: false` on each object schema in `schema` that declares all of its
273/// fields, so a validator rejects keys the schema does not name.
274///
275/// An object schema declares all of its fields when it lists `properties`, says nothing about
276/// `additionalProperties`, `patternProperties` or `unevaluatedProperties`, and has no `$ref`,
277/// `allOf`, `anyOf`, `oneOf` or `if` beside its `properties` that could add more. Schemas that
278/// describe part of an object are left open: `allOf` branches, `if`/`then`/`else`, `not`,
279/// `dependentSchemas`, the `anyOf`/`oneOf` branches of an object that has `properties` of its
280/// own (a flattened enum), and definitions an `allOf` branch references.
281///
282/// # Example
283///
284/// ```rust
285/// use adk_tool::close_object_schemas;
286/// use serde_json::json;
287///
288/// let mut schema = json!({
289///     "type": "object",
290///     "properties": { "address": { "$ref": "#/$defs/Address" } },
291///     "$defs": {
292///         "Address": { "type": "object", "properties": { "city": { "type": "string" } } }
293///     }
294/// });
295/// close_object_schemas(&mut schema);
296/// assert_eq!(schema["additionalProperties"], false);
297/// assert_eq!(schema["$defs"]["Address"]["additionalProperties"], false);
298/// ```
299pub 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        // A branch is a whole value only under `anyOf`/`oneOf` of an object with no fields of its own.
347        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
364/// Records the definition names that `allOf` branches reference, which describe part of an object.
365fn 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
386/// Reduces a schema generated for a `#[tool]` argument type to the form sent to the model.
387///
388/// Removes the root `$schema` and `title`, and reduces nullable types that some providers
389/// reject: `{"type": ["string", "null"]}` becomes `{"type": "string"}`, and an `anyOf` of one
390/// schema and `null` becomes that schema. Validation uses the schema before this reduction, so a
391/// model may still send `null` for an optional field.
392///
393/// # Example
394///
395/// ```rust
396/// use adk_tool::model_facing_schema;
397/// use serde_json::json;
398///
399/// let schema = model_facing_schema(json!({
400///     "$schema": "https://json-schema.org/draft/2020-12/schema",
401///     "title": "Args",
402///     "type": "object",
403///     "properties": { "note": { "type": ["string", "null"] } }
404/// }));
405/// assert_eq!(schema, json!({
406///     "type": "object",
407///     "properties": { "note": { "type": "string" } }
408/// }));
409/// ```
410pub 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        // The `$ref` node itself takes its fields from the definition.
475        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        // A flattened enum: the branches only name the variant's own fields.
499        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}