Skip to main content

magic_coder_types/
tools.rs

1use serde::{Deserialize, Serialize};
2use uuid::Uuid;
3
4#[cfg(feature = "schemars")]
5use schemars::{JsonSchema, schema_for};
6#[cfg(feature = "schemars")]
7use serde_json::Value;
8
9/// Convert a Rust struct schema into an OpenAI tool `parameters` object.
10///
11/// - remove `$schema` and `title`
12/// - convert `definitions` to `$defs`
13/// - convert `oneOf` to `anyOf`
14#[cfg(feature = "schemars")]
15pub fn tool_parameters<T: JsonSchema>() -> Value {
16    let mut v = serde_json::to_value(schema_for!(T)).expect("can't parse value from schema");
17
18    // remove the $schema and title fields
19    if let Some(value) = v.as_object_mut() {
20        value.remove("$schema");
21        value.remove("title");
22    }
23
24    let mut v_str = serde_json::to_string(&v).unwrap();
25    v_str = v_str
26        .replace("/definitions/", "/$defs/")
27        .replace("\"definitions\":", "\"$defs\":");
28
29    // Replace oneOf with anyOf, because it's better supported by the LLMs
30    v_str = v_str.replace("\"oneOf\":", "\"anyOf\":");
31
32    let mut v: Value = serde_json::from_str(&v_str).expect("can't parse value from updated schema");
33    enforce_openai_strict_schema(&mut v);
34    v
35}
36
37#[cfg(feature = "schemars")]
38fn enforce_openai_strict_schema(v: &mut Value) {
39    match v {
40        Value::Object(map) => {
41            // Recurse first so we fix nested schemas too.
42            for (_k, child) in map.iter_mut() {
43                enforce_openai_strict_schema(child);
44            }
45
46            // If this looks like an object schema, enforce strict rules.
47            let is_object = map
48                .get("type")
49                .and_then(|t| t.as_str())
50                .is_some_and(|t| t == "object");
51            let has_props = map.get("properties").is_some();
52            if is_object || has_props {
53                map.entry("additionalProperties".to_string())
54                    .or_insert(Value::Bool(false));
55
56                if let Some(Value::Object(props)) = map.get("properties") {
57                    let mut keys: Vec<String> = props.keys().cloned().collect();
58                    keys.sort();
59                    map.insert(
60                        "required".to_string(),
61                        Value::Array(keys.into_iter().map(Value::String).collect()),
62                    );
63                }
64            }
65        }
66        Value::Array(arr) => {
67            for child in arr.iter_mut() {
68                enforce_openai_strict_schema(child);
69            }
70        }
71        _ => {}
72    }
73}
74
75#[derive(Debug, Clone, Serialize, Deserialize)]
76#[cfg_attr(feature = "schemars", derive(JsonSchema))]
77pub struct ReadFileArgs {
78    /// Path to file.
79    pub path: String,
80    /// Optional starting line (0-based).
81    pub offset: Option<usize>,
82    /// Optional maximum number of lines to read.
83    pub limit: Option<usize>,
84}
85
86#[derive(Debug, Clone, Serialize, Deserialize)]
87#[cfg_attr(feature = "schemars", derive(JsonSchema))]
88pub struct ListDirArgs {
89    /// Directory path to list.
90    pub path: String,
91}
92
93#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
94#[cfg_attr(feature = "schemars", derive(JsonSchema))]
95#[serde(rename_all = "snake_case")]
96pub enum GlobKind {
97    Files,
98    Dirs,
99    All,
100}
101
102#[derive(Debug, Clone, Serialize, Deserialize)]
103#[cfg_attr(feature = "schemars", derive(JsonSchema))]
104pub struct GlobArgs {
105    /// Glob pattern to match. Supports `*`, `**`, `?`, and character classes.
106    pub pattern: String,
107    /// Optional directory root to search under. Defaults to `"."`.
108    pub path: Option<String>,
109    /// Optional maximum number of returned paths. Defaults to `50`.
110    pub limit: Option<usize>,
111    /// Optional match kind. Defaults to `files`.
112    pub kind: Option<GlobKind>,
113    /// Optional exclude patterns. Defaults to an empty list.
114    #[serde(default)]
115    pub exclude: Vec<String>,
116}
117
118#[derive(Debug, Clone, Serialize, Deserialize)]
119#[cfg_attr(feature = "schemars", derive(JsonSchema))]
120pub struct GrepArgs {
121    /// Regex pattern to search for.
122    pub pattern: String,
123    /// Optional path (file or directory) to search in.
124    pub path: Option<String>,
125    /// Optional glob filter, e.g. `"*.rs"`.
126    pub glob: Option<String>,
127    /// Optional limit for returned matches.
128    pub head_limit: Option<usize>,
129}
130
131#[derive(Debug, Clone, Serialize, Deserialize)]
132#[cfg_attr(feature = "schemars", derive(JsonSchema))]
133pub struct RunShellArgs {
134    /// Shell command line to run (executed via `bash -lc`), supports pipes/redirection.
135    pub command: String,
136    /// Optional working directory.
137    pub cwd: Option<String>,
138    /// Optional timeout in seconds for foreground execution.
139    /// Omit to use the default 30 second timeout.
140    /// Must be omitted when `bg=true`.
141    /// For longer-running work like model training, set a larger value up front on the safe side to avoid retries.
142    pub timeout_seconds: Option<u64>,
143    /// Optional maximum captured bytes per stream (stdout/stderr) for foreground execution.
144    /// Must be omitted when `bg=true`.
145    ///
146    /// Truncated output keeps roughly the first 30% and last 70%, so very large
147    /// values are usually unnecessary; prefer a few KB or low tens of KB and only
148    /// increase if needed.
149    pub max_output_bytes: Option<u64>,
150    /// When true, spawn the shell in the background and return immediately with a shell id.
151    #[serde(default)]
152    pub bg: bool,
153}
154
155#[derive(Debug, Clone, Serialize, Deserialize)]
156#[cfg_attr(feature = "schemars", derive(JsonSchema))]
157pub struct ReadShellOutputArgs {
158    /// Background shell id returned by `run_shell` with `bg=true`.
159    pub shell_id: String,
160    /// When true, read from the start of the log. Defaults to `false` meaning read from the end.
161    #[serde(default)]
162    pub from_start: bool,
163    /// Optional 0-based line offset from the selected side. Defaults to `0`.
164    pub offset: Option<usize>,
165    /// Optional maximum number of lines to read. Defaults to `200`, max `1000`.
166    pub limit: Option<usize>,
167}
168
169#[derive(Debug, Clone, Serialize, Deserialize)]
170#[cfg_attr(feature = "schemars", derive(JsonSchema))]
171pub struct StopShellArgs {
172    /// Background shell id returned by `run_shell` with `bg=true`.
173    pub shell_id: String,
174}
175
176#[derive(Debug, Clone, Serialize, Deserialize)]
177#[cfg_attr(feature = "schemars", derive(JsonSchema))]
178pub struct SleepArgs {
179    /// Sleep duration in seconds. Clients may clamp this to a supported range.
180    pub seconds: u64,
181    /// Background shell ids to watch. Use an empty array for a plain timer.
182    /// If any watched shell exits early, the sleep may end early.
183    #[serde(default)]
184    pub shell_ids: Vec<String>,
185}
186
187#[derive(Debug, Clone, Serialize, Deserialize)]
188#[cfg_attr(feature = "schemars", derive(JsonSchema))]
189pub struct ApplyDiffArgs {
190    /// Patch text to apply to the working tree.
191    ///
192    /// Use the unified diff starting with `diff --git ...`
193    pub diff: String,
194
195    /// Optional working directory.
196    pub cwd: Option<String>,
197}
198
199#[derive(Debug, Clone, Serialize, Deserialize)]
200#[cfg_attr(feature = "schemars", derive(JsonSchema))]
201pub struct DeleteFilesArgs {
202    /// Paths to delete (relative to project root; no absolute paths; no `..`).
203    pub paths: Vec<String>,
204}
205
206#[derive(Debug, Clone, Serialize, Deserialize)]
207#[cfg_attr(feature = "schemars", derive(JsonSchema))]
208pub struct CallMcpToolArgs {
209    /// Connected local MCP server UUID.
210    pub server_id: Uuid,
211    /// Name of the tool to call on the selected MCP server.
212    pub tool_name: String,
213    /// Arguments object matching the selected MCP tool's advertised input schema.
214    #[serde(default)]
215    pub arguments: serde_json::Map<String, serde_json::Value>,
216}
217
218/// Tools (function definitions) to send to the OpenAI Responses API.
219#[cfg(feature = "schemars")]
220pub fn openai_tools() -> Vec<Value> {
221    vec![
222        serde_json::json!({
223            "type": "function",
224            "name": "read_file",
225            "description": "Read a local file (by path), optionally with offset/limit. Returns plain text with a frontmatter block containing `path`, `offset`, `limit`, `total_lines`, `truncated`, and `returned_lines`, followed by the requested line-numbered file contents.",
226            "strict": true,
227            "parameters": tool_parameters::<ReadFileArgs>(),
228        }),
229        serde_json::json!({
230            "type": "function",
231            "name": "list_dir",
232            "description": "List a local directory (by path). Returns plain text with `Path`, `Entries`, and one entry per line similar to `ls`; directories end with `/`.",
233            "strict": true,
234            "parameters": tool_parameters::<ListDirArgs>(),
235        }),
236        serde_json::json!({
237            "type": "function",
238            "name": "glob",
239            "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.",
240            "strict": true,
241            "parameters": tool_parameters::<GlobArgs>(),
242        }),
243        serde_json::json!({
244            "type": "function",
245            "name": "grep",
246            "description": "Search for a regex pattern in files. Returns a JSON string including matches (file, line_number, line). May be truncated to head_limit.",
247            "strict": true,
248            "parameters": tool_parameters::<GrepArgs>(),
249        }),
250        serde_json::json!({
251            "type": "function",
252            "name": "run_shell",
253            "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`.",
254            "parameters": tool_parameters::<RunShellArgs>(),
255        }),
256        serde_json::json!({
257            "type": "function",
258            "name": "read_shell_output",
259            "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.",
260            "strict": true,
261            "parameters": tool_parameters::<ReadShellOutputArgs>(),
262        }),
263        serde_json::json!({
264            "type": "function",
265            "name": "stop_shell",
266            "description": "Stop a background shell started with `run_shell(bg=true)` and discard its retained state and logs.",
267            "strict": true,
268            "parameters": tool_parameters::<StopShellArgs>(),
269        }),
270        serde_json::json!({
271            "type": "function",
272            "name": "sleep",
273            "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.",
274            "strict": true,
275            "parameters": tool_parameters::<SleepArgs>(),
276        }),
277        serde_json::json!({
278            "type": "function",
279            "name": "apply_diff",
280            "description": "Apply a patch to the local working tree (create/update files). Use either the `*** Begin Patch` / `*** Update File:` format or a git-style unified diff starting with `diff --git`. Returns a JSON string describing what changed or an error.",
281            "strict": true,
282            "parameters": tool_parameters::<ApplyDiffArgs>(),
283        }),
284        serde_json::json!({
285            "type": "function",
286            "name": "delete_files",
287            "description": "Delete one or more files by path (relative to project root). Returns a JSON string listing deleted and missing paths.",
288            "strict": true,
289            "parameters": tool_parameters::<DeleteFilesArgs>(),
290        }),
291        serde_json::json!({
292            "type": "function",
293            "name": "call_mcp_tool",
294            "description": "Call one tool from a connected local MCP server by `server_id` and `tool_name`. The `arguments` field must be a JSON object matching that tool's advertised input schema.",
295            "parameters": tool_parameters::<CallMcpToolArgs>(),
296        }),
297    ]
298}
299
300#[cfg(test)]
301mod tests {
302    use super::*;
303    use serde_json::json;
304
305    #[test]
306    fn glob_args_default_exclude_to_empty_list() {
307        let args: GlobArgs = serde_json::from_value(json!({
308            "pattern": "**/*.rs",
309            "path": "src",
310            "limit": 50,
311            "kind": "files",
312        }))
313        .expect("glob args");
314
315        assert_eq!(args.pattern, "**/*.rs");
316        assert_eq!(args.path.as_deref(), Some("src"));
317        assert_eq!(args.limit, Some(50));
318        assert_eq!(args.kind, Some(GlobKind::Files));
319        assert!(args.exclude.is_empty());
320    }
321
322    #[cfg(feature = "schemars")]
323    #[test]
324    fn run_shell_tool_schema_encourages_small_output_limits() {
325        let run_shell = openai_tools()
326            .into_iter()
327            .find(|tool| tool.get("name").and_then(Value::as_str) == Some("run_shell"))
328            .expect("run_shell tool");
329
330        let description = run_shell
331            .get("description")
332            .and_then(Value::as_str)
333            .expect("run_shell description");
334        assert!(description.contains("max_output_bytes"));
335        assert!(description.contains("30%"));
336        assert!(description.contains("70%"));
337        assert!(description.contains("smallest limit"));
338        assert!(description.contains("bg=true"));
339        assert!(description.contains("omit `timeout_seconds`"));
340        assert!(description.contains("omit `max_output_bytes`"));
341
342        let timeout_description = run_shell
343            .get("parameters")
344            .and_then(|value| value.get("properties"))
345            .and_then(|value| value.get("timeout_seconds"))
346            .and_then(|value| value.get("description"))
347            .and_then(Value::as_str)
348            .expect("timeout_seconds description");
349        assert!(timeout_description.contains("30 second timeout"));
350        assert!(timeout_description.contains("model training"));
351        assert!(timeout_description.contains("safe side"));
352        assert!(timeout_description.contains("Must be omitted when `bg=true`"));
353
354        let max_output_description = run_shell
355            .get("parameters")
356            .and_then(|value| value.get("properties"))
357            .and_then(|value| value.get("max_output_bytes"))
358            .and_then(|value| value.get("description"))
359            .and_then(Value::as_str)
360            .expect("max_output_bytes description");
361        assert!(max_output_description.contains("30%"));
362        assert!(max_output_description.contains("70%"));
363        assert!(max_output_description.contains("few KB"));
364        assert!(max_output_description.contains("Must be omitted when `bg=true`"));
365
366        let properties = run_shell
367            .get("parameters")
368            .and_then(|value| value.get("properties"))
369            .and_then(Value::as_object)
370            .expect("run_shell parameters");
371        assert!(properties.contains_key("bg"));
372    }
373
374    #[cfg(feature = "schemars")]
375    #[test]
376    fn openai_tools_include_glob_tool() {
377        let glob_tool = openai_tools()
378            .into_iter()
379            .find(|tool| tool.get("name").and_then(Value::as_str) == Some("glob"))
380            .expect("glob tool");
381
382        let description = glob_tool
383            .get("description")
384            .and_then(Value::as_str)
385            .expect("glob description");
386        assert!(description.contains("path discovery"));
387        assert!(description.contains("Returned"));
388        assert!(description.contains("Total"));
389
390        let properties = glob_tool
391            .get("parameters")
392            .and_then(|value| value.get("properties"))
393            .and_then(Value::as_object)
394            .expect("glob parameters");
395        assert!(properties.contains_key("pattern"));
396        assert!(properties.contains_key("path"));
397        assert!(properties.contains_key("limit"));
398        assert!(properties.contains_key("kind"));
399        assert!(properties.contains_key("exclude"));
400    }
401
402    #[cfg(feature = "schemars")]
403    #[test]
404    fn openai_tools_describe_plaintext_file_and_directory_reads() {
405        let tools = openai_tools();
406
407        let read_file = tools
408            .iter()
409            .find(|tool| tool.get("name").and_then(Value::as_str) == Some("read_file"))
410            .expect("read_file tool");
411        let read_file_description = read_file
412            .get("description")
413            .and_then(Value::as_str)
414            .expect("read_file description");
415        assert!(read_file_description.contains("Returns plain text"));
416        assert!(read_file_description.contains("frontmatter"));
417        assert!(read_file_description.contains("returned_lines"));
418        assert!(read_file_description.contains("line-numbered"));
419
420        let list_dir = tools
421            .iter()
422            .find(|tool| tool.get("name").and_then(Value::as_str) == Some("list_dir"))
423            .expect("list_dir tool");
424        let list_dir_description = list_dir
425            .get("description")
426            .and_then(Value::as_str)
427            .expect("list_dir description");
428        assert!(list_dir_description.contains("Returns plain text"));
429        assert!(list_dir_description.contains("Path"));
430        assert!(list_dir_description.contains("Entries"));
431        assert!(list_dir_description.contains("similar to `ls`"));
432        assert!(list_dir_description.contains("directories end with `/`"));
433    }
434
435    #[cfg(feature = "schemars")]
436    #[test]
437    fn openai_tools_describe_apply_diff_formats() {
438        let apply_diff = openai_tools()
439            .into_iter()
440            .find(|tool| tool.get("name").and_then(Value::as_str) == Some("apply_diff"))
441            .expect("apply_diff tool");
442
443        let description = apply_diff
444            .get("description")
445            .and_then(Value::as_str)
446            .expect("apply_diff description");
447
448        assert!(description.contains("*** Begin Patch"));
449        assert!(description.contains("*** Update File:"));
450        assert!(description.contains("diff --git"));
451    }
452
453    #[test]
454    fn background_shell_tool_args_default_to_tail_reads() {
455        let read_shell_output: ReadShellOutputArgs = serde_json::from_value(json!({
456            "shell_id": "bg_123"
457        }))
458        .expect("read_shell_output args");
459        assert_eq!(read_shell_output.shell_id, "bg_123");
460        assert!(!read_shell_output.from_start);
461        assert_eq!(read_shell_output.offset, None);
462        assert_eq!(read_shell_output.limit, None);
463
464        let run_shell: RunShellArgs = serde_json::from_value(json!({
465            "command": "echo hi"
466        }))
467        .expect("run_shell args");
468        assert_eq!(run_shell.command, "echo hi");
469        assert!(!run_shell.bg);
470
471        let sleep: SleepArgs = serde_json::from_value(json!({
472            "seconds": 30,
473            "shell_ids": ["bg_123", "bg_456"]
474        }))
475        .expect("sleep args");
476        assert_eq!(sleep.seconds, 30);
477        assert_eq!(sleep.shell_ids, vec!["bg_123", "bg_456"]);
478
479        let timer_only_sleep: SleepArgs = serde_json::from_value(json!({
480            "seconds": 15
481        }))
482        .expect("timer-only sleep args");
483        assert_eq!(timer_only_sleep.seconds, 15);
484        assert!(timer_only_sleep.shell_ids.is_empty());
485    }
486
487    #[cfg(feature = "schemars")]
488    #[test]
489    fn openai_tools_include_background_shell_tools() {
490        let tools = openai_tools();
491        let names = tools
492            .iter()
493            .filter_map(|tool| tool.get("name").and_then(Value::as_str))
494            .collect::<Vec<_>>();
495
496        assert!(names.contains(&"read_shell_output"));
497        assert!(names.contains(&"stop_shell"));
498        assert!(names.contains(&"sleep"));
499    }
500
501    #[test]
502    fn call_mcp_tool_args_default_arguments_to_empty_object() {
503        let args: CallMcpToolArgs = serde_json::from_value(json!({
504            "server_id": "00000000-0000-0000-0000-000000000000",
505            "tool_name": "create_page"
506        }))
507        .expect("call_mcp_tool args");
508
509        assert_eq!(args.server_id, Uuid::nil());
510        assert_eq!(args.tool_name, "create_page");
511        assert!(args.arguments.is_empty());
512    }
513
514    #[cfg(feature = "schemars")]
515    #[test]
516    fn openai_tools_include_call_mcp_tool() {
517        let tool = openai_tools()
518            .into_iter()
519            .find(|tool| tool.get("name").and_then(Value::as_str) == Some("call_mcp_tool"))
520            .expect("call_mcp_tool");
521
522        let description = tool
523            .get("description")
524            .and_then(Value::as_str)
525            .expect("call_mcp_tool description");
526        assert!(description.contains("connected local MCP server"));
527        assert!(description.contains("server_id"));
528        assert!(description.contains("tool_name"));
529
530        let properties = tool
531            .get("parameters")
532            .and_then(|value| value.get("properties"))
533            .and_then(Value::as_object)
534            .expect("call_mcp_tool parameters");
535        assert!(properties.contains_key("server_id"));
536        assert!(properties.contains_key("tool_name"));
537        assert!(properties.contains_key("arguments"));
538        assert_eq!(
539            properties["arguments"].get("additionalProperties"),
540            Some(&Value::Bool(true))
541        );
542        assert!(tool.get("strict").is_none());
543    }
544}