43 KiB
Claude Agent SDK - Documentație Completă
Cuprins
- Overview
- Ce este Claude Agent SDK
- Instalare și Setup
- Arhitectură și Concepte Cheie
- Features Principale
- Cazuri de Utilizare
- Exemple de Cod
- Integrări Posibile
- Monitoring și Debugging
- Best Practices
- Resurse și Referințe
Overview
Claude Agent SDK este SDK-ul oficial de la Anthropic care permite dezvoltatorilor să construiască agenți AI custom folosind aceeași arhitectură și tooling care stau la baza Claude Code.
Insight Principal
Claude Code nu este doar pentru coding! Este un "agent harness" puternic care poate fi folosit pentru orice tip de task automat: knowledge management, customer support, research, automation workflows, și mult mai mult.
De ce este Important?
- Flexibility: Construiește agenți custom pentru orice use case
- Production-Ready: Include context management, permissions, error handling out-of-the-box
- Extensible: Suport complet pentru MCP (Model Context Protocol) servers
- Programmable: Integrează-l în orice workflow, application sau automation
Ce este Claude Agent SDK
Evoluția Numelui
- Înainte: Claude Code SDK
- Acum: Claude Agent SDK (redenumit în 2025)
- Motiv: SDK-ul poate fi folosit pentru mult mai mult decât coding
Arhitectura Core
Claude Agent SDK este construit peste "agent harness" care alimentează Claude Code CLI. Oferă:
┌─────────────────────────────────────┐
│ Your Custom Application/Workflow │
│ (Telegram, Obsidian, Email, etc.) │
└──────────────┬──────────────────────┘
│
┌──────────────▼──────────────────────┐
│ Claude Agent SDK (Python/TS) │
│ • Context Management │
│ • Tool Execution │
│ • Permission System │
│ • MCP Integration │
└──────────────┬──────────────────────┘
│
┌──────────────▼──────────────────────┐
│ Claude API (Anthropic) │
│ Claude Sonnet 4.5 / Opus │
└─────────────────────────────────────┘
Instalare și Setup
Cerințe
- Python: 3.10+
- Node.js: Necesar pentru unele features
- API Key: Anthropic API key SAU Claude subscription (Pro/Max plan)
Instalare Python
# Instalare SDK
pip install claude-agent-sdk
# Verificare instalare
python -c "from claude_agent_sdk import query; print('OK')"
Instalare TypeScript/Node.js
# Instalare SDK
npm install @anthropic-ai/claude-agent-sdk
# SAU cu yarn
yarn add @anthropic-ai/claude-agent-sdk
Autentificare
Opțiunea 1: Anthropic API Key (plătești per token)
Configurează variabila de mediu ANTHROPIC_API_KEY folosind mecanismul specific shell-ului tău (ex.: comanda
export).
Opțiunea 2: Claude Subscription (recomandat pentru development)
# Folosește Claude Pro/Max plan
claude-code login
Avantaj Opțiunea 2: Nu plătești API credits separat dacă ai deja subscription.
Arhitectură și Concepte Cheie
1. Message Blocks
Claude Agent SDK funcționează pe conceptul de message blocks - nu streamează token-by-token, ci returnează blocuri complete de acțiuni:
User Request
↓
[Block 1] Text: "I'll help you with that"
↓
[Block 2] Tool Use: Reading file xyz.py
↓
[Block 3] Text: "I found the issue"
↓
[Block 4] Tool Use: Editing file xyz.py
↓
[Block 5] Text: "Done! Here's what I changed..."
↓
[Final Block] Result: Task completed
2. Query Function
Funcția centrală pentru interacțiunea cu agentul:
from claude_agent_sdk import query
# Query returnează un iterator de message blocks
messages = query(
messages=[{"role": "user", "content": "Your request"}],
options=agent_options
)
# Iterează prin blocks
for message in messages:
# Process each block
print(message)
3. Agent Options
Configurarea agentului prin options:
agent_options = {
"systemPrompt": "You are a helpful assistant...",
"cwd": "/path/to/working/directory",
"allowedTools": ["read", "write", "bash", "glob"],
"mcpServers": {
"server-name": {
"command": "node",
"args": ["server.js"]
}
}
}
4. Context Management Automat
SDK-ul gestionează automat:
- Context overflow prevention: Compactare automată când contextu devine prea mare
- Session management: Păstrează history-ul conversației
- Caching: Automatic prompt caching pentru performanță
Features Principale
1. Rich Tool Ecosystem
Built-in Tools:
- File Operations: Read, Write, Edit, Glob (pattern matching)
- Code Execution: Bash commands, Python scripts
- Web Search: Integrare cu search engines
- Web Fetch: Descarcă și procesează conținut web
Example:
agent_options = {
"allowedTools": [
"read", # Citire fișiere
"write", # Scriere fișiere
"edit", # Editare fișiere (find & replace)
"glob", # Găsire fișiere prin pattern
"bash", # Execuție comenzi
"websearch", # Căutare web
"webfetch" # Fetch URL-uri
]
}
2. Granular Permissions
Control fin asupra ce poate face agentul:
# Permisiuni stricte
permissions = {
"allowedTools": ["read", "glob"], # Doar citire, fără modificări
"cwd": "/safe/directory", # Limitează la un director
}
# Permisiuni complete
permissions = {
"allowedTools": "*", # Toate tool-urile
"bash": {
"allowedCommands": ["git", "npm", "pytest"] # Doar comenzi specifice
}
}
3. MCP Server Integration
Model Context Protocol (MCP) permite extinderea capabilities:
mcp_config = {
"mcpServers": {
# Standard I/O server
"sequential-thinking": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-sequential-thinking"]
},
# SSE server
"custom-api": {
"url": "http://localhost:3000/sse",
"transport": "sse"
},
# Asana integration (project management)
"asana": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-asana"]
}
}
}
Popular MCP Servers:
sequential-thinking: Extended thinking/reasoningfilesystem: Advanced file operationsgithub: GitHub API integrationslack: Slack integrationgoogle-drive: Google Drive accessdatabase: SQL database access
4. Streaming vs Single-Shot Mode
Streaming Mode (default):
# Primești blocks incremental pe măsură ce sunt generate
for message in query(messages, options):
print(message) # Block disponibil imediat
Single-Shot Mode (pentru batch processing):
# Așteaptă completion complet
result = query_sync(messages, options)
all_blocks = list(result)
5. Custom System Prompts
Definește comportamentul agentului:
options = {
"systemPrompt": """You are an expert DevOps engineer specializing in:
- Infrastructure as Code (Terraform, CloudFormation)
- CI/CD pipelines (GitHub Actions, GitLab CI)
- Container orchestration (Kubernetes, Docker)
When solving problems:
1. Always explain your reasoning
2. Provide production-ready solutions
3. Include error handling
4. Follow security best practices
Current project: Kubernetes migration for e-commerce platform
"""
}
Cazuri de Utilizare
1. Knowledge Management & Note-Taking
Use Case: Automatizare work cu knowledge bases (Obsidian, Notion)
Exemplu din Transcript:
- Integrare Claude în Obsidian vault
- Editare automată a note-urilor și scripturi YouTube
- Acces de pe telefon prin Telegram
Beneficii:
- Search inteligent prin notes
- Organizare automată
- Generare conținut structurat
- Sync între multiple devices
2. Personal AI Assistants
Use Case: Asistenți personali pentru task automation
Capabilities:
- 📅 Calendar management
- ✈️ Travel planning
- 📧 Email handling
- 📝 Meeting notes
- 🔍 Research și briefing
Exemplu:
# Personal assistant cu acces la calendar și email
options = {
"systemPrompt": "You are my personal assistant. Help with scheduling, emails, and research.",
"mcpServers": {
"google-calendar": {...},
"gmail": {...}
}
}
3. Custom Coding Assistants
Use Case: AI coding assistants customizați pentru proiectele tale
Diferențe față de Claude Code standard:
- ✅ Custom system prompts pentru tech stack-ul tău
- ✅ Pre-configured MCP servers pentru API-urile tale
- ✅ Custom permissions și safety rules
- ✅ Integration în CI/CD pipeline
- ✅ Monitoring și logging custom
Exemplu:
# Coding assistant pentru Django projects
options = {
"systemPrompt": """Expert Django developer.
Tech stack: Django 5.0, PostgreSQL, Redis, Celery
Always follow: Django best practices, write tests, type hints""",
"cwd": "/path/to/django/project",
"allowedTools": ["read", "write", "edit", "bash", "grep"],
"mcpServers": {
"postgres": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres"],
"env": {"DATABASE_URL": "postgresql://..."}
}
}
}
4. Customer Support Automation
Use Case: Agenți pentru customer support
Features:
- Handle ambiguous user requests
- Access customer data (CRM integration)
- Multi-turn conversations
- Escalation la human când e necesar
- Multi-language support
Exemplu Workflow:
Customer Question
→ Agent retrieves order history (MCP: Database)
→ Agent checks shipping status (MCP: Shipping API)
→ Agent provides personalized answer
→ If complex: Escalate to human + provide context
5. Finance & Investment Agents
Use Case: Analiza financiară și investment research
Capabilities:
- Portfolio analysis
- Market data retrieval
- Investment calculations
- Risk assessment
- Report generation
Exemplu:
options = {
"systemPrompt": "Financial analyst. Analyze portfolios and provide investment insights.",
"mcpServers": {
"alpha-vantage": {...}, # Stock data
"fred": {...} # Economic data
},
"allowedTools": ["read", "write", "python"] # Pentru calculations
}
6. SRE & DevOps Automation
Use Case: Site Reliability Engineering tasks
Applications:
- Incident diagnosis
- Log analysis
- Infrastructure changes
- Deployment automation
- Health check monitoring
Exemplu:
# SRE agent pentru production troubleshooting
options = {
"systemPrompt": """SRE agent. Diagnose and fix production issues.
Access: Kubernetes cluster, logs, metrics dashboards
Never: Make destructive changes without confirmation""",
"mcpServers": {
"kubernetes": {...},
"datadog": {...},
"pagerduty": {...}
}
}
7. Research & Content Creation
Use Case: Deep research și video/content creation
Din Transcript:
- Anthropic folosește Claude Code pentru video creation
- Research automation
- Content organization
Workflow:
Research Topic
→ Web search + article fetching
→ Summary generation
→ Organize findings în structure
→ Generate script/outline
→ Export în format final (MD, PDF, etc.)
8. Telegram/Slack Bots
Use Case: Conversational interfaces în messaging apps
Din Transcript:
- Telegram bot cu Claude Code integration
- Remote code execution de pe telefon
- Real-time file editing
Features:
- Multi-user support
- Persistent sessions
- Command system
- File upload/download
- Monitoring dashboard
Exemple de Cod
Exemplu 1: Simple Query (Minimal)
from claude_agent_sdk import query
# Definire options
options = {
"systemPrompt": "You are a helpful coding assistant."
}
# Mesaje
messages = [
{"role": "user", "content": "What is Python list comprehension?"}
]
# Query agent
for message in query(messages=messages, options=options):
# Fiecare message este un block
if hasattr(message, 'content'):
print(message.content)
Output:
[System Prompt Block]
[Response Block]: Python list comprehension is a concise way to create lists...
[Final Result Block]: Task completed
Exemplu 2: Custom CLI Agent
from claude_agent_sdk import AgentClient
import os
# Agent options
options = {
"systemPrompt": "You are an expert Python developer.",
"cwd": os.getcwd(),
"allowedTools": ["read", "write", "edit", "bash", "glob"],
}
# Create client (reusable pentru multiple queries)
client = AgentClient(options)
# Conversation history
conversation = []
print("Custom Claude CLI - Type 'exit' to quit\n")
while True:
# User input
user_input = input("You: ").strip()
if user_input.lower() in ['exit', 'quit']:
break
# Add user message
conversation.append({"role": "user", "content": user_input})
# Query agent
assistant_response = ""
for message in client.query(conversation):
# Handle different message types
if message.type == "text":
print(f"Assistant: {message.content}")
assistant_response += message.content
elif message.type == "tool_use":
print(f"[Using tool: {message.tool_name}]")
elif message.type == "final_result":
print("[Done]\n")
# Add assistant response to conversation
if assistant_response:
conversation.append({"role": "assistant", "content": assistant_response})
Usage:
$ python custom_cli.py
Custom Claude CLI - Type 'exit' to quit
You: List Python files in current directory
[Using tool: bash]
Assistant: You have 3 Python files: cli.py, agent.py, utils.py
[Done]
You: Read agent.py
[Using tool: read]
Assistant: Here's the content of agent.py...
[Done]
Exemplu 3: Obsidian Integration
Use Case: Claude Code integration în Obsidian pentru knowledge management
from fastapi import FastAPI, Request
from claude_agent_sdk import AgentClient
import json
app = FastAPI()
# Obsidian vault path
VAULT_PATH = "/home/user/ObsidianVault"
# Agent configuration
agent_options = {
"systemPrompt": """You are a knowledge management assistant for Obsidian.
Help organize notes, create summaries, and maintain the knowledge base.
Always preserve markdown formatting and internal links.""",
"cwd": VAULT_PATH,
"allowedTools": ["read", "write", "edit", "glob", "grep"],
# Sequential thinking MCP pentru better reasoning
"mcpServers": {
"sequential-thinking": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-sequential-thinking"]
}
}
}
# Create reusable client
agent = AgentClient(agent_options)
# OpenAI-compatible endpoint (pentru Obsidian Copilot plugin)
@app.post("/v1/chat/completions")
async def chat_completions(request: Request):
body = await request.json()
# Extract messages from OpenAI format
messages = body.get("messages", [])
# Convert to Claude format
claude_messages = [
{"role": msg["role"], "content": msg["content"]}
for msg in messages
]
# Query agent
response_text = ""
for message in agent.query(claude_messages):
if message.type == "text":
response_text += message.content
# Return în OpenAI format (pentru compatibility cu Copilot)
return {
"choices": [{
"message": {
"role": "assistant",
"content": response_text
}
}]
}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8080)
Setup Obsidian:
- Instalează "Copilot" community plugin
- Settings → Copilot → Custom API
- Base URL:
http://localhost:8080/v1 - Model:
claude(orice string)
Usage în Obsidian:
User: My AI automations list is too long. Make it shorter.
Agent:
[Using Glob tool to find file]
[Reading AI automations note]
[Editing file - condensing bullet points]
Done! I've shortened your list from 15 to 8 key items.
Exemplu 4: Telegram Bot with Remote Coding
Use Case: Control Claude Code remote prin Telegram (din telefon!)
import os
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, filters, ContextTypes
from claude_agent_sdk import AgentClient
# Telegram bot token
BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
# Global agent client (updated când user schimbă directory)
current_cwd = os.getcwd()
agent_client = None
def create_agent(cwd: str, system_prompt: str = None):
"""Create or update agent cu noul working directory"""
global agent_client
options = {
"systemPrompt": system_prompt or "You are a helpful coding assistant.",
"cwd": cwd,
"allowedTools": ["read", "write", "edit", "bash", "glob", "grep"],
# MCP servers
"mcpServers": {
"sequential-thinking": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-sequential-thinking"]
}
}
}
agent_client = AgentClient(options)
return agent_client
# Initialize agent
create_agent(current_cwd)
# Command: /setdir
async def set_directory(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Change working directory pentru agent"""
global current_cwd
if not context.args:
await update.message.reply_text(f"Current directory: {current_cwd}")
return
new_dir = " ".join(context.args)
if os.path.isdir(new_dir):
current_cwd = new_dir
create_agent(current_cwd)
await update.message.reply_text(f"✅ Working directory set to: {new_dir}")
else:
await update.message.reply_text(f"❌ Directory not found: {new_dir}")
# Command: /status
async def status(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Show agent status"""
await update.message.reply_text(f"""
📊 Agent Status:
• Working Directory: {current_cwd}
• Tools: read, write, edit, bash, glob, grep
• MCP Servers: sequential-thinking
""")
# Handle normal messages (queries to Claude)
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle user messages - send to Claude Agent"""
user_message = update.message.text
# Send "typing" indicator
await update.message.chat.send_action("typing")
# Query agent
messages = [{"role": "user", "content": user_message}]
response_blocks = []
tool_uses = []
for message in agent_client.query(messages):
if message.type == "text":
response_blocks.append(message.content)
elif message.type == "tool_use":
tool_uses.append(f"🔧 {message.tool_name}")
# Combine response
full_response = "\n\n".join(response_blocks)
if tool_uses:
tools_used = "\n".join(tool_uses)
full_response = f"{tools_used}\n\n{full_response}"
# Send back to user
await update.message.reply_text(full_response)
# Main
def main():
app = ApplicationBuilder().token(BOT_TOKEN).build()
# Handlers
app.add_handler(CommandHandler("setdir", set_directory))
app.add_handler(CommandHandler("status", status))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
print("🤖 Telegram bot started!")
app.run_polling()
if __name__ == "__main__":
main()
Usage (din Telegram pe telefon):
User: /status
Bot: 📊 Agent Status:
• Working Directory: /home/user/projects
• Tools: read, write, edit, bash, glob, grep
• MCP Servers: sequential-thinking
User: /setdir /home/user/django-app
Bot: ✅ Working directory set to: /home/user/django-app
User: Add a TODO comment in views.py to refactor the login function
Bot: 🔧 glob
🔧 read
🔧 edit
Done! I've added a TODO comment in views.py at line 45 above the login function.
User: Use sequential thinking to give me 5 ideas for improving the app
Bot: 🔧 sequential-thinking
🔧 sequential-thinking
🔧 read
Here are 5 improvement ideas:
1. Add Redis caching for database queries...
2. Implement rate limiting on API endpoints...
...
Din Transcript - Self-Improving Agent:
# Agent-ul își modifică propriul cod pentru a adăuga MCP server!
User (via Telegram): Add the sequential-thinking MCP server to my Claude agent
Agent:
[Reads current bot code]
[Finds MCP configuration section]
[Edits bot.py to add sequential-thinking config]
✅ Done! Sequential thinking MCP server added. Restart the bot to use it.
Exemplu 5: MCP Server Setup
Different Types of MCP Servers:
mcp_configs = {
# 1. Standard I/O Server (most common)
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/allowed/path"],
"transport": "stdio"
},
# 2. SSE (Server-Sent Events) Server
"custom-api": {
"url": "http://localhost:3000/sse",
"transport": "sse"
},
# 3. With Environment Variables
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": os.getenv("GITHUB_TOKEN")
}
},
# 4. Database Access
"postgres": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres"],
"env": {
"DATABASE_URL": "postgresql://<user>:<password>@localhost/db"
}
},
# 5. Custom Local Server
"my-custom-server": {
"command": "python",
"args": ["./servers/my_server.py"],
"cwd": "/path/to/project"
}
}
# Use în agent options
options = {
"systemPrompt": "...",
"mcpServers": mcp_configs
}
Popular MCP Servers List:
| Server | Purpose | Install |
|---|---|---|
sequential-thinking |
Extended reasoning | npx -y @modelcontextprotocol/server-sequential-thinking |
filesystem |
File operations | npx -y @modelcontextprotocol/server-filesystem |
github |
GitHub API | npx -y @modelcontextprotocol/server-github |
gitlab |
GitLab API | npx -y @modelcontextprotocol/server-gitlab |
postgres |
PostgreSQL | npx -y @modelcontextprotocol/server-postgres |
mysql |
MySQL/MariaDB | npx -y @modelcontextprotocol/server-mysql |
sqlite |
SQLite | npx -y @modelcontextprotocol/server-sqlite |
slack |
Slack integration | npx -y @modelcontextprotocol/server-slack |
google-drive |
Google Drive | npx -y @modelcontextprotocol/server-google-drive |
brave-search |
Web search | npx -y @modelcontextprotocol/server-brave-search |
Exemplu 6: Session Management & Conversation History
from claude_agent_sdk import AgentClient
import json
from datetime import datetime
class ConversationManager:
"""Manage multi-turn conversations with persistent history"""
def __init__(self, session_file="session.json"):
self.session_file = session_file
self.history = self.load_session()
# Agent options
self.options = {
"systemPrompt": "You are a helpful assistant.",
"cwd": "/workspace",
"allowedTools": "*"
}
self.client = AgentClient(self.options)
def load_session(self):
"""Load conversation history from file"""
try:
with open(self.session_file, 'r') as f:
return json.load(f)
except FileNotFoundError:
return []
def save_session(self):
"""Save conversation history to file"""
with open(self.session_file, 'w') as f:
json.dump(self.history, f, indent=2)
def chat(self, user_message: str) -> str:
"""Send message and get response"""
# Add user message to history
self.history.append({
"role": "user",
"content": user_message,
"timestamp": datetime.now().isoformat()
})
# Query agent with full history
response_text = ""
for message in self.client.query(self.history):
if message.type == "text":
response_text += message.content
# Add assistant response to history
self.history.append({
"role": "assistant",
"content": response_text,
"timestamp": datetime.now().isoformat()
})
# Persist to disk
self.save_session()
return response_text
def clear(self):
"""Clear conversation history"""
self.history = []
self.save_session()
# Usage
manager = ConversationManager("my_session.json")
# Turn 1
print(manager.chat("What is FastAPI?"))
# Turn 2 (remembers context!)
print(manager.chat("Show me an example endpoint"))
# Turn 3
print(manager.chat("Add error handling to that example"))
# Clear when done
# manager.clear()
Exemplu 7: Error Handling & Retries
from claude_agent_sdk import AgentClient, AgentError
import time
def query_with_retry(client: AgentClient, messages: list, max_retries=3):
"""Query agent cu retry logic pentru errors"""
for attempt in range(max_retries):
try:
results = []
for message in client.query(messages):
results.append(message)
return results
except AgentError as e:
if "rate_limit" in str(e).lower():
# Rate limit - wait and retry
wait_time = 2 ** attempt # Exponential backoff
print(f"Rate limited. Waiting {wait_time}s before retry...")
time.sleep(wait_time)
elif "context_length" in str(e).lower():
# Context too long - truncate history
print("Context too long. Truncating history...")
messages = messages[-10:] # Keep last 10 messages
else:
# Other error - re-raise
raise
except Exception as e:
print(f"Unexpected error: {e}")
if attempt == max_retries - 1:
raise
time.sleep(1)
raise Exception(f"Failed after {max_retries} retries")
# Usage
client = AgentClient({"systemPrompt": "..."})
messages = [{"role": "user", "content": "Help me debug this code"}]
try:
results = query_with_retry(client, messages)
for msg in results:
print(msg)
except Exception as e:
print(f"Failed: {e}")
Integrări Posibile
1. Development Tools
| Tool | Integration Type | Use Case |
|---|---|---|
| VS Code | Extension/API | Custom coding assistant în IDE |
| JetBrains IDEs | Plugin | IntelliJ, PyCharm, WebStorm integration |
| Vim/Neovim | Plugin/RPC | Terminal-based coding assistant |
| GitHub | Actions/Webhooks | CI/CD automation, PR reviews |
| GitLab | CI/CD | Pipeline automation |
| Jira | API | Ticket analysis, task automation |
2. Communication Platforms
| Platform | Integration | Use Case |
|---|---|---|
| Telegram | Bot API | Remote coding, notifications |
| Slack | Bot/Slash Commands | Team assistant, code reviews |
| Discord | Bot | Community support, automation |
| IMAP/SMTP | Email automation, summarization | |
| Business API | Customer support |
3. Productivity Tools
| Tool | Integration | Use Case |
|---|---|---|
| Obsidian | Plugin/API | Knowledge management |
| Notion | API | Database management, content creation |
| Todoist | API | Task automation |
| Google Calendar | API | Scheduling, reminders |
| Trello | API | Project management |
4. Development Platforms
| Platform | Integration | Use Case |
|---|---|---|
| Vercel | Deploy hooks | Auto-deploy & testing |
| Netlify | Build plugins | CI/CD automation |
| AWS | Lambda | Serverless agent execution |
| Google Cloud | Cloud Functions | Scalable agents |
| Docker | Container | Isolated agent environments |
5. Databases & Storage
| Service | MCP Server | Use Case |
|---|---|---|
| PostgreSQL | server-postgres |
Database queries, migrations |
| MySQL | server-mysql |
Database operations |
| MongoDB | Custom | NoSQL operations |
| Redis | Custom | Cache management |
| S3 | Custom | File storage/retrieval |
6. Monitoring & Analytics
| Tool | Integration | Use Case |
|---|---|---|
| Sentry | SDK Integration | Error tracking, performance |
| Datadog | API | Metrics, logs, traces |
| Grafana | API | Dashboard queries |
| New Relic | API | Performance monitoring |
| Prometheus | API | Metrics querying |
Monitoring și Debugging
Sentry Integration (din Transcript)
De ce Sentry pentru AI Agents?
- ✅ Vezi toate deciziile pe care le-a luat agentul
- ✅ Token usage tracking
- ✅ Performance metrics (timp de execuție)
- ✅ Tool call tracing
- ✅ Error tracking
Setup:
import sentry_sdk
from sentry_sdk.integrations.anthropic import AnthropicIntegration
# Initialize Sentry cu AI monitoring
sentry_sdk.init(
dsn="your-sentry-dsn",
integrations=[
AnthropicIntegration(), # Special pentru Claude/Anthropic
],
traces_sample_rate=1.0, # 100% trace sampling
)
# Use Claude Agent SDK normally
from claude_agent_sdk import AgentClient
client = AgentClient({...})
# Toate queries sunt automat tracked în Sentry!
for message in client.query(messages):
print(message)
Ce Vezi în Sentry Dashboard:
📊 Trace: "User request - Fix authentication bug"
├─ Span: Agent Query (2.3s)
│ ├─ Input tokens: 1,234
│ ├─ Output tokens: 567
│ └─ Model: claude-sonnet-4.5
│
├─ Tool: glob (0.1s)
│ └─ Pattern: "**/*auth*.py"
│
├─ Tool: read (0.05s)
│ └─ File: auth/views.py
│
├─ Tool: edit (0.2s)
│ └─ Changes: +5 lines, -3 lines
│
└─ Total: 2.65s, 1,801 tokens
Exemplu cu Sentry (Telegram Bot):
import sentry_sdk
from sentry_sdk.integrations.anthropic import AnthropicIntegration
from claude_agent_sdk import AgentClient
from telegram.ext import ApplicationBuilder, MessageHandler, filters
# Sentry setup
sentry_sdk.init(
dsn=os.getenv("SENTRY_DSN"),
integrations=[AnthropicIntegration()],
traces_sample_rate=1.0,
environment="production",
)
async def handle_message(update, context):
user_message = update.message.text
# Sentry automatically tracks this!
with sentry_sdk.start_transaction(op="agent_query", name=user_message[:50]):
agent = AgentClient(options)
for message in agent.query([{"role": "user", "content": user_message}]):
if message.type == "text":
await update.message.reply_text(message.content)
# Bot setup
app = ApplicationBuilder().token(os.getenv("BOT_TOKEN")).build()
app.add_handler(MessageHandler(filters.TEXT, handle_message))
app.run_polling()
Beneficii în Production:
- Debugging: Vezi exact ce a făcut agentul pentru fiecare request
- Validation: Verifică dacă agentul face deciziile corecte
- Cost Tracking: Monitorizează token usage
- Performance: Identifică bottlenecks
- Errors: Catch și debug issues rapid
Custom Logging
import logging
from claude_agent_sdk import AgentClient
# Setup logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('agent.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
def query_with_logging(client, messages):
"""Query cu detailed logging"""
logger.info(f"Starting query with {len(messages)} messages")
tool_calls = []
response_text = ""
for message in client.query(messages):
if message.type == "text":
logger.info(f"Text response: {message.content[:100]}...")
response_text += message.content
elif message.type == "tool_use":
logger.info(f"Tool use: {message.tool_name} with args: {message.args}")
tool_calls.append(message.tool_name)
elif message.type == "error":
logger.error(f"Agent error: {message.error}")
logger.info(f"Query completed. Tools used: {tool_calls}")
return response_text
Best Practices
1. Security & Permissions
❌ BAD - Prea permisiv:
options = {
"allowedTools": "*", # TOT!
"cwd": "/" # ROOT ACCESS!
}
✅ GOOD - Granular permissions:
options = {
"allowedTools": ["read", "glob"], # Doar citire
"cwd": "/safe/project/directory", # Specific directory
"bash": {
"allowedCommands": ["git status", "npm test"] # Specific commands
}
}
2. System Prompts
❌ BAD - Vague:
"systemPrompt": "You are helpful."
✅ GOOD - Specific și contextual:
"systemPrompt": """You are an expert DevOps engineer for our e-commerce platform.
Tech Stack:
- Backend: Django 5.0, PostgreSQL, Redis
- Frontend: Next.js 14, TypeScript
- Infrastructure: Kubernetes on AWS EKS
- CI/CD: GitHub Actions
Guidelines:
1. Always write production-ready code with error handling
2. Include unit tests for new features
3. Follow our coding standards (Black, ESLint)
4. Document infrastructure changes
5. Never commit secrets or credentials
Current task: Kubernetes migration from EC2 instances
"""
3. Error Handling
✅ Always wrap queries în try-catch:
try:
for message in agent.query(messages):
process(message)
except AgentError as e:
logger.error(f"Agent error: {e}")
# Fallback logic
except Exception as e:
logger.error(f"Unexpected error: {e}")
sentry_sdk.capture_exception(e)
4. Context Management
❌ BAD - Unlimited history:
# History devine prea mare!
conversation_history.append(every_single_message)
✅ GOOD - Truncate sau summarize:
# Păstrează doar ultimele N mesaje
MAX_HISTORY = 20
if len(conversation_history) > MAX_HISTORY:
# Păstrează system prompt + ultimele mesaje
conversation_history = [
conversation_history[0], # System prompt
*conversation_history[-MAX_HISTORY:]
]
5. MCP Server Management
✅ Use environment variables pentru secrets:
"mcpServers": {
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": os.getenv("GITHUB_TOKEN") # ✅ Din env
# ❌ NU: evita hardcodarea token-ului direct în configurație
}
}
}
6. Testing
✅ Test agent behavior:
import pytest
from claude_agent_sdk import AgentClient
def test_agent_file_reading():
"""Test că agentul poate citi fișiere"""
client = AgentClient({
"cwd": "/test/directory",
"allowedTools": ["read"]
})
messages = [{"role": "user", "content": "Read test.txt"}]
used_tools = []
for message in client.query(messages):
if message.type == "tool_use":
used_tools.append(message.tool_name)
assert "read" in used_tools
def test_agent_permissions():
"""Test că permissions sunt respectate"""
client = AgentClient({
"allowedTools": ["read"] # Doar read
})
messages = [{"role": "user", "content": "Delete file.txt"}]
with pytest.raises(PermissionError):
list(client.query(messages))
7. Performance Optimization
✅ Use prompt caching:
# Claude Agent SDK face asta automat, dar poți optimiza prin:
# - Păstrează system prompts consistente
# - Reuse același client pentru multiple queries
# - Evită schimbări frecvente de configuration
client = AgentClient(options) # ✅ Create once
for user_request in requests:
# ✅ Reuse client - automatic caching!
client.query([{"role": "user", "content": user_request}])
8. Monitoring în Production
✅ Always monitor în production:
# 1. Sentry pentru traces
sentry_sdk.init(dsn="...", integrations=[AnthropicIntegration()])
# 2. Custom metrics
from prometheus_client import Counter, Histogram
agent_queries = Counter('agent_queries_total', 'Total agent queries')
agent_duration = Histogram('agent_duration_seconds', 'Agent query duration')
@agent_duration.time()
def query_agent(messages):
agent_queries.inc()
return list(client.query(messages))
# 3. Logging
logger.info(f"Agent query: {user_message}")
9. Cost Management
✅ Track și optimize costs:
# Monitor token usage
total_tokens = 0
for message in client.query(messages):
if hasattr(message, 'usage'):
total_tokens += message.usage.get('total_tokens', 0)
logger.info(f"Total tokens used: {total_tokens}")
# Set limits
if total_tokens > MAX_TOKENS_PER_SESSION:
raise Exception("Token limit exceeded")
10. Deployment
✅ Containerize pentru consistency:
# Dockerfile pentru agent deployment
FROM python:3.11-slim
# Install Node.js (pentru MCP servers)
RUN apt-get update && apt-get install -y nodejs npm
WORKDIR /app
# Install dependencies
COPY requirements.txt .
RUN pip install -r requirements.txt
# Copy agent code
COPY . .
# Environment variables (definește-le în runtime sau pipeline)
# - ANTHROPIC_API_KEY
# - SENTRY_DSN
CMD ["python", "agent.py"]
Resurse și Referințe
Documentație Oficială
- Claude Agent SDK Docs: https://docs.claude.com/en/api/agent-sdk/overview
- GitHub Python SDK: https://github.com/anthropics/claude-agent-sdk-python
- GitHub TypeScript SDK: https://github.com/anthropics/claude-agent-sdk-typescript
- Migration Guide (Code SDK → Agent SDK): https://docs.claude.com/en/api/agent-sdk/migration
Anthropic Blog Posts
- Building Agents with Claude Agent SDK: https://www.anthropic.com/engineering/building-agents-with-the-claude-agent-sdk
- Enabling Claude Code to Work More Autonomously: https://www.anthropic.com/news/enabling-claude-code-to-work-more-autonomously
- Agent Skills: https://www.anthropic.com/engineering/equipping-agents-for-the-real-world-with-agent-skills
Tutorials și Guides
- DataCamp Tutorial: https://www.datacamp.com/tutorial/how-to-use-claude-agent-sdk
- Practical Guide to Custom Coding Agents: https://www.eesel.ai/blog/custom-coding-agents-claude-code-sdk
- Python SDK Guide 2025: https://www.eesel.ai/blog/python-claude-code-sdk
MCP (Model Context Protocol)
- MCP Documentation: https://modelcontextprotocol.io
- MCP Servers List: https://github.com/modelcontextprotocol/servers
- Create Custom MCP Server: https://modelcontextprotocol.io/docs/creating-servers
Monitoring & Observability
- Sentry AI Monitoring: https://docs.sentry.io/platforms/python/integrations/anthropic/
- LangSmith (alternative): https://docs.smith.langchain.com/
- Weights & Biases (alternative): https://wandb.ai/
Example Projects & Repositories
- Claude Code Examples (din transcript): https://github.com/[repository-link-from-video]
- Awesome Claude Agents: https://github.com/topics/claude-agent-sdk
- Community Examples: https://github.com/anthropics/anthropic-cookbook
Community
- Discord: Anthropic Discord server
- Reddit: r/ClaudeAI
- Twitter: @AnthropicAI
Concluzie
Claude Agent SDK nu este doar pentru coding - este o platformă completă pentru a construi orice tip de agent AI care beneficiază de:
✅ File operations puternice (read, write, edit, search) ✅ Code execution (bash, Python, etc.) ✅ Extensibility (MCP servers pentru orice API/service) ✅ Production-ready features (permissions, error handling, context management) ✅ Flexibility (integrează în orice app/workflow)
Key Takeaways
- Beyond Coding: Use pentru knowledge management, automation, research, support
- Programmable: Controlează totul - system prompts, permissions, tools, MCP servers
- Integration-Friendly: Telegram, Obsidian, Slack, Email, CI/CD, etc.
- Production-Ready: Built-in monitoring (Sentry), error handling, caching
- Future-Proof: Arhitectura care va fi copiată de alte AI coding tools
Următorii Pași
- Experimentează cu quick start examples
- Alege un use case (e.g., Telegram bot, Obsidian integration)
- Configurează MCP servers pentru API-urile tale
- Setup monitoring (Sentry)
- Deploy în production (Docker, AWS Lambda, etc.)
Happy Building! 🚀
Documentație generată pe baza transcriptului "Claude Code's Real Purpose" și documentației oficiale Anthropic (Ianuarie 2025)