1use serde::{Deserialize, Serialize};
7use serde_json::Value;
8use std::collections::HashSet;
9
10use crate::error::Result;
11
12pub trait Tool: Send + Sync {
51 fn name(&self) -> &str;
53
54 fn description(&self) -> &str;
56
57 fn arguments_schema(&self) -> Value;
59
60 fn call(&self, arguments: Value) -> Result<ToolOutput>;
66}
67
68#[derive(Debug, Clone, Serialize, Deserialize)]
70pub struct ToolOutput {
71 pub content: String,
73}
74
75impl ToolOutput {
76 pub fn new(content: impl Into<String>) -> Self {
78 Self {
79 content: content.into(),
80 }
81 }
82
83 pub fn from_json<T: Serialize>(value: &T) -> Result<Self> {
85 let content = serde_json::to_string(value)?;
86 Ok(Self { content })
87 }
88}
89
90#[derive(Debug, Clone, Serialize, Deserialize)]
92pub(crate) struct ToolDefinition {
93 pub name: String,
94 pub description: String,
95 #[serde(rename = "argumentsSchema")]
96 pub arguments_schema: Value,
97}
98
99pub(crate) fn tools_to_json(tools: &[&dyn Tool]) -> crate::error::Result<String> {
105 let mut seen = HashSet::new();
106 let mut definitions = Vec::with_capacity(tools.len());
107
108 for tool in tools {
109 let name = tool.name().trim();
110 if name.is_empty() {
111 return Err(crate::error::Error::InvalidInput(
112 "Tool name cannot be empty".to_string(),
113 ));
114 }
115 if !seen.insert(name.to_string()) {
116 return Err(crate::error::Error::InvalidInput(format!(
117 "Duplicate tool name: {name}"
118 )));
119 }
120
121 let schema = tool.arguments_schema();
122 let schema_obj = schema.as_object().ok_or_else(|| {
123 crate::error::Error::InvalidInput(format!(
124 "Tool '{name}' arguments schema must be a JSON object"
125 ))
126 })?;
127 if let Some(Value::String(ty)) = schema_obj.get("type")
128 && ty != "object"
129 {
130 return Err(crate::error::Error::InvalidInput(format!(
131 "Tool '{name}' arguments schema must have type \"object\""
132 )));
133 }
134
135 definitions.push(ToolDefinition {
136 name: name.to_string(),
137 description: tool.description().to_string(),
138 arguments_schema: schema,
139 });
140 }
141
142 serde_json::to_string(&definitions)
143 .map_err(|e| crate::error::Error::InvalidInput(format!("Failed to serialize tools: {e}")))
144}
145
146#[derive(Debug, Serialize, Deserialize)]
148pub(crate) struct ToolResult {
149 pub success: bool,
150 #[serde(skip_serializing_if = "Option::is_none")]
151 pub content: Option<String>,
152 #[serde(skip_serializing_if = "Option::is_none")]
153 pub error: Option<String>,
154}
155
156impl ToolResult {
157 pub fn success(output: ToolOutput) -> Self {
158 Self {
159 success: true,
160 content: Some(output.content),
161 error: None,
162 }
163 }
164
165 pub fn error(message: impl Into<String>) -> Self {
166 Self {
167 success: false,
168 content: None,
169 error: Some(message.into()),
170 }
171 }
172
173 pub fn to_json(&self) -> String {
174 serde_json::to_string(self).unwrap_or_else(|_| {
175 r#"{"success":false,"error":"Failed to serialize result"}"#.to_string()
176 })
177 }
178}
179
180#[cfg(test)]
181mod tests {
182 use serde_json::{Value, json};
183
184 use crate::error::Result;
185 use crate::tool::{Tool, ToolDefinition, ToolOutput, ToolResult, tools_to_json};
186
187 struct TestTool;
188
189 impl Tool for TestTool {
190 fn name(&self) -> &'static str {
191 "test_tool"
192 }
193
194 fn description(&self) -> &'static str {
195 "A test tool"
196 }
197
198 fn arguments_schema(&self) -> Value {
199 json!({
200 "type": "object",
201 "properties": {
202 "input": {"type": "string"}
203 }
204 })
205 }
206
207 fn call(&self, arguments: Value) -> Result<ToolOutput> {
208 let input = arguments["input"].as_str().unwrap_or("default");
209 Ok(ToolOutput::new(format!("Processed: {input}")))
210 }
211 }
212
213 #[test]
214 fn test_tool_definition() {
215 let tool = TestTool;
216 let def = ToolDefinition {
217 name: tool.name().to_string(),
218 description: tool.description().to_string(),
219 arguments_schema: tool.arguments_schema(),
220 };
221
222 assert_eq!(def.name, "test_tool");
223 assert_eq!(def.description, "A test tool");
224 }
225
226 #[test]
227 fn test_tools_to_json() {
228 let tool = TestTool;
229 let tools: Vec<&dyn Tool> = vec![&tool];
230 let json = tools_to_json(&tools).expect("serialization should succeed");
231
232 assert!(json.contains("test_tool"));
233 assert!(json.contains("A test tool"));
234 }
235
236 #[test]
237 fn test_tools_to_json_duplicate_names() {
238 struct ToolA;
239 struct ToolB;
240
241 impl Tool for ToolA {
242 fn name(&self) -> &'static str {
243 "duplicate"
244 }
245
246 fn description(&self) -> &'static str {
247 "Tool A"
248 }
249
250 fn arguments_schema(&self) -> Value {
251 json!({"type": "object"})
252 }
253
254 fn call(&self, _arguments: Value) -> Result<ToolOutput> {
255 Ok(ToolOutput::new("ok"))
256 }
257 }
258
259 impl Tool for ToolB {
260 fn name(&self) -> &'static str {
261 "duplicate"
262 }
263
264 fn description(&self) -> &'static str {
265 "Tool B"
266 }
267
268 fn arguments_schema(&self) -> Value {
269 json!({"type": "object"})
270 }
271
272 fn call(&self, _arguments: Value) -> Result<ToolOutput> {
273 Ok(ToolOutput::new("ok"))
274 }
275 }
276
277 let tools: Vec<&dyn Tool> = vec![&ToolA, &ToolB];
278 let err = tools_to_json(&tools).expect_err("expected duplicate error");
279 assert!(err.to_string().contains("Duplicate tool name"));
280 }
281
282 #[test]
283 fn test_tools_to_json_requires_object_schema() {
284 struct BadTool;
285
286 impl Tool for BadTool {
287 fn name(&self) -> &'static str {
288 "bad"
289 }
290
291 fn description(&self) -> &'static str {
292 "Bad schema"
293 }
294
295 fn arguments_schema(&self) -> Value {
296 json!("not-an-object")
297 }
298
299 fn call(&self, _arguments: Value) -> Result<ToolOutput> {
300 Ok(ToolOutput::new("ok"))
301 }
302 }
303
304 let tools: Vec<&dyn Tool> = vec![&BadTool];
305 let err = tools_to_json(&tools).expect_err("expected schema error");
306 assert!(
307 err.to_string()
308 .contains("arguments schema must be a JSON object")
309 );
310 }
311
312 #[test]
313 fn test_tools_to_json_requires_object_type() {
314 struct WrongTypeTool;
315
316 impl Tool for WrongTypeTool {
317 fn name(&self) -> &'static str {
318 "wrong_type"
319 }
320
321 fn description(&self) -> &'static str {
322 "Wrong type"
323 }
324
325 fn arguments_schema(&self) -> Value {
326 json!({"type": "string"})
327 }
328
329 fn call(&self, _arguments: Value) -> Result<ToolOutput> {
330 Ok(ToolOutput::new("ok"))
331 }
332 }
333
334 let tools: Vec<&dyn Tool> = vec![&WrongTypeTool];
335 let err = tools_to_json(&tools).expect_err("expected type error");
336 assert!(err.to_string().contains("must have type \"object\""));
337 }
338
339 #[test]
340 fn test_tool_output() {
341 let output = ToolOutput::new("Hello, World!");
342 assert_eq!(output.content, "Hello, World!");
343 }
344
345 #[test]
346 fn test_tool_result_json() {
347 let result = ToolResult::success(ToolOutput::new("OK"));
348 let json = result.to_json();
349 assert!(json.contains("\"success\":true"));
350 assert!(json.contains("\"content\":\"OK\""));
351 }
352}