claude-code-agent-sdk 0.1.39

Rust SDK for Claude Code CLI with bidirectional streaming, hooks, custom tools, and plugin support
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
//! Configuration types for Claude Agent SDK

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use typed_builder::TypedBuilder;

use super::efficiency::EfficiencyConfig;
use super::hooks::{HookEvent, HookMatcher};
use super::mcp::McpServers;
use super::permissions::CanUseToolCallback;
use super::plugin::SdkPluginConfig;

/// Main configuration options for Claude Agent
#[derive(Clone, TypedBuilder)]
#[builder(doc)]
pub struct ClaudeAgentOptions {
    /// Tools configuration (list of tool names or preset)
    #[builder(default, setter(strip_option))]
    pub tools: Option<Tools>,
    /// List of allowed tool names
    #[builder(default, setter(into))]
    pub allowed_tools: Vec<String>,
    /// System prompt configuration
    #[builder(default, setter(into, strip_option))]
    pub system_prompt: Option<SystemPrompt>,
    /// MCP server configuration
    #[builder(default)]
    pub mcp_servers: McpServers,
    /// Permission mode
    #[builder(default, setter(strip_option))]
    pub permission_mode: Option<PermissionMode>,
    /// Whether to continue the conversation
    #[builder(default = false)]
    pub continue_conversation: bool,
    /// Session ID to resume
    #[builder(default, setter(into, strip_option))]
    pub resume: Option<String>,
    /// Maximum number of turns
    #[builder(default, setter(strip_option))]
    pub max_turns: Option<u32>,
    /// List of disallowed tool names
    #[builder(default, setter(into))]
    pub disallowed_tools: Vec<String>,
    /// Model to use
    #[builder(default, setter(into, strip_option))]
    pub model: Option<String>,
    /// Fallback model to use if primary model fails
    #[builder(default, setter(into, strip_option))]
    pub fallback_model: Option<String>,
    /// Beta features to enable
    /// See https://docs.anthropic.com/en/api/beta-headers
    #[builder(default, setter(into))]
    pub betas: Vec<SdkBeta>,
    /// Maximum budget in USD for the conversation
    #[builder(default, setter(strip_option))]
    pub max_budget_usd: Option<f64>,
    /// Maximum tokens for thinking blocks
    #[builder(default, setter(strip_option))]
    pub max_thinking_tokens: Option<u32>,
    /// Tool name for permission prompts
    #[builder(default, setter(into, strip_option))]
    pub permission_prompt_tool_name: Option<String>,
    /// Working directory
    #[builder(default, setter(into, strip_option))]
    pub cwd: Option<PathBuf>,
    /// Path to Claude CLI
    #[builder(default, setter(into, strip_option))]
    pub cli_path: Option<PathBuf>,
    /// Settings file path
    #[builder(default, setter(into, strip_option))]
    pub settings: Option<String>,
    /// Additional directories to include
    #[builder(default, setter(into))]
    pub add_dirs: Vec<PathBuf>,
    /// Environment variables
    #[builder(default)]
    pub env: HashMap<String, String>,
    /// Extra CLI arguments
    #[builder(default)]
    pub extra_args: HashMap<String, Option<String>>,
    /// Maximum buffer size for subprocess output
    #[builder(default, setter(strip_option))]
    pub max_buffer_size: Option<usize>,
    /// Callback for stderr output
    #[builder(default, setter(strip_option))]
    pub stderr_callback: Option<Arc<dyn Fn(String) + Send + Sync>>,
    /// Callback for tool usage permission
    #[builder(default, setter(strip_option))]
    pub can_use_tool: Option<CanUseToolCallback>,
    /// Hook callbacks
    #[builder(default, setter(strip_option))]
    pub hooks: Option<HashMap<HookEvent, Vec<HookMatcher>>>,
    /// User identifier
    #[builder(default, setter(into, strip_option))]
    pub user: Option<String>,
    /// Whether to include partial messages in stream
    #[builder(default = false)]
    pub include_partial_messages: bool,
    /// Whether to fork the session
    #[builder(default = false)]
    pub fork_session: bool,
    /// Custom agent definitions
    #[builder(default, setter(strip_option))]
    pub agents: Option<HashMap<String, AgentDefinition>>,
    /// Setting sources to use.
    ///
    /// When `None`, the SDK does **not** load any filesystem settings,
    /// providing isolation for SDK applications.
    ///
    /// Programmatic options (like `agents`, `allowed_tools`) always override filesystem settings.
    #[builder(default, setter(strip_option))]
    pub setting_sources: Option<Vec<SettingSource>>,
    /// Sandbox configuration for bash command isolation
    /// Filesystem and network restrictions are derived from permission rules (Read/Edit/WebFetch),
    /// not from these sandbox settings.
    #[builder(default, setter(strip_option))]
    pub sandbox: Option<SandboxSettings>,
    /// Plugin configurations for custom plugins
    #[builder(default, setter(into))]
    pub plugins: Vec<SdkPluginConfig>,
    /// Output format for structured outputs (matches Messages API structure)
    /// Example: `json!({"type": "json_schema", "schema": {"type": "object", "properties": {...}}})`
    #[builder(default, setter(strip_option))]
    pub output_format: Option<serde_json::Value>,
    /// Enable file checkpointing to track file changes during the session.
    /// When enabled, files can be rewound to their state at any user message
    /// using `ClaudeClient.rewind_files()`.
    #[builder(default = false)]
    pub enable_file_checkpointing: bool,
    /// Timeout for control requests (initialize, interrupt, etc.).
    /// Default is 60 seconds, aligned with Python SDK behavior.
    /// Set to `None` to disable timeout (not recommended).
    #[builder(default = Some(Duration::from_secs(60)))]
    pub control_request_timeout: Option<Duration>,
    /// Skip CLI version check (default: false)
    /// Set to true to skip version compatibility check, saving about 100-500ms
    #[builder(default = false)]
    pub skip_version_check: bool,
    /// Reserved — `--verbose` is always sent to the CLI unconditionally.
    ///
    /// The `--verbose` flag is required when using `--output-format stream-json`,
    /// which is the SDK's default transport mode. This field is kept for
    /// backwards compatibility but has no effect.
    #[builder(default = true)]
    pub verbose: bool,
    /// Enable automatic CLI download when Claude Code CLI is not found.
    ///
    /// When `true`, if `find_cli()` exhausts all discovery strategies, it will
    /// attempt to download the CLI binary to `~/.claude/sdk/bundled/` as a last
    /// resort. This involves running the official install script from
    /// `https://claude.ai/install.sh` (Unix) or `https://claude.ai/install.ps1` (Windows).
    ///
    /// Default is `false` — the SDK will not make network requests unless explicitly opted in.
    #[builder(default = false)]
    pub auto_download_cli: bool,
    /// Efficiency tracking and hook injection configuration
    #[builder(default, setter(strip_option))]
    pub efficiency: Option<EfficiencyConfig>,
}

impl Default for ClaudeAgentOptions {
    fn default() -> Self {
        Self::builder().build()
    }
}

/// System prompt configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum SystemPrompt {
    /// Direct text prompt
    Text(String),
    /// Preset-based prompt
    Preset(SystemPromptPreset),
}

impl From<String> for SystemPrompt {
    fn from(text: String) -> Self {
        SystemPrompt::Text(text)
    }
}

impl From<&str> for SystemPrompt {
    fn from(text: &str) -> Self {
        SystemPrompt::Text(text.to_string())
    }
}

/// System prompt preset
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemPromptPreset {
    /// Type field (always "preset")
    #[serde(rename = "type")]
    pub type_: String,
    /// Preset name (e.g., "claude_code")
    pub preset: String,
    /// Text to append to the preset
    #[serde(skip_serializing_if = "Option::is_none")]
    pub append: Option<String>,
}

impl SystemPromptPreset {
    /// Create a new preset with the given name
    pub fn new(preset: impl Into<String>) -> Self {
        Self {
            type_: "preset".to_string(),
            preset: preset.into(),
            append: None,
        }
    }

    /// Create a preset with appended text
    pub fn with_append(preset: impl Into<String>, append: impl Into<String>) -> Self {
        Self {
            type_: "preset".to_string(),
            preset: preset.into(),
            append: Some(append.into()),
        }
    }
}

/// Permission mode for tool execution
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum PermissionMode {
    /// Default permission mode
    #[serde(rename = "default")]
    Default,
    /// Accept edits automatically
    AcceptEdits,
    /// Plan mode
    #[serde(rename = "plan")]
    Plan,
    /// Bypass all permissions
    BypassPermissions,
}

/// Controls which filesystem-based configuration sources the SDK loads settings from.
///
/// When multiple sources are loaded, settings are merged with this precedence (highest to lowest):
/// 1. `Local`
/// 2. `Project`
/// 3. `User`
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum SettingSource {
    /// User settings from `~/.claude/settings.json`
    User,
    /// Project settings from `.claude/settings.json` (team-shared settings)
    Project,
    /// Local settings from `.claude/settings.local.json` (highest priority, git-ignored)
    Local,
}

/// Custom agent definition
#[derive(Debug, Clone, Serialize, Deserialize, TypedBuilder)]
#[builder(doc)]
pub struct AgentDefinition {
    /// Agent description
    #[builder(setter(into))]
    pub description: String,
    /// Agent prompt
    #[builder(setter(into))]
    pub prompt: String,
    /// Tools available to the agent
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(into, strip_option))]
    pub tools: Option<Vec<String>>,
    /// Model to use for the agent
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub model: Option<AgentModel>,
}

/// Model selection for agents
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum AgentModel {
    /// Claude Sonnet
    Sonnet,
    /// Claude Opus
    Opus,
    /// Claude Haiku
    Haiku,
    /// Inherit from parent
    Inherit,
}

/// SDK Beta features
/// See https://docs.anthropic.com/en/api/beta-headers
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum SdkBeta {
    /// Extended context window (1M tokens)
    #[serde(rename = "context-1m-2025-08-07")]
    Context1M,
}

/// Tools configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Tools {
    /// List of tool names
    List(Vec<String>),
    /// Preset configuration
    Preset(ToolsPreset),
}

/// Tools preset configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolsPreset {
    /// Type field (always "preset")
    #[serde(rename = "type")]
    pub type_: String,
    /// Preset name (e.g., "claude_code")
    pub preset: String,
}

impl ToolsPreset {
    /// Create a new tools preset
    pub fn new(preset: impl Into<String>) -> Self {
        Self {
            type_: "preset".to_string(),
            preset: preset.into(),
        }
    }

    /// Create the default claude_code preset
    pub fn claude_code() -> Self {
        Self::new("claude_code")
    }
}

/// Network configuration for sandbox
#[derive(Debug, Clone, Default, Serialize, Deserialize, TypedBuilder)]
#[builder(doc)]
pub struct SandboxNetworkConfig {
    /// Unix socket paths accessible in sandbox (e.g., SSH agents)
    #[serde(skip_serializing_if = "Option::is_none", rename = "allowUnixSockets")]
    #[builder(default, setter(into, strip_option))]
    pub allow_unix_sockets: Option<Vec<String>>,

    /// Allow all Unix sockets (less secure)
    #[serde(
        skip_serializing_if = "Option::is_none",
        rename = "allowAllUnixSockets"
    )]
    #[builder(default, setter(strip_option))]
    pub allow_all_unix_sockets: Option<bool>,

    /// Allow binding to localhost ports (macOS only)
    #[serde(skip_serializing_if = "Option::is_none", rename = "allowLocalBinding")]
    #[builder(default, setter(strip_option))]
    pub allow_local_binding: Option<bool>,

    /// HTTP proxy port if bringing your own proxy
    #[serde(skip_serializing_if = "Option::is_none", rename = "httpProxyPort")]
    #[builder(default, setter(strip_option))]
    pub http_proxy_port: Option<u16>,

    /// SOCKS5 proxy port if bringing your own proxy
    #[serde(skip_serializing_if = "Option::is_none", rename = "socksProxyPort")]
    #[builder(default, setter(strip_option))]
    pub socks_proxy_port: Option<u16>,
}

/// Violations to ignore in sandbox
#[derive(Debug, Clone, Default, Serialize, Deserialize, TypedBuilder)]
#[builder(doc)]
pub struct SandboxIgnoreViolations {
    /// File paths for which violations should be ignored
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(into, strip_option))]
    pub file: Option<Vec<String>>,

    /// Network hosts for which violations should be ignored
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(into, strip_option))]
    pub network: Option<Vec<String>>,
}

/// Sandbox settings configuration
///
/// Controls how Claude Code sandboxes bash commands for filesystem
/// and network isolation.
///
/// **Important:** Filesystem and network restrictions are configured via permission
/// rules, not via these sandbox settings:
/// - Filesystem read restrictions: Use Read deny rules
/// - Filesystem write restrictions: Use Edit allow/deny rules
/// - Network restrictions: Use WebFetch allow/deny rules
#[derive(Debug, Clone, Default, Serialize, Deserialize, TypedBuilder)]
#[builder(doc)]
pub struct SandboxSettings {
    /// Enable bash sandboxing (macOS/Linux only). Default: False
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub enabled: Option<bool>,

    /// Auto-approve bash commands when sandboxed. Default: True
    #[serde(
        skip_serializing_if = "Option::is_none",
        rename = "autoAllowBashIfSandboxed"
    )]
    #[builder(default, setter(strip_option))]
    pub auto_allow_bash_if_sandboxed: Option<bool>,

    /// Commands that should run outside the sandbox (e.g., ["git", "docker"])
    #[serde(skip_serializing_if = "Option::is_none", rename = "excludedCommands")]
    #[builder(default, setter(into, strip_option))]
    pub excluded_commands: Option<Vec<String>>,

    /// Allow commands to bypass sandbox via dangerouslyDisableSandbox.
    /// When False, all commands must run sandboxed (or be in excludedCommands). Default: True
    #[serde(
        skip_serializing_if = "Option::is_none",
        rename = "allowUnsandboxedCommands"
    )]
    #[builder(default, setter(strip_option))]
    pub allow_unsandboxed_commands: Option<bool>,

    /// Network configuration for sandbox
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub network: Option<SandboxNetworkConfig>,

    /// Violations to ignore
    #[serde(skip_serializing_if = "Option::is_none", rename = "ignoreViolations")]
    #[builder(default, setter(strip_option))]
    pub ignore_violations: Option<SandboxIgnoreViolations>,

    /// Enable weaker sandbox for unprivileged Docker environments
    /// (Linux only). Reduces security. Default: False
    #[serde(
        skip_serializing_if = "Option::is_none",
        rename = "enableWeakerNestedSandbox"
    )]
    #[builder(default, setter(strip_option))]
    pub enable_weaker_nested_sandbox: Option<bool>,
}

// ============================================================================
// ClaudeAgentOptions Helper Methods
// ============================================================================

impl ClaudeAgentOptions {
    /// Configure tools to use ACP MCP server instead of CLI built-in.
    ///
    /// This disables the CLI's built-in tools and enables the corresponding
    /// MCP tools with the `mcp__acp__` prefix.
    ///
    /// When Claude needs to execute a tool like `Bash`, it will call
    /// `mcp__acp__Bash` instead, which routes to your SDK MCP server.
    ///
    /// # Arguments
    ///
    /// * `tools` - List of tool names to replace (e.g., `["Bash", "Read", "Write"]`)
    ///
    /// # Example
    ///
    /// ```
    /// use claude_code_agent_sdk::ClaudeAgentOptions;
    ///
    /// let mut options = ClaudeAgentOptions::builder().build();
    /// options.use_acp_tools(&["Bash", "Read", "Write", "Edit"]);
    ///
    /// // Now options.disallowed_tools contains ["Bash", "Read", "Write", "Edit"]
    /// // And options.allowed_tools contains ["mcp__acp__Bash", "mcp__acp__Read", ...]
    /// ```
    pub fn use_acp_tools(&mut self, tools: &[&str]) {
        use super::mcp::acp_tool_name;

        for tool in tools {
            let tool_str = (*tool).to_string();

            // Disable CLI built-in tool
            if !self.disallowed_tools.contains(&tool_str) {
                self.disallowed_tools.push(tool_str);
            }

            // Enable MCP tool with prefix
            let mcp_name = acp_tool_name(tool);
            if !self.allowed_tools.contains(&mcp_name) {
                self.allowed_tools.push(mcp_name);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_control_request_timeout_default() {
        let opts = ClaudeAgentOptions::default();
        // Default should be 60 seconds
        assert_eq!(opts.control_request_timeout, Some(Duration::from_secs(60)));
    }

    #[test]
    fn test_control_request_timeout_custom() {
        let opts = ClaudeAgentOptions::builder()
            .control_request_timeout(Some(Duration::from_secs(30)))
            .build();
        assert_eq!(opts.control_request_timeout, Some(Duration::from_secs(30)));
    }

    #[test]
    fn test_control_request_timeout_none() {
        let opts = ClaudeAgentOptions::builder()
            .control_request_timeout(None)
            .build();
        assert_eq!(opts.control_request_timeout, None);
    }
}