Skip to main content

rig_agent/tool/
registry.rs

1//! Ordered tool registrations, request catalogs, and inline dispatch by name.
2//!
3//! ```
4//! use rig_agent::tool::ToolSet;
5//! let tools = ToolSet::default();
6//! assert!(tools.catalog().is_empty());
7//! ```
8
9use std::sync::Arc;
10
11use indexmap::IndexMap;
12use rig_core::serve::adapters::ToolAdapter;
13use rig_core::serve::{ErasedHandler, Serve};
14use rig_core::{
15    completion::ToolDefinition,
16    effect::{
17        EffectKind, Family, FamilyDescriptor, Key, ToolEmbeddingDescriptor, family, tool_key,
18    },
19    embeddings::{embed::EmbedError, tool::ToolSchema},
20    error::{ErrorKind, ErrorReport},
21    message::ToolName,
22    tool::{
23        DynamicTool, LivenessFn, Tool, ToolContext, ToolEmbedding, ToolExecutionError, ToolResult,
24        tool_definition,
25    },
26};
27
28use super::catalog::ToolCatalog;
29
30/// One registration: the tool's serde description, the key it is (or will
31/// be) served under, and the erased handler a table takes. Cloning shares the
32/// handler.
33#[derive(Clone)]
34pub struct RegisteredTool {
35    definition: Arc<ToolDefinition>,
36    embedding: Option<ToolEmbeddingDescriptor>,
37    key: Key<family::Tool>,
38    handler: ErasedHandler,
39    liveness: Option<LivenessFn>,
40}
41
42impl std::fmt::Debug for RegisteredTool {
43    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        f.debug_struct("RegisteredTool")
45            .field("name", &self.definition.name)
46            .field("key", &self.key)
47            .field("retrievable", &self.embedding.is_some())
48            .finish_non_exhaustive()
49    }
50}
51
52impl RegisteredTool {
53    /// Register a typed tool.
54    pub fn from_tool<T>(tool: T) -> Self
55    where
56        T: Tool + 'static,
57    {
58        let definition = tool_definition(&tool);
59        Self::from_parts(
60            definition,
61            None,
62            ErasedHandler::new(ToolAdapter::new(tool)),
63            None,
64        )
65    }
66
67    /// Register a retrievable tool with embedding context in its descriptor.
68    /// Returns an error if the context cannot be serialized.
69    pub fn from_retrievable<T>(tool: T) -> Result<Self, serde_json::Error>
70    where
71        T: ToolEmbedding + 'static,
72    {
73        let adapter = ToolAdapter::retrievable(tool)?;
74        let definition = tool_definition(adapter.tool());
75        let embedding = adapter.embedding().cloned();
76        Ok(Self::from_parts(
77            definition,
78            embedding,
79            ErasedHandler::new(adapter),
80            None,
81        ))
82    }
83
84    /// Register a runtime-defined tool.
85    pub fn from_dynamic(tool: DynamicTool) -> Self {
86        let (definition, handler, liveness) = tool.into_parts();
87        Self::from_parts(definition, None, handler, liveness)
88    }
89
90    /// Register a handler under its descriptor's key.
91    /// Returns `HandlerUnavailable` if the descriptor is not tool-family.
92    pub fn from_handler(handler: impl Serve + 'static) -> Result<Self, ErrorReport> {
93        let descriptor = handler.descriptor();
94        let FamilyDescriptor::Tool {
95            name,
96            description,
97            parameters,
98            embedding,
99        } = descriptor.family
100        else {
101            return Err(ErrorReport::new(
102                ErrorKind::HandlerUnavailable,
103                format!(
104                    "handler `{}` serves the {} family, not tool_call",
105                    descriptor.key,
106                    descriptor.family.family()
107                ),
108            ));
109        };
110        let name = ToolName::new(name).map_err(|_| {
111            ErrorReport::new(
112                ErrorKind::HandlerUnavailable,
113                format!(
114                    "handler `{}` serves a tool with an empty name",
115                    descriptor.key
116                ),
117            )
118        })?;
119        Ok(Self {
120            definition: Arc::new(ToolDefinition {
121                name,
122                description,
123                parameters,
124                annotations: Default::default(),
125            }),
126            embedding,
127            key: Key::new_unchecked(descriptor.key),
128            handler: ErasedHandler::new(handler),
129            liveness: None,
130        })
131    }
132
133    /// Whether this registration is served under the default `tool:<name>`
134    /// key (a registry that pins generations re-keys only those).
135    pub(crate) fn has_default_key(&self) -> bool {
136        *self.key.raw() == tool_key(&self.definition.name)
137    }
138
139    fn from_parts(
140        definition: ToolDefinition,
141        embedding: Option<ToolEmbeddingDescriptor>,
142        handler: ErasedHandler,
143        liveness: Option<LivenessFn>,
144    ) -> Self {
145        let key = Key::new_unchecked(tool_key(&definition.name));
146        Self {
147            definition: Arc::new(definition),
148            embedding,
149            key,
150            handler,
151            liveness,
152        }
153    }
154
155    /// Serve this registration under `key` instead of the default
156    /// `tool:<name>` (a registry that pins generations does this).
157    pub fn with_key(mut self, key: Key<family::Tool>) -> Self {
158        self.key = key;
159        self
160    }
161
162    /// The tool's name.
163    pub fn name(&self) -> String {
164        self.definition.name.to_string()
165    }
166
167    /// The key the handler is served under: a tool key, proven at
168    /// construction (the descriptor was checked to be tool-family).
169    pub fn key(&self) -> &Key<family::Tool> {
170        &self.key
171    }
172
173    /// The erased handler.
174    pub fn handler(&self) -> &ErasedHandler {
175        &self.handler
176    }
177
178    /// The definition advertised to the model.
179    pub(crate) fn definition(&self) -> Arc<ToolDefinition> {
180        Arc::clone(&self.definition)
181    }
182
183    /// The embedding context, for retrievable tools.
184    pub fn embedding(&self) -> Option<&ToolEmbeddingDescriptor> {
185        self.embedding.as_ref()
186    }
187
188    /// Whether the tool's owner still serves it (`true` without a probe).
189    pub fn is_live(&self) -> bool {
190        self.liveness.as_ref().is_none_or(|probe| probe())
191    }
192
193    /// Execute inline on a dispatch snapshot of inbound context. On completion,
194    /// replace result metadata with what the tool published, or an empty result
195    /// map if nothing was published. Inbound values remain unchanged; dropping
196    /// the future mid-call leaves the caller's entire context unchanged.
197    /// Handler errors and wrong-family outcomes become failed tool results.
198    pub async fn execute(&self, args: String, context: &mut ToolContext) -> ToolResult {
199        let name = self.definition.name.to_string();
200        // Context travels outside the serializable effect payload.
201        let published = rig_core::tool::PublishedContext::new();
202        let outcome = rig_core::serve::serve_inline_with(
203            &self.handler,
204            EffectKind::ToolCall { name, args },
205            vec![
206                std::sync::Arc::new(context.for_dispatch()),
207                published.clone() as std::sync::Arc<dyn std::any::Any + Send + Sync>,
208            ],
209        )
210        .await;
211        // What the tool published is this call's result metadata; a handler
212        // that published nothing (or never ran) leaves an empty result map.
213        context.accept_dispatch_result(published.take().unwrap_or_default());
214        outcome
215            .and_then(family::Tool::unwrap)
216            .unwrap_or_else(|report| ToolResult::failed(report.into()))
217    }
218}
219
220/// One entry of a [`ToolSet`]: the registration plus whether it is
221/// advertised on every request or only when retrieved.
222#[derive(Clone)]
223pub(crate) struct ToolRegistration {
224    pub(crate) tool: RegisteredTool,
225    pub(crate) always_exposed: bool,
226}
227
228/// Insertion-ordered named tool registrations and their advertisement policy.
229/// Direct execution is inline; hosts may install the registrations in a table.
230#[derive(Clone, Default)]
231pub struct ToolSet {
232    pub(crate) tools: IndexMap<String, ToolRegistration>,
233}
234
235impl ToolSet {
236    /// A set from typed tools.
237    pub fn from_tools<T>(tools: Vec<T>) -> Self
238    where
239        T: Tool + 'static,
240    {
241        let mut set = Self::default();
242        for tool in tools {
243            set.add_tool(tool);
244        }
245        set
246    }
247
248    /// Whether a tool named `name` is registered.
249    pub fn contains(&self, name: &str) -> bool {
250        self.tools.contains_key(name)
251    }
252
253    /// Register a typed tool; returns its name.
254    pub fn add_tool<T>(&mut self, tool: T) -> String
255    where
256        T: Tool + 'static,
257    {
258        self.insert(RegisteredTool::from_tool(tool), true)
259    }
260
261    /// Register a runtime-defined tool; returns its name.
262    pub fn add_dynamic_tool(&mut self, tool: DynamicTool) -> String {
263        self.insert(RegisteredTool::from_dynamic(tool), true)
264    }
265
266    /// Register a retrievable tool; returns its name. A context that does
267    /// not serialize is the error, and nothing is registered.
268    pub fn add_retrieved_tool<T>(&mut self, tool: T) -> Result<String, serde_json::Error>
269    where
270        T: ToolEmbedding + 'static,
271    {
272        RegisteredTool::from_retrievable(tool).map(|registered| self.insert(registered, true))
273    }
274
275    /// Register an already-built registration; returns its name.
276    pub fn add_registered_tool(&mut self, tool: RegisteredTool) -> String {
277        self.insert(tool, true)
278    }
279
280    /// Register `tool`, advertised on every request or only when retrieved;
281    /// a replaced registration that was always exposed stays so.
282    pub(crate) fn insert(&mut self, tool: RegisteredTool, always_exposed: bool) -> String {
283        let name = tool.name();
284        let registration = ToolRegistration {
285            tool,
286            always_exposed,
287        };
288        self.insert_registration(name.clone(), registration);
289        name
290    }
291
292    fn insert_registration(&mut self, name: String, mut registration: ToolRegistration) {
293        if let Some(current) = self.tools.get_mut(&name) {
294            registration.always_exposed |= current.always_exposed;
295            *current = registration;
296            tracing::warn!(tool_name = %name, "replacing an existing tool registration");
297        } else {
298            self.tools.insert(name, registration);
299        }
300    }
301
302    /// Remove the tool named `name`.
303    pub fn remove_tool(&mut self, name: &str) {
304        self.tools.shift_remove(name);
305    }
306
307    /// Merge `set`'s registrations, keeping their exposure.
308    pub fn add_tools(&mut self, set: ToolSet) {
309        for (name, registration) in set.tools {
310            self.insert_registration(name, registration);
311        }
312    }
313
314    /// Merge `set`'s registrations as retrieval-only (not always exposed).
315    pub fn add_retrievable_tools(&mut self, set: ToolSet) {
316        for (name, mut registration) in set.tools {
317            registration.always_exposed = false;
318            self.insert_registration(name, registration);
319        }
320    }
321
322    /// The registration named `name`.
323    pub fn get(&self, name: &str) -> Option<&RegisteredTool> {
324        self.tools.get(name).map(|registration| &registration.tool)
325    }
326
327    /// Every registration, in insertion order.
328    pub fn iter(&self) -> impl Iterator<Item = (&str, &RegisteredTool)> {
329        self.tools
330            .iter()
331            .map(|(name, registration)| (name.as_str(), &registration.tool))
332    }
333
334    /// Every name, in insertion order.
335    pub fn names(&self) -> impl Iterator<Item = &str> {
336        self.tools.keys().map(String::as_str)
337    }
338
339    /// Number of registrations.
340    pub fn len(&self) -> usize {
341        self.tools.len()
342    }
343
344    /// Whether the set is empty.
345    pub fn is_empty(&self) -> bool {
346        self.tools.is_empty()
347    }
348
349    /// Names advertised on every request.
350    pub fn always_exposed_names(&self) -> impl Iterator<Item = &str> {
351        self.tools
352            .iter()
353            .filter_map(|(name, registration)| registration.always_exposed.then_some(name.as_str()))
354    }
355
356    /// Move `name` to the end of the insertion order.
357    pub(crate) fn move_to_end(&mut self, name: &str) -> bool {
358        self.tools
359            .shift_remove_entry(name)
360            .is_some_and(|(name, registration)| {
361                self.tools.insert(name, registration);
362                true
363            })
364    }
365
366    /// The always-exposed registrations as a catalog.
367    pub fn catalog(&self) -> ToolCatalog {
368        ToolCatalog::from_registered(
369            self.tools
370                .iter()
371                .filter(|(_, registration)| registration.always_exposed)
372                .map(|(name, registration)| (name.clone(), registration.tool.clone()))
373                .collect(),
374        )
375    }
376
377    /// Every definition, in insertion order.
378    pub fn tool_definitions(&self) -> Vec<Arc<ToolDefinition>> {
379        self.tools
380            .values()
381            .map(|registration| registration.tool.definition())
382            .collect()
383    }
384
385    /// Run the tool named `name` inline ([`RegisteredTool::execute`]),
386    /// publishing its result metadata into `context`; a name nothing is
387    /// registered under is a `not_found` failure, with no metadata.
388    pub async fn execute(
389        &self,
390        name: &str,
391        args: impl Into<String>,
392        context: &mut ToolContext,
393    ) -> ToolResult {
394        let Some(tool) = self.get(name) else {
395            context.clear_dispatch_result();
396            return ToolResult::failed(
397                ToolExecutionError::not_found(format!("no tool named `{name}` is registered"))
398                    .with_model_feedback(format!("tool `{name}` not found")),
399            );
400        };
401        tracing::debug!(target: "rig", tool_name = name, "calling tool");
402        tool.execute(args.into(), context).await
403    }
404
405    /// The embedding schemas of the retrievable registrations.
406    pub fn schemas(&self) -> Result<Vec<ToolSchema>, EmbedError> {
407        Ok(self
408            .tools
409            .iter()
410            .filter_map(|(name, registration)| {
411                registration.tool.embedding().map(|embedding| ToolSchema {
412                    name: name.clone(),
413                    context: embedding.context.clone(),
414                    embedding_docs: embedding.embedding_docs.clone(),
415                })
416            })
417            .collect())
418    }
419}
420
421#[cfg(test)]
422mod tests;