Claude Code Architecture Deep Dive
Overview
Claude Code 是 Anthropic 的官方 CLI 代理编程工具,遵循 Unix 哲学 —— 可组合、可脚本化。核心设计模式是反馈循环: gather context -> take action -> verify work -> repeat。
Core Architecture
Design Principles
- Unix Philosophy: 可组合、可脚本化,与现有工具协作
- Feedback Loop: gather context -> take action -> verify work -> repeat
- Hierarchical Config: Managed > CLI > Local > Project > User
- Context Isolation: 子代理独立上下文窗口
- Security First: Deny 规则优先于 Allow
Terminal-First Design
Claude Code 直接在开发者终端中运行,支持管道和脚本化:
# Pipeline exampletail -f app.log | claude -p "Slack me if you see any anomalies"
# Automation exampleclaude -p "If there are new text strings, translate them into French and raise a PR"Built-in Tools
Claude Code 提供 14+ 核心工具:
File Operations
| Tool | Description | Permission |
|---|---|---|
| Read | 读取文件 (支持图片、PDF、Jupyter notebooks) | No |
| Write | 创建/覆盖文件 | Yes |
| Edit | 精确字符串替换编辑 | Yes |
| MultiEdit | 原子化多次编辑单个文件 | Yes |
| Glob | 快速文件模式匹配 (如 **/*.js) | No |
| Grep | 基于正则的内容搜索 | No |
Execution & Search
| Tool | Description | Permission |
|---|---|---|
| Bash | 执行 shell 命令 (默认超时 2 分钟,最大 10 分钟) | Yes |
| WebSearch | 网络搜索,支持域名过滤 | Yes |
| WebFetch | 获取并 AI 分析网页内容 (缓存 15 分钟,最大 10MB) | Yes |
| Task | 启动子代理处理复杂任务 | No |
Task Management
| Tool | Description | Permission |
|---|---|---|
| TodoRead/TodoWrite | 结构化任务跟踪 | No |
| AskUserQuestion | 多选题式用户交互 | No |
| NotebookEdit | 编辑 Jupyter notebook cells | Yes |
| Skill | 执行自定义 skill | Yes |
| KillShell | 终止后台 bash 进程 | No |
Subagent System
子代理是运行在独立上下文窗口中的专用 AI 助手,每个都有自定义 system prompt 和工具访问权限。
Built-in Subagents
| Agent | Model | Tools | Purpose |
|---|---|---|---|
| Explore | Haiku | Read-only (Read, Grep, Glob, Bash) | 快速代码库搜索和分析 |
| Plan | Inherits | Read-only | 计划模式下的研究代理 |
| general-purpose | Inherits | All tools | 复杂多步骤任务 |
| Bash | Inherits | Bash only | 独立上下文执行终端命令 |
| statusline-setup | Sonnet | All | 配置状态栏 |
| Claude Code Guide | Haiku | All | 回答 Claude Code 使用问题 |
Context Handling
- Explore: 全新上下文 (搜索任务通常独立)
- general-purpose / Plan: 继承完整上下文
Creating Custom Subagents
在 .claude/agents/ 目录创建 Markdown 文件:
---name: code-reviewerdescription: Reviews code for quality and best practicestools: Read, Glob, Grepmodel: sonnetpermissionMode: defaultskills: - api-conventionshooks: PreToolUse: - matcher: "Bash" hooks: - type: command command: "./scripts/validate-readonly.sh"---
You are a code reviewer. When invoked, analyze the code and providespecific, actionable feedback on quality, security, and best practices.Supported Frontmatter Fields
| Field | Required | Description |
|---|---|---|
name | Yes | 唯一标识符 (lowercase + hyphens) |
description | Yes | 何时委托给此子代理 |
tools | No | 允许的工具 (省略则继承全部) |
disallowedTools | No | 禁用的工具 |
model | No | sonnet, opus, haiku, or inherit |
permissionMode | No | default, acceptEdits, dontAsk, bypassPermissions, plan |
skills | No | 预加载的 skills |
hooks | No | 生命周期钩子 |
Key Limitations
- 子代理 不能嵌套 (不能再创建子代理)
- MCP 工具在后台子代理中 不可用
- 每次调用创建新实例,需显式恢复上下文
Hooks System
Hooks 允许在代理生命周期的特定点注入自定义逻辑。
Hook Events
| Event | When it fires |
|---|---|
SessionStart | 会话开始/恢复 |
UserPromptSubmit | 用户提交 prompt |
PreToolUse | 工具执行前 |
PermissionRequest | 权限对话框出现时 |
PostToolUse | 工具成功执行后 |
PostToolUseFailure | 工具执行失败后 |
SubagentStart | 子代理启动 |
SubagentStop | 子代理结束 |
Stop | Claude 完成响应 |
PreCompact | 上下文压缩前 |
SessionEnd | 会话终止 |
Notification | Claude Code 发送通知 |
Configuration
Hooks 在 settings 文件中配置:
~/.claude/settings.json(user).claude/settings.json(project).claude/settings.local.json(local, gitignored)
{ "hooks": { "PreToolUse": [ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "./scripts/validate-edit.sh", "timeout": 60 } ] } ], "PostToolUse": [ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "./scripts/run-formatter.sh" } ] } ] }}Matcher Patterns
| Pattern | Description | Example |
|---|---|---|
| Exact | 精确匹配 | Write |
| Regex | 正则匹配 | Edit|Write |
| Wildcard | 匹配所有 | * or "" |
| Prefix | 前缀匹配 | Notebook.* |
Hook Input Format
所有 hooks 通过 stdin 接收 JSON:
{ "session_id": "string", "transcript_path": "/path/to/transcript.jsonl", "cwd": "/current/working/directory", "permission_mode": "default", "hook_event_name": "PreToolUse", "tool_name": "Bash", "tool_input": { "command": "npm run test", "timeout": 120000 }, "tool_use_id": "toolu_01ABC123..."}Hook Output Format
{ "continue": true, "stopReason": "string", "suppressOutput": true, "systemMessage": "string", "hookSpecificOutput": { "hookEventName": "PreToolUse", "permissionDecision": "allow|deny|ask", "permissionDecisionReason": "string", "updatedInput": { "field": "new_value" }, "additionalContext": "string" }}Exit Codes
| Code | Meaning |
|---|---|
| 0 | 成功,解析 JSON 输出 |
| 2 | 阻塞错误,仅使用 stderr |
| Other | 非阻塞错误 (verbose 模式显示) |
PreToolUse: Input Modification Example
PreToolUse hooks 可以在执行前修改工具输入:
#!/usr/bin/env python3import jsonimport sys
input_data = json.load(sys.stdin)
if input_data.get("tool_name") == "Write": file_path = input_data.get("tool_input", {}).get("file_path", "") # Redirect to sandbox if file_path.startswith("/etc/"): print(json.dumps({ "hookSpecificOutput": { "hookEventName": "PreToolUse", "permissionDecision": "deny", "permissionDecisionReason": "System directory write blocked" } })) sys.exit(0)
sys.exit(0)MCP Integration
MCP (Model Context Protocol) 是连接 AI 与外部工具的开放标准,被称为 “AI 的 USB-C”。
Transport Types
| Type | Use Case | Example |
|---|---|---|
| HTTP (推荐) | 远程服务 | claude mcp add --transport http notion https://mcp.notion.com/mcp |
| Stdio | 本地服务 | claude mcp add --transport stdio db -- npx @bytebase/dbhub |
| SSE (废弃) | 旧版远程 | claude mcp add --transport sse asana https://mcp.asana.com/sse |
Scope Hierarchy
| Scope | Storage | Use Case |
|---|---|---|
| Local | ~/.claude.json (project path) | 个人、敏感凭证 |
| Project | .mcp.json | 团队共享 (version control) |
| User | ~/.claude.json | 跨项目个人工具 |
Precedence: Local > Project > User
Server Management
# Add serversclaude mcp add --transport http notion https://mcp.notion.com/mcpclaude mcp add --transport stdio db -- npx @bytebase/dbhub --dsn "postgres://..."
# Manageclaude mcp listclaude mcp get githubclaude mcp remove github
# Check status in Claude Code/mcpAdvanced Features
MCP Resources - 通过 @ 提及引用外部资源:
> Can you analyze @github:issue://123 and suggest a fix?> Compare @postgres:schema://users with @docs:file://api/documentationMCP Prompts as Commands:
> /mcp__github__list_prs> /mcp__github__pr_review 456Tool Search - 工具描述超过上下文 10% 时自动启用:
ENABLE_TOOL_SEARCH=auto:5 claude # Custom 5% thresholdENABLE_TOOL_SEARCH=true claude # Always enabledOutput Limits
- Warning threshold: 10,000 tokens
- Default limit: 25,000 tokens
- Configure:
MAX_MCP_OUTPUT_TOKENS=50000
Configuration Example
.mcp.json (Project scope):
{ "mcpServers": { "github": { "type": "http", "url": "https://api.githubcopilot.com/mcp/", "headers": { "Authorization": "Bearer ${GITHUB_TOKEN}" } }, "db": { "type": "stdio", "command": "npx", "args": ["-y", "@bytebase/dbhub", "--dsn", "${DATABASE_URL}"] } }}Permissions System
Configuration Hierarchy (Precedence)
- Managed (
managed-settings.json) - 系统级,IT 部署,最高优先级 - CLI arguments - 命令行参数
- Local (
.claude/settings.local.json) - 个人本地,gitignored - Project (
.claude/settings.json) - 项目共享 - User (
~/.claude/settings.json) - 用户级
Permission Rules
| Rule | Behavior |
|---|---|
| allow | 自动批准匹配的命令 |
| deny | 完全阻止匹配的命令 (最高优先级) |
| ask | 强制确认提示 |
Evaluation order: deny -> allow -> ask
Configuration Example
{ "permissions": { "allow": [ "Bash(npm run:*)", "Bash(git commit:*)", "Read(./src/**)" ], "deny": [ "Read(./.env*)", "Read(./secrets/**)", "Bash(rm -rf:*)", "Bash(curl:*)" ], "ask": [ "Bash(git push:*)" ], "defaultMode": "default" }}Pattern Syntax
| Pattern | Description | Example |
|---|---|---|
:* (suffix) | 前缀匹配,带词边界 | Bash(npm run:*) matches npm run test |
* (anywhere) | Glob 匹配 | Bash(git * main) |
| Exact | 完全匹配 | Read(./.env) |
| Glob | 目录模式 | Edit(./src/**) |
| Domain | 域名匹配 | WebFetch(domain:example.com) |
Tool-Specific Rules
{ "permissions": { "allow": [ "Bash(npm run:*)", // Bash prefix "Bash(git * main)", // Bash glob "Read(./src/**)", // Read directory "WebFetch(domain:docs.com)", // WebFetch domain "MCP(server:tool)", // MCP tool "Task(Explore)" // Subagent ] }}Permission Modes
| Mode | Behavior |
|---|---|
default | 首次使用工具时提示 |
acceptEdits | 自动接受文件编辑 |
plan | 只读模式 (分析但不修改) |
bypassPermissions | 跳过所有权限检查 (危险) |
Security: PreToolUse Hook Alternative
由于权限系统存在已知问题,使用 PreToolUse hook 作为更可靠的保护:
#!/usr/bin/env python3import jsonimport sys
input_data = json.load(sys.stdin)tool_name = input_data.get("tool_name")tool_input = input_data.get("tool_input", {})
# Block sensitive file accessif tool_name == "Read": file_path = tool_input.get("file_path", "") if ".env" in file_path or "secrets" in file_path: print(json.dumps({ "hookSpecificOutput": { "hookEventName": "PreToolUse", "permissionDecision": "deny", "permissionDecisionReason": "Sensitive file access blocked" } })) sys.exit(0)
sys.exit(0)Skills & Slash Commands
Skills
存储在 .claude/skills/ 目录的 Markdown 文件:
---name: api-developerdescription: Implement API endpoints following conventionsagent: general-purpose---
## Instructions
Follow REST conventions when implementing API endpoints.Use proper HTTP status codes and error handling.特点:
- 可被 Claude 主动调用
- 支持捆绑脚本和模板
- 字符预算: 15,000 (可通过
SLASH_COMMAND_TOOL_CHAR_BUDGET调整)
Slash Commands
存储在 .claude/commands/ 目录:
---allowed-tools: Bash, Read---
Run the tests for: $ARGUMENTS使用: /<command-name> [arguments]
Skills vs Slash Commands
| Feature | Skills | Slash Commands |
|---|---|---|
| Location | .claude/skills/ | .claude/commands/ |
| Claude 主动调用 | Yes | No |
| 支持脚本捆绑 | Yes | No |
| 终端自动补全 | No | Yes |
Environment Variables
Authentication
ANTHROPIC_API_KEY=sk-...CLAUDE_CODE_USE_BEDROCK=trueCLAUDE_CODE_USE_VERTEX=trueCLAUDE_CODE_USE_FOUNDRY=trueModel Configuration
ANTHROPIC_MODEL=claude-sonnet-4-5-20250929ANTHROPIC_DEFAULT_HAIKU_MODEL=claude-3-5-haiku-20241022ANTHROPIC_DEFAULT_SONNET_MODEL=claude-3-5-sonnet-20241022ANTHROPIC_DEFAULT_OPUS_MODEL=claude-4-1-opus-20250805CLAUDE_CODE_SUBAGENT_MODEL=claude-haiku-3-5-20241022Performance Tuning
CLAUDE_CODE_MAX_OUTPUT_TOKENS=32000 # Default: 32000, Max: 64000CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS=20000MAX_MCP_OUTPUT_TOKENS=25000MAX_THINKING_TOKENS=31999CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=95 # Auto-compaction thresholdBash Configuration
BASH_DEFAULT_TIMEOUT_MS=30000BASH_MAX_TIMEOUT_MS=3600000BASH_MAX_OUTPUT_LENGTH=100000CLAUDE_CODE_SHELL=bashTelemetry & Updates
DISABLE_TELEMETRY=1DISABLE_ERROR_REPORTING=1DISABLE_AUTOUPDATER=1Complete Settings Example
{ "permissions": { "allow": [ "Bash(npm run:*)", "Bash(git commit:*)", "Bash(docker compose:*)", "Read(.)" ], "deny": [ "Bash(git push:*)", "Bash(rm -rf:*)", "Read(.env)", "Read(.env.*)", "Read(./secrets/**)" ], "ask": [ "Bash(git push:*)" ], "defaultMode": "default" }, "env": { "NODE_ENV": "development", "CLAUDE_CODE_ENABLE_TELEMETRY": "1" }, "hooks": { "PreToolUse": [ { "matcher": "Bash", "hooks": [ { "type": "command", "command": "./scripts/validate-bash.sh" } ] } ], "PostToolUse": [ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "./scripts/format-file.sh" } ] } ] }, "sandbox": { "enabled": true, "excludedCommands": ["docker"] }, "attribution": { "commit": "Generated with Claude Code", "pr": "" }, "model": "claude-sonnet-4-5-20250929", "language": "english", "alwaysThinkingEnabled": false}