TypeScript SDK Reference
A comprehensive reference for building applications with the Anthropic Agent SDK (TypeScript), enabling programmatic interactions with Claude Code and custom tool integrations.
Installation
npm install @anthropic-ai/claude-agent-sdk
Quick Start
Core Functions
| Function |
Purpose |
Key Use Case |
query() |
Primary interface for Claude Code interactions |
Send prompts, stream responses, manage multi-turn conversations |
tool() |
Define MCP tools with type-safe schemas |
Create custom tools for agents using Zod validation |
createSdkMcpServer() |
Create in-process MCP servers |
Host tools natively in your application |
Example: Basic Query
import { query } from '@anthropic-ai/claude-agent-sdk';
const result = query({
prompt: "Analyze this code and suggest improvements",
options: {
allowedTools: ['Read', 'Grep'],
model: 'claude-opus'
}
});
for await (const message of result) {
if (message.type === 'assistant') {
console.log(message.message.content);
}
}
Main Functions Reference
query()
Streams Claude Code responses with full message type support. Returns an async generator of SDKMessage objects.
Parameters:
prompt: string or async iterable of messages (streaming mode)
options: Configuration object (see Options below)
Returns: Query object (extends AsyncGenerator<SDKMessage, void>)
Key Methods:
.interrupt() – Interrupt streaming (streaming mode only)
.setPermissionMode(mode) – Change permissions dynamically (streaming mode only)
tool()
Creates type-safe MCP tool definitions using Zod schemas. Handlers receive validated inputs and must return CallToolResult.
Parameters:
name: Tool identifier
description: Natural language description
inputSchema: Zod schema defining inputs
handler: Async function (args: z.infer<Schema>, extra?: unknown) => Promise<CallToolResult>
Returns: SdkMcpToolDefinition<Schema>
createSdkMcpServer()
Creates an in-process MCP server for hosting custom tools. Runs in the same Node.js process—no subprocess overhead.
Parameters:
name: Server identifier
version: Optional semantic version
tools: Array of tool definitions from tool()
Returns: McpSdkServerConfigWithInstance (ready for mcpServers option)
Key Configuration Options
Essential Options
| Option |
Type |
Default |
Purpose |
allowedTools |
string[] |
All available |
Restrict which tools Claude can use |
disallowedTools |
string[] |
[] |
Explicitly block tools |
model |
string |
CLI default |
Override Claude model (e.g., 'claude-opus') |
cwd |
string |
process.cwd() |
Working directory for operations |
abortController |
AbortController |
New instance |
Control task cancellation |
Advanced Options
| Option |
Type |
Default |
Purpose |
systemPrompt |
string or preset object |
None |
Custom system instructions or Claude Code preset |
agents |
Record<string, AgentDefinition> |
undefined |
Programmatically define subagents with custom prompts |
mcpServers |
Record<string, McpServerConfig> |
{} |
Connect stdio, SSE, HTTP, or SDK MCP servers |
settingSources |
('user' | 'project' | 'local')[] |
[] |
Load filesystem settings (CLAUDE.md, settings.json) |
permissionMode |
PermissionMode |
'default' |
'default', 'acceptEdits', 'bypassPermissions', or 'plan' |
maxThinkingTokens |
number |
undefined |
Token limit for extended thinking |
maxTurns |
number |
undefined |
Maximum conversation turns before stopping |
resume |
string |
undefined |
Resume a previous session by ID |
forkSession |
boolean |
false |
Fork to new session on resume instead of continuing |
Message Types Overview
The query() generator yields SDKMessage objects. Common types:
| Message Type |
When Emitted |
Key Fields |
'system' |
Session initialization |
tools, model, permissionMode, slash_commands |
'user' |
User input sent |
message (APIUserMessage), uuid |
'assistant' |
Claude responds |
message (APIAssistantMessage with content/tool_use) |
'result' |
Query completes |
subtype ('success' or error), usage, total_cost_usd |
'stream_event' |
Partial streaming data |
event (only if includePartialMessages: true) |
See Message Types Reference for complete definitions.
Types Reference Overview
Core Configuration Types
Options – Query configuration with 20+ properties (Tools, MCP, permissions, execution)
PermissionMode – Control execution permissions: 'default', 'acceptEdits', 'bypassPermissions', 'plan'
SettingSource – Filesystem config scope: 'user', 'project', 'local'
Agent & Tool Types
AgentDefinition – Subagent config: description, prompt, tools, model override
SdkMcpToolDefinition – Output of tool() function with Zod schema binding
McpServerConfig – Union of stdio, SSE, HTTP, or SDK server configs
MCP Server Configuration
| Config Type |
Transport |
Use Case |
McpStdioServerConfig |
stdio (subprocess) |
External tools, sandboxing |
McpSSEServerConfig |
Server-Sent Events |
Remote tools, pub/sub patterns |
McpHttpServerConfig |
HTTP |
REST-based tools, cloud integrations |
McpSdkServerConfigWithInstance |
In-process |
Custom tools, no subprocess overhead |
Hook Types
HookEvent – Event names: PreToolUse, PostToolUse, Notification, UserPromptSubmit, SessionStart, SessionEnd, etc.
HookCallback – Async function receiving hook input and returning decisions
HookInput – Union of all hook input types; each extends BaseHookInput
See Types Reference for detailed type definitions.
Tool Input/Output Reference
Built-in Tool Inputs
All tool names map to input schemas:
| Tool |
Purpose |
Key Input |
Task |
Delegate to subagent |
description, prompt, subagent_type |
Bash |
Run shell commands |
command, optional timeout, run_in_background |
Read |
Read files/images/PDFs |
file_path, optional offset/limit |
Write / Edit |
Modify files |
file_path, content or old/new strings |
Glob |
Pattern matching |
pattern, optional path |
Grep |
Regex search |
pattern, optional filters (glob, type, -B/-A/-C) |
WebFetch |
Fetch & analyze URLs |
url, prompt for AI analysis |
WebSearch |
Web search |
query, optional domain filters |
NotebookEdit |
Jupyter notebooks |
notebook_path, new_source, edit_mode |
TodoWrite |
Task tracking |
todos array with status, content, activeForm |
See Tool Reference for complete input/output schemas and examples.
Common Patterns
Streaming with Progress
const result = query({
prompt: "Your task here",
options: {
includePartialMessages: true,
permissionMode: 'bypassPermissions'
}
});
for await (const msg of result) {
if (msg.type === 'stream_event') {
// Handle streaming events
console.log('Streaming:', msg.event);
} else if (msg.type === 'result') {
console.log('Cost:', msg.total_cost_usd, 'Usage:', msg.usage);
}
}
Custom MCP Tools
import { tool, createSdkMcpServer, query } from '@anthropic-ai/claude-agent-sdk';
import { z } from 'zod';
const myTool = tool(
'my-calculator',
'Add two numbers',
{ a: z.number(), b: z.number() },
async ({ a, b }) => ({
content: [{ type: 'text', text: `Result: ${a + b}` }]
})
);
const server = createSdkMcpServer({
name: 'my-tools',
tools: [myTool]
});
const result = query({
prompt: "Use my-calculator to add 5 + 3",
options: {
mcpServers: { 'my-tools': server }
}
});
Loading Project Settings
const result = query({
prompt: "Add a feature following project conventions",
options: {
systemPrompt: {
type: 'preset',
preset: 'claude_code' // Enables Claude Code system prompt
},
settingSources: ['project'], // Load .claude/settings.json & CLAUDE.md
allowedTools: ['Read', 'Write', 'Edit', 'Bash']
}
});
Related Resources
1---2name: typescript-sdk-reference3description: Comprehensive reference for the TypeScript Agent SDK with functions, types, and interfaces for programmatic Claude Code interactions4---5
6# TypeScript SDK Reference
7
8A comprehensive reference for building applications with the **Anthropic Agent SDK** (TypeScript), enabling programmatic interactions with Claude Code and custom tool integrations.
9
10## Installation
11
12```bash
13npm install @anthropic-ai/claude-agent-sdk
14```
15
16## Quick Start
17
18### Core Functions
19
20| Function | Purpose | Key Use Case |
21|----------|---------|--------------|
22| **`query()`** | Primary interface for Claude Code interactions | Send prompts, stream responses, manage multi-turn conversations |
23| **`tool()`** | Define MCP tools with type-safe schemas | Create custom tools for agents using Zod validation |
24| **`createSdkMcpServer()`** | Create in-process MCP servers | Host tools natively in your application |
25
26### Example: Basic Query
27
28```typescript
29import { query } from '@anthropic-ai/claude-agent-sdk';
30
31const result = query({
32 prompt: "Analyze this code and suggest improvements",
33 options: {
34 allowedTools: ['Read', 'Grep'],
35 model: 'claude-opus'
36 }
37});
38
39for await (const message of result) {
40 if (message.type === 'assistant') {
41 console.log(message.message.content);
42 }
43}
44```
45
46## Main Functions Reference
47
48### `query()`
49
50Streams Claude Code responses with full message type support. Returns an async generator of `SDKMessage` objects.
51
52**Parameters:**
53- `prompt`: string or async iterable of messages (streaming mode)
54- `options`: Configuration object (see [Options](#key-configuration-options) below)
55
56**Returns:** `Query` object (extends `AsyncGenerator<SDKMessage, void>`)
57
58**Key Methods:**
59- `.interrupt()` – Interrupt streaming (streaming mode only)
60- `.setPermissionMode(mode)` – Change permissions dynamically (streaming mode only)
61
62### `tool()`
63
64Creates type-safe MCP tool definitions using Zod schemas. Handlers receive validated inputs and must return `CallToolResult`.
65
66**Parameters:**
67- `name`: Tool identifier
68- `description`: Natural language description
69- `inputSchema`: Zod schema defining inputs
70- `handler`: Async function `(args: z.infer<Schema>, extra?: unknown) => Promise<CallToolResult>`
71
72**Returns:** `SdkMcpToolDefinition<Schema>`
73
74### `createSdkMcpServer()`
75
76Creates an in-process MCP server for hosting custom tools. Runs in the same Node.js process—no subprocess overhead.
77
78**Parameters:**
79- `name`: Server identifier
80- `version`: Optional semantic version
81- `tools`: Array of tool definitions from `tool()`
82
83**Returns:** `McpSdkServerConfigWithInstance` (ready for `mcpServers` option)
84
85---
86
87## Key Configuration Options
88
89### Essential Options
90
91| Option | Type | Default | Purpose |
92|--------|------|---------|---------|
93| `allowedTools` | `string[]` | All available | Restrict which tools Claude can use |
94| `disallowedTools` | `string[]` | `[]` | Explicitly block tools |
95| `model` | `string` | CLI default | Override Claude model (e.g., `'claude-opus'`) |
96| `cwd` | `string` | `process.cwd()` | Working directory for operations |
97| `abortController` | `AbortController` | New instance | Control task cancellation |
98
99### Advanced Options
100
101| Option | Type | Default | Purpose |
102|--------|------|---------|---------|
103| `systemPrompt` | string or preset object | None | Custom system instructions or Claude Code preset |
104| `agents` | `Record<string, AgentDefinition>` | `undefined` | Programmatically define subagents with custom prompts |
105| `mcpServers` | `Record<string, McpServerConfig>` | `{}` | Connect stdio, SSE, HTTP, or SDK MCP servers |
106| `settingSources` | `('user' \| 'project' \| 'local')[]` | `[]` | Load filesystem settings (CLAUDE.md, settings.json) |
107| `permissionMode` | `PermissionMode` | `'default'` | `'default'`, `'acceptEdits'`, `'bypassPermissions'`, or `'plan'` |
108| `maxThinkingTokens` | `number` | `undefined` | Token limit for extended thinking |
109| `maxTurns` | `number` | `undefined` | Maximum conversation turns before stopping |
110| `resume` | `string` | `undefined` | Resume a previous session by ID |
111| `forkSession` | `boolean` | `false` | Fork to new session on resume instead of continuing |
112
113---
114
115## Message Types Overview
116
117The `query()` generator yields `SDKMessage` objects. Common types:
118
119| Message Type | When Emitted | Key Fields |
120|--------------|-------------|------------|
121| `'system'` | Session initialization | `tools`, `model`, `permissionMode`, `slash_commands` |
122| `'user'` | User input sent | `message` (APIUserMessage), `uuid` |
123| `'assistant'` | Claude responds | `message` (APIAssistantMessage with content/tool_use) |
124| `'result'` | Query completes | `subtype` ('success' or error), `usage`, `total_cost_usd` |
125| `'stream_event'` | Partial streaming data | `event` (only if `includePartialMessages: true`) |
126
127See [Message Types Reference](./MESSAGE_TYPES.md) for complete definitions.
128
129---
130
131## Types Reference Overview
132
133### Core Configuration Types
134
135- **`Options`** – Query configuration with 20+ properties (Tools, MCP, permissions, execution)
136- **`PermissionMode`** – Control execution permissions: `'default'`, `'acceptEdits'`, `'bypassPermissions'`, `'plan'`
137- **`SettingSource`** – Filesystem config scope: `'user'`, `'project'`, `'local'`
138
139### Agent & Tool Types
140
141- **`AgentDefinition`** – Subagent config: `description`, `prompt`, `tools`, `model` override
142- **`SdkMcpToolDefinition`** – Output of `tool()` function with Zod schema binding
143- **`McpServerConfig`** – Union of stdio, SSE, HTTP, or SDK server configs
144
145### MCP Server Configuration
146
147| Config Type | Transport | Use Case |
148|------------|-----------|----------|
149| `McpStdioServerConfig` | stdio (subprocess) | External tools, sandboxing |
150| `McpSSEServerConfig` | Server-Sent Events | Remote tools, pub/sub patterns |
151| `McpHttpServerConfig` | HTTP | REST-based tools, cloud integrations |
152| `McpSdkServerConfigWithInstance` | In-process | Custom tools, no subprocess overhead |
153
154### Hook Types
155
156- **`HookEvent`** – Event names: `PreToolUse`, `PostToolUse`, `Notification`, `UserPromptSubmit`, `SessionStart`, `SessionEnd`, etc.
157- **`HookCallback`** – Async function receiving hook input and returning decisions
158- **`HookInput`** – Union of all hook input types; each extends `BaseHookInput`
159
160See [Types Reference](./TYPES.md) for detailed type definitions.
161
162---
163
164## Tool Input/Output Reference
165
166### Built-in Tool Inputs
167
168All tool names map to input schemas:
169
170| Tool | Purpose | Key Input |
171|------|---------|-----------|
172| `Task` | Delegate to subagent | `description`, `prompt`, `subagent_type` |
173| `Bash` | Run shell commands | `command`, optional `timeout`, `run_in_background` |
174| `Read` | Read files/images/PDFs | `file_path`, optional offset/limit |
175| `Write` / `Edit` | Modify files | `file_path`, `content` or old/new strings |
176| `Glob` | Pattern matching | `pattern`, optional `path` |
177| `Grep` | Regex search | `pattern`, optional filters (glob, type, -B/-A/-C) |
178| `WebFetch` | Fetch & analyze URLs | `url`, `prompt` for AI analysis |
179| `WebSearch` | Web search | `query`, optional domain filters |
180| `NotebookEdit` | Jupyter notebooks | `notebook_path`, `new_source`, `edit_mode` |
181| `TodoWrite` | Task tracking | `todos` array with status, content, activeForm |
182
183See [Tool Reference](./TOOLS.md) for complete input/output schemas and examples.
184
185---
186
187## Common Patterns
188
189### Streaming with Progress
190
191```typescript
192const result = query({
193 prompt: "Your task here",
194 options: {
195 includePartialMessages: true,
196 permissionMode: 'bypassPermissions'
197 }
198});
199
200for await (const msg of result) {
201 if (msg.type === 'stream_event') {
202 // Handle streaming events
203 console.log('Streaming:', msg.event);
204 } else if (msg.type === 'result') {
205 console.log('Cost:', msg.total_cost_usd, 'Usage:', msg.usage);
206 }
207}
208```
209
210### Custom MCP Tools
211
212```typescript
213import { tool, createSdkMcpServer, query } from '@anthropic-ai/claude-agent-sdk';
214import { z } from 'zod';
215
216const myTool = tool(
217 'my-calculator',
218 'Add two numbers',
219 { a: z.number(), b: z.number() },
220 async ({ a, b }) => ({
221 content: [{ type: 'text', text: `Result: ${a + b}` }]
222 })
223);
224
225const server = createSdkMcpServer({
226 name: 'my-tools',
227 tools: [myTool]
228});
229
230const result = query({
231 prompt: "Use my-calculator to add 5 + 3",
232 options: {
233 mcpServers: { 'my-tools': server }
234 }
235});
236```
237
238### Loading Project Settings
239
240```typescript
241const result = query({
242 prompt: "Add a feature following project conventions",
243 options: {
244 systemPrompt: {
245 type: 'preset',
246 preset: 'claude_code' // Enables Claude Code system prompt
247 },
248 settingSources: ['project'], // Load .claude/settings.json & CLAUDE.md
249 allowedTools: ['Read', 'Write', 'Edit', 'Bash']
250 }
251});
252```
253
254---
255
256## Related Resources
257
258- **[Full API Reference](../../docs/external/typescript-sdk.md)** – Complete type definitions and schemas
259- **[Message Types Reference](./MESSAGE_TYPES.md)** – SDKMessage union types and examples
260- **[Types Reference](./TYPES.md)** – Detailed Options, AgentDefinition, PermissionMode docs
261- **[Tool Reference](./TOOLS.md)** – Input/output schemas for all built-in tools
262- **[SDK Overview](https://docs.anthropic.com/en/api/agent-sdk/overview)** – Getting started guide
263- **[Common Workflows](https://docs.anthropic.com/en/docs/claude-code/common-workflows)** – Step-by-step patterns
264- **[CLI Reference](https://docs.anthropic.com/en/docs/claude-code/cli-reference)** – Command-line interface docs