claude-sdk-rs 1.0.0

Rust SDK for Claude AI with CLI integration - type-safe async API for Claude Code and direct SDK usage
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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
use reqwest::{Client, StatusCode};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::Duration;

use crate::mcp::core::error::WorkflowError;

/// Slack API service for real API integration
///
/// This service provides actual HTTP API calls to Slack's Web API.
/// Documentation: https://api.slack.com/web
#[derive(Debug, Clone)]
pub struct SlackApiService {
    client: Client,
    bot_token: String,
    base_url: String,
}

/// Represents a Slack channel
#[derive(Debug, Serialize, Deserialize)]
pub struct Channel {
    pub id: String,
    pub name: String,
    pub is_channel: bool,
    pub is_group: bool,
    pub is_im: bool,
    pub is_mpim: bool,
    pub is_private: bool,
    pub created: i64,
    pub is_archived: bool,
    pub is_general: bool,
    pub name_normalized: String,
    pub is_shared: bool,
    pub is_org_shared: bool,
    pub is_member: Option<bool>,
    pub num_members: Option<i32>,
    pub topic: Option<ChannelTopic>,
    pub purpose: Option<ChannelPurpose>,
}

/// Channel topic
#[derive(Debug, Serialize, Deserialize)]
pub struct ChannelTopic {
    pub value: String,
    pub creator: String,
    pub last_set: i64,
}

/// Channel purpose
#[derive(Debug, Serialize, Deserialize)]
pub struct ChannelPurpose {
    pub value: String,
    pub creator: String,
    pub last_set: i64,
}

/// Represents a Slack user
#[derive(Debug, Serialize, Deserialize)]
pub struct User {
    pub id: String,
    pub team_id: String,
    pub name: String,
    pub deleted: bool,
    pub real_name: String,
    pub tz: Option<String>,
    pub tz_label: Option<String>,
    pub is_admin: Option<bool>,
    pub is_owner: Option<bool>,
    pub is_primary_owner: Option<bool>,
    pub is_restricted: Option<bool>,
    pub is_ultra_restricted: Option<bool>,
    pub is_bot: bool,
    pub is_app_user: bool,
    pub profile: UserProfile,
}

/// User profile information
#[derive(Debug, Serialize, Deserialize)]
pub struct UserProfile {
    pub title: Option<String>,
    pub phone: Option<String>,
    pub skype: Option<String>,
    pub real_name: String,
    pub display_name: String,
    pub status_text: Option<String>,
    pub status_emoji: Option<String>,
    pub email: Option<String>,
}

/// Represents a Slack message
#[derive(Debug, Serialize, Deserialize)]
pub struct Message {
    pub ts: String,
    pub thread_ts: Option<String>,
    pub user: Option<String>,
    pub text: String,
    pub attachments: Option<Vec<Attachment>>,
    pub blocks: Option<Vec<serde_json::Value>>,
    pub channel: Option<String>,
}

/// Message attachment
#[derive(Debug, Serialize, Deserialize)]
pub struct Attachment {
    pub color: Option<String>,
    pub fallback: Option<String>,
    pub title: Option<String>,
    pub text: Option<String>,
    pub fields: Option<Vec<AttachmentField>>,
}

/// Attachment field
#[derive(Debug, Serialize, Deserialize)]
pub struct AttachmentField {
    pub title: String,
    pub value: String,
    pub short: bool,
}

/// API response wrapper
#[derive(Debug, Serialize, Deserialize)]
pub struct SlackResponse<T> {
    pub ok: bool,
    pub error: Option<String>,
    #[serde(flatten)]
    pub data: Option<T>,
}

/// Channel list response
#[derive(Debug, Serialize, Deserialize)]
pub struct ChannelListResponse {
    pub channels: Vec<Channel>,
}

/// User info response
#[derive(Debug, Serialize, Deserialize)]
pub struct UserInfoResponse {
    pub user: User,
}

/// Message post response
#[derive(Debug, Serialize, Deserialize)]
pub struct PostMessageResponse {
    pub ts: String,
    pub channel: String,
    pub message: Message,
}

/// Channel history response
#[derive(Debug, Serialize, Deserialize)]
pub struct ChannelHistoryResponse {
    pub messages: Vec<Message>,
    pub has_more: bool,
}

impl SlackApiService {
    /// Create a new Slack API service
    pub fn new(bot_token: String) -> Self {
        let client = Client::builder()
            .timeout(Duration::from_secs(30))
            .build()
            .expect("Failed to create HTTP client");

        Self {
            client,
            bot_token,
            base_url: "https://slack.com/api".to_string(),
        }
    }

    /// Create a new Slack API service with custom base URL (for testing)
    pub fn with_base_url(bot_token: String, base_url: String) -> Self {
        let client = Client::builder()
            .timeout(Duration::from_secs(30))
            .build()
            .expect("Failed to create HTTP client");

        Self {
            client,
            bot_token,
            base_url,
        }
    }

    /// Send a message to a channel
    pub async fn post_message(
        &self,
        channel: &str,
        text: &str,
        thread_ts: Option<&str>,
        blocks: Option<Vec<serde_json::Value>>,
    ) -> Result<PostMessageResponse, WorkflowError> {
        let url = format!("{}/chat.postMessage", self.base_url);

        let mut body = serde_json::json!({
            "channel": channel,
            "text": text
        });

        if let Some(ts) = thread_ts {
            body["thread_ts"] = serde_json::json!(ts);
        }

        if let Some(blocks) = blocks {
            body["blocks"] = serde_json::json!(blocks);
        }

        let response = self
            .client
            .post(&url)
            .header("Authorization", format!("Bearer {}", self.bot_token))
            .header("Content-Type", "application/json")
            .json(&body)
            .send()
            .await
            .map_err(|e| WorkflowError::ExternalServiceError {
                service: "Slack".to_string(),
                message: format!("Failed to post message: {}", e),
            })?;

        if response.status() == StatusCode::UNAUTHORIZED {
            return Err(WorkflowError::AuthenticationError {
                message: "Invalid Slack bot token".to_string(),
            });
        }

        let slack_response: SlackResponse<PostMessageResponse> =
            response.json().await.map_err(|e| {
                WorkflowError::SerializationError(format!("Failed to parse response: {}", e))
            })?;

        if !slack_response.ok {
            return Err(WorkflowError::ExternalServiceError {
                service: "Slack".to_string(),
                message: format!(
                    "Slack API error: {}",
                    slack_response
                        .error
                        .unwrap_or_else(|| "Unknown error".to_string())
                ),
            });
        }

        slack_response
            .data
            .ok_or_else(|| WorkflowError::ExternalServiceError {
                service: "Slack".to_string(),
                message: "No data in successful response".to_string(),
            })
    }

    /// List channels in the workspace
    pub async fn list_channels(
        &self,
        exclude_archived: bool,
        types: Option<&str>,
        limit: Option<u32>,
    ) -> Result<Vec<Channel>, WorkflowError> {
        let url = format!("{}/conversations.list", self.base_url);

        let mut params = HashMap::new();
        params.insert("exclude_archived", exclude_archived.to_string());
        if let Some(types) = types {
            params.insert("types", types.to_string());
        }
        if let Some(limit) = limit {
            params.insert("limit", limit.to_string());
        }

        let response = self
            .client
            .get(&url)
            .header("Authorization", format!("Bearer {}", self.bot_token))
            .query(&params)
            .send()
            .await
            .map_err(|e| WorkflowError::ExternalServiceError {
                service: "Slack".to_string(),
                message: format!("Failed to list channels: {}", e),
            })?;

        if response.status() == StatusCode::UNAUTHORIZED {
            return Err(WorkflowError::AuthenticationError {
                message: "Invalid Slack bot token".to_string(),
            });
        }

        let slack_response: SlackResponse<ChannelListResponse> =
            response.json().await.map_err(|e| {
                WorkflowError::SerializationError(format!("Failed to parse response: {}", e))
            })?;

        if !slack_response.ok {
            return Err(WorkflowError::ExternalServiceError {
                service: "Slack".to_string(),
                message: format!(
                    "Slack API error: {}",
                    slack_response
                        .error
                        .unwrap_or_else(|| "Unknown error".to_string())
                ),
            });
        }

        Ok(slack_response.data.map(|d| d.channels).unwrap_or_default())
    }

    /// Get user information
    pub async fn get_user_info(&self, user_id: &str) -> Result<User, WorkflowError> {
        let url = format!("{}/users.info", self.base_url);

        let mut params = HashMap::new();
        params.insert("user", user_id.to_string());

        let response = self
            .client
            .get(&url)
            .header("Authorization", format!("Bearer {}", self.bot_token))
            .query(&params)
            .send()
            .await
            .map_err(|e| WorkflowError::ExternalServiceError {
                service: "Slack".to_string(),
                message: format!("Failed to get user info: {}", e),
            })?;

        let slack_response: SlackResponse<UserInfoResponse> =
            response.json().await.map_err(|e| {
                WorkflowError::SerializationError(format!("Failed to parse response: {}", e))
            })?;

        if !slack_response.ok {
            if slack_response.error.as_deref() == Some("user_not_found") {
                return Err(WorkflowError::NotFound {
                    resource: format!("User with ID: {}", user_id),
                });
            }
            return Err(WorkflowError::ExternalServiceError {
                service: "Slack".to_string(),
                message: format!(
                    "Slack API error: {}",
                    slack_response
                        .error
                        .unwrap_or_else(|| "Unknown error".to_string())
                ),
            });
        }

        slack_response
            .data
            .map(|d| d.user)
            .ok_or_else(|| WorkflowError::ExternalServiceError {
                service: "Slack".to_string(),
                message: "No data in successful response".to_string(),
            })
    }

    /// Get channel information
    pub async fn get_channel_info(&self, channel_id: &str) -> Result<Channel, WorkflowError> {
        let url = format!("{}/conversations.info", self.base_url);

        let mut params = HashMap::new();
        params.insert("channel", channel_id.to_string());

        let response = self
            .client
            .get(&url)
            .header("Authorization", format!("Bearer {}", self.bot_token))
            .query(&params)
            .send()
            .await
            .map_err(|e| WorkflowError::ExternalServiceError {
                service: "Slack".to_string(),
                message: format!("Failed to get channel info: {}", e),
            })?;

        let slack_response: SlackResponse<serde_json::Value> =
            response.json().await.map_err(|e| {
                WorkflowError::SerializationError(format!("Failed to parse response: {}", e))
            })?;

        if !slack_response.ok {
            if slack_response.error.as_deref() == Some("channel_not_found") {
                return Err(WorkflowError::NotFound {
                    resource: format!("Channel with ID: {}", channel_id),
                });
            }
            return Err(WorkflowError::ExternalServiceError {
                service: "Slack".to_string(),
                message: format!(
                    "Slack API error: {}",
                    slack_response
                        .error
                        .unwrap_or_else(|| "Unknown error".to_string())
                ),
            });
        }

        slack_response
            .data
            .and_then(|d| d.get("channel").cloned())
            .ok_or_else(|| WorkflowError::ExternalServiceError {
                service: "Slack".to_string(),
                message: "No channel data in response".to_string(),
            })
            .and_then(|c| {
                serde_json::from_value(c).map_err(|e| {
                    WorkflowError::SerializationError(format!("Failed to parse channel: {}", e))
                })
            })
    }

    /// Get channel history
    pub async fn get_channel_history(
        &self,
        channel: &str,
        limit: Option<u32>,
        oldest: Option<&str>,
        latest: Option<&str>,
    ) -> Result<ChannelHistoryResponse, WorkflowError> {
        let url = format!("{}/conversations.history", self.base_url);

        let mut params = HashMap::new();
        params.insert("channel", channel.to_string());
        if let Some(limit) = limit {
            params.insert("limit", limit.to_string());
        }
        if let Some(oldest) = oldest {
            params.insert("oldest", oldest.to_string());
        }
        if let Some(latest) = latest {
            params.insert("latest", latest.to_string());
        }

        let response = self
            .client
            .get(&url)
            .header("Authorization", format!("Bearer {}", self.bot_token))
            .query(&params)
            .send()
            .await
            .map_err(|e| WorkflowError::ExternalServiceError {
                service: "Slack".to_string(),
                message: format!("Failed to get channel history: {}", e),
            })?;

        let slack_response: SlackResponse<ChannelHistoryResponse> =
            response.json().await.map_err(|e| {
                WorkflowError::SerializationError(format!("Failed to parse response: {}", e))
            })?;

        if !slack_response.ok {
            return Err(WorkflowError::ExternalServiceError {
                service: "Slack".to_string(),
                message: format!(
                    "Slack API error: {}",
                    slack_response
                        .error
                        .unwrap_or_else(|| "Unknown error".to_string())
                ),
            });
        }

        slack_response
            .data
            .ok_or_else(|| WorkflowError::ExternalServiceError {
                service: "Slack".to_string(),
                message: "No data in successful response".to_string(),
            })
    }

    /// Search messages in the workspace
    pub async fn search_messages(
        &self,
        query: &str,
        count: Option<u32>,
        page: Option<u32>,
    ) -> Result<Vec<Message>, WorkflowError> {
        let url = format!("{}/search.messages", self.base_url);

        let mut params = HashMap::new();
        params.insert("query", query.to_string());
        if let Some(count) = count {
            params.insert("count", count.to_string());
        }
        if let Some(page) = page {
            params.insert("page", page.to_string());
        }

        let response = self
            .client
            .get(&url)
            .header("Authorization", format!("Bearer {}", self.bot_token))
            .query(&params)
            .send()
            .await
            .map_err(|e| WorkflowError::ExternalServiceError {
                service: "Slack".to_string(),
                message: format!("Failed to search messages: {}", e),
            })?;

        let slack_response: SlackResponse<serde_json::Value> =
            response.json().await.map_err(|e| {
                WorkflowError::SerializationError(format!("Failed to parse response: {}", e))
            })?;

        if !slack_response.ok {
            return Err(WorkflowError::ExternalServiceError {
                service: "Slack".to_string(),
                message: format!(
                    "Slack API error: {}",
                    slack_response
                        .error
                        .unwrap_or_else(|| "Unknown error".to_string())
                ),
            });
        }

        // Extract messages from search results
        Ok(slack_response
            .data
            .and_then(|d| d.get("messages").cloned())
            .and_then(|m| m.get("matches").cloned())
            .and_then(|matches| serde_json::from_value::<Vec<Message>>(matches).ok())
            .unwrap_or_default())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use wiremock::matchers::{header, method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    #[tokio::test]
    async fn test_post_message() {
        let mock_server = MockServer::start().await;
        let api = SlackApiService::with_base_url("test-bot-token".to_string(), mock_server.uri());

        Mock::given(method("POST"))
            .and(path("/chat.postMessage"))
            .and(header("Authorization", "Bearer test-bot-token"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "ok": true,
                "ts": "1234567890.123456",
                "channel": "C1234567890",
                "message": {
                    "ts": "1234567890.123456",
                    "user": "U1234567890",
                    "text": "Hello, world!",
                    "channel": "C1234567890"
                }
            })))
            .mount(&mock_server)
            .await;

        let result = api
            .post_message("C1234567890", "Hello, world!", None, None)
            .await
            .unwrap();
        assert_eq!(result.channel, "C1234567890");
        assert_eq!(result.message.text, "Hello, world!");
    }

    #[tokio::test]
    async fn test_list_channels() {
        let mock_server = MockServer::start().await;
        let api = SlackApiService::with_base_url("test-bot-token".to_string(), mock_server.uri());

        Mock::given(method("GET"))
            .and(path("/conversations.list"))
            .and(header("Authorization", "Bearer test-bot-token"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "ok": true,
                "channels": [{
                    "id": "C1234567890",
                    "name": "general",
                    "is_channel": true,
                    "is_group": false,
                    "is_im": false,
                    "is_mpim": false,
                    "is_private": false,
                    "created": 1449252889,
                    "is_archived": false,
                    "is_general": true,
                    "name_normalized": "general",
                    "is_shared": false,
                    "is_org_shared": false
                }]
            })))
            .mount(&mock_server)
            .await;

        let result = api.list_channels(true, None, None).await.unwrap();
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].name, "general");
    }

    #[tokio::test]
    async fn test_authentication_error() {
        let mock_server = MockServer::start().await;
        let api = SlackApiService::with_base_url("invalid-token".to_string(), mock_server.uri());

        Mock::given(method("POST"))
            .and(path("/chat.postMessage"))
            .respond_with(ResponseTemplate::new(401))
            .mount(&mock_server)
            .await;

        let result = api.post_message("C1234567890", "Hello", None, None).await;
        assert!(matches!(
            result.unwrap_err(),
            WorkflowError::AuthenticationError { .. }
        ));
    }
}