Agent SDK reference - Python - Claude Code Docs
Documentation Index Fetch the complete documentation index at: /docs/llms.txt Use this file to discover all available pages before exploring further. Skip to main content Assistant Responses are generated using AI and may contain mistakes. Installation Install the package into a virtual environment. On recent Debian, Ubuntu, and Homebrew Python installs, running pip install against system Python fails with error: externally-managed-environment . python3 -m venv .venv source .venv/bin/activate pip install claude-agent-sdk For uv, Windows PowerShell, and API key setup, see Setup in the Agent SDK quickstart .
Choosing between query() and ClaudeSDKClient The Python SDK provides two ways to interact with Claude Code: Feature query() ClaudeSDKClient Session Creates a new session by default Reuses same session Conversation Single exchange Multiple exchanges in same context Connection Managed automatically Manual control Streaming Input ✅ Supported ✅ Supported Interrupts ❌ Not supported ✅ Supported Hooks ✅ Supported ✅ Supported Custom Tools ✅ Supported ✅ Supported Continue Chat Manual via continue_conversation or resume ✅ Automatic Use Case One-off tasks Continuous conversations Use ClaudeSDKClient for interactive applications such as chat interfaces, or when the next action depends on Claude’s response.
Functions Signature blocks and bare async for / async with fragments on this page are illustrative. To run them, wrap the body in async def main(): ... and call asyncio.run(main()) . query() Creates a new session for each interaction with Claude Code by default. Returns an async iterator that yields messages as they arrive. Each call to query() starts fresh with no memory of previous interactions unless you pass continue_conversation=True or resume in ClaudeAgentOptions .
See Sessions . async def query ( * , prompt : str | AsyncIterable[dict[ str , Any]], options : ClaudeAgentOptions | None = None , transport : Transport | None = None ) -> AsyncIterator[Message] Parameters Parameter Type Description prompt str | AsyncIterable[dict] The input prompt as a string or async iterable for streaming mode options ClaudeAgentOptions | None Optional configuration object (defaults to ClaudeAgentOptions() if None) transport Transport | None Optional custom transport for communicating with the CLI process Returns Returns an AsyncIterator[Message] that yields messages from the conversation.
Example - With options import asyncio from claude_agent_sdk import query, ClaudeAgentOptions async def main (): options = ClaudeAgentOptions( system_prompt = "You are an expert Python developer" , permission_mode = "acceptEdits" , ) async for message in query( prompt = "Create a Python web server" , options = options): print (message) asyncio.run(main()) tool() Decorator for defining MCP tools with type safety. def tool ( name : str , description : str , input_schema : type | dict[ str , Any], annotations : ToolAnnotations | None = None ) -> Callable[[Callable[[Any], Awaitable[dict[ str , Any]]]], SdkMcpTool[Any]] Parameters Parameter Type Description name str Unique identifier for the tool description str Human-readable description of what the tool does input_schema type | dict[str, Any] Schema defining the tool’s input parameters.
See Input schema options annotations ToolAnnotations | None Optional MCP tool annotations providing behavioral hints to clients Input schema options Simple type mapping (recommended): { "text" : str , "count" : int , "enabled" : bool } JSON Schema format (for complex validation): { "type" : "object" , "properties" : { "text" : { "type" : "string" }, "count" : { "type" : "integer" , "minimum" : 0 }, }, "required" : [ "text" ], } TypedDict class : a typed schema whose NotRequired keys are left out of required .
Python 3.11 and later : import TypedDict and NotRequired from typing . Python 3.10 : typing has no NotRequired . Import TypedDict and NotRequired from typing_extensions , which the SDK installs on Python 3.10. from typing import Annotated, Any, NotRequired, TypedDict from claude_agent_sdk import tool class ForecastArgs ( TypedDict ): latitude: Annotated[ float , "Latitude coordinate" ] hours: NotRequired[Annotated[ int , "How many hours of forecast to return" ]] @tool ( "get_forecast" , "Get the hourly forecast for a location" , ForecastArgs) async def get_forecast ( args : dict[ str , Any]) -> dict[ str , Any]: hours = args.get( "hours" , 12 ) return { "content" : [{ "type" : "text" , "text" : f " { hours } -hour forecast for { args[ 'latitude' ] } " }]} In the simple mapping and TypedDict forms, wrap a type in Annotated[type, "description"] to set the field’s description.
Returns A decorator function that wraps the tool implementation and returns an SdkMcpTool instance. Example from claude_agent_sdk import tool from typing import Any @tool ( "greet" , "Greet a user" , { "name" : str }) async def greet ( args : dict[ str , Any]) -> dict[ str , Any]: return { "content" : [{ "type" : "text" , "text" : f "Hello, { args[ 'name' ] } !" }]} ToolAnnotations Behavioral hints for a tool, passed as the annotations argument of tool() .
ToolAnnotations extends the MCP SDK’s mcp.types.ToolAnnotations with a maxResultSizeChars field, and you can write each hint in camelCase or snake_case: ToolAnnotations(readOnlyHint=True) and ToolAnnotations(read_only_hint=True) are equivalent. To read a hint back from the object, use the spelling your installed mcp package declares: .readOnlyHint on mcp 1.x and .read_only_hint on 2.x, while .maxResultSizeChars works on both.
You can also pass a plain mcp.types.ToolAnnotations wherever the SDK accepts annotations. The snake_case names and the typed maxResultSizeChars field require Python Agent SDK 0.2.140 or later. Versions 0.1.31 through 0.2.139 re-export mcp.types.ToolAnnotations unchanged. On versions 0.1.55 through 0.2.139 you can still pass maxResultSizeChars as a keyword argument: the MCP class accepts extra fields, and the SDK forwards the value to Claude Code.
All fields are optional. Clients shouldn’t rely on the hints for security decisions. Field Type Default Description title str | None None Human-readable title for the tool readOnlyHint bool | None False If True , the tool does not modify its environment destructiveHint bool | None True If True , the tool may perform destructive updates (only meaningful when readOnlyHint is False ) idempotentHint bool | None False If True , repeated calls with the same arguments have no additional effect (only meaningful when readOnlyHint is False ) openWorldHint bool | None True If True , the tool interacts with external entities (for example, web search).
If False , the tool’s domain is closed (for example, a memory tool) maxResultSizeChars int | None None Number of characters up to which Claude Code keeps this tool’s text result inline in the conversation instead of saving it to a file, up to 500,000. Results that contain images aren’t affected. A Claude Code setting rather than an MCP hint: the SDK sends it in the tool’s _meta as anthropic/maxResultSizeChars .
See Raise the limit for a specific tool from claude_agent_sdk import tool, ToolAnnotations from typing import Any @tool ( "search" , "Search the web" , { "query" : str }, annotations = ToolAnnotations( readOnlyHint = True , openWorldHint = True ), ) async def search ( args : dict[ str , Any]) -> dict[ str , Any]: return { "content" : [{ "type" : "text" , "text" : f "Results for: { args[ 'query' ] } " }]} create_sdk_mcp_server() Create an in-process MCP server that runs within your Python application. def create_sdk_mcp_server ( name : str , version : str = "1.0.0" , tools : list[SdkMcpTool[Any]] | None = None ) -> McpSdkServerConfig Parameters Parameter Type Default Description name str - Unique identifier for the server version str "1.0.0" Server version string tools list[SdkMcpTool[Any]] | None None List of tool functions created with @tool decorator Returns Returns an McpSdkServerConfi
The rest of this page is on the live site.