use serde_json::{Map, Value, json};
pub(crate) const MAX_TOOL_SCHEMA_BYTES: usize = 5_000;
pub(crate) const MAX_TOOL_SCHEMA_DEPTH: usize = 3;
const ANNOTATION_KEYS: &[&str] = &[
"$schema",
"$id",
"$comment",
"title",
"examples",
"example",
"default",
"deprecated",
"readOnly",
"writeOnly",
"externalDocs",
"contentEncoding",
"contentMediaType",
];
const SCHEMA_MAPS: &[&str] = &["properties", "patternProperties", "$defs", "definitions"];
pub(crate) fn fit_schema_to_budget(schema: &mut Value) -> FitOutcome {
if compact_bytes(schema) <= MAX_TOOL_SCHEMA_BYTES {
return FitOutcome::Untouched;
}
for (pass, step) in [
(
"annotations",
(|v: &mut Value| strip_annotations(v)) as fn(&mut Value),
),
("nested prose", drop_nested_prose),
("depth", clamp_depth),
("property prose", drop_property_prose),
("the tool's own prose", drop_root_prose),
] {
step(schema);
if compact_bytes(schema) <= MAX_TOOL_SCHEMA_BYTES {
return FitOutcome::Compressed(pass);
}
}
FitOutcome::OverBudget
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum FitOutcome {
Untouched,
Compressed(&'static str),
OverBudget,
}
fn compact_bytes(schema: &Value) -> usize {
serde_json::to_string(schema).map(|s| s.len()).unwrap_or(0)
}
fn walk_schemas(
node: &mut Value,
depth: usize,
f: &mut impl FnMut(&mut Map<String, Value>, usize),
) {
match node {
Value::Object(map) => {
let is_container = map.keys().any(|k| SCHEMA_MAPS.contains(&k.as_str()))
&& !map.contains_key("type")
&& !map.contains_key("enum");
if !is_container {
f(map, depth);
}
for (key, child) in map.iter_mut() {
let next = if SCHEMA_MAPS.contains(&key.as_str()) {
depth
} else {
depth + 1
};
walk_schemas(child, next, f);
}
}
Value::Array(items) => {
for child in items.iter_mut() {
walk_schemas(child, depth, f);
}
}
_ => {}
}
}
fn strip_annotations(schema: &mut Value) {
walk_schemas(schema, 0, &mut |map, _| {
for key in ANNOTATION_KEYS {
map.remove(*key);
}
});
}
fn drop_nested_prose(schema: &mut Value) {
walk_schemas(schema, 0, &mut |map, depth| {
if depth >= 2 {
map.remove("description");
}
});
}
fn drop_property_prose(schema: &mut Value) {
walk_schemas(schema, 0, &mut |map, depth| {
if depth == 1 {
map.remove("description");
}
});
}
fn drop_root_prose(schema: &mut Value) {
if let Value::Object(map) = schema {
map.remove("description");
}
}
fn clamp_depth(schema: &mut Value) {
let mut over: Vec<(Vec<String>, Value)> = Vec::new();
clamp_depth_at(schema, 0, &mut Vec::new(), &mut over);
for (path, bare) in over {
let mut slot = &mut *schema;
for key in &path {
slot = match slot {
Value::Object(m) => m.entry(key.as_str()).or_insert(json!({})),
Value::Array(a) => &mut a[key.parse::<usize>().unwrap_or(0)],
other => other,
};
}
*slot = bare;
}
}
fn clamp_depth_at(
node: &mut Value,
depth: usize,
path: &mut Vec<String>,
over: &mut Vec<(Vec<String>, Value)>,
) {
if !matches!(node, Value::Object(_) | Value::Array(_)) {
return;
}
if depth > MAX_TOOL_SCHEMA_DEPTH
&& let Value::Object(_) = node
{
let bare = node.get("type").cloned().unwrap_or_else(|| json!("object"));
over.push((path.clone(), json!({ "type": bare })));
return;
}
match node {
Value::Object(map) => {
let keys: Vec<String> = map.keys().cloned().collect();
for key in keys {
let next = if SCHEMA_MAPS.contains(&key.as_str()) {
depth
} else {
depth + 1
};
path.push(key.clone());
if let Some(child) = map.get_mut(&key) {
clamp_depth_at(child, next, path, over);
}
path.pop();
}
}
Value::Array(items) => {
for (i, child) in items.iter_mut().enumerate() {
path.push(i.to_string());
clamp_depth_at(child, depth, path, over);
path.pop();
}
}
_ => {}
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::Map;
fn oversized_schema(props: usize, prose: usize) -> Value {
let mut properties = Map::new();
for i in 0..props {
properties.insert(
format!("arg_{i}"),
json!({
"type": "object",
"title": format!("Argument {i}"),
"description": "a".repeat(prose),
"properties": {
"inner": {
"type": "string",
"description": "b".repeat(prose),
}
}
}),
);
}
json!({
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "An oversized tool",
"type": "object",
"description": "C".repeat(prose),
"properties": properties,
"required": ["arg_0"],
})
}
fn bytes(schema: &Value) -> usize {
compact_bytes(schema)
}
#[test]
fn a_schema_under_budget_is_left_alone() {
let mut schema = json!({"type": "object", "properties": {"p": {"type": "string"}}});
let before = schema.clone();
assert_eq!(fit_schema_to_budget(&mut schema), FitOutcome::Untouched);
assert_eq!(schema, before, "under budget means untouched");
}
#[test]
fn the_argument_surface_survives_every_pass() {
let mut schema = oversized_schema(40, 400);
fit_schema_to_budget(&mut schema);
let props = schema["properties"].as_object().expect("properties kept");
assert_eq!(props.len(), 40, "no argument may be dropped");
assert!(props.contains_key("arg_0"), "names survive verbatim");
assert_eq!(props["arg_0"]["type"], "object", "types survive");
assert_eq!(schema["required"], json!(["arg_0"]), "`required` survives");
assert_eq!(schema["type"], "object", "the root type survives");
}
#[test]
fn annotations_go_and_prose_stays() {
let mut schema = oversized_schema(3, 1_200);
assert!(
bytes(&schema) > MAX_TOOL_SCHEMA_BYTES,
"fixture starts over"
);
strip_annotations(&mut schema);
assert!(schema["$schema"].is_null(), "`$schema` is an annotation");
assert!(schema["title"].is_null(), "`title` is an annotation");
assert!(
schema["description"].is_string()
&& schema["properties"]["arg_0"]["description"].is_string(),
"a pass named 'annotations' must not touch prose of any level"
);
}
#[test]
fn nested_prose_goes_before_the_tools_own() {
let mut schema = oversized_schema(3, 900);
assert!(
bytes(&schema) > MAX_TOOL_SCHEMA_BYTES,
"fixture starts over"
);
drop_nested_prose(&mut schema);
assert!(
bytes(&schema) <= MAX_TOOL_SCHEMA_BYTES,
"fixture must fit after nested prose alone, or this asserts nothing"
);
assert!(
schema["description"].is_string(),
"the tool's own words outlive the nested ones"
);
assert!(
schema["properties"]["arg_0"]["description"].is_string(),
"an argument's own words outlive the nested ones too"
);
assert!(
schema["properties"]["arg_0"]["properties"]["inner"]["description"].is_null(),
"the nested prose is what went"
);
}
#[test]
fn the_ladder_stops_as_soon_as_it_fits() {
let mut schema = oversized_schema(3, 900);
let outcome = fit_schema_to_budget(&mut schema);
assert_eq!(outcome, FitOutcome::Compressed("nested prose"));
assert!(
schema["properties"]["arg_0"]["description"].is_string(),
"a pass the ladder never reached must not have fired"
);
}
#[test]
fn a_tool_that_cannot_fit_is_kept_not_dropped() {
let mut schema = oversized_schema(200, 400);
assert_eq!(fit_schema_to_budget(&mut schema), FitOutcome::OverBudget);
assert_eq!(
schema["properties"].as_object().map(|p| p.len()),
Some(200),
"even a hopeless schema keeps its arguments"
);
}
#[test]
fn deep_nesting_is_flattened_not_truncated() {
let mut schema = json!({
"type": "object",
"properties": {
"a": {
"type": "object",
"properties": {
"b": {
"type": "object",
"properties": {
"c": {
"type": "object",
"properties": {
"d": { "type": "string", "description": "deep" }
}
}
}
}
}
}
}
});
clamp_depth(&mut schema);
let c = &schema["properties"]["a"]["properties"]["b"]["properties"]["c"];
let d = &c["properties"]["d"];
assert_eq!(
d.as_object().map(|m| m.len()),
Some(1),
"past the ceiling a subschema is its bare type and nothing else"
);
assert_eq!(d["type"], "string", "the bare type is kept");
assert!(
c["properties"].is_object() && c["type"] == "object",
"levels at or under the ceiling keep their structure"
);
assert!(
schema["properties"]["a"]["properties"]["b"]["type"] == "object",
"and are not flattened by a pass aimed deeper down"
);
}
#[test]
fn a_type_name_is_never_treated_as_a_schema() {
let mut schema = json!({
"type": "object",
"properties": {
"a": {
"type": "object",
"properties": {
"b": {
"type": "object",
"properties": {
"c": {
"type": "object",
"properties": {
"d": { "type": "string", "description": "deep" }
}
}
}
}
}
}
}
});
clamp_depth(&mut schema);
assert_eq!(
schema["properties"]["a"]["properties"]["b"]["properties"]["c"]["type"],
json!("object"),
"a type name stays a name"
);
}
}