The Claude Agent SDK: A Beginner Guide for Developers

The Claude Agent SDK: A Beginner Guide for Developers

The Claude Agent SDK lets you put the same agent that powers Claude Code inside your own Python or TypeScript program. Instead of typing prompts into a terminal, your code sends a task, Claude reads files, edits code and runs commands, and your program reads the results. This guide walks through what the SDK is, how to build your first agent and how to keep it under control.

You do not need to be an AI expert. If you can run a script and set an environment variable, you can follow along.

This is Part 53 of 53 in our Claude Code tutorials series. In the previous part we sent Claude Code tasks from Slack, the web and your phone with cloud sessions.

Tested with Claude Code v2.1.310 on October 26, 2026, on macOS.

This is a docs-based tutorial. Every screenshot is a highlighted capture of Anthropic’s official Agent SDK pages, taken that day. We did not run the SDK for this article, because it needs an API key that bills per use, so the steps and code come from the official documentation.

We tested on macOS; the Windows and Linux steps follow Anthropic’s official instructions.

The Claude Agent SDK at a Glance

The Agent SDK is Claude Code as a library: the same tools, agent loop and context management, programmable from your own code.

QuestionAnswer
What is it?A library that runs the Claude Code binary and exposes it to your code
LanguagesPython and TypeScript
RequirementsNode.js 18+ or Python 3.10+, plus an API key from the Claude Console
Main functionquery, which streams messages as Claude works
Built-in toolsRead, Write, Edit, Glob, Grep, Bash, WebSearch, WebFetch and more
ControlsAllowed tools, permission mode, max turns, max budget

What Is the Claude Agent SDK?

An agent is an application that completes a task by planning its own steps and calling tools that read files, run commands or edit code. The official overview says the Agent SDK gives you the same tools, agent loop and context management that power Claude Code. You get them in Python and TypeScript.

Official Agent SDK overview page with the first paragraph highlighted
The overview page describes the SDK as Claude Code’s agent as a library

Think of it this way. In the terminal you are the one typing. With the SDK, your program types for you.

That makes it a good fit for background jobs, internal tools and automation. If you only want to chat and code by hand, the normal Claude Code app from our Claude Code introduction is simpler.

Which Claude tool should you use?

Anthropic offers four ways to build with Claude, and they differ in who runs the agent. The official overview lays them out in one table.

Official comparison table with the Agent SDK row highlighted
The first row is the Agent SDK: Claude Code’s agent inside your own application
  • Agent SDK: embed Claude Code’s agent in your own Python or TypeScript application, in a process you operate.
  • Claude Code CLI: interactive development and one-off tasks from a terminal.
  • Client SDK: call the Claude API directly. You write the tool loop yourself, or let the beta tool runner drive it.
  • Managed Agents: Anthropic hosts the agent harness, with sessions in a managed cloud sandbox or a self-hosted one.
Decision ladder: terminal use means Claude Code CLI, hosted means Managed Agents, writing the loop yourself means Client SDK, otherwise Agent SDK
Follow the questions to find the right tool

If you want the same agent loop from another language, the docs suggest running the CLI as a subprocess with the -p flag and –output-format json.

What You Get Out of the Box

The SDK is not a bare model call. It brings along many Claude Code features, so you do not have to rebuild them.

Official capabilities table listing built-in tools, hooks, subagents, MCP, permissions and sessions
The capabilities table: tools, hooks, subagents, MCP, permissions, sessions and more
CapabilityWhat it does
Built-in toolsRead, write and edit files, run commands, search the web
HooksRun custom code at key points in the agent lifecycle
SubagentsSpawn specialized agents for focused subtasks
MCPConnect external tools and data sources
PermissionsControl which tools run automatically and which need approval
SessionsKeep context across exchanges, then resume or fork later
Skills, commands and memoryLoad from your project’s .claude folder, like Claude Code
PluginsPackage skills, agents, hooks and MCP servers

Many of these will sound familiar from earlier parts, such as skills and plugins. The SDK uses the same ideas, only driven from code.

Set Up Your First Agent

The official quickstart builds an agent that finds and fixes bugs in a small file. We will follow it in the TypeScript flavor first, then show the Python code.

Step 1: Create a project folder

Make a new folder for the quickstart. For your own projects, the SDK can run from any folder, and it has access to files in that folder and its subfolders by default.

mkdir my-agent
cd my-agent

Step 2: Install the SDK

For a new TypeScript project, the docs use these commands. Setting the module type lets your script use top-level await, and tsx runs TypeScript files directly.

npm init -y
npm pkg set type=module
npm install @anthropic-ai/claude-agent-sdk
npm install --save-dev tsx
Official quickstart install commands with the npm install line for the Agent SDK highlighted
The package name is @anthropic-ai/claude-agent-sdk

For Python, the docs show uv add claude-agent-sdk, or pip install claude-agent-sdk inside a virtual environment. Both SDKs bundle a native Claude Code binary, so most installs need no separate Claude Code install.

Two exceptions are worth knowing. If pip installs the source distribution instead of a platform wheel, for example on ARM64 Windows, install Claude Code natively. If you skip optional dependencies with npm ci –omit=optional, the TypeScript SDK gets no binary.

Step 3: Set your API key

Get a key from the Claude Console and set it in the shell where you will run your agent.

export ANTHROPIC_API_KEY=your-api-key
Official quickstart showing the export ANTHROPIC_API_KEY command highlighted
The SDK reads the key from the environment of the process that runs your agent

The SDK does not load .env files on its own. If you keep the key in one, load it yourself, for example with the dotenv package.

The docs also describe setting variables for Amazon Bedrock, Google Cloud’s Agent Platform and Microsoft Foundry if you use those providers. Keep your key out of your code and out of Git; our security guide covers safe habits.

One rule from the docs matters if you build products: unless previously approved, Anthropic does not allow third-party developers to offer claude.ai login or rate limits for their products. Use API key authentication instead.

Step 4: Create a file with bugs

The agent needs something to fix. Create utils.py with two planted bugs.

def calculate_average(numbers):
    total = 0
    for num in numbers:
        total += num
    return total / len(numbers)


def get_user_name(user):
    return user["name"].upper()

The first function crashes with a division by zero on an empty list. The second crashes with a TypeError if you pass None.

Write the Agent

Create agent.py for Python, or agent.ts for TypeScript. Here is the Python version from the official quickstart.

import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ResultMessage


async def main():
    # Agentic loop: streams messages as Claude works
    async for message in query(
        prompt="Review utils.py for bugs that would cause crashes. Fix any issues you find.",
        options=ClaudeAgentOptions(
            allowed_tools=["Read", "Edit", "Glob"],  # Auto-approve these tools
            permission_mode="acceptEdits",  # Auto-approve file edits
        ),
    ):
        # Print human-readable output
        if isinstance(message, AssistantMessage):
            for block in message.content:
                if hasattr(block, "text"):
                    print(block.text)  # Claude's reasoning
                elif hasattr(block, "name"):
                    print(f"Tool: {block.name}")  # Tool being called
        elif isinstance(message, ResultMessage):
            print(f"Done: {message.subtype}")  # Final result


asyncio.run(main())
Official quickstart Python code block highlighted
The whole agent fits in about twenty lines

The three parts of the code

Official quickstart list explaining query, prompt and options, with the query item highlighted
The docs explain the three main parts: query, prompt and options
  • query is the main entry point. It creates the agentic loop and returns an async iterator, so you use async for to stream messages as Claude works.
  • prompt is what you want Claude to do. Claude decides which tools to use.
  • options configures the agent. This example pre-approves Read, Edit and Glob, and sets the permission mode to acceptEdits so file changes go through without asking. Other options include a system prompt and MCP servers.

The message handling inside the loop only filters for readable output. Without it you would see raw message objects, including system initialization and internal state, which helps for debugging but is noisy.

Run the Agent and Read the Result

Run it with npx tsx agent.ts for TypeScript, uv run agent.py with uv, or python agent.py with pip. As it works, the agent prints its reasoning and each tool it calls, and ends with Done: success.

Afterward, open utils.py. Per the docs, you will see defensive code that handles empty lists and null users.

The agent read the file, worked out which inputs would crash, and edited the file to add error handling. That is the key difference from a normal API call: Claude executes the tools directly instead of asking you to do it.

If you see an authentication error such as Not logged in or Invalid API key, check that ANTHROPIC_API_KEY is set in the same shell where you ran the agent.

How the Agent Loop Works

Behind query sits the agent loop. The official loop page describes a simple cycle.

Official agent loop page with the numbered steps and a small loop diagram
Receive prompt, evaluate, run tools, repeat, return the result
  1. Receive prompt: Claude gets your prompt, the system prompt, tool definitions and history. The SDK yields a SystemMessage with the subtype init.
  2. Evaluate and respond: Claude replies with text, tool calls or both.
  3. Execute tools: the SDK runs each requested tool and feeds the results back.
  4. Repeat: each full cycle is one turn, and it continues until Claude replies with no tool calls.
  5. Return result: the SDK yields a final AssistantMessage, then a ResultMessage with the final text, token usage, cost and session ID.
Diagram of an Agent SDK run: your code calls query, the loop of Claude deciding and the SDK running tools repeats, then a ResultMessage returns
Your code sends one prompt and reads the stream until the ResultMessage

A quick question might take one or two turns. A bigger job, such as fixing failing tests, can chain many tool calls: run the tests, read the files, edit the code and run the tests again. The docs call each of these a turn and count only the tool-use turns against any limit you set.

Choose the Tools and Permissions

Tools decide what your agent can do. The quickstart gives three handy sets.

Official quickstart table of tool sets with the full automation row highlighted
More tools means more power, so start small
ToolsWhat the agent can do
Read, Glob, GrepRead-only analysis
Read, Edit, GlobAnalyze and modify code
Read, Edit, Bash, Glob, GrepFull automation

Three options work together to decide what actually runs.

allowed_tools auto-approves the tools you list. disallowed_tools blocks tools no matter what else is set. permission_mode controls how much human oversight you want.

When a tool call is denied, Claude gets a rejection message and usually tries another approach or tells you it could not continue.

You can also scope a tool with a rule such as Bash(npm *) to allow only certain commands. This mirrors the permission ideas in Claude Code automation, where there is also no person to click Approve.

Keep Cost and Runtime Under Control

An agent with no limits can run long on open-ended prompts. The loop page recommends setting a budget as a good default for production agents.

Official turns and budget table with the max budget row highlighted
Max turns and max budget both default to no limit
OptionWhat it controlsDefault
max_turns (maxTurns in TypeScript)Maximum tool-use round tripsNo limit
max_budget_usd (maxBudgetUsd)Estimated spend at which the loop stopsNo limit

When a limit is hit, the SDK returns a ResultMessage with an error subtype, either error_max_turns or error_max_budget_usd.

One detail to remember: the response that reaches the cap still completes, so spend can pass the cap by about the cost of that one response. Leave some headroom.

There is also an effort option, from low to max, that trades reasoning depth for lower cost and faster replies. For more on spending, see our guide to managing costs.

Customize Your Agent

All of these tweaks change fields on the same options object. The quickstart shows three.

Add web search

options = ClaudeAgentOptions(
    allowed_tools=["Read", "Edit", "Glob", "WebSearch"], permission_mode="acceptEdits"
)

Give Claude a system prompt

options = ClaudeAgentOptions(
    allowed_tools=["Read", "Edit", "Glob"],
    permission_mode="acceptEdits",
    system_prompt="You are a senior Python developer. Always follow PEP 8 style guidelines.",
)

Let it run commands

options = ClaudeAgentOptions(
    allowed_tools=["Read", "Edit", "Glob", "Bash"], permission_mode="acceptEdits"
)

With Bash enabled, the docs suggest the prompt: Write unit tests for utils.py, run them, and fix any failures.

Try It Yourself

Practice with the same project, using the safest setup first. Keep Bash off until you are comfortable.

  1. Build the my-agent folder and utils.py from this guide.
  2. Run the agent once and compare utils.py before and after.
  3. Change only the prompt to one of the docs’ ideas and run it again.
  4. Add max_turns to your options and watch what happens with a small number.

Copy-paste prompts from the quickstart to try:

Add docstrings to all functions in utils.py
Add type hints to all functions in utils.py
Create a README.md documenting the functions in utils.py

Common Mistakes

  • Forgetting the API key. The SDK reads ANTHROPIC_API_KEY from the shell that runs your agent, and it does not read .env files by itself.
  • Giving too many tools too early. Start read-only, then add Edit, and add Bash last.
  • Running with no limits. Without max_turns or a budget, open-ended prompts can run long.
  • Breaking out of the stream early. A few trailing system events can arrive after the ResultMessage, so read the stream to the end.
  • Using Claude Code branding in your product. The overview says partners may not call their agent Claude Code or imitate its look.

Pro Tips

  • Print only the message types you care about, then log everything when you need to debug.
  • Use the same project setup you rely on in the terminal. The SDK loads skills, commands and memory from your .claude folders, so a good CLAUDE.md file still helps.
  • Use lower effort for simple, well-scoped tasks such as listing files.
  • Read the Agent SDK overview, the quickstart and the agent loop page next, then explore hooks, sessions and MCP servers.

Cheat Sheet

Cheat sheet card with Agent SDK setup commands and key options
Setup commands and options worth saving

Frequently Asked Questions

What is the difference between the Agent SDK and Claude Code?

Claude Code is the terminal app you use by hand. The Agent SDK is a library that runs the same agent from your Python or TypeScript code.

Do I need Claude Code installed to use the SDK?

Usually not. Both SDKs bundle a native Claude Code binary, so most installs need nothing extra. A few installs, such as pip on ARM64 Windows, have no bundled binary and need a native Claude Code install.

Which languages does it support?

Python and TypeScript. For other languages, the docs suggest running the CLI as a subprocess with the -p flag and –output-format json.

How do I log in?

Set an ANTHROPIC_API_KEY from the Claude Console. The docs also cover Amazon Bedrock, Google Cloud and Microsoft Foundry. Offering claude.ai login in your own product is not allowed unless Anthropic has approved it.

How do I stop an agent from running too long?

Set max_turns to cap tool-use round trips and max_budget_usd to cap estimated spend. When a limit is reached, the final result carries an error subtype you can check.

Conclusion

The Claude Agent SDK turns Claude Code into a building block. With one query call, a short prompt and a few options, you can have an agent read, edit and test code for you, while allowed tools, permission modes, turn limits and budgets keep it in bounds. Start with the bug-fixing quickstart, keep your tools minimal, and grow from there. That also completes our 53-part tour, so head back to the tutorials hub and try the Claude AI tools on your own projects.

Previous in the series: Part 52: Claude Code in Slack, on the Web and on Mobile

Newsletter

New AI tools in your inbox

The best new tools and the AI news that matters, in one short email. Unsubscribe any time.

Free · No spam · Unsubscribe any time

✓ Looks like you’re subscribed

Loading Google’s sign-up form…

Looks like you’re already subscribed

Thanks for reading! New AI tools and the AI news that matters will land in your inbox.

Not subscribed yet? Refresh the page to load the sign-up form.

The sign-up form couldn’t load. If you use an ad or content blocker, allow news.google.com and reload the page.

Free instant check before you pay. Takes a few seconds.

Scroll to Top