
Image by author
, Introduction
Are you tired of duct-taping scripts, tools, and prompts together? Cloud Agent SDK lets you turn your cloud code Turn “Plan → Build → Run” workflows into real, programmable agents, so you can automate tasks, wire up tools, and ship command line interface (CLI) apps without lots of glue code. If you already like to use cloud In Terminal, this Software Development Kit (SDK) gives you the same vibe with proper structure, state and extensibility.
In this tutorial, you will install the Cloud Agent SDK and create a small, multi-tool CLI that chains steps from start to finish (Plan → Task → Verify). Plus, you’ll see how to register tools, manage contexts, and organize agent loops for local workflows like debugging, code generation, and deployment.
, What is Cloud Agent SDK?
anthropic‘S cloud sonnet 4.5 Marks a significant advancement in capabilities, including a state-of-the-art coding model that excels in industry benchmarks for logic, mathematics, and long-context tasks. This release includes a Chrome extension, a memory tool, and document creation features. is an extraordinary ingredient Cloud Agent SDKis built on the foundation of cloud code,
The Cloud Agent SDK enables developers to create, extend, and customize applications powered by the cloud. It allows integration with your local environment, gives the cloud access to your tools and facilitates the orchestration of complex workflows including coding, research, note taking and automation.
, Installation of Cloud Agent SDK
Before building, make sure you have set up both cloud code cli and this Cloud Agent SDK,
, 1. Prerequisites
- Python, Version 3.10 or higher.
- node.js, For CLI version 18+.
- cloud api key Or anthropological account.
, 2. Install Cloud Code CLI
We will install Cloud 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 To sign in to your terminal.
, 3. Install Cloud Agent SDK (Python)
Install the Cloud Agent Python SDK using the Pip package manager.
pip install claude-agent-sdk
If you have a CLINotFoundErrorMake sure the Cloud CLI is installed correctly and included in your PATH.
, Building a Multi-Tool App with the Cloud Agent SDK
In this section, we will build trendsmith The application, which tracks live market trends across various industries including startups, AI, finance, and sustainability.
it combines cloud sonnet 4.5, web search, webfetchAnd local storage Tools in a single multi-agent system.
create python file trend_smith.py And add the following code to it:
, 1. Import and basic settings
It loads Python libraries, the Cloud Agent SDK type, a small help menu, model names, and soft gray text styles 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 = " 33(90m"
RESET = " 33(0m"
, 2. System Prompt and Report Destination
It sets “house rules” for answers (fast, concise, coherent sections) and chooses a reports/ Folder next to your script for saved short descriptions.
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 securely
These helpers make safe file names, create folders if necessary, and always try a home-folder fallback so your reports can still be 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
It keeps what you need for one request: streamed text, model, tool count, token usage and time, then cleanly resets 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 Term Summary
It prints a clean gray box to show model, token, tool usage, and duration without blending 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. Main Loop (All-in-One)
It starts the app, reads your command, asks AI, streams the answer, saves /trend Prints reports, and summaries.
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 nn" + 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 app
Now we will test the app by running the Python file. Here’s a quick recap on how to use the CLI application:
- /trend “
, → Brief multi-source scan, automatically savedreports/,_ .md - /scan “
, → One-page quick scan (≤1 WebFetch), prints only. - /Help → Shows the order.
- /exit → leaves.


Image by author
we have experimented /trend Option to find 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 provided complete feedback, auto-saved the report to a Markdown file, and generated a usage summary. It cost us $0.136.


Image by author
Here’s a preview of the Markdown report saved on AI Chips Startups.


Image by author
Now we will test the scanning option and generate a summary about the topic using web search.
It uses a simple web search and fetch tool to produce concise summaries on the topic.


Image by author
, final thoughts
This app ran smoothly, and is working with Cloud Agent SDK Was really fun. If you are already on cloud code Plan, I highly recommend trying this to transform your daily terminal workflow into a reliable, repeatable agentic cli,
Use this:
- Automate common development tasks (debug, test, deploy).
- Script simple analysis or ops routines.
- Package your flows into reusable, shareable tools.
The SDK is suitable for professionals who want Stability, reproducibilityAnd Low glue-code overheadAnd yes, you can also ask Cloud Code for help building agentic applications with the SDK,
abid ali awan ,@1Abidaliyawan) 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 telecommunications engineering. Their vision is to create AI products using graph neural networks for students struggling with mental illness.