spinny:~/writing $ less building-ai-agents-claude-agent-sdk.md
12Il Claude Agent SDK ti offre accesso programmatico allo stesso agent loop che alimenta Claude Code. I tuoi agenti possono leggere file, eseguire comandi shell, cercare sul web, modificare codice, chiamare API esterne tramite server MCP e orchestrare sub-agenti - il tutto con poche righe di TypeScript o Python.34A differenza del Client SDK standard di Anthropic, dove devi costruire il tuo tool loop, l'Agent SDK gestisce internamente l'esecuzione dei tool, la gestione del contesto, i retry e l'orchestrazione. Tu descrivi cosa vuoi, fornisci gli strumenti, e l'agente si occupa del resto.56## Architettura78L'SDK segue un loop semplice: **raccogliere il contesto, agire, verificare, ripetere**.910```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]1819 subgraph "Built-in Tools"20 T1[Read / Write / Edit]21 T2[Bash / Terminal]22 T3[Glob / Grep]23 T4[WebSearch / WebFetch]24 end2526 subgraph "Custom Tools via MCP"27 M1[Your API]28 M2[Database]29 M3[Slack / GitHub / etc.]30 end3132 Tool --> T133 Tool --> M134```3536Il punto di ingresso principale e `query()`, che restituisce un iteratore asincrono che trasmette messaggi in streaming mentre l'agente lavora. Ogni messaggio ti dice cosa sta facendo l'agente: ragionamento, chiamata a un tool, ricezione di un risultato o consegna dell'output finale.3738## Per iniziare3940### Installazione4142```bash43# TypeScript44npm install @anthropic-ai/claude-agent-sdk4546# Python47pip install claude-agent-sdk48```4950Hai bisogno di una chiave API Anthropic impostata come `ANTHROPIC_API_KEY` nel tuo ambiente.5152### Il tuo primo agente5354```typescript55import { query } from "@anthropic-ai/claude-agent-sdk";5657const conversation = query({58 prompt: "Find all TODO comments in the codebase and create a summary",59 options: {60 allowedTools: ["Read", "Glob", "Grep"],61 },62});6364for 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```7374Tutto qui. L'agente usera Glob per trovare i file, Grep per cercare i pattern TODO, Read per ispezionare le corrispondenze e restituire un riassunto strutturato. Non devi scrivere la logica di orchestrazione - l'SDK se ne occupa.7576### Equivalente Python7778```python79from claude_agent_sdk import query8081async 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```9091## Tool integrati9293L'SDK include gli stessi tool disponibili in Claude Code:9495| Tool | Descrizione |96|------|-------------|97| **Read** | Legge il contenuto dei file |98| **Write** | Crea nuovi file |99| **Edit** | Apporta modifiche mirate a file esistenti |100| **Bash** | Esegue comandi shell |101| **Glob** | Trova file tramite pattern |102| **Grep** | Cerca nel contenuto dei file con regex |103| **WebSearch** | Effettua ricerche sul web |104| **WebFetch** | Scarica un URL e ne restituisce il contenuto |105| **AskUserQuestion** | Chiede un input all'utente |106107Puoi controllare quali tool l'agente puo utilizzare tramite `allowedTools`. Se un tool non e nella lista, l'agente non puo chiamarlo.108109## Modalita di permesso110111Dato che gli agenti eseguono comandi reali su sistemi reali, i permessi sono importanti.112113| Modalita | Comportamento | Caso d'uso |114|------|----------|----------|115| `default` | Un callback `canUseTool` personalizzato decide per ogni chiamata | Controllo granulare |116| `acceptEdits` | Approva automaticamente le operazioni sui file, chiede conferma per Bash | Workflow di sviluppo |117| `dontAsk` | Nega tutto cio che non e in allowedTools | Agenti con restrizioni |118| `bypassPermissions` | Approva tutto automaticamente | Ambienti sandbox affidabili |119| `auto` | Un classificatore del modello valuta la sicurezza | Automazione bilanciata |120121```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```130131Per l'uso in produzione, esegui sempre gli agenti in ambienti sandbox (container, VM) e usa la modalita di permesso piu restrittiva che consenta comunque all'agente di svolgere il proprio lavoro.132133## Creare tool personalizzati con MCP134135La vera potenza dell'SDK sta nell'estendere gli agenti con i tuoi strumenti. I tool personalizzati vengono definiti come server MCP in-process - nessuna gestione di sottoprocessi, nessun overhead di rete.136137### Esempio: tool meteo138139```typescript140import { tool, createSdkMcpServer, query } from "@anthropic-ai/claude-agent-sdk";141import { z } from "zod";142143const 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);165166const weatherServer = createSdkMcpServer({167 name: "weather",168 version: "1.0.0",169 tools: [getTemperature],170});171172for 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```184185I tool personalizzati seguono la convenzione di naming `mcp__{nome_server}__{nome_tool}`. Puoi usare i caratteri jolly in `allowedTools`: `"mcp__weather__*"` abilita tutti i tool del server meteo.186187### Esempio: tool per query al database188189```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 }203204 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```216217## Connettere server MCP esterni218219Oltre ai tool in-process, puoi connetterti a qualsiasi server MCP esistente - gli stessi server che funzionano con Claude Desktop, Cursor e altri client MCP.220221```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```238239Puoi combinare piu server MCP. L'agente vede tutti i tool di tutti i server connessi e li utilizza secondo necessita.240241```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```249250## Orchestrazione multi-agente251252Per workflow complessi, puoi definire sub-agenti specializzati a cui l'agente principale delega. Ogni sub-agente ha il proprio prompt, i propri tool e la propria area di competenza.253254```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```282283Includi `"Agent"` in `allowedTools` del genitore per abilitare la delega. I sub-agenti vengono eseguiti con i propri tool e non possono accedere a quelli del genitore a meno che non sia esplicitamente concesso.284285```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```295296## Sessioni e continuita297298Gli agenti possono mantenere il contesto tra piu query usando le sessioni. Cattura il `session_id` dalla prima interazione e passalo in `resume` per le query successive.299300```typescript301let sessionId: string | undefined;302303// 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}312313// 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```322323## Claude Managed Agents324325Se non vuoi gestire tu stesso l'infrastruttura degli agenti, i **Claude Managed Agents** (lanciati ad aprile 2026) offrono un servizio cloud completamente gestito. Anthropic si occupa dei container, dello scaling e mette a disposizione una API in streaming.326327```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 end334335 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```342343La differenza fondamentale: con l'Agent SDK, esegui l'agent loop nella tua infrastruttura. Con i Managed Agents, Anthropic ospita e gestisce l'agente per te. Interagisci tramite un'API basata su sessioni e ricevi eventi tramite Server-Sent Events.344345**Prezzi:**346- **Agent SDK**: solo le tariffe standard per token dell'API Claude. L'hosting e a tuo carico.347- **Managed Agents**: tariffe per token piu $0,08 per ora di sessione (fatturati al millisecondo).348349## Best practice per la produzione350351### 1. Usa sempre un sandbox352353Non eseguire mai agenti con permessi illimitati su una macchina di produzione. Usa container (Docker, Fly.io, Modal) o ambienti sandbox (E2B, Vercel Sandbox).354355### 2. Limita l'accesso ai tool356357Segui il principio del privilegio minimo. Un agente che genera report non ha bisogno di `Bash` o `Write`.358359```typescript360// Too permissive361allowedTools: ["Read", "Write", "Edit", "Bash", "Glob", "Grep"]362363// Better: only what's needed364allowedTools: ["Read", "Glob", "Grep"]365```366367### 3. Usa gli hook come guardrail368369Gli hook ti permettono di intercettare le chiamate ai tool prima e dopo l'esecuzione. Usali per logging, validazione e rate limiting.370371```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```389390### 4. Gestisci gli errori in modo appropriato391392L'agent loop puo produrre errori - fallimenti dei tool, limiti di rate dell'API, overflow della finestra di contesto. Controlla sempre i tipi di messaggio.393394```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```411412### 5. Monitora il consumo di token413414Gli agent loop possono consumare una quantita significativa di token, specialmente con codebase di grandi dimensioni. L'SDK include la compattazione automatica del contesto, ma dovresti comunque monitorare l'utilizzo.415416## Conclusione417418Il Claude Agent SDK trasforma un LLM da una macchina che risponde a domande in qualcosa di piu simile a uno sviluppatore junior. I tuoi agenti possono leggere, scrivere, eseguire, verificare e iterare - lo stesso workflow che segue un essere umano.419420Parti in piccolo: crea un agente con pochi tool integrati. Poi aggiungi tool MCP personalizzati per il tuo dominio specifico. Scala verso l'orchestrazione multi-agente quando i tuoi workflow richiedono specializzazione.421422L'agent loop e lo stesso che alimenta Claude Code. Se puo creare software, i tuoi agenti possono fare altrettanto.423424> **Checklist per iniziare:**425>426> - [x] Installa l'SDK (`npm install @anthropic-ai/claude-agent-sdk`)427> - [x] Imposta `ANTHROPIC_API_KEY` nel tuo ambiente428> - [x] Crea un agente semplice con i tool integrati (Read, Glob, Grep)429> - [x] Aggiungi un tool personalizzato tramite server MCP in-process430> - [x] Connetti un server MCP esterno (GitHub, PostgreSQL, ecc.)431> - [x] Implementa l'orchestrazione multi-agente con sub-agenti432> - [x] Configura un ambiente sandbox per la produzione433> - [x] Aggiungi hook per logging e guardrail434
:Creare agenti IA con il Claude Agent SDK: una guida praticalines 1-434 (END) — press q to close