一行要約

claude -p は Agent SDK の CLI 版であり、CI やスクリプトで再現性が要るなら --bare(hook / skill / plugin / MCP / auto memory / CLAUDE.md の自動発見をすべて飛ばす)を付けるのが推奨。

要点

基本

claude -p "Find and fix the bug in auth.py" --allowedTools "Read,Edit,Bash"
  • 成功で exit code 0、失敗で非ゼロ。スクリプトは exit status で分岐できる
  • 不正なフラグは実行前に stderr へ報告される。実行中の失敗(認証エラーなど)は stdout に結果として出る
  • -p と併用できないオプションがある — --bg は拒否される。--cloud はタスク記述と併用すると拒否され、セッション ID と併用するとそのクラウドセッションにメッセージを積んで終了する

--bare(CI での推奨)

Add --bare to reduce startup time by skipping auto-discovery of hooks, skills, plugins, MCP servers, auto memory, and CLAUDE.md. --bare を付けると、hook・skill・plugin・MCP サーバ・auto memory・CLAUDE.md の自動探索を省略して起動時間を短縮できる。

A hook in a teammate’s ~/.claude or an MCP server in the project’s .mcp.json won’t run, because bare mode never reads them. teammate の ~/.claude にある hook や、プロジェクトの .mcp.json にある MCP サーバは動かない。bare モードはそれらを一切読まないからである。

認証の注意: bare mode は OAuth 認証情報も system keychain も読まない。Anthropic API を使うなら ANTHROPIC_API_KEY を環境に設定する(Bedrock / Agent Platform / Foundry は各プロバイダの認証情報を通常どおり読む)。

bare mode で使えるツールは Bash、ファイル読み取り、ファイル編集。必要な context はフラグで渡す。

ロードしたいものフラグ
system prompt への追記--append-system-prompt, --append-system-prompt-file
設定--settings <file-or-json>
MCP サーバ--mcp-config <file-or-json>
カスタムエージェント--agents <json>
plugin--plugin-dir <path>, --plugin-url <url>

出力形式

--output-format内容
text(既定)プレーンテキスト
json結果・セッション ID・メタデータを含む構造化 JSON。total_cost_usd とモデル別のコスト内訳も含む(クライアント側の推定値)
stream-json改行区切り JSON。リアルタイムストリーミング

スキーマに従わせるには --output-format json + --json-schema。結果は structured_output フィールドに入る。

Claude Code accepts schemas that use the format keyword, such as "format": "email", but treats format as an annotation and doesn’t enforce it. Claude Code は "format": "email" のように format キーワードを使うスキーマを受け付けるが、format は注釈として扱い、強制はしない

ストリーミング

--output-format stream-json --verbose --include-partial-messages でトークンごとに受け取る。最後の行は result メッセージで、最終応答テキスト・コスト・セッションメタデータを含む。

subagent のメッセージparent_tool_use_id にそれを起こしたツール呼び出しの ID を持つ(メイン会話は null)。既定では subagent の tool_use / tool_result ブロックだけが出る。 --forward-subagent-text または CLAUDE_CODE_FORWARD_SUBAGENT_TEXT でテキストと thinking も出せる。入れ子の subagent も全深さで転送されるので、ID を辿れば入れ子ツリーを再構築できる。

主要なイベント:

イベント用途
system/initセッションメタデータ(モデル、ツール、MCP サーバ、plugin)。通常は最初のイベント
system/api_retryリトライ可能なエラーでの再試行。attempt / max_retries / retry_delay_ms / error_status / error
system/plugin_installmarketplace plugin のインストール進捗(CLAUDE_CODE_SYNC_PLUGIN_INSTALL 設定時)

CI で plugin / MCP のロード失敗を検知するsystem/init のフィールド):

フィールド内容
pluginsロードに成功した plugin
plugin_errorsロード時エラー。エラーがなければキー自体が省略される
mcp_serversセッション内の MCP サーバと status
mcp_server_errors検証で skip された --mcp-config エントリ。エラーがなければキーが省略されるので、非空配列で CI を落とせる

system/initcapabilities 配列を見ればプロトコル挙動を feature-detect できる。バージョン文字列の比較ではなくこちらを使う。

権限の扱い

  • --allowedTools で個別ツールを事前承認する
  • セッション全体の基準を決めるなら permission mode を渡す
    • dontAskpermissions.allow と読み取り専用コマンド以外を拒否。ロックダウンした CI 向け
    • acceptEdits — ファイル書き込みと mkdir / touch / mv / cp を自動承認。それ以外のシェルコマンドとネットワークリクエストには --allowedTools か allow ルールが要る。なければ実行しようとした時点で run が中断する

The --allowedTools flag uses permission rule syntax. The trailing * enables prefix matching, so Bash(git diff *) allows any command starting with git diff. The space before * is important: without it, Bash(git diff*) would also match git diff-index. --allowedTools フラグは permission ルールの構文を使う。末尾の * が前方一致を有効にするので、Bash(git diff *)git diff で始まる任意のコマンドを許可する。* の前の空白が重要である。空白がないと Bash(git diff*)git diff-index にも一致してしまう。

バックグラウンドタスクの扱い

  • バックグラウンド Bash タスク(dev server や watch build)は、最終結果が返り stdin が閉じてから約5秒後に終了させられる
  • バックグラウンドの subagent と workflow はこの5秒の対象外 — 結果が最終出力の一部なので claude -p は完了を待つ。待ち時間は既定で最大10分CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS で調整、0 で無制限)
  • SIGTERM で停止すると、進行中のターンを中断し、実行中の Bash のプロセスツリーを終了させ、SessionEnd hook を走らせて exit code 143 で終了する

その他の注意

  • パイプで渡す stdin は 10MB が上限。 超えるとエラーで非ゼロ終了する。大きい入力はファイルに書いてパスをプロンプトで参照する
  • -p モードでも user-invocable な skill とカスタムコマンドは使える — プロンプト文字列に /skill-name を入れれば展開される。/login のような端末専用の組み込みコマンドは使えない
  • /model/effort/fast/color/rename は値を引数として受け取る(/model sonnet)。設定変更は /config thinking=false の形

そのまま使える具体例

CI 向けの最小形:

claude --bare -p "Summarize README.md" --allowedTools "Read"

パイプで渡してファイルに書き出す:

cat build-error.txt | claude -p 'concisely explain the root cause of this build error' > output.txt

package.json に typo linter として組み込むdiff をパイプするので Bash 権限が不要になるのが巧い):

{
  "scripts": {
    "lint:claude": "git diff main | claude -p \"you are a typo linter. for each typo in this diff, report filename:line on one line and the issue on the next. return nothing else.\""
  }
}

構造化出力:

claude -p "Extract the main function names from auth.py" \
  --output-format json \
  --json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}'

jq で取り出す:

claude -p "Summarize this project" --output-format json | jq -r '.result'
 
claude -p "Extract function names from auth.py" \
  --output-format json \
  --json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}' \
  | jq '.structured_output'

ストリーミングしてテキストだけ流す:

claude -p "Write a poem" --output-format stream-json --verbose --include-partial-messages | \
  jq -rj 'select(.type == "stream_event" and .event.delta.type? == "text_delta") | .event.delta.text'

ツールを事前承認する:

claude -p "Run the test suite and fix any failures" \
  --allowedTools "Bash,Read,Edit"
 
claude -p "Apply the lint fixes" --permission-mode acceptEdits

コミットを作らせる(接頭辞マッチの空白に注意):

claude -p "Look at my staged changes and create an appropriate commit" \
  --allowedTools "Bash(git diff *),Bash(git log *),Bash(git status *),Bash(git commit *)"

PR のセキュリティレビュースクリプトreview.shbash review.sh 123 で実行):

gh pr diff "$1" | claude -p \
  --append-system-prompt "You are a security engineer. Review for vulnerabilities." \
  --output-format json

会話を継続する:

# First request
claude -p "Review this codebase for performance issues"
 
# Continue the most recent conversation
claude -p "Now focus on the database queries" --continue
 
# 特定のセッションを resume する
session_id=$(claude -p "Start a review" --output-format json | jq -r '.session_id')
claude -p "Continue that review" --resume "$session_id"

原典で言及されている関連文書

  • permission-modesdontAsk / acceptEdits の詳細
  • sub-agents — バックグラウンド subagent の待機とツールセット
  • hooks-guide-p モードで走る hook(--bare では走らない)
  • workflows-p では workflow が待機実行になる
  • costs--output-format jsontotal_cost_usd

未取得の派生リンク