TypeScript SDK Reference
Provides detailed TypeScript SDK documentation for Anthropic's Claude Agent SDK, covering functions, configuration options, and tool interfaces. Includes practical code examples for querying Claude, creating MCP tools, and managing agent interactions programmatically.
Packaged view
This page reorganizes the original catalog entry around fit, installability, and workflow context first. The original raw source lives below.
Install command
npx @skill-hub/cli install captaincrouton89-claude-typescript-sdk-reference
Repository
Skill path: .claude/skills/typescript-sdk-reference
Provides detailed TypeScript SDK documentation for Anthropic's Claude Agent SDK, covering functions, configuration options, and tool interfaces. Includes practical code examples for querying Claude, creating MCP tools, and managing agent interactions programmatically.
Open repositoryBest for
Primary workflow: Ship Full Stack.
Technical facets: Full Stack, Backend, Integration.
Target audience: TypeScript developers building applications with Claude's Agent SDK, particularly those integrating MCP tools or creating custom agent workflows.
License: Unknown.
Original source
Catalog source: SkillHub Club.
Repository owner: CaptainCrouton89.
This is still a mirrored public skill entry. Review the repository before installing into production workflows.
What it helps with
- Install TypeScript SDK Reference into Claude Code, Codex CLI, Gemini CLI, or OpenCode workflows
- Review https://github.com/CaptainCrouton89/.claude before adding TypeScript SDK Reference to shared team environments
- Use TypeScript SDK Reference for development workflows
Works across
Favorites: 0.
Sub-skills: 0.
Aggregator: No.
Original source / Raw SKILL.md
---
name: TypeScript SDK Reference
description: Comprehensive reference for the TypeScript Agent SDK with functions, types, and interfaces for programmatic Claude Code interactions
allowed-tools:
- Read
- Write
- Edit
- Task
---
# 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
```bash
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
```typescript
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](#key-configuration-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](./MESSAGE_TYPES.md) 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](./TYPES.md) 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](./TOOLS.md) for complete input/output schemas and examples.
---
## Common Patterns
### Streaming with Progress
```typescript
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
```typescript
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
```typescript
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
- **[Full API Reference](../../docs/external/typescript-sdk.md)** – Complete type definitions and schemas
- **[Message Types Reference](./MESSAGE_TYPES.md)** – SDKMessage union types and examples
- **[Types Reference](./TYPES.md)** – Detailed Options, AgentDefinition, PermissionMode docs
- **[Tool Reference](./TOOLS.md)** – Input/output schemas for all built-in tools
- **[SDK Overview](https://docs.anthropic.com/en/api/agent-sdk/overview)** – Getting started guide
- **[Common Workflows](https://docs.anthropic.com/en/docs/claude-code/common-workflows)** – Step-by-step patterns
- **[CLI Reference](https://docs.anthropic.com/en/docs/claude-code/cli-reference)** – Command-line interface docs
---
## Referenced Files
> The following files are referenced in this skill and included for context.
### MESSAGE_TYPES.md
```markdown
# Message Types Reference
Complete documentation of all `SDKMessage` types returned by the `query()` generator.
## SDKMessage Union
```typescript
type SDKMessage =
| SDKSystemMessage
| SDKUserMessage
| SDKUserMessageReplay
| SDKAssistantMessage
| SDKPartialAssistantMessage
| SDKResultMessage
| SDKCompactBoundaryMessage;
```
---
## System Messages
### `SDKSystemMessage`
Emitted once at session initialization with environment and capabilities info.
```typescript
type SDKSystemMessage = {
type: 'system';
subtype: 'init';
uuid: UUID;
session_id: string;
apiKeySource: 'user' | 'project' | 'org' | 'temporary';
cwd: string;
tools: string[]; // Available tool names
mcp_servers: {
name: string;
status: string; // 'ready', 'error', etc.
}[];
model: string;
permissionMode: PermissionMode;
slash_commands: string[];
output_style: string;
}
```
**When:** Session starts or resumes
**Use:** Verify available tools and confirm session state
### `SDKCompactBoundaryMessage`
Emitted when conversation is compacted to save tokens (manual or automatic).
```typescript
type SDKCompactBoundaryMessage = {
type: 'system';
subtype: 'compact_boundary';
uuid: UUID;
session_id: string;
compact_metadata: {
trigger: 'manual' | 'auto';
pre_tokens: number;
};
}
```
---
## User Messages
### `SDKUserMessage`
User input sent to Claude (may lack UUID in initial send).
```typescript
type SDKUserMessage = {
type: 'user';
uuid?: UUID;
session_id: string;
message: APIUserMessage; // From @anthropic-ai/sdk
parent_tool_use_id: string | null;
}
```
### `SDKUserMessageReplay`
User message replayed with guaranteed UUID (for session history).
```typescript
type SDKUserMessageReplay = {
type: 'user';
uuid: UUID; // Always present
session_id: string;
message: APIUserMessage;
parent_tool_use_id: string | null;
}
```
**Note:** Use `uuid` for reliable session tracking across messages.
---
## Assistant Messages
### `SDKAssistantMessage`
Full assistant response with generated content or tool calls.
```typescript
type SDKAssistantMessage = {
type: 'assistant';
uuid: UUID;
session_id: string;
message: APIAssistantMessage; // Contains: id, role, content[]
parent_tool_use_id: string | null;
}
```
**Content blocks in `message.content`:**
- `{ type: 'text'; text: string }` – Generated text
- `{ type: 'tool_use'; id: string; name: string; input: object }` – Tool invocation
- `{ type: 'thinking'; thinking: string }` – Extended thinking output (if enabled)
### `SDKPartialAssistantMessage`
Streaming partial updates (only when `includePartialMessages: true`).
```typescript
type SDKPartialAssistantMessage = {
type: 'stream_event';
event: RawMessageStreamEvent; // From @anthropic-ai/sdk
parent_tool_use_id: string | null;
uuid: UUID;
session_id: string;
}
```
**Stream event types:**
- `content_block_start` – New content block starting
- `content_block_delta` – Partial content update
- `content_block_stop` – Content block complete
- `message_start`, `message_delta`, `message_stop` – Message lifecycle
---
## Result Messages
### `SDKResultMessage`
Final result when query completes or errors.
**Success case:**
```typescript
type SDKResultMessage = {
type: 'result';
subtype: 'success';
uuid: UUID;
session_id: string;
duration_ms: number;
duration_api_ms: number;
is_error: false;
num_turns: number;
result: string; // Summary of work done
total_cost_usd: number;
usage: NonNullableUsage;
permission_denials: SDKPermissionDenial[];
}
```
**Error cases:**
```typescript
type SDKResultMessage = {
type: 'result';
subtype: 'error_max_turns' | 'error_during_execution';
uuid: UUID;
session_id: string;
duration_ms: number;
duration_api_ms: number;
is_error: true;
num_turns: number;
total_cost_usd: number;
usage: NonNullableUsage;
permission_denials: SDKPermissionDenial[];
}
```
**Usage tracking:**
```typescript
type NonNullableUsage = {
input_tokens: number;
output_tokens: number;
cache_creation_input_tokens: number;
cache_read_input_tokens: number;
}
```
**Permission denials:**
```typescript
type SDKPermissionDenial = {
tool_name: string;
tool_use_id: string;
tool_input: ToolInput;
}
```
---
## Processing Patterns
### Collect Results
```typescript
import { query } from '@anthropic-ai/claude-agent-sdk';
const result = query({ prompt: "Your task" });
let usage = { input: 0, output: 0 };
let cost = 0;
for await (const message of result) {
if (message.type === 'result') {
usage = message.usage;
cost = message.total_cost_usd;
console.log(`Completed in ${message.duration_ms}ms, cost: $${cost}`);
}
}
```
### Monitor Tool Calls
```typescript
for await (const message of result) {
if (message.type === 'assistant') {
for (const block of message.message.content) {
if (block.type === 'tool_use') {
console.log(`Tool: ${block.name}, Input: ${JSON.stringify(block.input)}`);
}
}
}
}
```
### Stream Partial Output
```typescript
const result = query({
prompt: "Generate output",
options: { includePartialMessages: true }
});
for await (const message of result) {
if (message.type === 'stream_event') {
if (message.event.type === 'content_block_delta') {
process.stdout.write(message.event.delta.text);
}
}
}
```
---
## Related
- [Types Reference](./TYPES.md) – Options, AgentDefinition, PermissionMode
- [Tool Reference](./TOOLS.md) – ToolInput and ToolOutput schemas
- [Main SKILL.md](./SKILL.md) – Quick overview
```
### TYPES.md
```markdown
# Types Reference
Comprehensive documentation of configuration and utility types.
---
## Options Type
Main configuration object for `query()` function.
### Execution & Model
| Property | Type | Default | Purpose |
|----------|------|---------|---------|
| `model` | `string` | CLI default | Claude model ID (e.g., `'claude-opus'`, `'claude-sonnet'`) |
| `maxThinkingTokens` | `number` | `undefined` | Max tokens for extended thinking (applicable models only) |
| `maxTurns` | `number` | `undefined` | Halt after N conversation turns |
| `fallbackModel` | `string` | `undefined` | Fallback model if primary fails |
### Tool & Permissions
| Property | Type | Default | Purpose |
|----------|------|---------|---------|
| `allowedTools` | `string[]` | All tools | Restrict which tools Claude can use |
| `disallowedTools` | `string[]` | `[]` | Explicitly deny specific tools |
| `canUseTool` | `CanUseTool` function | `undefined` | Custom permission function with fine-grained control |
| `permissionMode` | `PermissionMode` | `'default'` | Global permission behavior (see below) |
| `permissionPromptToolName` | `string` | `undefined` | MCP tool for custom permission prompts |
### File System & Execution
| Property | Type | Default | Purpose |
|----------|------|---------|---------|
| `cwd` | `string` | `process.cwd()` | Working directory for file operations |
| `additionalDirectories` | `string[]` | `[]` | Extra directories Claude can access |
| `env` | `Dict<string>` | `process.env` | Environment variables available to operations |
| `executable` | `'bun' \| 'deno' \| 'node'` | Auto-detect | JavaScript runtime for execution |
| `executableArgs` | `string[]` | `[]` | Arguments passed to the executable |
| `pathToClaudeCodeExecutable` | `string` | Auto-detect | Path to Claude Code binary |
| `extraArgs` | `Record<string, string \| null>` | `{}` | Additional arguments passed through |
### Initialization & Settings
| Property | Type | Default | Purpose |
|----------|------|---------|---------|
| `systemPrompt` | `string \| { type: 'preset'; preset: 'claude_code'; append?: string }` | `undefined` | Custom or preset system instructions |
| `settingSources` | `('user' \| 'project' \| 'local')[]` | `[]` | Load filesystem settings (CLAUDE.md, settings.json) |
| `resume` | `string` | `undefined` | Resume previous session by ID |
| `forkSession` | `boolean` | `false` | Fork new session on resume instead of continuing |
| `continue` | `boolean` | `false` | Continue most recent conversation |
### Streaming & Events
| Property | Type | Default | Purpose |
|----------|------|---------|---------|
| `includePartialMessages` | `boolean` | `false` | Emit `stream_event` messages during generation |
| `hooks` | `Partial<Record<HookEvent, HookCallbackMatcher[]>>` | `{}` | Event hooks (PreToolUse, PostToolUse, etc.) |
| `stderr` | `(data: string) => void` | `undefined` | Callback for stderr output |
### External Integrations
| Property | Type | Default | Purpose |
|----------|------|---------|---------|
| `mcpServers` | `Record<string, McpServerConfig>` | `{}` | MCP server configs (stdio, SSE, HTTP, SDK) |
| `strictMcpConfig` | `boolean` | `false` | Enforce strict MCP configuration validation |
| `agents` | `Record<string, AgentDefinition>` | `undefined` | Programmatic subagent definitions |
### Cancellation
| Property | Type | Default | Purpose |
|----------|------|---------|---------|
| `abortController` | `AbortController` | New instance | Cancellation token for the operation |
---
## PermissionMode Type
Controls Claude's access to file operations and tools.
```typescript
type PermissionMode =
| 'default' // Prompt user for file edits, tool use
| 'acceptEdits' // Auto-accept file edits without prompting
| 'bypassPermissions' // Skip all permission checks
| 'plan' // Planning mode—no execution, only output plans
```
### Decision Table
| Mode | File Edit | Tool Use | Query | Use Case |
|------|-----------|----------|-------|----------|
| `'default'` | Prompt | Prompt | Run | Interactive sessions |
| `'acceptEdits'` | Auto-accept | Prompt | Run | Semi-automated, trust edits |
| `'bypassPermissions'` | Auto-accept | Auto-accept | Run | CI/CD, full automation |
| `'plan'` | Output only | Output only | No-op | Planning, safety checks |
### Dynamic Changes
Change permissions mid-session using the `Query.setPermissionMode()` method:
```typescript
const result = query({ prompt: "Your task", options: { permissionMode: 'default' } });
for await (const msg of result) {
if (msg.type === 'assistant') {
// Switch to bypass mode after analysis
await result.setPermissionMode('bypassPermissions');
}
}
```
---
## AgentDefinition Type
Configuration for programmatically defined subagents.
```typescript
type AgentDefinition = {
description: string; // When to use this agent (required)
prompt: string; // System prompt (required)
tools?: string[]; // Allowed tools; inherits all if omitted
model?: 'sonnet' | 'opus' | 'haiku' | 'inherit'; // Model override
}
```
### Example: Custom Subagent
```typescript
const agents = {
'code-reviewer': {
description: 'Review code for quality, security, and performance',
prompt: `You are a senior code reviewer. Evaluate code against these criteria:
1. Security: Check for vulnerabilities
2. Performance: Identify bottlenecks
3. Maintainability: Assess clarity and patterns`,
tools: ['Read', 'Grep', 'Bash'],
model: 'opus' // Use powerful model for review
},
'test-writer': {
description: 'Write comprehensive unit tests',
prompt: `You are an expert test engineer specializing in coverage and edge cases.`,
tools: ['Read', 'Write', 'Edit'],
model: 'sonnet'
}
};
const result = query({
prompt: "Review this code for security issues",
options: { agents }
});
```
---
## SettingSource Type
Controls which filesystem-based configuration sources are loaded.
```typescript
type SettingSource = 'user' | 'project' | 'local';
```
### Sources & Locations
| Source | File | Scope | Precedence |
|--------|------|-------|-----------|
| `'user'` | `~/.claude/settings.json` | Global | Lowest (overridden by others) |
| `'project'` | `.claude/settings.json` | Per-repo | Medium |
| `'local'` | `.claude/settings.local.json` | Git-ignored | Highest (overrides all) |
### Precedence Order
When multiple sources are loaded, settings merge with this priority (highest to lowest):
1. Local settings (`.claude/settings.local.json`)
2. Project settings (`.claude/settings.json`)
3. User settings (`~/.claude/settings.json`)
4. Programmatic options (always override filesystem)
### Default Behavior
When `settingSources` is **omitted** or **`[]`**, the SDK **does not** load any filesystem settings. This provides isolation for SDK applications.
### Loading CLAUDE.md
To load project instructions from `CLAUDE.md`:
```typescript
const result = query({
prompt: "Add a feature following project conventions",
options: {
systemPrompt: {
type: 'preset',
preset: 'claude_code' // Enable Claude Code system prompt
},
settingSources: ['project'] // Load .claude/settings.json & CLAUDE.md
}
});
```
---
## Permission Control Types
### CanUseTool Function
Custom permission callback for granular tool access control.
```typescript
type CanUseTool = (
toolName: string,
input: ToolInput,
options: {
signal: AbortSignal;
suggestions?: PermissionUpdate[];
}
) => Promise<PermissionResult>;
```
### PermissionResult
```typescript
type PermissionResult =
| {
behavior: 'allow';
updatedInput?: ToolInput; // Optional input sanitization
updatedPermissions?: PermissionUpdate[];
}
| {
behavior: 'deny';
message: string; // Reason for denial
interrupt?: boolean; // Stop session?
};
```
### PermissionUpdate
Modify permissions dynamically during execution.
```typescript
type PermissionUpdate =
| {
type: 'addRules' | 'replaceRules' | 'removeRules';
rules: PermissionRuleValue[];
behavior: 'allow' | 'deny' | 'ask';
destination: PermissionUpdateDestination;
}
| {
type: 'setMode';
mode: PermissionMode;
destination: PermissionUpdateDestination;
}
| {
type: 'addDirectories' | 'removeDirectories';
directories: string[];
destination: PermissionUpdateDestination;
};
```
---
## MCP Server Configuration Types
### McpServerConfig Union
```typescript
type McpServerConfig =
| McpStdioServerConfig
| McpSSEServerConfig
| McpHttpServerConfig
| McpSdkServerConfigWithInstance;
```
### Stdio (Subprocess)
```typescript
type McpStdioServerConfig = {
type?: 'stdio';
command: string; // Executable path
args?: string[]; // Command arguments
env?: Record<string, string>; // Environment variables
}
```
**Use:** External tools, sandboxed execution
### SSE (Server-Sent Events)
```typescript
type McpSSEServerConfig = {
type: 'sse';
url: string; // Server endpoint
headers?: Record<string, string>; // Auth headers
}
```
**Use:** Remote tools, pub/sub patterns
### HTTP
```typescript
type McpHttpServerConfig = {
type: 'http';
url: string; // Server endpoint
headers?: Record<string, string>; // Auth headers
}
```
**Use:** REST-based tools, cloud integrations
### SDK (In-Process)
```typescript
type McpSdkServerConfigWithInstance = {
type: 'sdk';
name: string; // Server name
instance: McpServer; // Actual server instance
}
```
**Use:** Custom tools, no subprocess overhead (fastest)
---
## Hook Types
### HookEvent
Available hook events for lifecycle monitoring.
```typescript
type HookEvent =
| 'PreToolUse' // Before tool execution
| 'PostToolUse' // After tool completes
| 'Notification' // User notifications
| 'UserPromptSubmit' // User input sent
| 'SessionStart' // Session initialized
| 'SessionEnd' // Session closed
| 'Stop' // Stop button pressed
| 'SubagentStop' // Subagent stopped
| 'PreCompact'; // Before conversation compaction
```
### HookCallback
```typescript
type HookCallback = (
input: HookInput, // Event-specific data
toolUseID: string | undefined, // Associated tool
options: { signal: AbortSignal } // Cancellation token
) => Promise<HookJSONOutput>;
```
### BaseHookInput
All hooks inherit common fields:
```typescript
type BaseHookInput = {
session_id: string;
transcript_path: string;
cwd: string;
permission_mode?: string;
}
```
### Hook Output
```typescript
type HookJSONOutput = {
continue?: boolean; // Continue execution?
suppressOutput?: boolean; // Hide output?
decision?: 'approve' | 'block'; // Approve/block action
systemMessage?: string; // Add context to prompt
reason?: string; // Explanation
hookSpecificOutput?: {
// Hook-specific decisions
};
};
```
---
## Related
- [Message Types](./MESSAGE_TYPES.md) – SDKMessage definitions
- [Tool Reference](./TOOLS.md) – Tool input/output schemas
- [Main SKILL.md](./SKILL.md) – Quick overview
```
### TOOLS.md
```markdown
# Tool Reference
Complete input/output schemas for all built-in Claude Code tools.
---
## Quick Lookup
| Tool | Input | Output | Purpose |
|------|-------|--------|---------|
| `Task` | `AgentInput` | `TaskOutput` | Delegate to subagent |
| `Bash` | `BashInput` | `BashOutput` | Execute shell commands |
| `BashOutput` | `BashOutputInput` | `BashOutputToolOutput` | Retrieve background shell output |
| `Read` | `FileReadInput` | `ReadOutput` | Read files, images, PDFs, notebooks |
| `Write` | `FileWriteInput` | `WriteOutput` | Write files to filesystem |
| `Edit` | `FileEditInput` | `EditOutput` | String replace in files |
| `MultiEdit` | `FileMultiEditInput` | `MultiEditOutput` | Multiple edits in single file |
| `Glob` | `GlobInput` | `GlobOutput` | Pattern-based file matching |
| `Grep` | `GrepInput` | `GrepOutput` | Regex search across files |
| `KillBash` | `KillShellInput` | `KillBashOutput` | Terminate background shell |
| `NotebookEdit` | `NotebookEditInput` | `NotebookEditOutput` | Edit Jupyter notebook cells |
| `WebFetch` | `WebFetchInput` | `WebFetchOutput` | Fetch & analyze web content |
| `WebSearch` | `WebSearchInput` | `WebSearchOutput` | Web search |
| `TodoWrite` | `TodoWriteInput` | `TodoWriteOutput` | Manage task lists |
| `ExitPlanMode` | `ExitPlanModeInput` | `ExitPlanModeOutput` | Exit planning mode |
| `ListMcpResources` | `ListMcpResourcesInput` | `ListMcpResourcesOutput` | List MCP resources |
| `ReadMcpResource` | `ReadMcpResourceInput` | `ReadMcpResourceOutput` | Read MCP resource |
---
## Core File Operations
### Read
Read files: text, images (PNG/JPG), PDFs (with page extraction), or Jupyter notebooks.
**Input:**
```typescript
interface FileReadInput {
file_path: string; // Absolute path (required)
offset?: number; // Start line (1-indexed)
limit?: number; // Number of lines to read
}
```
**Output (text):**
```typescript
interface TextFileOutput {
content: string; // Lines with line numbers
total_lines: number; // Total file lines
lines_returned: number; // Actual lines returned
}
```
**Output (image):**
```typescript
interface ImageFileOutput {
image: string; // Base64 encoded data
mime_type: string; // e.g., 'image/png'
file_size: number; // Bytes
}
```
**Output (PDF):**
```typescript
interface PDFFileOutput {
pages: Array<{
page_number: number;
text?: string;
images?: Array<{ image: string; mime_type: string }>;
}>;
total_pages: number;
}
```
**Output (Jupyter Notebook):**
```typescript
interface NotebookFileOutput {
cells: Array<{
cell_type: 'code' | 'markdown';
source: string;
outputs?: any[];
execution_count?: number;
}>;
metadata?: Record<string, any>;
}
```
### Write
Write entire file content (overwrites if exists).
**Input:**
```typescript
interface FileWriteInput {
file_path: string; // Absolute path (required)
content: string; // Full content
}
```
**Output:**
```typescript
interface WriteOutput {
message: string; // Confirmation
bytes_written: number;
file_path: string;
}
```
### Edit
Single string replacement with exact matching.
**Input:**
```typescript
interface FileEditInput {
file_path: string; // Absolute path (required)
old_string: string; // Text to find (must be unique or use replace_all)
new_string: string; // Replacement text (must differ from old_string)
replace_all?: boolean; // Replace all occurrences?
}
```
**Output:**
```typescript
interface EditOutput {
message: string;
replacements: number; // How many replacements made
file_path: string;
}
```
### MultiEdit
Batch multiple edits in one operation (atomic—all succeed or none do).
**Input:**
```typescript
interface FileMultiEditInput {
file_path: string;
edits: Array<{
old_string: string;
new_string: string;
replace_all?: boolean;
}>;
}
```
**Output:**
```typescript
interface MultiEditOutput {
message: string;
edits_applied: number;
file_path: string;
}
```
---
## Shell Operations
### Bash
Execute shell commands with optional timeout and background support.
**Input:**
```typescript
interface BashInput {
command: string; // Shell command (required)
description?: string; // 5-10 word description of what command does
timeout?: number; // Max milliseconds (max 600000)
run_in_background?: boolean; // Run in background and return shellId?
}
```
**Output:**
```typescript
interface BashOutput {
output: string; // Combined stdout + stderr (max 30000 chars)
exitCode: number;
killed?: boolean; // Was process killed by timeout?
shellId?: string; // For background: use BashOutput tool to poll
}
```
### BashOutput
Poll output from background shell.
**Input:**
```typescript
interface BashOutputInput {
bash_id: string;
filter?: string; // Optional regex to filter lines
}
```
**Output:**
```typescript
interface BashOutputToolOutput {
output: string; // New output since last check
status: 'running' | 'completed' | 'failed';
exitCode?: number; // Set when completed
}
```
### KillBash
Terminate background shell.
**Input:**
```typescript
interface KillShellInput {
shell_id: string; // From BashOutput tool's shellId
}
```
**Output:**
```typescript
interface KillBashOutput {
message: string;
shell_id: string;
}
```
---
## Search & Matching
### Glob
Fast pattern-based file matching.
**Input:**
```typescript
interface GlobInput {
pattern: string; // Glob pattern (e.g., "**/*.js")
path?: string; // Search directory (default: cwd)
}
```
**Output:**
```typescript
interface GlobOutput {
matches: string[]; // Matching file paths (sorted by mtime)
count: number;
search_path: string;
}
```
### Grep
Ripgrep-based regex search with filtering.
**Input:**
```typescript
interface GrepInput {
pattern: string; // Regex pattern (required)
path?: string; // Search directory (default: cwd)
glob?: string; // Glob filter (e.g., "*.ts")
type?: string; // File type (e.g., "js", "py")
output_mode?: 'content' | 'files_with_matches' | 'count';
'-i'?: boolean; // Case insensitive
'-n'?: boolean; // Show line numbers (content mode)
'-B'?: number; // Lines before match
'-A'?: number; // Lines after match
'-C'?: number; // Lines before and after
head_limit?: number; // Limit results (first N)
multiline?: boolean; // Enable multiline matching
}
```
**Output (content mode):**
```typescript
interface GrepContentOutput {
matches: Array<{
file: string;
line_number?: number;
line: string;
before_context?: string[];
after_context?: string[];
}>;
total_matches: number;
}
```
**Output (files mode):**
```typescript
interface GrepFilesOutput {
files: string[];
count: number;
}
```
**Output (count mode):**
```typescript
interface GrepCountOutput {
counts: Array<{
file: string;
count: number;
}>;
total: number;
}
```
---
## Web Operations
### WebFetch
Fetch URL and process with AI analysis.
**Input:**
```typescript
interface WebFetchInput {
url: string; // Full URL (required)
prompt: string; // AI analysis prompt (required)
}
```
**Output:**
```typescript
interface WebFetchOutput {
response: string; // AI's analysis
url: string;
final_url?: string; // After redirects
status_code?: number;
}
```
### WebSearch
Search the web.
**Input:**
```typescript
interface WebSearchInput {
query: string; // Search query (required)
allowed_domains?: string[]; // Only these domains
blocked_domains?: string[]; // Never these domains
}
```
**Output:**
```typescript
interface WebSearchOutput {
results: Array<{
title: string;
url: string;
snippet: string;
metadata?: Record<string, any>;
}>;
total_results: number;
query: string;
}
```
---
## Notebook Operations
### NotebookEdit
Edit, insert, or delete Jupyter notebook cells.
**Input:**
```typescript
interface NotebookEditInput {
notebook_path: string; // Absolute path (required)
new_source: string; // Cell source code (required)
cell_id?: string; // Target cell
cell_type?: 'code' | 'markdown'; // Cell type (required for insert)
edit_mode?: 'replace' | 'insert' | 'delete';
}
```
**Output:**
```typescript
interface NotebookEditOutput {
message: string;
edit_type: 'replaced' | 'inserted' | 'deleted';
cell_id?: string;
total_cells: number;
}
```
---
## Delegation
### Task
Delegate complex work to a specialist subagent.
**Input:**
```typescript
interface AgentInput {
description: string; // 3-5 word task description (required)
prompt: string; // Full task instructions (required)
subagent_type: string; // Agent type: 'general-purpose', 'backend-developer',
// 'frontend-ui-developer', 'code-finder', etc.
}
```
**Output:**
```typescript
interface TaskOutput {
result: string; // Final result from subagent
usage?: {
input_tokens: number;
output_tokens: number;
cache_creation_input_tokens?: number;
cache_read_input_tokens?: number;
};
total_cost_usd?: number;
duration_ms?: number;
}
```
---
## Task Management
### TodoWrite
Create or update task lists.
**Input:**
```typescript
interface TodoWriteInput {
todos: Array<{
content: string; // Imperative description (required)
status: 'pending' | 'in_progress' | 'completed';
activeForm: string; // Present continuous form (required)
}>;
}
```
**Output:**
```typescript
interface TodoWriteOutput {
message: string;
stats: {
total: number;
pending: number;
in_progress: number;
completed: number;
};
}
```
### ExitPlanMode
Exit planning mode and prompt user for approval.
**Input:**
```typescript
interface ExitPlanModeInput {
plan: string; // Plan markdown (required)
}
```
**Output:**
```typescript
interface ExitPlanModeOutput {
message: string;
approved?: boolean; // User approved?
}
```
---
## MCP Resources
### ListMcpResources
List available MCP resources from connected servers.
**Input:**
```typescript
interface ListMcpResourcesInput {
server?: string; // Filter by server name
}
```
**Output:**
```typescript
interface ListMcpResourcesOutput {
resources: Array<{
uri: string;
name: string;
description?: string;
mimeType?: string;
server: string;
}>;
total: number;
}
```
### ReadMcpResource
Read a specific MCP resource.
**Input:**
```typescript
interface ReadMcpResourceInput {
server: string; // MCP server name (required)
uri: string; // Resource URI (required)
}
```
**Output:**
```typescript
interface ReadMcpResourceOutput {
contents: Array<{
uri: string;
mimeType?: string;
text?: string;
blob?: string;
}>;
server: string;
}
```
---
## ToolInput & ToolOutput Union Types
All tool inputs combined:
```typescript
type ToolInput =
| AgentInput
| BashInput
| BashOutputInput
| FileEditInput
| FileMultiEditInput
| FileReadInput
| FileWriteInput
| GlobInput
| GrepInput
| KillShellInput
| NotebookEditInput
| WebFetchInput
| WebSearchInput
| TodoWriteInput
| ExitPlanModeInput
| ListMcpResourcesInput
| ReadMcpResourceInput;
```
All tool outputs combined:
```typescript
type ToolOutput =
| TaskOutput
| BashOutput
| BashOutputToolOutput
| EditOutput
| MultiEditOutput
| ReadOutput
| WriteOutput
| GlobOutput
| GrepOutput
| KillBashOutput
| NotebookEditOutput
| WebFetchOutput
| WebSearchOutput
| TodoWriteOutput
| ExitPlanModeOutput
| ListMcpResourcesOutput
| ReadMcpResourceOutput;
```
---
## Related
- [Types Reference](./TYPES.md) – Options, PermissionMode, AgentDefinition
- [Message Types](./MESSAGE_TYPES.md) – SDKMessage definitions
- [Main SKILL.md](./SKILL.md) – Quick overview
```