Claude Agent SDK ให้คุณเข้าถึง Agent Loop เดียวกันกับที่ขับเคลื่อน Claude Code ผ่านโค้ด Agent ของคุณสามารถอ่านไฟล์ รันคำสั่ง Shell ค้นหาเว็บ แก้ไขโค้ด เรียก API ภายนอกผ่าน MCP Server และจัดการ Sub-Agent - ทั้งหมดนี้ด้วยโค้ด TypeScript หรือ Python เพียงไม่กี่บรรทัด
ต่างจาก Anthropic Client SDK มาตรฐานที่คุณต้องสร้าง Tool Loop เอง Agent SDK จัดการการรันเครื่องมือ การจัดการ Context การลองใหม่ และการจัดการ (Orchestration) ภายในทั้งหมด คุณเพียงอธิบายสิ่งที่ต้องการ จัดเตรียมเครื่องมือ แล้ว Agent จะจัดการส่วนที่เหลือเอง
สถาปัตยกรรม
SDK ทำงานตาม Loop ง่ายๆ: รวบรวม Context, ดำเนินการ, ตรวจสอบ, ทำซ้ำ
Entry Point หลักคือ query() ซึ่งส่งคืน Async Iterator ที่สตรีมข้อความขณะ Agent ทำงาน แต่ละข้อความบอกคุณว่า Agent กำลังทำอะไร: กำลังคิด เรียกเครื่องมือ รับผลลัพธ์ หรือส่งมอบผลลัพธ์สุดท้าย
เริ่มต้นใช้งาน
การติดตั้ง
# TypeScript npm install @anthropic-ai/claude-agent-sdk # Python pip install claude-agent-sdk
คุณต้องตั้งค่า Anthropic API Key เป็น ANTHROPIC_API_KEY ในตัวแปรสภาพแวดล้อม
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); } }
เท่านี้เอง Agent จะใช้ Glob ค้นหาไฟล์ Grep ค้นหาแพทเทิร์น TODO, Read ตรวจสอบผลลัพธ์ที่ตรงกัน และส่งคืนสรุปที่มีโครงสร้าง คุณไม่ต้องเขียน Orchestration Logic เอง - SDK จัดการให้
เวอร์ชัน Python
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}")
เครื่องมือในตัว
SDK มาพร้อมกับเครื่องมือเดียวกันกับที่มีใน Claude Code:
| เครื่องมือ | คำอธิบาย |
|---|---|
| Read | อ่านเนื้อหาไฟล์ |
| Write | สร้างไฟล์ใหม่ |
| Edit | แก้ไขไฟล์ที่มีอยู่แบบเจาะจง |
| Bash | รันคำสั่ง Shell |
| Glob | ค้นหาไฟล์ตามแพทเทิร์น |
| Grep | ค้นหาเนื้อหาไฟล์ด้วย Regex |
| WebSearch | ค้นหาเว็บ |
| WebFetch | ดึง URL และส่งคืนเนื้อหา |
| AskUserQuestion | ถามผู้ใช้เพื่อรับข้อมูล |
คุณควบคุมว่า Agent จะใช้เครื่องมือใดได้ผ่าน allowedTools หากเครื่องมือไม่อยู่ในรายการ Agent จะไม่สามารถเรียกใช้ได้
โหมดสิทธิ์
เนื่องจาก Agent รันคำสั่งจริงบนระบบจริง สิทธิ์จึงมีความสำคัญ
| โหมด | พฤติกรรม | กรณีใช้งาน |
|---|---|---|
default | Callback canUseTool ที่กำหนดเองตัดสินใจทีละการเรียก | การควบคุมแบบละเอียด |
acceptEdits | อนุมัติการดำเนินการไฟล์อัตโนมัติ ถาม Bash | เวิร์กโฟลว์การพัฒนา |
dontAsk | ปฏิเสธทุกอย่างที่ไม่อยู่ใน allowedTools | Agent ที่ถูกจำกัด |
bypassPermissions | อนุมัติทุกอย่างอัตโนมัติ | สภาพแวดล้อม Sandbox ที่เชื่อถือได้ |
auto | ตัวจำแนกของโมเดลตัดสินความปลอดภัย | การทำงานอัตโนมัติแบบสมดุล |
const conversation = query({ prompt: "Refactor the auth module to use JWT", options: { allowedTools: ["Read", "Edit", "Glob", "Grep", "Bash"], permissionMode: "acceptEdits", }, });
สำหรับการใช้งานจริง ควรรัน Agent ในสภาพแวดล้อมแบบ Sandbox (Container, VM) เสมอ และใช้โหมดสิทธิ์ที่จำกัดที่สุดที่ยังให้ Agent ทำงานได้
การสร้างเครื่องมือที่กำหนดเองด้วย MCP
พลังที่แท้จริงของ SDK มาจากการขยาย Agent ด้วยเครื่องมือของคุณเอง เครื่องมือที่กำหนดเองถูกนิยามเป็น In-process MCP Server - ไม่ต้องจัดการ Subprocess ไม่มี Network Overhead
ตัวอย่าง: เครื่องมือสภาพอากาศ
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); } }
เครื่องมือที่กำหนดเองใช้รูปแบบการตั้งชื่อ mcp__{server_name}__{tool_name} คุณสามารถใช้ Wildcard ใน allowedTools: "mcp__weather__*" อนุญาตเครื่องมือทั้งหมดจาก Weather Server
ตัวอย่าง: เครื่องมือ Query ฐานข้อมูล
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), }, ], }; } );
การเชื่อมต่อ MCP Server ภายนอก
นอกเหนือจากเครื่องมือ In-process คุณสามารถเชื่อมต่อกับ MCP Server ที่มีอยู่ใดก็ได้ - เซิร์ฟเวอร์เดียวกันที่ทำงานกับ Claude Desktop, Cursor และ MCP Client อื่นๆ
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__*"], }, })) { // ... }
คุณสามารถรวม MCP Server หลายตัวเข้าด้วยกัน Agent จะเห็นเครื่องมือทั้งหมดจากทุกเซิร์ฟเวอร์ที่เชื่อมต่อและใช้ตามความจำเป็น
การจัดการหลาย Agent (Multi-Agent Orchestration)
สำหรับเวิร์กโฟลว์ที่ซับซ้อน คุณสามารถกำหนด Sub-Agent เฉพาะทางที่ Agent หลักมอบหมายงานให้ Sub-Agent แต่ละตัวมี Prompt เครื่องมือ และพื้นที่เฉพาะทางของตัวเอง
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 }
ใส่ "Agent" ใน allowedTools ของ Agent หลักเพื่อเปิดใช้การมอบหมาย Sub-Agent รันด้วยเครื่องมือของตัวเองและไม่สามารถเข้าถึงเครื่องมือของ Agent หลักได้เว้นแต่จะได้รับอนุญาตอย่างชัดเจน
Session และความต่อเนื่อง
Agent สามารถรักษา Context ข้ามหลาย Query ได้โดยใช้ Session จับ session_id จากการโต้ตอบครั้งแรกและส่งใน resume สำหรับ Query ถัดไป
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
หากคุณไม่ต้องการโฮสต์โครงสร้างพื้นฐานของ Agent ด้วยตัวเอง Claude Managed Agents (เปิดตัวเมษายน 2026) ให้บริการคลาวด์แบบ Fully Managed Anthropic รัน Container จัดการ Scaling และให้ Streaming API
ความแตกต่างสำคัญ: ด้วย Agent SDK คุณรัน Agent Loop ในโครงสร้างพื้นฐานของคุณเอง ด้วย Managed Agents Anthropic โฮสต์และรัน Agent ให้คุณ คุณโต้ตอบผ่าน API แบบ Session และรับ Event ผ่าน Server-Sent Events
ราคา:
- Agent SDK: อัตรา Token ของ Claude API มาตรฐานเท่านั้น คุณจัดการโฮสติ้งเอง
- Managed Agents: อัตรา Token บวก $0.08 ต่อชั่วโมง Session (คิดค่าบริการต่อมิลลิวินาที)
แนวทางปฏิบัติที่ดีสำหรับ Production
1. ใช้ Sandbox เสมอ
อย่ารัน Agent ด้วยสิทธิ์ไม่จำกัดบนเครื่อง Production ใช้ Container (Docker, Fly.io, Modal) หรือสภาพแวดล้อม Sandbox (E2B, Vercel Sandbox)
2. จำกัดการเข้าถึงเครื่องมือ
ปฏิบัติตามหลักสิทธิ์น้อยที่สุด Agent ที่สร้างรายงานไม่จำเป็นต้องมี Bash หรือ Write
// Too permissive allowedTools: ["Read", "Write", "Edit", "Bash", "Glob", "Grep"] // Better: only what's needed allowedTools: ["Read", "Glob", "Grep"]
3. ใช้ Hook เป็นราวกั้น
Hook ให้คุณดักจับการเรียกเครื่องมือก่อนและหลังการทำงาน ใช้สำหรับการบันทึก Log การตรวจสอบ และการจำกัดอัตรา
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. จัดการข้อผิดพลาดอย่างสง่างาม
Agent Loop อาจเกิดข้อผิดพลาด - เครื่องมือล้มเหลว API Rate Limit Context Window ล้น ตรวจสอบประเภทข้อความเสมอ
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. ตรวจสอบการใช้ Token
Agent Loop อาจใช้ Token จำนวนมาก โดยเฉพาะกับ Codebase ขนาดใหญ่ SDK มี Context Compaction อัตโนมัติ แต่คุณยังควรตรวจสอบการใช้งาน
สรุป
Claude Agent SDK เปลี่ยน LLM จากเครื่องตอบคำถามให้เป็นสิ่งที่ใกล้เคียงกับนักพัฒนารุ่นใหม่ Agent ของคุณสามารถอ่าน เขียน รัน ตรวจสอบ และทำซ้ำ - เวิร์กโฟลว์เดียวกับที่มนุษย์ทำ
เริ่มจากเล็กๆ: สร้าง Agent ด้วยเครื่องมือในตัวสักสองสามตัว จากนั้นเพิ่มเครื่องมือ MCP ที่กำหนดเองสำหรับโดเมนเฉพาะของคุณ ขยายไปสู่ Multi-Agent Orchestration เมื่อเวิร์กโฟลว์ของคุณต้องการความเชี่ยวชาญเฉพาะทาง
Agent Loop เดียวกันกับที่ขับเคลื่อน Claude Code หากมันสร้างซอฟต์แวร์ได้ Agent ของคุณก็ทำได้เช่นกัน
รายการตรวจสอบสำหรับเริ่มต้น:
- ติดตั้ง SDK (
npm install @anthropic-ai/claude-agent-sdk)- ตั้งค่า
ANTHROPIC_API_KEYในตัวแปรสภาพแวดล้อม- สร้าง Agent อย่างง่ายด้วยเครื่องมือในตัว (Read, Glob, Grep)
- เพิ่มเครื่องมือที่กำหนดเองผ่าน In-process MCP Server
- เชื่อมต่อ MCP Server ภายนอก (GitHub, PostgreSQL เป็นต้น)
- สร้าง Multi-Agent Orchestration ด้วย Sub-Agent
- ตั้งค่าสภาพแวดล้อม Sandbox สำหรับ Production
- เพิ่ม Hook สำหรับการบันทึก Log และราวกั้น