Agent SDK: Bringing Claude Code's Capabilities Into Your Own Applications
📚 Series Navigation: The previous article 44 GitHub Actions taught you how to integrate Claude with CI, letting it automate tasks in PRs and pipelines. This article goes a step further—moving beyond pipelines to treat the entire set of Claude Code capabilities as a library, embedding it directly into your own applications and services. The Agent SDK is the official channel to programmatically initialize a Claude agent.
Let's talk about something that transitions you from a "tool user" to a "tool maker."
Throughout the first 40+ chapters, you have been a user of Claude Code—running claude in the terminal, chatting with it, and watching it modify code. This is its "front end." But there is also a "back end" you likely haven't touched: its core—the agent loop that reads files, executes commands, and thinks before acting—can be programmatically driven by your own code.
This is the Agent SDK (an Agent Software Development Kit, a set of libraries that lets you programmatically call the Claude Code core in Python or TypeScript). Simply put, it transforms Claude Code from a CLI utility into a function within your code. With a few lines of code, you can run an AI agent inside your own application that autonomously reads code, modifies files, and performs web searches.
The value of this SDK becomes clear when you want to build something like an "automated PR review bot." If you route through raw APIs, even a simple task like "having the model read a file" requires writing boilerplate—stuffing file contents into requests, handling the model's request to "read file X," executing the file read, and returning results... back and forth. With the Agent SDK, all that boilerplate vanishes; three lines of code let Claude read files and patch bugs on its own. Today, we'll pave this path for you.
After reading this article, you will get:
- A brief explanation of what the Agent SDK is and which parts of Claude Code it exposes for you
- How it differs from the CLI you run daily—same core, two different entry points
- Its fundamental difference from the "raw API" (without understanding this, you might end up reinventing the wheel)
- How to choose between TypeScript and Python, which packages to install, and what prerequisites are required
- A hands-on minimal agent implementation with expected output: letting it autonomously detect and patch a bug
- A clear perspective on who this tool is suited for and whether you should learn it now
01 Understand First: What the Agent SDK Exposes from Claude Code
Conclusion first: the Agent SDK packages the Claude Code core into a library, allowing you to use code (Python or TypeScript) to initialize a Claude agent identical to the CLI.
Recall the "agent loop" from Chapter 03—Claude's workflow operates as a cycle of "Think → Act → Observe": thinking about the next step, calling a tool to act (reading files, running commands), and observing the result to determine the subsequent action. When using claude in the terminal, you benefit from this loop coupled with built-in tools like Read, Edit, and Bash (detailed in Chapter 03).
Key realization: this loop and toolset are not exclusive to the CLI; they can be programmatically driven by your own code. The official documentation states this clearly:
The Agent SDK provides you with the same tools, agent loop, and context management as Claude Code, programmable in Python and TypeScript.
Analogy: Bringing a café's automatic coffee machine into your own kitchen. You buy coffee at the local shop daily (using the CLI), which is convenient. But if you want to serve the same coffee in your own breakfast shop, you can't tell customers to visit the café. Instead, you install the same machine in your shop: retaining the same bean-grinding, extraction, and milk-frothing core, but embedded in your workflow. When to brew, who to serve, and what breakfast set to pair it with are controlled entirely by your code. The Agent SDK is that portable machine—same core, running inside your own application.
What does it expose? The official documentation clarifies that the key components powering Claude Code's capabilities are all included in the SDK:
- Built-in Tools: Read, Write, Edit, Bash, Glob, Grep, and WebSearch work out of the box; you do not need to implement tool execution logic yourself
- Agent Loop: The orchestrating Think-Act-Observe cycle is handled automatically by the SDK
- Context Management: It tracks read files and dialogue histories for you
- Advanced Integrations: Hooks, subagents, MCP, permission controls, and session resumption—all CLI extension points are programmatically accessible in the SDK
In practice, when would you need it? Here are three common scenarios:
- "I want to build a Slack bot that reads error logs sent by developers, locates the issue in the codebase, and proposes a fix"—this requires embedding the agent within your Slack integration
- "I want to run a scheduled cron job that scans the codebase for TODOs every night and compiles them into a report"—requiring programmatically starting the agent and collecting its outputs
- "I want to add an 'AI assistant' feature to my application where Claude directly edits the user's project files"—which necessitates the SDK
These three tasks are awkward to handle via CLI—as the CLI is designed for interactive use by a human sitting at a terminal. These use cases require programmatic triggers and automated result retrieval, which is the primary domain of the SDK.
💡 Summary in one sentence: The Agent SDK packages Claude Code's core (tools + agent loop + context management) into a library, letting you programmatically initialize a Claude agent identical to the CLI and integrate it into your own applications and services.
02 How It Differs from the CLI: Same Core, Two Entry Points
This is a common point of confusion, so let's clarify: the Agent SDK and the CLI you run daily share the exact same underlying core. The only difference is the entry point—one is driven by manual keystrokes, the other by code.
The official documentation sums it up perfectly:
Same power, different interface.
Analogy: The same coffee machine manually operated at a counter vs. integrated into a vending machine. It is the same coffee machine (same core). Positioned behind a counter, a barista brews cups manually for customers, asking, "Would you like sugar?"—this is the CLI, suitable for live, interactive adjustments with a human present. Putting that same machine inside a vending machine—accepting coins, pressing buttons, and dispensing coffee automatically without supervision—is the SDK, perfect for programmatic triggers and unattended runs. The machinery is identical; only who presses the start button changes.
When to use which? The official documentation provides a clear comparison table:
| Use Case | Best Choice |
|---|---|
| Interactive development (iterating while sitting at terminal) | CLI |
| One-off tasks (quick manual command execution) | CLI |
| CI/CD pipelines (automated CI runs) | SDK |
| Custom applications (integrating into your own product) | SDK |
| Production automation (unattended, scheduled tasks) | SDK |
The trick to reading this table: ask yourself, "Am I sitting here watching this run, or is it triggered programmatically?" If a human is supervising and needs to intervene—use the CLI; if it starts automatically and returns results programmatically—use the SDK.
The official guide adds a note, addressing any concern that learning one makes the other redundant:
Many teams use both: the CLI for day-to-day development, and the SDK for production. Workflows translate directly between them.
This is highly practical. Many developers adopt this pattern: coding during the day with claude running in the terminal (CLI); once a workflow is repeated manually five times, they script it with the SDK to automate it. The concepts of prompt design, tool delegation, and permission configuration are identical—every bit of experience you gain with the CLI carries over to the SDK.
So do not view them as opposing tools. Think of it this way: the CLI is the entry point for human interaction, while the SDK is the entry point for programmatic automation—both backed by the same Claude Code core. Here is the relationship mapped out:

The meaning of this diagram: there are two different entry points on top—human keystrokes for the CLI, programmatic calls for the SDK; but both route to the same Claude Code core, executing the same workflows under the hood. This is why it is called a "same core, two entry points" model.
💡 Summary in one sentence: The CLI and the SDK share the same core and offer two entry points—interactive manual runs use the CLI, while unattended automated workflows use the SDK; they are frequently used together, and CLI experience translates directly to the SDK.
03 Clear the Confusion: The Agent SDK Is Not the "Raw API"
This is the most critical distinction in this article. Without understanding this, you might think you are using the SDK when you are actually reinventing wheels that Claude has already built for you.
You've probably heard of the "Anthropic API" or the "Client SDK" (the client libraries used to connect directly to the model APIs). While sharing similar names and both driving Claude, they perform entirely different tasks. Here is the distinction in one sentence:
The Client SDK provides a "conversational model" where you write the tool-execution loop; the Agent SDK provides an "active agent" where it runs the tool-execution loop for you.
The official documentation explains this distinction clearly:
The Anthropic Client SDK provides you direct API access: you send prompts and implement tool execution yourself. The Agent SDK provides you with Claude with built-in tool execution.
Analogy: Buying raw beans to roast and brew yourself vs. buying an automatic espresso machine. The Client SDK is like buying raw coffee beans—they are high-quality beans (the model is powerful), but to enjoy a cup, roasting, grinding, boiling water, extracting, and frothing milk must all be handled by you manually. The Agent SDK gives you the automatic machine—you press "Americano," it handles grinding and extraction internally, and dispenses a ready cup. The underlying model uses the same beans, but the execution steps are automated.
In code, the difference is stark. Here is the comparison (Python) provided in the official docs; observe the boilerplate difference:
# Client SDK: You must implement the tool-execution loop yourself
response = client.messages.create(...)
while response.stop_reason == "tool_use":
result = your_tool_executor(response.tool_use) # You must implement tool execution yourself
response = client.messages.create(tool_result=result, **params) # feed the results back
# Agent SDK: Claude executes the tools itself
async for message in query(prompt="Fix the bug in auth.py"):
print(message)Notice the boilerplate? The while loop in the Client SDK—"model requests tool -> you execute it -> send results back -> model continues thinking"—is the tedious logic mentioned earlier. The model only "expresses" its desire to read auth.py, but the actual reading action must be written by you, and the contents manually returned. You have to implement this entire tool-execution loop from scratch.
The Agent SDK encapsulates this entire while loop inside the query() function. You simply instruct it to "fix the bug in auth.py," and it determines which files to read, reads them, edits them, and verifies changes autonomously, while you just consume the message stream.
This is the source of the pitfall mentioned at the beginning. When building a PR review bot, it is easy to get stuck on this while loop for days—intercepting the model's tool_use, implementing "read file" or "git diff" manually, and returning results. The logic is winded and easily misses edge cases. Once you realize the Agent SDK handles all of this, hundreds of lines of glue code can be deleted instantly, leaving only a simple query() call. Remember this comparison:
| Client SDK (Raw API) | Agent SDK | |---------|----------------------|-----------| | What you get | Conversational model | Active agent | | Who executes tools | You write code to execute them | Claude executes them automatically | | The while tool-execution loop | You implement from scratch | SDK handles it for you | | Built-in tools (file IO, commands) | None, implement yourself | Out of the box | | Best suited for | Extreme customization without filesystem access | An active agent that directly modifies files and runs tools |
Rule of thumb: If you need "an agent that directly reads files, runs commands, and modifies code"—choose the Agent SDK and avoid the while loop. Only consider the Client SDK if you do not require filesystem operations and need raw chat with fine-grained control over every API exchange.
💡 Summary in one sentence: The Agent SDK is not the raw API—the raw API (Client SDK) gives you a model where you write the tool-execution loop; the Agent SDK gives you an agent where it executes tools automatically; if you want a Claude that modifies files and runs tools, use the Agent SDK.
04 Two Languages: TypeScript and Python, Installation and Prerequisites
The Agent SDK officially supports two runtimes, pick the one you prefer: TypeScript or Python. Their features are fully aligned, and the official docs provide code examples for both. Do not worry about "which has more features"—choose the language your team and active projects already use.
How to choose: pick the SDK matching your application stack. If your backend uses Node or frontend build tools—choose TypeScript; if you handle data, scripting, or AI engineering—choose Python. There is no right or wrong; follow your project.
What Package to Install and Prerequisites
The installation commands and prerequisites differ, summarized from the official docs:
| TypeScript | Python | |
|---|---|---|
| Installation Command | npm install @anthropic-ai/claude-agent-sdk | pip install claude-agent-sdk |
| Environment Prerequisite | Node.js 18+ | Python 3.10+ |
| Need to install Claude Code separately? | No (SDK bundles a local binary) | See notes below |
A convenient detail on the TypeScript side is explicitly noted in the documentation:
The TypeScript SDK bundles a local Claude Code binary for your platform as an optional dependency, so you do not need to install Claude Code separately.
This means the TS SDK works immediately upon installation without requiring you to install Claude Code beforehand.
The Python setup has a version requirement highlighted by the docs—it requires Python 3.10 or higher. If pip throws No matching distribution found for claude-agent-sdk, your Python version is likely too old. Verify it first:
python3 --version # macOS / Linux
py --version # WindowsUpgrade if it is below 3.10. Installing on older systems easily trips here—where the default python is 3.9, triggering the No matching distribution error. Upgrading to 3.11 fixes it instantly.
Storing the API Key
Regardless of runtime, you must configure an Anthropic API key (the credential used to call the models). The official documentation recommends creating a .env file in your project directory:
ANTHROPIC_API_KEY=your-api-keyObtain your key from the Claude Console (platform.claude.com); never commit it to Git—ensure it is added to
.gitignore. The details of API key setups were covered in Chapter 04.
Here is an important billing note highlighted in the official documentation (affecting your balance):
Starting June 15, 2026, Agent SDK and
claude -pusage on subscription plans will draw from a new monthly Agent SDK credit allotment, separate from your interactive usage limits.
In short: the "interactive quota" in your subscription (used for terminal chats) and the "Agent SDK quota" are billed separately. Do not assume that having a subscription allows unlimited SDK runs; SDK usage tracks its own allotment. Refer to the official guide for details.
💡 Summary in one sentence: The two SDKs are fully aligned—choose based on language: TS uses
npm install @anthropic-ai/claude-agent-sdk(Node 18+, bundles binary), Python usespip install claude-agent-sdk(requires 3.10+); both requireANTHROPIC_API_KEYand track SDK usage separately from interactive limits.
05 Understanding the Code: query() Is the Entry Point
Let's look at code to build a concrete understanding. The primary entry point of the Agent SDK is a single function: query(). Understand this, and you unlock the SDK.
Let's break down the minimal official example. First, Python:
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions
async def main():
async for message in query(
prompt="Find and fix the bug in auth.py",
options=ClaudeAgentOptions(allowed_tools=["Read", "Edit", "Bash"]),
):
print(message) # Claude reads file, locates bug, and fixes it
asyncio.run(main())TypeScript alternative:
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "Find and fix the bug in auth.ts",
options: { allowedTools: ["Read", "Edit", "Bash"] }
})) {
console.log(message); // Claude reads file, locates bug, and fixes it
}That's it. It breaks down into three key parameters (summarized from official definitions):
① query()—The entry point of the agent loop. It returns an "async iterator" (an object that streams messages sequentially), allowing you to use async for (or for await in TS) to stream every message emitted during Claude's execution: its thinking process, tool calls, tool outputs, and the final result.
② prompt—What you want it to do. Identical to instructions typed in the CLI. Here, it is "Find and fix the bug in auth.py." Claude determines which tools to use.
③ options—Configuration for the agent. The most common option is allowed_tools (allowedTools in TS), pre-approving which tools the agent can run. Passing Read, Edit, and Bash permits it to read files, modify files, and run terminal commands.
Note that the async for / for await loop continues running until Claude completes the task or errors out. It yields a message per iteration, while the SDK manages tool execution, context, and retries under the hood. From the docs:
The SDK handles the orchestration (tool execution, context management, retries) so you can just consume the stream.
This is the main benefit over raw APIs—notice that there is no while loop handling tools in this code; it is entirely encapsulated inside query().
Let's highlight another key aspect: delegating tools equals delegating permissions (aligning with Chapter 20). What you declare in allowed_tools dictates what the agent can modify. The official documentation maps these options:
| Granted Tools | What the agent can do |
|---|---|
Read, Glob, Grep | Read-only analysis (inspecting without modification) |
Read, Edit, Glob | Analysis + code edits |
Read, Edit, Bash, Glob, Grep | Full automation (reading, editing, and running commands) |
Want to build a "read-only, secure agent"? Grant only Read, Glob, and Grep. This is more robust than temporary CLI approvals—since the agent lacks Edit entirely, it has no way to modify files.
A tip for Python users: in addition to stateless
query()calls, the Python SDK providesClaudeSDKClient—which wrapsquery()to automatically share a session across calls without manually trackingresumetokens. This is ideal for chats or REPLs; statelessquery()is sufficient for one-off tasks.
💡 Summary in one sentence: The SDK's entry point is
query()—accepting apromptandoptions(whereallowed_toolsrestricts accessible actions) and returning a message stream consumed viaasync for; thewhiletool-execution loop required by raw APIs is completely handled byquery().
06 Practice: Build an Agent that Autonomously Patches a Bug in 5 Minutes
Let's walk through the classic official introductory agent—writing code with intentional bugs, and having the agent detect and fix them. This runs independently of active projects. We will use Python (TypeScript follows the same logic, with commands marked at each step).
Prerequisites: Node.js 18+ or Python 3.10+, and an Anthropic API key. Installing the SDK and running model requests require active internet access.
Step 1: Create a directory and navigate into it
mkdir my-agent
cd my-agentStep 2: Install the SDK and configure the API key
Python (using built-in venv):
python3 -m venv .venv
source .venv/bin/activate
pip install claude-agent-sdkTypeScript alternative:
npm install @anthropic-ai/claude-agent-sdk.
Create a .env file in the my-agent directory containing your key:
ANTHROPIC_API_KEY=your-api-keyExpected: pip install outputs Successfully installed claude-agent-sdk-.... Seeing this means the SDK is installed. If it errors with No matching distribution found, verify that your Python version is 3.10+ (Section 04).
Step 3: Create a file containing bugs
Create utils.py in the directory, pasting this snippet (the official example containing two potential crash bugs):
def calculate_average(numbers):
total = 0
for num in numbers:
total += num
return total / len(numbers)
def get_user_name(user):
return user["name"].upper()The bugs are: calling calculate_average([]) with an empty list triggers a division-by-zero crash, and calling get_user_name(None) throws a TypeError.
Step 4: Implement the agent
Create agent.py, pasting the quickstart code (comments translated):
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ResultMessage
async def main():
# Agent loop: Claude streams messages during execution
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"], # Pre-approve these tools
permission_mode="acceptEdits", # Auto-approve file edits
),
):
# Print only user-friendly blocks
if isinstance(message, AssistantMessage):
for block in message.content:
if hasattr(block, "text"):
print(block.text) # Claude's thought process
elif hasattr(block, "name"):
print(f"Tool: {block.name}") # The tool being executed
elif isinstance(message, ResultMessage):
print(f"Done: {message.subtype}") # Final result
asyncio.run(main())We added the option permission_mode="acceptEdits"—auto-approving file edits so the agent modifies files without pausing for manual consent (appropriate for trusted scratch scripts). The official SDK offers several permission modes:
| Mode | Behavior | Use Case |
|---|---|---|
acceptEdits | Auto-approves file edits and common filesystem commands; other actions prompt you | Trusted developer workflows (used in this example) |
bypassPermissions | Executes all tools without prompting | Sandboxed CI or fully trusted environments |
default | Requires you to supply a callback handling approvals | Custom approval flows |
dontAsk | Rejects unapproved tools immediately without prompting | Locked CI, headless scripts |
plan | Allows read-only tools; Claude analyzes without modifying files | Pre-execution planning before approval |
Step 5: Run the agent
python agent.pyTypeScript alternative:
npx tsx agent.ts.
Expected: The terminal streams the agent's workflow—beginning with its thoughts (e.g., stating it will inspect utils.py), followed by Tool: Read and Tool: Edit lines, ending with Done: success. Seeing Done: success means execution completed.
Step 6: Verify the modifications
Open utils.py. Expected: You will see that the agent inserted defensive checks—e.g., adding a check in calculate_average returning 0 (or throwing an error) if the list is empty, and handling None or missing fields in get_user_name.
This highlights the utility of the Agent SDK, as noted by the official docs:
This is what makes the Agent SDK different: Claude executes tools directly, rather than asking you to implement them.
Throughout this workflow, the agent autonomously reads utils.py to understand context -> detects crashes -> edits the file adding check bounds. You wrote zero logic; it handled everything.
Running this example walks you through the flow: "install SDK -> set API key -> call query() -> configure tools/permissions -> consume stream -> verify output." This forms the skeleton of any SDK agent you write—adjusting the prompt, tool configurations, permissions, or MCP settings as needed.
Side note: the official docs suggest trying different prompts to observe how the same script performs various tasks:
"Add type hints to all functions in utils.py"(adding type hints), or"Write unit tests for utils.py, run them, and fix any failures"(writing and executing test suites—which requires addingBashtoallowed_tools).
💡 Summary in one sentence: Running the introductory agent takes six steps—create directory, install SDK/configure key, create buggy file, write
query()script, runpython agent.py, and verify files are patched; writing the code once provides more clarity than reading parameters.
07 Who Is This For: Should You Learn It Now?
A candid note: the Agent SDK is not a tool everyone must learn immediately, but if you want to automate workflows using Claude, you will eventually need it. Here is how to determine if it is for you.
First, when you do not need it. If you only want Claude to write code, patch bugs, and run commands in your terminal—stick to the CLI and avoid the SDK. The SDK is for "writing programs to drive Claude"; if you have no programming integration needs, it adds unnecessary complexity. Rushing to use the SDK right after learning the CLI often leads to getting stuck on async iterators, distracting from actual development.
When should you adopt it? If you match any of these three signals:
| Signal (Your Goal) | Should you use the SDK? |
|---|---|
| "I just want it to write code in my terminal" | ❌ Use the CLI, ignore the SDK |
| "I've repeated the same process manually N times and want to automate it" | ✅ Yes, script it using the SDK |
| "I want to add active AI capabilities that edit files to my application" | ✅ Yes, this is the SDK's primary use case |
| "I want to build a bot or scheduled cron task running the agent" | ✅ Yes, handling this via CLI is awkward |
The official documentation outlines a practical path forward:
A common path is to prototype locally with the Agent SDK, and then migrate to Managed Agents for production.
Here, a new concept appears—Managed Agents. Simply put, it is a REST API where Anthropic manages the hosting of the agent and execution sandbox. Your application sends events and receives results without managing process environments or session storage. The Agent SDK, conversely, runs the agent loop inside your own process. The official comparison:
| Agent SDK | Managed Agents | |
|---|---|---|
| Execution Environment | Your own process and infrastructure | Anthropic-managed infrastructure |
| Interface | Python / TypeScript libraries | REST API |
| Accessed Files | Real files on your local machine | A hosted sandbox per session |
| Best Suited For | Local prototyping and agents that operate on your filesystem directly | Production use cases where you want to avoid hosting sandboxes or sessions |
For most developers, the path is clear: start by prototyping locally using the Agent SDK (as shown in Section 06), and migrate to Managed Agents when ready to scale for production or when you want to delegate sandbox management. Prototyping forms the starting point, while managed services represent the production grade—for now, focus on mastering the Agent SDK.
A final thought: automating repetitive tasks—such as scanning dependencies weekly and outputting reports—via SDK scripts is highly satisfying. Seeing a report compiled autonomously by a scheduled task waiting for you in the morning provides a sense of building a self-operating tool that the CLI cannot match. If you find yourself tired of manual repetitions, it's time to explore the SDK.
💡 Summary in one sentence: If you only want Claude in the terminal—stick to the CLI; if you want to automate processes or integrate file-modifying AI features into apps—use the SDK; the path is "prototype locally with the Agent SDK, scale via Managed Agents," so master the SDK first.
08 Summary
This article lifted the hood on Claude Code—showing that its core can be imported as a library inside your own applications, known as the Agent SDK.
Let's review the key points:
| What you want to understand | Answer | Key Point |
|---|---|---|
| What the Agent SDK is | Claude Code core packaged as a library | Same tools + loop + context; programmatically driven |
| Relationship to the CLI | Same core, two entry points | CLI is for human keystrokes, SDK is for code; concepts carry over |
| Difference from raw APIs | Who runs the tool loop | Raw API requires you to write a while loop; the SDK runs it internally |
| Which runtime to choose | Choose based on your stack | TS (Node 18+) or Python (3.10+); features are aligned |
| Entry Point | query() | Accepts prompt + options, returns a message stream |
| Should you learn it? | Depends on automation or integration needs | Ignore if you only use the CLI; adopt if scripting or integrating |
You should now be able to: explain what the Agent SDK exposes, clarify that CLI and SDK are "same core, two entry points," distinguish it from raw APIs, choose between TS and Python runtimes, understand query() call patterns, and run the bug-patching agent test. More importantly, you know whether you should adopt it now—which is more valuable than rushing to write code.
At this point, your understanding of Claude Code shifts from a CLI utility to a programmable, file-modifying agent toolkit. It is no longer just a tool you use, but a component you can build with.
The next chapter 46 "Development Configurations"—you learned how to write agents with the SDK, but practical development requires more than query(): managing API keys securely, separating environments (dev/prod), and setting environment variables for third-party model providers. We will clarify these bootstrap prerequisites in the next chapter. Think about it: a script that runs locally but fails to connect on a server is usually due to configuration issues—we'll help you prevent these pitfalls.