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
//! Complete Integration Test Example
//!
//! This example demonstrates end-to-end integration testing
//! for the Claude Agent SDK.

use anyhow::Result;
use claude_agent_sdk::{
    ClaudeAgentOptions, ClaudeClient, ContentBlock, McpServerConfig, McpToolResultContent, Message,
    PermissionMode, ToolResult, create_sdk_mcp_server, query, query_stream, tool,
};
use futures::stream::StreamExt;
use serde_json::json;
use std::sync::Arc;

#[tokio::main]
async fn main() -> Result<()> {
    println!("=== Complete Integration Test Example ===\n");

    // Run all integration tests
    let mut passed = 0;
    let mut failed = 0;

    // Test 1: Basic Query
    println!("Running: Basic Query");
    match test_basic_query().await {
        Ok(_) => { println!("   ✓ PASSED\n"); passed += 1; },
        Err(e) => { println!("   ✗ FAILED: {}\n", e); failed += 1; },
    }

    // Test 2: Streaming Query
    println!("Running: Streaming Query");
    match test_streaming_query().await {
        Ok(_) => { println!("   ✓ PASSED\n"); passed += 1; },
        Err(e) => { println!("   ✗ FAILED: {}\n", e); failed += 1; },
    }

    // Test 3: Custom Tools
    println!("Running: Custom Tools");
    match test_custom_tools().await {
        Ok(_) => { println!("   ✓ PASSED\n"); passed += 1; },
        Err(e) => { println!("   ✗ FAILED: {}\n", e); failed += 1; },
    }

    // Test 4: Bidirectional Client
    println!("Running: Bidirectional Client");
    match test_bidirectional_client().await {
        Ok(_) => { println!("   ✓ PASSED\n"); passed += 1; },
        Err(e) => { println!("   ✗ FAILED: {}\n", e); failed += 1; },
    }

    // Test 5: Error Handling
    println!("Running: Error Handling");
    match test_error_handling().await {
        Ok(_) => { println!("   ✓ PASSED\n"); passed += 1; },
        Err(e) => { println!("   ✗ FAILED: {}\n", e); failed += 1; },
    }

    // Test 6: Permission System
    println!("Running: Permission System");
    match test_permission_system().await {
        Ok(_) => { println!("   ✓ PASSED\n"); passed += 1; },
        Err(e) => { println!("   ✗ FAILED: {}\n", e); failed += 1; },
    }

    // Test 7: Hooks
    println!("Running: Hooks");
    match test_hooks().await {
        Ok(_) => { println!("   ✓ PASSED\n"); passed += 1; },
        Err(e) => { println!("   ✗ FAILED: {}\n", e); failed += 1; },
    }

    // Test 8: Budget Control
    println!("Running: Budget Control");
    match test_budget_control().await {
        Ok(_) => { println!("   ✓ PASSED\n"); passed += 1; },
        Err(e) => { println!("   ✗ FAILED: {}\n", e); failed += 1; },
    }

    // Test 9: Session Management
    println!("Running: Session Management");
    match test_session_management().await {
        Ok(_) => { println!("   ✓ PASSED\n"); passed += 1; },
        Err(e) => { println!("   ✗ FAILED: {}\n", e); failed += 1; },
    }

    // Test 10: Concurrent Operations
    println!("Running: Concurrent Operations");
    match test_concurrent_operations().await {
        Ok(_) => { println!("   ✓ PASSED\n"); passed += 1; },
        Err(e) => { println!("   ✗ FAILED: {}\n", e); failed += 1; },
    }

    let total = passed + failed;

    // Print summary
    println!("=== Test Summary ===");
    println!("Total: {}", total);
    println!("Passed: {}", passed);
    println!("Failed: {}", failed);

    if failed > 0 {
        println!("\n⚠️  Some tests failed");
        std::process::exit(1);
    } else {
        println!("\n✅ All tests passed!");
    }

    Ok(())
}

/// Test 1: Basic query functionality
async fn test_basic_query() -> Result<()> {
    let messages = query("What is 2 + 2?", None).await?;

    assert!(!messages.is_empty(), "Should receive messages");

    let has_response = messages.iter().any(|m| matches!(m, Message::Assistant(_)));

    assert!(has_response, "Should have assistant response");
    Ok(())
}

/// Test 2: Streaming query functionality
async fn test_streaming_query() -> Result<()> {
    let mut stream = query_stream("What is 2 + 2?", None).await?;

    let mut count = 0;
    while let Some(result) = stream.next().await {
        let _msg = result?;
        count += 1;
    }

    assert!(count > 0, "Should receive messages via stream");
    Ok(())
}

/// Test 3: Custom tools integration
async fn test_custom_tools() -> Result<()> {
    async fn calculator_tool(args: serde_json::Value) -> Result<ToolResult> {
        let a = args["a"].as_i64().unwrap_or(0);
        let b = args["b"].as_i64().unwrap_or(0);

        Ok(ToolResult {
            content: vec![McpToolResultContent::Text {
                text: format!("{} + {} = {}", a, b, a + b),
            }],
            is_error: false,
        })
    }

    let calc_tool = tool!(
        "calculator",
        "Add two numbers",
        json!({
            "type": "object",
            "properties": {
                "a": {"type": "integer"},
                "b": {"type": "integer"}
            },
            "required": ["a", "b"]
        }),
        calculator_tool
    );

    let server = create_sdk_mcp_server("calc-server", "1.0.0", vec![calc_tool]);

    let mut mcp_servers = std::collections::HashMap::new();
    mcp_servers.insert("calc-server".to_string(), McpServerConfig::Sdk(server));

    let options = ClaudeAgentOptions::builder()
        .mcp_servers(claude_agent_sdk::McpServers::Dict(mcp_servers))
        .allowed_tools(vec!["mcp__calc-server__calculator".to_string()])
        .permission_mode(PermissionMode::BypassPermissions)
        .build();

    let _messages = query("Use the calculator to add 5 and 3", Some(options)).await?;
    Ok(())
}

/// Test 4: Bidirectional client
async fn test_bidirectional_client() -> Result<()> {
    let mut client = ClaudeClient::new(ClaudeAgentOptions::default());

    client.connect().await?;

    client.query("What is 2 + 2?").await?;

    let mut response_count = 0;
    {
        let mut stream = client.receive_response();

        while let Some(result) = stream.next().await {
            let msg = result?;
            if matches!(msg, Message::Result(_)) {
                break;
            }
            response_count += 1;
        }
    } // Drop stream here

    client.disconnect().await?;

    assert!(response_count > 0, "Should receive responses");
    Ok(())
}

/// Test 5: Error handling
async fn test_error_handling() -> Result<()> {
    // Test with invalid configuration
    let result = query("", None).await; // Empty query

    // Should either succeed or fail gracefully
    match result {
        Ok(_) => Ok(()),
        Err(_) => Ok(()), // Error is acceptable
    }
}

/// Test 6: Permission system
async fn test_permission_system() -> Result<()> {
    let options = ClaudeAgentOptions::builder()
        .permission_mode(PermissionMode::BypassPermissions)
        .allowed_tools(vec!["Read".to_string()])
        .build();

    let _messages = query("List files in current directory", Some(options)).await?;
    Ok(())
}

/// Test 7: Hooks system
async fn test_hooks() -> Result<()> {
    use claude_agent_sdk::{HookContext, HookInput, HookJsonOutput, HookMatcher, Hooks};
    use std::sync::Arc;

    async fn test_hook(
        _input: HookInput,
        _tool_use_id: Option<String>,
        _context: HookContext,
    ) -> HookJsonOutput {
        HookJsonOutput::Sync(Default::default())
    }

    let mut hooks = Hooks::new();
    hooks.add_pre_tool_use_with_matcher("Read", test_hook);

    let options = ClaudeAgentOptions::builder()
        .hooks(hooks.build())
        .build();

    let _messages = query("Read README.md", Some(options)).await?;
    Ok(())
}

/// Test 8: Budget control
async fn test_budget_control() -> Result<()> {
    let options = ClaudeAgentOptions::builder()
        .max_budget_usd(0.01) // Very small budget
        .max_turns(2)
        .build();

    let _messages = query("What is 2 + 2?", Some(options)).await?;
    Ok(())
}

/// Test 9: Session management
async fn test_session_management() -> Result<()> {
    let options1 = ClaudeAgentOptions::builder()
        .resume("test-session-1".to_string())
        .build();

    let options2 = ClaudeAgentOptions::builder()
        .resume("test-session-2".to_string())
        .build();

    let _msg1 = query("Remember: X = 1", Some(options1)).await?;
    let _msg2 = query("Remember: X = 2", Some(options2)).await?;

    // Verify sessions are isolated
    let options_check = ClaudeAgentOptions::builder()
        .resume("test-session-1".to_string())
        .continue_conversation(true)
        .build();

    let msg_check = query("What is X?", Some(options_check)).await?;

    // Should have X = 1, not X = 2
    let response_text = extract_response_text(&msg_check);
    let has_correct_value = response_text.contains("1");

    assert!(has_correct_value, "Session should maintain separate state");
    Ok(())
}

/// Test 10: Concurrent operations
async fn test_concurrent_operations() -> Result<()> {
    use futures::stream::{self, StreamExt, TryStreamExt};

    let queries = vec!["What is 2 + 2?", "What is 3 + 3?", "What is 4 + 4?"];

    let results: Vec<_> = stream::iter(queries)
        .map(|q| async move { query(q, None).await })
        .buffer_unordered(3)
        .try_collect()
        .await?;

    assert_eq!(results.len(), 3, "Should complete all queries");
    Ok(())
}

/// Test 11: Multimodal input
async fn test_multimodal_input() -> Result<()> {
    use claude_agent_sdk::{UserContentBlock, query_with_content};

    let base64_data = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==";

    let messages = query_with_content(
        vec![
            UserContentBlock::text("What color is this image?"),
            UserContentBlock::image_base64("image/png", base64_data)?,
        ],
        None,
    )
    .await?;

    assert!(!messages.is_empty(), "Should handle multimodal input");
    Ok(())
}

/// Test 12: Fallback model
async fn test_fallback_model() -> Result<()> {
    let options = ClaudeAgentOptions::builder()
        .model("claude-opus-4-5")
        .fallback_model("claude-sonnet-4-5".to_string())
        .build();

    let _messages = query("What is 2 + 2?", Some(options)).await?;
    Ok(())
}

/// Test 13: Extended thinking
async fn test_extended_thinking() -> Result<()> {
    let options = ClaudeAgentOptions::builder()
        .max_thinking_tokens(10000)
        .build();

    let _messages = query("Solve this complex problem", Some(options)).await?;
    Ok(())
}

/// Test 14: Tool restrictions
async fn test_tool_restrictions() -> Result<()> {
    let options = ClaudeAgentOptions::builder()
        .allowed_tools(vec!["Read".to_string()])
        .disallowed_tools(vec!["Write".to_string()])
        .build();

    let _messages = query("Read README.md", Some(options)).await?;
    Ok(())
}

/// Test 15: System prompts
async fn test_system_prompts() -> Result<()> {
    use claude_agent_sdk::SystemPrompt;

    let options = ClaudeAgentOptions::builder()
        .system_prompt(SystemPrompt::Text(
            "You are a helpful assistant focused on brevity.".to_string(),
        ))
        .build();

    let _messages = query("What is 2 + 2? Be brief.", Some(options)).await?;
    Ok(())
}

/// Test 16: CLI path configuration
async fn test_cli_path_config() -> Result<()> {
    use std::path::PathBuf;

    let options = ClaudeAgentOptions::builder()
        .cli_path(PathBuf::from("claude"))
        .build();

    let _messages = query("What is 2 + 2?", Some(options)).await?;
    Ok(())
}

/// Test 17: Working directory
async fn test_working_directory() -> Result<()> {
    use std::path::PathBuf;

    let options = ClaudeAgentOptions::builder()
        .cwd(PathBuf::from("/tmp"))
        .build();

    let _messages = query("What is the current directory?", Some(options)).await?;
    Ok(())
}

/// Test 18: Environment variables
async fn test_environment_variables() -> Result<()> {
    use std::collections::HashMap;

    let mut env = HashMap::new();
    env.insert("TEST_VAR".to_string(), "test_value".to_string());

    let options = ClaudeAgentOptions::builder().env(env).build();

    let _messages = query("What is the value of TEST_VAR?", Some(options)).await?;
    Ok(())
}

/// Test 19: Fork session
async fn test_fork_session() -> Result<()> {
    let options = ClaudeAgentOptions::builder().fork_session(true).build();

    let _messages = query("What is 2 + 2?", Some(options)).await?;

    // Fork session should not remember previous context
    let options2 = ClaudeAgentOptions::builder().fork_session(true).build();

    let _messages2 = query("What did I ask before?", Some(options2)).await?;

    Ok(())
}

/// Test 20: Max turns enforcement
async fn test_max_turns_enforcement() -> Result<()> {
    let options = ClaudeAgentOptions::builder().max_turns(1).build();

    let messages = query("What is 2 + 2?", Some(options)).await?;

    // Should respect max turns
    assert!(!messages.is_empty(), "Should get at least one message");
    Ok(())
}

/// Helper function to extract response text
fn extract_response_text(messages: &[Message]) -> String {
    let mut text = String::new();

    for msg in messages {
        if let Message::Assistant(assistant_msg) = msg {
            for block in &assistant_msg.message.content {
                if let ContentBlock::Text(content) = block {
                    text.push_str(&content.text);
                }
            }
        }
    }

    text
}

/// Performance assertions
async fn test_performance_assertions() -> Result<()> {
    use std::time::Instant;

    let start = Instant::now();
    let _messages = query("What is 2 + 2?", None).await?;
    let elapsed = start.elapsed();

    // Should complete within reasonable time
    assert!(
        elapsed.as_secs() < 30,
        "Query should complete within 30 seconds"
    );

    println!("   Performance: {:?}", elapsed);
    Ok(())
}

/// Memory leak check
async fn test_memory_leak() -> Result<()> {
    // Run multiple queries to check for memory leaks
    for i in 0..10 {
        let _messages = query(&format!("Query {}", i), None).await?;
    }

    // If we reach here without OOM, no obvious memory leak
    Ok(())
}

/// Cleanup and teardown
async fn test_cleanup() -> Result<()> {
    // Test proper resource cleanup
    let mut client = ClaudeClient::new(ClaudeAgentOptions::default());
    client.connect().await?;
    client.disconnect().await?;

    // Client should be properly cleaned up
    Ok(())
}