1use aither_core::llm::tool::{
6 IntoToolResult, RegisterError, Tool, ToolDefinition, ToolResult, Tools as CoreTools,
7};
8#[cfg(feature = "mcp")]
9use aither_mcp::{McpConnection, McpToolService};
10
11pub struct AgentTools {
15 eager: CoreTools,
17
18 #[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 #[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 pub fn register<T: Tool + 'static>(&mut self, tool: T) -> Result<(), RegisterError> {
58 self.eager.register(tool)
59 }
60
61 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 #[must_use]
95 pub fn definitions(&self) -> Vec<ToolDefinition> {
96 self.eager.definitions()
97 }
98
99 #[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 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 #[must_use]
163 pub const fn eager(&self) -> &CoreTools {
164 &self.eager
165 }
166
167 pub const fn eager_mut(&mut self) -> &mut CoreTools {
169 &mut self.eager
170 }
171
172 #[cfg(feature = "mcp")]
176 pub fn register_mcp(&mut self, conn: McpConnection) {
177 self.mcp.push(McpToolService::new(conn));
178 }
179
180 #[cfg(feature = "mcp")]
182 #[must_use]
183 pub const fn mcp_count(&self) -> usize {
184 self.mcp.len()
185 }
186
187 #[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 pub fn merge(&mut self, _other: Self) {
201 }
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 #[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}