Learn Claude Code -- Harness Engineering for Real Agents
7/18/2026, 11:18:05 PM · Source
Master the art of agent harness engineering by building a complete operational vehicle for AI models, starting from a basic agent loop up to complex multi-agent systems and MCP integrations.
True agency is trained into deep learning models, not engineered via procedural code or orchestration graphs. To become a functioning product, an intelligent model requires a robust vehicle: a harness that manages tools, knowledge, context, and permissions. This guide explores harness engineering, drawing from the minimal yet highly effective architecture of Claude Code to teach you how to build real-world agent systems from the ground up.
GitHub - shareAI-lab/learn-claude-code: Bash is all you need - A nano claude code–like 「agent harness」, built from 0 to 1
Languages available: English | 中文 | 日本語
Where Agency Comes From: Model vs. Harness
Agency—the capacity to perceive, reason, and act—comes from model training, not from external code orchestration. The model is the driver; the harness is the vehicle.
At the core of every agent is a neural network shaped by billions of gradient updates on sequences of perception, reasoning, and action. Humans are the biological proof of this concept: we perceive through senses, reason through a brain, and act through a body. When AI labs refer to an "agent," they mean a trained model operating within an environmental infrastructure.
The historical record of model-driven agency is unambiguous:
- 2013 (DeepMind DQN plays Atari): A single neural network, receiving only raw pixels and game scores, mastered seven Atari 2600 games without game-specific rules. By 2015, it scaled to 49 games at a professional level, proving that models learn from experience.
- 2019 (OpenAI Five conquers Dota 2): Five neural networks played 45,000 years of Dota 2 against themselves over ten months, defeating the TI8 world champions 2-0. They won 99.4% of 42,729 public games without scripted strategies.
- 2019 (DeepMind AlphaStar masters StarCraft II): AlphaStar defeated professional players 10-1 in closed matches and achieved Grandmaster rank on the European server, overcoming incomplete information and real-time combinatorial action spaces.
- 2019 (Tencent Jueyu dominates Honor of Kings): Tencent AI Lab's "Jueyu" system defeated KPL professional players in full 5v5 matches. In 1v1 play, pros won just 1 out of 15 matches. Training intensity reached the equivalent of 440 human years per day.
- 2024–2025 (LLM agents reshape software engineering): LLMs like Claude, GPT, and Gemini are deployed as coding agents. They read codebases, implement features, and debug failures. The architecture remains identical: a trained model placed in an environment and granted tools for perception and action.
Every milestone points to the same fact: Agency is trained, not coded. However, models still need an environment to act within—whether an Atari emulator, a game client, or an IDE and shell terminal. The model supplies the intelligence; the harness supplies the action space.
What an Agent Is NOT
The term "agent" has been hijacked by a prompt-plumbing industry featuring drag-and-drop workflow builders, no-code platforms, and prompt-chain orchestration libraries. These systems operate on a shared delusion: that stringing LLM API calls together with if-else branches, node graphs, and hardcoded routing logic constitutes "building an agent."
These are Rube Goldberg machines—over-engineered, brittle, procedural rule pipelines with an LLM wedged in as a text-completion node. You cannot brute-force intelligence by stacking procedural rule trees and prompt waterfalls.
The Shift to Harness Engineering
When you build an agent product, your work falls into one of two categories:
- Training a Model: Adjusting weights through reinforcement learning, fine-tuning, or RLHF to shape behavioral trajectories.
- Building a Harness: Writing the operational code that gives a model its environment.
A harness provides everything an agent needs to work in a specific domain:
Tools: file I/O, shell, network, database, browser
Knowledge: product docs, domain references, API specs, style guides
Observation: git diff, error logs, browser state, sensor data
Action: CLI commands, API calls, UI interactions
Permissions: sandbox isolation, approval workflows, trust boundaries
What Harness Engineers Actually Do
The quality of the harness directly determines how effectively the model's intelligence can express itself. Your role as a harness engineer is to:
- Implement Tools: Give the agent hands. Design atomic, composable, and clearly described tools for file operations, shell execution, database queries, and browser control.
- Curate Knowledge: Give the agent domain expertise. Load documentation, specs, and style guides on-demand rather than upfront.
- Manage Context: Give the agent clean memory. Use subagent isolation to prevent noise leakage, context compaction to prevent history bloat, and task systems to persist goals.
- Control Permissions: Establish boundaries. Sandbox file access, require explicit human approval for destructive actions, and enforce trust boundaries.
- Collect Trajectory Data: Treat execution sequences as training signals. Real-world execution histories are the raw material for fine-tuning the next generation of models.
The Claude Code Pattern
Claude Code is an elegant agent harness implementation because of what it does not do: it does not try to be the agent. It does not impose rigid workflows or substitute hand-crafted decision trees for the model's own judgment. It simply provides tools, knowledge, context management, and permission boundaries, then gets out of the way.
Stripping Claude Code down to its essence reveals:
- An agent loop
- Core tools (bash, read, write, edit, glob, grep, browser)
- On-demand skill loading
- Context compaction
- Subagent spawning
- A task system with dependency graphs
- Async mailbox team coordination
- Worktree-isolated parallel execution
- Permission governance
- An extension hooks system
- Memory persistence
- Model Context Protocol (MCP) external capability routing
The Agent Pattern
THE AGENT PATTERN
=================
User --> messages[] --> LLM --> response
|
stop_reason == "tool_use"?
/ \
yes no
| |
execute tools return text
append results
loop back -----------------> messages[]
The model decides when to call tools and when to stop. The harness code simply executes what the model requests.
Core Pattern Implementation
Each lesson in this project layers one harness mechanism on top of this fundamental loop:
def agent_loop(messages):
while True:
response = client.messages.create(
model=MODEL, system=SYSTEM,
messages=messages, tools=TOOLS,
)
messages.append({"role": "assistant",
"content": response.content})
if response.stop_reason != "tool_use":
return
results = []
for block in response.content:
if block.type == "tool_use":
output = TOOL_HANDLERS[block.name](**block.input)
results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": output,
})
messages.append({"role": "user", "content": results})
20 Progressive Lessons
The curriculum is structured around 20 core lessons, each introducing a critical harness mechanism with a guiding principle:
- s01 "One loop & Bash is all you need" — One tool + one loop = one agent.
- s02 "Adding a tool means adding one handler" — Keep the loop untouched; register new tools into the dispatch map.
- s03 "Set boundaries first, then grant freedom" — Check what can run, what must stop, and what needs approval.
- s04 "Hook around the loop, never rewrite the loop" — Add extension points without modifying the main loop.
- s05 "An agent without a plan drifts" — List steps before execution to double completion rates.
- s06 "Big tasks split small, each subtask gets clean context" — Run subagents for side work and bring back only the result.
- s07 "Load knowledge on demand, not upfront" — List skills first; expand them only when needed.
- s08 "Context always fills up—have a way to make room" — Use multi-layer compaction strategies for infinite sessions.
- s09 "Remember what matters, forget what doesn't" — Implement memory selection, extraction, and consolidation.
- s10 "Prompts are assembled at runtime, not hardcoded" — Use section-based concatenation loaded on-demand.
- s11 "Errors aren't the end, they're the start of a retry" — Retry, manage context space, or try fallback models when tasks fail.
- s12 "Big goals break into small tasks, ordered, persisted to disk" — Build a file-backed task graph for multi-agent coordination.
- s13 "Slow ops go background, agent keeps thinking" — Run background threads and inject notifications on completion.
- s14 "Fire on schedule, no human kick needed" — Trigger time-based autonomous tasks.
- s15 "Too big for one agent—delegate to teammates" — Organize persistent teammates using asynchronous mailboxes.
- s16 "Teammates need shared communication rules" — Enforce a rigid request-reply format for coordination.
- s17 "Teammates check the board, claim work themselves" — Establish self-organizing agent teams.
- s18 "Each works in its own directory, no interference" — Bind tasks to independent directories using worktrees.
- s19 "Not enough capability? Plug in more via MCP" — Connect external tools into a unified tool pool via Model Context Protocol.
- s20 "Many mechanisms, one loop" — Integrate all components into a single, comprehensive agent harness.
Project Scope Boundaries
To keep the learning path clear, this repository uses simplified teaching implementations of some production architectures:
- Minimal event/hook bus lifecycles are used instead of a full enterprise event bus (
PreToolUse,SessionStart, etc.). - Permission policies and trust workflows are basic rather than fully enterprise rule-governed.
- Worktree lifecycles and session control (resume/fork) are kept minimal.
- The MCP runtime is a direct implementation (omitting complex OAuth, polling, or transport routing).
- The mailbox protocol uses a straightforward JSONL file structure.
Learning Path
The course progression moves from core execution, to task management, memory handling, asynchronous background operations, and finally multi-agent collaboration.
Course Structures and Track Migration
This project includes a legacy 12-lesson track alongside a comprehensive 20-lesson track. Ensure you are using the correct folders, as chapter numbers differ between versions.
Legacy-to-Current Chapter Mapping
| Legacy 12-Lesson Track | Current 20-Lesson Track | Topic |
|---|---|---|
| old s01 | new s01 | Agent Loop |
| old s02 | new s02 | Tool Use |
| old s03 | new s05 | TodoWrite |
| old s04 | new s06 | Subagent |
| old s05 | new s07 | Skill Loading |
| old s06 | new s08 | Context Compact |
| old s07 | new s12 | Task System |
| old s08 | new s13 | Background Tasks |
| old s09 | new s15 | Agent Teams |
| old s10 | new s16 | Team Protocols |
| old s11 | new s17 | Autonomous Agents |
| old s12 | new s18 | Worktree Isolation |
| N/A | s03, s04, s09, s10, s11, s14, s19, s20 | Permission, Hooks, Memory, System Prompt, Error Recovery, Cron, MCP, Comprehensive Agent |
Curriculum Reference Index
| Chapter | Topic | Key Concepts |
|---|---|---|
| s01 | Agent Loop | messages / while True / stop_reason |
| s02 | Tool Use | TOOL_HANDLERS / dispatch map / concurrency |
| s03 | Permission System | PermissionRule / approval pipeline |
| s04 | Hook System | PreToolUse / PostToolUse / extension points |
| s05 | TodoWrite | TodoItem / plan-then-execute |
| s06 | Subagent | fresh messages[] / context isolation |
| s07 | Skill Loading | SkillManifest / on-demand injection |
| s08 | Context Compact | snipCompact / microCompact / toolResultBudget / autoCompact |
| s09 | Memory System | selection / extraction / consolidation |
| s10 | System Prompt | runtime assembly / section concatenation |
| s11 | Error Recovery | token escalation / fallback model / retry strategies |
| s12 | Task System | TaskRecord / blockedBy / disk persistence |
| s13 | Background Tasks | threaded execution / notification queue |
| s14 | Cron Scheduler | durable scheduling / session-scoped triggers |
| s15 | Agent Teams | MessageBus / inbox / permission bubbling |
| s16 | Team Protocols | shutdown handshake / plan approval |
| s17 | Autonomous Agents | idle cycle / auto-claim / self-organization |
| s18 | Worktree Isolation | WorktreeRecord / task-directory binding |
| s19 | MCP Plugin | multi-transport / channel routing / tool pool assembly |
| s20 | Comprehensive Agent | all mechanisms integrated around one loop |
Getting Started
Each chapter is structured as a standalone folder containing explanations, runnable code, and visual aids:
s08_context_compact/
README.md # Core lesson with inline code
README.en.md # English translation
README.ja.md # Japanese translation
code.py # Standalone runnable implementation
images/ # SVG diagrams
To begin exploring the codebase and running the lessons:
# Clone the repository
git clone https://github.com/shareAI-lab/learn-claude-code
# Navigate to the workspace
cd learn-claude-code
# Install required packages
pip install -r requirements.txt
# Configure environmental variables
cp .env.example .env
Key Takeaways
- Intelligence is Learned, Not Coded: AI agency is the product of model training (gradient updates, reinforcement learning, trajectory exposure), not brittle prompt-chaining libraries or procedural rule engines.
- The Harness is Your Product: The engineering objective is to build a reliable vehicle—handling state, tool inputs, file sandboxes, context management, and permissions—while allowing the model to make the execution decisions.
- The Power of the Agent Loop: Keep your core agent loop absolute and simple. Extend behavior by adding tool handlers, hooking actions, managing context state, and isolated subagents rather than complicating the central loop.
- Data is the Ultimate Asset: Designing a robust execution harness allows you to capture actual trajectory data, which serves as the training feedback loop to make future models smarter.
To review the implementation details or run the chapters locally, check out the GitHub repository.
Learning map
Stage 1: Core Loops & Safe Tool Execution
- s01-s04: The Foundation
- Learn how a single
while Trueloop drives LLM execution, registers custom tools in a dispatch map, enforces strict permission boundaries, and implements extension points via hooks without refactoring the core logic.
- Learn how a single
Stage 2: Planning & Context Maintenance
- s05-s11: Plan, Split, and Compact
- Learn to prevent context bloat and keep agents on target. Work with planning-first workflows (TodoWrite), delegate large tasks to isolated subagents, apply multi-layer context compaction strategies, and set up fallback error-recovery mechanisms.
Stage 3: Dynamic Tasks & Collaboration
- s12-s20: Scaling to Production
- Handle multi-agent teams. Learn to persist task dependency graphs to disk, run background processes asynchronously, establish mailbox communication standards, split directories cleanly using worktrees, and plug in external tools with Model Context Protocol (MCP).
Get hands-on — step by step
-
Set Up the Workspace: Clone the tutorial codebase and install the project requirements:
git clone https://github.com/shareAI-lab/learn-claude-code cd learn-claude-code pip install -r requirements.txt -
Configure API Access: Copy the template environment file and add your Anthropic API Key:
cp .env.example .env # Open .env and populate your ANTHROPIC_API_KEY -
Run the Basic Loop (s01): Execute the first lesson to understand how Claude utilizes bash commands in a loop:
python s01_agent_loop/code.py -
Add Custom Handlers (s02): Inspect
s02_tool_use/code.py. Define a new tool dictionary for custom file manipulation and register it in theTOOL_HANDLERSdispatch map. -
Explore MCP Integration & Full Assembly (s20): Inspect the final project files to observe how MCP plugins connect external API pools to the consolidated agent harness.
Top 3 sources
- 1shareAI-lab/learn-claude-code GitHub Repository
The official open-source repository containing the 20-lesson guide to building a micro Claude Code agent harness from scratch.
https://github.com/shareAI-lab/learn-claude-code
- 2Model Context Protocol (MCP) Documentation
The official documentation for MCP, defining the open standard used to connect AI models safely to data sources and tools.
https://modelcontextprotocol.io
- 3Anthropic Claude API & Developer Documentation
Official Anthropic portal covering computer use, tool calling capabilities, prompt engineering guidelines, and API setup instructions.
https://docs.anthropic.com/en/docs/welcome
Links are AI-suggested — worth a quick sanity check before diving in.