Skip to main content

erio_tools/
registry.rs

1//! Tool registry for managing and executing tools.
2
3use crate::result::ToolResult;
4use crate::tool::Tool;
5use erio_core::ToolError;
6use serde_json::Value;
7use std::collections::HashMap;
8
9/// Registry for managing tools.
10pub struct ToolRegistry {
11    tools: HashMap<String, Box<dyn Tool>>,
12}
13
14impl ToolRegistry {
15    /// Creates a new empty registry.
16    pub fn new() -> Self {
17        Self {
18            tools: HashMap::new(),
19        }
20    }
21
22    /// Registers a tool in the registry.
23    pub fn register<T: Tool + 'static>(&mut self, tool: T) {
24        let name = tool.name().to_string();
25        self.tools.insert(name, Box::new(tool));
26    }
27
28    /// Returns the number of registered tools.
29    pub fn len(&self) -> usize {
30        self.tools.len()
31    }
32
33    /// Returns `true` if the registry is empty.
34    pub fn is_empty(&self) -> bool {
35        self.tools.is_empty()
36    }
37
38    /// Gets a tool by name.
39    pub fn get(&self, name: &str) -> Option<&dyn Tool> {
40        self.tools.get(name).map(AsRef::as_ref)
41    }
42
43    /// Returns `true` if a tool with the given name exists.
44    pub fn contains(&self, name: &str) -> bool {
45        self.tools.contains_key(name)
46    }
47
48    /// Returns a list of all registered tool names.
49    pub fn list(&self) -> Vec<&str> {
50        self.tools.keys().map(String::as_str).collect()
51    }
52
53    /// Executes a tool by name with the given parameters.
54    pub async fn execute(&self, name: &str, params: Value) -> Result<ToolResult, ToolError> {
55        let tool = self
56            .get(name)
57            .ok_or_else(|| ToolError::NotFound(name.into()))?;
58        tool.execute(params).await
59    }
60}
61
62impl Default for ToolRegistry {
63    fn default() -> Self {
64        Self::new()
65    }
66}