strands/tools/
registry.rs1use 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#[derive(Clone, Default)]
22pub struct ToolRegistry {
23 tools: IndexMap<String, Arc<dyn Tool>>,
24 sort_tool_specs: bool,
25}
26
27impl ToolRegistry {
28 pub fn new() -> Self {
30 Self::default()
31 }
32
33 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 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 #[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 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 #[must_use]
127 pub fn get(&self, name: &str) -> Option<&Arc<dyn Tool>> {
128 self.tools.get(name)
129 }
130
131 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 pub fn remove(&mut self, name: &str) {
162 self.tools.shift_remove(name);
163 }
164
165 pub fn clear(&mut self) {
167 self.tools.clear();
168 }
169
170 #[must_use]
172 pub fn list(&self) -> Vec<Arc<dyn Tool>> {
173 self.tools.values().cloned().collect()
174 }
175
176 #[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 #[must_use]
191 pub fn sort_tool_specs(&self) -> bool {
192 self.sort_tool_specs
193 }
194
195 pub fn set_sort_tool_specs(&mut self, sort: bool) {
197 self.sort_tool_specs = sort;
198 }
199
200 #[must_use]
202 pub fn is_empty(&self) -> bool {
203 self.tools.is_empty()
204 }
205}
206
207fn 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;