Skip to content
AI Skills Central

Type to search Agent Skills, workflows, tutorials, tools and the glossary.

Tutorial

Build an agent with the Claude Agent SDK

Built-in tools, a custom tool, a permission callback, a subagent and a project skill, tested before you spend tokens.

By Intermediate50 min hands-on
Bookmark

Bookmarks are kept in your free account, so you can find this page again on any device.

Sign in to bookmark
Quiz at the end
On this page

In this tutorial you build a release-notes agent on the Claude Agent SDK. It reads a project with Claude Code’s built-in tools, calls a custom tool you write for the list of merged pull requests, follows a house-style skill, hands its draft to a read-only checker subagent, and may write exactly one file. You will understand what the SDK gives you that a hand-written loop does not, and the three controls that decide what such an agent can do: which tools exist, which are approved, and the callback that decides the rest.

The first agent tutorial builds the loop by hand on the OpenAI Agents SDK. The Claude Agent SDK takes a different approach: it runs the same agent harness as Claude Code, with its tools, context management, subagents and skills, and you configure it from Python. This page was written against claude-agent-sdk 0.2.189, which bundles Claude Code 2.1.332, and checked against the Agent SDK documentation on 25 November 2026. The custom tool, the permission callback and the session set-up were run that day, and step 6 shows that output. The model run needs your API key, so this page shows no model output; yours will be the agent’s own words.

What the SDK handles for you

You write The SDK does
A prompt and an options object Runs the agent loop: model calls, tool calls, retries and context compaction
Nothing Provides Claude Code’s built-in tools: Read, Glob, Grep, Edit, Write, Bash, WebFetch and others
A Python function with @tool Serves it to Claude as an MCP tool, in your process
A permission callback Calls it for any tool call that no rule or mode has already decided
Subagent definitions Lets Claude delegate to them through the Agent tool, each with its own context and tools
SKILL.md folders on disk Discovers them and loads one when Claude decides it is relevant

1. Create the project

uv init --bare --python 3.12 release-agent
cd release-agent
uv add "claude-agent-sdk==0.2.189"
export ANTHROPIC_API_KEY=sk-ant-...

The SDK reads the key from the environment of the process that runs the agent. It does not load .env files. Anthropic’s quickstart also says that, unless Anthropic has approved it, a product you build on the SDK may not offer claude.ai login to its users; use API keys or a cloud provider’s credentials.

2. Give the agent something to work on

The agent needs a list of merged pull requests. In a real repository a tool would call your Git host. Here it reads a file, so the run is repeatable. Create prs.json:

[
  {"number": 412, "title": "Add CSV export to the reports page", "labels": ["feature"], "author": "priya"},
  {"number": 415, "title": "Fix crash when a report has no rows", "labels": ["bug"], "author": "tom"},
  {"number": 418, "title": "Bump requests from 2.32 to 2.33", "labels": ["dependencies"], "author": "dependabot"},
  {"number": 421, "title": "Speed up the dashboard query by caching totals", "labels": ["performance"], "author": "priya"},
  {"number": 423, "title": "Remove the deprecated /v1/export endpoint", "labels": ["breaking"], "author": "sam"}
]

Then a project skill with the house style. Create .claude/skills/release-notes/SKILL.md:

---
name: release-notes
description: House style for release notes. Use when writing or editing RELEASE_NOTES.md or any changelog entry for this project.
---

# Release notes house style

- Start with a "Breaking changes" section if any PR is labelled `breaking`. Say what users must change.
- Then "New", "Fixed" and "Faster" sections, in that order. Leave out empty sections.
- One bullet per PR, written for users, not developers. End each bullet with the PR number, like `(#412)`.
- Leave out dependency bumps unless they fix a security issue.
- No marketing words. Plain UK English.

The skill is plain instructions in a folder. Claude sees only its name and description until a task calls for it, then reads the rest. The same folder works in Claude Code itself; Agent Skills in Claude Code covers the format.

3. Write a custom tool

Create tools.py:

# tools.py: a custom tool the agent can call, served from an in-process MCP server
import json
from pathlib import Path
from typing import Any

from claude_agent_sdk import create_sdk_mcp_server, tool


@tool(
    "list_merged_prs",
    "List pull requests merged since the last release, with their labels.",
    {"since_tag": str},
)
async def list_merged_prs(args: dict[str, Any]) -> dict[str, Any]:
    # A real version would call your Git host's API with args["since_tag"].
    prs = json.loads(Path("prs.json").read_text())
    return {"content": [{"type": "text", "text": json.dumps(prs, indent=2)}]}


repo_server = create_sdk_mcp_server(name="repo", version="1.0.0", tools=[list_merged_prs])

@tool takes a name, a description and an input schema (here a simple type mapping), and the handler returns MCP-style content blocks. create_sdk_mcp_server wraps the tools in an MCP server that runs inside your Python process, so there is no separate server to start. Claude sees the tool as mcp__repo__list_merged_prs: mcp__, the server key you give it in the options, then the tool name.

4. Configure the agent

Create agent.py:

# agent.py: a release-notes agent on the Claude Agent SDK
import asyncio
import os

from claude_agent_sdk import (
    AgentDefinition,
    AssistantMessage,
    ClaudeAgentOptions,
    PermissionResultAllow,
    PermissionResultDeny,
    ResultMessage,
    TextBlock,
    ToolPermissionContext,
    ToolUseBlock,
    query,
)

from tools import repo_server

ALLOWED_OUTPUT = os.path.abspath("RELEASE_NOTES.md")


async def only_release_notes(
    tool_name: str, input_data: dict, context: ToolPermissionContext
) -> PermissionResultAllow | PermissionResultDeny:
    """Called for any tool call that no rule or mode has already approved."""
    if tool_name in ("Write", "Edit"):
        path = os.path.abspath(input_data.get("file_path", ""))
        if path == ALLOWED_OUTPUT:
            return PermissionResultAllow(updated_input=input_data)
        return PermissionResultDeny(message=f"You may only write {ALLOWED_OUTPUT}")
    return PermissionResultDeny(message=f"{tool_name} is not allowed in this agent")


options = ClaudeAgentOptions(
    model="claude-haiku-5-5",
    cwd=os.getcwd(),
    system_prompt="You write release notes for this repository. Be accurate: every PR you mention must exist.",
    mcp_servers={"repo": repo_server},
    allowed_tools=["Read", "Glob", "Grep", "Agent", "mcp__repo__list_merged_prs"],
    disallowed_tools=["Bash", "WebFetch", "WebSearch"],
    can_use_tool=only_release_notes,
    setting_sources=["project"],  # loads .claude/skills from this folder
    skills=["release-notes"],
    agents={
        "checker": AgentDefinition(
            description="Checks a release notes draft against the merged PR list. Use before finishing.",
            prompt="Read RELEASE_NOTES.md and compare it with the PR list you are given. "
            "Report any PR that is missing, wrongly described or in the wrong section. Do not edit files.",
            tools=["Read", "Grep"],
            model="haiku",
        )
    },
    max_turns=20,
    max_budget_usd=0.50,
)

PROMPT = (
    "Write RELEASE_NOTES.md for the release after tag v2.3.0. "
    "Get the merged PRs with the list_merged_prs tool, follow the release-notes skill, "
    "then ask the checker agent to review the draft and fix what it finds."
)


async def main() -> None:
    async for message in query(prompt=PROMPT, options=options):
        if isinstance(message, AssistantMessage):
            for block in message.content:
                if isinstance(block, ToolUseBlock):
                    print(f"tool: {block.name} {block.input}")
                elif isinstance(block, TextBlock):
                    print(block.text)
        elif isinstance(message, ResultMessage):
            print(f"done: {message.subtype}, {message.num_turns} turns, ${message.total_cost_usd}")


if __name__ == "__main__":
    asyncio.run(main())

The options are where the agent’s limits live. Read them as three layers:

  • What exists. disallowed_tools=["Bash", "WebFetch", "WebSearch"] removes those tools from Claude’s context, so it cannot run shell commands or reach the web at all. A bare tool name in this list removes the tool; a pattern such as Bash(rm *) would only deny matching calls.
  • What is pre-approved. allowed_tools approves the read-only tools, the subagent tool and the custom tool without asking. It does not restrict Claude to those tools; anything else still exists and falls through to the next layer.
  • What decides the rest. Write is neither removed nor pre-approved, so each call reaches only_release_notes, which allows one path and denies everything else. Since Claude Code 2.1.302, an SDK session with no permission mode starts in default mode, where a call that needs approval and has no rule, hook or callback to approve it is denied (SDK permissions).

The rest:

  • setting_sources=["project"] loads the project’s .claude/ folder, which is where the skill lives. Without a source that includes project, the SDK finds no project skills. It also means project CLAUDE.md and settings load, and your personal ~/.claude settings do not.
  • skills=["release-notes"] limits which skills Claude may invoke to that one.
  • The checker subagent gets only Read and Grep, and its own short prompt. Its context starts fresh: it sees only what Claude passes it, not the main conversation. AgentDefinition uses camelCase for multi-word fields such as disallowedTools, unlike ClaudeAgentOptions.
  • max_turns and max_budget_usd stop a confused run. If the budget is reached, the run ends with the result subtype error_max_budget_usd.
  • model="claude-haiku-5-5" is the cheapest current model on Anthropic’s models page. For harder writing, switch to claude-sonnet-5-5.

5. Check the tool and the callback without a model

Test the parts you wrote before spending tokens. Create check_offline.py:

# check_offline.py: test the tool and the permission callback without calling a model
import asyncio

from agent import only_release_notes
from tools import list_merged_prs


async def main() -> None:
    result = await list_merged_prs.handler({"since_tag": "v2.3.0"})
    print(result["content"][0]["text"][:120], "...")

    for name, data in [
        ("Write", {"file_path": "RELEASE_NOTES.md", "content": "x"}),
        ("Write", {"file_path": "src/app.py", "content": "x"}),
        ("Bash", {"command": "rm -rf build"}),
    ]:
        decision = await only_release_notes(name, data, None)
        print(name, data.get("file_path", data.get("command")), "->", decision.behavior)


asyncio.run(main())
uv run check_offline.py
[
  {
    "number": 412,
    "title": "Add CSV export to the reports page",
    "labels": [
      "feature"
    ],
    " ...
Write RELEASE_NOTES.md -> allow
Write src/app.py -> deny
Bash rm -rf build -> deny

list_merged_prs.handler is the decorated function, so you can unit-test tools like any other code. The callback is a plain async function too. Put both in your test suite.

6. Confirm the session loads what you expect

The first message of every session is a SystemMessage with subtype init that lists the tools, agents and skills the session has. Printing it is the quickest way to catch a skill that did not load or a tool you meant to remove. Create probe.py:

import asyncio

from claude_agent_sdk import SystemMessage, query

from agent import options


async def main():
    try:
        async for m in query(prompt="hi", options=options):
            if isinstance(m, SystemMessage) and m.subtype == "init":
                d = m.data
                print("skills:", [s for s in d.get("skills", []) if "release" in str(s)])
                print("tools:", [t for t in d.get("tools", []) if t.startswith("mcp__") or t in ("Agent", "Task", "Write", "Bash", "Skill")])
                print("agents:", d.get("agents"))
                print("permissionMode:", d.get("permissionMode"))
            else:
                print(type(m).__name__, getattr(m, "subtype", ""))
    except Exception as e:
        print("error:", str(e)[:120])


asyncio.run(main())
uv run probe.py

Our run, made without a key, shows the set-up before the session fails on authentication (the SDK’s warning is shortened here):

CanUseToolShadowedWarning: can_use_tool will not be invoked for: Read, Glob, Grep, Agent, mcp__repo__list_merged_prs. An allowed_tools entry that allows a whole tool auto-approves it before the callback is consulted. ...
skills: ['release-notes']
tools: ['Task', 'Skill', 'Write', 'mcp__repo__list_merged_prs']
agents: ['checker', 'claude', 'Explore', 'general-purpose', 'Plan', 'statusline-setup']
permissionMode: default
AssistantMessage
ResultMessage success
error: Claude Code returned an error result: Not logged in · Please run /login (exit code: 1)

What it tells you:

  • The release-notes skill was found, and the custom tool is registered.
  • Bash is absent from the tool list, because disallowed_tools removed it. Write is present but not pre-approved.
  • The subagent tool appears as Task in the init list, although tool-use blocks call it Agent; the SDK docs say to match both names when you detect subagent calls.
  • The checker agent is available, alongside Claude Code’s built-in ones such as Explore and general-purpose.
  • The warning is the SDK doing its job: it names the tools whose calls will never reach your callback because allowed_tools approves them first. That is what you want for read-only tools. If you ever need the callback to see every call to a tool, remove it from allowed_tools, or use a PreToolUse hook, which runs for approved calls too.
  • Without a key, the login error comes back as the assistant’s reply and a result marked success. The SDK then raises on the non-zero exit, so judge a run by whether it raises, not by the result subtype alone.

With ANTHROPIC_API_KEY set, the same probe prints the init lines and then the model’s reply instead of the login error.

7. Run the agent

uv run agent.py

The script prints each tool call and each block of Claude’s text as they stream, then a done: line with the result subtype, the number of turns and the cost in dollars. The order of calls and the wording are the model’s choice and change between runs.

Then check the work yourself, against the inputs, not against the agent’s summary:

  1. Every PR except the dependency bump appears once, with its number.
  2. The breaking change comes first and says what users must change.
  3. No file other than RELEASE_NOTES.md changed (git status if the folder is a repository).

To see the callback at work in a real run, change the prompt to ask for a copy in docs/RELEASE_NOTES.md as well. The callback denies that write with your message, and Claude receives the message as the tool result.

Pitfalls

Not logged in · Please run /login. The key is not in the environment of the process running the agent. Export it in the same shell, or load your .env yourself before calling the SDK.

The skill never loads. setting_sources must include "project" for .claude/skills/ in your working folder, and cwd must be at or below the folder that holds .claude/. The init message’s skills list shows what was found.

Your callback never sees a call. A bare tool name in allowed_tools approves every call to that tool before the callback runs, and so do acceptEdits and bypassPermissions modes. The CanUseToolShadowedWarning names the affected tools. Keep checks that must always run in a hook.

allowed_tools with bypassPermissions approves everything. In bypass mode, tools you did not list are approved too. Use disallowed_tools for anything the agent must not have, whatever the mode.

TypeError from AgentDefinition. Its multi-word fields are camelCase (disallowedTools, mcpServers, maxTurns), unlike ClaudeAgentOptions. A snake_case keyword raises.

Breaking out of the message loop early. The SDK docs warn that break inside async for can cause asyncio clean-up problems. Let the stream end, or use ClaudeSDKClient and its interrupt support when you need to stop.

Next steps

Covers

Check your understanding

Claude Agent SDK quiz

What the SDK runs for you, custom tools, the three permission layers, setting sources and skills, subagents, the init message, testing without a model and common pitfalls.

8 questions · pass mark 70%

Question 1 of 80 answered
  1. You add "Bash" to disallowed_tools. What does that do?
Back to top