docs
0
# Configuration Options
1
2
The ClaudeAgentOptions dataclass provides comprehensive configuration for controlling Claude's behavior, permissions, tools, and execution environment. It's used with both the query() function and ClaudeSDKClient.
3
4
## Capabilities
5
6
### ClaudeAgentOptions
7
8
Configuration dataclass for customizing Claude SDK behavior including tool access, permissions, MCP servers, execution environment, and conversation settings.
9
10
```python { .api }
11
@dataclass
12
class ClaudeAgentOptions:
13
"""
14
Query options for Claude SDK.
15
16
This dataclass provides comprehensive configuration for controlling Claude's
17
behavior, permissions, tools, and execution environment. All fields are optional
18
with sensible defaults.
19
20
Tool Control:
21
- allowed_tools: Explicit list of tool names Claude can use
22
- disallowed_tools: Explicit list of tool names Claude cannot use
23
- mcp_servers: MCP server configurations for custom tools
24
25
Permissions:
26
- permission_mode: Control how permissions are handled
27
- can_use_tool: Callback for custom permission logic
28
29
Conversation Control:
30
- continue_conversation: Continue from last conversation
31
- resume: Resume specific session by ID
32
- max_turns: Limit conversation length
33
- fork_session: Fork resumed sessions to new session ID
34
35
System Configuration:
36
- system_prompt: Custom system prompt or preset
37
- model: AI model to use
38
- cwd: Working directory for tool execution
39
- env: Environment variables
40
- settings: Settings configuration
41
- add_dirs: Additional directories for context
42
43
Advanced Features:
44
- hooks: Event hooks for custom logic
45
- agents: Custom agent definitions
46
- can_use_tool: Permission callback
47
- include_partial_messages: Enable streaming of partial messages
48
"""
49
50
allowed_tools: list[str] = field(default_factory=list)
51
"""List of tool names that Claude is allowed to use.
52
53
When specified, Claude can only use tools in this list. Useful for
54
restricting Claude to specific capabilities for security or workflow reasons.
55
56
Examples:
57
- ['Read', 'Bash'] - Only allow reading files and running bash commands
58
- ['Write', 'Edit'] - Only allow file modifications
59
- [] - No restrictions (default)
60
"""
61
62
system_prompt: str | SystemPromptPreset | None = None
63
"""Custom system prompt or preset configuration.
64
65
Can be either:
66
- A string with custom instructions
67
- A SystemPromptPreset dict to use a preset and optionally append text
68
- None to use default system prompt
69
70
Examples:
71
- "You are a Python expert who explains code clearly"
72
- {"type": "preset", "preset": "claude_code", "append": "Focus on security"}
73
"""
74
75
mcp_servers: dict[str, McpServerConfig] | str | Path = field(default_factory=dict)
76
"""MCP server configurations for custom tools.
77
78
Can be:
79
- A dictionary mapping server names to configurations
80
- A string path to MCP config file
81
- A Path object to MCP config file
82
- Empty dict for no custom servers (default)
83
84
See mcp-config.md for detailed configuration options.
85
"""
86
87
permission_mode: PermissionMode | None = None
88
"""Permission mode for tool execution.
89
90
Controls how Claude handles tool permissions:
91
- 'default': Prompt user for dangerous operations (default)
92
- 'acceptEdits': Auto-accept file edits, prompt for other dangerous ops
93
- 'plan': Generate plan without executing tools
94
- 'bypassPermissions': Allow all tools without prompting (use with caution)
95
"""
96
97
continue_conversation: bool = False
98
"""Whether to continue from the last conversation.
99
100
When True, continues the most recent conversation session. Maintains
101
all context from the previous session.
102
"""
103
104
resume: str | None = None
105
"""Session ID to resume.
106
107
Specify a session ID to resume a specific conversation. Session IDs
108
are included in ResultMessage objects.
109
"""
110
111
max_turns: int | None = None
112
"""Maximum number of conversation turns before stopping.
113
114
Limits the conversation length to prevent infinite loops or excessive
115
API usage. One turn = one user message + one assistant response.
116
"""
117
118
disallowed_tools: list[str] = field(default_factory=list)
119
"""List of tool names that Claude cannot use.
120
121
Explicitly prevents Claude from using specific tools even if they would
122
normally be available. Takes precedence over allowed_tools.
123
124
Examples:
125
- ['Bash'] - Prevent shell command execution
126
- ['Write', 'Edit', 'MultiEdit'] - Prevent file modifications
127
"""
128
129
model: str | None = None
130
"""AI model to use for the conversation.
131
132
Specify a Claude model identifier. If None, uses the default model.
133
134
Examples:
135
- 'claude-sonnet-4-5'
136
- 'claude-opus-4-1-20250805'
137
- 'claude-opus-4-20250514'
138
"""
139
140
permission_prompt_tool_name: str | None = None
141
"""Tool name to use for permission prompts.
142
143
When set, permission prompts will be sent as tool calls to this tool
144
instead of being handled by the SDK.
145
"""
146
147
cwd: str | Path | None = None
148
"""Working directory for tool execution.
149
150
All file operations and bash commands will be executed relative to
151
this directory. If None, uses current working directory.
152
"""
153
154
settings: str | None = None
155
"""Settings configuration.
156
157
JSON string or path to settings file for Claude Code configuration.
158
"""
159
160
add_dirs: list[str | Path] = field(default_factory=list)
161
"""Additional directories to add to Claude's context.
162
163
These directories will be available for Claude to explore and work with.
164
Useful for multi-directory projects.
165
"""
166
167
env: dict[str, str] = field(default_factory=dict)
168
"""Environment variables for tool execution.
169
170
These variables will be available to bash commands and tools executed
171
by Claude. Useful for providing API keys, configuration, etc.
172
173
Example:
174
{"API_KEY": "secret", "DEBUG": "true"}
175
"""
176
177
extra_args: dict[str, str | None] = field(default_factory=dict)
178
"""Arbitrary CLI flags to pass to Claude Code.
179
180
Advanced option for passing additional command-line flags not covered
181
by other options. Keys are flag names, values are flag values (or None
182
for boolean flags).
183
184
Example:
185
{"--verbose": None, "--timeout": "30"}
186
"""
187
188
max_buffer_size: int | None = None
189
"""Maximum bytes when buffering CLI stdout.
190
191
Limits memory usage when buffering output from the Claude Code CLI.
192
If None, uses default buffer size.
193
"""
194
195
debug_stderr: Any = sys.stderr
196
"""Deprecated: File-like object for debug output.
197
198
This field is deprecated. Use the stderr callback instead.
199
"""
200
201
stderr: Callable[[str], None] | None = None
202
"""Callback for stderr output from Claude Code CLI.
203
204
This function will be called with each line of stderr output from the
205
CLI process. Useful for logging or debugging.
206
207
Example:
208
lambda line: logging.debug(f"CLI: {line}")
209
"""
210
211
can_use_tool: CanUseTool | None = None
212
"""Custom tool permission callback.
213
214
When set, this async function is called before each tool execution to
215
determine if the tool should be allowed. Provides full control over
216
tool permissions.
217
218
See permissions.md for details.
219
"""
220
221
hooks: dict[HookEvent, list[HookMatcher]] | None = None
222
"""Hook configurations for custom event handling.
223
224
Hooks allow you to inject custom logic at specific points in Claude's
225
execution loop. Maps hook events to lists of matchers with callbacks.
226
227
See hooks.md for details.
228
"""
229
230
user: str | None = None
231
"""User identifier for the conversation.
232
233
Optional identifier for tracking conversations by user. Useful in
234
multi-user applications.
235
"""
236
237
include_partial_messages: bool = False
238
"""Enable streaming of partial message updates.
239
240
When True, the SDK will emit StreamEvent messages containing partial
241
content as it's generated. Useful for real-time UIs.
242
243
See messages.md for StreamEvent details.
244
"""
245
246
fork_session: bool = False
247
"""Fork resumed sessions to new session ID.
248
249
When True, resumed sessions will fork to a new session ID rather than
250
continuing the previous session. Useful for creating conversation branches.
251
"""
252
253
agents: dict[str, AgentDefinition] | None = None
254
"""Custom agent definitions.
255
256
Define custom agents with specific tools, prompts, and models. Maps
257
agent names to AgentDefinition objects.
258
259
See agents.md for details.
260
"""
261
262
setting_sources: list[SettingSource] | None = None
263
"""Setting sources to load.
264
265
Specify which setting files to load. Options:
266
- 'user': User-level settings
267
- 'project': Project-level settings
268
- 'local': Local settings
269
270
If None, uses default setting sources.
271
"""
272
```
273
274
## Usage Examples
275
276
### Basic Configuration
277
278
```python
279
from claude_agent_sdk import ClaudeAgentOptions, query
280
281
options = ClaudeAgentOptions(
282
system_prompt="You are a Python expert",
283
allowed_tools=["Read", "Write", "Bash"],
284
permission_mode='acceptEdits',
285
cwd="/home/user/project"
286
)
287
288
async for msg in query(prompt="Analyze this codebase", options=options):
289
print(msg)
290
```
291
292
### Tool Restrictions
293
294
```python
295
from claude_agent_sdk import ClaudeAgentOptions, query
296
297
# Only allow read operations
298
options = ClaudeAgentOptions(
299
allowed_tools=["Read", "Glob", "Grep"],
300
disallowed_tools=["Write", "Edit", "Bash"]
301
)
302
303
async for msg in query(prompt="Search for TODO comments", options=options):
304
print(msg)
305
```
306
307
### Custom System Prompt
308
309
```python
310
from claude_agent_sdk import ClaudeAgentOptions, query
311
312
# Using a string
313
options = ClaudeAgentOptions(
314
system_prompt="""You are a security expert. When analyzing code:
315
1. Look for security vulnerabilities
316
2. Check for proper input validation
317
3. Verify authentication and authorization"""
318
)
319
320
# Using a preset with append
321
options = ClaudeAgentOptions(
322
system_prompt={
323
"type": "preset",
324
"preset": "claude_code",
325
"append": "Focus on performance optimization"
326
}
327
)
328
```
329
330
### Session Management
331
332
```python
333
from claude_agent_sdk import ClaudeAgentOptions, query, ResultMessage
334
335
# Start a conversation
336
options = ClaudeAgentOptions()
337
result = None
338
339
async for msg in query(prompt="Explain Python generators", options=options):
340
if isinstance(msg, ResultMessage):
341
result = msg
342
print(f"Session ID: {msg.session_id}")
343
344
# Continue the conversation
345
options.continue_conversation = True
346
async for msg in query(prompt="Can you show an example?", options=options):
347
print(msg)
348
349
# Resume a specific session
350
options.resume = result.session_id
351
options.continue_conversation = False
352
async for msg in query(prompt="What about async generators?", options=options):
353
print(msg)
354
```
355
356
### MCP Server Configuration
357
358
```python
359
from claude_agent_sdk import ClaudeAgentOptions, create_sdk_mcp_server, tool
360
361
# Create custom tools
362
@tool("get_weather", "Get weather for a city", {"city": str})
363
async def get_weather(args):
364
return {"content": [{"type": "text", "text": f"Weather in {args['city']}: Sunny"}]}
365
366
# Create SDK MCP server
367
weather_server = create_sdk_mcp_server("weather", tools=[get_weather])
368
369
# Configure options
370
options = ClaudeAgentOptions(
371
mcp_servers={"weather": weather_server},
372
allowed_tools=["get_weather"]
373
)
374
```
375
376
### Environment and Working Directory
377
378
```python
379
from pathlib import Path
380
from claude_agent_sdk import ClaudeAgentOptions, query
381
382
options = ClaudeAgentOptions(
383
cwd="/home/user/myproject",
384
env={
385
"DATABASE_URL": "postgresql://localhost/mydb",
386
"API_KEY": "secret_key",
387
"DEBUG": "true"
388
},
389
add_dirs=[
390
Path("/home/user/shared"),
391
Path("/home/user/libs")
392
]
393
)
394
395
async for msg in query(prompt="Run the database migration", options=options):
396
print(msg)
397
```
398
399
### Turn Limits
400
401
```python
402
from claude_agent_sdk import ClaudeAgentOptions, query
403
404
# Limit conversation to prevent runaway loops
405
options = ClaudeAgentOptions(
406
max_turns=5, # Stop after 5 back-and-forth exchanges
407
allowed_tools=["Bash"]
408
)
409
410
async for msg in query(
411
prompt="Fix all Python files in this directory",
412
options=options
413
):
414
print(msg)
415
```
416
417
### Model Selection
418
419
```python
420
from claude_agent_sdk import ClaudeAgentOptions, query
421
422
# Use specific model
423
options = ClaudeAgentOptions(
424
model='claude-sonnet-4-5'
425
)
426
427
async for msg in query(prompt="Write a complex algorithm", options=options):
428
print(msg)
429
```
430
431
### Partial Message Streaming
432
433
```python
434
from claude_agent_sdk import ClaudeAgentOptions, query, StreamEvent
435
436
options = ClaudeAgentOptions(
437
include_partial_messages=True
438
)
439
440
async for msg in query(prompt="Write a long essay", options=options):
441
if isinstance(msg, StreamEvent):
442
# Handle streaming content updates
443
print(f"Partial update: {msg.event}")
444
```
445
446
### Session Forking
447
448
```python
449
from claude_agent_sdk import ClaudeAgentOptions, query, ResultMessage
450
451
# Get a session
452
session_id = None
453
async for msg in query(prompt="Explain decorators", options=ClaudeAgentOptions()):
454
if isinstance(msg, ResultMessage):
455
session_id = msg.session_id
456
457
# Fork the session to create a branch
458
options = ClaudeAgentOptions(
459
resume=session_id,
460
fork_session=True # Creates new session instead of continuing
461
)
462
463
async for msg in query(prompt="Now explain metaclasses", options=options):
464
if isinstance(msg, ResultMessage):
465
print(f"New session ID: {msg.session_id}") # Different from original
466
```
467
468
### Stderr Logging
469
470
```python
471
import logging
472
from claude_agent_sdk import ClaudeAgentOptions, query
473
474
logging.basicConfig(level=logging.DEBUG)
475
476
options = ClaudeAgentOptions(
477
stderr=lambda line: logging.debug(f"Claude CLI: {line}")
478
)
479
480
async for msg in query(prompt="Hello", options=options):
481
print(msg)
482
```
483
484
### Custom Agents
485
486
```python
487
from claude_agent_sdk import ClaudeAgentOptions, AgentDefinition, query
488
489
# Define custom agents
490
options = ClaudeAgentOptions(
491
agents={
492
"reviewer": AgentDefinition(
493
description="Code review expert",
494
prompt="You are a code reviewer. Focus on best practices and bugs.",
495
tools=["Read", "Grep"],
496
model="sonnet"
497
),
498
"implementer": AgentDefinition(
499
description="Code implementation expert",
500
prompt="You are an implementation expert. Write clean, tested code.",
501
tools=["Read", "Write", "Edit", "Bash"],
502
model="sonnet"
503
)
504
}
505
)
506
507
async for msg in query(prompt="Review this code then implement fixes", options=options):
508
print(msg)
509
```
510
511
### Setting Sources
512
513
```python
514
from claude_agent_sdk import ClaudeAgentOptions, query
515
516
# Load only project and local settings, skip user settings
517
options = ClaudeAgentOptions(
518
setting_sources=["project", "local"]
519
)
520
521
async for msg in query(prompt="Use project configuration", options=options):
522
print(msg)
523
```
524
525
### Multiple Directory Context
526
527
```python
528
from pathlib import Path
529
from claude_agent_sdk import ClaudeAgentOptions, query
530
531
options = ClaudeAgentOptions(
532
cwd="/home/user/main-project",
533
add_dirs=[
534
Path("/home/user/shared-utils"),
535
Path("/home/user/config"),
536
Path("/home/user/docs")
537
]
538
)
539
540
async for msg in query(
541
prompt="Analyze code in all these directories",
542
options=options
543
):
544
print(msg)
545
```
546
547
### Permission Modes
548
549
```python
550
from claude_agent_sdk import ClaudeAgentOptions, query
551
552
# Plan mode - generate plan without execution
553
plan_options = ClaudeAgentOptions(
554
permission_mode='plan'
555
)
556
557
async for msg in query(prompt="How would you refactor this?", options=plan_options):
558
print(msg)
559
560
# Accept edits mode - auto-accept file changes
561
edit_options = ClaudeAgentOptions(
562
permission_mode='acceptEdits',
563
allowed_tools=["Read", "Write", "Edit"]
564
)
565
566
async for msg in query(prompt="Implement the refactoring", options=edit_options):
567
print(msg)
568
```
569
570
### Combined Configuration
571
572
```python
573
from pathlib import Path
574
from claude_agent_sdk import ClaudeAgentOptions, query
575
576
# Comprehensive configuration example
577
options = ClaudeAgentOptions(
578
# Tools
579
allowed_tools=["Read", "Write", "Edit", "Bash", "Grep", "Glob"],
580
disallowed_tools=["Bash.run_in_background"],
581
582
# Permissions
583
permission_mode='acceptEdits',
584
585
# System
586
system_prompt="You are a senior software engineer specializing in Python",
587
model='claude-sonnet-4-5',
588
589
# Environment
590
cwd="/home/user/project",
591
env={"ENVIRONMENT": "development", "LOG_LEVEL": "debug"},
592
add_dirs=[Path("/home/user/shared")],
593
594
# Session
595
max_turns=10,
596
continue_conversation=False,
597
598
# Advanced
599
include_partial_messages=True,
600
stderr=lambda line: print(f"[CLI] {line}"),
601
)
602
603
async for msg in query(
604
prompt="Build a REST API with FastAPI",
605
options=options
606
):
607
print(msg)
608
```
609