Getting Started with Cloud Agent SDK

by SkillAiNest

Getting Started with Cloud Agent SDKGetting Started with Cloud Agent SDK
Photo by author

# Introduction

Tired of duct taping scripts, tools, and pointers together? Cloud Agent SDK Lets you turn around Claude Code “Plan → Build → Run” workflows into real, programmable agents, so you can automate tasks without tons of glue code, wire up tools, and ship command-line interface (CLI) apps. If you like to use already Claude In Terminal, this software development kit (SDK) provides you with the same web interface with proper structure, state and extensions.

In this tutorial, you’ll compile the CloudAgent SDK and create a small, multi-tool CLI that creates an end-to-end (Plan → Act → Verify) chain. Along the way, you’ll see how to register tools, manage contexts, and orchestrate agent loops for local workflows like debugging, code generation, and deployment.

# What is Cloud Agent SDK?

AnthropicClaude Sonnet 4.5 Capabilities mark a significant advance, featuring an advanced coding model that excels in industry benchmarks for reasoning, arithmetic and long context tasks. This release includes a Chrome extension, Memory tool, and document creation features. is the standout ingredient Cloud Agent SDKbased on Claude Code.

The Cloud Agent SDK enables developers to create, extend, and customize cloud-powered applications. It allows integration with your local environment, provides 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 both set up Cloud Code CLI And Cloud Agent SDK.

// 1. Conditions

  • The python: Version 3.10 or higher.
  • node.js: Version 18+ for CLI.
  • Cloud API key or the anthropic account.

// 2. Install CloudCode CLI

We will install CloudCode CLI on Windows by typing the following command in PowerShell:

irm  | 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 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 Cloud CLI is properly installed and included in your path.

# Building a Multi-Tool App with Cloud Agent SDK

In this section, we will build trend The application, which tracks market trends live across various industries, including startups, AI, finance, and sustainability.

It adds up Claude Sonnet 4.5for , for , for , . Web searchfor , for , for , . Web Fetchand Local storage tools in a single multi-agent system.

Create a python file trend_smith.py And add the following code to it:

// 1. Imports and basic settings

It loads Python libraries, CloudAgent SDK types, a small help menu, the model name, and a soft gray text style for the 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 and report destination

It determines the “house rules” for answers (fast, compact, constant parts) and chooses one 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 securely

These helpers save filenames, create folders if needed, and always try the home folder fallback so your report is still 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"
        _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 every run

This allows you to set what you need for one request: streamed text, model, tool count, token usage, and time, then cleanly reset 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

It prints a neat gray box to show the model, token, device 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 (one by one)

It starts the app, reads your command, asks the AI, answers, saves /trend Prints summary reports, and

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

Now we will test the app by running the python file. Here’s a quick refresher on how to use the CLI application:

  • / trend “ → Short multi-source scan, auto save reports/_.md.
  • /scan “ Page Quick scan of a page (≤1 webfetch), prints only.
  • / help → Displays the command.
  • / Get out → Leave.

Getting Started with Cloud Agent SDKGetting Started with Cloud Agent SDK
Photo by author

We have used /trend Option to search for AI chip startups.

/trend "AI chip startups"

Consequently, the app uses various search and web scraping tools to collect information from various websites.

Getting Started with Cloud Agent SDKGetting Started with Cloud Agent SDK
Photo by author

Finally, it provides a complete response, automatically saves the report to a Markdown file, and generates a usage summary. It costs USD 0.136.

Getting Started with Cloud Agent SDKGetting Started with Cloud Agent SDK
Photo by author

Here’s a preview of the archived Markdown report on AI chips startups.

Getting Started with Cloud Agent SDKGetting Started with Cloud Agent SDK
Photo by author

Now we will test the scanning option and generate summary about this topic using web search.

It uses a simple web search and retrieval tool to generate a short summary on the topic.

Getting Started with Cloud Agent SDKGetting Started with Cloud Agent SDK
Photo by author

# Final thoughts

This app is easy to use, and works with Cloud Agent SDK It was really fun. If you are already there Claude Code Make a plan, I highly recommend you try to change your daily terminal workflow to a reliable, repeatable one Agentic CLIS.

Use it:

  • Automate common dev tasks (debug, test, deploy).
  • Script simple analytics or OPS routines.
  • Package your flow into a reusable, shareable tool.

SDK is a good fit for professionals who want stabilityfor , for , for , . Reproducibilityand Low glow code overhead. And yes, you can also ask Cloudcode to help you build your own agent application with the SDK.

Abid Ali Owan For centuries.@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 create an AI product using graph neural networks for students with mental illness.

You may also like

Leave a Comment

At Skillainest, we believe the future belongs to those who embrace AI, upgrade their skills, and stay ahead of the curve.

Get latest news

Subscribe my Newsletter for new blog posts, tips & new photos. Let's stay updated!

@2025 Skillainest.Designed and Developed by Pro