Claude Code Architecture Deep Dive

Overview

Claude Code 是 Anthropic 的官方 CLI 代理编程工具,遵循 Unix 哲学 —— 可组合、可脚本化。核心设计模式是反馈循环: gather context -> take action -> verify work -> repeat

Core Architecture

Design Principles

  1. Unix Philosophy: 可组合、可脚本化,与现有工具协作
  2. Feedback Loop: gather context -> take action -> verify work -> repeat
  3. Hierarchical Config: Managed > CLI > Local > Project > User
  4. Context Isolation: 子代理独立上下文窗口
  5. Security First: Deny 规则优先于 Allow

Terminal-First Design

Claude Code 直接在开发者终端中运行,支持管道和脚本化:

# Pipeline example
tail -f app.log | claude -p "Slack me if you see any anomalies"
# Automation example
claude -p "If there are new text strings, translate them into French and raise a PR"

Built-in Tools

Claude Code 提供 14+ 核心工具:

File Operations

ToolDescriptionPermission
Read读取文件 (支持图片、PDF、Jupyter notebooks)No
Write创建/覆盖文件Yes
Edit精确字符串替换编辑Yes
MultiEdit原子化多次编辑单个文件Yes
Glob快速文件模式匹配 (如 **/*.js)No
Grep基于正则的内容搜索No
ToolDescriptionPermission
Bash执行 shell 命令 (默认超时 2 分钟,最大 10 分钟)Yes
WebSearch网络搜索,支持域名过滤Yes
WebFetch获取并 AI 分析网页内容 (缓存 15 分钟,最大 10MB)Yes
Task启动子代理处理复杂任务No

Task Management

ToolDescriptionPermission
TodoRead/TodoWrite结构化任务跟踪No
AskUserQuestion多选题式用户交互No
NotebookEdit编辑 Jupyter notebook cellsYes
Skill执行自定义 skillYes
KillShell终止后台 bash 进程No

Subagent System

子代理是运行在独立上下文窗口中的专用 AI 助手,每个都有自定义 system prompt 和工具访问权限。

Built-in Subagents

AgentModelToolsPurpose
ExploreHaikuRead-only (Read, Grep, Glob, Bash)快速代码库搜索和分析
PlanInheritsRead-only计划模式下的研究代理
general-purposeInheritsAll tools复杂多步骤任务
BashInheritsBash only独立上下文执行终端命令
statusline-setupSonnetAll配置状态栏
Claude Code GuideHaikuAll回答 Claude Code 使用问题

Context Handling

  • Explore: 全新上下文 (搜索任务通常独立)
  • general-purpose / Plan: 继承完整上下文

Creating Custom Subagents

.claude/agents/ 目录创建 Markdown 文件:

---
name: code-reviewer
description: Reviews code for quality and best practices
tools: Read, Glob, Grep
model: sonnet
permissionMode: default
skills:
- api-conventions
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/validate-readonly.sh"
---
You are a code reviewer. When invoked, analyze the code and provide
specific, actionable feedback on quality, security, and best practices.

Supported Frontmatter Fields

FieldRequiredDescription
nameYes唯一标识符 (lowercase + hyphens)
descriptionYes何时委托给此子代理
toolsNo允许的工具 (省略则继承全部)
disallowedToolsNo禁用的工具
modelNosonnet, opus, haiku, or inherit
permissionModeNodefault, acceptEdits, dontAsk, bypassPermissions, plan
skillsNo预加载的 skills
hooksNo生命周期钩子

Key Limitations

  • 子代理 不能嵌套 (不能再创建子代理)
  • MCP 工具在后台子代理中 不可用
  • 每次调用创建新实例,需显式恢复上下文

Hooks System

Hooks 允许在代理生命周期的特定点注入自定义逻辑。

Hook Events

EventWhen it fires
SessionStart会话开始/恢复
UserPromptSubmit用户提交 prompt
PreToolUse工具执行前
PermissionRequest权限对话框出现时
PostToolUse工具成功执行后
PostToolUseFailure工具执行失败后
SubagentStart子代理启动
SubagentStop子代理结束
StopClaude 完成响应
PreCompact上下文压缩前
SessionEnd会话终止
NotificationClaude 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

PatternDescriptionExample
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

CodeMeaning
0成功,解析 JSON 输出
2阻塞错误,仅使用 stderr
Other非阻塞错误 (verbose 模式显示)

PreToolUse: Input Modification Example

PreToolUse hooks 可以在执行前修改工具输入:

#!/usr/bin/env python3
import json
import 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

TypeUse CaseExample
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

ScopeStorageUse Case
Local~/.claude.json (project path)个人、敏感凭证
Project.mcp.json团队共享 (version control)
User~/.claude.json跨项目个人工具

Precedence: Local > Project > User

Server Management

# Add servers
claude mcp add --transport http notion https://mcp.notion.com/mcp
claude mcp add --transport stdio db -- npx @bytebase/dbhub --dsn "postgres://..."
# Manage
claude mcp list
claude mcp get github
claude mcp remove github
# Check status in Claude Code
/mcp

Advanced Features

MCP Resources - 通过 @ 提及引用外部资源:

> Can you analyze @github:issue://123 and suggest a fix?
> Compare @postgres:schema://users with @docs:file://api/documentation

MCP Prompts as Commands:

> /mcp__github__list_prs
> /mcp__github__pr_review 456

Tool Search - 工具描述超过上下文 10% 时自动启用:

ENABLE_TOOL_SEARCH=auto:5 claude # Custom 5% threshold
ENABLE_TOOL_SEARCH=true claude # Always enabled

Output 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)

  1. Managed (managed-settings.json) - 系统级,IT 部署,最高优先级
  2. CLI arguments - 命令行参数
  3. Local (.claude/settings.local.json) - 个人本地,gitignored
  4. Project (.claude/settings.json) - 项目共享
  5. User (~/.claude/settings.json) - 用户级

Permission Rules

RuleBehavior
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

PatternDescriptionExample
:* (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

ModeBehavior
default首次使用工具时提示
acceptEdits自动接受文件编辑
plan只读模式 (分析但不修改)
bypassPermissions跳过所有权限检查 (危险)

Security: PreToolUse Hook Alternative

由于权限系统存在已知问题,使用 PreToolUse hook 作为更可靠的保护:

#!/usr/bin/env python3
import json
import sys
input_data = json.load(sys.stdin)
tool_name = input_data.get("tool_name")
tool_input = input_data.get("tool_input", {})
# Block sensitive file access
if 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-developer
description: Implement API endpoints following conventions
agent: 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

FeatureSkillsSlash Commands
Location.claude/skills/.claude/commands/
Claude 主动调用YesNo
支持脚本捆绑YesNo
终端自动补全NoYes

Environment Variables

Authentication

ANTHROPIC_API_KEY=sk-...
CLAUDE_CODE_USE_BEDROCK=true
CLAUDE_CODE_USE_VERTEX=true
CLAUDE_CODE_USE_FOUNDRY=true

Model Configuration

ANTHROPIC_MODEL=claude-sonnet-4-5-20250929
ANTHROPIC_DEFAULT_HAIKU_MODEL=claude-3-5-haiku-20241022
ANTHROPIC_DEFAULT_SONNET_MODEL=claude-3-5-sonnet-20241022
ANTHROPIC_DEFAULT_OPUS_MODEL=claude-4-1-opus-20250805
CLAUDE_CODE_SUBAGENT_MODEL=claude-haiku-3-5-20241022

Performance Tuning

CLAUDE_CODE_MAX_OUTPUT_TOKENS=32000 # Default: 32000, Max: 64000
CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS=20000
MAX_MCP_OUTPUT_TOKENS=25000
MAX_THINKING_TOKENS=31999
CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=95 # Auto-compaction threshold

Bash Configuration

BASH_DEFAULT_TIMEOUT_MS=30000
BASH_MAX_TIMEOUT_MS=3600000
BASH_MAX_OUTPUT_LENGTH=100000
CLAUDE_CODE_SHELL=bash

Telemetry & Updates

DISABLE_TELEMETRY=1
DISABLE_ERROR_REPORTING=1
DISABLE_AUTOUPDATER=1

Complete 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
}

References

Read Next

Git 常用命令与技巧

Read Previous

Claude Code Skills 完全指南