little cups of claude

tips and techniques for Claude and Claude Code

#22: Agent SDK Basics 🛠️

Today we'll begin looking at the Claude Agent SDK, which lets us run the same agent that powers Claude Code from inside our own TypeScript or Python code.

It gives us Claude Code's built-in tools, its agent loop, and its context management as a library. We hand it a prompt, and it reads files, runs commands, and edits code on its own while we watch the messages stream by. Let's get started.

Installing It

There's a package for each language:

# TypeScript
bun add @anthropic-ai/claude-agent-sdk

# Python
uv add claude-agent-sdk

Both packages bundle a native Claude Code binary, so most installs don't need a separate Claude Code install. Authentication comes from an API key in the environment:

export ANTHROPIC_API_KEY=your-api-key

The SDK reads it from the process environment. It doesn't load .env files on its own, so if we keep the key there, we load it ourselves first.

Our First Agent

Everything starts with query(). It returns an async iterator that yields messages as Claude works:

import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({
  prompt: "Review utils.py for bugs that would cause crashes. Fix them.",
  options: {
    allowedTools: ["Read", "Edit", "Glob"],
    permissionMode: "acceptEdits",
  },
})) {
  if (message.type === "result") console.log(`Done: ${message.subtype}`);
}

Here's the same agent in Python:

import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage

async def main():
    async for message in query(
        prompt="Review utils.py for bugs that would cause crashes. Fix them.",
        options=ClaudeAgentOptions(
            allowed_tools=["Read", "Edit", "Glob"],
            permission_mode="acceptEdits",
        ),
    ):
        if isinstance(message, ResultMessage):
            print(f"Done: {message.subtype}")

asyncio.run(main())

Claude reads the file, spots the edge cases, and edits in the fixes. We never wrote a single tool. Neat!

Watching It Think

The loop yields more than the final result. Assistant messages carry Claude's text and the tools it's calling:

if (message.type === "assistant" && message.message?.content) {
  for (const block of message.message.content) {
    if ("text" in block) console.log(block.text);
    else if ("name" in block) console.log(`Tool: ${block.name}`);
  }
}

Without some filtering like this, we'd see every raw message, including system initialization. That's handy for debugging and noisy otherwise.

Choosing The Tools

allowedTools pre-approves tools, so the list roughly sets how much the agent can do on its own:

  • Read, Glob, Grep for read-only analysis
  • Read, Edit, Glob to analyze and change code
  • add Bash for full automation, like writing tests and running them

A custom system prompt shapes the agent's personality:

options = ClaudeAgentOptions(
    allowed_tools=["Read", "Edit", "Glob", "Bash"],
    permission_mode="acceptEdits",
    system_prompt="You are Hal, a careful senior Python developer.",
)

What Comes Along

The SDK also loads skills, commands, and memory from our project's .claude/ folder and ~/.claude/, the same as Claude Code. On top of that, there's support for hooks, subagents, MCP servers, permissions, and sessions we can resume or fork later.

Watch Out

Agents built on the SDK should authenticate with an API key (or a cloud provider like Amazon Bedrock). Unless Anthropic has approved it, third-party products can't offer claude.ai login or its rate limits.

For languages other than TypeScript and Python, we can run the CLI as a subprocess with claude -p and --output-format json instead.

More info about the Agent SDK can be found at the Claude Code docs.

Share

Share on Threads