Skip to main content

tinyharness_lib/tools/
tool.rs

1use std::collections::HashMap;
2use std::future::Future;
3use std::pin::Pin;
4
5use schemars::Schema;
6
7/// Extract required string arguments from the tool arguments map.
8///
9/// Creates `let` bindings for each named argument, with early return on missing args.
10///
11/// # Example
12/// ```ignore
13/// extract_args!(args, path, content);
14/// // expands to:
15/// // let path = match require_arg(&args, "path") { Ok(v) => v, Err(e) => return e };
16/// // let content = match require_arg(&args, "content") { Ok(v) => v, Err(e) => return e };
17/// ```
18#[macro_export]
19macro_rules! extract_args {
20    ($args:expr, $($name:ident),* $(,)?) => {
21        $(
22            let $name = match $crate::tools::tool::require_arg(&$args, stringify!($name)) {
23                Ok(v) => v,
24                Err(e) => return e,
25            };
26        )*
27    };
28}
29
30pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
31
32/// Classifies a tool by its side effects, used to determine whether the tool
33/// requires user approval before execution.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum ToolCategory {
36    /// Safe to execute automatically — reads data without side effects
37    /// (ls, read, grep, glob).
38    ReadOnly,
39    /// Modifies the filesystem or executes commands — needs user approval
40    /// (write, edit, run).
41    Destructive,
42    /// Returns a signal that the caller must interpret; not meant to be
43    /// executed as a normal tool (switch_mode, question, auto_compact).
44    Signal,
45}
46
47pub struct Tool {
48    pub name: String,
49    pub description: String,
50    pub parameters: Schema,
51    pub category: ToolCategory,
52    pub handler: Box<dyn Fn(HashMap<String, String>) -> BoxFuture<'static, String> + Send + Sync>,
53}
54
55impl Tool {
56    /// Convert this tool into a `ToolDefinition` for the provider.
57    pub fn to_definition(&self) -> crate::provider::ToolDefinition {
58        crate::provider::ToolDefinition {
59            name: self.name.clone(),
60            description: self.description.clone(),
61            parameters: self.parameters.clone(),
62        }
63    }
64}
65
66pub async fn execute_tool_call(tool: &Tool, arguments: &serde_json::Value) -> String {
67    let args: HashMap<String, String> = arguments
68        .as_object()
69        .map(|obj| {
70            obj.iter()
71                .map(|(k, v)| {
72                    // Use to_string() instead of as_str() so JSON numbers (e.g. "timeout": 60000)
73                    // are correctly converted to "60000" rather than silently becoming "".
74                    let val = match v {
75                        serde_json::Value::String(s) => s.clone(),
76                        other => other.to_string(),
77                    };
78                    (k.clone(), val)
79                })
80                .collect()
81        })
82        .unwrap_or_default();
83
84    (tool.handler)(args).await
85}
86
87/// Extract a required string argument from the tool arguments map.
88/// Returns an error message if the key is missing.
89pub fn require_arg(args: &HashMap<String, String>, name: &str) -> Result<String, String> {
90    args.get(name)
91        .cloned()
92        .ok_or_else(|| format!("Error: '{}' argument is required", name))
93}
94
95/// Extract an optional string argument from the tool arguments map.
96/// Returns `None` if the key is missing.
97pub fn optional_arg<'a>(args: &'a HashMap<String, String>, name: &str) -> Option<&'a String> {
98    args.get(name)
99}
100
101/// Build a JSON Schema for a tool that accepts string parameters.
102/// `required_params`: list of (name, description) pairs for required parameters.
103/// `optional_params`: list of (name, description, default_value) for optional parameters.
104pub fn build_string_params_schema(
105    required_params: &[(&str, &str)],
106    optional_params: &[(&str, &str, &str)],
107) -> Schema {
108    let mut properties = serde_json::Map::new();
109    let mut required = Vec::new();
110
111    for (name, description) in required_params {
112        properties.insert(
113            name.to_string(),
114            serde_json::json!({
115                "type": "string",
116                "description": description
117            }),
118        );
119        required.push(name.to_string());
120    }
121
122    for (name, description, _default_val) in optional_params {
123        properties.insert(
124            name.to_string(),
125            serde_json::json!({
126                "type": "string",
127                "description": description
128            }),
129        );
130    }
131
132    let schema_value = serde_json::json!({
133        "type": "object",
134        "properties": properties,
135        "required": required,
136        "additionalProperties": false
137    });
138
139    serde_json::from_value(schema_value).unwrap()
140}
141
142/// Convenience constructor for creating a `Tool` with a string-parameters schema.
143pub fn make_tool(
144    name: &str,
145    description: &str,
146    category: ToolCategory,
147    parameters: Schema,
148    handler: impl Fn(HashMap<String, String>) -> BoxFuture<'static, String> + Send + Sync + 'static,
149) -> Tool {
150    Tool {
151        name: name.to_string(),
152        description: description.to_string(),
153        parameters,
154        category,
155        handler: Box::new(handler),
156    }
157}