typescript-sdk-reference
Comprehensive reference for the TypeScript Agent SDK with functions, types, and interfaces for programmatic Claude Code interactions
Install
mkdir -p .claude/skills/typescript-sdk-reference && curl -L -o skill.zip "https://mcp.directory/api/skills/download/6992" && unzip -o skill.zip -d .claude/skills/typescript-sdk-reference && rm skill.zipInstalls to .claude/skills/typescript-sdk-reference
About this skill
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 identifierdescription: Natural language descriptioninputSchema: Zod schema defining inputshandler: 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 identifierversion: Optional semantic versiontools: Array of tool definitions fromtool()
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,modeloverrideSdkMcpToolDefinition– Output oftool()function with Zod schema bindingMcpServerConfig– 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 decisionsHookInput– Union of all hook input types; each extendsBaseHookInput
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
- Full API Reference – Complete type definitions and schemas
- Message Types Reference – SDKMessage union types and examples
- Types Reference – Detailed Options, AgentDefinition, PermissionMode docs
- Tool Reference – Input/output schemas for all built-in tools
- SDK Overview – Getting started guide
- Common Workflows – Step-by-step patterns
- CLI Reference – Command-line interface docs
More by CaptainCrouton89
View all skills by CaptainCrouton89 →You might also like
flutter-development
aj-geddes
Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.
drawio-diagrams-enhanced
jgtolentino
Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.
ui-ux-pro-max
nextlevelbuilder
"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."
godot
bfollington
This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.
nano-banana-pro
garg-aayush
Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.
fastapi-templates
wshobson
Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.
Related MCP Servers
Browse all serversTypeScript Refactoring offers advanced TypeScript/JavaScript code analysis and intelligent refactoring for seamless and
Snowfort Circuit MCP — MCP server for AI coding agents enabling browser automation, electron automation and AI test auto
AI-ready access to Grafana UI: full React component library—TypeScript source, MDX docs, Storybook examples, tests, and
Ant Design MCP Server: AI assistants for Ant Design docs, examples, APIs. Multi-version support and natural-language que
Find the best flights with our tool, featuring real-time search, flexible date price discovery, and direct booking like
Boost your AI code assistant with Context7: inject real-time API documentation from OpenAPI specification sources into y
Stay ahead of the MCP ecosystem
Get weekly updates on new skills and servers.