Claude 代码 SDK
Claude Code SDK

原始链接: https://docs.anthropic.com/en/docs/claude-code/sdk

Claude Code SDK允许开发者通过命令行接口以编程方式将Claude Code集成到应用程序中,TypeScript和Python SDK即将推出。它支持非交互式使用,方便了AI驱动的编程助手。 主要功能包括: * **多轮对话:**恢复或继续现有会话。 * **自定义提示:**覆盖或追加默认系统提示。 * **MCP配置:**通过JSON配置集成外部工具和资源,需要使用`--allowedTools`标志明确允许工具。 可用的输出格式包括文本(默认)、JSON(结构化数据)和流式JSON(逐条消息)。SDK支持各种CLI选项来控制输出格式、恢复对话、限制轮数和管理MCP工具。 最佳实践包括:使用JSON输出进行解析;处理错误;管理会话;设置超时;以及遵守速率限制。一个实际应用是Claude Code GitHub Actions。

这篇 Hacker News 讨论串探讨了 Anthropic 的 Claude Code SDK 及其对软件开发的潜在影响。评论者们就编码代理的“理想最终状态”展开了辩论,一些人设想 AI 能够处理大部分编码任务,从而解放人类去从事更高层次的设计和策划工作。另一些人则更倾向于基于键盘的交互和异步通信。讨论还涉及到软件工程师可能面临的失业问题、清晰 Jira 任务的重要性以及开源编码代理的兴起。用户们比较了 Claude Code 与其他 AI 编码工具(如 Aider 和 OpenAI 的 Codex),讨论了它们的优缺点,尤其是在用户体验和与各种模型的集成方面。成本考量、Anthropic 的 Max 计划的优势以及 Gemini 作为强劲竞争对手的出现也得到了探讨。一些用户表达了对 Claude Code 开源版本的渴望,并强调了其他工具的优势。
相关文章

原文

The Claude Code SDK allows developers to programmatically integrate Claude Code into their applications. It enables running Claude Code as a subprocess, providing a way to build AI-powered coding assistants and tools that leverage Claude’s capabilities.

The SDK currently support command line usage. TypeScript and Python SDKs are coming soon.

Basic SDK usage

The Claude Code SDK allows you to use Claude Code in non-interactive mode from your applications. Here’s a basic example:

Advanced usage

Multi-turn conversations

For multi-turn conversations, you can resume conversations or continue from the most recent session:

Custom system prompts

You can provide custom system prompts to guide Claude’s behavior:

You can also append instructions to the default system prompt:

MCP Configuration

The Model Context Protocol (MCP) allows you to extend Claude Code with additional tools and resources from external servers. Using the --mcp-config flag, you can load MCP servers that provide specialized capabilities like database access, API integrations, or custom tooling.

Create a JSON configuration file with your MCP servers:

Then use it with Claude Code:

Note: When using MCP tools, you must explicitly allow them using the --allowedTools flag. MCP tool names follow the pattern mcp__<serverName>__<toolName> where:

  • serverName is the key from your MCP configuration file
  • toolName is the specific tool provided by that server

This security measure ensures that MCP tools are only used when explicitly permitted.

Available CLI options

The SDK leverages all the CLI options available in Claude Code. Here are the key ones for SDK usage:

FlagDescriptionExample
--print, -pRun in non-interactive modeclaude -p "query"
--output-formatSpecify output format (text, json, stream-json)claude -p --output-format json
--resume, -rResume a conversation by session IDclaude --resume abc123
--continue, -cContinue the most recent conversationclaude --continue
--verboseEnable verbose loggingclaude --verbose
--max-turnsLimit agentic turns in non-interactive modeclaude --max-turns 3
--system-promptOverride system prompt (only with --print)claude --system-prompt "Custom instruction"
--append-system-promptAppend to system prompt (only with --print)claude --append-system-prompt "Custom instruction"
--allowedToolsComma/space-separated list of allowed tools (includes MCP tools)claude --allowedTools "Bash(npm install),mcp__filesystem__*"
--disallowedToolsComma/space-separated list of denied toolsclaude --disallowedTools "Bash(git commit),mcp__github__*"
--mcp-configLoad MCP servers from a JSON fileclaude --mcp-config servers.json
--permission-prompt-toolMCP tool for handling permission prompts (only with --print)claude --permission-prompt-tool mcp__auth__prompt

For a complete list of CLI options and features, see the CLI usage documentation.

Output formats

The SDK supports multiple output formats:

Text output (default)

Returns just the response text:

JSON output

Returns structured data including metadata:

Response format:

Streaming JSON output

Streams each message as it is received:

Each conversation begins with an initial init system message, followed by a list of user and assistant messages, followed by a final result system message with stats. Each message is emitted as a separate JSON object.

Message schema

Messages returned from the JSON API are strictly typed according to the following schema:

We will soon publish these types in a JSONSchema-compatible format. We use semantic versioning for the main Claude Code package to communicate breaking changes to this format.

Examples

Simple script integration

Processing files with Claude

Session management

Best practices

  1. Use JSON output format for programmatic parsing of responses:

  2. Handle errors gracefully - check exit codes and stderr:

  3. Use session management for maintaining context in multi-turn conversations

  4. Consider timeouts for long-running operations:

  5. Respect rate limits when making multiple requests by adding delays between calls

Real-world applications

The Claude Code SDK enables powerful integrations with your development workflow. One notable example is the Claude Code GitHub Actions, which uses the SDK to provide automated code review, PR creation, and issue triage capabilities directly in your GitHub workflow.

联系我们 contact @ memedata.com