docs
0
# Configuration Options
1
2
The `ClaudeAgentOptions` dataclass provides comprehensive configuration for the Claude SDK, covering tools, prompts, permissions, budgets, models, MCP servers, hooks, and more.
3
4
## Capabilities
5
6
### ClaudeAgentOptions
7
8
Complete configuration for Claude SDK client and query function.
9
10
```python { .api }
11
@dataclass
12
class ClaudeAgentOptions:
13
"""Configuration options for Claude SDK."""
14
15
# Tool configuration
16
allowed_tools: list[str] = field(default_factory=list)
17
disallowed_tools: list[str] = field(default_factory=list)
18
19
# Prompt configuration
20
system_prompt: str | SystemPromptPreset | None = None
21
22
# MCP server configuration
23
mcp_servers: dict[str, McpServerConfig] | str | Path = field(default_factory=dict)
24
25
# Permission configuration
26
permission_mode: PermissionMode | None = None
27
permission_prompt_tool_name: str | None = None
28
can_use_tool: CanUseTool | None = None
29
30
# Session configuration
31
continue_conversation: bool = False
32
resume: str | None = None
33
fork_session: bool = False
34
35
# Budget and limits
36
max_turns: int | None = None
37
max_budget_usd: float | None = None
38
max_thinking_tokens: int | None = None
39
40
# Model configuration
41
model: str | None = None
42
fallback_model: str | None = None
43
44
# Working directory and CLI
45
cwd: str | Path | None = None
46
cli_path: str | Path | None = None
47
add_dirs: list[str | Path] = field(default_factory=list)
48
49
# Settings and sources
50
settings: str | None = None
51
setting_sources: list[SettingSource] | None = None
52
53
# Environment
54
env: dict[str, str] = field(default_factory=dict)
55
extra_args: dict[str, str | None] = field(default_factory=dict)
56
57
# Callbacks
58
stderr: Callable[[str], None] | None = None
59
debug_stderr: Any = sys.stderr # Deprecated: Use stderr callback instead
60
61
# Hooks and plugins
62
hooks: dict[HookEvent, list[HookMatcher]] | None = None
63
agents: dict[str, AgentDefinition] | None = None
64
plugins: list[SdkPluginConfig] = field(default_factory=list)
65
66
# Advanced features
67
include_partial_messages: bool = False
68
output_format: dict[str, Any] | None = None
69
max_buffer_size: int | None = None
70
user: str | None = None
71
```
72
73
### Tool Configuration
74
75
Control which tools Claude can use.
76
77
**Fields:**
78
79
- `allowed_tools` (list[str]): List of tools Claude is allowed to use. Common tools include:
80
- `"Read"`: Read files
81
- `"Write"`: Write new files
82
- `"Edit"`: Edit existing files
83
- `"MultiEdit"`: Edit multiple files
84
- `"Bash"`: Execute shell commands
85
- `"Glob"`: Search for files by pattern
86
- `"Grep"`: Search file contents
87
- Custom tool names from MCP servers
88
89
- `disallowed_tools` (list[str]): List of tools to explicitly disallow. Takes precedence over `allowed_tools`.
90
91
**Usage Example:**
92
93
```python
94
from claude_agent_sdk import ClaudeAgentOptions
95
96
# Allow specific tools
97
options = ClaudeAgentOptions(
98
allowed_tools=["Read", "Write", "Bash"]
99
)
100
101
# Allow all except specific tools
102
options = ClaudeAgentOptions(
103
disallowed_tools=["Bash"] # Allow everything except shell commands
104
)
105
106
# Combine with custom MCP tools
107
options = ClaudeAgentOptions(
108
allowed_tools=["Read", "Write", "calculate", "fetch_data"],
109
mcp_servers={"my_server": my_mcp_server}
110
)
111
```
112
113
### Prompt Configuration
114
115
Configure Claude's system prompt.
116
117
**Fields:**
118
119
- `system_prompt` (str | SystemPromptPreset | None): System prompt configuration. Can be:
120
- A string for custom prompts
121
- A SystemPromptPreset dict to use presets
122
- None to use default Claude Code prompt
123
124
**SystemPromptPreset:**
125
126
```python { .api }
127
class SystemPromptPreset(TypedDict):
128
"""System prompt preset configuration."""
129
130
type: Literal["preset"]
131
preset: Literal["claude_code"]
132
append: NotRequired[str]
133
```
134
135
**Usage Example:**
136
137
```python
138
from claude_agent_sdk import ClaudeAgentOptions
139
140
# Custom system prompt
141
options = ClaudeAgentOptions(
142
system_prompt="You are an expert Python developer specializing in async programming."
143
)
144
145
# Use Claude Code preset
146
options = ClaudeAgentOptions(
147
system_prompt={"type": "preset", "preset": "claude_code"}
148
)
149
150
# Extend Claude Code preset
151
options = ClaudeAgentOptions(
152
system_prompt={
153
"type": "preset",
154
"preset": "claude_code",
155
"append": "Always explain your reasoning step by step."
156
}
157
)
158
```
159
160
### MCP Server Configuration
161
162
Configure Model Context Protocol servers for custom tools.
163
164
**Fields:**
165
166
- `mcp_servers` (dict[str, McpServerConfig] | str | Path): MCP server configurations. Can be:
167
- Dictionary mapping server names to configurations
168
- String path to MCP config file
169
- Path object to MCP config file
170
171
**Usage Example:**
172
173
```python
174
from claude_agent_sdk import ClaudeAgentOptions, create_sdk_mcp_server, tool
175
176
# In-process SDK server
177
@tool("calculate", "Perform calculation", {"expression": str})
178
async def calculate(args):
179
result = eval(args["expression"])
180
return {"content": [{"type": "text", "text": str(result)}]}
181
182
calc_server = create_sdk_mcp_server("calculator", tools=[calculate])
183
184
options = ClaudeAgentOptions(
185
mcp_servers={"calc": calc_server},
186
allowed_tools=["calculate"]
187
)
188
189
# Subprocess stdio server
190
options = ClaudeAgentOptions(
191
mcp_servers={
192
"filesystem": {
193
"command": "npx",
194
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]
195
}
196
}
197
)
198
199
# Multiple servers
200
options = ClaudeAgentOptions(
201
mcp_servers={
202
"calc": calc_server,
203
"web": {
204
"type": "sse",
205
"url": "http://localhost:3000/sse"
206
}
207
}
208
)
209
```
210
211
### Permission Configuration
212
213
Control tool execution permissions.
214
215
**Fields:**
216
217
- `permission_mode` (PermissionMode | None): Permission mode. Options:
218
- `"default"`: CLI prompts for dangerous tools
219
- `"acceptEdits"`: Auto-accept file edits
220
- `"plan"`: Plan mode, no execution
221
- `"bypassPermissions"`: Allow all tools (use with caution)
222
223
- `permission_prompt_tool_name` (str | None): Tool name for custom permission prompts. Set to `"stdio"` for programmatic control.
224
225
- `can_use_tool` (CanUseTool | None): Callback function for programmatic permission control. See [Permission Control](./permission-control.md) for details.
226
227
**Usage Example:**
228
229
```python
230
from claude_agent_sdk import ClaudeAgentOptions
231
232
# Auto-accept file edits
233
options = ClaudeAgentOptions(
234
permission_mode="acceptEdits",
235
allowed_tools=["Read", "Write", "Edit"]
236
)
237
238
# Plan mode (no execution)
239
options = ClaudeAgentOptions(
240
permission_mode="plan",
241
allowed_tools=["Read", "Write", "Bash"]
242
)
243
244
# Programmatic control
245
async def my_permission_handler(tool_name, tool_input, context):
246
if tool_name == "Bash":
247
# Review bash commands
248
if "rm -rf" in tool_input.get("command", ""):
249
return PermissionResultDeny(message="Dangerous command blocked")
250
return PermissionResultAllow()
251
252
options = ClaudeAgentOptions(
253
can_use_tool=my_permission_handler,
254
allowed_tools=["Read", "Write", "Bash"]
255
)
256
```
257
258
### Session Configuration
259
260
Control conversation session behavior.
261
262
**Fields:**
263
264
- `continue_conversation` (bool): Continue previous conversation in current directory. Default: False.
265
266
- `resume` (str | None): Resume specific session by ID.
267
268
- `fork_session` (bool): Fork resumed session to new ID instead of continuing. Default: False.
269
270
**Usage Example:**
271
272
```python
273
from claude_agent_sdk import ClaudeAgentOptions
274
275
# Continue last conversation
276
options = ClaudeAgentOptions(
277
continue_conversation=True,
278
cwd="/path/to/project"
279
)
280
281
# Resume specific session
282
options = ClaudeAgentOptions(
283
resume="session-id-123"
284
)
285
286
# Fork from existing session
287
options = ClaudeAgentOptions(
288
resume="session-id-123",
289
fork_session=True
290
)
291
```
292
293
### Budget and Limits
294
295
Set spending and token limits.
296
297
**Fields:**
298
299
- `max_turns` (int | None): Maximum conversation turns before stopping.
300
301
- `max_budget_usd` (float | None): Maximum spending limit in USD.
302
303
- `max_thinking_tokens` (int | None): Maximum tokens for extended thinking blocks.
304
305
**Usage Example:**
306
307
```python
308
from claude_agent_sdk import ClaudeAgentOptions
309
310
# Limit turns
311
options = ClaudeAgentOptions(
312
max_turns=10
313
)
314
315
# Limit spending
316
options = ClaudeAgentOptions(
317
max_budget_usd=1.00
318
)
319
320
# Limit thinking tokens
321
options = ClaudeAgentOptions(
322
max_thinking_tokens=5000
323
)
324
325
# Combined limits
326
options = ClaudeAgentOptions(
327
max_turns=20,
328
max_budget_usd=5.00,
329
max_thinking_tokens=10000
330
)
331
```
332
333
### Model Configuration
334
335
Configure AI models.
336
337
**Fields:**
338
339
- `model` (str | None): AI model to use. Examples:
340
- `"claude-sonnet-4-5-20250929"`
341
- `"claude-opus-4-1-20250805"`
342
- `"claude-haiku-4-20250514"`
343
344
- `fallback_model` (str | None): Fallback model if primary fails.
345
346
**Usage Example:**
347
348
```python
349
from claude_agent_sdk import ClaudeAgentOptions
350
351
# Specific model
352
options = ClaudeAgentOptions(
353
model="claude-sonnet-4-5-20250929"
354
)
355
356
# With fallback
357
options = ClaudeAgentOptions(
358
model="claude-opus-4-1-20250805",
359
fallback_model="claude-sonnet-4-5-20250929"
360
)
361
```
362
363
### Working Directory and CLI
364
365
Configure working directory and CLI path.
366
367
**Fields:**
368
369
- `cwd` (str | Path | None): Working directory for tool execution.
370
371
- `cli_path` (str | Path | None): Path to Claude Code CLI executable. If None, uses bundled CLI.
372
373
- `add_dirs` (list[str | Path]): Additional directories to add to permissions.
374
375
**Usage Example:**
376
377
```python
378
from pathlib import Path
379
from claude_agent_sdk import ClaudeAgentOptions
380
381
# Set working directory
382
options = ClaudeAgentOptions(
383
cwd="/path/to/project"
384
)
385
386
# Use custom CLI
387
options = ClaudeAgentOptions(
388
cli_path="/usr/local/bin/claude"
389
)
390
391
# Add permission directories
392
options = ClaudeAgentOptions(
393
cwd="/path/to/project",
394
add_dirs=[
395
"/path/to/project/src",
396
"/path/to/project/tests"
397
]
398
)
399
```
400
401
### Settings and Sources
402
403
Configure settings sources.
404
405
**Fields:**
406
407
- `settings` (str | None): Settings string.
408
409
- `setting_sources` (list[SettingSource] | None): Setting sources to load. Options:
410
- `"user"`: User-level settings
411
- `"project"`: Project-level settings
412
- `"local"`: Local directory settings
413
414
**Usage Example:**
415
416
```python
417
from claude_agent_sdk import ClaudeAgentOptions
418
419
# Specific setting sources
420
options = ClaudeAgentOptions(
421
setting_sources=["project", "local"]
422
)
423
424
# Custom settings
425
options = ClaudeAgentOptions(
426
settings='{"theme": "dark", "verbose": true}'
427
)
428
```
429
430
### Environment
431
432
Configure environment variables and extra arguments.
433
434
**Fields:**
435
436
- `env` (dict[str, str]): Environment variables for CLI process.
437
438
- `extra_args` (dict[str, str | None]): Extra CLI arguments. Maps flag names to values.
439
440
**Usage Example:**
441
442
```python
443
from claude_agent_sdk import ClaudeAgentOptions
444
445
# Set environment variables
446
options = ClaudeAgentOptions(
447
env={
448
"ANTHROPIC_API_KEY": "sk-...",
449
"DEBUG": "true"
450
}
451
)
452
453
# Pass extra CLI flags
454
options = ClaudeAgentOptions(
455
extra_args={
456
"--verbose": None, # Boolean flag
457
"--log-level": "debug" # Flag with value
458
}
459
)
460
```
461
462
### Callbacks
463
464
Configure callback functions.
465
466
**Fields:**
467
468
- `stderr` (Callable[[str], None] | None): Callback for stderr output from CLI. Receives each stderr line as it's produced.
469
470
- `debug_stderr` (Any): Deprecated. File-like object for debug output. Use `stderr` callback instead. Default: sys.stderr.
471
472
**Usage Example:**
473
474
```python
475
from claude_agent_sdk import ClaudeAgentOptions
476
477
def handle_stderr(line: str):
478
print(f"CLI stderr: {line}")
479
480
options = ClaudeAgentOptions(
481
stderr=handle_stderr
482
)
483
```
484
485
**Note:** The `debug_stderr` field is deprecated and maintained only for backwards compatibility. Use the `stderr` callback for all new code.
486
487
### Hooks and Plugins
488
489
Configure hooks and plugins.
490
491
**Fields:**
492
493
- `hooks` (dict[HookEvent, list[HookMatcher]] | None): Hook configurations. See [Hook System](./hook-system.md) for details.
494
495
- `agents` (dict[str, AgentDefinition] | None): Custom agent definitions. See [Agent Definitions](./agent-definitions.md) for details.
496
497
- `plugins` (list[SdkPluginConfig]): Plugin configurations. See [Plugin Support](./index.md#plugin-support) for details.
498
499
**Usage Example:**
500
501
```python
502
from claude_agent_sdk import ClaudeAgentOptions, HookMatcher
503
504
async def pre_bash_hook(input, tool_use_id, context):
505
# Validate bash commands
506
if "rm -rf" in input["tool_input"]["command"]:
507
return {"decision": "block", "reason": "Dangerous command"}
508
return {}
509
510
options = ClaudeAgentOptions(
511
hooks={
512
"PreToolUse": [
513
HookMatcher(matcher="Bash", hooks=[pre_bash_hook])
514
]
515
}
516
)
517
```
518
519
### Advanced Features
520
521
Advanced configuration options.
522
523
**Fields:**
524
525
- `include_partial_messages` (bool): Include partial streaming messages (StreamEvent). Default: False.
526
527
- `output_format` (dict[str, Any] | None): Structured output schema. Follows Anthropic Messages API format.
528
529
- `max_buffer_size` (int | None): Maximum bytes when buffering CLI stdout.
530
531
- `user` (str | None): User identifier.
532
533
**Usage Example:**
534
535
```python
536
from claude_agent_sdk import ClaudeAgentOptions
537
538
# Enable partial messages
539
options = ClaudeAgentOptions(
540
include_partial_messages=True
541
)
542
543
# Structured output
544
options = ClaudeAgentOptions(
545
output_format={
546
"type": "json_schema",
547
"schema": {
548
"type": "object",
549
"properties": {
550
"answer": {"type": "number"},
551
"explanation": {"type": "string"}
552
},
553
"required": ["answer"]
554
}
555
}
556
)
557
558
# Set buffer size
559
options = ClaudeAgentOptions(
560
max_buffer_size=1024 * 1024 # 1MB
561
)
562
563
# Set user identifier
564
options = ClaudeAgentOptions(
565
user="user-123"
566
)
567
```
568
569
## Complete Configuration Example
570
571
```python
572
from claude_agent_sdk import (
573
ClaudeAgentOptions, create_sdk_mcp_server, tool,
574
HookMatcher, AgentDefinition
575
)
576
577
# Define custom tool
578
@tool("search_docs", "Search documentation", {"query": str})
579
async def search_docs(args):
580
# Implementation
581
return {"content": [{"type": "text", "text": "Found..."}]}
582
583
# Create MCP server
584
docs_server = create_sdk_mcp_server("docs", tools=[search_docs])
585
586
# Define hook
587
async def validate_writes(input, tool_use_id, context):
588
if input["tool_name"] in ["Write", "Edit"]:
589
# Validate file operations
590
pass
591
return {}
592
593
# Complete configuration
594
options = ClaudeAgentOptions(
595
# Tools
596
allowed_tools=["Read", "Write", "Edit", "search_docs"],
597
disallowed_tools=["Bash"],
598
599
# Prompt
600
system_prompt="You are an expert technical writer.",
601
602
# MCP servers
603
mcp_servers={"docs": docs_server},
604
605
# Permissions
606
permission_mode="acceptEdits",
607
608
# Limits
609
max_turns=50,
610
max_budget_usd=10.00,
611
max_thinking_tokens=20000,
612
613
# Model
614
model="claude-sonnet-4-5-20250929",
615
fallback_model="claude-opus-4-1-20250805",
616
617
# Working directory
618
cwd="/path/to/project",
619
add_dirs=["/path/to/project/docs"],
620
621
# Hooks
622
hooks={
623
"PreToolUse": [
624
HookMatcher(matcher="Write|Edit", hooks=[validate_writes])
625
]
626
},
627
628
# Agents
629
agents={
630
"reviewer": AgentDefinition(
631
description="Code reviewer",
632
prompt="Review code for quality",
633
tools=["Read", "Grep"],
634
model="sonnet"
635
)
636
},
637
638
# Environment
639
env={"LOG_LEVEL": "debug"},
640
641
# Callbacks
642
stderr=lambda line: print(f"[CLI] {line}"),
643
644
# Advanced
645
include_partial_messages=False,
646
user="developer-123"
647
)
648
```
649
650
## Configuration Validation
651
652
The SDK validates configuration at runtime:
653
654
- `can_use_tool` requires streaming mode (ClaudeSDKClient or AsyncIterable prompt)
655
- `can_use_tool` and `permission_prompt_tool_name` are mutually exclusive
656
- Model names must be valid Anthropic model identifiers
657
- Paths must exist when specified
658
- MCP server configurations must be valid
659
660
Validation errors raise `ValueError` with descriptive messages.
661