Use the Agent SDK to run Claude Code programmatically from the CLI, Python, or TypeScript.
使用 Agent SDK 从 CLI、Python 或 TypeScript 中通过编程运行 Claude Code。
The Agent SDK gives you the same tools, agent loop, and context management that power Claude Code. It's available as a CLI for scripts and CI/CD, or as Python and TypeScript packages for full programmatic control.
Agent SDK 为你提供了与 Claude Code 相同的功能、agent循环和上下文管理工具。它可作为脚本和 CI/CD 的 CLI 使用,或作为 Python 和 TypeScript 包实现完全的程序化控制。
The CLI was previously called "headless mode." The -p flag and all CLI options work the same way.
CLI 之前被称为"无头模式"。 -p 标志和所有 CLI 选项的工作方式相同。
To run Claude Code programmatically from the CLI, pass -p with your prompt and any CLI options:
要在 CLI 中编程运行 Claude Code,请将 -p 与您的提示词和任何 其它CLI 选项一起传递:
claude -p "Find and fix the bug in auth.py" --allowedTools "Read,Edit,Bash"
This page covers using the Agent SDK via the CLI (claude -p). For the Python and TypeScript SDK packages with structured outputs, tool approval callbacks, and native message objects, see the full Agent SDK documentation.
本章介绍了通过 CLI( claude -p )来使用Agent SDK。有关 Python 和 TypeScript SDK 包,包括结构化输出、工具审批回调和原生消息对象,请参阅完整的Agent SDK 文档。
https://platform.claude.com/docs/en/agent-sdk/overview
后续会对Agent SDK文档进行详细介绍
一,Basic usage 基本用法
Add the -p (or --print) flag to any claude command to run it non-interactively. All CLI options work with -p, including:
将 -p (或 --print )标志添加到任何 claude 命令中,以使其非交互式运行。所有 CLI 选项都与 -p 兼容,包括:
--continue for continuing conversations 用于继续对话
--allowedTools for auto-approving tools 用于自动批准工具
--output-format for structured output 用于结构化输出
This example asks Claude a question about your codebase and prints the response:
下面这个例子询问 Claude 关于你的代码库的问题,并打印响应:
claude -p "What does the auth module do?"
二,Examples 示例
These examples highlight common CLI patterns.
下面这些示例展示了常见的 CLI 模式。
2.1,Get structured output 获取结构化输出
Use --output-format to control how responses are returned:
使用 --output-format 控制响应的返回方式:
1,text (default): plain text output 纯文本输出
2,json: structured JSON with result, session ID, and metadata
带有结果、会话 ID 和元数据的结构化 JSON
3,stream-json: newline-delimited JSON for real-time streaming
用于实时流式传输的新行分隔 JSON
This example returns a project summary as JSON with session metadata, with the text result in the result field:
下面这个示例返回一个项目摘要作为 JSON,包含会话元数据,文本结果在 result 字段中:
claude -p "Summarize this project" --output-format json
To get output conforming to a specific schema, use --output-format json with --json-schema and a JSON Schema definition.
The response includes metadata about the request (session ID, usage, etc.) with the structured output in the structured_output field.
要获取符合特定模式的输出,使用 --output-format json 与 --json-schema 和一个 JSON 模式定义。
响应包含请求的元数据(会话 ID、使用情况等),结构化输出在 structured_output 字段中。
This example extracts function names and returns them as an array of strings:
下面这个示例提取函数名,并将它们作为字符串数组返回:
```bash
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"]}'
```
其中,--json-schema:你返回的 JSON 必须严格符合这个结构,定义了返回数据必须是一个对象,里面必须有 functions 键,且是个字符串数组
比如
{
"functions": [
"login_user",
"register_user",
"verify_token",
"refresh_token",
"logout"
]
}
Use a tool like jq to parse the response and extract specific fields:
使用 jq 之类的工具解析响应并提取特定字段:
```bash
Extract the text result
claude -p "Summarize this project" --output-format json | jq -r '.result'
Extract structured output
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'
```
2.2,Auto-approve tools 自动批准工具
Use --allowedTools to let Claude use certain tools without prompting. This example runs a test suite and fixes failures, allowing Claude to execute Bash commands and read/edit files without asking for permission:
使用 --allowedTools 让 Claude 无需提示即可使用某些工具。下面的示例运行测试套件并修复失败,允许 Claude 执行 Bash 命令和读写文件而无需请求权限:
```bash
claude -p "Run the test suite and fix any failures" \
--allowedTools "Bash,Read,Edit"
```
2.3,Create a commit 创建一个提交
This example reviews staged changes and creates a commit with an appropriate message:
下面的示例审查暂存更改,并使用适当的消息创建一个提交:
```bash
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 *)"
```
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 标志使用权限规则语法。尾部 * 启用前缀匹配,因此 Bash(git diff *) 允许任何以 git diff 开头的命令。 * 前的空格很重要:没有它, Bash(git diff*) 也会匹配 git diff-index 。
User-invoked skills like /commit and built-in commands are only available in interactive mode. In -p mode, describe the task you want to accomplish instead.
用户触发的技能如 /commit 和内置命令仅在交互模式下可用。在 -p 模式下,请描述您想要完成的任务。
2.4,Customize the system prompt 自定义系统提示
Use --append-system-prompt to add instructions while keeping Claude Code's default behavior. This example pipes a PR diff to Claude and instructs it to review for security vulnerabilities:
使用 --append-system-prompt 添加指令,同时保留 Claude Code 的默认行为。下面示例将 PR 差异管道传输到 Claude,并指示其检查安全漏洞:
```basg
gh pr diff "$1" | claude -p \
--append-system-prompt "You are a security engineer. Review for vulnerabilities." \
--output-format json
```
--system-prompt to fully replace the default prompt. 这个可以完全替换默认的系统提示词
2.5,Continue conversations 继续对话
Use --continue to continue the most recent conversation, or --resume with a session ID to continue a specific conversation. This example runs a review, then sends follow-up prompts:
使用 --continue 继续最近的对话,或使用 --resume 加上会话 ID 继续特定对话。下面示例运行一次评审,然后发送后续提示:
```bash
First request
claude -p "Review this codebase for performance issues" #审查这个代码库的性能问题
Continue the most recent conversation
claude -p "Now focus on the database queries" --continue #现在专注于数据库查询
claude -p "Generate a summary of all issues found" --continue #生成发现的所有问题的摘要
```
If you're running multiple conversations, capture the session ID to resume a specific one:
如果你正在运行多个对话,捕获会话 ID 以继续特定的对话:
```bash
session_id=$(claude -p "Start a review" --output-format json | jq -r '.session_id')
claude -p "Continue that review" --resume "$session_id"
```
小结
将 -p (或 --print )标志添加到任何 claude 命令中,以使其非交互式运行