Skip to main content

vtcode_utility_tool_specs/
json_schema.rs

1use serde::{Deserialize, Serialize};
2use serde_json::{Map, Value, json};
3
4pub type JsonSchema = Value;
5
6#[derive(Clone, Debug, Serialize, Deserialize)]
7#[serde(untagged)]
8pub enum AdditionalProperties {
9    Boolean(bool),
10    Schema(Box<JsonSchema>),
11}
12
13impl From<bool> for AdditionalProperties {
14    fn from(value: bool) -> Self {
15        Self::Boolean(value)
16    }
17}
18
19#[must_use]
20pub fn parse_tool_input_schema(value: &Value) -> JsonSchema {
21    let mut schema = value.clone();
22    sanitize_json_schema(&mut schema);
23    schema
24}
25
26fn sanitize_json_schema(value: &mut Value) {
27    match value {
28        Value::Bool(_) => {
29            *value = json!({ "type": "string" });
30        }
31        Value::Object(map) => sanitize_schema_object(map),
32        Value::Array(items) => {
33            for item in items {
34                sanitize_json_schema(item);
35            }
36        }
37        Value::Null | Value::Number(_) | Value::String(_) => {}
38    }
39}
40
41fn sanitize_schema_object(map: &mut Map<String, Value>) {
42    if let Some(properties) = map.get_mut("properties").and_then(Value::as_object_mut) {
43        for schema in properties.values_mut() {
44            sanitize_json_schema(schema);
45        }
46    }
47
48    if let Some(items) = map.get_mut("items") {
49        sanitize_json_schema(items);
50    }
51
52    if let Some(prefix_items) = map.get_mut("prefixItems") {
53        sanitize_json_schema(prefix_items);
54    }
55
56    if let Some(additional_properties) = map.get_mut("additionalProperties")
57        && !matches!(additional_properties, Value::Bool(_))
58    {
59        sanitize_json_schema(additional_properties);
60    }
61
62    if let Some(any_of) = map.get_mut("anyOf") {
63        sanitize_json_schema(any_of);
64    }
65
66    if let Some(const_value) = map.remove("const") {
67        drop(map.insert("enum".to_string(), Value::Array(vec![const_value])));
68    }
69
70    let mut schema_types = normalized_schema_types(map);
71    if schema_types.is_empty() && map.contains_key("anyOf") {
72        return;
73    }
74
75    if schema_types.is_empty() {
76        if map.contains_key("properties") || map.contains_key("required") || map.contains_key("additionalProperties") {
77            schema_types.push("object");
78        } else if map.contains_key("items") || map.contains_key("prefixItems") {
79            schema_types.push("array");
80        } else if map.contains_key("enum") || map.contains_key("format") {
81            schema_types.push("string");
82        } else if map.contains_key("minimum")
83            || map.contains_key("maximum")
84            || map.contains_key("exclusiveMinimum")
85            || map.contains_key("exclusiveMaximum")
86            || map.contains_key("multipleOf")
87        {
88            schema_types.push("number");
89        } else {
90            schema_types.push("string");
91        }
92    }
93
94    write_schema_types(map, &schema_types);
95    ensure_default_children_for_schema_types(map, &schema_types);
96}
97
98fn normalized_schema_types(map: &Map<String, Value>) -> Vec<&'static str> {
99    let Some(schema_type) = map.get("type") else {
100        return Vec::new();
101    };
102
103    match schema_type {
104        Value::String(schema_type) => schema_type_from_str(schema_type).into_iter().collect(),
105        Value::Array(schema_types) => schema_types
106            .iter()
107            .filter_map(Value::as_str)
108            .filter_map(schema_type_from_str)
109            .collect(),
110        _ => Vec::new(),
111    }
112}
113
114fn write_schema_types(map: &mut Map<String, Value>, schema_types: &[&'static str]) {
115    match schema_types {
116        [] => {
117            drop(map.remove("type"));
118        }
119        [schema_type] => {
120            drop(map.insert("type".to_string(), Value::String((*schema_type).to_string())));
121        }
122        _ => {
123            drop(
124                map.insert(
125                    "type".to_string(),
126                    Value::Array(
127                        schema_types
128                            .iter()
129                            .map(|schema_type| Value::String((*schema_type).to_string()))
130                            .collect(),
131                    ),
132                ),
133            );
134        }
135    }
136}
137
138fn ensure_default_children_for_schema_types(map: &mut Map<String, Value>, schema_types: &[&str]) {
139    if schema_types.contains(&"object") && !map.contains_key("properties") {
140        drop(map.insert("properties".to_string(), Value::Object(Map::new())));
141    }
142
143    if schema_types.contains(&"array") && !map.contains_key("items") {
144        drop(map.insert("items".to_string(), json!({ "type": "string" })));
145    }
146}
147
148fn schema_type_from_str(schema_type: &str) -> Option<&'static str> {
149    match schema_type {
150        "string" => Some("string"),
151        "number" => Some("number"),
152        "integer" => Some("integer"),
153        "boolean" => Some("boolean"),
154        "object" => Some("object"),
155        "array" => Some("array"),
156        "null" => Some("null"),
157        _ => None,
158    }
159}
160
161#[cfg(test)]
162mod tests {
163    use super::parse_tool_input_schema;
164    use serde_json::{Value, json};
165
166    #[test]
167    fn parse_tool_input_schema_preserves_schema_field_names() {
168        let schema = parse_tool_input_schema(&json!({
169            "type": "object",
170            "properties": {
171                "input": {"type": "string"}
172            },
173            "additionalProperties": false,
174            "anyOf": [
175                {"required": ["input"]},
176                {"required": ["patch"]}
177            ]
178        }));
179
180        let serialized = serde_json::to_value(&schema).expect("serialize schema");
181        assert_eq!(serialized["additionalProperties"], Value::Bool(false));
182        assert!(serialized["anyOf"].is_array());
183        assert!(serialized.get("additional_properties").is_none());
184        assert!(serialized.get("any_of").is_none());
185    }
186
187    #[test]
188    fn parse_tool_input_schema_parses_object_additional_properties_schema() {
189        let schema = parse_tool_input_schema(&json!({
190            "type": "object",
191            "additionalProperties": {
192                "type": "string",
193                "description": "value"
194            }
195        }));
196
197        assert_eq!(schema["type"], "object");
198        assert_eq!(schema["additionalProperties"]["type"], "string");
199        assert_eq!(schema["additionalProperties"]["description"], "value");
200    }
201
202    #[test]
203    fn parse_tool_input_schema_preserves_nested_any_of_and_nullable_type_unions() {
204        let schema = parse_tool_input_schema(&json!({
205            "type": "object",
206            "properties": {
207                "open": {
208                    "anyOf": [
209                        {
210                            "type": "array",
211                            "items": {
212                                "type": "object",
213                                "properties": {
214                                    "ref_id": {"type": "string"},
215                                    "lineno": {"type": ["integer", "null"]}
216                                },
217                                "required": ["ref_id"],
218                                "additionalProperties": false
219                            }
220                        },
221                        {"type": "null"}
222                    ]
223                },
224                "message": {"type": ["string", "null"]}
225            },
226            "additionalProperties": false
227        }));
228
229        let variants = schema["properties"]["open"]["anyOf"].as_array().expect("open anyOf");
230        assert_eq!(variants.len(), 2);
231        assert_eq!(variants[0]["type"], "array");
232        assert_eq!(variants[0]["items"]["type"], "object");
233        assert_eq!(variants[0]["items"]["properties"]["lineno"]["type"], json!(["integer", "null"]));
234        assert_eq!(schema["properties"]["message"]["type"], json!(["string", "null"]));
235    }
236
237    #[test]
238    fn parse_tool_input_schema_preserves_integer_and_string_enums() {
239        let schema = parse_tool_input_schema(&json!({
240            "type": "object",
241            "properties": {
242                "page": {"type": "integer"},
243                "response_length": {
244                    "type": "string",
245                    "enum": ["short", "medium", "long"]
246                },
247                "kind": {
248                    "type": "const",
249                    "const": "tagged"
250                }
251            }
252        }));
253
254        assert_eq!(schema["properties"]["page"]["type"], "integer");
255        assert_eq!(schema["properties"]["response_length"]["enum"], json!(["short", "medium", "long"]));
256        assert_eq!(schema["properties"]["kind"]["type"], "string");
257        assert_eq!(schema["properties"]["kind"]["enum"], json!(["tagged"]));
258    }
259}