Skip to main content

magic_coder_types/
tools.rs

1use serde::{Deserialize, Serialize};
2
3#[cfg(feature = "schemars")]
4use schemars::{JsonSchema, schema_for};
5#[cfg(feature = "schemars")]
6use serde_json::Value;
7
8/// Convert a Rust struct schema into an OpenAI tool `parameters` object.
9///
10/// - remove `$schema` and `title`
11/// - convert `definitions` to `$defs`
12/// - convert `oneOf` to `anyOf`
13#[cfg(feature = "schemars")]
14pub fn tool_parameters<T: JsonSchema>() -> Value {
15    let mut v = serde_json::to_value(schema_for!(T)).expect("can't parse value from schema");
16
17    // remove the $schema and title fields
18    if let Some(value) = v.as_object_mut() {
19        value.remove("$schema");
20        value.remove("title");
21    }
22
23    let mut v_str = serde_json::to_string(&v).unwrap();
24    v_str = v_str
25        .replace("/definitions/", "/$defs/")
26        .replace("\"definitions\":", "\"$defs\":");
27
28    // Replace oneOf with anyOf, because it's better supported by the LLMs
29    v_str = v_str.replace("\"oneOf\":", "\"anyOf\":");
30
31    let mut v: Value = serde_json::from_str(&v_str).expect("can't parse value from updated schema");
32    enforce_openai_strict_schema(&mut v);
33    v
34}
35
36#[cfg(feature = "schemars")]
37fn enforce_openai_strict_schema(v: &mut Value) {
38    match v {
39        Value::Object(map) => {
40            // Recurse first so we fix nested schemas too.
41            for (_k, child) in map.iter_mut() {
42                enforce_openai_strict_schema(child);
43            }
44
45            // If this looks like an object schema, enforce strict rules.
46            let is_object = map
47                .get("type")
48                .and_then(|t| t.as_str())
49                .is_some_and(|t| t == "object");
50            let has_props = map.get("properties").is_some();
51            if is_object || has_props {
52                map.entry("additionalProperties".to_string())
53                    .or_insert(Value::Bool(false));
54
55                if let Some(Value::Object(props)) = map.get("properties") {
56                    let mut keys: Vec<String> = props.keys().cloned().collect();
57                    keys.sort();
58                    map.insert(
59                        "required".to_string(),
60                        Value::Array(keys.into_iter().map(Value::String).collect()),
61                    );
62                }
63            }
64        }
65        Value::Array(arr) => {
66            for child in arr.iter_mut() {
67                enforce_openai_strict_schema(child);
68            }
69        }
70        _ => {}
71    }
72}
73
74#[derive(Debug, Clone, Serialize, Deserialize)]
75#[cfg_attr(feature = "schemars", derive(JsonSchema))]
76pub struct ReadFileArgs {
77    /// Path to file.
78    pub path: String,
79    /// Optional starting line (0-based).
80    pub offset: Option<usize>,
81    /// Optional maximum number of lines to read.
82    pub limit: Option<usize>,
83}
84
85#[derive(Debug, Clone, Serialize, Deserialize)]
86#[cfg_attr(feature = "schemars", derive(JsonSchema))]
87pub struct ListDirArgs {
88    /// Directory path to list.
89    pub path: String,
90}
91
92#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
93#[cfg_attr(feature = "schemars", derive(JsonSchema))]
94#[serde(rename_all = "snake_case")]
95pub enum GlobKind {
96    Files,
97    Dirs,
98    All,
99}
100
101#[derive(Debug, Clone, Serialize, Deserialize)]
102#[cfg_attr(feature = "schemars", derive(JsonSchema))]
103pub struct GlobArgs {
104    /// Glob pattern to match. Supports `*`, `**`, `?`, and character classes.
105    pub pattern: String,
106    /// Optional directory root to search under. Defaults to `"."`.
107    pub path: Option<String>,
108    /// Optional maximum number of returned paths. Defaults to `50`.
109    pub limit: Option<usize>,
110    /// Optional match kind. Defaults to `files`.
111    pub kind: Option<GlobKind>,
112    /// Optional exclude patterns. Defaults to an empty list.
113    #[serde(default)]
114    pub exclude: Vec<String>,
115}
116
117#[derive(Debug, Clone, Serialize, Deserialize)]
118#[cfg_attr(feature = "schemars", derive(JsonSchema))]
119pub struct GrepArgs {
120    /// Regex pattern to search for.
121    pub pattern: String,
122    /// Optional path (file or directory) to search in.
123    pub path: Option<String>,
124    /// Optional glob filter, e.g. `"*.rs"`.
125    pub glob: Option<String>,
126    /// Optional limit for returned matches.
127    pub head_limit: Option<usize>,
128}
129
130#[derive(Debug, Clone, Serialize, Deserialize)]
131#[cfg_attr(feature = "schemars", derive(JsonSchema))]
132pub struct RunShellArgs {
133    /// Shell command line to run (executed via `bash -lc`), supports pipes/redirection.
134    pub command: String,
135    /// Optional working directory (relative to project root).
136    pub cwd: Option<String>,
137    /// Optional timeout in seconds for foreground execution.
138    /// Omit to use the default 30 second timeout.
139    /// Must be omitted when `bg=true`.
140    /// For longer-running work like model training, set a larger value up front on the safe side to avoid retries.
141    pub timeout_seconds: Option<u64>,
142    /// Optional maximum captured bytes per stream (stdout/stderr) for foreground execution.
143    /// Must be omitted when `bg=true`.
144    ///
145    /// Truncated output keeps roughly the first 30% and last 70%, so very large
146    /// values are usually unnecessary; prefer a few KB or low tens of KB and only
147    /// increase if needed.
148    pub max_output_bytes: Option<u64>,
149    /// When true, spawn the shell in the background and return immediately with a shell id.
150    #[serde(default)]
151    pub bg: bool,
152}
153
154#[derive(Debug, Clone, Serialize, Deserialize)]
155#[cfg_attr(feature = "schemars", derive(JsonSchema))]
156pub struct ReadShellOutputArgs {
157    /// Background shell id returned by `run_shell` with `bg=true`.
158    pub shell_id: String,
159    /// When true, read from the start of the log. Defaults to `false` meaning read from the end.
160    #[serde(default)]
161    pub from_start: bool,
162    /// Optional 0-based line offset from the selected side. Defaults to `0`.
163    pub offset: Option<usize>,
164    /// Optional maximum number of lines to read. Defaults to `200`, max `1000`.
165    pub limit: Option<usize>,
166}
167
168#[derive(Debug, Clone, Serialize, Deserialize)]
169#[cfg_attr(feature = "schemars", derive(JsonSchema))]
170pub struct StopShellArgs {
171    /// Background shell id returned by `run_shell` with `bg=true`.
172    pub shell_id: String,
173}
174
175#[derive(Debug, Clone, Serialize, Deserialize)]
176#[cfg_attr(feature = "schemars", derive(JsonSchema))]
177pub struct SleepArgs {
178    /// Sleep duration in seconds. Clients may clamp this to a supported range.
179    pub seconds: u64,
180    /// Background shell ids to watch. Use an empty array for a plain timer.
181    /// If any watched shell exits early, the sleep may end early.
182    #[serde(default)]
183    pub shell_ids: Vec<String>,
184}
185
186#[derive(Debug, Clone, Serialize, Deserialize)]
187#[cfg_attr(feature = "schemars", derive(JsonSchema))]
188pub struct ApplyDiffArgs {
189    /// Patch text to apply to the working tree.
190    ///
191    /// Use the `apply_patch` format starting with `*** Begin Patch`.
192    pub diff: String,
193}
194
195#[derive(Debug, Clone, Serialize, Deserialize)]
196#[cfg_attr(feature = "schemars", derive(JsonSchema))]
197pub struct DeleteFilesArgs {
198    /// Paths to delete (relative to project root; no absolute paths; no `..`).
199    pub paths: Vec<String>,
200}
201
202/// Tools (function definitions) to send to the OpenAI Responses API.
203#[cfg(feature = "schemars")]
204pub fn openai_tools() -> Vec<Value> {
205    vec![
206        serde_json::json!({
207            "type": "function",
208            "name": "read_file",
209            "description": "Read a local file (by path), optionally with offset/limit. Returns a JSON string with keys: path, offset, limit, total_lines, content, numbered_content, fingerprint{hash64,len_bytes}, truncated.",
210            "strict": true,
211            "parameters": tool_parameters::<ReadFileArgs>(),
212        }),
213        serde_json::json!({
214            "type": "function",
215            "name": "list_dir",
216            "description": "List a local directory (by path). Returns a JSON string: { path, entries: [{ name, is_dir, is_file }, ...] }.",
217            "strict": true,
218            "parameters": tool_parameters::<ListDirArgs>(),
219        }),
220        serde_json::json!({
221            "type": "function",
222            "name": "glob",
223            "description": "Find local file or directory paths using a glob pattern under a search root. Use this for path discovery when you need matching paths, not file contents. Returns plain text with Returned, Total, and one relative path per line.",
224            "strict": true,
225            "parameters": tool_parameters::<GlobArgs>(),
226        }),
227        serde_json::json!({
228            "type": "function",
229            "name": "grep",
230            "description": "Search for a regex pattern in files. Returns a JSON string including matches (file, line_number, line). May be truncated to head_limit.",
231            "strict": true,
232            "parameters": tool_parameters::<GrepArgs>(),
233        }),
234        serde_json::json!({
235            "type": "function",
236            "name": "run_shell",
237            "description": "Run a shell command via `bash -lc` (supports pipes/redirection). Requires user confirmation unless the client auto-approves it. Use `max_output_bytes` intentionally for foreground runs: prefer the smallest limit that answers the question, and increase only when needed. Oversize output is cut from the middle, preserving roughly the first 30% and last 70%, so large requests are rarely necessary just to inspect the tail. Set `bg=true` to start a background shell that returns immediately with a shell id. When `bg=true`, omit `timeout_seconds` and omit `max_output_bytes`.",
238            "parameters": tool_parameters::<RunShellArgs>(),
239        }),
240        serde_json::json!({
241            "type": "function",
242            "name": "read_shell_output",
243            "description": "Read captured output from a background shell started with `run_shell(bg=true)`. Output is line-oriented. By default it reads from the end; set `from_start=true` to read from the beginning.",
244            "strict": true,
245            "parameters": tool_parameters::<ReadShellOutputArgs>(),
246        }),
247        serde_json::json!({
248            "type": "function",
249            "name": "stop_shell",
250            "description": "Stop a background shell started with `run_shell(bg=true)` and discard its retained state and logs.",
251            "strict": true,
252            "parameters": tool_parameters::<StopShellArgs>(),
253        }),
254        serde_json::json!({
255            "type": "function",
256            "name": "sleep",
257            "description": "Wait for 15 to 275 seconds. Provide `shell_ids` to return early when any watched background shell exits. Use `shell_ids: []` for a plain timer.",
258            "strict": true,
259            "parameters": tool_parameters::<SleepArgs>(),
260        }),
261        serde_json::json!({
262            "type": "function",
263            "name": "apply_diff",
264            "description": "Apply a patch to the local working tree (create/update files). Use the `*** Begin Patch` / `*** Update File:` format. Returns a JSON string describing what changed or an error.",
265            "strict": true,
266            "parameters": tool_parameters::<ApplyDiffArgs>(),
267        }),
268        serde_json::json!({
269            "type": "function",
270            "name": "delete_files",
271            "description": "Delete one or more files by path (relative to project root). Returns a JSON string listing deleted and missing paths.",
272            "strict": true,
273            "parameters": tool_parameters::<DeleteFilesArgs>(),
274        }),
275    ]
276}
277
278#[cfg(test)]
279mod tests {
280    use super::*;
281    use serde_json::json;
282
283    #[test]
284    fn glob_args_default_exclude_to_empty_list() {
285        let args: GlobArgs = serde_json::from_value(json!({
286            "pattern": "**/*.rs",
287            "path": "src",
288            "limit": 50,
289            "kind": "files",
290        }))
291        .expect("glob args");
292
293        assert_eq!(args.pattern, "**/*.rs");
294        assert_eq!(args.path.as_deref(), Some("src"));
295        assert_eq!(args.limit, Some(50));
296        assert_eq!(args.kind, Some(GlobKind::Files));
297        assert!(args.exclude.is_empty());
298    }
299
300    #[cfg(feature = "schemars")]
301    #[test]
302    fn run_shell_tool_schema_encourages_small_output_limits() {
303        let run_shell = openai_tools()
304            .into_iter()
305            .find(|tool| tool.get("name").and_then(Value::as_str) == Some("run_shell"))
306            .expect("run_shell tool");
307
308        let description = run_shell
309            .get("description")
310            .and_then(Value::as_str)
311            .expect("run_shell description");
312        assert!(description.contains("max_output_bytes"));
313        assert!(description.contains("30%"));
314        assert!(description.contains("70%"));
315        assert!(description.contains("smallest limit"));
316        assert!(description.contains("bg=true"));
317        assert!(description.contains("omit `timeout_seconds`"));
318        assert!(description.contains("omit `max_output_bytes`"));
319
320        let timeout_description = run_shell
321            .get("parameters")
322            .and_then(|value| value.get("properties"))
323            .and_then(|value| value.get("timeout_seconds"))
324            .and_then(|value| value.get("description"))
325            .and_then(Value::as_str)
326            .expect("timeout_seconds description");
327        assert!(timeout_description.contains("30 second timeout"));
328        assert!(timeout_description.contains("model training"));
329        assert!(timeout_description.contains("safe side"));
330        assert!(timeout_description.contains("Must be omitted when `bg=true`"));
331
332        let max_output_description = run_shell
333            .get("parameters")
334            .and_then(|value| value.get("properties"))
335            .and_then(|value| value.get("max_output_bytes"))
336            .and_then(|value| value.get("description"))
337            .and_then(Value::as_str)
338            .expect("max_output_bytes description");
339        assert!(max_output_description.contains("30%"));
340        assert!(max_output_description.contains("70%"));
341        assert!(max_output_description.contains("few KB"));
342        assert!(max_output_description.contains("Must be omitted when `bg=true`"));
343
344        let properties = run_shell
345            .get("parameters")
346            .and_then(|value| value.get("properties"))
347            .and_then(Value::as_object)
348            .expect("run_shell parameters");
349        assert!(properties.contains_key("bg"));
350    }
351
352    #[cfg(feature = "schemars")]
353    #[test]
354    fn openai_tools_include_glob_tool() {
355        let glob_tool = openai_tools()
356            .into_iter()
357            .find(|tool| tool.get("name").and_then(Value::as_str) == Some("glob"))
358            .expect("glob tool");
359
360        let description = glob_tool
361            .get("description")
362            .and_then(Value::as_str)
363            .expect("glob description");
364        assert!(description.contains("path discovery"));
365        assert!(description.contains("Returned"));
366        assert!(description.contains("Total"));
367
368        let properties = glob_tool
369            .get("parameters")
370            .and_then(|value| value.get("properties"))
371            .and_then(Value::as_object)
372            .expect("glob parameters");
373        assert!(properties.contains_key("pattern"));
374        assert!(properties.contains_key("path"));
375        assert!(properties.contains_key("limit"));
376        assert!(properties.contains_key("kind"));
377        assert!(properties.contains_key("exclude"));
378    }
379
380    #[test]
381    fn background_shell_tool_args_default_to_tail_reads() {
382        let read_shell_output: ReadShellOutputArgs = serde_json::from_value(json!({
383            "shell_id": "bg_123"
384        }))
385        .expect("read_shell_output args");
386        assert_eq!(read_shell_output.shell_id, "bg_123");
387        assert!(!read_shell_output.from_start);
388        assert_eq!(read_shell_output.offset, None);
389        assert_eq!(read_shell_output.limit, None);
390
391        let run_shell: RunShellArgs = serde_json::from_value(json!({
392            "command": "echo hi"
393        }))
394        .expect("run_shell args");
395        assert_eq!(run_shell.command, "echo hi");
396        assert!(!run_shell.bg);
397
398        let sleep: SleepArgs = serde_json::from_value(json!({
399            "seconds": 30,
400            "shell_ids": ["bg_123", "bg_456"]
401        }))
402        .expect("sleep args");
403        assert_eq!(sleep.seconds, 30);
404        assert_eq!(sleep.shell_ids, vec!["bg_123", "bg_456"]);
405
406        let timer_only_sleep: SleepArgs = serde_json::from_value(json!({
407            "seconds": 15
408        }))
409        .expect("timer-only sleep args");
410        assert_eq!(timer_only_sleep.seconds, 15);
411        assert!(timer_only_sleep.shell_ids.is_empty());
412    }
413
414    #[cfg(feature = "schemars")]
415    #[test]
416    fn openai_tools_include_background_shell_tools() {
417        let tools = openai_tools();
418        let names = tools
419            .iter()
420            .filter_map(|tool| tool.get("name").and_then(Value::as_str))
421            .collect::<Vec<_>>();
422
423        assert!(names.contains(&"read_shell_output"));
424        assert!(names.contains(&"stop_shell"));
425        assert!(names.contains(&"sleep"));
426    }
427}