Claude Agent SDK: Python & TypeScript
Python과 TypeScript에서 Claude Agent SDK로 에이전트를 만들어 보세요. 공식 패키지 이름, query(), ClaudeSDKClient, QCode를 통한 실행 방법을 다뤄요 (2026).
API 키가 필요하신가요? 회원가입 →엔드포인트 & Base URL →
이 페이지 목차
최종 확인: 2026-10-20 · 📄 공식 문서 기준 (Claude Agent SDK 개요, Python 및 TypeScript 레퍼런스, 2026-10-20 확인)
Claude Agent SDK는 Claude Code를 라이브러리로 사용하기 위한 Anthropic의 공식 패키지예요. Python은 claude-agent-sdk, TypeScript는 @anthropic-ai/claude-agent-sdk를 설치한 뒤 query()를 호출하면 돼요. Claude Code 바이너리를 실행하는 라이브러리로, 기본 제공 도구, 권한, 세션, 훅을 갖추고 있어서 Claude Code의 기능을 직접 만든 애플리케이션에 내장할 수 있어요 (2026-10-20 확인).
Claude Agent SDK란?¶
Claude Agent SDK는 다음을 할 수 있는 애플리케이션을 만들도록 돕는 구성 요소를 제공해요:
- 자연어 지시를 이해하고 복잡한 작업을 실행
- 도구 사용 (검색, 코드 실행, 파일 작업 등)
- 대화 컨텍스트 유지로 멀티턴 상호작용 지원
- 외부 서비스 연결 (MCP 서버 경유)
Agent SDK 설치¶
Python¶
pip install claude-agent-sdk
TypeScript¶
npm install @anthropic-ai/claude-agent-sdk
SDK 버전은 함께 번들되는 Claude Code 버전을 따라가요. 공식 예시에서 SDK v0.3.191은 Claude Code v2.1.191을 번들해요 (2026-10-20 확인). 이 문서는 Claude Code 2.1.330을 기준으로 해요 (설치 가이드 참고). 현재 릴리스에 번들된 버전은 SDK 릴리스 노트에서 확인하세요.
query()로 빠르게 시작하기¶
Python¶
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions
async def main():
options = ClaudeAgentOptions()
async for message in query(prompt="Create a Python web server", options=options):
print(message)
asyncio.run(main())
TypeScript¶
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "Create a Python web server",
options: {}
})) {
console.log(message);
}
query()는 기본적으로 새 세션을 만들어요. 같은 세션에서 여러 번 주고받으려면 Python에서는 ClaudeSDKClient를 사용하세요 (2026-10-20 확인).
QCode 설정¶
Python의 ClaudeAgentOptions(env={...})는 상속된 프로세스 환경 위에 변수를 병합해요:
from claude_agent_sdk import ClaudeAgentOptions
options = ClaudeAgentOptions(
env={
"ANTHROPIC_BASE_URL": "https://api.qcode.cc/api", # switch to https://asia.qcode.cc/api if mainland China access is unstable
"ANTHROPIC_AUTH_TOKEN": "cr_your_api_key",
}
)
TypeScript에서는 options.env가 process.env를 대체하므로, PATH처럼 상속된 변수를 유지하려면 ...process.env를 펼쳐 넣으세요:
const options = { env: { ...process.env, ANTHROPIC_BASE_URL: "https://api.qcode.cc/api", ANTHROPIC_AUTH_TOKEN: "cr_..." } };
API 키로 인증하세요. 공식 문서에 따르면 서드파티 개발자는 SDK로 만든 제품에 claude.ai 로그인을 제공할 수 없어요 (2026-10-20 확인). QCode는 토큰 단위로 과금하며, 모델별 요금은 qcode.cc/models에 나와 있어요.
Agent SDK vs Claude Code CLI vs Client SDK¶
| 항목 | Agent SDK | Claude Code CLI | Client SDK |
|---|---|---|---|
| 형태 | Python / TypeScript 라이브러리 | 터미널 인터페이스 | anthropic / @anthropic-ai/sdk |
| 실행 방식 | Claude Code 바이너리를 실행하는 라이브러리 | 터미널에서 대화형으로 사용 | Messages API를 직접 호출 |
| 기본 제공 | 도구, 권한, 세션, 훅 | 도구, 권한, 세션, 훅 | 도구 호출을 직접 코드로 처리 |
| 사용 용도 | 직접 만든 애플리케이션에 Claude Code 내장 | 일상적인 대화형 개발 | Messages API 직접 호출 |
Client SDK: Messages API 직접 호출¶
아래 예시는 Agent SDK가 아니라 Client SDK(anthropic / @anthropic-ai/sdk)를 사용해요. Messages API만 직접 호출하면 될 때 사용하세요.
Client SDK 설치¶
Python SDK¶
pip install anthropic
TypeScript SDK¶
npm install @anthropic-ai/sdk
기본 메시지 호출¶
from anthropic import Anthropic
# Via QCode.cc API
client = Anthropic(
base_url="https://api.qcode.cc/api",
api_key="cr_your_api_key"
)
message = client.messages.create(
model="claude-opus-5-5",
max_tokens=4096,
messages=[
{"role": "user", "content": "Explain what a RESTful API is"}
]
)
print(message.content[0].text)
스트리밍 응답¶
with client.messages.stream(
model="claude-opus-5-5",
max_tokens=1024,
messages=[
{"role": "user", "content": "Write a Python quicksort function"}
]
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
도구 사용¶
도구 사용은 에이전트의 핵심 기능으로, 모델이 외부 도구를 호출할 수 있게 해요.
도구 정의¶
from anthropic import Anthropic
client = Anthropic(
base_url="https://api.qcode.cc/api",
api_key="cr_your_api_key"
)
# Define search tool
tools = [
{
"name": "search_web",
"description": "Search the web for information",
"input_schema": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Search keywords"
}
},
"required": ["query"]
}
},
{
"name": "calculate",
"description": "Perform mathematical calculations",
"input_schema": {
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": "Mathematical expression, e.g., '2 + 3 * 4'"
}
},
"required": ["expression"]
}
}
]
# Send message with tools
message = client.messages.create(
model="claude-opus-5-5",
max_tokens=4096,
messages=[
{"role": "user", "content": "Calculate (15 + 25) * 2 and search for what this means"}
],
tools=tools
)
# Define a safe calculator before processing tool calls:
# tool arguments returned by the model can also be steered by prompt injection —
# never execute them with eval().
import ast
import operator
_OPS = {ast.Add: operator.add, ast.Sub: operator.sub,
ast.Mult: operator.mul, ast.Div: operator.truediv}
def safe_calculate(expression: str):
"""Allow only numbers and + - * / so no arbitrary code can run."""
def _eval(node):
if isinstance(node, ast.Expression):
return _eval(node.body)
if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
return node.value
if isinstance(node, ast.BinOp) and type(node.op) in _OPS:
return _OPS[type(node.op)](_eval(node.left), _eval(node.right))
raise ValueError("only numbers and + - * / are supported")
return _eval(ast.parse(expression, mode="eval"))
# Process tool calls
for content in message.content:
if content.type == "text":
print(content.text)
elif content.type == "tool_use":
print(f"Calling tool: {content.name}")
print(f"Parameters: {content.input}")
# Simulate executing the tool
if content.name == "calculate":
result = safe_calculate(content.input["expression"])
tool_result = str(result)
elif content.name == "search_web":
tool_result = f"Results for '{content.input['query']}'..."
# Send the result back to the model
message = client.messages.create(
model="claude-opus-5-5",
max_tokens=4096,
messages=[
{"role": "user", "content": "Calculate (15 + 25) * 2 and search for what this means"},
message,
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": content.id,
"content": tool_result
}
]
}
],
tools=tools
)
스트리밍 도구 호출¶
with client.messages.stream(
model="claude-opus-5-5",
max_tokens=4096,
messages=[
{"role": "user", "content": "Create a file named hello.py that prints 'Hello, World!'"}
],
tools=[
{
"name": "write_file",
"description": "Write content to a file",
"input_schema": {
"type": "object",
"properties": {
"filename": {"type": "string"},
"content": {"type": "string"}
},
"required": ["filename", "content"]
}
}
]
) as stream:
for event in stream:
if event.type == "content_block_delta":
if event.delta.type == "text_delta":
print(event.delta.text, end="", flush=True)
elif event.delta.type == "input_json_delta":
print(event.delta.partial_json, end="", flush=True)
프롬프트 캐싱¶
프롬프트 캐싱은 긴 대화의 비용을 크게 줄일 수 있어요:
# System prompt (will be cached)
system_prompt = """You are a professional code review assistant.
Your responsibilities:
1. Check code security
2. Identify performance issues
3. Verify code standards
4. Provide improvement suggestions
"""
# Use cache_control to mark cacheable content
message = client.messages.create(
model="claude-opus-5-5",
max_tokens=4096,
system=[
{
"type": "text",
"text": system_prompt,
"cache_control": {"type": "ephemeral"}
}
],
messages=[
{"role": "user", "content": "Review @src/auth/login.ts"}
]
)
에이전트 구축 예시¶
from anthropic import Anthropic
from typing import List
class CodeReviewAgent:
def __init__(self, api_key: str):
self.client = Anthropic(
base_url="https://api.qcode.cc/api",
api_key=api_key
)
self.system_prompt = """You are a professional code review assistant.
Focus on: security, performance, readability, best practices.
Output for each review: issue list, severity, fix suggestions."""
def review(self, code_snippet: str) -> str:
message = self.client.messages.create(
model="claude-opus-5-5",
max_tokens=4096,
system=self.system_prompt,
messages=[
{"role": "user", "content": f"Review this code:\n\n{code_snippet}"}
]
)
return message.content[0].text
# Usage
agent = CodeReviewAgent("cr_your_api_key")
result = agent.review("SELECT * FROM users WHERE id = " + user_id)
Client SDK용 QCode.cc 설정¶
import os
# Method 1: Environment variable
os.environ["ANTHROPIC_BASE_URL"] = "https://api.qcode.cc/api"
os.environ["ANTHROPIC_AUTH_TOKEN"] = "cr_your_key"
client = Anthropic() # Auto-reads environment variables
# Method 2: Asia node (recommended for mainland China)
client = Anthropic(
base_url="https://api.qcode.cc/api",
api_key="cr_your_key"
)
다음 단계¶
QCode 시작하기
Claude Code, Codex 등에 API 키 하나를 쓰세요. 토큰 단위로 과금하며 모델별 가격은 qcode.cc/models에 있어요