claude-agent 0.2.25

Rust SDK for building AI agents with Anthropic's Claude - Direct API, no CLI dependency
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
//! Grep tool - content search with regex using ripgrep.

use std::process::Stdio;

use async_trait::async_trait;
use schemars::JsonSchema;
use serde::Deserialize;
use tokio::process::Command;

use super::SchemaTool;
use super::context::ExecutionContext;
use crate::types::ToolResult;

#[derive(Debug, Deserialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct GrepInput {
    /// The regular expression pattern to search for in file contents
    pub pattern: String,
    /// File or directory to search in (rg PATH). Defaults to current working directory.
    #[serde(default)]
    pub path: Option<String>,
    /// Glob pattern to filter files (e.g. "*.js", "*.{ts,tsx}") - maps to rg --glob
    #[serde(default)]
    pub glob: Option<String>,
    /// File type to search (rg --type). Common types: js, py, rust, go, java, etc.
    #[serde(default, rename = "type")]
    pub file_type: Option<String>,
    /// Output mode: "files_with_matches" shows only file paths (default), "content" shows matching lines, "count" shows match counts
    #[serde(default)]
    pub output_mode: Option<String>,
    /// Case insensitive search (rg -i)
    #[serde(default, rename = "-i")]
    pub case_insensitive: Option<bool>,
    /// Show line numbers in output (rg -n). Requires output_mode: "content". Defaults to true.
    #[serde(default, rename = "-n")]
    pub line_numbers: Option<bool>,
    /// Number of lines to show after each match (rg -A). Requires output_mode: "content".
    #[serde(default, rename = "-A")]
    pub after_context: Option<u32>,
    /// Number of lines to show before each match (rg -B). Requires output_mode: "content".
    #[serde(default, rename = "-B")]
    pub before_context: Option<u32>,
    /// Number of lines to show before and after each match (rg -C). Requires output_mode: "content".
    #[serde(default, rename = "-C")]
    pub context: Option<u32>,
    /// Enable multiline mode where . matches newlines and patterns can span lines (rg -U --multiline-dotall). Default: false.
    #[serde(default)]
    pub multiline: Option<bool>,
    /// Limit output to first N lines/entries. Works across all output modes. Defaults to 0 (unlimited).
    #[serde(default)]
    pub head_limit: Option<usize>,
    /// Skip first N lines/entries before applying head_limit. Works across all output modes. Defaults to 0.
    #[serde(default)]
    pub offset: Option<usize>,
}

#[derive(Debug, Clone, Copy, Default)]
pub struct GrepTool;

#[async_trait]
impl SchemaTool for GrepTool {
    type Input = GrepInput;

    const NAME: &'static str = "Grep";
    const DESCRIPTION: &'static str = r#"A powerful search tool built on ripgrep

  Usage:
  - ALWAYS use Grep for search tasks. NEVER invoke `grep` or `rg` as a Bash command. The Grep tool has been optimized for correct permissions and access.
  - Supports full regex syntax (e.g., "log.*Error", "function\s+\w+")
  - Filter files with glob parameter (e.g., "*.js", "**/*.tsx") or type parameter (e.g., "js", "py", "rust")
  - Output modes: "content" shows matching lines, "files_with_matches" shows only file paths (default), "count" shows match counts
  - Use Task tool for open-ended searches requiring multiple rounds
  - Pattern syntax: Uses ripgrep (not grep) - literal braces need escaping (use `interface\{\}` to find `interface{}` in Go code)
  - Multiline matching: By default patterns match within single lines only. For cross-line patterns like `struct \{[\s\S]*?field`, use `multiline: true`"#;

    async fn handle(&self, input: GrepInput, context: &ExecutionContext) -> ToolResult {
        let search_path = match context.try_resolve_or_root_for(Self::NAME, input.path.as_deref()) {
            Ok(path) => path,
            Err(e) => return e,
        };

        let mut cmd = Command::new("rg");

        match input.output_mode.as_deref() {
            Some("content") => {
                if input.line_numbers.unwrap_or(true) {
                    cmd.arg("-n");
                }
            }
            Some("files_with_matches") | None => {
                cmd.arg("-l");
            }
            Some("count") => {
                cmd.arg("-c");
            }
            Some(mode) => {
                return ToolResult::error(format!("Unknown output_mode: {}", mode));
            }
        }

        if input.case_insensitive.unwrap_or(false) {
            cmd.arg("-i");
        }

        if let Some(c) = input.context {
            cmd.arg("-C").arg(c.to_string());
        } else {
            if let Some(a) = input.after_context {
                cmd.arg("-A").arg(a.to_string());
            }
            if let Some(b) = input.before_context {
                cmd.arg("-B").arg(b.to_string());
            }
        }

        if let Some(t) = &input.file_type {
            cmd.arg("-t").arg(t);
        }

        if let Some(g) = &input.glob {
            cmd.arg("-g").arg(g);
        }

        if input.multiline.unwrap_or(false) {
            cmd.arg("-U").arg("--multiline-dotall");
        }

        cmd.arg(&input.pattern);
        cmd.arg(&search_path);
        cmd.stdout(Stdio::piped());
        cmd.stderr(Stdio::piped());

        let output = match cmd.output().await {
            Ok(o) => o,
            Err(e) => {
                return ToolResult::error(format!(
                    "Failed to execute ripgrep (is rg installed?): {}",
                    e
                ));
            }
        };

        let stdout = String::from_utf8_lossy(&output.stdout);
        let stderr = String::from_utf8_lossy(&output.stderr);

        if !output.status.success() && !stderr.is_empty() {
            return ToolResult::error(format!("Ripgrep error: {}", stderr));
        }

        if stdout.is_empty() {
            return ToolResult::success("No matches found");
        }

        let result = apply_pagination(&stdout, input.offset, input.head_limit);
        ToolResult::success(result)
    }
}

fn apply_pagination(content: &str, offset: Option<usize>, limit: Option<usize>) -> String {
    let offset = offset.unwrap_or(0);
    match limit {
        Some(limit) => content
            .lines()
            .skip(offset)
            .take(limit)
            .collect::<Vec<_>>()
            .join("\n"),
        None if offset > 0 => content.lines().skip(offset).collect::<Vec<_>>().join("\n"),
        None => content.to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tools::Tool;
    use tempfile::tempdir;
    use tokio::fs;

    #[test]
    fn test_grep_input_parsing() {
        let input: GrepInput = serde_json::from_value(serde_json::json!({
            "pattern": "test",
            "-i": true
        }))
        .unwrap();

        assert_eq!(input.pattern, "test");
        assert_eq!(input.case_insensitive, Some(true));
    }

    #[test]
    fn test_grep_input_all_options() {
        let input: GrepInput = serde_json::from_value(serde_json::json!({
            "pattern": "fn main",
            "path": "src",
            "glob": "*.rs",
            "type": "rust",
            "output_mode": "content",
            "-i": false,
            "-n": true,
            "-A": 2,
            "-B": 1,
            "-C": 3
        }))
        .unwrap();

        assert_eq!(input.pattern, "fn main");
        assert_eq!(input.path, Some("src".to_string()));
        assert_eq!(input.glob, Some("*.rs".to_string()));
        assert_eq!(input.file_type, Some("rust".to_string()));
        assert_eq!(input.output_mode, Some("content".to_string()));
        assert_eq!(input.case_insensitive, Some(false));
        assert_eq!(input.line_numbers, Some(true));
        assert_eq!(input.after_context, Some(2));
        assert_eq!(input.before_context, Some(1));
        assert_eq!(input.context, Some(3));
    }

    #[tokio::test]
    async fn test_grep_basic_search() {
        let dir = tempdir().unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();

        fs::write(
            root.join("test.rs"),
            "fn main() {\n    println!(\"hello\");\n}",
        )
        .await
        .unwrap();
        fs::write(root.join("lib.rs"), "pub fn helper() {}")
            .await
            .unwrap();

        let test_context = super::super::context::ExecutionContext::from_path(&root).unwrap();
        let tool = GrepTool;

        // Default output_mode is now files_with_matches, so it returns file paths
        let result = tool
            .execute(serde_json::json!({"pattern": "fn main"}), &test_context)
            .await;

        match &result.output {
            crate::types::ToolOutput::Success(content) => {
                assert!(content.contains("test.rs"));
            }
            crate::types::ToolOutput::Error(e) => {
                let error_message = e.to_string();
                if error_message.contains("is rg installed") {
                    return;
                }
                panic!("Unexpected error: {}", error_message);
            }
            _ => {}
        }
    }

    #[tokio::test]
    async fn test_grep_no_matches() {
        let dir = tempdir().unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();

        fs::write(root.join("test.txt"), "hello world")
            .await
            .unwrap();

        let test_context = super::super::context::ExecutionContext::from_path(&root).unwrap();
        let tool = GrepTool;

        let result = tool
            .execute(
                serde_json::json!({"pattern": "nonexistent_pattern_xyz"}),
                &test_context,
            )
            .await;

        match &result.output {
            crate::types::ToolOutput::Success(content) => {
                assert!(content.contains("No matches"));
            }
            crate::types::ToolOutput::Error(e) => {
                let error_message = e.to_string();
                if error_message.contains("is rg installed") {
                    return;
                }
                panic!("Unexpected error: {}", error_message);
            }
            _ => {}
        }
    }

    #[tokio::test]
    async fn test_grep_case_insensitive() {
        let dir = tempdir().unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();

        fs::write(root.join("test.txt"), "Hello World\nHELLO WORLD")
            .await
            .unwrap();

        let test_context = super::super::context::ExecutionContext::from_path(&root).unwrap();
        let tool = GrepTool;

        let result = tool
            .execute(
                serde_json::json!({"pattern": "hello", "-i": true, "output_mode": "content"}),
                &test_context,
            )
            .await;

        match &result.output {
            crate::types::ToolOutput::Success(content) => {
                assert!(content.contains("Hello") || content.contains("HELLO"));
            }
            crate::types::ToolOutput::Error(e) => {
                let error_message = e.to_string();
                if error_message.contains("is rg installed") {
                    return;
                }
                panic!("Unexpected error: {}", error_message);
            }
            _ => {}
        }
    }

    #[tokio::test]
    async fn test_grep_files_with_matches_mode() {
        let dir = tempdir().unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();

        fs::write(root.join("a.txt"), "pattern here").await.unwrap();
        fs::write(root.join("b.txt"), "no match").await.unwrap();

        let test_context = super::super::context::ExecutionContext::from_path(&root).unwrap();
        let tool = GrepTool;

        let result = tool
            .execute(
                serde_json::json!({"pattern": "pattern", "output_mode": "files_with_matches"}),
                &test_context,
            )
            .await;

        match &result.output {
            crate::types::ToolOutput::Success(content) => {
                assert!(content.contains("a.txt"));
                assert!(!content.contains("b.txt"));
            }
            crate::types::ToolOutput::Error(e) => {
                let error_message = e.to_string();
                if error_message.contains("is rg installed") {
                    return;
                }
                panic!("Unexpected error: {}", error_message);
            }
            _ => {}
        }
    }

    #[tokio::test]
    async fn test_grep_count_mode() {
        let dir = tempdir().unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();

        fs::write(root.join("test.txt"), "line1\nline2\nline3")
            .await
            .unwrap();

        let test_context = super::super::context::ExecutionContext::from_path(&root).unwrap();
        let tool = GrepTool;

        let result = tool
            .execute(
                serde_json::json!({"pattern": "line", "output_mode": "count"}),
                &test_context,
            )
            .await;

        match &result.output {
            crate::types::ToolOutput::Success(content) => {
                assert!(content.contains("3") || content.contains(":3"));
            }
            crate::types::ToolOutput::Error(e) => {
                let error_message = e.to_string();
                if error_message.contains("is rg installed") {
                    return;
                }
                panic!("Unexpected error: {}", error_message);
            }
            _ => {}
        }
    }

    #[tokio::test]
    async fn test_grep_invalid_output_mode() {
        let dir = tempdir().unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();

        fs::write(root.join("test.txt"), "content").await.unwrap();

        let test_context = super::super::context::ExecutionContext::from_path(&root).unwrap();
        let tool = GrepTool;

        let result = tool
            .execute(
                serde_json::json!({"pattern": "test", "output_mode": "invalid_mode"}),
                &test_context,
            )
            .await;

        match &result.output {
            crate::types::ToolOutput::Error(e) => {
                assert!(e.to_string().contains("Unknown output_mode"));
            }
            _ => panic!("Expected error for invalid output_mode"),
        }
    }

    #[tokio::test]
    async fn test_grep_with_glob_filter() {
        let dir = tempdir().unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();

        fs::write(root.join("code.rs"), "fn test() {}")
            .await
            .unwrap();
        fs::write(root.join("doc.md"), "fn test() {}")
            .await
            .unwrap();

        let test_context = super::super::context::ExecutionContext::from_path(&root).unwrap();
        let tool = GrepTool;

        let result = tool
            .execute(
                serde_json::json!({"pattern": "fn test", "glob": "*.rs", "output_mode": "files_with_matches"}),
                &test_context,
            )
            .await;

        match &result.output {
            crate::types::ToolOutput::Success(content) => {
                assert!(content.contains("code.rs"));
                assert!(!content.contains("doc.md"));
            }
            crate::types::ToolOutput::Error(e) => {
                let error_message = e.to_string();
                if error_message.contains("is rg installed") {
                    return;
                }
                panic!("Unexpected error: {}", error_message);
            }
            _ => {}
        }
    }
}