bamboo-tools 2026.5.1

Tool execution and integrations for the Bamboo agent framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
//! Integration tests for Tool Registry

#[cfg(test)]
mod tests {
    use async_trait::async_trait;
    use bamboo_agent_core::{RegistryError, Tool, ToolError, ToolRegistry, ToolResult};
    use serde_json::json;

    // Test tool implementations
    struct TestTool {
        name: String,
        description: String,
        should_fail: bool,
    }

    impl TestTool {
        fn new(name: &str, description: &str) -> Self {
            Self {
                name: name.to_string(),
                description: description.to_string(),
                should_fail: false,
            }
        }

        fn with_failure(name: &str, description: &str) -> Self {
            Self {
                name: name.to_string(),
                description: description.to_string(),
                should_fail: true,
            }
        }
    }

    #[async_trait]
    impl Tool for TestTool {
        fn name(&self) -> &str {
            &self.name
        }

        fn description(&self) -> &str {
            &self.description
        }

        fn parameters_schema(&self) -> serde_json::Value {
            json!({
                "type": "object",
                "properties": {
                    "input": {
                        "type": "string",
                        "description": "Input parameter"
                    }
                },
                "required": ["input"]
            })
        }

        async fn execute(&self, args: serde_json::Value) -> Result<ToolResult, ToolError> {
            if self.should_fail {
                return Err(ToolError::Execution("Intentional failure".to_string()));
            }

            let input = args["input"].as_str().unwrap_or("default");
            Ok(ToolResult {
                success: true,
                result: format!("Processed: {}", input),
                display_preference: Some("text".to_string()),
            })
        }
    }

    // Another test tool for variety
    struct CalculatorTool;

    #[async_trait]
    impl Tool for CalculatorTool {
        fn name(&self) -> &str {
            "calculator"
        }

        fn description(&self) -> &str {
            "Performs basic arithmetic operations"
        }

        fn parameters_schema(&self) -> serde_json::Value {
            json!({
                "type": "object",
                "properties": {
                    "a": { "type": "number", "description": "First operand" },
                    "b": { "type": "number", "description": "Second operand" },
                    "operation": {
                        "type": "string",
                        "enum": ["add", "subtract", "multiply", "divide"],
                        "description": "Operation to perform"
                    }
                },
                "required": ["a", "b", "operation"]
            })
        }

        async fn execute(&self, args: serde_json::Value) -> Result<ToolResult, ToolError> {
            let a = args["a"]
                .as_f64()
                .ok_or_else(|| ToolError::InvalidArguments("Missing or invalid 'a'".to_string()))?;
            let b = args["b"]
                .as_f64()
                .ok_or_else(|| ToolError::InvalidArguments("Missing or invalid 'b'".to_string()))?;
            let op = args["operation"]
                .as_str()
                .ok_or_else(|| ToolError::InvalidArguments("Missing 'operation'".to_string()))?;

            let result = match op {
                "add" => a + b,
                "subtract" => a - b,
                "multiply" => a * b,
                "divide" => {
                    if b == 0.0 {
                        return Err(ToolError::Execution("Division by zero".to_string()));
                    }
                    a / b
                }
                _ => {
                    return Err(ToolError::InvalidArguments(format!(
                        "Unknown operation: {}",
                        op
                    )))
                }
            };

            Ok(ToolResult {
                success: true,
                result: result.to_string(),
                display_preference: None,
            })
        }
    }

    mod tool_registration {
        use super::*;

        #[tokio::test]
        async fn test_tool_registration() {
            let registry = ToolRegistry::new();
            let tool = TestTool::new("test_tool", "A test tool");

            // Test registration succeeds
            let result = registry.register(tool);
            assert!(result.is_ok(), "Tool registration should succeed");

            // Test tool is retrievable
            let retrieved = registry.get("test_tool");
            assert!(retrieved.is_some(), "Registered tool should be retrievable");
            assert_eq!(retrieved.unwrap().name(), "test_tool");
        }

        #[tokio::test]
        async fn test_duplicate_tool_registration() {
            let registry = ToolRegistry::new();
            let tool1 = TestTool::new("unique_tool", "First tool");
            let tool2 = TestTool::new("unique_tool", "Duplicate tool");

            registry.register(tool1).unwrap();

            // Duplicate registration should fail
            let result = registry.register(tool2);
            assert!(
                matches!(result, Err(RegistryError::DuplicateTool(name)) if name == "unique_tool")
            );
        }

        #[tokio::test]
        async fn test_multiple_tools_registration() {
            let registry = ToolRegistry::new();

            registry
                .register(TestTool::new("tool_a", "Tool A"))
                .unwrap();
            registry
                .register(TestTool::new("tool_b", "Tool B"))
                .unwrap();
            registry.register(CalculatorTool).unwrap();

            assert_eq!(registry.len(), 3);
            assert!(registry.contains("tool_a"));
            assert!(registry.contains("tool_b"));
            assert!(registry.contains("calculator"));
        }

        #[tokio::test]
        async fn test_tool_unregistration() {
            let registry = ToolRegistry::new();
            registry
                .register(TestTool::new("temp_tool", "Temporary"))
                .unwrap();

            assert!(registry.contains("temp_tool"));

            let removed = registry.unregister("temp_tool");
            assert!(removed, "Unregister should return true for existing tool");
            assert!(!registry.contains("temp_tool"));

            // Unregistering non-existent tool returns false
            let removed_again = registry.unregister("temp_tool");
            assert!(!removed_again);
        }

        #[tokio::test]
        async fn test_registry_clear() {
            let registry = ToolRegistry::new();
            registry.register(TestTool::new("tool1", "Tool 1")).unwrap();
            registry.register(TestTool::new("tool2", "Tool 2")).unwrap();

            assert_eq!(registry.len(), 2);

            registry.clear();

            assert_eq!(registry.len(), 0);
            assert!(registry.is_empty());
        }
    }

    mod tool_execution {
        use super::*;

        #[tokio::test]
        async fn test_tool_execution() {
            let registry = ToolRegistry::new();
            registry
                .register(TestTool::new("processor", "Data processor"))
                .unwrap();

            let tool = registry.get("processor").unwrap();
            let result = tool.execute(json!({"input": "hello"})).await;

            assert!(result.is_ok());
            let tool_result = result.unwrap();
            assert!(tool_result.success);
            assert_eq!(tool_result.result, "Processed: hello");
        }

        #[tokio::test]
        async fn test_tool_execution_failure() {
            let registry = ToolRegistry::new();
            registry
                .register(TestTool::with_failure("failing_tool", "Always fails"))
                .unwrap();

            let tool = registry.get("failing_tool").unwrap();
            let result = tool.execute(json!({})).await;

            assert!(result.is_err());
            assert!(matches!(result, Err(ToolError::Execution(_))));
        }

        #[tokio::test]
        async fn test_calculator_add() {
            let registry = ToolRegistry::new();
            registry.register(CalculatorTool).unwrap();

            let tool = registry.get("calculator").unwrap();
            let result = tool
                .execute(json!({
                    "a": 10.0,
                    "b": 5.0,
                    "operation": "add"
                }))
                .await
                .unwrap();

            assert!(result.success);
            assert_eq!(result.result, "15");
        }

        #[tokio::test]
        async fn test_calculator_divide_by_zero() {
            let registry = ToolRegistry::new();
            registry.register(CalculatorTool).unwrap();

            let tool = registry.get("calculator").unwrap();
            let result = tool
                .execute(json!({
                    "a": 10.0,
                    "b": 0.0,
                    "operation": "divide"
                }))
                .await;

            assert!(result.is_err());
        }

        #[tokio::test]
        async fn test_invalid_arguments() {
            let registry = ToolRegistry::new();
            registry.register(CalculatorTool).unwrap();

            let tool = registry.get("calculator").unwrap();
            let result = tool
                .execute(json!({
                    "a": "not a number",
                    "b": 5.0,
                    "operation": "add"
                }))
                .await;

            assert!(result.is_err());
            assert!(matches!(result, Err(ToolError::InvalidArguments(_))));
        }
    }

    mod tool_schema_generation {
        use super::*;

        #[tokio::test]
        async fn test_tool_schema_generation() {
            let registry = ToolRegistry::new();
            registry
                .register(TestTool::new("schema_test", "Schema test tool"))
                .unwrap();

            let tool = registry.get("schema_test").unwrap();
            let schema = tool.to_schema();

            assert_eq!(schema.schema_type, "function");
            assert_eq!(schema.function.name, "schema_test");
            assert_eq!(schema.function.description, "Schema test tool");
            assert!(schema.function.parameters.get("properties").is_some());
        }

        #[tokio::test]
        async fn test_list_tools() {
            let registry = ToolRegistry::new();
            registry
                .register(TestTool::new("tool1", "First tool"))
                .unwrap();
            registry
                .register(TestTool::new("tool2", "Second tool"))
                .unwrap();

            let tools = registry.list_tools();
            assert_eq!(tools.len(), 2);

            let names: Vec<String> = tools.iter().map(|s| s.function.name.clone()).collect();
            assert!(names.contains(&"tool1".to_string()));
            assert!(names.contains(&"tool2".to_string()));
        }

        #[tokio::test]
        async fn test_list_tool_names() {
            let registry = ToolRegistry::new();
            registry
                .register(TestTool::new("alpha", "Alpha tool"))
                .unwrap();
            registry
                .register(TestTool::new("beta", "Beta tool"))
                .unwrap();

            let names = registry.list_tool_names();
            assert_eq!(names.len(), 2);
            assert!(names.contains(&"alpha".to_string()));
            assert!(names.contains(&"beta".to_string()));
        }

        #[tokio::test]
        async fn test_calculator_schema() {
            let registry = ToolRegistry::new();
            registry.register(CalculatorTool).unwrap();

            let tool = registry.get("calculator").unwrap();
            let schema = tool.to_schema();

            assert_eq!(schema.function.name, "calculator");

            let params = &schema.function.parameters;
            let properties = params.get("properties").unwrap();
            assert!(properties.get("a").is_some());
            assert!(properties.get("b").is_some());
            assert!(properties.get("operation").is_some());

            let operation = properties.get("operation").unwrap();
            let enum_values = operation.get("enum").unwrap().as_array().unwrap();
            assert_eq!(enum_values.len(), 4);
        }
    }

    mod registry_edge_cases {
        use super::*;
        use bamboo_agent_core::normalize_tool_name;

        #[tokio::test]
        async fn test_empty_registry() {
            let registry = ToolRegistry::new();
            assert!(registry.is_empty());
            assert_eq!(registry.len(), 0);
            assert!(registry.get("anything").is_none());
        }

        #[tokio::test]
        async fn test_get_nonexistent_tool() {
            let registry = ToolRegistry::new();
            registry
                .register(TestTool::new("exists", "Exists"))
                .unwrap();

            assert!(registry.get("exists").is_some());
            assert!(registry.get("does_not_exist").is_none());
        }

        #[tokio::test]
        async fn test_normalize_tool_name() {
            assert_eq!(normalize_tool_name("simple_tool"), "simple_tool");
            assert_eq!(normalize_tool_name("default::tool_name"), "tool_name");
            assert_eq!(normalize_tool_name("a::b::c::tool"), "tool");
            assert_eq!(normalize_tool_name(""), "");
        }

        #[tokio::test]
        async fn test_concurrent_registration() {
            let registry = std::sync::Arc::new(ToolRegistry::new());
            let mut handles = vec![];

            for i in 0..10 {
                let reg = registry.clone();
                let handle = tokio::spawn(async move {
                    let tool = TestTool::new(&format!("concurrent_tool_{}", i), "Concurrent tool");
                    reg.register(tool)
                });
                handles.push(handle);
            }

            for handle in handles {
                handle.await.unwrap().unwrap();
            }

            assert_eq!(registry.len(), 10);
        }
    }
}