spinny:~/writing $ vim building-ai-agents-claude-agent-sdk.md
1~2Claude Agent SDK cung cấp cho bạn quyền truy cập lập trình vào cùng Agent Loop đang vận hành Claude Code. Agent của bạn có thể đọc file, chạy lệnh Shell, tìm kiếm web, chỉnh sửa code, gọi API bên ngoài thông qua MCP Server và điều phối Sub-Agent - tất cả chỉ với vài dòng TypeScript hoặc Python.3~4Khác với Anthropic Client SDK tiêu chuẩn nơi bạn phải tự xây dựng Tool Loop, Agent SDK xử lý việc thực thi công cụ, quản lý Context, thử lại và điều phối bên trong. Bạn mô tả những gì bạn muốn, cung cấp các công cụ, và Agent sẽ tự xử lý phần còn lại.5~6## Kiến trúc7~8SDK theo một vòng lặp đơn giản: **thu thập Context, thực hiện hành động, xác minh, lặp lại**.9~10```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]18~19 subgraph "Built-in Tools"20 T1[Read / Write / Edit]21 T2[Bash / Terminal]22 T3[Glob / Grep]23 T4[WebSearch / WebFetch]24 end25~26 subgraph "Custom Tools via MCP"27 M1[Your API]28 M2[Database]29 M3[Slack / GitHub / etc.]30 end31~32 Tool --> T133 Tool --> M134```35~36Điểm vào chính là `query()`, trả về một Async Iterator phát các thông điệp khi Agent làm việc. Mỗi thông điệp cho bạn biết Agent đang làm gì: suy luận, gọi công cụ, nhận kết quả, hoặc trả về kết quả cuối cùng.37~38## Bắt đầu39~40### Cài đặt41~42```bash43# TypeScript44npm install @anthropic-ai/claude-agent-sdk45~46# Python47pip install claude-agent-sdk48```49~50Bạn cần đặt Anthropic API Key là `ANTHROPIC_API_KEY` trong biến môi trường.51~52### Agent đầu tiên của bạn53~54```typescript55import { query } from "@anthropic-ai/claude-agent-sdk";56~57const conversation = query({58 prompt: "Find all TODO comments in the codebase and create a summary",59 options: {60 allowedTools: ["Read", "Glob", "Grep"],61 },62});63~64for 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```73~74Chỉ có vậy thôi. Agent sẽ sử dụng Glob để tìm file, Grep để tìm kiếm pattern TODO, Read để kiểm tra kết quả khớp, và trả về bản tóm tắt có cấu trúc. Bạn không cần viết logic điều phối - SDK xử lý tất cả.75~76### Phiên bản Python77~78```python79from claude_agent_sdk import query80~81async 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```90~91## Công cụ tích hợp sẵn92~93SDK đi kèm với các công cụ tương tự như trong Claude Code:94~95| Công cụ | Mô tả |96|------|-------------|97| **Read** | Đọc nội dung file |98| **Write** | Tạo file mới |99| **Edit** | Chỉnh sửa có mục tiêu trên file hiện có |100| **Bash** | Chạy lệnh Shell |101| **Glob** | Tìm file theo pattern |102| **Grep** | Tìm kiếm nội dung file bằng Regex |103| **WebSearch** | Tìm kiếm web |104| **WebFetch** | Lấy URL và trả về nội dung |105| **AskUserQuestion** | Hỏi người dùng để nhập liệu |106~107Bạn kiểm soát công cụ nào Agent có thể sử dụng thông qua `allowedTools`. Nếu một công cụ không có trong danh sách, Agent không thể gọi nó.108~109## Chế độ quyền110~111Vì Agent thực thi lệnh thật trên hệ thống thật, quyền hạn rất quan trọng.112~113| Chế độ | Hành vi | Trường hợp sử dụng |114|------|----------|----------|115| `default` | Callback `canUseTool` tùy chỉnh quyết định theo từng lần gọi | Kiểm soát chi tiết |116| `acceptEdits` | Tự động phê duyệt thao tác file, hỏi khi dùng Bash | Workflow phát triển |117| `dontAsk` | Từ chối mọi thứ không có trong allowedTools | Agent bị hạn chế |118| `bypassPermissions` | Tự động phê duyệt tất cả | Môi trường Sandbox đáng tin cậy |119| `auto` | Bộ phân loại của model quyết định mức độ an toàn | Tự động hóa cân bằng |120~121```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```130~131Trong môi trường Production, luôn chạy Agent trong môi trường Sandbox (Container, VM) và sử dụng chế độ quyền hạn chế nhất mà vẫn cho phép Agent hoàn thành công việc.132~133## Xây dựng công cụ tùy chỉnh với MCP134~135Sức mạnh thực sự của SDK đến từ việc mở rộng Agent bằng công cụ của riêng bạn. Công cụ tùy chỉnh được định nghĩa là MCP Server trong tiến trình (In-process) - không cần quản lý Subprocess, không có Network Overhead.136~137### Ví dụ: Công cụ thời tiết138~139```typescript140import { tool, createSdkMcpServer, query } from "@anthropic-ai/claude-agent-sdk";141import { z } from "zod";142~143const 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);165~166const weatherServer = createSdkMcpServer({167 name: "weather",168 version: "1.0.0",169 tools: [getTemperature],170});171~172for 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```184~185Công cụ tùy chỉnh tuân theo quy ước đặt tên `mcp__{server_name}__{tool_name}`. Bạn có thể dùng Wildcard trong `allowedTools`: `"mcp__weather__*"` cho phép tất cả công cụ từ Weather Server.186~187### Ví dụ: Công cụ truy vấn cơ sở dữ liệu188~189```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 }203~204 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```216~217## Kết nối MCP Server bên ngoài218~219Ngoài công cụ In-process, bạn có thể kết nối với bất kỳ MCP Server nào hiện có - cùng những Server hoạt động với Claude Desktop, Cursor và các MCP Client khác.220~221```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```238~239Bạn có thể kết hợp nhiều MCP Server. Agent sẽ thấy tất cả công cụ từ tất cả Server đã kết nối và sử dụng chúng khi cần thiết.240~241```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```249~250## Điều phối đa Agent251~252Đối với các Workflow phức tạp, bạn có thể định nghĩa các Sub-Agent chuyên biệt mà Agent cha ủy quyền cho. Mỗi Sub-Agent có Prompt, công cụ và lĩnh vực tập trung riêng.253~254```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```282~283Thêm `"Agent"` vào `allowedTools` của Agent cha để bật tính năng ủy quyền. Sub-Agent chạy với công cụ riêng của chúng và không thể truy cập công cụ của Agent cha trừ khi được cấp quyền rõ ràng.284~285```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```295~296## Session và tính liên tục297~298Agent có thể duy trì Context qua nhiều Query bằng cách sử dụng Session. Lấy `session_id` từ lần tương tác đầu tiên và truyền vào `resume` cho các Query tiếp theo.299~300```typescript301let sessionId: string | undefined;302~303// 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}312~313// 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```322~323## Claude Managed Agents324~325Nếu bạn không muốn tự host hạ tầng Agent, **Claude Managed Agents** (ra mắt tháng 4 năm 2026) cung cấp dịch vụ đám mây được quản lý hoàn toàn. Anthropic chạy Container, xử lý Scaling và cung cấp Streaming API.326~327```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 end334~335 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```342~343Khác biệt chính: với Agent SDK, bạn chạy Agent Loop trong hạ tầng của riêng bạn. Với Managed Agents, Anthropic host và chạy Agent cho bạn. Bạn tương tác thông qua API dựa trên Session và nhận Event qua Server-Sent Events.344~345**Giá:**346- **Agent SDK**: chỉ tính theo giá Token của Claude API tiêu chuẩn. Bạn tự xử lý hosting.347- **Managed Agents**: giá Token cộng thêm $0.08 mỗi giờ Session (tính theo mili giây).348~349## Các phương pháp tốt nhất cho Production350~351### 1. Luôn sử dụng Sandbox352~353Không bao giờ chạy Agent với quyền không giới hạn trên máy Production. Sử dụng Container (Docker, Fly.io, Modal) hoặc môi trường Sandbox (E2B, Vercel Sandbox).354~355### 2. Giới hạn quyền truy cập công cụ356~357Tuân theo nguyên tắc đặc quyền tối thiểu. Agent tạo báo cáo không cần `Bash` hay `Write`.358~359```typescript360// Too permissive361allowedTools: ["Read", "Write", "Edit", "Bash", "Glob", "Grep"]362~363// Better: only what's needed364allowedTools: ["Read", "Glob", "Grep"]365```366~367### 3. Sử dụng Hook làm lan can bảo vệ368~369Hook cho phép bạn chặn các lời gọi công cụ trước và sau khi thực thi. Sử dụng cho việc ghi Log, xác thực và giới hạn tốc độ.370~371```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```389~390### 4. Xử lý lỗi một cách tinh tế391~392Agent Loop có thể tạo ra lỗi - công cụ thất bại, API Rate Limit, Context Window tràn. Luôn kiểm tra loại thông điệp.393~394```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```411~412### 5. Giám sát lượng Token sử dụng413~414Agent Loop có thể tiêu thụ lượng Token đáng kể, đặc biệt với Codebase lớn. SDK bao gồm tính năng tự động nén Context, nhưng bạn vẫn nên giám sát lượng sử dụng.415~416## Kết luận417~418Claude Agent SDK biến LLM từ một máy trả lời câu hỏi thành thứ gì đó gần với một lập trình viên mới vào nghề. Agent của bạn có thể đọc, viết, thực thi, xác minh và lặp lại - cùng Workflow mà con người thực hiện.419~420Bắt đầu từ nhỏ: xây dựng một Agent với vài công cụ tích hợp sẵn. Sau đó thêm công cụ MCP tùy chỉnh cho lĩnh vực cụ thể của bạn. Mở rộng lên điều phối đa Agent khi Workflow của bạn cần sự chuyên môn hóa.421~422Agent Loop là cùng một vòng lặp đang vận hành Claude Code. Nếu nó có thể xây dựng phần mềm, Agent của bạn cũng làm được.423~424> **Danh sách kiểm tra để bắt đầu:**425>426> - [x] Cài đặt SDK (`npm install @anthropic-ai/claude-agent-sdk`)427> - [x] Đặt `ANTHROPIC_API_KEY` trong biến môi trường428> - [x] Xây dựng Agent đơn giản với công cụ tích hợp sẵn (Read, Glob, Grep)429> - [x] Thêm công cụ tùy chỉnh qua In-process MCP Server430> - [x] Kết nối MCP Server bên ngoài (GitHub, PostgreSQL, v.v.)431> - [x] Triển khai điều phối đa Agent với Sub-Agent432> - [x] Thiết lập môi trường Sandbox cho Production433> - [x] Thêm Hook cho việc ghi Log và lan can bảo vệ434~
NORMAL · building-ai-agents-claude-agent-sdk.md [readonly]434 lines · :q to close