The query API, Input Modes and Options
`query()` starts Claude Code's agent loop in a subprocess and streams messages back to you; the options object decides which model runs it, how far it may go, what it sees and what it may touch. Know the two input modes, the Python `query()` vs `ClaudeSDKClient` split, and the handful of option defaults that trip people up: the minimal system prompt, setting sources, `env` semantics, and the turn and budget caps.
Key points
- 1
Packages:
claude-agent-sdk(Python 3.10+,from claude_agent_sdk import query, ClaudeAgentOptions) and@anthropic-ai/claude-agent-sdk(Node 18+). Both bundle a native Claude Code binary. Without it (npm ci --omit=optional, or a Python sdist with no platform wheel), install Claude Code natively and setpathToClaudeCodeExecutable/cli_path. - 2
The Agent SDK embeds Claude Code's loop, built-in tools, permissions, hooks and sessions in a process you operate. The client SDK calls the Messages API, and you write the loop (or use the beta tool runner). Managed Agents is an Anthropic-hosted harness and sandbox. The CLI is for terminal work.
- 3
Input modes: a string prompt is single message input. An
AsyncIterableof user messages is streaming input (the recommended mode), which adds image attachments, queued messages, interrupts and natural multi-turn context. In TypeScript,interrupt(),setModel(),setPermissionMode()andapplyFlagSettings()work only in streaming input mode. - 4
In Python,
query()returns a plain iterator: it supports streaming input, hooks and custom tools, but not interrupts.ClaudeSDKClientreuses one session and addsinterrupt(),set_model()andset_permission_mode(). Afterinterrupt(), drain the old task's messages withreceive_response()before reading a new answer. - 5
System prompt: leaving it unset gives a minimal tool-calling prompt (unlike
claude -p).{ type: "preset", preset: "claude_code" }is Claude Code's prompt, and addingappendis the lowest-risk customization. A string replaces everything. Python has a{"type": "file"}form for large prompts; TypeScript accepts astring[]split bySYSTEM_PROMPT_DYNAMIC_BOUNDARYfor caching. - 6
The system prompt is recorded on a session's first request and reused on resume until compaction, so a new
appendon resume is ignored. Change instructions mid-session through the conversation or hookadditionalContext; keepsnapshot: falsefor iterating on wording.excludeDynamicSections: trueon the preset makes the prompt identical across users so they share a cache entry. - 7
settingSourcesomitted means["user", "project", "local"], the same as the CLI. An explicit list loads only the sources it names ("project"is needed for repo CLAUDE.md, rules, settings, hooks and skills), and[]loads none. Managed policy,~/.claude.jsonand auto memory are read regardless. - 8
Tool options:
toolssets the base set of built-in tools ([]removes them all).allowedToolsonly auto-approves and never restricts. A bare name indisallowedToolsremoves the tool from context, while a scoped rule such asBash(rm *)denies matching calls in every mode, includingbypassPermissions. - 9
Caps:
maxTurnscounts tool-use round trips (0means no limit).maxBudgetUsdis checked after each response, can overshoot by about one response plus running subagents, counts subagent spend, and0is rejected. Hitting a cap giveserror_max_turns/error_max_budget_usd; a single-shotquery()then raises, while a streaming session stays alive. - 10
env: in TypeScript it replaces the subprocess environment (spreadprocess.env); in Python it merges over the inherited one.cwdis fixed for the session (there is no setter) and decides where project settings, hooks and skills load from.additionalDirectoriesgrants file access, not configuration. - 11
Model controls:
modelaccepts an alias or a full name, andfallbackModeltakes a backup or a comma-separated chain.effortislow | medium | high | xhigh | maxand is independent ofthinking(adaptive,enabledwithbudgetTokens, ordisabled). There are notemperature,top_pormax_tokensoptions.setModel()with no argument goes to Claude Code's default model. - 12
Cancelling: in TypeScript, use
abortControllerorQuery.close(), which works in any mode and ends the subprocess;interrupt()stops the current turn of a streaming session you want to keep alive. UseverbatimPrompts: truewhen prompt text comes from third parties, so@pathmentions and slash commands are not expanded.
Common traps
Saying
allowedTools: ["Read"]makes an agent read-only. Unlisted tools remain available, and withbypassPermissionsevery one of them is approved.Migrating from
claude-code-sdkby renaming imports only. The default system prompt changed to minimal, so add theclaude_codepreset to keep the old behaviour.Passing
settingSources: ["user"]and wondering why the repo's CLAUDE.md is ignored, or assuming[]also disables managed policy and auto memory.Porting Python
env={...}to TypeScript verbatim. TypeScript replaces the environment, soPATHandANTHROPIC_API_KEYdisappear.Calling
interrupt()orsetModel()on a TypeScript query started with a string prompt, or looking forinterrupt()on the Pythonquery()iterator.Treating
maxBudgetUsdas a hard ceiling. It can overshoot, so leave headroom. Also beware a config loader that maps empty fields to0: that removes the turn cap and makes the budget cap fail at startup.Expecting a changed
appendor custom prompt to take effect when you resume a session. The recorded prompt is reused until compaction.
Read the source
Further reading
Suggest a resourceNo extra reading for The query API, Input Modes and Options yet. Found a guide, video or cheat sheet that made it click? Share it and help the next learner.
Test yourself on The query API, Input Modes and Options
Ten questions, with the answer and explanation after each one.