主题
Headless 与 Agent SDK(编程式)
用 Agent SDK 以编程方式运行 Claude Code:通过 CLI(claude -p)在脚本/CI 中跑,或用 Python/TypeScript 包做完整程序控制。
是什么
Headless(非交互)模式让你不进入交互式 TUI 就运行 Claude Code,核心是给任意 claude 命令加 -p(即 --print)让它一次性执行并打印结果。它由 Agent SDK 提供支撑——SDK 给你与 Claude Code 相同的 tools、agent loop 和 context management,既可作为 CLI 用于脚本和 CI/CD,也可作为 Python 和 TypeScript 包做完整的程序化控制(结构化输出、工具审批回调、原生 message 对象)。本页专讲通过 CLI(claude -p)使用 Agent SDK;Python/TS 包另见 Agent SDK 文档。
怎么工作
- 给任意 claude 命令加 -p(或 --print)即进入非交互模式:一次性接收 prompt、执行、打印响应后退出。例:claude -p "What does the auth module do?"。所有 CLI options 都可与 -p 配合使用。
- 默认(不加 --bare)时,claude -p 会加载与交互式会话相同的 context,包括工作目录或 ~/.claude 中配置的 hooks、skills、plugins、MCP servers、auto memory 和 CLAUDE.md(auto-discovery 自动发现)。
- --bare 模式跳过上述全部自动发现以缩短启动时间:teammate 的 ~/.claude 里的 hook、项目 .mcp.json 里的 MCP server 都不会跑,因为 bare 模式根本不读取它们;只有你显式传入的 flag 才生效。这保证 CI/脚本在每台机器上得到相同结果。
- bare 模式下 Claude 默认仍能用 Bash、file read、file edit 三类工具;其它 context 必须用 flag 显式注入(system prompt、settings、MCP、agents、plugin)。
- bare 模式还跳过 OAuth 和 keychain 读取,因此 Anthropic 鉴权必须来自 ANTHROPIC_API_KEY,或来自传给 --settings 的 JSON 中的 apiKeyHelper;Bedrock/Vertex/Foundry 用各自 provider 的常规凭证。
- 非交互模式会读取 stdin,可像普通命令行工具一样管道输入、重定向输出,例:cat build-error.txt | claude -p '...' > output.txt。
- --output-format 控制响应格式;其中 json 含 result/session ID/metadata,可用 jq 解析;stream-json 为按行分隔的 JSON 事件流(real-time streaming)。
- 流式事件类型:system/init 是首个事件(除非设了 CLAUDE_CODE_SYNC_PLUGIN_INSTALL,此时 plugin_install 事件先于它);API 请求遇可重试错误时在重试前发 system/api_retry 事件。
- 权限:--allowedTools 让指定工具免确认;也可用 permission mode 设整会话基线(dontAsk / acceptEdits)。allowedTools 用 permission rule syntax,支持前缀匹配。
- 会话延续:--continue 续最近一次对话;--resume <session_id> 续指定会话(session_id 可从 --output-format json 的 .session_id 取得)。
怎么配置 / 用法
基本调用:claude -p "Find and fix the bug in auth.py" --allowedTools "Read,Edit,Bash"
bare 模式(推荐用于脚本/SDK/CI):claude --bare -p "Summarize this file" --allowedTools "Read"
bare 模式下注入 context 的 flag:
- System prompt additions:
--append-system-prompt、--append-system-prompt-file - Settings:
--settings <file-or-json> - MCP servers:
--mcp-config <file-or-json> - Custom agents:
--agents <json> - A plugin:
--plugin-dir <path>、--plugin-url <url>
管道 + 重定向:cat build-error.txt | claude -p 'concisely explain the root cause of this build error' > output.txt
package.json 里做 linter(注意转义双引号以兼容 Windows): "lint:claude": "git diff main | claude -p \"you are a typo linter. ...\""
结构化输出(schema):
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"]}'结构化结果在 structured_output 字段;用 jq '.structured_output' 取。
流式:claude -p "Explain recursion" --output-format stream-json --verbose --include-partial-messages 过滤 text delta:| jq -rj 'select(.type == "stream_event" and .event.delta.type? == "text_delta") | .event.delta.text'
权限模式:claude -p "Apply the lint fixes" --permission-mode acceptEdits
创建 commit(前缀匹配,注意 * 前的空格): 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 *)"
追加 system prompt:gh pr diff "$1" | claude -p --append-system-prompt "You are a security engineer. Review for vulnerabilities." --output-format json
续会话:
claude -p "Review this codebase for performance issues"
claude -p "Now focus on the database queries" --continue
session_id=$(claude -p "Start a review" --output-format json | jq -r '.session_id')
claude -p "Continue that review" --resume "$session_id"什么时候用
- 在脚本、CI/CD、build script 中以非交互方式跑 Claude Code 时用 -p。
- CI/脚本中务必加 --bare:需要每台机器结果一致、不被本地随意配置(teammate 的 hook、项目 MCP)污染时。
- 需要把命令行数据(如 build log、git diff、PR diff)喂给 Claude 并重定向输出时,用管道 + -p。
- 需要脚本可解析的结果时用 --output-format json(含 total_cost_usd 和 per-model cost breakdown,可逐次追踪花费而不必查 usage dashboard);需要严格符合 schema 的结果用 --json-schema。
- 需要实时 token 流时用 --output-format stream-json --verbose --include-partial-messages。
- 需要完整程序控制(结构化输出、工具审批回调、原生 message 对象)时,别用 CLI,改用 Python 或 TypeScript 的 Agent SDK 包。
- 不要在 -p 模式里指望 user-invoked skills(如 /code-review)或 built-in commands——它们只在交互模式可用;-p 模式下应直接描述要完成的任务。
限制 / 坑
- user-invoked skills(如 /code-review)和 built-in commands 只在 interactive mode 可用;-p 模式下不可用,需改为直接描述任务。
- 自 Claude Code v2.1.128 起,管道 stdin 上限为 10MB;超限会以清晰错误 + 非零状态退出。处理更大输入需写入文件并在 prompt 中引用文件路径,而非管道。
- bare 模式不读取 hooks、skills、plugins、MCP servers、auto memory、CLAUDE.md——任何未显式传入的 flag 都不生效。
- bare 模式跳过 OAuth 和 keychain 读取,鉴权必须来自 ANTHROPIC_API_KEY 或 --settings JSON 中的 apiKeyHelper(Bedrock/Vertex/Foundry 用各自凭证)。
- permission mode dontAsk 会拒绝不在 permissions.allow 规则或 read-only command set 内的一切操作。
- acceptEdits 仅免确认写文件并自动批准 mkdir/touch/mv/cp 等常见文件系统命令;其它 shell 命令和 network 请求仍需 --allowedTools 条目或 permissions.allow 规则,否则一旦尝试就 abort。
- allowedTools 前缀匹配中 * 前的空格很关键:Bash(git diff ) 才正确;Bash(git diff) 会误匹配 git diff-index。
- 重要计费变更:自 June 15, 2026 起,订阅计划上的 Agent SDK 和 claude -p 用量将从一个新的 monthly Agent SDK credit 扣除,与交互式使用额度分开。
硬事实速查(25 条)
- -p 等价于 --print,是进入非交互模式的核心 flag。
- --bare:跳过 hooks/skills/plugins/MCP servers/auto memory/CLAUDE.md 的 auto-discovery,缩短启动;官方称是 scripted 和 SDK 调用的推荐模式,未来会成为 -p 的默认。
- bare 模式默认可用工具:Bash、file read、file edit。
- --output-format 取值三种:text(默认,纯文本)、json(带 result/session ID/metadata 的结构化 JSON)、stream-json(按行分隔 JSON,real-time streaming)。
- json 输出中文本结果在 result 字段;--json-schema 的结构化结果在 structured_output 字段。
- --output-format json 响应包含 total_cost_usd 和 per-model cost breakdown。
- 流式需要三个 flag 组合:--output-format stream-json + --verbose + --include-partial-messages。
- context 注入 flag:--append-system-prompt、--append-system-prompt-file、--settings <file-or-json>、--mcp-config <file-or-json>、--agents <json>、--plugin-dir <path>、--plugin-url <url>。
- --system-prompt 可完全替换默认 prompt;--append-system-prompt 在保留默认行为基础上追加。
- 权限 flag:--allowedTools(逗号分隔工具列表,用 permission rule syntax,支持
*前缀匹配)、--permission-mode(如 acceptEdits、dontAsk)。 - permission mode dontAsk:拒绝不在 permissions.allow 或 read-only command set 内的操作,适合 locked-down CI。
- permission mode acceptEdits:免确认写文件,并自动批准 mkdir、touch、mv、cp。
- 会话延续:--continue(续最近一次)、--resume <session_id>(续指定会话)。
- session_id 取法:claude -p ... --output-format json | jq -r '.session_id'。
- 鉴权来源(bare 模式):ANTHROPIC_API_KEY 或 --settings JSON 内 apiKeyHelper;Bedrock/Vertex/Foundry 用 provider 凭证。
- 环境变量 CLAUDE_CODE_SYNC_PLUGIN_INSTALL:设置后 plugin_install 事件先于 system/init;marketplace plugins 在 first turn 前安装时发 system/plugin_install 事件。
- system/init 事件报告 session metadata:model、tools、MCP servers、loaded plugins;是 stream 首个事件(除非设了 CLAUDE_CODE_SYNC_PLUGIN_INSTALL)。
- system/init 的 plugins 字段:成功加载的 plugin(每个含 name 和 path);plugin_errors 字段:加载错误(每个含 plugin、type、message),可用来在 plugin 未加载时 fail CI(无错误时该 key 省略)。
- system/api_retry 事件字段:type="system"、subtype="api_retry"、attempt(整数,从 1 起)、max_retries(整数)、retry_delay_ms(整数)、error_status(整数或 null,连接错误无 HTTP 响应时为 null)、error(类别:authentication_failed/oauth_org_not_allowed/billing_error/rate_limit/invalid_request/model_not_found/server_error/max_output_tokens/unknown)、uuid、session_id。
- system/plugin_install 事件 status 取值:started、installed、failed、completed(started/completed 包住整体安装;installed/failed 报告单个 marketplace);可选字段 name、error;含 uuid、session_id。
- stdin 上限 10MB(自 Claude Code v2.1.128 起);超限报错 + 非零退出码。
- JSON Schema 例(提取函数名为字符串数组):{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}。
- Agent SDK 提供与 Claude Code 相同的 tools、agent loop、context management;有 Python 和 TypeScript 包。
- 计费:自 June 15, 2026,订阅计划上 Agent SDK 和 claude -p 用量改从独立的 monthly Agent SDK credit 扣除。
- 流式 jq 技巧:-r 输出 raw 字符串(无引号),-j 不加换行连接(token 连续流出)。