Follow Discord
Sweep 22 Oct 2026 · 21:04Z Build v2.1.309 528 read Stable v2.1.308 Latest v2.1.309 Next v2.1.309 Feeds RSS JSON llms.txt llms-full.txt Unofficial
One change · claude-code

Agent SDK reference - TypeScript changedagent-sdk/typescript

Nearest release: v2.1.232, published 7 hours before this site recorded the change. Shown because the two are within 24 hours of each other. Nothing here says the release caused the edit.

Recorded here
Lines+4,839added
Lines−0removed
From line — no hunk to open at
First seen 14 Aug 2026 this site's first read of the page
Recorded edits115to this page, all time

# Agent SDK reference - TypeScript ## Installation ### Compile to a single executable ## Functions ### `query()` #### Parameters #### Returns ### `startup()` #### Parameters #### Returns #### Example ### `tool()` #### Parameters #### `ToolAnnotations` ### `createSdkMcpServer()` #### Parameters ### `listSessions()` #### Parameters #### Return type: `SDKSessionInfo` #### Example ### `getSessionMessages()` #### Parameters #### Return type: `SessionMessage` #### Example ### `getSessionInfo()` #### Parameters ### `renameSession()` #### Parameters ### `tagSession()` #### Parameters ### `resolveSettings()` #### Parameters #### Return type: `ResolvedSettings` #### Example ## Types ### `Options` #### Handle slow or stalled API responses ### `Query` object #### Methods #### `applyFlagSettings()` ### `WarmQuery` #### Methods ### `SDKControlInitializeResponse` ### `SDKControlInterruptResponse` ### `SDKControlGetContextUsageResponse` ### `SDKControlReadFileResponse` ### `AgentDefinition` ### `AgentMcpServerSpec` ### `SettingSource` #### Default behavior #### Why use settingSources #### Settings precedence ### `PermissionMode` ### `CanUseTool` ### `PermissionResult` ### `ToolConfig` ### `McpServerConfig` #### `McpStdioServerConfig` #### `McpSSEServerConfig` #### `McpHttpServerConfig` #### `McpSdkServerConfigWithInstance` #### `McpClaudeAIProxyServerConfig` ### `SdkPluginConfig` ## Message Types ### `SDKMessage` ### `SDKAssistantMessage` ### `SDKUserMessage` ### `SDKUserMessageReplay` ### `SDKResultMessage` ### `SDKSystemMessage` ### `SDKPartialAssistantMessage` ### `SDKCompactBoundaryMessage` ### `SDKInformationalMessage` ### `SDKWorkerShuttingDownMessage` ### `SDKPluginInstallMessage` ### `SDKPermissionDeniedMessage` ### `SDKPermissionDenial` ### `SDKMessageOrigin` ### Task-notification subkinds ### Peer origin fields ## Hook Types ### `HookEvent` ### `HookCallback` ### `HookCallbackMatcher` ### `HookInput` ### `BaseHookInput` #### `PreToolUseHookInput` #### `PostToolUseHookInput` #### `PostToolUseFailureHookInput` #### `PostToolBatchHookInput` #### `PermissionDeniedHookInput` #### `NotificationHookInput` #### `UserPromptSubmitHookInput` #### `UserPromptExpansionHookInput` #### `SessionStartHookInput` #### `SessionEndHookInput` #### `StopHookInput` #### `StopFailureHookInput` #### `SubagentStartHookInput` #### `SubagentStopHookInput` #### `PreCompactHookInput` #### `PostCompactHookInput` #### `PermissionRequestHookInput` #### `SetupHookInput` #### `TeammateIdleHookInput` #### `TaskCreatedHookInput` #### `TaskCompletedHookInput` #### `ElicitationHookInput` #### `ElicitationResultHookInput` #### `ConfigChangeHookInput` #### `InstructionsLoadedHookInput` #### `DirectoryAddedHookInput` #### `WorktreeCreateHookInput` #### `WorktreeRemoveHookInput` #### `CwdChangedHookInput` #### `FileChangedHookInput` #### `MessageDisplayHookInput` ### `HookJSONOutput` #### `AsyncHookJSONOutput` #### `SyncHookJSONOutput` ## Tool Input Types ### `ToolInputSchemas` ### Agent ### AskUserQuestion ### Bash ### Monitor ### TaskOutput ### Edit ### Read ### Write ### Glob ### Grep ### TaskStop ### NotebookEdit ### WebFetch ### WebSearch ### Workflow ### TodoWrite ### TaskCreate ### TaskUpdate ### TaskGet ### TaskList ### ExitPlanMode ### ListMcpResources ### ReadMcpResource ### EnterWorktree ### ExitWorktree ### EnterPlanMode ### CronCreate ### CronDelete ### CronList ### ScheduleWakeup ### RemoteTrigger ### PushNotification ### REPL ### ReportFindings ### Artifact ### Projects ### ReadMcpResourceDir ### RefreshMcpTools ### ShowOnboardingRolePicker ### McpInput ## Tool Output Types ### `ToolOutputSchemas` ### Agent ### AskUserQuestion ### Bash ### Monitor ### Edit ### Read ### Write ### Glob ### Grep ### TaskStop ### NotebookEdit ### WebFetch ### WebSearch ### Workflow ### TodoWrite ### TaskCreate ### TaskUpdate ### TaskGet ### TaskList ### ExitPlanMode ### ListMcpResources ### ReadMcpResource ### EnterWorktree ### ExitWorktree ### EnterPlanMode ### CronCreate ### CronDelete ### CronList ### ScheduleWakeup ### RemoteTrigger ### PushNotification ### REPL ### ReportFindings ### Artifact ### Projects ### ReadMcpResourceDir ### RefreshMcpTools ### ShowOnboardingRolePicker ### McpOutput ## Permission Types ### `PermissionUpdate` ### `PermissionBehavior` ### `PermissionUpdateDestination` ### `PermissionRuleValue` ## Other Types ### `ApiKeySource` ### `SdkBeta` ### `SlashCommand` ### `ModelInfo` ### `AgentInfo` ### `McpServerStatus` ### `McpServerStatusConfig` ### `AccountInfo` ### `ModelUsage` ### `ConfigScope` ### `NonNullableUsage` ### `Usage` ### `CallToolResult` ### `ThinkingConfig` ### `SpawnedProcess` ### `SpawnOptions` ### `McpSetServersResult` ### `RewindFilesResult` ### `SDKStatusMessage` ### `SDKTaskNotificationMessage` ### `SDKToolUseSummaryMessage` ### `SDKHookStartedMessage` ### `SDKHookProgressMessage` ### `SDKHookResponseMessage` ### `SDKToolProgressMessage` ### `SDKAuthStatusMessage` ### `SDKTaskStartedMessage` ### `SDKTaskProgressMessage` ### `SDKTaskUpdatedMessage` ### `SDKBackgroundTasksChangedMessage` ### `SDKThinkingTokensMessage` ### `SDKFilesPersistedEvent` ### `SDKRateLimitEvent` ### `SDKLocalCommandOutputMessage` ### `SDKCommandsChangedMessage` ### `SDKPromptSuggestionMessage` ### `SDKConversationResetMessage` ### `AbortError` ## Sandbox Configuration ### `SandboxSettings` #### Example usage ### `SandboxNetworkConfig` ### `SandboxFilesystemConfig` ### Permissions Fallback for Unsandboxed Commands ## See also

The whole hunk

4839 lines, first recorded
/
lines

This page is larger than the 256 KiB this site keeps, so one side of the diff below stops where the stored text does.

The first capture of this source. The page was already there, and this is what it said.

# Agent SDK reference - TypeScript

> Complete API reference for the TypeScript Agent SDK, including all functions, types, and interfaces.

<script src="/docs/components/typescript-sdk-type-links.js" defer />

## Installation

```bash theme={null}
npm install @anthropic-ai/claude-agent-sdk
```

<Note>
  The SDK bundles a native Claude Code binary for your platform as an optional dependency such as `@anthropic-ai/claude-agent-sdk-darwin-arm64`. Most installs need no separate Claude Code install. The SDK version tracks the bundled Claude Code version: SDK v0.3.191 bundles Claude Code v2.1.191, so a feature on this page that requires a Claude Code version needs the SDK release with the same patch number or later. If your package manager skips optional dependencies, the SDK throws `Native CLI binary for <platform> not found`; set [`pathToClaudeCodeExecutable`](#options) to a separately installed `claude` binary instead.

  If your package manager doesn't apply npm's `libc` field, as Yarn 1.x doesn't, you get both the glibc and musl platform packages on Linux, roughly doubling the install size. The SDK still launches the correct variant. To reclaim the space in a container image, delete the platform package that doesn't match the libc where your app runs; for a glibc runtime on x64, that's `rm -rf node_modules/@anthropic-ai/claude-agent-sdk-linux-x64-musl`. On a development machine the deletion is temporary, since Yarn reinstalls the package on the next dependency change.
</Note>

### Compile to a single executable

When you compile your application into a single-file executable with `bun build --compile`, the SDK cannot resolve the bundled CLI binary at runtime. `require.resolve` does not work inside the compiled executable's `$bunfs` virtual filesystem, so the SDK throws `Native CLI binary for <platform> not found`.

To work around this, embed the platform binary as a file asset, extract it to a real path at startup with `extractFromBunfs()`, and pass that path to [`pathToClaudeCodeExecutable`](#options).

The `extractFromBunfs()` helper requires `@anthropic-ai/claude-agent-sdk` v0.3.144 or later. The example below builds for macOS on Apple Silicon:

```typescript theme={null}
import binPath from "@anthropic-ai/claude-agent-sdk-darwin-arm64/claude" with { type: "file" };
import { extractFromBunfs } from "@anthropic-ai/claude-agent-sdk/extract";
import { query } from "@anthropic-ai/claude-agent-sdk";

const cliPath = extractFromBunfs(binPath);

for await (const message of query({
  prompt: "Hello",
  options: { pathToClaudeCodeExecutable: cliPath },
})) {
  console.log(message);
}
```

`extractFromBunfs()` copies the embedded binary out of the compiled executable's virtual filesystem to a per-user temp directory and returns the real path. Outside a compiled executable it returns the input path unchanged, so the same code runs in development without modification.

Each compiled executable embeds a single platform's binary. Match the platform package in the import to your `--target`:

* To cross-compile, install the non-matching platform package, for example `npm install @anthropic-ai/claude-agent-sdk-linux-x64 --force`.
* On Windows, the binary subpath is `claude.exe`, for example `@anthropic-ai/claude-agent-sdk-win32-x64/claude.exe`.

## Functions

### `query()`

The primary function for interacting with Claude Code. Creates an async generator that streams messages as they arrive.

```typescript theme={null}
function query({
  prompt,
  options
}: {
  prompt: string | AsyncIterable<SDKUserMessage>;
  options?: Options;
}): Query;
```

#### Parameters

| Parameter | Type                                                             | Description                                                       |
| :-------- | :--------------------------------------------------------------- | :---------------------------------------------------------------- |
| `prompt`  | `string \| AsyncIterable<`[`SDKUserMessage`](#sdkusermessage)`>` | The input prompt as a string or async iterable for streaming mode |
| `options` | [`Options`](#options)                                            | Optional configuration object (see Options type below)            |

#### Returns

Returns a [`Query`](#query-object) object that extends `AsyncGenerator<`[`SDKMessage`](#sdkmessage)`, void>` with additional methods.

### `startup()`

Pre-warms the CLI subprocess by spawning it and completing the initialize handshake before a prompt is available. The returned [`WarmQuery`](#warmquery) handle accepts a prompt later and writes it to an already-ready process, so the first `query()` call resolves without paying subprocess spawn and initialization cost inline.

```typescript theme={null}
function startup(params?: {
  options?: Options;
  initializeTimeoutMs?: number;
}): Promise<WarmQuery>;
```

#### Parameters

| Parameter             | Type                  | Description                                                                                                                                                                    |
| :-------------------- | :-------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `options`             | [`Options`](#options) | Optional configuration object. Same as the `options` parameter to `query()`                                                                                                    |
| `initializeTimeoutMs` | `number`              | Maximum time in milliseconds to wait for subprocess initialization. Defaults to `60000`. If initialization does not complete in time, the promise rejects with a timeout error |

#### Returns

Returns a `Promise<`[`WarmQuery`](#warmquery)`>` that resolves once the subprocess has spawned and completed its initialize handshake.

#### Example

Call `startup()` early, for example on application boot, then call `.query()` on the returned handle once a prompt is ready. This moves subprocess spawn and initialization out of the critical path.

```typescript theme={null}
import { startup } from "@anthropic-ai/claude-agent-sdk";

// Pay startup cost upfront
const warm = await startup({ options: { maxTurns: 3 } });

// Later, when a prompt is ready, this is immediate
for await (const message of warm.query("What files are here?")) {
  console.log(message);
}
```

### `tool()`

Creates a type-safe MCP tool definition for use with SDK MCP servers.

```typescript theme={null}
function tool<Schema extends AnyZodRawShape>(
  name: string,
  description: string,
  inputSchema: Schema,
  handler: (args: InferShape<Schema>, extra: unknown) => Promise<CallToolResult>,
  extras?: { annotations?: ToolAnnotations; searchHint?: string; alwaysLoad?: boolean }
): SdkMcpToolDefinition<Schema>;
```

#### Parameters

| Parameter     | Type                                                                                                   | Description                                                                                                                                                                                                                                                                                                   |
| :------------ | :----------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `name`        | `string`                                                                                               | The name of the tool                                                                                                                                                                                                                                                                                          |
| `description` | `string`                                                                                               | A description of what the tool does                                                                                                                                                                                                                                                                           |
| `inputSchema` | `Schema extends AnyZodRawShape`                                                                        | Zod schema defining the tool's input parameters (supports both Zod 3 and Zod 4)                                                                                                                                                                                                                               |
| `handler`     | `(args, extra) => Promise<`[`CallToolResult`](#calltoolresult)`>`                                      | Async function that executes the tool logic                                                                                                                                                                                                                                                                   |
| `extras`      | `{ annotations?: `[`ToolAnnotations`](#toolannotations)`; searchHint?: string; alwaysLoad?: boolean }` | Optional extras. `annotations` provides MCP behavioral hints to clients. `searchHint` is a one-line capability phrase shown in the deferred-tool list when [tool search](/docs/en/agent-sdk/tool-search) is active. `alwaysLoad: true` keeps this tool's full schema in the initial prompt instead of deferring it |

#### `ToolAnnotations`

Re-exported from `@modelcontextprotocol/sdk/types.js`. All fields are optional hints; clients should not rely on them for security decisions.

| Field             | Type      | Default     | Description                                                                                                                                          |
| :---------------- | :-------- | :---------- | :--------------------------------------------------------------------------------------------------------------------------------------------------- |
| `title`           | `string`  | `undefined` | Human-readable title for the tool                                                                                                                    |
| `readOnlyHint`    | `boolean` | `false`     | If `true`, the tool does not modify its environment                                                                                                  |
| `destructiveHint` | `boolean` | `true`      | If `true`, the tool may perform destructive updates (only meaningful when `readOnlyHint` is `false`)                                                 |
| `idempotentHint`  | `boolean` | `false`     | If `true`, repeated calls with the same arguments have no additional effect (only meaningful when `readOnlyHint` is `false`)                         |
| `openWorldHint`   | `boolean` | `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) |

```typescript theme={null}
import { tool } from "@anthropic-ai/claude-agent-sdk";
import { z } from "zod";

const searchTool = tool(
  "search",
  "Search the web",
  { query: z.string() },
  async ({ query }) => {
    return { content: [{ type: "text", text: `Results for: ${query}` }] };
  },
  { annotations: { readOnlyHint: true, openWorldHint: true } }
);
```

### `createSdkMcpServer()`

Creates an MCP server instance that runs in the same process as your application.

```typescript theme={null}
function createSdkMcpServer(options: {
  name: string;
  version?: string;
  instructions?: string;
  tools?: Array<SdkMcpToolDefinition<any>>;
  alwaysLoad?: boolean;
}): McpSdkServerConfigWithInstance;
```

#### Parameters

| Parameter              | Type                          | Description                                                                                                                                                                                          |
| :--------------------- | :---------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `options.name`         | `string`                      | The name of the MCP server                                                                                                                                                                           |
| `options.version`      | `string`                      | Optional version string                                                                                                                                                                              |
| `options.instructions` | `string`                      | Optional server instructions, returned from `initialize` and surfaced to the model as an MCP instructions block                                                                                      |
| `options.tools`        | `Array<SdkMcpToolDefinition>` | Array of tool definitions created with [`tool()`](#tool)                                                                                                                                             |
| `options.alwaysLoad`   | `boolean`                     | When `true`, every tool from this server stays in the initial prompt and is never deferred behind [tool search](/docs/en/agent-sdk/tool-search). Combines with per-tool `alwaysLoad` in [`tool()`](#tool) |

### `listSessions()`

Discovers and lists past sessions with light metadata. Filter by project directory or list sessions across all projects.

```typescript theme={null}
function listSessions(options?: ListSessionsOptions): Promise<SDKSessionInfo[]>;
```

#### Parameters

| Parameter                  | Type      | Default     | Description                                                                        |
| :------------------------- | :-------- | :---------- | :--------------------------------------------------------------------------------- |
| `options.dir`              | `string`  | `undefined` | Directory to list sessions for. When omitted, returns sessions across all projects |
| `options.limit`            | `number`  | `undefined` | Maximum number of sessions to return                                               |
| `options.includeWorktrees` | `boolean` | `true`      | When `dir` is inside a git repository, include sessions from all worktree paths    |

#### Return type: `SDKSessionInfo`

| Property       | Type                  | Description                                                                 |
| :------------- | :-------------------- | :-------------------------------------------------------------------------- |
| `sessionId`    | `string`              | Unique session identifier (UUID)                                            |
| `summary`      | `string`              | Display title: custom title, auto-generated summary, or first prompt        |
| `lastModified` | `number`              | Last modified time in milliseconds since epoch                              |
| `fileSize`     | `number \| undefined` | Session file size in bytes. Only populated for local JSONL storage          |
| `customTitle`  | `string \| undefined` | User-set session title (via `/rename`)                                      |
| `firstPrompt`  | `string \| undefined` | First meaningful user prompt in the session                                 |
| `gitBranch`    | `string \| undefined` | Git branch at the end of the session                                        |
| `cwd`          | `string \| undefined` | Working directory for the session                                           |
| `tag`          | `string \| undefined` | User-set session tag (see [`tagSession()`](#tagsession))                    |
| `createdAt`    | `number \| undefined` | Creation time in milliseconds since epoch, from the first entry's timestamp |

#### Example

Print the 10 most recent sessions for a project. Results are sorted by `lastModified` descending, so the first item is the newest. Omit `dir` to search across all projects.

```typescript theme={null}
import { listSessions } from "@anthropic-ai/claude-agent-sdk";

const sessions = await listSessions({ dir: "/path/to/project", limit: 10 });

for (const session of sessions) {
  console.log(`${session.summary} (${session.sessionId})`);
}
```

### `getSessionMessages()`

Reads user and assistant messages from a past session transcript.

```typescript theme={null}
function getSessionMessages(
  sessionId: string,
  options?: GetSessionMessagesOptions
): Promise<SessionMessage[]>;
```

#### Parameters

| Parameter        | Type     | Default     | Description                                                                   |
| :--------------- | :------- | :---------- | :---------------------------------------------------------------------------- |
| `sessionId`      | `string` | required    | Session UUID to read (see `listSessions()`)                                   |
| `options.dir`    | `string` | `undefined` | Project directory to find the session in. When omitted, searches all projects |
| `options.limit`  | `number` | `undefined` | Maximum number of messages to return                                          |
| `options.offset` | `number` | `undefined` | Number of messages to skip from the start                                     |

#### Return type: `SessionMessage`

| Property             | Type                    | Description                                                                                                                                                                                                                                                                   |
| :------------------- | :---------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `type`               | `"user" \| "assistant"` | Message role                                                                                                                                                                                                                                                                  |
| `uuid`               | `string`                | Unique message identifier                                                                                                                                                                                                                                                     |
| `session_id`         | `string`                | Session this message belongs to                                                                                                                                                                                                                                               |
| `message`            | `unknown`               | Raw message payload from the transcript                                                                                                                                                                                                                                       |
| `parent_tool_use_id` | `string \| null`        | For subagent messages, the `tool_use_id` of the spawning `Agent` tool call. `null` for main-session messages and older sessions                                                                                                                                               |
| `parent_agent_id`    | `string \| null`        | For messages from a [nested subagent](/docs/en/sub-agents#let-subagents-spawn-their-own-subagents), the `agentId` of the subagent that spawned it. `null` for main-session messages, messages from top-level subagents, and older sessions. Requires Claude Code v2.1.202 or later |

#### Example

```typescript theme={null}
import { listSessions, getSessionMessages } from "@anthropic-ai/claude-agent-sdk";

const [latest] = await listSessions({ dir: "/path/to/project", limit: 1 });

if (latest) {
  const messages = await getSessionMessages(latest.sessionId, {
    dir: "/path/to/project",
    limit: 20
  });

  for (const msg of messages) {
    console.log(`[${msg.type}] ${msg.uuid}`);
  }
}
```

### `getSessionInfo()`

Reads metadata for a single session by ID without scanning the full project directory.

```typescript theme={null}
function getSessionInfo(
  sessionId: string,
  options?: GetSessionInfoOptions
): Promise<SDKSessionInfo | undefined>;
```

#### Parameters

| Parameter     | Type     | Default     | Description                                                            |
| :------------ | :------- | :---------- | :--------------------------------------------------------------------- |
| `sessionId`   | `string` | required    | UUID of the session to look up                                         |
| `options.dir` | `string` | `undefined` | Project directory path. When omitted, searches all project directories |

Cut at 300 lines. The page has the rest.

Feedback