clawd_code_sdk
Class info¶
Classes¶
| Name | Children | Inherits |
|---|---|---|
| APIError clawd_code_sdk._errors Base exception for Anthropic API errors. |
||
| AuthenticationError clawd_code_sdk._errors Raised when API authentication fails (401). |
||
| BillingError clawd_code_sdk._errors Raised when there's a billing issue with the API account. |
||
| CLIConnectionError clawd_code_sdk._errors Raised when unable to connect to Claude Code. |
||
| CLIJSONDecodeError clawd_code_sdk._errors Raised when unable to decode JSON from CLI output. |
||
| CLINotFoundError clawd_code_sdk._errors Raised when Claude Code is not found or not installed. |
||
| CanUseToolShadowedWarning clawd_code_sdk._errors ``on_permission`` is a callback, but some tool calls are auto-approved before it runs. |
||
| ClaudeSDKError clawd_code_sdk._errors Base exception for all Claude SDK errors. |
||
| ControlRequestError clawd_code_sdk._errors Raised when a control protocol request fails. |
||
| ControlRequestTimeoutError clawd_code_sdk._errors Raised when a control protocol request times out. |
||
| ForkSessionResult clawd_code_sdk._internal.session_mutations Result of a fork operation. |
||
| InvalidRequestError clawd_code_sdk._errors Raised when the API request is invalid (400). |
||
| LineFramer clawd_code_sdk._internal.transport.subprocess_utils Reassembles complete lines from a stream that yields arbitrary chunks. |
||
| McpError clawd_code_sdk._errors Raised when an MCP-related control request fails. |
||
| ProcessError clawd_code_sdk._errors Raised when the CLI process fails. |
||
| RateLimitError clawd_code_sdk._errors Raised when API rate limits are exceeded (429). |
||
| ResultError clawd_code_sdk._errors The CLI reported an error result and then exited non-zero. |
||
| SdkMcpBridge clawd_code_sdk._internal.sdk_mcp_bridge Routes raw JSON-RPC for one in-process MCP server through mcp's memory transport. |
||
| SdkMcpBridgeError clawd_code_sdk._internal.sdk_mcp_bridge Raised when a message cannot be delivered to an SDK MCP server. |
||
| ServerError clawd_code_sdk._errors Raised when the API server encounters an error (500/529). |
||
| SubprocessCLITransport clawd_code_sdk._internal.transport.subprocess_cli Subprocess transport using Claude Code CLI. |
||
| Transport clawd_code_sdk._internal.transport Abstract transport for Claude communication. |
Re-exported classes¶
| Class | Module | Description |
|---|---|---|
| AgentDefinition | clawd_code_sdk.models.agents | User-facing agent definition configuration. |
| AgentHookHandler | clawd_code_sdk.models.hooks | Agent hook handler with multi-turn tool access. |
| AppliedSettings | clawd_code_sdk.models.control | The currently applied model and effort settings. |
| AssistantMessage | clawd_code_sdk.models.messages | Assistant message with content blocks. |
| BaseHookInput | clawd_code_sdk.models.hooks | Base hook input fields present across many hook events. |
| BaseResultMessage | clawd_code_sdk.models.messages | Base result message with cost and usage information. |
| BaseSystemMessage | clawd_code_sdk.models.system_messages | Base class for all system messages. |
| ClaudeAgentOptions | clawd_code_sdk.models.options | Query options for Claude SDK. |
| ClaudeCodeSettings | clawd_code_sdk.models.settings | Configuration settings for Claude Code. Learn more: https://code.claude.com/docs/en/settings. |
| ClaudeSDKClient | clawd_code_sdk.client | Client for bidirectional, interactive conversations with Claude Code. |
| CommandHookHandler | clawd_code_sdk.models.hooks | |
| ContinueLatest | clawd_code_sdk.models.options | Continue the most recent conversation. |
| ConversationTurn | clawd_code_sdk.session | Collected result of a single send/receive cycle. |
| Filesystem | clawd_code_sdk.models.settings | Filesystem access control for sandboxed commands. See https://code.claude.com/docs/en/sandboxing#filesystem-isolation. |
| FromPR | clawd_code_sdk.models.options | Resume sessions linked to a specific GitHub PR. |
| GetSettingsResponse | clawd_code_sdk.models.control | Response from get_settings() containing effective and per-source settings. |
| HookContext | clawd_code_sdk.models.hooks | Context information for hook callbacks. |
| HookMatcher | clawd_code_sdk.models.hooks | Hook matcher configuration. |
| HookMatcherConfig | clawd_code_sdk.models.hooks | Declarative hook matcher for agent/skill/settings hook configuration. |
| Hooks | clawd_code_sdk.models.settings | Lifecycle event hooks that run at configurable points during Claude Code operation (tool use, session start/end, notifications, prompt submit, message display, and more), not just before/after tool executions. See https://code.claude.com/docs/en/hooks. |
| ImageBlock | clawd_code_sdk.models.content_blocks | Image content block (storage-only, not emitted on the wire). |
| ImageSource | clawd_code_sdk.models.content_blocks | Base64-encoded image source data. |
| InitSystemMessage | clawd_code_sdk.models.system_messages | System init message with session metadata. |
| McpAuthenticateResponse | clawd_code_sdk.models.control | Response from authenticating with an MCP server. |
| McpSdkServerConfig | clawd_code_sdk.models.mcp | SDK MCP server configuration (serializable, no instance). |
| McpSdkServerConfigWithInstance | clawd_code_sdk.models.mcp | SDK MCP server config with a live McpServer instance. Not serializable. |
| McpSetServersResult | clawd_code_sdk.models.mcp | Result of a setMcpServers operation. |
| Network | clawd_code_sdk.models.settings | Configures network isolation settings for the sandboxed bash environment, including domain restrictions, Unix socket access, and custom proxy configuration. |
| NewSession | clawd_code_sdk.models.options | Start a fresh session. |
| NotificationHookInput | clawd_code_sdk.models.hooks | Input data for Notification hook events. |
| NotificationHookSpecificOutput | clawd_code_sdk.models.hooks | Hook-specific output for Notification events. |
| PermissionRequestHookInput | clawd_code_sdk.models.hooks | Input data for PermissionRequest hook events. |
| PermissionRequestHookSpecificOutput | clawd_code_sdk.models.hooks | Hook-specific output for PermissionRequest events. |
| PermissionResultAllow | clawd_code_sdk.models.permissions | Allow permission result. |
| PermissionResultDeny | clawd_code_sdk.models.permissions | Deny permission result. |
| Permissions | clawd_code_sdk.models.settings | Tool usage permissions configuration. |
| PostCompactHookInput | clawd_code_sdk.models.hooks | Input data for PostCompact hook events. |
| PostToolUseFailureHookInput | clawd_code_sdk.models.hooks | Input data for PostToolUseFailure hook events. |
| PostToolUseFailureHookSpecificOutput | clawd_code_sdk.models.hooks | Hook-specific output for PostToolUseFailure events. |
| PostToolUseHookInput | clawd_code_sdk.models.hooks | Input data for PostToolUse hook events. |
| PreCompactHookInput | clawd_code_sdk.models.hooks | Input data for PreCompact hook events. |
| PreToolUseHookInput | clawd_code_sdk.models.hooks | Input data for PreToolUse hook events. |
| PromptHookHandler | clawd_code_sdk.models.hooks | LLM prompt hook handler. |
| RemoteControlResponse | clawd_code_sdk.models.control | Response from enabling remote control. |
| ResultErrorMessage | clawd_code_sdk.models.messages | Error result message. |
| ResultSuccessMessage | clawd_code_sdk.models.messages | Successful result message. |
| ResumeSession | clawd_code_sdk.models.options | Resume an existing session by ID. |
| SDKSessionInfo | clawd_code_sdk.models.session | Session metadata returned by list_sessions. |
| Sandbox | clawd_code_sdk.models.settings | Sandbox execution configuration. See https://code.claude.com/docs/en/sandboxing. |
| SdkMcpTool | clawd_code_sdk.mcp_utils | Definition for an SDK MCP tool. |
| SdkPluginConfig | clawd_code_sdk.models.mcp | SDK plugin configuration. |
| Session | clawd_code_sdk.session | A managed Claude session wrapping a ClaudeSDKClient. |
| SessionManager | clawd_code_sdk.session | Manages multiple concurrent Claude SDK sessions. |
| SessionMessage | clawd_code_sdk.models.session | A message from a session transcript. |
| SessionSnapshot | clawd_code_sdk.session | Read-only snapshot of session metadata at a point in time. |
| SettingsSource | clawd_code_sdk.models.control | A single settings source with its raw settings. |
| StopHookInput | clawd_code_sdk.models.hooks | Input data for Stop hook events. |
| SubagentStartHookInput | clawd_code_sdk.models.hooks | Input data for SubagentStart hook events. |
| SubagentStartHookSpecificOutput | clawd_code_sdk.models.hooks | Hook-specific output for SubagentStart events. |
| SubagentStopHookInput | clawd_code_sdk.models.hooks | Input data for SubagentStop hook events. |
| TextBlock | clawd_code_sdk.models.content_blocks | Text content block. |
| ThinkingBlock | clawd_code_sdk.models.content_blocks | Thinking/reasoning content block. |
| ThinkingConfigAdaptive | clawd_code_sdk.models.thinking | Adaptive thinking configuration - model decides thinking budget. |
| ThinkingConfigDisabled | clawd_code_sdk.models.thinking | Disabled thinking configuration. |
| ThinkingConfigEnabled | clawd_code_sdk.models.thinking | Enabled thinking configuration with explicit token budget. |
| ToolCallSummary | clawd_code_sdk.session | Summary of a single tool invocation within a conversation turn. |
| ToolPermissionContext | clawd_code_sdk.models.permissions | Context information for tool permission callbacks. |
| ToolResultBlock | clawd_code_sdk.models.content_blocks | Tool result content block. |
| ToolUseBlock | clawd_code_sdk.models.content_blocks | Tool use content block. |
| UserDocumentPrompt | clawd_code_sdk.models.prompts | A user prompt containing a base64-encoded PDF document. |
| UserDocumentURLPrompt | clawd_code_sdk.models.prompts | A user prompt containing a PDF document referenced by URL. |
| UserImagePrompt | clawd_code_sdk.models.prompts | A user prompt containing a single base64-encoded image. |
| UserImageURLPrompt | clawd_code_sdk.models.prompts | A user prompt containing an image referenced by URL. |
| UserMessage | clawd_code_sdk.models.messages | User message. |
| UserPlainTextDocumentPrompt | clawd_code_sdk.models.prompts | A user prompt containing a plain text document. |
| UserPromptSubmitHookInput | clawd_code_sdk.models.hooks | Input data for UserPromptSubmit hook events. |
| UserTextPrompt | clawd_code_sdk.models.prompts | A text-only user prompt. |
🛈 DocStrings¶
Claude SDK for Python.
AgentHooksConfig
module-attribute
¶
AgentHooksConfig = dict[HookEvent, list[HookMatcherConfig]]
Type alias for the hooks field on AgentDefinition.
Maps hook event names to lists of matcher configs. Example::
hooks: AgentHooksConfig = {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [{"type": "command", "command": "./check.sh"}],
}
],
}
CommandHookHandler
module-attribute
¶
CommandHookHandler = TypedDict(
"CommandHookHandler",
{
"type": Literal["command"],
"command": str,
"timeout": NotRequired[float],
"async": NotRequired[bool],
"statusMessage": NotRequired[str],
"once": NotRequired[bool],
},
)
Bash command hook handler.
See https://code.claude.com/docs/en/hooks#command-hook-fields
ContentBlock
module-attribute
¶
ContentBlock = Annotated[
TextBlock
| ThinkingBlock
| ToolUseBlock
| ToolResultBlock
| ImageBlock
| DocumentBlock
| ServerContentBlock,
Discriminator("type"),
]
All content block types (used for storage/JSONL which doesn't distinguish by role).
HookHandler
module-attribute
¶
HookHandler = CommandHookHandler | PromptHookHandler | AgentHookHandler
Union of all declarative hook handler types.
Message
module-attribute
¶
Message = Annotated[
Annotated[UserMessage, Tag("user")]
| Annotated[AssistantMessage, Tag("assistant")]
| Annotated[ResultSuccessMessage, Tag("result_success")]
| Annotated[ResultErrorMessage, Tag("result_error")]
| Annotated[StreamEvent, Tag("stream_event")]
| Annotated[RateLimitMessage, Tag("rate_limit_event")]
| Annotated[ToolProgressMessage, Tag("tool_progress")]
| Annotated[ToolUseSummaryMessage, Tag("tool_use_summary")]
| Annotated[AuthStatusMessage, Tag("auth_status")]
| Annotated[PromptSuggestionMessage, Tag("prompt_suggestion")]
| Annotated[ConversationResetMessage, Tag("conversation_reset")]
| Annotated[CommandLifecycleMessage, Tag("command_lifecycle")]
| Annotated[SystemMessageUnion, Tag("system")],
Discriminator(_message_discriminator),
]
Discriminated union of all wire-format message types.
OnUserQuestion
module-attribute
¶
OnUserQuestion = Callable[
[AskUserQuestionInput, ToolPermissionContext], Awaitable[PermissionResult]
]
Callback for handling AskUserQuestion elicitation requests.
Called when Claude asks the user a clarifying question. The callback should return a PermissionResultAllow with updated_input containing the answers, or a PermissionResultDeny to cancel.
SessionConfig
module-attribute
¶
SessionConfig = NewSession | ResumeSession | ContinueLatest | FromPR
Union of all session configuration types.
Can also be specified as a plain str, which is a shortcut for
ResumeSession(session_id=str).
UserPrompt
module-attribute
¶
UserPrompt = (
UserTextPrompt
| UserImagePrompt
| UserImageURLPrompt
| UserDocumentPrompt
| UserDocumentURLPrompt
| UserPlainTextDocumentPrompt
| UserFilePrompt
)
Union type for all user prompt dataclasses.
APIError
¶
Bases: ClaudeSDKError
Base exception for Anthropic API errors.
This exception is raised when the API returns an error response that was previously returned as a text message. Subclasses provide more specific error types for programmatic handling.
Attributes:
| Name | Type | Description |
|---|---|---|
error_type |
The type of API error (e.g., "rate_limit", "invalid_request"). |
|
message |
The error message from the API. |
|
model |
The model that was being used when the error occurred. |
Source code in src/clawd_code_sdk/_errors.py
AgentDefinition
¶
Bases: ClaudeCodeBaseModel
User-facing agent definition configuration.
Accepts ergonomic Python inputs (e.g. dict-style mcp_servers)
and converts to the wire format via to_wire().
Source code in src/clawd_code_sdk/models/agents.py
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 | |
auto_compact_window
class-attribute
instance-attribute
¶
Token count at which this agent compacts its own conversation as a subagent.
Only lowers the inherited window. No effect on the main session agent.
background
class-attribute
instance-attribute
¶
Whether this agent runs in the background.
critical_system_reminder_experimental
class-attribute
instance-attribute
¶
critical_system_reminder_experimental: str | None = Field(
default=None, title="Critical System Reminder", alias="criticalSystemReminder_EXPERIMENTAL"
)
Critical system reminder message to display to the user.
description
class-attribute
instance-attribute
¶
A brief description of the agent's purpose.
disallowed_tools
class-attribute
instance-attribute
¶
disallowed_tools: list[ToolName | str] | None = Field(
default=None, title="Disallowed Tools", examples=["Bash"]
)
Tools this agent is not allowed to use.
effort
class-attribute
instance-attribute
¶
effort: ReasoningEffort | int | None = Field(
default=None, title="Reasoning effort", examples=["high"]
)
Effort level for thinking depth.
hooks
class-attribute
instance-attribute
¶
hooks: AgentHooksConfig | None = Field(default=None, title='Agent Hooks')
Hook configurations for this agent.
initial_prompt
class-attribute
instance-attribute
¶
Auto-submitted as the first user turn when this agent is the main thread agent.
Slash commands are processed. Prepended to any user-provided prompt.
isolation
class-attribute
instance-attribute
¶
isolation: Literal["worktree"] | None = Field(
default=None, title="Isolation Mode", examples=["worktree"]
)
Isolation mode. "worktree" runs the agent in a separate git worktree.
max_turns
class-attribute
instance-attribute
¶
Maximum number of agentic turns (API round-trips) before stopping.
mcp_servers
class-attribute
instance-attribute
¶
MCP servers for this agent.
Maps server names to configs. Use None as the value to reference
a server already configured in settings::
memory
class-attribute
instance-attribute
¶
memory: SettingSource | None = Field(
default=None, title="Agent Memory", examples=["user", "project"]
)
Persistent cross-session memory scope for this agent.
model
class-attribute
instance-attribute
¶
model: ModelName | Literal["inherit"] | str | None = Field(
default=None, title="Agent Model", examples=["sonnet"]
)
The model to use for this agent.
observer
class-attribute
instance-attribute
¶
Agent type(s) (comma-separated, max 4) auto-spawned as background observers.
observer_message
class-attribute
instance-attribute
¶
Supplemental postamble appended to each activity digest sent to the observer.
omit_claude_md
class-attribute
instance-attribute
¶
Run without user/project/local CLAUDE.md files when running as a subagent.
permission_mode
class-attribute
instance-attribute
¶
permission_mode: PermissionMode | None = Field(
default=None, title="Permission Mode", examples=["bypassPermissions"]
)
Permission mode for this agent.
prompt
class-attribute
instance-attribute
¶
The prompt to use for this agent.
skills
class-attribute
instance-attribute
¶
Skills this agent has.
tools
class-attribute
instance-attribute
¶
The tools this agent has access to.
to_wire
¶
Serialize to the wire-format dict for the CLI control protocol.
Converts dict-style mcp_servers to the array format the CLI expects:
{"git": config} -> [{"git": config}]
Returns a camelCase dict with None values excluded.
Source code in src/clawd_code_sdk/models/agents.py
to_wire_model
¶
to_wire_model() -> AgentWireDefinition
Serialize to the wire-format dict for the CLI control protocol.
Converts dict-style mcp_servers to the array format the CLI expects:
{"git": config} -> [{"git": config}]
Returns a camelCase dict with None values excluded.
Source code in src/clawd_code_sdk/models/agents.py
AgentHookHandler
¶
Bases: TypedDict
Agent hook handler with multi-turn tool access.
See https://code.claude.com/docs/en/hooks#agent-based-hooks
Source code in src/clawd_code_sdk/models/hooks.py
AppliedSettings
¶
Bases: BaseModel
The currently applied model and effort settings.
Source code in src/clawd_code_sdk/models/control.py
AssistantMessage
¶
Bases: BaseModel
Assistant message with content blocks.
Source code in src/clawd_code_sdk/models/messages.py
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 | |
aborted
class-attribute
instance-attribute
¶
Set when the turn was aborted while this message was streaming.
api_error_origin
class-attribute
instance-attribute
¶
first_party when Anthropic's own API sent the error response.
api_error_params
class-attribute
instance-attribute
¶
api_error_params: ApiErrorParams | None = None
Parameters of the API error, for the error kinds that have any.
api_error_status
class-attribute
instance-attribute
¶
HTTP status code of the API error when is_api_error_message is true.
api_error_type
class-attribute
instance-attribute
¶
The error.type of the API error response body, e.g. rate_limit_error.
is_api_error_message
class-attribute
instance-attribute
¶
True when this assistant message wraps an API error (undocumented).
request_id
class-attribute
instance-attribute
¶
API request ID that produced this message.
supersedes
class-attribute
instance-attribute
¶
UUIDs of previously emitted assistant messages this one replaces.
thinking_display
class-attribute
instance-attribute
¶
Active thinking display mode (undocumented).
thinking_duration_ms
class-attribute
instance-attribute
¶
How long the model spent thinking for this message (undocumented).
tool_use_meta
class-attribute
instance-attribute
¶
tool_use_meta: list[ToolUseMeta] | None = None
Display metadata for the tool_use blocks in this message (undocumented).
user_message_uuid
class-attribute
instance-attribute
¶
UUID of the user message this assistant message responds to.
user_message_uuids
class-attribute
instance-attribute
¶
UUIDs of all user messages this assistant message responds to (batched turns).
wire_ingest_context
class-attribute
instance-attribute
¶
Per-tool_use ingest context (e.g. cwd), keyed by tool_use ID (undocumented).
wire_tool_inputs
class-attribute
instance-attribute
¶
Tool inputs as sent on the wire, keyed by tool_use ID (undocumented).
raise_if_api_error
¶
Raise the appropriate API exception if error is set.
Source code in src/clawd_code_sdk/models/messages.py
to_otel
¶
Convert SDK content block objects into semconv OutputMessages.
Source code in src/clawd_code_sdk/models/messages.py
AuthenticationError
¶
Bases: APIError
Raised when API authentication fails (401).
This typically indicates an invalid API key or insufficient permissions.
Source code in src/clawd_code_sdk/_errors.py
BaseHookInput
¶
Bases: TypedDict
Base hook input fields present across many hook events.
Source code in src/clawd_code_sdk/models/hooks.py
prompt_id
instance-attribute
¶
ID of the user prompt that started the current turn.
BaseResultMessage
¶
Bases: BaseMessage
Base result message with cost and usage information.
Note: Fields use inconsistent scoping. See per-field docs for details.
Source code in src/clawd_code_sdk/models/messages.py
begun_message_ids
class-attribute
instance-attribute
¶
API message IDs (msg_...) the turn began (undocumented, CLI 2.1.330+).
duration_api_ms
instance-attribute
¶
Cumulative API time across the entire session.
fast_mode_state
class-attribute
instance-attribute
¶
Whether fast mode was enabled.
model_usage
class-attribute
instance-attribute
¶
model_usage: dict[str, ModelUsage] = Field(default_factory=dict, validation_alias='modelUsage')
Cumulative token usage per model across the entire session.
model_usage_since_last_result
class-attribute
instance-attribute
¶
model_usage_since_last_result: dict[str, ModelUsage] | None = None
Per-model usage accrued since the previous result (undocumented).
permission_denials
class-attribute
instance-attribute
¶
permission_denials: list[SDKPermissionDenial] = []
Permission denials from the last API call only (per-turn).
process_turn_index
class-attribute
instance-attribute
¶
Index of this turn within the CLI process (undocumented).
queued_turn_count
class-attribute
instance-attribute
¶
Number of turns still queued after this result.
safety_stops
class-attribute
instance-attribute
¶
Number of safety stops during the turn (undocumented).
subagent_stats
class-attribute
instance-attribute
¶
subagent_stats: SubagentStats | None = None
Subagent statistics for the turn (undocumented).
terminal_reason
class-attribute
instance-attribute
¶
Why the query loop terminated.
Unset when the loop was bypassed (local slash command) or interrupted externally (budget/retry limits checked between yields).
total_cost_usd
instance-attribute
¶
Cumulative cost across the entire session.
turn_start_resume_kind
class-attribute
instance-attribute
¶
How the turn started relative to a resume, e.g. "none" (undocumented).
user_message_uuid
class-attribute
instance-attribute
¶
UUID of the user message that started this turn.
user_message_uuids
class-attribute
instance-attribute
¶
UUIDs of all user messages handled in this turn.
BaseSystemMessage
¶
Bases: BaseModel
Base class for all system messages.
Source code in src/clawd_code_sdk/models/system_messages.py
BillingError
¶
Bases: APIError
Raised when there's a billing issue with the API account.
This may indicate insufficient credits, expired subscription, or other billing-related issues.
Source code in src/clawd_code_sdk/_errors.py
CLIConnectionError
¶
Bases: ClaudeSDKError
Raised when unable to connect to Claude Code.
CLIJSONDecodeError
¶
Bases: ClaudeSDKError
Raised when unable to decode JSON from CLI output.
Source code in src/clawd_code_sdk/_errors.py
CLINotFoundError
¶
Bases: CLIConnectionError
Raised when Claude Code is not found or not installed.
Source code in src/clawd_code_sdk/_errors.py
CanUseToolShadowedWarning
¶
Bases: UserWarning
on_permission is a callback, but some tool calls are auto-approved before it runs.
Emitted on connect. The TypeScript SDK reports the same condition as a process warning
with code CLAUDE_SDK_CAN_USE_TOOL_SHADOWED. Suppress it with
warnings.filterwarnings("ignore", category=CanUseToolShadowedWarning).
Source code in src/clawd_code_sdk/_errors.py
ClaudeAgentOptions
dataclass
¶
Query options for Claude SDK.
Source code in src/clawd_code_sdk/models/options.py
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 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 | |
add_dirs
class-attribute
instance-attribute
¶
Add additional working directories.
agent
class-attribute
instance-attribute
¶
Agent name for the main thread. The agent must be defined in agents or settings.
agent_progress_summaries
class-attribute
instance-attribute
¶
Enable periodic AI-generated progress summaries for running subagents.
When True, the subagent's conversation is forked every ~30s to produce a short present-tense description (e.g. 'Analyzing authentication module'), emitted on task_progress events via the summary field. The fork reuses the subagent's model and prompt cache, so cost is typically minimal.
Applies to both foreground and background subagents. Defaults to False.
agents
class-attribute
instance-attribute
¶
agents: dict[str, AgentDefinition] | None = None
SubAgent definitions.
allow_dangerously_skip_permissions
class-attribute
instance-attribute
¶
Must be True when using permission_mode='bypassPermissions'.
allowed_tools
class-attribute
instance-attribute
¶
Tools which execute without prompting for permission.
capture_sdk_mcp_manifests
class-attribute
instance-attribute
¶
Do the in-process MCP servers' handshake before connecting and send its results.
The initialize request then carries each server's initialize and first
tools/list results (sdkMcpServerManifests), so the CLI connects them without
control round trips before the first turn. A server whose handshake fails, or that the
CLI does not take, is handshaken over the control channel as before. Off when the
CLAUDE_AGENT_SDK_DISABLE_MCP_MANIFESTS environment variable is set (as upstream).
chrome
class-attribute
instance-attribute
¶
Add the chrome-tools MCP server (-> Claude Code browser extension) to the agent.
cli_path
class-attribute
instance-attribute
¶
CLI path override (auto-detects by default).
context_1m
class-attribute
instance-attribute
¶
Enable 1M token context window (Sonnet 4/4.5 only).
cwd
class-attribute
instance-attribute
¶
The working directory for the agent.
debug_file
class-attribute
instance-attribute
¶
Write debug logs to a specific file path. Implicitly enables debug mode.
disable_parallel_tool_use
class-attribute
instance-attribute
¶
Disable parallel too use (only one tool_use block per response).
disallowed_tools
class-attribute
instance-attribute
¶
Tools that are removed from agent context and cant be used.
effort
class-attribute
instance-attribute
¶
Effort level for thinking depth.
enable_agent_teams
class-attribute
instance-attribute
¶
Enable the experimental agent teams feature.
enable_file_checkpointing
class-attribute
instance-attribute
¶
Enable file checkpointing to track file changes during the session.
When enabled, files can be rewound to their state at any user message
using ClaudeSDKClient.rewind_files().
enable_tool_search
class-attribute
instance-attribute
¶
Enable or disable MCP tool search.
When many MCP tools are configured, tool definitions can consume a significant portion of the context window. Tool search dynamically loads tools on-demand instead of preloading all of them.
True: Always enabled.False: Always disabled, all MCP tools loaded upfront."auto": Activates when MCP tools exceed 10% of context (default behavior).int: Auto-activates at this percentage threshold (e.g.5for 5%).None(default): Uses Claude Code's default (auto at 10%).
Requires models that support tool_reference blocks (Sonnet 4+, Opus 4+).
env
class-attribute
instance-attribute
¶
Environment variables for the CLI subprocess.
exclude_dynamic_sections
class-attribute
instance-attribute
¶
Whether to exclude dynamic sections from the system prompt.
extra_args
class-attribute
instance-attribute
¶
Arbitrary extra CLI flags.
fallback_model
class-attribute
instance-attribute
¶
Fallback model in case default one is overloaded.
fine_grained_tool_streaming
class-attribute
instance-attribute
¶
Stream tool input to the client as the model writes it (fine-grained tool streaming).
With it, stream_event messages carry tool input JSON as it is generated, so a UI can
show a long Write/Edit input live and the tool call starts sooner. It saves no
tokens. The partial tool input JSON is not validated by the API, and some endpoints
reject the request with HTTP 400 (proxies / gateways, some models on Bedrock and Vertex).
"auto"(default): on when the CLI talks to Anthropic's API directly (noCLAUDE_CODE_USE_BEDROCK/_VERTEX/ other provider env,ANTHROPIC_BASE_URLunset orapi.anthropic.com); otherwise the CLI's own default applies.True/False: force it on / off.
CLAUDE_CODE_ENABLE_FINE_GRAINED_TOOL_STREAMING in env overrides this option.
forward_subagent_text
class-attribute
instance-attribute
¶
Forward subagent text and thinking blocks as messages with parent_tool_use_id set.
By default only tool_use/tool_result blocks from subagents are emitted.
hooks
class-attribute
instance-attribute
¶
hooks: dict[HookEvent, list[HookMatcher]] | None = None
Hook configurations.
include_builtin_system_prompt
class-attribute
instance-attribute
¶
Whether to include Claude Code's builtin system prompt.
When True (default) and system_prompt is set, it is appended to the builtin system prompt. When False, the system_prompt replaces it entirely.
include_hook_events
class-attribute
instance-attribute
¶
Include hook lifecycle events in the output stream.
When True, hook_started, hook_progress, and hook_response system
messages will be emitted for all hook event types. SessionStart and Setup
hook events are always emitted regardless of this setting.
instrument
class-attribute
instance-attribute
¶
Whether to instrument the session with tracing hooks.
max_budget_usd
class-attribute
instance-attribute
¶
Maximum amount of USD budget which may be consumed.
max_buffer_size
class-attribute
instance-attribute
¶
Max bytes when buffering CLI stdout.
max_turns
class-attribute
instance-attribute
¶
Maximum allowed amount of agentic turns.
mcp_servers
class-attribute
instance-attribute
¶
MCP servers for the agent.
mcp_servers_delivery
class-attribute
instance-attribute
¶
How the mcp_servers that Claude Code runs or connects to (stdio, SSE, HTTP) reach it.
"initialize"(default): in the initialize request over stdin (the CLI is started with--await-initialize), so serverenvandheadersstay off the command line, where other users of the machine can read them. Needs Claude Code 2.1.261 or newer; connecting fails if the CLI does not take them (mcp_servers_applied)."argv": in one--mcp-configflag, for older Claude Code. Deprecated upstream.
In-process servers (McpSdkServerConfigWithInstance) and an mcp_servers file path
are not affected, and a launch with --sdk-url in extra_args always uses
--mcp-config, as that session cannot read the request at launch.
on_elicitation
class-attribute
instance-attribute
¶
on_elicitation: OnElicitation | None = None
Callback for handling MCP elicitation requests.
Called when an MCP server requests user input (form fields, URL auth, etc.) and no hook handles the request first.
If not provided, elicitation requests that aren't handled by hooks will be declined automatically.
on_permission
class-attribute
instance-attribute
¶
Permission handler for tool execution.
Accepts either:
- A callback function (CanUseTool): The SDK routes permission requests
through the control protocol to this callback. Automatically adds
--permission-prompt-tool stdio to the CLI.
- A string: Name of an MCP tool to handle permission prompts
(passed as --permission-prompt-tool <name> to the CLI).
- None: Default behavior.
Interaction with permission_mode:
"default": All tool calls are routed to this handler."acceptEdits": All tool calls are routed to this handler. The handler is responsible for implementing the auto-approve-edits policy."plan": Only the syntheticExitPlanModetool is routed here. Actual modification tools are blocked by the CLI before reaching the handler."dontAsk": This handler is NEVER invoked. The CLI auto-denies all tools not pre-approved via the permissions config internally."bypassPermissions": This handler is NEVER invoked. The CLI auto-approves all tools internally.
Tools that allowed_tools allows outright ("Read", "Read()", "Read(*)")
never reach the handler either. Connecting emits a CanUseToolShadowedWarning when
a callback is set together with "bypassPermissions" or such entries.
on_user_question
class-attribute
instance-attribute
¶
on_user_question: OnUserQuestion | None = None
Callback for handling AskUserQuestion elicitation requests.
Called when Claude asks the user a clarifying question via the AskUserQuestion tool. If not set, these requests fall through to on_permission (if it's a callback) for backwards compatibility.
output_schema
class-attribute
instance-attribute
¶
JSON schema for structured output.
Accepts either a JSON schema dict or a Python type (Pydantic model, dataclass, TypedDict, etc.) which will be converted to a JSON schema automatically.
When set, Claude will return responses conforming to this schema.
Examples:
As a dict¶
output_schema={"type": "object", "properties": {"name": {"type": "string"}}}
As a type¶
output_schema=MyPydanticModel
per_task_stop_affordance
class-attribute
instance-attribute
¶
Declare that this consumer can stop individual background tasks (stop_task).
When declared, an interrupt only aborts the current turn and spares running background agents/workflows.
permission_mode
class-attribute
instance-attribute
¶
Permission mode.
permission_prompts
class-attribute
instance-attribute
¶
Who answers permission prompts.
"host" (default): this process, through on_permission.
"none": nobody - permission mode, rules and hooks still decide, and anything
that would otherwise prompt is denied immediately.
plan_mode_instructions
class-attribute
instance-attribute
¶
Custom workflow body for the plan-mode system reminder.
plugin_delivery
class-attribute
instance-attribute
¶
How plugins reach Claude Code.
"argv"(default): one--plugin-dirflag per plugin. Works with any Claude Code version, but the command line grows with the plugin count (Windows refuses one past 32,767 characters)."initialize": in the initialize request over stdin (the CLI is started with--await-initialize); connecting fails if the CLI does not load them (plugins_applied). A launch with--sdk-urlinextra_argsalways uses argv.
plugins
class-attribute
instance-attribute
¶
plugins: list[SdkPluginConfig] = field(default_factory=list)
"Plugin configurations to load.
project_config_root
class-attribute
instance-attribute
¶
The trusted checkout that cwd is a worktree of.
Project settings, .mcp.json, the .claude config trees and
CLAUDE_PROJECT_DIR come from here instead of cwd. Absolute path.
prompt_suggestions
class-attribute
instance-attribute
¶
Whether to create prompt suggestions.
replay_user_messages
class-attribute
instance-attribute
¶
Whether to replay user messages in the session.
sandbox
class-attribute
instance-attribute
¶
sandbox: Sandbox | None = None
Sandbox configuration for bash command isolation.
Filesystem and network restrictions are derived from permission rules (Read/Edit/WebFetch), not from these sandbox settings.
session
class-attribute
instance-attribute
¶
session: str | SessionConfig | None = None
Session configuration.
Controls how the CLI session is started:
- None or NewSession(): Start a fresh session.
- "session-id" or ResumeSession(session_id="..."): Resume by ID.
- ContinueLatest(): Continue the most recent conversation.
setting_sources
class-attribute
instance-attribute
¶
Sources to load filesystem settings from.
None loads the CLI's defaults (user, project, local); [] loads none.
settings
class-attribute
instance-attribute
¶
settings: str | Path | ClaudeCodeSettings | None = None
Settings configuration.
Accepts:
- A str or Path: interpreted as a path to a settings JSON file.
- A ClaudeCodeSettings instance: serialized to JSON automatically.
- None: no explicit settings.
skills
class-attribute
instance-attribute
¶
List of skills to use for the agent.
stderr
class-attribute
instance-attribute
¶
Callback for stderr output from CLI.
strict_mcp_config
class-attribute
instance-attribute
¶
Enforce strict validation of MCP server configurations.
system_prompt
class-attribute
instance-attribute
¶
System prompt for the agent.
system_prompt_snapshot
class-attribute
instance-attribute
¶
Snapshot the system prompt on the first request and reuse it verbatim.
Keeps the prompt byte-identical across requests and resumes (better cache hits).
task_budget
class-attribute
instance-attribute
¶
API-side task budget in tokens.
When set, the model is made aware of its remaining token budget so it can
pace tool use and wrap up before the limit. The CLI sends this as
output_config.task_budget with the task-budgets-2026-03-13 beta
header automatically.
thinking
class-attribute
instance-attribute
¶
Controls thinking behavior.
tool_aliases
class-attribute
instance-attribute
¶
Redirect built-in tool names to other tools, e.g. {"Bash": "mcp__ws__bash"}.
Single-hop; complementary to disallowed_tools, not a replacement.
tool_config
class-attribute
instance-attribute
¶
tool_config: ToolConfig | None = None
Per-tool configuration for built-in tools.
tools
class-attribute
instance-attribute
¶
tools: list[ToolName | str] | ToolsPreset | None = None
Tools available to the agent.
verbatim_prompts
class-attribute
instance-attribute
¶
Send every user message with client_composed: true.
The CLI then delivers the prompt text as written: no @path expansion and
no slash-command dispatch. Requires Claude Code 2.1.248+.
worktree
class-attribute
instance-attribute
¶
Create a new git worktree for the session (with optional name).
argv_mcp_servers
¶
The servers for --mcp-config.
All of them, or only the in-process ones when the others go in the initialize request.
Source code in src/clawd_code_sdk/models/options.py
build_settings_value
¶
Build the CLI --settings value, merging sandbox if provided.
Returns:
| Type | Description |
|---|---|
str | None
|
A JSON string, a file path, or None. |
Source code in src/clawd_code_sdk/models/options.py
initialize_mcp_servers
¶
The servers to send in the initialize request, or None to send none there.
Source code in src/clawd_code_sdk/models/options.py
initialize_plugins
¶
The plugins to send in the initialize request, or None to pass them as flags.
Source code in src/clawd_code_sdk/models/options.py
reads_initialize_at_launch
¶
Whether the CLI waits for the initialize request (--await-initialize).
sdk_mcp_server_configs
¶
Settings of the in-process MCP servers (timeout, tool policy), by server name.
Source code in src/clawd_code_sdk/models/options.py
ClaudeCodeSettings
¶
Bases: ClaudeCodeBaseModel
Configuration settings for Claude Code. Learn more: https://code.claude.com/docs/en/settings.
Source code in src/clawd_code_sdk/models/settings.py
3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 | |
advisor_model
class-attribute
instance-attribute
¶
Model for the server-side advisor tool. Accepts a model alias ("opus", "sonnet", or "fable" on v2.1.170+) or a full model ID. Overridden by the --advisor CLI flag for the session, and blocked when the model is outside the availableModels allowlist. See https://code.claude.com/docs/en/advisor
agent
class-attribute
instance-attribute
¶
Name of an agent (built-in or custom) to use for the main thread. Applies the agent's system prompt, tool restrictions, and model. See https://code.claude.com/docs/en/sub-agents
agent_push_notif_enabled
class-attribute
instance-attribute
¶
When Remote Control is connected, allow Claude to send proactive push notifications to your phone, for example when a long task finishes. Requires Claude Code v2.1.119 or later. See https://code.claude.com/docs/en/remote-control#mobile-push-notifications
allow_all_claude_ai_mcps
class-attribute
instance-attribute
¶
(Managed settings only) Load claude.ai connectors alongside a deployed managed-mcp.json, which otherwise takes exclusive control and suppresses them. See https://code.claude.com/docs/en/managed-mcp
allow_managed_hooks_only
class-attribute
instance-attribute
¶
(Managed settings only) Prevent loading of user, project, and plugin hooks. Only allows managed hooks and SDK hooks. See https://code.claude.com/docs/en/settings#hook-configuration
allow_managed_mcp_servers_only
class-attribute
instance-attribute
¶
(Managed settings only) When true, only allowedMcpServers from managed settings are respected; MCP servers defined in user, project, or local settings are ignored. deniedMcpServers still merges from all sources. See https://code.claude.com/docs/en/managed-mcp
allow_managed_permission_rules_only
class-attribute
instance-attribute
¶
allow_managed_permission_rules_only: bool | None = Field(
None, alias="allowManagedPermissionRulesOnly"
)
(Managed settings only) Prevent user and project settings from defining allow, ask, or deny permission rules. Only rules in managed settings apply. See https://code.claude.com/docs/en/settings#permission-settings
allowed_channel_plugins
class-attribute
instance-attribute
¶
allowed_channel_plugins: list[AllowedChannelPlugin] | None = Field(
None, alias="allowedChannelPlugins"
)
(Managed settings only) Allowlist of channel plugins that may run, each identified by its marketplace and plugin name. When set, only the listed plugins can push inbound channel messages while channelsEnabled is true. Replaces the default Anthropic allowlist when set; undefined falls back to the default and an empty array blocks all channel plugins. Requires channelsEnabled: true. See https://code.claude.com/docs/en/channels#restrict-which-channel-plugins-can-run
allowed_http_hook_urls
class-attribute
instance-attribute
¶
allowed_http_hook_urls: list[AllowedHttpHookUrl] | None = Field(
None,
alias="allowedHttpHookUrls",
examples=[["https://hooks.example.com/*", "http://localhost:*"]],
)
Allowlist of URL patterns that HTTP hooks may target. Supports * as a wildcard. When set, hooks with non-matching URLs are blocked. Undefined = no restriction, empty array = block all HTTP hooks. Arrays merge across settings sources. See https://code.claude.com/docs/en/settings#hook-configuration
allowed_mcp_servers
class-attribute
instance-attribute
¶
allowed_mcp_servers: (
list[
AllowedMcpServerByServerName | AllowedMcpServerByServerCommand | AllowedMcpServerByServerUrl
]
| None
) = Field(None, alias="allowedMcpServers")
Enterprise allowlist of MCP servers that can be used. Applies to all scopes including enterprise servers from managed-mcp.json. If undefined, all servers are allowed. If empty array, no servers are allowed. Denylist takes precedence - if a server is on both lists, it is denied. See https://code.claude.com/docs/en/mcp#restriction-options
always_thinking_enabled
class-attribute
instance-attribute
¶
Enable extended thinking by default for all sessions. Typically configured via the /config command rather than editing directly. See https://code.claude.com/docs/en/common-workflows#use-extended-thinking-thinking-mode
api_key_helper
class-attribute
instance-attribute
¶
api_key_helper: str | None = Field(
None, alias="apiKeyHelper", examples=["/bin/generate_temp_api_key.sh"], min_length=1
)
Path to a script that outputs authentication values. See https://code.claude.com/docs/en/settings#available-settings
ask_user_question_timeout
class-attribute
instance-attribute
¶
ask_user_question_timeout: Literal["60s", "5m", "10m", "never"] | None = Field(
"never", alias="askUserQuestionTimeout"
)
Idle time before an unanswered AskUserQuestion dialog auto-continues with whatever options you had already selected. Accepts "60s", "5m", "10m", or "never" (default: "never", which waits until you answer). Appears in /config as Question auto-continue timeout, which writes this key to user settings. Not read from project or local settings. Requires Claude Code v2.1.200 or later. See https://code.claude.com/docs/en/settings#available-settings
attribution
class-attribute
instance-attribute
¶
attribution: Attribution | None = None
Customize attribution for git commits and pull requests. See https://code.claude.com/docs/en/settings#attribution-settings
auto_compact_enabled
class-attribute
instance-attribute
¶
Automatically compact the conversation when context approaches the limit. Also configurable via the DISABLE_AUTO_COMPACT environment variable. See https://code.claude.com/docs/en/settings#available-settings
auto_connect_ide
class-attribute
instance-attribute
¶
Automatically connect to a running IDE when Claude Code starts from an external terminal (default: false). Appears in /config as Auto-connect to IDE (external terminal) when running outside a VS Code or JetBrains terminal. Also configurable via the CLAUDE_CODE_AUTO_CONNECT_IDE environment variable, which overrides this when set. See https://code.claude.com/docs/en/settings#global-config-settings
auto_install_ide_extension
class-attribute
instance-attribute
¶
Automatically install the Claude Code IDE extension when running from a VS Code terminal (default: true). Appears in /config as Auto-install IDE extension when running inside a VS Code or JetBrains terminal. You can also set the CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL environment variable to 1. See https://code.claude.com/docs/en/settings#global-config-settings
auto_memory_directory
class-attribute
instance-attribute
¶
Custom directory path for auto-memory storage. Supports ~/ prefix for home-directory expansion. Ignored if set in checked-in project settings (.claude/settings.json) for security. Defaults to ~/.claude/projects/<sanitized-cwd>/memory/ when unset. See https://code.claude.com/docs/en/memory
auto_memory_enabled
class-attribute
instance-attribute
¶
Enable automatic memory saves that capture useful context to ~/.claude/projects/<project>/memory/ (derived from the git repository, shared across worktrees). Also configurable via CLAUDE_CODE_DISABLE_AUTO_MEMORY environment variable (set to 1 to disable, 0 to enable). See https://code.claude.com/docs/en/memory#storage-location
auto_mode
class-attribute
instance-attribute
¶
auto_mode: AutoMode | None = Field(None, alias='autoMode')
Customization for the auto mode classifier prompt. Typically configured in managed settings to tune the allow/deny rules used when permissions.defaultMode is "auto". By default, allow, soft_deny, and environment REPLACE the corresponding built-in classifier section entirely. Include the literal string "$defaults" as an array entry (added in v2.1.118) to splice the built-in defaults in at that position alongside your custom rules. See https://code.claude.com/docs/en/permissions
auto_scroll_enabled
class-attribute
instance-attribute
¶
In fullscreen rendering, follow new output to the bottom of the conversation. Appears in /config as Auto-scroll. Permission prompts still scroll into view when this is off. See https://code.claude.com/docs/en/fullscreen
auto_updates_channel
class-attribute
instance-attribute
¶
auto_updates_channel: Literal["stable", "latest"] | None = Field(
"latest", alias="autoUpdatesChannel"
)
Release channel to follow for updates. Use "stable" for a version that is typically about one week old and skips versions with major regressions, or "latest" (default) for the most recent release. Set DISABLE_AUTOUPDATER=1 to disable background auto-updates, or DISABLE_UPDATES=1 (added in v2.1.118) to block all update paths including manual claude update.
available_models
class-attribute
instance-attribute
¶
available_models: list[str] | None = Field(
None, alias="availableModels", examples=[["sonnet", "haiku"]]
)
Restrict which models users can select. When defined at multiple settings levels (user, project, etc.), arrays are merged and deduplicated. See https://code.claude.com/docs/en/model-config#restrict-model-selection
away_summary_enabled
class-attribute
instance-attribute
¶
Show a one-line session recap when you return to the terminal after a few minutes away. Set to false (or turn off Session recap in /config) to disable. See https://code.claude.com/docs/en/settings#available-settings
aws_auth_refresh
class-attribute
instance-attribute
¶
aws_auth_refresh: str | None = Field(
None, alias="awsAuthRefresh", examples=["aws sso login --profile myprofile"], min_length=1
)
Command to run when AWS credentials are expired or unavailable; its output is shown to the user but interactive input is not supported. Also drives the "Claude Platform on AWS · refresh credentials" option in /login when configured. See https://code.claude.com/docs/en/amazon-bedrock#advanced-credential-configuration
aws_credential_export
class-attribute
instance-attribute
¶
aws_credential_export: str | None = Field(
None, alias="awsCredentialExport", examples=["/bin/generate_aws_grant.sh"], min_length=1
)
Command that outputs AWS credentials as JSON (in the form {"Credentials": {"AccessKeyId": ..., "SecretAccessKey": ..., "SessionToken": ...}}). The output is captured silently. Use when you cannot modify the .aws directory and must return credentials directly. See https://code.claude.com/docs/en/amazon-bedrock#advanced-credential-configuration
ax_screen_reader
class-attribute
instance-attribute
¶
Render screen-reader-friendly output: flat text without decorative borders or animations screen-reader mode always uses the classic renderer, so the tui setting has no effect while it is active. The CLAUDE_AX_SCREEN_READER environment variable and --ax-screen-reader flag take precedence. Requires Claude Code v2.1.181 or later. See https://code.claude.com/docs/en/settings#available-settings
blocked_marketplaces
class-attribute
instance-attribute
¶
blocked_marketplaces: (
list[
BlockedMarketplaceUrl
| BlockedMarketplaceGithub
| BlockedMarketplaceGit
| BlockedMarketplaceNpm
| BlockedMarketplaceFile
| BlockedMarketplaceDirectory
| BlockedMarketplaceHostPattern
| BlockedMarketplacePathPattern
| BlockedMarketplaceSkillsDir
]
| None
) = Field(None, alias="blockedMarketplaces")
(Managed settings only) Blocklist of marketplace sources. These exact sources are blocked from being added as marketplaces. The check happens before downloading, so blocked sources never touch the filesystem.
browser_external_page_tools
class-attribute
instance-attribute
¶
browser_external_page_tools: Literal["disabled"] | None = Field(
None, alias="browserExternalPageTools"
)
(Managed settings only) Set to "disabled" to prevent Claude from using tools to read or act on external pages in the desktop app's Browser pane. Users can still navigate to external sites themselves, and local dev server previews are unaffected. See https://code.claude.com/docs/en/desktop#browse-external-sites
channels_enabled
class-attribute
instance-attribute
¶
(Managed settings only) Allow channels for the organization. On claude.ai Team and Enterprise plans, channels are blocked when this is unset or false. For Anthropic Console accounts using API key authentication, channels are allowed by default unless the organization deploys managed settings, in which case this key must be set to true. See https://code.claude.com/docs/en/channels#enterprise-controls
claude_md
class-attribute
instance-attribute
¶
(Managed settings only) CLAUDE.md-style instructions injected as organization-managed memory. Honored only from managed/policy settings. See https://code.claude.com/docs/en/settings#available-settings
claude_md_excludes
class-attribute
instance-attribute
¶
claude_md_excludes: list[ClaudeMdExclude] | None = Field(
None,
alias="claudeMdExcludes",
examples=[["**/monorepo/CLAUDE.md", "/home/user/monorepo/other-team/.claude/rules/**"]],
)
Glob patterns for CLAUDE.md files to exclude from loading. Useful in monorepos to skip irrelevant instructions from other teams. Patterns match against absolute file paths. Arrays merge across settings layers. Managed policy CLAUDE.md files cannot be excluded. See https://code.claude.com/docs/en/memory#exclude-specific-claude-md-files
cleanup_period_days
class-attribute
instance-attribute
¶
Number of days to retain sessions, orphaned subagent worktrees, tasks, shell snapshots, and backups. Minimum is 1; setting 0 is rejected with a validation error. See https://code.claude.com/docs/en/settings#available-settings
company_announcements
class-attribute
instance-attribute
¶
Company announcements to display at startup (one will be randomly selected if multiple are provided)
default_shell
class-attribute
instance-attribute
¶
Default shell for input-box ! commands. Default: bash. Using "powershell" routes ! commands through PowerShell on Windows and requires CLAUDE_CODE_USE_POWERSHELL_TOOL=1 with pwsh on PATH. See https://code.claude.com/docs/en/settings#available-settings
denied_mcp_servers
class-attribute
instance-attribute
¶
denied_mcp_servers: (
list[DeniedMcpServerByServerName | DeniedMcpServerByServerCommand | DeniedMcpServerByServerUrl]
| None
) = Field(None, alias="deniedMcpServers")
Enterprise denylist of MCP servers that are explicitly blocked. If a server is on the denylist, it will be blocked across all scopes including enterprise. Denylist takes precedence over allowlist - if a server is on both lists, it is denied. See https://code.claude.com/docs/en/mcp#restriction-options
diff_tool
class-attribute
instance-attribute
¶
Where to display file diffs when an IDE is connected: "auto" (default) opens diffs in the IDE's diff viewer, "terminal" keeps them in the terminal. Appears in /config as Diff tool only when Claude Code is connected to a VS Code or JetBrains IDE. See https://code.claude.com/docs/en/settings#global-config-settings
disable_agent_view
class-attribute
instance-attribute
¶
(Managed settings) Turn off background agents and the agent view: claude agents, --bg, /background, and the on-demand supervisor. Also configurable via the CLAUDE_CODE_DISABLE_AGENT_VIEW environment variable (set to 1 to disable). See https://code.claude.com/docs/en/agent-view
disable_all_hooks
class-attribute
instance-attribute
¶
Disable all hooks and statusLine execution. When true in managed settings, user and project-level disableAllHooks cannot override it. See https://code.claude.com/docs/en/hooks#disable-or-remove-hooks
disable_artifact
class-attribute
instance-attribute
¶
Disable the Artifact tool, which publishes session output as a private web page on claude.ai. Also configurable via the CLAUDE_CODE_DISABLE_ARTIFACT environment variable. See https://code.claude.com/docs/en/settings#available-settings
disable_auto_mode
class-attribute
instance-attribute
¶
Set to "disable" to prevent auto mode from being activated: removes auto from the Shift+Tab cycle and rejects --permission-mode auto at startup. See https://code.claude.com/docs/en/settings#available-settings
disable_browser_external_navigation
class-attribute
instance-attribute
¶
disable_browser_external_navigation: bool | None = Field(
None, alias="disableBrowserExternalNavigation"
)
(Managed settings only) Set to true to turn off external browsing in the desktop app's Browser pane. Neither users nor Claude can navigate to external sites, and localhost dev server previews are unaffected. The value must be the JSON boolean true; the string "true" is ignored. See https://code.claude.com/docs/en/desktop#browse-external-sites
disable_bundled_skills
class-attribute
instance-attribute
¶
Disable the skills and workflows that ship with Claude Code: bundled skills and workflows are removed entirely, while built-in slash commands like /init stay typable but are hidden from the model. Skills from plugins, .claude/skills/, and .claude/commands/ are unaffected. Also configurable via the CLAUDE_CODE_DISABLE_BUNDLED_SKILLS environment variable. See https://code.claude.com/docs/en/settings#available-settings
disable_claude_ai_connectors
class-attribute
instance-attribute
¶
Disable claude.ai MCP connectors so they are not auto-fetched or connected. A value of true in any settings source takes precedence. Requires Claude Code v2.1.182 or later. See https://code.claude.com/docs/en/settings#available-settings
disable_deep_link_registration
class-attribute
instance-attribute
¶
disable_deep_link_registration: Literal["disable"] | None = Field(
None, alias="disableDeepLinkRegistration"
)
Set to "disable" to prevent Claude Code from registering the claude-cli:// deep-link protocol handler on startup. Most useful in managed settings where users cannot override it. See https://code.claude.com/docs/en/settings#available-settings
disable_mobile_simulator_tools
class-attribute
instance-attribute
¶
(Managed settings only) Set to true to block Claude's tools for the desktop app's iOS Simulator pane. Users keep manual use of the pane; only Claude's access is removed. The value must be the JSON boolean true; any other value is ignored, and a malformed value such as "true" or 1 logs a warning. See https://code.claude.com/docs/en/desktop-ios-simulator#turn-off-simulator-access
disable_remote_control
class-attribute
instance-attribute
¶
Disable Remote Control: blocks claude remote-control, the --remote-control flag, auto-start, and the in-session toggle. Requires Claude Code v2.1.128 or later. See https://code.claude.com/docs/en/remote-control
disable_sideload_flags
class-attribute
instance-attribute
¶
(Managed settings only) Reject the --plugin-dir, --plugin-url, --agents, and --mcp-config CLI flags at startup, which users could otherwise pass to bypass strictKnownMarketplaces for a single run. Also rejects these flags from any surface that spawns the CLI with them internally, currently Cowork local sessions in the desktop app. A --mcp-config whose servers are all in-process type: "sdk" entries is still accepted, so the Agent SDK and VS Code extension keep working. Does not block claude mcp add, .mcp.json, or SDK setMcpServers(); pair with allowedMcpServers for per-server MCP control. Requires Claude Code v2.1.193 or later. See https://code.claude.com/docs/en/settings#available-settings
disable_skill_shell_execution
class-attribute
instance-attribute
¶
Disable inline shell execution for !`...` and ```! blocks in skills and custom slash commands from user, project, plugin, or additional-directory sources. Commands are replaced with [shell command execution disabled by policy] instead of being run. Bundled and managed skills are not affected. Most useful in managed settings where users cannot override it. See https://code.claude.com/docs/en/settings#available-settings
disable_workflows
class-attribute
instance-attribute
¶
Disable dynamic workflows and bundled workflow commands. Also configurable via the CLAUDE_CODE_DISABLE_WORKFLOWS environment variable. See https://code.claude.com/docs/en/settings#available-settings
disabled_mcpjson_servers
class-attribute
instance-attribute
¶
disabled_mcpjson_servers: list[DisabledMcpjsonServer] | None = Field(
None, alias="disabledMcpjsonServers", examples=[["filesystem"]]
)
List of rejected MCP servers from .mcp.json. See https://code.claude.com/docs/en/mcp
editor_mode
class-attribute
instance-attribute
¶
Key binding mode for the input prompt: "normal" or "vim". Appears in /config as Editor mode. See https://code.claude.com/docs/en/terminal-config#edit-prompts-with-vim-keybindings
effort_level
class-attribute
instance-attribute
¶
effort_level: Literal["low", "medium", "high", "xhigh", "max"] | None = Field(
None, alias="effortLevel"
)
Persist adaptive reasoning effort across sessions. Set to low, medium, high, or xhigh; max and ultracode are session-only and are not accepted in the settings file (use the CLAUDE_CODE_EFFORT_LEVEL environment variable or /effort for a session-only max). Effort is supported on Fable 5, Opus 4.8, Opus 4.7, Opus 4.6, and Sonnet 4.6, with xhigh sitting between high and max (added in v2.1.111). Defaults: Fable 5 and Opus 4.8 default to high; Opus 4.6 and Sonnet 4.6 default to high on all plans (Pro/Max raised from medium to high in v2.1.117); Opus 4.7 defaults to xhigh. Use /effort auto to reset to model default. Also configurable via CLAUDE_CODE_EFFORT_LEVEL environment variable. See https://code.claude.com/docs/en/model-config#adjust-effort-level
emoji_completion_enabled
class-attribute
instance-attribute
¶
Show emoji suggestions when you type : plus a shortcode in the prompt input, and replace a completed shortcode such as
with its emoji (default: true). Set to false to disable both. Requires Claude Code v2.1.217 or later. See https://code.claude.com/docs/en/interactive-mode#emoji-shortcodes
enable_all_project_mcp_servers
class-attribute
instance-attribute
¶
enable_all_project_mcp_servers: bool | None = Field(
None, alias="enableAllProjectMcpServers", examples=[True]
)
Whether to automatically approve all MCP servers in the project. See https://code.claude.com/docs/en/mcp
enable_artifact
class-attribute
instance-attribute
¶
Enable or disable the Artifact tool for this user. When unset, the default follows the feature's availability for your account. The Artifacts row in /config writes this key. A managed disableArtifact and your organization's admin setting take precedence, and the key is ignored in project and local settings (.claude/settings.json, .claude/settings.local.json), which a repository could otherwise commit. Requires Claude Code v2.1.196 or later. See https://code.claude.com/docs/en/artifacts
enabled_mcpjson_servers
class-attribute
instance-attribute
¶
enabled_mcpjson_servers: list[EnabledMcpjsonServer] | None = Field(
None, alias="enabledMcpjsonServers", examples=[["memory", "github"]]
)
List of approved MCP servers from .mcp.json. See https://code.claude.com/docs/en/mcp
enabled_plugins
class-attribute
instance-attribute
¶
Enabled plugins using plugin-id@marketplace-id format. Example: { "formatter@anthropic-tools": true }. See https://code.claude.com/docs/en/plugins
enforce_available_models
class-attribute
instance-attribute
¶
(Managed settings) Extend the availableModels allowlist to the Default model option (requires v2.1.175+). Requires a non-empty availableModels list; when the account-type default is not in the allowlist, Default resolves to the first allowed entry instead. Has no effect when availableModels is unset or empty. See https://code.claude.com/docs/en/model-config#enforce-the-allowlist-for-the-default-model
env
class-attribute
instance-attribute
¶
env: Env | None = Field(
default_factory=lambda: Env.model_validate({}),
examples=[
{
"ANTHROPIC_MODEL": "claude-opus-4-1",
"ANTHROPIC_SMALL_FAST_MODEL": "claude-3-5-haiku-latest",
}
],
)
Environment variables to set for Claude Code sessions. Many environment variables provide settings dimensions not available as dedicated settings.json properties (e.g., thinking tokens, prompt caching, bash timeouts, shell configuration). See https://code.claude.com/docs/en/settings#environment-variables for the full list.
external_editor_context
class-attribute
instance-attribute
¶
Prepend Claude's previous response as #-commented context when you open the external editor with Ctrl+G (default: false). Appears in /config as Show last response in external editor. See https://code.claude.com/docs/en/settings#global-config-settings
extra_known_marketplaces
class-attribute
instance-attribute
¶
extra_known_marketplaces: dict[str, ExtraKnownMarketplaces] | None = Field(
None, alias="extraKnownMarketplaces"
)
Additional marketplaces to make available for this repository. Typically used in repository .claude/settings.json to ensure team members have required plugin sources. See https://code.claude.com/docs/en/plugin-marketplaces
fallback_model
class-attribute
instance-attribute
¶
Fallback model chain tried in order when the primary model is overloaded, unavailable, or returns a non-retryable server error. Capped at three entries after deduplication; accepts model names or aliases, and "default" expands to the account-type default. Overridden by the --fallback-model CLI flag for the session. See https://code.claude.com/docs/en/model-config#fallback-model-chains
fast_mode
class-attribute
instance-attribute
¶
Enable fast mode, which uses Claude Opus 5 by default (since v2.1.219) for faster output at higher per-token cost without downgrading to a smaller model. Requires extra usage enabled. Toggle with the /fast command. Supported on Opus 5 and Opus 4.8; fast mode for Opus 4.7 was deprecated on June 25, 2026 and removed on July 24, 2026. Before v2.1.219 fast mode defaulted to Opus 4.8 (v2.1.154 through v2.1.218) and to Opus 4.7 (v2.1.142 through v2.1.153). See https://code.claude.com/docs/en/fast-mode
fast_mode_per_session_opt_in
class-attribute
instance-attribute
¶
Require per-session opt-in for fast mode. When true, fast mode does not persist across sessions and users must enable it with /fast each session. Useful for controlling costs. See https://code.claude.com/docs/en/fast-mode
feedback_survey_rate
class-attribute
instance-attribute
¶
feedback_survey_rate: float | None = Field(
None, alias="feedbackSurveyRate", examples=[0.05], ge=0.0, le=1.0
)
Probability (0–1) that the session quality survey appears when eligible. A value of 0.05 means 5% of eligible sessions. See https://code.claude.com/docs/en/settings#available-settings
field_schema
class-attribute
instance-attribute
¶
JSON Schema reference for Claude Code settings
file_checkpointing_enabled
class-attribute
instance-attribute
¶
Snapshot edited files so /rewind can restore them. Also configurable via the CLAUDE_CODE_DISABLE_FILE_CHECKPOINTING environment variable (set to 1 to disable). See https://code.claude.com/docs/en/checkpointing
file_suggestion
class-attribute
instance-attribute
¶
file_suggestion: FileSuggestion | None = Field(
None,
alias="fileSuggestion",
examples=[{"type": "command", "command": "~/.claude/file-suggestion.sh"}],
)
Configure a custom script for @ file autocomplete. See https://code.claude.com/docs/en/settings#file-suggestion-settings
footer_links_regexes
class-attribute
instance-attribute
¶
footer_links_regexes: list[FooterLinksRegex] | None = Field(None, alias='footerLinksRegexes')
Render extra clickable badges in the footer when a regex matches turn output (tool results and assistant responses). Read from user, --settings flag, and managed settings only; ignored in project and local settings. Requires Claude Code v2.1.176 or later. See https://code.claude.com/docs/en/settings#available-settings
force_login_gateway_url
class-attribute
instance-attribute
¶
force_login_gateway_url: str | None = Field(
None, alias="forceLoginGatewayUrl", examples=["https://claude-gateway.example.com"]
)
Pre-fills and locks the gateway URL on the /login Cloud gateway screen. Either this key or forceLoginMethod: "gateway" surfaces that screen; set both so the URL is filled in. Honored only at the managed policy tier; ignored in user and project settings. See https://code.claude.com/docs/en/claude-apps-gateway#set-the-gateway-url
force_login_method
class-attribute
instance-attribute
¶
force_login_method: Literal["claudeai", "console", "gateway"] | None = Field(
None, alias="forceLoginMethod", examples=["claudeai"]
)
Use "claudeai" to restrict login to Claude.ai accounts, "console" to restrict login to Claude Console accounts, or "gateway" to restrict login to a cloud gateway. On Claude Code v2.1.212 or later, every first-party login path enforces the restriction, including the VS Code extension, the Agent SDK, claude setup-token, and /install-github-app; before v2.1.212, only terminal logins enforced it. See https://code.claude.com/docs/en/authentication#restrict-login-to-your-organization
force_login_org_uuid
class-attribute
instance-attribute
¶
force_login_org_uuid: ForceLoginOrgUuid | list[ForceLoginOrgUuidItem] | None = Field(
None, alias="forceLoginOrgUUID", examples=["xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"]
)
Organization UUID to use for OAuth login, or an array of UUIDs to allow several organizations. An empty array fails closed and blocks every login. See https://code.claude.com/docs/en/authentication#restrict-login-to-your-organization
force_remote_settings_refresh
class-attribute
instance-attribute
¶
(Managed settings only) Block CLI startup until remote managed settings are freshly fetched from the server. If the fetch fails, the CLI exits (fail-closed) rather than continuing with cached settings. When not set, startup continues without waiting for remote settings. See https://code.claude.com/docs/en/server-managed-settings
gcp_auth_refresh
class-attribute
instance-attribute
¶
gcp_auth_refresh: str | None = Field(
None, alias="gcpAuthRefresh", examples=["gcloud auth application-default login"], min_length=1
)
Command to run when GCP credentials are expired or cannot be loaded. The command's output is displayed to the user but interactive input is not supported; it times out after three minutes. See https://code.claude.com/docs/en/google-vertex-ai#advanced-credential-configuration
hooks
class-attribute
instance-attribute
¶
hooks: Hooks | None = Field(
None,
examples=[
{
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [{"type": "command", "command": "prettier --write", "timeout": 5}],
}
]
}
],
)
Lifecycle event hooks that run at configurable points during Claude Code operation (tool use, session start/end, notifications, prompt submit, message display, and more), not just before/after tool executions. See https://code.claude.com/docs/en/hooks
http_hook_allowed_env_vars
class-attribute
instance-attribute
¶
http_hook_allowed_env_vars: list[HttpHookAllowedEnvVar] | None = Field(
None, alias="httpHookAllowedEnvVars", examples=[["MY_TOKEN", "HOOK_SECRET"]]
)
Allowlist of environment variable names HTTP hooks may interpolate into headers. When set, each hook's effective allowedEnvVars is the intersection with this list. Undefined = no restriction. Arrays merge across settings sources. See https://code.claude.com/docs/en/settings#hook-configuration
include_co_authored_by
class-attribute
instance-attribute
¶
DEPRECATED. Use 'attribution' instead. Whether to include the co-authored-by Claude byline in git commits and pull requests (default: true)
include_git_instructions
class-attribute
instance-attribute
¶
Include built-in git commit and PR workflow instructions in Claude's system prompt. Also configurable via CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS environment variable (set to 1 to disable). See https://code.claude.com/docs/en/settings#available-settings
input_needed_notif_enabled
class-attribute
instance-attribute
¶
When Remote Control is connected, send a push notification to your phone when a permission prompt or question is waiting for input. Requires Claude Code v2.1.119 or later. See https://code.claude.com/docs/en/settings#available-settings
language
class-attribute
instance-attribute
¶
Configure Claude's preferred response language (e.g., "japanese", "spanish", "french"). Claude will respond in this language by default. Also sets the voice dictation language and terminal tab session title generation. See https://code.claude.com/docs/en/settings#available-settings
managed_mcp_servers
class-attribute
instance-attribute
¶
(Managed settings, third-party Desktop deployments only) MCP server configurations pushed to all users. Each entry specifies the transport and connection details, plus an optional toolPolicy map. Delivered through the managed settings file or MDM. See https://code.claude.com/docs/en/desktop#enterprise-configuration
minimum_version
class-attribute
instance-attribute
¶
Minimum Claude Code version to stay on. Prevents downgrades when switching release channels. See https://code.claude.com/docs/en/settings#available-settings
model
class-attribute
instance-attribute
¶
Override the default model used by Claude Code. For finer control, use environment variables: ANTHROPIC_MODEL (runtime override), ANTHROPIC_DEFAULT_OPUS_MODEL, ANTHROPIC_DEFAULT_SONNET_MODEL, ANTHROPIC_DEFAULT_HAIKU_MODEL (per-class pinning), CLAUDE_CODE_SUBAGENT_MODEL (subagent model). See https://code.claude.com/docs/en/model-config
model_overrides
class-attribute
instance-attribute
¶
model_overrides: dict[str, str] | None = Field(
None,
alias="modelOverrides",
examples=[
{
"claude-opus-4-6": "arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/opus-prod"
}
],
)
Map Anthropic model IDs to provider-specific model IDs such as Bedrock inference profile ARNs, Vertex AI version names, or Foundry deployment names. Each model picker entry uses its mapped value when calling the provider API. Unknown keys are ignored. See https://code.claude.com/docs/en/model-config#override-model-ids-per-version
otel_headers_helper
class-attribute
instance-attribute
¶
Path to an executable, or a shell command line with arguments, that outputs OpenTelemetry headers as a JSON object. Runs at startup and re-runs on the interval set by CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS. Requires CLAUDE_CODE_ENABLE_TELEMETRY=1. See https://code.claude.com/docs/en/monitoring-usage#dynamic-headers
output_style
class-attribute
instance-attribute
¶
output_style: str | None = Field(
None,
alias="outputStyle",
examples=["default", "Proactive", "Explanatory", "Learning"],
min_length=1,
)
Controls the output style for assistant responses. Built-in styles: default, Proactive, Explanatory, Learning. Custom styles can be added in ~/.claude/output-styles/ or .claude/output-styles/. See https://code.claude.com/docs/en/output-styles
parent_settings_behavior
class-attribute
instance-attribute
¶
parent_settings_behavior: Literal["first-wins", "merge"] | None = Field(
"first-wins", alias="parentSettingsBehavior"
)
(Admin/managed settings only) Controls how SDK managedSettings (parent tier) merge with inherited settings. 'first-wins': first non-empty value applies (default). 'merge': merge arrays and objects. See https://code.claude.com/docs/en/server-managed-settings
permission_explainer_enabled
class-attribute
instance-attribute
¶
Show a model-generated explanation of the command when you press Ctrl+E on a Bash or PowerShell permission prompt (default: true). Set to false to turn the shortcut off. See https://code.claude.com/docs/en/permissions#permission-system
permissions
class-attribute
instance-attribute
¶
permissions: Permissions | None = Field(
None,
examples=[
{
"allow": ["Bash(git add:*)"],
"ask": ["Bash(gh pr create:*)", "Bash(git commit:*)"],
"deny": ["Read(*.env)", "Bash(rm:*)", "Bash(curl:*)"],
"defaultMode": "default",
}
],
)
Tool usage permissions configuration. See https://code.claude.com/docs/en/permissions and https://code.claude.com/docs/en/settings#permission-settings See https://code.claude.com/docs/en/tools-reference for full list of tools available to Claude.
plans_directory
class-attribute
instance-attribute
¶
plans_directory: str | None = Field("~/.claude/plans", alias="plansDirectory", examples=["./plans"])
Customize where plan files are stored. Path is relative to project root (default: ~/.claude/plans)
plugin_configs
class-attribute
instance-attribute
¶
plugin_configs: dict[str, PluginConfigs] | None = Field(None, alias='pluginConfigs')
Per-plugin configuration including MCP server user configs and plugin options, keyed by plugin ID (plugin@marketplace format). See https://code.claude.com/docs/en/plugins
plugin_suggestion_marketplaces
class-attribute
instance-attribute
¶
plugin_suggestion_marketplaces: list[str] | None = Field(None, alias="pluginSuggestionMarketplaces")
(Managed settings only) Allowlist of marketplace names whose plugins may surface as contextual "suggested for this directory" tips in the /plugin Discover tab. No marketplace-declared suggestions surface without this allowlist. The built-in first-party frontend-design tip is unaffected. See https://code.claude.com/docs/en/settings#available-settings
plugin_trust_message
class-attribute
instance-attribute
¶
(Managed settings only) Custom message appended to the plugin trust warning shown before installation. Use to provide organization-specific context about approved plugins. See https://code.claude.com/docs/en/settings#plugin-settings
policy_helper
class-attribute
instance-attribute
¶
policy_helper: PolicyHelper | None = Field(None, alias='policyHelper')
Admin-deployed executable that computes managed settings dynamically at startup. Honored only from MDM or the system managed-settings.json. Requires Claude Code v2.1.136 or later. See https://code.claude.com/docs/en/settings#available-settings
pr_url_template
class-attribute
instance-attribute
¶
pr_url_template: str | None = Field(
None,
alias="prUrlTemplate",
examples=["https://reviews.example.com/{owner}/{repo}/pull/{number}"],
)
URL template for the PR badge shown in the footer and in tool-result summaries. Substitutes placeholders {host}, {owner}, {repo}, {number}, {url} from the gh-reported PR URL. Use this to point PR links at an internal code-review tool instead of github.com. Does not affect #123 autolinks in Claude's prose. See https://code.claude.com/docs/en/settings#available-settings
preferred_notif_channel
class-attribute
instance-attribute
¶
preferred_notif_channel: (
Literal[
"auto",
"terminal_bell",
"iterm2",
"iterm2_with_bell",
"kitty",
"ghostty",
"notifications_disabled",
]
| None
) = Field("auto", alias="preferredNotifChannel")
Method for task-complete and permission-prompt notifications. "auto" (default) sends a desktop notification in iTerm2, Ghostty, and Kitty and does nothing in other terminals; "terminal_bell" rings the bell in any terminal; "notifications_disabled" turns them off. See https://code.claude.com/docs/en/terminal-config#get-a-terminal-bell-or-notification
prefers_reduced_motion
class-attribute
instance-attribute
¶
Reduce or disable UI animations (spinners, shimmer, flash effects) for accessibility
process_wrapper
class-attribute
instance-attribute
¶
process_wrapper: str | None = Field(
None, alias="processWrapper", examples=["/opt/corp/launcher --profile claude"]
)
Corporate launcher command placed in front of the background processes Claude Code starts. Honored from managed settings, a --settings file, and user settings only; the CLAUDE_CODE_PROCESS_WRAPPER environment variable takes precedence when both are set. Requires Claude Code v2.1.210 or later. See https://code.claude.com/docs/en/corporate-launcher
remote_control_at_startup
class-attribute
instance-attribute
¶
Connect Remote Control automatically when each interactive session starts. true = always, false = never, unset = organization default. Requires Claude Code v2.1.119 or later. See https://code.claude.com/docs/en/remote-control#enable-remote-control-for-all-sessions
require_cowork_full_vm_sandbox
class-attribute
instance-attribute
¶
(Managed settings only) Run Claude's tools inside an isolated virtual machine instead of on your Mac. Disables the desktop app's iOS Simulator pane and Claude's simulator tools entirely, so the pane cannot attach a device while it is set. See https://code.claude.com/docs/en/desktop-ios-simulator#turn-off-simulator-access
required_maximum_version
class-attribute
instance-attribute
¶
(Managed settings only) Maximum Claude Code version allowed to start. If the running version is newer, Claude Code exits at startup with instructions to install an approved version. See https://code.claude.com/docs/en/admin-setup#decide-what-to-enforce
required_minimum_version
class-attribute
instance-attribute
¶
(Managed settings only) Minimum Claude Code version required to start. If the running version is older, Claude Code exits at startup rather than only warning. See https://code.claude.com/docs/en/admin-setup#decide-what-to-enforce
respect_gitignore
class-attribute
instance-attribute
¶
Control whether the @ file picker respects .gitignore patterns. When true (default), files matching .gitignore patterns are excluded from suggestions
respond_to_bash_commands
class-attribute
instance-attribute
¶
Whether Claude responds after an input-box ! shell command runs (v2.1.186+). Set to false to add the command output to context without a response. See https://code.claude.com/docs/en/interactive-mode#shell-mode-with--prefix
sandbox
class-attribute
instance-attribute
¶
sandbox: Sandbox | None = None
Sandbox execution configuration. See https://code.claude.com/docs/en/sandboxing
show_clear_context_on_plan_accept
class-attribute
instance-attribute
¶
When true, the plan-approval dialog offers a "clear context" option. Defaults to false.
show_thinking_summaries
class-attribute
instance-attribute
¶
Show thinking summaries in the transcript view (Ctrl+O). Thinking summaries are not generated by default in interactive sessions; set to true to restore. See https://code.claude.com/docs/en/settings#available-settings
show_turn_duration
class-attribute
instance-attribute
¶
Show turn duration messages after responses (e.g., "Cooked for 1m 6s"). Set to false to hide these messages (default: true)
skill_listing_budget_fraction
class-attribute
instance-attribute
¶
skill_listing_budget_fraction: float | None = Field(
0.01, alias="skillListingBudgetFraction", gt=0.0, le=1.0
)
Fraction of the model context window reserved for the skill listing sent to Claude (default 0.01 = 1%). When the listing exceeds this, descriptions are shortened to fit. Also configurable via the SLASH_COMMAND_TOOL_CHAR_BUDGET environment variable (fixed character count). See https://code.claude.com/docs/en/skills#skill-descriptions-are-cut-short
skill_listing_max_desc_chars
class-attribute
instance-attribute
¶
Per-skill character cap on the combined description and when_to_use text in the skill listing Claude sees each turn. Text longer than this is truncated. See https://code.claude.com/docs/en/skills#skill-descriptions-are-cut-short
skill_overrides
class-attribute
instance-attribute
¶
skill_overrides: dict[str, Literal["on", "name-only", "user-invocable-only", "off"]] | None = Field(
None, alias="skillOverrides", examples=[{"legacy-context": "name-only", "deploy": "off"}]
)
Per-skill visibility overrides. Controls whether skills appear to Claude and in the / picker. Values: 'on' (name and description shown, default), 'name-only' (name only), 'user-invocable-only' (hidden from Claude, visible in /), 'off' (hidden everywhere). Plugin skills are not affected by this setting. See https://code.claude.com/docs/en/skills#override-skill-visibility-from-settings
skip_dangerous_mode_permission_prompt
class-attribute
instance-attribute
¶
skip_dangerous_mode_permission_prompt: bool | None = Field(
None, alias="skipDangerousModePermissionPrompt"
)
Whether the user has accepted the bypass permissions mode dialog. Typically managed by the CLI rather than set by hand.
skip_web_fetch_preflight
class-attribute
instance-attribute
¶
Skip the WebFetch blocklist check for enterprise environments with restrictive security policies. See https://code.claude.com/docs/en/settings#available-settings
skipped_marketplaces
class-attribute
instance-attribute
¶
List of marketplace names the user has chosen not to install when prompted. See https://code.claude.com/docs/en/discover-plugins
skipped_plugins
class-attribute
instance-attribute
¶
List of plugin IDs (plugin@marketplace format) the user has chosen not to install when prompted. See https://code.claude.com/docs/en/discover-plugins
spinner_tips_enabled
class-attribute
instance-attribute
¶
Show tips in the spinner while Claude is working. Set to false to disable tips (default: true)
spinner_tips_override
class-attribute
instance-attribute
¶
spinner_tips_override: SpinnerTipsOverride | None = Field(None, alias='spinnerTipsOverride')
Customize the tips displayed in the spinner while Claude is working. See https://code.claude.com/docs/en/settings#available-settings
spinner_verbs
class-attribute
instance-attribute
¶
spinner_verbs: SpinnerVerbs | None = Field(None, alias='spinnerVerbs')
Customize the verbs shown in spinner progress messages
ssh_configs
class-attribute
instance-attribute
¶
ssh_configs: list[SshConfig] | None = Field(None, alias='sshConfigs')
(Managed settings) Pre-configured SSH connections distributed to Desktop users. See https://code.claude.com/docs/en/desktop#ssh-sessions
ssh_host_allowlist
class-attribute
instance-attribute
¶
(Managed settings only) Allowlist restricting Desktop SSH sessions to approved hosts. Patterns are case-insensitive; * matches any host and *.example.com matches example.com and any subdomain. See https://code.claude.com/docs/en/desktop#ssh-sessions
status_line
class-attribute
instance-attribute
¶
status_line: StatusLine | None = Field(
None, alias="statusLine", examples=[{"type": "command", "command": "~/.claude/statusline.sh"}]
)
Custom status line display configuration. See https://code.claude.com/docs/en/statusline
strict_known_marketplaces
class-attribute
instance-attribute
¶
strict_known_marketplaces: (
list[
StrictMarketplaceHostPattern
| StrictMarketplaceGithub
| StrictMarketplaceGit
| StrictMarketplaceUrl
| StrictMarketplaceNpm
| StrictMarketplaceFile
| StrictMarketplaceDirectory
| StrictMarketplacePathPattern
| StrictMarketplaceSkillsDir
]
| None
) = Field(
None,
alias="strictKnownMarketplaces",
examples=[
[
{"source": "github", "repo": "acme-corp/approved-plugins"},
{"source": "npm", "package": "@acme-corp/compliance-plugins"},
]
],
)
(Managed settings only) Allowlist of plugin marketplaces users can add. Undefined = no restrictions, empty array = lockdown. Uses exact matching for source specifications. See https://code.claude.com/docs/en/plugin-marketplaces#managed-marketplace-restrictions
strict_plugin_only_customization
class-attribute
instance-attribute
¶
strict_plugin_only_customization: bool | StrictPluginOnlyCustomization | None = Field(
None, alias="strictPluginOnlyCustomization"
)
(Managed settings) Block non-plugin customization sources for the listed surfaces. Array form locks specific surfaces (e.g., ["skills", "hooks"]); true locks all four; false is an explicit no-op. See https://code.claude.com/docs/en/plugins-reference
subagent_status_line
class-attribute
instance-attribute
¶
subagent_status_line: SubagentStatusLine | None = Field(None, alias='subagentStatusLine')
Status line configuration for subagent sessions. See https://code.claude.com/docs/en/statusline#subagent-status-lines
syntax_highlighting_disabled
class-attribute
instance-attribute
¶
Disable syntax highlighting in diffs, code blocks, and file previews. See https://code.claude.com/docs/en/settings#available-settings
teammate_default_model
class-attribute
instance-attribute
¶
Default model for agent team teammates when the spawn prompt does not specify one. Set to a model alias such as "sonnet", or null to inherit the lead's current /model selection. Appears in /config as Default teammate model. See https://code.claude.com/docs/en/agent-teams
teammate_mode
class-attribute
instance-attribute
¶
teammate_mode: Literal["auto", "in-process", "tmux", "iterm2"] | None = Field(
"in-process", alias="teammateMode"
)
How agent team teammates display: "auto" picks split panes in tmux or iTerm2, in-process otherwise; "iterm2" (added in v2.1.186) forces iTerm2 native split panes and requires the it2 CLI (it shows an error with the install command if it2 is missing). The default is "in-process" (it was "auto" before v2.1.179). Agent teams are experimental and disabled by default. Enable them by adding CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS to your settings.json or environment. See https://code.claude.com/docs/en/agent-teams#choose-a-display-mode
terminal_progress_bar_enabled
class-attribute
instance-attribute
¶
Enable the terminal progress bar that shows progress in supported terminals like Windows Terminal and iTerm2 (default: true)
theme
class-attribute
instance-attribute
¶
theme: (
Literal[
"auto", "dark", "light", "dark-daltonized", "light-daltonized", "dark-ansi", "light-ansi"
]
| Theme
| None
) = None
Color theme for the interface: auto, dark, light, the daltonized variants (deuteranopia-friendly), the ansi variants (16-color terminals), or a custom theme reference such as custom:<slug> or custom:<plugin-name>:<slug>. See https://code.claude.com/docs/en/terminal-config#match-the-color-theme
tui
class-attribute
instance-attribute
¶
TUI rendering mode. Use "fullscreen" for the flicker-free alt-screen renderer with virtualized scrollback; "default" for the classic main-screen renderer. Corresponds to the /tui command. See https://code.claude.com/docs/en/settings#available-settings
use_auto_mode_during_plan
class-attribute
instance-attribute
¶
When true, apply the auto mode classifier during plan mode to auto-approve safe read-only tool calls while planning. Has no effect unless permissions.defaultMode allows auto. See https://code.claude.com/docs/en/permissions
verbose
class-attribute
instance-attribute
¶
Show full tool output instead of truncated summaries. The --verbose flag overrides this for a single session. Requires Claude Code v2.1.119 or later. See https://code.claude.com/docs/en/settings#available-settings
view_mode
class-attribute
instance-attribute
¶
Transcript view mode. "default" shows standard interactive view; "verbose" shows expanded tool details; "focus" shows prompt, one-line tool summaries, and final response only (Ctrl+O toggle). See https://code.claude.com/docs/en/settings#available-settings
vim_insert_mode_remaps
class-attribute
instance-attribute
¶
vim_insert_mode_remaps: dict[str, str] | None = Field(
None, alias="vimInsertModeRemaps", examples=[{"jj": "<Esc>"}]
)
Map two-key INSERT-mode sequences to Escape in vim editor mode. Each key is exactly two printable characters typed in sequence, and <Esc> is the only supported target; other entries are ignored. Read from user, --settings flag, and managed settings only, so a repository's checked-in settings cannot remap your keystrokes. Has no effect unless editorMode is "vim". Requires Claude Code v2.1.208 or later. See https://code.claude.com/docs/en/interactive-mode#remap-insert-mode-key-sequences
voice
class-attribute
instance-attribute
¶
voice: Voice | None = None
Voice dictation settings: enabled turns dictation on, mode selects "hold" or "tap", and autoSubmit sends the prompt on key release in hold mode. Written automatically when you run /voice. Requires a Claude.ai account. See https://code.claude.com/docs/en/voice-dictation
voice_enabled
class-attribute
instance-attribute
¶
Legacy alias for voice.enabled; prefer the voice object. Requires a Claude.ai account. See https://code.claude.com/docs/en/settings#available-settings
wheel_scroll_acceleration_enabled
class-attribute
instance-attribute
¶
wheel_scroll_acceleration_enabled: bool | None = Field(None, alias="wheelScrollAccelerationEnabled")
In fullscreen rendering, accelerate mouse-wheel scroll speed during fast scrolls (v2.1.174+). Set to false for a constant scroll rate per wheel notch. See https://code.claude.com/docs/en/fullscreen#mouse-wheel-scrolling
workflow_keyword_trigger_enabled
class-attribute
instance-attribute
¶
Whether including the keyword "ultracode" in a prompt triggers a dynamic workflow. Requires Claude Code v2.1.157 or later. See https://code.claude.com/docs/en/settings#available-settings
workflow_size_guideline
class-attribute
instance-attribute
¶
workflow_size_guideline: Literal["unrestricted", "small", "medium", "large"] | None = Field(
"unrestricted", alias="workflowSizeGuideline"
)
Sets the agent count Claude aims for in the dynamic workflows it writes. Claude Code sends the value to Claude as advice, not an enforced cap. Accepts "unrestricted" (default, which sends no guideline), "small", "medium", or "large". Appears in /config as Dynamic workflow size, and can be set with /config workflowSizeGuideline=small. Requires Claude Code v2.1.202 or later. On v2.1.203 or later the guideline's agent count also replaces the default threshold for the Large workflow warning. See https://code.claude.com/docs/en/workflows#set-a-size-guideline
worktree
class-attribute
instance-attribute
¶
worktree: Worktree | None = None
Configuration for --worktree sessions. See https://code.claude.com/docs/en/settings#worktree-settings
wsl_inherits_windows_settings
class-attribute
instance-attribute
¶
(Windows managed settings only) When true, Claude Code on WSL reads managed settings from the Windows policy chain in addition to /etc/claude-code, with Windows sources taking priority. Only honored when set in the HKLM registry key or C:\Program Files\ClaudeCode\managed-settings.json, both of which require Windows admin to write. For HKCU policy to also apply on WSL, the flag must additionally be set in HKCU itself. Has no effect on native Windows. See https://code.claude.com/docs/en/settings#available-settings
ClaudeSDKClient
¶
Client for bidirectional, interactive conversations with Claude Code.
Key features: - Bidirectional: Send and receive messages at any time - Stateful: Maintains conversation context across messages - Interactive: Send follow-ups based on responses - Control flow: Support for interrupts and session management
Caveat: As of v0.0.21, you cannot use a ClaudeSDKClient instance across different async runtime contexts (e.g., different trio nurseries or asyncio task groups). The client internally maintains a persistent anyio task group for reading messages that remains active from connect() until disconnect(). This means you must complete all operations with the client within the same async context where it was connected. Ideally, this limitation should not exist.
Source code in src/clawd_code_sdk/client.py
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 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 | |
query_cost
instance-attribute
¶
Cost in USD for the current/last query only (reset on each query() call).
query_usage
instance-attribute
¶
Token usage for the current/last query only (reset on each query() call).
session_cost
instance-attribute
¶
Cumulative cost in USD across all queries in this session.
session_state
instance-attribute
¶
Cumulative token usage across all queries in this session.
status
instance-attribute
¶
Current client status, or None when idle.
__aenter__
async
¶
Enter async context - automatically connects with empty stream for interactive use.
__aexit__
async
¶
__init__
¶
__init__(options: ClaudeAgentOptions | None = None, transport: Transport | None = None) -> None
Initialize Claude SDK client.
Source code in src/clawd_code_sdk/client.py
apply_flag_settings
async
¶
apply_flag_settings(settings: ClaudeCodeSettings) -> None
Apply runtime settings overrides without restarting the session.
Flag settings are an in-memory settings source that gets merged with other sources (user, project, etc.) to produce the effective settings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
settings
|
ClaudeCodeSettings
|
Settings to apply. Only fields that were set explicitly (and are not None) are sent: defaults would override every other settings source. |
required |
Source code in src/clawd_code_sdk/client.py
background_tasks
async
¶
Move running foreground tasks (or a single tool use) to the background.
Returns:
| Type | Description |
|---|---|
bool
|
Whether anything was backgrounded. |
Source code in src/clawd_code_sdk/client.py
call_tool
async
¶
call_tool(
tool: str, arguments: dict[str, Any] | None = None, *, timeout: float | None = 600.0
) -> Any
Call a tool on the server.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool
|
str
|
The name of the tool to call |
required |
arguments
|
dict[str, Any] | None
|
Optional dictionary of arguments for the tool |
None
|
timeout
|
float | None
|
Seconds to wait for the tool's result (None: no limit) |
600.0
|
Returns:
| Type | Description |
|---|---|
Any
|
The result of the tool call |
Source code in src/clawd_code_sdk/client.py
cancel_async_message
async
¶
Drop a pending async user message from the command queue by uuid.
Source code in src/clawd_code_sdk/client.py
channel_enable
async
¶
Enable MCP channel notifications for a marketplace plugin server.
Source code in src/clawd_code_sdk/client.py
claude_oauth_wait_for_completion
async
¶
claude_oauth_wait_for_completion(
*, timeout: float | None = None
) -> ClaudeOAuthWaitForCompletionResponse
Wait for an in-progress Claude OAuth flow to complete.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timeout
|
float | None
|
Seconds to wait for the user to finish the browser login (None, the default: no limit). |
None
|
Returns:
| Type | Description |
|---|---|
ClaudeOAuthWaitForCompletionResponse
|
Account details (email, organization, subscriptionType, etc.). |
Source code in src/clawd_code_sdk/client.py
connect
async
¶
Connect to Claude Code CLI and initialize the session.
Source code in src/clawd_code_sdk/client.py
disconnect
async
¶
end_session
async
¶
generate_session_title
async
¶
generate_session_title(
description: str, *, persist: bool = False, timeout: float | None = 120.0
) -> str | None
Generate a session title from description with the CLI's title model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
description
|
str
|
Text to title (the CLI reads its trailing ~1000 characters). |
required |
persist
|
bool
|
Store it as the current session's title; a session that has a title already returns that one. |
False
|
timeout
|
float | None
|
Seconds to wait for the model (None: no limit). |
120.0
|
Returns:
| Type | Description |
|---|---|
str | None
|
The title, or None when the text is too short to title. |
Source code in src/clawd_code_sdk/client.py
get_binary_version
async
¶
Get version info of the running Claude Code binary.
get_context_usage
async
¶
get_context_usage(
detail: Literal["summary", "full"] | None = None,
) -> SDKControlGetContextUsageResponse
Get a breakdown of current context window usage by category.
Source code in src/clawd_code_sdk/client.py
get_file
async
¶
get_file(path: str, max_bytes: int | None = None) -> SDKControlReadFileResponse
Get the contents of a file from the server.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to the file to read |
required |
max_bytes
|
int | None
|
Maximum number of bytes to read (default: None, no limit) |
None
|
Returns:
| Type | Description |
|---|---|
SDKControlReadFileResponse
|
The file contents and metadata |
Source code in src/clawd_code_sdk/client.py
get_hooks_listing
async
¶
Get the listing of configured hooks (same data as /hooks).
get_mcp_status
async
¶
get_mcp_status() -> list[McpServerStatusEntry]
Get current MCP server connection status.
Returns:
| Type | Description |
|---|---|
list[McpServerStatusEntry]
|
Validated MCP status response containing server statuses, |
list[McpServerStatusEntry]
|
configurations, tools, and connection information. |
Source code in src/clawd_code_sdk/client.py
get_server_info
async
¶
get_server_info() -> ClaudeCodeServerInfo | None
Get server initialization info including available commands and output styles.
Returns initialization information from the Claude Code server including: - Available commands (slash commands, system commands, etc.) - Current and available output styles - Server capabilities
Returns:
| Type | Description |
|---|---|
ClaudeCodeServerInfo | None
|
Parsed server info, or None if not yet initialized |
Source code in src/clawd_code_sdk/client.py
get_settings
async
¶
get_settings() -> GetSettingsResponse
Get the effective merged settings and raw per-source settings.
Source code in src/clawd_code_sdk/client.py
get_task_output
async
¶
get_task_output(task_id: str) -> SDKControlGetTaskOutputResponse
Read the output collected so far for a background task.
Source code in src/clawd_code_sdk/client.py
get_usage
async
¶
get_usage(*, skip_behaviors: bool = True) -> SDKControlGetUsageResponse
Get session usage and plan rate-limit windows (experimental, shape may change).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
skip_behaviors
|
bool
|
Skip the (slow) scan of local transcripts that fills
|
True
|
Source code in src/clawd_code_sdk/client.py
interrupt
async
¶
interrupt(*, cancel_queued: bool = False) -> SDKControlInterruptResponse | None
Send interrupt signal (only works with streaming mode).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cancel_queued
|
bool
|
Also cancel queued (not yet started) user messages. |
False
|
Returns:
| Type | Description |
|---|---|
SDKControlInterruptResponse | None
|
Which queued messages are still queued / were cancelled |
SDKControlInterruptResponse | None
|
(None on CLIs that don't report it). |
Source code in src/clawd_code_sdk/client.py
list_models
async
¶
list_models() -> list[ClaudeCodeModelInfo]
Fetch the list of available models from the CLI.
Source code in src/clawd_code_sdk/client.py
list_permission_rules
async
¶
List the effective permission rules (raw state payload).
Source code in src/clawd_code_sdk/client.py
mcp_authenticate
async
¶
mcp_authenticate(server_name: str) -> McpAuthenticateResponse
Trigger OAuth authentication for an MCP server.
Returns:
| Type | Description |
|---|---|
McpAuthenticateResponse
|
Response indicating whether user action is required and the auth URL if so. |
Source code in src/clawd_code_sdk/client.py
mcp_clear_auth
async
¶
Clear OAuth credentials for an MCP server.
Source code in src/clawd_code_sdk/client.py
mcp_oauth_callback_url
async
¶
Provide an OAuth redirect callback URL to complete an MCP server OAuth flow.
After the user completes browser-based OAuth, call this with the full redirect URL (containing the authorization code) to finish the flow.
Source code in src/clawd_code_sdk/client.py
mcp_reconnect
async
¶
Reconnect to an MCP server.
mcp_toggle
async
¶
Enable or disable an MCP server.
Source code in src/clawd_code_sdk/client.py
one_shot
async
classmethod
¶
one_shot(
*prompts: str | UserPrompt,
options: ClaudeAgentOptions | None = None,
transport: Transport | None = None,
) -> AsyncIterator[Message]
One-shot query convenience method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*prompts
|
str | UserPrompt
|
One or more content blocks to send. |
()
|
options
|
ClaudeAgentOptions | None
|
Optional configuration. |
None
|
transport
|
Transport | None
|
Optional transport implementation override. |
None
|
Yields:
| Type | Description |
|---|---|
AsyncIterator[Message]
|
Messages from the conversation |
Source code in src/clawd_code_sdk/client.py
query
async
¶
query(
*prompts: str | UserPrompt,
session_id: str = "default",
parent_tool_use_id: str | None = None,
should_query: bool = True,
priority: MessagePriority | None = None,
uuid: str | None = None,
) -> None
Send a new user message with one or more content blocks.
Starts a new query: query_usage and query_cost count from here.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*prompts
|
str | UserPrompt
|
One or more content blocks. Strings are converted to
UserTextPrompt automatically. Pass multiple to combine, e.g.
|
()
|
session_id
|
str
|
Session identifier for the message. |
'default'
|
parent_tool_use_id
|
str | None
|
If responding to a tool use, the tool_use block ID. |
None
|
should_query
|
bool
|
Whether to query the model for a response. Defaults to True. |
True
|
priority
|
MessagePriority | None
|
The priority of the message. Defaults to None. |
None
|
uuid
|
str | None
|
ID of the message; the CLI then reports its progress as
|
None
|
Source code in src/clawd_code_sdk/client.py
read_mcp_resource
async
¶
read_mcp_resource(server_name: str, uri: str) -> SDKControlMcpReadResourceResponse
Read a resource from a connected MCP server.
Source code in src/clawd_code_sdk/client.py
receive_messages
async
¶
receive_messages() -> AsyncIterator[Message]
Receive all messages from Claude.
Source code in src/clawd_code_sdk/client.py
receive_response
async
¶
receive_response() -> AsyncIterator[Message]
Receive messages from Claude until the response is complete.
This async iterator yields all messages in sequence and automatically
terminates when the session transitions to idle state — the
authoritative signal that the CLI has fully finished its turn
(held-back results flushed, background agent loops exited).
Stopping Behavior:
- Yields each message as it's received
- Terminates after yielding a SessionStateChangedMessage with
state='idle'
- The final message in the collected list will always be the idle
state-change message
Yields:
| Name | Type | Description |
|---|---|---|
Message |
AsyncIterator[Message]
|
Each message received |
Note
To collect all messages: messages = [msg async for msg in client.receive_response()]
Source code in src/clawd_code_sdk/client.py
register_repo_root
async
¶
register_repo_root(
directory: str | Path,
*,
reload_claude_md: bool | None = None,
reload_plugins: bool | None = None,
reload_skills: bool | None = None,
) -> None
Register an additional repository root for the session (like /add-dir).
Source code in src/clawd_code_sdk/client.py
reload_output_styles
async
¶
Re-scan output styles from disk and return the available style names.
Source code in src/clawd_code_sdk/client.py
reload_skills
async
¶
reload_skills() -> list[ClaudeCodeCommandInfo]
Re-scan skills from disk and return the refreshed skill list.
Source code in src/clawd_code_sdk/client.py
remote_control
async
¶
remote_control(*, enabled: bool) -> RemoteControlResponse | None
Toggle the remote control REPL bridge for external session access.
When enabled, starts a bridge that allows remote clients to send prompts, permission responses, interrupts, and model changes into the session.
Returns:
| Type | Description |
|---|---|
RemoteControlResponse | None
|
A |
RemoteControlResponse | None
|
when enabling, or |
Source code in src/clawd_code_sdk/client.py
rewind_files
async
¶
Rewind tracked files to their state at a specific user message.
Requires
enable_file_checkpointing=Trueto track file changesextra_args={"replay-user-messages": None}to receive UserMessage objects withuuidin the response stream
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_message_id
|
str
|
UUID of the user message to rewind to. This should be
the |
required |
Example
options = ClaudeAgentOptions(
enable_file_checkpointing=True,
extra_args={"replay-user-messages": None},
)
async with ClaudeSDKClient(options) as client:
await client.query("Make some changes to my files")
async for msg in client.receive_response():
if isinstance(msg, UserMessage) and msg.uuid:
checkpoint_id = msg.uuid # Save this for later
# Later, rewind to that point
await client.rewind_files(checkpoint_id)
Source code in src/clawd_code_sdk/client.py
seed_read_state
async
¶
Seed the CLI's readFileState cache with a path+mtime entry.
Use when the client observed a Read that has since been removed from context (e.g. by snip), so a subsequent Edit won't fail "file not read yet". If the file changed on disk since the given mtime, the seed is skipped and Edit will correctly require a fresh Read.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to the file that was previously Read |
required |
mtime
|
int
|
File mtime (floored ms) at the time of the observed Read |
required |
Source code in src/clawd_code_sdk/client.py
set_max_thinking_tokens
async
¶
set_max_thinking_tokens(
max_thinking_tokens: int | None,
thinking_display: Literal["summarized", "omitted", "highlights"] | None = None,
) -> None
Set the maximum number of thinking tokens (and optionally the display mode).
Source code in src/clawd_code_sdk/client.py
set_mcp_servers
async
¶
set_mcp_servers(servers: dict[str, ExternalMcpServerConfig]) -> McpSetServersResult
Add, replace, or remove MCP servers dynamically mid-session.
Allows dynamic registration of MCP servers without restarting the session. Pass an empty dict to remove all dynamic servers.
The server name is automatically injected from the dict key into each config, so callers don't need to specify it redundantly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
servers
|
dict[str, ExternalMcpServerConfig]
|
Dictionary mapping server names to server configurations. Values are typed MCP server configs (McpStdioServerConfig, McpSSEServerConfig, McpHttpServerConfig, or McpSdkServerConfig). |
required |
Returns:
| Type | Description |
|---|---|
McpSetServersResult
|
Dictionary with results: |
McpSetServersResult
|
|
McpSetServersResult
|
|
McpSetServersResult
|
|
Source code in src/clawd_code_sdk/client.py
set_model
async
¶
Change the AI model during conversation (only works with streaming mode).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str | None
|
The model to use, or None to use default. Example: 'claude-sonnet-4-5' |
None
|
Source code in src/clawd_code_sdk/client.py
set_permission_mode
async
¶
set_permission_mode(mode: PermissionMode) -> SDKControlSetPermissionModeResponse | None
Change permission mode during conversation (only works with streaming mode).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
PermissionMode
|
The permission mode to set. Valid options: - 'default': CLI prompts for dangerous tools - 'acceptEdits': Auto-accept file edits - 'plan': Plan mode for planning tasks - 'bypassPermissions': Allow all tools (use with caution) |
required |
Returns:
| Type | Description |
|---|---|
SDKControlSetPermissionModeResponse | None
|
The mode now in effect (it can differ from |
SDKControlSetPermissionModeResponse | None
|
CLI answered without a payload (before Claude Code 2.1.332). |
Source code in src/clawd_code_sdk/client.py
side_question
async
¶
side_question(question: str, *, timeout: float | None = 600.0) -> SideQuestionResponse
Send a side question to the model using the current conversation context.
The model answers the question without it being added to the main conversation history.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
question
|
str
|
The question to ask the model. |
required |
timeout
|
float | None
|
Seconds to wait for the answer (None: no limit). |
600.0
|
Returns:
| Type | Description |
|---|---|
SideQuestionResponse
|
The model's answer, or None if no context was available. |
Source code in src/clawd_code_sdk/client.py
steer
async
¶
steer(
*prompts: str | UserPrompt, priority: MessagePriority = "now", session_id: str = "default"
) -> str
Send a user message into the running query instead of starting a new one.
query_usage and query_cost keep counting the running query. With
"now" the CLI takes the message in at once: it ends the cycle that is
generating (which reports a result of its own) or moves a running foreground
tool to the background, and works on the message in the same query. "later"
waits for the running cycle (e.g. while a permission request is open).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*prompts
|
str | UserPrompt
|
Content blocks of the message (strings become text blocks). |
()
|
priority
|
MessagePriority
|
When the CLI takes the message in. |
'now'
|
session_id
|
str
|
Session identifier for the message. |
'default'
|
Returns:
| Type | Description |
|---|---|
str
|
The message's uuid, which |
str
|
results' |
Source code in src/clawd_code_sdk/client.py
stop_task
async
¶
supported_agents
async
¶
supported_agents() -> list[ClaudeCodeAgentInfo]
Get the list of available subagents for the current session.
Returns:
| Type | Description |
|---|---|
list[ClaudeCodeAgentInfo]
|
List of available agents with their names, descriptions, and configuration. |
Source code in src/clawd_code_sdk/client.py
update_settings
async
¶
Persist settings to the local or user settings file.
Source code in src/clawd_code_sdk/client.py
ClaudeSDKError
¶
ContinueLatest
dataclass
¶
Bases: BaseSessionConfig
Continue the most recent conversation.
Source code in src/clawd_code_sdk/models/options.py
fork
class-attribute
instance-attribute
¶
If True, fork to a new session ID instead of continuing in-place.
ConversationTurn
dataclass
¶
Collected result of a single send/receive cycle.
Source code in src/clawd_code_sdk/session.py
Filesystem
¶
Bases: ClaudeCodeBaseModel
Filesystem access control for sandboxed commands. See https://code.claude.com/docs/en/sandboxing#filesystem-isolation.
Source code in src/clawd_code_sdk/models/settings.py
allow_managed_read_paths_only
class-attribute
instance-attribute
¶
(Managed settings only) When true, only allowRead paths from managed settings are used; user, project, and local allowRead entries are ignored. denyRead still merges from all sources. See https://code.claude.com/docs/en/sandboxing#filesystem-isolation
allow_read
class-attribute
instance-attribute
¶
Paths to re-allow reading within denyRead regions. Takes precedence over denyRead for matching paths. See https://code.claude.com/docs/en/sandboxing#granting-subprocess-write-access-to-specific-paths
allow_write
class-attribute
instance-attribute
¶
Paths where subprocesses are allowed to write. Supports prefixes: // (absolute), ~/ (home directory), / (relative to settings file), ./ or no prefix (relative path). See https://code.claude.com/docs/en/sandboxing#granting-subprocess-write-access-to-specific-paths
deny_read
class-attribute
instance-attribute
¶
Paths where subprocesses are explicitly denied read access. See https://code.claude.com/docs/en/sandboxing#filesystem-isolation
deny_write
class-attribute
instance-attribute
¶
Paths where subprocesses are explicitly denied write access. Takes precedence over allowWrite. See https://code.claude.com/docs/en/sandboxing#filesystem-isolation
disabled
class-attribute
instance-attribute
¶
Skip filesystem isolation while keeping network isolation: sandboxed commands get unrestricted read and write access to the host filesystem, and network egress stays confined to network.allowedDomains. Only honored from user, managed, or CLI --settings settings (default: false). Requires Claude Code v2.1.216 or later. See https://code.claude.com/docs/en/sandboxing#disable-filesystem-isolation
FromPR
dataclass
¶
Bases: BaseSessionConfig
Resume sessions linked to a specific GitHub PR.
Accepts a PR number or URL. Sessions are automatically linked
when created via gh pr create.
Source code in src/clawd_code_sdk/models/options.py
GetSettingsResponse
¶
Bases: BaseModel
Response from get_settings() containing effective and per-source settings.
Source code in src/clawd_code_sdk/models/control.py
effective
instance-attribute
¶
The merged effective settings (ClaudeCodeSettings shape, camelCase keys).
HookContext
¶
Bases: TypedDict
Context information for hook callbacks.
Fields
signal: Reserved for future abort signal support. Currently always None.
Source code in src/clawd_code_sdk/models/hooks.py
HookMatcher
¶
Bases: BaseModel
Hook matcher configuration.
Source code in src/clawd_code_sdk/models/hooks.py
on_failure
class-attribute
instance-attribute
¶
What to do when a hook callback fails (raises, times out).
"continue" ignores the failure, "block" fails closed and blocks the action.
Requires a CLI that reports hook_on_failure_supported.
HookMatcherConfig
¶
Bases: TypedDict
Declarative hook matcher for agent/skill/settings hook configuration.
See https://code.claude.com/docs/en/hooks#matcher-patterns
Source code in src/clawd_code_sdk/models/hooks.py
Hooks
¶
Bases: ClaudeCodeBaseModel
Lifecycle event hooks that run at configurable points during Claude Code operation (tool use, session start/end, notifications, prompt submit, message display, and more), not just before/after tool executions. See https://code.claude.com/docs/en/hooks.
Source code in src/clawd_code_sdk/models/settings.py
3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 | |
config_change
class-attribute
instance-attribute
¶
config_change: list[HookMatcher] | None = Field(None, alias='ConfigChange')
Hooks that run when settings, managed settings, or skill files change during a session. Supports matchers: user_settings, project_settings, local_settings, policy_settings, skills. Command handlers only. Exit code 2 blocks the change (except policy_settings which is audit-only). See https://code.claude.com/docs/en/hooks#configchange
cwd_changed
class-attribute
instance-attribute
¶
cwd_changed: list[HookMatcher] | None = Field(None, alias='CwdChanged')
Hooks that run when the working directory changes. Provides cwd (new directory) and previous_cwd. Matchers are ignored; fires on every directory change. See https://code.claude.com/docs/en/hooks#cwdchanged
directory_added
class-attribute
instance-attribute
¶
directory_added: list[HookMatcher] | None = Field(None, alias='DirectoryAdded')
UNDOCUMENTED. Hooks that run after /add-dir or the SDK register_repo_root control request registers a new working directory mid-session (added v2.1.219)
elicitation
class-attribute
instance-attribute
¶
elicitation: list[HookMatcher] | None = Field(None, alias='Elicitation')
Hooks that run when an MCP server requests user input during a tool call. See https://code.claude.com/docs/en/hooks
elicitation_result
class-attribute
instance-attribute
¶
elicitation_result: list[HookMatcher] | None = Field(None, alias='ElicitationResult')
Hooks that run after a user responds to an MCP elicitation, before the response is sent back to the server. See https://code.claude.com/docs/en/hooks
file_changed
class-attribute
instance-attribute
¶
file_changed: list[HookMatcher] | None = Field(None, alias='FileChanged')
Hooks that run when a watched file is created, modified, or deleted. Supports filename matchers. Provides file_path and file_event_type (created, modified, deleted). See https://code.claude.com/docs/en/hooks#filechanged
instructions_loaded
class-attribute
instance-attribute
¶
instructions_loaded: list[HookMatcher] | None = Field(None, alias='InstructionsLoaded')
Hooks that run when a CLAUDE.md or .claude/rules/*.md file is loaded into context. Fires at session start and when files are lazily loaded (e.g., nested traversal, path glob match). No decision control; used for audit logging and observability. Does not support matchers. See https://code.claude.com/docs/en/hooks#instructionsloaded
message_display
class-attribute
instance-attribute
¶
message_display: list[HookMatcher] | None = Field(None, alias='MessageDisplay')
Hooks that run while assistant message text is displayed
notification
class-attribute
instance-attribute
¶
notification: list[HookMatcher] | None = Field(None, alias='Notification')
Hooks that trigger on notifications
permission_denied
class-attribute
instance-attribute
¶
permission_denied: list[HookMatcher] | None = Field(None, alias='PermissionDenied')
Hooks that run when a tool call is denied by the auto mode classifier. Supports matchers on tool name. See https://code.claude.com/docs/en/hooks
permission_request
class-attribute
instance-attribute
¶
permission_request: list[HookMatcher] | None = Field(None, alias='PermissionRequest')
Hooks that run when a permission dialog appears
post_compact
class-attribute
instance-attribute
¶
post_compact: list[HookMatcher] | None = Field(None, alias='PostCompact')
Hooks that run after the context is compacted. See https://code.claude.com/docs/en/hooks
post_tool_batch
class-attribute
instance-attribute
¶
post_tool_batch: list[HookMatcher] | None = Field(None, alias='PostToolBatch')
Hooks that run after a full batch of parallel tool calls resolves, before the next model call. Exit code 2 blocks the agentic loop. Does not support matchers. See https://code.claude.com/docs/en/hooks
post_tool_use
class-attribute
instance-attribute
¶
post_tool_use: list[HookMatcher] | None = Field(None, alias='PostToolUse')
Hooks that run after tool completion
post_tool_use_failure
class-attribute
instance-attribute
¶
post_tool_use_failure: list[HookMatcher] | None = Field(None, alias='PostToolUseFailure')
Hooks that run after a tool fails
pre_compact
class-attribute
instance-attribute
¶
pre_compact: list[HookMatcher] | None = Field(None, alias='PreCompact')
Hooks that run before the context is compacted
pre_tool_use
class-attribute
instance-attribute
¶
pre_tool_use: list[HookMatcher] | None = Field(None, alias='PreToolUse')
Hooks that run before tool calls
session_end
class-attribute
instance-attribute
¶
session_end: list[HookMatcher] | None = Field(None, alias='SessionEnd')
Hooks that run when a session ends
session_start
class-attribute
instance-attribute
¶
session_start: list[HookMatcher] | None = Field(None, alias='SessionStart')
Hooks that run when a new session starts
setup
class-attribute
instance-attribute
¶
setup: list[HookMatcher] | None = Field(None, alias='Setup')
UNDOCUMENTED. Hooks that run during repository initialization (--init, --init-only) or maintenance (--maintenance)
stop
class-attribute
instance-attribute
¶
stop: list[HookMatcher] | None = Field(None, alias='Stop')
Hooks that run when agents finish responding. Does not run on user interrupt
stop_failure
class-attribute
instance-attribute
¶
stop_failure: list[HookMatcher] | None = Field(None, alias='StopFailure')
Hooks that run when a turn ends due to an API error (e.g., rate_limit, authentication_failed, billing_error, invalid_request, server_error, max_output_tokens, unknown). Matcher can scope to specific error types. Hook output and exit code are ignored. See https://code.claude.com/docs/en/hooks
subagent_start
class-attribute
instance-attribute
¶
subagent_start: list[HookMatcher] | None = Field(None, alias='SubagentStart')
Hooks that run when a subagent is spawned
subagent_stop
class-attribute
instance-attribute
¶
subagent_stop: list[HookMatcher] | None = Field(None, alias='SubagentStop')
Hooks that run when subagents finish responding
task_completed
class-attribute
instance-attribute
¶
task_completed: list[HookMatcher] | None = Field(None, alias='TaskCompleted')
Hooks that run when a task is being marked as completed. Exit code 2 prevents completion and sends feedback. Does not support matchers. See https://code.claude.com/docs/en/hooks#taskcompleted
task_created
class-attribute
instance-attribute
¶
task_created: list[HookMatcher] | None = Field(None, alias='TaskCreated')
Hooks that run when a task is being created via TaskCreate. Exit code 2 rolls back task creation. Does not support matchers. See https://code.claude.com/docs/en/hooks#taskcreated
teammate_idle
class-attribute
instance-attribute
¶
teammate_idle: list[HookMatcher] | None = Field(None, alias='TeammateIdle')
Hooks that run when an agent team teammate is about to go idle. Exit code 2 sends feedback and keeps the teammate working. Does not support matchers. Agent teams are experimental. See https://code.claude.com/docs/en/hooks#teammateidle
user_prompt_expansion
class-attribute
instance-attribute
¶
user_prompt_expansion: list[HookMatcher] | None = Field(None, alias='UserPromptExpansion')
Hooks that run when a user-typed command expands into a prompt, before it reaches Claude. Exit code 2 blocks the expansion. Supports matchers on command name. See https://code.claude.com/docs/en/hooks
user_prompt_submit
class-attribute
instance-attribute
¶
user_prompt_submit: list[HookMatcher] | None = Field(None, alias='UserPromptSubmit')
Hooks that run when a user submits a prompt
worktree_create
class-attribute
instance-attribute
¶
worktree_create: list[HookMatcher] | None = Field(None, alias='WorktreeCreate')
Hooks that run when a worktree is created via --worktree or isolation: "worktree" in subagents. Command handlers only, no matchers. Hook must print absolute path to created worktree on stdout; non-zero exit fails creation. See https://code.claude.com/docs/en/hooks#worktreecreate
worktree_remove
class-attribute
instance-attribute
¶
worktree_remove: list[HookMatcher] | None = Field(None, alias='WorktreeRemove')
Hooks that run when a worktree is being removed at session exit or when a subagent finishes. Command handlers only, no matchers. Used for cleanup tasks; cannot block removal. See https://code.claude.com/docs/en/hooks#worktreeremove
ImageBlock
¶
Bases: BaseContentBlock
Image content block (storage-only, not emitted on the wire).
Source code in src/clawd_code_sdk/models/content_blocks.py
ImageSource
¶
InitSystemMessage
¶
Bases: BaseSystemMessage
System init message with session metadata.
Source code in src/clawd_code_sdk/models/system_messages.py
additional_directories
class-attribute
instance-attribute
¶
Extra working directories added to the session (undocumented).
fast_mode_state
class-attribute
instance-attribute
¶
Whether fast mode was enabled.
memory_paths
class-attribute
instance-attribute
¶
Auto-memory directories by kind (undocumented).
messaging_socket_path
class-attribute
instance-attribute
¶
Path of the CLI's local messaging socket (undocumented).
original_cwd
class-attribute
instance-attribute
¶
The cwd the session was started in (undocumented).
served_by_anthropic
class-attribute
instance-attribute
¶
Whether requests are served by Anthropic directly (undocumented).
startup_timing
class-attribute
instance-attribute
¶
Startup timing diagnostics (undocumented, nested phase timings).
user_message_uuids
class-attribute
instance-attribute
¶
Client uuids of the user messages the turn takes in (undocumented, CLI 2.1.330+).
InvalidRequestError
¶
Bases: APIError
Raised when the API request is invalid (400).
This may indicate invalid parameters, unsupported model, or malformed input. Check the error message for details about what needs to be corrected.
Source code in src/clawd_code_sdk/_errors.py
McpAuthenticateResponse
¶
Bases: ClaudeCodeBaseModel
Response from authenticating with an MCP server.
Source code in src/clawd_code_sdk/models/control.py
McpSdkServerConfig
dataclass
¶
SDK MCP server configuration (serializable, no instance).
Source code in src/clawd_code_sdk/models/mcp.py
timeout
class-attribute
instance-attribute
¶
Per-request timeout for this server in milliseconds.
McpSdkServerConfigWithInstance
dataclass
¶
Bases: McpSdkServerConfig
SDK MCP server config with a live McpServer instance. Not serializable.
Source code in src/clawd_code_sdk/models/mcp.py
McpSetServersResult
¶
Bases: ClaudeCodeBaseModel
Result of a setMcpServers operation.
Source code in src/clawd_code_sdk/models/mcp.py
Network
¶
Bases: ClaudeCodeBaseModel
Configures network isolation settings for the sandboxed bash environment, including domain restrictions, Unix socket access, and custom proxy configuration.
Source code in src/clawd_code_sdk/models/settings.py
allow_all_unix_sockets
class-attribute
instance-attribute
¶
Allow all Unix domain socket connections. If true, this overrides allowUnixSockets. See https://code.claude.com/docs/en/sandboxing#network-isolation
allow_local_binding
class-attribute
instance-attribute
¶
Allow binding to local network addresses (e.g., localhost ports). Defaults to false if not specified. See https://code.claude.com/docs/en/sandboxing#network-isolation
allow_mach_lookup
class-attribute
instance-attribute
¶
allow_mach_lookup: list[AllowMachLookupItem] | None = Field(
None, alias="allowMachLookup", examples=[["com.apple.coresimulator.*"]]
)
macOS only. Additional XPC/Mach service names the sandbox may look up. Supports a single trailing * for prefix matching. Needed for tools that communicate via XPC such as the iOS Simulator or Playwright. See https://code.claude.com/docs/en/sandboxing#network-isolation
allow_managed_domains_only
class-attribute
instance-attribute
¶
(Managed settings only) Only allowedDomains and WebFetch(domain:...) allow rules from managed settings are respected. User, project, local, and flag settings domains are ignored. Denied domains are still respected from all sources. Non-allowed domains are automatically blocked without user prompts. See https://code.claude.com/docs/en/sandboxing#network-isolation
allow_unix_sockets
class-attribute
instance-attribute
¶
Allow Unix domain sockets for local IPC (SSH agent, Docker, etc.). Provide an array of specific paths. Defaults to blocking if not specified. See https://code.claude.com/docs/en/sandboxing#network-isolation
allowed_domains
class-attribute
instance-attribute
¶
Allowlist of network domains for sandboxed commands. Supports wildcard patterns like *.example.com. See https://code.claude.com/docs/en/sandboxing#network-isolation
denied_domains
class-attribute
instance-attribute
¶
Blocklist of network domains for sandboxed commands. Blocks specific domains even when a broader allowedDomains wildcard would otherwise permit them. Supports wildcard patterns like *.example.com. See https://code.claude.com/docs/en/sandboxing#network-isolation
http_proxy_port
class-attribute
instance-attribute
¶
HTTP proxy port to use for network filtering. If not specified, a proxy server will be started automatically. See https://code.claude.com/docs/en/sandboxing#custom-proxy-configuration
socks_proxy_port
class-attribute
instance-attribute
¶
SOCKS proxy port to use for network filtering. If not specified, a proxy server will be started automatically. See https://code.claude.com/docs/en/sandboxing#custom-proxy-configuration
strict_allowlist
class-attribute
instance-attribute
¶
UNDOCUMENTED. Deny non-allowlisted hosts for sandboxed commands without prompting (added v2.1.219). See https://code.claude.com/docs/en/sandboxing#network-isolation
tls_terminate
class-attribute
instance-attribute
¶
tls_terminate: TlsTerminate | None = Field(None, alias='tlsTerminate')
Experimental. Terminate TLS inside the sandbox proxy so it can read the contents of HTTPS requests. Required for mask credential substitution. Set {} to generate an ephemeral certificate authority for the session, or set caCertPath and caKeyPath to use your own. Only honored from user, managed, or CLI --settings settings, not from .claude/settings.json or .claude/settings.local.json. Requires Claude Code v2.1.199 or later. See https://code.claude.com/docs/en/sandboxing#protect-credentials
NewSession
dataclass
¶
Bases: BaseSessionConfig
Start a fresh session.
Source code in src/clawd_code_sdk/models/options.py
NotificationHookInput
¶
Bases: BaseHookInput
Input data for Notification hook events.
Source code in src/clawd_code_sdk/models/hooks.py
NotificationHookSpecificOutput
¶
Bases: TypedDict
Hook-specific output for Notification events.
Source code in src/clawd_code_sdk/models/hooks.py
PermissionRequestHookInput
¶
Bases: BaseHookInput
Input data for PermissionRequest hook events.
Source code in src/clawd_code_sdk/models/hooks.py
PermissionRequestHookSpecificOutput
¶
Bases: TypedDict
Hook-specific output for PermissionRequest events.
Source code in src/clawd_code_sdk/models/hooks.py
PermissionResultAllow
¶
Bases: ClaudeCodeBaseModel
Allow permission result.
Source code in src/clawd_code_sdk/models/permissions.py
PermissionResultDeny
¶
Bases: ClaudeCodeBaseModel
Deny permission result.
Source code in src/clawd_code_sdk/models/permissions.py
Permissions
¶
Bases: ClaudeCodeBaseModel
Tool usage permissions configuration. See https://code.claude.com/docs/en/permissions and https://code.claude.com/docs/en/settings#permission-settings See https://code.claude.com/docs/en/tools-reference for full list of tools available to Claude.
Source code in src/clawd_code_sdk/models/settings.py
3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 | |
additional_directories
class-attribute
instance-attribute
¶
additional_directories: list[AdditionalDirectory] | None = Field(
None, alias="additionalDirectories", examples=[["//Users/alice/Documents", "~/projects"]]
)
Additional directories to include in the permission scope
allow
class-attribute
instance-attribute
¶
allow: list[PermissionRule] | None = None
List of permission rules for allowed operations
ask
class-attribute
instance-attribute
¶
ask: list[PermissionRule] | None = None
List of permission rules that should always prompt for confirmation
block_writes_outside_working_directories
class-attribute
instance-attribute
¶
block_writes_outside_working_directories: bool | None = Field(
None, alias="blockWritesOutsideWorkingDirectories"
)
When true, the Write, Edit, and NotebookEdit tools refuse paths outside the working directories in every permission mode, including bypassPermissions, apart from some of Claude Code's own files. Does not limit shell commands, MCP tools, or the programs hooks run; use sandboxing for those. A true in any settings file applies; false is the same as unset. Requires Claude Code v2.1.314 or later. See https://code.claude.com/docs/en/settings-reference#permissions-blockwritesoutsideworkingdirectories
default_mode
class-attribute
instance-attribute
¶
default_mode: (
Literal[
"acceptEdits",
"bypassPermissions",
"default",
"delegate",
"dontAsk",
"plan",
"auto",
"manual",
]
| None
) = Field(None, alias="defaultMode")
Default permission mode. "default": prompts on first use. UNDOCUMENTED. "manual": accepted alias for "default" (the CLI/VS Code/JetBrains UI now labels this mode "Manual" as of v2.1.200; permission-modes.md has not yet been updated to mention it). "acceptEdits": auto-accepts file edits. "plan": read-only, no modifications. UNDOCUMENTED. "delegate": coordination-only for agent team leads (agent teams are experimental; enable via CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS). "dontAsk": auto-denies unless pre-approved via permissions. "bypassPermissions": skips all prompts (use only in isolated environments). "auto": auto-approves tool calls with background safety checks that verify actions align with your request. See https://code.claude.com/docs/en/permissions
deny
class-attribute
instance-attribute
¶
deny: list[PermissionRule] | None = None
List of permission rules for denied operations
disable_auto_mode
class-attribute
instance-attribute
¶
Set to "disable" to prevent auto mode from being activated. Removes auto from the Shift+Tab cycle and rejects --permission-mode auto at startup. Most useful in managed settings where users cannot override it. See https://code.claude.com/docs/en/permissions
disable_bypass_permissions_mode
class-attribute
instance-attribute
¶
disable_bypass_permissions_mode: Literal["disable"] | None = Field(
None, alias="disableBypassPermissionsMode"
)
Disable the ability to bypass permission prompts
PostCompactHookInput
¶
Bases: BaseHookInput
Input data for PostCompact hook events.
Source code in src/clawd_code_sdk/models/hooks.py
PostToolUseFailureHookInput
¶
Bases: BaseHookInput
Input data for PostToolUseFailure hook events.
Source code in src/clawd_code_sdk/models/hooks.py
PostToolUseFailureHookSpecificOutput
¶
Bases: TypedDict
Hook-specific output for PostToolUseFailure events.
Source code in src/clawd_code_sdk/models/hooks.py
PostToolUseHookInput
¶
Bases: BaseHookInput
Input data for PostToolUse hook events.
Source code in src/clawd_code_sdk/models/hooks.py
PreCompactHookInput
¶
Bases: BaseHookInput
Input data for PreCompact hook events.
Source code in src/clawd_code_sdk/models/hooks.py
PreToolUseHookInput
¶
Bases: BaseHookInput
Input data for PreToolUse hook events.
Source code in src/clawd_code_sdk/models/hooks.py
ProcessError
¶
Bases: ClaudeSDKError
Raised when the CLI process fails.
Source code in src/clawd_code_sdk/_errors.py
PromptHookHandler
¶
Bases: TypedDict
LLM prompt hook handler.
See https://code.claude.com/docs/en/hooks#prompt-and-agent-hook-fields
Source code in src/clawd_code_sdk/models/hooks.py
RateLimitError
¶
Bases: APIError
Raised when API rate limits are exceeded (429).
Applications should implement retry logic with exponential backoff when handling this exception.
Source code in src/clawd_code_sdk/_errors.py
RemoteControlResponse
¶
Bases: BaseModel
Response from enabling remote control.
Contains the URLs and identifiers needed for remote clients to connect to the session.
Source code in src/clawd_code_sdk/models/control.py
ResultError
¶
Bases: ProcessError
The CLI reported an error result and then exited non-zero.
Replaces the bare "exit code 1" ProcessError that follows an
is_error result frame (e.g. a refused resume, error_max_turns), so
the exception carries what the CLI actually reported. Subclasses
ProcessError so existing handlers keep catching it. (Upstream #1198/#1205.)
Source code in src/clawd_code_sdk/_errors.py
ResultErrorMessage
¶
ResultSuccessMessage
¶
Bases: BaseResultMessage
Successful result message.
Source code in src/clawd_code_sdk/models/messages.py
first_request_cache_read_input_tokens
class-attribute
instance-attribute
¶
The cache-read part of first_request_input_tokens (internal, CLI 2.1.330+).
first_request_input_tokens
class-attribute
instance-attribute
¶
Input tokens (cache reads and writes included) of the model call sent at
request_sent_wall_ms; only with it, and only when above zero (internal, CLI 2.1.330+).
local_command
class-attribute
instance-attribute
¶
Set when the turn was a local slash command (no model call).
ResumeSession
dataclass
¶
Bases: BaseSessionConfig
Resume an existing session by ID.
Source code in src/clawd_code_sdk/models/options.py
at_message
class-attribute
instance-attribute
¶
Resume from a specific message UUID within the session.
drops_turn
class-attribute
instance-attribute
¶
Guard for truncating resume (--resume-drops-turn).
Declares the user message UUID of the turn that at_message is expected to
drop. The CLI refuses the resume if the truncation would discard anything else.
Only meaningful together with at_message.
fork
class-attribute
instance-attribute
¶
If True, fork to a new session ID instead of continuing in-place.
SDKSessionInfo
¶
Bases: BaseModel
Session metadata returned by list_sessions.
Source code in src/clawd_code_sdk/models/session.py
archived
class-attribute
instance-attribute
¶
Whether the session has been archived.
created_at
class-attribute
instance-attribute
¶
Creation time in milliseconds since epoch.
custom_title
class-attribute
instance-attribute
¶
User-set session title via /rename.
file_size
class-attribute
instance-attribute
¶
Session file size in bytes.
first_prompt
class-attribute
instance-attribute
¶
First meaningful user prompt in the session.
git_branch
class-attribute
instance-attribute
¶
Git branch at the end of the session.
last_modified
instance-attribute
¶
Last modified time in milliseconds since epoch.
summary
instance-attribute
¶
Display title for the session: custom title, auto-generated summary, or first prompt.
Sandbox
¶
Bases: ClaudeCodeBaseModel
Sandbox execution configuration. See https://code.claude.com/docs/en/sandboxing.
Source code in src/clawd_code_sdk/models/settings.py
2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 | |
allow_apple_events
class-attribute
instance-attribute
¶
Allow sandboxed commands to send Apple Events on macOS (v2.1.181+). Honored only from user, managed, or CLI settings; project settings cannot enable it. See https://code.claude.com/docs/en/sandboxing#limitations
allow_unsandboxed_commands
class-attribute
instance-attribute
¶
Allow commands to run outside the sandbox via the dangerouslyDisableSandbox parameter. When false, the dangerouslyDisableSandbox parameter is completely ignored and all commands must run sandboxed. Default: true. See https://code.claude.com/docs/en/sandboxing#limitations
auto_allow_bash_if_sandboxed
class-attribute
instance-attribute
¶
Automatically allow bash commands without prompting when they run in the sandbox. Only applies to commands that will run sandboxed. See https://code.claude.com/docs/en/sandboxing#sandbox-modes
bwrap_path
class-attribute
instance-attribute
¶
(Managed setting only) Path to custom bubblewrap (bwrap) binary for Linux/WSL sandbox. Overrides default. See https://code.claude.com/docs/en/server-managed-settings
credentials
class-attribute
instance-attribute
¶
credentials: Credentials | None = None
Block sandboxed commands from reading credential files and secret environment variables (v2.1.187+). Entries merge across settings scopes. See https://code.claude.com/docs/en/sandboxing#protect-credentials
enable_weaker_nested_sandbox
class-attribute
instance-attribute
¶
Enable weaker sandbox mode for unprivileged docker environments where --proc mounting fails. This significantly reduces the strength of the sandbox and should only be used when this risk is acceptable. Default: false (secure). See https://code.claude.com/docs/en/sandboxing#limitations
enable_weaker_network_isolation
class-attribute
instance-attribute
¶
macOS only. Allow access to the system TLS trust service (com.apple.trustd.agent) in the sandbox. Required for Go-based tools like gh, gcloud, and terraform to verify TLS certificates when using httpProxyPort with a MITM proxy and custom CA. Reduces security by opening a potential data exfiltration path. Default: false. See https://code.claude.com/docs/en/sandboxing
enabled
class-attribute
instance-attribute
¶
Enable sandboxed bash. See https://code.claude.com/docs/en/sandboxing#enable-sandboxing
enabled_platforms
class-attribute
instance-attribute
¶
enabled_platforms: list[Literal["macos", "linux", "wsl", "windows"]] | None = Field(
None, alias="enabledPlatforms"
)
Limit the entire sandbox configuration to the listed platforms. On platforms not in the list the sandbox config is inert: no sandbox, no auto-allow, no startup warning, and no failIfUnavailable exit. When omitted, all supported platforms are included. Only honored from managed (policy) settings.
excluded_commands
class-attribute
instance-attribute
¶
Commands that should never run in the sandbox (e.g., ["git", "docker"]). See https://code.claude.com/docs/en/sandboxing#configure-sandboxing
fail_if_unavailable
class-attribute
instance-attribute
¶
When true, make sandbox startup a hard failure if required sandbox dependencies are missing. Default: false (sandbox is skipped with a warning). See https://code.claude.com/docs/en/sandboxing#enable-sandboxing
filesystem
class-attribute
instance-attribute
¶
filesystem: Filesystem | None = None
Filesystem access control for sandboxed commands. See https://code.claude.com/docs/en/sandboxing#filesystem-isolation
ignore_violations
class-attribute
instance-attribute
¶
Map of command patterns to filesystem paths to ignore violations for. Use "*" to match all commands
network
class-attribute
instance-attribute
¶
network: Network | None = None
Configures network isolation settings for the sandboxed bash environment, including domain restrictions, Unix socket access, and custom proxy configuration.
ripgrep
class-attribute
instance-attribute
¶
ripgrep: Ripgrep | None = None
Custom ripgrep configuration for Claude Code's bundled ripgrep support. Overrides the bundled binary and arguments.
socat_path
class-attribute
instance-attribute
¶
(Managed setting only) Path to custom socat binary for Linux/WSL network proxying. Overrides default. See https://code.claude.com/docs/en/server-managed-settings
SdkMcpTool
dataclass
¶
Definition for an SDK MCP tool.
Source code in src/clawd_code_sdk/mcp_utils.py
SdkPluginConfig
¶
Bases: ClaudeCodeBaseModel
SDK plugin configuration.
Currently only local plugins are supported via the 'local' type.
Source code in src/clawd_code_sdk/models/mcp.py
skip_mcp_discovery
class-attribute
instance-attribute
¶
Load skills/hooks/agents/commands but not the plugin's MCP servers.
Use when the SDK host owns this plugin's MCP connections.
ServerError
¶
Bases: APIError
Raised when the API server encounters an error (500/529).
This includes internal server errors (500) and overload errors (529). Applications should implement retry logic for transient server errors.
Source code in src/clawd_code_sdk/_errors.py
Session
¶
A managed Claude session wrapping a ClaudeSDKClient.
Not constructed directly — use SessionManager.create_session().
Source code in src/clawd_code_sdk/session.py
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 | |
close
async
¶
Disconnect and release resources. Idempotent.
interrupt
async
¶
send
async
¶
send(prompt: str) -> AsyncIterator[Message]
Send a prompt and stream response messages.
Combines client.query() + client.receive_response() into one call.
Yields every message including the final ResultMessage, then stops.
The completed ConversationTurn is appended to self.turns.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the session is not in IDLE state. |
Source code in src/clawd_code_sdk/session.py
send_and_collect
async
¶
send_and_collect(prompt: str) -> ConversationTurn
Send a prompt and return the full collected response.
Convenience for cases where streaming is not needed.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the session is not in IDLE state or no ResultMessage was received. |
Source code in src/clawd_code_sdk/session.py
set_max_thinking_tokens
async
¶
set_model
async
¶
set_permission_mode
async
¶
set_permission_mode(mode: PermissionMode) -> SDKControlSetPermissionModeResponse | None
Change permission mode during conversation (returns the mode now in effect).
Source code in src/clawd_code_sdk/session.py
SessionManager
¶
Manages multiple concurrent Claude SDK sessions.
Usage::
async with SessionManager() as manager:
s1 = await manager.create_session("coding", options=opts)
turn = await s1.send_and_collect("Explain this codebase")
print(turn.text)
s2 = await manager.create_session("review", options=opts, prompt="Review my PR")
async for msg in s2.send("What issues did you find?"):
...
Source code in src/clawd_code_sdk/session.py
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 | |
active_sessions
property
¶
active_sessions: dict[str, Session]
Sessions in IDLE or RESPONDING state.
__init__
¶
Initialize the session manager.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_concurrent_sessions
|
int | None
|
Optional cap on simultaneous connected
sessions. |
None
|
Source code in src/clawd_code_sdk/session.py
__iter__
¶
close_all
async
¶
Close all sessions, concurrently. Errors during individual closes are suppressed.
Source code in src/clawd_code_sdk/session.py
close_session
async
¶
Close and remove a specific session.
Raises:
| Type | Description |
|---|---|
KeyError
|
If session_id not found. |
Source code in src/clawd_code_sdk/session.py
create_session
async
¶
create_session(
session_id: str | None = None,
*,
options: ClaudeAgentOptions | None = None,
transport: Transport | None = None,
prompt: str | None = None,
connect: bool = True,
) -> Session
Create and optionally connect a new session.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id
|
str | None
|
Explicit ID, or auto-generated UUID if None. |
None
|
options
|
ClaudeAgentOptions | None
|
Session-specific options. |
None
|
transport
|
Transport | None
|
Optional custom transport. |
None
|
prompt
|
str | None
|
If provided, sent as the initial prompt on connect. |
None
|
connect
|
bool
|
If True (default), connect immediately. |
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If session_id already exists. |
RuntimeError
|
If max_concurrent_sessions would be exceeded. |
Source code in src/clawd_code_sdk/session.py
get_session
¶
get_session(session_id: str) -> Session
Get a session by ID.
Raises:
| Type | Description |
|---|---|
KeyError
|
If session_id not found. |
Source code in src/clawd_code_sdk/session.py
resume_session
async
¶
resume_session(
session_id: str,
*,
options: ClaudeAgentOptions | None = None,
transport: Transport | None = None,
) -> Session
Resume a previously persisted session by ID.
Sets session to a :class:ResumeSession config on the options,
then connects.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id
|
str
|
The session ID to resume. |
required |
options
|
ClaudeAgentOptions | None
|
Session-specific options ( |
None
|
transport
|
Transport | None
|
Optional custom transport. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If session_id already exists in this manager. |
Source code in src/clawd_code_sdk/session.py
snapshots
¶
snapshots() -> dict[str, SessionSnapshot]
SessionMessage
¶
Bases: BaseModel
A message from a session transcript.
Returned by get_session_messages for reading historical session data.
Source code in src/clawd_code_sdk/models/session.py
parent_agent_id
class-attribute
instance-attribute
¶
For messages of nested subagents: agent id of the subagent that spawned this one.
parent_tool_use_id
class-attribute
instance-attribute
¶
For subagent messages: id of the Agent tool_use in the parent session that spawned
the subagent (from its .meta.json sidecar). None for top-level session messages.
SessionSnapshot
dataclass
¶
Read-only snapshot of session metadata at a point in time.
Source code in src/clawd_code_sdk/session.py
SettingsSource
¶
Bases: BaseModel
A single settings source with its raw settings.
Source code in src/clawd_code_sdk/models/control.py
StopHookInput
¶
SubagentStartHookInput
¶
Bases: BaseHookInput
Input data for SubagentStart hook events.
Source code in src/clawd_code_sdk/models/hooks.py
SubagentStartHookSpecificOutput
¶
Bases: TypedDict
Hook-specific output for SubagentStart events.
Source code in src/clawd_code_sdk/models/hooks.py
SubagentStopHookInput
¶
Bases: BaseHookInput
Input data for SubagentStop hook events.
Source code in src/clawd_code_sdk/models/hooks.py
TextBlock
¶
Bases: BaseContentBlock
Text content block.
Source code in src/clawd_code_sdk/models/content_blocks.py
ThinkingBlock
¶
Bases: BaseContentBlock
Thinking/reasoning content block.
Source code in src/clawd_code_sdk/models/content_blocks.py
ThinkingConfigAdaptive
¶
Bases: ClaudeCodeBaseModel
Adaptive thinking configuration - model decides thinking budget.
Source code in src/clawd_code_sdk/models/thinking.py
display
class-attribute
instance-attribute
¶
Controls how thinking content appears in the response.
When set to summarized, thinking is returned normally. When set to omitted,
thinking content is redacted but a signature is returned for multi-turn
continuity. Defaults to summarized.
ThinkingConfigDisabled
¶
Bases: ClaudeCodeBaseModel
Disabled thinking configuration.
Source code in src/clawd_code_sdk/models/thinking.py
ThinkingConfigEnabled
¶
Bases: ClaudeCodeBaseModel
Enabled thinking configuration with explicit token budget.
Source code in src/clawd_code_sdk/models/thinking.py
budget_tokens
instance-attribute
¶
Determines how many tokens Claude can use for its internal reasoning process.
Larger budgets can enable more thorough analysis for complex problems, improving
response quality.
Must be ≥1024 and less than max_tokens.
See
extended thinking
for details.
display
class-attribute
instance-attribute
¶
Controls how thinking content appears in the response.
When set to summarized, thinking is returned normally. When set to omitted,
thinking content is redacted but a signature is returned for multi-turn
continuity. Defaults to summarized.
ToolCallSummary
dataclass
¶
Summary of a single tool invocation within a conversation turn.
Source code in src/clawd_code_sdk/session.py
ToolPermissionContext
dataclass
¶
Context information for tool permission callbacks.
Source code in src/clawd_code_sdk/models/permissions.py
agent_id
class-attribute
instance-attribute
¶
The agent that initiated the tool call, if in a multi-agent setup.
blocked_path
class-attribute
instance-attribute
¶
The file path that triggered the permission request, if applicable.
For example, when a Bash command tries to access a path outside allowed directories.
decision_reason
class-attribute
instance-attribute
¶
Why the CLI triggered the permission check.
description
class-attribute
instance-attribute
¶
Human-readable subtitle from the bridge.
E.g. "Claude will have read and write access to files in ~/Downloads".
display_name
class-attribute
instance-attribute
¶
Short noun phrase for the tool action (e.g. "Read file").
Suitable for button labels or compact UI.
input
class-attribute
instance-attribute
¶
The input to the tool that generated this permission request.
suggestions
class-attribute
instance-attribute
¶
Permission suggestions from CLI for updating permissions.
So the user won't be prompted again for this tool during this session.
title
class-attribute
instance-attribute
¶
Full permission prompt sentence rendered by the bridge.
E.g. "Claude wants to read foo.txt". Use this as the primary prompt text when present instead of reconstructing from toolName+input.
tool_name
class-attribute
instance-attribute
¶
The name of the tool that generated this permission request.
tool_use_id
instance-attribute
¶
Unique identifier for this specific tool call within the assistant message.
Multiple tool calls in the same assistant message will have different tool_use_ids.
from_permission_request
classmethod
¶
from_permission_request(req: SDKControlPermissionRequest) -> Self
Create a PermissionContext from a permission request.
Source code in src/clawd_code_sdk/models/permissions.py
ToolResultBlock
¶
Bases: BaseContentBlock
Tool result content block.
Source code in src/clawd_code_sdk/models/content_blocks.py
extract_text
¶
Extract text content from this tool result.
Source code in src/clawd_code_sdk/models/content_blocks.py
ToolUseBlock
¶
Bases: BaseContentBlock
Tool use content block.
Source code in src/clawd_code_sdk/models/content_blocks.py
Transport
¶
Bases: ABC
Abstract transport for Claude communication.
WARNING: This internal API is exposed for custom transport implementations (e.g., remote Claude Code connections). The Claude Code team may change or or remove this abstract class in any future release. Custom implementations must be updated to match interface changes.
This is a low-level transport interface that handles raw I/O with the Claude process or service. The Query class builds on top of this to implement the control protocol and message routing.
Source code in src/clawd_code_sdk/_internal/transport/__init__.py
close
abstractmethod
async
¶
connect
abstractmethod
async
¶
Connect the transport and prepare for communication.
For subprocess transports, this starts the process. For network transports, this establishes the connection.
Source code in src/clawd_code_sdk/_internal/transport/__init__.py
end_input
abstractmethod
async
¶
read_messages
abstractmethod
¶
Read and parse messages from the transport.
Yields:
| Type | Description |
|---|---|
AsyncIterator[dict[str, Any]]
|
Parsed JSON messages from the transport |
write
abstractmethod
async
¶
Write raw data to the transport.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
str
|
Raw string data to write (typically JSON + newline) |
required |
UserDocumentPrompt
dataclass
¶
A user prompt containing a base64-encoded PDF document.
Source code in src/clawd_code_sdk/models/prompts.py
context
class-attribute
instance-attribute
¶
Optional context about the document.
media_type
class-attribute
instance-attribute
¶
MIME type of the document.
to_content_block
¶
Return the Anthropic API content block dict.
Source code in src/clawd_code_sdk/models/prompts.py
UserDocumentURLPrompt
dataclass
¶
A user prompt containing a PDF document referenced by URL.
Source code in src/clawd_code_sdk/models/prompts.py
context
class-attribute
instance-attribute
¶
Optional context about the document.
to_content_block
¶
Return the Anthropic API content block dict.
Source code in src/clawd_code_sdk/models/prompts.py
UserImagePrompt
dataclass
¶
A user prompt containing a single base64-encoded image.
Source code in src/clawd_code_sdk/models/prompts.py
to_content_block
¶
Return the Anthropic API content block dict.
Source code in src/clawd_code_sdk/models/prompts.py
UserImageURLPrompt
dataclass
¶
A user prompt containing an image referenced by URL.
Source code in src/clawd_code_sdk/models/prompts.py
to_content_block
¶
Return the Anthropic API content block dict.
UserMessage
¶
Bases: BaseModel
User message.
Source code in src/clawd_code_sdk/models/messages.py
agent_id
class-attribute
instance-attribute
¶
Subagent ID when this message belongs to a subagent transcript.
client_composed
class-attribute
instance-attribute
¶
Set when the host composed this message (as opposed to the user typing it).
tool_result_meta
class-attribute
instance-attribute
¶
tool_result_meta: list[ToolResultMeta] | None = None
Per-tool-result metadata, e.g. how permission was decided (undocumented).
uuid
class-attribute
instance-attribute
¶
Always set for incoming user messages, can be omitted for objects created in query().
parse_command_output
¶
Extract output from legacy XML-tagged command output in user messages.
Source code in src/clawd_code_sdk/models/messages.py
UserPlainTextDocumentPrompt
dataclass
¶
A user prompt containing a plain text document.
Source code in src/clawd_code_sdk/models/prompts.py
context
class-attribute
instance-attribute
¶
Optional context about the document.
media_type
class-attribute
instance-attribute
¶
MIME type (always text/plain).
to_content_block
¶
Return the Anthropic API content block dict.
Source code in src/clawd_code_sdk/models/prompts.py
UserPromptSubmitHookInput
¶
Bases: BaseHookInput
Input data for UserPromptSubmit hook events.
Source code in src/clawd_code_sdk/models/hooks.py
UserTextPrompt
dataclass
¶
create_sdk_mcp_server
¶
create_sdk_mcp_server(
name: str, version: str = "1.0.0", tools: list[SdkMcpTool[Any]] | None = None
) -> McpSdkServerConfigWithInstance
Create an in-process MCP server that runs within your Python application.
Unlike external MCP servers that run as separate processes, SDK MCP servers run directly in your application's process. This provides: - Better performance (no IPC overhead) - Simpler deployment (single process) - Easier debugging (same process) - Direct access to your application's state
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Unique identifier for the server. This name is used to reference the server in the mcp_servers configuration. |
required |
version
|
str
|
Server version string. Defaults to "1.0.0". This is for informational purposes and doesn't affect functionality. |
'1.0.0'
|
tools
|
list[SdkMcpTool[Any]] | None
|
List of SdkMcpTool instances created with the @tool decorator. These are the functions that Claude can call through this server. If None or empty, the server will have no tools (rarely useful). |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
McpSdkServerConfigWithInstance |
McpSdkServerConfigWithInstance
|
A configuration object that can be passed to |
McpSdkServerConfigWithInstance
|
ClaudeAgentOptions.mcp_servers. Its |
|
McpSdkServerConfigWithInstance
|
|
|
McpSdkServerConfigWithInstance
|
in-memory MCP transport. |
Example
Simple calculator server:
@tool("add", "Add numbers", {"a": float, "b": float}) ... async def add(args): ... return {"content": [{"type": "text", "text": f"Sum: {args['a'] + args['b']}"}]}
calculator = create_sdk_mcp_server(name="calculator", tools=[add]) options = ClaudeAgentOptions(mcp_servers={"calc": calculator})
Bringing your own server: any mcp.server.Server built with the
installed mcp package can be used in place of this helper, and the
requests it handles (tools, resources, prompts, ...) are served.
Requests and notifications the server sends to the client (sampling,
elicitation, roots, logging, progress, list_changed) are not forwarded:
from mcp.server import Server my_server = Server("mine") # register handlers with the mcp API config = McpSdkServerConfigWithInstance(name="mine", instance=my_server)
Notes
- Tool arguments are validated against the tool's input schema. Unknown tools, invalid arguments and exceptions raised by a handler are all reported to Claude as error results rather than failing the request.
- Works with both mcp 1.x and mcp 2.x.
Source code in src/clawd_code_sdk/mcp_utils.py
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 | |
delete_session
¶
Delete a session by removing its JSONL file and subagent transcripts.
This is a hard delete — the {session_id}.jsonl file is removed
permanently, along with the sibling {session_id}/ subdirectory that
holds subagent transcripts (if it exists). SDK users who need soft-delete
semantics can use tag_session(id, '__hidden') and filter on listing
instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id
|
str
|
UUID of the session to delete. |
required |
directory
|
str | None
|
Project directory path (same semantics as
|
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
FileNotFoundError
|
If the session file cannot be found. |
Example
Delete a session::
delete_session("550e8400-e29b-41d4-a716-446655440000")
Source code in src/clawd_code_sdk/_internal/session_mutations.py
fork_session
¶
fork_session(
session_id: str,
directory: str | None = None,
up_to_message_id: str | None = None,
title: str | None = None,
) -> ForkSessionResult
Fork a session into a new branch with fresh UUIDs.
Copies transcript messages from the source session into a new session
file, remapping every message UUID and preserving the parentUuid
chain. Supports up_to_message_id for branching from a specific
point in the conversation.
Forked sessions start without undo history (file-history snapshots are not copied).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id
|
str
|
UUID of the source session to fork. |
required |
directory
|
str | None
|
Project directory path (same semantics as
|
None
|
up_to_message_id
|
str | None
|
Slice transcript up to this message UUID (inclusive). If omitted, copies the full transcript. |
None
|
title
|
str | None
|
Custom title for the fork. If omitted, derives from the original title + " (fork)". |
None
|
Returns:
| Type | Description |
|---|---|
ForkSessionResult
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
FileNotFoundError
|
If the source session file cannot be found. |
ValueError
|
If the session has no messages to fork, or if
|
Example
Fork a session::
result = fork_session("550e8400-e29b-41d4-a716-446655440000")
print(result.session_id)
Fork from a specific point::
result = fork_session(
"550e8400-e29b-41d4-a716-446655440000",
up_to_message_id="660e8400-e29b-41d4-a716-446655440001",
)
Source code in src/clawd_code_sdk/_internal/session_mutations.py
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 | |
get_session_info
¶
get_session_info(session_id: str, directory: str | None = None) -> SDKSessionInfo | None
Reads metadata for a single session by ID.
Wraps _read_session_lite for one file — no O(n) directory scan.
Directory resolution matches get_session_messages: directory is
the project path; when omitted, all project directories are searched for
the session file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id
|
str
|
UUID of the session to look up. |
required |
directory
|
str | None
|
Project directory path (same semantics as
|
None
|
Returns:
| Type | Description |
|---|---|
SDKSessionInfo | None
|
|
SDKSessionInfo | None
|
is not found, is a sidechain session, or has no extractable summary. |
Source code in src/clawd_code_sdk/_internal/sessions.py
get_session_messages
¶
get_session_messages(
session_id: str, directory: str | None = None, limit: int | None = None, offset: int = 0
) -> list[SessionMessage]
Reads a session's conversation messages from its JSONL transcript file.
Parses the full JSONL, builds the conversation chain via parentUuid
links, and returns user/assistant messages in chronological order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id
|
str
|
UUID of the session to read. |
required |
directory
|
str | None
|
Project directory to find the session in. If omitted,
searches all project directories under |
None
|
limit
|
int | None
|
Maximum number of messages to return. |
None
|
offset
|
int
|
Number of messages to skip from the start. |
0
|
Returns:
| Type | Description |
|---|---|
list[SessionMessage]
|
List of |
list[SessionMessage]
|
an empty list if the session is not found, the session_id is not a |
list[SessionMessage]
|
valid UUID, or the transcript contains no visible messages. |
Source code in src/clawd_code_sdk/_internal/sessions.py
get_subagent_messages
¶
get_subagent_messages(
session_id: str,
agent_id: str,
directory: str | None = None,
limit: int | None = None,
offset: int = 0,
) -> list[SessionMessage]
Reads a subagent's conversation messages from its JSONL transcript file.
Parses the subagent transcript, builds the conversation chain via
parentUuid links, and returns user/assistant messages in
chronological order. Each message's parent_tool_use_id is the id of
the Agent tool_use in the parent session that spawned this subagent
(and parent_agent_id the spawning subagent, for nested subagents),
read from the agent-<agentId>.meta.json sidecar next to the
transcript; both are None if the sidecar is missing or unusable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id
|
str
|
UUID of the parent session. |
required |
agent_id
|
str
|
ID of the subagent (as returned by |
required |
directory
|
str | None
|
Project directory to find the session in. If omitted,
searches all project directories under |
None
|
limit
|
int | None
|
Maximum number of messages to return. |
None
|
offset
|
int
|
Number of messages to skip from the start. |
0
|
Returns:
| Type | Description |
|---|---|
list[SessionMessage]
|
List of |
list[SessionMessage]
|
an empty list if the session or subagent is not found, the |
list[SessionMessage]
|
session_id is not a valid UUID, or the transcript contains no |
list[SessionMessage]
|
user/assistant messages. |
Source code in src/clawd_code_sdk/_internal/sessions.py
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 | |
list_sessions
¶
list_sessions(
directory: str | None = None,
limit: int | None = None,
offset: int = 0,
include_worktrees: bool = True,
) -> list[SDKSessionInfo]
Lists sessions with metadata extracted from stat + head/tail reads.
When directory is provided, returns sessions for that project
directory and its git worktrees. When omitted, returns sessions
across all projects.
Use limit and offset for pagination.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory
|
str | None
|
Directory to list sessions for. When provided, returns sessions for this project directory (and optionally its git worktrees). When omitted, returns sessions across all projects. |
None
|
limit
|
int | None
|
Maximum number of sessions to return. |
None
|
offset
|
int
|
Number of sessions to skip from the start of the sorted
result set. Use with |
0
|
include_worktrees
|
bool
|
When |
True
|
Returns:
| Type | Description |
|---|---|
list[SDKSessionInfo]
|
List of |
Source code in src/clawd_code_sdk/_internal/sessions.py
list_subagents
¶
Lists subagent IDs for a given session by scanning the subagents directory.
Subagent transcripts are stored at
~/.claude/projects/<project>/<sessionId>/subagents/agent-<agentId>.jsonl
(and may be nested in subdirectories such as workflows/<runId>/).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id
|
str
|
UUID of the parent session. |
required |
directory
|
str | None
|
Project directory to find the session in. If omitted,
searches all project directories under |
None
|
Returns:
| Type | Description |
|---|---|
list[str]
|
List of subagent ID strings. Returns an empty list if the session |
list[str]
|
is not found, the session_id is not a valid UUID, or the session |
list[str]
|
has no subagents. |
Example
List subagent IDs for a session::
agent_ids = list_subagents(
"550e8400-e29b-41d4-a716-446655440000",
directory="/path/to/project",
)
Source code in src/clawd_code_sdk/_internal/sessions.py
rename_session
¶
Rename a session by appending a custom-title entry.
list_sessions reads the LAST custom-title from the file tail, so
repeated calls are safe — the most recent wins.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id
|
str
|
UUID of the session to rename. |
required |
title
|
str
|
New session title. Leading/trailing whitespace is stripped. Must be non-empty after stripping. |
required |
directory
|
str | None
|
Project directory path (same semantics as
|
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
FileNotFoundError
|
If the session file cannot be found. |
Example
Rename a session in a specific project::
rename_session(
"550e8400-e29b-41d4-a716-446655440000",
"My refactoring session",
directory="/path/to/project",
)
Source code in src/clawd_code_sdk/_internal/session_mutations.py
tag_session
¶
Tag a session. Pass None to clear the tag.
Appends a {type:'tag',tag:<tag>,sessionId:<id>} JSONL entry.
list_sessions reads the LAST tag from the file tail — most recent
wins. Passing None appends an empty-string tag entry which
list_sessions treats as None (cleared).
Tags are Unicode-sanitized before storing (removes zero-width chars, directional marks, private-use characters, etc.) for CLI filter compatibility.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id
|
str
|
UUID of the session to tag. |
required |
tag
|
str | None
|
Tag string, or |
required |
directory
|
str | None
|
Project directory path (same semantics as
|
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
FileNotFoundError
|
If the session file cannot be found. |
Example
Tag a session::
tag_session(
"550e8400-e29b-41d4-a716-446655440000",
"experiment",
directory="/path/to/project",
)
Clear a tag::
tag_session(session_id, None)
Source code in src/clawd_code_sdk/_internal/session_mutations.py
tool
¶
tool(
name: str,
description: str,
input_schema: type | dict[str, Any],
*,
title: str | None = None,
annotations: ToolAnnotations | None = None,
output_schema: dict[str, Any] | None = None,
meta: dict[str, Any] | None = None,
search_hint: str | None = None,
always_load: bool | None = None,
max_result_size_chars: int | None = None,
) -> Callable[[Callable[[Any], Awaitable[dict[str, Any]]]], SdkMcpTool[Any]]
Decorator for defining MCP tools with type safety.
Creates a tool that can be used with SDK MCP servers. The tool runs in-process within your Python application, providing better performance than external MCP servers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Unique identifier for the tool. This is what Claude will use to reference the tool in function calls. |
required |
description
|
str
|
Human-readable description of what the tool does. This helps Claude understand when to use the tool. |
required |
input_schema
|
type | dict[str, Any]
|
Schema defining the tool's input parameters. Can be either: - A dictionary mapping parameter names to types (e.g., {"text": str}) - A TypedDict class for more complex schemas - A JSON Schema dictionary for full validation |
required |
title
|
str | None
|
Optional human-readable display name for the tool. If not set, clients typically use the name. |
None
|
annotations
|
ToolAnnotations | None
|
Optional annotations for the tool. |
None
|
output_schema
|
dict[str, Any] | None
|
Optional JSON Schema describing the tool's output format. |
None
|
meta
|
dict[str, Any] | None
|
Optional metadata dict sent as |
None
|
search_hint
|
str | None
|
Optional hint text for tool search/discovery. |
None
|
always_load
|
bool | None
|
Optional flag indicating whether the tool should always be loaded. |
None
|
max_result_size_chars
|
int | None
|
Optional size (in characters) up to which Claude Code keeps the tool's result inline instead of persisting it with a preview. |
None
|
Returns:
| Type | Description |
|---|---|
Callable[[Callable[[Any], Awaitable[dict[str, Any]]]], SdkMcpTool[Any]]
|
A decorator function that wraps the tool implementation and returns |
Callable[[Callable[[Any], Awaitable[dict[str, Any]]]], SdkMcpTool[Any]]
|
an SdkMcpTool instance ready for use with create_sdk_mcp_server(). |
Notes
- The tool function must be async
- The function receives a single dict argument with the input parameters
- The function should return a dict with a "content" key containing the response
- Errors can be indicated by including "is_error": True in the response