# How to build an agent with Claude: Agent SDK and tool use

> Two routes from Anthropic's docs: the Agent SDK for a ready-made loop and built-in tools, or the Messages API when you want to write the loop yourself.

URL: https://claudegpt.si/news/claude-how-to-build-an-agent  
Published: 2026-11-02T06:55:23.874Z  
Author: ClaudeGPT Si Newsroom  
Section: Guides  
Topics: Claude, Anthropic, AI agents, Agent SDK, How to  
Publisher: ClaudeGPT Si

## Key takeaways

- Anthropic's Agent SDK packages Claude Code's agent loop and built-in tools as a Python and TypeScript library.
- The quickstart needs Node.js 18.14+ or Python 3.10+, an API key in ANTHROPIC_API_KEY, and about 25 lines of code.
- To write your own loop on the Messages API, keep calling Claude while stop_reason is tool_use and return each result in a tool_result block.

To build an agent with Claude, pick one of two routes. The [Agent SDK](https://code.claude.com/docs/en/agent-sdk/overview) gives you Claude Code's agent loop and built-in tools as a Python or TypeScript library. The [Messages API with tool use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview) gives you the raw parts, and you write the loop yourself. This guide covers both, as described in Anthropic's docs on November 2, 2026.

An agent, in Anthropic's definition, is an application that completes a task by planning its own steps and calling tools that read files, run commands, or edit code. The two routes differ in how much of that work you take on.

## Which route to use

The Agent SDK overview compares the options in a table. The short version:

| You want to | Use |
| --- | --- |
| Embed Claude Code's agent in your own Python or TypeScript app, in a process you run | Agent SDK |
| Call the Claude API directly and control every step | Client SDK, with your own tool loop or the beta tool runner |
| Have Anthropic host the agent loop | Managed Agents |

If you want file editing, shell access and permissions without writing them, start with the Agent SDK. If you want a small agent with your own tools and nothing else, use tool use on the Messages API.

## Build an agent with the Agent SDK

This route follows the official quickstart, which builds an agent that finds and fixes bugs in a file. We did not run these commands for this guide. They are copied from the docs, so check them against the current quickstart if a version changes.

### What you need first

- Node.js 18.14 or newer, or Python 3.10 or newer.
- An Anthropic account and an API key from the Claude Console.

### Step 1: Create a project and install the SDK

```bash
mkdir my-agent
cd my-agent
```

For Python with pip, create a virtual environment and install the package:

```bash
python3 -m venv .venv
source .venv/bin/activate
pip install claude-agent-sdk
```

For a new TypeScript project:

```bash
npm init -y
npm pkg set type=module
npm install @anthropic-ai/claude-agent-sdk
npm install --save-dev tsx
```

Both SDKs bundle a native Claude Code binary, so most installs need no separate Claude Code install. The docs note a few exceptions, such as an install that skips npm optional dependencies.

### Step 2: Set your API key

```bash
export ANTHROPIC_API_KEY=your-api-key
```

The SDK reads the key from the environment of the process that runs your agent. It does not load `.env` files, so load one yourself if you use it. The docs also list Amazon Bedrock, Google Cloud's Agent Platform and Microsoft Foundry as supported providers, each switched on with an environment variable.

Anthropic says that unless previously approved, third-party developers may not offer claude.ai login or its rate limits in products built on the SDK. Use API key authentication.

### Step 3: Write the agent

Create `agent.py`. The quickstart points it at a file called `utils.py` with two bugs, a division by zero in `calculate_average` and a crash in `get_user_name` when passed `None`.

```python
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())
```

Three parts do the work. `query` starts the agent loop and returns an async iterator, so you stream messages as Claude reads, thinks and calls tools. `prompt` says what you want done, and Claude picks the tools. `options` configures the agent: here, `allowed_tools` pre-approves three tools and `permission_mode="acceptEdits"` approves file edits automatically.

### Step 4: Run it

```bash
python agent.py
```

With uv, use `uv run agent.py`. For TypeScript, use `npx tsx agent.ts`. The agent prints its reasoning and each tool it calls, and ends with `Done: success`. Open `utils.py` afterward and you should see code that handles empty lists and a missing user.

### Step 5: Change what the agent can do

The tools you allow set the agent's reach. The quickstart gives three examples:

| Tools | What the agent can do |
| --- | --- |
| `Read`, `Glob`, `Grep` | Read-only analysis |
| `Read`, `Edit`, `Glob` | Analyze and modify code |
| `Read`, `Edit`, `Bash`, `Glob`, `Grep` | Full automation |

Add `WebSearch` to let it search the web, `Bash` to let it run commands, or a `system_prompt` string to give it a role. Beyond that, the SDK supports hooks (custom code at points in the agent's lifecycle), subagents for focused subtasks, MCP servers for external tools, permissions, and sessions that keep context across exchanges.

## Build an agent with tool use on the Messages API

This route is for when you want your own tools and your own loop. The idea is simple. You describe tools to Claude. Claude decides when to call one and returns a structured request. Your code runs it and sends the result back. Anthropic's docs split tools by where the code runs: client tools run in your application, and server tools such as web search run on Anthropic's infrastructure.

### Define a tool

A tool has a name, a description and an `input_schema` in JSON Schema form. This example is from the tool use overview:

```python
tools = [
    {
        "name": "get_weather",
        "description": "Get the current weather for a given location.",
        "input_schema": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "City and state, e.g. San Francisco, CA",
                }
            },
            "required": ["location"],
        },
    }
]
```

### Run the loop

When Claude wants a tool, the response has `stop_reason: "tool_use"` and a `tool_use` block. You run the operation and reply with a `tool_result` block whose `tool_use_id` matches the call. The docs' agent tutorial turns this into a loop that runs while `response.stop_reason == "tool_use"` and ends when Claude stops asking for tools:

```python
while response.stop_reason == "tool_use":
    tool_use = next(block for block in response.content if block.type == "tool_use")
    result = run_tool(tool_use.name, tool_use.input)

    messages.append({"role": "assistant", "content": response.content})
    messages.append(
        {
            "role": "user",
            "content": [
                {
                    "type": "tool_result",
                    "tool_use_id": tool_use.id,
                    "content": json.dumps(result),
                }
            ],
        }
    )

    response = client.messages.create(
        model="claude-opus-5-5",
        max_tokens=1024,
        tools=tools,
        tool_choice={"type": "auto", "disable_parallel_tool_use": True},
        messages=messages,
    )
```

Here `run_tool` is your own function. The tutorial's version handles one tool call per turn, because it sets `disable_parallel_tool_use` to true. If you allow parallel calls, the tutorial says the loop must handle every `tool_use` block in a response, not just the first. The tutorial's visible code also has no cap on iterations, so add your own limit in production.

### Report failures to Claude

If a tool fails, do not crash. Send the error back with `is_error` set to true so Claude can retry with corrected input, ask the user, or explain the limit:

```python
except Exception as exc:
    tool_results.append(
        {
            "type": "tool_result",
            "tool_use_id": block.id,
            "content": str(exc),
            "is_error": True,
        }
    )
```

### Let the SDK drive the loop

Writing the loop is optional. The docs describe a beta tool runner in the client SDKs that runs your tools and sends the results back automatically. For schemas that must always match, add `strict: true` to your tool definitions.

## Common problems

- **Authentication errors such as "Not logged in" or "Invalid API key."** Set `ANTHROPIC_API_KEY` in the shell where you run the agent. The SDK does not read `.env` files by itself.
- **Claude does not call your tool.** The tool use docs say a light line in the system prompt, such as "Use the tools to investigate before responding," makes tool calls more likely. You can also force a call with `tool_choice`.
- **Claude guesses a missing argument.** The docs say Claude Sonnet in particular may infer a value instead of asking. Make required fields explicit in the schema description.
- **Costs run higher than expected.** Tool names, descriptions and schemas count as input tokens, and the API adds a tool use system prompt. The docs list 286 tokens for Claude Sonnet 5.5 and Claude Opus 5.5 with `auto` tool choice. Server tools such as web search can add usage charges. Prices change, so check the current pricing page.

## Where to go next

Read the [agent loop](https://code.claude.com/docs/en/agent-sdk/agent-loop.md) page to see how Claude plans and decides a task is done, then the permissions page before you give an agent `Bash`. Anthropic also publishes [example agents](https://github.com/anthropics/claude-agent-sdk-demos), including an email assistant and a research agent. For hosting, the Agent SDK docs cover Docker, cloud and CI/CD deployment.

For how Anthropic's SDK compares with a rival, see our comparison of the [Cursor SDK and the Claude Agent SDK](https://claudegpt.si/news/cursor-sdk-vs-claude-agent-sdk).

## Frequently asked questions

### Can you build an agent in Claude?

Yes. Anthropic offers the Agent SDK for Python and TypeScript, the Messages API with tool use for a loop you write yourself, and Managed Agents, where Anthropic hosts the loop.

### How do I build an AI agent with Claude for free?

The pages we read describe no free tier for the SDK. The quickstart requires an Anthropic account and an API key, and API use is billed by tokens. Check the current pricing page before you build.

### What is the difference between the Agent SDK and tool use?

The Agent SDK runs the agent loop for you and includes tools such as Read, Edit and Bash. With tool use on the Messages API you define the tools and write the loop yourself, or use the beta tool runner.

### Does the Claude Agent SDK need Claude Code installed?

Usually not. Both SDKs bundle a native Claude Code binary. Some installs, such as the Python source distribution on ARM64 Windows, have no bundled binary and need Claude Code installed separately.

## Sources

- [Agent SDK overview](https://code.claude.com/docs/en/agent-sdk/overview), Anthropic
- [Agent SDK quickstart](https://code.claude.com/docs/en/agent-sdk/quickstart), Anthropic
- [Tool use with Claude](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview), Anthropic
- [Tutorial: Build a tool-using agent](https://platform.claude.com/docs/en/agents-and-tools/tool-use/build-a-tool-using-agent), Anthropic
