adk-tool 0.6.0

Tool system for Rust Agent Development Kit (ADK-Rust) agents (FunctionTool, MCP, Google Search)
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
use adk_core::{AdkError, Result, Tool, ToolContext};
use async_trait::async_trait;
use serde::Deserialize;
use serde_json::{Value, json};
use std::io::{ErrorKind, Write};
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::sync::Arc;

fn invalid_input(message: impl Into<String>) -> AdkError {
    AdkError::tool(message.into())
}

fn resolve_workspace_path(path: &str) -> std::result::Result<PathBuf, String> {
    let raw = Path::new(path);
    let resolved = if raw.is_absolute() {
        raw.to_path_buf()
    } else {
        std::env::current_dir()
            .map_err(|error| format!("failed to resolve current directory: {error}"))?
            .join(raw)
    };
    Ok(resolved)
}

async fn render_view(path: &str, view_range: Option<(u32, u32)>) -> Result<String> {
    if let Some((start, end)) = view_range
        && (start == 0 || end == 0 || start > end)
    {
        return Err(invalid_input("view_range must use positive 1-based line numbers"));
    }

    let resolved = resolve_workspace_path(path).map_err(AdkError::tool)?;
    let metadata = tokio::fs::metadata(&resolved)
        .await
        .map_err(|error| AdkError::tool(format!("failed to inspect '{path}': {error}")))?;

    if metadata.is_dir() {
        let mut entries = tokio::fs::read_dir(&resolved).await.map_err(|error| {
            AdkError::tool(format!("failed to read directory '{path}': {error}"))
        })?;
        let mut listing = String::new();
        while let Some(entry) = entries.next_entry().await.map_err(|error| {
            AdkError::tool(format!("failed to read directory '{path}': {error}"))
        })? {
            let name = entry.file_name();
            listing.push_str(&name.to_string_lossy());
            listing.push('\n');
        }
        return Ok(listing);
    }

    let content = tokio::fs::read_to_string(&resolved)
        .await
        .map_err(|error| AdkError::tool(format!("failed to read '{path}': {error}")))?;

    let lines: Vec<&str> = content.split_terminator('\n').collect();
    let visible = lines
        .iter()
        .enumerate()
        .filter_map(|(index, line)| {
            let line_no = index as u32 + 1;
            view_range
                .map(|(start, end)| (start..=end).contains(&line_no))
                .unwrap_or(true)
                .then_some(*line)
        })
        .collect::<Vec<_>>()
        .join("\n");

    Ok(format!("{visible}\n"))
}

async fn create_file(path: &str, file_text: &str) -> Result<String> {
    let resolved = resolve_workspace_path(path).map_err(AdkError::tool)?;
    if let Some(parent) = resolved.parent() {
        tokio::fs::create_dir_all(parent).await.map_err(|error| {
            AdkError::tool(format!("failed to create parent directories for '{path}': {error}"))
        })?;
    }

    let mut file =
        std::fs::OpenOptions::new().create_new(true).write(true).open(&resolved).map_err(
            |error| match error.kind() {
                ErrorKind::AlreadyExists => AdkError::tool(format!("file '{path}' already exists")),
                _ => AdkError::tool(format!("failed to create '{path}': {error}")),
            },
        )?;
    file.write_all(file_text.as_bytes())
        .map_err(|error| AdkError::tool(format!("failed to write '{path}': {error}")))?;
    Ok("success".to_string())
}

async fn str_replace(path: &str, old_str: &str, new_str: &str) -> Result<String> {
    let resolved = resolve_workspace_path(path).map_err(AdkError::tool)?;
    let content = tokio::fs::read_to_string(&resolved)
        .await
        .map_err(|error| AdkError::tool(format!("failed to read '{path}': {error}")))?;

    let matches = content.matches(old_str).count();
    match matches {
        0 => Err(invalid_input(format!("old_str not found in '{path}'"))),
        1 => {
            let updated = content.replacen(old_str, new_str, 1);
            tokio::fs::write(&resolved, updated)
                .await
                .map_err(|error| AdkError::tool(format!("failed to update '{path}': {error}")))?;
            Ok("success".to_string())
        }
        _ => Err(invalid_input(format!(
            "old_str appears multiple times in '{path}'; use a more specific match"
        ))),
    }
}

async fn insert_text(path: &str, insert_line: u32, insert_text: &str) -> Result<String> {
    if insert_line == 0 {
        return Err(invalid_input("insert_line must be >= 1"));
    }

    let resolved = resolve_workspace_path(path).map_err(AdkError::tool)?;
    let content = tokio::fs::read_to_string(&resolved)
        .await
        .map_err(|error| AdkError::tool(format!("failed to read '{path}': {error}")))?;
    let mut lines = content.split_terminator('\n').map(str::to_string).collect::<Vec<_>>();

    let insert_index = insert_line as usize - 1;
    if insert_index > lines.len() {
        return Err(invalid_input(format!(
            "insert_line {insert_line} is out of range for '{path}'"
        )));
    }

    lines.insert(insert_index, insert_text.to_string());
    let mut updated = lines.join("\n");
    updated.push('\n');
    tokio::fs::write(&resolved, updated)
        .await
        .map_err(|error| AdkError::tool(format!("failed to update '{path}': {error}")))?;
    Ok("success".to_string())
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum BashVersion {
    V20241022,
    V20250124,
}

impl BashVersion {
    fn type_name(self) -> &'static str {
        match self {
            Self::V20241022 => "bash_20241022",
            Self::V20250124 => "bash_20250124",
        }
    }
}

#[derive(Debug, Clone)]
struct AnthropicBashTool {
    version: BashVersion,
}

impl AnthropicBashTool {
    const fn new(version: BashVersion) -> Self {
        Self { version }
    }

    fn declaration_json(&self) -> Value {
        json!({
            "type": self.version.type_name(),
            "name": "bash",
        })
    }
}

#[derive(Debug, Deserialize)]
struct BashArgs {
    command: String,
    #[serde(default)]
    restart: bool,
}

#[async_trait]
impl Tool for AnthropicBashTool {
    fn name(&self) -> &str {
        "bash"
    }

    fn description(&self) -> &str {
        "Executes shell commands for Anthropic's native bash tool."
    }

    fn declaration(&self) -> Value {
        json!({
            "name": self.name(),
            "description": self.description(),
            "x-adk-anthropic-tool": self.declaration_json(),
        })
    }

    async fn execute(&self, _ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
        let args: BashArgs = serde_json::from_value(args)
            .map_err(|error| AdkError::tool(format!("invalid bash arguments: {error}")))?;
        let output = tokio::process::Command::new("sh")
            .arg("-lc")
            .arg(&args.command)
            .stdin(Stdio::null())
            .output()
            .await
            .map_err(|error| AdkError::tool(format!("failed to execute bash command: {error}")))?;

        let stdout = String::from_utf8_lossy(&output.stdout);
        let stderr = String::from_utf8_lossy(&output.stderr);
        let exit_code = output.status.code().unwrap_or(-1);
        let restart_note =
            if args.restart { "bash session restart requested before execution\n" } else { "" };

        Ok(Value::String(format!("{restart_note}{stdout}{stderr}\nexit_code: {exit_code}\n")))
    }
}

/// Anthropic native bash tool declaration for the `bash_20241022` version.
#[derive(Debug, Clone, Default)]
pub struct AnthropicBashTool20241022;

impl AnthropicBashTool20241022 {
    /// Create a new `bash_20241022` tool.
    pub fn new() -> Self {
        Self
    }
}

#[async_trait]
impl Tool for AnthropicBashTool20241022 {
    fn name(&self) -> &str {
        "bash"
    }

    fn description(&self) -> &str {
        "Executes shell commands for Anthropic's native bash tool."
    }

    fn declaration(&self) -> Value {
        AnthropicBashTool::new(BashVersion::V20241022).declaration()
    }

    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
        AnthropicBashTool::new(BashVersion::V20241022).execute(ctx, args).await
    }
}

/// Anthropic native bash tool declaration for the `bash_20250124` version.
#[derive(Debug, Clone, Default)]
pub struct AnthropicBashTool20250124;

impl AnthropicBashTool20250124 {
    /// Create a new `bash_20250124` tool.
    pub fn new() -> Self {
        Self
    }
}

#[async_trait]
impl Tool for AnthropicBashTool20250124 {
    fn name(&self) -> &str {
        "bash"
    }

    fn description(&self) -> &str {
        "Executes shell commands for Anthropic's native bash tool."
    }

    fn declaration(&self) -> Value {
        AnthropicBashTool::new(BashVersion::V20250124).declaration()
    }

    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
        AnthropicBashTool::new(BashVersion::V20250124).execute(ctx, args).await
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TextEditorVersion {
    V20250124,
    V20250429,
    V20250728,
}

impl TextEditorVersion {
    fn type_name(self) -> &'static str {
        match self {
            Self::V20250124 => "text_editor_20250124",
            Self::V20250429 => "text_editor_20250429",
            Self::V20250728 => "text_editor_20250728",
        }
    }

    fn tool_name(self) -> &'static str {
        match self {
            Self::V20250124 => "str_replace_editor",
            Self::V20250429 | Self::V20250728 => "str_replace_based_edit_tool",
        }
    }
}

#[derive(Debug, Clone)]
struct AnthropicTextEditorTool {
    version: TextEditorVersion,
    max_characters: Option<i32>,
}

impl AnthropicTextEditorTool {
    const fn new(version: TextEditorVersion, max_characters: Option<i32>) -> Self {
        Self { version, max_characters }
    }

    fn declaration_json(&self) -> Value {
        json!({
            "type": self.version.type_name(),
            "name": self.version.tool_name(),
            "max_characters": self.max_characters,
        })
    }
}

#[derive(Debug, Deserialize)]
struct ViewArgs {
    path: String,
    view_range: Option<(u32, u32)>,
}

#[derive(Debug, Deserialize)]
struct StrReplaceArgs {
    path: String,
    old_str: String,
    new_str: Option<String>,
}

#[derive(Debug, Deserialize)]
struct InsertArgs {
    path: String,
    insert_line: u32,
    insert_text: Option<String>,
    new_str: Option<String>,
}

#[derive(Debug, Deserialize)]
struct CreateArgs {
    path: String,
    file_text: String,
}

#[derive(Debug, Deserialize)]
struct TextEditorCommand {
    command: String,
}

#[async_trait]
impl Tool for AnthropicTextEditorTool {
    fn name(&self) -> &str {
        self.version.tool_name()
    }

    fn description(&self) -> &str {
        "Executes Anthropic's native text editor commands against local files."
    }

    fn declaration(&self) -> Value {
        json!({
            "name": self.name(),
            "description": self.description(),
            "x-adk-anthropic-tool": self.declaration_json(),
        })
    }

    async fn execute(&self, _ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
        let command: TextEditorCommand = serde_json::from_value(args.clone())
            .map_err(|error| AdkError::tool(format!("invalid text editor arguments: {error}")))?;

        let rendered = match command.command.as_str() {
            "view" => {
                let args: ViewArgs = serde_json::from_value(args).map_err(|error| {
                    AdkError::tool(format!("invalid text editor view arguments: {error}"))
                })?;
                render_view(&args.path, args.view_range).await?
            }
            "str_replace" => {
                let args: StrReplaceArgs = serde_json::from_value(args).map_err(|error| {
                    AdkError::tool(format!("invalid text editor replace arguments: {error}"))
                })?;
                str_replace(&args.path, &args.old_str, args.new_str.as_deref().unwrap_or(""))
                    .await?
            }
            "insert" => {
                let args: InsertArgs = serde_json::from_value(args).map_err(|error| {
                    AdkError::tool(format!("invalid text editor insert arguments: {error}"))
                })?;
                let payload = args.insert_text.or(args.new_str).ok_or_else(|| {
                    invalid_input("text editor insert requires insert_text or new_str")
                })?;
                insert_text(&args.path, args.insert_line, &payload).await?
            }
            "create" => {
                let args: CreateArgs = serde_json::from_value(args).map_err(|error| {
                    AdkError::tool(format!("invalid text editor create arguments: {error}"))
                })?;
                create_file(&args.path, &args.file_text).await?
            }
            other => {
                return Err(invalid_input(format!("unsupported text editor command '{other}'")));
            }
        };

        Ok(Value::String(rendered))
    }
}

/// Anthropic native text editor declaration for `text_editor_20250124`.
#[derive(Debug, Clone, Default)]
pub struct AnthropicTextEditorTool20250124;

impl AnthropicTextEditorTool20250124 {
    /// Create a new `text_editor_20250124` tool.
    pub fn new() -> Self {
        Self
    }
}

#[async_trait]
impl Tool for AnthropicTextEditorTool20250124 {
    fn name(&self) -> &str {
        "str_replace_editor"
    }

    fn description(&self) -> &str {
        "Executes Anthropic's native text editor commands against local files."
    }

    fn declaration(&self) -> Value {
        AnthropicTextEditorTool::new(TextEditorVersion::V20250124, None).declaration()
    }

    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
        AnthropicTextEditorTool::new(TextEditorVersion::V20250124, None).execute(ctx, args).await
    }
}

/// Anthropic native text editor declaration for `text_editor_20250429`.
#[derive(Debug, Clone, Default)]
pub struct AnthropicTextEditorTool20250429 {
    max_characters: Option<i32>,
}

impl AnthropicTextEditorTool20250429 {
    /// Create a new `text_editor_20250429` tool.
    pub fn new() -> Self {
        Self::default()
    }

    /// Limit the number of characters returned when viewing a file.
    pub fn with_max_characters(mut self, max_characters: i32) -> Self {
        self.max_characters = Some(max_characters);
        self
    }
}

#[async_trait]
impl Tool for AnthropicTextEditorTool20250429 {
    fn name(&self) -> &str {
        "str_replace_based_edit_tool"
    }

    fn description(&self) -> &str {
        "Executes Anthropic's native text editor commands against local files."
    }

    fn declaration(&self) -> Value {
        AnthropicTextEditorTool::new(TextEditorVersion::V20250429, self.max_characters)
            .declaration()
    }

    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
        AnthropicTextEditorTool::new(TextEditorVersion::V20250429, self.max_characters)
            .execute(ctx, args)
            .await
    }
}

/// Anthropic native text editor declaration for `text_editor_20250728`.
#[derive(Debug, Clone, Default)]
pub struct AnthropicTextEditorTool20250728 {
    max_characters: Option<i32>,
}

impl AnthropicTextEditorTool20250728 {
    /// Create a new `text_editor_20250728` tool.
    pub fn new() -> Self {
        Self::default()
    }

    /// Limit the number of characters returned when viewing a file.
    pub fn with_max_characters(mut self, max_characters: i32) -> Self {
        self.max_characters = Some(max_characters);
        self
    }
}

#[async_trait]
impl Tool for AnthropicTextEditorTool20250728 {
    fn name(&self) -> &str {
        "str_replace_based_edit_tool"
    }

    fn description(&self) -> &str {
        "Executes Anthropic's native text editor commands against local files."
    }

    fn declaration(&self) -> Value {
        AnthropicTextEditorTool::new(TextEditorVersion::V20250728, self.max_characters)
            .declaration()
    }

    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
        AnthropicTextEditorTool::new(TextEditorVersion::V20250728, self.max_characters)
            .execute(ctx, args)
            .await
    }
}