Headless 模式跟 Agent SDK
在腳本跟 CI/CD pipeline 自動跑 Claude
⏱ 預估 ~6 分鐘
01 · 讀一讀
你目前跟 Claude Code 做的一切都是互動的 — 你打、Claude 回、你核准。但如果你要 Claude 自動跑呢?在每個 pull request 審查的 CI/CD pipeline?每晚修 lint 錯誤的腳本?
Headless 模式(claude -p)沒互動終端機跑 Claude。你給它 prompt、它做事、回結果。沒打字、沒核准對話框 — 就輸入跟輸出。
這是團隊把 Claude 整合到自動流程的方式:code review bot、test fixer、文件產生器,跟更多。
💡 想像一下互動 Claude 像在你桌前跟同事對話。Headless Claude 像 email 任務給他們 — 你送請求、他們做、你拿結果回來。不用來回。
重點整理
- claude -p 非互動跑 Claude(headless 模式)
- 適合腳本、CI/CD pipeline、自動化
- 沒核准對話 — 預先指定允許的工具
- 輸出可以是文字、JSON、串流 JSON
02 · 看程式碼
下面是常見 headless 模式模式。-p 旗標讓它非互動。
基本 headless 用法
# Simple query
claude -p "Find all TODO comments in this project"
# With allowed tools (auto-approved, no prompts)
claude -p "Run tests and fix failures" \
--allowedTools "Bash(npm test*),Read,Edit"
# Structured JSON output
claude -p "List all API endpoints" \
--output-format json
-p 旗標('print' 縮寫)讓 Claude 非互動跑。--allowedTools 預先核准特定工具,Claude 不用 permission 提示就能工作。--output-format json 回結構化資料而不是純文字 — 別的程式要 parse 結果時有用。
03 · 看程式碼
下面是團隊怎麼在 CI/CD pipeline 用 headless 模式 — 每個 pull request 跑的自動 code reviewer。
GitHub Actions — 自動 code review
# .github/workflows/claude-review.yml
name: Claude Code Review
on: [pull_request]
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Review PR
run: |
claude -p "Review the changes in this PR. \
Focus on bugs, security, and performance." \
--allowedTools "Read,Grep,Glob" \
--output-format text
這 GitHub Action 在每個 pull request headless 模式跑 Claude。它只允許 read-only 工具(Read、Grep、Glob)、Claude 能分析程式但不能改任何東西。Review 輸出出現在 CI log 給團隊讀。
04 · 讀一讀
更複雜自動化,Anthropic 提供 Agent SDK — Claude 工具支援的 Python 跟 TypeScript 函式庫建 production agent。
Agent SDK 給你一切的程式化控制:有哪些工具、怎麼處理結果、session 管理(接續對話)、甚至 MCP server 連線。它是支援最複雜 Claude Code 整合的。
CLI(claude -p)適合簡單自動化。Agent SDK 給你要完整程式控制時用 — 自訂錯誤處理、串流結果、串多個 Claude 呼叫、或在 Claude 能力上蓋產品。
重點整理
- Agent SDK:Python 跟 TypeScript 函式庫做 production agent
- 完整程式控制工具、session、結果
- CLI(claude -p):簡單自動化跟腳本
- Agent SDK:複雜應用程式跟 production 系統
- Session 管理:程式化捕獲跟接續對話
05 · 看程式碼
下面是 TypeScript 簡單 Agent SDK 例子,程式化找跟修 bug。
Agent SDK — bug fixer
import { query } from '@anthropic-ai/claude-agent-sdk';
for await (const msg of query({
prompt: "Find and fix the failing test in auth.test.ts",
options: {
allowedTools: ["Read", "Edit", "Bash"],
}
})) {
if (msg.result) {
console.log('Fix applied:', msg.result);
}
}
Agent SDK 給你串流介面 — Claude 工作你迭代訊息。allowedTools 陣列控制 Claude 能做什麼。Claude 完成時,result 訊息有做了什麼的總結。這是怎麼蓋能讀、編、跑指令的自動 agent。
06 · 選擇題
哪個旗標讓 Claude Code 非互動跑,沒互動終端機?
- claude --headless
- claude --auto
- claude -p
- claude --batch
07 · 填空
在 CI/CD pipeline 跑 Claude 不要使用者互動,用 claude _____ "你的 prompt"。
08 · 配對
配對每種自動化方法到最佳用途。
(本節為互動練習,請啟用 JavaScript 體驗)
⚠ 完整互動體驗需要 JavaScript。請啟用 JavaScript 後重新整理。
※ 本站為獨立繁中教學專案,非 Anthropic 官方產品。Claude™ 為 Anthropic, PBC 商標。