1use anyhow::{anyhow, Result};
8use async_trait::async_trait;
9use serde::{Deserialize, Serialize};
10use serde_json::Value as JsonValue;
11use std::collections::HashMap;
12use std::sync::Arc;
13use tokio::sync::RwLock;
14use tracing::{debug, info, warn};
15
16#[derive(Debug, Clone, Serialize, Deserialize)]
18pub struct ToolParameter {
19 pub name: String,
21 pub description: String,
23 pub param_type: ParameterType,
25 pub required: bool,
27 pub default_value: Option<JsonValue>,
29 pub constraints: Option<ParameterConstraints>,
31}
32
33#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
35pub enum ParameterType {
36 String,
38 Integer,
40 Float,
42 Boolean,
44 Array,
46 Object,
48 Any,
50}
51
52#[derive(Debug, Clone, Serialize, Deserialize)]
54pub struct ParameterConstraints {
55 pub min: Option<f64>,
57 pub max: Option<f64>,
59 pub allowed_values: Option<Vec<JsonValue>>,
61 pub pattern: Option<String>,
63 pub min_length: Option<usize>,
65 pub max_length: Option<usize>,
67}
68
69#[derive(Debug, Clone, Serialize, Deserialize)]
71pub struct ToolResult {
72 pub success: bool,
74 pub data: JsonValue,
76 pub error: Option<String>,
78 pub execution_time_ms: u64,
80 pub metadata: HashMap<String, String>,
82}
83
84#[derive(Debug, Clone, Serialize, Deserialize)]
86pub struct ToolDefinition {
87 pub id: String,
89 pub name: String,
91 pub description: String,
93 pub parameters: Vec<ToolParameter>,
95 pub category: ToolCategory,
97 pub is_async: bool,
99 pub tags: Vec<String>,
101 pub examples: Vec<ToolExample>,
103}
104
105#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
107pub enum ToolCategory {
108 Retrieval,
110 Transformation,
112 Analysis,
114 ExternalAPI,
116 Utility,
118 Custom,
120}
121
122#[derive(Debug, Clone, Serialize, Deserialize)]
124pub struct ToolExample {
125 pub description: String,
127 pub input: HashMap<String, JsonValue>,
129 pub output: JsonValue,
131}
132
133#[async_trait]
135pub trait CustomTool: Send + Sync {
136 fn definition(&self) -> ToolDefinition;
138
139 async fn execute(&self, parameters: HashMap<String, JsonValue>) -> Result<ToolResult>;
141
142 fn validate(&self, parameters: &HashMap<String, JsonValue>) -> Result<()> {
144 let definition = self.definition();
145
146 for param in &definition.parameters {
148 if param.required && !parameters.contains_key(¶m.name) {
149 return Err(anyhow!("Missing required parameter: {}", param.name));
150 }
151
152 if let Some(value) = parameters.get(¶m.name) {
154 self.validate_parameter(param, value)?;
155 }
156 }
157
158 Ok(())
159 }
160
161 fn validate_parameter(&self, param: &ToolParameter, value: &JsonValue) -> Result<()> {
163 match param.param_type {
165 ParameterType::String => {
166 if !value.is_string() {
167 return Err(anyhow!("Parameter {} must be a string", param.name));
168 }
169 }
170 ParameterType::Integer => {
171 if !value.is_i64() && !value.is_u64() {
172 return Err(anyhow!("Parameter {} must be an integer", param.name));
173 }
174 }
175 ParameterType::Float => {
176 if !value.is_f64() && !value.is_i64() {
177 return Err(anyhow!("Parameter {} must be a number", param.name));
178 }
179 }
180 ParameterType::Boolean => {
181 if !value.is_boolean() {
182 return Err(anyhow!("Parameter {} must be a boolean", param.name));
183 }
184 }
185 ParameterType::Array => {
186 if !value.is_array() {
187 return Err(anyhow!("Parameter {} must be an array", param.name));
188 }
189 }
190 ParameterType::Object => {
191 if !value.is_object() {
192 return Err(anyhow!("Parameter {} must be an object", param.name));
193 }
194 }
195 ParameterType::Any => {} }
197
198 if let Some(constraints) = ¶m.constraints {
200 self.validate_constraints(param, value, constraints)?;
201 }
202
203 Ok(())
204 }
205
206 fn validate_constraints(
208 &self,
209 param: &ToolParameter,
210 value: &JsonValue,
211 constraints: &ParameterConstraints,
212 ) -> Result<()> {
213 if let Some(num) = value.as_f64() {
215 if let Some(min) = constraints.min {
216 if num < min {
217 return Err(anyhow!("Parameter {} must be >= {}", param.name, min));
218 }
219 }
220 if let Some(max) = constraints.max {
221 if num > max {
222 return Err(anyhow!("Parameter {} must be <= {}", param.name, max));
223 }
224 }
225 }
226
227 let len = value
229 .as_str()
230 .map(|s| s.len())
231 .or_else(|| value.as_array().map(|arr| arr.len()));
232
233 if let Some(length) = len {
234 if let Some(min_len) = constraints.min_length {
235 if length < min_len {
236 return Err(anyhow!(
237 "Parameter {} length must be >= {}",
238 param.name,
239 min_len
240 ));
241 }
242 }
243 if let Some(max_len) = constraints.max_length {
244 if length > max_len {
245 return Err(anyhow!(
246 "Parameter {} length must be <= {}",
247 param.name,
248 max_len
249 ));
250 }
251 }
252 }
253
254 if let Some(allowed) = &constraints.allowed_values {
256 if !allowed.contains(value) {
257 return Err(anyhow!(
258 "Parameter {} must be one of: {:?}",
259 param.name,
260 allowed
261 ));
262 }
263 }
264
265 if let Some(pattern) = &constraints.pattern {
267 if let Some(s) = value.as_str() {
268 let regex = regex::Regex::new(pattern)?;
269 if !regex.is_match(s) {
270 return Err(anyhow!(
271 "Parameter {} must match pattern: {}",
272 param.name,
273 pattern
274 ));
275 }
276 }
277 }
278
279 Ok(())
280 }
281}
282
283pub struct CustomToolsRegistry {
285 tools: Arc<RwLock<HashMap<String, Arc<dyn CustomTool>>>>,
287 execution_history: Arc<RwLock<Vec<ToolExecution>>>,
289}
290
291#[derive(Debug, Clone)]
293pub struct ToolExecution {
294 pub tool_id: String,
295 pub timestamp: chrono::DateTime<chrono::Utc>,
296 pub parameters: HashMap<String, JsonValue>,
297 pub result: ToolResult,
298}
299
300impl CustomToolsRegistry {
301 pub fn new() -> Self {
303 info!("Initialized custom tools registry");
304
305 Self {
306 tools: Arc::new(RwLock::new(HashMap::new())),
307 execution_history: Arc::new(RwLock::new(Vec::new())),
308 }
309 }
310
311 pub async fn register_tool(&self, tool: Arc<dyn CustomTool>) -> Result<()> {
313 let definition = tool.definition();
314 info!("Registering custom tool: {}", definition.id);
315
316 let mut tools = self.tools.write().await;
317 if tools.contains_key(&definition.id) {
318 warn!("Tool {} already exists, replacing", definition.id);
319 }
320
321 tools.insert(definition.id.clone(), tool);
322
323 Ok(())
324 }
325
326 pub async fn get_tool(&self, tool_id: &str) -> Option<Arc<dyn CustomTool>> {
328 let tools = self.tools.read().await;
329 tools.get(tool_id).cloned()
330 }
331
332 pub async fn list_tools(&self) -> Vec<ToolDefinition> {
334 let tools = self.tools.read().await;
335 tools.values().map(|t| t.definition()).collect()
336 }
337
338 pub async fn list_tools_by_category(&self, category: ToolCategory) -> Vec<ToolDefinition> {
340 let tools = self.tools.read().await;
341 tools
342 .values()
343 .map(|t| t.definition())
344 .filter(|d| d.category == category)
345 .collect()
346 }
347
348 pub async fn search_by_tag(&self, tag: &str) -> Vec<ToolDefinition> {
350 let tools = self.tools.read().await;
351 tools
352 .values()
353 .map(|t| t.definition())
354 .filter(|d| d.tags.iter().any(|t| t == tag))
355 .collect()
356 }
357
358 pub async fn execute_tool(
360 &self,
361 tool_id: &str,
362 parameters: HashMap<String, JsonValue>,
363 ) -> Result<ToolResult> {
364 debug!(
365 "Executing tool: {} with parameters: {:?}",
366 tool_id, parameters
367 );
368
369 let tool = self
370 .get_tool(tool_id)
371 .await
372 .ok_or_else(|| anyhow!("Tool not found: {}", tool_id))?;
373
374 tool.validate(¶meters)?;
376
377 let start_time = std::time::Instant::now();
379 let result = tool.execute(parameters.clone()).await?;
380
381 let execution = ToolExecution {
383 tool_id: tool_id.to_string(),
384 timestamp: chrono::Utc::now(),
385 parameters,
386 result: result.clone(),
387 };
388
389 let mut history = self.execution_history.write().await;
390 history.push(execution);
391
392 if history.len() > 1000 {
394 history.drain(0..500);
395 }
396
397 debug!(
398 "Tool execution completed in {}ms",
399 start_time.elapsed().as_millis()
400 );
401
402 Ok(result)
403 }
404
405 pub async fn unregister_tool(&self, tool_id: &str) -> Result<()> {
407 let mut tools = self.tools.write().await;
408
409 if tools.remove(tool_id).is_none() {
410 return Err(anyhow!("Tool not found: {}", tool_id));
411 }
412
413 info!("Unregistered tool: {}", tool_id);
414 Ok(())
415 }
416
417 pub async fn get_execution_history(&self, tool_id: &str) -> Vec<ToolExecution> {
419 let history = self.execution_history.read().await;
420 history
421 .iter()
422 .filter(|e| e.tool_id == tool_id)
423 .cloned()
424 .collect()
425 }
426
427 pub async fn get_statistics(&self) -> ToolStatistics {
429 let tools = self.tools.read().await;
430 let history = self.execution_history.read().await;
431
432 let total_tools = tools.len();
433 let total_executions = history.len();
434
435 let mut execution_counts = HashMap::new();
436 let mut success_counts = HashMap::new();
437
438 for execution in history.iter() {
439 *execution_counts
440 .entry(execution.tool_id.clone())
441 .or_insert(0) += 1;
442
443 if execution.result.success {
444 *success_counts.entry(execution.tool_id.clone()).or_insert(0) += 1;
445 }
446 }
447
448 ToolStatistics {
449 total_tools,
450 total_executions,
451 execution_counts,
452 success_counts,
453 }
454 }
455}
456
457impl Default for CustomToolsRegistry {
458 fn default() -> Self {
459 Self::new()
460 }
461}
462
463#[derive(Debug, Clone, Serialize, Deserialize)]
465pub struct ToolStatistics {
466 pub total_tools: usize,
468 pub total_executions: usize,
470 pub execution_counts: HashMap<String, usize>,
472 pub success_counts: HashMap<String, usize>,
474}
475
476pub struct EchoTool;
478
479#[async_trait]
480impl CustomTool for EchoTool {
481 fn definition(&self) -> ToolDefinition {
482 ToolDefinition {
483 id: "echo".to_string(),
484 name: "Echo Tool".to_string(),
485 description: "Simple echo tool that returns the input message".to_string(),
486 parameters: vec![ToolParameter {
487 name: "message".to_string(),
488 description: "Message to echo".to_string(),
489 param_type: ParameterType::String,
490 required: true,
491 default_value: None,
492 constraints: None,
493 }],
494 category: ToolCategory::Utility,
495 is_async: false,
496 tags: vec!["utility".to_string(), "test".to_string()],
497 examples: vec![ToolExample {
498 description: "Echo hello world".to_string(),
499 input: {
500 let mut map = HashMap::new();
501 map.insert(
502 "message".to_string(),
503 JsonValue::String("hello".to_string()),
504 );
505 map
506 },
507 output: JsonValue::String("hello".to_string()),
508 }],
509 }
510 }
511
512 async fn execute(&self, parameters: HashMap<String, JsonValue>) -> Result<ToolResult> {
513 let start_time = std::time::Instant::now();
514
515 let message = parameters
516 .get("message")
517 .and_then(|v| v.as_str())
518 .ok_or_else(|| anyhow!("Missing message parameter"))?;
519
520 Ok(ToolResult {
521 success: true,
522 data: JsonValue::String(message.to_string()),
523 error: None,
524 execution_time_ms: start_time.elapsed().as_millis() as u64,
525 metadata: HashMap::new(),
526 })
527 }
528}
529
530#[cfg(test)]
531mod tests {
532 use super::*;
533
534 #[tokio::test]
535 async fn test_registry_creation() {
536 let registry = CustomToolsRegistry::new();
537 let tools = registry.list_tools().await;
538 assert_eq!(tools.len(), 0);
539 }
540
541 #[tokio::test]
542 async fn test_register_and_execute_tool() {
543 let registry = CustomToolsRegistry::new();
544 let echo_tool = Arc::new(EchoTool);
545
546 registry
547 .register_tool(echo_tool)
548 .await
549 .expect("should succeed");
550
551 let mut params = HashMap::new();
552 params.insert("message".to_string(), JsonValue::String("test".to_string()));
553
554 let result = registry
555 .execute_tool("echo", params)
556 .await
557 .expect("should succeed");
558
559 assert!(result.success);
560 assert_eq!(result.data, JsonValue::String("test".to_string()));
561 }
562
563 #[tokio::test]
564 async fn test_list_tools() {
565 let registry = CustomToolsRegistry::new();
566 let echo_tool = Arc::new(EchoTool);
567
568 registry
569 .register_tool(echo_tool)
570 .await
571 .expect("should succeed");
572
573 let tools = registry.list_tools().await;
574 assert_eq!(tools.len(), 1);
575 assert_eq!(tools[0].id, "echo");
576 }
577
578 #[tokio::test]
579 async fn test_parameter_validation() {
580 let registry = CustomToolsRegistry::new();
581 let echo_tool = Arc::new(EchoTool);
582
583 registry
584 .register_tool(echo_tool)
585 .await
586 .expect("should succeed");
587
588 let params = HashMap::new();
590 let result = registry.execute_tool("echo", params).await;
591 assert!(result.is_err());
592 }
593
594 #[tokio::test]
595 async fn test_statistics() {
596 let registry = CustomToolsRegistry::new();
597 let echo_tool = Arc::new(EchoTool);
598
599 registry
600 .register_tool(echo_tool)
601 .await
602 .expect("should succeed");
603
604 let mut params = HashMap::new();
605 params.insert("message".to_string(), JsonValue::String("test".to_string()));
606
607 for _ in 0..5 {
609 let _ = registry.execute_tool("echo", params.clone()).await;
610 }
611
612 let stats = registry.get_statistics().await;
613 assert_eq!(stats.total_tools, 1);
614 assert_eq!(stats.total_executions, 5);
615 }
616}