cc-agent-sdk 0.1.7

claude agent sdk
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
//! Comprehensive examples of using ClaudeClient for streaming mode.
//!
//! This file demonstrates various patterns for building applications with
//! the ClaudeClient streaming interface.
//!
//! The queries are intentionally simplistic. In reality, a query can be a more
//! complex task that Claude SDK uses its agentic capabilities and tools (e.g. run
//! bash commands, edit files, search the web, fetch web content) to accomplish.
//!
//! Usage:
//! cargo run --example 14_streaming_mode - List the examples
//! cargo run --example 14_streaming_mode all - Run all examples
//! cargo run --example 14_streaming_mode basic_streaming - Run a specific example

use claude_agent_sdk::{
    ClaudeAgentOptions, ClaudeClient, ContentBlock, Message, ToolResultContent,
};
use futures::StreamExt;
use std::env;
use std::time::Duration;

/// Standardized message display function.
///
/// - UserMessage: "User: <content>"
/// - AssistantMessage: "Claude: <content>"
/// - SystemMessage: ignored
/// - ResultMessage: "Result ended" + cost if available
fn display_message(msg: &Message) {
    match msg {
        Message::User(user_msg) => {
            if let Some(ref content) = user_msg.content {
                for block in content {
                    if let ContentBlock::Text(text) = block {
                        println!("User: {}", text.text);
                    }
                }
            } else if let Some(ref text) = user_msg.text {
                println!("User: {}", text);
            }
        },
        Message::Assistant(assistant_msg) => {
            for block in &assistant_msg.message.content {
                if let ContentBlock::Text(text) = block {
                    println!("Claude: {}", text.text);
                }
            }
        },
        Message::System(_) => {
            // Ignore system messages
        },
        Message::Result(_) => {
            println!("Result ended");
        },
        _ => {},
    }
}

/// Basic streaming with context manager.
async fn example_basic_streaming() -> Result<(), Box<dyn std::error::Error>> {
    println!("=== Basic Streaming Example ===");

    let mut client = ClaudeClient::new(ClaudeAgentOptions::default());
    client.connect().await?;

    println!("User: What is 2+2?");
    client.query("What is 2+2?").await?;

    // Receive complete response using the helper method
    let mut stream = client.receive_response();
    while let Some(message) = stream.next().await {
        display_message(&message?);
    }
    drop(stream);

    client.disconnect().await?;

    println!("\n");
    Ok(())
}

/// Multi-turn conversation using receive_response helper.
async fn example_multi_turn_conversation() -> Result<(), Box<dyn std::error::Error>> {
    println!("=== Multi-Turn Conversation Example ===");

    let mut client = ClaudeClient::new(ClaudeAgentOptions::default());
    client.connect().await?;

    // First turn
    println!("User: What's the capital of France?");
    client.query("What's the capital of France?").await?;

    // Extract and print response
    let mut stream = client.receive_response();
    while let Some(message) = stream.next().await {
        display_message(&message?);
    }
    drop(stream);

    // Second turn - follow-up
    println!("\nUser: What's the population of that city?");
    client.query("What's the population of that city?").await?;

    let mut stream = client.receive_response();
    while let Some(message) = stream.next().await {
        display_message(&message?);
    }
    drop(stream);

    client.disconnect().await?;

    println!("\n");
    Ok(())
}

/// Use ClaudeAgentOptions to configure the client.
async fn example_with_options() -> Result<(), Box<dyn std::error::Error>> {
    println!("=== Custom Options Example ===");

    // Configure options
    let options = ClaudeAgentOptions {
        allowed_tools: vec!["Read".to_string(), "Write".to_string()], // Allow file operations
        system_prompt: Some("You are a helpful coding assistant.".into()),
        ..Default::default()
    };

    let mut client = ClaudeClient::new(options);
    client.connect().await?;

    println!("User: Create a simple hello.txt file with a greeting message");
    client
        .query("Create a simple hello.txt file with a greeting message")
        .await?;

    let mut tool_uses = Vec::new();
    let mut stream = client.receive_response();
    while let Some(message) = stream.next().await {
        let msg = message?;
        if let Message::Assistant(ref assistant_msg) = msg {
            display_message(&msg);
            for block in &assistant_msg.message.content {
                if let ContentBlock::ToolUse(tool_use) = block {
                    tool_uses.push(tool_use.name.clone());
                }
            }
        } else {
            display_message(&msg);
        }
    }
    drop(stream);

    if !tool_uses.is_empty() {
        println!("Tools used: {}", tool_uses.join(", "));
    }

    client.disconnect().await?;

    println!("\n");
    Ok(())
}

/// Manually handle message stream for custom logic.
async fn example_manual_message_handling() -> Result<(), Box<dyn std::error::Error>> {
    println!("=== Manual Message Handling Example ===");

    let mut client = ClaudeClient::new(ClaudeAgentOptions::default());
    client.connect().await?;

    client
        .query("List 5 programming languages and their main use cases")
        .await?;

    // Manually process messages with custom logic
    let mut languages_found = Vec::new();
    let language_list = vec!["Python", "JavaScript", "Java", "C++", "Go", "Rust", "Ruby"];

    let mut stream = client.receive_messages();
    while let Some(message) = stream.next().await {
        let msg = message?;
        match msg {
            Message::Assistant(assistant_msg) => {
                for block in assistant_msg.message.content {
                    if let ContentBlock::Text(text) = block {
                        println!("Claude: {}", text.text);
                        // Custom logic: extract language names
                        for lang in &language_list {
                            if text.text.contains(lang)
                                && !languages_found.contains(&lang.to_string())
                            {
                                languages_found.push(lang.to_string());
                                println!("Found language: {}", lang);
                            }
                        }
                    }
                }
            },
            Message::Result(_) => {
                display_message(&msg);
                println!("Total languages mentioned: {}", languages_found.len());
                break;
            },
            _ => {},
        }
    }
    drop(stream);

    client.disconnect().await?;

    println!("\n");
    Ok(())
}

/// Example showing tool use blocks when running bash commands.
async fn example_bash_command() -> Result<(), Box<dyn std::error::Error>> {
    println!("=== Bash Command Example ===");

    let mut client = ClaudeClient::new(ClaudeAgentOptions::default());
    client.connect().await?;

    println!("User: Run a bash echo command");
    client
        .query("Run a bash echo command that says 'Hello from bash!'")
        .await?;

    // Track all message types received
    let mut message_types = Vec::new();

    let mut stream = client.receive_messages();
    while let Some(message) = stream.next().await {
        let msg = message?;
        message_types.push(
            format!("{:?}", msg)
                .split('(')
                .next()
                .unwrap_or("Unknown")
                .to_string(),
        );

        match msg {
            Message::User(user_msg) => {
                // User messages can contain tool results
                if let Some(ref content) = user_msg.content {
                    for block in content {
                        if let ContentBlock::Text(text) = block {
                            println!("User: {}", text.text);
                        } else if let ContentBlock::ToolResult(tool_result) = block {
                            let content_str = match &tool_result.content {
                                Some(ToolResultContent::Text(s)) => s.as_str(),
                                Some(ToolResultContent::Blocks(_)) => "[structured content]",
                                None => "None",
                            };
                            let preview = if content_str.len() > 100 {
                                &content_str[..100]
                            } else {
                                content_str
                            };
                            println!(
                                "Tool Result (id: {}): {}...",
                                tool_result.tool_use_id, preview
                            );
                        }
                    }
                }
            },
            Message::Assistant(assistant_msg) => {
                // Assistant messages can contain tool use blocks
                for block in assistant_msg.message.content {
                    match block {
                        ContentBlock::Text(text) => {
                            println!("Claude: {}", text.text);
                        },
                        ContentBlock::ToolUse(tool_use) => {
                            println!("Tool Use: {} (id: {})", tool_use.name, tool_use.id);
                            if tool_use.name == "Bash"
                                && let Some(command) = tool_use.input.get("command")
                                && let Some(cmd_str) = command.as_str()
                            {
                                println!("  Command: {}", cmd_str);
                            }
                        },
                        _ => {},
                    }
                }
            },
            Message::Result(result_msg) => {
                println!("Result ended");
                if let Some(cost) = result_msg.total_cost_usd {
                    println!("Cost: ${:.4}", cost);
                }
                break;
            },
            _ => {},
        }
    }
    drop(stream);

    // Get unique message types
    let mut unique_types: Vec<_> = message_types.into_iter().collect();
    unique_types.sort();
    unique_types.dedup();
    println!("\nMessage types received: {}", unique_types.join(", "));

    client.disconnect().await?;

    println!("\n");
    Ok(())
}

/// Demonstrate server info and interrupt capabilities.
async fn example_control_protocol() -> Result<(), Box<dyn std::error::Error>> {
    println!("=== Control Protocol Example ===");
    println!("Shows server info retrieval and interrupt capability\n");

    let mut client = ClaudeClient::new(ClaudeAgentOptions::default());
    client.connect().await?;

    // 1. Get server initialization info
    println!("1. Getting server info...");
    let server_info = client.get_server_info().await;

    if let Some(info) = server_info {
        println!("✓ Server info retrieved successfully!");
        if let Some(commands) = info.get("commands")
            && let Some(commands_array) = commands.as_array()
        {
            println!("  - Available commands: {}", commands_array.len());
        }
        if let Some(output_style) = info.get("output_style") {
            println!("  - Output style: {}", output_style);
        }

        // Show available output styles if present
        if let Some(styles) = info.get("available_output_styles")
            && let Some(styles_array) = styles.as_array()
        {
            let style_names: Vec<_> = styles_array.iter().filter_map(|s| s.as_str()).collect();
            println!("  - Available output styles: {}", style_names.join(", "));
        }

        // Show a few example commands
        if let Some(commands) = info.get("commands")
            && let Some(commands_array) = commands.as_array()
        {
            println!("  - Example commands:");
            for cmd in commands_array.iter().take(5) {
                if let Some(name) = cmd.get("name")
                    && let Some(name_str) = name.as_str()
                {
                    println!("    • {}", name_str);
                }
            }
        }
    } else {
        println!("✗ No server info available (may not be in streaming mode)");
    }

    println!("\n2. Testing interrupt capability...");

    // Start a long-running task
    println!("User: Count from 1 to 20 slowly");
    client
        .query("Count from 1 to 20 slowly, pausing between each number")
        .await?;

    // Start consuming messages in background to enable interrupt
    let mut messages = Vec::new();
    let mut stream = client.receive_response();

    // Read a few messages
    for _ in 0..3 {
        if let Some(message) = stream.next().await {
            let msg = message?;
            if let Message::Assistant(ref assistant_msg) = msg {
                for block in &assistant_msg.message.content {
                    if let ContentBlock::Text(text) = block {
                        // Print first 50 chars to show progress
                        let preview = if text.text.len() > 50 {
                            &text.text[..50]
                        } else {
                            &text.text
                        };
                        println!("Claude: {}...", preview);
                        break;
                    }
                }
            }
            messages.push(msg);
        }
    }
    drop(stream);

    // Wait a moment then interrupt
    tokio::time::sleep(Duration::from_secs(2)).await;
    println!("\n[Sending interrupt after 2 seconds...]");

    match client.interrupt().await {
        Ok(_) => println!("✓ Interrupt sent successfully"),
        Err(e) => println!("✗ Interrupt failed: {}", e),
    }

    // Wait for interrupt to process
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Send new query after interrupt
    println!("\nUser: Just say 'Hello!'");
    client.query("Just say 'Hello!'").await?;

    let mut stream = client.receive_response();
    while let Some(message) = stream.next().await {
        let msg = message?;
        if let Message::Assistant(ref assistant_msg) = msg {
            for block in &assistant_msg.message.content {
                if let ContentBlock::Text(text) = block {
                    println!("Claude: {}", text.text);
                }
            }
        }
    }
    drop(stream);

    client.disconnect().await?;

    println!("\n");
    Ok(())
}

/// Demonstrate proper error handling.
async fn example_error_handling() -> Result<(), Box<dyn std::error::Error>> {
    println!("=== Error Handling Example ===");

    let mut client = ClaudeClient::new(ClaudeAgentOptions::default());

    match client.connect().await {
        Ok(_) => {
            // Send a message that will take time to process
            println!("User: Run a bash sleep command for 60 seconds not in the background");
            client
                .query("Run a bash sleep command for 60 seconds not in the background")
                .await?;

            // Try to receive response with a short timeout
            let mut messages = Vec::new();
            let timeout_duration = Duration::from_secs(10);

            match tokio::time::timeout(timeout_duration, async {
                let mut stream = client.receive_response();
                while let Some(message) = stream.next().await {
                    let msg = message?;
                    if let Message::Assistant(ref assistant_msg) = msg {
                        for block in &assistant_msg.message.content {
                            if let ContentBlock::Text(text) = block {
                                let preview = if text.text.len() > 50 {
                                    &text.text[..50]
                                } else {
                                    &text.text
                                };
                                println!("Claude: {}...", preview);
                            }
                        }
                    } else if let Message::Result(_) = msg {
                        display_message(&msg);
                    }
                    messages.push(msg);
                }
                Ok::<(), Box<dyn std::error::Error>>(())
            })
            .await
            {
                Ok(result) => {
                    result?;
                },
                Err(_) => {
                    println!(
                        "\nResponse timeout after 10 seconds - demonstrating graceful handling"
                    );
                    println!("Received {} messages before timeout", messages.len());
                },
            }
        },
        Err(e) => {
            println!("Connection error: {}", e);
        },
    }

    // Always disconnect
    client.disconnect().await?;

    println!("\n");
    Ok(())
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let args: Vec<String> = env::args().collect();

    if args.len() < 2 {
        // List available examples
        println!("Usage: cargo run --example 14_streaming_mode <example_name>");
        println!("\nAvailable examples:");
        println!("  all - Run all examples");
        println!("  basic_streaming");
        println!("  multi_turn_conversation");
        println!("  with_options");
        println!("  manual_message_handling");
        println!("  bash_command");
        println!("  control_protocol");
        println!("  error_handling");
        return Ok(());
    }

    let example_name = &args[1];

    match example_name.as_str() {
        "all" => {
            // Run all examples
            println!("\n=== Running: basic_streaming ===\n");
            example_basic_streaming().await?;
            println!("{}\n", "-".repeat(50));

            println!("\n=== Running: multi_turn_conversation ===\n");
            example_multi_turn_conversation().await?;
            println!("{}\n", "-".repeat(50));

            println!("\n=== Running: with_options ===\n");
            example_with_options().await?;
            println!("{}\n", "-".repeat(50));

            println!("\n=== Running: manual_message_handling ===\n");
            example_manual_message_handling().await?;
            println!("{}\n", "-".repeat(50));

            println!("\n=== Running: bash_command ===\n");
            example_bash_command().await?;
            println!("{}\n", "-".repeat(50));

            println!("\n=== Running: control_protocol ===\n");
            example_control_protocol().await?;
            println!("{}\n", "-".repeat(50));

            println!("\n=== Running: error_handling ===\n");
            example_error_handling().await?;
            println!("{}\n", "-".repeat(50));
        },
        "basic_streaming" => example_basic_streaming().await?,
        "multi_turn_conversation" => example_multi_turn_conversation().await?,
        "with_options" => example_with_options().await?,
        "manual_message_handling" => example_manual_message_handling().await?,
        "bash_command" => example_bash_command().await?,
        "control_protocol" => example_control_protocol().await?,
        "error_handling" => example_error_handling().await?,
        _ => {
            println!("Error: Unknown example '{}'", example_name);
            println!("\nAvailable examples:");
            println!("  all - Run all examples");
            println!("  basic_streaming");
            println!("  multi_turn_conversation");
            println!("  with_options");
            println!("  manual_message_handling");
            println!("  bash_command");
            println!("  control_protocol");
            println!("  error_handling");
            std::process::exit(1);
        },
    }

    Ok(())
}