spinny:~/writing $ vim building-ai-agents-claude-agent-sdk.md
1~2Claude Agent SDK daiot programmnyi dostup k tomu zhe tsiklu agenta, kotoryi stoit za Claude Code. Vashi agenty mogut chitat faily, vypolniat komandy obolochki, iskat v internete, redaktirovat kod, vyzyvat vneshnie API cherez MCP-servery i orkestirovat sub-agentov - vsio eto iz neskolkikh strok TypeScript ili Python.3~4V otlichie ot standartnogo Anthropic Client SDK, gde vy sami stroite tsikl instrumentov, Agent SDK vnutrenne obrabatyvaet vypolnenie instrumentov, upravlenie kontekstom, povtornye popytki i orkestratsiiu. Vy opisyvaete to, chto khotite, predostavliaete instrumenty, a agent razbiraitsia s ostalnym.5~6## Arkhitektura7~8SDK sleduet prostomu tsiklu: **soberi kontekst, vypolni deistvie, prover, povtori**.9~10```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]18~19 subgraph "Built-in Tools"20 T1[Read / Write / Edit]21 T2[Bash / Terminal]22 T3[Glob / Grep]23 T4[WebSearch / WebFetch]24 end25~26 subgraph "Custom Tools via MCP"27 M1[Your API]28 M2[Database]29 M3[Slack / GitHub / etc.]30 end31~32 Tool --> T133 Tool --> M134```35~36Osnovnaia tochka vkhoda - `query()`, kotoraia vozvrashchaet asinkhronny iterator, transliriuiushchii soobshcheniia po mere raboty agenta. Kazhdoe soobshchenie govori vam, chto delaet agent: razmyshliaet, vyzyvaet instrument, poluchaet rezultat ili dostavliaet itogovyi vyvod.37~38## Nachalo raboty39~40### Ustanovka41~42```bash43# TypeScript44npm install @anthropic-ai/claude-agent-sdk45~46# Python47pip install claude-agent-sdk48```49~50Vam nuzhen API-kliuch Anthropic, ustanovlenny kak `ANTHROPIC_API_KEY` v vashem okruzhenii.51~52### Vash pervyi agent53~54```typescript55import { query } from "@anthropic-ai/claude-agent-sdk";56~57const conversation = query({58 prompt: "Find all TODO comments in the codebase and create a summary",59 options: {60 allowedTools: ["Read", "Glob", "Grep"],61 },62});63~64for 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```73~74Vot i vsio. Agent ispolzuet Glob dlia poiska failov, Grep dlia poiska patternov TODO, Read dlia izucheniia sovpadenii i verniot strukturirovannoe reziume. Vy ne pishete logiku orkestratsii - SDK berot eto na sebia.75~76### Ekvivalent na Python77~78```python79from claude_agent_sdk import query80~81async 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```90~91## Vstroennye instrumenty92~93SDK postavliaetsia s temi zhe instrumentami, kotorye dostupny v Claude Code:94~95| Instrument | Opisanie |96|------|-------------|97| **Read** | Chtenie soderzhimogo failov |98| **Write** | Sozdanie novykh failov |99| **Edit** | Tselevye pravki v sushchestvuiushchikh failakh |100| **Bash** | Vypolnenie komand obolochki |101| **Glob** | Poisk failov po patternu |102| **Grep** | Poisk v soderzhimom failov s pomoshchiu regex |103| **WebSearch** | Poisk v internete |104| **WebFetch** | Zagruzka URL i vozvrat ego soderzhimogo |105| **AskUserQuestion** | Zapros vvoda ot polzovatelia |106~107Vy kontroliruete, kakie instrumenty agent mozhet ispolzovat, cherez `allowedTools`. Esli instrumenta net v spiske, agent ne mozhet ego vyzvat.108~109## Rezhimy razreshenii110~111Poskolku agenty vypolniaiut nastoyashchie komandy na nastoyashchikh sistemakh, razresheniia vazhny.112~113| Rezhim | Povedenie | Primenenie |114|------|----------|----------|115| `default` | Polzovatelsky callback `canUseTool` reshaet pri kazhdom vyzove | Tonkaia nastroika |116| `acceptEdits` | Avtoodobrenie failovykh operatsii, zapros dlia Bash | Rabochie protsessy razrabotki |117| `dontAsk` | Otkaz vo vsem, chto ne v allowedTools | Ogranichennye agenty |118| `bypassPermissions` | Avtomaticheskoe odobrenie vsego | Doverennye sandbox-sredy |119| `auto` | Klassifikator modeli reshaet o bezopasnosti | Sbalansirovannaia avtomatizatsiia |120~121```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```130~131Dlia produktsionnogo ispolzovaniia vsegda zapuskaite agentov v izolirovannykh sredakh (konteinery, virtualnye mashiny) i ispolzuyte samyi strogiiy rezhim razreshenii, kotoryi vsio eshchio pozvoliaet agentu vypolniat svoiu rabotu.132~133## Sozdanie polzovatelskikh instrumentov s MCP134~135Nastoiashchaia sila SDK zakliuchaetsia v rasshirenii agentov vashimi sobstvennymi instrumentami. Polzovatelskie instrumenty opredeliaiutsia kak in-process MCP-servery - bez upravleniia podprotsessami, bez setevykh nakladnykh raskhodov.136~137### Primer: Instrument pogody138~139```typescript140import { tool, createSdkMcpServer, query } from "@anthropic-ai/claude-agent-sdk";141import { z } from "zod";142~143const 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);165~166const weatherServer = createSdkMcpServer({167 name: "weather",168 version: "1.0.0",169 tools: [getTemperature],170});171~172for 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```184~185Polzovatelskie instrumenty sleduiut konventsii imenovaniia `mcp__{imia_servera}__{imia_instrumenta}`. Vy mozhete ispolzovat podstanovochnye znaki v `allowedTools`: `"mcp__weather__*"` razreshaet vse instrumenty s servera pogody.186~187### Primer: Instrument zaprosov k baze dannykh188~189```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 }203~204 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```216~217## Podkliuchenie vneshnikh MCP-serverov218~219Pomimo in-process instrumentov, vy mozhete podkliuchatsia k liubomu sushchestvuiushchemu MCP-serveru - tem zhe serveram, kotorye rabotaiut s Claude Desktop, Cursor i drugimi MCP-klientami.220~221```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```238~239Vy mozhete kombinirovat neskolko MCP-serverov. Agent vidit vse instrumenty so vsekh podkliuchennykh serverov i ispolzuet ikh po mere neobkhodimosti.240~241```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```249~250## Orkestratsiia neskolkikh agentov251~252Dlia slozhnykh rabochikh protsessov vy mozhete opredelit spetsializirovannykh sub-agentov, kotorym roditelsky agent delegiruet zadachi. U kazhdogo sub-agenta svoi prompt, instrumenty i oblast fokusa.253~254```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```282~283Dobavte `"Agent"` v `allowedTools` roditelskogo agenta dlia vkliucheniia delegirovaniia. Sub-agenty rabotaiut so svoimi instrumentami i ne imeiut dostupa k instrumentam roditelia, esli eto ne predostavleno iavno.284~285```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```295~296## Sessii i nepreryvnost297~298Agenty mogut sokhraniat kontekst mezhdu neskolkimi zaprosami s pomoshchiu sessii. Zakhvatite `session_id` iz pervogo vzaimodeistviia i peredaite ego v `resume` dlia poslesuiushchikh zaprosov.299~300```typescript301let sessionId: string | undefined;302~303// 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}312~313// 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```322~323## Claude Managed Agents324~325Esli vy ne khotite razvorachivat infrastrukturu agenta samostoiatelno, **Claude Managed Agents** (zapushcheny v aprele 2026) predostavliaet polnostiu upravliaemyi oblachny servis. Anthropic zapuskaet konteinery, obrabatyvaet masshtabirovanie i predostavliaet streaming API.326~327```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 end334~335 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```342~343Kliuchevoe razlichie: s Agent SDK vy zapuskaete tsikl agenta v svoei sobstvennoi infrastrukture. S Managed Agents Anthropic razmeshshaet i zapuskaet agenta za vas. Vy vzaimodeistuvete cherez API na osnove sessii i poluchaete sobytiia cherez Server-Sent Events.344~345**Tseny:**346- **Agent SDK**: tolko standartnye tarify na tokeny Claude API. Khosting na vashei storone.347- **Managed Agents**: tarify na tokeny plius 0,08 USD za chas sessii (tarifikatsiia pomillisekundno).348~349## Luchshie praktiki dlia produktsii350~351### 1. Vsegda izoliruyte352~353Nikogda ne zapuskaite agentov s neogranichennymi razresheniiami na produktsionnoi mashine. Ispolzuite konteinery (Docker, Fly.io, Modal) ili izolirovannye sredy (E2B, Vercel Sandbox).354~355### 2. Ogranichivaite dostup k instrumentam356~357Sleduyte printsipu naimenshikh privilegii. Agentu, generiruiushchemu otchioty, ne nuzhny `Bash` ili `Write`.358~359```typescript360// Too permissive361allowedTools: ["Read", "Write", "Edit", "Bash", "Glob", "Grep"]362~363// Better: only what's needed364allowedTools: ["Read", "Glob", "Grep"]365```366~367### 3. Ispolzuyte hooks dlia zashchitnykh ograzhdenii368~369Hooks pozvoliaiut perekhvatyvat vyzovy instrumentov do i posle vypolneniia. Ispolzuyte ikh dlia logirovaniia, validatsii i ogranicheniia chastoty.370~371```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```389~390### 4. Obrabatyvyte oshibki akkuratno391~392Tsikl agenta mozhet generirovat oshibki - sboi instrumentov, limity API, perepolnenie kontekstnogo okna. Vsegda proveryaite tipy soobshchenii.393~394```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```411~412### 5. Monitorte ispolzovanie tokenov413~414Tsikly agentov mogut potrebliat znachitelnoe kolichestvo tokenov, osobenno s bolshimi bazami koda. SDK vkliuchaet avtomaticheskuiu kompaktsiiu konteksta, no vy vsio ravno dolzhny monitorit ispolzovanie.415~416## Zakliuchenie417~418Claude Agent SDK prevrashchaet LLM iz mashiny dlia otvetov na voprosy v chto-to blizhe k junior-razrabotchiku. Vashi agenty mogut chitat, pisat, vypolniat, proveriat i iteirovat - tot zhe workflow, kotoromu sleduet chelovek.419~420Nachinte s malogo: sozdaite agenta s neskolkimi vstroennymi instrumentami. Zatem dobavte polzovatelskie MCP-instrumenty dlia vashei konkretnoi oblasti. Masshtabiruyte do orkestratsii neskolkikh agentov, kogda vashi protsessy trebuiut spetsializatsii.421~422Tsikl agenta - tot zhe, kotoryi stoit za Claude Code. Esli on mozhet sozdavat programmnoe obespechenie, vashi agenty toge smogut.423~424> **Chek-list dlia nachala:**425>426> - [x] Ustanovite SDK (`npm install @anthropic-ai/claude-agent-sdk`)427> - [x] Ustanovite `ANTHROPIC_API_KEY` v vashem okruzhenii428> - [x] Sozdaite prostogo agenta so vstroennymi instrumentami (Read, Glob, Grep)429> - [x] Dobavte polzovatelsky instrument cherez in-process MCP-server430> - [x] Podkliuchite vneshni MCP-server (GitHub, PostgreSQL, i t.d.)431> - [x] Realizuyte orkestratsiiu neskolkikh agentov s sub-agentami432> - [x] Nastroite izolirovannuiu sredu dlia produktsii433> - [x] Dobavte hooks dlia logirovaniia i zashchitnykh ograzhdenii434~
NORMAL · building-ai-agents-claude-agent-sdk.md [readonly]434 lines · :q to close