Skip to main content

agent_runtime/tool/
registry.rs

1//! In-memory registration, schema validation, and execution of tool implementations.
2
3use super::{RegisteredTool, Tool, ToolDispatcher, ToolError};
4use crate::{ToolContext, ToolDefinition};
5use agent_config::{ConfigError, read_toml};
6use async_trait::async_trait;
7use serde_json::Value;
8use std::{collections::BTreeMap, path::Path, sync::Arc};
9
10/// In-memory registry of executable tools.
11#[derive(Default)]
12pub struct ToolRegistry {
13    tools: BTreeMap<String, RegisteredTool>,
14}
15
16impl ToolRegistry {
17    pub fn new() -> Self {
18        Self::default()
19    }
20
21    /// Load a tool definition from TOML and register it with its implementation.
22    ///
23    /// This is the standard registration path for tool integration crates: the
24    /// definition is parsed, its JSON Schema is compiled, and the implementation
25    /// is bound to the definition in one operation.
26    pub fn register_from_file(
27        &mut self,
28        definition_path: impl AsRef<Path>,
29        implementation: impl Tool + 'static,
30    ) -> Result<(), ConfigError> {
31        let definition_path = definition_path.as_ref();
32        let definition = read_toml(definition_path)?;
33        self.register_definition(definition, implementation, Some(definition_path))
34    }
35
36    /// Register an already constructed definition.
37    ///
38    /// This is useful for programmatic tools and tests. Integration crates
39    /// should normally use `register_from_file` so metadata loading follows
40    /// the same convention everywhere.
41    pub fn register(
42        &mut self,
43        definition: ToolDefinition,
44        implementation: impl Tool + 'static,
45    ) -> Result<(), ConfigError> {
46        self.register_definition(definition, implementation, None)
47    }
48
49    fn register_definition(
50        &mut self,
51        definition: ToolDefinition,
52        implementation: impl Tool + 'static,
53        source_path: Option<&Path>,
54    ) -> Result<(), ConfigError> {
55        if self.tools.contains_key(&definition.name) {
56            return Err(ConfigError::duplicate(
57                "tool",
58                &definition.name,
59                source_path.map(Path::to_path_buf),
60            ));
61        }
62
63        let validator = jsonschema::validator_for(&definition.parameters).map_err(|error| {
64            ConfigError::invalid(
65                "tool",
66                source_path.map(Path::to_path_buf),
67                format!("invalid schema for '{}': {error}", definition.name),
68            )
69        })?;
70
71        self.tools.insert(
72            definition.name.clone(),
73            RegisteredTool {
74                definition,
75                implementation: Arc::new(implementation),
76                validator,
77            },
78        );
79
80        Ok(())
81    }
82
83    /// Returns whether an executable implementation is registered for the given name.
84    pub fn contains(&self, name: &str) -> bool {
85        self.tools.contains_key(name)
86    }
87
88    pub fn definition(&self, name: &str) -> Option<ToolDefinition> {
89        self.tools.get(name).map(|tool| tool.definition.clone())
90    }
91
92    /// Returns the definitions of all registered tools.
93    pub fn definitions(&self) -> Vec<ToolDefinition> {
94        self.tools
95            .values()
96            .map(|tool| tool.definition.clone())
97            .collect()
98    }
99}
100
101#[async_trait]
102impl ToolDispatcher for ToolRegistry {
103    fn definition(&self, name: &str) -> Option<ToolDefinition> {
104        self.definition(name)
105    }
106
107    async fn execute(
108        &self,
109        context: &ToolContext,
110        name: &str,
111        arguments: Value,
112    ) -> Result<String, ToolError> {
113        let tool = self
114            .tools
115            .get(name)
116            .ok_or_else(|| ToolError::UnknownTool(name.into()))?;
117
118        // Validate the arguments coming from the model, it is not a trusted source!
119        let errors = tool
120            .validator
121            .iter_errors(&arguments)
122            .map(|error| error.to_string())
123            .collect::<Vec<_>>();
124
125        if !errors.is_empty() {
126            return Err(ToolError::InvalidArguments {
127                tool_name: name.to_owned(),
128                errors,
129            });
130        }
131
132        tool.implementation.execute(context, arguments).await
133    }
134}
135
136#[cfg(test)]
137mod registration_tests {
138    use std::{fs, path::PathBuf};
139
140    use super::*;
141
142    struct TestDirectory(PathBuf);
143
144    impl TestDirectory {
145        fn new() -> Self {
146            let path = std::env::temp_dir()
147                .join(format!("tool-registration-test-{}", uuid::Uuid::new_v4()));
148            fs::create_dir_all(&path).unwrap();
149            Self(path)
150        }
151
152        fn file(&self, name: &str) -> PathBuf {
153            self.0.join(name)
154        }
155    }
156
157    impl Drop for TestDirectory {
158        fn drop(&mut self) {
159            let _ = fs::remove_dir_all(&self.0);
160        }
161    }
162
163    struct NoopTool;
164
165    #[async_trait]
166    impl Tool for NoopTool {
167        async fn execute(
168            &self,
169            _context: &ToolContext,
170            _arguments: Value,
171        ) -> Result<String, ToolError> {
172            Ok(String::new())
173        }
174    }
175
176    struct ContextTool(std::sync::Arc<std::sync::Mutex<Option<(Option<String>, Option<String>)>>>);
177
178    #[async_trait]
179    impl Tool for ContextTool {
180        async fn execute(
181            &self,
182            context: &ToolContext,
183            _arguments: Value,
184        ) -> Result<String, ToolError> {
185            *self.0.lock().unwrap() = Some((
186                context.user_id.clone(),
187                context
188                    .family
189                    .as_ref()
190                    .map(|family| family.family_id.clone()),
191            ));
192            Ok("context received".into())
193        }
194    }
195
196    #[tokio::test]
197    async fn dispatches_authenticated_context_to_tool_implementation() {
198        let captured_context = std::sync::Arc::new(std::sync::Mutex::new(None));
199        let mut registry = ToolRegistry::new();
200        registry
201            .register(
202                ToolDefinition {
203                    name: "context".into(),
204                    description: "Reads trusted context".into(),
205                    parameters: serde_json::json!({"type": "object"}),
206                },
207                ContextTool(captured_context.clone()),
208            )
209            .unwrap();
210
211        let context = ToolContext {
212            user_id: Some("user-42".into()),
213            family: Some(crate::FamilyContext {
214                family_id: "trusted-family".into(),
215                family_name: "Home".into(),
216                family_role: "owner".into(),
217                relationship: "father".into(),
218                members: Vec::new(),
219            }),
220            ..ToolContext::default()
221        };
222        let output = registry
223            .execute(
224                &context,
225                "context",
226                serde_json::json!({"family_id": "model-forged-family"}),
227            )
228            .await
229            .unwrap();
230
231        assert_eq!(output, "context received");
232        assert_eq!(
233            captured_context.lock().unwrap().as_ref(),
234            Some(&(Some("user-42".into()), Some("trusted-family".into())))
235        );
236
237        registry
238            .execute(&ToolContext::default(), "context", serde_json::json!({}))
239            .await
240            .unwrap();
241        assert_eq!(
242            captured_context.lock().unwrap().as_ref(),
243            Some(&(None, None))
244        );
245    }
246
247    #[test]
248    fn loads_definition_and_registers_implementation_from_file() {
249        let directory = TestDirectory::new();
250        let path = directory.file("example.toml");
251        fs::write(
252            &path,
253            r#"
254name = "example"
255description = "An example tool"
256
257[parameters]
258type = "object"
259additionalProperties = false
260"#,
261        )
262        .unwrap();
263
264        let mut registry = ToolRegistry::new();
265        registry.register_from_file(&path, NoopTool).unwrap();
266
267        assert!(registry.contains("example"));
268        assert_eq!(
269            registry.definition("example").unwrap().description,
270            "An example tool"
271        );
272    }
273
274    #[test]
275    fn schema_errors_keep_the_definition_path() {
276        let directory = TestDirectory::new();
277        let path = directory.file("invalid-schema.toml");
278        fs::write(
279            &path,
280            r#"
281name = "invalid"
282description = "Invalid schema"
283
284[parameters]
285type = "not-a-json-schema-type"
286"#,
287        )
288        .unwrap();
289
290        let mut registry = ToolRegistry::new();
291        let error = registry.register_from_file(&path, NoopTool).unwrap_err();
292
293        assert!(matches!(
294            error,
295            ConfigError::Invalid { path: Some(error_path), .. } if error_path == path
296        ));
297    }
298
299    #[test]
300    fn duplicate_file_registration_reports_the_second_definition_path() {
301        let directory = TestDirectory::new();
302        let first = directory.file("first.toml");
303        let second = directory.file("second.toml");
304        let definition = r#"
305name = "duplicate"
306description = "Duplicate tool"
307
308[parameters]
309type = "object"
310"#;
311        fs::write(&first, definition).unwrap();
312        fs::write(&second, definition).unwrap();
313
314        let mut registry = ToolRegistry::new();
315        registry.register_from_file(&first, NoopTool).unwrap();
316        let error = registry.register_from_file(&second, NoopTool).unwrap_err();
317
318        assert!(matches!(
319            error,
320            ConfigError::Duplicate { path: Some(error_path), .. } if error_path == second
321        ));
322    }
323}