ה-Claude Agent SDK מעניק לכם גישה תוכניתית לאותו agent loop שמפעיל את Claude Code. ה-agents שלכם יכולים לקרוא קבצים, להריץ פקודות shell, לחפש באינטרנט, לערוך קוד, לקרוא ל-APIs חיצוניים דרך MCP servers, ולתזמר sub-agents - הכל מכמה שורות של TypeScript או Python.
בניגוד ל-Anthropic Client SDK הסטנדרטי שבו אתם בונים tool loop משלכם, ה-Agent SDK מטפל ב-tool execution, context management, retries ו-orchestration באופן פנימי. אתם מתארים מה אתם רוצים, מספקים את ה-tools, וה-agent מבין את השאר.
ארכיטקטורה
ה-SDK עוקב אחר לולאה פשוטה: אסוף context, בצע פעולה, ודא, חזור.
נקודת הכניסה המרכזית היא query(), שמחזירה async iterator אשר מזרים הודעות בזמן שה-agent עובד. כל הודעה מספרת לכם מה ה-agent עושה: חושב, קורא ל-tool, מקבל תוצאה, או מספק את הפלט הסופי.
התחלת העבודה
התקנה
# 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 - ה-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}")
Built-in Tools
ה-SDK מגיע עם אותם tools הזמינים ב-Claude Code:
| Tool | Description |
|---|---|
| Read | קריאת תוכן קובץ |
| Write | יצירת קבצים חדשים |
| Edit | ביצוע עריכות ממוקדות בקבצים קיימים |
| Bash | הרצת פקודות shell |
| Glob | חיפוש קבצים לפי תבנית |
| Grep | חיפוש תוכן קבצים עם regex |
| WebSearch | חיפוש באינטרנט |
| WebFetch | שליפת URL והחזרת תוכנו |
| AskUserQuestion | בקשת קלט מהמשתמש |
אתם שולטים אילו tools ה-agent יכול להשתמש באמצעות allowedTools. אם tool לא נמצא ברשימה, ה-agent לא יכול לקרוא לו.
Permission Modes
מכיוון ש-agents מריצים פקודות אמיתיות על מערכות אמיתיות, הרשאות חשובות.
| Mode | Behavior | Use Case |
|---|---|---|
default | callback canUseTool מותאם אישית מחליט לכל קריאה | שליטה עדינה |
acceptEdits | אישור אוטומטי של פעולות קובץ, בקשה עבור Bash | Development workflows |
dontAsk | דחיית כל דבר שאינו ב-allowedTools | Restricted agents |
bypassPermissions | אישור הכל אוטומטית | Trusted sandboxed environments |
auto | מסווג המודל מחליט על בטיחות | אוטומציה מאוזנת |
const conversation = query({ prompt: "Refactor the auth module to use JWT", options: { allowedTools: ["Read", "Edit", "Glob", "Grep", "Bash"], permissionMode: "acceptEdits", }, });
לשימוש ב-production, תמיד הריצו agents בסביבות sandboxed (containers, VMs) והשתמשו ב-permission mode המגביל ביותר שעדיין מאפשר ל-agent לבצע את עבודתו.
בניית Custom Tools עם MCP
הכוח האמיתי של ה-SDK מגיע מהרחבת agents עם tools משלכם. Custom tools מוגדרים כ-MCP servers בתוך התהליך - ללא ניהול subprocess, ללא network overhead.
דוגמה: 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); } }
Custom tools עוקבים אחר מוסכמת השמות mcp__{server_name}__{tool_name}. אתם יכולים להשתמש ב-wildcards ב-allowedTools: "mcp__weather__*" מאפשר את כל ה-tools מה-weather server.
דוגמה: 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), }, ], }; } );
התחברות ל-External MCP Servers
מעבר ל-tools בתוך התהליך, אתם יכולים להתחבר לכל MCP server קיים - אותם servers שעובדים עם Claude Desktop, Cursor ו-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__*"], }, })) { // ... }
אתם יכולים לשלב מספר MCP servers. ה-agent רואה את כל ה-tools מכל ה-servers המחוברים ומשתמש בהם לפי הצורך.
Multi-Agent Orchestration
עבור workflows מורכבים, אתם יכולים להגדיר sub-agents מתמחים שאליהם ה-agent ההורה מאציל. לכל sub-agent יש prompt, tools ותחום מיקוד משלו.
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 של ההורה כדי לאפשר האצלה. Sub-agents רצים עם ה-tools שלהם ולא יכולים לגשת ל-tools של ההורה אלא אם כן הוענקו להם במפורש.
Sessions ורציפות
Agents יכולים לשמור על context במספר queries באמצעות sessions. קחו את ה-session_id מהאינטראקציה הראשונה והעבירו אותו ב-resume עבור 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
אם אתם לא רוצים לארח את תשתית ה-agent בעצמכם, Claude Managed Agents (הושק באפריל 2026) מספק שירות ענן מנוהל במלואו. Anthropic מריצה את ה-containers, מטפלת ב-scaling ומספקת streaming API.
ההבדל המרכזי: עם Agent SDK, אתם מריצים את ה-agent loop בתשתית שלכם. עם Managed Agents, Anthropic מארחת ומריצה את ה-agent עבורכם. אתם מתקשרים דרך API מבוסס session ומקבלים events באמצעות Server-Sent Events.
תמחור:
- Agent SDK: תעריפי tokens סטנדרטיים של Claude API בלבד. אתם מטפלים ב-hosting.
- Managed Agents: תעריפי tokens בתוספת $0.08 לשעת session (מחויב לפי millisecond).
Production Best Practices
1. תמיד השתמשו ב-Sandbox
לעולם אל תריצו agents עם הרשאות בלתי מוגבלות על מכונת production. השתמשו ב-containers (Docker, Fly.io, Modal) או בסביבות sandboxed (E2B, Vercel Sandbox).
2. הגבילו גישה ל-Tools
עקבו אחר עקרון ההרשאה המינימלית. agent שמייצר דוחות לא צריך Bash או Write.
// Too permissive allowedTools: ["Read", "Write", "Edit", "Bash", "Glob", "Grep"] // Better: only what's needed allowedTools: ["Read", "Glob", "Grep"]
3. השתמשו ב-Hooks עבור Guardrails
hooks מאפשרים לכם ליירט tool calls לפני ואחרי execution. השתמשו בהם עבור logging, validation ו-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. טפלו בשגיאות בחן
ה-agent loop יכול לייצר שגיאות - כשלי tool, מגבלות קצב של API, הצפת 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. עקבו אחר שימוש ב-Tokens
Agent loops יכולים לצרוך tokens משמעותיים, במיוחד עם codebases גדולים. ה-SDK כולל context compaction אוטומטי, אך עדיין כדאי לעקוב אחר השימוש.
סיכום
ה-Claude Agent SDK הופך LLM ממכונת מענה לשאלות למשהו הקרוב יותר ל-developer ג'וניור. ה-agents שלכם יכולים לקרוא, לכתוב, להריץ, לוודא ולהתקדם בצעדים - אותו workflow שאדם עוקב אחריו.
התחילו בקטן: בנו agent עם כמה built-in tools. אז הוסיפו custom MCP tools עבור התחום הספציפי שלכם. התרחבו ל-multi-agent orchestration כאשר ה-workflows שלכם דורשים התמחות.
ה-agent loop הוא אותו loop שמפעיל את Claude Code. אם הוא יכול לבנות תוכנה, גם ה-agents שלכם יכולים.
Getting Started Checklist:
- התקינו את ה-SDK (
npm install @anthropic-ai/claude-agent-sdk)- הגדירו
ANTHROPIC_API_KEYבסביבה שלכם- בנו agent פשוט עם built-in tools (Read, Glob, Grep)
- הוסיפו custom tool באמצעות MCP server בתוך התהליך
- התחברו ל-MCP server חיצוני (GitHub, PostgreSQL וכו')
- יישמו multi-agent orchestration עם sub-agents
- הגדירו סביבה sandboxed עבור production
- הוסיפו hooks עבור logging ו-guardrails