# 【Agent SDK】TypeScript実装

> この章では、Claude Agent SDKのTypeScript実装について詳しく解説します。TypeScript SDKは、型安全性を活かした堅牢なAgent開発を可能にします。

- URL: https://cardene.dev/books/claude-code-guide/17-02-sdk-typescript
- 本: Claude Code完全ガイド (https://cardene.dev/books/claude-code-guide.md)
- 章: 72 / 100
- 前の章: https://cardene.dev/books/claude-code-guide/17-01-sdk-overview.md
- 次の章: https://cardene.dev/books/claude-code-guide/17-03-sdk-python.md
- 公開日: 2025-11-24
- 更新日: 2025-11-24
- トピック: AI
- タグ: claude, claudecode, LLM, agent

## 概要

この章では、Claude Agent SDKのTypeScript実装について詳しく解説します。
TypeScript SDKは、型安全性を活かした堅牢なAgent開発を可能にします。
`query()`関数を中心としたAPIリファレンス、オプション設定、メッセージタイプ、Hookの使い方を理解することで、本格的なAgentアプリケーションを構築できます。

## インストール

npmを使用してTypeScript SDKをインストールします。

```bash
npm install @anthropic-ai/claude-agent-sdk
```

このコマンドでnpmレジストリから`@anthropic-ai/claude-agent-sdk`パッケージをインストールします。
Node.js 18以上が必要です。

## query関数

`query()`は、Claude Agent SDKの主要なエントリーポイントです。
非同期ジェネレータとしてメッセージをストリーミングで返します。

### 基本的な使い方

`query()`関数の基本的な使い方を以下に示します。

```typescript:basic_query.ts
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()`関数のシグネチャを以下に示します。

```typescript
function query({
  prompt,
  options
}: {
  prompt: string | AsyncIterable<SDKUserMessage>;
  options?: Options;
}): Query
```

`prompt`パラメータは文字列またはストリーミングモード用の非同期イテラブルを受け取ります。
`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の設定例

カスタムシステムプロンプトを設定する例を以下に示します。

```typescript:custom_system_prompt.ts
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のシステムプロンプトを使用する例を以下に示します。

```typescript:preset_system_prompt.ts
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`は、ファイルシステムから読み込む設定ソースを制御します。

```typescript
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()` | アカウント情報を取得 |

### ファイルチェックポイントの使用例

ファイルチェックポイント機能を使用してファイルを巻き戻す例を以下に示します。

```typescript:file_checkpointing.ts
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`は以下の型の共用体です。

```typescript
type SDKMessage =
  | SDKAssistantMessage
  | SDKUserMessage
  | SDKUserMessageReplay
  | SDKResultMessage
  | SDKSystemMessage
  | SDKPartialAssistantMessage
  | SDKCompactBoundaryMessage;
```

### SDKAssistantMessage

Claudeからの応答メッセージを表します。

```typescript
type SDKAssistantMessage = {
  type: 'assistant';
  uuid: UUID;
  session_id: string;
  message: APIAssistantMessage;
  parent_tool_use_id: string | null;
}
```

`message`プロパティにはAnthropic SDKの`APIAssistantMessage`が含まれ、テキストやツール呼び出しの情報が入っています。

### SDKResultMessage

タスク完了時の結果メッセージを表します。

```typescript
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

システム初期化メッセージを表します。

```typescript
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サーバーの情報が含まれます。

### メッセージのフィルタリング例

人間が読める出力のみを表示する例を以下に示します。

```typescript:message_filtering.ts
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イベントを以下に示します。

```typescript
type HookEvent =
  | 'PreToolUse'
  | 'PostToolUse'
  | 'PostToolUseFailure'
  | 'Notification'
  | 'UserPromptSubmit'
  | 'SessionStart'
  | 'SessionEnd'
  | 'Stop'
  | 'SubagentStart'
  | 'SubagentStop'
  | 'PreCompact'
  | 'PermissionRequest';
```

### HookCallback

Hookコールバック関数の型を以下に示します。

```typescript
type HookCallback = (
  input: HookInput,
  toolUseID: string | undefined,
  options: { signal: AbortSignal }
) => Promise<HookJSONOutput>;
```

### Hookの使用例

ファイル変更をログに記録するHookの例を以下に示します。

```typescript:hook_example.ts
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`を拡張しています。

```typescript
type BaseHookInput = {
  session_id: string;
  transcript_path: string;
  cwd: string;
  permission_mode?: string;
}
```

主要なHookInput型を以下に示します。

```typescript
// ツール実行前
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の戻り値の型を以下に示します。

```typescript
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`はすべてのツール入力型の共用体です。

```typescript
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)

```typescript
interface AgentInput {
  description: string;  // タスクの短い説明（3-5単語）
  prompt: string;       // Agentに実行させるタスク
  subagent_type: string; // 使用するAgent種別
}
```

#### BashInput

```typescript
interface BashInput {
  command: string;
  timeout?: number;
  description?: string;
  run_in_background?: boolean;
}
```

#### FileReadInput (Read)

```typescript
interface FileReadInput {
  file_path: string;  // 読み取るファイルの絶対パス
  offset?: number;    // 開始行番号
  limit?: number;     // 読み取る行数
}
```

#### FileWriteInput (Write)

```typescript
interface FileWriteInput {
  file_path: string;  // 書き込み先の絶対パス
  content: string;    // 書き込む内容
}
```

#### FileEditInput (Edit)

```typescript
interface FileEditInput {
  file_path: string;
  old_string: string;
  new_string: string;
  replace_all?: boolean;
}
```

#### GlobInput

```typescript
interface GlobInput {
  pattern: string;  // globパターン
  path?: string;    // 検索ディレクトリ（デフォルトはcwd）
}
```

#### GrepInput

```typescript
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

```typescript
interface WebFetchInput {
  url: string;     // 取得するURL
  prompt: string;  // コンテンツに対して実行するプロンプト
}
```

#### WebSearchInput

```typescript
interface WebSearchInput {
  query: string;              // 検索クエリ
  allowed_domains?: string[]; // 許可ドメインリスト
  blocked_domains?: string[]; // ブロックドメインリスト
}
```

#### TodoWriteInput

```typescript
interface TodoWriteInput {
  todos: Array<{
    content: string;     // タスクの説明
    status: 'pending' | 'in_progress' | 'completed';
    activeForm: string;  // タスクのアクティブ形式
  }>;
}
```

### 主要なツール出力型

代表的なツールの出力型を以下に示します。

#### TaskOutput

```typescript
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

```typescript
interface BashOutput {
  output: string;
  exitCode: number;
  killed?: boolean;
  shellId?: string;
}
```

#### ReadOutput

```typescript
type ReadOutput =
  | TextFileOutput
  | ImageFileOutput
  | PDFFileOutput
  | NotebookFileOutput;

interface TextFileOutput {
  content: string;      // 行番号付きのファイル内容
  total_lines: number;  // ファイルの総行数
  lines_returned: number; // 返された行数
}
```

#### WriteOutput

```typescript
interface WriteOutput {
  message: string;       // 成功メッセージ
  bytes_written: number; // 書き込んだバイト数
  file_path: string;     // 書き込んだファイルパス
}
```

#### EditOutput

```typescript
interface EditOutput {
  message: string;      // 確認メッセージ
  replacements: number; // 置換回数
  file_path: string;    // 編集したファイルパス
}
```

#### GlobOutput

```typescript
interface GlobOutput {
  matches: string[];   // マッチしたファイルパス
  count: number;       // マッチ数
  search_path: string; // 検索ディレクトリ
}
```

#### GrepOutput

```typescript
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

```typescript
interface WebFetchOutput {
  response: string;     // AIモデルの応答
  url: string;          // 取得したURL
  final_url?: string;   // リダイレクト後の最終URL
  status_code?: number; // HTTPステータスコード
}
```

#### WebSearchOutput

```typescript
interface WebSearchOutput {
  results: Array<{
    title: string;
    url: string;
    snippet: string;
    metadata?: Record<string, any>;
  }>;
  total_results: number;
  query: string;
}
```

## MCP設定

MCPサーバーの設定方法を解説します。

### McpServerConfig

MCPサーバーは複数の接続方式をサポートしています。

```typescript
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サーバーに接続する例を以下に示します。

```typescript:mcp_stdio.ts
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サーバーを作成できます。

```typescript:mcp_inprocess.ts
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の定義を以下に示します。

```typescript
type AgentDefinition = {
  description: string;
  tools?: string[];
  prompt: string;
  model?: 'sonnet' | 'opus' | 'haiku' | 'inherit';
}
```

### Subagentの使用例

コードレビュー用のSubagentを定義する例を以下に示します。

```typescript:subagent_example.ts
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

```typescript
type PermissionMode =
  | 'default'           // 標準の権限動作
  | 'acceptEdits'       // ファイル編集を自動承認
  | 'bypassPermissions' // すべての権限チェックをバイパス
  | 'plan'              // 計画モード（実行なし）
```

### PermissionResult

権限チェックの結果を表す型です。

```typescript
type PermissionResult =
  | {
      behavior: 'allow';
      updatedInput: ToolInput;
      updatedPermissions?: PermissionUpdate[];
    }
  | {
      behavior: 'deny';
      message: string;
      interrupt?: boolean;
    }
```

### PermissionUpdate

権限を更新するための操作を表す型です。

```typescript
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`で細かい権限制御が可能です。

```typescript:custom_permission.ts
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

```typescript
type SandboxSettings = {
  enabled?: boolean;                  // サンドボックスモードを有効化
  autoAllowBashIfSandboxed?: boolean; // サンドボックス内のBashを自動承認
  excludedCommands?: string[];        // サンドボックスをバイパスするコマンド
  allowUnsandboxedCommands?: boolean; // サンドボックス外実行のリクエストを許可
  network?: NetworkSandboxSettings;   // ネットワーク設定
  ignoreViolations?: SandboxIgnoreViolations;  // 違反を無視する設定
  enableWeakerNestedSandbox?: boolean; // 互換性のための弱いサンドボックス
}
```

### NetworkSandboxSettings

```typescript
type NetworkSandboxSettings = {
  allowLocalBinding?: boolean;   // ローカルポートへのバインドを許可
  allowUnixSockets?: string[];   // アクセスを許可するUnixソケットパス
  allowAllUnixSockets?: boolean; // すべてのUnixソケットへのアクセスを許可
  httpProxyPort?: number;        // HTTPプロキシポート
  socksProxyPort?: number;       // SOCKSプロキシポート
}
```

### SandboxIgnoreViolations

```typescript
type SandboxIgnoreViolations = {
  file?: string[];    // 違反を無視するファイルパスパターン
  network?: string[]; // 違反を無視するネットワークパターン
}
```

### サンドボックスの使用例

サンドボックスを有効にしてビルドを実行する例を以下に示します。

```typescript:sandbox_example.ts
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

```typescript
type ApiKeySource = 'user' | 'project' | 'org' | 'temporary';
```

### SdkBeta

利用可能なベータ機能です。

```typescript
type SdkBeta = 'context-1m-2025-08-07';
```

`betas`オプションに指定することで、100万トークンのコンテキストウィンドウを有効にできます。

### SlashCommand

```typescript
type SlashCommand = {
  name: string;
  description: string;
  argumentHint: string;
}
```

### ModelInfo

```typescript
type ModelInfo = {
  value: string;
  displayName: string;
  description: string;
}
```

### McpServerStatus

```typescript
type McpServerStatus = {
  name: string;
  status: 'connected' | 'failed' | 'needs-auth' | 'pending';
  serverInfo?: {
    name: string;
    version: string;
  };
}
```

### AccountInfo

```typescript
type AccountInfo = {
  email?: string;
  organization?: string;
  subscriptionType?: string;
  tokenSource?: string;
  apiKeySource?: string;
}
```

### ModelUsage

モデルごとの使用統計です。

```typescript
type ModelUsage = {
  inputTokens: number;
  outputTokens: number;
  cacheReadInputTokens: number;
  cacheCreationInputTokens: number;
  webSearchRequests: number;
  costUSD: number;
  contextWindow: number;
}
```

### Usage

Anthropic SDKからのトークン使用統計です。

```typescript
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ツールの結果型です。

```typescript
type CallToolResult = {
  content: Array<{
    type: 'text' | 'image' | 'resource';
    // 追加フィールドは型により異なる
  }>;
  isError?: boolean;
}
```

### AbortError

中断操作用のカスタムエラークラスです。

```typescript
class AbortError extends Error {}
```

## V2インターフェース（プレビュー）

V2インターフェースは、マルチターン会話をより簡単に実装できる新しいAPIです。

:::message alert
V2インターフェースは**不安定なプレビュー**です。
フィードバックに基づいてAPIが変更される可能性があります。
セッションフォークなど一部の機能はV1でのみ利用可能です。
:::

### V2の主な特徴

V2では非同期ジェネレータの管理が不要になり、3つの概念に簡素化されています。

- `createSession()` / `resumeSession()` - 会話の開始または継続
- `session.send()` - メッセージの送信
- `session.stream()` - レスポンスの取得

### ワンショットプロンプト

単発のクエリには`unstable_v2_prompt()`を使用します。

```typescript:v2_oneshot.ts
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()`を使用します。

```typescript:v2_multiturn.ts
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を保存して後で再開できます。

```typescript:v2_resume.ts
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
// 自動クリーンアップ（TypeScript 5.2+）
await using session = unstable_v2_createSession({
  model: 'claude-sonnet-4-5-20250929'
});
// ブロック終了時に自動でsession.close()が呼ばれる
```

古いTypeScriptバージョンでは手動でクローズします。

```typescript
// 手動クリーンアップ
const session = unstable_v2_createSession({
  model: 'claude-sonnet-4-5-20250929'
});
// ... セッションを使用 ...
session.close();
```

### V1とV2の比較

| 観点 | V1 | V2 |
|------|----|----|
| マルチターン | 入力ジェネレータの調整が必要 | `send()`/`stream()`で簡単 |
| 状態管理 | ジェネレータ状態の管理が必要 | セッションオブジェクトで管理 |
| セッションフォーク | 対応 | 未対応（プレビュー） |
| クリーンアップ | 手動管理 | `await using`で自動 |

## 参考資料

https://platform.claude.com/docs/en/agent-sdk/typescript
https://platform.claude.com/docs/en/agent-sdk/typescript-v2-preview
