Claude Agent SDK는 Claude Code를 구동하는 것과 동일한 에이전트 루프에 대한 프로그래밍 방식의 접근을 제공합니다. 에이전트는 파일 읽기, 셸 명령 실행, 웹 검색, 코드 편집, MCP 서버를 통한 외부 API 호출, 서브 에이전트 오케스트레이션 - 이 모든 것을 TypeScript 또는 Python 몇 줄로 수행할 수 있습니다.
표준 Anthropic Client SDK에서는 직접 도구 루프를 구축해야 하지만, Agent SDK는 도구 실행, 컨텍스트 관리, 재시도, 오케스트레이션을 내부적으로 처리합니다. 원하는 것을 설명하고 도구를 제공하면, 에이전트가 나머지를 알아서 처리합니다.
아키텍처
SDK는 간단한 루프를 따릅니다: 컨텍스트 수집, 액션 실행, 검증, 반복.
핵심 진입점은 query()로, 에이전트가 작업하는 동안 메시지를 스트리밍하는 비동기 이터레이터를 반환합니다. 각 메시지는 에이전트가 무엇을 하고 있는지 알려줍니다: 추론 중, 도구 호출 중, 결과 수신 중, 또는 최종 출력 전달 중.
시작하기
설치
# TypeScript npm install @anthropic-ai/claude-agent-sdk # Python pip install claude-agent-sdk
환경 변수에 ANTHROPIC_API_KEY로 Anthropic API 키를 설정해야 합니다.
첫 번째 에이전트
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); } }
이게 전부입니다. 에이전트는 Glob으로 파일을 찾고, Grep으로 TODO 패턴을 검색하고, Read로 매칭 결과를 확인한 후 구조화된 요약을 반환합니다. 오케스트레이션 로직을 직접 작성할 필요가 없습니다 - SDK가 처리합니다.
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}")
내장 도구
SDK에는 Claude Code에서 사용 가능한 것과 동일한 도구가 포함되어 있습니다:
| 도구 | 설명 |
|---|---|
| Read | 파일 내용 읽기 |
| Write | 새 파일 생성 |
| Edit | 기존 파일에 대한 대상 편집 |
| Bash | 셸 명령 실행 |
| Glob | 패턴으로 파일 찾기 |
| Grep | 정규 표현식으로 파일 내용 검색 |
| WebSearch | 웹 검색 |
| WebFetch | URL을 가져와 내용 반환 |
| AskUserQuestion | 사용자에게 입력 요청 |
allowedTools를 통해 에이전트가 사용할 수 있는 도구를 제어합니다. 목록에 없는 도구는 에이전트가 호출할 수 없습니다.
권한 모드
에이전트는 실제 시스템에서 실제 명령을 실행하므로 권한이 중요합니다.
| 모드 | 동작 | 사용 사례 |
|---|---|---|
default | 커스텀 canUseTool 콜백이 호출마다 결정 | 세밀한 제어 |
acceptEdits | 파일 작업 자동 승인, Bash는 프롬프트 | 개발 워크플로 |
dontAsk | allowedTools에 없는 모든 것 거부 | 제한된 에이전트 |
bypassPermissions | 모든 것을 자동 승인 | 신뢰할 수 있는 샌드박스 환경 |
auto | 모델 분류기가 안전성 결정 | 균형 잡힌 자동화 |
const conversation = query({ prompt: "Refactor the auth module to use JWT", options: { allowedTools: ["Read", "Edit", "Glob", "Grep", "Bash"], permissionMode: "acceptEdits", }, });
프로덕션 환경에서는 항상 샌드박스화된 환경(컨테이너, VM)에서 에이전트를 실행하고, 에이전트가 작업을 수행할 수 있는 범위 내에서 가장 제한적인 권한 모드를 사용하세요.
MCP로 커스텀 도구 구축하기
SDK의 진정한 힘은 자체 도구로 에이전트를 확장할 수 있다는 것입니다. 커스텀 도구는 인프로세스 MCP 서버로 정의됩니다 - 서브프로세스 관리도 네트워크 오버헤드도 필요 없습니다.
예시: 날씨 도구
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); } }
커스텀 도구는 mcp__{server_name}__{tool_name} 명명 규칙을 따릅니다. allowedTools에서 와일드카드를 사용할 수 있습니다: "mcp__weather__*"는 weather 서버의 모든 도구를 허용합니다.
예시: 데이터베이스 쿼리 도구
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), }, ], }; } );
외부 MCP 서버 연결
인프로세스 도구 외에도 기존 MCP 서버에 연결할 수 있습니다 - Claude Desktop, Cursor 및 기타 MCP 클라이언트에서 작동하는 동일한 서버입니다.
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__*"], }, })) { // ... }
여러 MCP 서버를 결합할 수 있습니다. 에이전트는 연결된 모든 서버의 모든 도구를 인식하고 필요에 따라 사용합니다.
멀티 에이전트 오케스트레이션
복잡한 워크플로의 경우, 부모 에이전트가 작업을 위임하는 전문 서브 에이전트를 정의할 수 있습니다. 각 서브 에이전트는 자체 프롬프트, 도구, 전문 영역을 가집니다.
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 }
위임을 활성화하려면 부모의 allowedTools에 "Agent"를 포함시키세요. 서브 에이전트는 자체 도구로 실행되며, 명시적으로 부여되지 않는 한 부모의 도구에 접근할 수 없습니다.
세션과 연속성
에이전트는 세션을 사용하여 여러 쿼리에 걸쳐 컨텍스트를 유지할 수 있습니다. 첫 번째 상호작용에서 session_id를 캡처하고 후속 쿼리에서 resume에 전달합니다.
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
에이전트 인프라를 직접 호스팅하고 싶지 않다면, Claude Managed Agents(2026년 4월 출시)가 완전 관리형 클라우드 서비스를 제공합니다. Anthropic이 컨테이너를 실행하고, 스케일링을 처리하며, 스트리밍 API를 제공합니다.
핵심 차이점: Agent SDK에서는 자체 인프라에서 에이전트 루프를 실행합니다. Managed Agents에서는 Anthropic이 에이전트를 호스팅하고 실행합니다. 세션 기반 API를 통해 상호작용하고 Server-Sent Events를 통해 이벤트를 수신합니다.
가격:
- Agent SDK: 표준 Claude API 토큰 요금만. 호스팅은 직접 처리합니다.
- Managed Agents: 토큰 요금에 세션 시간당 $0.08 추가(밀리초 단위 과금).
프로덕션 베스트 프랙티스
1. 항상 샌드박스화하기
프로덕션 머신에서 무제한 권한으로 에이전트를 실행하지 마세요. 컨테이너(Docker, Fly.io, Modal) 또는 샌드박스 환경(E2B, Vercel Sandbox)을 사용하세요.
2. 도구 접근 제한하기
최소 권한 원칙을 따르세요. 보고서를 생성하는 에이전트에는 Bash나 Write가 필요 없습니다.
// Too permissive allowedTools: ["Read", "Write", "Edit", "Bash", "Glob", "Grep"] // Better: only what's needed allowedTools: ["Read", "Glob", "Grep"]
3. Hook으로 가드레일 설정하기
Hook을 사용하면 도구 호출 실행 전후에 인터셉트할 수 있습니다. 로깅, 유효성 검사, 속도 제한에 활용하세요.
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. 오류를 우아하게 처리하기
에이전트 루프는 오류를 생성할 수 있습니다 - 도구 실패, API 속도 제한, 컨텍스트 윈도우 오버플로. 항상 메시지 타입을 확인하세요.
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. 토큰 사용량 모니터링하기
에이전트 루프는 특히 대규모 코드베이스에서 상당한 토큰을 소비할 수 있습니다. SDK에는 자동 컨텍스트 압축 기능이 포함되어 있지만, 여전히 사용량을 모니터링해야 합니다.
결론
Claude Agent SDK는 LLM을 질문 응답 머신에서 주니어 개발자에 가까운 존재로 변화시킵니다. 에이전트는 읽기, 쓰기, 실행, 검증, 반복이 가능합니다 - 사람이 따르는 것과 동일한 워크플로입니다.
작게 시작하세요: 몇 가지 내장 도구로 에이전트를 구축하세요. 그런 다음 특정 도메인에 맞는 커스텀 MCP 도구를 추가하세요. 워크플로에 전문화가 필요해지면 멀티 에이전트 오케스트레이션으로 확장하세요.
에이전트 루프는 Claude Code를 구동하는 것과 동일합니다. 그것이 소프트웨어를 만들 수 있다면, 여러분의 에이전트도 할 수 있습니다.
시작 체크리스트:
- SDK 설치하기 (
npm install @anthropic-ai/claude-agent-sdk)- 환경 변수에
ANTHROPIC_API_KEY설정하기- 내장 도구(Read, Glob, Grep)로 간단한 에이전트 구축하기
- 인프로세스 MCP 서버로 커스텀 도구 추가하기
- 외부 MCP 서버(GitHub, PostgreSQL 등) 연결하기
- 서브 에이전트로 멀티 에이전트 오케스트레이션 구현하기
- 프로덕션용 샌드박스 환경 구축하기
- 로깅 및 가드레일용 Hook 추가하기