Skip to main content

codive_core/
tool.rs

1//! Tool trait and registry for the Agent system
2//!
3//! This module defines the [`Tool`] trait that all tools must implement,
4//! and the [`ToolRegistry`] for managing available tools.
5//!
6//! # Architecture
7//!
8//! Tools are the primary way the agent interacts with the outside world:
9//! - Reading/writing files
10//! - Executing commands
11//! - Making web requests
12//! - etc.
13//!
14//! Each tool has:
15//! - A unique name
16//! - A description (shown to the LLM)
17//! - A JSON Schema for parameters
18//! - An async execute method
19//!
20//! # Example
21//!
22//! ```rust,ignore
23//! use codive_core::tool::{Tool, ToolOutput};
24//! use async_trait::async_trait;
25//!
26//! struct EchoTool;
27//!
28//! #[async_trait]
29//! impl Tool for EchoTool {
30//!     fn name(&self) -> &str { "echo" }
31//!     fn description(&self) -> &str { "Echoes back the input" }
32//!     fn parameters_schema(&self) -> serde_json::Value {
33//!         serde_json::json!({
34//!             "type": "object",
35//!             "properties": {
36//!                 "message": { "type": "string" }
37//!             },
38//!             "required": ["message"]
39//!         })
40//!     }
41//!     async fn execute(&self, params: serde_json::Value) -> ToolOutput {
42//!         let message = params["message"].as_str().unwrap_or("no message");
43//!         ToolOutput::success(message)
44//!     }
45//! }
46//! ```
47
48use codive_prompts::PromptStore;
49use async_trait::async_trait;
50use serde::{Deserialize, Serialize};
51use std::collections::HashMap;
52use std::sync::Arc;
53
54// ============================================================================
55// ToolOutput
56// ============================================================================
57
58/// Metadata about a file change from a tool execution
59///
60/// This is used by write/edit tools to capture the before/after state
61/// of files they modify, enabling diff display in the TUI.
62#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
63pub struct FileChangeMetadata {
64    /// Path to the modified file
65    pub file_path: String,
66    /// Content before the change (None for new files)
67    pub old_content: Option<String>,
68    /// Content after the change
69    pub new_content: String,
70}
71
72/// The output of a tool execution
73///
74/// Tools return this to indicate success or failure. The output is
75/// always a string that will be sent back to the LLM.
76#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
77pub struct ToolOutput {
78    /// The output content (success message or error details)
79    pub content: String,
80    /// Whether the execution was successful
81    pub is_error: bool,
82    /// Optional metadata about file changes (for diff display)
83    #[serde(default, skip_serializing_if = "Option::is_none")]
84    pub file_change: Option<FileChangeMetadata>,
85}
86
87impl ToolOutput {
88    /// Create a successful tool output
89    pub fn success(content: impl Into<String>) -> Self {
90        Self {
91            content: content.into(),
92            is_error: false,
93            file_change: None,
94        }
95    }
96
97    /// Create an error tool output
98    pub fn error(content: impl Into<String>) -> Self {
99        Self {
100            content: content.into(),
101            is_error: true,
102            file_change: None,
103        }
104    }
105
106    /// Check if this output represents a successful execution
107    pub fn is_success(&self) -> bool {
108        !self.is_error
109    }
110
111    /// Attach file change metadata to the output (builder pattern)
112    pub fn with_file_change(
113        mut self,
114        file_path: impl Into<String>,
115        old_content: Option<String>,
116        new_content: impl Into<String>,
117    ) -> Self {
118        self.file_change = Some(FileChangeMetadata {
119            file_path: file_path.into(),
120            old_content,
121            new_content: new_content.into(),
122        });
123        self
124    }
125}
126
127// ============================================================================
128// Tool Trait
129// ============================================================================
130
131/// A tool that can be executed by the agent
132///
133/// Tools are the primary way the agent interacts with the outside world.
134/// Each tool must be:
135/// - `Send` - Can be transferred between threads
136/// - `Sync` - Can be shared between threads
137///
138/// # Implementing a Tool
139///
140/// 1. Define a struct for your tool
141/// 2. Implement the `Tool` trait
142/// 3. Register it with `ToolRegistry`
143///
144/// # Thread Safety
145///
146/// The `Send + Sync` bounds are required because:
147/// - Tools may be called from different async tasks
148/// - The registry holds tools as `Arc<dyn Tool>`
149/// - Multiple requests may use the same tool concurrently
150#[async_trait]
151pub trait Tool: Send + Sync {
152    /// The unique name of this tool
153    ///
154    /// This is used by the LLM to call the tool and must be unique
155    /// within a registry.
156    fn name(&self) -> &str;
157
158    /// A human-readable description of what this tool does
159    ///
160    /// This is shown to the LLM to help it decide when to use the tool.
161    /// Be clear and concise about the tool's purpose and capabilities.
162    fn description(&self) -> &str;
163
164    /// JSON Schema describing the tool's parameters
165    ///
166    /// This schema is sent to the LLM so it knows what parameters
167    /// to provide. Use standard JSON Schema format.
168    ///
169    /// # Example
170    ///
171    /// ```json
172    /// {
173    ///   "type": "object",
174    ///   "properties": {
175    ///     "path": {
176    ///       "type": "string",
177    ///       "description": "The file path to read"
178    ///     }
179    ///   },
180    ///   "required": ["path"]
181    /// }
182    /// ```
183    fn parameters_schema(&self) -> serde_json::Value;
184
185    /// Execute the tool with the given parameters
186    ///
187    /// Parameters are passed as a JSON value matching the schema
188    /// returned by `parameters_schema()`.
189    ///
190    /// # Returns
191    ///
192    /// A `ToolOutput` indicating success or failure with a message.
193    async fn execute(&self, params: serde_json::Value) -> ToolOutput;
194}
195
196// ============================================================================
197// ToolInfo
198// ============================================================================
199
200/// Static information about a tool (for serialization to LLM)
201///
202/// This struct contains just the metadata needed to tell the LLM
203/// about available tools. It's separate from `Tool` because it
204/// can be serialized.
205#[derive(Debug, Clone, Serialize, Deserialize)]
206pub struct ToolInfo {
207    /// The tool's name
208    pub name: String,
209    /// The tool's description
210    pub description: String,
211    /// JSON Schema for parameters
212    pub parameters: serde_json::Value,
213}
214
215impl ToolInfo {
216    /// Create ToolInfo from a Tool implementation
217    pub fn from_tool(tool: &dyn Tool) -> Self {
218        Self {
219            name: tool.name().to_string(),
220            description: tool.description().to_string(),
221            parameters: tool.parameters_schema(),
222        }
223    }
224}
225
226// ============================================================================
227// ToolRegistry
228// ============================================================================
229
230/// A registry of available tools
231///
232/// The registry stores tools and provides lookup by name.
233/// Tools are stored as `Arc<dyn Tool>` to allow sharing.
234///
235/// # Thread Safety
236///
237/// The registry uses `Arc` for thread-safe sharing of tools.
238/// Multiple async tasks can look up and execute tools concurrently.
239///
240/// # Example
241///
242/// ```rust,ignore
243/// let mut registry = ToolRegistry::new();
244/// registry.register(Arc::new(MyTool));
245///
246/// if let Some(tool) = registry.get("my_tool") {
247///     let output = tool.execute(params).await;
248/// }
249/// ```
250#[derive(Default)]
251pub struct ToolRegistry {
252    tools: HashMap<String, Arc<dyn Tool>>,
253}
254
255impl ToolRegistry {
256    /// Create a new empty registry
257    pub fn new() -> Self {
258        Self {
259            tools: HashMap::new(),
260        }
261    }
262
263    /// Register a tool
264    ///
265    /// If a tool with the same name already exists, it will be replaced.
266    pub fn register(&mut self, tool: Arc<dyn Tool>) {
267        let name = tool.name().to_string();
268        self.tools.insert(name, tool);
269    }
270
271    /// Get a tool by name
272    ///
273    /// Returns `None` if no tool with that name is registered.
274    pub fn get(&self, name: &str) -> Option<Arc<dyn Tool>> {
275        self.tools.get(name).cloned()
276    }
277
278    /// Check if a tool is registered
279    pub fn contains(&self, name: &str) -> bool {
280        self.tools.contains_key(name)
281    }
282
283    /// Get the number of registered tools
284    pub fn len(&self) -> usize {
285        self.tools.len()
286    }
287
288    /// Check if the registry is empty
289    pub fn is_empty(&self) -> bool {
290        self.tools.is_empty()
291    }
292
293    /// Get info for all registered tools
294    ///
295    /// Returns a vector of `ToolInfo` suitable for sending to an LLM.
296    pub fn tool_infos(&self) -> Vec<ToolInfo> {
297        self.tools
298            .values()
299            .map(|tool| ToolInfo::from_tool(tool.as_ref()))
300            .collect()
301    }
302
303    /// Get info for all registered tools with descriptions from PromptStore
304    ///
305    /// This allows tool descriptions to be overridden via the prompt configuration.
306    /// If a tool has an override in the PromptStore, that description is used;
307    /// otherwise, falls back to the tool's built-in description.
308    pub fn tool_infos_with_store(&self, store: &PromptStore) -> Vec<ToolInfo> {
309        self.tools
310            .values()
311            .map(|tool| {
312                let description = store
313                    .tool(tool.name())
314                    .unwrap_or_else(|| tool.description())
315                    .to_string();
316
317                ToolInfo {
318                    name: tool.name().to_string(),
319                    description,
320                    parameters: tool.parameters_schema(),
321                }
322            })
323            .collect()
324    }
325
326    /// Get the names of all registered tools
327    pub fn names(&self) -> Vec<&str> {
328        self.tools.keys().map(|s| s.as_str()).collect()
329    }
330
331    /// Remove a tool by name
332    ///
333    /// Returns the removed tool if it existed.
334    pub fn unregister(&mut self, name: &str) -> Option<Arc<dyn Tool>> {
335        self.tools.remove(name)
336    }
337}
338
339// Allow debug printing of the registry
340impl std::fmt::Debug for ToolRegistry {
341    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
342        f.debug_struct("ToolRegistry")
343            .field("tools", &self.names())
344            .finish()
345    }
346}
347
348// ============================================================================
349// RUST CONCEPTS EXPLAINED (for learning)
350// ============================================================================
351//
352// 1. `#[async_trait]`
353//    - Rust doesn't natively support async fn in traits (yet - it's coming!)
354//    - `async_trait` macro transforms async fns into boxed futures
355//    - This has a small runtime cost but enables async traits
356//
357// 2. `Send + Sync` bounds
358//    - `Send` = safe to transfer between threads
359//    - `Sync` = safe to share references between threads
360//    - Required for tools that may be called from different async tasks
361//    - Most types are Send + Sync by default
362//
363// 3. `dyn Tool`
364//    - "Dynamic dispatch" - the concrete type is determined at runtime
365//    - Contrast with generics (static dispatch, type known at compile time)
366//    - Allows storing different tool types in the same HashMap
367//
368// 4. `Arc<dyn Tool>`
369//    - `Arc` = Atomic Reference Counted pointer (thread-safe)
370//    - Allows multiple owners of the same tool
371//    - When last Arc is dropped, the tool is deallocated
372//
373// 5. `HashMap<String, Arc<dyn Tool>>`
374//    - Tools indexed by name for O(1) lookup
375//    - `Arc<dyn Tool>` allows storing any type implementing Tool
376//
377// 6. Why `&str` in trait vs `String` in ToolInfo?
378//    - Trait returns `&str` - avoids allocation, caller can convert if needed
379//    - ToolInfo stores `String` - owns its data for serialization
380//
381// 7. `impl Trait` vs generics
382//    - `impl Into<String>` - accepts anything convertible to String
383//    - More flexible API: can pass &str, String, Cow<str>, etc.
384//
385// **📚 Read:**
386// - [Rust Book Ch 10.2 - Traits](https://doc.rust-lang.org/book/ch10-02-traits.html)
387// - [Rust Book Ch 17.2 - Trait Objects](https://doc.rust-lang.org/book/ch17-02-trait-objects.html)
388// - [Async Book Ch 4 - Pinning](https://rust-lang.github.io/async-book/04_pinning/01_chapter.html)
389
390// ============================================================================
391// Tests
392// ============================================================================
393
394#[cfg(test)]
395mod tests {
396    use super::*;
397
398    // A simple test tool for unit tests
399    struct TestTool {
400        name: String,
401    }
402
403    impl TestTool {
404        fn new(name: impl Into<String>) -> Self {
405            Self { name: name.into() }
406        }
407    }
408
409    #[async_trait]
410    impl Tool for TestTool {
411        fn name(&self) -> &str {
412            &self.name
413        }
414
415        fn description(&self) -> &str {
416            "A test tool for unit tests"
417        }
418
419        fn parameters_schema(&self) -> serde_json::Value {
420            serde_json::json!({
421                "type": "object",
422                "properties": {
423                    "input": { "type": "string" }
424                }
425            })
426        }
427
428        async fn execute(&self, params: serde_json::Value) -> ToolOutput {
429            let input = params
430                .get("input")
431                .and_then(|v| v.as_str())
432                .unwrap_or("default");
433            ToolOutput::success(format!("Processed: {}", input))
434        }
435    }
436
437    #[test]
438    fn test_tool_output_success() {
439        let output = ToolOutput::success("done");
440        assert!(output.is_success());
441        assert!(!output.is_error);
442        assert_eq!(output.content, "done");
443    }
444
445    #[test]
446    fn test_tool_output_error() {
447        let output = ToolOutput::error("failed");
448        assert!(!output.is_success());
449        assert!(output.is_error);
450        assert_eq!(output.content, "failed");
451    }
452
453    #[test]
454    fn test_registry_register_and_get() {
455        let mut registry = ToolRegistry::new();
456        assert!(registry.is_empty());
457
458        registry.register(Arc::new(TestTool::new("test")));
459        assert!(!registry.is_empty());
460        assert_eq!(registry.len(), 1);
461        assert!(registry.contains("test"));
462
463        let tool = registry.get("test").unwrap();
464        assert_eq!(tool.name(), "test");
465    }
466
467    #[test]
468    fn test_registry_get_nonexistent() {
469        let registry = ToolRegistry::new();
470        assert!(registry.get("nonexistent").is_none());
471    }
472
473    #[test]
474    fn test_registry_multiple_tools() {
475        let mut registry = ToolRegistry::new();
476        registry.register(Arc::new(TestTool::new("tool1")));
477        registry.register(Arc::new(TestTool::new("tool2")));
478        registry.register(Arc::new(TestTool::new("tool3")));
479
480        assert_eq!(registry.len(), 3);
481        assert!(registry.contains("tool1"));
482        assert!(registry.contains("tool2"));
483        assert!(registry.contains("tool3"));
484    }
485
486    #[test]
487    fn test_registry_replace_tool() {
488        let mut registry = ToolRegistry::new();
489        registry.register(Arc::new(TestTool::new("test")));
490        registry.register(Arc::new(TestTool::new("test"))); // Same name
491
492        // Should still have just one tool
493        assert_eq!(registry.len(), 1);
494    }
495
496    #[test]
497    fn test_registry_unregister() {
498        let mut registry = ToolRegistry::new();
499        registry.register(Arc::new(TestTool::new("test")));
500        assert!(registry.contains("test"));
501
502        let removed = registry.unregister("test");
503        assert!(removed.is_some());
504        assert!(!registry.contains("test"));
505        assert!(registry.is_empty());
506    }
507
508    #[test]
509    fn test_registry_names() {
510        let mut registry = ToolRegistry::new();
511        registry.register(Arc::new(TestTool::new("alpha")));
512        registry.register(Arc::new(TestTool::new("beta")));
513
514        let mut names = registry.names();
515        names.sort();
516        assert_eq!(names, vec!["alpha", "beta"]);
517    }
518
519    #[test]
520    fn test_tool_info_from_tool() {
521        let tool = TestTool::new("my_tool");
522        let info = ToolInfo::from_tool(&tool);
523
524        assert_eq!(info.name, "my_tool");
525        assert_eq!(info.description, "A test tool for unit tests");
526        assert!(info.parameters.is_object());
527    }
528
529    #[test]
530    fn test_registry_tool_infos() {
531        let mut registry = ToolRegistry::new();
532        registry.register(Arc::new(TestTool::new("tool1")));
533        registry.register(Arc::new(TestTool::new("tool2")));
534
535        let infos = registry.tool_infos();
536        assert_eq!(infos.len(), 2);
537    }
538
539    #[tokio::test]
540    async fn test_tool_execute() {
541        let tool = TestTool::new("test");
542        let output = tool.execute(serde_json::json!({"input": "hello"})).await;
543
544        assert!(output.is_success());
545        assert_eq!(output.content, "Processed: hello");
546    }
547
548    #[tokio::test]
549    async fn test_tool_execute_via_registry() {
550        let mut registry = ToolRegistry::new();
551        registry.register(Arc::new(TestTool::new("test")));
552
553        let tool = registry.get("test").unwrap();
554        let output = tool.execute(serde_json::json!({"input": "world"})).await;
555
556        assert!(output.is_success());
557        assert_eq!(output.content, "Processed: world");
558    }
559
560    #[test]
561    fn test_registry_debug() {
562        let mut registry = ToolRegistry::new();
563        registry.register(Arc::new(TestTool::new("test")));
564
565        let debug = format!("{:?}", registry);
566        assert!(debug.contains("ToolRegistry"));
567        assert!(debug.contains("test"));
568    }
569}