← THE LIBRARY

Engineering / Agent framework / FIELD GUIDE

Build your first agent with the Claude Agent SDK

One file, one custom tool, a locked permission policy and a run you can check line by line.

Checked 22 Oct 2026

Pinned source guide with authored example files. Original project by Anthropic; guide and labeled adaptations by Agent Setup Kits.

Use case
First agent in your code
Architecture
Single agent, one tool
Trigger
Manual, python agent.py
Runs
Your machine, your key
License
MIT repo, Commercial Terms
Human approval
Fixed allowlist, rest denied

First step

bash
mkdir claude-agent-first && cd claude-agent-first

Copy this first step, then read the setup and the human approval notes before you go further.

01 / PURPOSE

The autonomous job

Answer one prompt by calling a single custom tool (a word counter) through the Claude Agent SDK, with every built-in tool removed and anything not pre-approved denied, then print the full message stream for inspection.

02 / SYSTEM

Architecture and handoffs

Single agent in your own process. The script builds ClaudeAgentOptions and opens a ClaudeSDKClient; the SDK runs the bundled Claude Code binary, which calls the Anthropic API. The custom tool runs in an in-process SDK MCP server named counter and is addressed as mcp__counter__word_count. tools=[] removes built-ins, permission_mode=dontAsk denies anything not on the allowlist, setting_sources=[] skips filesystem settings, and ENABLE_TOOL_SEARCH=false loads the tool schema up front.

System for Build your first agent with the Claude Agent SDK Your process: tools=[], dontAsk run + API key prompt + options model turns allowed call removed / denied message stream HUMAN Developer SERVICE agent.py AGENT Claude agent (SDK + binary) SERVICE word_count tool SERVICE Anthropic API SERVICE Built-in tools ASK
Built from this kit's roles, tools and boundaryHumanAgentServiceBoundary
01 / HUMAN

Developer

Writes the script, sets the API key, runs it and checks the output

HandoffDecides whether the run proved the tool call

02 / AGENT

Claude agent (via Claude Code binary)

Plans, calls the word_count tool and reports the result

HandoffEnds with a ResultMessage

03 / SERVICE

Anthropic API

Serves each model turn

HandoffReturns model output to the binary

04 / SERVICE

word_count tool (in-process MCP server)

Counts words in the given text

HandoffReturns a text content block to the agent

Model
Anthropic hosted model; the SDK default when model is unset. No model ID is pinned in this kit.
Memory
Single session, no resume. setting_sources=[] skips user, project and local settings and CLAUDE.md; managed policy, ~/.claude.json and auto memory under ~/.claude/projects/ are still read per Anthropic's docs.

03 / CONNECTIONS

Tools and triggers

Tool access described by this edition
ToolPurposeAccess
mcp__counter__word_countCount the words in a block of textPure function in your process; pre-approved by full name; no filesystem, shell or network

What starts the work

  • Manual A developer runs python agent.py (or npx tsx agent.ts) with ANTHROPIC_API_KEY set in the shell.
Permissions in this edition
ControlDecision
Call one in-process pure functionYes
Send the prompt and tool results to the Anthropic APIYes
Read the API key from the process environmentYes
No runtime human approval: the kit is a fixed allowlist; the tool runs without a prompt and anything else that needs approval is denied by dontAsk.Ask
Enforced by the SDK: built-ins removed and unapproved calls denied.Ask
Not enforced: the system prompt that tells Claude to use the tool is guidance only.Ask
To add a gate, use can_use_tool (not reached by allowlisted tools) or a PreToolUse hook for every call.Ask
bypassPermissions is excluded; it approves every tool that deny rules do not block, and the allowlist does not limit it.Ask
Built-in tools removed (tools=[]); only mcp__counter__word_count is allowed; permission_mode dontAsk denies every other call that would need approval; user, project and local settings skipped (setting_sources=[]); auto memory off (CLAUDE_CODE_DISABLE_AUTO_MEMORY=1); managed policy and ~/.claude.json still load; max_turns=4. The process still runs with the invoking user's permissions.Yes

04 / BOUNDARIES

Capabilities and safety

Credentials
ANTHROPIC_API_KEY (or cloud provider credentials) set in the shell; the SDK does not load .env files. Never put the key in the script or commit it.
Shutdown
The script exits after the ResultMessage; Ctrl+C stops it early. max_turns=4 caps the loop.

Capabilities

  • Call one in-process pure function
  • Send the prompt and tool results to the Anthropic API
  • Read the API key from the process environment

05 / SETUP

The files behind the workflow.

Start with INSTALL.md and the setup notes above. Original-project files retain their attribution and license; our installation notes, dependency profiles and custom wrappers are identified separately.

  1. Create the project

  2. Install the SDK

  3. Set your key

  4. Add agent.py

  5. Run it and check four things

INSTALL.mdView file +

Setup instructions, prerequisites and edition-specific integration notes

Download INSTALL.md ↓

# Claude Agent SDK setup kit: install notes

Checked 2026-10-22 against anthropics/claude-agent-sdk-python at commit 6b4a557e9f395934bd16e78b04e0f09833eb387e (v0.2.172) and the official Agent SDK docs. The TypeScript path was checked against @anthropic-ai/claude-agent-sdk 0.3.308.

## Requirements
- Python 3.10 or later (package metadata), or Node.js 18 or later (npm engines field). You need only one.
- An Anthropic API key from the Claude Console, or a supported cloud provider (see below).
- Billing: every run uses tokens. Check Anthropic's pricing page before leaving anything running.

## Python
```bash
mkdir claude-agent-first && cd claude-agent-first
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt     # claude-agent-sdk==0.2.172
export ANTHROPIC_API_KEY=...        # set it in this shell; never in the file
python agent.py
```
The wheel bundles the Claude Code CLI (2.1.308 for this release), so no separate install is needed on platforms with a prebuilt wheel. If pip falls back to the source distribution (Anthropic's example is ARM64 Windows), install Claude Code natively or set `cli_path`.

## TypeScript
```bash
npm install          # uses package.json in this kit
export ANTHROPIC_API_KEY=...
npx tsx agent.ts
```
npm 7 or later installs the SDK's peer dependencies (@anthropic-ai/sdk, @modelcontextprotocol/sdk) automatically. Do not install with `--omit=optional`: the bundled Claude Code binary arrives through optional dependencies.

## Keys and providers
The SDK reads `ANTHROPIC_API_KEY` from the process environment. It does not load `.env` files. If you keep one, load it yourself and add `.env` to `.gitignore`.
Cloud providers are selected with environment variables plus that cloud's credentials: `CLAUDE_CODE_USE_BEDROCK=1`, `CLAUDE_CODE_USE_ANTHROPIC_AWS=1` with `ANTHROPIC_AWS_WORKSPACE_ID`, `CLAUDE_CODE_USE_VERTEX=1`, or `CLAUDE_CODE_USE_FOUNDRY=1`.
Anthropic does not allow third-party developers to offer claude.ai login or rate limits in products built on the SDK unless previously approved. This kit uses an API key.

Agent Setup Kits authored documentation for Pinned source guide with authored example files; upstream code and licenses remain attributed separately

agent.pyView file +

The one-tool Python agent

Download agent.py ↓

# agent.py: a one-tool Claude Agent SDK agent.
# Pattern adapted from the README of anthropics/claude-agent-sdk-python (MIT),
# pinned at commit 6b4a557e9f395934bd16e78b04e0f09833eb387e (v0.2.172).
import asyncio

from claude_agent_sdk import (
    ClaudeAgentOptions,
    ClaudeSDKClient,
    ResultMessage,
    create_sdk_mcp_server,
    tool,
)


@tool("word_count", "Count the words in a block of text", {"text": str})
async def word_count(args):
    count = len(args["text"].split())
    return {"content": [{"type": "text", "text": f"{count} words"}]}


counter = create_sdk_mcp_server(name="counter", version="1.0.0", tools=[word_count])

options = ClaudeAgentOptions(
    mcp_servers={"counter": counter},
    tools=[],                                   # remove every built-in tool
    allowed_tools=["mcp__counter__word_count"], # pre-approve the one tool
    permission_mode="dontAsk",                  # deny anything not pre-approved
    setting_sources=[],                         # ignore local Claude Code settings
    env={
        "ENABLE_TOOL_SEARCH": "false",          # load the tool schema up front
        "CLAUDE_CODE_DISABLE_AUTO_MEMORY": "1", # keep auto memory out of the prompt
    },
    system_prompt="You count words. Always use the word_count tool, then report the number.",
    max_turns=4,
)


async def main():
    async with ClaudeSDKClient(options=options) as client:
        await client.query(
            "How many words are in: the quick brown fox jumps over the lazy dog"
        )
        async for message in client.receive_response():
            print(message)
            if isinstance(message, ResultMessage):
                # subtype "success" alone is not enough: an API error or a
                # refusal also arrives as success with is_error=True.
                ok = (
                    message.subtype == "success"
                    and not message.is_error
                    and message.terminal_reason == "completed"
                )
                print("RUN OK" if ok else f"RUN FAILED: {message.terminal_reason} {message.result}")


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

Agent Setup Kits authored, adapted from the custom-tool example in the upstream README (MIT) at the pinned commit; import-checked against claude-agent-sdk 0.2.172

agent.tsView file +

The same agent with the TypeScript SDK

Download agent.ts ↓

// agent.ts: the same one-tool agent with the TypeScript SDK.
// The npm package @anthropic-ai/claude-agent-sdk is distributed under
// Anthropic's Commercial Terms ("SEE LICENSE IN README.md"), not MIT.
import { query, tool, createSdkMcpServer } from "@anthropic-ai/claude-agent-sdk";
import { z } from "zod";

const wordCount = tool(
  "word_count",
  "Count the words in a block of text",
  { text: z.string() },
  async ({ text }) => ({
    content: [{ type: "text", text: `${text.trim().split(/\s+/).length} words` }],
  })
);

const counter = createSdkMcpServer({ name: "counter", version: "1.0.0", tools: [wordCount] });

for await (const message of query({
  prompt: "How many words are in: the quick brown fox jumps over the lazy dog",
  options: {
    mcpServers: { counter },
    tools: [],
    allowedTools: ["mcp__counter__word_count"],
    permissionMode: "dontAsk",
    settingSources: [],
    env: { ...process.env, ENABLE_TOOL_SEARCH: "false", CLAUDE_CODE_DISABLE_AUTO_MEMORY: "1" }, // env replaces, so spread
    systemPrompt: "You count words. Always use the word_count tool, then report the number.",
    maxTurns: 4,
  },
})) {
  console.log(message);
  if (message.type === "result") {
    // "success" alone is not enough: an API error or refusal also arrives as success with is_error true.
    const ok = message.subtype === "success" && !message.is_error && message.terminal_reason === "completed";
    console.log(ok ? "RUN OK" : `RUN FAILED: ${message.terminal_reason}`);
  }
}

Agent Setup Kits authored, adapted from the official custom tools guide; type-checked against @anthropic-ai/claude-agent-sdk 0.3.308

requirements.txtView file +

Exact Python SDK pin

Download requirements.txt ↓

# Exact pin checked 2026-10-22. Its own dependencies resolve from PyPI at install time.
claude-agent-sdk==0.2.172

Agent Setup Kits authored

package.jsonView file +

Exact TypeScript dependency pins

Download package.json ↓

{
  "name": "claude-agent-first",
  "private": true,
  "type": "module",
  "scripts": { "start": "tsx agent.ts" },
  "dependencies": {
    "@anthropic-ai/claude-agent-sdk": "0.3.308",
    "zod": "4.6.7"
  },
  "devDependencies": {
    "tsx": "4.23.15"
  }
}

Agent Setup Kits authored

SOURCE.mdView file +

Original-project attribution, source hashes and adaptation notes

Download SOURCE.md ↓

# Sources and attribution

Based on the Claude Agent SDK, by Anthropic.
- Python SDK: https://github.com/anthropics/claude-agent-sdk-python, pinned at https://github.com/anthropics/claude-agent-sdk-python/commit/6b4a557e9f395934bd16e78b04e0f09833eb387e (v0.2.172, released 2026-10-22). Repository LICENSE file: MIT (copy included as LICENSE-claude-agent-sdk-python.txt).
- TypeScript SDK: https://github.com/anthropics/claude-agent-sdk-typescript, tag v0.3.308 at https://github.com/anthropics/claude-agent-sdk-typescript/commit/c17fea5598f39c93fefa63608586fe58519837b6. The npm package declares "SEE LICENSE IN README.md".

Anthropic's README and docs state that use of the SDK is governed by Anthropic's Commercial Terms of Service (https://www.anthropic.com/legal/commercial-terms), except where a component's own LICENSE file says otherwise. The models are Anthropic's paid, hosted service.

What Agent Setup Kits wrote: agent.py and agent.ts (adapted from the custom-tool example in the upstream README and the official custom tools guide), requirements.txt, package.json, INSTALL.md and this file. This guide is independent and not endorsed by Anthropic.

Agent Setup Kits authored documentation for Pinned source guide with authored example files; upstream code and licenses remain attributed separately

LICENSE-claude-agent-sdk-python.txtView file +

Upstream MIT license text

Download LICENSE-claude-agent-sdk-python.txt ↓

MIT License

Copyright (c) 2025 Anthropic, PBC

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Verbatim copy of LICENSE at the pinned commit

06 / ORIGINAL WORK

Sources, pins, and license

This guide draws on Claude Agent SDK by Anthropic, at the linked source revision. Agent Setup Kits is independent of the upstream project. Edition-specific changes are labeled in the file provenance.

Claude Agent SDK, by Anthropic

Pinned source guide with authored example files

Open source
Sources this edition relies on
SourceWhat it supports
Immutable source revision (tag v0.2.172) ↗Exact Python SDK snapshot
README.md ↗pip install, Python 3.10+, bundled CLI, cli_path, allowed_tools is a permission allowlist, custom tool example, Commercial Terms note
pyproject.toml ↗version 0.2.172, requires-python >=3.10, license MIT
src/claude_agent_sdk/types.py ↗ClaudeAgentOptions fields tools, allowed_tools, permission_mode (incl. dontAsk, auto), setting_sources, max_turns, max_budget_usd, env, cli_path; ResultMessage fields
src/claude_agent_sdk/_cli_version.py ↗Bundled Claude Code CLI 2.1.308
LICENSE ↗MIT license file
TypeScript SDK tag v0.3.308 ↗TypeScript package version checked
npm @anthropic-ai/claude-agent-sdk 0.3.308 ↗Node >=18 engines, license SEE LICENSE IN README.md, zod ^4 peer
Agent SDK overview (official docs) ↗Agent SDK vs Client SDK vs Managed Agents, claude.ai login restriction, Commercial Terms
Quickstart (official docs) ↗Node 18+ or Python 3.10+, bundled binary exceptions, no .env loading, provider env vars, auth error strings
Custom tools (official docs) ↗@tool and tool() signatures, create_sdk_mcp_server, mcp__server__tool naming, tools: [] removes built-ins, tool search default
Configure permissions (official docs) ↗Evaluation order, dontAsk lockdown pattern, bypassPermissions warning, canUseTool not reached by allowed tools, PreToolUse hook
Python reference (official docs) ↗max_budget_usd estimate can overshoot, setting_sources=[] ignored in 0.1.59 and earlier, ResultMessage subtypes
Tool search (official docs) ↗Tool search on by default; ENABLE_TOOL_SEARCH=false loads all definitions up front
Claude Code features in the SDK (official docs) ↗What settingSources does not control
Migration guide (official docs) ↗Rename from Claude Code SDK and package names; settingSources default
Anthropic Commercial Terms of Service ↗Terms referenced by the SDK README and docs
Source versions and guide targets
ComponentPinSource
Python SDK source (tag v0.2.172)6b4a557e9f395934bd16e78b04e0f09833eb387eOriginal source ↗
claude-agent-sdk (PyPI)0.2.172Original source ↗
Bundled Claude Code CLI2.1.308Original source ↗
@anthropic-ai/claude-agent-sdk (npm)0.3.308Original source ↗
zod (npm)4.6.7Original source ↗
tsx (npm)4.23.15Original source ↗

MIT (Python SDK repository); Anthropic Commercial Terms govern use

The Python SDK repository LICENSE file is MIT. Anthropic's README and docs state that use of the SDK is governed by Anthropic's Commercial Terms of Service except where a component's LICENSE file says otherwise. The TypeScript npm package declares SEE LICENSE IN README.md and is not MIT. The models are Anthropic's paid hosted service. The upstream MIT license file is included; kit code is authored by Agent Setup Kits, adapted from upstream examples.

Read the original license ↗

Related guides

Your privacy choices

Choose optional tools. Rejecting them keeps the setup library available. Advertising consent stays off.

Choices stay in this browser for 90 days. You can change them using Privacy settings. Privacy and cookie details