Claude Code AI Agent Architecture

Claude Code Architecture Deep DiveClaude Code Architecture Deep Dive

By Anirach Mingkhwan AI Developer Tools 2026 · 7 min read
Claude Code — เจาะลึกสถาปัตยกรรม Claude Code
ในบทความนี้
  1. Overview: Claude Code คืออะไร?
  2. Core Architecture Layers
  3. Tool System - ความสามารถของ Claude Code
  4. Context Management
  5. MCP: Model Context Protocol
  6. Sub-agents: Parallel Execution
  7. Security Model
  8. Model Routing
  9. Hooks System
  10. สรุป: Lessons Learned
In this post
  1. Overview: What Is Claude Code?
  2. Core Architecture Layers
  3. Tool System — What Claude Code Can Do
  4. Context Management
  5. MCP: Model Context Protocol
  6. Sub-agents: Parallel Execution
  7. Security Model
  8. Model Routing
  9. Hooks System
  10. Summary: Lessons Learned

Claude Code คือ AI Coding Assistant แบบ CLI จาก Anthropic ที่ไม่ใช่แค่ chatbot แต่เป็น autonomous agent ที่อ่าน/เขียนไฟล์, รัน commands, และทำงานจริงใน codebase ของคุณได้

วันนี้มาเจาะลึก สถาปัตยกรรมเบื้องหลัง ว่า Claude Code ออกแบบระบบยังไงให้ AI ทำงานได้อย่างปลอดภัยและมีประสิทธิภาพ


Overview: Claude Code คืออะไร?

Claude Code ต่างจาก ChatGPT หรือ web-based AI ตรงที่มันรันใน terminal ของคุณ และมีสิทธิ์เข้าถึง filesystem, Git, และ shell commands ได้จริง:

Developer
พิมพ์คำสั่ง
->
Claude Code CLI
Agent loop
->
Tools
Read/Write/Bash
->
Codebase
Files & Git
Key insight: Claude Code ไม่ใช่แค่ wrapper รอบ API แต่เป็น agentic system ที่มี tool use, memory, และ execution environment ครบ

Core Architecture Layers

Claude Code แบ่งเป็น 4 layers หลัก:

1
User Interface Layer
Terminal UI, VSCode Extension, input handling
2
Agent Controller
Main loop, context management, model routing
3
Tool Execution Layer
File ops, Bash, Grep, Search, MCP servers
4
System Integration
Git, filesystem, permissions, sandboxing

1. User Interface Layer

Claude Code รองรับหลาย interfaces:

  • CLI Mode - รันใน terminal ด้วย claude command
  • VSCode Extension - Embedded ใน editor พร้อม context awareness
  • API/SDK Mode - สำหรับ automation และ CI/CD

2. Agent Controller - หัวใจของระบบ

Agent Controller คือ "สมอง" ที่ควบคุมการทำงานทั้งหมด:

Agent Loop
Input Processing
User message
Context injection
Model Call
Claude API
Tool selection
Execution
Run tools
Collect results
Loop until done

แต่ละ iteration ของ loop:

  1. Receive input - user message + tool results จาก iteration ก่อน
  2. Build context - รวม system prompt, CLAUDE.md, conversation history
  3. Call Claude - ส่งไป API และรับ response + tool calls
  4. Execute tools - รัน tools ที่ Claude เลือก (Read, Write, Bash, etc.)
  5. Check completion - ถ้ายังไม่เสร็จ กลับไป step 1

Tool System - ความสามารถของ Claude Code

Claude Code มี built-in tools ที่ให้ AI โต้ตอบกับ codebase ได้:

Read อ่านไฟล์
Write สร้างไฟล์ใหม่
Edit แก้ไขไฟล์
Bash รัน commands
Glob ค้นหาไฟล์
Grep ค้นหา content
Agent Spawn sub-agents
WebSearch ค้นหาเว็บ

Tool Execution Flow

User: "Fix the bug in auth.ts"

Claude thinks: I need to read the file first
  -> Tool: Read(file_path="src/auth.ts")
  <- Returns: file content

Claude thinks: I see the issue, let me fix it
  -> Tool: Edit(file_path="src/auth.ts", old_string="...", new_string="...")
  <- Returns: success

Claude thinks: Let me verify by running tests
  -> Tool: Bash(command="npm test")
  <- Returns: All tests passed

Claude: "Fixed the null check bug in auth.ts. Tests passing."

Permission Model

Claude Code มีระบบ permission modes ที่ผู้ใช้เลือกได้:

ModeAuto-approveUse case
Askไม่มี - ถามทุกครั้งLearning, sensitive code
Auto-editRead/Edit อัตโนมัติDevelopment workflow
Full autoทุก toolCI/CD, automation

Context Management

หนึ่งในความท้าทายของ AI agent คือ context window มีจำกัด Claude Code จัดการด้วยหลายวิธี:

1. CLAUDE.md - Project Memory

ไฟล์ CLAUDE.md ในโปรเจคเป็น persistent context ที่ถูกโหลดทุกครั้ง:

# CLAUDE.md

## Project Overview
E-commerce API built with Node.js + PostgreSQL

## Development
- Run tests: npm test
- Start dev: npm run dev
- DB migration: npm run migrate

## Conventions
- Use camelCase for variables
- All API routes in /src/routes/
- Error handling via middleware

2. Automatic Context Injection

Claude Code ฉีด context อัตโนมัติ:

  • Git status - current branch, uncommitted changes
  • IDE selection - highlighted code ใน VSCode
  • Recent conversation - compressed summary ถ้ายาวเกิน
  • Tool results - output จาก tools ก่อนหน้า

3. Context Compaction

เมื่อ conversation ยาวเกินไป Claude Code จะ compact ข้อความเก่าเป็น summary เพื่อประหยัด tokens:

Full History
100k tokens
->
Compaction
AI summarize
->
Summary + Recent
~20k tokens

MCP: Model Context Protocol

MCP คือ protocol ที่ให้ Claude Code เชื่อมต่อกับ external tools ได้ไม่จำกัด:

MCP
Database MCP
Query PostgreSQL, MySQL โดยตรง
MCP
Browser MCP
Control Playwright browser
MCP
Docker MCP
Manage containers
MCP
Custom MCPs
Build your own tools

MCP Architecture

Claude Code
    |
    +-- Built-in Tools (Read, Write, Bash, etc.)
    |
    +-- MCP Client
         |
         +-- stdio:// -> Local MCP Server
         +-- sse:// -> Remote MCP Server
         +-- docker:// -> Containerized MCP

MCP servers ทำให้ Claude Code ขยายความสามารถได้ไม่จำกัด โดยไม่ต้องแก้ core code


Sub-agents: Parallel Execution

Claude Code สามารถ spawn sub-agents เพื่อทำงานขนานกันได้:

Multi-agent Execution
Main Agent
Coordinate
spawns
Sub-agent 1
Research code
Sub-agent 2
Run tests
Sub-agent 3
Check docs

Sub-agent types ที่มี:

  • Explore - ค้นหาและเข้าใจ codebase
  • Plan - วางแผน implementation
  • General-purpose - ทำงานทั่วไป
  • Background - รันแบบ async ไม่ block main

Security Model

Claude Code ออกแบบมาให้ safe by default:

1. Sandbox Execution

Bash commands รันใน sandbox ที่:

  • จำกัด network access
  • ป้องกันการเข้าถึงไฟล์นอก working directory
  • Block dangerous commands (rm -rf /, etc.)

2. Prompt Injection Defense

Claude Code ระวัง prompt injection จาก external sources:

  • Tool outputs ถูก sanitize
  • File contents ถูก mark เป็น untrusted
  • User ได้รับ warning ถ้าพบ suspicious content

3. Git Safety

มี safeguards สำหรับ Git operations:

  • ไม่ force push ไป main/master โดยไม่ถาม
  • ไม่ reset --hard โดยไม่ warning
  • Commit message ต้องมี Co-Authored-By

Model Routing

Claude Code เลือกใช้ model ตาม task:

ModelUse caseTrade-off
OpusComplex reasoning, architectureSlow, expensive
SonnetGeneral coding, defaultBalanced
HaikuSimple tasks, sub-agentsFast, cheap

ผู้ใช้สามารถ override ด้วย /model command หรือตั้งค่าใน settings


Hooks System

Claude Code มี hooks ที่ให้ inject custom logic ได้:

# .claude/settings.json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "command": "echo 'Running: $TOOL_INPUT' >> ~/.claude/bash.log"
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Edit",
        "command": "prettier --write $FILE_PATH"
      }
    ]
  }
}

Hook types ที่รองรับ:

  • PreToolUse - ก่อนรัน tool
  • PostToolUse - หลังรัน tool
  • Notification - แจ้งเตือน events

สรุป: Lessons Learned

จากการศึกษา Claude Code architecture เราได้เรียนรู้:

Loop
Agent Loop Pattern
Think -> Act -> Observe -> Repeat
Tool
Tool Abstraction
Capability = Tool definitions
Context
Context Management
Persistent + Dynamic + Compaction
Safety
Safety by Design
Permissions + Sandbox + Confirmation
Key takeaway: การสร้าง AI Agent ที่ทำงานจริงได้ต้องคิดเรื่อง tool design, context management, และ safety ไม่ใช่แค่ prompt engineering

Claude Code is a CLI AI Coding Assistant from Anthropic — not just a chatbot, but an autonomous agent that reads and writes files, runs commands, and does real work inside your codebase.

Today we go deep into the architecture behind it: how Claude Code is designed so that an AI can work both safely and efficiently.


Overview: What Is Claude Code?

Claude Code differs from ChatGPT or any web-based AI in one decisive way: it runs in your terminal, with genuine access to the filesystem, Git, and shell commands:

Developer
Types a command
->
Claude Code CLI
Agent loop
->
Tools
Read/Write/Bash
->
Codebase
Files & Git
Key insight: Claude Code is not merely a wrapper around an API. It is an agentic system with the full set — tool use, memory, and an execution environment

Core Architecture Layers

Claude Code divides into four main layers:

1
User Interface Layer
Terminal UI, VSCode Extension, input handling
2
Agent Controller
Main loop, context management, model routing
3
Tool Execution Layer
File ops, Bash, Grep, Search, MCP servers
4
System Integration
Git, filesystem, permissions, sandboxing

1. User Interface Layer

Claude Code supports several interfaces:

  • CLI Mode - runs in the terminal via the claude command
  • VSCode Extension - embedded in the editor, with context awareness
  • API/SDK Mode - for automation and CI/CD

2. Agent Controller — the Heart of the System

The Agent Controller is the "brain" that governs everything the system does:

Agent Loop
Input Processing
User message
Context injection
Model Call
Claude API
Tool selection
Execution
Run tools
Collect results
Loop until done

Each iteration of the loop:

  1. Receive input - the user message plus tool results from the previous iteration
  2. Build context - assemble the system prompt, CLAUDE.md, and conversation history
  3. Call Claude - send it to the API and get back a response plus tool calls
  4. Execute tools - run the tools Claude selected (Read, Write, Bash, etc.)
  5. Check completion - if the work is not finished, return to step 1

Tool System — What Claude Code Can Do

Claude Code ships with built-in tools that let the AI act on the codebase:

Read Read files
Write Create new files
Edit Edit files
Bash Run commands
Glob Find files
Grep Search content
Agent Spawn sub-agents
WebSearch Search the web

Tool Execution Flow

User: "Fix the bug in auth.ts"

Claude thinks: I need to read the file first
  -> Tool: Read(file_path="src/auth.ts")
  <- Returns: file content

Claude thinks: I see the issue, let me fix it
  -> Tool: Edit(file_path="src/auth.ts", old_string="...", new_string="...")
  <- Returns: success

Claude thinks: Let me verify by running tests
  -> Tool: Bash(command="npm test")
  <- Returns: All tests passed

Claude: "Fixed the null check bug in auth.ts. Tests passing."

Permission Model

Claude Code has a set of permission modes the user chooses from:

ModeAuto-approveUse case
AskNone - asks every timeLearning, sensitive code
Auto-editRead/Edit automaticallyDevelopment workflow
Full autoEvery toolCI/CD, automation

Context Management

One of the standing challenges for an AI agent is that the context window is finite. Claude Code manages it in several ways:

1. CLAUDE.md - Project Memory

A CLAUDE.md file in the project is persistent context, loaded every single time:

# CLAUDE.md

## Project Overview
E-commerce API built with Node.js + PostgreSQL

## Development
- Run tests: npm test
- Start dev: npm run dev
- DB migration: npm run migrate

## Conventions
- Use camelCase for variables
- All API routes in /src/routes/
- Error handling via middleware

2. Automatic Context Injection

Claude Code injects context automatically:

  • Git status - current branch, uncommitted changes
  • IDE selection - the code highlighted in VSCode
  • Recent conversation - a compressed summary once it runs long
  • Tool results - output from the preceding tools

3. Context Compaction

When a conversation grows too long, Claude Code compacts the older messages into a summary to save tokens:

Full History
100k tokens
->
Compaction
AI summarize
->
Summary + Recent
~20k tokens

MCP: Model Context Protocol

MCP is the protocol that lets Claude Code connect to external tools without limit:

MCP
Database MCP
Query PostgreSQL and MySQL directly
MCP
Browser MCP
Control Playwright browser
MCP
Docker MCP
Manage containers
MCP
Custom MCPs
Build your own tools

MCP Architecture

Claude Code
    |
    +-- Built-in Tools (Read, Write, Bash, etc.)
    |
    +-- MCP Client
         |
         +-- stdio:// -> Local MCP Server
         +-- sse:// -> Remote MCP Server
         +-- docker:// -> Containerized MCP

MCP servers let Claude Code extend its capabilities without limit, and without anyone editing the core code.


Sub-agents: Parallel Execution

Claude Code can spawn sub-agents to work in parallel:

Multi-agent Execution
Main Agent
Coordinate
spawns
Sub-agent 1
Research code
Sub-agent 2
Run tests
Sub-agent 3
Check docs

The sub-agent types available:

  • Explore - search and understand the codebase
  • Plan - plan the implementation
  • General-purpose - ordinary work of any kind
  • Background - runs async, never blocking the main agent

Security Model

Claude Code is designed to be safe by default:

1. Sandbox Execution

Bash commands run in a sandbox that:

  • Limits network access
  • Prevents access to files outside the working directory
  • Blocks dangerous commands (rm -rf /, etc.)

2. Prompt Injection Defense

Claude Code stays wary of prompt injection from external sources:

  • Tool outputs are sanitised
  • File contents are marked untrusted
  • The user gets a warning when suspicious content turns up

3. Git Safety

There are safeguards around Git operations:

  • No force push to main/master without asking
  • No reset --hard without a warning
  • Commit messages must carry Co-Authored-By

Model Routing

Claude Code picks its model to suit the task:

ModelUse caseTrade-off
OpusComplex reasoning, architectureSlow, expensive
SonnetGeneral coding, defaultBalanced
HaikuSimple tasks, sub-agentsFast, cheap

The user can override that with the /model command, or set it in settings.


Hooks System

Claude Code carries hooks for injecting custom logic:

# .claude/settings.json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "command": "echo 'Running: $TOOL_INPUT' >> ~/.claude/bash.log"
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Edit",
        "command": "prettier --write $FILE_PATH"
      }
    ]
  }
}

The hook types supported:

  • PreToolUse - before a tool runs
  • PostToolUse - after a tool runs
  • Notification - event notifications

Summary: Lessons Learned

From studying the Claude Code architecture, here is what we take away:

Loop
Agent Loop Pattern
Think -> Act -> Observe -> Repeat
Tool
Tool Abstraction
Capability = Tool definitions
Context
Context Management
Persistent + Dynamic + Compaction
Safety
Safety by Design
Permissions + Sandbox + Confirmation
Key takeaway: building an AI agent that does real work means thinking about tool design, context management, and safety — not just prompt engineering

Part of the AI Developer Tools Series