Skip to main content

nanobot/tools/
base.rs

1use async_trait::async_trait;
2use serde_json::{Map, Value, json};
3
4#[async_trait]
5pub trait Tool: Send + Sync {
6    fn name(&self) -> &str;
7    fn description(&self) -> &str;
8    fn parameters(&self) -> Value;
9
10    async fn execute(&self, params: &Map<String, Value>) -> anyhow::Result<String>;
11
12    fn validate_params(&self, params: &Map<String, Value>) -> Vec<String> {
13        let schema = self.parameters();
14        let schema_type = schema
15            .get("type")
16            .and_then(Value::as_str)
17            .unwrap_or("object");
18        if schema_type != "object" {
19            return vec![format!("schema for {} must be object type", self.name())];
20        }
21        validate_value(&Value::Object(params.clone()), &schema, "", "parameter")
22    }
23
24    fn to_schema(&self) -> Value {
25        json!({
26            "type": "function",
27            "function": {
28                "name": self.name(),
29                "description": self.description(),
30                "parameters": self.parameters(),
31            }
32        })
33    }
34}
35
36fn validate_value(value: &Value, schema: &Value, path: &str, fallback_label: &str) -> Vec<String> {
37    let schema_type = schema
38        .get("type")
39        .and_then(Value::as_str)
40        .unwrap_or("object");
41    let label = if path.is_empty() {
42        fallback_label
43    } else {
44        path
45    };
46    let mut errors = Vec::new();
47
48    match schema_type {
49        "string" => {
50            if let Some(s) = value.as_str() {
51                if let Some(min_len) = schema.get("minLength").and_then(Value::as_u64) {
52                    if s.len() < min_len as usize {
53                        errors.push(format!("{label} must be at least {min_len} chars"));
54                    }
55                }
56                if let Some(max_len) = schema.get("maxLength").and_then(Value::as_u64) {
57                    if s.len() > max_len as usize {
58                        errors.push(format!("{label} must be at most {max_len} chars"));
59                    }
60                }
61            } else {
62                errors.push(format!("{label} should be string"));
63                return errors;
64            }
65        }
66        "integer" => {
67            if let Some(num) = value.as_i64() {
68                if let Some(min) = schema.get("minimum").and_then(Value::as_i64) {
69                    if num < min {
70                        errors.push(format!("{label} must be >= {min}"));
71                    }
72                }
73                if let Some(max) = schema.get("maximum").and_then(Value::as_i64) {
74                    if num > max {
75                        errors.push(format!("{label} must be <= {max}"));
76                    }
77                }
78            } else {
79                errors.push(format!("{label} should be integer"));
80                return errors;
81            }
82        }
83        "number" => {
84            if let Some(num) = value.as_f64() {
85                if let Some(min) = schema.get("minimum").and_then(Value::as_f64) {
86                    if num < min {
87                        errors.push(format!("{label} must be >= {min}"));
88                    }
89                }
90                if let Some(max) = schema.get("maximum").and_then(Value::as_f64) {
91                    if num > max {
92                        errors.push(format!("{label} must be <= {max}"));
93                    }
94                }
95            } else {
96                errors.push(format!("{label} should be number"));
97                return errors;
98            }
99        }
100        "boolean" => {
101            if !value.is_boolean() {
102                errors.push(format!("{label} should be boolean"));
103                return errors;
104            }
105        }
106        "array" => {
107            if let Some(arr) = value.as_array() {
108                if let Some(item_schema) = schema.get("items") {
109                    for (idx, item) in arr.iter().enumerate() {
110                        let child_path = if path.is_empty() {
111                            format!("[{idx}]")
112                        } else {
113                            format!("{path}[{idx}]")
114                        };
115                        errors.extend(validate_value(
116                            item,
117                            item_schema,
118                            &child_path,
119                            fallback_label,
120                        ));
121                    }
122                }
123            } else {
124                errors.push(format!("{label} should be array"));
125                return errors;
126            }
127        }
128        "object" => {
129            if let Some(obj) = value.as_object() {
130                let props = schema
131                    .get("properties")
132                    .and_then(Value::as_object)
133                    .cloned()
134                    .unwrap_or_default();
135                if let Some(required) = schema.get("required").and_then(Value::as_array) {
136                    for required_key in required.iter().filter_map(Value::as_str) {
137                        if !obj.contains_key(required_key) {
138                            if path.is_empty() {
139                                errors.push(format!("missing required {required_key}"));
140                            } else {
141                                errors.push(format!("missing required {path}.{required_key}"));
142                            }
143                        }
144                    }
145                }
146                for (key, item) in obj {
147                    if let Some(prop_schema) = props.get(key) {
148                        let child_path = if path.is_empty() {
149                            key.to_string()
150                        } else {
151                            format!("{path}.{key}")
152                        };
153                        errors.extend(validate_value(
154                            item,
155                            prop_schema,
156                            &child_path,
157                            fallback_label,
158                        ));
159                    }
160                }
161            } else {
162                errors.push(format!("{label} should be object"));
163                return errors;
164            }
165        }
166        _ => {}
167    }
168
169    if let Some(enums) = schema.get("enum").and_then(Value::as_array) {
170        if !enums.iter().any(|candidate| candidate == value) {
171            errors.push(format!(
172                "{label} must be one of {}",
173                Value::Array(enums.clone())
174            ));
175        }
176    }
177
178    errors
179}
180
181#[cfg(test)]
182mod tests {
183    use super::*;
184    use crate::tools::registry::ToolRegistry;
185
186    struct SampleTool;
187
188    #[async_trait]
189    impl Tool for SampleTool {
190        fn name(&self) -> &str {
191            "sample"
192        }
193
194        fn description(&self) -> &str {
195            "sample tool"
196        }
197
198        fn parameters(&self) -> Value {
199            json!({
200                "type": "object",
201                "properties": {
202                    "query": { "type": "string", "minLength": 2 },
203                    "count": { "type": "integer", "minimum": 1, "maximum": 10 },
204                    "mode": { "type": "string", "enum": ["fast", "full"] },
205                    "meta": {
206                        "type": "object",
207                        "properties": {
208                            "tag": { "type": "string" },
209                            "flags": {
210                                "type": "array",
211                                "items": { "type": "string" }
212                            }
213                        },
214                        "required": ["tag"]
215                    }
216                },
217                "required": ["query", "count"]
218            })
219        }
220
221        async fn execute(&self, _params: &Map<String, Value>) -> anyhow::Result<String> {
222            Ok("ok".to_string())
223        }
224    }
225
226    #[test]
227    fn validate_missing_required() {
228        let tool = SampleTool;
229        let params = json!({ "query": "hi" })
230            .as_object()
231            .cloned()
232            .unwrap_or_default();
233        let errors = tool.validate_params(&params).join("; ");
234        assert!(errors.contains("missing required count"));
235    }
236
237    #[test]
238    fn validate_type_and_range() {
239        let tool = SampleTool;
240        let params = json!({ "query": "hi", "count": 0 })
241            .as_object()
242            .cloned()
243            .unwrap_or_default();
244        let errors = tool.validate_params(&params);
245        assert!(errors.iter().any(|e| e.contains("count must be >= 1")));
246
247        let params = json!({ "query": "hi", "count": "2" })
248            .as_object()
249            .cloned()
250            .unwrap_or_default();
251        let errors = tool.validate_params(&params);
252        assert!(errors.iter().any(|e| e.contains("count should be integer")));
253    }
254
255    #[test]
256    fn validate_enum_and_min_length() {
257        let tool = SampleTool;
258        let params = json!({ "query": "h", "count": 2, "mode": "slow" })
259            .as_object()
260            .cloned()
261            .unwrap_or_default();
262        let errors = tool.validate_params(&params);
263        assert!(
264            errors
265                .iter()
266                .any(|e| e.contains("query must be at least 2 chars"))
267        );
268        assert!(errors.iter().any(|e| e.contains("mode must be one of")));
269    }
270
271    #[test]
272    fn validate_nested_object_and_array() {
273        let tool = SampleTool;
274        let params = json!({
275            "query": "hi",
276            "count": 2,
277            "meta": {
278                "flags": [1, "ok"]
279            }
280        })
281        .as_object()
282        .cloned()
283        .unwrap_or_default();
284        let errors = tool.validate_params(&params);
285        assert!(
286            errors
287                .iter()
288                .any(|e| e.contains("missing required meta.tag"))
289        );
290        assert!(
291            errors
292                .iter()
293                .any(|e| e.contains("meta.flags[0] should be string"))
294        );
295    }
296
297    #[test]
298    fn validate_ignores_unknown_fields() {
299        let tool = SampleTool;
300        let params = json!({ "query": "hi", "count": 2, "extra": "x" })
301            .as_object()
302            .cloned()
303            .unwrap_or_default();
304        let errors = tool.validate_params(&params);
305        assert!(errors.is_empty());
306    }
307
308    #[tokio::test]
309    async fn registry_returns_validation_error() {
310        let mut registry = ToolRegistry::new();
311        registry.register(std::sync::Arc::new(SampleTool));
312        let result = registry
313            .execute("sample", json!({ "query": "hi" }).as_object().unwrap())
314            .await;
315        assert!(result.contains("Invalid parameters"));
316    }
317}