Skip to content
Easy AI How-To

AdvancedClaudeBuilding

Build your first AI agent with tool use (Claude subscription, no API key)

This guide is for developers who know a little Python and want to build a real agent: Claude decides which of your tools to call, the tools run, and a loop continues until the job is done. The main path runs on a Claude Pro or Max subscription through the Claude Agent SDK, so you don't need an API key or a per-call bill. The main example is about 40 lines. The last section rebuilds the same agent on the pay-per-call Claude API, so you also learn the loop, tokens, and cost. Everything here was checked against Anthropic's and OpenAI's docs on October 17, 2026. SDKs and model names change, so check the linked docs before you ship.

Time
About 35 minutes
Checked
Tools
Claude Agent SDK overview, Agent SDK: custom tools, Claude Code authentication, Claude Code legal and compliance, OpenAI Codex CLI, Claude API tool use overview, Stop reasons

If a button name on the screen does not match this guide, follow the action. These products rename buttons often. This is an advanced guide: it uses code, and each technical term is explained the first time it appears. Model names and prices change, so check the linked docs before you ship.

Steps

  1. Know what an agent is

    Tool use (also called function calling) lets Claude ask your program to run a function you describe. Claude never runs your code itself: it asks, your code does the work, and the result goes back to Claude. An agent is that exchange in a loop. Claude asks for a tool, the tool runs, Claude reads the result and either asks for another tool or gives its final answer. The code that repeats this is the agent loop. A harness is a program that runs that loop for you. Here the harness is Claude Code, driven from Python by the Claude Agent SDK.

  2. Sign in to Claude Code with your subscription

    Install Claude Code, then run claude once. On first launch it opens a browser so you can log in with your claude.ai account (Pro or Max):

    curl -fsSL https://claude.ai/install.sh | bash   # Windows PowerShell: irm https://claude.ai/install.ps1 | iex
    unset ANTHROPIC_API_KEY                          # an API key would take priority over your login
    claude
    

    Inside Claude Code, run /status to confirm you're using your subscription login, then exit. Your agent's usage counts against your plan's limits instead of a per-call bill.

  3. Set up the project

    Make a folder with a virtual environment and install the Agent SDK. The Python package bundles the Claude Code binary, and it uses the same login.

    mkdir first-agent && cd first-agent
    python3 -m venv .venv && source .venv/bin/activate
    pip install claude-agent-sdk
    
  4. Write the agent: two custom tools and a query

    A custom tool is an async Python function marked with the @tool decorator. You give it a name, a description, and an input schema (here a simple dict of names to types). The description matters most, because it's how Claude decides when to call the tool. create_sdk_mcp_server wraps your tools in an in-process MCP server, so they run inside your script, not as a separate program. Each tool's full name is mcp__{server}__{tool}. Listing those names in allowed_tools lets them run without a permission prompt. tools=[] removes Claude Code's built-in tools (files, shell), so this agent can only use yours. Save this as agent.py:

    import asyncio
    from datetime import date, datetime, timedelta
    from zoneinfo import ZoneInfo
    
    from claude_agent_sdk import (AssistantMessage, ClaudeAgentOptions, ResultMessage,
                                  ToolUseBlock, create_sdk_mcp_server, query, tool)
    
    
    def reply(text):
        return {"content": [{"type": "text", "text": text}]}
    
    
    @tool("get_current_time", "Current date, time, and weekday in an IANA time zone, such as America/Chicago", {"timezone": str})
    async def get_current_time(args):
        now = datetime.now(ZoneInfo(args["timezone"]))
        return reply(f"{now:%Y-%m-%d %H:%M}, {now:%A}")
    
    
    @tool("add_days", "Add days (negative to go back) to a YYYY-MM-DD date. Returns the new date and weekday", {"start_date": str, "days": int})
    async def add_days(args):
        new_date = date.fromisoformat(args["start_date"]) + timedelta(days=args["days"])
        return reply(f"{new_date.isoformat()}, {new_date:%A}")
    
    
    options = ClaudeAgentOptions(
        mcp_servers={"dates": create_sdk_mcp_server(name="dates", version="1.0.0", tools=[get_current_time, add_days])},
        allowed_tools=["mcp__dates__get_current_time", "mcp__dates__add_days"],
        tools=[],      # no built-in tools (files, shell): only yours
        max_turns=10,  # safety stop
    )
    
    
    async def main():
        async for message in query(prompt="What date is 45 days from today in Chicago, and what weekday is that?", options=options):
            if isinstance(message, AssistantMessage):
                for block in message.content:
                    if isinstance(block, ToolUseBlock):
                        print(f"tool call: {block.name} {block.input}")
            elif isinstance(message, ResultMessage):
                print(f"\n[{message.subtype}] {message.result}")
    
    
    asyncio.run(main())
    

    There's no loop in your code. query runs it: each message it streams is a step, and max_turns stops it if it never finishes.

  5. Run it and watch the tool calls

    Run python agent.py. You should see lines like tool call: mcp__dates__get_current_time {'timezone': 'America/Chicago'}, then mcp__dates__add_days with today's date and 45, and finally [success] with the answer. Claude may call the tools in one turn or across several. Tool search is on by default, so you may also see a ToolSearch call while Claude loads your tool's schema. Those printed lines are your trace, the first place to look when an agent misbehaves. If you see Not logged in, run claude again and sign in, and make sure ANTHROPIC_API_KEY isn't set.

  6. What your subscription login is (and isn't) for

    Anthropic's docs are explicit here. The subscription sign-in is for you, running Claude Code and your own Agent SDK scripts. Pro and Max limits "assume ordinary, individual usage of Claude Code and the Agent SDK." The Agent SDK quickstart itself shows API-key setup, and Anthropic does not allow developers to offer claude.ai login inside their own products, or to route other people's requests through a Free, Pro, or Max plan. So: learn and build personal tools on your subscription. When you ship an agent for other people, switch it to an API key (or a supported cloud provider), which is the last section of this guide.

  7. On ChatGPT: Codex CLI

    The ChatGPT-side equivalent is OpenAI's Codex CLI. Install it (curl -fsSL https://chatgpt.com/codex/install.sh | sh on macOS or Linux), run codex, and choose Sign in with ChatGPT. You can add your own tools to it as MCP servers with codex mcp, and script it with codex exec.

  8. Next step: the same agent on the API (pay per call)

    The harness hid the loop. To see exactly what it does, and to learn about tokens and cost, build the same agent on the raw Claude API. Here you write the loop, and every turn is a billed API call. Create an API key in the Claude Console under API keys (API billing is separate from a claude.ai subscription), store it in an environment variable, never in code, and install the Anthropic Python SDK:

    export ANTHROPIC_API_KEY="your-key-here"
    pip install anthropic
    

    You'll build one file, agent_api.py, in three parts. Paste each part below the last one.

  9. API version, part 1: describe your tools

    A tool definition has three fields: name (letters, numbers, _ or -), description (plain English: what it does, when to use it, what it returns), and input_schema (a JSON Schema, a standard way to describe the arguments and their types). The description matters most, because it's how Claude decides when to call the tool. This agent gets two small tools that need no outside service: one reads the clock, one does date math.

    import json
    from datetime import date, datetime, timedelta
    from zoneinfo import ZoneInfo
    
    import anthropic
    
    client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY
    MODEL = "claude-sonnet-5-5"
    MAX_TURNS = 10  # stop condition: never let the loop run forever
    
    tools = [
        {
            "name": "get_current_time",
            "description": (
                "Returns the current date, time, and weekday in one IANA time zone, "
                "such as America/Chicago. Use it whenever the answer depends on "
                "today's date or the current time. It does not convert between zones."
            ),
            "input_schema": {
                "type": "object",
                "properties": {
                    "timezone": {
                        "type": "string",
                        "description": "IANA time zone name, e.g. America/Chicago",
                    }
                },
                "required": ["timezone"],
            },
        },
        {
            "name": "add_days",
            "description": (
                "Adds a number of days to a calendar date and returns the new date "
                "and its weekday. Use a negative number to go back in time. "
                "The start date must be in YYYY-MM-DD format."
            ),
            "input_schema": {
                "type": "object",
                "properties": {
                    "start_date": {"type": "string", "description": "Date as YYYY-MM-DD"},
                    "days": {"type": "integer", "description": "Days to add (negative subtracts)"},
                },
                "required": ["start_date", "days"],
            },
        },
    ]
    

    claude-sonnet-5-5 is a fast, mid-priced current model. Check the models page for the latest IDs.

  10. API version, part 2: write the functions the tools run

    These are ordinary Python functions. run_tool looks up the function by the name Claude asked for and returns its output as text. If something goes wrong, it returns the error message and a flag instead of crashing, so Claude can see what happened and try again.

    def get_current_time(timezone):
        now = datetime.now(ZoneInfo(timezone))
        return json.dumps({"now": now.isoformat(timespec="minutes"), "weekday": now.strftime("%A")})
    
    
    def add_days(start_date, days):
        result = date.fromisoformat(start_date) + timedelta(days=days)
        return json.dumps({"date": result.isoformat(), "weekday": result.strftime("%A")})
    
    
    TOOL_FUNCTIONS = {"get_current_time": get_current_time, "add_days": add_days}
    
    
    def run_tool(name, tool_input):
        """Run one tool. Returns (output_text, is_error)."""
        if name not in TOOL_FUNCTIONS:
            return f"Unknown tool: {name}", True
        try:
            return TOOL_FUNCTIONS[name](**tool_input), False
        except Exception as error:  # report the problem to Claude instead of crashing
            return f"{type(error).__name__}: {error}", True
    
  11. API version, part 3: write the agent loop yourself

    Every API response has a stop_reason: why Claude stopped writing. "tool_use" means Claude wants a tool. Its reply then contains one or more tool_use blocks, each with an id, the tool name, and an input that matches your schema. You run each one and answer with a user message of tool_result blocks. Each result carries the matching tool_use_id and your output as content, plus is_error: true if the tool failed. Any other stop reason ends the loop. MAX_TURNS is your safety stop, so a confused agent can't call tools (and spend money) forever. Run it with python agent_api.py: the printed turn N: stop_reason=... lines are the same trace the SDK showed you, now with the loop in plain sight.

    def run_agent(question):
        messages = [{"role": "user", "content": question}]
    
        for turn in range(1, MAX_TURNS + 1):
            response = client.messages.create(
                model=MODEL,
                max_tokens=1024,
                tools=tools,
                messages=messages,
            )
            print(f"turn {turn}: stop_reason={response.stop_reason}")
    
            # Anything other than "tool_use" means Claude is done (or stopped for another reason).
            if response.stop_reason != "tool_use":
                answer = "".join(block.text for block in response.content if block.type == "text")
                return answer, response.stop_reason
    
            # Keep Claude's full reply, including its tool_use blocks, in the history.
            messages.append({"role": "assistant", "content": response.content})
    
            # Run every tool Claude asked for and send all results back in ONE user message.
            results = []
            for block in response.content:
                if block.type == "tool_use":
                    output, failed = run_tool(block.name, block.input)
                    print(f"  {block.name}({block.input}) -> {output}")
                    results.append(
                        {
                            "type": "tool_result",
                            "tool_use_id": block.id,
                            "content": output,
                            "is_error": failed,
                        }
                    )
            messages.append({"role": "user", "content": results})
    
        return f"Stopped after {MAX_TURNS} turns without a final answer.", "max_turns"
    
    
    if __name__ == "__main__":
        answer, reason = run_agent("What date is 45 days from today in Chicago, and what weekday is that?")
        print(f"\n[{reason}]\n{answer}")
    
  12. API version: handle every way the loop can end

    end_turn is the normal finish. max_tokens means the reply hit your max_tokens cap and was cut off. If the last block is a half-written tool_use, retry with a higher cap. refusal means Claude declined the request. max_turns is the label this script uses when it hits its own MAX_TURNS limit. It isn't an API value. In a real app, treat everything except end_turn as "not finished" and log it instead of showing it as an answer. (If you later add Anthropic-run server tools such as web search, also handle pause_turn by sending the conversation back so Claude can continue.)

  13. Check the answer yourself

    Look at the trace. Did Claude pass the right time zone? Did add_days get today's date and 45? Check the final date against a calendar. An agent can call the right tools and still word the answer wrong, so check the final answer against the tool outputs. This applies to both versions. Before you give an agent tools that change things (send email, delete files, spend money), add a step where a person approves each of those actions.

Tips

  • Start on your subscription to learn. Move to an API key before other people use your agent.

  • Keep tools=[] (or a short list of built-ins) until you trust the agent. Adding Bash or Edit lets it run commands and change files.

  • API version: send the assistant's full response.content back unchanged. Dropping its tool_use blocks, or sending a tool result without its matching tool_use_id, causes a 400 error.

  • In the message with your tool results, put the tool_result blocks first and don't add text after them. Extra text after results can make Claude end its turn early.

  • Treat tool output that comes from outside (web pages, emails, uploads) as untrusted. Keep it inside tool_result blocks, never in your system prompt, because it may contain instructions meant to hijack the agent.

  • On Claude Opus 5.5 and Sonnet 5.5, forcing a tool with tool_choice set to any or tool returns a 400 error. Leave it on the default (auto) and say in the prompt when a tool should be used.

  • On Windows, ZoneInfo needs time zone data: run pip install tzdata if you get a ZoneInfoNotFoundError.

Common questions

Why start with the Agent SDK instead of the API?

Paying per call while you experiment adds up, and an API account needs billing set up first. The Agent SDK runs on the Claude subscription you may already have, and it handles the loop, retries, and context for you. The API version teaches what the harness does, and it's what you use when you ship to other people.

On the API, is there a way to skip writing the loop?

Yes. The Anthropic Python SDK has a beta Tool Runner (client.beta.messages.tool_runner) that builds tool definitions from functions marked with @beta_tool and runs the loop for you. Writing the loop by hand once shows you what it does, and you'll need that knowledge when you add approvals, logging, or limits.

How is this different from an MCP server?

The Agent SDK version actually uses one: create_sdk_mcp_server is a small MCP server that lives inside your script. A standalone MCP server packages tools so any MCP-capable app, such as Claude Desktop, can use them. See Build your first MCP server for that route.

How much does an agent run cost?

On the subscription path, it counts against your plan's usage limits, with no per-call bill. On the API, every turn is a normal API call. Your tool definitions, the growing conversation, and every tool_use and tool_result block count as tokens, so long loops get more expensive with each turn. Keep MAX_TURNS low while testing. Use prompt caching when the same long instructions repeat, and check usage in the Console.

How do I know my agent is good, not just working once?

Write a few test questions with known answers and run them after every change. The evals guide shows how.

Free newsletter

Learn AI by doing, one how-to at a time

New how-tos across all of AI: everyday tools, RAG, agents, local models, and taking a proof of concept to production. Each one is something you can try yourself, because the best way to learn AI is by doing it. Free, and you can unsubscribe in one click.

Subscribe free

Opens our sign-up page on beehiiv. Privacy