Overview
Tools implement theTool trait, which defines their interface and execution logic:
Step-by-Step Guide
use anyhow::Result;
use async_trait::async_trait;
use serde_json::{json, Value};
use crate::tools::traits::{Tool, ToolResult};
/// A tool that fetches URLs and returns HTTP status
pub struct HttpGetTool;
#[async_trait]
impl Tool for HttpGetTool {
fn name(&self) -> &str {
"http_get"
}
fn description(&self) -> &str {
"Fetch a URL and return the HTTP status code and content length"
}
fn parameters_schema(&self) -> Value {
json!({
"type": "object",
"properties": {
"url": {
"type": "string",
"description": "URL to fetch"
}
},
"required": ["url"]
})
}
}
async fn execute(&self, args: Value) -> Result<ToolResult> {
// Extract and validate parameters
let url = args["url"]
.as_str()
.ok_or_else(|| anyhow::anyhow!("Missing 'url' parameter"))?;
// Execute the tool logic
match reqwest::get(url).await {
Ok(resp) => {
let status = resp.status().as_u16();
let len = resp.content_length().unwrap_or(0);
Ok(ToolResult {
success: status < 400,
output: format!("HTTP {status} — {len} bytes"),
error: None,
})
}
Err(e) => Ok(ToolResult {
success: false,
output: String::new(),
error: Some(format!("Request failed: {e}"))
}),
}
}
pub fn default_tools() -> Vec<Box<dyn Tool>> {
vec![
Box::new(ShellTool),
Box::new(FileReadTool),
Box::new(HttpGetTool), // Your new tool
// ... other tools
]
}
Complete Example
Here’s the full implementation fromexamples/custom_tool.rs:
Advanced Patterns
Stateful Tools
Tools with internal state:Parameter Validation
Strict parameter checking:Security Guards
Enforce security policies:Best Practices
Return structured results
Return structured results
Always use
ToolResult with clear success/failure indicators:Validate all inputs
Validate all inputs
Never trust LLM-generated parameters:
Keep execution time bounded
Keep execution time bounded
Implement timeouts for long-running operations:
Document parameters clearly
Document parameters clearly
Use descriptive parameter schemas:
Never log sensitive data
Never log sensitive data
Redact credentials and secrets:
Next Steps
Peripherals
Control hardware with peripheral tools
Custom Memory
Implement custom memory backends