概要
この章では、Claude Agent SDKのTypeScript実装について詳しく解説します。
TypeScript SDKは、型安全性を活かした堅牢なAgent開発を可能にします。
query()関数を中心としたAPIリファレンス、オプション設定、メッセージタイプ、Hookの使い方を理解することで、本格的なAgentアプリケーションを構築できます。
インストール
npmを使用してTypeScript SDKをインストールします。
npm install @anthropic-ai/claude-agent-sdkこのコマンドでnpmレジストリから@anthropic-ai/claude-agent-sdkパッケージをインストールします。
Node.js 18以上が必要です。
query関数
query()は、Claude Agent SDKの主要なエントリーポイントです。
非同期ジェネレータとしてメッセージをストリーミングで返します。
基本的な使い方
query()関数の基本的な使い方を以下に示します。
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "auth.pyのバグを見つけて修正してください",
options: { allowedTools: ["Read", "Edit", "Bash"] }
})) {
console.log(message);
}このコードはfor await...of構文で非同期イテレータを処理します。
promptにタスクの指示を、optionsに設定を渡します。
Claudeがファイルを読み、バグを見つけ、修正する過程がストリーミングで返されます。
関数シグネチャ
query()関数のシグネチャを以下に示します。
function query({
prompt,
options
}: {
prompt: string | AsyncIterable<SDKUserMessage>;
options?: Options;
}): Querypromptパラメータは文字列またはストリーミングモード用の非同期イテラブルを受け取ります。
optionsパラメータはオプションの設定オブジェクトです。
戻り値はQueryオブジェクトで、AsyncGenerator<SDKMessage, void>を拡張しています。
Optionsの詳細
Options型はquery()関数の動作を制御する設定オブジェクトです。
主要なプロパティを以下に示します。
基本設定
| プロパティ | 型 | デフォルト | 説明 |
|---|---|---|---|
model |
string |
CLIのデフォルト | 使用するClaudeモデル |
cwd |
string |
process.cwd() |
作業ディレクトリ |
systemPrompt |
string | object |
undefined |
システムプロンプト設定 |
maxTurns |
number |
undefined |
最大会話ターン数 |
maxBudgetUsd |
number |
undefined |
最大予算(USD) |
ツール設定
| プロパティ | 型 | デフォルト | 説明 |
|---|---|---|---|
allowedTools |
string[] |
全ツール | 許可するツール名のリスト |
disallowedTools |
string[] |
[] |
禁止するツール名のリスト |
tools |
string[] | object |
undefined |
ツール設定(プリセット対応) |
権限設定
| プロパティ | 型 | デフォルト | 説明 |
|---|---|---|---|
permissionMode |
PermissionMode |
'default' |
権限モード |
canUseTool |
CanUseTool |
undefined |
カスタム権限関数 |
allowDangerouslySkipPermissions |
boolean |
false |
権限バイパスの有効化 |
セッション設定
| プロパティ | 型 | デフォルト | 説明 |
|---|---|---|---|
resume |
string |
undefined |
再開するセッションID |
forkSession |
boolean |
false |
セッションをフォークして新IDで継続 |
continue |
boolean |
false |
直近の会話を継続 |
MCP設定
| プロパティ | 型 | デフォルト | 説明 |
|---|---|---|---|
mcpServers |
Record<string, McpServerConfig> |
{} |
MCPサーバー設定 |
strictMcpConfig |
boolean |
false |
厳密なMCPバリデーション |
Subagent設定
| プロパティ | 型 | デフォルト | 説明 |
|---|---|---|---|
agents |
Record<string, AgentDefinition> |
undefined |
Subagentの定義 |
Hook設定
| プロパティ | 型 | デフォルト | 説明 |
|---|---|---|---|
hooks |
Partial<Record<HookEvent, HookCallbackMatcher[]>> |
{} |
Hookコールバック |
実行環境設定
| プロパティ | 型 | デフォルト | 説明 |
|---|---|---|---|
abortController |
AbortController |
new AbortController() |
操作キャンセル用コントローラ |
additionalDirectories |
string[] |
[] |
Claudeがアクセスできる追加ディレクトリ |
env |
Dict<string> |
process.env |
環境変数 |
executable |
'bun' | 'deno' | 'node' |
自動検出 | JavaScriptランタイム |
executableArgs |
string[] |
[] |
ランタイムへの引数 |
pathToClaudeCodeExecutable |
string |
ビルトイン | Claude Code実行ファイルのパス |
stderr |
(data: string) => void |
undefined |
stderrのコールバック |
その他の設定
| プロパティ | 型 | デフォルト | 説明 |
|---|---|---|---|
settingSources |
SettingSource[] |
[] |
読み込む設定ソース |
plugins |
SdkPluginConfig[] |
[] |
プラグイン設定 |
sandbox |
SandboxSettings |
undefined |
サンドボックス設定 |
betas |
SdkBeta[] |
[] |
ベータ機能の有効化 |
outputFormat |
object |
undefined |
構造化出力の形式 |
enableFileCheckpointing |
boolean |
false |
ファイルチェックポイント |
includePartialMessages |
boolean |
false |
部分メッセージの受信 |
extraArgs |
Record<string, string | null> |
{} |
追加引数 |
fallbackModel |
string |
undefined |
プライマリ失敗時のフォールバックモデル |
maxThinkingTokens |
number |
undefined |
思考プロセスの最大トークン数 |
permissionPromptToolName |
string |
undefined |
権限プロンプト用MCPツール名 |
resumeSessionAt |
string |
undefined |
特定メッセージUUIDからセッション再開 |
systemPromptの設定例
カスタムシステムプロンプトを設定する例を以下に示します。
import { query } from "@anthropic-ai/claude-agent-sdk";
// カスタム文字列として設定
for await (const message of query({
prompt: "コードをレビューしてください",
options: {
allowedTools: ["Read", "Glob", "Grep"],
systemPrompt: "あなたはシニアPython開発者です。常にPEP 8スタイルガイドに従ってください。"
}
})) {
if ("result" in message) console.log(message.result);
}このコードはカスタムシステムプロンプトを文字列として設定しています。 Claudeにシニア開発者としての役割を与え、特定のスタイルガイドに従うよう指示しています。
Claude Codeのシステムプロンプトを使用する例を以下に示します。
import { query } from "@anthropic-ai/claude-agent-sdk";
// Claude Codeプリセットを使用
for await (const message of query({
prompt: "プロジェクトの構造を分析してください",
options: {
systemPrompt: {
type: 'preset',
preset: 'claude_code',
append: '日本語で回答してください。'
},
settingSources: ['project'] // CLAUDE.mdを読み込む
}
})) {
if ("result" in message) console.log(message.result);
}このコードはpreset: 'claude_code'でClaude Codeのシステムプロンプトを使用し、appendで追加指示を付与しています。
settingSources: ['project']を設定することで、プロジェクトのCLAUDE.mdファイルも読み込まれます。
settingSourcesの設定
settingSourcesは、ファイルシステムから読み込む設定ソースを制御します。
type SettingSource = 'user' | 'project' | 'local';各値の意味を以下に示します。
| 値 | 説明 | 場所 |
|---|---|---|
'user' |
グローバルユーザー設定 | ~/.claude/settings.json |
'project' |
プロジェクト設定(バージョン管理対象) | .claude/settings.json |
'local' |
ローカル設定(gitignore対象) | .claude/settings.local.json |
デフォルトではsettingSourcesは空配列で、ファイルシステムから設定を読み込みません。
CLAUDE.mdを使用する場合は['project']を含める必要があります。
Queryインターフェース
query()関数が返すQueryオブジェクトは、AsyncGeneratorを拡張し、追加のメソッドを提供します。
メソッド一覧
| メソッド | 説明 |
|---|---|
interrupt() |
クエリを中断(ストリーミング入力モードのみ) |
rewindFiles(userMessageUuid) |
指定したメッセージ時点のファイル状態に復元 |
setPermissionMode(mode) |
権限モードを変更 |
setModel(model) |
モデルを変更 |
setMaxThinkingTokens(tokens) |
思考トークンの最大値を変更 |
supportedCommands() |
利用可能なスラッシュコマンドを取得 |
supportedModels() |
利用可能なモデル情報を取得 |
mcpServerStatus() |
接続中のMCPサーバーのステータスを取得 |
accountInfo() |
アカウント情報を取得 |
ファイルチェックポイントの使用例
ファイルチェックポイント機能を使用してファイルを巻き戻す例を以下に示します。
import { query } from "@anthropic-ai/claude-agent-sdk";
const q = query({
prompt: "utils.pyをリファクタリングしてください",
options: {
allowedTools: ["Read", "Edit"],
enableFileCheckpointing: true // チェックポイントを有効化
}
});
let targetUuid: string | undefined;
for await (const message of q) {
if (message.type === 'user') {
targetUuid = message.uuid; // ユーザーメッセージのUUIDを保存
}
console.log(message);
}
// 必要に応じてファイルを巻き戻し
if (targetUuid) {
await q.rewindFiles(targetUuid);
console.log('ファイルを巻き戻しました');
}このコードはenableFileCheckpointing: trueでファイル変更の追跡を有効にしています。
rewindFiles()メソッドで指定したユーザーメッセージ時点のファイル状態に復元できます。
メッセージタイプ
query()から返されるメッセージはSDKMessage型で、複数のサブタイプがあります。
SDKMessage
SDKMessageは以下の型の共用体です。
type SDKMessage =
| SDKAssistantMessage
| SDKUserMessage
| SDKUserMessageReplay
| SDKResultMessage
| SDKSystemMessage
| SDKPartialAssistantMessage
| SDKCompactBoundaryMessage;SDKAssistantMessage
Claudeからの応答メッセージを表します。
type SDKAssistantMessage = {
type: 'assistant';
uuid: UUID;
session_id: string;
message: APIAssistantMessage;
parent_tool_use_id: string | null;
}messageプロパティにはAnthropic SDKのAPIAssistantMessageが含まれ、テキストやツール呼び出しの情報が入っています。
SDKResultMessage
タスク完了時の結果メッセージを表します。
type SDKResultMessage = {
type: 'result';
subtype: 'success' | '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;
result?: string; // successの場合
total_cost_usd: number;
usage: NonNullableUsage;
modelUsage: { [modelName: string]: ModelUsage };
permission_denials: SDKPermissionDenial[];
errors?: string[]; // エラーの場合
structured_output?: unknown; // 構造化出力
}subtypeで成功またはエラーの種類を判別できます。
total_cost_usdで実行コストを、usageでトークン使用量を確認できます。
SDKSystemMessage
システム初期化メッセージを表します。
type SDKSystemMessage = {
type: 'system';
subtype: 'init';
uuid: UUID;
session_id: string;
apiKeySource: ApiKeySource;
cwd: string;
tools: string[];
mcp_servers: { name: string; status: string; }[];
model: string;
permissionMode: PermissionMode;
slash_commands: string[];
output_style: string;
}セッション開始時に送信され、利用可能なツールやMCPサーバーの情報が含まれます。
メッセージのフィルタリング例
人間が読める出力のみを表示する例を以下に示します。
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "utils.pyのバグを修正してください",
options: {
allowedTools: ["Read", "Edit", "Glob"],
permissionMode: "acceptEdits"
}
})) {
if (message.type === "assistant" && message.message?.content) {
for (const block of message.message.content) {
if ("text" in block) {
console.log(block.text); // Claudeの推論
} else if ("name" in block) {
console.log(`ツール: ${block.name}`); // 呼び出されたツール
}
}
} else if (message.type === "result") {
console.log(`完了: ${message.subtype}`);
}
}このコードはassistantタイプのメッセージからテキストとツール呼び出しを抽出しています。
resultタイプで最終結果を表示します。
Hookの型定義
Hooksは、Agentのライフサイクルの特定のポイントでカスタムコードを実行する仕組みです。
HookEvent
利用可能なHookイベントを以下に示します。
type HookEvent =
| 'PreToolUse'
| 'PostToolUse'
| 'PostToolUseFailure'
| 'Notification'
| 'UserPromptSubmit'
| 'SessionStart'
| 'SessionEnd'
| 'Stop'
| 'SubagentStart'
| 'SubagentStop'
| 'PreCompact'
| 'PermissionRequest';HookCallback
Hookコールバック関数の型を以下に示します。
type HookCallback = (
input: HookInput,
toolUseID: string | undefined,
options: { signal: AbortSignal }
) => Promise<HookJSONOutput>;Hookの使用例
ファイル変更をログに記録するHookの例を以下に示します。
import { query, HookCallback } from "@anthropic-ai/claude-agent-sdk";
import { appendFileSync } from "fs";
const logFileChange: HookCallback = async (input) => {
const filePath = (input as any).tool_input?.file_path ?? "unknown";
appendFileSync(
"./audit.log",
`${new Date().toISOString()}: modified ${filePath}\n`
);
return {};
};
for await (const message of query({
prompt: "utils.pyの可読性を改善してください",
options: {
permissionMode: "acceptEdits",
hooks: {
PostToolUse: [{ matcher: "Edit|Write", hooks: [logFileChange] }]
}
}
})) {
if ("result" in message) console.log(message.result);
}このコードはPostToolUseイベントでEditまたはWriteツールが使用された後にコールバックを実行します。
matcherは正規表現でツール名をフィルタリングします。
ファイルパスをログファイルに記録することで、変更の監査証跡を残します。
HookInput詳細
各Hookイベントに対応する入力型があります。すべての型はBaseHookInputを拡張しています。
type BaseHookInput = {
session_id: string;
transcript_path: string;
cwd: string;
permission_mode?: string;
}主要なHookInput型を以下に示します。
// ツール実行前
type PreToolUseHookInput = BaseHookInput & {
hook_event_name: 'PreToolUse';
tool_name: string;
tool_input: unknown;
}
// ツール実行後
type PostToolUseHookInput = BaseHookInput & {
hook_event_name: 'PostToolUse';
tool_name: string;
tool_input: unknown;
tool_response: unknown;
}
// ツール実行失敗
type PostToolUseFailureHookInput = BaseHookInput & {
hook_event_name: 'PostToolUseFailure';
tool_name: string;
tool_input: unknown;
error: string;
is_interrupt?: boolean;
}
// セッション開始
type SessionStartHookInput = BaseHookInput & {
hook_event_name: 'SessionStart';
source: 'startup' | 'resume' | 'clear' | 'compact';
}
// Subagent開始
type SubagentStartHookInput = BaseHookInput & {
hook_event_name: 'SubagentStart';
agent_id: string;
agent_type: string;
}HookJSONOutput
Hookの戻り値の型を以下に示します。
type HookJSONOutput = AsyncHookJSONOutput | SyncHookJSONOutput;
// 非同期Hook
type AsyncHookJSONOutput = {
async: true;
asyncTimeout?: number;
}
// 同期Hook
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>;
} | {
hookEventName: 'UserPromptSubmit' | 'SessionStart' | 'PostToolUse';
additionalContext?: string;
};
}continue: falseでAgentの実行を停止、decision: 'block'でツール使用を拒否できます。
hookSpecificOutputでイベント固有の出力を返すことも可能です。
ツール入出力の型
SDKはすべてのビルトインツールの入出力型を提供しています。
ToolInput型
ToolInputはすべてのツール入力型の共用体です。
type ToolInput =
| AgentInput // Task
| AskUserQuestionInput
| BashInput
| FileEditInput // Edit
| FileReadInput // Read
| FileWriteInput // Write
| GlobInput
| GrepInput
| KillShellInput // KillBash
| NotebookEditInput
| WebFetchInput
| WebSearchInput
| TodoWriteInput
| ExitPlanModeInput
| ListMcpResourcesInput
| ReadMcpResourceInput;主要なツール入力型
代表的なツールの入力型を以下に示します。
AgentInput (Task)
interface AgentInput {
description: string; // タスクの短い説明(3-5単語)
prompt: string; // Agentに実行させるタスク
subagent_type: string; // 使用するAgent種別
}BashInput
interface BashInput {
command: string;
timeout?: number;
description?: string;
run_in_background?: boolean;
}FileReadInput (Read)
interface FileReadInput {
file_path: string; // 読み取るファイルの絶対パス
offset?: number; // 開始行番号
limit?: number; // 読み取る行数
}FileWriteInput (Write)
interface FileWriteInput {
file_path: string; // 書き込み先の絶対パス
content: string; // 書き込む内容
}FileEditInput (Edit)
interface FileEditInput {
file_path: string;
old_string: string;
new_string: string;
replace_all?: boolean;
}GlobInput
interface GlobInput {
pattern: string; // globパターン
path?: string; // 検索ディレクトリ(デフォルトはcwd)
}GrepInput
interface 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;
head_limit?: number;
multiline?: boolean;
}WebFetchInput
interface WebFetchInput {
url: string; // 取得するURL
prompt: string; // コンテンツに対して実行するプロンプト
}WebSearchInput
interface WebSearchInput {
query: string; // 検索クエリ
allowed_domains?: string[]; // 許可ドメインリスト
blocked_domains?: string[]; // ブロックドメインリスト
}TodoWriteInput
interface TodoWriteInput {
todos: Array<{
content: string; // タスクの説明
status: 'pending' | 'in_progress' | 'completed';
activeForm: string; // タスクのアクティブ形式
}>;
}主要なツール出力型
代表的なツールの出力型を以下に示します。
TaskOutput
interface TaskOutput {
result: string; // 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;
}BashOutput
interface BashOutput {
output: string;
exitCode: number;
killed?: boolean;
shellId?: string;
}ReadOutput
type ReadOutput =
| TextFileOutput
| ImageFileOutput
| PDFFileOutput
| NotebookFileOutput;
interface TextFileOutput {
content: string; // 行番号付きのファイル内容
total_lines: number; // ファイルの総行数
lines_returned: number; // 返された行数
}WriteOutput
interface WriteOutput {
message: string; // 成功メッセージ
bytes_written: number; // 書き込んだバイト数
file_path: string; // 書き込んだファイルパス
}EditOutput
interface EditOutput {
message: string; // 確認メッセージ
replacements: number; // 置換回数
file_path: string; // 編集したファイルパス
}GlobOutput
interface GlobOutput {
matches: string[]; // マッチしたファイルパス
count: number; // マッチ数
search_path: string; // 検索ディレクトリ
}GrepOutput
type GrepOutput =
| GrepContentOutput
| GrepFilesOutput
| GrepCountOutput;
interface GrepContentOutput {
matches: Array<{
file: string;
line_number?: number;
line: string;
before_context?: string[];
after_context?: string[];
}>;
total_matches: number;
}
interface GrepFilesOutput {
files: string[]; // マッチを含むファイル
count: number; // ファイル数
}WebFetchOutput
interface WebFetchOutput {
response: string; // AIモデルの応答
url: string; // 取得したURL
final_url?: string; // リダイレクト後の最終URL
status_code?: number; // HTTPステータスコード
}WebSearchOutput
interface WebSearchOutput {
results: Array<{
title: string;
url: string;
snippet: string;
metadata?: Record<string, any>;
}>;
total_results: number;
query: string;
}MCP設定
MCPサーバーの設定方法を解説します。
McpServerConfig
MCPサーバーは複数の接続方式をサポートしています。
type McpServerConfig =
| McpStdioServerConfig
| McpSSEServerConfig
| McpHttpServerConfig
| McpSdkServerConfigWithInstance;
// Stdio接続
type McpStdioServerConfig = {
type?: 'stdio';
command: string;
args?: string[];
env?: Record<string, string>;
}
// SSE接続
type McpSSEServerConfig = {
type: 'sse';
url: string;
headers?: Record<string, string>;
}
// HTTP接続
type McpHttpServerConfig = {
type: 'http';
url: string;
headers?: Record<string, string>;
}
// SDK内蔵サーバー
type McpSdkServerConfigWithInstance = {
type: 'sdk';
name: string;
instance: McpServer;
}Stdio接続の例
Playwright MCPサーバーに接続する例を以下に示します。
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "example.comを開いて内容を説明してください",
options: {
mcpServers: {
playwright: {
command: "npx",
args: ["@playwright/mcp@latest"]
}
}
}
})) {
if ("result" in message) console.log(message.result);
}このコードはmcpServersオプションでPlaywright MCPサーバーを設定しています。
commandに実行コマンド、argsに引数を指定します。
インプロセスMCPサーバー
createSdkMcpServer()でアプリケーション内にMCPサーバーを作成できます。
import { query, createSdkMcpServer, tool } from "@anthropic-ai/claude-agent-sdk";
import { z } from "zod";
// カスタムツールを定義
const weatherTool = tool(
"get_weather",
"指定した都市の天気を取得します",
{ city: z.string().describe("都市名") },
async ({ city }) => ({
content: [{ type: "text", text: `${city}の天気は晴れです` }]
})
);
// MCPサーバーを作成
const weatherServer = createSdkMcpServer({
name: "weather-server",
version: "1.0.0",
tools: [weatherTool]
});
for await (const message of query({
prompt: "東京の天気を教えてください",
options: {
mcpServers: {
weather: weatherServer
}
}
})) {
if ("result" in message) console.log(message.result);
}このコードはtool()関数でZodスキーマを使用した型安全なツールを定義しています。
createSdkMcpServer()でインプロセスMCPサーバーを作成し、mcpServersオプションに渡します。
Subagent設定
Subagentは、メインAgentから独立したコンテキストで動作する子Agentです。
AgentDefinition
Subagentの定義を以下に示します。
type AgentDefinition = {
description: string;
tools?: string[];
prompt: string;
model?: 'sonnet' | 'opus' | 'haiku' | 'inherit';
}Subagentの使用例
コードレビュー用のSubagentを定義する例を以下に示します。
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "code-reviewer Agentを使ってこのコードベースをレビューしてください",
options: {
allowedTools: ["Read", "Glob", "Grep", "Task"],
agents: {
"code-reviewer": {
description: "品質とセキュリティのレビューを行う専門家",
prompt: "コード品質を分析し、改善点を提案してください。",
tools: ["Read", "Glob", "Grep"]
}
}
}
})) {
if ("result" in message) console.log(message.result);
}このコードはagentsオプションでSubagentを定義しています。
TaskツールをallowedToolsに含めることで、Subagentの呼び出しが可能になります。
Subagentはdescriptionに基づいて適切なタイミングで使用されます。
権限管理
権限モードとカスタム権限関数について解説します。
PermissionMode
type PermissionMode =
| 'default' // 標準の権限動作
| 'acceptEdits' // ファイル編集を自動承認
| 'bypassPermissions' // すべての権限チェックをバイパス
| 'plan' // 計画モード(実行なし)PermissionResult
権限チェックの結果を表す型です。
type PermissionResult =
| {
behavior: 'allow';
updatedInput: ToolInput;
updatedPermissions?: PermissionUpdate[];
}
| {
behavior: 'deny';
message: string;
interrupt?: boolean;
}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; }
type PermissionBehavior = 'allow' | 'deny' | 'ask';
type PermissionUpdateDestination =
| 'userSettings' // グローバルユーザー設定
| 'projectSettings' // プロジェクト設定
| 'localSettings' // ローカル設定(gitignore対象)
| 'session' // 現在のセッションのみ
type PermissionRuleValue = {
toolName: string;
ruleContent?: string;
}カスタム権限関数
canUseToolで細かい権限制御が可能です。
import { query, CanUseTool } from "@anthropic-ai/claude-agent-sdk";
const canUseTool: CanUseTool = async (toolName, input, options) => {
// 特定のディレクトリへの書き込みを禁止
if (toolName === "Write" || toolName === "Edit") {
const filePath = (input as any).file_path || "";
if (filePath.includes("/protected/")) {
return {
behavior: 'deny',
message: '保護されたディレクトリへの書き込みは許可されていません'
};
}
}
return {
behavior: 'allow',
updatedInput: input
};
};
for await (const message of query({
prompt: "プロジェクト全体をリファクタリングしてください",
options: {
allowedTools: ["Read", "Write", "Edit", "Glob"],
permissionMode: "default",
canUseTool
}
})) {
console.log(message);
}このコードはcanUseToolコールバックでツール使用の可否を判定しています。
/protected/を含むパスへの書き込みを拒否し、それ以外は許可します。
behavior: 'deny'で拒否理由をメッセージとして返します。
サンドボックス設定
コマンド実行のサンドボックス化を設定できます。
SandboxSettings
type SandboxSettings = {
enabled?: boolean; // サンドボックスモードを有効化
autoAllowBashIfSandboxed?: boolean; // サンドボックス内のBashを自動承認
excludedCommands?: string[]; // サンドボックスをバイパスするコマンド
allowUnsandboxedCommands?: boolean; // サンドボックス外実行のリクエストを許可
network?: NetworkSandboxSettings; // ネットワーク設定
ignoreViolations?: SandboxIgnoreViolations; // 違反を無視する設定
enableWeakerNestedSandbox?: boolean; // 互換性のための弱いサンドボックス
}NetworkSandboxSettings
type NetworkSandboxSettings = {
allowLocalBinding?: boolean; // ローカルポートへのバインドを許可
allowUnixSockets?: string[]; // アクセスを許可するUnixソケットパス
allowAllUnixSockets?: boolean; // すべてのUnixソケットへのアクセスを許可
httpProxyPort?: number; // HTTPプロキシポート
socksProxyPort?: number; // SOCKSプロキシポート
}SandboxIgnoreViolations
type SandboxIgnoreViolations = {
file?: string[]; // 違反を無視するファイルパスパターン
network?: string[]; // 違反を無視するネットワークパターン
}サンドボックスの使用例
サンドボックスを有効にしてビルドを実行する例を以下に示します。
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "プロジェクトをビルドしてテストを実行してください",
options: {
allowedTools: ["Read", "Bash", "Glob"],
sandbox: {
enabled: true,
autoAllowBashIfSandboxed: true,
network: {
allowLocalBinding: true // 開発サーバー用
}
}
}
})) {
if ("result" in message) console.log(message.result);
}このコードはsandbox.enabled: trueでサンドボックスモードを有効にしています。
autoAllowBashIfSandboxed: trueでサンドボックス内のBashコマンドを自動承認します。
network.allowLocalBinding: trueでローカルポートへのバインドを許可し、開発サーバーの起動を可能にします。
その他の型定義
SDKで使用されるその他の重要な型を以下に示します。
ApiKeySource
type ApiKeySource = 'user' | 'project' | 'org' | 'temporary';SdkBeta
利用可能なベータ機能です。
type SdkBeta = 'context-1m-2025-08-07';betasオプションに指定することで、100万トークンのコンテキストウィンドウを有効にできます。
SlashCommand
type SlashCommand = {
name: string;
description: string;
argumentHint: string;
}ModelInfo
type ModelInfo = {
value: string;
displayName: string;
description: string;
}McpServerStatus
type McpServerStatus = {
name: string;
status: 'connected' | 'failed' | 'needs-auth' | 'pending';
serverInfo?: {
name: string;
version: string;
};
}AccountInfo
type AccountInfo = {
email?: string;
organization?: string;
subscriptionType?: string;
tokenSource?: string;
apiKeySource?: string;
}ModelUsage
モデルごとの使用統計です。
type ModelUsage = {
inputTokens: number;
outputTokens: number;
cacheReadInputTokens: number;
cacheCreationInputTokens: number;
webSearchRequests: number;
costUSD: number;
contextWindow: number;
}Usage
Anthropic SDKからのトークン使用統計です。
type Usage = {
input_tokens: number | null;
output_tokens: number | null;
cache_creation_input_tokens?: number | null;
cache_read_input_tokens?: number | null;
}
// null不可バージョン
type NonNullableUsage = {
[K in keyof Usage]: NonNullable<Usage[K]>;
}CallToolResult
MCPツールの結果型です。
type CallToolResult = {
content: Array<{
type: 'text' | 'image' | 'resource';
// 追加フィールドは型により異なる
}>;
isError?: boolean;
}AbortError
中断操作用のカスタムエラークラスです。
class AbortError extends Error {}V2インターフェース(プレビュー)
V2インターフェースは、マルチターン会話をより簡単に実装できる新しいAPIです。
V2インターフェースは不安定なプレビューです。 フィードバックに基づいてAPIが変更される可能性があります。 セッションフォークなど一部の機能はV1でのみ利用可能です。
V2の主な特徴
V2では非同期ジェネレータの管理が不要になり、3つの概念に簡素化されています。
createSession()/resumeSession()- 会話の開始または継続session.send()- メッセージの送信session.stream()- レスポンスの取得
ワンショットプロンプト
単発のクエリにはunstable_v2_prompt()を使用します。
import { unstable_v2_prompt } from '@anthropic-ai/claude-agent-sdk';
const result = await unstable_v2_prompt('2 + 2 は何ですか?', {
model: 'claude-sonnet-4-5-20250929'
});
console.log(result.result);このコードは単一のプロンプトを送信し、結果を取得するシンプルな使い方です。 セッション管理が不要な場合に適しています。
マルチターン会話
複数ターンの会話にはunstable_v2_createSession()を使用します。
import { unstable_v2_createSession } from '@anthropic-ai/claude-agent-sdk';
await using session = unstable_v2_createSession({
model: 'claude-sonnet-4-5-20250929'
});
// ターン1
await session.send('5 + 3 は何ですか?');
for await (const msg of session.stream()) {
if (msg.type === 'assistant') {
const text = msg.message.content
.filter(block => block.type === 'text')
.map(block => block.text)
.join('');
console.log(text);
}
}
// ターン2
await session.send('それを2倍してください');
for await (const msg of session.stream()) {
if (msg.type === 'assistant') {
const text = msg.message.content
.filter(block => block.type === 'text')
.map(block => block.text)
.join('');
console.log(text);
}
}このコードはawait using(TypeScript 5.2+)でセッションの自動クリーンアップを行っています。
send()でメッセージを送信し、stream()でレスポンスをストリーミング受信します。
セッションはコンテキストを保持するため、前のターンを参照した会話が可能です。
セッションの再開
セッションIDを保存して後で再開できます。
import {
unstable_v2_createSession,
unstable_v2_resumeSession,
type SDKMessage
} from '@anthropic-ai/claude-agent-sdk';
function getAssistantText(msg: SDKMessage): string | null {
if (msg.type !== 'assistant') return null;
return msg.message.content
.filter(block => block.type === 'text')
.map(block => block.text)
.join('');
}
// 初期セッションを作成
const session = unstable_v2_createSession({
model: 'claude-sonnet-4-5-20250929'
});
await session.send('この数字を覚えてください: 42');
let sessionId: string | undefined;
for await (const msg of session.stream()) {
sessionId = msg.session_id;
const text = getAssistantText(msg);
if (text) console.log('初回応答:', text);
}
console.log('セッションID:', sessionId);
session.close();
// 後でセッションを再開
await using resumedSession = unstable_v2_resumeSession(sessionId!, {
model: 'claude-sonnet-4-5-20250929'
});
await resumedSession.send('先ほど覚えてもらった数字は何でしたか?');
for await (const msg of resumedSession.stream()) {
const text = getAssistantText(msg);
if (text) console.log('再開後の応答:', text);
}このコードは初回セッションでsession_idを取得し、unstable_v2_resumeSession()で再開しています。
セッション再開により、前の会話のコンテキストが保持されます。
セッションのクリーンアップ
セッションは手動または自動でクローズできます。
await using(TypeScript 5.2+)を使用すると、ブロック終了時に自動でクリーンアップされます。
// 自動クリーンアップ(TypeScript 5.2+)
await using session = unstable_v2_createSession({
model: 'claude-sonnet-4-5-20250929'
});
// ブロック終了時に自動でsession.close()が呼ばれる古いTypeScriptバージョンでは手動でクローズします。
// 手動クリーンアップ
const session = unstable_v2_createSession({
model: 'claude-sonnet-4-5-20250929'
});
// ... セッションを使用 ...
session.close();V1とV2の比較
| 観点 | V1 | V2 |
|---|---|---|
| マルチターン | 入力ジェネレータの調整が必要 | send()/stream()で簡単 |
| 状態管理 | ジェネレータ状態の管理が必要 | セッションオブジェクトで管理 |
| セッションフォーク | 対応 | 未対応(プレビュー) |
| クリーンアップ | 手動管理 | await usingで自動 |