Image by Author
# Introduction
Tired of duct-taping scripts, tools, and prompts together? The Claude Agent SDK lets you turn your Claude Code “plan → build → run” workflow into real, programmable agents, so you can automate tasks, wire up tools, and ship command line interface (CLI) apps without tons of glue code. If you already like using Claude in the terminal, this software development kit (SDK) gives you the same vibe with proper structure, state, and extensibility.
In this tutorial, you will set up the Claude Agent SDK and build a small, multi-tool CLI that chains steps end-to-end (plan → act → verify). Along the way, you’ll see how to register tools, manage context, and orchestrate agent loops for local workflows like debugging, code generation, and deployment.
# What is the Claude Agent SDK?
Anthropic‘s Claude Sonnet 4.5 marks a significant advancement in capabilities, featuring a state-of-the-art coding model that excels in industry benchmarks for reasoning, mathematics, and long-context tasks. This release includes a Chrome extension, a memory tool, and document generation features. The standout component is the Claude Agent SDK, built on the foundation of Claude Code.
The Claude Agent SDK enables developers to create, extend, and customize applications powered by Claude. It allows integration with your local environment, granting Claude access to your tools and facilitating the orchestration of complex workflows, including coding, research, note-taking, and automation.
# Setting Up the Claude Agent SDK
Before building, make sure you’ve set up both Claude Code CLI and the Claude Agent SDK.
// 1. Prerequisites
- Python: version 3.10 or higher.
- Node.js: version 18+ for the CLI.
- Claude API Key or Anthropic account.
// 2. Install Claude Code CLI
We will install the Claude Code CLI on Windows by typing the following command in PowerShell:
irm https://claude.ai/install.ps1 | iex
Then add this path to your system environment:
Restart PowerShell and test:
For other platforms, consider using the npm package manager:
npm i -g @anthropic-ai/claude-code
After installation, type claude in your terminal to sign in.
// 3. Install the Claude Agent SDK (Python)
Install the Claude Agent Python SDK using the pip package manager.
pip install claude-agent-sdk
If you get a CLINotFoundError, ensure the Claude CLI is correctly installed and included in your PATH.
# Building a Multi-Tool App with the Claude Agent SDK
In this section, we will build the TrendSmith application, which tracks live market trends across various industries, including startups, AI, finance, and sustainability.
It combines Claude Sonnet 4.5, WebSearch, WebFetch, and local storage tools into a single multi-agent system.
Create the Python file trend_smith.py and add the following code to it:
// 1. Imports & Basic Settings
This loads Python libraries, the Claude Agent SDK types, a tiny help menu, the model name, and soft gray text styling for status lines.
import asyncio
import os
import re
import sys
import time
from datetime import datetime
from pathlib import Path
from claude_agent_sdk import (
AssistantMessage,
ClaudeAgentOptions,
ClaudeSDKClient,
ResultMessage,
TextBlock,
ToolResultBlock,
ToolUseBlock,
)
HELP = """Commands:
/trend Quick multi-source scan (auto-saves markdown)
/scan Short one-page scan
/help /exit Help / Quit
"""
MODEL = os.getenv("CLAUDE_MODEL", "sonnet") # e.g. "sonnet-4.5"
GRAY = "\033[90m"
RESET = "\033[0m"
// 2. System Prompt & Report Destination
This sets the “house rules” for answers (fast, compact, consistent sections) and chooses a reports/ folder next to your script for saved briefs.
SYS = """You are TrendSmith, a fast, concise trend researcher.
- Finish quickly (~20 s).
- For /trend: ≤1 WebSearch + ≤2 WebFetch from distinct domains.
- For /scan: ≤1 WebFetch only.
Return for /trend:
TL;DR (1 line)
3-5 Signals (short bullets)
Key Players, Risks, 30/90-day Watchlist
Sources (markdown: **Title** -- URL)
Return for /scan: 5 bullets + TL;DR + Sources.
After finishing /trend, the client will auto-save your full brief.
"""
BASE = Path(__file__).parent
REPORTS = BASE / "reports"
// 3. Saving Files Safely
These helpers make filenames safe, create folders if needed, and always try a home-folder fallback so your report still gets saved.
def _ts():
return datetime.now().strftime("%Y%m%d_%H%M")
def _sanitize(s: str):
return re.sub(r"[^\w\-.]+", "_", s).strip("_") or "untitled"
def _ensure_dir(p: Path):
try:
p.mkdir(parents=True, exist_ok=True)
except Exception:
pass
def _safe_write(path: Path, text: str) -> Path:
"""Write text to path; if directory/permission fails, fall back to ~/TrendSmith/reports."""
try:
_ensure_dir(path.parent)
path.write_text(text, encoding="utf-8")
return path
except Exception:
home_reports = Path.home() / "TrendSmith"https://www.kdnuggets.com/"reports"
_ensure_dir(home_reports)
fb = home_reports / path.name
fb.write_text(text, encoding="utf-8")
return fb
def save_report(topic: str, text: str) -> Path:
filename = f"{_sanitize(topic)}_{_ts()}.md"
target = REPORTS / filename
return _safe_write(target, text.strip() + "\n")
// 4. Tracking Each Run
This keeps what you need for one request: streamed text, model, tool counts, token usage, and timing, then resets cleanly before the next request.
class State:
def __init__(self):
self.brief = ""
self.model_raw = None
self.usage = {}
self.cost = None
self.last_cmd = None
self.last_topic = None
self.tools = {}
self.t0 = 0.0
self.t1 = 0.0
def reset(self):
self.brief = ""
self.model_raw = None
self.usage = {}
self.cost = None
self.tools = {}
self.t0 = time.perf_counter()
self.t1 = 0.0
def friendly_model(name: str | None) -> str:
if not name:
return MODEL
n = (name or "").lower()
if "sonnet-4-5" in n or "sonnet_4_5" in n:
return "Claude 4.5 Sonnet"
if "sonnet" in n:
return "Claude Sonnet"
if "haiku" in n:
return "Claude Haiku"
if "opus" in n:
return "Claude Opus"
return name or "Unknown"
// 5. Short Run Summary
This prints a neat gray box to show the model, tokens, tool usage, and duration, without mixing into your streamed content.
def usage_footer(st: State, opts_model: str):
st.t1 = st.t1 or time.perf_counter()
dur = st.t1 - st.t0
usage = st.usage or {}
it = usage.get("input_tokens")
ot = usage.get("output_tokens")
total = usage.get("total_tokens")
if total is None and (it is not None or ot is not None):
total = (it or 0) + (ot or 0)
tools_used = ", ".join(f"{k}×{v}" for k, v in st.tools.items()) or "--"
model_label = friendly_model(st.model_raw or opts_model)
box = [
"┌─ Run Summary ─────────────────────────────────────────────",
f"│ Model: {model_label}",
f"│ Tokens: {total if total is not None else '?'}"
+ (f" (in={it if it is not None else '?'} | out={ot if ot is not None else '?'})"
if (it is not None or ot is not None) else ""),
f"│ Tools: {tools_used}",
f"│ Duration: {dur:.1f}s",
"└───────────────────────────────────────────────────────────",
]
print(GRAY + "\n".join(box) + RESET, file=sys.stderr)
// 6. The Main Loop (All-in-One)
This starts the app, reads your command, asks the AI, streams the answer, saves /trend reports, and prints the summary.
async def main():
"""Setup → REPL → parse → query/stream → auto-save → summary."""
st = State()
_ensure_dir(REPORTS)
opts = ClaudeAgentOptions(
model=MODEL,
system_prompt=SYS,
allowed_tools=["WebFetch", "WebSearch"],
)
print("📈 TrendSmith \n\n" + HELP)
async with ClaudeSDKClient(options=opts) as client:
while True:
# Read input
try:
user = input("\nYou: ").strip()
except (EOFError, KeyboardInterrupt):
print("\nBye!")
break
if not user:
continue
low = user.lower()
# Basic commands
if low in {"/exit", "exit", "quit"}:
print("Bye!")
break
if low in {"/help", "help"}:
print(HELP)
continue
# Parse into a prompt
if low.startswith("/trend "):
topic = user.split(" ", 1)[1].strip().strip('"')
if not topic:
print('e.g. /trend "AI chip startups"')
continue
st.last_cmd, st.last_topic = "trend", topic
prompt = f"Run a fast trend scan for '{topic}' following the output spec."
elif low.startswith("/scan "):
q = user.split(" ", 1)[1].strip()
if not q:
print('e.g. /scan "AI hardware news"')
continue
st.last_cmd, st.last_topic = "scan", q
prompt = f"Quick scan for '{q}' in under 10s (≤1 WebFetch). Return 5 bullets + TL;DR + sources."
else:
st.last_cmd, st.last_topic = "free", None
prompt = user
# Execute request and stream results
st.reset()
print(f"{GRAY}▶ Working...{RESET}")
try:
await client.query(prompt)
except Exception as e:
print(f"{GRAY}❌ Query error: {e}{RESET}")
continue
try:
async for m in client.receive_response():
if isinstance(m, AssistantMessage):
st.model_raw = st.model_raw or m.model
for b in m.content:
if isinstance(b, TextBlock):
st.brief += b.text or ""
print(b.text or "", end="")
elif isinstance(b, ToolUseBlock):
name = b.name or "Tool"
st.tools[name] = st.tools.get(name, 0) + 1
print(f"{GRAY}\n🛠 Tool: {name}{RESET}")
elif isinstance(b, ToolResultBlock):
pass # quiet tool payloads
elif isinstance(m, ResultMessage):
st.usage = m.usage or {}
st.cost = m.total_cost_usd
except Exception as e:
print(f"{GRAY}\n⚠ Stream error: {e}{RESET}")
# Auto-save trend briefs and show the summary
if st.last_cmd == "trend" and st.brief.strip():
try:
saved_path = save_report(st.last_topic or "trend", st.brief)
print(f"\n{GRAY}✅ Auto-saved → {saved_path}{RESET}")
except Exception as e:
print(f"{GRAY}⚠ Save error: {e}{RESET}")
st.t1 = time.perf_counter()
usage_footer(st, opts.model)
if __name__ == "__main__":
asyncio.run(main())
# Testing the TrendSmith Application
We will now test the app by running the Python file. Here is a quick recap on how to use the CLI application:
- /trend “<topic>” → brief multi-source scan, auto-saved to
reports/<topic>_<ts>.md. - /scan “<query>” → one-page quick scan (≤1 WebFetch), prints only.
- /help → shows commands.
- /exit → quits.

Image by Author
We have used the /trend option to search for AI chip startups.
/trend "AI chip startups"
As a result, the app has used various search and web scraping tools to gather information from different websites.

Image by Author
Ultimately, it has provided the full response, auto-saved the report in the markdown file, and generated the usage summary. It cost us $0.136.

Image by Author
Here is a preview of the saved Markdown report on the AI Chips Startups.

Image by Author
We will now test the scanning option and generate a summary about the topic using a web search.
It utilizes a simple web search and fetch tool to generate a short summary on the topic.

Image by Author
# Final Thoughts
This app ran smoothly, and working with the Claude Agent SDK was genuinely fun. If you are already on the Claude Code plan, I highly recommend trying it to transform your day-to-day terminal workflow into reliable, repeatable agentic CLIs.
Use it to:
- Automate common dev tasks (debug, test, deploy).
- Script simple analytics or ops routines.
- Package your flow into a reusable, shareable tool.
The SDK is a good fit for professionals who want stability, reproducibility, and low glue-code overhead. And yes, you can even ask Claude Code to help you build the agentic application itself with the SDK.
Abid Ali Awan (@1abidaliawan) is a certified data scientist professional who loves building machine learning models. Currently, he is focusing on content creation and writing technical blogs on machine learning and data science technologies. Abid holds a Master’s degree in technology management and a bachelor’s degree in telecommunication engineering. His vision is to build an AI product using a graph neural network for students struggling with mental illness.

