1use std::collections::{HashMap, HashSet};
12
13use schemars::JsonSchema as SchemarsJsonSchema;
14
15use crate::error::{Error, Result, ToolValidationError};
16use crate::types::{JsonObject, JsonSchema, JsonValue};
17
18const JSON_SCHEMA_FORMATS: [&str; 19] = [
19 "date-time",
20 "date",
21 "time",
22 "duration",
23 "email",
24 "idn-email",
25 "hostname",
26 "idn-hostname",
27 "ipv4",
28 "ipv6",
29 "uri",
30 "uri-reference",
31 "iri",
32 "iri-reference",
33 "uuid",
34 "uri-template",
35 "json-pointer",
36 "relative-json-pointer",
37 "regex",
38];
39
40const SINGLE_SUBSCHEMA_KEYS: [&str; 10] = [
41 "items",
42 "additionalProperties",
43 "unevaluatedProperties",
44 "unevaluatedItems",
45 "contains",
46 "propertyNames",
47 "not",
48 "if",
49 "then",
50 "else",
51];
52
53const SUBSCHEMA_LIST_KEYS: [&str; 4] = ["prefixItems", "allOf", "anyOf", "oneOf"];
54
55const SUBSCHEMA_MAP_KEYS: [&str; 3] = ["properties", "patternProperties", "dependentSchemas"];
56
57const DEFS_KEYS: [&str; 2] = ["$defs", "definitions"];
58
59#[must_use]
89pub fn schema_for<T: SchemarsJsonSchema>() -> JsonSchema {
90 normalize_schema(schemars::schema_for!(T).to_value())
91}
92
93#[must_use]
100pub fn normalize_schema(mut schema: JsonSchema) -> JsonSchema {
101 let defs = take_defs(&mut schema);
102 let recursive = recursive_defs(&defs);
103 let mut kept = JsonObject::new();
104 for (name, def) in &defs {
105 if recursive.contains(name.as_str()) {
106 let mut def = def.clone();
107 inline_refs(&mut def, &defs, &recursive, &mut Vec::new());
108 clean(&mut def);
109 kept.insert(name.clone(), def);
110 }
111 }
112 inline_refs(&mut schema, &defs, &recursive, &mut Vec::new());
113 clean(&mut schema);
114 if let JsonValue::Object(root) = &mut schema {
115 root.remove("$schema");
116 if !kept.is_empty() {
117 root.insert("$defs".to_owned(), JsonValue::Object(kept));
118 }
119 }
120 schema
121}
122
123fn take_defs(schema: &mut JsonSchema) -> HashMap<String, JsonValue> {
124 let JsonValue::Object(root) = schema else {
125 return HashMap::new();
126 };
127 DEFS_KEYS
128 .iter()
129 .filter_map(|key| root.remove(*key))
130 .filter_map(|defs| match defs {
131 JsonValue::Object(defs) => Some(defs),
132 _ => None,
133 })
134 .flatten()
135 .collect()
136}
137
138fn def_name(reference: &str) -> Option<&str> {
139 reference
140 .strip_prefix("#/$defs/")
141 .or_else(|| reference.strip_prefix("#/definitions/"))
142}
143
144fn collect_refs<'a>(schema: &'a JsonValue, refs: &mut Vec<&'a str>) {
145 match schema {
146 JsonValue::Object(map) => {
147 if let Some(name) = map.get("$ref").and_then(JsonValue::as_str).and_then(def_name) {
148 refs.push(name);
149 }
150 map.values().for_each(|value| collect_refs(value, refs));
151 }
152 JsonValue::Array(items) => items.iter().for_each(|item| collect_refs(item, refs)),
153 _ => {}
154 }
155}
156
157fn recursive_defs(defs: &HashMap<String, JsonValue>) -> HashSet<String> {
158 let edges: HashMap<&str, Vec<&str>> = defs
159 .iter()
160 .map(|(name, def)| {
161 let mut refs = Vec::new();
162 collect_refs(def, &mut refs);
163 (name.as_str(), refs)
164 })
165 .collect();
166 defs.keys()
167 .filter(|name| reaches(&edges, name, name))
168 .cloned()
169 .collect()
170}
171
172fn reaches(edges: &HashMap<&str, Vec<&str>>, from: &str, target: &str) -> bool {
173 let mut stack: Vec<&str> = edges.get(from).cloned().unwrap_or_default();
174 let mut seen = HashSet::new();
175 while let Some(next) = stack.pop() {
176 if next == target {
177 return true;
178 }
179 if seen.insert(next) {
180 stack.extend(edges.get(next).into_iter().flatten().copied());
181 }
182 }
183 false
184}
185
186fn inline_refs(
187 schema: &mut JsonValue,
188 defs: &HashMap<String, JsonValue>,
189 recursive: &HashSet<String>,
190 stack: &mut Vec<String>,
191) {
192 match schema {
193 JsonValue::Object(map) => {
194 let target = map
195 .get("$ref")
196 .and_then(JsonValue::as_str)
197 .and_then(def_name)
198 .filter(|name| !recursive.contains(*name) && !stack.iter().any(|seen| seen == name))
199 .map(str::to_owned);
200 if let Some(name) = target
201 && let Some(JsonValue::Object(def)) = defs.get(&name)
202 {
203 map.remove("$ref");
204 let siblings = std::mem::take(map);
205 map.extend(def.clone());
206 map.extend(siblings);
207 stack.push(name);
208 map.values_mut()
209 .for_each(|value| inline_refs(value, defs, recursive, stack));
210 stack.pop();
211 return;
212 }
213 map.values_mut()
214 .for_each(|value| inline_refs(value, defs, recursive, stack));
215 }
216 JsonValue::Array(items) => items
217 .iter_mut()
218 .for_each(|item| inline_refs(item, defs, recursive, stack)),
219 _ => {}
220 }
221}
222
223fn clean(schema: &mut JsonValue) {
225 let JsonValue::Object(map) = schema else {
226 return;
227 };
228 map.remove("title");
229 let unknown_format = map
230 .get("format")
231 .and_then(JsonValue::as_str)
232 .is_some_and(|format| !JSON_SCHEMA_FORMATS.contains(&format));
233 if unknown_format {
234 map.remove("format");
235 }
236 for key in SINGLE_SUBSCHEMA_KEYS {
237 match map.get_mut(key) {
238 Some(JsonValue::Array(items)) => items.iter_mut().for_each(clean),
239 Some(subschema) => clean(subschema),
240 None => {}
241 }
242 }
243 for key in SUBSCHEMA_LIST_KEYS {
244 if let Some(JsonValue::Array(items)) = map.get_mut(key) {
245 items.iter_mut().for_each(clean);
246 }
247 }
248 for key in SUBSCHEMA_MAP_KEYS.iter().chain(&DEFS_KEYS) {
249 if let Some(JsonValue::Object(entries)) = map.get_mut(*key) {
250 entries.values_mut().for_each(clean);
251 }
252 }
253}
254
255#[derive(Debug)]
257pub struct SchemaValidator {
258 validator: jsonschema::Validator,
259}
260
261impl SchemaValidator {
262 pub fn new(schema: &JsonSchema) -> Result<Self> {
268 let validator = jsonschema::validator_for(schema)
269 .map_err(|error| Error::other(format!("invalid input schema: {error}")))?;
270 Ok(Self { validator })
271 }
272
273 pub fn validate(&self, input: &JsonValue) -> Result<(), ToolValidationError> {
281 let issues: Vec<String> = self
282 .validator
283 .iter_errors(input)
284 .map(|error| {
285 let path = error.instance_path().as_str();
286 if path.is_empty() {
287 format!("- {error}")
288 } else {
289 format!("- {path}: {error}")
290 }
291 })
292 .collect();
293 if issues.is_empty() {
294 return Ok(());
295 }
296 Err(ToolValidationError::new(format!(
297 "Validation failed:\n{}",
298 issues.join("\n")
299 )))
300 }
301}
302
303#[cfg(test)]
304mod tests {
305 use serde_json::json;
306
307 use super::*;
308
309 #[derive(schemars::JsonSchema)]
311 #[allow(dead_code, reason = "schema-only type")]
312 struct Point {
313 x: f64,
315 y: i32,
316 }
317
318 #[derive(schemars::JsonSchema)]
319 #[allow(dead_code, reason = "schema-only type")]
320 struct Shape {
321 origin: Point,
323 corners: Vec<Point>,
324 label: Option<String>,
325 when: Option<String>,
326 }
327
328 #[derive(schemars::JsonSchema)]
329 #[allow(dead_code, reason = "schema-only type")]
330 struct Tree {
331 name: String,
332 children: Vec<Tree>,
333 }
334
335 #[test]
336 fn inlines_subschemas_and_drops_titles_and_non_standard_formats() {
337 assert_eq!(
338 schema_for::<Shape>(),
339 json!({
340 "type": "object",
341 "properties": {
342 "origin": {
343 "description": "The origin.",
344 "type": "object",
345 "properties": {
346 "x": {"description": "Horizontal.", "type": "number"},
347 "y": {"type": "integer"}
348 },
349 "required": ["x", "y"]
350 },
351 "corners": {
352 "type": "array",
353 "items": {
354 "description": "A point.",
355 "type": "object",
356 "properties": {
357 "x": {"description": "Horizontal.", "type": "number"},
358 "y": {"type": "integer"}
359 },
360 "required": ["x", "y"]
361 }
362 },
363 "label": {"type": ["string", "null"]},
364 "when": {"type": ["string", "null"]}
365 },
366 "required": ["origin", "corners"]
367 })
368 );
369 }
370
371 #[derive(schemars::JsonSchema)]
372 #[allow(dead_code, reason = "schema-only type")]
373 struct Forest {
374 trees: Vec<Tree>,
375 }
376
377 #[test]
378 fn keeps_recursive_types_under_defs() {
379 let schema = schema_for::<Forest>();
380 assert_eq!(schema["properties"]["trees"]["items"], json!({"$ref": "#/$defs/Tree"}));
381 let tree = &schema["$defs"]["Tree"];
382 assert_eq!(tree["properties"]["children"]["items"], json!({"$ref": "#/$defs/Tree"}));
383 assert_eq!(tree["properties"]["name"], json!({"type": "string"}));
384 assert!(tree.get("title").is_none());
385 let root = schema_for::<Tree>();
386 assert_eq!(root["properties"]["children"]["items"], json!({"$ref": "#"}));
387 assert!(root.get("title").is_none());
388 }
389
390 #[test]
391 fn keeps_standard_formats_and_properties_named_title() {
392 let schema = normalize_schema(json!({
393 "$schema": "https://json-schema.org/draft/2020-12/schema",
394 "title": "Root",
395 "type": "object",
396 "properties": {
397 "title": {"type": "string", "title": "Title", "format": "date-time"},
398 "count": {"type": "integer", "format": "uint32"}
399 }
400 }));
401 assert_eq!(
402 schema,
403 json!({
404 "type": "object",
405 "properties": {
406 "title": {"type": "string", "format": "date-time"},
407 "count": {"type": "integer"}
408 }
409 })
410 );
411 }
412
413 #[test]
414 fn validates_input_and_lists_every_violation() {
415 let validator = SchemaValidator::new(&json!({
416 "type": "object",
417 "properties": {"name": {"type": "string"}, "age": {"type": "number"}},
418 "required": ["name", "age"]
419 }))
420 .unwrap();
421 validator.validate(&json!({"name": "John", "age": 30})).unwrap();
422 let error = validator.validate(&json!({"age": "thirty"})).unwrap_err();
423 assert_eq!(
424 error.to_string(),
425 "Validation failed:\n- \"name\" is a required property\n- /age: \"thirty\" is not of type \"number\""
426 );
427 }
428
429 #[test]
430 fn rejects_an_invalid_schema() {
431 assert!(SchemaValidator::new(&json!({"type": 12})).is_err());
432 }
433}