TY

typescript-sdk-reference

A guide for using the Anthropic TypeScript Agent SDK to build applications that interact with Claude Code.

Install

mkdir -p .claude/skills/typescript-sdk-reference && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/6992" && unzip -o skill.zip -d .claude/skills/typescript-sdk-reference && rm skill.zip

Installs to .claude/skills/typescript-sdk-reference

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Comprehensive reference for the TypeScript Agent SDK with functions, types, and interfaces for programmatic Claude Code interactions
132 charsno explicit “when” trigger
Advanced

Key capabilities

  • Executing programmatic Claude Code queries
  • Defining type-safe MCP tools
  • Managing conversation streaming
  • Configuring subagent definitions
  • Connecting custom MCP servers

How it works

The SDK provides a programmatic interface to interact with Claude Code, allowing developers to define custom tools, manage conversation state, and stream responses via an async generator.

Inputs & outputs

You give it
Prompt and configuration options
You get back
Streamed SDKMessage objects

When to use typescript-sdk-reference

  • Define a custom tool with Zod validation
  • Query Claude Code programmatically
  • Stream agent responses in a custom application

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

FunctionPurposeKey Use Case
query()Primary interface for Claude Code interactionsSend prompts, stream responses, manage multi-turn conversations
tool()Define MCP tools with type-safe schemasCreate custom tools for agents using Zod validation
createSdkMcpServer()Create in-process MCP serversHost 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

OptionTypeDefaultPurpose
allowedToolsstring[]All availableRestrict which tools Claude can use
disallowedToolsstring[][]Explicitly block tools
modelstringCLI defaultOverride Claude model (e.g., 'claude-opus')
cwdstringprocess.cwd()Working directory for operations
abortControllerAbortControllerNew instanceControl task cancellation

Advanced Options

OptionTypeDefaultPurpose
systemPromptstring or preset objectNoneCustom system instructions or Claude Code preset
agentsRecord<string, AgentDefinition>undefinedProgrammatically define subagents with custom prompts
mcpServersRecord<string, McpServerConfig>{}Connect stdio, SSE, HTTP, or SDK MCP servers
settingSources('user' | 'project' | 'local')[][]Load filesystem settings (CLAUDE.md, settings.json)
permissionModePermissionMode'default''default', 'acceptEdits', 'bypassPermissions', or 'plan'
maxThinkingTokensnumberundefinedToken limit for extended thinking
maxTurnsnumberundefinedMaximum conversation turns before stopping
resumestringundefinedResume a previous session by ID
forkSessionbooleanfalseFork to new session on resume instead of continuing

Message Types Overview

The query() generator yields SDKMessage objects. Common types:

Message TypeWhen EmittedKey Fields
'system'Session initializationtools, model, permissionMode, slash_commands
'user'User input sentmessage (APIUserMessage), uuid
'assistant'Claude respondsmessage (APIAssistantMessage with content/tool_use)
'result'Query completessubtype ('success' or error), usage, total_cost_usd
'stream_event'Partial streaming dataevent (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 TypeTransportUse Case
McpStdioServerConfigstdio (subprocess)External tools, sandboxing
McpSSEServerConfigServer-Sent EventsRemote tools, pub/sub patterns
McpHttpServerConfigHTTPREST-based tools, cloud integrations
McpSdkServerConfigWithInstanceIn-processCustom 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:

ToolPurposeKey Input
TaskDelegate to subagentdescription, prompt, subagent_type
BashRun shell commandscommand, optional timeout, run_in_background
ReadRead files/images/PDFsfile_path, optional offset/limit
Write / EditModify filesfile_path, content or old/new strings
GlobPattern matchingpattern, optional path
GrepRegex searchpattern, optional filters (glob, type, -B/-A/-C)
WebFetchFetch & analyze URLsurl, prompt for AI analysis
WebSearchWeb searchquery, optional domain filters
NotebookEditJupyter notebooksnotebook_path, new_source, edit_mode
TodoWriteTask trackingtodos 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

When not to use it

  • When simple CLI interaction is sufficient

Prerequisites

Node.js environment@anthropic-ai/claude-agent-sdk package

Limitations

  • Requires Node.js process
  • Limited to SDK-supported message types

How it compares

It enables native integration of Claude Code capabilities into custom applications rather than relying on the CLI.

Compared to similar skills

typescript-sdk-reference side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
typescript-sdk-reference (this skill)110moReviewAdvanced
mcp-builder1363moReviewAdvanced
copilot-sdk74moReviewIntermediate
chatgpt-app-builder52moReviewAdvanced

Try saying

Example prompts that trigger this skill in your AI assistant.

More by CaptainCrouton89

View all by CaptainCrouton89

reviewing-code

CaptainCrouton89

Systematically evaluate code changes for security, correctness, performance, and spec alignment. Use when reviewing PRs, assessing code quality, or verifying implementation against requirements.

21105

railway-cli-management

CaptainCrouton89

Deploy, manage services, view logs, and configure Railway infrastructure. Use when deploying to Railway, managing environment variables, viewing deployment logs, scaling services, or managing volumes.

9139

writing-like-user

CaptainCrouton89

Emulate the user's personal writing voice and style patterns. Use when the user asks to write content in their voice, draft documents, compose messages, or requests "write this like me" or "in my style."

687

gathering-requirements

CaptainCrouton89

Systematically clarify user needs, preferences, and constraints before planning or implementation. Classifies work type, investigates existing systems, discovers edge cases and integration points, resolves assumptions, and creates detailed specifications. Use when building features, enhancements, or integrations where requirements need clarification.

31

auditing-security

CaptainCrouton89

Identify and remediate vulnerabilities through systematic code analysis. Use when performing security assessments, pre-deployment reviews, compliance validation (OWASP, PCI-DSS, GDPR), investigating known vulnerabilities, or post-incident analysis.

10

documenting-code

CaptainCrouton89

Maintain project documentation synchronized with code. Keep feature specs, API contracts, and README current with init-project standards. Use when updating docs after code changes, adding new features, or ensuring documentation completeness.

14

You might also like

mcp-builder

anthropics

Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).

136215

copilot-sdk

github

Build agentic applications with GitHub Copilot SDK. Use when embedding AI agents in apps, creating custom tools, implementing streaming responses, managing sessions, connecting to MCP servers, or creating custom agents. Triggers on Copilot SDK, GitHub SDK, agentic app, embed Copilot, programmable agent, MCP server, custom agent.

763

chatgpt-app-builder

mcp-use

Build ChatGPT apps with interactive widgets using mcp-use and OpenAI Apps SDK. Use when creating ChatGPT apps, building MCP servers with widgets, defining React widgets, working with Apps SDK, or when user mentions ChatGPT widgets, mcp-use widgets, or Apps SDK development.

535

create-mcp-app

modelcontextprotocol

This skill should be used when the user asks to "create an MCP App", "add a UI to an MCP tool", "build an interactive MCP View", "scaffold an MCP App", or needs guidance on MCP Apps SDK patterns, UI-resource registration, MCP App lifecycle, or host integration. Provides comprehensive guidance for building MCP Apps with interactive UIs.

331

mcp-developer

Jeffallan

Use when building MCP servers or clients that connect AI systems with external tools and data sources. Invoke for MCP protocol compliance, TypeScript/Python SDKs, resource providers, tool functions.

16

create-mcp-servers

glittercowboy

Create Model Context Protocol (MCP) servers that expose tools, resources, and prompts to Claude. Use when building custom integrations, APIs, data sources, or any server that Claude should interact with via the MCP protocol. Supports both TypeScript and Python implementations.

15

Search skills

Search the agent skills registry