adk-tool 0.7.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
//! Individual Slack tool implementations.
//!
//! Each tool calls a Slack Web API endpoint using `reqwest` and maps
//! Slack API errors to [`AdkError`].

use crate::slack::toolset::TokenSource;
use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result, Tool, ToolContext};
use async_trait::async_trait;
use serde_json::{Value, json};
use std::sync::Arc;

/// Base URL for the Slack Web API.
const SLACK_API_BASE: &str = "https://slack.com/api";

/// Resolve the Slack Bot Token from the configured [`TokenSource`].
///
/// For [`TokenSource::Direct`], returns the token directly.
/// For [`TokenSource::SecretRef`], calls `ctx.get_secret()` and returns an
/// error if the secret is not configured or not found.
async fn resolve_token(token_source: &TokenSource, ctx: &Arc<dyn ToolContext>) -> Result<String> {
    match token_source {
        TokenSource::Direct(token) => Ok(token.clone()),
        TokenSource::SecretRef(secret_name) => {
            let secret = ctx.get_secret(secret_name).await?;
            secret.ok_or_else(|| {
                AdkError::new(
                    ErrorComponent::Tool,
                    ErrorCategory::Unauthorized,
                    "tool.slack.missing_token",
                    format!("Slack bot token secret '{secret_name}' not found. Configure a SecretProvider or use SlackToolset::new() with a direct token."),
                )
            })
        }
    }
}

/// Parse a Slack API JSON response, returning the response body on success
/// or mapping the Slack error to an [`AdkError`].
fn parse_slack_response(body: Value) -> Result<Value> {
    let ok = body["ok"].as_bool().unwrap_or(false);
    if ok {
        Ok(body)
    } else {
        let error_code = body["error"].as_str().unwrap_or("unknown_error");
        let category = match error_code {
            "not_authed" | "invalid_auth" | "token_revoked" | "token_expired"
            | "account_inactive" => ErrorCategory::Unauthorized,
            "channel_not_found" | "not_in_channel" | "message_not_found" => ErrorCategory::NotFound,
            "ratelimited" => ErrorCategory::RateLimited,
            "invalid_arguments" | "missing_scope" | "too_many_attachments" | "no_text" => {
                ErrorCategory::InvalidInput
            }
            _ => ErrorCategory::Internal,
        };
        Err(AdkError::new(
            ErrorComponent::Tool,
            category,
            "tool.slack.api_error",
            format!("Slack API error: {error_code}"),
        ))
    }
}

// ---------------------------------------------------------------------------
// slack_send_message
// ---------------------------------------------------------------------------

/// Post a message to a Slack channel or thread.
///
/// Calls the [`chat.postMessage`](https://api.slack.com/methods/chat.postMessage)
/// Slack Web API endpoint.
pub(crate) struct SlackSendMessage {
    client: reqwest::Client,
    token_source: TokenSource,
}

impl SlackSendMessage {
    pub fn new(client: reqwest::Client, token_source: TokenSource) -> Self {
        Self { client, token_source }
    }
}

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

    fn description(&self) -> &str {
        "Post a message to a Slack channel or thread. Returns the message timestamp on success."
    }

    fn parameters_schema(&self) -> Option<Value> {
        Some(json!({
            "type": "object",
            "properties": {
                "channel": {
                    "type": "string",
                    "description": "The Slack channel ID to post to (e.g. C01234ABCDE)."
                },
                "text": {
                    "type": "string",
                    "description": "The message text to post."
                },
                "thread_ts": {
                    "type": "string",
                    "description": "Optional thread timestamp to reply in a thread."
                }
            },
            "required": ["channel", "text"]
        }))
    }

    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
        let token = resolve_token(&self.token_source, &ctx).await?;

        let channel = args["channel"].as_str().ok_or_else(|| {
            AdkError::new(
                ErrorComponent::Tool,
                ErrorCategory::InvalidInput,
                "tool.slack.missing_channel",
                "Missing required parameter 'channel'",
            )
        })?;
        let text = args["text"].as_str().ok_or_else(|| {
            AdkError::new(
                ErrorComponent::Tool,
                ErrorCategory::InvalidInput,
                "tool.slack.missing_text",
                "Missing required parameter 'text'",
            )
        })?;

        let mut body = json!({
            "channel": channel,
            "text": text,
        });
        if let Some(thread_ts) = args["thread_ts"].as_str() {
            body["thread_ts"] = json!(thread_ts);
        }

        let response = self
            .client
            .post(format!("{SLACK_API_BASE}/chat.postMessage"))
            .bearer_auth(&token)
            .json(&body)
            .send()
            .await
            .map_err(|e| {
                AdkError::new(
                    ErrorComponent::Tool,
                    ErrorCategory::Unavailable,
                    "tool.slack.request_failed",
                    format!("Slack API request failed: {e}"),
                )
            })?;

        let resp_body: Value = response.json().await.map_err(|e| {
            AdkError::new(
                ErrorComponent::Tool,
                ErrorCategory::Internal,
                "tool.slack.invalid_response",
                format!("Failed to parse Slack API response: {e}"),
            )
        })?;

        let resp = parse_slack_response(resp_body)?;
        Ok(json!({
            "ok": true,
            "ts": resp["ts"],
            "channel": resp["channel"],
        }))
    }
}

// ---------------------------------------------------------------------------
// slack_read_channel
// ---------------------------------------------------------------------------

/// Retrieve recent messages from a Slack channel.
///
/// Calls the [`conversations.history`](https://api.slack.com/methods/conversations.history)
/// Slack Web API endpoint.
pub(crate) struct SlackReadChannel {
    client: reqwest::Client,
    token_source: TokenSource,
}

impl SlackReadChannel {
    pub fn new(client: reqwest::Client, token_source: TokenSource) -> Self {
        Self { client, token_source }
    }
}

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

    fn description(&self) -> &str {
        "Retrieve recent messages from a Slack channel."
    }

    fn parameters_schema(&self) -> Option<Value> {
        Some(json!({
            "type": "object",
            "properties": {
                "channel": {
                    "type": "string",
                    "description": "The Slack channel ID to read from."
                },
                "limit": {
                    "type": "integer",
                    "description": "Maximum number of messages to return (default 20, max 1000)."
                }
            },
            "required": ["channel"]
        }))
    }

    fn is_read_only(&self) -> bool {
        true
    }

    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
        let token = resolve_token(&self.token_source, &ctx).await?;

        let channel = args["channel"].as_str().ok_or_else(|| {
            AdkError::new(
                ErrorComponent::Tool,
                ErrorCategory::InvalidInput,
                "tool.slack.missing_channel",
                "Missing required parameter 'channel'",
            )
        })?;
        let limit = args["limit"].as_u64().unwrap_or(20);

        let response = self
            .client
            .get(format!("{SLACK_API_BASE}/conversations.history"))
            .bearer_auth(&token)
            .query(&[("channel", channel), ("limit", &limit.to_string())])
            .send()
            .await
            .map_err(|e| {
                AdkError::new(
                    ErrorComponent::Tool,
                    ErrorCategory::Unavailable,
                    "tool.slack.request_failed",
                    format!("Slack API request failed: {e}"),
                )
            })?;

        let resp_body: Value = response.json().await.map_err(|e| {
            AdkError::new(
                ErrorComponent::Tool,
                ErrorCategory::Internal,
                "tool.slack.invalid_response",
                format!("Failed to parse Slack API response: {e}"),
            )
        })?;

        let resp = parse_slack_response(resp_body)?;
        Ok(json!({
            "ok": true,
            "messages": resp["messages"],
        }))
    }
}

// ---------------------------------------------------------------------------
// slack_add_reaction
// ---------------------------------------------------------------------------

/// Add an emoji reaction to a Slack message.
///
/// Calls the [`reactions.add`](https://api.slack.com/methods/reactions.add)
/// Slack Web API endpoint.
pub(crate) struct SlackAddReaction {
    client: reqwest::Client,
    token_source: TokenSource,
}

impl SlackAddReaction {
    pub fn new(client: reqwest::Client, token_source: TokenSource) -> Self {
        Self { client, token_source }
    }
}

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

    fn description(&self) -> &str {
        "Add an emoji reaction to a message in a Slack channel."
    }

    fn parameters_schema(&self) -> Option<Value> {
        Some(json!({
            "type": "object",
            "properties": {
                "channel": {
                    "type": "string",
                    "description": "The Slack channel ID containing the message."
                },
                "timestamp": {
                    "type": "string",
                    "description": "The timestamp of the message to react to."
                },
                "name": {
                    "type": "string",
                    "description": "The emoji name without colons (e.g. 'thumbsup')."
                }
            },
            "required": ["channel", "timestamp", "name"]
        }))
    }

    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
        let token = resolve_token(&self.token_source, &ctx).await?;

        let channel = args["channel"].as_str().ok_or_else(|| {
            AdkError::new(
                ErrorComponent::Tool,
                ErrorCategory::InvalidInput,
                "tool.slack.missing_channel",
                "Missing required parameter 'channel'",
            )
        })?;
        let timestamp = args["timestamp"].as_str().ok_or_else(|| {
            AdkError::new(
                ErrorComponent::Tool,
                ErrorCategory::InvalidInput,
                "tool.slack.missing_timestamp",
                "Missing required parameter 'timestamp'",
            )
        })?;
        let name = args["name"].as_str().ok_or_else(|| {
            AdkError::new(
                ErrorComponent::Tool,
                ErrorCategory::InvalidInput,
                "tool.slack.missing_name",
                "Missing required parameter 'name' (emoji name without colons)",
            )
        })?;

        let body = json!({
            "channel": channel,
            "timestamp": timestamp,
            "name": name,
        });

        let response = self
            .client
            .post(format!("{SLACK_API_BASE}/reactions.add"))
            .bearer_auth(&token)
            .json(&body)
            .send()
            .await
            .map_err(|e| {
                AdkError::new(
                    ErrorComponent::Tool,
                    ErrorCategory::Unavailable,
                    "tool.slack.request_failed",
                    format!("Slack API request failed: {e}"),
                )
            })?;

        let resp_body: Value = response.json().await.map_err(|e| {
            AdkError::new(
                ErrorComponent::Tool,
                ErrorCategory::Internal,
                "tool.slack.invalid_response",
                format!("Failed to parse Slack API response: {e}"),
            )
        })?;

        parse_slack_response(resp_body)?;
        Ok(json!({ "ok": true }))
    }
}

// ---------------------------------------------------------------------------
// slack_list_threads
// ---------------------------------------------------------------------------

/// List active threads in a Slack channel.
///
/// Calls the [`conversations.replies`](https://api.slack.com/methods/conversations.replies)
/// Slack Web API endpoint for each threaded message found in the channel history.
/// Returns thread root messages that have replies.
pub(crate) struct SlackListThreads {
    client: reqwest::Client,
    token_source: TokenSource,
}

impl SlackListThreads {
    pub fn new(client: reqwest::Client, token_source: TokenSource) -> Self {
        Self { client, token_source }
    }
}

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

    fn description(&self) -> &str {
        "List active threads in a Slack channel. Returns messages that have thread replies."
    }

    fn parameters_schema(&self) -> Option<Value> {
        Some(json!({
            "type": "object",
            "properties": {
                "channel": {
                    "type": "string",
                    "description": "The Slack channel ID to list threads from."
                },
                "limit": {
                    "type": "integer",
                    "description": "Maximum number of messages to scan for threads (default 50, max 1000)."
                }
            },
            "required": ["channel"]
        }))
    }

    fn is_read_only(&self) -> bool {
        true
    }

    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
        let token = resolve_token(&self.token_source, &ctx).await?;

        let channel = args["channel"].as_str().ok_or_else(|| {
            AdkError::new(
                ErrorComponent::Tool,
                ErrorCategory::InvalidInput,
                "tool.slack.missing_channel",
                "Missing required parameter 'channel'",
            )
        })?;
        let limit = args["limit"].as_u64().unwrap_or(50);

        // First, fetch channel history to find messages with threads
        let response = self
            .client
            .get(format!("{SLACK_API_BASE}/conversations.history"))
            .bearer_auth(&token)
            .query(&[("channel", channel), ("limit", &limit.to_string())])
            .send()
            .await
            .map_err(|e| {
                AdkError::new(
                    ErrorComponent::Tool,
                    ErrorCategory::Unavailable,
                    "tool.slack.request_failed",
                    format!("Slack API request failed: {e}"),
                )
            })?;

        let resp_body: Value = response.json().await.map_err(|e| {
            AdkError::new(
                ErrorComponent::Tool,
                ErrorCategory::Internal,
                "tool.slack.invalid_response",
                format!("Failed to parse Slack API response: {e}"),
            )
        })?;

        let resp = parse_slack_response(resp_body)?;

        // Filter messages that have thread replies (reply_count > 0)
        let threads: Vec<Value> = resp["messages"]
            .as_array()
            .unwrap_or(&vec![])
            .iter()
            .filter(|msg| msg["reply_count"].as_u64().is_some_and(|count| count > 0))
            .map(|msg| {
                json!({
                    "thread_ts": msg["ts"],
                    "text": msg["text"],
                    "user": msg["user"],
                    "reply_count": msg["reply_count"],
                    "latest_reply": msg["latest_reply"],
                })
            })
            .collect();

        Ok(json!({
            "ok": true,
            "threads": threads,
        }))
    }
}