spinny:~/writing $ less building-ai-agents-claude-agent-sdk.md
12Binibigyan 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.34Hindi 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.56## Architecture78Sumusunod ang SDK sa isang simpleng loop: **mangolekta ng context, kumilos, i-verify, ulitin**.910```mermaid11graph TD12 Input[User Prompt] --> Loop[Agent Loop]13 Loop --> Reason[Claude Reasons]14 Reason --> Tool[Call Tool]15 Tool --> Result[Tool Result]16 Result --> Loop17 Reason --> Done[Final Response]1819 subgraph "Built-in Tools"20 T1[Read / Write / Edit]21 T2[Bash / Terminal]22 T3[Glob / Grep]23 T4[WebSearch / WebFetch]24 end2526 subgraph "Custom Tools via MCP"27 M1[Your API]28 M2[Database]29 M3[Slack / GitHub / etc.]30 end3132 Tool --> T133 Tool --> M134```3536Ang 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.3738## Pagsisimula3940### Installation4142```bash43# TypeScript44npm install @anthropic-ai/claude-agent-sdk4546# Python47pip install claude-agent-sdk48```4950Kailangan mo ng Anthropic API key na itinakda bilang `ANTHROPIC_API_KEY` sa iyong environment.5152### Ang Iyong Unang Agent5354```typescript55import { query } from "@anthropic-ai/claude-agent-sdk";5657const conversation = query({58 prompt: "Find all TODO comments in the codebase and create a summary",59 options: {60 allowedTools: ["Read", "Glob", "Grep"],61 },62});6364for await (const message of conversation) {65 if (message.type === "assistant") {66 process.stdout.write(message.content);67 }68 if (message.type === "result" && message.subtype === "success") {69 console.log("\nDone:", message.result);70 }71}72```7374Iyon 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.7576### Python Equivalent7778```python79from claude_agent_sdk import query8081async for message in query(82 prompt="Find all TODO comments in the codebase and create a summary",83 options={"allowed_tools": ["Read", "Glob", "Grep"]},84):85 if message.type == "assistant":86 print(message.content, end="")87 if message.type == "result" and message.subtype == "success":88 print(f"\nDone: {message.result}")89```9091## Built-in Tools9293Ang SDK ay may parehong tools na available sa Claude Code:9495| Tool | Description |96|------|-------------|97| **Read** | Basahin ang nilalaman ng file |98| **Write** | Lumikha ng bagong files |99| **Edit** | Gumawa ng targeted edits sa mga umiiral na files |100| **Bash** | Magpatakbo ng shell commands |101| **Glob** | Maghanap ng files sa pamamagitan ng pattern |102| **Grep** | Maghanap ng nilalaman ng file gamit ang regex |103| **WebSearch** | Maghanap sa web |104| **WebFetch** | Kunin ang URL at ibalik ang nilalaman nito |105| **AskUserQuestion** | Hilingin sa user ang input |106107Kinokontrol 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.108109## Permission Modes110111Dahil nagpapatakbo ang agents ng tunay na commands sa tunay na systems, mahalaga ang permissions.112113| Mode | Behavior | Use Case |114|------|----------|----------|115| `default` | Custom `canUseTool` callback ang nagpapasya per-call | Fine-grained control |116| `acceptEdits` | Auto-approve ng file operations, humihingi para sa Bash | Development workflows |117| `dontAsk` | Tatanggihan ang anumang wala sa allowedTools | Restricted agents |118| `bypassPermissions` | Awtomatikong aaprubahan ang lahat | Trusted sandboxed environments |119| `auto` | Model classifier ang nagpapasya ng safety | Balanced automation |120121```typescript122const conversation = query({123 prompt: "Refactor the auth module to use JWT",124 options: {125 allowedTools: ["Read", "Edit", "Glob", "Grep", "Bash"],126 permissionMode: "acceptEdits",127 },128});129```130131Para 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.132133## Pagbuo ng Custom Tools gamit ang MCP134135Ang 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.136137### Halimbawa: Weather Tool138139```typescript140import { tool, createSdkMcpServer, query } from "@anthropic-ai/claude-agent-sdk";141import { z } from "zod";142143const getTemperature = tool(144 "get_temperature",145 "Get the current temperature at a location",146 {147 latitude: z.number().describe("Latitude"),148 longitude: z.number().describe("Longitude"),149 },150 async ({ latitude, longitude }) => {151 const res = await fetch(152 `https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}¤t=temperature_2m&temperature_unit=celsius`153 );154 const data = await res.json();155 return {156 content: [157 {158 type: "text",159 text: `Current temperature: ${data.current.temperature_2m}C`,160 },161 ],162 };163 }164);165166const weatherServer = createSdkMcpServer({167 name: "weather",168 version: "1.0.0",169 tools: [getTemperature],170});171172for await (const message of query({173 prompt: "What's the weather like in Rome?",174 options: {175 mcpServers: { weather: weatherServer },176 allowedTools: ["mcp__weather__get_temperature"],177 },178})) {179 if (message.type === "result" && message.subtype === "success") {180 console.log(message.result);181 }182}183```184185Sumusunod 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.186187### Halimbawa: Database Query Tool188189```typescript190const queryDb = tool(191 "query_database",192 "Run a read-only SQL query against the application database",193 {194 sql: z.string().describe("SQL SELECT query to execute"),195 },196 async ({ sql }) => {197 // Validate: only allow SELECT queries198 if (!sql.trim().toUpperCase().startsWith("SELECT")) {199 return {200 content: [{ type: "text", text: "Error: Only SELECT queries are allowed." }],201 };202 }203204 const result = await pool.query(sql);205 return {206 content: [207 {208 type: "text",209 text: JSON.stringify(result.rows, null, 2),210 },211 ],212 };213 }214);215```216217## Pagkonekta sa External MCP Servers218219Bukod 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.220221```typescript222for await (const message of query({223 prompt: "Check the latest issues in the frontend repo and summarize them",224 options: {225 mcpServers: {226 github: {227 command: "npx",228 args: ["-y", "@modelcontextprotocol/server-github"],229 env: { GITHUB_PERSONAL_ACCESS_TOKEN: process.env.GITHUB_TOKEN },230 },231 },232 allowedTools: ["mcp__github__*"],233 },234})) {235 // ...236}237```238239Maaari mong pagsamahin ang maraming MCP servers. Nakikita ng agent ang lahat ng tools mula sa lahat ng nakakonektang servers at gagamitin ito kung kinakailangan.240241```mermaid242graph LR243 Agent[Your Agent] --> SDK[Agent SDK]244 SDK --> InProcess[In-process MCP\nCustom Tools]245 SDK --> GitHub[GitHub MCP Server]246 SDK --> Postgres[PostgreSQL MCP Server]247 SDK --> Slack[Slack MCP Server]248```249250## Multi-Agent Orchestration251252Para 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.253254```typescript255for await (const message of query({256 prompt: "Review the PR, check for security issues, and update the changelog",257 options: {258 allowedTools: ["Read", "Edit", "Bash", "Glob", "Grep", "Agent"],259 agents: [260 {261 name: "security-reviewer",262 description: "Reviews code for security vulnerabilities",263 prompt: "You are a security expert. Analyze code for OWASP Top 10 vulnerabilities.",264 allowedTools: ["Read", "Glob", "Grep"],265 },266 {267 name: "changelog-writer",268 description: "Updates the CHANGELOG.md file based on recent changes",269 prompt: "You maintain the project changelog. Follow Keep a Changelog format.",270 allowedTools: ["Read", "Edit", "Bash"],271 },272 ],273 },274})) {275 // The parent agent will:276 // 1. Read the PR diff277 // 2. Delegate security review to security-reviewer278 // 3. Delegate changelog update to changelog-writer279 // 4. Synthesize results280}281```282283Isama 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.284285```mermaid286graph TD287 Parent[Parent Agent] --> SR[Security Reviewer\nRead, Glob, Grep]288 Parent --> CW[Changelog Writer\nRead, Edit, Bash]289 SR --> Report[Security Report]290 CW --> Updated[Updated CHANGELOG]291 Report --> Parent292 Updated --> Parent293 Parent --> Final[Final Summary]294```295296## Sessions at Continuity297298Ang 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.299300```typescript301let sessionId: string | undefined;302303// First query304for await (const message of query({305 prompt: "Read the project structure and understand the architecture",306 options: { allowedTools: ["Read", "Glob", "Grep"] },307})) {308 if (message.type === "init") {309 sessionId = message.session_id;310 }311}312313// Follow-up query (same session, full context preserved)314for await (const message of query({315 prompt: "Now refactor the auth module based on what you learned",316 resume: sessionId,317 options: { allowedTools: ["Read", "Edit", "Bash"] },318})) {319 // Agent remembers the full project context from the first query320}321```322323## Claude Managed Agents324325Kung 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.326327```mermaid328graph LR329 subgraph "Self-hosted (Agent SDK)"330 Code[Your Code] --> SDK2[Agent SDK]331 SDK2 --> API[Claude API]332 SDK2 --> Tools[Your Tools]333 end334335 subgraph "Managed Agents"336 App[Your App] --> MAPI[Managed Agents API]337 MAPI --> Container[Anthropic-hosted Container]338 Container --> API2[Claude API]339 Container --> Tools2[Tools in Container]340 end341```342343Ang 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.344345**Pricing:**346- **Agent SDK**: standard Claude API token rates lamang. Ikaw ang humahawak sa hosting.347- **Managed Agents**: token rates plus $0.08 bawat session-hour (sinisingil bawat millisecond).348349## Production Best Practices350351### 1. Palaging Mag-Sandbox352353Huwag 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).354355### 2. Limitahan ang Tool Access356357Sundin ang prinsipyo ng least privilege. Ang isang agent na gumagawa ng reports ay hindi nangangailangan ng `Bash` o `Write`.358359```typescript360// Too permissive361allowedTools: ["Read", "Write", "Edit", "Bash", "Glob", "Grep"]362363// Better: only what's needed364allowedTools: ["Read", "Glob", "Grep"]365```366367### 3. Gumamit ng Hooks para sa Guardrails368369Pinapayagan 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.370371```typescript372const conversation = query({373 prompt: "Analyze the codebase",374 options: {375 allowedTools: ["Read", "Glob", "Grep"],376 hooks: {377 PreToolUse: async (toolName, input) => {378 console.log(`Tool call: ${toolName}`, input);379 // Return false to block the call380 if (toolName === "Bash" && input.command.includes("rm")) {381 return false;382 }383 return true;384 },385 },386 },387});388```389390### 4. Hawakan ang mga Error nang Maganda391392Ang agent loop ay maaaring magbunga ng mga error - tool failures, API rate limits, context window overflow. Palaging suriin ang message types.393394```typescript395for await (const message of conversation) {396 switch (message.type) {397 case "assistant":398 // Agent reasoning399 break;400 case "tool_use":401 // Agent is calling a tool402 break;403 case "result":404 if (message.subtype === "error") {405 console.error("Agent failed:", message.error);406 }407 break;408 }409}410```411412### 5. I-monitor ang Token Usage413414Ang 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.415416## Konklusyon417418Ang 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.419420Magsimula 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.421422Ang agent loop ay ang parehong isa na nagpapagana sa Claude Code. Kung kaya nitong gumawa ng software, kaya rin ng iyong agents.423424> **Getting Started Checklist:**425>426> - [x] I-install ang SDK (`npm install @anthropic-ai/claude-agent-sdk`)427> - [x] Itakda ang `ANTHROPIC_API_KEY` sa iyong environment428> - [x] Bumuo ng simpleng agent na may built-in tools (Read, Glob, Grep)429> - [x] Magdagdag ng custom tool sa pamamagitan ng in-process MCP server430> - [x] Kumonekta sa external MCP server (GitHub, PostgreSQL, atbp.)431> - [x] Ipatupad ang multi-agent orchestration na may sub-agents432> - [x] Mag-set up ng sandboxed environment para sa production433> - [x] Magdagdag ng hooks para sa logging at guardrails434
:Pagbuo ng AI Agents gamit ang Claude Agent SDK: Isang Praktikal na Gabaylines 1-434 (END) — press q to close