How Claude Code Works: Architecture & Internals
A technical deep-dive into Claude Code's internal mechanisms, based on official Anthropic documentation and verified community analysis.
Author: Florian BRUNIAUX | Contributions from Claude (Anthropic)
Reading time: ~25 minutes (full) | ~5 minutes (TL;DR only)
Last verified: February 2026 (Claude Code v2.1.34)
Source Transparency
This document combines three tiers of sources:
| Tier | Description | Confidence | Example |
|---|---|---|---|
| Tier 1 | Official Anthropic documentation | 100% | anthropic.com/engineering/* |
| Tier 2 | Verified reverse-engineering | 70-90% | PromptLayer analysis, code.claude.com behavior |
| Tier 3 | Community inference | 40-70% | Observed but not officially confirmed |
Each claim is marked with its confidence level. Always prefer official documentation when available.
TL;DR - 5 Bullet Summary
Simple Loop: Claude Code runs a
while(tool_call)loop — no DAGs, no classifiers, no RAG. The model decides everything.Eight Core Tools: Bash (universal adapter), Read, Edit, Write, Grep, Glob, Task (sub-agents), TodoWrite. That's the entire arsenal.
Search Strategy Evolution: Early Claude Code versions experimented with RAG using Voyage embeddings for semantic code search. Anthropic switched to grep-based (ripgrep) agentic search after internal benchmarks showed superior performance with lower operational complexity — no index sync required, no security liabilities from external embedding providers. This "Search, Don't Index" philosophy trades latency/tokens for simplicity/security. Community plugins (ast-grep for AST patterns) and MCP servers (Serena for symbols, grepai for RAG) available for specialized needs.
Source: Latent Space podcast (May 2025), ast-grep documentation
200K Token Budget: Context window shared between system prompt, history, tool results, and response buffer. Auto-compacts at ~75-92% capacity.
Sub-agents = Isolation: The
Tasktool spawns sub-agents with their own context. They cannot spawn more sub-agents (depth=1). Only their summary returns.Philosophy: "Less scaffolding, more model" — trust Claude's reasoning instead of building complex orchestration systems around it.
Visual Overview
Before diving into the technical details, this diagram by Mohamed Ali Ben Salem captures the essential architecture:
Source: Mohamed Ali Ben Salem on LinkedIn — Used with attribution
Key insight: Claude Code is NOT a new AI model — it's an orchestration layer that connects Claude (Opus/Sonnet/Haiku) to your development environment through file editing, command execution, and repository navigation.
Table of Contents
- The Master Loop
- The Tool Arsenal
- Context Management Internals
- Sub-Agent Architecture
- Permission & Security Model
- MCP Integration
- The Edit Tool: How It Actually Works
- Session Persistence
- Philosophy: Less Scaffolding, More Model
- Claude Code vs Alternatives
- Sources & References
- Appendix: What We Don't Know
1. The Master Loop
Confidence: 100% (Tier 1 - Official) Source: Anthropic Engineering Blog
At its core, Claude Code is remarkably simple:
┌─────────────────────────────────────────────────────────────┐
│ CLAUDE CODE MASTER LOOP │
├─────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────────┐ │
│ │ Your Prompt │ │
│ └──────┬───────┘ │
│ │ │
│ ▼ │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ │ │
│ │ CLAUDE REASONS │ │
│ │ (No classifier, no routing layer) │ │
│ │ │ │
│ └────────────────────────┬─────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌────────────────┐ │
│ │ Tool Call? │ │
│ └───────┬────────┘ │
│ │ │
│ YES │ NO │
│ ┌─────────────────┴─────────────────┐ │
│ │ │ │
│ ▼ ▼ │
│ ┌────────────┐ ┌────────────┐ │
│ │ Execute │ │ Text │ │
│ │ Tool │ │ Response │ │
│ │ │ │ (DONE) │ │
│ └─────┬──────┘ └────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────┐ │
│ │ Feed Result │ │
│ │ to Claude │──────────────────┐ │
│ └─────────────┘ │ │
│ │ │
│ ▼ │
│ ┌────────────────┐ │
│ │ LOOP BACK │ │
│ │ (Next turn) │ │
│ └────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
What This Means
The entire architecture is a simple while loop:
while (claude_response.has_tool_call):
result = execute_tool(tool_call)
claude_response = send_to_claude(result)
return claude_response.text
There is no:
- Intent classifier
- Task router
- RAG/embedding pipeline
- DAG orchestrator
- Planner/executor split
The model itself decides when to call tools, which tools to call, and when it's done. This is the "agentic loop" pattern described in Anthropic's engineering blog.
Why This Design?
- Simplicity: Fewer components = fewer failure modes
- Model-driven: Claude's reasoning is better than hand-coded heuristics
- Flexibility: No rigid pipeline constraining what Claude can do
- Debuggability: Easy to understand what happened and why
Native Capabilities Audit
Use this checklist to verify you understand Claude Code's full surface area. Each capability is documented in detail elsewhere in this guide.
The 11 Native Capabilities:
Event Hooks — Bash/PowerShell scripts triggered on tool execution
- PreToolUse, PostToolUse, UserPromptSubmit, Notification
- See: Section 5 Hooks
Skill-Scoped Hooks — Event hooks specific to skill execution context
- Lifecycle management per skill
- See: Ultimate Guide Section 5.11
Background Agents — Async task execution (test suites, long operations)
- Non-blocking agent spawning
- See: Section 4.2 Sub-Agent Architecture
Explore Subagent —
/explorefor codebase analysis- Read-only codebase exploration
- See: Section 4.2 Sub-Agents
Plan Subagent —
/planfor read-only planning mode- Safe architectural exploration
- See: Ultimate Guide Section 2.3
Task Tool — Hierarchical task delegation to specialized agents
- Parallel task execution, depth=1 sub-agents
- See: Section 4.2 Sub-Agent Architecture
Agent Teams — Multi-agent parallel coordination (experimental v2.1.32+)
- Git-based coordination, autonomous task claiming
- See: Ultimate Guide Section 9.20
Per-Task Model Selection — Dynamic model switching mid-session
/model opus|sonnet|haikuon task boundaries- See: Section 10 Cost Optimization
MCP Protocol Integration — Model Context Protocol for tool extensions
- Context7, Sequential, Serena, Playwright, etc.
- See: Section 6 MCP Integration
Permission Modes — Fine-grained control over tool execution
- Default, auto-accept, plan mode, custom rules
- See: Section 5 Permission & Security Model
Session Memory — Persistent context across sessions
- CLAUDE.md, memory files, project state
- See: Section 8 Session Persistence
Onboarding Tip: If you haven't explored all 11 capabilities, you're likely missing productivity opportunities. Focus on the unchecked items above.
Source: Synthesized from Gur Sannikov analysis
2. The Tool Arsenal
Confidence: 100% (Tier 1 - Official) Source: code.claude.com/docs
Claude Code has exactly 8 core tools:
| Tool | Purpose | Key Behavior | Token Cost |
|---|---|---|---|
Bash |
Execute shell commands | Universal adapter, most powerful | Low (command) + Variable (output) |
Read |
Read file contents | Max 2000 lines, handles truncation | High for large files |
Edit |
Modify existing files | Diff-based, requires exact match | Medium |
Write |
Create/overwrite files | Must read first if file exists | Medium |
Grep |
Search file contents | Ripgrep-based (regex), replaced RAG/embedding approach. For structural code search (AST-based), see ast-grep plugin. Trade-off: Grep (fast, simple) vs ast-grep (precise, setup required) vs Serena MCP (semantic, symbol-aware) | Low |
Glob |
Find files by pattern | Path matching, sorted by mtime | Low |
Task |
Spawn sub-agents | Isolated context, depth=1 limit | High (new context) |
TodoWrite |
Track progress | Structured task management | Low |
The Bash Universal Adapter
Key insight: Bash is Claude's swiss-army knife. It can:
- Run any CLI tool (git, npm, docker, curl...)
- Execute scripts
- Chain commands with pipes
- Access system state
The model has been trained on massive amounts of shell data, making it highly effective at using Bash as a universal adapter when specialized tools aren't enough.
Tool Selection Logic
Claude decides which tool to use based on the task. There's no hardcoded routing:
┌─────────────────────────────────────────────────────┐
│ TOOL SELECTION (Model-Driven) │
├─────────────────────────────────────────────────────┤
│ │
│ "Read auth.ts" → Read tool │
│ "Find all test files" → Glob tool │
│ "Search for TODO" → Grep tool │
│ "Run npm test" → Bash tool │
│ "Explore the codebase" → Task tool (sub-agent) │
│ "Track my progress" → TodoWrite tool │
│ │
│ The model learns these patterns during training, │
│ not from explicit rules. │
│ │
└─────────────────────────────────────────────────────┘
Extended Tool Ecosystem
Beyond the 8 core tools, Claude Code can leverage:
MCP Servers (Model Context Protocol):
- Serena: Symbol-aware code navigation + session memory
- grepai: Semantic search + call graph analysis (Ollama-based)
- Context7: Official library documentation lookup
- Sequential: Structured multi-step reasoning
- Playwright: Browser automation and E2E testing
Community Plugins:
- ast-grep: AST-based structural code search (explicit invocation)
Search Tool Selection Matrix
Claude Code offers multiple ways to search code, each with specific strengths:
| Search Need | Native Tool | MCP/Plugin Alternative | When to Escalate |
|---|---|---|---|
| Exact text | Grep (ripgrep) |
- | Never (fastest) |
| Function name | Grep |
Serena find_symbol |
Multi-file refactoring |
| By meaning | - | grepai search |
Don't know exact text |
| Call graph | - | grepai trace_callers |
Dependency analysis |
| Structural pattern | - | ast-grep | Large migrations (>50k lines) |
| File structure | - | Serena get_symbols_overview |
Need symbol context |
Performance Comparison:
| Tool | Speed | Setup | Use Case |
|---|---|---|---|
| Grep (ripgrep) | ⚡ ~20ms | ✅ None | 90% of searches |
| Serena | ⚡ ~100ms | ⚠️ MCP | Refactoring, symbols |
| grepai | 🐢 ~500ms | ⚠️ Ollama + MCP | Semantic, call graph |
| ast-grep | 🕐 ~200ms | ⚠️ Plugin | AST patterns, migrations |
Decision principle: Start with Grep (fastest), escalate to specialized tools only when needed.
📖 Deep Dive: See Search Tools Mastery for comprehensive workflows combining all search tools.
3. Context Management Internals
Confidence: 80% (Tier 2 - Partially Official) Sources:
- platform.claude.com/docs (Tier 1)
- Observed behavior (Tier 2)
Claude Code operates within a fixed context window (~200K tokens, varies by model).
Context Budget Breakdown
┌─────────────────────────────────────────────────────────────┐
│ CONTEXT BUDGET (~200K tokens) │
├─────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ System Prompt (~5-15K) │ │
│ │ • Tool definitions │ │
│ │ • Safety instructions │ │
│ │ • Behavioral guidelines │ │
│ │ • See detailed breakdown below ↓ │ │
│ ├──────────────────────────────────────────────────────┤ │
│ │ CLAUDE.md Files (~1-10K) │ │
│ │ • Global ~/.claude/CLAUDE.md │ │
│ │ • Project /CLAUDE.md │ │
│ │ • Local /.claude/CLAUDE.md │ │
│ ├──────────────────────────────────────────────────────┤ │
│ │ Conversation History (variable) │ │
│ │ • Your prompts │ │
│ │ • Claude's responses │ │
│ │ • Tool call records │ │
│ ├──────────────────────────────────────────────────────┤ │
│ │ Tool Results (variable) │ │
│ │ • File contents from Read │ │
│ │ • Command outputs from Bash │ │
│ │ • Search results from Grep │ │
│ ├──────────────────────────────────────────────────────┤ │
│ │ Reserved for Response (~40-45K) │ │
│ │ • Claude's thinking │ │
│ │ • Generated code/text │ │
│ └──────────────────────────────────────────────────────┘ │
│ │
│ USABLE = Total - System - Reserved ≈ 140-150K tokens │
│ │
└─────────────────────────────────────────────────────────────┘
System Prompt Contents
Confidence: 100% (Tier 1 - Official Anthropic Documentation) Sources:
Claude system prompts (~5-15K tokens) are publicly published by Anthropic as part of their transparency commitment. These prompts define:
Core Components:
- Tool definitions: Bash, Read, Edit, Write, Grep, Glob, Task, TodoWrite
- Safety instructions: Content policies, refusal patterns (see Security Hardening)
- Behavioral guidelines: Task-first approach, MVP-first, no over-engineering
- Context instructions: How to gather and use project context
Important Distinctions:
- Claude.ai/Mobile: Published prompts available publicly
- Anthropic API: Different default instructions, configurable by developers
- Claude Code CLI: Agentic coding assistant with context-gathering behavior
Community Analysis (for deeper understanding):
- Simon Willison's Claude 4 Analysis (May 2025): Deep-dive into thinking blocks, search rules, safety guardrails
- PromptHub Technical Breakdown (June 2025): Detailed analysis of prompt engineering patterns
→ Cross-reference: For security implications, see Section 5: Permission & Security Model
Note: Claude Code system prompts may differ from Claude.ai/mobile versions. The above sources cover the Claude family; Code-specific prompts are integrated into the CLI tool's behavior.
Auto-Compaction
Confidence: 75% (Tier 2 - Community-verified with research backing)
When context usage exceeds a threshold, Claude Code automatically summarizes older conversation turns:
| Source | Reported Threshold | Notes |
|---|---|---|
| VS Code extension | ~75% usage (25% remaining) | GitHub #11819 (Nov 2025) |
| CLI version | 1-5% remaining | More conservative than VS Code |
| PromptLayer analysis | 92% | Historical observation |
| Steve Kinney | 95% | Session Management Guide (Jul 2025) |
User-triggered /compact |
Anytime | Manual control |
What happens during compaction:
- Older conversation turns are summarized
- Tool results are condensed
- Recent context is preserved in full
- The model receives a "context was compacted" signal
Performance Impact (Research-backed):
Recent research and practitioner observations confirm quality degradation with auto-compaction:
- LLM performance drops 50-70% on complex tasks as context grows from 1K to 32K tokens (Context Rot Research, Jul 2025)
- 11 out of 12 models fall below 50% of their short-context performance at 32K tokens (NoLiMa benchmark)
- Auto-compact loses nuance and breaks references through repeated compression cycles (Claude Saves Tokens, Forgets Everything, Jan 2026)
- Attention mechanism struggles with retrieval burden in high-context scenarios
Community Consensus: Manual /compact at logical breakpoints > waiting for auto-compact to trigger.
Recommended Strategy (Lorenz, 2026):
| Context % | Action | Rationale |
|---|---|---|
| 70% | Warning - Plan cleanup | Early awareness |
| 85% | Manual handoff recommended | Prevent auto-compact degradation |
| 95% | Force handoff | Severe quality degradation |
User control: Use /compact manually to trigger summarization at logical breakpoints, or use session handoffs (see Session Handoffs) to preserve intent over compressed history.
Context Preservation Strategies
| Strategy | When to Use | How |
|---|---|---|
| Sub-agents | Exploratory tasks | Task tool for isolated search |
| Manual compact | Proactive cleanup | /compact command |
| Clear session | Fresh start needed | /clear command |
| Specific reads | Know what you need | Read exact files, not directories |
| CLAUDE.md | Persistent context | Store conventions in memory files |
Session Degradation Limits
Confidence: 70% (Tier 2 - Practitioner studies, arXiv research)
Claude Code's effectiveness degrades predictably under certain conditions:
| Condition | Observed Threshold | Symptom |
|---|---|---|
| Conversation turns | 15-25 turns | Loses track of earlier constraints |
| Token accumulation | 80-100K tokens | Ignores requirements stated early in session |
| Problem scope | >5 files simultaneously | Inconsistent changes, missed files |
Success rates by scope (from practitioner studies):
| Scope | Success Rate | Example |
|---|---|---|
| 1-3 files | ~85% | Fix bug in single module |
| 4-7 files | ~60% | Refactor feature across components |
| 8+ files | ~40% | Codebase-wide changes |
Mitigation strategies:
- Checkpoint prompts: "Before continuing, recap the current requirements and constraints."
- Session resets: Start fresh for new tasks (
/clear) - Scope tightly: Break large tasks into focused sub-tasks
- Use sub-agents: Delegate exploration to
Tasktool to preserve main context
4. Sub-Agent Architecture
Confidence: 100% (Tier 1 - Documented behavior) Source: code.claude.com/docs + System prompt (visible in tool definitions)
The Task tool spawns sub-agents for parallel or isolated work.
Isolation Model
┌─────────────────────────────────────────────────────────────┐
│ MAIN AGENT │
│ │
│ ┌───────────────────────────────────────────────────────┐ │
│ │ Context: Full conversation + all file reads │ │
│ │ │ │
│ │ Task("Explore authentication patterns") │ │
│ │ │ │ │
│ │ ▼ │ │
│ │ ┌─────────────────────────────────────────────────┐ │ │
│ │ │ SUB-AGENT (Spawned) │ │ │
│ │ │ │ │ │
│ │ │ • Own fresh context window │ │ │
│ │ │ • Receives: task description only │ │ │
│ │ │ • Has access to: same tools (except Task) │ │ │
│ │ │ • CANNOT spawn sub-sub-agents (depth = 1) │ │ │
│ │ │ • Returns: summary text only │ │ │
│ │ │ │ │ │
│ │ └─────────────────────────────────────────────────┘ │ │
│ │ │ │ │
│ │ ▼ │ │
│ │ Result: "Found 3 auth patterns: JWT in..." │ │
│ │ (Only this text enters main context) │ │
│ │ │ │
│ └───────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
Why Depth = 1?
Limiting sub-agents to one level prevents:
- Recursive explosion: Agent-ception would consume infinite resources
- Context pollution: Each level would accumulate context
- Debugging nightmares: Tracking multi-level agent chains is hard
- Unpredictable costs: Nested agents = unpredictable token usage
Sub-Agent Types
Claude Code offers specialized sub-agent types via the subagent_type parameter:
| Type | Purpose | Tools Available |
|---|---|---|
Explore |
Codebase exploration | All read-only tools |
Plan |
Architecture planning | All except Edit/Write |
Bash |
Command execution | Bash only |
general-purpose |
Complex multi-step | All tools |
When to Use Sub-Agents
| Use Case | Why Sub-Agent Helps |
|---|---|
| Searching large codebases | Keeps main context clean |
| Parallel exploration | Multiple searches simultaneously |
| Risky exploration | Errors don't pollute main context |
| Specialized analysis | Different "mindset" for different tasks |
5. Permission & Security Model
Confidence: 100% (Tier 1 - Official) Sources:
Claude Code has a layered security model:
┌─────────────────────────────────────────────────────────────┐
│ PERMISSION LAYERS │
├─────────────────────────────────────────────────────────────┤
│ │
│ Layer 1: INTERACTIVE PROMPTS │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ Claude wants to run: rm -rf node_modules │ │
│ │ [Allow once] [Allow always] [Deny] [Edit command] │ │
│ └────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ Layer 2: ALLOW/DENY RULES (settings.json) │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ { │ │
│ │ "permissions": { │ │
│ │ "allow": ["Bash(npm *)", "Read"], │ │
│ │ "deny": ["Bash(rm -rf *)"] │ │
│ │ } │ │
│ │ } │ │
│ └────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ Layer 3: HOOKS (Pre/Post execution) │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ PreToolUse: Validate before execution │ │
│ │ PostToolUse: Audit after execution │ │
│ │ PermissionRequest: Override permission prompts │ │
│ └────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ Layer 4: SANDBOX MODE (Optional isolation) │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ Filesystem isolation + Network restrictions │ │
│ └────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
Dangerous Pattern Detection
Confidence: 80% (Tier 2 - Observed but not exhaustive)
Claude Code appears to flag certain patterns for extra scrutiny:
| Pattern | Risk | Behavior |
|---|---|---|
rm -rf |
Destructive deletion | Always prompts |
sudo |
Privilege escalation | Always prompts |
curl | sh |
Remote code execution | Always prompts |
chmod 777 |
Insecure permissions | Always prompts |
git push --force |
History destruction | Always prompts |
DROP TABLE |
Data destruction | Always prompts |
This is not a complete blocklist — patterns are likely detected through model training rather than explicit rules.
Native Sandbox (v2.1.0+)
Confidence: 100% (Tier 1 - Official) Source: code.claude.com/docs/en/sandboxing
Claude Code includes built-in native sandboxing using OS-level primitives for process-level isolation:
┌──────────────────────────────────────────────────────┐
│ Native Sandbox Architecture │
├──────────────────────────────────────────────────────┤
│ │
│ Bash Command Request │
│ │ │
│ ▼ │
│ Sandbox Wrapper (Seatbelt/bubblewrap) │
│ │ │
│ ├─ Filesystem: read all, write CWD only │
│ ├─ Network: SOCKS5 proxy + domain filtering │
│ ├─ Process: isolated environment │
│ │ │
│ ▼ │
│ OS Kernel Enforcement │
│ │ │
│ ├─ Allowed: operations within boundaries │
│ ├─ Blocked: violations at system call level │
│ └─ Notify: user receives alert on violation │
│ │
└──────────────────────────────────────────────────────┘
OS Primitives:
| Platform | Mechanism | Notes |
|---|---|---|
| macOS | Seatbelt (TrustedBSD MAC) | Built-in, kernel-level system call filtering |
| Linux/WSL2 | bubblewrap (namespaces + seccomp) | Requires: sudo apt-get install bubblewrap socat |
| WSL1 | ❌ Not supported | bubblewrap needs kernel features unavailable |
| Windows | ⏳ Planned | Not yet available |
Isolation Model:
Filesystem:
- Read: Entire computer (except denied paths)
- Write: Current working directory only (configurable)
- Blocked: Modifications outside CWD, credentials directories (
~/.ssh,~/.aws)
Network:
- Proxy: All connections routed through SOCKS5 proxy
- Domain filtering: Allowlist/denylist mode
- Default blocked: Private CIDRs, localhost ranges
Process:
- Shared kernel: Vulnerable to kernel exploits (unlike Docker microVM)
- Child processes: Inherit same sandbox restrictions
- Escape hatch:
dangerouslyDisableSandboxparameter for incompatible tools
Sandbox Modes:
- Auto-allow mode: Bash commands auto-approved if sandboxed (recommended for daily dev)
- Regular permissions mode: All commands require explicit approval (high-security)
Security Trade-offs:
| Aspect | Native Sandbox | Docker Sandboxes (microVM) |
|---|---|---|
| Kernel isolation | ❌ Shared kernel | ✅ Separate kernel per VM |
| Setup | 0 deps (macOS), 2 pkgs (Linux) | Docker Desktop 4.58+ |
| Overhead | Minimal (~1-3% CPU) | Moderate (~5-10% CPU) |
| Use case | Daily dev, trusted code | Untrusted code, max security |
Security Limitations:
⚠️ Domain fronting: CDNs (Cloudflare, Akamai) can bypass domain filtering
⚠️ Unix sockets: Misconfigured allowUnixSockets grants privilege escalation
⚠️ Filesystem: Overly broad write permissions enable attacks on $PATH directories
When to use:
- ✅ Native Sandbox: Daily development, trusted team, lightweight setup
- ✅ Docker Sandboxes: Untrusted code, kernel exploit protection, Docker-in-Docker needed
Deep dive: See Native Sandboxing Guide for complete technical reference, configuration examples, and troubleshooting.
Hooks System
Hooks allow programmatic control over Claude's actions:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [{
"type": "command",
"command": "/path/to/validate-command.sh"
}]
}
],
"PostToolUse": [
{
"matcher": "*",
"hooks": [{
"type": "command",
"command": "/path/to/audit-log.sh"
}]
}
]
}
}
Hook capabilities:
| Capability | Supported | How |
|---|---|---|
| Block execution | Yes | Exit code 2 |
| Modify parameters | Yes | Return modified JSON |
| Log actions | Yes | Write to file in hook |
| Async processing | Yes | Set async: true in hook config (v2.1.0+) |
Hook JSON payload (passed via stdin):
{
"session_id": "abc123",
"transcript_path": "/home/user/.claude/projects/.../transcript.jsonl",
"cwd": "/path/to/project",
"permission_mode": "default",
"hook_event_name": "PreToolUse",
"tool_name": "Bash",
"tool_input": {
"command": "npm install lodash"
}
}
Common fields sent to all events: session_id, transcript_path, cwd, permission_mode, hook_event_name. Event-specific fields (e.g., tool_name/tool_input for PreToolUse) are added on top.
→ Cross-reference: See Section 7 - Hooks in the main guide for complete examples.
6. MCP Integration
Confidence: 100% (Tier 1 - Official) Source: code.claude.com/docs/en/mcp
MCP (Model Context Protocol) servers extend Claude Code with additional tools.
MCP Architecture Overview
💡 Visual Guide: The following diagram illustrates how MCP creates a secure control layer between LLMs and real systems. The LLM layer has no direct data access - the MCP Server enforces security policies before tools can interact with databases, APIs, or files.
Figure 1: MCP Architecture showing separation between thinking (LLM), control (MCP Server), and execution (Tools). Design inspired by Dinesh Kumar's LinkedIn visualization, recreated under Apache-2.0 license.
Key security boundaries:
- Yellow layer (LLM): Reasoning only - No Data Access
- Orange layer (MCP Server): Security control point (policies, validation, logs)
- Grey layer (Real Systems): Protected data - Hidden From AI
How MCP Works (Technical Details)
┌─────────────────────────────────────────────────────────────┐
│ MCP INTEGRATION │
├─────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ CLAUDE CODE │ │
│ │ │ │
│ │ Native Tools MCP Tools │ │
│ │ ┌─────────┐ ┌─────────────────────────┐ │ │
│ │ │ Bash │ │ mcp__serena__* │ │ │
│ │ │ Read │ │ mcp__context7__* │ │ │
│ │ │ Edit │ │ mcp__playwright__* │ │ │
│ │ │ ... │ │ mcp__custom__* │ │ │
│ │ └─────────┘ └───────────┬─────────────┘ │ │
│ │ │ │ │
│ └──────────────────────────────────┼──────────────────┘ │
│ │ │
│ JSON-RPC 2.0 │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ MCP SERVER │ │
│ │ │ │
│ │ stdio/HTTP transport │ │
│ │ Tool definitions (JSON Schema) │ │
│ │ Tool implementations │ │
│ │ │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
Key MCP Facts
| Aspect | Behavior |
|---|---|
| Protocol | JSON-RPC 2.0 over stdio or HTTP |
| Tool naming | mcp__<server>__<tool> convention |
| Context sharing | Only via tool parameters and return values |
| Lifecycle | Server starts on first use, stays alive during session |
| Permissions | Same system as native tools |
What MCP Cannot Do
| Limitation | Explanation |
|---|---|
| Access conversation history | Only sees tool params, not full context |
| Maintain state across calls | Each call is independent (unless server implements caching) |
| Modify Claude's system prompt | Tools only, no prompt injection |
| Bypass permissions | Same security layer as native tools |
→ Cross-reference: See Section 8.6 - MCP Security for security considerations.
MCP Extensions: Apps (SEP-1865)
Status: Stable (January 26, 2026) Spec: SEP-1865 on GitHub Co-authored by: OpenAI, Anthropic, MCP-UI creators
What Are MCP Apps?
MCP Apps is the first official extension to the Model Context Protocol, enabling MCP servers to deliver interactive user interfaces alongside traditional tool responses.
The problem solved: Traditional text-based responses create friction for workflows requiring exploration. Each interaction (sort, filter, drill-down) demands a new prompt cycle. MCP Apps eliminates this "context gap" by rendering interactive UIs directly in the conversation.
Technical Architecture
Two core primitives:
Tools with UI metadata:
{ "name": "query_database", "description": "Query customer database", "_meta": { "ui": { "resourceUri": "ui://dashboard/customers" } } }UI Resources (
ui://scheme):- Server-side HTML/JavaScript bundles
- Rendered in sandboxed iframes by host
- Bidirectional JSON-RPC communication via
postMessage
Communication flow:
┌─────────────────────────────────────────────────────────┐
│ MCP APPS ARCHITECTURE │
├─────────────────────────────────────────────────────────┤
│ │
│ ┌──────────────┐ ┌──────────────┐ │
│ │ MCP Client │◄───────►│ MCP Server │ │
│ │ (C
…(truncated)