The core agent function — run Claude on a prompt and stream typed messages back.
query() is the primary way to run the Claude Code agent loop from TypeScript. It takes a prompt and an options object, then returns an async generator that yields SDKMessage objects as the agent works through the task.
MCP servers to connect before the agent starts. Supports stdio, sse, and http transport types. In-process SDK servers created with createSdkMcpServer() use type 'sdk'.
query() returns AsyncGenerator<SDKMessage>. Iterate it with for await.The generator completes (returns) after yielding the final result message. The result is always the last message in the stream.
An assistant turn. message.content is an array of TextBlock, ToolUseBlock, or ThinkingBlock items from the Anthropic SDK. error is set if the turn failed (e.g. 'rate_limit').
Final message on a successful run. Key fields: result (text summary), total_cost_usd, usage, num_turns, duration_ms, structured_output (if outputFormat was set).
import { query } from '@anthropic-ai/claude-code'async function runAgent(prompt: string): Promise<string> { for await (const message of query({ prompt })) { if (message.type === 'result') { if (message.subtype === 'success') return message.result throw new Error(`Agent failed: ${message.errors?.join(', ')}`) } } throw new Error('No result received')}const answer = await runAgent('Summarize the README in one sentence.')console.log(answer)
The generator throws AbortError when cancelled via AbortSignal. Other fatal errors (network failures, authentication errors) propagate as standard Error instances.Non-fatal errors — such as a rate-limit retry — are emitted as system (api_retry) messages rather than thrown, so your iteration loop continues.
import { query, AbortError } from '@anthropic-ai/claude-code'try { for await (const message of query({ prompt: 'Do something.' })) { if (message.type === 'system' && message.subtype === 'api_retry') { console.warn(`API error, retrying (attempt ${message.attempt})…`) } }} catch (err) { if (err instanceof AbortError) { // user cancelled } else { // unexpected error throw err }}
When the agent attempts a tool call and permission is denied, the denial is recorded in SDKResultSuccess.permission_denials — an array of { tool_name, tool_use_id, tool_input } objects. The agent sees the denial as a tool result and may adjust its approach or stop.
permissionMode: 'bypassPermissions' skips all permission checks and is intended for controlled, sandboxed environments only. Never use it on production machines or directories with sensitive data.