Claude Code From Scratch

GitHub stars
License: MIT
TypeScript
Lines of Code

Build Claude Code from scratch, step by step

📘 Read Tutorial Online →   |   中文

📖 Want to understand the internals? Companion project How Claude Code Works — 12 deep-dive articles, 330K+ characters, source-level analysis of Claude Code’s architecture


Claude Code open-sourced 500K lines of TypeScript. Too much to read?

This project recreates Claude Code’s core architecture in ~4300 lines — Agent Loop, 13 tools (with parallel + streaming execution), 4-tier context compression, semantic memory recall, skills, multi-agent, MCP integration — with each step comparing the real source to our simplified version.

This isn’t a demo — it’s a step-by-step tutorial. Follow along, write a few thousand lines of code yourself, and quickly grasp the essence of the best coding agent out there. No need to wade through hundreds of thousands of lines.

Step-by-Step Tutorial

13 chapters in two phases — first build a working Coding Agent, then add advanced capabilities. Each chapter includes real code + Claude Code source comparison:

ChapterContentSource Mapping
Phase 1: Build a Working Coding Agent
1. Agent LoopCore loop: call LLM → execute tools → repeatagent.tsquery.ts
2. Tool System13 tools + mtime guard + deferred loadingtools.tsTool.ts + 66 tools
3. System PromptPrompt engineering + @include syntaxprompt.tsprompts.ts
4. CLI & SessionsREPL, Ctrl+C, session persistencecli.tscli.tsx
5. StreamingDual-backend + streaming tool exec + parallelagent.tsapi/claude.ts
6. Permissions5 modes + declarative rules + danger detectiontools.tspermissions/ (52KB)
7. Context4-tier compression + large result persistenceagent.tscompact/
Phase 2: Advanced Capabilities
8. Memory4-type memory + semantic recall + async prefetchmemory.tsmemory.ts
9. SkillsSkill discovery + inline/fork dual modeskills.tsSkillTool/
10. Plan ModeRead-only planning + 4-option approval workflowagent.tsEnterPlanMode
11. Multi-AgentSub-Agent fork-return architecturesubagent.tsAgentTool/
12. MCP IntegrationJSON-RPC over stdio for external toolsmcp.tsmcpClient.ts
13. ComparisonFull comparison + extension ideasGlobal

Quick Start

git clone https://github.com/Windy3f3f3f3f/claude-code-from-scratch.git
cd claude-code-from-scratch
npm install && npm run build

API Configuration

Two backends supported, auto-detected via environment variables:

Option 1: Anthropic Format (Recommended)

export ANTHROPIC_API_KEY="sk-ant-xxx"
# Optional: use a proxy
export ANTHROPIC_BASE_URL="https://aihubmix.com"

Option 2: OpenAI-Compatible Format

export OPENAI_API_KEY="sk-xxx"
export OPENAI_BASE_URL="https://api.openai.com/v1"

Default model is claude-opus-4-6. Customize via env var or CLI flag:

export MINI_CLAUDE_MODEL="claude-sonnet-4-6"    # env var
npm start -- --model gpt-4o                      # CLI flag (higher priority)

Run

TypeScript

npm start                    # Interactive REPL mode (recommended)
npm start -- --resume        # Resume last session
npm start -- --yolo          # Skip safety confirmations
npm start -- --plan          # Plan mode: analyze only, no modifications
npm start -- --accept-edits  # Auto-approve file edits
npm start -- --dont-ask      # CI mode: auto-deny confirmable actions
npm start -- --max-cost 0.50 # Cost limit (USD)
npm start -- --max-turns 20  # Turn limit

Python

mini-claude-py               # Interactive REPL mode (recommended)
mini-claude-py --resume      # Resume last session
mini-claude-py --yolo        # Skip safety confirmations
mini-claude-py --plan        # Plan mode: analyze only, no modifications
mini-claude-py --accept-edits # Auto-approve file edits
mini-claude-py --dont-ask    # CI mode: auto-deny confirmable actions
mini-claude-py --max-cost 0.50 # Cost limit (USD)
mini-claude-py --max-turns 20  # Turn limit

Install globally to use from any directory:

TypeScript

npm link                     # Global install
cd ~/your-project
mini-claude                  # Launch directly

Python

cd python
pip install -e .             # Global install (editable mode)
cd ~/your-project
mini-claude-py               # Launch directly

REPL Commands

CommandFunction
/clearClear conversation history
/costShow cumulative token usage and cost
/compactManually trigger conversation compaction
/memoryList saved memories
/skillsList available skills
/<skill>Invoke a registered skill (e.g. /commit)

See CLI & Sessions and Testing

Comparison with Claude Code

AspectClaude CodeMini Claude Code
PurposeProduction coding agentEducational / minimal
Tools66+ built-in13 tools (6 core + web_fetch + tool_search + skill + agent + plan mode)
Tool ExecutionConcurrent + streaming early startParallel + streaming early start
Context4-level compression pipeline4-tier compression + large result persistence (>30KB)
Permissions7-layer + AST analysis5 modes + declarative rules + regex detection
Edit Validation14-step pipelineQuote normalization + uniqueness + mtime guard + diff output
Memory4 types + semantic recall4 types + semantic recall + async prefetch
Skills6 sources + inline/fork2 sources + inline/fork
Multi-AgentSub-Agent + Coordinator + SwarmSub-Agent (3 built-in + custom agents)
MCP IntegrationmcpClient.ts + dynamic tool discoveryMcpManager + JSON-RPC over stdio
Budget ControlUSD/turns/abortUSD + turn limits
Code Size500k+ lines~4300 lines (TS) / ~3800 lines (Python)

Core Capabilities

  • Agent Loop: Automatically calls tools, processes results, iterates until done
  • 13 Tools: Read/write/edit files (mtime guard), search, shell, WebFetch, ToolSearch (deferred loading), skills, sub-agents, Plan Mode
  • Streaming: Real-time output, Anthropic + OpenAI backends, streaming tool early execution
  • Parallel Tool Execution: Read-only tools (read_file, grep_search, etc.) auto-parallelized, 2-3x speedup
  • 4-Tier Context Compression: Budget trimming → stale snip → microcompact → auto-compact + large result persistence (>30KB to disk)
  • Permission System: 5 modes + declarative allow/deny rules in .claude/settings.json + 16 dangerous command patterns
  • Memory System: 4 types + semantic recall (sideQuery model selection) + async prefetch
  • Skills System: Load reusable prompt templates, supports inline injection and fork sub-agent execution
  • Multi-Agent: Sub-Agent fork-return pattern (3 built-in + .claude/agents/ custom types)
  • MCP Integration: JSON-RPC over stdio to connect external tool servers, dynamic tool discovery
  • System Prompt: @include syntax for recursive imports, .claude/rules/ auto-loading, template variables
  • Extended Thinking: Anthropic extended thinking support (--thinking), adaptive/enabled/disabled modes
  • Budget Control: --max-cost USD limit + --max-turns turn limit, auto-stop on exceed
  • Session Persistence: Auto-save conversations, --resume to restore
  • Cross-Platform: Windows / macOS / Linux, auto-detects shell (PowerShell / bash / zsh)
  • Error Recovery: Exponential backoff + random jitter retry (max 3 attempts), graceful Ctrl+C

Project Structure

src/
├── agent.ts        # Agent loop: streaming, parallel exec, 4-tier compress  (1501 lines)
├── tools.ts        # Tools: 13 tools + mtime guard + deferred loading       (858 lines)
├── cli.ts          # CLI entry: args, REPL, budget flags                    (371 lines)
├── memory.ts       # Memory: 4 types + semantic recall + async prefetch     (376 lines)
├── mcp.ts          # MCP client: JSON-RPC over stdio                        (266 lines)
├── prompt.ts       # System prompt: @include + template + injection         (230 lines)
├── ui.ts           # Terminal output: colors, formatting, sub-agent         (211 lines)
├── subagent.ts     # Sub-agent: 3 built-in + custom agent discovery         (199 lines)
├── skills.ts       # Skills system: discovery + inline/fork modes           (175 lines)
├── session.ts      # Session persistence: save/load/list                    (63 lines)
├── frontmatter.ts  # Shared YAML frontmatter parser                         (41 lines)
                                                            Total: ~4291 lines

License

MIT