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
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
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.
Sign in to Claude Code with your subscription
Install Claude Code, then run
claudeonce. 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 claudeInside Claude Code, run
/statusto 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.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-sdkWrite the agent: two custom tools and a query
A custom tool is an async Python function marked with the
@tooldecorator. 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_serverwraps your tools in an in-process MCP server, so they run inside your script, not as a separate program. Each tool's full name ismcp__{server}__{tool}. Listing those names inallowed_toolslets 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 asagent.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.
queryruns it: each message it streams is a step, andmax_turnsstops it if it never finishes.Run it and watch the tool calls
Run
python agent.py. You should see lines liketool call: mcp__dates__get_current_time {'timezone': 'America/Chicago'}, thenmcp__dates__add_dayswith today's date and45, 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 aToolSearchcall while Claude loads your tool's schema. Those printed lines are your trace, the first place to look when an agent misbehaves. If you seeNot logged in, runclaudeagain and sign in, and make sureANTHROPIC_API_KEYisn't set.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.
On ChatGPT: Codex CLI
The ChatGPT-side equivalent is OpenAI's Codex CLI. Install it (
curl -fsSL https://chatgpt.com/codex/install.sh | shon macOS or Linux), runcodex, and choose Sign in with ChatGPT. You can add your own tools to it as MCP servers withcodex mcp, and script it withcodex exec.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 anthropicYou'll build one file,
agent_api.py, in three parts. Paste each part below the last one.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), andinput_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-5is a fast, mid-priced current model. Check the models page for the latest IDs.API version, part 2: write the functions the tools run
These are ordinary Python functions.
run_toollooks 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}", TrueAPI 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 moretool_useblocks, each with anid, the toolname, and aninputthat matches your schema. You run each one and answer with ausermessage oftool_resultblocks. Each result carries the matchingtool_use_idand your output ascontent, plusis_error: trueif the tool failed. Any other stop reason ends the loop.MAX_TURNSis your safety stop, so a confused agent can't call tools (and spend money) forever. Run it withpython agent_api.py: the printedturn 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}")API version: handle every way the loop can end
end_turnis the normal finish.max_tokensmeans the reply hit yourmax_tokenscap and was cut off. If the last block is a half-writtentool_use, retry with a higher cap.refusalmeans Claude declined the request.max_turnsis the label this script uses when it hits its ownMAX_TURNSlimit. It isn't an API value. In a real app, treat everything exceptend_turnas "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 handlepause_turnby sending the conversation back so Claude can continue.)Check the answer yourself
Look at the trace. Did Claude pass the right time zone? Did
add_daysget today's date and45? 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. AddingBashorEditlets it run commands and change files.API version: send the assistant's full
response.contentback unchanged. Dropping itstool_useblocks, or sending a tool result without its matchingtool_use_id, causes a 400 error.In the message with your tool results, put the
tool_resultblocks 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_resultblocks, 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_choiceset toanyortoolreturns a 400 error. Leave it on the default (auto) and say in the prompt when a tool should be used.On Windows,
ZoneInfoneeds time zone data: runpip install tzdataif 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.
More guides
BeginnerClaudeDocuments
Explain a bill or official letter
Paste a bill or letter into free Claude and get plain English, the deadline, and what is actually being asked.
About 10 minutes using Claude
BeginnerClaudeWriting
Write a clear email
Tell free Claude who you are writing to and what you need. You get a short draft, and you send it yourself.
About 8 minutes using Claude
BeginnerClaudeWriting
Rewrite resume bullets from real work
Ask free Claude for three resume bullets that use only the facts you provide, with blanks where a number is missing.
About 12 minutes using Claude