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/patterns.md

View on GitHub
# Agent SDK Patterns — Python

## Basic Agent

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

async def main():
    async for message in query(
        prompt="Explain what this repository does",
        options=ClaudeAgentOptions(
            cwd="/path/to/project",
            allowed_tools=["Read", "Glob", "Grep"]
        )
    ):
        if isinstance(message, ResultMessage):
            print(message.result)

anyio.run(main)
```

---

## Custom Tools

Custom tools require an MCP server. Use `ClaudeSDKClient` for full control (custom SDK MCP tools require `ClaudeSDKClient` — `query()` only supports external stdio/http MCP servers).

```python
import anyio
from claude_agent_sdk import (
    tool,
    create_sdk_mcp_server,
    ClaudeSDKClient,
    ClaudeAgentOptions,
    AssistantMessage,
    TextBlock,
)

@tool("get_weather", "Get the current weather for a location", {"location": str})
async def get_weather(args):
    location = args["location"]
    return {"content": [{"type": "text", "text": f"The weather in {location} is sunny and 72°F."}]}

server = create_sdk_mcp_server("weather-tools", tools=[get_weather])

async def main():
    options = ClaudeAgentOptions(mcp_servers={"weather": server})
    async with ClaudeSDKClient(options=options) as client:
        await client.query("What's the weather in Paris?")
        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)
```

---

## Hooks

### After Tool Use Hook

Log file changes after any edit:

```python
import anyio
from datetime import datetime
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')
    with open('./audit.log', 'a') as f:
        f.write(f"{datetime.now()}: modified {file_path}\n")
    return {}

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

anyio.run(main)
```

---

## Subagents

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

async def main():
    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)

anyio.run(main)
```

---

## MCP Server Integration

### Browser Automation (Playwright)

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

async def main():
    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)

anyio.run(main)
```

### Database Access (PostgreSQL)

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

async def main():
    async for message in query(
        prompt="Show me the top 10 users by order count",
        options=ClaudeAgentOptions(
            mcp_servers={
                "postgres": {
                    "command": "npx",
                    "args": ["-y", "@modelcontextprotocol/server-postgres"],
                    "env": {"DATABASE_URL": os.environ["DATABASE_URL"]}
                }
            }
        )
    ):
        if isinstance(message, ResultMessage):
            print(message.result)

anyio.run(main)
```

---

## Permission Modes

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

async def main():
    # Default: prompt for dangerous operations
    async for message in query(
        prompt="Delete all test files",
        options=ClaudeAgentOptions(
            allowed_tools=["Bash"],
            permission_mode="default"  # Will prompt before deleting
        )
    ):
        pass

    # Plan: agent creates a plan before making changes
    async for message in query(
        prompt="Refactor the auth system",
        options=ClaudeAgentOptions(
            allowed_tools=["Read", "Edit"],
            permission_mode="plan"
        )
    ):
        pass

    # Accept edits: auto-accept file edits
    async for message in query(
        prompt="Refactor this module",
        options=ClaudeAgentOptions(
            allowed_tools=["Read", "Edit"],
            permission_mode="acceptEdits"
        )
    ):
        pass

    # Bypass: skip all prompts (use with caution)
    async for message in query(
        prompt="Set up the development environment",
        options=ClaudeAgentOptions(
            allowed_tools=["Bash", "Write"],
            permission_mode="bypassPermissions"
        )
    ):
        pass

anyio.run(main)
```

---

## Error Recovery

```python
import anyio
from claude_agent_sdk import (
    query,
    ClaudeAgentOptions,
    CLINotFoundError,
    CLIConnectionError,
    ProcessError,
    ResultMessage,
)

async def run_with_recovery():
    try:
        async for message in query(
            prompt="Fix the failing tests",
            options=ClaudeAgentOptions(
                allowed_tools=["Read", "Edit", "Bash"],
                max_turns=10
            )
        ):
            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}")
    except ProcessError as e:
        print(f"Process error: {e}")

anyio.run(run_with_recovery)
```

---

## Session Resumption

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

async def main():
    session_id = None

    # First query: capture the session ID
    async for message in query(
        prompt="Read the authentication module",
        options=ClaudeAgentOptions(allowed_tools=["Read", "Glob"])
    ):
        if isinstance(message, SystemMessage) and message.subtype == "init":
            session_id = message.data.get("session_id")

    # Resume with full context from the first query
    async for message in query(
        prompt="Now find all places that call it",  # "it" = auth module
        options=ClaudeAgentOptions(resume=session_id)
    ):
        if isinstance(message, ResultMessage):
            print(message.result)

anyio.run(main)
```

---

## Session History

```python
from claude_agent_sdk import list_sessions, get_session_messages

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

# Retrieve messages from the most recent session (sync function — no await)
if sessions:
    messages = get_session_messages(session_id=sessions[0].session_id)
    for msg in messages:
        print(msg)
```

---

## Session Mutations

```python
from claude_agent_sdk import rename_session, tag_session

session_id = "your-session-id"

# Rename a session
rename_session(session_id=session_id, title="Refactoring auth module")

# Tag a session for filtering
tag_session(session_id=session_id, tag="experiment-v2")

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

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

---

## Custom System Prompt

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

async def main():
    async for message in query(
        prompt="Review this code",
        options=ClaudeAgentOptions(
            allowed_tools=["Read", "Glob", "Grep"],
            system_prompt="""You are a senior code reviewer focused on:
1. Security vulnerabilities
2. Performance issues
3. Code maintainability

Always provide specific line numbers and suggestions for improvement."""
        )
    ):
        if isinstance(message, ResultMessage):
            print(message.result)

anyio.run(main)
```
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