vtcode_utility_tool_specs/
json_schema.rs1use 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") || 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 map.remove("type");
118 }
119 [schema_type] => {
120 map.insert("type".to_string(), Value::String((*schema_type).to_string()));
121 }
122 _ => {
123 map.insert(
124 "type".to_string(),
125 Value::Array(
126 schema_types
127 .iter()
128 .map(|schema_type| Value::String((*schema_type).to_string()))
129 .collect(),
130 ),
131 );
132 }
133 }
134}
135
136fn ensure_default_children_for_schema_types(map: &mut Map<String, Value>, schema_types: &[&str]) {
137 if schema_types.contains(&"object") && !map.contains_key("properties") {
138 map.insert("properties".to_string(), Value::Object(Map::new()));
139 }
140
141 if schema_types.contains(&"array") && !map.contains_key("items") {
142 map.insert("items".to_string(), json!({ "type": "string" }));
143 }
144}
145
146fn schema_type_from_str(schema_type: &str) -> Option<&'static str> {
147 match schema_type {
148 "string" => Some("string"),
149 "number" => Some("number"),
150 "integer" => Some("integer"),
151 "boolean" => Some("boolean"),
152 "object" => Some("object"),
153 "array" => Some("array"),
154 "null" => Some("null"),
155 _ => None,
156 }
157}
158
159#[cfg(test)]
160mod tests {
161 use super::parse_tool_input_schema;
162 use serde_json::{Value, json};
163
164 #[test]
165 fn parse_tool_input_schema_preserves_schema_field_names() {
166 let schema = parse_tool_input_schema(&json!({
167 "type": "object",
168 "properties": {
169 "input": {"type": "string"}
170 },
171 "additionalProperties": false,
172 "anyOf": [
173 {"required": ["input"]},
174 {"required": ["patch"]}
175 ]
176 }));
177
178 let serialized = serde_json::to_value(&schema).expect("serialize schema");
179 assert_eq!(serialized["additionalProperties"], Value::Bool(false));
180 assert!(serialized["anyOf"].is_array());
181 assert!(serialized.get("additional_properties").is_none());
182 assert!(serialized.get("any_of").is_none());
183 }
184
185 #[test]
186 fn parse_tool_input_schema_parses_object_additional_properties_schema() {
187 let schema = parse_tool_input_schema(&json!({
188 "type": "object",
189 "additionalProperties": {
190 "type": "string",
191 "description": "value"
192 }
193 }));
194
195 assert_eq!(schema["type"], "object");
196 assert_eq!(schema["additionalProperties"]["type"], "string");
197 assert_eq!(schema["additionalProperties"]["description"], "value");
198 }
199
200 #[test]
201 fn parse_tool_input_schema_preserves_nested_any_of_and_nullable_type_unions() {
202 let schema = parse_tool_input_schema(&json!({
203 "type": "object",
204 "properties": {
205 "open": {
206 "anyOf": [
207 {
208 "type": "array",
209 "items": {
210 "type": "object",
211 "properties": {
212 "ref_id": {"type": "string"},
213 "lineno": {"type": ["integer", "null"]}
214 },
215 "required": ["ref_id"],
216 "additionalProperties": false
217 }
218 },
219 {"type": "null"}
220 ]
221 },
222 "message": {"type": ["string", "null"]}
223 },
224 "additionalProperties": false
225 }));
226
227 let variants = schema["properties"]["open"]["anyOf"].as_array().expect("open anyOf");
228 assert_eq!(variants.len(), 2);
229 assert_eq!(variants[0]["type"], "array");
230 assert_eq!(variants[0]["items"]["type"], "object");
231 assert_eq!(variants[0]["items"]["properties"]["lineno"]["type"], json!(["integer", "null"]));
232 assert_eq!(schema["properties"]["message"]["type"], json!(["string", "null"]));
233 }
234
235 #[test]
236 fn parse_tool_input_schema_preserves_integer_and_string_enums() {
237 let schema = parse_tool_input_schema(&json!({
238 "type": "object",
239 "properties": {
240 "page": {"type": "integer"},
241 "response_length": {
242 "type": "string",
243 "enum": ["short", "medium", "long"]
244 },
245 "kind": {
246 "type": "const",
247 "const": "tagged"
248 }
249 }
250 }));
251
252 assert_eq!(schema["properties"]["page"]["type"], "integer");
253 assert_eq!(schema["properties"]["response_length"]["enum"], json!(["short", "medium", "long"]));
254 assert_eq!(schema["properties"]["kind"]["type"], "string");
255 assert_eq!(schema["properties"]["kind"]["enum"], json!(["tagged"]));
256 }
257}