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    RegisterError, Tool, ToolContext, 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    /// Returns definitions of all registered tools.
62    #[must_use]
63    pub fn definitions(&self) -> Vec<ToolDefinition> {
64        self.eager.definitions()
65    }
66
67    /// Returns all tool definitions (eager + MCP).
68    #[must_use]
69    pub fn active_definitions(&self) -> Vec<ToolDefinition> {
70        #[cfg(feature = "mcp")]
71        {
72            let mut defs = self.definitions();
73            for conn in &self.mcp {
74                defs.extend(conn.definitions());
75            }
76            defs
77        }
78
79        #[cfg(not(feature = "mcp"))]
80        {
81            self.definitions()
82        }
83    }
84
85    /// Calls a tool by name with JSON arguments.
86    ///
87    /// Searches eager tools first, then MCP tools. An eager tool runs with
88    /// `cx` as its [`ToolContext`]; an MCP tool runs in its server, which
89    /// reports to nobody here because no progress token is sent with the
90    /// request.
91    ///
92    /// # Errors
93    ///
94    /// Returns an error if the tool is not found or execution fails.
95    pub async fn call(
96        &self,
97        name: &str,
98        args: &str,
99        cx: ToolContext,
100    ) -> aither_core::Result<ToolResult> {
101        if self.eager.definitions().iter().any(|d| d.name() == name) {
102            return self.eager.call(name, args, cx).await;
103        }
104
105        #[cfg(feature = "mcp")]
106        for conn in &self.mcp {
107            if conn.has_tool(name) {
108                let args_value: serde_json::Value =
109                    serde_json::from_str(args).map_err(|e| anyhow::anyhow!("Invalid JSON: {e}"))?;
110
111                let result = conn
112                    .call(name, args_value)
113                    .await
114                    .map_err(|e| anyhow::anyhow!("MCP tool error: {e}"))?;
115
116                return aither_mcp::call_result_to_tool_result(result)
117                    .map_err(|e| anyhow::anyhow!("MCP tool error: {e}"));
118            }
119        }
120
121        Err(anyhow::anyhow!("Tool '{name}' not found"))
122    }
123
124    /// Returns a reference to the underlying eager tools.
125    #[must_use]
126    pub const fn eager(&self) -> &CoreTools {
127        &self.eager
128    }
129
130    /// Returns a mutable reference to the underlying eager tools.
131    pub const fn eager_mut(&mut self) -> &mut CoreTools {
132        &mut self.eager
133    }
134
135    /// Registers an MCP connection.
136    ///
137    /// All tools from the MCP server will be available for the agent to use.
138    #[cfg(feature = "mcp")]
139    pub fn register_mcp(&mut self, conn: McpConnection) {
140        self.mcp.push(McpToolService::new(conn));
141    }
142
143    /// Returns the number of registered MCP connections.
144    #[cfg(feature = "mcp")]
145    #[must_use]
146    pub const fn mcp_count(&self) -> usize {
147        self.mcp.len()
148    }
149
150    /// Returns definitions from all MCP connections.
151    #[cfg(feature = "mcp")]
152    #[must_use]
153    pub fn mcp_definitions(&self) -> Vec<ToolDefinition> {
154        self.mcp
155            .iter()
156            .flat_map(aither_mcp::McpToolService::definitions)
157            .collect()
158    }
159
160    /// Merge another `AgentTools` into this one.
161    ///
162    /// Note: MCP connections are not cloned (they would require ownership transfer).
163    pub fn merge(&mut self, _other: Self) {
164        // Core tools cannot be merged without re-registering concrete tool instances.
165    }
166}
167
168#[cfg(test)]
169mod tests {
170    use super::*;
171    use schemars::JsonSchema;
172    use serde::Deserialize;
173    use std::borrow::Cow;
174
175    struct DummyTool {
176        name: String,
177    }
178
179    /// Arguments for the dummy test tool.
180    #[derive(Debug, JsonSchema, Deserialize)]
181    struct DummyArgs {}
182
183    impl Tool for DummyTool {
184        fn name(&self) -> Cow<'static, str> {
185            Cow::Owned(self.name.clone())
186        }
187
188        type Arguments = DummyArgs;
189
190        type Res = ToolResult;
191
192        fn call(
193            &self,
194            _args: Self::Arguments,
195            _cx: aither_core::llm::ToolContext,
196        ) -> impl std::future::Future<Output = aither_core::Result<Self::Res>> + Send {
197            std::future::ready(Ok(ToolResult::text("ok")))
198        }
199    }
200
201    /// A tool that answers with a PNG.
202    #[cfg(feature = "mcp")]
203    struct Screenshot;
204
205    #[cfg(feature = "mcp")]
206    impl Tool for Screenshot {
207        fn name(&self) -> Cow<'static, str> {
208            Cow::Borrowed("screenshot")
209        }
210
211        type Arguments = DummyArgs;
212
213        type Res = ToolResult;
214
215        fn call(
216            &self,
217            _args: Self::Arguments,
218            _cx: aither_core::llm::ToolContext,
219        ) -> impl std::future::Future<Output = aither_core::Result<Self::Res>> + Send {
220            std::future::ready(Ok(ToolResult::image(
221                vec![0x89, b'P', b'N', b'G'],
222                "image/png",
223            )))
224        }
225    }
226
227    #[cfg(feature = "mcp")]
228    #[tokio::test]
229    async fn an_mcp_image_result_reaches_the_model_as_an_image() {
230        use aither_mcp::transport::DuplexTransport;
231
232        let (server_end, client_end) = DuplexTransport::pair();
233        let mut exposed = aither_core::llm::tool::Tools::new();
234        exposed.register(Screenshot).expect("screenshot registers");
235        let mut mcp_server = aither_mcp::McpServer::new(server_end, exposed, "screens", "1");
236        let running = tokio::spawn(async move { mcp_server.run().await });
237
238        let conn = McpConnection::connect(&executor_core::tokio::TokioGlobal, client_end, ())
239            .await
240            .expect("connects");
241        let mut tools = AgentTools::new();
242        tools.register_mcp(conn);
243
244        let result = tools
245            .call("screenshot", "{}", aither_core::llm::ToolContext::new())
246            .await
247            .expect("the call succeeds");
248
249        assert_eq!(
250            result,
251            ToolResult::Binary {
252                mime: "image/png".to_string(),
253                content: vec![0x89, b'P', b'N', b'G'],
254            }
255        );
256        running.abort();
257    }
258
259    #[test]
260    fn test_register_eager() {
261        let mut tools = AgentTools::new();
262        tools
263            .register(DummyTool {
264                name: "test".to_string(),
265            })
266            .expect("dummy tool should register");
267
268        assert_eq!(tools.definitions().len(), 1);
269    }
270}