Claude Agent SDK, Claude Code'u calistiran ayni ajan dongusune programatik erisim saglar. Ajanlariniz dosyalari okuyabilir, shell komutlarini calistirabilir, web'de arama yapabilir, kod duzenleyebilir, MCP sunuculari uzerinden harici API'leri cagirabilir ve alt ajanlari orkestre edebilir - hepsi birkaç satir TypeScript veya Python ile.
Kendi arac dongunuzu olusturdugumuz standart Anthropic Client SDK'nin aksine, Agent SDK arac calistirma, context yonetimi, yeniden denemeler ve orkestrasyonu dahili olarak yonetir. Ne istediginizi tanimlarsiniz, araclari saglarsiniz ve ajan gerisini halleder.
Mimari
SDK basit bir donguyu takip eder: context topla, harekete gec, dogrula, tekrarla.
Ana giris noktasi query() fonksiyonudur; bu fonksiyon ajan calisirken mesajlari stream eden bir async iterator dondurur. Her mesaj ajanin ne yaptigini soyler: muhakeme, arac cagrisi, sonuc alma veya nihai ciktiyi sunma.
Baslarken
Kurulum
# TypeScript npm install @anthropic-ai/claude-agent-sdk # Python pip install claude-agent-sdk
Ortaminizda ANTHROPIC_API_KEY olarak bir Anthropic API anahtari ayarlamaniz gerekir.
Ilk Ajaniniz
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); } }
Hepsi bu kadar. Ajan dosyalari bulmak icin Glob, TODO kaliplarini aramak icin Grep, eslesen dosyalari incelemek icin Read kullanacak ve yapilandirilmis bir ozet dondurecektir. Orkestrasyon mantigi yazmak zorunda degilsiniz - SDK bunu halleder.
Python Karsiligi
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}")
Yerlesik Araclar
SDK, Claude Code'da bulunan ayni araclarla gelir:
| Arac | Aciklama |
|---|---|
| Read | Dosya icerigini oku |
| Write | Yeni dosyalar olustur |
| Edit | Mevcut dosyalarda hedefli duzenlemeler yap |
| Bash | Shell komutlarini calistir |
| Glob | Kaliba gore dosya bul |
| Grep | Regex ile dosya iceriginde ara |
| WebSearch | Web'de ara |
| WebFetch | Bir URL'yi getir ve icerigini dondur |
| AskUserQuestion | Kullanicidan girdi iste |
Ajanin hangi araclari kullanabilecegini allowedTools ile kontrol edersiniz. Bir arac listede yoksa, ajan onu cagiramaz.
Izin Modlari
Ajanlar gercek sistemlerde gercek komutlar calistirdigindan, izinler onemlidir.
| Mod | Davranis | Kullanim Alani |
|---|---|---|
default | Ozel canUseTool callback'i her cagri icin karar verir | Ince ayar kontrolu |
acceptEdits | Dosya islemlerini otomatik onayla, Bash icin sor | Gelistirme is akislari |
dontAsk | allowedTools'da olmayanlarini reddet | Kisitli ajanlar |
bypassPermissions | Her seyi otomatik onayla | Guvenilir sandbox ortamlari |
auto | Model siniflandirici guvenlik kararini verir | Dengeli otomasyon |
const conversation = query({ prompt: "Refactor the auth module to use JWT", options: { allowedTools: ["Read", "Edit", "Glob", "Grep", "Bash"], permissionMode: "acceptEdits", }, });
Uretim kullanimi icin, ajanlari her zaman sandbox ortamlarinda (konteynerler, VM'ler) calistirin ve ajanin isini yapmasina izin veren en kisitlayici izin modunu kullanin.
MCP ile Ozel Araclar Olusturma
SDK'nin gercek gucu, ajanlari kendi araclarinizla genisletmekten gelir. Ozel araclar islem ici MCP sunuculari olarak tanimlanir - alt islem yonetimi yok, ag yuku yok.
Ornek: Hava Durumu Araci
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); } }
Ozel araclar mcp__{server_name}__{tool_name} adlandirma kuralini takip eder. allowedTools'da joker karakter kullanabilirsiniz: "mcp__weather__*" hava durumu sunucusundaki tum araclara izin verir.
Ornek: Veritabani Sorgu Araci
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), }, ], }; } );
Harici MCP Sunucularina Baglanma
Islem ici araclarin otesinde, mevcut herhangi bir MCP sunucusuna baglanabilirsiniz - Claude Desktop, Cursor ve diger MCP istemcileriyle calisan ayni sunucular.
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__*"], }, })) { // ... }
Birden fazla MCP sunucusunu birlestirebilirsiniz. Ajan bagli tum sunuculardaki tum araclari gorur ve gerektiginde kullanir.
Coklu Ajan Orkestrasyonu
Karmasik is akislari icin, ana ajanin gorev devrettigi uzmanlasmis alt ajanlar tanimlayabilirsiniz. Her alt ajanin kendi prompt'u, araclari ve odak alani vardir.
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 }
Gorev devrini etkinlestirmek icin ana ajanin allowedTools listesine "Agent" ekleyin. Alt ajanlar kendi araclariyla calisir ve acikca izin verilmedikce ana ajanin araclarina erisemez.
Oturumlar ve Sureklilik
Ajanlar oturumlar kullanarak birden fazla sorgu boyunca context'i koruyabilir. Ilk etkilesimden session_id'yi yakalayin ve sonraki sorgularda resume ile iletin.
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
Ajan altyapisini kendiniz barindirmak istemiyorsaniz, Claude Managed Agents (Nisan 2026'da piyasaya suruldu) tamamen yonetilen bir bulut hizmeti sunar. Anthropic konteynerleri calistirir, olceklendirmeyi yonetir ve bir streaming API saglar.
Temel fark: Agent SDK ile ajan dongusunu kendi altyapinizda calistirirsiniz. Managed Agents ile Anthropic ajaninizi sizin icin barindirir ve calistirir. Oturum tabanli bir API uzerinden etkilesim kurar ve Server-Sent Events araciligiyla olaylar alirsiniz.
Fiyatlandirma:
- Agent SDK: yalnizca standart Claude API token ucretleri. Barindirmayi siz yonetirsiniz.
- Managed Agents: token ucretleri arti oturum saati basina $0.08 (milisaniye bazinda faturalandirilir).
Uretim En Iyi Uygulamalari
1. Her Zaman Sandbox Kullanin
Uretim makinesinde asla sinirlandirilmamis izinlerle ajan calistirmayin. Konteynerler (Docker, Fly.io, Modal) veya sandbox ortamlari (E2B, Vercel Sandbox) kullanin.
2. Arac Erisimini Sinirlandir
En az yetki ilkesini takip edin. Rapor ureten bir ajanin Bash veya Write'a ihtiyaci yoktur.
// Too permissive allowedTools: ["Read", "Write", "Edit", "Bash", "Glob", "Grep"] // Better: only what's needed allowedTools: ["Read", "Glob", "Grep"]
3. Koruma Kalipari Icin Hooks Kullanin
Hooks, calistirmadan once ve sonra arac cagrilarini yakalmanizi saglar. Bunlari loglama, dogrulama ve hiz sinirlamasi icin kullanin.
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. Hatalari Duzgun Sekilde Ele Alin
Ajan dongusu hatalar uretebilir - arac hatalari, API hiz sinirlari, context penceresi tasmasi. Her zaman mesaj tiplerini kontrol edin.
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 Kullanimini Izleyin
Ajan donguleri ozellikle buyuk kod tabanlariyla onemli miktarda token tuketebilir. SDK otomatik context sikistirma icerir, ancak yine de kullanimi izlemelisiniz.
Sonuc
Claude Agent SDK, bir LLM'yi soru-cevap makinesinden bir junior gelistiriciye daha yakin bir seye donusturur. Ajanlariniz okuyabilir, yazabilir, calistirabilir, dogrulayabilir ve tekrarlayabilir - bir insanin takip ettigi ayni is akisi.
Kucukten baslayin: birkaç yerlesik aracla bir ajan olusturun. Ardindan kendi alaniniz icin ozel MCP araclari ekleyin. Is akislariniz uzmanlasma gerektirdiginde coklu ajan orkestrasyonuna olcekleyin.
Ajan dongusu, Claude Code'u calistiran aynidir. O yazilim gelistirebiliyorsa, ajanlariniz da gelistirebilir.
Baslangic Kontrol Listesi:
- SDK'yi kurun (
npm install @anthropic-ai/claude-agent-sdk)- Ortaminizda
ANTHROPIC_API_KEYayarlayin- Yerlesik araclarla (Read, Glob, Grep) basit bir ajan olusturun
- Islem ici MCP sunucusu araciligiyla ozel bir arac ekleyin
- Harici bir MCP sunucusu (GitHub, PostgreSQL, vb.) baglayin
- Alt ajanlarla coklu ajan orkestrasyonu uygulayin
- Uretim icin sandbox ortami kurun
- Loglama ve koruma kaliplari icin hooks ekleyin