Skip to main content

aither_agent/
tools.rs

1//! Tools registry for the agent.
2//!
3//! All registered tools are always loaded into the LLM context.
4
5use aither_core::llm::tool::{
6    IntoToolResult, RegisterError, Tool, ToolContext, ToolDefinition, ToolResult,
7    Tools as CoreTools,
8};
9#[cfg(feature = "mcp")]
10use aither_mcp::{McpConnection, McpToolService};
11
12/// Tools registry used by the agent.
13///
14/// All tools are eager-loaded and included in every LLM request.
15pub struct AgentTools {
16    /// Always-loaded tools.
17    eager: CoreTools,
18
19    /// MCP connections (when mcp feature is enabled).
20    #[cfg(feature = "mcp")]
21    mcp: Vec<McpToolService>,
22}
23
24impl Default for AgentTools {
25    fn default() -> Self {
26        Self::new()
27    }
28}
29
30impl std::fmt::Debug for AgentTools {
31    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32        let mut s = f.debug_struct("AgentTools");
33        s.field("eager", &self.eager);
34        #[cfg(feature = "mcp")]
35        s.field("mcp", &self.mcp);
36        s.finish()
37    }
38}
39
40impl AgentTools {
41    /// Creates a new empty tools registry.
42    #[must_use]
43    pub const fn new() -> Self {
44        Self {
45            eager: CoreTools::new(),
46            #[cfg(feature = "mcp")]
47            mcp: Vec::new(),
48        }
49    }
50
51    /// Registers an eager (always-loaded) tool.
52    ///
53    /// # Errors
54    ///
55    /// Returns [`RegisterError`] if the name collides with a tool that is
56    /// already registered, or the tool has no description for the model to
57    /// read.
58    pub fn register<T: Tool + 'static>(&mut self, tool: T) -> Result<(), RegisterError> {
59        self.eager.register(tool)
60    }
61
62    /// Registers a dynamic terminal tool (type-erased).
63    ///
64    /// This is used for child terminal tools in subagents where the concrete type
65    /// is not known at compile time.
66    ///
67    /// # Panics
68    ///
69    /// Panics if the tool cannot be registered: another tool already uses
70    /// its name, or it carries no description for the model to read. Both
71    /// are mistakes in the calling program.
72    pub fn register_dyn_terminal(&mut self, dyn_tool: aither_sandbox::DynTerminalTool) {
73        use futures_core::Future;
74        use std::pin::Pin;
75
76        for entry in dyn_tool.into_entries() {
77            let handler = entry.handler;
78            self.eager.register_dyn(
79                entry.definition,
80                move |args: &str, cx: ToolContext| -> Pin<
81                    Box<dyn Future<Output = aither_core::Result<ToolResult>> + Send>,
82                > {
83                let handler = handler.clone();
84                let args = args.to_string();
85                Box::pin(async move {
86                    handler(&args, cx).await.into_tool_result()
87                })
88                },
89            )
90            .expect("dynamic terminal tool registration must succeed: duplicate name or missing description");
91        }
92    }
93
94    /// Returns definitions of all registered tools.
95    #[must_use]
96    pub fn definitions(&self) -> Vec<ToolDefinition> {
97        self.eager.definitions()
98    }
99
100    /// Returns all tool definitions (eager + MCP).
101    #[must_use]
102    pub fn active_definitions(&self) -> Vec<ToolDefinition> {
103        #[cfg(feature = "mcp")]
104        {
105            let mut defs = self.definitions();
106            for conn in &self.mcp {
107                defs.extend(conn.definitions());
108            }
109            defs
110        }
111
112        #[cfg(not(feature = "mcp"))]
113        {
114            self.definitions()
115        }
116    }
117
118    /// Calls a tool by name with JSON arguments.
119    ///
120    /// Searches eager tools first, then MCP tools. An eager tool runs with
121    /// `cx` as its [`ToolContext`]; an MCP tool runs in its server, which
122    /// reports to nobody here because no progress token is sent with the
123    /// request.
124    ///
125    /// # Errors
126    ///
127    /// Returns an error if the tool is not found or execution fails.
128    pub async fn call(
129        &self,
130        name: &str,
131        args: &str,
132        cx: ToolContext,
133    ) -> aither_core::Result<ToolResult> {
134        if self.eager.definitions().iter().any(|d| d.name() == name) {
135            return self.eager.call(name, args, cx).await;
136        }
137
138        #[cfg(feature = "mcp")]
139        for conn in &self.mcp {
140            if conn.has_tool(name) {
141                let args_value: serde_json::Value =
142                    serde_json::from_str(args).map_err(|e| anyhow::anyhow!("Invalid JSON: {e}"))?;
143
144                let result = conn
145                    .call(name, args_value)
146                    .await
147                    .map_err(|e| anyhow::anyhow!("MCP tool error: {e}"))?;
148
149                let output = result
150                    .content
151                    .into_iter()
152                    .filter_map(|c| match c {
153                        aither_mcp::Content::Text(t) => Some(t.text),
154                        _ => None,
155                    })
156                    .collect::<Vec<_>>()
157                    .join("\n");
158
159                return if result.is_error {
160                    Err(anyhow::anyhow!("{output}"))
161                } else {
162                    output.into_tool_result()
163                };
164            }
165        }
166
167        Err(anyhow::anyhow!("Tool '{name}' not found"))
168    }
169
170    /// Returns a reference to the underlying eager tools.
171    #[must_use]
172    pub const fn eager(&self) -> &CoreTools {
173        &self.eager
174    }
175
176    /// Returns a mutable reference to the underlying eager tools.
177    pub const fn eager_mut(&mut self) -> &mut CoreTools {
178        &mut self.eager
179    }
180
181    /// Registers an MCP connection.
182    ///
183    /// All tools from the MCP server will be available for the agent to use.
184    #[cfg(feature = "mcp")]
185    pub fn register_mcp(&mut self, conn: McpConnection) {
186        self.mcp.push(McpToolService::new(conn));
187    }
188
189    /// Returns the number of registered MCP connections.
190    #[cfg(feature = "mcp")]
191    #[must_use]
192    pub const fn mcp_count(&self) -> usize {
193        self.mcp.len()
194    }
195
196    /// Returns definitions from all MCP connections.
197    #[cfg(feature = "mcp")]
198    #[must_use]
199    pub fn mcp_definitions(&self) -> Vec<ToolDefinition> {
200        self.mcp
201            .iter()
202            .flat_map(aither_mcp::McpToolService::definitions)
203            .collect()
204    }
205
206    /// Merge another `AgentTools` into this one.
207    ///
208    /// Note: MCP connections are not cloned (they would require ownership transfer).
209    pub fn merge(&mut self, _other: Self) {
210        // Core tools cannot be merged without re-registering concrete tool instances.
211    }
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217    use schemars::JsonSchema;
218    use serde::Deserialize;
219    use std::borrow::Cow;
220
221    struct DummyTool {
222        name: String,
223    }
224
225    /// Arguments for the dummy test tool.
226    #[derive(Debug, JsonSchema, Deserialize)]
227    struct DummyArgs {}
228
229    impl Tool for DummyTool {
230        fn name(&self) -> Cow<'static, str> {
231            Cow::Owned(self.name.clone())
232        }
233
234        type Arguments = DummyArgs;
235
236        type Res = ToolResult;
237
238        fn call(
239            &self,
240            _args: Self::Arguments,
241            _cx: aither_core::llm::ToolContext,
242        ) -> impl std::future::Future<Output = aither_core::Result<Self::Res>> + Send {
243            std::future::ready(Ok(ToolResult::text("ok")))
244        }
245    }
246
247    #[test]
248    fn test_register_eager() {
249        let mut tools = AgentTools::new();
250        tools
251            .register(DummyTool {
252                name: "test".to_string(),
253            })
254            .expect("dummy tool should register");
255
256        assert_eq!(tools.definitions().len(), 1);
257    }
258}