use serde_json::{Map, Value};
const MAX_DEPTH: usize = 24;
pub fn normalize_tool_schema(schema: &Value) -> Value {
let normalized = normalize_node(schema, schema, 0);
if normalized.get("type").and_then(Value::as_str) == Some("object") {
return normalized;
}
let mut map = Map::new();
map.insert("type".to_string(), Value::String("object".to_string()));
if let Some(description) = normalized.get("description") {
map.insert("description".to_string(), description.clone());
}
Value::Object(map)
}
fn normalize_node(node: &Value, root: &Value, depth: usize) -> Value {
if depth > MAX_DEPTH {
return unconstrained_object();
}
let Value::Object(node) = node else {
return unconstrained_object();
};
let mut node = node.clone();
collapse_indirections(&mut node, root);
fold_keywords(&mut node);
build_portable(&node, root, depth)
}
fn collapse_indirections(node: &mut Map<String, Value>, root: &Value) {
for _ in 0..MAX_DEPTH {
if let Some(reference) = node.remove("$ref") {
let target = reference
.as_str()
.and_then(|r| r.strip_prefix('#'))
.and_then(|pointer| root.pointer(pointer))
.and_then(Value::as_object);
if let Some(target) = target {
for (key, value) in target {
node.entry(key.clone()).or_insert_with(|| value.clone());
}
}
continue;
}
if let Some(all_of) = node.remove("allOf") {
if let Value::Array(branches) = all_of {
for branch in branches {
if let Value::Object(branch) = branch {
for (key, value) in branch {
node.entry(key).or_insert(value);
}
}
}
}
continue;
}
if let Some(one_of) = node.remove("oneOf") {
if let Value::Array(mut extra) = one_of {
if let Some(Value::Array(mut any_of)) = node.remove("anyOf") {
any_of.append(&mut extra);
extra = any_of;
}
node.insert("anyOf".to_string(), Value::Array(extra));
}
continue;
}
if let Some(any_of) = node.remove("anyOf") {
let Value::Array(mut branches) = any_of else { continue };
let with_null = branches.len();
branches.retain(|branch| !is_null_type(branch));
if branches.len() != with_null {
node.insert("nullable".to_string(), Value::Bool(true));
}
match branches.len() {
0 => {}
1 => {
if let Value::Object(branch) = branches.remove(0) {
for (key, value) in branch {
node.entry(key).or_insert(value);
}
}
}
_ => {
let stable = branches.len() == with_null;
node.insert("anyOf".to_string(), Value::Array(branches));
if stable {
break;
}
}
}
continue;
}
break;
}
}
fn fold_keywords(node: &mut Map<String, Value>) {
if let Some(value) = node.remove("const") {
node.entry("enum").or_insert_with(|| Value::Array(vec![value]));
}
if let Some(bound) = node.remove("exclusiveMinimum")
&& bound.is_number()
{
node.entry("minimum").or_insert(bound);
}
if let Some(bound) = node.remove("exclusiveMaximum")
&& bound.is_number()
{
node.entry("maximum").or_insert(bound);
}
if let Some(Value::Array(examples)) = node.remove("examples")
&& let Some(first) = examples.into_iter().next()
{
node.entry("example").or_insert(first);
}
}
fn build_portable(node: &Map<String, Value>, root: &Value, depth: usize) -> Value {
let mut out = Map::new();
let mut nullable = node.get("nullable").and_then(Value::as_bool).unwrap_or(false);
let mut types: Vec<String> = match node.get("type") {
Some(Value::String(t)) => vec![t.clone()],
Some(Value::Array(list)) => {
list.iter().filter_map(Value::as_str).map(str::to_string).collect()
}
_ => Vec::new(),
};
if types.iter().any(|t| t == "null") {
types.retain(|t| t != "null");
nullable = true;
}
let mut any_of: Vec<Value> = match node.get("anyOf") {
Some(Value::Array(branches)) => {
branches.iter().map(|b| normalize_node(b, root, depth + 1)).collect()
}
_ => Vec::new(),
};
let enum_values: Vec<Value> = match node.get("enum") {
Some(Value::Array(values)) => {
let non_null: Vec<Value> = values.iter().filter(|v| !v.is_null()).cloned().collect();
if non_null.len() != values.len() {
nullable = true;
}
non_null
}
_ => Vec::new(),
};
let properties: Map<String, Value> = match node.get("properties") {
Some(Value::Object(props)) => props
.iter()
.map(|(name, schema)| (name.clone(), normalize_node(schema, root, depth + 1)))
.collect(),
_ => Map::new(),
};
let required: Vec<Value> = match node.get("required") {
Some(Value::Array(names)) => names
.iter()
.filter(|name| name.as_str().is_some_and(|n| properties.contains_key(n)))
.cloned()
.collect(),
_ => Vec::new(),
};
let items = match node.get("items").or_else(|| node.get("prefixItems")) {
Some(Value::Array(elements)) => {
let mut normalized: Vec<Value> =
elements.iter().map(|e| normalize_node(e, root, depth + 1)).collect();
match normalized.len() {
0 => None,
1 => Some(normalized.remove(0)),
_ => {
let mut union = Map::new();
union.insert("anyOf".to_string(), Value::Array(normalized));
Some(Value::Object(union))
}
}
}
Some(schema) => Some(normalize_node(schema, root, depth + 1)),
None => None,
};
let insert_typed = |out: &mut Map<String, Value>, ty: &str| match ty {
"array" => {
let items = items.clone().unwrap_or_else(unconstrained_object);
out.insert("items".to_string(), items);
}
"object" => {
if !required.is_empty() {
out.insert("required".to_string(), Value::Array(required.clone()));
}
if !properties.is_empty() {
out.insert("properties".to_string(), Value::Object(properties.clone()));
}
}
_ => {}
};
if any_of.is_empty() && types.len() > 1 {
any_of = types
.drain(..)
.map(|t| {
let mut branch = Map::new();
branch.insert("type".to_string(), Value::String(t.clone()));
insert_typed(&mut branch, &t);
Value::Object(branch)
})
.collect();
}
let ty = if any_of.is_empty() {
Some(declared_or_inferred_type(types, &enum_values, &properties, items.is_some()))
} else {
out.insert("anyOf".to_string(), Value::Array(any_of));
None
};
if let Some(ty) = &ty {
out.insert("type".to_string(), Value::String(ty.clone()));
}
for key in ["description", "title", "format"] {
if let Some(value @ Value::String(_)) = node.get(key) {
out.insert(key.to_string(), value.clone());
}
}
let enum_values = if enum_values.iter().all(|v| v.as_str().is_some_and(|s| !s.is_empty())) {
enum_values
} else {
let allowed = enum_values.iter().map(Value::to_string).collect::<Vec<_>>().join(", ");
let hint = match enum_values.len() {
1 => format!("Must be {allowed}."),
_ => format!("Allowed values: {allowed}."),
};
let description = match out.get("description").and_then(Value::as_str) {
Some(existing) => format!("{existing} {hint}"),
None => hint,
};
out.insert("description".to_string(), Value::String(description));
Vec::new()
};
for key in [
"minimum",
"maximum",
"minItems",
"maxItems",
"minLength",
"maxLength",
"minProperties",
"maxProperties",
] {
if let Some(value) = node.get(key).filter(|v| v.is_number()) {
out.insert(key.to_string(), value.clone());
}
}
for key in ["default", "example"] {
if let Some(value) = node.get(key) {
out.insert(key.to_string(), value.clone());
}
}
if !enum_values.is_empty() {
out.insert("enum".to_string(), Value::Array(enum_values));
}
if let Some(ty) = &ty {
insert_typed(&mut out, ty);
}
if nullable {
out.insert("nullable".to_string(), Value::Bool(true));
}
Value::Object(out)
}
fn declared_or_inferred_type(
mut types: Vec<String>,
enum_values: &[Value],
properties: &Map<String, Value>,
has_items: bool,
) -> String {
if let Some(ty) = types.pop() {
return ty;
}
if let Some(first) = enum_values.first() {
let ty = match first {
Value::Bool(_) => "boolean",
Value::Number(_) if enum_values.iter().all(|v| v.as_i64().is_some()) => "integer",
Value::Number(_) => "number",
_ => "string",
};
return ty.to_string();
}
if properties.is_empty() && has_items {
return "array".to_string();
}
"object".to_string()
}
fn unconstrained_object() -> Value {
let mut map = Map::new();
map.insert("type".to_string(), Value::String("object".to_string()));
Value::Object(map)
}
fn is_null_type(schema: &Value) -> bool {
schema.as_object().is_some_and(|s| s.get("type").and_then(Value::as_str) == Some("null"))
}
#[cfg(test)]
mod normalize_tests {
use super::normalize_tool_schema;
use serde_json::{Value, json};
fn corpus() -> Vec<Value> {
vec![
json!({
"type": "object",
"properties": {
"limit": {"type": "integer", "exclusiveMinimum": 0, "description": "max rows"}
}
}),
json!({
"type": "object",
"properties": {"n": {"type": "number", "minimum": 1, "exclusiveMinimum": true}}
}),
json!({
"type": "object",
"$defs": {
"Point": {
"type": "object",
"properties": {"x": {"type": "number"}},
"required": ["x"]
},
"Mode": {"type": "string", "enum": ["fast", "slow"]}
},
"properties": {
"origin": {"$ref": "#/$defs/Point"},
"mode": {"allOf": [{"$ref": "#/$defs/Mode"}], "default": "fast"}
},
"required": ["origin"]
}),
json!({
"type": "object",
"properties": {
"name": {
"anyOf": [{"type": "string"}, {"type": "null"}],
"default": null,
"description": "optional name"
}
}
}),
json!({
"type": "object",
"$schema": "https://json-schema.org/draft/2020-12/schema",
"additionalProperties": false,
"properties": {
"id": {"oneOf": [{"type": "string"}, {"type": "integer"}]},
"kind": {"const": "user"},
"score": {"type": ["number", "null"], "multipleOf": 0.5},
"text_or_num": {"type": ["string", "number"]}
},
"required": ["id", "ghost"]
}),
json!({
"type": "object",
"properties": {
"anything": {},
"count": {"enum": [1, 2]},
"mode": {"enum": ["a", null]},
"list": {"items": {"type": "string"}},
"pair": {"type": "array", "items": [{"type": "string"}, {"type": "integer"}]}
}
}),
json!({
"type": "object",
"$defs": {
"Node": {
"type": "object",
"properties": {"next": {"$ref": "#/$defs/Node"}}
}
},
"properties": {"root": {"$ref": "#/$defs/Node"}}
}),
json!({
"type": "object",
"properties": {
"email": {
"type": "string",
"description": "recipient email",
"format": "email",
"pattern": "^(?!blocked@example\\.com$).+@.+$"
}
},
"required": ["email"]
}),
json!({
"type": "object",
"properties": {
"mode": {
"anyOf": [
{"type": "string"},
{
"type": "object",
"properties": {
"headless": {"type": "boolean", "const": false, "default": false}
}
}
]
},
"flag": {"enum": [true, false], "description": "toggle"},
"level": {"type": "number", "enum": [0.5, 1]},
"blank": {"type": "string", "const": ""}
}
}),
json!({
"type": "object",
"properties": {
"source_paths": {
"type": "array",
"items": {
"type": ["null", "boolean", "object", "array", "number", "string"],
"items": {}
}
},
"target": {
"type": ["string", "object"],
"properties": {"path": {"type": "string"}},
"required": ["path"]
},
"grid": {"type": "array", "items": {"type": "array"}},
"name": {
"type": "string",
"items": {"type": "string"},
"properties": {"a": {"type": "string"}},
"required": ["a"]
}
}
}),
json!(true),
json!({"type": "string", "description": "not an object"}),
json!({"type": "object", "properties": {}}),
]
}
#[test]
fn exclusive_minimum_folds_into_minimum() {
let normalized = normalize_tool_schema(&corpus()[0]);
assert_eq!(
normalized["properties"]["limit"],
json!({"type": "integer", "minimum": 0, "description": "max rows"})
);
}
#[test]
fn draft4_boolean_exclusive_bound_drops() {
let normalized = normalize_tool_schema(&corpus()[1]);
assert_eq!(normalized["properties"]["n"], json!({"type": "number", "minimum": 1}));
}
#[test]
fn local_refs_inline_and_defs_disappear() {
let normalized = normalize_tool_schema(&corpus()[2]);
assert!(normalized.get("$defs").is_none());
assert_eq!(
normalized["properties"]["origin"],
json!({
"type": "object",
"properties": {"x": {"type": "number"}},
"required": ["x"]
})
);
assert_eq!(
normalized["properties"]["mode"],
json!({"type": "string", "enum": ["fast", "slow"], "default": "fast"})
);
assert_eq!(normalized["required"], json!(["origin"]));
}
#[test]
fn optional_anyof_null_becomes_nullable() {
let normalized = normalize_tool_schema(&corpus()[3]);
assert_eq!(
normalized["properties"]["name"],
json!({
"type": "string",
"nullable": true,
"default": null,
"description": "optional name"
})
);
}
#[test]
fn unions_consts_and_unknown_keywords() {
let normalized = normalize_tool_schema(&corpus()[4]);
assert!(normalized.get("$schema").is_none());
assert!(normalized.get("additionalProperties").is_none());
let props = &normalized["properties"];
assert_eq!(props["id"], json!({"anyOf": [{"type": "string"}, {"type": "integer"}]}));
assert_eq!(props["kind"], json!({"type": "string", "enum": ["user"]}));
assert_eq!(props["score"], json!({"type": "number", "nullable": true}));
assert_eq!(
props["text_or_num"],
json!({"anyOf": [{"type": "string"}, {"type": "number"}]})
);
assert_eq!(normalized["required"], json!(["id"]));
}
#[test]
fn untyped_nodes_get_inferred_types() {
let normalized = normalize_tool_schema(&corpus()[5]);
let props = &normalized["properties"];
assert_eq!(props["anything"], json!({"type": "object"}));
assert_eq!(
props["count"],
json!({"type": "integer", "description": "Allowed values: 1, 2."})
);
assert_eq!(props["mode"], json!({"type": "string", "enum": ["a"], "nullable": true}));
assert_eq!(props["list"], json!({"type": "array", "items": {"type": "string"}}));
assert_eq!(
props["pair"],
json!({
"type": "array",
"items": {"anyOf": [{"type": "string"}, {"type": "integer"}]}
})
);
}
#[test]
fn cyclic_refs_terminate() {
let normalized = normalize_tool_schema(&corpus()[6]);
assert_eq!(normalized["type"], "object");
assert!(normalized.get("$defs").is_none());
}
#[test]
fn regex_patterns_drop_while_other_string_guidance_survives() {
let normalized = normalize_tool_schema(&corpus()[7]);
assert_eq!(
normalized["properties"]["email"],
json!({
"type": "string",
"description": "recipient email",
"format": "email"
})
);
assert_eq!(normalized["required"], json!(["email"]));
}
#[test]
fn non_string_enums_move_into_description() {
let normalized = normalize_tool_schema(&corpus()[8]);
let props = &normalized["properties"];
assert_eq!(
props["mode"]["anyOf"][1]["properties"]["headless"],
json!({"type": "boolean", "description": "Must be false.", "default": false})
);
assert_eq!(
props["flag"],
json!({"type": "boolean", "description": "toggle Allowed values: true, false."})
);
assert_eq!(
props["level"],
json!({"type": "number", "description": "Allowed values: 0.5, 1."})
);
assert_eq!(props["blank"], json!({"type": "string", "description": "Must be \"\"."}));
}
#[test]
fn type_specific_keywords_sit_only_on_their_type() {
let normalized = normalize_tool_schema(&corpus()[9]);
let props = &normalized["properties"];
assert_eq!(
props["source_paths"],
json!({
"type": "array",
"items": {
"anyOf": [
{"type": "boolean"},
{"type": "object"},
{"type": "array", "items": {"type": "object"}},
{"type": "number"},
{"type": "string"}
],
"nullable": true
}
})
);
assert_eq!(
props["target"],
json!({
"anyOf": [
{"type": "string"},
{
"type": "object",
"properties": {"path": {"type": "string"}},
"required": ["path"]
}
]
})
);
assert_eq!(
props["grid"],
json!({"type": "array", "items": {"type": "array", "items": {"type": "object"}}})
);
assert_eq!(props["name"], json!({"type": "string"}));
}
#[test]
fn degenerate_top_levels_coerce_to_object() {
assert_eq!(normalize_tool_schema(&json!(true)), json!({"type": "object"}));
assert_eq!(
normalize_tool_schema(&json!({"type": "string", "description": "not an object"})),
json!({"type": "object", "description": "not an object"})
);
assert_eq!(
normalize_tool_schema(&json!({"type": "object", "properties": {}})),
json!({"type": "object"})
);
}
#[test]
fn normalization_is_a_fixpoint() {
for (i, schema) in corpus().iter().enumerate() {
let once = normalize_tool_schema(schema);
let twice = normalize_tool_schema(&once);
assert_eq!(twice, once, "corpus[{i}] is not a fixpoint:\n{once:#}");
}
}
}