pypi / claude-agent-sdk
claude-agent-sdk
What changed in claude-agent-sdk 0.1 to 0.2, from its official release notes, upgrade guides and advisories. Sources checked 2026-10-20.
9 breaking2 security2 deprecations123 new APIs and options7 behavior and defaults10 tooling61 fixes and other
See which of these apply to your code, ranked, in your agent:
npx @unstale/cli initclaude-agent-sdk 0.251 changes
Breaking changes 8
Changed ignoreViolations to dict[str, list[str]] to match the CLI schema, allowing command-pattern substrings to map to violation-text substrings.
Skill names are validated at connect time and malformed or delimiter-carrying values raise ValueError, preventing --allowedTools injection; replace wildcard strings with skills="all" or a Skill(...) rule in allowed_tools.
On Windows, resume values containing cmd.exe metacharacters or newlines now raise ValueError, preventing injection if a cmd.exe hop is reintroduced.
On Windows, session_id values containing cmd.exe metacharacters or newlines now raise ValueError, preventing injection if a cmd.exe hop is reintroduced.
Spawning .bat and .cmd CLI scripts is blocked on Windows to prevent command injection; users of npm's claude.cmd shim should switch to a native installer, explicit claude.exe path, or platform wheel that bundles the CLI.
MCP servers connect in the background by default, so sessions start immediately and slow servers report status: "pending" in init. Set MCP_CONNECTION_NONBLOCKING=0 to restore waiting up to 5s, or use alwaysLoad: true to require a server in turn 1.
The field type is narrowed from list[Any] | None to list[dict[str, Any]] | None, enabling proper type-checking for consumers.
Headless and SDK sessions use Task tools instead of TodoWrite. Tool consumers should accumulate tasks by task ID rather than replacing a snapshot list.
Security 1
The
--resumevalue is passed as a single=-joined argv token so a dash-prefixed value is not misinterpreted as an independent CLI flag.
New APIs and options 20
Added typed output classes and missing input fields for hooks, giving hook implementations precise type information instead of untyped dicts.
Typed the init system message payload, including nested types, so developers can cast msg.data and access fields such as capabilities, model, and mcp_servers.
Sets a bounded wait ceiling for background activity; the default is 10 minutes, preventing indefinite hangs.
Added verbatim_prompts, defaulting to False. When True, user messages reach the CLI unchanged, preventing @path expansion and slash-command dispatch.
Adds a new typed dict for custom system prompts.
Adds a snapshot field to control whether resumed sessions keep the system prompt from the first request or rebuild it on every request.
A new ClaudeAgentOptions boolean forwards a subagent's text and thinking blocks as stream messages, allowing consumers to render the full nested transcript.
In-process SDK MCP servers support mcp 2.x alongside 1.x, using mcp's in-memory transport so hand-built servers work at full fidelity; tool cancellation on interrupt is also supported on mcp 2.x.
The SDK raises ResultError, a ProcessError subclass, after the CLI exits following a terminal error result; its structured payload lets callers branch on failure reason without string matching.
SessionMessage gains a parent_agent_id field containing the spawning agent's id.
Adds a guard to validate that only entries from a specific turn are discarded during resume.
Adds an option to fork a session at an earlier transcript entry, enabling a rewind without silently dropping unobserved messages.
The SDK surfaces conversation reset events as a message with conversation and session identifiers, so applications can detect transcript-discarding flows. The Message union is widened.
Exports types for representing message origin and its kinds, including task notification subkinds.
Adds an origin field that identifies why a turn was initiated, distinguishing application-submitted prompts from session-injected turns.
Adds an origin field that identifies why a turn was initiated, distinguishing application-submitted prompts from session-injected turns.
Types model_usage as dict[str, ModelUsage] instead of dict[str, Any]; the new ModelUsage TypedDict includes optional canonicalModel and provider fields.
Adds terminal_reason to report why the query loop ended, including whether the turn was cancelled via ClaudeSDKClient.interrupt().
Adds a type for task_updated status values, supporting reliable active-task bookkeeping.
A public type alias for Claude effort string levels is exported from the package root for downstream SDK wrappers and type annotations.
Behavior and default changes 2
The permission callback now works with string prompts as well as ClaudeSDKClient; stdin remains open so the CLI can send permission requests over the control protocol.
ToolAnnotations accepts both camelCase and snake_case hint names on every mcp version.
Tooling 5
The bundled Claude CLI was updated to version 2.1.300.
The bundled Claude CLI was updated, which may affect SDK users running it.
The bundled Claude CLI was updated; the notes do not specify what changed for developers.
The bundled Claude CLI was updated, which may affect the CLI behavior used by the SDK.
The bundled Claude CLI was updated to version 2.1.172.
Fixes and other changes 15
The SDK keeps stdin open until the CLI reports idle, preventing follow-up turns from failing when a background subagent finishes just before the turn result arrives.
Subagent transcript readers now recover parent_tool_use_id from metadata, linking each subagent's messages to the Agent tool_use block in the parent session.
Pending control requests now receive the CLI's actual resume rejection error instead of a generic command-failed message.
Resuming from a SessionStore now copies settings files into the temporary config directory, preserving authentication, hooks, environment variables, and permissions.
Keeps stdin open until all in-flight background tasks complete and the final result frame arrives, preventing SDK-MCP tool calls from failing and PreToolUse hooks from being bypassed.
Values starting with - are now passed using --flag=value form, preventing them from being misinterpreted as separate CLI flags.
The
--session-idvalue is passed as a single=-joined argv token so a dash-prefixed value is not misinterpreted as an independent CLI flag.A runtime warning is now emitted when a can_use_tool callback is registered alongside allowed_tools or bypassPermissions, which silently prevents the callback from firing.
Fixed an uncaught TypeError when the CLI emits a message whose content is a plain string or another non-dict value instead of a list of content blocks.
Fixed whitespace loss when a single NDJSON line exceeds the 64 KiB stream buffer, avoiding corruption of tool output or assistant message content.
Subprocess cleanup is shielded from asyncio cancellation so SIGTERM/SIGKILL teardown runs and prevents orphaned claude child processes when the parent task is cancelled.
Terminal system/task_updated events are exposed as typed messages with task_id, patch, status, session_id, and uuid fields, preventing active-task tracking from hanging when no TaskNotificationMessage follows.
Adds a frozenset of terminal task statuses for reliable active-task bookkeeping.
Fixed crashes when passing session_store= to query() or ClaudeSDKClient under trio by porting session store code paths from asyncio primitives to anyio.
Exceptions from a user-provided stderr callback are caught per line, so a failing callback no longer stops delivery of subsequent stderr lines for the session.
claude-agent-sdk 0.1163 changes
Breaking changes 1
Stderr piping now depends solely on whether a stderr callback is registered; detection of --debug-to-stderr was dropped from the transport layer.
Security 1
Added tag_session() with Unicode sanitization.
Deprecations 2
Using
Skillinallowed_toolsis deprecated in favor of theskillsoption onClaudeAgentOptions.The field is deprecated in favor of the new thinking field, which takes precedence.
New APIs and options 103
The
skillsoption provides more granular control over available skills.Adds the HTTP status code from failing API calls to result messages, providing a safe-to-log field for classifying errors when is_error=True.
Added xhigh as an effort level, with fallback to high on models other than Opus 4.7.
Added xhigh as an effort level, with fallback to high on models other than Opus 4.7.
Added include_hook_events to emit hook events from the CLI and yield them from the message stream as HookEventMessage.
When True, the CLI uses only MCP servers passed via mcp_servers, ignoring project, user, and global MCP configurations for deterministic server sets.
Added updatedToolOutput to replace any tool's output before it reaches the model, not just MCP tools.
Added support for the defer hook decision in permissionDecision.
Added the DeferredToolUse dataclass on deferred_tool_use for deferred tool use round trips.
Added decision_reason, blocked_path, title, display_name, and description fields to enable richer permission prompts in can_use_tool callbacks.
Adds the session_store_flush option with batched or eager modes; eager delivers transcript frames to SessionStore.append() in near-real-time instead of waiting for the end-of-turn flush.
Added domain allowlist and network lookup fields, enabling Python SDK users to configure network allowlists with proper type hints.
Adds a content block type that surfaces results from server-executed tools that were previously silently dropped.
Adds a helper for O(1)-per-session list views using summary sidecars.
Replays a local on-disk session into any SessionStore adapter, enabling migration from local storage to remote stores.
Adds a content block type that surfaces server-executed tool calls, such as advisor and web_search, that were previously silently dropped.
Adds an optional protocol method so stores with append-time summary sidecars can serve list_session_summaries without loading full transcripts, reducing round-trips from N to 1 for N sessions.
Adds a display field forwarded as --thinking-display, letting callers override Opus 4.7's default "omitted" behavior and receive summarized thinking text.
Adds a store-backed helper for forking a session.
Adds an in-memory reference implementation of SessionStore.
Adds a store-backed helper for listing sessions.
Adds transcript mirroring via --session-mirror.
Adds the ability to resume a session from a SessionStore.
Adds a SessionStore protocol with append, load, list_sessions, delete, and list_subkeys methods, bringing Python support to parity with the TypeScript SDK.
Added a top-level ClaudeAgentOptions parameter to enable all discovered skills, selected named skills, or no skills without manually configuring allowed_tools and setting_sources.
Adds a session helper for reading subagent transcripts and inspecting subagent message chains.
Adds a session helper for listing subagents spawned during a session.
Adds "auto" to PermissionMode, bringing parity with the TypeScript SDK and CLI v2.1.90+.
Adds exclude_dynamic_sections to move per-user dynamic sections out of the system prompt, enabling cross-user prompt cache hits.
Added a session_id option for specifying custom session IDs.
Added a ClaudeSDKClient method for querying context window usage by category.
Exposed agent_id in ToolPermissionContext to distinguish parallel permission requests.
Exposed tool_use_id in ToolPermissionContext to distinguish parallel permission requests.
The @tool decorator and create_sdk_mcp_server support per-parameter descriptions in JSON Schema using typing.Annotated.
Adds the disallowedTools field to AgentDefinition.
Adds the initialPrompt field to AgentDefinition.
Adds the maxTurns field to AgentDefinition.
Adds an API to delete a session.
Adds an API to fork a session.
Adds offset-based pagination for session listing.
Adds CLI support for specifying a system prompt file via SystemPromptFile.
Adds a task_budget option for token budget management.
Adds a function for retrieving session metadata.
Adds the created_at field to SDKSessionInfo for session metadata.
Adds the tag field to SDKSessionInfo for session metadata.
Added the mcpServers field to AgentDefinition.
Added the memory field to AgentDefinition.
Added the skills field to AgentDefinition.
Added a typed RateLimitEvent message.
Added rename_session() for session renaming.
Added a method for runtime MCP server management.
Added a top-level function for retrieving past session data.
Added a top-level function for retrieving past session data.
Added a typed status for runtime MCP server management.
Added the
agent_idfield to tool-lifecycle hook inputs.Added the
agent_typefield to tool-lifecycle hook inputs.Added the
agent_idfield to tool-lifecycle hook inputs.Added the
agent_typefield to tool-lifecycle hook inputs.Added the
agent_idfield to tool-lifecycle hook inputs.Added the
agent_typefield to tool-lifecycle hook inputs.Added a method for runtime MCP server management.
Added a field for inspecting why a conversation turn ended.
Added a message subclass for better type safety when handling task-related events.
Added a message subclass for better type safety when handling task-related events.
Added a message subclass for better type safety when handling task-related events.
Adds a ClaudeAgentOptions field accepting low, medium, high, or max to control thinking depth.
Adds a ClaudeAgentOptions field for fine-grained control over extended thinking, taking precedence over max_thinking_tokens.
The @tool decorator accepts an annotations parameter for MCP tool metadata hints such as readOnlyHint and destructiveHint.
ToolAnnotations is re-exported from claude_agent_sdk for convenient access to MCP tool annotation types.
Adds the Notification hook event, with NotificationHookInput and NotificationHookSpecificOutput, for handling notification events.
Adds the PermissionRequest hook event, with PermissionRequestHookInput and PermissionRequestHookSpecificOutput, for handling permission requests.
Adds the tool_use_id field to PostToolUseHookInput.
Adds the updatedMCPToolOutput field to PostToolUseHookSpecificOutput.
Adds the tool_use_id field to PreToolUseHookInput.
Adds the additionalContext field to PreToolUseHookSpecificOutput.
Adds the SubagentStart hook event, with SubagentStartHookInput and SubagentStartHookSpecificOutput, for handling subagent startup.
Adds the agent_id field to SubagentStopHookInput.
Adds the agent_transcript_path field to SubagentStopHookInput.
Adds the agent_type field to SubagentStopHookInput.
Adds a hook event for handling tool use failures.
Adds the input type for the PostToolUseFailure hook event.
Adds the hook-specific output type for the PostToolUseFailure event.
Added a public ClaudeSDKClient method for querying MCP server connection status without accessing private internals.
Adds a UUID to the UserMessage response type to improve developer experience for rewind.
Adds an option to enable file checkpointing.
Adds support for rewinding files.
Adds the betas option to support SDK betas.
Adds a tools option to ClaudeAgentOptions.
Adds the SdkBeta type for SDK beta support.
A sandbox adapter interface was created for the Python SDK.
When present, this environment variable overrides the initialize() timeout.
Adds the AssistantMessageError type.
Adds a timeout parameter to HookMatcher.
The pip package now bundles the Claude Code CLI, so installing the package includes the CLI.
The SDK now supports the Claude CLI located at ~/.claude/local/claude.
Structured output support was added.
Adds the max_thinking_tokens option to ClaudeAgentOptions.
Adds the /generate-changelog slash command.
Adds the max_budget_usd option to the Python SDK.
The Python SDK adds plugin support, allowing developers to use plugins with the SDK.
Adds base64 image handling to sdk_mcp_server tool calling.
Adds an environment variable for skipping the SDK version check.
Adds cli_path support to ClaudeAgentOptions, allowing developers to configure the CLI path.
Behavior and default changes 5
Propagates TRACEPARENT and TRACESTATE to the CLI subprocess when an OpenTelemetry span is active, connecting SDK and CLI traces end-to-end.
Preserves dropped fields on AssistantMessage for forward compatibility.
Preserves dropped fields on ResultMessage for forward compatibility.
Fallback model handling was added for parity with the TypeScript SDK.
Uses an empty system prompt by default.
Tooling 5
Adds a 13-contract conformance test harness for third-party SessionStore adapter authors.
Added a macOS x86_64 wheel to the published matrix.
The bundled Claude CLI was updated; SDK users receive the newer bundled version.
The SDK now bundles Claude CLI version 2.1.9.
The claude code CLI is bundled for linux arm64.
Fixes and other changes 46
Exceptions raised after an error result now carry the result's actual error text instead of the generic exit-code message.
Suggestions are deserialized as PermissionUpdate instances instead of raw dicts, so they can be inspected and echoed back in PermissionResultAllow without AttributeError.
Fixed an unclosed MemoryObjectReceiveStream ResourceWarning on disconnect by closing the receive stream at the consumer boundary.
An atexit handler terminates live CLI subprocesses when the parent process exits, preventing orphaned claude processes from leaking.
Fixed list_sessions returning created_at=None when the first JSONL record lacks a timestamp, by scanning the full head buffer.
Fixed a Trio nursery stack corruption error when breaking out of query() iteration inside a nursery with options.stderr set.
Fixed a no-running-event-loop error when using ClaudeSDKClient or query() under trio.
Deleting a session now also removes its sibling subagent transcript directory.
An empty list now passes --setting-sources= to disable all filesystem settings instead of loading default settings.
Adaptive and disabled thinking configurations now map to the corresponding --thinking CLI arguments instead of --max-thinking-tokens values.
Forwards maxResultSizeChars from ToolAnnotations via _meta, preventing silent truncation of large MCP tool results in the CLI.
Using query() with a string prompt no longer deadlocks when hooks or MCP servers trigger many tool calls.
When omitted, --setting-sources is no longer passed as an empty string, preventing the CLI from misparsing subsequent flags.
Fixed connect(prompt="...") silently dropping the string prompt, which caused receive_messages() to hang indefinitely.
In-flight hook callbacks are properly cancelled when the CLI abandons them.
Fixes a cross-task cancel scope RuntimeError during async generator cleanup.
Filters the CLAUDECODE environment variable from the subprocess environment.
Defers CLI discovery to connect() to avoid blocking async event loops.
Skips non-JSON lines on CLI stdout to prevent buffer corruption.
Adds a SIGKILL fallback when the SIGTERM handler blocks during close().
Adds the missing dontAsk permission mode to the types.
Passes initialize_timeout from the environment variable in query().
Converts TypedDict input_schema values to proper JSON Schema in SDK MCP tools.
Retries install.sh fetches on HTTP 429 with pipefail and jitter.
Propagates the is_error flag from SDK MCP tool results.
Uses typing_extensions.TypedDict on Python 3.10 to support NotRequired.
Handles resource_link and embedded resource content types in SDK MCP tools.
Adds the missing errors field to ResultMessage.
Removes the stdin timeout for hooks and SDK MCP servers.
Removes a duplicate version warning and includes the CLI path.
Per-turn usage is now preserved on AssistantMessage.
Now uses default-if-absent semantics to match the TS SDK.
The env-var workaround was reverted; partial-message delivery is now handled upstream.
Fixed include_partial_messages=True not delivering input_json_delta events by enabling fine-grained tool streaming in the subprocess.
Fixed string prompts closing stdin before MCP server initialization completed, which caused MCP servers to fail to register.
Unrecognized CLI message types are now silently skipped instead of raising MessageParseError and crashing the session, enabling forward compatibility with future CLI message types.
Large agent definitions are sent through the initialize control request via stdin, avoiding platform-specific CLI argument size limits that could silently prevent registration.
Fixed the error field not being populated; it is now read from the top level of the response.
The error field is parsed, enabling rate limit detection.
CLI errors are propagated to pending control requests.
A write lock prevents concurrent transport writes.
Adds a runtime placeholder for Pydantic 2.12+ compatibility.
When SDK MCP is present, the SDK waits for the first result before closing stdin.
Fixes the type of HookMatcher.timeout to float.
Windows CLI downloads now use the PowerShell installer.
Handles the Windows command line length limit for the --agents option.