Agent SDK Reference - TypeScript
การติดตั้ง
npm install @anthropic-ai/claude-agent-sdk
SDK รวม native Claude Code binary สำหรับ platform ของคุณเป็น optional dependency หาก package manager ของคุณข้าม optional dependencies ให้ตั้งค่า pathToClaudeCodeExecutable ไปยัง binary claude ที่ติดตั้งแยกต่างหากแทน
Compile เป็น single executable
เมื่อใช้ bun build --compile ให้ embed platform binary เป็น file asset:
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);
}
Functions
query()
ฟังก์ชันหลักสำหรับการโต้ตอบกับ Claude Code สร้าง async generator ที่ stream messages
function query({
prompt,
options
}: {
prompt: string | AsyncIterable<SDKUserMessage>;
options?: Options;
}): Query;
startup()
Pre-warms CLI subprocess ก่อนที่ prompt จะพร้อมใช้งาน
function startup(params?: {
options?: Options;
initializeTimeoutMs?: number;
}): Promise<WarmQuery>;
ตัวอย่าง:
import { startup } from "@anthropic-ai/claude-agent-sdk";
const warm = await startup({ options: { maxTurns: 3 } });
for await (const message of warm.query("What files are here?")) {
console.log(message);
}
tool()
สร้าง MCP tool definition ที่มี type safety
function tool<Schema extends AnyZodRawShape>(
name: string,
description: string,
inputSchema: Schema,
handler: (args: InferShape<Schema>, extra: unknown) => Promise<CallToolResult>,
extras?: { annotations?: ToolAnnotations }
): SdkMcpToolDefinition<Schema>;
ตัวอย่าง:
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()
สร้าง MCP server instance ที่รันใน process เดียวกัน
function createSdkMcpServer(options: {
name: string;
version?: string;
tools?: Array<SdkMcpToolDefinition<any>>;
}): McpSdkServerConfigWithInstance;
listSessions()
ค้นพบและแสดง sessions ในอดีตพร้อม metadata
function listSessions(options?: ListSessionsOptions): Promise<SDKSessionInfo[]>;
ตัวอย่าง:
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()
อ่าน user และ assistant messages จาก session transcript ในอดีต
function getSessionMessages(
sessionId: string,
options?: GetSessionMessagesOptions
): Promise<SessionMessage[]>;
getSessionInfo()
อ่าน metadata สำหรับ session เดียวตาม ID
function getSessionInfo(
sessionId: string,
options?: GetSessionInfoOptions
): Promise<SDKSessionInfo | undefined>;
renameSession()
เปลี่ยนชื่อ session โดยเพิ่ม custom-title entry
function renameSession(
sessionId: string,
title: string,
options?: SessionMutationOptions
): Promise<void>;
tagSession()
Tag session ส่ง null เพื่อล้าง tag
function tagSession(
sessionId: string,
tag: string | null,
options?: SessionMutationOptions
): Promise<void>;
resolveSettings()
Resolve Claude Code settings ที่มีผลบังคับใช้สำหรับไดเรกทอรีโดยไม่ต้อง spawn CLI
function resolveSettings(
options?: ResolveSettingsOptions
): Promise<ResolvedSettings>;
ตัวอย่าง:
import { resolveSettings } from "@anthropic-ai/claude-agent-sdk";
const { effective, provenance } = await resolveSettings({
cwd: "/path/to/project",
settingSources: ["user", "project", "local"],
});
console.log(`Cleanup period: ${effective.cleanupPeriodDays} days`);
console.log(`Set by: ${provenance.cleanupPeriodDays?.source}`);
Key Types
Options
Configuration object สำหรับ query() พร้อม properties มากมายรวมถึง:
| Property | Type | Default | คำอธิบาย |
|---|---|---|---|
abortController | AbortController | new AbortController() | Controller สำหรับยกเลิก operations |
additionalDirectories | string[] | [] | ไดเรกทอรีเพิ่มเติมที่ Claude สามารถเข้าถึงได้ |
agent | string | undefined | ชื่อ agent สำหรับ main thread |
agents | Record<string, AgentDefinition> | undefined | กำหนด subagents แบบ programmatic |
allowedTools | string[] | [] | Tools ที่จะ auto-approve |
betas | SdkBeta[] | [] | เปิดใช้งาน beta features |
canUseTool | CanUseTool | undefined | ฟังก์ชัน permission แบบ custom |
continue | boolean | false | Continue conversation ล่าสุด |
cwd | string | process.cwd() | ไดเรกทอรีทำงานปัจจุบัน |
debug | boolean | false | เปิดใช้งาน debug mode |
disallowedTools | string[] | [] | Tools ที่จะปฏิเสธ |
effort | 'low'|'medium'|'high'|'xhigh'|'max' | Model default | ควบคุมความลึกของ reasoning |
enableFileCheckpointing | boolean | false | เปิดใช้งานการติดตามการเปลี่ยนแปลงไฟล์ |
env | Record<string, string | undefined> | process.env | Environment variables |
executable | 'bun'|'deno'|'node' | Auto-detected | JavaScript runtime |
maxTurns | number | undefined | จำนวน agentic turns สูงสุด |
model | string | Default from CLI | Claude model alias หรือชื่อ |
mcpServers | Record<string, McpServerConfig> | {} | MCP server configurations |
permissionMode | PermissionMode | 'default' | Permission mode สำหรับเซสชัน |
persistSession | boolean | true | เปิดใช้งาน session persistence |
resume | string | undefined | Session ID ที่จะ resume |
sessionId | string | Auto-generated | ใช้ UUID เฉพาะ |
sessionStore | SessionStore | undefined | External session storage |
settings | string | Settings | undefined | Inline settings หรือ path ของไฟล์ settings |
systemPrompt | string | {...} | undefined | การ configure system prompt |
thinking | ThinkingConfig | { type: 'adaptive' } | พฤติกรรม reasoning |
tools | string[] | {...} | undefined | Tool configuration |
จัดการ API responses ที่ช้าหรือค้าง
const result = query({
prompt: "Analyze this code",
options: {
env: {
...process.env,
API_TIMEOUT_MS: "120000",
CLAUDE_CODE_MAX_RETRIES: "2",
CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS: "120000",
},
},
});
Query object
Interface ที่คืนค่าโดยฟังก์ชัน query()
interface Query extends AsyncGenerator<SDKMessage, void> {
interrupt(): Promise<void>;
rewindFiles(
userMessageId: string,
options?: { dryRun?: boolean }
): Promise<RewindFilesResult>;
setPermissionMode(mode: PermissionMode): Promise<void>;
setModel(model?: string): Promise<void>;
setMaxThinkingTokens(maxThinkingTokens: number | null): Promise<void>;
applyFlagSettings(settings: { [K in keyof Settings]?: Settings[K] | null }): Promise<void>;
initializationResult(): Promise<SDKControlInitializeResponse>;
supportedCommands(): Promise<SlashCommand[]>;
supportedModels(): Promise<ModelInfo[]>;
supportedAgents(): Promise<AgentInfo[]>;
mcpServerStatus(): Promise<McpServerStatus[]>;
accountInfo(): Promise<AccountInfo>;
reconnectMcpServer(serverName: string): Promise<void>;
toggleMcpServer(serverName: string, enabled: boolean): Promise<void>;
setMcpServers(servers: Record<string, McpServerConfig>): Promise<McpSetServersResult>;
streamInput(stream: AsyncIterable<SDKUserMessage>): Promise<void>;
stopTask(taskId: string): Promise<void>;
close(): void;
}
WarmQuery
Handle ที่คืนค่าโดย startup() Subprocess ถูก pre-spawned และ initialized แล้ว
interface WarmQuery extends AsyncDisposable {
query(prompt: string | AsyncIterable<SDKUserMessage>): Query;
close(): void;
}
PermissionMode
type PermissionMode =
| "default" // พฤติกรรม permission มาตรฐาน
| "acceptEdits" // Auto-accept file edits
| "bypassPermissions" // Bypass permission checks
| "plan" // Planning mode - explore โดยไม่แก้ไข
| "dontAsk" // ไม่ถาม ปฏิเสธถ้าไม่ได้ pre-approve
| "auto"; // ใช้ model classifier
AgentDefinition
Configuration สำหรับ subagent ที่กำหนดแบบ programmatic
type AgentDefinition = {
description: string;
tools?: string[];
disallowedTools?: string[];
prompt: string;
model?: string;
mcpServers?: AgentMcpServerSpec[];
skills?: string[];
initialPrompt?: string;
maxTurns?: number;
background?: boolean;
memory?: "user" | "project" | "local";
effort?: "low" | "medium" | "high" | "xhigh" | "max" | number;
permissionMode?: PermissionMode;
};
SettingSource
ควบคุม filesystem configuration sources ที่จะโหลด
type SettingSource = "user" | "project" | "local";
| ค่า | คำอธิบาย | ตำแหน่ง |
|---|---|---|
'user' | Global user settings | ~/.claude/settings.json |
'project' | Shared project settings | .claude/settings.json |
'local' | Local project settings | .claude/settings.local.json |
ตัวอย่าง:
// ปิด filesystem settings
const result = query({
prompt: "Analyze this code",
options: { settingSources: [] }
});
// โหลดเฉพาะ project settings
const result = query({
prompt: "Run CI checks",
options: { settingSources: ["project"] }
});
MCPServerConfig
Configuration สำหรับ MCP servers
type McpServerConfig =
| McpStdioServerConfig
| McpSSEServerConfig
| McpHttpServerConfig
| McpSdkServerConfigWithInstance;
Message Types
SDKMessage
Union type ของ messages ที่เป็นไปได้ทั้งหมดที่คืนค่าโดย query
SDKAssistantMessage
Assistant response message
type SDKAssistantMessage = {
type: "assistant";
uuid: UUID;
session_id: string;
message: BetaMessage;
parent_tool_use_id: string | null;
error?: SDKAssistantMessageError;
};
SDKUserMessage
User input message
type SDKUserMessage = {
type: "user";
uuid?: UUID;
session_id?: string;
message: MessageParam;
parent_tool_use_id: string | null;
isSynthetic?: boolean;
shouldQuery?: boolean;
tool_use_result?: unknown;
origin?: SDKMessageOrigin;
};
SDKResultMessage
Final result message พร้อม success หรือ error subtypes รวมถึง usage metrics และข้อมูลค่าใช้จ่าย