Skip to main content

strands/tools/
registry.rs

1//! The tool registry.
2
3use std::fmt;
4use std::sync::Arc;
5
6use indexmap::IndexMap;
7
8use super::source::ToolSource;
9use super::tool::{Tool, is_valid_tool_name};
10use crate::error::{ToolNotFoundError, ToolValidationError};
11use crate::types::ToolSpec;
12
13type Result<T, E = crate::error::Error> = std::result::Result<T, E>;
14
15const MAX_TOOL_NAME_LENGTH: usize = 64;
16
17/// The tools an agent can call, by name (`ToolRegistry`).
18///
19/// Names are unique, and two names that differ only by `-` versus `_` count as the same name.
20/// Cloning is cheap: the tools are shared.
21#[derive(Clone, Default)]
22pub struct ToolRegistry {
23    tools: IndexMap<String, Arc<dyn Tool>>,
24    sort_tool_specs: bool,
25}
26
27impl ToolRegistry {
28    /// Creates an empty registry.
29    pub fn new() -> Self {
30        Self::default()
31    }
32
33    /// Creates a registry holding `tools`.
34    ///
35    /// # Errors
36    ///
37    /// As [`ToolRegistry::add`].
38    pub fn with_tools(tools: impl Into<ToolSource>) -> Result<Self> {
39        let mut registry = Self::new();
40        registry.add(tools)?;
41        Ok(registry)
42    }
43
44    /// Registers one tool or a list of tools (`add`). Tools before a failing one stay registered.
45    ///
46    /// # Errors
47    ///
48    /// [`ToolValidationError`] when a name or description is invalid, the name is already
49    /// registered (also under a `-`/`_` variant), or `tools` holds an MCP client.
50    pub fn add(&mut self, tools: impl Into<ToolSource>) -> Result<()> {
51        for tool in tools.into().into_registry_tools()? {
52            validate_new_tool(tool.as_ref(), &self.tools)?;
53            self.tools.insert(tool.name().to_owned(), tool);
54        }
55        Ok(())
56    }
57
58    /// Swaps one source's tools for its new list in a single step, keeping the source's
59    /// position. Each new tool is checked against the registry without `current` and against the
60    /// new tools before it; a tool that fails the check is skipped, so another source's tool with
61    /// the same name stays registered.
62    ///
63    /// A tool in `current` that is not the one registered under its name is left alone. The new
64    /// tools take the place of the first removed one; when none was removed they go before
65    /// `insert_before` if it is registered, else at the end. Returns the tools of `next` that
66    /// were skipped, each with the reason.
67    #[cfg_attr(
68        not(feature = "mcp"),
69        allow(dead_code, reason = "only MCP tool refreshes swap tools")
70    )]
71    pub(crate) fn swap(
72        &mut self,
73        current: &[Arc<dyn Tool>],
74        next: Vec<Arc<dyn Tool>>,
75        insert_before: Option<&Arc<dyn Tool>>,
76    ) -> Vec<(Arc<dyn Tool>, ToolValidationError)> {
77        let mut remaining = self.tools.clone();
78        let mut insert_at = None;
79        for tool in current {
80            if let Some(index) = registered_index(&remaining, tool) {
81                remaining.shift_remove_index(index);
82                insert_at = Some(insert_at.map_or(index, |at: usize| at.min(index)));
83            }
84        }
85        let insert_at = insert_at
86            .or_else(|| insert_before.and_then(|anchor| registered_index(&remaining, anchor)))
87            .unwrap_or(remaining.len());
88        let mut checked = remaining.clone();
89        let mut accepted = Vec::new();
90        let mut skipped = Vec::new();
91        for tool in next {
92            match validate_new_tool(tool.as_ref(), &checked) {
93                Ok(()) => {
94                    checked.insert(tool.name().to_owned(), tool.clone());
95                    accepted.push(tool);
96                }
97                Err(error) => skipped.push((tool, error)),
98            }
99        }
100        let tail = remaining.split_off(insert_at);
101        remaining.extend(accepted.into_iter().map(|tool| (tool.name().to_owned(), tool)));
102        remaining.extend(tail);
103        self.tools = remaining;
104        skipped
105    }
106
107    /// Registers tools, replacing tools of the same name.
108    ///
109    /// # Errors
110    ///
111    /// [`ToolValidationError`] when a name or description is invalid, a new name conflicts with
112    /// a `-`/`_` variant of a registered one, or `tools` holds an MCP client.
113    pub fn add_or_replace(&mut self, tools: impl Into<ToolSource>) -> Result<()> {
114        for tool in tools.into().into_registry_tools()? {
115            validate_properties(tool.as_ref())?;
116            let name = tool.name().to_owned();
117            if !self.tools.contains_key(&name) {
118                check_normalized_conflict(&name, &self.tools)?;
119            }
120            self.tools.insert(name, tool);
121        }
122        Ok(())
123    }
124
125    /// The tool registered under exactly `name` (`get`).
126    #[must_use]
127    pub fn get(&self, name: &str) -> Option<&Arc<dyn Tool>> {
128        self.tools.get(name)
129    }
130
131    /// Resolves a name the model used (`resolve`): an exact match, then a registered name whose
132    /// `-` become `_` (`my_tool` finds `my-tool`), then a case-insensitive match.
133    ///
134    /// # Errors
135    ///
136    /// [`ToolNotFoundError`] when nothing matches.
137    pub fn resolve(&self, name: &str) -> Result<&Arc<dyn Tool>> {
138        if let Some(tool) = self.tools.get(name) {
139            return Ok(tool);
140        }
141        let hyphen_match = name
142            .contains('_')
143            .then(|| {
144                self.tools
145                    .iter()
146                    .find(|(registered, _)| registered.replace('-', "_") == name)
147            })
148            .flatten();
149        if let Some((_, tool)) = hyphen_match {
150            return Ok(tool);
151        }
152        let lower = name.to_lowercase();
153        self.tools
154            .iter()
155            .find(|(registered, _)| registered.to_lowercase() == lower)
156            .map(|(_, tool)| tool)
157            .ok_or_else(|| ToolNotFoundError::new(name).into())
158    }
159
160    /// Removes a tool by name; does nothing when it is not registered (`remove`).
161    pub fn remove(&mut self, name: &str) {
162        self.tools.shift_remove(name);
163    }
164
165    /// Removes every tool (`clear`).
166    pub fn clear(&mut self) {
167        self.tools.clear();
168    }
169
170    /// Every registered tool, in registration order (`list`).
171    #[must_use]
172    pub fn list(&self) -> Vec<Arc<dyn Tool>> {
173        self.tools.values().cloned().collect()
174    }
175
176    /// The specs of every registered tool: sorted by name when
177    /// [`sort_tool_specs`](Self::sort_tool_specs) is set, otherwise in registration order
178    /// (`toolSpecs`).
179    #[must_use]
180    pub fn tool_specs(&self) -> Vec<ToolSpec> {
181        let mut specs: Vec<ToolSpec> = self.tools.values().map(|tool| tool.tool_spec()).collect();
182        if self.sort_tool_specs {
183            specs.sort_by(|left, right| left.name.cmp(&right.name));
184        }
185        specs
186    }
187
188    /// Whether [`tool_specs`](Self::tool_specs) sorts specs by name (`sortToolSpecs`). Defaults
189    /// to `false`, which keeps registration order.
190    #[must_use]
191    pub fn sort_tool_specs(&self) -> bool {
192        self.sort_tool_specs
193    }
194
195    /// Sets whether [`tool_specs`](Self::tool_specs) sorts specs by name.
196    pub fn set_sort_tool_specs(&mut self, sort: bool) {
197        self.sort_tool_specs = sort;
198    }
199
200    /// Whether no tools are registered.
201    #[must_use]
202    pub fn is_empty(&self) -> bool {
203        self.tools.is_empty()
204    }
205}
206
207/// The index of `tool` in `tools` when it is the tool registered under its name.
208fn registered_index(tools: &IndexMap<String, Arc<dyn Tool>>, tool: &Arc<dyn Tool>) -> Option<usize> {
209    let (index, _, registered) = tools.get_full(tool.name())?;
210    Arc::ptr_eq(registered, tool).then_some(index)
211}
212
213fn validate_new_tool(tool: &dyn Tool, tools: &IndexMap<String, Arc<dyn Tool>>) -> Result<(), ToolValidationError> {
214    validate_properties(tool)?;
215    let name = tool.name();
216    if tools.contains_key(name) {
217        return Err(ToolValidationError::new(format!(
218            "Tool with name '{name}' already registered"
219        )));
220    }
221    check_normalized_conflict(name, tools)
222}
223
224fn check_normalized_conflict(name: &str, tools: &IndexMap<String, Arc<dyn Tool>>) -> Result<(), ToolValidationError> {
225    let normalized = name.replace('-', "_");
226    let conflict = tools
227        .keys()
228        .find(|existing| existing.as_str() != name && existing.replace('-', "_") == normalized);
229    match conflict {
230        Some(existing) => Err(ToolValidationError::new(format!(
231            "Tool name '{name}' already exists as '{existing}'. Cannot add a duplicate tool which differs by a '-' or '_'"
232        ))),
233        None => Ok(()),
234    }
235}
236
237fn validate_properties(tool: &dyn Tool) -> Result<(), ToolValidationError> {
238    let name = tool.name();
239    if name.is_empty() || name.len() > MAX_TOOL_NAME_LENGTH {
240        return Err(ToolValidationError::new(format!(
241            "tool_name=<{name}> | Tool name must be between 1 and {MAX_TOOL_NAME_LENGTH} characters"
242        )));
243    }
244    if !is_valid_tool_name(name) {
245        return Err(ToolValidationError::new(format!(
246            "tool_name=<{name}> | Tool name must contain only alphanumeric characters, hyphens, and underscores"
247        )));
248    }
249    if tool.description().is_empty() {
250        return Err(ToolValidationError::new(format!(
251            "tool_name=<{name}> | Tool description must be a non-empty string"
252        )));
253    }
254    Ok(())
255}
256
257impl fmt::Debug for ToolRegistry {
258    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
259        f.debug_list().entries(self.tools.keys()).finish()
260    }
261}
262
263#[cfg(test)]
264mod tests;