Skip to main content

vtcode_utility_tool_specs/
lib.rs

1#![allow(missing_docs)]
2//! Passive JSON schemas for utility, file, scheduling, and collaboration tool surfaces.
3
4#![recursion_limit = "256"]
5
6use serde_json::{Value, json};
7
8mod collaboration;
9mod json_schema;
10#[cfg(feature = "mcp")]
11mod mcp_tool;
12mod responses_api;
13
14pub use collaboration::{
15    agent_parameters, close_agent_parameters, request_user_input_description,
16    request_user_input_parameters, resume_agent_parameters, send_input_parameters,
17    spawn_agent_parameters, spawn_background_subprocess_parameters, wait_agent_parameters,
18};
19pub use json_schema::{AdditionalProperties, JsonSchema, parse_tool_input_schema};
20#[cfg(feature = "mcp")]
21pub use mcp_tool::{ParsedMcpTool, parse_mcp_tool};
22pub use responses_api::{FreeformTool, FreeformToolFormat, ResponsesApiTool};
23
24pub const SEMANTIC_ANCHOR_GUIDANCE: &str =
25    "Prefer stable semantic @@ anchors such as function, class, method, or impl names.";
26
27/// Explicit, format-bearing description for the `patch` alias field. The old
28/// value ("Alias for input") gave the model no format guidance, so it often
29/// placed a standard unified diff (`---`/`+++`) there — which `apply_patch`
30/// rejects. This mirrors the `input` description so both alias fields carry
31/// identical, complete format guidance (see checkpoint turn_615 for the
32/// failure this prevents).
33pub const APPLY_PATCH_ALIAS_DESCRIPTION: &str = "Patch in VT Code format (*** Begin Patch, *** Update File: path, @@ hunk, -/+ lines, *** End Patch). Same envelope as 'input'; do NOT use unified diff (--- /+++ format).";
34pub const DEFAULT_APPLY_PATCH_INPUT_DESCRIPTION: &str = "Patch in VT Code format: *** Begin Patch, *** Update File: path, @@ hunk, -/+ lines, *** End Patch";
35
36#[must_use]
37pub fn with_semantic_anchor_guidance(base: &str) -> String {
38    let trimmed = base.trim_end();
39    if trimmed.contains(SEMANTIC_ANCHOR_GUIDANCE) {
40        trimmed.to_string()
41    } else if trimmed.ends_with('.') {
42        format!("{trimmed} {SEMANTIC_ANCHOR_GUIDANCE}")
43    } else {
44        format!("{trimmed}. {SEMANTIC_ANCHOR_GUIDANCE}")
45    }
46}
47
48#[must_use]
49pub fn apply_patch_parameter_schema(input_description: &str) -> Value {
50    json!({
51        "type": "object",
52        "properties": {
53            "input": {
54                "type": "string",
55                "description": with_semantic_anchor_guidance(input_description)
56            },
57            "patch": {
58                "type": "string",
59                "description": with_semantic_anchor_guidance(APPLY_PATCH_ALIAS_DESCRIPTION)
60            }
61        },
62        "anyOf": [
63            {"required": ["input"]},
64            {"required": ["patch"]}
65        ]
66    })
67}
68
69#[must_use]
70pub fn apply_patch_parameters() -> Value {
71    apply_patch_parameter_schema(DEFAULT_APPLY_PATCH_INPUT_DESCRIPTION)
72}
73
74#[must_use]
75pub fn cron_parameters() -> Value {
76    json!({
77        "type": "object",
78        "required": ["action"],
79        "additionalProperties": false,
80        "properties": {
81            "action": {
82                "type": "string",
83                "enum": ["create", "list", "delete"],
84                "description": "create: schedule a prompt (requires prompt and exactly one of cron, delay_minutes, or run_at). list: show scheduled prompts. delete: remove one by id."
85            },
86            "prompt": {"type": "string", "description": "create: prompt to run when the task fires."},
87            "name": {"type": "string", "description": "create: optional short label for the task."},
88            "cron": {"type": "string", "description": "create: five-field cron expression for recurring tasks."},
89            "delay_minutes": {"type": "integer", "description": "create: fixed recurring interval in minutes."},
90            "run_at": {"type": "string", "description": "create: one-shot fire time in RFC3339 or local datetime form."},
91            "id": {"type": "string", "description": "delete: session scheduled task id to delete."}
92        }
93    })
94}
95
96#[must_use]
97pub fn mcp_parameters() -> Value {
98    json!({
99        "type": "object",
100        "required": ["action"],
101        "properties": {
102            "action": {
103                "type": "string",
104                "enum": ["search_tools", "get_tool_details", "list_servers", "connect", "disconnect"],
105                "description": "search_tools: find MCP tools by natural-language query. get_tool_details: fetch the full input schema for one MCP tool name. list_servers: list configured servers and their connection state. connect or disconnect: manage one configured MCP server by name."
106            },
107            "query": {"type": "string", "description": "search_tools: natural language query describing the MCP capability to find."},
108            "detail_level": {"type": "string", "enum": ["name", "name_description", "full"], "description": "search_tools: response detail level."},
109            "limit": {"type": "integer", "minimum": 1, "maximum": 25, "description": "search_tools: maximum number of results to return."},
110            "name": {"type": "string", "description": "get_tool_details: exact MCP tool name. connect or disconnect: configured MCP server name."}
111        },
112        "additionalProperties": false
113    })
114}
115
116#[must_use]
117pub fn cron_create_parameters() -> Value {
118    json!({
119        "type": "object",
120        "required": ["prompt"],
121        "additionalProperties": false,
122        "properties": {
123            "prompt": {"type": "string", "description": "Prompt to run when the task fires."},
124            "name": {"type": "string", "description": "Optional short label for the task."},
125            "cron": {"type": "string", "description": "Five-field cron expression for recurring tasks."},
126            "delay_minutes": {"type": "integer", "description": "Fixed recurring interval in minutes."},
127            "run_at": {
128                "type": "string",
129                "description": "One-shot fire time in RFC3339 or local datetime form. Use this instead of `cron` or `delay_minutes` for reminders."
130            }
131        }
132    })
133}
134
135#[must_use]
136pub fn cron_list_parameters() -> Value {
137    json!({
138        "type": "object",
139        "properties": {},
140        "additionalProperties": false
141    })
142}
143
144#[must_use]
145pub fn cron_delete_parameters() -> Value {
146    json!({
147        "type": "object",
148        "required": ["id"],
149        "properties": {
150            "id": {"type": "string", "description": "Session scheduled task id to delete."}
151        }
152    })
153}
154
155#[must_use]
156pub fn exec_command_parameters() -> Value {
157    json!({
158        "type": "object",
159        "required": ["cmd"],
160        "properties": {
161            "cmd": {"type": "string", "description": "Shell command to execute, subject to command policy. Examples include `ls`, `rg`, `find`, `cat`, `sed`, `awk`, build tools, and test tools."},
162            "yield_time_ms": {"type": "integer", "description": "Wait before returning output (ms). If the command is still running, the response includes a session_id for write_stdin.", "default": 10000},
163            "max_output_tokens": {"type": "integer", "description": "Output token cap. Large or truncated output can return a spool_path for the full output."},
164            "workdir": {"type": "string", "description": "Working directory."},
165            "tty": {"type": "boolean", "description": "Run the command in PTY mode for interactive or terminal-sensitive commands.", "default": false},
166            "sandbox_permissions": {
167                "type": "string",
168                "enum": ["use_default", "with_additional_permissions", "require_escalated", "bypass_sandbox"],
169                "description": "Sandbox permission mode for this command.",
170                "default": "use_default"
171            },
172            "additional_permissions": {
173                "type": "object",
174                "description": "Additional filesystem access requested with sandbox_permissions set to with_additional_permissions.",
175                "properties": {
176                    "fs_read": {"type": "array", "items": {"type": "string"}},
177                    "fs_write": {"type": "array", "items": {"type": "string"}}
178                },
179                "additionalProperties": false
180            },
181            "justification": {"type": "string", "description": "Short approval question required for escalated or bypassed sandbox execution."}
182        },
183        "additionalProperties": false
184    })
185}
186
187#[must_use]
188pub fn write_stdin_parameters() -> Value {
189    json!({
190        "type": "object",
191        "required": ["session_id", "chars"],
192        "properties": {
193            "session_id": {"type": "string", "description": "Active execution session id."},
194            "chars": {"type": "string", "description": "Bytes to write to stdin. Pass an empty string to poll without sending input."},
195            "yield_time_ms": {"type": "integer", "description": "Wait before returning fresh session output (ms).", "default": 1000},
196            "max_output_tokens": {"type": "integer", "description": "Output token cap for the continuation response. Large or truncated output can return a spool_path for the full output."}
197        },
198        "additionalProperties": false
199    })
200}
201
202#[must_use]
203pub fn code_search_parameters() -> Value {
204    json!({
205        "type": "object",
206        "required": ["query"],
207        "additionalProperties": false,
208        "properties": {
209            "query": {
210                "type": "string",
211                "minLength": 1,
212                "pattern": "\\S",
213                "description": "Literal code or path query. Smart-case applies to content and exact symbol-name matching: a wholly lower-case query matches case-insensitively, while an upper-case character makes matching case-sensitive. Path matching remains fuzzy and case-insensitive."
214            },
215            "path": {
216                "type": "string",
217                "minLength": 1,
218                "pattern": "\\S",
219                "description": "Workspace-relative file or directory to search. Omit to search the workspace root."
220            },
221            "file_types": {
222                "type": "array",
223                "minItems": 1,
224                "items": {
225                    "type": "string",
226                    "minLength": 1,
227                    "pattern": "\\S"
228                },
229                "description": "Language names or common file extensions, with or without one leading dot."
230            },
231            "result_types": {
232                "type": "array",
233                "minItems": 1,
234                "items": {
235                    "type": "string",
236                    "enum": ["definition", "usage", "text", "path"]
237                },
238                "description": "Result categories to include. Omit to include all four categories."
239            },
240            "max_results": {
241                "type": "integer",
242                "minimum": 1,
243                "maximum": 100,
244                "description": "Maximum number of merged results to return. Omit for 20."
245            }
246        }
247    })
248}
249
250#[must_use]
251pub fn list_files_parameters() -> Value {
252    json!({
253        "type": "object",
254        "properties": {
255            "path": {"type": "string", "description": "Directory or file path to inspect.", "default": "."},
256            "mode": {
257                "type": "string",
258                "enum": ["list", "recursive", "tree", "find_name", "find_content", "largest", "file", "files"],
259                "description": "Listing mode. Use page/per_page to continue paginated results.",
260                "default": "list"
261            },
262            "pattern": {"type": "string", "description": "Optional glob-style path filter."},
263            "name_pattern": {"type": "string", "description": "Optional name filter for list/find_name modes."},
264            "content_pattern": {"type": "string", "description": "Content query for find_content mode."},
265            "page": {"type": "integer", "description": "1-indexed results page.", "minimum": 1},
266            "per_page": {"type": "integer", "description": "Items per page.", "minimum": 1},
267            "max_results": {"type": "integer", "description": "Maximum total results to consider before pagination.", "minimum": 1},
268            "include_hidden": {"type": "boolean", "description": "Include dotfiles and hidden entries.", "default": false},
269            "response_format": {"type": "string", "enum": ["concise", "detailed"], "description": "Verbosity of the listing output.", "default": "concise"},
270            "case_sensitive": {"type": "boolean", "description": "Case-sensitive name matching.", "default": false}
271        }
272    })
273}
274
275#[cfg(test)]
276mod tests {
277    use super::*;
278    use serde_json::json;
279
280    #[test]
281    fn apply_patch_parameter_schema_keeps_alias_and_guidance_consistent() {
282        let schema = apply_patch_parameter_schema("Patch in VT Code format");
283
284        // Both `input` and `patch` alias fields now carry the format
285        // description AND the semantic-anchor guidance, preventing the model
286        // from placing a unified diff in `patch` (see checkpoint turn_615).
287        assert_eq!(
288            schema["properties"]["patch"]["description"],
289            with_semantic_anchor_guidance(APPLY_PATCH_ALIAS_DESCRIPTION)
290        );
291        let patch_description = schema["properties"]["patch"]["description"]
292            .as_str()
293            .expect("patch description");
294        assert!(patch_description.contains("*** Begin Patch"));
295        assert!(patch_description.contains("unified diff"));
296        assert!(patch_description.contains(SEMANTIC_ANCHOR_GUIDANCE));
297
298        let input_description = schema["properties"]["input"]["description"]
299            .as_str()
300            .expect("input description");
301        assert!(input_description.contains(SEMANTIC_ANCHOR_GUIDANCE));
302    }
303
304    #[test]
305    fn codex_baseline_exec_schemas_use_public_names_shape() {
306        let exec_params = exec_command_parameters();
307        assert_eq!(exec_params["required"], json!(["cmd"]));
308        assert!(exec_params["properties"]["cmd"].is_object());
309        assert!(exec_params["properties"]["workdir"].is_object());
310        assert!(
311            exec_params["properties"]["yield_time_ms"]["description"]
312                .as_str()
313                .expect("exec yield description")
314                .contains("session_id")
315        );
316        assert!(
317            exec_params["properties"]["max_output_tokens"]["description"]
318                .as_str()
319                .expect("exec max output description")
320                .contains("spool_path")
321        );
322        assert_eq!(exec_params["properties"]["tty"]["type"], "boolean");
323        assert_eq!(exec_params["properties"]["tty"]["default"], false);
324        assert_eq!(exec_params["properties"]["yield_time_ms"]["default"], 10000);
325        assert_eq!(
326            exec_params["properties"]["sandbox_permissions"]["enum"],
327            json!([
328                "use_default",
329                "with_additional_permissions",
330                "require_escalated",
331                "bypass_sandbox"
332            ])
333        );
334        assert_eq!(exec_params["properties"]["sandbox_permissions"]["default"], "use_default");
335        assert_eq!(
336            exec_params["properties"]["additional_permissions"]["properties"]["fs_read"]["items"]["type"],
337            "string"
338        );
339        assert_eq!(
340            exec_params["properties"]["additional_permissions"]["properties"]["fs_write"]["items"]
341                ["type"],
342            "string"
343        );
344        assert_eq!(
345            exec_params["properties"]["additional_permissions"]["additionalProperties"],
346            false
347        );
348        assert_eq!(exec_params["properties"]["justification"]["type"], "string");
349        assert_eq!(exec_params["additionalProperties"], false);
350        for command in ["ls", "rg", "find", "cat", "sed", "awk"] {
351            assert!(
352                exec_params["properties"]["cmd"]["description"]
353                    .as_str()
354                    .expect("cmd description")
355                    .contains(command),
356                "{command} should be described as an exec_command.cmd example"
357            );
358            assert!(
359                exec_params["properties"].get(command).is_none(),
360                "{command} must not be modelled as a separate exec_command field"
361            );
362        }
363
364        let stdin_params = write_stdin_parameters();
365        assert_eq!(stdin_params["required"], json!(["session_id", "chars"]));
366        assert!(stdin_params["properties"]["session_id"].is_object());
367        assert_eq!(stdin_params["properties"]["chars"]["type"], "string");
368        assert!(
369            stdin_params["properties"]["chars"]["description"]
370                .as_str()
371                .is_some_and(|description| description.contains("empty string"))
372        );
373        assert!(stdin_params["properties"]["chars"].is_object());
374        assert!(
375            stdin_params["properties"]["yield_time_ms"]["description"]
376                .as_str()
377                .expect("stdin yield description")
378                .contains("fresh session output")
379        );
380        assert!(
381            stdin_params["properties"]["max_output_tokens"]["description"]
382                .as_str()
383                .expect("stdin max output description")
384                .contains("spool_path")
385        );
386        assert_eq!(stdin_params["additionalProperties"], false);
387    }
388
389    #[test]
390    fn code_search_schema_exposes_exact_five_property_contract() {
391        let params = code_search_parameters();
392        let properties = params["properties"].as_object().expect("properties");
393        let mut property_names = properties.keys().map(String::as_str).collect::<Vec<_>>();
394        property_names.sort_unstable();
395
396        assert_eq!(params["required"], json!(["query"]));
397        assert_eq!(property_names, ["file_types", "max_results", "path", "query", "result_types"]);
398        assert_eq!(params["additionalProperties"], false);
399        assert_eq!(params["properties"]["query"]["pattern"], "\\S");
400        assert_eq!(params["properties"]["file_types"]["minItems"], 1);
401        assert_eq!(params["properties"]["result_types"]["minItems"], 1);
402        assert_eq!(
403            params["properties"]["result_types"]["items"]["enum"],
404            json!(["definition", "usage", "text", "path"])
405        );
406        assert_eq!(params["properties"]["max_results"]["minimum"], 1);
407        assert_eq!(params["properties"]["max_results"]["maximum"], 100);
408        assert!(params.get("anyOf").is_none());
409    }
410
411    #[test]
412    fn legacy_list_files_schema_exposes_pagination_fields() {
413        let list_params = list_files_parameters();
414        assert!(list_params["properties"]["page"].is_object());
415        assert!(list_params["properties"]["per_page"].is_object());
416        assert!(
417            list_params["properties"]["mode"]["enum"]
418                .as_array()
419                .expect("mode enum")
420                .iter()
421                .any(|value| value == "recursive")
422        );
423    }
424
425    #[test]
426    fn semantic_anchor_guidance_is_appended_once() {
427        let base = "Patch in VT Code format.";
428        let with_guidance = with_semantic_anchor_guidance(base);
429
430        assert!(with_guidance.contains(SEMANTIC_ANCHOR_GUIDANCE));
431        assert_eq!(with_semantic_anchor_guidance(&with_guidance), with_guidance);
432    }
433
434    #[test]
435    fn default_apply_patch_parameters_keep_expected_alias_shape() {
436        let schema = apply_patch_parameters();
437
438        assert_eq!(
439            schema["anyOf"],
440            json!([
441                {"required": ["input"]},
442                {"required": ["patch"]}
443            ])
444        );
445    }
446}