Skip to content

guanyang/open-agent-hub / skills/claude-api

claude-api

Unverified

Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER — read BEFORE opening the target file; don't skip because it "looks like a one-liner" — whenever: the prompt names Claude/Anthropic in any form (Claude, Anthropic, Fable, Opus, Sonnet, Haiku, `anthropic`, `@anthropic-ai`, `claude-*`, `us.anthropic.*`, `[1m]`); the user asks about an LLM (pricing/model choice/limits/caching) — never answer from memory; OR the task is LLM-shaped with provider unstated (agent/MCP/tool-definition/multi-agent/RAG/LLM-judge/computer-use; generate/summarize/extract/classify/rewrite/converse over NL; debugging refusals/cutoffs/streaming/tool-calls/tokens). SKIP only when another provider is being worked on (overrides all triggers): OpenAI/GPT/Gemini/Llama/Mistral/Cohere/Ollama named in the query; OR `grep -rE 'openai|langchain_openai|google.generativeai|genai|mistralai|cohere|ollama'` over the project hits (run this grep FIRST if no provider named — don't Read the file).

FileKindSize
LICENSE.txtmarkdown11.1 KB
SKILL.mdskill md102.7 KB
csharp/claude-api.mdmarkdown15.3 KB
csharp/claude-api/README.mdmarkdown18.5 KB
csharp/claude-api/batches.mdmarkdown413 B
csharp/claude-api/files-api.mdmarkdown900 B
csharp/claude-api/streaming.mdmarkdown787 B
csharp/claude-api/tool-use.mdmarkdown7.4 KB
curl/examples.mdmarkdown9.5 KB
curl/managed-agents.mdmarkdown10.5 KB
go/claude-api.mdmarkdown14.4 KB
go/claude-api/README.mdmarkdown8.3 KB
go/claude-api/files-api.mdmarkdown936 B
go/claude-api/streaming.mdmarkdown1.0 KB
go/claude-api/tool-use.mdmarkdown9.8 KB
go/managed-agents/README.mdmarkdown21.9 KB
java/claude-api.mdmarkdown15.5 KB
java/claude-api/README.mdmarkdown11.7 KB
java/claude-api/files-api.mdmarkdown1.2 KB
java/claude-api/streaming.mdmarkdown655 B
java/claude-api/tool-use.mdmarkdown10.9 KB
java/managed-agents/README.mdmarkdown20.0 KB
php/claude-api.mdmarkdown11.5 KB
php/claude-api/README.mdmarkdown6.4 KB
php/claude-api/batches.mdmarkdown447 B
php/claude-api/files-api.mdmarkdown476 B
php/claude-api/streaming.mdmarkdown682 B
php/claude-api/tool-use.mdmarkdown9.5 KB
php/managed-agents/README.mdmarkdown16.2 KB
python/agent-sdk/README.mdmarkdown12.4 KB
python/agent-sdk/patterns.mdmarkdown9.0 KB
python/claude-api/README.mdmarkdown20.1 KB
python/claude-api/batches.mdmarkdown5.6 KB
python/claude-api/files-api.mdmarkdown4.4 KB
python/claude-api/sdk-upgrade.mdmarkdown28.1 KB
python/claude-api/streaming.mdmarkdown11.7 KB
python/claude-api/tool-use.mdmarkdown20.9 KB
python/managed-agents/README.mdmarkdown14.5 KB
ruby/claude-api.mdmarkdown3.4 KB
ruby/claude-api/README.mdmarkdown4.7 KB
ruby/claude-api/streaming.mdmarkdown235 B
ruby/claude-api/tool-use.mdmarkdown2.6 KB
ruby/managed-agents/README.mdmarkdown11.9 KB
shared/admin-api.mdmarkdown11.3 KB
shared/agent-design.mdmarkdown8.5 KB
shared/anthropic-cli.mdmarkdown23.4 KB
shared/claude-platform-on-aws.mdmarkdown4.3 KB
shared/cost-optimization.mdmarkdown57.1 KB
shared/error-codes.mdmarkdown20.3 KB
shared/evals/build-eval.mdmarkdown53.5 KB
shared/evals/cost-hillclimb.mdmarkdown31.0 KB
shared/evals/eval-audit.mdmarkdown27.2 KB
shared/evals/eval-hillclimb.mdmarkdown67.5 KB
shared/evals/report/SCHEMA.mdmarkdown15.7 KB
shared/evals/report/build-report-lite.mjsscript26.7 KB
shared/evals/report/runner-scaffold.mjsscript32.4 KB
shared/live-sources.mdmarkdown17.3 KB
shared/managed-agents-api-reference.mdmarkdown34.5 KB
shared/managed-agents-client-patterns.mdmarkdown11.8 KB
shared/managed-agents-core.mdmarkdown32.7 KB
shared/managed-agents-environments.mdmarkdown13.9 KB
shared/managed-agents-events.mdmarkdown25.4 KB
shared/managed-agents-memory.mdmarkdown11.1 KB
shared/managed-agents-multiagent.mdmarkdown65.1 KB
shared/managed-agents-onboarding-from-quickstart.mdmarkdown19.3 KB
shared/managed-agents-onboarding-from-url.mdmarkdown31.9 KB
shared/managed-agents-onboarding.mdmarkdown16.4 KB
shared/managed-agents-outcomes.mdmarkdown8.8 KB
shared/managed-agents-overview.mdmarkdown14.2 KB
shared/managed-agents-quickstarts/bug-hunter.mdmarkdown7.9 KB
shared/managed-agents-quickstarts/contract-tracker.mdmarkdown1.8 KB
shared/managed-agents-quickstarts/data-analyst.mdmarkdown1.5 KB
shared/managed-agents-quickstarts/deep-researcher.mdmarkdown2.4 KB
shared/managed-agents-quickstarts/explainer-video-maker.mdmarkdown4.8 KB
shared/managed-agents-quickstarts/field-monitor.mdmarkdown2.1 KB
shared/managed-agents-quickstarts/incident-commander.mdmarkdown1.7 KB
shared/managed-agents-quickstarts/performance-tuner.mdmarkdown11.1 KB
shared/managed-agents-quickstarts/sprint-retro-facilitator.mdmarkdown2.0 KB
shared/managed-agents-quickstarts/structured-extractor.mdmarkdown1.5 KB
shared/managed-agents-quickstarts/support-agent.mdmarkdown1.4 KB
shared/managed-agents-quickstarts/support-to-eng-escalator.mdmarkdown1.8 KB
shared/managed-agents-quickstarts/watchlist-scanner.mdmarkdown5.5 KB
shared/managed-agents-scheduled-deployments.mdmarkdown9.3 KB
shared/managed-agents-self-hosted-sandboxes.mdmarkdown27.3 KB
shared/managed-agents-tools.mdmarkdown37.0 KB
shared/managed-agents-webhooks.mdmarkdown11.1 KB
shared/model-migration.mdmarkdown338.1 KB
shared/models.mdmarkdown17.1 KB
shared/platform-availability.mdmarkdown7.2 KB
shared/preserved-thinking-migration.mdmarkdown62.5 KB
shared/preserved-thinking-migration/causes.mdmarkdown38.8 KB
shared/preserved-thinking-migration/drop_block_probe.pyscript65.0 KB
shared/preserved-thinking-migration/prefix_diff.pyscript91.8 KB
shared/prompt-audit.mdmarkdown48.2 KB
shared/prompt-caching.mdmarkdown32.3 KB
shared/token-counting.mdmarkdown1.6 KB
shared/tool-use-concepts.mdmarkdown43.3 KB
typescript/agent-sdk/README.mdmarkdown10.6 KB
typescript/agent-sdk/patterns.mdmarkdown4.6 KB
typescript/claude-api/README.mdmarkdown15.5 KB
typescript/claude-api/batches.mdmarkdown2.5 KB
typescript/claude-api/files-api.mdmarkdown2.3 KB
typescript/claude-api/streaming.mdmarkdown9.3 KB
typescript/claude-api/tool-use.mdmarkdown23.7 KB
typescript/managed-agents/README.mdmarkdown13.7 KB

python/agent-sdk/README.md

View on GitHub
# Agent SDK — Python

The Claude Agent SDK provides a higher-level interface for building AI agents with built-in tools, safety features, and agentic capabilities.

## Installation

```bash
pip install claude-agent-sdk
```

---

## Quick Start

```python
import anyio
from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage

async def main():
    async for message in query(
        prompt="Explain this codebase",
        options=ClaudeAgentOptions(allowed_tools=["Read", "Glob", "Grep"])
    ):
        if isinstance(message, ResultMessage):
            print(message.result)

anyio.run(main)
```

---

## Built-in Tools

| Tool      | Description                          |
| --------- | ------------------------------------ |
| Read      | Read files in the workspace          |
| Write     | Create new files                     |
| Edit      | Make precise edits to existing files |
| Bash      | Execute shell commands               |
| Glob      | Find files by pattern                |
| Grep      | Search files by content              |
| WebSearch | Search the web for information       |
| WebFetch        | Fetch and analyze web pages          |
| AskUserQuestion | Ask user clarifying questions         |
| Agent           | Spawn subagents                      |

---

## Primary Interfaces

### `query()` — Simple One-Shot Usage

The `query()` function is the simplest way to run an agent. It returns an async iterator of messages.

```python
from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage

async for message in query(
    prompt="Explain this codebase",
    options=ClaudeAgentOptions(allowed_tools=["Read", "Glob", "Grep"])
):
    if isinstance(message, ResultMessage):
        print(message.result)
```

### `ClaudeSDKClient` — Full Control

`ClaudeSDKClient` provides full control over the agent lifecycle. Use it when you need custom tools, hooks, streaming, or the ability to interrupt execution.

```python
import anyio
from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions, AssistantMessage, TextBlock

async def main():
    options = ClaudeAgentOptions(allowed_tools=["Read", "Glob", "Grep"])
    async with ClaudeSDKClient(options=options) as client:
        await client.query("Explain this codebase")
        async for message in client.receive_response():
            if isinstance(message, AssistantMessage):
                for block in message.content:
                    if isinstance(block, TextBlock):
                        print(block.text)

anyio.run(main)
```

`ClaudeSDKClient` supports:

- **Context manager** (`async with`) for automatic resource cleanup
- **`client.query(prompt)`** to send a prompt to the agent
- **`receive_response()`** for streaming messages until completion
- **`interrupt()`** to stop agent execution mid-task
- **Required for custom tools** (via SDK MCP servers)

---

## Permission System

```python
from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage

async for message in query(
    prompt="Refactor the authentication module",
    options=ClaudeAgentOptions(
        allowed_tools=["Read", "Edit", "Write"],
        permission_mode="acceptEdits"  # Auto-accept file edits
    )
):
    if isinstance(message, ResultMessage):
        print(message.result)
```

Permission modes:

- `"default"`: Prompt for dangerous operations
- `"plan"`: Planning only, no execution
- `"acceptEdits"`: Auto-accept file edits
- `"bypassPermissions"`: Skip all prompts (use with caution)

---

## MCP (Model Context Protocol) Support

```python
from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage

async for message in query(
    prompt="Open example.com and describe what you see",
    options=ClaudeAgentOptions(
        mcp_servers={
            "playwright": {"command": "npx", "args": ["@playwright/mcp@latest"]}
        }
    )
):
    if isinstance(message, ResultMessage):
        print(message.result)
```

---

## Hooks

Customize agent behavior with hooks using callback functions:

```python
from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher, ResultMessage

async def log_file_change(input_data, tool_use_id, context):
    file_path = input_data.get('tool_input', {}).get('file_path', 'unknown')
    print(f"Modified: {file_path}")
    return {}

async for message in query(
    prompt="Refactor utils.py",
    options=ClaudeAgentOptions(
        permission_mode="acceptEdits",
        hooks={
            "PostToolUse": [HookMatcher(matcher="Edit|Write", hooks=[log_file_change])]
        }
    )
):
    if isinstance(message, ResultMessage):
        print(message.result)
```

Hook callback inputs for tool-lifecycle events (`PreToolUse`, `PostToolUse`, `PostToolUseFailure`) include `agent_id` and `agent_type` fields, allowing hooks to identify which agent (main or subagent) triggered the tool call.

Available hook events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `UserPromptSubmit`, `Stop`, `SubagentStop`, `PreCompact`, `Notification`, `SubagentStart`, `PermissionRequest`

---

## Common Options

`query()` takes a top-level `prompt` (string) and an `options` object (`ClaudeAgentOptions`):

```python
async for message in query(prompt="...", options=ClaudeAgentOptions(...)):
```

| Option                              | Type   | Description                                                                |
| ----------------------------------- | ------ | -------------------------------------------------------------------------- |
| `cwd`                               | string | Working directory for file operations                                      |
| `allowed_tools`                     | list   | Tools the agent can use (e.g., `["Read", "Edit", "Bash"]`)                |
| `tools`                             | list   | Built-in tools to make available (restricts the default set)               |
| `disallowed_tools`                  | list   | Tools to explicitly disallow                                               |
| `permission_mode`                   | string | How to handle permission prompts                                           |
| `mcp_servers`                       | dict   | MCP servers to connect to                                                  |
| `hooks`                             | dict   | Hooks for customizing behavior                                             |
| `system_prompt`                     | string | Custom system prompt                                                       |
| `max_turns`                         | int    | Maximum agent turns before stopping                                        |
| `max_budget_usd`                    | float  | Maximum budget in USD for the query                                        |
| `model`                             | string | Model ID (default: determined by CLI)                                      |
| `agents`                            | dict   | Subagent definitions (`dict[str, AgentDefinition]`)                        |
| `output_format`                     | dict   | Structured output schema                                                   |
| `thinking`                          | dict   | Thinking/reasoning control                                                 |
| `betas`                             | list   | Beta features to enable (e.g., `["context-1m-2025-08-07"]`)               |
| `setting_sources`                   | list   | Settings to load (e.g., `["project"]`). Default: none (no CLAUDE.md files) |
| `env`                               | dict   | Environment variables to set for the session                               |

---

## Message Types

```python
from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage, SystemMessage

async for message in query(
    prompt="Find TODO comments",
    options=ClaudeAgentOptions(allowed_tools=["Read", "Glob", "Grep"])
):
    if isinstance(message, ResultMessage):
        print(message.result)
        print(f"Stop reason: {message.stop_reason}")  # e.g., "end_turn", "max_turns"
    elif isinstance(message, SystemMessage) and message.subtype == "init":
        session_id = message.data.get("session_id")  # Capture for resuming later
```

`AssistantMessage` includes per-turn `usage` data (a dict matching the Anthropic API usage shape) for tracking costs:

```python
from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage

async for message in query(prompt="...", options=ClaudeAgentOptions()):
    if isinstance(message, AssistantMessage) and message.usage:
        print(f"Input: {message.usage['input_tokens']}, Output: {message.usage['output_tokens']}")
```

Typed task message subclasses are available for better type safety when handling subagent task events:
- `TaskStartedMessage` — emitted when a subagent task is registered
- `TaskProgressMessage` — real-time progress updates with cumulative usage metrics
- `TaskNotificationMessage` — task completion notifications

`RateLimitEvent` is emitted when the rate limit status transitions (e.g., from `allowed` to `allowed_warning` or `rejected`). Use it to warn users or back off gracefully:

```python
from claude_agent_sdk import query, ClaudeAgentOptions, RateLimitEvent

async for message in query(prompt="...", options=ClaudeAgentOptions()):
    if isinstance(message, RateLimitEvent):
        print(f"Rate limit status: {message.rate_limit_info.status}")
        if message.rate_limit_info.resets_at:
            print(f"Resets at: {message.rate_limit_info.resets_at}")
```

---

## Subagents

```python
from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition, ResultMessage

async for message in query(
    prompt="Use the code-reviewer agent to review this codebase",
    options=ClaudeAgentOptions(
        allowed_tools=["Read", "Glob", "Grep", "Agent"],
        agents={
            "code-reviewer": AgentDefinition(
                description="Expert code reviewer for quality and security reviews.",
                prompt="Analyze code quality and suggest improvements.",
                tools=["Read", "Glob", "Grep"]
            )
        }
    )
):
    if isinstance(message, ResultMessage):
        print(message.result)
```

---

## Error Handling

```python
from claude_agent_sdk import query, ClaudeAgentOptions, CLINotFoundError, CLIConnectionError, ResultMessage

try:
    async for message in query(
        prompt="...",
        options=ClaudeAgentOptions(allowed_tools=["Read"])
    ):
        if isinstance(message, ResultMessage):
            print(message.result)
except CLINotFoundError:
    print("Claude Code CLI not found. Install with: pip install claude-agent-sdk")
except CLIConnectionError as e:
    print(f"Connection error: {e}")
```

---

## Session History

Retrieve past session data with top-level functions:

```python
from claude_agent_sdk import list_sessions, get_session_messages

# List all past sessions (sync function — no await)
sessions = list_sessions()
for session in sessions:
    print(f"{session.session_id}: {session.cwd}")

# Get messages from a specific session (sync function — no await)
messages = get_session_messages(session_id="...")
for msg in messages:
    print(msg)
```

### Session Mutations

Rename or tag sessions (sync functions — no await):

```python
from claude_agent_sdk import rename_session, tag_session

# Rename a session
rename_session(session_id="...", title="My refactoring session")

# Tag a session (tags are Unicode-sanitized automatically)
tag_session(session_id="...", tag="experiment")

# Clear a tag
tag_session(session_id="...", tag=None)

# Optionally scope to a specific project directory
rename_session(session_id="...", title="New title", directory="/path/to/project")
```

---

## MCP Server Management

Manage MCP servers at runtime using `ClaudeSDKClient`:

```python
async with ClaudeSDKClient(options=options) as client:
    # Reconnect a disconnected MCP server
    await client.reconnect_mcp_server("my-server")

    # Toggle an MCP server on/off
    await client.toggle_mcp_server("my-server", enabled=False)

    # Get status of all MCP servers
    status = await client.get_mcp_status()  # returns McpStatusResponse
```

---

## Best Practices

1. **Always specify allowed_tools** — Explicitly list which tools the agent can use
2. **Set working directory** — Always specify `cwd` for file operations
3. **Use appropriate permission modes** — Start with `"default"` and only escalate when needed
4. **Handle all message types** — Check for `ResultMessage` to get agent output
5. **Limit max_turns** — Prevent runaway agents with reasonable limits
rea-changelog-updatemorluto/reaPrepare or rewrite REA release changelogs and GitHub release notes from pinned Git history, with verified contributor thanks and Release Please synchronization.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
academy-guideanthropics/skillsStop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials, and use cases from Claude Academy (academy.claude.com), Anthropic's learning hub. Trigger on: "how do I", "how can I", "getting started with", "what can Claude do", "teach me", "learn to use"; questions about artifacts, projects, skills, plugins, connectors, MCP; requests about rolling Claude out to a team, class, or organization; and any ask for training materials, onboarding content, or learning resources. Use it when the user is learning how to use a feature or product — not when they are mid-task and just want the task done. This skill composes with other skills: after consulting product documentation to answer how a Claude feature works, also check here for a matching course or tutorial — a docs-grounded answer and an Academy recommendation belong together. Only recommend on a strong match; never invent Academy content.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
claude-apianthropics/skillsReference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER — read BEFORE opening the target file; don't skip because it "looks like a one-liner" — whenever: the prompt names Claude/Anthropic in any form (Claude, Anthropic, Fable, Opus, Sonnet, Haiku, `anthropic`, `@anthropic-ai`, `claude-*`, `us.anthropic.*`, `[1m]`); the user asks about an LLM (pricing/model choice/limits/caching) — never answer from memory; OR the task is LLM-shaped with provider unstated (agent/MCP/tool-definition/multi-agent/RAG/LLM-judge/computer-use; generate/summarize/extract/classify/rewrite/converse over NL; debugging refusals/cutoffs/streaming/tool-calls/tokens). SKIP only when another provider is being worked on (overrides all triggers): OpenAI/GPT/Gemini/Llama/Mistral/Cohere/Ollama named in the query; OR `grep -rE 'openai|langchain_openai|google.generativeai|genai|mistralai|cohere|ollama'` over the project hits (run this grep FIRST if no provider named — don't Read the file).Stars: 198kUpdated Claude CodeCodexUnverifiedInstall
doc-coauthoringanthropics/skillsGuide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision docs, or similar structured content. This workflow helps users efficiently transfer context, refine content through iteration, and verify the doc works for readers. Trigger when user mentions writing docs, creating proposals, drafting specs, or similar documentation tasks.Stars: 198kUpdated Claude CodeCodexVerifiedInstall