Binibigyan ka ng Claude Agent SDK ng programmatic access sa parehong agent loop na nagpapagana sa Claude Code. Ang iyong agents ay maaaring magbasa ng files, magpatakbo ng shell commands, maghanap sa web, mag-edit ng code, tumawag sa external APIs sa pamamagitan ng MCP servers, at mag-orchestrate ng sub-agents - lahat mula sa ilang linya ng TypeScript o Python.
Hindi tulad ng standard Anthropic Client SDK kung saan gagawa ka ng sarili mong tool loop, hinahawakan ng Agent SDK ang tool execution, context management, retries, at orchestration sa loob. Ilalarawan mo kung ano ang gusto mo, ibibigay mo ang tools, at aalamin ng agent ang iba pa.
Architecture
Sumusunod ang SDK sa isang simpleng loop: mangolekta ng context, kumilos, i-verify, ulitin.
Ang core entry point ay query(), na nagbabalik ng async iterator na nag-stream ng messages habang gumagana ang agent. Bawat message ay nagsasabi sa iyo kung ano ang ginagawa ng agent: nangangatwiran, tumatawag ng tool, tumatanggap ng resulta, o naghahatid ng final output.
Pagsisimula
Installation
# TypeScript npm install @anthropic-ai/claude-agent-sdk # Python pip install claude-agent-sdk
Kailangan mo ng Anthropic API key na itinakda bilang ANTHROPIC_API_KEY sa iyong environment.
Ang Iyong Unang Agent
import { query } from "@anthropic-ai/claude-agent-sdk"; const conversation = query({ prompt: "Find all TODO comments in the codebase and create a summary", options: { allowedTools: ["Read", "Glob", "Grep"], }, }); for await (const message of conversation) { if (message.type === "assistant") { process.stdout.write(message.content); } if (message.type === "result" && message.subtype === "success") { console.log("\nDone:", message.result); } }
Iyon lang. Gagamitin ng agent ang Glob para maghanap ng files, Grep para maghanap ng TODO patterns, Read para inspeksyunin ang mga match, at magbabalik ng structured summary. Hindi mo isinusulat ang orchestration logic - hinahawakan ito ng SDK.
Python Equivalent
from claude_agent_sdk import query async for message in query( prompt="Find all TODO comments in the codebase and create a summary", options={"allowed_tools": ["Read", "Glob", "Grep"]}, ): if message.type == "assistant": print(message.content, end="") if message.type == "result" and message.subtype == "success": print(f"\nDone: {message.result}")
Built-in Tools
Ang SDK ay may parehong tools na available sa Claude Code:
| Tool | Description |
|---|---|
| Read | Basahin ang nilalaman ng file |
| Write | Lumikha ng bagong files |
| Edit | Gumawa ng targeted edits sa mga umiiral na files |
| Bash | Magpatakbo ng shell commands |
| Glob | Maghanap ng files sa pamamagitan ng pattern |
| Grep | Maghanap ng nilalaman ng file gamit ang regex |
| WebSearch | Maghanap sa web |
| WebFetch | Kunin ang URL at ibalik ang nilalaman nito |
| AskUserQuestion | Hilingin sa user ang input |
Kinokontrol mo kung aling tools ang magagamit ng agent sa pamamagitan ng allowedTools. Kung ang isang tool ay wala sa listahan, hindi ito matatawag ng agent.
Permission Modes
Dahil nagpapatakbo ang agents ng tunay na commands sa tunay na systems, mahalaga ang permissions.
| Mode | Behavior | Use Case |
|---|---|---|
default | Custom canUseTool callback ang nagpapasya per-call | Fine-grained control |
acceptEdits | Auto-approve ng file operations, humihingi para sa Bash | Development workflows |
dontAsk | Tatanggihan ang anumang wala sa allowedTools | Restricted agents |
bypassPermissions | Awtomatikong aaprubahan ang lahat | Trusted sandboxed environments |
auto | Model classifier ang nagpapasya ng safety | Balanced automation |
const conversation = query({ prompt: "Refactor the auth module to use JWT", options: { allowedTools: ["Read", "Edit", "Glob", "Grep", "Bash"], permissionMode: "acceptEdits", }, });
Para sa production use, palaging patakbuhin ang agents sa sandboxed environments (containers, VMs) at gamitin ang pinaka-restrictive na permission mode na pumapayag pa rin sa agent na gawin ang kanyang trabaho.
Pagbuo ng Custom Tools gamit ang MCP
Ang tunay na kapangyarihan ng SDK ay nagmumula sa pagpapalawak ng agents gamit ang iyong sariling tools. Ang custom tools ay tinutukoy bilang in-process MCP servers - walang subprocess management, walang network overhead.
Halimbawa: Weather Tool
import { tool, createSdkMcpServer, query } from "@anthropic-ai/claude-agent-sdk"; import { z } from "zod"; const getTemperature = tool( "get_temperature", "Get the current temperature at a location", { latitude: z.number().describe("Latitude"), longitude: z.number().describe("Longitude"), }, async ({ latitude, longitude }) => { const res = await fetch( `https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}¤t=temperature_2m&temperature_unit=celsius` ); const data = await res.json(); return { content: [ { type: "text", text: `Current temperature: ${data.current.temperature_2m}C`, }, ], }; } ); const weatherServer = createSdkMcpServer({ name: "weather", version: "1.0.0", tools: [getTemperature], }); for await (const message of query({ prompt: "What's the weather like in Rome?", options: { mcpServers: { weather: weatherServer }, allowedTools: ["mcp__weather__get_temperature"], }, })) { if (message.type === "result" && message.subtype === "success") { console.log(message.result); } }
Sumusunod ang custom tools sa naming convention na mcp__{server_name}__{tool_name}. Maaari kang gumamit ng wildcards sa allowedTools: Ang "mcp__weather__*" ay pumapayag sa lahat ng tools mula sa weather server.
Halimbawa: Database Query Tool
const queryDb = tool( "query_database", "Run a read-only SQL query against the application database", { sql: z.string().describe("SQL SELECT query to execute"), }, async ({ sql }) => { // Validate: only allow SELECT queries if (!sql.trim().toUpperCase().startsWith("SELECT")) { return { content: [{ type: "text", text: "Error: Only SELECT queries are allowed." }], }; } const result = await pool.query(sql); return { content: [ { type: "text", text: JSON.stringify(result.rows, null, 2), }, ], }; } );
Pagkonekta sa External MCP Servers
Bukod sa in-process tools, maaari kang kumonekta sa anumang umiiral na MCP server - ang parehong servers na gumagana sa Claude Desktop, Cursor, at iba pang MCP clients.
for await (const message of query({ prompt: "Check the latest issues in the frontend repo and summarize them", options: { mcpServers: { github: { command: "npx", args: ["-y", "@modelcontextprotocol/server-github"], env: { GITHUB_PERSONAL_ACCESS_TOKEN: process.env.GITHUB_TOKEN }, }, }, allowedTools: ["mcp__github__*"], }, })) { // ... }
Maaari mong pagsamahin ang maraming MCP servers. Nakikita ng agent ang lahat ng tools mula sa lahat ng nakakonektang servers at gagamitin ito kung kinakailangan.
Multi-Agent Orchestration
Para sa mga kumplikadong workflow, maaari kang magtukoy ng specialized sub-agents kung saan nag-de-delegate ang parent agent. Bawat sub-agent ay may sariling prompt, tools, at focus area.
for await (const message of query({ prompt: "Review the PR, check for security issues, and update the changelog", options: { allowedTools: ["Read", "Edit", "Bash", "Glob", "Grep", "Agent"], agents: [ { name: "security-reviewer", description: "Reviews code for security vulnerabilities", prompt: "You are a security expert. Analyze code for OWASP Top 10 vulnerabilities.", allowedTools: ["Read", "Glob", "Grep"], }, { name: "changelog-writer", description: "Updates the CHANGELOG.md file based on recent changes", prompt: "You maintain the project changelog. Follow Keep a Changelog format.", allowedTools: ["Read", "Edit", "Bash"], }, ], }, })) { // The parent agent will: // 1. Read the PR diff // 2. Delegate security review to security-reviewer // 3. Delegate changelog update to changelog-writer // 4. Synthesize results }
Isama ang "Agent" sa allowedTools ng parent para mapagana ang delegation. Ang sub-agents ay tumatakbo gamit ang sarili nilang tools at hindi maaaring mag-access sa tools ng parent maliban kung tahasang ipinagkaloob.
Sessions at Continuity
Ang agents ay maaaring magpanatili ng context sa maraming queries gamit ang sessions. Kunin ang session_id mula sa unang interaction at ipasa ito sa resume para sa mga sumusunod na queries.
let sessionId: string | undefined; // First query for await (const message of query({ prompt: "Read the project structure and understand the architecture", options: { allowedTools: ["Read", "Glob", "Grep"] }, })) { if (message.type === "init") { sessionId = message.session_id; } } // Follow-up query (same session, full context preserved) for await (const message of query({ prompt: "Now refactor the auth module based on what you learned", resume: sessionId, options: { allowedTools: ["Read", "Edit", "Bash"] }, })) { // Agent remembers the full project context from the first query }
Claude Managed Agents
Kung ayaw mong i-host mismo ang agent infrastructure, ang Claude Managed Agents (inilunsad noong Abril 2026) ay nagbibigay ng fully managed cloud service. Pinapatakbo ng Anthropic ang containers, hinahawakan ang scaling, at nagbibigay ng streaming API.
Ang pangunahing pagkakaiba: sa Agent SDK, pinapatakbo mo ang agent loop sa sarili mong infrastructure. Sa Managed Agents, ang Anthropic ang nag-host at nagpapatakbo ng agent para sa iyo. Nakikipag-ugnayan ka sa pamamagitan ng session-based API at tumatanggap ng events sa pamamagitan ng Server-Sent Events.
Pricing:
- Agent SDK: standard Claude API token rates lamang. Ikaw ang humahawak sa hosting.
- Managed Agents: token rates plus $0.08 bawat session-hour (sinisingil bawat millisecond).
Production Best Practices
1. Palaging Mag-Sandbox
Huwag kailanman magpatakbo ng agents na may walang-limitasyong permissions sa isang production machine. Gumamit ng containers (Docker, Fly.io, Modal) o sandboxed environments (E2B, Vercel Sandbox).
2. Limitahan ang Tool Access
Sundin ang prinsipyo ng least privilege. Ang isang agent na gumagawa ng reports ay hindi nangangailangan ng Bash o Write.
// Too permissive allowedTools: ["Read", "Write", "Edit", "Bash", "Glob", "Grep"] // Better: only what's needed allowedTools: ["Read", "Glob", "Grep"]
3. Gumamit ng Hooks para sa Guardrails
Pinapayagan ka ng hooks na i-intercept ang tool calls bago at pagkatapos ng execution. Gamitin ang mga ito para sa logging, validation, at rate limiting.
const conversation = query({ prompt: "Analyze the codebase", options: { allowedTools: ["Read", "Glob", "Grep"], hooks: { PreToolUse: async (toolName, input) => { console.log(`Tool call: ${toolName}`, input); // Return false to block the call if (toolName === "Bash" && input.command.includes("rm")) { return false; } return true; }, }, }, });
4. Hawakan ang mga Error nang Maganda
Ang agent loop ay maaaring magbunga ng mga error - tool failures, API rate limits, context window overflow. Palaging suriin ang message types.
for await (const message of conversation) { switch (message.type) { case "assistant": // Agent reasoning break; case "tool_use": // Agent is calling a tool break; case "result": if (message.subtype === "error") { console.error("Agent failed:", message.error); } break; } }
5. I-monitor ang Token Usage
Ang agent loops ay maaaring gumamit ng malaking tokens, lalo na sa malalaking codebases. Ang SDK ay may kasamang automatic context compaction, ngunit dapat mo pa ring i-monitor ang paggamit.
Konklusyon
Ang Claude Agent SDK ay ginagawang isang LLM mula sa isang question-answering machine patungo sa isang bagay na mas malapit sa isang junior developer. Ang iyong agents ay maaaring magbasa, magsulat, magpatakbo, mag-verify, at mag-iterate - ang parehong workflow na sinusunod ng tao.
Magsimula sa maliit: bumuo ng agent na may ilang built-in tools. Pagkatapos ay magdagdag ng custom MCP tools para sa iyong tiyak na domain. I-scale up sa multi-agent orchestration kapag ang iyong workflows ay nangangailangan ng specialization.
Ang agent loop ay ang parehong isa na nagpapagana sa Claude Code. Kung kaya nitong gumawa ng software, kaya rin ng iyong agents.
Getting Started Checklist:
- I-install ang SDK (
npm install @anthropic-ai/claude-agent-sdk)- Itakda ang
ANTHROPIC_API_KEYsa iyong environment- Bumuo ng simpleng agent na may built-in tools (Read, Glob, Grep)
- Magdagdag ng custom tool sa pamamagitan ng in-process MCP server
- Kumonekta sa external MCP server (GitHub, PostgreSQL, atbp.)
- Ipatupad ang multi-agent orchestration na may sub-agents
- Mag-set up ng sandboxed environment para sa production
- Magdagdag ng hooks para sa logging at guardrails