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        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")
77            || map.contains_key("required")
78            || map.contains_key("additionalProperties")
79        {
80            schema_types.push("object");
81        } else if map.contains_key("items") || map.contains_key("prefixItems") {
82            schema_types.push("array");
83        } else if map.contains_key("enum") || map.contains_key("format") {
84            schema_types.push("string");
85        } else if map.contains_key("minimum")
86            || map.contains_key("maximum")
87            || map.contains_key("exclusiveMinimum")
88            || map.contains_key("exclusiveMaximum")
89            || map.contains_key("multipleOf")
90        {
91            schema_types.push("number");
92        } else {
93            schema_types.push("string");
94        }
95    }
96
97    write_schema_types(map, &schema_types);
98    ensure_default_children_for_schema_types(map, &schema_types);
99}
100
101fn normalized_schema_types(map: &Map<String, Value>) -> Vec<&'static str> {
102    let Some(schema_type) = map.get("type") else {
103        return Vec::new();
104    };
105
106    match schema_type {
107        Value::String(schema_type) => schema_type_from_str(schema_type).into_iter().collect(),
108        Value::Array(schema_types) => schema_types
109            .iter()
110            .filter_map(Value::as_str)
111            .filter_map(schema_type_from_str)
112            .collect(),
113        _ => Vec::new(),
114    }
115}
116
117fn write_schema_types(map: &mut Map<String, Value>, schema_types: &[&'static str]) {
118    match schema_types {
119        [] => {
120            map.remove("type");
121        }
122        [schema_type] => {
123            map.insert("type".to_string(), Value::String((*schema_type).to_string()));
124        }
125        _ => {
126            map.insert(
127                "type".to_string(),
128                Value::Array(
129                    schema_types
130                        .iter()
131                        .map(|schema_type| Value::String((*schema_type).to_string()))
132                        .collect(),
133                ),
134            );
135        }
136    }
137}
138
139fn ensure_default_children_for_schema_types(map: &mut Map<String, Value>, schema_types: &[&str]) {
140    if schema_types.contains(&"object") && !map.contains_key("properties") {
141        map.insert("properties".to_string(), Value::Object(Map::new()));
142    }
143
144    if schema_types.contains(&"array") && !map.contains_key("items") {
145        map.insert("items".to_string(), json!({ "type": "string" }));
146    }
147}
148
149fn schema_type_from_str(schema_type: &str) -> Option<&'static str> {
150    match schema_type {
151        "string" => Some("string"),
152        "number" => Some("number"),
153        "integer" => Some("integer"),
154        "boolean" => Some("boolean"),
155        "object" => Some("object"),
156        "array" => Some("array"),
157        "null" => Some("null"),
158        _ => None,
159    }
160}
161
162#[cfg(test)]
163mod tests {
164    use super::parse_tool_input_schema;
165    use serde_json::{Value, json};
166
167    #[test]
168    fn parse_tool_input_schema_preserves_schema_field_names() {
169        let schema = parse_tool_input_schema(&json!({
170            "type": "object",
171            "properties": {
172                "input": {"type": "string"}
173            },
174            "additionalProperties": false,
175            "anyOf": [
176                {"required": ["input"]},
177                {"required": ["patch"]}
178            ]
179        }));
180
181        let serialized = serde_json::to_value(&schema).expect("serialize schema");
182        assert_eq!(serialized["additionalProperties"], Value::Bool(false));
183        assert!(serialized["anyOf"].is_array());
184        assert!(serialized.get("additional_properties").is_none());
185        assert!(serialized.get("any_of").is_none());
186    }
187
188    #[test]
189    fn parse_tool_input_schema_parses_object_additional_properties_schema() {
190        let schema = parse_tool_input_schema(&json!({
191            "type": "object",
192            "additionalProperties": {
193                "type": "string",
194                "description": "value"
195            }
196        }));
197
198        assert_eq!(schema["type"], "object");
199        assert_eq!(schema["additionalProperties"]["type"], "string");
200        assert_eq!(schema["additionalProperties"]["description"], "value");
201    }
202
203    #[test]
204    fn parse_tool_input_schema_preserves_nested_any_of_and_nullable_type_unions() {
205        let schema = parse_tool_input_schema(&json!({
206            "type": "object",
207            "properties": {
208                "open": {
209                    "anyOf": [
210                        {
211                            "type": "array",
212                            "items": {
213                                "type": "object",
214                                "properties": {
215                                    "ref_id": {"type": "string"},
216                                    "lineno": {"type": ["integer", "null"]}
217                                },
218                                "required": ["ref_id"],
219                                "additionalProperties": false
220                            }
221                        },
222                        {"type": "null"}
223                    ]
224                },
225                "message": {"type": ["string", "null"]}
226            },
227            "additionalProperties": false
228        }));
229
230        let variants = schema["properties"]["open"]["anyOf"].as_array().expect("open anyOf");
231        assert_eq!(variants.len(), 2);
232        assert_eq!(variants[0]["type"], "array");
233        assert_eq!(variants[0]["items"]["type"], "object");
234        assert_eq!(
235            variants[0]["items"]["properties"]["lineno"]["type"],
236            json!(["integer", "null"])
237        );
238        assert_eq!(schema["properties"]["message"]["type"], json!(["string", "null"]));
239    }
240
241    #[test]
242    fn parse_tool_input_schema_preserves_integer_and_string_enums() {
243        let schema = parse_tool_input_schema(&json!({
244            "type": "object",
245            "properties": {
246                "page": {"type": "integer"},
247                "response_length": {
248                    "type": "string",
249                    "enum": ["short", "medium", "long"]
250                },
251                "kind": {
252                    "type": "const",
253                    "const": "tagged"
254                }
255            }
256        }));
257
258        assert_eq!(schema["properties"]["page"]["type"], "integer");
259        assert_eq!(
260            schema["properties"]["response_length"]["enum"],
261            json!(["short", "medium", "long"])
262        );
263        assert_eq!(schema["properties"]["kind"]["type"], "string");
264        assert_eq!(schema["properties"]["kind"]["enum"], json!(["tagged"]));
265    }
266}