前提条件

  • Node.js 18+

インストール

NPMから@anthropic-ai/claude-codeをインストールします:

npm install -g @anthropic-ai/claude-code

TypeScript SDKのソースコードを表示するには、NPMの@anthropic-ai/claude-codeページをご覧ください。

基本的な使用方法

TypeScript SDKを通じた主要なインターフェースはquery関数で、メッセージが到着するとそれらをストリーミングする非同期イテレータを返します:

import { query } from "@anthropic-ai/claude-code";

for await (const message of query({
  prompt: "システムパフォーマンスを分析する",
  abortController: new AbortController(),
  options: {
    maxTurns: 5,
    systemPrompt: "あなたはパフォーマンスエンジニアです",
    allowedTools: ["Bash", "Read", "WebSearch"]
  }
})) {
  if (message.type === "result") {
    console.log(message.result);
  }
}

設定オプション

引数説明デフォルト
abortControllerAbortController操作をキャンセルするためのアボートコントローラーnew AbortController()
additionalDirectoriesstring[]セッションに含める追加ディレクトリundefined
allowedToolsstring[]Claudeが使用を許可されているツールのリストデフォルトですべてのツールが有効
appendSystemPromptstringデフォルトのシステムプロンプトに追加するテキストundefined
canUseToolCanUseToolツール使用のためのカスタム許可関数undefined
continueboolean最新のセッションを継続するfalse
customSystemPromptstringデフォルトのシステムプロンプトを完全に置き換えるundefined
cwdstring現在の作業ディレクトリprocess.cwd()
disallowedToolsstring[]Claudeが使用を許可されていないツールのリストundefined
envDict<string>設定する環境変数undefined
executable'bun' | 'deno' | 'node'使用するJavaScriptランタイムNode.jsで実行時はnode、Bunで実行時はbun
executableArgsstring[]実行可能ファイルに渡す引数[]
fallbackModelstringプライマリモデルが失敗した場合に使用するモデルundefined
maxThinkingTokensnumberClaudeの思考プロセスの最大トークン数undefined
maxTurnsnumber会話ターンの最大数undefined
mcpServersRecord<string, McpServerConfig>MCPサーバー設定undefined
modelstring使用するClaudeモデルCLI設定からのデフォルトを使用
pathToClaudeCodeExecutablestringClaude Code実行可能ファイルへのパス@anthropic-ai/claude-codeに付属する実行可能ファイル
permissionModePermissionModeセッションの許可モード"default" (オプション: "default", "acceptEdits", "bypassPermissions", "plan")
permissionPromptToolNamestring許可プロンプト用MCPツールの名前undefined
resumestring再開するセッションIDundefined
stderr(data: string) => voidstderr出力のコールバックundefined
strictMcpConfigboolean厳密なMCP設定検証を強制するundefined

マルチターン会話

マルチターン会話には2つのオプションがあります。

レスポンスを生成して再開するか、メッセージの配列に対して非同期/ジェネレータを受け入れるストリーミング入力モードを使用できます。現在のところ、ストリーミング入力モードは、メッセージ経由で画像を添付する唯一の方法です。

セッション管理での再開

import { query } from "@anthropic-ai/claude-code";

// 最新の会話を継続
for await (const message of query({
  prompt: "今度はより良いパフォーマンスのためにこれをリファクタリングしてください",
  options: { continue: true }
})) {
  if (message.type === "result") console.log(message.result);
}

// 特定のセッションを再開
for await (const message of query({
  prompt: "テストを更新してください",
  options: {
    resume: "550e8400-e29b-41d4-a716-446655440000",
    maxTurns: 3
  }
})) {
  if (message.type === "result") console.log(message.result);
}

ストリーミング入力モード

ストリーミング入力モードでは、単一の文字列の代わりに非同期イテラブルとしてメッセージを提供できます。これにより、マルチターン会話、画像添付、動的メッセージ生成が可能になります:

import { query } from "@anthropic-ai/claude-code";

// ストリーミングメッセージ用の非同期ジェネレータを作成
async function* generateMessages() {
  yield {
    type: "user" as const,
    message: {
      role: "user" as const,
      content: "このコードベースの分析を開始してください"
    }
  };
  
  // 何らかの条件またはユーザー入力を待つ
  await new Promise(resolve => setTimeout(resolve, 1000));
  
  yield {
    type: "user" as const,
    message: {
      role: "user" as const,
      content: "今度は認証モジュールに焦点を当ててください"
    }
  };
}

// ストリーミング入力を使用
for await (const message of query({
  prompt: generateMessages(),
  options: {
    maxTurns: 5,
    allowedTools: ["Read", "Grep", "Bash"]
  }
})) {
  if (message.type === "result") {
    console.log(message.result);
  }
}

画像付きストリーミング入力

ストリーミング入力モードは、メッセージ経由で画像を添付する唯一の方法です:

import { query } from "@anthropic-ai/claude-code";
import { readFileSync } from "fs";

async function* messagesWithImage() {
  // テキスト付きの画像を送信
  yield {
    type: "user" as const,
    message: {
      role: "user" as const,
      content: [
        {
          type: "text",
          text: "このスクリーンショットを分析して改善案を提案してください"
        },
        {
          type: "image",
          source: {
            type: "base64",
            media_type: "image/png",
            data: readFileSync("screenshot.png", "base64")
          }
        }
      ]
    }
  };
}

for await (const message of query({
  prompt: messagesWithImage()
})) {
  if (message.type === "result") console.log(message.result);
}

カスタムシステムプロンプト

システムプロンプトは、エージェントの役割、専門知識、動作を定義します:

import { query } from "@anthropic-ai/claude-code";

// SREインシデント対応エージェント
for await (const message of query({
  prompt: "APIがダウンしています、調査してください",
  options: {
    systemPrompt: "あなたはSREの専門家です。問題を体系的に診断し、実行可能な解決策を提供してください。",
    maxTurns: 3
  }
})) {
  if (message.type === "result") console.log(message.result);
}

// デフォルトのシステムプロンプトに追加
for await (const message of query({
  prompt: "この関数をリファクタリングしてください",
  options: {
    appendSystemPrompt: "常に包括的なエラーハンドリングとユニットテストを含めてください。",
    maxTurns: 2
  }
})) {
  if (message.type === "result") console.log(message.result);
}

MCP経由のカスタムツール

Model Context Protocol (MCP)により、エージェントにカスタムツールと機能を提供できます:

import { query } from "@anthropic-ai/claude-code";

// 監視ツール付きSREエージェント
for await (const message of query({
  prompt: "決済サービスの障害を調査してください",
  options: {
    mcpConfig: "sre-tools.json",
    allowedTools: ["mcp__datadog", "mcp__pagerduty", "mcp__kubernetes"],
    systemPrompt: "あなたはSREです。監視データを使用して問題を診断してください。",
    maxTurns: 4
  }
})) {
  if (message.type === "result") console.log(message.result);
}

MCPを使用したカスタムツール

MCPを使用してカスタムツールを実装できます。例えば、カスタム許可処理ツールを作成する方法は次のとおりです。

const server = new McpServer({
  name: "Test permission prompt MCP Server",
  version: "0.0.1",
});

server.tool(
  "approval_prompt",
  '許可チェックをシミュレート - 入力に"allow"が含まれている場合は承認、そうでなければ拒否',
  {
    tool_name: z.string().describe("許可を要求するツールの名前"),
    input: z.object({}).passthrough().describe("ツールの入力"),
    tool_use_id: z.string().optional().describe("一意のツール使用リクエストID"),
  },
  async ({ tool_name, input }) => {
    return {
      content: [
        {
          type: "text",
          text: JSON.stringify(
            JSON.stringify(input).includes("allow")
              ? {
                  behavior: "allow",
                  updatedInput: input,
                }
              : {
                  behavior: "deny",
                  message: "テストapproval_promptツールによって許可が拒否されました",
                }
          ),
        },
      ],
    };
  }
);

// SDKで使用
import { query } from "@anthropic-ai/claude-code";

for await (const message of query({
  prompt: "コードベースを分析してください",
  options: {
    permissionPromptTool: "mcp__test-server__approval_prompt",
    mcpConfig: "my-config.json",
    allowedTools: ["Read", "Grep"]
  }
})) {
  if (message.type === "result") console.log(message.result);
}

出力形式

テキスト出力(デフォルト)

// デフォルトのテキスト出力
for await (const message of query({
  prompt: "src/components/Header.tsxファイルを説明してください"
})) {
  if (message.type === "result") {
    console.log(message.result);
    // 出力: これは...を示すReactコンポーネントです
  }
}

JSON出力

// JSON風アクセスのためにすべてのメッセージを収集
const messages = [];
for await (const message of query({
  prompt: "データレイヤーはどのように動作しますか?"
})) {
  messages.push(message);
}

// メタデータ付きの結果メッセージにアクセス
const result = messages.find(m => m.type === "result");
console.log({
  result: result.result,
  cost: result.total_cost_usd,
  duration: result.duration_ms
});

入力形式

// 直接プロンプト
for await (const message of query({
  prompt: "このコードを説明してください"
})) {
  if (message.type === "result") console.log(message.result);
}

// 変数から
const userInput = "このコードを説明してください";
for await (const message of query({ prompt: userInput })) {
  if (message.type === "result") console.log(message.result);
}

エージェント統合例

SREインシデント対応エージェント

import { query } from "@anthropic-ai/claude-code";

// 自動インシデント対応エージェント
async function investigateIncident(
  incidentDescription: string,
  severity = "medium"
) {
  const messages = [];

  for await (const message of query({
    prompt: `インシデント: ${incidentDescription} (重要度: ${severity})`,
    options: {
      systemPrompt: "あなたはSREの専門家です。問題を診断し、影響を評価し、即座のアクション項目を提供してください。",
      maxTurns: 6,
      allowedTools: ["Bash", "Read", "WebSearch", "mcp__datadog"],
      mcpConfig: "monitoring-tools.json"
    }
  })) {
    messages.push(message);
  }

  return messages.find(m => m.type === "result");
}

// 使用方法
const result = await investigateIncident("決済APIが500エラーを返しています", "high");
console.log(result.result);

自動セキュリティレビュー

import { query } from "@anthropic-ai/claude-code";
import { execSync } from "child_process";

async function auditPR(prNumber: number) {
  // PR差分を取得
  const prDiff = execSync(`gh pr diff ${prNumber}`, { encoding: 'utf8' });

  const messages = [];
  for await (const message of query({
    prompt: prDiff,
    options: {
      systemPrompt: "あなたはセキュリティエンジニアです。このPRの脆弱性、安全でないパターン、コンプライアンス問題をレビューしてください。",
      maxTurns: 3,
      allowedTools: ["Read", "Grep", "WebSearch"]
    }
  })) {
    messages.push(message);
  }

  return messages.find(m => m.type === "result");
}

// 使用方法
const report = await auditPR(123);
console.log(JSON.stringify(report, null, 2));

マルチターン法務アシスタント

import { query } from "@anthropic-ai/claude-code";

async function legalReview() {
  // 法務レビューセッションを開始
  let sessionId: string;

  for await (const message of query({
    prompt: "法務レビューセッションを開始してください",
    options: { maxTurns: 1 }
  })) {
    if (message.type === "system" && message.subtype === "init") {
      sessionId = message.session_id;
    }
  }

  // 同じセッションを使用したマルチステップレビュー
  const steps = [
    "contract.pdfの責任条項をレビューしてください",
    "GDPR要件への準拠を確認してください",
    "リスクのエグゼクティブサマリーを生成してください"
  ];

  for (const step of steps) {
    for await (const message of query({
      prompt: step,
      options: { resume: sessionId, maxTurns: 2 }
    })) {
      if (message.type === "result") {
        console.log(`ステップ: ${step}`);
        console.log(message.result);
      }
    }
  }
}

メッセージスキーマ

JSON APIから返されるメッセージは、以下のスキーマに従って厳密に型付けされています:

type SDKMessage =
  // アシスタントメッセージ
  | {
      type: "assistant";
      uuid: string;
      session_id: string;
      message: Message; // Anthropic SDKから
      parent_tool_use_id: string | null;
    }

  // ユーザーメッセージ(入力)
  | {
      type: "user";
      uuid?: string;
      session_id: string;
      message: MessageParam; // Anthropic SDKから
      parent_tool_use_id: string | null;
    }

  // ユーザーメッセージ(出力/リプレイ、必須UUID付き)
  | {
      type: "user";
      uuid: string;
      session_id: string;
      message: MessageParam; // Anthropic SDKから
      parent_tool_use_id: string | null;
    }

  // 成功時の最後のメッセージとして発行
  | {
      type: "result";
      subtype: "success";
      uuid: UUID;
      session_id: string;
      duration_ms: number;
      duration_api_ms: number;
      is_error: boolean;
      num_turns: number;
      result: string;
      total_cost_usd: number;
      usage: Usage;
      permission_denials: SDKPermissionDenial[];
    }

  // エラーまたは最大ターン時の最後のメッセージとして発行
  | {
      type: "result";
      subtype: "error_max_turns" | "error_during_execution";
      uuid: UUID;
      session_id: string;
      duration_ms: number;
      duration_api_ms: number;
      is_error: boolean;
      num_turns: number;
      total_cost_usd: number;
      usage: Usage;
      permission_denials: SDKPermissionDenial[];
    }

  // 会話の開始時に最初のメッセージとして発行
  | {
      type: "system";
      subtype: "init";
      uuid: UUID;
      session_id: string;
      apiKeySource: "user" | "project" | "org" | "temporary";
      cwd: string;
      tools: string[];
      mcp_servers: {
        name: string;
        status: string;
      }[];
      model: string;
      permissionMode: "default" | "acceptEdits" | "bypassPermissions" | "plan";
      slash_commands: string[];
      output_style: string;
    };

  type SDKPermissionDenial = {
    tool_name: string;
    tool_use_id: string;
    tool_input: Record<string, unknown>;
  }

追加のサポート型:

MessageMessageParamUsage型は、Anthropic TypeScript SDKで利用できます。

関連リソース