Claude Code: Полная документация — Субагенты, Hooks, Skills, MCP и Architecture
Дата: 2026-07-12
Версия Claude Code: 2.1.200+
Язык оригинала: English
Консолидировано из: docs.claude.com, code.claude.com/docs
Оглавление
- Claude Code: Общая архитектура
- Agent SDK: Ядро системы
- Субагенты (Subagents)
- Model Context Protocol (MCP)
- Skills: Расширение возможностей
- Hooks: Перехват и контроль поведения
- Permissions: Система управления доступом
- Configuration: Настройка системы
- Headless режим (claude -p)
- Agent Teams: Многоагентная координация
Claude Code: Общая архитектура
Claude Code — это агентная система, которая читает кодовую базу, редактирует файлы, запускает команды и интегрируется с инструментами разработки. Работает на нескольких поверхностях (surfaces): терминал, IDE расширения, десктоп-приложение и веб.
Архитектурные уровни
┌─────────────────────────────────────────────────────┐
│ User Interface Layer │
│ (Terminal CLI | VS Code | JetBrains | Desktop | │
│ Web | Remote Control) │
└────────────────┬────────────────────────────────────┘
│
┌────────────────▼────────────────────────────────────┐
│ Agent Orchestration Layer │
│ - Main Agent Loop │
│ - Subagent Spawning & Coordination │
│ - Session Management │
│ - Conversation Compaction │
└────────────────┬────────────────────────────────────┘
│
┌────────────────▼────────────────────────────────────┐
│ Tool Execution & MCP Layer │
│ - Built-in Tools (Read, Edit, Bash, WebFetch...) │
│ - MCP Server Integration │
│ - Tool Search & Discovery │
│ - Custom Tools (SDK) │
└────────────────┬────────────────────────────────────┘
│
┌────────────────▼────────────────────────────────────┐
│ Extensibility & Configuration Layer │
│ - Skills (.claude/skills/) │
│ - Hooks (PreToolUse, PostToolUse, etc.) │
│ - CLAUDE.md Memory System │
│ - Plugins & Marketplace │
└─────────────────────────────────────────────────────┘
Ключевые возможности (What You Can Do)
- Автоматизация рутины — написание тестов, исправление lint ошибок, обновление зависимостей
- Разработка и отладка — планирование, написание кода, отладка через промпты
- Git & PR workflows — коммиты, ветвление, открытие PR
- MCP интеграция — доступ к Google Drive, Jira, Slack, кастомным API
- Специализированные задачи — через skills и hooks
- Многоагентные системы — параллельное выполнение через субагентов
- Планирование задач — Routines на Anthropic инфраструктуре или локальные scheduled tasks
Agent SDK: Ядро системы
Agent SDK — это Python и TypeScript библиотека, которая даёт разработчикам полный контроль над агентом, эквивалентный Claude Code CLI, но программируемо.
Установка
Python (требует Python 3.10+)
pip install claude-agent-sdk
TypeScript
npm install @anthropic-ai/claude-agent-sdk
Базовый пример
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions
async def main():
async for message in query(
prompt="Find and fix the bug in auth.py",
options=ClaudeAgentOptions(allowed_tools=["Read", "Edit", "Bash"]),
):
if hasattr(message, "result"):
print(message.result)
asyncio.run(main())
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "Find and fix the bug in auth.ts",
options: { allowedTools: ["Read", "Edit", "Bash"] }
})) {
if ("result" in message) console.log(message.result);
}
Аутентификация
export ANTHROPIC_API_KEY=your-api-key
Поддерживает также:
- Amazon Bedrock: CLAUDE_CODE_USE_BEDROCK=1 + AWS credentials
- Claude Platform on AWS: CLAUDE_CODE_USE_ANTHROPIC_AWS=1 + ANTHROPIC_AWS_WORKSPACE_ID
- Google Cloud Vertex AI: CLAUDE_CODE_USE_VERTEX=1 + GCP credentials
- Microsoft Azure Foundry: CLAUDE_CODE_USE_FOUNDRY=1 + Azure credentials
Встроенные инструменты (Built-in Tools)
Агент имеет встроенный доступ без реализации пользователя:
| Инструмент | Описание |
|---|---|
Read |
Чтение любого файла в рабочей директории |
Write |
Создание новых файлов |
Edit |
Точечное редактирование существующих файлов |
Bash |
Выполнение терминальных команд, git операций |
Monitor |
Отслеживание фонового скрипта, реакция на каждую строку вывода |
Glob |
Поиск файлов по паттерну (**/*.ts, src/**/*.py) |
Grep |
Поиск в файлах с regex |
WebSearch |
Поиск в интернете за актуальной информацией |
WebFetch |
Загрузка и парсинг контента веб-страниц |
AskUserQuestion |
Уточняющие вопросы с множественным выбором |
Сравнение с другими инструментами
| Категория | Agent SDK | Client SDK | Claude Code CLI | Managed Agents |
|---|---|---|---|---|
| Запуск | Ваш процесс | Ваш процесс | Локально или cloud | Anthropic инфра |
| Интерфейс | Library (Python/TS) | API | CLI | REST API |
| Работает с | Файлы на вашей инфре | Любые данные | Локальные файлы | Managed sandbox |
| Состояние | JSONL на диске | В памяти | В памяти или disk | Anthropic-hosted event log |
| Custom tools | In-process functions | Manual loop | Tool definitions | Trigger execution |
| Лучший для | Local dev, prototype | Direct API access | Interactive work | Production, long-running |
Субагенты (Subagents)
Субагенты — это отдельные экземпляры агента, которые основной агент может спавнить для выполнения сосредоточенных подзадач.
Преимущества использования
- Изоляция контекста — промежуточные инструменты и результаты остаются в субагенте, только финальное сообщение возвращается родителю
- Параллелизм — несколько субагентов выполняются одновременно (зависит от способа вызова)
- Специализированные инструкции — каждый субагент имеет свой system prompt с экспертизой
- Ограничение инструментов — субагент может быть ограничен определённым набором tools
Создание субагента (Programmatic)
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition
async def main():
async for message in query(
prompt="Review the authentication module for security issues",
options=ClaudeAgentOptions(
allowed_tools=["Read", "Grep", "Glob", "Agent"],
agents={
"code-reviewer": AgentDefinition(
description="Expert code review specialist. Use for quality, security, and maintainability reviews.",
prompt="""You are a code review specialist with expertise in security, performance, and best practices.
When reviewing code:
- Identify security vulnerabilities
- Check for performance issues
- Verify adherence to coding standards
- Suggest specific improvements
Be thorough but concise in your feedback.""",
tools=["Read", "Grep", "Glob"],
model="sonnet",
),
"test-runner": AgentDefinition(
description="Runs and analyzes test suites. Use for test execution and coverage analysis.",
prompt="""You are a test execution specialist. Run tests and provide clear analysis of results.
Focus on:
- Running test commands
- Analyzing test output
- Identifying failing tests
- Suggesting fixes for failures""",
tools=["Bash", "Read", "Grep"],
),
},
),
):
if hasattr(message, "result"):
print(message.result)
asyncio.run(main())
AgentDefinition Configuration
| Поле | Тип | Обязателен | Описание |
|---|---|---|---|
description |
string | Да | Когда использовать этого агента |
prompt |
string | Да | System prompt, определяет поведение |
tools |
string[] | Нет | Массив допустимых инструментов. Если опущено, наследует все |
disallowedTools |
string[] | Нет | Инструменты для удаления (удаляет из tools родителя) |
model |
string | Нет | Override модели (alias: fable, opus, sonnet, haiku, inherit) |
skills |
string[] | Нет | Список skill names для preload |
memory |
string | Нет | Источник памяти: 'user' \| 'project' \| 'local' |
mcpServers |
array | Нет | MCP серверы, доступные субагенту |
initialPrompt |
string | Нет | Auto-submitted как первая user턴 |
maxTurns |
number | Нет | Max agentic turns до остановки |
background |
boolean | Нет | Запустить как non-blocking background task |
effort |
enum | Нет | Уровень reasoning: 'low' \| 'medium' \| 'high' \| 'xhigh' \| 'max' |
permissionMode |
enum | Нет | Permission mode для tool execution |
Что субагент наследует от родителя
✅ Наследует:
- Собственный system prompt (AgentDefinition.prompt)
- Project CLAUDE.md
- Tool definitions (или subset в tools)
- Agent tool's prompt
❌ НЕ наследует:
- Историю разговора родителя
- Preloaded skill content (если не в AgentDefinition.skills)
- System prompt родителя
Автоматический вызов
Claude автоматически вызывает субагенты на основе description. Явно запросить: "Use the code-reviewer agent to..."
Nested subagents
Субагент может спавнить своих собственных субагентов. Максимальная глубина: 5 уровней. Можно отключить, удалив Agent из tools или добавив в disallowedTools.
Динамическая конфигурация
def create_security_agent(security_level: str) -> AgentDefinition:
is_strict = security_level == "strict"
return AgentDefinition(
description="Security code reviewer",
prompt=f"You are a {'strict' if is_strict else 'balanced'} security reviewer...",
tools=["Read", "Grep", "Glob"],
model="opus" if is_strict else "sonnet", # Используй более мощную модель для строгой проверки
)
async def main():
async for message in query(
prompt="Review this PR for security issues",
options=ClaudeAgentOptions(
allowed_tools=["Read", "Grep", "Glob", "Agent"],
agents={
"security-reviewer": create_security_agent("strict")
},
),
):
if hasattr(message, "result"):
print(message.result)
Обнаружение вызова субагента
from claude_agent_sdk import ToolUseBlock
if hasattr(message, "content") and message.content:
for block in message.content:
if isinstance(block, ToolUseBlock) and block.name in ("Task", "Agent"):
print(f"Subagent invoked: {block.input.get('subagent_type')}")
if hasattr(message, "parent_tool_use_id") and message.parent_tool_use_id:
print(" (running inside subagent)")
Resume субагента
Субагент можно возобновить, чтобы продолжить с того же места:
# Capture session_id и agent_id из первого запроса
# Затем resume с той же session_id
async for message in query(
prompt=f"Resume agent {agent_id} and list the top 3 most complex endpoints",
options=ClaudeAgentOptions(
allowed_tools=["Read", "Grep", "Glob", "Agent"],
agents=AGENTS,
resume=session_id # ← Resume!
),
):
if hasattr(message, "result"):
print(message.result)
Model Context Protocol (MCP)
MCP — открытый стандарт для подключения AI агентов к внешним инструментам и источникам данных: базы данных, API (Slack, GitHub), и пользовательские инструменты.
Быстрый старт
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "Use the docs MCP server to explain what hooks are in Claude Code",
options: {
mcpServers: {
"claude-code-docs": {
type: "http",
url: "https://code.claude.com/docs/mcp"
}
},
allowedTools: ["mcp__claude-code-docs__*"]
}
})) {
if (message.type === "result" && message.subtype === "success") {
console.log(message.result);
}
}
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
async def main():
options = ClaudeAgentOptions(
mcp_servers={
"claude-code-docs": {
"type": "http",
"url": "https://code.claude.com/docs/mcp",
}
},
allowed_tools=["mcp__claude-code-docs__*"],
)
async for message in query(
prompt="Use the docs MCP server to explain what hooks are in Claude Code",
options=options,
):
if isinstance(message, ResultMessage) and message.subtype == "success":
print(message.result)
asyncio.run(main())
Добавление MCP сервера (в коде)
for await (const message of query({
prompt: "List files in my project",
options: {
mcpServers: {
filesystem: {
command: "npx",
args: ["-y", "@modelcontextprotocol/server-filesystem", "/Users/me/projects"]
}
},
allowedTools: ["mcp__filesystem__*"]
}
})) {
if (message.type === "result" && message.subtype === "success") {
console.log(message.result);
}
}
Конфигурация через .mcp.json
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/me/projects"]
}
}
}
Типы транспорта
1. stdio — локальные процессы
const options = {
mcpServers: {
github: {
command: "npx",
args: ["-y", "@modelcontextprotocol/server-github"],
env: {
GITHUB_TOKEN: process.env.GITHUB_TOKEN
}
}
},
allowedTools: ["mcp__github__list_issues", "mcp__github__search_issues"]
};
2. HTTP/SSE — облачные и удалённые серверы
const options = {
mcpServers: {
"remote-api": {
type: "sse", // или "http" для streamable HTTP
url: "https://api.example.com/mcp/sse",
headers: {
Authorization: `Bearer ${process.env.API_TOKEN}`
}
}
},
allowedTools: ["mcp__remote-api__*"]
};
3. SDK MCP Servers — custom tools in-process
Определяются кодом прямо в SDK приложении.
Разрешение MCP инструментов
MCP инструменты требуют явного разрешения. Именование: mcp__<server-name>__<tool-name>
allowedTools: [
"mcp__github__*", // Все инструменты от github сервера
"mcp__db__query", // Только query от db сервера
"mcp__slack__send_message" // Только send_message от slack
]
Аутентификация
Переменные окружения (stdio servers)
github: {
command: "npx",
args: ["-y", "@modelcontextprotocol/server-github"],
env: {
GITHUB_TOKEN: process.env.GITHUB_TOKEN
}
}
HTTP Headers (remote servers)
"secure-api": {
type: "http",
url: "https://api.example.com/mcp",
headers: {
Authorization: `Bearer ${process.env.API_TOKEN}`
}
}
OAuth2
const accessToken = await getAccessTokenFromOAuthFlow();
const options = {
mcpServers: {
"oauth-api": {
type: "http",
url: "https://api.example.com/mcp",
headers: {
Authorization: `Bearer ${accessToken}`
}
}
},
allowedTools: ["mcp__oauth-api__*"]
};
Примеры
Список issues из GitHub репозитория
export GITHUB_TOKEN=ghp_xxxxxxxxxxxxxxxxxxxx
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "List the 3 most recent issues in anthropics/claude-code",
options: {
mcpServers: {
github: {
command: "npx",
args: ["-y", "@modelcontextprotocol/server-github"],
env: {
GITHUB_TOKEN: process.env.GITHUB_TOKEN
}
}
},
allowedTools: ["mcp__github__list_issues"]
}
})) {
if (message.type === "system" && message.subtype === "init") {
console.log("MCP servers:", message.mcp_servers);
}
if (message.type === "result" && message.subtype === "success") {
console.log(message.result);
}
}
Query к Postgres базе
const connectionString = process.env.DATABASE_URL;
for await (const message of query({
prompt: "How many users signed up last week? Break it down by day.",
options: {
mcpServers: {
postgres: {
command: "npx",
args: ["-y", "@modelcontextprotocol/server-postgres", connectionString]
}
},
allowedTools: ["mcp__postgres__query"]
}
})) {
if (message.type === "result" && message.subtype === "success") {
console.log(message.result);
}
}
Tool Search
Когда много MCP инструментов, их определения занимают значительную часть context window. Tool search решает это, скрывая определения инструментов и загружая только нужные в каждый turn.
Включен по умолчанию.
Обработка ошибок
Проверяй init message для статуса подключения:
if (message.type === "system" && message.subtype === "init") {
const failedServers = message.mcp_servers.filter((s) => s.status !== "connected");
if (failedServers.length > 0) {
console.warn("Failed to connect:", failedServers);
}
}
Распространённые причины: - Missing env variables — проверь tokens и credentials - Server not installed — verify package exists и Node.js в PATH - Invalid connection string — check format и доступность БД - Network issues — check URL reachability и firewalls
Skills: Расширение возможностей
Skills расширяют возможности Claude. Создаёшь файл SKILL.md с инструкциями, и Claude добавляет его в свой инструментарий. Claude использует skills когда они релевантны, или ты вызываешь их явно с /skill-name.
Создание skill
---
name: code-review
description: Review code for quality and security
invoke: claude
---
You are an expert code reviewer. When reviewing code:
- Identify security vulnerabilities
- Check for performance issues
- Verify adherence to coding standards
- Suggest specific improvements
Focus on practical feedback that improves the codebase.
Структура файлов
.claude/skills/
├── deploy/
│ ├── SKILL.md # Определение skill
│ ├── deployment-guide.md # Поддерживающий файл
│ └── templates/
│ └── rollback.sh
├── code-review/
│ └── SKILL.md
└── lint-fix/
└── SKILL.md
Frontmatter опции
---
name: skill-name # ID для /skill-name
description: What it does # Когда Claude его вызовет
invoke: claude|manual # claude = авто, manual = /skill-name
disabled: false # Скрыть skill (опционально)
---
Когда использовать skill vs CLAUDE.md
- CLAUDE.md: Project context, coding standards, preferences (всегда загружен)
- Skill: Повторяемые workflows, checklist, procedures (загружается только при использовании)
Skills основаны на открытом стандарте Agent Skills.
Hooks: Перехват и контроль поведения
Hooks — callback функции, которые выполняются в ответ на события агента: вызов инструмента, начало сессии, остановка выполнения.
Возможности
- Блокировать опасные операции — например, деструктивные shell команды
- Логирование и аудит — каждый вызов инструмента
- Трансформация входов/выходов — санитизация данных, injection credentials
- Требование утверждения — для чувствительных действий
- Отслеживание жизненного цикла — управление состоянием, cleanup ресурсов
Как работают hooks
1. Event fires (tool called, session started, etc.)
↓
2. SDK собирает registered hooks для этого события
↓
3. Matchers фильтруют, какие hooks запустить
↓
4. Callback functions выполняются
↓
5. Callback возвращает decision: allow/deny/ask/defer
Доступные hooks
| Hook Event | Python | TypeScript | Когда срабатывает | Примеры использования |
|---|---|---|---|---|
PreToolUse |
✅ | ✅ | Запрос на вызов инструмента (может блокировать) | Блокировать опасные shell команды |
PostToolUse |
✅ | ✅ | Результат выполнения инструмента | Логировать все изменения файлов |
PostToolUseFailure |
✅ | ✅ | Ошибка выполнения инструмента | Обработать ошибки инструмента |
PostToolBatch |
❌ | ✅ | Полный batch инструментов разрешился | Inject conventions один раз на batch |
UserPromptSubmit |
✅ | ✅ | User prompt submission | Inject дополнительный контекст |
Stop |
✅ | ✅ | Остановка агента | Сохранить состояние сессии |
SubagentStart |
✅ | ✅ | Инициализация субагента | Отслеживать параллельные задачи |
SubagentStop |
✅ | ✅ | Завершение субагента | Агрегировать результаты |
PreCompact |
✅ | ✅ | Запрос на compaction разговора | Архивировать полный transcript |
PermissionRequest |
✅ | ✅ | Permission dialog отобразится | Custom permission handling |
Notification |
✅ | ✅ | Agent status messages | Отправить в Slack/PagerDuty |
Пример: Блокировать .env файлы
import asyncio
from claude_agent_sdk import (
ClaudeSDKClient,
ClaudeAgentOptions,
HookMatcher,
)
async def protect_env_files(input_data, tool_use_id, context):
file_path = input_data["tool_input"].get("file_path", "")
file_name = file_path.split("/")[-1]
if file_name == ".env":
return {
"hookSpecificOutput": {
"hookEventName": input_data["hook_event_name"],
"permissionDecision": "deny",
"permissionDecisionReason": "Cannot modify .env files",
}
}
return {}
async def main():
options = ClaudeAgentOptions(
hooks={
"PreToolUse": [HookMatcher(matcher="Write|Edit", hooks=[protect_env_files])]
}
)
async with ClaudeSDKClient(options=options) as client:
await client.query("Update the database configuration")
async for message in client.receive_response():
print(message)
asyncio.run(main())
Конфигурация hooks
options = ClaudeAgentOptions(
hooks={
"PreToolUse": [
HookMatcher(matcher="Bash", hooks=[my_callback])
]
}
)
Matchers
Matchers фильтруют когда callbacks срабатывают. Для tool-based hooks: match against tool name.
// Exact match
{ matcher: "Write|Edit" } // Write или Edit
{ matcher: "Write, Edit" } // То же
// Regex
{ matcher: "^mcp__" } // Все MCP инструменты
{ matcher: "Edit.*" } // Edit и NotebookEdit
// Wildcard (exact-match characters only)
{ matcher: "*" } // Все события
Callback inputs и outputs
Inputs:
{
session_id: string
cwd: string
hook_event_name: string
tool_name?: string
tool_input?: Record<string, unknown>
agent_id?: string // При вызове внутри субагента
agent_type?: string
}
Outputs:
{
systemMessage?: string // Сообщение пользователю
continue?: boolean // Продолжать ли выполнение
hookSpecificOutput?: {
permissionDecision?: "allow" | "deny" | "ask" | "defer"
permissionDecisionReason?: string
updatedInput?: Record<string, unknown>
additionalContext?: string
}
}
Примеры
Логирование всех изменений файлов
async def log_file_change(input_data, tool_use_id, context):
file_path = input_data.get("tool_input", {}).get("file_path", "unknown")
with open("./audit.log", "a") as f:
f.write(f"{datetime.now()}: modified {file_path}\n")
return {}
options = ClaudeAgentOptions(
hooks={
"PostToolUse": [
HookMatcher(matcher="Edit|Write", hooks=[log_file_change])
]
}
)
Перенаправить в sandbox
async def redirect_to_sandbox(input_data, tool_use_id, context):
if input_data["tool_name"] == "Write":
original_path = input_data["tool_input"].get("file_path", "")
return {
"hookSpecificOutput": {
"hookEventName": input_data["hook_event_name"],
"permissionDecision": "allow",
"updatedInput": {
**input_data["tool_input"],
"file_path": f"/sandbox{original_path}",
},
}
}
return {}
Отправить webhook после каждого инструмента
import asyncio
import json
import urllib.request
from datetime import datetime
def _send_webhook(tool_name):
data = json.dumps({
"tool": tool_name,
"timestamp": datetime.now().isoformat(),
}).encode()
req = urllib.request.Request(
"https://api.example.com/webhook",
data=data,
headers={"Content-Type": "application/json"},
method="POST",
)
urllib.request.urlopen(req)
async def webhook_notifier(input_data, tool_use_id, context):
if input_data["hook_event_name"] != "PostToolUse":
return {}
try:
await asyncio.to_thread(_send_webhook, input_data["tool_name"])
except Exception as e:
print(f"Webhook request failed: {e}")
return {}
Отслеживание субагента
async def subagent_tracker(input_data, tool_use_id, context):
print(f"[SUBAGENT] Completed: {input_data['agent_id']}")
print(f" Transcript: {input_data['agent_transcript_path']}")
print(f" Tool use ID: {tool_use_id}")
return {}
options = ClaudeAgentOptions(
hooks={"SubagentStop": [HookMatcher(hooks=[subagent_tracker])]}
)
Permissions: Система управления доступом
Permission system контролирует какие инструменты агент может использовать и на какие файлы/домены может получить доступ.
Трёхуровневая система
| Тип инструмента | Пример | Требует одобрения? | "Don't ask again"? |
|---|---|---|---|
| Read-only | File reads, Grep | Нет, в рабочей директории | N/A |
| Bash commands | Shell execution | Да, кроме встроенного набора read-only | Постоянно per command |
| File modification | Edit/Write files | Да | До конца сессии |
Permission modes
| Mode | Описание |
|---|---|
default (manual) |
Стандартно: prompt на первом использовании каждого инструмента |
acceptEdits |
Автопринятие file edits и mkdir, touch, mv, cp в рабочей директории |
plan |
Читать и run read-only commands, но не редактировать |
auto |
Auto-approve с background safety checks |
dontAsk |
Auto-deny unless pre-approved via /permissions |
bypassPermissions |
Skip prompts (кроме явных ask rules и rm -rf /) |
Синтаксис правил
Tool
Tool(specifier)
Примеры правил
{
"permissions": {
"allow": [
"Bash(npm run build)", // Точный command
"Bash(npm run test *)", // Prefix с wildcard
"Read(./.env)", // Чтение .env
"Read(~/Documents/*.pdf)", // Home-relative path
"WebFetch(domain:example.com)", // Только example.com
"Agent(code-reviewer)", // Специфичный субагент
"mcp__github__list_issues" // MCP инструмент
],
"deny": [
"Bash(git push *)", // Блокировать git push
"Bash(curl *)", // Блокировать curl
"Read(/secrets/**)", // Блокировать secrets
"mcp__*" // Блокировать все MCP
],
"ask": [
"Bash(rm *)", // Просить подтверждение
"Edit(/config/**)" // Просить для конфигов
]
}
}
Bash Wildcards
Bash(npm run *) // npm run <anything>
Bash(* install) // <anything> install
Bash(git * main) // git <anything> main
Bash(ls *) // Boundary: ls -la (✅), но не lsof
Bash(ls*) // No boundary: оба матчат
Read & Edit patterns (gitignore style)
Read(//Users/alice/secrets/**) // Absolute path
Read(~/Documents/*.pdf) // Home-relative
Edit(/src/**/*.ts) // Project-relative
Read(*.env) // Current directory relative
WebFetch domain rules
WebFetch(domain:example.com) // example.com только
WebFetch(domain:*.example.com) // Все поддомены (не сам example.com)
WebFetch(domain:*.*.example.com) // example.com и поддомены
WebFetch(domain:*) // Все домены
MCP rules
mcp__puppeteer // Все инструменты от puppeteer
mcp__puppeteer__puppeteer_navigate // Конкретный инструмент
Приоритет правил
- Deny (самый высокий приоритет)
- Ask
- Allow (самый низкий приоритет)
Первое совпадение в этом порядке определяет исход.
Расширение permissions с hooks
Hooks могут выполнять custom permission evaluation:
# Hook с priority
# Blocking hook (exit code 2) применяется ДО permission rules
# Deny rules ВСЕ РАВНО имеют приоритет
Working directories
По умолчанию Claude имеет доступ к файлам в директории запуска. Расширить можно:
claude --add-dir /path/to/another/project
Или в сессии:
/add-dir /path/to/another/project
Или persistent в settings:
{
"permissions": {
"additionalDirectories": ["/path/to/project1", "/path/to/project2"]
}
}
Managed settings
Для организаций: администраторы могут развернуть managed settings, которые не могут быть переопределены пользователем или проектом.
Delivery mechanisms: - MDM/OS-level policies - Managed settings files - Server-managed settings - Self-hosted Claude apps gateway
Configuration: Настройка системы
Четыре scope конфигурации
┌─────────────────────────────────┐
│ 1. Managed (server/plist/reg) │ ← Самый высокий приоритет
├─────────────────────────────────┤
│ 2. Command line arguments │
├─────────────────────────────────┤
│ 3. Local project (.claude/*.local.json) │
├─────────────────────────────────┤
│ 4. Shared project (.claude/) │
├─────────────────────────────────┤
│ 5. User (~/.claude/) │ ← Самый низкий приоритет
└─────────────────────────────────┘
Основные файлы конфигурации
~/.claude/settings.json # User settings (все проекты)
.claude/settings.json # Project settings (shared с team)
.claude/settings.local.json # Personal overrides (gitignored)
.mcp.json # Project-scoped MCP серверы
CLAUDE.md / .claude/CLAUDE.md # System instructions & memory
JSON Schema
{
"$schema": "https://json.schemastore.org/claude-code-settings.json",
"permissions": {
"allow": ["Bash(npm run lint)"],
"deny": ["Bash(curl *)"],
"additionalDirectories": ["/path/to/project"]
},
"model": "claude-3-5-sonnet",
"autoMemoryEnabled": true,
"editorMode": "vim",
"env": {
"CLAUDE_CODE_ENABLE_TELEMETRY": "1"
},
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"command": "~/.claude/hooks/pre-tool-use.sh"
}
]
},
"defaultMode": "acceptEdits",
"sandboxing": {
"enabled": true,
"filesystem": {
"allowRead": ["/tmp", "/Users/alice/public"],
"denyRead": ["/Users/alice/private"]
}
}
}
Популярные настройки
| Настройка | Тип | Описание |
|---|---|---|
model |
string | Default model (alias: sonnet, opus, etc) |
defaultMode |
string | Permission mode по умолчанию |
autoMemoryEnabled |
boolean | Auto-capture learnings |
editorMode |
string | vim, emacs, или nano |
permissions |
object | Permission rules |
hooks |
object | Hook configurations |
env |
object | Environment variables |
outputStyle |
string | How agent formats responses |
Когда edits вступают в силу
Instant reload (no restart):
- permissions
- hooks
- apiKeyHelper
- Большинство настроек
Restart required:
- model (используй /model command вместо этого)
- outputStyle
Когда использовать каждый scope
- Managed: Organization-wide security policies
- User: Personal preferences, tools для всех проектов
- Project: Team-shared settings, standardized tooling
- Local: Personal overrides, testing, machine-specific
Headless режим (claude -p)
Headless mode позволяет piping логов в Claude и использование в CI/CD.
# Анализировать логи
tail -200 app.log | claude -p "Slack me if you see anomalies"
# Автоматизировать переводы в CI
claude -p "translate new strings into French and raise a PR for review"
# Bulk operations по файлам
git diff main --name-only | claude -p "review these changed files for security"
Параметры
claude -p "your prompt" # Pipe mode (stdin)
claude -p "prompt" < input.txt # From file
claude "regular prompt" # Normal interactive mode
Agent Teams: Многоагентная координация
Параллельное выполнение
Несколько субагентов могут выполняться одновременно для независимых подзадач:
async def main():
async for message in query(
prompt="Review the authentication module",
options=ClaudeAgentOptions(
allowed_tools=["Read", "Grep", "Glob", "Agent"],
agents={
"style-checker": AgentDefinition(...),
"security-scanner": AgentDefinition(...),
"test-coverage": AgentDefinition(...),
},
),
):
if hasattr(message, "result"):
print(message.result)
Coordinate agents
Главный агент распределяет работу, assign subtasks, и merges results.
Dynamic workflows
Для координации десятков/сотен агентов используй Workflow tool (TypeScript SDK v0.3.149+):
for await (const message of query({
prompt: "Process 100 customer records in parallel",
options: {
allowedTools: ["Workflow"],
// Workflow конфигурация
}
})) {
if ("result" in message) console.log(message.result);
}
Заключение: Интеграция всех компонентов
Claude Code представляет собой многоуровневую систему, где:
- Agent SDK даёт programmatic access ко всем возможностям
- Субагенты enable parallelization и specialization
- MCP connects external tools & data sources
- Skills package repeatable workflows
- Hooks intercept & control behaviour
- Permissions enforce security & safety
- Configuration scopes settings по уровням организации
Типичный production workflow
# 1. Инициализировать с MCP & субагентами
options = ClaudeAgentOptions(
mcp_servers={"github": {...}, "postgres": {...}},
agents={
"code-reviewer": AgentDefinition(...),
"security-scanner": AgentDefinition(...),
},
allowed_tools=["Read", "Bash", "Agent", "mcp__github__*"],
permission_mode="acceptEdits",
hooks={
"PreToolUse": [
HookMatcher(matcher="Bash(rm *)", hooks=[safety_check])
]
}
)
# 2. Запустить main agent с instructions
async for message in query(
prompt="Review PR #123 for security and code quality",
options=options
):
if hasattr(message, "result"):
process_result(message.result)
# 3. Субагенты запустятся параллельно
# 4. MCP инструменты доступны для обоих
# 5. Hooks блокируют опасные операции
# 6. Permissions enforcement гарантирует compliance
Ресурсы и ссылки
- Claude Code Docs: https://code.claude.com/docs
- Agent SDK Overview: https://code.claude.com/docs/en/agent-sdk/overview
- Subagents: https://code.claude.com/docs/en/agent-sdk/subagents
- MCP Documentation: https://code.claude.com/docs/en/agent-sdk/mcp
- Skills Guide: https://code.claude.com/docs/en/skills
- Hooks Guide: https://code.claude.com/docs/en/agent-sdk/hooks
- Permissions: https://code.claude.com/docs/en/permissions
- Configuration: https://code.claude.com/docs/en/configuration
- MCP Server Directory: https://github.com/modelcontextprotocol/servers
- Agent SDK Examples: https://github.com/anthropics/claude-agent-sdk-demos
- Python SDK Changelog: https://github.com/anthropics/claude-agent-sdk-python/blob/main/CHANGELOG.md
- TypeScript SDK Changelog: https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/CHANGELOG.md
Дата последнего обновления документации: 2026-07-12
Версия Claude Code: 2.1.200 и позже
Python Agent SDK: 0.3.149+
TypeScript Agent SDK: 0.3.149+