インストール
npm install @anthropic-ai/claude-agent-sdk
SDK は、@anthropic-ai/claude-agent-sdk-darwin-arm64 などのオプション依存関係として、プラットフォーム用のネイティブ Claude Code バイナリをバンドルしています。Claude Code を別途インストールする必要はありません。パッケージマネージャーがオプション依存関係をスキップする場合、SDK は Native CLI binary for <platform> not found をスローします。代わりに、別途インストールされた claude バイナリに pathToClaudeCodeExecutable を設定してください。
query()
Claude Code と対話するための主要な関数です。メッセージが到着するにつれてストリーミングする非同期ジェネレータを作成します。
function query({
prompt,
options
}: {
prompt: string | AsyncIterable<SDKUserMessage>;
options?: Options;
}): Query;
パラメータ
| パラメータ | 型 | 説明 |
|---|
prompt | string | AsyncIterable<SDKUserMessage> | 文字列またはストリーミングモード用の非同期反復可能オブジェクトとしての入力プロンプト |
options | Options | オプションの設定オブジェクト(以下の Options 型を参照) |
戻り値
Query オブジェクトを返します。これは AsyncGenerator<SDKMessage, void> を拡張し、追加のメソッドを持ちます。
startup()
プロンプトが利用可能になる前に、CLI サブプロセスをスポーンして初期化ハンドシェイクを完了することで、プリウォーミングします。返された WarmQuery ハンドルは後でプロンプトを受け入れ、既に準備ができているプロセスに書き込むため、最初の query() 呼び出しはサブプロセスのスポーンと初期化コストをインラインで支払うことなく解決します。
function startup(params?: {
options?: Options;
initializeTimeoutMs?: number;
}): Promise<WarmQuery>;
パラメータ
| パラメータ | 型 | 説明 |
|---|
options | Options | オプションの設定オブジェクト。query() の options パラメータと同じです |
initializeTimeoutMs | number | サブプロセス初期化を待つ最大時間(ミリ秒)。デフォルトは 60000 です。初期化が時間内に完了しない場合、プロミスはタイムアウトエラーで拒否されます |
戻り値
サブプロセスがスポーンされ、初期化ハンドシェイクを完了したら解決する Promise<WarmQuery> を返します。
アプリケーションブート時など、早期に startup() を呼び出し、プロンプトが準備できたら返されたハンドルで .query() を呼び出します。これにより、サブプロセスのスポーンと初期化をクリティカルパスから移動させます。
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);
}
SDK MCP サーバーで使用するためのタイプセーフな MCP ツール定義を作成します。
function tool<Schema extends AnyZodRawShape>(
name: string,
description: string,
inputSchema: Schema,
handler: (args: InferShape<Schema>, extra: unknown) => Promise<CallToolResult>,
extras?: { annotations?: ToolAnnotations }
): SdkMcpToolDefinition<Schema>;
パラメータ
| パラメータ | 型 | 説明 |
|---|
name | string | ツールの名前 |
description | string | ツールが何をするかの説明 |
inputSchema | Schema extends AnyZodRawShape | ツールの入力パラメータを定義する Zod スキーマ(Zod 3 と Zod 4 の両方をサポート) |
handler | (args, extra) => Promise<CallToolResult> | ツールロジックを実行する非同期関数 |
extras | { annotations?: ToolAnnotations } | クライアントに動作ヒントを提供するオプションの MCP ツール注釈 |
@modelcontextprotocol/sdk/types.js から再エクスポートされます。すべてのフィールドはオプションのヒントです。クライアントはセキュリティ決定のためにこれらに依存すべきではありません。
| フィールド | 型 | デフォルト | 説明 |
|---|
title | string | undefined | ツールの人間が読める形式のタイトル |
readOnlyHint | boolean | false | true の場合、ツールはその環境を変更しません |
destructiveHint | boolean | true | true の場合、ツールは破壊的な更新を実行する可能性があります(readOnlyHint が false の場合のみ意味があります) |
idempotentHint | boolean | false | true の場合、同じ引数での繰り返し呼び出しは追加の効果がありません(readOnlyHint が false の場合のみ意味があります) |
openWorldHint | boolean | true | true の場合、ツールは外部エンティティと対話します(例:ウェブ検索)。false の場合、ツールのドメインは閉じています(例:メモリツール) |
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 サーバーインスタンスを作成します。
function createSdkMcpServer(options: {
name: string;
version?: string;
tools?: Array<SdkMcpToolDefinition<any>>;
}): McpSdkServerConfigWithInstance;
パラメータ
| パラメータ | 型 | 説明 |
|---|
options.name | string | MCP サーバーの名前 |
options.version | string | オプションのバージョン文字列 |
options.tools | Array<SdkMcpToolDefinition> | tool() で作成されたツール定義の配列 |
listSessions()
軽いメタデータを含む過去のセッションを検出してリストします。プロジェクトディレクトリでフィルタリングするか、すべてのプロジェクト全体でセッションをリストします。
function listSessions(options?: ListSessionsOptions): Promise<SDKSessionInfo[]>;
パラメータ
| パラメータ | 型 | デフォルト | 説明 |
|---|
options.dir | string | undefined | セッションをリストするディレクトリ。省略すると、すべてのプロジェクト全体でセッションを返します |
options.limit | number | undefined | 返すセッションの最大数 |
options.includeWorktrees | boolean | true | dir が git リポジトリ内にある場合、すべての worktree パスからセッションを含めます |
戻り値の型:SDKSessionInfo
| プロパティ | 型 | 説明 |
|---|
sessionId | string | 一意のセッション識別子(UUID) |
summary | string | 表示タイトル:カスタムタイトル、自動生成されたサマリー、または最初のプロンプト |
lastModified | number | エポック以降のミリ秒単位での最後の変更時刻 |
fileSize | number | undefined | セッションファイルサイズ(バイト)。ローカル JSONL ストレージの場合のみ入力されます |
customTitle | string | undefined | ユーザーが設定したセッションタイトル(/rename 経由) |
firstPrompt | string | undefined | セッション内の最初の意味のあるユーザープロンプト |
gitBranch | string | undefined | セッション終了時の Git ブランチ |
cwd | string | undefined | セッションの作業ディレクトリ |
tag | string | undefined | ユーザーが設定したセッションタグ(tagSession() を参照) |
createdAt | number | undefined | 最初のエントリのタイムスタンプからのエポック以降のミリ秒単位での作成時刻 |
プロジェクトの 10 個の最新セッションを出力します。結果は lastModified の降順でソートされるため、最初の項目が最新です。dir を省略してすべてのプロジェクト全体を検索します。
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()
過去のセッショントランスクリプトからユーザーおよびアシスタントメッセージを読み取ります。
function getSessionMessages(
sessionId: string,
options?: GetSessionMessagesOptions
): Promise<SessionMessage[]>;
パラメータ
| パラメータ | 型 | デフォルト | 説明 |
|---|
sessionId | string | 必須 | 読み取るセッション UUID(listSessions() を参照) |
options.dir | string | undefined | セッションを見つけるプロジェクトディレクトリ。省略すると、すべてのプロジェクトを検索します |
options.limit | number | undefined | 返すメッセージの最大数 |
options.offset | number | undefined | 開始からスキップするメッセージ数 |
戻り値の型:SessionMessage
| プロパティ | 型 | 説明 |
|---|
type | "user" | "assistant" | メッセージロール |
uuid | string | 一意のメッセージ識別子 |
session_id | string | このメッセージが属するセッション |
message | unknown | トランスクリプトからの生のメッセージペイロード |
parent_tool_use_id | null | 予約済み |
import { listSessions, getSessionMessages } from "@anthropic-ai/claude-agent-sdk";
const [latest] = await listSessions({ dir: "/path/to/project", limit: 1 });
if (latest) {
const messages = await getSessionMessages(latest.sessionId, {
dir: "/path/to/project",
limit: 20
});
for (const msg of messages) {
console.log(`[${msg.type}] ${msg.uuid}`);
}
}
getSessionInfo()
プロジェクトディレクトリ全体をスキャンせずに、ID でセッションのメタデータを読み取ります。
function getSessionInfo(
sessionId: string,
options?: GetSessionInfoOptions
): Promise<SDKSessionInfo | undefined>;
パラメータ
| パラメータ | 型 | デフォルト | 説明 |
|---|
sessionId | string | 必須 | ルックアップするセッションの UUID |
options.dir | string | undefined | プロジェクトディレクトリパス。省略すると、すべてのプロジェクトディレクトリを検索します |
SDKSessionInfo を返すか、セッションが見つからない場合は undefined を返します。
renameSession()
カスタムタイトルエントリを追加することでセッションの名前を変更します。繰り返し呼び出しは安全です。最新のタイトルが優先されます。
function renameSession(
sessionId: string,
title: string,
options?: SessionMutationOptions
): Promise<void>;
パラメータ
| パラメータ | 型 | デフォルト | 説明 |
|---|
sessionId | string | 必須 | 名前を変更するセッションの UUID |
title | string | 必須 | 新しいタイトル。空白をトリミングした後、空でない必要があります |
options.dir | string | undefined | プロジェクトディレクトリパス。省略すると、すべてのプロジェクトディレクトリを検索します |
セッションにタグを付けます。null を渡してタグをクリアします。繰り返し呼び出しは安全です。最新のタグが優先されます。
function tagSession(
sessionId: string,
tag: string | null,
options?: SessionMutationOptions
): Promise<void>;
パラメータ
| パラメータ | 型 | デフォルト | 説明 |
|---|
sessionId | string | 必須 | タグを付けるセッションの UUID |
tag | string | null | 必須 | タグ文字列、またはクリアする場合は null |
options.dir | string | undefined | プロジェクトディレクトリパス。省略すると、すべてのプロジェクトディレクトリを検索します |
Options
query() 関数の設定オブジェクト。
| プロパティ | 型 | デフォルト | 説明 |
|---|
abortController | AbortController | new AbortController() | 操作をキャンセルするためのコントローラー |
additionalDirectories | string[] | [] | Claude がアクセスできる追加ディレクトリ |
agent | string | undefined | メインスレッドのエージェント名。エージェントは agents オプションまたは設定で定義される必要があります |
agents | Record<string, [AgentDefinition](#agent-definition)> | undefined | プログラムでサブエージェントを定義します |
allowDangerouslySkipPermissions | boolean | false | パーミッションのバイパスを有効にします。permissionMode: 'bypassPermissions' を使用する場合に必須です |
allowedTools | string[] | [] | プロンプトなしで自動承認するツール。これは Claude をこれらのツールのみに制限しません。リストされていないツールは permissionMode と canUseTool にフォールスルーします。ツールをブロックするには disallowedTools を使用します。パーミッション を参照してください |
betas | SdkBeta[] | [] | ベータ機能を有効にします |
canUseTool | CanUseTool | undefined | ツール使用のためのカスタムパーミッション関数 |
continue | boolean | false | 最新の会話を続けます |
cwd | string | process.cwd() | 現在の作業ディレクトリ |
debug | boolean | false | Claude Code プロセスのデバッグモードを有効にします |
debugFile | string | undefined | デバッグログを特定のファイルパスに書き込みます。暗黙的にデバッグモードを有効にします |
disallowedTools | string[] | [] | 常に拒否するツール。拒否ルールが最初にチェックされ、allowedTools と permissionMode(bypassPermissions を含む)をオーバーライドします |
effort | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'high' | Claude がその応答にどれだけの努力を費やすかを制御します。適応的思考と連携して思考の深さをガイドします |
enableFileCheckpointing | boolean | false | ファイル変更追跡を有効にして巻き戻します。ファイルチェックポイント を参照してください |
env | Record<string, string | undefined> | process.env | 環境変数。CLAUDE_AGENT_SDK_CLIENT_APP を設定して、User-Agent ヘッダーでアプリを識別します |
executable | 'bun' | 'deno' | 'node' | 自動検出 | 使用する JavaScript ランタイム |
executableArgs | string[] | [] | 実行可能ファイルに渡す引数 |
extraArgs | Record<string, string | null> | {} | 追加の引数 |
fallbackModel | string | undefined | プライマリが失敗した場合に使用するモデル |
forkSession | boolean | false | resume で再開するときに、元のセッション ID を続行する代わりに新しいセッション ID にフォークします |
hooks | Partial<Record<HookEvent, HookCallbackMatcher[]>> | {} | イベントのフックコールバック |
includePartialMessages | boolean | false | 部分的なメッセージイベントを含めます |
maxBudgetUsd | number | undefined | クライアント側のコスト推定がこの USD 値に達したときにクエリを停止します。total_cost_usd と同じ推定と比較されます。コストと使用状況を追跡 で精度の注意事項を参照してください |
maxThinkingTokens | number | undefined | 非推奨: 代わりに thinking を使用してください。思考プロセスの最大トークン数 |
maxTurns | number | undefined | 最大 agentic ターン数(ツール使用ラウンドトリップ) |
mcpServers | Record<string, [McpServerConfig](#mcp-server-config)> | {} | MCP サーバー設定 |
model | string | CLI からのデフォルト | 使用する Claude モデル |
outputFormat | { type: 'json_schema', schema: JSONSchema } | undefined | エージェント結果の出力形式を定義します。詳細は 構造化出力 を参照してください |
pathToClaudeCodeExecutable | string | バンドルされたネイティブバイナリから自動解決 | Claude Code 実行可能ファイルへのパス。インストール中にオプション依存関係がスキップされた場合、またはプラットフォームがサポートされているセットにない場合にのみ必要です |
permissionMode | PermissionMode | 'default' | セッションのパーミッションモード |
permissionPromptToolName | string | undefined | パーミッションプロンプト用の MCP ツール名 |
persistSession | boolean | true | false の場合、セッション永続化をディスクに無効にします。セッションは後で再開できません |
plugins | SdkPluginConfig[] | [] | ローカルパスからカスタムプラグインをロードします。詳細は プラグイン を参照してください |
promptSuggestions | boolean | false | プロンプト提案を有効にします。各ターン後に予測される次のユーザープロンプトを含む prompt_suggestion メッセージを発行します |
resume | string | undefined | 再開するセッション ID |
resumeSessionAt | string | undefined | 特定のメッセージ UUID でセッションを再開します |
sandbox | SandboxSettings | undefined | サンドボックス動作をプログラムで設定します。詳細は サンドボックス設定 を参照してください |
sessionId | string | 自動生成 | 自動生成する代わりに、セッションに特定の UUID を使用します |
settingSources | SettingSource[] | CLI デフォルト(すべてのソース) | ロードするファイルシステム設定を制御します。ユーザー、プロジェクト、ローカル設定を無効にするには [] を渡します。管理ポリシー設定は関係なくロードされます。Claude Code 機能を使用 を参照してください |
spawnClaudeCodeProcess | (options: SpawnOptions) => SpawnedProcess | undefined | Claude Code プロセスをスポーンするカスタム関数。VM、コンテナ、またはリモート環境で Claude Code を実行するために使用します |
stderr | (data: string) => void | undefined | stderr 出力のコールバック |
strictMcpConfig | boolean | false | 厳密な MCP 検証を強制します |
systemPrompt | string | { type: 'preset'; preset: 'claude_code'; append?: string; excludeDynamicSections?: boolean } | undefined(最小限のプロンプト) | システムプロンプト設定。カスタムプロンプト用の文字列を渡すか、Claude Code のシステムプロンプトを使用するには { type: 'preset', preset: 'claude_code' } を渡します。プリセットオブジェクト形式を使用する場合、追加の指示で拡張するには append を追加し、マシン全体でプロンプトキャッシュの再利用を改善 するためにセッションごとのコンテキストを最初のユーザーメッセージに移動するには excludeDynamicSections: true を設定します |
thinking | ThinkingConfig | サポートされているモデルの場合 { type: 'adaptive' } | Claude の思考/推論動作を制御します。オプションについては ThinkingConfig を参照してください |
toolConfig | ToolConfig | undefined | 組み込みツール動作の設定。詳細は ToolConfig を参照してください |
tools | string[] | { type: 'preset'; preset: 'claude_code' } | undefined | ツール設定。ツール名の配列を渡すか、Claude Code のデフォルトツールを取得するにはプリセットを使用します |
Query オブジェクト
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>;
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;
}
メソッド
| メソッド | 説明 |
|---|
interrupt() | クエリを中断します(ストリーミング入力モードでのみ利用可能) |
rewindFiles(userMessageId, options?) | ファイルを指定されたユーザーメッセージの状態に復元します。{ dryRun: true } を渡して変更をプレビューします。enableFileCheckpointing: true が必須です。ファイルチェックポイント を参照してください |
setPermissionMode() | パーミッションモードを変更します(ストリーミング入力モードでのみ利用可能) |
setModel() | モデルを変更します(ストリーミング入力モードでのみ利用可能) |
setMaxThinkingTokens() | 非推奨: 代わりに thinking オプションを使用してください。最大思考トークン数を変更します |
initializationResult() | サポートされているコマンド、モデル、アカウント情報、出力スタイル設定を含む完全な初期化結果を返します |
supportedCommands() | 利用可能なスラッシュコマンドを返します |
supportedModels() | 表示情報を含む利用可能なモデルを返します |
supportedAgents() | 利用可能なサブエージェントを AgentInfo[] として返します |
mcpServerStatus() | 接続された MCP サーバーのステータスを返します |
accountInfo() | アカウント情報を返します |
reconnectMcpServer(serverName) | 名前で MCP サーバーを再接続します |
toggleMcpServer(serverName, enabled) | 名前で MCP サーバーを有効または無効にします |
setMcpServers(servers) | このセッションの MCP サーバーセットを動的に置き換えます。追加、削除、エラーが発生したサーバーに関する情報を返します |
streamInput(stream) | マルチターン会話のためにクエリに入力メッセージをストリーミングします |
stopTask(taskId) | ID で実行中のバックグラウンドタスクを停止します |
close() | クエリを閉じて、基になるプロセスを終了します。クエリを強制的に終了し、すべてのリソースをクリーンアップします |
WarmQuery
startup() によって返されるハンドル。サブプロセスは既にスポーンされ、初期化されているため、このハンドルで query() を呼び出すと、スタートアップレイテンシーなしで準備ができているプロセスにプロンプトを直接書き込みます。
interface WarmQuery extends AsyncDisposable {
query(prompt: string | AsyncIterable<SDKUserMessage>): Query;
close(): void;
}
メソッド
| メソッド | 説明 |
|---|
query(prompt) | プリウォーミングされたサブプロセスにプロンプトを送信し、Query を返します。WarmQuery ごとに 1 回だけ呼び出すことができます |
close() | プロンプトを送信せずにサブプロセスを閉じます。不要になったウォームクエリを破棄するために使用します |
WarmQuery は AsyncDisposable を実装しているため、自動クリーンアップのために await using で使用できます。
SDKControlInitializeResponse
initializationResult() の戻り値の型。セッション初期化データを含みます。
type SDKControlInitializeResponse = {
commands: SlashCommand[];
agents: AgentInfo[];
output_style: string;
available_output_styles: string[];
models: ModelInfo[];
account: AccountInfo;
fast_mode_state?: "off" | "cooldown" | "on";
};
AgentDefinition
プログラムで定義されたサブエージェントの設定。
type AgentDefinition = {
description: string;
tools?: string[];
disallowedTools?: string[];
prompt: string;
model?: "sonnet" | "opus" | "haiku" | "inherit";
mcpServers?: AgentMcpServerSpec[];
skills?: string[];
maxTurns?: number;
criticalSystemReminder_EXPERIMENTAL?: string;
};
| フィールド | 必須 | 説明 |
|---|
description | はい | このエージェントをいつ使用するかの自然言語説明 |
tools | いいえ | 許可されたツール名の配列。省略すると、親からすべてのツールを継承します |
disallowedTools | いいえ | このエージェントに対して明示的に許可しないツール名の配列 |
prompt | はい | エージェントのシステムプロンプト |
model | いいえ | このエージェントのモデルオーバーライド。省略または 'inherit' の場合、メインモデルを使用します |
mcpServers | いいえ | このエージェントの MCP サーバー仕様 |
skills | いいえ | エージェントコンテキストにプリロードするスキル名の配列 |
maxTurns | いいえ | 停止する前の最大 agentic ターン数(API ラウンドトリップ) |
criticalSystemReminder_EXPERIMENTAL | いいえ | 実験的:システムプロンプトに追加される重要なリマインダー |
AgentMcpServerSpec
サブエージェントで利用可能な MCP サーバーを指定します。サーバー名(親の mcpServers 設定からサーバーを参照する文字列)またはインラインサーバー設定レコード(サーバー名を設定にマッピング)です。
type AgentMcpServerSpec = string | Record<string, McpServerConfigForProcessTransport>;
ここで McpServerConfigForProcessTransport は McpStdioServerConfig | McpSSEServerConfig | McpHttpServerConfig | McpSdkServerConfig です。
SettingSource
SDK がどのファイルシステムベースの設定ソースから設定をロードするかを制御します。
type SettingSource = "user" | "project" | "local";
| 値 | 説明 | 場所 |
|---|
'user' | グローバルユーザー設定 | ~/.claude/settings.json |
'project' | 共有プロジェクト設定(バージョン管理) | .claude/settings.json |
'local' | ローカルプロジェクト設定(gitignored) | .claude/settings.local.json |
デフォルト動作
settingSources が省略または undefined の場合、query() は Claude Code CLI と同じファイルシステム設定をロードします:ユーザー、プロジェクト、ローカル。管理ポリシー設定はすべての場合にロードされます。このオプションに関係なく読み取られる入力については settingSources が制御しないもの を参照してください。
settingSources を使用する理由
ファイルシステム設定を無効にする:
// ディスクからユーザー、プロジェクト、またはローカル設定をロードしません
const result = query({
prompt: "Analyze this code",
options: { settingSources: [] }
});
すべてのファイルシステム設定を明示的にロードする:
const result = query({
prompt: "Analyze this code",
options: {
settingSources: ["user", "project", "local"] // すべての設定をロード
}
});
特定の設定ソースのみをロードする:
// プロジェクト設定のみをロードし、ユーザーとローカルを無視します
const result = query({
prompt: "Run CI checks",
options: {
settingSources: ["project"] // .claude/settings.json のみ
}
});
テストと CI 環境:
// ローカル設定を除外することで、CI で一貫した動作を確保します
const result = query({
prompt: "Run tests",
options: {
settingSources: ["project"], // チーム共有設定のみ
permissionMode: "bypassPermissions"
}
});
SDK のみのアプリケーション:
// すべてをプログラムで定義します。
// ファイルシステム設定ソースをオプトアウトするには [] を渡します。
const result = query({
prompt: "Review this PR",
options: {
settingSources: [],
agents: {
/* ... */
},
mcpServers: {
/* ... */
},
allowedTools: ["Read", "Grep", "Glob"]
}
});
CLAUDE.md プロジェクト指示をロードする:
// プロジェクト設定をロードして CLAUDE.md ファイルを含めます
const result = query({
prompt: "Add a new feature following project conventions",
options: {
systemPrompt: {
type: "preset",
preset: "claude_code" // Claude Code のシステムプロンプトを使用
},
settingSources: ["project"], // プロジェクトディレクトリから CLAUDE.md をロード
allowedTools: ["Read", "Write", "Edit"]
}
});
設定の優先順位
複数のソースがロードされる場合、設定はこの優先順位(高から低)でマージされます:
- ローカル設定(
.claude/settings.local.json)
- プロジェクト設定(
.claude/settings.json)
- ユーザー設定(
~/.claude/settings.json)
agents と allowedTools などのプログラム的なオプションは、ユーザー、プロジェクト、ローカルのファイルシステム設定をオーバーライドします。管理ポリシー設定はプログラム的なオプションより優先されます。
PermissionMode
type PermissionMode =
| "default" // 標準的なパーミッション動作
| "acceptEdits" // ファイル編集を自動承認
| "bypassPermissions" // すべてのパーミッションチェックをバイパス
| "plan" // 計画モード - 実行なし
| "dontAsk" // パーミッションをプロンプトしない、事前承認されていない場合は拒否
| "auto"; // モデル分類器を使用して各ツール呼び出しを承認または拒否
ツール使用を制御するためのカスタムパーミッション関数型。
type CanUseTool = (
toolName: string,
input: Record<string, unknown>,
options: {
signal: AbortSignal;
suggestions?: PermissionUpdate[];
blockedPath?: string;
decisionReason?: string;
toolUseID: string;
agentID?: string;
}
) => Promise<PermissionResult>;
| オプション | 型 | 説明 |
|---|
signal | AbortSignal | 操作を中止する必要がある場合にシグナルされます |
suggestions | PermissionUpdate[] | 提案されたパーミッション更新。ユーザーがこのツールに対して再度プロンプトされないようにします |
blockedPath | string | パーミッションリクエストをトリガーしたファイルパス(該当する場合) |
decisionReason | string | このパーミッションリクエストがトリガーされた理由を説明します |
toolUseID | string | アシスタントメッセージ内のこの特定のツール呼び出しの一意の識別子 |
agentID | string | サブエージェント内で実行している場合、サブエージェントの ID |
PermissionResult
パーミッションチェックの結果。
type PermissionResult =
| {
behavior: "allow";
updatedInput?: Record<string, unknown>;
updatedPermissions?: PermissionUpdate[];
toolUseID?: string;
}
| {
behavior: "deny";
message: string;
interrupt?: boolean;
toolUseID?: string;
};
組み込みツール動作の設定。
type ToolConfig = {
askUserQuestion?: {
previewFormat?: "markdown" | "html";
};
};
| フィールド | 型 | 説明 |
|---|
askUserQuestion.previewFormat | 'markdown' | 'html' | AskUserQuestion オプションの preview フィールドにオプトインし、そのコンテンツ形式を設定します。設定されていない場合、Claude はプレビューを発行しません |
McpServerConfig
MCP サーバーの設定。
type McpServerConfig =
| McpStdioServerConfig
| McpSSEServerConfig
| McpHttpServerConfig
| McpSdkServerConfigWithInstance;
McpStdioServerConfig
type McpStdioServerConfig = {
type?: "stdio";
command: string;
args?: string[];
env?: Record<string, string>;
};
McpSSEServerConfig
type McpSSEServerConfig = {
type: "sse";
url: string;
headers?: Record<string, string>;
};
McpHttpServerConfig
type McpHttpServerConfig = {
type: "http";
url: string;
headers?: Record<string, string>;
};
McpSdkServerConfigWithInstance
type McpSdkServerConfigWithInstance = {
type: "sdk";
name: string;
instance: McpServer;
};
McpClaudeAIProxyServerConfig
type McpClaudeAIProxyServerConfig = {
type: "claudeai-proxy";
url: string;
id: string;
};
SdkPluginConfig
SDK でプラグインをロードするための設定。
type SdkPluginConfig = {
type: "local";
path: string;
};
| フィールド | 型 | 説明 |
|---|
type | 'local' | 'local' である必要があります(現在ローカルプラグインのみサポート) |
path | string | プラグインディレクトリへの絶対パスまたは相対パス |
例:
plugins: [
{ type: "local", path: "./my-plugin" },
{ type: "local", path: "/absolute/path/to/plugin" }
];
プラグインの作成と使用に関する完全な情報については、プラグイン を参照してください。
メッセージ型
SDKMessage
クエリによって返されるすべての可能なメッセージの共用体型。
type SDKMessage =
| SDKAssistantMessage
| SDKUserMessage
| SDKUserMessageReplay
| SDKResultMessage
| SDKSystemMessage
| SDKPartialAssistantMessage
| SDKCompactBoundaryMessage
| SDKStatusMessage
| SDKLocalCommandOutputMessage
| SDKHookStartedMessage
| SDKHookProgressMessage
| SDKHookResponseMessage
| SDKPluginInstallMessage
| SDKToolProgressMessage
| SDKAuthStatusMessage
| SDKTaskNotificationMessage
| SDKTaskStartedMessage
| SDKTaskProgressMessage
| SDKFilesPersistedEvent
| SDKToolUseSummaryMessage
| SDKRateLimitEvent
| SDKPromptSuggestionMessage;
SDKAssistantMessage
アシスタント応答メッセージ。
type SDKAssistantMessage = {
type: "assistant";
uuid: UUID;
session_id: string;
message: BetaMessage; // Anthropic SDK から
parent_tool_use_id: string | null;
error?: SDKAssistantMessageError;
};
message フィールドは Anthropic SDK の BetaMessage です。id、content、model、stop_reason、usage などのフィールドを含みます。
SDKAssistantMessageError は以下のいずれかです:'authentication_failed'、'billing_error'、'rate_limit'、'invalid_request'、'server_error'、'max_output_tokens'、または 'unknown'。
SDKUserMessage
ユーザー入力メッセージ。
type SDKUserMessage = {
type: "user";
uuid?: UUID;
session_id: string;
message: MessageParam; // Anthropic SDK から
parent_tool_use_id: string | null;
isSynthetic?: boolean;
shouldQuery?: boolean;
tool_use_result?: unknown;
};
shouldQuery を false に設定して、アシスタントターンをトリガーせずにメッセージをトランスクリプトに追加します。メッセージは保持され、ターンをトリガーする次のユーザーメッセージにマージされます。これを使用して、バンドで実行したコマンドの出力など、モデル呼び出しを費やさずにコンテキストを注入します。
SDKUserMessageReplay
必須 UUID を含む再生されたユーザーメッセージ。
type SDKUserMessageReplay = {
type: "user";
uuid: UUID;
session_id: string;
message: MessageParam;
parent_tool_use_id: string | null;
isSynthetic?: boolean;
tool_use_result?: unknown;
isReplay: true;
};
SDKResultMessage
最終結果メッセージ。
type SDKResultMessage =
| {
type: "result";
subtype: "success";
uuid: UUID;
session_id: string;
duration_ms: number;
duration_api_ms: number;
is_error: boolean;
num_turns: number;
result: string;
stop_reason: string | null;
total_cost_usd: number;
usage: NonNullableUsage;
modelUsage: { [modelName: string]: ModelUsage };
permission_denials: SDKPermissionDenial[];
structured_output?: unknown;
}
| {
type: "result";
subtype:
| "error_max_turns"
| "error_during_execution"
| "error_max_budget_usd"
| "error_max_structured_output_retries";
uuid: UUID;
session_id: string;
duration_ms: number;
duration_api_ms: number;
is_error: boolean;
num_turns: number;
stop_reason: string | null;
total_cost_usd: number;
usage: NonNullableUsage;
modelUsage: { [modelName: string]: ModelUsage };
permission_denials: SDKPermissionDenial[];
errors: string[];
};
SDKSystemMessage
システム初期化メッセージ。
type SDKSystemMessage = {
type: "system";
subtype: "init";
uuid: UUID;
session_id: string;
agents?: string[];
apiKeySource: ApiKeySource;
betas?: string[];
claude_code_version: string;
cwd: string;
tools: string[];
mcp_servers: {
name: string;
status: string;
}[];
model: string;
permissionMode: PermissionMode;
slash_commands: string[];
output_style: string;
skills: string[];
plugins: { name: string; path: string }[];
};
SDKPartialAssistantMessage
ストリーミング部分メッセージ(includePartialMessages が true の場合のみ)。
type SDKPartialAssistantMessage = {
type: "stream_event";
event: BetaRawMessageStreamEvent; // Anthropic SDK から
parent_tool_use_id: string | null;
uuid: UUID;
session_id: string;
};
SDKCompactBoundaryMessage
会話圧縮境界を示すメッセージ。
type SDKCompactBoundaryMessage = {
type: "system";
subtype: "compact_boundary";
uuid: UUID;
session_id: string;
compact_metadata: {
trigger: "manual" | "auto";
pre_tokens: number;
};
};
SDKPluginInstallMessage
プラグインインストール進捗イベント。CLAUDE_CODE_SYNC_PLUGIN_INSTALL が設定されている場合に発行されるため、Agent SDK アプリケーションは最初のターンの前にマーケットプレイスプラグインのインストールを追跡できます。started と completed ステータスは全体的なインストールをブラケットします。installed と failed ステータスは個別のマーケットプレイスをレポートし、name を含みます。
type SDKPluginInstallMessage = {
type: "system";
subtype: "plugin_install";
status: "started" | "installed" | "failed" | "completed";
name?: string;
error?: string;
uuid: UUID;
session_id: string;
};
SDKPermissionDenial
拒否されたツール使用に関する情報。
type SDKPermissionDenial = {
tool_name: string;
tool_use_id: string;
tool_input: Record<string, unknown>;
};
フック型
フックの使用に関する包括的なガイド、例、一般的なパターンについては、フックガイド を参照してください。
HookEvent
利用可能なフックイベント。
type HookEvent =
| "PreToolUse"
| "PostToolUse"
| "PostToolUseFailure"
| "Notification"
| "UserPromptSubmit"
| "SessionStart"
| "SessionEnd"
| "Stop"
| "SubagentStart"
| "SubagentStop"
| "PreCompact"
| "PermissionRequest"
| "Setup"
| "TeammateIdle"
| "TaskCompleted"
| "ConfigChange"
| "WorktreeCreate"
| "WorktreeRemove";
HookCallback
フックコールバック関数型。
type HookCallback = (
input: HookInput, // すべてのフック入力型の共用体
toolUseID: string | undefined,
options: { signal: AbortSignal }
) => Promise<HookJSONOutput>;
HookCallbackMatcher
オプションのマッチャーを含むフック設定。
interface HookCallbackMatcher {
matcher?: string;
hooks: HookCallback[];
timeout?: number; // このマッチャーのすべてのフックのタイムアウト(秒)
}
すべてのフック入力型の共用体型。
type HookInput =
| PreToolUseHookInput
| PostToolUseHookInput
| PostToolUseFailureHookInput
| NotificationHookInput
| UserPromptSubmitHookInput
| SessionStartHookInput
| SessionEndHookInput
| StopHookInput
| SubagentStartHookInput
| SubagentStopHookInput
| PreCompactHookInput
| PermissionRequestHookInput
| SetupHookInput
| TeammateIdleHookInput
| TaskCompletedHookInput
| ConfigChangeHookInput
| WorktreeCreateHookInput
| WorktreeRemoveHookInput;
すべてのフック入力型が拡張する基本インターフェース。
type BaseHookInput = {
session_id: string;
transcript_path: string;
cwd: string;
permission_mode?: string;
agent_id?: string;
agent_type?: string;
};
type PreToolUseHookInput = BaseHookInput & {
hook_event_name: "PreToolUse";
tool_name: string;
tool_input: unknown;
tool_use_id: string;
};
PostToolUseHookInput
type PostToolUseHookInput = BaseHookInput & {
hook_event_name: "PostToolUse";
tool_name: string;
tool_input: unknown;
tool_response: unknown;
tool_use_id: string;
};
PostToolUseFailureHookInput
type PostToolUseFailureHookInput = BaseHookInput & {
hook_event_name: "PostToolUseFailure";
tool_name: string;
tool_input: unknown;
tool_use_id: string;
error: string;
is_interrupt?: boolean;
};
type NotificationHookInput = BaseHookInput & {
hook_event_name: "Notification";
message: string;
title?: string;
notification_type: string;
};
type UserPromptSubmitHookInput = BaseHookInput & {
hook_event_name: "UserPromptSubmit";
prompt: string;
};
type SessionStartHookInput = BaseHookInput & {
hook_event_name: "SessionStart";
source: "startup" | "resume" | "clear" | "compact";
agent_type?: string;
model?: string;
};
type SessionEndHookInput = BaseHookInput & {
hook_event_name: "SessionEnd";
reason: ExitReason; // EXIT_REASONS 配列からの文字列
};
type StopHookInput = BaseHookInput & {
hook_event_name: "Stop";
stop_hook_active: boolean;
last_assistant_message?: string;
};
type SubagentStartHookInput = BaseHookInput & {
hook_event_name: "SubagentStart";
agent_id: string;
agent_type: string;
};
type SubagentStopHookInput = BaseHookInput & {
hook_event_name: "SubagentStop";
stop_hook_active: boolean;
agent_id: string;
agent_transcript_path: string;
agent_type: string;
last_assistant_message?: string;
};
type PreCompactHookInput = BaseHookInput & {
hook_event_name: "PreCompact";
trigger: "manual" | "auto";
custom_instructions: string | null;
};
type PermissionRequestHookInput = BaseHookInput & {
hook_event_name: "PermissionRequest";
tool_name: string;
tool_input: unknown;
permission_suggestions?: PermissionUpdate[];
};
type SetupHookInput = BaseHookInput & {
hook_event_name: "Setup";
trigger: "init" | "maintenance";
};
type TeammateIdleHookInput = BaseHookInput & {
hook_event_name: "TeammateIdle";
teammate_name: string;
team_name: string;
};
type TaskCompletedHookInput = BaseHookInput & {
hook_event_name: "TaskCompleted";
task_id: string;
task_subject: string;
task_description?: string;
teammate_name?: string;
team_name?: string;
};
type ConfigChangeHookInput = BaseHookInput & {
hook_event_name: "ConfigChange";
source:
| "user_settings"
| "project_settings"
| "local_settings"
| "policy_settings"
| "skills";
file_path?: string;
};
type WorktreeCreateHookInput = BaseHookInput & {
hook_event_name: "WorktreeCreate";
name: string;
};
type WorktreeRemoveHookInput = BaseHookInput & {
hook_event_name: "WorktreeRemove";
worktree_path: string;
};
HookJSONOutput
フック戻り値。
type HookJSONOutput = AsyncHookJSONOutput | SyncHookJSONOutput;
AsyncHookJSONOutput
type AsyncHookJSONOutput = {
async: true;
asyncTimeout?: number;
};
SyncHookJSONOutput
type SyncHookJSONOutput = {
continue?: boolean;
suppressOutput?: boolean;
stopReason?: string;
decision?: "approve" | "block";
systemMessage?: string;
reason?: string;
hookSpecificOutput?:
| {
hookEventName: "PreToolUse";
permissionDecision?: "allow" | "deny" | "ask";
permissionDecisionReason?: string;
updatedInput?: Record<string, unknown>;
additionalContext?: string;
}
| {
hookEventName: "UserPromptSubmit";
additionalContext?: string;
}
| {
hookEventName: "SessionStart";
additionalContext?: string;
}
| {
hookEventName: "Setup";
additionalContext?: string;
}
| {
hookEventName: "SubagentStart";
additionalContext?: string;
}
| {
hookEventName: "PostToolUse";
additionalContext?: string;
updatedMCPToolOutput?: unknown;
}
| {
hookEventName: "PostToolUseFailure";
additionalContext?: string;
}
| {
hookEventName: "Notification";
additionalContext?: string;
}
| {
hookEventName: "PermissionRequest";
decision:
| {
behavior: "allow";
updatedInput?: Record<string, unknown>;
updatedPermissions?: PermissionUpdate[];
}
| {
behavior: "deny";
message?: string;
interrupt?: boolean;
};
};
};
ツール入力型
すべての組み込み Claude Code ツールの入力スキーマのドキュメント。これらの型は @anthropic-ai/claude-agent-sdk からエクスポートされ、タイプセーフなツール相互作用に使用できます。
すべてのツール入力型の共用体。@anthropic-ai/claude-agent-sdk からエクスポートされます。
type ToolInputSchemas =
| AgentInput
| AskUserQuestionInput
| BashInput
| TaskOutputInput
| ConfigInput
| EnterWorktreeInput
| ExitPlanModeInput
| FileEditInput
| FileReadInput
| FileWriteInput
| GlobInput
| GrepInput
| ListMcpResourcesInput
| McpInput
| MonitorInput
| NotebookEditInput
| ReadMcpResourceInput
| SubscribeMcpResourceInput
| SubscribePollingInput
| TaskStopInput
| TodoWriteInput
| UnsubscribeMcpResourceInput
| UnsubscribePollingInput
| WebFetchInput
| WebSearchInput;
Agent
ツール名: Agent(以前は Task。これはまだエイリアスとして受け入れられます)
type AgentInput = {
description: string;
prompt: string;
subagent_type: string;
model?: "sonnet" | "opus" | "haiku";
resume?: string;
run_in_background?: boolean;
max_turns?: number;
name?: string;
team_name?: string;
mode?: "acceptEdits" | "bypassPermissions" | "default" | "dontAsk" | "plan";
isolation?: "worktree";
};
複雑なマルチステップタスクを自律的に処理する新しいエージェントを起動します。
AskUserQuestion
ツール名: AskUserQuestion
type AskUserQuestionInput = {
questions: Array<{
question: string;
header: string;
options: Array<{ label: string; description: string; preview?: string }>;
multiSelect: boolean;
}>;
};
実行中にユーザーに明確化の質問をします。使用方法の詳細については、承認とユーザー入力を処理 を参照してください。
Bash
ツール名: Bash
type BashInput = {
command: string;
timeout?: number;
description?: string;
run_in_background?: boolean;
dangerouslyDisableSandbox?: boolean;
};
オプションのタイムアウトとバックグラウンド実行を備えた永続的なシェルセッションで bash コマンドを実行します。
Monitor
ツール名: Monitor
type MonitorInput = {
command: string;
description: string;
timeout_ms?: number;
persistent?: boolean;
};
バックグラウンドスクリプトを実行し、各 stdout 行を Claude にイベントとして配信するため、ポーリングなしで反応できます。persistent: true をセッション長のウォッチ(ログテールなど)に設定します。Monitor は Bash と同じパーミッションルールに従います。動作とプロバイダーの可用性については、Monitor ツールリファレンス を参照してください。
TaskOutput
ツール名: TaskOutput
type TaskOutputInput = {
task_id: string;
block: boolean;
timeout: number;
};
実行中または完了したバックグラウンドタスクから出力を取得します。
Edit
ツール名: Edit
type FileEditInput = {
file_path: string;
old_string: string;
new_string: string;
replace_all?: boolean;
};
ファイル内で正確な文字列置換を実行します。
Read
ツール名: Read
type FileReadInput = {
file_path: string;
offset?: number;
limit?: number;
pages?: string;
};
テキスト、画像、PDF、Jupyter ノートブックを含むローカルファイルシステムからファイルを読み取ります。PDF ページ範囲には pages を使用します(例:"1-5")。
Write
ツール名: Write
type FileWriteInput = {
file_path: string;
content: string;
};
ローカルファイルシステムにファイルを書き込み、存在する場合は上書きします。
Glob
ツール名: Glob
type GlobInput = {
pattern: string;
path?: string;
};
任意のコードベースサイズで機能する高速ファイルパターンマッチング。
Grep
ツール名: Grep
type GrepInput = {
pattern: string;
path?: string;
glob?: string;
type?: string;
output_mode?: "content" | "files_with_matches" | "count";
"-i"?: boolean;
"-n"?: boolean;
"-B"?: number;
"-A"?: number;
"-C"?: number;
context?: number;
head_limit?: number;
offset?: number;
multiline?: boolean;
};
ripgrep に基づいた正規表現サポート付きの強力な検索ツール。
TaskStop
ツール名: TaskStop
type TaskStopInput = {
task_id?: string;
shell_id?: string; // 非推奨:task_id を使用
};
ID でバックグラウンドタスクまたはシェルを停止します。
NotebookEdit
ツール名: NotebookEdit
type NotebookEditInput = {
notebook_path: string;
cell_id?: string;
new_source: string;
cell_type?: "code" | "markdown";
edit_mode?: "replace" | "insert" | "delete";
};
Jupyter ノートブックファイルのセルを編集します。
WebFetch
ツール名: WebFetch
type WebFetchInput = {
url: string;
prompt: string;
};
URL からコンテンツを取得し、AI モデルで処理します。
WebSearch
ツール名: WebSearch
type WebSearchInput = {
query: string;
allowed_domains?: string[];
blocked_domains?: string[];
};
ウェブを検索し、フォーマットされた結果を返します。
TodoWrite
ツール名: TodoWrite
type TodoWriteInput = {
todos: Array<{
content: string;
status: "pending" | "in_progress" | "completed";
activeForm: string;
}>;
};
進捗を追跡するための構造化タスクリストを作成および管理します。
ExitPlanMode
ツール名: ExitPlanMode
type ExitPlanModeInput = {
allowedPrompts?: Array<{
tool: "Bash";
prompt: string;
}>;
};
計画モードを終了します。オプションで、計画を実装するために必要なプロンプトベースのパーミッションを指定します。
ListMcpResources
ツール名: ListMcpResources
type ListMcpResourcesInput = {
server?: string;
};
接続されたサーバーから利用可能な MCP リソースをリストします。
ReadMcpResource
ツール名: ReadMcpResource
type ReadMcpResourceInput = {
server: string;
uri: string;
};
サーバーから特定の MCP リソースを読み取ります。
Config
ツール名: Config
type ConfigInput = {
setting: string;
value?: string | boolean | number;
};
設定値を取得または設定します。
EnterWorktree
ツール名: EnterWorktree
type EnterWorktreeInput = {
name?: string;
path?: string;
};
分離された作業用の一時的な git worktree を作成して入力します。新しい worktree を作成する代わりに、現在のリポジトリの既存の worktree に切り替えるには path を渡します。name と path は相互に排他的です。
ツール出力型
すべての組み込み Claude Code ツールの出力スキーマのドキュメント。これらの型は @anthropic-ai/claude-agent-sdk からエクスポートされ、各ツールによって返される実際の応答データを表します。
すべてのツール出力型の共用体。
type ToolOutputSchemas =
| AgentOutput
| AskUserQuestionOutput
| BashOutput
| ConfigOutput
| EnterWorktreeOutput
| ExitPlanModeOutput
| FileEditOutput
| FileReadOutput
| FileWriteOutput
| GlobOutput
| GrepOutput
| ListMcpResourcesOutput
| MonitorOutput
| NotebookEditOutput
| ReadMcpResourceOutput
| TaskStopOutput
| TodoWriteOutput
| WebFetchOutput
| WebSearchOutput;
Agent
ツール名: Agent(以前は Task。これはまだエイリアスとして受け入れられます)
type AgentOutput =
| {
status: "completed";
agentId: string;
content: Array<{ type: "text"; text: string }>;
totalToolUseCount: number;
totalDurationMs: number;
totalTokens: number;
usage: {
input_tokens: number;
output_tokens: number;
cache_creation_input_tokens: number | null;
cache_read_input_tokens: number | null;
server_tool_use: {
web_search_requests: number;
web_fetch_requests: number;
} | null;
service_tier: ("standard" | "priority" | "batch") | null;
cache_creation: {
ephemeral_1h_input_tokens: number;
ephemeral_5m_input_tokens: number;
} | null;
};
prompt: string;
}
| {
status: "async_launched";
agentId: string;
description: string;
prompt: string;
outputFile: string;
canReadOutputFile?: boolean;
}
| {
status: "sub_agent_entered";
description: string;
message: string;
};
サブエージェントからの結果を返します。status フィールドで判別されます:完了したタスクの場合は "completed"、バックグラウンドタスクの場合は "async_launched"、インタラクティブサブエージェントの場合は "sub_agent_entered"。
AskUserQuestion
ツール名: AskUserQuestion
type AskUserQuestionOutput = {
questions: Array<{
question: string;
header: string;
options: Array<{ label: string; description: string; preview?: string }>;
multiSelect: boolean;
}>;
answers: Record<string, string>;
};
質問とユーザーの回答を返します。
Bash
ツール名: Bash
type BashOutput = {
stdout: string;
stderr: string;
rawOutputPath?: string;
interrupted: boolean;
isImage?: boolean;
backgroundTaskId?: string;
backgroundedByUser?: boolean;
dangerouslyDisableSandbox?: boolean;
returnCodeInterpretation?: string;
structuredContent?: unknown[];
persistedOutputPath?: string;
persistedOutputSize?: number;
};
stdout/stderr が分割されたコマンド出力を返します。バックグラウンドコマンドには backgroundTaskId が含まれます。
Monitor
ツール名: Monitor
type MonitorOutput = {
taskId: string;
timeoutMs: number;
persistent?: boolean;
};
実行中のモニターのバックグラウンドタスク ID を返します。この ID を TaskStop で使用して、ウォッチを早期にキャンセルします。
Edit
ツール名: Edit
type FileEditOutput = {
filePath: string;
oldString: string;
newString: string;
originalFile: string;
structuredPatch: Array<{
oldStart: number;
oldLines: number;
newStart: number;
newLines: number;
lines: string[];
}>;
userModified: boolean;
replaceAll: boolean;
gitDiff?: {
filename: string;
status: "modified" | "added";
additions: number;
deletions: number;
changes: number;
patch: string;
};
};
編集操作の構造化された diff を返します。
Read
ツール名: Read
type FileReadOutput =
| {
type: "text";
file: {
filePath: string;
content: string;
numLines: number;
startLine: number;
totalLines: number;
};
}
| {
type: "image";
file: {
base64: string;
type: "image/jpeg" | "image/png" | "image/gif" | "image/webp";
originalSize: number;
dimensions?: {
originalWidth?: number;
originalHeight?: number;
displayWidth?: number;
displayHeight?: number;
};
};
}
| {
type: "notebook";
file: {
filePath: string;
cells: unknown[];
};
}
| {
type: "pdf";
file: {
filePath: string;
base64: string;
originalSize: number;
};
}
| {
type: "parts";
file: {
filePath: string;
originalSize: number;
count: number;
outputDir: string;
};
};
ファイルタイプに適切な形式でファイルコンテンツを返します。type フィールドで判別されます。
Write
ツール名: Write
type FileWriteOutput = {
type: "create" | "update";
filePath: string;
content: string;
structuredPatch: Array<{
oldStart: number;
oldLines: number;
newStart: number;
newLines: number;
lines: string[];
}>;
originalFile: string | null;
gitDiff?: {
filename: string;
status: "modified" | "added";
additions: number;
deletions: number;
changes: number;
patch: string;
};
};
構造化された diff 情報を含む書き込み結果を返します。
Glob
ツール名: Glob
type GlobOutput = {
durationMs: number;
numFiles: number;
filenames: string[];
truncated: boolean;
};
glob パターンに一致するファイルパスを返します。変更時刻でソートされます。
Grep
ツール名: Grep
type GrepOutput = {
mode?: "content" | "files_with_matches" | "count";
numFiles: number;
filenames: string[];
content?: string;
numLines?: number;
numMatches?: number;
appliedLimit?: number;
appliedOffset?: number;
};
検索結果を返します。形状は mode によって異なります:ファイルリスト、マッチを含むコンテンツ、またはマッチ数。
TaskStop
ツール名: TaskStop
type TaskStopOutput = {
message: string;
task_id: string;
task_type: string;
command?: string;
};
バックグラウンドタスクを停止した後の確認を返します。
NotebookEdit
ツール名: NotebookEdit
type NotebookEditOutput = {
new_source: string;
cell_id?: string;
cell_type: "code" | "markdown";
language: string;
edit_mode: string;
error?: string;
notebook_path: string;
original_file: string;
updated_file: string;
};
元のファイルと更新されたファイルコンテンツを含むノートブック編集の結果を返します。
WebFetch
ツール名: WebFetch
type WebFetchOutput = {
bytes: number;
code: number;
codeText: string;
result: string;
durationMs: number;
url: string;
};
HTTP ステータスとメタデータを含む取得されたコンテンツを返します。
WebSearch
ツール名: WebSearch
type WebSearchOutput = {
query: string;
results: Array<
| {
tool_use_id: string;
content: Array<{ title: string; url: string }>;
}
| string
>;
durationSeconds: number;
};
ウェブからの検索結果を返します。
TodoWrite
ツール名: TodoWrite
type TodoWriteOutput = {
oldTodos: Array<{
content: string;
status: "pending" | "in_progress" | "completed";
activeForm: string;
}>;
newTodos: Array<{
content: string;
status: "pending" | "in_progress" | "completed";
activeForm: string;
}>;
};
前のタスクリストと更新されたタスクリストを返します。
ExitPlanMode
ツール名: ExitPlanMode
type ExitPlanModeOutput = {
plan: string | null;
isAgent: boolean;
filePath?: string;
hasTaskTool?: boolean;
awaitingLeaderApproval?: boolean;
requestId?: string;
};
計画モード終了後の計画状態を返します。
ListMcpResources
ツール名: ListMcpResources
type ListMcpResourcesOutput = Array<{
uri: string;
name: string;
mimeType?: string;
description?: string;
server: string;
}>;
利用可能な MCP リソースの配列を返します。
ReadMcpResource
ツール名: ReadMcpResource
type ReadMcpResourceOutput = {
contents: Array<{
uri: string;
mimeType?: string;
text?: string;
}>;
};
要求された MCP リソースのコンテンツを返します。
Config
ツール名: Config
type ConfigOutput = {
success: boolean;
operation?: "get" | "set";
setting?: string;
value?: unknown;
previousValue?: unknown;
newValue?: unknown;
error?: string;
};
設定の取得または設定操作の結果を返します。
EnterWorktree
ツール名: EnterWorktree
type EnterWorktreeOutput = {
worktreePath: string;
worktreeBranch?: string;
message: string;
};
git worktree に関する情報を返します。
パーミッション型
PermissionUpdate
パーミッション更新の操作。
type PermissionUpdate =
| {
type: "addRules";
rules: PermissionRuleValue[];
behavior: PermissionBehavior;
destination: PermissionUpdateDestination;
}
| {
type: "replaceRules";
rules: PermissionRuleValue[];
behavior: PermissionBehavior;
destination: PermissionUpdateDestination;
}
| {
type: "removeRules";
rules: PermissionRuleValue[];
behavior: PermissionBehavior;
destination: PermissionUpdateDestination;
}
| {
type: "setMode";
mode: PermissionMode;
destination: PermissionUpdateDestination;
}
| {
type: "addDirectories";
directories: string[];
destination: PermissionUpdateDestination;
}
| {
type: "removeDirectories";
directories: string[];
destination: PermissionUpdateDestination;
};
PermissionBehavior
type PermissionBehavior = "allow" | "deny" | "ask";
PermissionUpdateDestination
type PermissionUpdateDestination =
| "userSettings" // グローバルユーザー設定
| "projectSettings" // ディレクトリごとのプロジェクト設定
| "localSettings" // Gitignored ローカル設定
| "session" // 現在のセッションのみ
| "cliArg"; // CLI 引数
PermissionRuleValue
type PermissionRuleValue = {
toolName: string;
ruleContent?: string;
};
その他の型
ApiKeySource
type ApiKeySource = "user" | "project" | "org" | "temporary" | "oauth";
SdkBeta
betas オプション経由で有効にできる利用可能なベータ機能。詳細は ベータヘッダー を参照してください。
type SdkBeta = "context-1m-2025-08-07";
context-1m-2025-08-07 ベータは 2026 年 4 月 30 日時点で廃止されました。Claude Sonnet 4.5 または Sonnet 4 でこの値を渡すと効果がなく、標準 200k トークンコンテキストウィンドウを超えるリクエストはエラーを返します。1M トークンコンテキストウィンドウを使用するには、Claude Sonnet 4.6、Claude Opus 4.6、または Claude Opus 4.7 に移行してください。これらには、ベータヘッダーなしで標準価格で 1M コンテキストが含まれます。
SlashCommand
利用可能なスラッシュコマンドに関する情報。
type SlashCommand = {
name: string;
description: string;
argumentHint: string;
};
ModelInfo
利用可能なモデルに関する情報。
type ModelInfo = {
value: string;
displayName: string;
description: string;
supportsEffort?: boolean;
supportedEffortLevels?: ("low" | "medium" | "high" | "xhigh" | "max")[];
supportsAdaptiveThinking?: boolean;
supportsFastMode?: boolean;
};
AgentInfo
Agent ツール経由で呼び出すことができる利用可能なサブエージェントに関する情報。
type AgentInfo = {
name: string;
description: string;
model?: string;
};
| フィールド | 型 | 説明 |
|---|
name | string | エージェント型識別子(例:"Explore"、"general-purpose") |
description | string | このエージェントをいつ使用するかの説明 |
model | string | undefined | このエージェントが使用するモデルエイリアス。省略すると、親のモデルを継承します |
McpServerStatus
接続された MCP サーバーのステータス。
type McpServerStatus = {
name: string;
status: "connected" | "failed" | "needs-auth" | "pending" | "disabled";
serverInfo?: {
name: string;
version: string;
};
error?: string;
config?: McpServerStatusConfig;
scope?: string;
tools?: {
name: string;
description?: string;
annotations?: {
readOnly?: boolean;
destructive?: boolean;
openWorld?: boolean;
};
}[];
};
McpServerStatusConfig
mcpServerStatus() によってレポートされた MCP サーバーの設定。これはすべての MCP サーバートランスポートタイプの共用体です。
type McpServerStatusConfig =
| McpStdioServerConfig
| McpSSEServerConfig
| McpHttpServerConfig
| McpSdkServerConfig
| McpClaudeAIProxyServerConfig;
各トランスポートタイプの詳細については、McpServerConfig を参照してください。
AccountInfo
認証されたユーザーのアカウント情報。
type AccountInfo = {
email?: string;
organization?: string;
subscriptionType?: string;
tokenSource?: string;
apiKeySource?: string;
};
ModelUsage
結果メッセージで返されるモデルごとの使用統計。costUSD 値はクライアント側の推定です。請求に関する注意事項については、コストと使用状況を追跡 を参照してください。
type ModelUsage = {
inputTokens: number;
outputTokens: number;
cacheReadInputTokens: number;
cacheCreationInputTokens: number;
webSearchRequests: number;
costUSD: number;
contextWindow: number;
maxOutputTokens: number;
};
ConfigScope
type ConfigScope = "local" | "user" | "project";
NonNullableUsage
すべての nullable フィールドが non-nullable になった Usage のバージョン。
type NonNullableUsage = {
[K in keyof Usage]: NonNullable<Usage[K]>;
};
Usage
トークン使用統計(@anthropic-ai/sdk から)。
type Usage = {
input_tokens: number | null;
output_tokens: number | null;
cache_creation_input_tokens?: number | null;
cache_read_input_tokens?: number | null;
};
MCP ツール結果型(@modelcontextprotocol/sdk/types.js から)。
type CallToolResult = {
content: Array<{
type: "text" | "image" | "resource";
// 追加フィールドはタイプによって異なります
}>;
isError?: boolean;
};
ThinkingConfig
Claude の思考/推論動作を制御します。非推奨の maxThinkingTokens より優先されます。
type ThinkingConfig =
| { type: "adaptive" } // モデルが推論のタイミングと量を決定します(Opus 4.6 以降)
| { type: "enabled"; budgetTokens?: number } // 固定思考トークン予算
| { type: "disabled" }; // 拡張思考なし
SpawnedProcess
カスタムプロセススポーニング用のインターフェース(spawnClaudeCodeProcess オプションで使用)。ChildProcess は既にこのインターフェースを満たしています。
interface SpawnedProcess {
stdin: Writable;
stdout: Readable;
readonly killed: boolean;
readonly exitCode: number | null;
kill(signal: NodeJS.Signals): boolean;
on(
event: "exit",
listener: (code: number | null, signal: NodeJS.Signals | null) => void
): void;
on(event: "error", listener: (error: Error) => void): void;
once(
event: "exit",
listener: (code: number | null, signal: NodeJS.Signals | null) => void
): void;
once(event: "error", listener: (error: Error) => void): void;
off(
event: "exit",
listener: (code: number | null, signal: NodeJS.Signals | null) => void
): void;
off(event: "error", listener: (error: Error) => void): void;
}
SpawnOptions
カスタムスポーン関数に渡されるオプション。
interface SpawnOptions {
command: string;
args: string[];
cwd?: string;
env: Record<string, string | undefined>;
signal: AbortSignal;
}
McpSetServersResult
setMcpServers() 操作の結果。
type McpSetServersResult = {
added: string[];
removed: string[];
errors: Record<string, string>;
};
RewindFilesResult
rewindFiles() 操作の結果。
type RewindFilesResult = {
canRewind: boolean;
error?: string;
filesChanged?: string[];
insertions?: number;
deletions?: number;
};
SDKStatusMessage
ステータス更新メッセージ(例:圧縮)。
type SDKStatusMessage = {
type: "system";
subtype: "status";
status: "compacting" | null;
permissionMode?: PermissionMode;
uuid: UUID;
session_id: string;
};
SDKTaskNotificationMessage
バックグラウンドタスクが完了、失敗、または停止したときの通知。バックグラウンドタスクには、run_in_background Bash コマンド、Monitor ウォッチ、バックグラウンドサブエージェントが含まれます。
type SDKTaskNotificationMessage = {
type: "system";
subtype: "task_notification";
task_id: string;
tool_use_id?: string;
status: "completed" | "failed" | "stopped";
output_file: string;
summary: string;
usage?: {
total_tokens: number;
tool_uses: number;
duration_ms: number;
};
uuid: UUID;
session_id: string;
};
会話でのツール使用のサマリー。
type SDKToolUseSummaryMessage = {
type: "tool_use_summary";
summary: string;
preceding_tool_use_ids: string[];
uuid: UUID;
session_id: string;
};
SDKHookStartedMessage
フックが実行を開始したときに発行されます。
type SDKHookStartedMessage = {
type: "system";
subtype: "hook_started";
hook_id: string;
hook_name: string;
hook_event: string;
uuid: UUID;
session_id: string;
};
SDKHookProgressMessage
フックが実行中に stdout/stderr 出力で発行されます。
type SDKHookProgressMessage = {
type: "system";
subtype: "hook_progress";
hook_id: string;
hook_name: string;
hook_event: string;
stdout: string;
stderr: string;
output: string;
uuid: UUID;
session_id: string;
};
SDKHookResponseMessage
フックが実行を終了したときに発行されます。
type SDKHookResponseMessage = {
type: "system";
subtype: "hook_response";
hook_id: string;
hook_name: string;
hook_event: string;
output: string;
stdout: string;
stderr: string;
exit_code?: number;
outcome: "success" | "error" | "cancelled";
uuid: UUID;
session_id: string;
};
ツール実行中に定期的に発行され、進捗を示します。
type SDKToolProgressMessage = {
type: "tool_progress";
tool_use_id: string;
tool_name: string;
parent_tool_use_id: string | null;
elapsed_time_seconds: number;
task_id?: string;
uuid: UUID;
session_id: string;
};
SDKAuthStatusMessage
認証フロー中に発行されます。
type SDKAuthStatusMessage = {
type: "auth_status";
isAuthenticating: boolean;
output: string[];
error?: string;
uuid: UUID;
session_id: string;
};
SDKTaskStartedMessage
バックグラウンドタスクが開始したときに発行されます。task_type フィールドは、バックグラウンド Bash コマンドと Monitor ウォッチの場合は "local_bash"、サブエージェントの場合は "local_agent"、またはリモートエージェントの場合は "remote_agent" です。
type SDKTaskStartedMessage = {
type: "system";
subtype: "task_started";
task_id: string;
tool_use_id?: string;
description: string;
task_type?: string;
uuid: UUID;
session_id: string;
};
SDKTaskProgressMessage
バックグラウンドタスクが実行中に定期的に発行されます。
type SDKTaskProgressMessage = {
type: "system";
subtype: "task_progress";
task_id: string;
tool_use_id?: string;
description: string;
usage: {
total_tokens: number;
tool_uses: number;
duration_ms: number;
};
last_tool_name?: string;
uuid: UUID;
session_id: string;
};
SDKFilesPersistedEvent
ファイルチェックポイントがディスクに永続化されたときに発行されます。
type SDKFilesPersistedEvent = {
type: "system";
subtype: "files_persisted";
files: { filename: string; file_id: string }[];
failed: { filename: string; error: string }[];
processed_at: string;
uuid: UUID;
session_id: string;
};
SDKRateLimitEvent
セッションがレート制限に遭遇したときに発行されます。
type SDKRateLimitEvent = {
type: "rate_limit_event";
rate_limit_info: {
status: "allowed" | "allowed_warning" | "rejected";
resetsAt?: number;
utilization?: number;
};
uuid: UUID;
session_id: string;
};
SDKLocalCommandOutputMessage
ローカルスラッシュコマンド(例:/voice または /cost)からの出力。トランスクリプトでアシスタント形式のテキストとして表示されます。
type SDKLocalCommandOutputMessage = {
type: "system";
subtype: "local_command_output";
content: string;
uuid: UUID;
session_id: string;
};
SDKPromptSuggestionMessage
promptSuggestions が有効な場合、各ターン後に発行されます。予測される次のユーザープロンプトを含みます。
type SDKPromptSuggestionMessage = {
type: "prompt_suggestion";
suggestion: string;
uuid: UUID;
session_id: string;
};
AbortError
中止操作のカスタムエラークラス。
class AbortError extends Error {}
サンドボックス設定
SandboxSettings
サンドボックス動作の設定。これを使用して、コマンドサンドボックスを有効にし、ネットワーク制限をプログラムで設定します。
type SandboxSettings = {
enabled?: boolean;
autoAllowBashIfSandboxed?: boolean;
excludedCommands?: string[];
allowUnsandboxedCommands?: boolean;
network?: SandboxNetworkConfig;
filesystem?: SandboxFilesystemConfig;
ignoreViolations?: Record<string, string[]>;
enableWeakerNestedSandbox?: boolean;
ripgrep?: { command: string; args?: string[] };
};
| プロパティ | 型 | デフォルト | 説明 |
|---|
enabled | boolean | false | コマンド実行のサンドボックスモードを有効にします |
autoAllowBashIfSandboxed | boolean | true | サンドボックスが有効な場合、bash コマンドを自動承認します |
excludedCommands | string[] | [] | 常にサンドボックス制限をバイパスするコマンド(例:['docker'])。これらはモデルの関与なしに自動的にサンドボックス外で実行されます |
allowUnsandboxedCommands | boolean | true | モデルがサンドボックス外でコマンドを実行するようにリクエストすることを許可します。true の場合、モデルはツール入力で dangerouslyDisableSandbox を設定でき、パーミッションシステム にフォールバックします |
network | SandboxNetworkConfig | undefined | ネットワーク固有のサンドボックス設定 |
filesystem | SandboxFilesystemConfig | undefined | 読み取り/書き込み制限のためのファイルシステム固有のサンドボックス設定 |
ignoreViolations | Record<string, string[]> | undefined | 違反カテゴリを無視するパターンのマップ(例:{ file: ['/tmp/*'], network: ['localhost'] }) |
enableWeakerNestedSandbox | boolean | false | 互換性のための弱いネストされたサンドボックスを有効にします |
ripgrep | { command: string; args?: string[] } | undefined | サンドボックス環境のカスタム ripgrep バイナリ設定 |
使用例
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "Build and test my project",
options: {
sandbox: {
enabled: true,
autoAllowBashIfSandboxed: true,
network: {
allowLocalBinding: true
}
}
}
})) {
if ("result" in message) console.log(message.result);
}
Unix ソケットセキュリティ: allowUnixSockets オプションは強力なシステムサービスへのアクセスを許可できます。例えば、/var/run/docker.sock を許可すると、Docker API 経由でホストシステムへの完全なアクセスが効果的に許可され、サンドボックス分離がバイパスされます。厳密に必要な Unix ソケットのみを許可し、各ソケットのセキュリティへの影響を理解してください。
SandboxNetworkConfig
サンドボックスモードのネットワーク固有の設定。
type SandboxNetworkConfig = {
allowedDomains?: string[];
deniedDomains?: string[];
allowManagedDomainsOnly?: boolean;
allowLocalBinding?: boolean;
allowUnixSockets?: string[];
allowAllUnixSockets?: boolean;
httpProxyPort?: number;
socksProxyPort?: number;
};
| プロパティ | 型 | デフォルト | 説明 |
|---|
allowedDomains | string[] | [] | サンドボックス化されたプロセスがアクセスできるドメイン名 |
deniedDomains | string[] | [] | サンドボックス化されたプロセスがアクセスできないドメイン名。allowedDomains より優先されます |
allowManagedDomainsOnly | boolean | false | ネットワークアクセスを allowedDomains のドメインのみに制限します |
allowLocalBinding | boolean | false | プロセスがローカルポートにバインドすることを許可します(例:開発サーバー) |
allowUnixSockets | string[] | [] | プロセスがアクセスできる Unix ソケットパス(例:Docker ソケット) |
allowAllUnixSockets | boolean | false | すべての Unix ソケットへのアクセスを許可します |
httpProxyPort | number | undefined | ネットワークリクエスト用の HTTP プロキシポート |
socksProxyPort | number | undefined | ネットワークリクエスト用の SOCKS プロキシポート |
SandboxFilesystemConfig
サンドボックスモードのファイルシステム固有の設定。
type SandboxFilesystemConfig = {
allowWrite?: string[];
denyWrite?: string[];
denyRead?: string[];
};
| プロパティ | 型 | デフォルト | 説明 |
|---|
allowWrite | string[] | [] | 書き込みアクセスを許可するファイルパターン |
denyWrite | string[] | [] | 書き込みアクセスを拒否するファイルパターン |
denyRead | string[] | [] | 読み取りアクセスを拒否するファイルパターン |
サンドボックス外コマンドのパーミッションフォールバック
allowUnsandboxedCommands が有効な場合、モデルはツール入力で dangerouslyDisableSandbox: true を設定することで、サンドボックス外でコマンドを実行するようにリクエストできます。これらのリクエストは既存のパーミッションシステムにフォールバックします。つまり、canUseTool ハンドラーが呼び出され、カスタム認可ロジックを実装できます。
excludedCommands vs allowUnsandboxedCommands:
excludedCommands:常にサンドボックスを自動的にバイパスするコマンドの静的リスト(例:['docker'])。モデルはこれを制御できません。
allowUnsandboxedCommands:モデルがツール入力で dangerouslyDisableSandbox: true を設定することで、実行時にサンドボックス外実行をリクエストすることを許可します。
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "Deploy my application",
options: {
sandbox: {
enabled: true,
allowUnsandboxedCommands: true // モデルはサンドボックス外実行をリクエストできます
},
permissionMode: "default",
canUseTool: async (tool, input) => {
// モデルがサンドボックスをバイパスするようにリクエストしているかチェック
if (tool === "Bash" && input.dangerouslyDisableSandbox) {
// モデルはこのコマンドをサンドボックス外で実行するようにリクエストしています
console.log(`Unsandboxed command requested: ${input.command}`);
if (isCommandAuthorized(input.command)) {
return { behavior: "allow" as const, updatedInput: input };
}
return {
behavior: "deny" as const,
message: "Command not authorized for unsandboxed execution"
};
}
return { behavior: "allow" as const, updatedInput: input };
}
}
})) {
if ("result" in message) console.log(message.result);
}
このパターンにより、以下が可能になります:
- モデルリクエストを監査: モデルがサンドボックス外実行をリクエストしたときにログします
- 許可リストを実装: 特定のコマンドのみがサンドボックス外で実行されることを許可します
- 承認ワークフローを追加: 特権操作に明示的な認可を要求します
dangerouslyDisableSandbox: true で実行されるコマンドはシステムへの完全なアクセスを持ちます。canUseTool ハンドラーがこれらのリクエストを慎重に検証することを確認してください。permissionMode が bypassPermissions に設定され、allowUnsandboxedCommands が有効な場合、モデルは承認プロンプトなしにサンドボックス外でコマンドを自律的に実行できます。この組み合わせにより、モデルはサンドボックス分離を静かにエスケープできます。
関連項目