claude-agents-sdk 0.1.7

Rust SDK for building agents with Claude Code CLI
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
//! Tests for tool permission callbacks and hook callbacks.

#![allow(clippy::type_complexity)]

use claude_agents_sdk::{
    ClaudeAgentOptions, HookCallback, HookContext, HookEvent, HookInput, HookMatcher, HookOutput,
    PermissionResult, PermissionResultAllow, PermissionResultDeny, PermissionUpdate,
    PreToolUseHookInput, SyncHookOutput, ToolPermissionContext,
};
use std::collections::HashMap;
use std::sync::Arc;

#[test]
fn test_permission_result_allow() {
    let result = PermissionResult::allow();

    match result {
        PermissionResult::Allow(allow) => {
            assert_eq!(allow.behavior, "allow");
            assert!(allow.updated_input.is_none());
            assert!(allow.updated_permissions.is_none());
        }
        _ => panic!("Expected allow result"),
    }
}

#[test]
fn test_permission_result_deny() {
    let result = PermissionResult::deny();

    match result {
        PermissionResult::Deny(deny) => {
            assert_eq!(deny.behavior, "deny");
            assert!(deny.message.is_empty());
            assert!(!deny.interrupt);
        }
        _ => panic!("Expected deny result"),
    }
}

#[test]
fn test_permission_result_deny_with_message() {
    let result = PermissionResult::deny_with_message("Security policy violation");

    match result {
        PermissionResult::Deny(deny) => {
            assert_eq!(deny.behavior, "deny");
            assert_eq!(deny.message, "Security policy violation");
            assert!(!deny.interrupt);
        }
        _ => panic!("Expected deny result"),
    }
}

#[test]
fn test_permission_result_allow_with_updated_input() {
    let updated_input = serde_json::json!({"safe_mode": true, "param": "value"});
    let result = PermissionResult::Allow(PermissionResultAllow::with_updated_input(
        updated_input.clone(),
    ));

    match result {
        PermissionResult::Allow(allow) => {
            assert_eq!(allow.behavior, "allow");
            assert!(allow.updated_input.is_some());
            let input = allow.updated_input.unwrap();
            assert_eq!(input["safe_mode"], true);
            assert_eq!(input["param"], "value");
        }
        _ => panic!("Expected allow result"),
    }
}

#[test]
fn test_permission_result_deny_with_interrupt() {
    let result = PermissionResultDeny::with_interrupt("Critical security violation");

    assert_eq!(result.behavior, "deny");
    assert_eq!(result.message, "Critical security violation");
    assert!(result.interrupt);
}

#[test]
fn test_tool_permission_context() {
    let context = ToolPermissionContext {
        suggestions: vec![],
    };

    assert!(context.suggestions.is_empty());
}

#[test]
fn test_tool_permission_context_with_suggestions() {
    use claude_agents_sdk::PermissionUpdateType;

    let context = ToolPermissionContext {
        suggestions: vec![PermissionUpdate {
            update_type: PermissionUpdateType::AddRules,
            rules: None,
            behavior: None,
            mode: None,
            directories: None,
            destination: None,
        }],
    };

    assert_eq!(context.suggestions.len(), 1);
}

#[test]
fn test_hook_matcher_creation() {
    let callback: HookCallback = Arc::new(|_input, _tool_use_id, _context| {
        Box::pin(async move { HookOutput::Sync(SyncHookOutput::default()) })
    });

    let matcher = HookMatcher {
        matcher: Some("Bash".to_string()),
        hooks: vec![callback],
        timeout: Some(30.0),
    };

    assert_eq!(matcher.matcher, Some("Bash".to_string()));
    assert_eq!(matcher.hooks.len(), 1);
    assert_eq!(matcher.timeout, Some(30.0));
}

#[test]
fn test_hook_matcher_without_matcher() {
    let callback: HookCallback = Arc::new(|_input, _tool_use_id, _context| {
        Box::pin(async move { HookOutput::Sync(SyncHookOutput::default()) })
    });

    let matcher = HookMatcher {
        matcher: None, // Match all tools
        hooks: vec![callback],
        timeout: None,
    };

    assert!(matcher.matcher.is_none());
    assert_eq!(matcher.hooks.len(), 1);
    assert!(matcher.timeout.is_none());
}

#[test]
fn test_sync_hook_output_default() {
    let output = SyncHookOutput::default();

    assert!(output.continue_.is_none());
    assert!(output.suppress_output.is_none());
    assert!(output.stop_reason.is_none());
    assert!(output.decision.is_none());
    assert!(output.system_message.is_none());
    assert!(output.reason.is_none());
    assert!(output.hook_specific_output.is_none());
}

#[test]
fn test_sync_hook_output_with_block() {
    let output = SyncHookOutput {
        continue_: Some(false),
        suppress_output: None,
        stop_reason: None,
        decision: Some("block".to_string()),
        system_message: None,
        reason: Some("Security policy violation".to_string()),
        hook_specific_output: None,
    };

    assert_eq!(output.continue_, Some(false));
    assert_eq!(output.decision, Some("block".to_string()));
    assert_eq!(output.reason, Some("Security policy violation".to_string()));
}

#[test]
fn test_hook_output_sync() {
    let output = HookOutput::Sync(SyncHookOutput::default());

    match output {
        HookOutput::Sync(sync) => {
            assert!(sync.continue_.is_none());
        }
        _ => panic!("Expected sync output"),
    }
}

#[test]
fn test_hook_output_async() {
    use claude_agents_sdk::AsyncHookOutput;

    let output = HookOutput::Async(AsyncHookOutput {
        async_: true,
        async_timeout: Some(5000),
    });

    match output {
        HookOutput::Async(async_out) => {
            assert!(async_out.async_);
            assert_eq!(async_out.async_timeout, Some(5000));
        }
        _ => panic!("Expected async output"),
    }
}

#[test]
fn test_options_with_hooks() {
    let callback: HookCallback = Arc::new(|_input, _tool_use_id, _context| {
        Box::pin(async move { HookOutput::Sync(SyncHookOutput::default()) })
    });

    let mut hooks: HashMap<HookEvent, Vec<HookMatcher>> = HashMap::new();
    hooks.insert(
        HookEvent::PreToolUse,
        vec![HookMatcher {
            matcher: Some("Bash".to_string()),
            hooks: vec![callback],
            timeout: None,
        }],
    );

    let mut options = ClaudeAgentOptions::new();
    options.hooks = Some(hooks);

    assert!(options.hooks.is_some());
    let hooks = options.hooks.unwrap();
    assert!(hooks.contains_key(&HookEvent::PreToolUse));
    assert_eq!(hooks.get(&HookEvent::PreToolUse).unwrap().len(), 1);
}

#[test]
fn test_options_with_can_use_tool() {
    use std::future::Future;
    use std::pin::Pin;

    let callback: Arc<
        dyn Fn(
                String,
                serde_json::Value,
                ToolPermissionContext,
            ) -> Pin<Box<dyn Future<Output = PermissionResult> + Send>>
            + Send
            + Sync,
    > = Arc::new(|tool_name, _input, _context| {
        Box::pin(async move {
            if tool_name == "Bash" {
                PermissionResult::deny_with_message("Bash not allowed")
            } else {
                PermissionResult::allow()
            }
        })
    });

    let mut options = ClaudeAgentOptions::new();
    options.can_use_tool = Some(callback);

    assert!(options.can_use_tool.is_some());
}

#[test]
fn test_hook_event_variants() {
    // Test all hook event variants
    let events = vec![
        HookEvent::PreToolUse,
        HookEvent::PostToolUse,
        HookEvent::PostToolUseFailure,
        HookEvent::UserPromptSubmit,
        HookEvent::Stop,
        HookEvent::SubagentStop,
        HookEvent::PreCompact,
        HookEvent::Notification,
        HookEvent::SubagentStart,
        HookEvent::PermissionRequest,
    ];

    // Verify they can be used as hash keys
    let mut map: HashMap<HookEvent, String> = HashMap::new();
    for event in events {
        map.insert(event, format!("{:?}", event));
    }

    assert_eq!(map.len(), 10);
    assert!(map.contains_key(&HookEvent::PreToolUse));
    assert!(map.contains_key(&HookEvent::PostToolUse));
    assert!(map.contains_key(&HookEvent::Notification));
    assert!(map.contains_key(&HookEvent::SubagentStart));
    assert!(map.contains_key(&HookEvent::PermissionRequest));
}

#[test]
fn test_hook_context_default() {
    let context = HookContext::default();
    // HookContext is currently empty but reserved for future use
    let _ = context; // Just verify it can be created
}

#[test]
fn test_permission_result_serialization() {
    let allow = PermissionResult::allow();
    let json = serde_json::to_string(&allow).unwrap();
    assert!(json.contains("allow"));

    let deny = PermissionResult::deny_with_message("Not allowed");
    let json = serde_json::to_string(&deny).unwrap();
    assert!(json.contains("deny"));
    assert!(json.contains("Not allowed"));
}

#[test]
fn test_sync_hook_output_serialization() {
    let output = SyncHookOutput {
        continue_: Some(true),
        suppress_output: Some(false),
        stop_reason: Some("Test reason".to_string()),
        decision: Some("allow".to_string()),
        system_message: Some("Test message".to_string()),
        reason: Some("Test reason detail".to_string()),
        hook_specific_output: None,
    };

    let json = serde_json::to_string(&output).unwrap();

    // Verify the serialized field name is "continue" not "continue_"
    assert!(json.contains("\"continue\""));
    assert!(!json.contains("\"continue_\""));
    assert!(json.contains("\"stopReason\""));
    assert!(json.contains("\"systemMessage\""));
}

#[tokio::test]
async fn test_hook_callback_execution() {
    use std::sync::atomic::{AtomicBool, Ordering};

    let called = Arc::new(AtomicBool::new(false));
    let called_clone = called.clone();

    let callback: HookCallback = Arc::new(move |input, _tool_use_id, _context| {
        let called = called_clone.clone();
        Box::pin(async move {
            called.store(true, Ordering::SeqCst);

            // Verify we received the expected input type
            match input {
                HookInput::PreToolUse(pre) => {
                    assert_eq!(pre.tool_name, "TestTool");
                }
                _ => panic!("Expected PreToolUse input"),
            }

            HookOutput::Sync(SyncHookOutput::default())
        })
    });

    // Create a mock PreToolUse input
    let input = HookInput::PreToolUse(PreToolUseHookInput {
        base: claude_agents_sdk::BaseHookInput {
            session_id: "test-session".to_string(),
            transcript_path: "/tmp/transcript".to_string(),
            cwd: "/test".to_string(),
            permission_mode: None,
        },
        hook_event_name: "PreToolUse".to_string(),
        tool_name: "TestTool".to_string(),
        tool_input: serde_json::json!({"param": "value"}),
        tool_use_id: "tu_123".to_string(),
    });

    // Call the callback
    let result = callback(input, None, HookContext::default()).await;

    assert!(called.load(Ordering::SeqCst));
    match result {
        HookOutput::Sync(_) => {}
        _ => panic!("Expected sync output"),
    }
}

#[test]
fn test_notification_hook_input_deserialization() {
    let json = serde_json::json!({
        "hook_event_name": "Notification",
        "session_id": "sess_1",
        "transcript_path": "/tmp/t",
        "cwd": "/test",
        "message": "Build complete",
        "title": "Build",
        "notification_type": "info"
    });

    let input: HookInput = serde_json::from_value(json).unwrap();
    match input {
        HookInput::Notification(n) => {
            assert_eq!(n.message, "Build complete");
            assert_eq!(n.title, Some("Build".to_string()));
            assert_eq!(n.notification_type, "info");
        }
        _ => panic!("Expected Notification input"),
    }
}

#[test]
fn test_subagent_start_hook_input_deserialization() {
    let json = serde_json::json!({
        "hook_event_name": "SubagentStart",
        "session_id": "sess_1",
        "transcript_path": "/tmp/t",
        "cwd": "/test",
        "agent_id": "agent_123",
        "agent_type": "code_review"
    });

    let input: HookInput = serde_json::from_value(json).unwrap();
    match input {
        HookInput::SubagentStart(s) => {
            assert_eq!(s.agent_id, "agent_123");
            assert_eq!(s.agent_type, "code_review");
        }
        _ => panic!("Expected SubagentStart input"),
    }
}

#[test]
fn test_permission_request_hook_input_deserialization() {
    let json = serde_json::json!({
        "hook_event_name": "PermissionRequest",
        "session_id": "sess_1",
        "transcript_path": "/tmp/t",
        "cwd": "/test",
        "tool_name": "Bash",
        "tool_input": {"command": "ls"}
    });

    let input: HookInput = serde_json::from_value(json).unwrap();
    match input {
        HookInput::PermissionRequest(p) => {
            assert_eq!(p.tool_name, "Bash");
            assert!(p.permission_suggestions.is_none());
        }
        _ => panic!("Expected PermissionRequest input"),
    }
}

#[test]
fn test_subagent_stop_hook_input_new_fields() {
    let json = serde_json::json!({
        "hook_event_name": "SubagentStop",
        "session_id": "sess_1",
        "transcript_path": "/tmp/t",
        "cwd": "/test",
        "stop_hook_active": true,
        "agent_id": "agent_456",
        "agent_transcript_path": "/tmp/agent_transcript",
        "agent_type": "code_review"
    });

    let input: HookInput = serde_json::from_value(json).unwrap();
    match input {
        HookInput::SubagentStop(s) => {
            assert!(s.stop_hook_active);
            assert_eq!(s.agent_id, "agent_456");
            assert_eq!(s.agent_transcript_path, "/tmp/agent_transcript");
            assert_eq!(s.agent_type, "code_review");
        }
        _ => panic!("Expected SubagentStop input"),
    }
}

#[test]
fn test_pre_tool_use_hook_input_tool_use_id() {
    let json = serde_json::json!({
        "hook_event_name": "PreToolUse",
        "session_id": "sess_1",
        "transcript_path": "/tmp/t",
        "cwd": "/test",
        "tool_name": "Read",
        "tool_input": {},
        "tool_use_id": "tu_789"
    });

    let input: HookInput = serde_json::from_value(json).unwrap();
    match input {
        HookInput::PreToolUse(p) => {
            assert_eq!(p.tool_use_id, "tu_789");
        }
        _ => panic!("Expected PreToolUse input"),
    }
}

#[test]
fn test_control_request_payload_mcp_status_serialization() {
    use claude_agents_sdk::ControlRequestPayload;

    let payload = ControlRequestPayload::McpStatus;
    let json = serde_json::to_string(&payload).unwrap();

    // Should serialize as {"subtype":"mcp_status"}
    assert!(json.contains("\"subtype\":\"mcp_status\""));
}