spinny:~/writing $ vim building-ai-agents-claude-agent-sdk.md
1~2Claude Agent SDK는 Claude Code를 구동하는 것과 동일한 에이전트 루프에 대한 프로그래밍 방식의 접근을 제공합니다. 에이전트는 파일 읽기, 셸 명령 실행, 웹 검색, 코드 편집, MCP 서버를 통한 외부 API 호출, 서브 에이전트 오케스트레이션 - 이 모든 것을 TypeScript 또는 Python 몇 줄로 수행할 수 있습니다.3~4표준 Anthropic Client SDK에서는 직접 도구 루프를 구축해야 하지만, Agent SDK는 도구 실행, 컨텍스트 관리, 재시도, 오케스트레이션을 내부적으로 처리합니다. 원하는 것을 설명하고 도구를 제공하면, 에이전트가 나머지를 알아서 처리합니다.5~6## 아키텍처7~8SDK는 간단한 루프를 따릅니다: **컨텍스트 수집, 액션 실행, 검증, 반복**.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~36핵심 진입점은 `query()`로, 에이전트가 작업하는 동안 메시지를 스트리밍하는 비동기 이터레이터를 반환합니다. 각 메시지는 에이전트가 무엇을 하고 있는지 알려줍니다: 추론 중, 도구 호출 중, 결과 수신 중, 또는 최종 출력 전달 중.37~38## 시작하기39~40### 설치41~42```bash43# TypeScript44npm install @anthropic-ai/claude-agent-sdk45~46# Python47pip install claude-agent-sdk48```49~50환경 변수에 `ANTHROPIC_API_KEY`로 Anthropic API 키를 설정해야 합니다.51~52### 첫 번째 에이전트53~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~74이게 전부입니다. 에이전트는 Glob으로 파일을 찾고, Grep으로 TODO 패턴을 검색하고, Read로 매칭 결과를 확인한 후 구조화된 요약을 반환합니다. 오케스트레이션 로직을 직접 작성할 필요가 없습니다 - SDK가 처리합니다.75~76### Python 버전77~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## 내장 도구92~93SDK에는 Claude Code에서 사용 가능한 것과 동일한 도구가 포함되어 있습니다:94~95| 도구 | 설명 |96|------|-------------|97| **Read** | 파일 내용 읽기 |98| **Write** | 새 파일 생성 |99| **Edit** | 기존 파일에 대한 대상 편집 |100| **Bash** | 셸 명령 실행 |101| **Glob** | 패턴으로 파일 찾기 |102| **Grep** | 정규 표현식으로 파일 내용 검색 |103| **WebSearch** | 웹 검색 |104| **WebFetch** | URL을 가져와 내용 반환 |105| **AskUserQuestion** | 사용자에게 입력 요청 |106~107`allowedTools`를 통해 에이전트가 사용할 수 있는 도구를 제어합니다. 목록에 없는 도구는 에이전트가 호출할 수 없습니다.108~109## 권한 모드110~111에이전트는 실제 시스템에서 실제 명령을 실행하므로 권한이 중요합니다.112~113| 모드 | 동작 | 사용 사례 |114|------|----------|----------|115| `default` | 커스텀 `canUseTool` 콜백이 호출마다 결정 | 세밀한 제어 |116| `acceptEdits` | 파일 작업 자동 승인, Bash는 프롬프트 | 개발 워크플로 |117| `dontAsk` | allowedTools에 없는 모든 것 거부 | 제한된 에이전트 |118| `bypassPermissions` | 모든 것을 자동 승인 | 신뢰할 수 있는 샌드박스 환경 |119| `auto` | 모델 분류기가 안전성 결정 | 균형 잡힌 자동화 |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~131프로덕션 환경에서는 항상 샌드박스화된 환경(컨테이너, VM)에서 에이전트를 실행하고, 에이전트가 작업을 수행할 수 있는 범위 내에서 가장 제한적인 권한 모드를 사용하세요.132~133## MCP로 커스텀 도구 구축하기134~135SDK의 진정한 힘은 자체 도구로 에이전트를 확장할 수 있다는 것입니다. 커스텀 도구는 인프로세스 MCP 서버로 정의됩니다 - 서브프로세스 관리도 네트워크 오버헤드도 필요 없습니다.136~137### 예시: 날씨 도구138~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~185커스텀 도구는 `mcp__{server_name}__{tool_name}` 명명 규칙을 따릅니다. `allowedTools`에서 와일드카드를 사용할 수 있습니다: `"mcp__weather__*"`는 weather 서버의 모든 도구를 허용합니다.186~187### 예시: 데이터베이스 쿼리 도구188~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## 외부 MCP 서버 연결218~219인프로세스 도구 외에도 기존 MCP 서버에 연결할 수 있습니다 - Claude Desktop, Cursor 및 기타 MCP 클라이언트에서 작동하는 동일한 서버입니다.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~239여러 MCP 서버를 결합할 수 있습니다. 에이전트는 연결된 모든 서버의 모든 도구를 인식하고 필요에 따라 사용합니다.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## 멀티 에이전트 오케스트레이션251~252복잡한 워크플로의 경우, 부모 에이전트가 작업을 위임하는 전문 서브 에이전트를 정의할 수 있습니다. 각 서브 에이전트는 자체 프롬프트, 도구, 전문 영역을 가집니다.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~283위임을 활성화하려면 부모의 `allowedTools`에 `"Agent"`를 포함시키세요. 서브 에이전트는 자체 도구로 실행되며, 명시적으로 부여되지 않는 한 부모의 도구에 접근할 수 없습니다.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## 세션과 연속성297~298에이전트는 세션을 사용하여 여러 쿼리에 걸쳐 컨텍스트를 유지할 수 있습니다. 첫 번째 상호작용에서 `session_id`를 캡처하고 후속 쿼리에서 `resume`에 전달합니다.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~325에이전트 인프라를 직접 호스팅하고 싶지 않다면, **Claude Managed Agents**(2026년 4월 출시)가 완전 관리형 클라우드 서비스를 제공합니다. Anthropic이 컨테이너를 실행하고, 스케일링을 처리하며, 스트리밍 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~343핵심 차이점: Agent SDK에서는 자체 인프라에서 에이전트 루프를 실행합니다. Managed Agents에서는 Anthropic이 에이전트를 호스팅하고 실행합니다. 세션 기반 API를 통해 상호작용하고 Server-Sent Events를 통해 이벤트를 수신합니다.344~345**가격:**346- **Agent SDK**: 표준 Claude API 토큰 요금만. 호스팅은 직접 처리합니다.347- **Managed Agents**: 토큰 요금에 세션 시간당 $0.08 추가(밀리초 단위 과금).348~349## 프로덕션 베스트 프랙티스350~351### 1. 항상 샌드박스화하기352~353프로덕션 머신에서 무제한 권한으로 에이전트를 실행하지 마세요. 컨테이너(Docker, Fly.io, Modal) 또는 샌드박스 환경(E2B, Vercel Sandbox)을 사용하세요.354~355### 2. 도구 접근 제한하기356~357최소 권한 원칙을 따르세요. 보고서를 생성하는 에이전트에는 `Bash`나 `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. Hook으로 가드레일 설정하기368~369Hook을 사용하면 도구 호출 실행 전후에 인터셉트할 수 있습니다. 로깅, 유효성 검사, 속도 제한에 활용하세요.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. 오류를 우아하게 처리하기391~392에이전트 루프는 오류를 생성할 수 있습니다 - 도구 실패, API 속도 제한, 컨텍스트 윈도우 오버플로. 항상 메시지 타입을 확인하세요.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. 토큰 사용량 모니터링하기413~414에이전트 루프는 특히 대규모 코드베이스에서 상당한 토큰을 소비할 수 있습니다. SDK에는 자동 컨텍스트 압축 기능이 포함되어 있지만, 여전히 사용량을 모니터링해야 합니다.415~416## 결론417~418Claude Agent SDK는 LLM을 질문 응답 머신에서 주니어 개발자에 가까운 존재로 변화시킵니다. 에이전트는 읽기, 쓰기, 실행, 검증, 반복이 가능합니다 - 사람이 따르는 것과 동일한 워크플로입니다.419~420작게 시작하세요: 몇 가지 내장 도구로 에이전트를 구축하세요. 그런 다음 특정 도메인에 맞는 커스텀 MCP 도구를 추가하세요. 워크플로에 전문화가 필요해지면 멀티 에이전트 오케스트레이션으로 확장하세요.421~422에이전트 루프는 Claude Code를 구동하는 것과 동일합니다. 그것이 소프트웨어를 만들 수 있다면, 여러분의 에이전트도 할 수 있습니다.423~424> **시작 체크리스트:**425>426> - [x] SDK 설치하기 (`npm install @anthropic-ai/claude-agent-sdk`)427> - [x] 환경 변수에 `ANTHROPIC_API_KEY` 설정하기428> - [x] 내장 도구(Read, Glob, Grep)로 간단한 에이전트 구축하기429> - [x] 인프로세스 MCP 서버로 커스텀 도구 추가하기430> - [x] 외부 MCP 서버(GitHub, PostgreSQL 등) 연결하기431> - [x] 서브 에이전트로 멀티 에이전트 오케스트레이션 구현하기432> - [x] 프로덕션용 샌드박스 환경 구축하기433> - [x] 로깅 및 가드레일용 Hook 추가하기434~
NORMAL · building-ai-agents-claude-agent-sdk.md [readonly]434 lines · :q to close