All skills
Skillintermediate

Agent SDK overview

> ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further.

Claude Code Knowledge Pack7/10/2026

Overview

Documentation Index

Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt Use this file to discover all available pages before exploring further.

Agent SDK overview

Build production AI agents with Claude Code as a library

The Claude Code SDK has been renamed to the Claude Agent SDK. If you're migrating from the old SDK, see the Migration Guide.

Build AI agents that autonomously read files, run commands, search the web, edit code, and more. The Agent SDK gives you the same tools, agent loop, and context management that power Claude Code, programmable in Python and TypeScript.

Opus 4.7 (claude-opus-4-7) requires Agent SDK v0.2.111 or later. If you see a thinking.type.enabled API error, see Troubleshooting.


from claude_agent_sdk import query, ClaudeAgentOptions

async def main():
    async for message in query(
        prompt="Find and fix the bug in auth.py",
        options=ClaudeAgentOptions(allowed_tools=["Read", "Edit", "Bash"]),
    ):
        print(message)  # Claude reads the file, finds the bug, edits it

asyncio.run(main())

for await (const message of query({
  prompt: "Find and fix the bug in auth.ts",
  options: { allowedTools: ["Read", "Edit", "Bash"] }
})) {
  console.log(message); // Claude reads the file, finds the bug, edits it
}

The Agent SDK includes built-in tools for reading files, running commands, and editing code, so your agent can start working immediately without you implementing tool execution. Dive into the quickstart or explore real agents built with the SDK:

Build a bug-fixing agent in minutes



Email assistant, research agent, and more

Get started

    ```bash theme={null}
    npm install @anthropic-ai/claude-agent-sdk
    ```
  

  
    ```bash theme={null}
    pip install claude-agent-sdk
    ```
  



  The TypeScript SDK bundles a native Claude Code binary for your platform as an optional dependency, so you don't need to install Claude Code separately.




Get an API key from the [Console](https://platform.claude.com/), then set it as an environment variable:

```bash theme={null}

```

The SDK also supports authentication via third-party API providers:

* **Amazon Bedrock**: set `CLAUDE_CODE_USE_BEDROCK=1` environment variable and configure AWS credentials
* **Google Vertex AI**: set `CLAUDE_CODE_USE_VERTEX=1` environment variable and configure Google Cloud credentials
* **Microsoft Azure**: set `CLAUDE_CODE_USE_FOUNDRY=1` environment variable and configure Azure credentials

See the setup guides for [Bedrock](/en/amazon-bedrock), [Vertex AI](/en/google-vertex-ai), or [Azure AI Foundry](/en/microsoft-foundry) for details.


  Unless previously approved, Anthropic does not allow third party developers to offer claude.ai login or rate limits for their products, including agents built on the Claude Agent SDK. Please use the API key authentication methods described in this document instead.




This example creates an agent that lists files in your current directory using built-in tools.


  ```python Python theme={null}

  from claude_agent_sdk import query, ClaudeAgentOptions

  async def main():
      async for message in query(
          prompt="What files are in this directory?",
          options=ClaudeAgentOptions(allowed_tools=["Bash", "Glob"]),
      ):
          if hasattr(message, "result"):
              print(message.result)

  asyncio.run(main())
  ```

  ```typescript TypeScript theme={null}

  for await (const message of query({
    prompt: "What files are in this directory?",
    options: { allowedTools: ["Bash", "Glob"] }
  })) {
    if ("result" in message) console.log(message.result);
  }
  ```

Ready to build? Follow the Quickstart to create an agent that finds and fixes bugs in minutes.

Capabilities

Everything that makes Claude Code powerful is available in the SDK:

Your agent can read files, run commands, and search codebases out of the box. Key tools include:

| Tool                                                                        | What it does                                                        |
| --------------------------------------------------------------------------- | ------------------------------------------------------------------- |
| **Read**                                                                    | Read any file in the working directory                              |
| **Write**                                                                   | Create new files                                                    |
| **Edit**                                                                    | Make precise edits to existing files                                |
| **Bash**                                                                    | Run terminal commands, scripts, git operations                      |
| **Monitor**                                                                 | Watch a background script and react to each output line as an event |
| **Glob**                                                                    | Find files by pattern (`**/*.ts`, `src/**/*.py`)                    |
| **Grep**                                                                    | Search file contents with regex                                     |
| **WebSearch**                                                               | Search the web for current information                              |
| **WebFetch**                                                                | Fetch and parse web page content                                    |
| **[AskUserQuestion](/en/agent-sdk/user-input#handle-clarifying-questions)** | Ask the user clarifying questions with multiple choice options      |

This example creates an agent that searches your codebase for TODO comments:


  ```python Python theme={null}

  from claude_agent_sdk import query, ClaudeAgentOptions

  async def main():
      async for message in query(
          prompt="Find all TODO comments and create a summary",
          options=ClaudeAgentOptions(allowed_tools=["Read", "Glob", "Grep"]),
      ):
          if hasattr(message, "result"):
              print(message.result)

  asyncio.run(main())
  ```

  ```typescript TypeScript theme={null}

  for await (const message of query({
    prompt: "Find all TODO comments and create a summary",
    options: { allowedTools: ["Read", "Glob", "Grep"] }
  })) {
    if ("result" in message) console.log(message.result);
  }
  ```




Run custom code at key points in the agent lifecycle. SDK hooks use callback functions to validate, log, block, or transform agent behavior.

**Available hooks:** `PreToolUse`, `PostToolUse`, `Stop`, `SessionStart`, `SessionEnd`, `UserPromptSubmit`, and more.

This example logs all file changes to an audit file:


  ```python Python theme={null}

  from datetime import datetime
  from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher

  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}\

") return {}

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

  asyncio.run(main())
  ```

  ```typescript TypeScript theme={null}

  const logFileChange: HookCallback = async (input) => {
    const filePath = (input as any).tool_input?.file_path ?? "unknown";
    await appendFile("./audit.log", `${new Date().toISOString()}: modified ${filePath}\

`); return {}; };

  for await (const message of query({
    prompt: "Refactor utils.py to improve readability",
    options: {
      permissionMode: "acceptEdits",
      hooks: {
        PostToolUse: [{ matcher: "Edit|Write", hooks: [logFileChange] }]
      }
    }
  })) {
    if ("result" in message) console.log(message.result);
  }
  ```


[Learn more about hooks →](/en/agent-sdk/hooks)



Spawn specialized agents to handle focused subtasks. Your main agent delegates work, and subagents report back with results.

Define custom agents with specialized instructions. Include `Agent` in `allowedTools` since subagents are invoked via the Agent tool:


  ```python Python theme={null}

  from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition

  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 hasattr(message, "result"):
              print(message.result)

  asyncio.run(main())
  ```

  ```typescript TypeScript theme={null}

  for await (const message of query({
    prompt: "Use the code-reviewer agent to review this codebase",
    options: {
      allowedTools: ["Read", "Glob", "Grep", "Agent"],
      agents: {
        "code-reviewer": {
          description: "Expert code reviewer for quality and security reviews.",
          prompt: "Analyze code quality and suggest improvements.",
          tools: ["Read", "Glob", "Grep"]
        }
      }
    }
  })) {
    if ("result" in message) console.log(message.result);
  }
  ```


Messages from within a subagent's context include a `parent_tool_use_id` field, letting you track which messages belong to which subagent execution.

[Learn more about subagents →](/en/agent-sdk/subagents)



Connect to external systems via the Model Context Protocol: databases, browsers, APIs, and [hundreds more](https://github.com/modelcontextprotocol/servers).

This example connects the [Playwright MCP server](https://github.com/microsoft/playwright-mcp) to give your agent browser automation capabilities:


  ```python Python theme={null}

  from claude_agent_sdk import query, ClaudeAgentOptions

  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 hasattr(message, "result"):
              print(message.result)

  asyncio.run(main())
  ```

  ```typescript TypeScript theme={null}

  for await (const message of query({
    prompt: "Open example.com and describe what you see",
    options: {
      mcpServers: {
        playwright: { command: "npx", args: ["@playwright/mcp@latest"] }
      }
    }
  })) {
    if ("result" in message) console.log(message.result);
  }
  ```


[Learn more about MCP →](/en/agent-sdk/mcp)



Control exactly which tools your agent can use. Allow safe operations, block dangerous ones, or require approval for sensitive actions.


  For interactive approval prompts and the `AskUserQuestion` tool, see [Handle approvals and user input](/en/agent-sdk/user-input).


This example creates a read-only agent that can analyze but not modify code. `allowed_tools` pre-approves `Read`, `Glob`, and `Grep`.


  ```python Python theme={null}

  from claude_agent_sdk import query, ClaudeAgentOptions

  async def main():
      async for message in query(
          prompt="Review this code for best practices",
          options=ClaudeAgentOptions(
              allowed_tools=["Read", "Glob", "Grep"],
          ),
      ):
          if hasattr(message, "result"):
              print(message.result)

  asyncio.run(main())
  ```

  ```typescript TypeScript theme={null}

  for await (const message of query({
    prompt: "Review this