環境変数

CLAUDE_CODE_SESSION_ID

Bash および PowerShell ツールのサブプロセス、フックコマンドのサブプロセス、stdio MCP サーバーのサブプロセスで、現在のセッション ID に自動設定される。Bash、PowerShell、フックではフック JSON 入力の session_id フィールドと一致し、/clear で更新される。MCP サーバーのサブプロセスは起動時に受け取った ID を保持する。--resume <session-id> を付けると、フックや Bash と一致する再開後の ID を受け取る。--continue や ID を明示しない --resume の場合は、代わりに最初の起動時の ID を受け取ることがある。スクリプトや外部ツールを、それを起動した Claude Code のセッションと関連付けるために使う。

使い方・用途

  • Bash や hooks に渡される session_id と同じ値をスクリプト側で参照できるため、セッションごとのログや成果物を一意に紐付ける仕組みを外部ツールで構築できる
  • stdio MCP サーバーのサブプロセスにもセッション ID が渡るため、MCP サーバー側から起動元のセッションを識別して動作を切り替えられる
  • -resume で再開したセッションでは再開後のセッション ID が Bash・hooks・stdio MCP サーバーに一貫して渡るため、再開後もセッションに紐付いた外部ツールの記録を継続できる
英語原文(公式ドキュメントより)

Set automatically to the current session ID in Bash and PowerShell tool subprocesses, hook command subprocesses, and stdio MCP server subprocesses. For Bash, PowerShell, and hooks this matches the session_id field in the hook JSON input and is updated on /clear. An MCP server subprocess retains the ID it was spawned with. On --resume <session-id> it receives the resumed ID, matching hooks and Bash. On --continue or --resume without an explicit ID it may receive the initial startup ID instead. Use to correlate scripts and external tools with the Claude Code session that launched them

関連する変更履歴

v2.1.163(1件)

Changed
stdio MCP サーバーが、--resume 実行時にフックや Bash と同じ CLAUDE_CODE_SESSION_ID を受け取るよう変更
英語原文を表示
stdio MCP servers now receive the same CLAUDE_CODE_SESSION_ID as hooks/Bash on --resume

変更後

外部ツールやログの相関分析を行う際に、MCP サーバーの動作を正確に現在のセッションに紐付けることができます。

関連ドキュメント

v2.1.154(1件)

Changed
Stdio MCPサーバーのサブプロセスに、環境変数CLAUDE_CODE_SESSION_IDとCLAUDECODE=1が渡されるようになりました。
英語原文を表示
Stdio MCP server subprocesses now receive CLAUDE_CODE_SESSION_ID and CLAUDECODE=1 in their environment

変更後

MCPサーバー側でセッションごとのログを記録したり、Claude Codeからの呼び出し時のみ特定の挙動をさせたりといった、より高度なインテグレーションが可能になります。

関連ドキュメント

v2.1.132(1件)

Added
Bash ツールのサブプロセス環境に CLAUDE_CODE_SESSION_ID 環境変数を追加し、フックに渡される session_id と一致させました
英語原文を表示
Added CLAUDE_CODE_SESSION_ID environment variable to the Bash tool subprocess environment, matching the session_id passed to hooks

変更後

セッションごとにログを分けたり、フックで開始した外部プロセスと Bash ツールでの操作を紐付けたりする自動化ワークフローがより確実かつ簡単に構築できるようになります。

関連ドキュメント