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