Skip to main content

tiny_agent_rs/tools/
tool.rs

1use std::collections::HashMap;
2
3/// A tool that can be executed by the agent
4pub trait Tool: Send + Sync + std::fmt::Debug {
5    /// The name of the tool (used in function calls)
6    fn name(&self) -> &'static str;
7
8    /// A description of what the tool does
9    fn description(&self) -> &'static str;
10
11    /// JSON Schema for the tool's parameters
12    fn parameters_schema(&self) -> serde_json::Value;
13
14    /// Execute the tool with given parameters
15    fn execute(
16        &self,
17        parameters: serde_json::Value,
18    ) -> std::pin::Pin<
19        Box<
20            dyn std::future::Future<Output = Result<serde_json::Value, crate::AgentError>>
21                + Send
22                + '_,
23        >,
24    >;
25}
26
27/// Registry for available tools
28#[derive(Debug, Default)]
29pub struct ToolRegistry {
30    tools: HashMap<String, Box<dyn Tool>>,
31}
32
33impl ToolRegistry {
34    /// Create a new empty registry
35    pub fn new() -> Self {
36        Self::default()
37    }
38
39    /// Register a tool
40    pub fn register<T: Tool + 'static>(&mut self, tool: T) {
41        self.tools.insert(tool.name().to_string(), Box::new(tool));
42    }
43
44    /// Get a tool by name
45    pub fn get(&self, name: &str) -> Option<&dyn Tool> {
46        self.tools.get(name).map(|tool| tool.as_ref())
47    }
48
49    /// Get all registered tools
50    pub fn list(&self) -> Vec<&dyn Tool> {
51        self.tools.values().map(|tool| tool.as_ref()).collect()
52    }
53
54    /// Generate tool schemas for OpenAI function calling
55    pub fn to_openai_tools(&self) -> Vec<serde_json::Value> {
56        self.tools
57            .values()
58            .map(|tool| {
59                serde_json::json!({
60                    "type": "function",
61                    "function": {
62                        "name": tool.name(),
63                        "description": tool.description(),
64                        "parameters": tool.parameters_schema()
65                    }
66                })
67            })
68            .collect()
69    }
70}