claude-code-headless について
claude-code-headlessは、スクリプトからClaude Codeを非対話で実行するスキルです。構造化出力、セッション継続、ツール権限、CI/CDでの利用方法を扱います。
主な機能
- 01非対話型CLI実行
- 02テキスト・JSON・stream-JSON出力
- 03セッションの再開と継続
- 04ツールの許可・拒否
- 05権限モードの設定
活用シーン
- 01スクリプトでのコード分析自動化
- 02CI/CDジョブでの応答解析
- 03セッションIDを使った複数ターン処理
MCP 対応
MCPサーバー設定ファイルを指定する `--mcp-config` オプションを紹介しています。
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ 0xdarkmatter/ claude-mods --skill claude-code-headlessインストール後、Claude Code で/claude-code-headlessを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
assets/.gitkeepreferences/output-formats.mdintegration-patterns.mdcli-options.mdscripts/.gitkeep詳細
Claude Code ヘッドレスモード
インタラクティブ UI を使わず、スクリプトから Claude Code を実行します。
クイックスタート
# Basic headless execution
claude -p "Explain this code" --allowedTools "Read,Grep"
# JSON output for parsing
claude -p "List files" --output-format json
# Continue conversation
claude -p "Start analysis" --output-format json > result.json
session=$(jq -r '.session_id' result.json)
claude --resume "$session" "Now fix the issues"
主な CLI オプション
| フラグ | 説明 |
|---|---|
-p, --print | 非インタラクティブ(ヘッドレス)モード |
--output-format | text、json、stream-json |
-r, --resume | セッション ID で再開 |
-c, --continue | 直近のセッションを続行 |
--allowedTools | 許可するツールをカンマ区切りで指定 |
--disallowedTools | 拒否するツールをカンマ区切りで指定 |
--mcp-config | MCP サーバー設定 JSON のパス |
--verbose | 詳細ログを有効化 |
--append-system-prompt | システムプロンプトに追加 |
権限モード
| モード | フラグ | 動作 |
|---|---|---|
| デフォルト | (なし) | 権限を確認します |
| 編集を承認 | --permission-mode acceptEdits | ファイルの変更を自動承認します |
| バイパス | --permission-mode bypassPermissions | すべての確認を省略します |
出力形式
テキスト(デフォルト)
claude -p "Hello"
# Outputs: Human-readable response
JSON
claude -p "Hello" --output-format json
{
"type": "result",
"subtype": "success",
"result": "Hello! How can I help?",
"session_id": "abc123",
"total_cost_usd": 0.001,
"duration_ms": 1234,
"num_turns": 1
}
Stream-JSON
claude -p "Hello" --output-format stream-json
# Real-time JSONL output for each message
よくあるパターン
ツールを制限したスクリプト
claude -p "Analyze the codebase" \
--allowedTools "Read,Grep,Glob" \
--disallowedTools "Write,Edit,Bash"
CI/CD との連携
claude -p "Review this PR diff" \
--permission-mode acceptEdits \
--output-format json \
--append-system-prompt "Focus on security issues"
複数ターンの自動化
session=$(claude -p "Start task" --output-format json | jq -r '.session_id')
claude --resume "$session" "Continue with step 2"
claude --resume "$session" "Finalize and report"
エラー処理
result=$(claude -p "Task" --output-format json)
if [[ $(echo "$result" | jq -r '.is_error') == "true" ]]; then
echo "Error: $(echo "$result" | jq -r '.result')" >&2
exit 1
fi
公式ドキュメント
- https://code.claude.com/docs/en/headless - ヘッドレスモードのリファレンス
- https://code.claude.com/docs/en/settings - 設定と権限
その他のリソース
./references/cli-options.md- CLI フラグの完全なリファレンス./references/output-formats.md- 出力形式のスキーマ./references/integration-patterns.md- CI/CD とスクリプトの例
関連項目: 自動化イベントについては claude-code-hooks、トラブルシューティングについては claude-code-debug を参照してください。
コメント
Markdown 対応