Skip to main content

vtcode_utility_tool_specs/
lib.rs

1#![allow(
2    missing_docs,
3    dead_code,
4    unused_imports,
5    reason = "Intentional compatibility, platform, or test-only suppression."
6)]
7
8//! Passive JSON schemas for utility, file, scheduling, collaboration, and goal tool surfaces.
9
10#![recursion_limit = "256"]
11use serde_json::{Value, json};
12
13mod collaboration;
14mod goal;
15mod json_schema;
16mod matrix;
17#[cfg(feature = "mcp")]
18mod mcp_tool;
19mod responses_api;
20mod tool_kind;
21
22pub use collaboration::{
23    AGENT_DESCRIPTION, ANSWER_SESSION_DESCRIPTION, ASK_SESSION_DESCRIPTION, LIST_SESSIONS_DESCRIPTION,
24    SUBAGENT_REASONING_EFFORT_VALUES, agent_parameters, answer_session_parameters, ask_session_parameters,
25    close_agent_parameters, list_sessions_parameters, request_user_input_description, request_user_input_parameters,
26    resume_agent_parameters, send_input_parameters, spawn_agent_parameters, spawn_background_subprocess_parameters,
27    wait_agent_parameters,
28};
29pub use goal::{get_goal_description, get_goal_parameters, update_goal_description, update_goal_parameters};
30pub use json_schema::{AdditionalProperties, JsonSchema, parse_tool_input_schema};
31pub use matrix::{MATRIX_DESCRIPTION, matrix_parameters, report_outcome};
32#[cfg(feature = "mcp")]
33pub use mcp_tool::{
34    MCP_UI_EXTENSION_ID, MCP_UI_RESOURCE_MIME_TYPE, MCP_UI_RESOURCE_SCHEME, McpToolVisibility, McpUiResourceMeta,
35    McpUiToolMeta, ParsedMcpTool, parse_mcp_tool, parse_ui_resource_meta,
36};
37pub use responses_api::{FreeformTool, FreeformToolFormat, ResponsesApiTool};
38pub(crate) use tool_kind::{CanonicalToolMeta, TokenBucket, ToolKind, ToolNamespace};
39
40pub const SEMANTIC_ANCHOR_GUIDANCE: &str =
41    "Prefer stable semantic @@ anchors such as function, class, method, or impl names.";
42
43/// Model-visible description of the `patch` alias field. The old value
44/// ("Alias for input") gave the model no format guidance, so it often placed
45/// a standard unified diff (`---`/`+++`) there — which `apply_patch` rejects
46/// (checkpoint turn_615). The full envelope and path rules live on the tool
47/// description and the `input` field; this alias keeps only the
48/// turn_615-critical rejection signal plus the alias relationship, so the
49/// same guidance is not sent three times per request.
50pub const APPLY_PATCH_ALIAS_DESCRIPTION: &str = "Alias for 'input': same VT Code patch envelope (*** Begin Patch … *** End Patch); unified diffs (---/+++ format) are rejected.";
51pub const DEFAULT_APPLY_PATCH_INPUT_DESCRIPTION: &str = "Patch in VT Code format: *** Begin Patch, *** Update File: path, @@ hunk, -/+ lines, *** End Patch. Every patch path must be workspace-relative; absolute paths, `..`, and traversal-like forms are rejected.";
52/// Model-visible description of the `apply_patch` tool. It leads with the
53/// accepted envelope so the model writes the right format on the first try,
54/// and states the unified-diff rejection and path rules as plain facts
55/// instead of shouted warnings. Registration sites append
56/// [`SEMANTIC_ANCHOR_GUIDANCE`] via [`with_semantic_anchor_guidance`].
57pub const APPLY_PATCH_TOOL_DESCRIPTION: &str = "Apply a patch in VT Code format (*** Begin Patch / *** Update File: path / @@ hunks with -/+ lines / *** End Patch); standard unified diffs (---/+++ format) are rejected. Inspect relevant hunks and anchors, including docs; edit a bounded region, refresh after mismatch, then verify. Strict inspection requires retained source; warn mode is advisory. *** Add File: path, *** Delete File: path, and *** Move to: path (after *** Update File) are also supported. Every patch path must be workspace-relative; absolute paths, `..`, and traversal-like forms are rejected. Changes require permission checks. Call this tool directly instead of through a shell; JSON calls use input (patch is an alias). Use complete current context/deletion lines, preserving internal whitespace; boundary whitespace and Unicode punctuation normalization are supported, but partial lines are rejected. A typed context mismatch permits one fresh bounded file read range per affected path per turn; other limits remain authoritative.";
58
59/// Default model-visible preview budget for function-tool results.
60pub const DEFAULT_MAX_OUTPUT_TOKENS: usize = 10_000;
61
62/// Wire schema for optional public decision recording.
63pub fn record_decision_parameters() -> Value {
64    serde_json::json!({"type":"object","additionalProperties":false,"required":["summary","rationale"],"properties":{
65        "summary":{"type":"string","minLength":1,"maxLength":240},
66        "rationale":{"type":"string","minLength":1,"maxLength":1000},
67        "alternatives":{"type":"array","maxItems":3,"items":{"type":"string","maxLength":1000}},
68        "evidence_ids":{"type":"array","maxItems":8,"items":{"type":"string","minLength":1,"maxLength":240}}
69    }})
70}
71/// Smallest valid model-visible preview budget for a function-tool result.
72pub const MIN_MAX_OUTPUT_TOKENS: usize = 1;
73/// Largest valid model-visible preview budget for a function-tool result.
74pub const MAX_MAX_OUTPUT_TOKENS: usize = 50_000;
75/// Canonical JSON property name for the common result-preview budget field.
76///
77/// Centralized so the strict dedicated validator in `vtcode-core` and any
78/// compatibility coercion both reference one name and cannot drift.
79pub const MAX_OUTPUT_TOKENS_FIELD: &str = "max_output_tokens";
80
81/// Adds the common result-preview budget field to an object-shaped tool schema.
82///
83/// The returned schema deliberately preserves every existing constraint,
84/// including `additionalProperties`, so callers can use it for legacy schemas
85/// without weakening their argument validation.
86#[must_use]
87pub fn with_max_output_tokens_parameter(mut schema: Value) -> Value {
88    let Some(schema_object) = schema.as_object_mut() else {
89        return schema;
90    };
91    let properties = schema_object
92        .entry("properties")
93        .or_insert_with(|| Value::Object(serde_json::Map::new()));
94    let Some(properties_object) = properties.as_object_mut() else {
95        return schema;
96    };
97    {
98        let _entry = properties_object.entry(MAX_OUTPUT_TOKENS_FIELD).or_insert_with(|| {
99            json!({
100                "type": "integer",
101                "minimum": MIN_MAX_OUTPUT_TOKENS,
102                "maximum": MAX_MAX_OUTPUT_TOKENS,
103                "default": DEFAULT_MAX_OUTPUT_TOKENS,
104                "description": "Maximum number of result tokens returned to the model. Full oversized output is spooled when available."
105            })
106        });
107    }
108    schema
109}
110
111#[must_use]
112pub fn with_semantic_anchor_guidance(base: &str) -> String {
113    let trimmed = base.trim_end();
114    if trimmed.contains(SEMANTIC_ANCHOR_GUIDANCE) {
115        trimmed.to_string()
116    } else if trimmed.ends_with('.') {
117        format!("{trimmed} {SEMANTIC_ANCHOR_GUIDANCE}")
118    } else {
119        format!("{trimmed}. {SEMANTIC_ANCHOR_GUIDANCE}")
120    }
121}
122
123#[must_use]
124pub fn apply_patch_parameter_schema(input_description: &str) -> Value {
125    json!({
126        "type": "object",
127        "properties": {
128            "input": {
129                "type": "string",
130                "description": with_semantic_anchor_guidance(input_description)
131            },
132            "patch": {
133                "type": "string",
134                "description": with_semantic_anchor_guidance(APPLY_PATCH_ALIAS_DESCRIPTION)
135            }
136        },
137        "anyOf": [
138            {"required": ["input"]},
139            {"required": ["patch"]}
140        ]
141    })
142}
143
144#[must_use]
145pub fn apply_patch_parameters() -> Value {
146    apply_patch_parameter_schema(DEFAULT_APPLY_PATCH_INPUT_DESCRIPTION)
147}
148
149#[must_use]
150pub fn cron_parameters() -> Value {
151    json!({
152        "type": "object",
153        "required": ["action"],
154        "additionalProperties": false,
155        "properties": {
156            "action": {
157                "type": "string",
158                "enum": ["create", "list", "delete"],
159                "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."
160            },
161            "prompt": {"type": "string", "description": "create: prompt to run when the task fires."},
162            "name": {"type": "string", "description": "create: optional short label for the task."},
163            "cron": {"type": "string", "description": "create: five-field cron expression for recurring tasks."},
164            "delay_minutes": {"type": "integer", "description": "create: fixed recurring interval in minutes."},
165            "run_at": {"type": "string", "description": "create: one-shot fire time in RFC3339 or local datetime form."},
166            "id": {"type": "string", "description": "delete: session scheduled task id to delete."}
167        }
168    })
169}
170
171/// Model-visible description of the `computer_use` tool: one approved turn
172/// driving an isolated browser. Trigger-led so task-to-tool matching wins
173/// over shell workarounds at selection time; states the approval gate and
174/// the redaction contract so the model invokes it correctly and sets
175/// expectations. Prerequisites stay out on purpose: the model cannot verify
176/// them, and the fail-closed `Disabled` outcomes (`disabled`, `unsupported
177/// provider`, `no target configured`, external scope) guide the off-state
178/// instead. Turn limits and the browser target stay in configuration.
179pub const COMPUTER_USE_DESCRIPTION: &str = "Use when the user asks to see, screenshot, or operate the isolated browser preview through its UI. The turn screenshots, clicks, types, and scrolls in an isolated browser with no network access, then reports a redacted summary. Not for the open web, local servers, or desktop apps — capture pages with a headless browser and automate native apps through the shell, all via exec_command. Every turn asks for human approval before acting, and screenshots never reach the transcript.";
180
181#[must_use]
182pub fn computer_use_parameters() -> Value {
183    json!({
184        "type": "object",
185        "required": ["task"],
186        "properties": {
187            "task": {"type": "string", "description": "Plain-words task for this turn, e.g. 'open the settings page and take a screenshot'. Keep it to one screen-sized goal; the turn budget caps executed actions."}
188        },
189        "additionalProperties": false
190    })
191}
192
193/// Model-visible description of the `mcp` tool. The `action` field description
194/// owns the per-action enumeration; this description keeps only the purpose,
195/// the server-search-vs-catalog-search distinction, and the disconnect guard.
196pub const MCP_DESCRIPTION: &str = "Discover and manage Model Context Protocol capabilities. Use the `action` field to find tools, fetch one tool schema, list configured servers, and connect or disconnect by name. action=search_tools searches only tools exposed by configured MCP servers; the separate search_tools tool searches the whole session catalog, including deferred built-in tools. Do not disconnect a server while one of its tool calls is active.";
197
198#[must_use]
199pub fn mcp_parameters() -> Value {
200    json!({
201        "type": "object",
202        "required": ["action"],
203        "properties": {
204            "action": {
205                "type": "string",
206                "enum": ["search_tools", "get_tool_details", "list_servers", "connect", "disconnect"],
207                "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."
208            },
209            "query": {"type": "string", "description": "search_tools: natural language query describing the MCP capability to find."},
210            "detail_level": {"type": "string", "enum": ["name", "name_description", "full"], "description": "search_tools: response detail level."},
211            "limit": {"type": "integer", "minimum": 1, "maximum": 25, "description": "search_tools: maximum number of results to return."},
212            "name": {"type": "string", "description": "get_tool_details: exact MCP tool name. connect or disconnect: configured MCP server name."}
213        },
214        "additionalProperties": false
215    })
216}
217
218#[must_use]
219pub fn cron_create_parameters() -> Value {
220    json!({
221        "type": "object",
222        "required": ["prompt"],
223        "additionalProperties": false,
224        "properties": {
225            "prompt": {"type": "string", "description": "Prompt to run when the task fires."},
226            "name": {"type": "string", "description": "Optional short label for the task."},
227            "cron": {"type": "string", "description": "Five-field cron expression for recurring tasks."},
228            "delay_minutes": {"type": "integer", "description": "Fixed recurring interval in minutes."},
229            "run_at": {
230                "type": "string",
231                "description": "One-shot fire time in RFC3339 or local datetime form. Use this instead of `cron` or `delay_minutes` for reminders."
232            }
233        }
234    })
235}
236
237#[must_use]
238pub fn cron_list_parameters() -> Value {
239    json!({
240        "type": "object",
241        "properties": {},
242        "additionalProperties": false
243    })
244}
245
246#[must_use]
247pub fn cron_delete_parameters() -> Value {
248    json!({
249        "type": "object",
250        "required": ["id"],
251        "properties": {
252            "id": {"type": "string", "description": "Session scheduled task id to delete."}
253        }
254    })
255}
256
257/// Model-visible description of the `exec_command` tool. The escalation
258/// justification requirement is stated once, on the `justification` field.
259pub const EXEC_COMMAND_DESCRIPTION: &str = "Run a shell command through the active sandbox policy and permission checks. Put normal shell tools such as ls, rg, find, cat, sed, awk, build tools, and test tools in cmd. Returns output, exit status, and a reusable session id when the command is still running. Inspect current target source before edits, then verify the bounded change. For file edits, use apply_patch instead of shell redirection or in-place editors such as `sed -i`. Use computer_use for the isolated browser preview when available. Expanded sandbox_permissions modes trigger an approval check before the command runs.";
260
261#[must_use]
262pub fn exec_command_parameters() -> Value {
263    json!({
264        "type": "object",
265        "required": ["cmd"],
266        "properties": {
267            "cmd": {"type": "string", "description": "Shell command to execute, subject to command policy. The tool description lists covered tools."},
268            "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. Values above 10000 turn this into a single-call long run: no outer timeout applies and the response returns after the yield window or command exit, whichever is first.", "default": 10000},
269            "background": {"type": "boolean", "description": "Start a retained background process and return after a bounded initial output window. At most three live background processes are allowed per VT Code runtime; use the returned session_id with `write_stdin` for the session lifecycle.", "default": false},
270            "stdin": {"type": "boolean", "description": "Keep pipe stdin open for later write_stdin input. Defaults to false (EOF); enable only for commands that need input. PTY input is always available.", "default": false},
271            "monitor_filter": {"type": "string", "description": "Optional case-sensitive substring filter for pipe runs; rejected for tty runs. Matching output lines accumulate into a bounded monitor_digest on run/wait/poll responses so long quiet commands cost no full-output polls. At most 256 characters."},
272            "max_output_tokens": {"type": "integer", "minimum": MIN_MAX_OUTPUT_TOKENS, "maximum": MAX_MAX_OUTPUT_TOKENS, "default": DEFAULT_MAX_OUTPUT_TOKENS, "description": "Output token cap. Large or truncated output can return a spool_path; an active session may set spool_complete=false for a readable partial snapshot, while an exited pending spool is withheld until a later wait."},
273            "workdir": {"type": "string", "description": "Working directory."},
274            "tty": {"type": "boolean", "description": "Run the command in PTY mode for interactive or terminal-sensitive commands.", "default": false},
275            "sandbox_permissions": {
276                "type": "string",
277                "enum": ["use_default", "with_additional_permissions", "require_escalated", "bypass_sandbox"],
278                "description": "Sandbox permission mode for this command. Omit it or use `use_default` for the normal sandbox. Non-empty `additional_permissions` is normalized to `with_additional_permissions`. `require_escalated` and `bypass_sandbox` require a non-empty `justification` and cannot be combined with `additional_permissions`.",
279                "default": "use_default"
280            },
281            "additional_permissions": {
282                "type": "object",
283                "description": "Optional extra filesystem roots to grant inside the sandbox. Non-empty `additional_permissions` implicitly requests `with_additional_permissions`; every path is normalized and must stay within allowed workspace or temp roots.",
284                "properties": {
285                    "fs_read": {"type": "array", "items": {"type": "string"}},
286                    "fs_write": {"type": "array", "items": {"type": "string"}}
287                },
288                "additionalProperties": false
289            },
290            "justification": {"type": "string", "description": "Short approval question for expanded sandbox scope. Required when sandbox_permissions is `require_escalated` or `bypass_sandbox`."}
291        },
292        "additionalProperties": false
293    })
294}
295
296/// Shared model-facing description for execution session controls.
297pub const WRITE_STDIN_DESCRIPTION: &str = "Control an owned exec session using its exact session_id (copy verbatim from next_wait_args/next_continue_args; never guess): action=\"write\" sends stdin (pipe runs require stdin:true at launch), action=\"wait\" blocks until exit or wait_timeout_seconds (preferred over polling for long runs; never kills), action=\"poll\" returns the latest output immediately, action=\"inspect\" reads a bounded snapshot, action=\"terminate\" kills the process group, action=\"close\" releases the session.";
298
299#[must_use]
300pub fn write_stdin_parameters() -> Value {
301    json!({
302        "type": "object",
303        "required": ["session_id"],
304        "properties": {
305            "session_id": {"type": "string", "description": "Active execution session id copied verbatim from the run response."},
306            "action": {"type": "string", "enum": ["write", "poll", "wait", "inspect", "terminate", "close"], "description": "write sends chars to stdin; wait blocks until exit or wait_timeout_seconds without killing (preferred for long runs); poll returns latest output immediately and sends no input; inspect reads a bounded snapshot; terminate kills the process group and captures output; close cancels and releases the session."},
307            "chars": {"type": "string", "description": "Bytes to write to stdin; only for action=\"write\". Omit only when action is wait/poll/inspect/terminate/close; an empty string sends no input (polls)."},
308            "yield_time_ms": {"type": "integer", "description": "Wait before returning fresh session output (ms).", "default": 1000},
309            "wait_timeout_seconds": {"type": "integer", "minimum": 1, "description": "Deadline for action=\"wait\" in seconds. A deadline-expired wait returns an in-progress session; call wait again with the same session_id. Explicit wait time is excluded from the per-turn wall-clock budget."},
310            "max_output_tokens": {"type": "integer", "minimum": MIN_MAX_OUTPUT_TOKENS, "maximum": MAX_MAX_OUTPUT_TOKENS, "default": DEFAULT_MAX_OUTPUT_TOKENS, "description": "Output token cap for the continuation response. Large or truncated output can return a spool_path; the response reports whether an active session has finished writing it."}
311        },
312        "anyOf": [
313            {"required": ["chars"]},
314            {"required": ["action"], "properties": {"action": {"enum": ["poll", "wait", "inspect", "terminate", "close"]}}}
315        ],
316        "additionalProperties": false
317    })
318}
319
320/// Model-visible description of the `search_tools` tool.
321pub const SEARCH_TOOLS_DESCRIPTION: &str = "Search the session tool catalog by capability and return ranked matches. Use it to find tools whose definitions are deferred and not yet sent to you, such as code_search, web_fetch, web_search, cron, and MCP server tools. Deferred matches are listed in `expanded_for_next_segment` and become callable on the next request. It is not needed for tools already defined in the current request; call those directly.";
322
323#[must_use]
324pub fn search_tools_parameters() -> Value {
325    with_max_output_tokens_parameter(json!({
326        "type": "object",
327        "required": ["query"],
328        "properties": {
329            "query": {
330                "type": "string",
331                "minLength": 1,
332                "description": "Natural-language description of the capability to discover."
333            },
334            "limit": {
335                "type": "integer",
336                "minimum": 1,
337                "maximum": 25,
338                "default": 5,
339                "description": "Maximum number of ranked matches to return (default: 5, max: 25)."
340            },
341            "detail_level": {
342                "type": "string",
343                "enum": ["name", "name_description", "full"],
344                "default": "name_description",
345                "description": "Fields returned per match (default: name_description). name returns the tool name and score; name_description adds the description; full also adds the parameter schema."
346            }
347        },
348        "additionalProperties": false
349    }))
350}
351
352#[must_use]
353pub fn code_search_parameters() -> Value {
354    json!({
355        "type": "object",
356        "required": ["query"],
357        "additionalProperties": false,
358        "properties": {
359            "query": {
360                "type": "string",
361                "minLength": 1,
362                "pattern": "\\S",
363                "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."
364            },
365            "path": {
366                "type": "string",
367                "minLength": 1,
368                "pattern": "\\S",
369                "description": "Workspace-relative file or directory to search. Omit to search the workspace root."
370            },
371            "file_types": {
372                "type": "array",
373                "minItems": 1,
374                "items": {
375                    "type": "string",
376                    "minLength": 1,
377                    "pattern": "\\S"
378                },
379                "description": "Language names or common file extensions, with or without one leading dot."
380            },
381            "result_types": {
382                "type": "array",
383                "minItems": 1,
384                "items": {
385                    "type": "string",
386                    "enum": ["definition", "usage", "text", "path"]
387                },
388                "description": "Result categories to include. Omit to include all four categories."
389            },
390            "max_results": {
391                "type": "integer",
392                "minimum": 1,
393                "maximum": 100,
394                "description": "Maximum number of merged results to return. Omit for 20."
395            }
396        }
397    })
398}
399
400#[must_use]
401pub fn list_files_parameters() -> Value {
402    json!({
403        "type": "object",
404        "properties": {
405            "path": {"type": "string", "description": "Directory or file path to inspect.", "default": "."},
406            "mode": {
407                "type": "string",
408                "enum": ["list", "recursive", "tree", "find_name", "find_content", "largest", "file", "files"],
409                "description": "Listing mode. Use page/per_page to continue paginated results.",
410                "default": "list"
411            },
412            "pattern": {"type": "string", "description": "Optional glob-style path filter."},
413            "name_pattern": {"type": "string", "description": "Optional name filter for list/find_name modes."},
414            "content_pattern": {"type": "string", "description": "Content query for find_content mode."},
415            "page": {"type": "integer", "description": "1-indexed results page.", "minimum": 1},
416            "per_page": {"type": "integer", "description": "Items per page.", "minimum": 1},
417            "max_results": {"type": "integer", "description": "Maximum total results to consider before pagination.", "minimum": 1},
418            "include_hidden": {"type": "boolean", "description": "Include dotfiles and hidden entries.", "default": false},
419            "response_format": {"type": "string", "enum": ["concise", "detailed"], "description": "Verbosity of the listing output.", "default": "concise"},
420            "case_sensitive": {"type": "boolean", "description": "Case-sensitive name matching.", "default": false}
421        }
422    })
423}
424
425#[cfg(test)]
426mod tests {
427    use serde_json::json;
428
429    use super::*;
430
431    #[test]
432    fn apply_patch_parameter_schema_keeps_alias_and_guidance_consistent() {
433        let schema = apply_patch_parameter_schema("Patch in VT Code format");
434
435        // Both `input` and `patch` alias fields now carry the format
436        // description AND the semantic-anchor guidance, preventing the model
437        // from placing a unified diff in `patch` (see checkpoint turn_615).
438        assert_eq!(
439            schema["properties"]["patch"]["description"],
440            with_semantic_anchor_guidance(APPLY_PATCH_ALIAS_DESCRIPTION)
441        );
442        let patch_description = schema["properties"]["patch"]["description"]
443            .as_str()
444            .expect("patch description");
445        assert!(patch_description.contains("*** Begin Patch"));
446        assert!(patch_description.contains("unified diff"));
447        assert!(patch_description.contains(SEMANTIC_ANCHOR_GUIDANCE));
448
449        let input_description = schema["properties"]["input"]["description"]
450            .as_str()
451            .expect("input description");
452        assert!(input_description.contains(SEMANTIC_ANCHOR_GUIDANCE));
453    }
454
455    #[test]
456    fn computer_use_schema_requires_task_and_states_the_contract() {
457        let schema = computer_use_parameters();
458        assert_eq!(schema["type"], json!("object"));
459        assert_eq!(schema["required"], json!(["task"]));
460        assert_eq!(schema["additionalProperties"], json!(false));
461        let task = schema["properties"]["task"].as_object().expect("task property");
462        assert_eq!(task["type"], json!("string"));
463        assert!(
464            task["description"].as_str().is_some_and(|text| text.contains("Plain-words")),
465            "task description must steer phrasing"
466        );
467        // Prerequisites (master switch, browser target, computer-use model)
468        // stay out of the description on purpose: the model cannot verify
469        // them, unverifiable preconditions route around the tool, and the
470        // fail-closed `Disabled` outcomes guide the off-state instead.
471        for absent in ["master switch", "browser target", "Needs the"] {
472            assert!(
473                !COMPUTER_USE_DESCRIPTION.contains(absent),
474                "description must not state unverifiable prerequisite {absent}"
475            );
476        }
477        for needle in [
478            "human approval",
479            "never reach the transcript",
480            "screenshot",
481            "isolated browser preview",
482            "no network access",
483            "capture pages with a headless browser",
484            "automate native apps through the shell",
485        ] {
486            assert!(COMPUTER_USE_DESCRIPTION.contains(needle), "description must state {needle}");
487        }
488    }
489
490    #[test]
491    fn search_tools_schema_documents_limit_and_detail_level_defaults() {
492        let schema = search_tools_parameters();
493        let limit = &schema["properties"]["limit"];
494        assert_eq!(limit["default"], json!(5));
495        assert_eq!(limit["maximum"], json!(25));
496        let limit_description = limit["description"].as_str().expect("limit description");
497        assert!(limit_description.contains("default: 5"));
498        assert!(limit_description.contains("max: 25"));
499
500        let detail_level = &schema["properties"]["detail_level"];
501        assert_eq!(detail_level["default"], json!("name_description"));
502        let detail_description = detail_level["description"].as_str().expect("detail_level description");
503        for level in ["name", "name_description", "full"] {
504            assert!(detail_description.contains(level), "{level}");
505        }
506
507        assert!(SEARCH_TOOLS_DESCRIPTION.contains("deferred"));
508        assert!(SEARCH_TOOLS_DESCRIPTION.contains("next request"));
509        assert!(SEARCH_TOOLS_DESCRIPTION.contains("MCP"));
510        assert!(SEARCH_TOOLS_DESCRIPTION.contains("not needed"));
511    }
512
513    #[test]
514    fn apply_patch_tool_description_leads_with_format_and_stays_calm() {
515        assert!(APPLY_PATCH_TOOL_DESCRIPTION.starts_with("Apply a patch in VT Code format (*** Begin Patch"));
516        assert!(APPLY_PATCH_TOOL_DESCRIPTION.contains("unified diffs"));
517        assert!(APPLY_PATCH_TOOL_DESCRIPTION.contains("workspace-relative"));
518        assert!(APPLY_PATCH_TOOL_DESCRIPTION.contains("permission checks"));
519        assert!(APPLY_PATCH_TOOL_DESCRIPTION.contains("JSON calls use input (patch is an alias)"));
520        assert!(APPLY_PATCH_TOOL_DESCRIPTION.contains("preserving internal whitespace"));
521        assert!(APPLY_PATCH_TOOL_DESCRIPTION.contains("one fresh bounded file read range"));
522        for description in [
523            APPLY_PATCH_TOOL_DESCRIPTION,
524            APPLY_PATCH_ALIAS_DESCRIPTION,
525            DEFAULT_APPLY_PATCH_INPUT_DESCRIPTION,
526        ] {
527            assert!(!description.contains("IMPORTANT"), "{description}");
528            assert!(!description.contains("NOT"), "{description}");
529            assert!(!description.contains("never"), "{description}");
530        }
531    }
532
533    #[test]
534    fn common_output_limit_parameter_preserves_strict_schema() {
535        let schema = with_max_output_tokens_parameter(json!({
536            "type": "object",
537            "properties": {"query": {"type": "string"}},
538            "additionalProperties": false
539        }));
540        assert_eq!(schema["additionalProperties"], json!(false));
541        assert_eq!(schema["properties"]["max_output_tokens"]["default"], json!(DEFAULT_MAX_OUTPUT_TOKENS));
542        assert_eq!(schema["properties"]["max_output_tokens"]["minimum"], json!(MIN_MAX_OUTPUT_TOKENS));
543        assert_eq!(schema["properties"]["max_output_tokens"]["maximum"], json!(MAX_MAX_OUTPUT_TOKENS));
544    }
545
546    #[test]
547    fn codex_baseline_exec_schemas_use_public_names_shape() {
548        let exec_params = exec_command_parameters();
549        assert_eq!(exec_params["required"], json!(["cmd"]));
550        assert!(exec_params["properties"]["cmd"].is_object());
551        assert!(exec_params["properties"]["workdir"].is_object());
552        assert!(
553            exec_params["properties"]["yield_time_ms"]["description"]
554                .as_str()
555                .expect("exec yield description")
556                .contains("session_id")
557        );
558        assert!(
559            exec_params["properties"]["yield_time_ms"]["description"]
560                .as_str()
561                .expect("exec yield description")
562                .contains("single-call long run")
563        );
564        assert!(
565            exec_params["properties"]["max_output_tokens"]["description"]
566                .as_str()
567                .expect("exec max output description")
568                .contains("spool_path")
569        );
570        assert_eq!(exec_params["properties"]["tty"]["type"], "boolean");
571        assert_eq!(exec_params["properties"]["tty"]["default"], false);
572        assert_eq!(exec_params["properties"]["background"]["type"], "boolean");
573        assert_eq!(exec_params["properties"]["background"]["default"], false);
574        assert_eq!(exec_params["properties"]["monitor_filter"]["type"], "string");
575        assert!(
576            exec_params["properties"]["monitor_filter"]["description"]
577                .as_str()
578                .expect("monitor_filter description")
579                .contains("monitor_digest")
580        );
581        assert_eq!(exec_params["properties"]["yield_time_ms"]["default"], 10000);
582        assert_eq!(
583            exec_params["properties"]["sandbox_permissions"]["enum"],
584            json!([
585                "use_default",
586                "with_additional_permissions",
587                "require_escalated",
588                "bypass_sandbox"
589            ])
590        );
591        assert_eq!(exec_params["properties"]["sandbox_permissions"]["default"], "use_default");
592        assert_eq!(
593            exec_params["properties"]["additional_permissions"]["properties"]["fs_read"]["items"]["type"],
594            "string"
595        );
596        assert_eq!(
597            exec_params["properties"]["additional_permissions"]["properties"]["fs_write"]["items"]["type"],
598            "string"
599        );
600        assert_eq!(exec_params["properties"]["additional_permissions"]["additionalProperties"], false);
601        assert_eq!(exec_params["properties"]["justification"]["type"], "string");
602        assert!(
603            exec_params["properties"]["sandbox_permissions"]["description"]
604                .as_str()
605                .expect("sandbox_permissions description")
606                .contains("normalized to `with_additional_permissions`")
607        );
608        assert!(
609            exec_params["properties"]["additional_permissions"]["description"]
610                .as_str()
611                .expect("additional_permissions description")
612                .contains("allowed workspace or temp roots")
613        );
614        assert!(
615            exec_params["properties"]["justification"]["description"]
616                .as_str()
617                .expect("justification description")
618                .contains("Required when sandbox_permissions is `require_escalated` or `bypass_sandbox`")
619        );
620        assert_eq!(exec_params["additionalProperties"], false);
621        // Example commands live once, in EXEC_COMMAND_DESCRIPTION; the `cmd`
622        // property defers to it instead of repeating the list on every
623        // request.
624        assert!(
625            exec_params["properties"]["cmd"]["description"]
626                .as_str()
627                .expect("cmd description")
628                .contains("tool description lists covered tools"),
629            "cmd description must defer the example list to the tool description"
630        );
631        for command in ["ls", "rg", "find", "cat", "sed", "awk"] {
632            assert!(
633                EXEC_COMMAND_DESCRIPTION.contains(command),
634                "{command} should be described as an exec_command example"
635            );
636            assert!(
637                exec_params["properties"].get(command).is_none(),
638                "{command} must not be modelled as a separate exec_command field"
639            );
640        }
641
642        let stdin_params = write_stdin_parameters();
643        assert_eq!(stdin_params["required"], json!(["session_id"]));
644        assert!(stdin_params["properties"]["session_id"].is_object());
645        assert_eq!(stdin_params["properties"]["chars"]["type"], "string");
646        assert_eq!(
647            stdin_params["properties"]["action"]["enum"],
648            json!(["write", "poll", "wait", "inspect", "terminate", "close"])
649        );
650        assert_eq!(exec_params["properties"]["stdin"]["default"], false);
651        assert!(stdin_params["properties"]["wait_timeout_seconds"].is_object());
652        assert!(
653            stdin_params["properties"].get("timeout_seconds").is_none(),
654            "write_stdin schema advertises only wait_timeout_seconds"
655        );
656        assert_eq!(stdin_params["anyOf"][1]["required"], json!(["action"]));
657        assert_eq!(
658            stdin_params["anyOf"][1]["properties"]["action"]["enum"],
659            json!(["poll", "wait", "inspect", "terminate", "close"])
660        );
661        assert!(
662            stdin_params["properties"]["chars"]["description"]
663                .as_str()
664                .is_some_and(|description| description.contains("empty string"))
665        );
666        assert!(stdin_params["properties"]["chars"].is_object());
667        assert!(
668            stdin_params["properties"]["yield_time_ms"]["description"]
669                .as_str()
670                .expect("stdin yield description")
671                .contains("fresh session output")
672        );
673        assert!(
674            stdin_params["properties"]["max_output_tokens"]["description"]
675                .as_str()
676                .expect("stdin max output description")
677                .contains("spool_path")
678        );
679        assert_eq!(stdin_params["additionalProperties"], false);
680    }
681
682    #[test]
683    fn mcp_description_distinguishes_server_search_from_catalog_search() {
684        assert!(MCP_DESCRIPTION.starts_with("Discover and manage Model Context Protocol capabilities."));
685        assert!(MCP_DESCRIPTION.contains("action=search_tools searches only tools exposed by configured MCP servers"));
686        assert!(MCP_DESCRIPTION.contains("the separate search_tools tool searches the whole session catalog"));
687    }
688
689    #[test]
690    fn agent_description_routes_shell_processes_to_exec_command() {
691        assert!(AGENT_DESCRIPTION.starts_with("Spawn and steer delegated child agents."));
692        assert!(AGENT_DESCRIPTION.contains("spawn_subprocess runs a subagent defined with background: true"));
693        assert!(AGENT_DESCRIPTION.contains("go through exec_command, with background=true"));
694        let action = agent_parameters()["properties"]["action"]["description"]
695            .as_str()
696            .unwrap_or_default()
697            .to_string();
698        assert!(!action.contains("daemons"), "{action}");
699    }
700
701    #[test]
702    fn exec_command_description_states_edit_routing_and_escalation_rules() {
703        assert!(EXEC_COMMAND_DESCRIPTION.starts_with("Run a shell command through the active sandbox policy"));
704        assert!(EXEC_COMMAND_DESCRIPTION.contains("For file edits, use apply_patch"));
705        assert!(EXEC_COMMAND_DESCRIPTION.contains("Use computer_use for the isolated browser preview when available"));
706        assert!(EXEC_COMMAND_DESCRIPTION.contains("approval check"));
707        // The justification requirement is stated once, on the `justification`
708        // field description; the tool description keeps only the approval-check
709        // routing rule instead of repeating the requirement on every request.
710        assert!(
711            !EXEC_COMMAND_DESCRIPTION.contains("non-empty justification"),
712            "justification requirement belongs to the field description"
713        );
714        for mode in ["require_escalated", "bypass_sandbox"] {
715            assert!(
716                exec_command_parameters()["properties"]["sandbox_permissions"]["enum"]
717                    .as_array()
718                    .expect("sandbox_permissions enum")
719                    .iter()
720                    .any(|value| value == mode),
721                "{mode} must stay a real sandbox_permissions value"
722            );
723        }
724    }
725
726    #[test]
727    fn code_search_schema_exposes_exact_five_property_contract() {
728        let params = code_search_parameters();
729        let properties = params["properties"].as_object().expect("properties");
730        let mut property_names = properties.keys().map(String::as_str).collect::<Vec<_>>();
731        property_names.sort_unstable();
732
733        assert_eq!(params["required"], json!(["query"]));
734        assert_eq!(property_names, ["file_types", "max_results", "path", "query", "result_types"]);
735        assert_eq!(params["additionalProperties"], false);
736        assert_eq!(params["properties"]["query"]["pattern"], "\\S");
737        assert_eq!(params["properties"]["file_types"]["minItems"], 1);
738        assert_eq!(params["properties"]["result_types"]["minItems"], 1);
739        assert_eq!(
740            params["properties"]["result_types"]["items"]["enum"],
741            json!(["definition", "usage", "text", "path"])
742        );
743        assert_eq!(params["properties"]["max_results"]["minimum"], 1);
744        assert_eq!(params["properties"]["max_results"]["maximum"], 100);
745        assert!(params.get("anyOf").is_none());
746    }
747
748    #[test]
749    fn legacy_list_files_schema_exposes_pagination_fields() {
750        let list_params = list_files_parameters();
751        assert!(list_params["properties"]["page"].is_object());
752        assert!(list_params["properties"]["per_page"].is_object());
753        assert!(
754            list_params["properties"]["mode"]["enum"]
755                .as_array()
756                .expect("mode enum")
757                .iter()
758                .any(|value| value == "recursive")
759        );
760    }
761
762    #[test]
763    fn semantic_anchor_guidance_is_appended_once() {
764        let base = "Patch in VT Code format.";
765        let with_guidance = with_semantic_anchor_guidance(base);
766
767        assert!(with_guidance.contains(SEMANTIC_ANCHOR_GUIDANCE));
768        assert_eq!(with_semantic_anchor_guidance(&with_guidance), with_guidance);
769    }
770
771    #[test]
772    fn default_apply_patch_parameters_keep_expected_alias_shape() {
773        let schema = apply_patch_parameters();
774
775        assert_eq!(
776            schema["anyOf"],
777            json!([
778                {"required": ["input"]},
779                {"required": ["patch"]}
780            ])
781        );
782    }
783}