To Claude Agent SDK sas dinei programmatiki prosvasi ston idio vrogcho agent pou trofodotei to Claude Code. Oi agents sas mporoun na diavazoun archeia, na ektheloun entoles shell, na psachnoun sto diadiktyo, na epexergazontai kodika, na kaloun eksoterika API mesw MCP servers kai na orchestroun sub-agents - ola apo liges grammes TypeScript i Python.
Se antithesi me to standard Anthropic Client SDK opou chtizetai ton diko sas tool loop, to Agent SDK diacheirizatai tin ekthelesi ergaleion, ti diacheirisi context, ta retries kai to orchestration essoteriko. Perigrafete ti thelete, parechete ta ergaleia kai o agent vriskei ton tropo.
Architektoniki
To SDK akolouthei enan aplo vrogcho: syllexi context, anadrome drasis, epivevaiosi, epanalipsi.
To kyrio simeio eisodou einai to query(), pou epistrefei enan asynchrono iterator pou kanei stream minimata kathos o agent ergazetai. Kathe minima sas lei ti kanei o agent: skeftetai, kalei ergaleio, lamvanei apotelesma i paradidei to teliko output.
Xekinontas
Enkatastasei
# TypeScript npm install @anthropic-ai/claude-agent-sdk # Python pip install claude-agent-sdk
Chreiazetai ena API key tis Anthropic orismeno os ANTHROPIC_API_KEY sto perivallon sas.
O protos sas 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); } }
Afto einai olo. O agent tha chrisimopoiisei to Glob gia na vrei archeia, to Grep gia na psaxei gia TODO patterns, to Read gia na exetasei ta apotelesmata kai tha epistrepsei mia domimeni perilipsi. Den grafete ti logiki orchestration - to SDK to diacheirizatai.
Antistiocho se 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}")
Ensomatomona ergaleia
To SDK perilamvanei ta idia ergaleia pou einai diathesima sto Claude Code:
| Ergaleio | Perigrafi |
|---|---|
| Read | Diavazei to periechomeno archeion |
| Write | Dimiourgia neon archeion |
| Edit | Stochevmenes allages se yparcha archeia |
| Bash | Ekthelesi entolon shell |
| Glob | Evresi archeion me vasi protypo |
| Grep | Anazitisi periechomenou archeion me regex |
| WebSearch | Anazitisi sto diadiktyo |
| WebFetch | Lipsi URL kai epistrofi tou periechomenou tou |
| AskUserQuestion | Aitisi eisodou apo ton christi |
Elegchete poia ergaleia mporei na chrisimopoiisei o agent mesw allowedTools. An ena ergaleio den einai sti lista, o agent den mporei na to kalesei.
Modes adeiodotisis
Epidei oi agents ektheloun pragmatikes entoles se pragmatika systimata, oi adeies echoun simasia.
| Mode | Symperifora | Chrisi |
|---|---|---|
default | Prosormosmeno canUseTool callback apofasizei ana klisi | Lepti elegchos |
acceptEdits | Aftomati egkrisi leitourgion archeion, erotisi gia Bash | Workflow anaptyxis |
dontAsk | Aporripsi otidhipote den einai sta allowedTools | Periorismenoi agents |
bypassPermissions | Aftomati egkrisi olou | Empistefmena sandbox perivallonta |
auto | O classifier tou montelou apofasizei gia tin asfaleia | Isorropimeni aftomaropoiisi |
const conversation = query({ prompt: "Refactor the auth module to use JWT", options: { allowedTools: ["Read", "Edit", "Glob", "Grep", "Bash"], permissionMode: "acceptEdits", }, });
Gia chrisi se paragogi, panta trechete tous agents se sandbox perivallonta (containers, VMs) kai chrisimopoiiste ton pio periorismeno mode adeiodotisis pou epitrepei ston agent na kanei ti douleia tou.
Dimiourgia prosarmosmeon ergaleion me MCP
I pragmatiki dynami tou SDK provlepetai apo tin epektasi ton agents me ta dika sas ergaleia. Ta prosormosmena ergaleia orizontai os in-process MCP servers - choris diacheirisi subprocess, choris diktyako overhead.
Paradigm: Ergaleio kairou
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); } }
Ta prosormosmena ergaleia akolouthoun tin convention onomasias mcp__{onoma_server}__{onoma_ergaleiou}. Mporeite na chrisimopoiisete wildcards sta allowedTools: to "mcp__weather__*" epitrepei ola ta ergaleia apo ton weather server.
Paradigm: Ergaleio erotimaton vaseon dedomenon
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), }, ], }; } );
Syndesi eksoterikou MCP servers
Pera apo ta in-process ergaleia, mporeite na syndethite me opoiodipote yparchi MCP server - tous idious servers pou doulevoun me to Claude Desktop, to Cursor kai allous 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__*"], }, })) { // ... }
Mporeite na syndiasete pollaplous MCP servers. O agent vlepei ola ta ergaleia apo olous tous syndedemenous servers kai ta chrisimopoiei opos chreiazetai.
Orchestration pollalon agents
Gia polyploka workflows, mporeite na orisete exeidikevmenous sub-agents stous opoious o gonikos agent anathei ergasies. Kathe sub-agent echei to diko tou prompt, ergaleia kai area estiasis.
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 }
Prostheste to "Agent" sta allowedTools tou gonikou agent gia na energopoiisete tin anathesi. Oi sub-agents trechoun me ta dika tous ergaleia kai den echoun prosvasi sta ergaleia tou gonea ektos an afto epitrapei rita.
Sessions kai synecheia
Oi agents mporoun na diatiroun context metaxy pollalon queries chrisimopoiontas sessions. Katagrapsite to session_id apo tin proti allilepidrasi kai perasete to sto resume gia epomenes erotiseis.
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
An den thelete na filoxenisete tin ypodomi tou agent monoi sas, to Claude Managed Agents (pou xekinise ton Aprilio 2026) parechei mia pliros diacherismeni yperisia cloud. I Anthropic trechei ta containers, diacheirizatai to scaling kai parechei streaming API.
I vasiki diafora: me to Agent SDK, trechete ton vrogcho agent stin diki sas ypodomi. Me ta Managed Agents, i Anthropic filoxeni kai trechei ton agent gia esenas. Epikinonite mesw enos API vasimenon se sessions kai lamvanete gegonota mesw Server-Sent Events.
Timologisi:
- Agent SDK: mono oi standard times token tou Claude API. Eseis diacheirizeste to hosting.
- Managed Agents: times token syn 0,08 USD ana ora session (chreosi ana millisecond).
Best practices gia paragogi
1. Panta apomononete
Pote min trechete agents me aperioristos adeies se michani paragogis. Chrisimopoiiste containers (Docker, Fly.io, Modal) i sandbox perivallonta (E2B, Vercel Sandbox).
2. Periorismos prosvasis ergaleion
Akolouthiste tin archi tis elachistis adeiodotisis. Enas agent pou dimiourgi anafores den chreiazetai Bash i Write.
// Too permissive allowedTools: ["Read", "Write", "Edit", "Bash", "Glob", "Grep"] // Better: only what's needed allowedTools: ["Read", "Glob", "Grep"]
3. Chrisimopoiiste hooks os asfalistikes diktyes
Ta hooks sas epitrepoun na parakolouthite kliseis ergaleion prin kai meta tin ekthelesi. Chrisimopoiiste ta gia logging, validation kai 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. Diacheiristite ta sfalata me charin
O vrogchos tou agent mporei na paraxei sfalata - apotyechies ergaleion, oria API, ypervasi tou context window. Panta elegchete tous typous minimaton.
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. Parakolouthiste ti chrisi token
Oi vrogchoi ton agents mporoun na katanalwsoun simantika tokens, eidika me megales vaseis kodika. To SDK perilamvanei aftomati sympiesi context, alla tha prepei na parakolouthite ti chrisi.
Symperasma
To Claude Agent SDK metatrepei ena LLM apo michani apantiseon se kati pou prosmoiazei se junior developer. Oi agents sas mporoun na diavazoun, na grafoun, na ektheloun, na epivevainoun kai na epanalmavanoun - to idio workflow pou akolouthei enas anthropos.
Xekiniste mikra: chtisteai enan agent me merika ensomatomona ergaleia. Meta prostheste prosormosmena MCP ergaleia gia ton diko sas tomea. Klimakosete se orchestration pollalon agents otan ta workflows sas apaitoun exeidikevsi.
O vrogchos tou agent einai o idios pou trofodotei to Claude Code. An mporei na chtisi logismiko, oi agents sas mporoun kai aftoi.
Lista elegchou gia xekinima:
- Egkatastiste to SDK (
npm install @anthropic-ai/claude-agent-sdk)- Oriste to
ANTHROPIC_API_KEYsto perivallon sas- Chtisteai enan aplo agent me ensomatomona ergaleia (Read, Glob, Grep)
- Prostheste ena prosormosmeno ergaleio mesw in-process MCP server
- Syndeste enan eksoteriko MCP server (GitHub, PostgreSQL, klp.)
- Ylopoiiste orchestration pollalon agents me sub-agents
- Rythiste ena sandbox perivallon gia paragogi
- Prostheste hooks gia logging kai asfalistikes diktyes