Version analyzed: March 31, 2026 leak
This page provides a bird’s-eye view of Claude Code’s architecture based on the leaked source code.
This page provides a bird’s-eye view of Claude Code’s architecture based on the leaked source code.
System Architecture
Claude Code is built as a multi-layered system with clear separation of concerns. Here’s the complete architecture:Layer Breakdown
1. Entry Layer
The entry point and user interface layer. main.tsx- CLI argument parsing via Commander.js
- Initialization and bootstrap
- Command routing
- Session management
- React + Ink terminal UI
- User input handling
- Message rendering
- Status indicators
2. Command & Tool Registry
Central registries for all available commands and tools. commands.ts- 50+ slash commands (e.g.,
/commit,/review,/config) - Command metadata and handlers
- Permission requirements
- User-facing command interface
- 40+ tool definitions
- Tool schemas (Zod validation)
- Permission models
- Tool execution wrappers
3. Core Engine
The heart of the agentic system. QueryEngine.ts- Orchestrates the complete agentic loop
- Manages conversation state
- Handles tool execution
- Implements retry logic
- Token budget management
- Context window handling
- Direct API communication
- Streaming response handling
- Error handling and retries
- Usage tracking
4. State Management
Three-tier state architecture: AppStateStore.ts (React State)- UI state (expanded views, selections)
- Tool permission context
- MCP connections
- Tasks and teammates
- Settings
- JSONL transcript format
- Message history
- Tool results
- Session metadata
- Resume capability
- Session ID
- Working directory
- Model configuration
- Cost tracking
- Telemetry state
5. API Layer
Communication with Claude models. services/api/claude.ts- Anthropic SDK wrapper
- Message normalization
- Tool schema injection
- Prompt caching
- Streaming implementation
- Direct: Anthropic API (default)
- Bedrock: AWS integration
- Vertex AI: Google Cloud integration
6. Tool Execution
The actual tool implementations.| Category | Tools |
|---|---|
| File Operations | FileRead, FileWrite, FileEdit, Glob, Grep |
| Shell | Bash, PowerShell, REPL |
| Web | WebFetch, WebSearch |
| Agent | AgentTool (spawn sub-agents) |
| MCP | ListMcpResources, ReadMcpResource, adapted MCP server tools |
| LSP | LSPTool (language server features) |
| Tasks | TaskCreate, TaskUpdate, TaskStop |
| Teams | TeamCreate, TeamDelete, SendMessage |
| Plan Mode | EnterPlanMode, ExitPlanMode |
| Worktree | EnterWorktree, ExitWorktree |
7. External Integrations
MCP (Model Context Protocol)- Connect to external MCP servers
- Tool discovery and invocation
- Resource access
- Authentication handling
- Code intelligence features
- Go-to-definition
- Find references
- Diagnostics
- VS Code extension integration
- JetBrains plugin integration
- Bidirectional communication
- Remote control capabilities
8. Context & Prompts
System prompt assembly and context gathering. constants/prompts.ts- System prompt builder
- Tool usage instructions
- Model-specific guidance
- Dynamic context injection
- User context (git status, environment)
- System context (OS, shell, capabilities)
- Working directory info
- MEMORY.md file management
- Persistent memory across sessions
- Auto-memory system
- Memory freshness tracking
Data Flow
User Input → Agent Output
Key Design Patterns
1. Tool System
Every tool follows a consistent pattern:The following block is illustrative pseudocode, not verbatim source.
2. Permission Model
Three-tier permission system:- Permission Mode - Global setting (default, plan, auto, bypass)
- Tool Rules - Per-tool allow/deny rules
- Runtime Checks - Dynamic permission evaluation
3. State Persistence
JSONL (JSON Lines) format for session transcripts:4. Streaming Architecture
All API responses stream incrementally:- Text deltas rendered in real-time
- Tool calls executed as they arrive
- Thinking blocks displayed progressively
- User can interrupt at any time
5. Context Management
Automatic context compression:- Summarization when approaching limits
- Tool result truncation
- Message compaction
- Cache-aware prompt assembly
Component Responsibilities
QueryEngine Responsibilities
- Orchestrate the agentic loop
- Manage conversation history
- Execute tools with permission checks
- Handle errors and retries
- Track token usage and costs
- Implement thinking mode
- Manage context window
AppState Responsibilities
- Store UI state
- Track MCP connections
- Manage tasks and teammates
- Hold permission context
- Cache settings
- Coordinate React renders
Tool Responsibilities
- Validate input schemas
- Execute operations safely
- Return structured results
- Render output for display
- Report progress
- Handle errors gracefully
MCP Client Responsibilities
- Connect to MCP servers
- Discover tools and resources
- Handle authentication
- Execute remote tools
- Manage server lifecycle
- Report connection status
Extensibility Points
Claude Code is designed to be extended:1. Plugins
Located in Claude config/plugin directories under the Claude config home (for example~/.claude/...) and project-level config:
- Add new tools
- Register hooks
- Provide MCP servers
- Customize behavior
2. Skills
Located in project/user/policy skill directories (for example.claude/skills and user-level Claude config skills dirs):
- Markdown-based workflows
- Reusable prompts
- Custom commands
- Conditional activation
3. MCP Servers
Configured via Claude settings sources (for example user/project/local/policy settings):- External tool providers
- Resource access
- Custom integrations
- Third-party services
4. Hooks
Event-driven automation:preToolUse- Before tool executionpostToolUse- After tool executionfileEdited- On file changespromptSubmit- On user inputagentStop- On agent completion
Performance Optimizations
1. Lazy Loading
- React components loaded on demand
- Feature-gated code eliminated at build time
- Dynamic imports for heavy modules
2. Caching
- Prompt caching (Anthropic API feature)
- Settings cache
- File state cache
- MCP tool schema cache
3. Parallel Execution
- Independent tool calls run in parallel
- MCP server connections established concurrently
- File operations batched when possible
4. Streaming
- Incremental response rendering
- Progressive tool execution
- Real-time user feedback
Security Architecture
Permission System
- Default Mode: Prompt for risky operations
- Plan Mode: More restrictive, requires explicit approval
- Auto Mode: Transcript classifier determines safety
- Bypass Mode: No prompts (dangerous, requires explicit opt-in)
Sandboxing
- Shell execution can run directly or through sandbox adapters, depending on mode/configuration
- File operations respect permission rules
- MCP servers run as separate processes
- Bridge connections require authentication
Audit Trail
- All tool executions logged
- Session transcripts persisted
- Permission denials recorded
- Cost tracking for accountability
Related Links
Control Flow
Detailed flow from user input to agent output
Project Structure
Complete directory structure and file organization
Agent Loop
Deep dive into the agentic loop implementation
Tools Overview
Understanding the tool system architecture