[KongchangAI]
· 2 min read· 1,389 words

Building an AI Coding Agent from Scratch: How Claude Code and Cursor Work Under the Hood

Building an AI Coding Agent from Scratch: How Claude Code and Cursor Work Under the Hood

AI coding agents consist of a model and an optimizable harness, centered on a tool-call loop and context management.

The article explains that an AI coding agent splits into two layers: the model and the harness. The model is hard to change, while the harness is configurable and buildable. The harness core is a while loop: send conversation history to the LLM, and if it returns a tool call, execute the tool, append the result, and request again until no tool calls remain, then output the final answer. Tools usually need only read, write, edit, and bash, plus web search. Skills are essentially organized prompts, using pointer files read on demand to avoid context bloat. The article also warns that repeatedly injecting the master prompt makes context snowball, and gives a debugging golden rule: print the full input sent to the LLM, because failures usually stem from context rather than the tools themselves.

Why Do You Need to Understand the Inner Workings of AI Coding Agents?

If you've used Claude Code or Cursor, you're probably familiar with the flow: pick a model (say, Opus), type a prompt, and hit Enter. But you may not realize that between your prompt and the model's visible output lies a complex harness. According to an in-depth breakdown from a YouTube tech channel, an AI Agent can be split into two parts: the model and the harness. The model is static and hard to change, while the harness is exactly the part we can optimize, configure, and even build from scratch. Understanding this layer lets you better configure tools like Claude Code and Cursor—and even write your own coding agent.

Basic structure of an AI Agent

The Core of an Agent: A Conversation Loop That Never Stops

Starting from the main function

The example program in the video starts from the main function. The author first writes a system prompt, then defines variables like the tools list and skills text, and concatenates the tools text and skills text into the final prompt. Then it enters the chat function—here a conversation variable is maintained, and an outer while True loop keeps waiting for user input. After receiving the user message, an inner loop starts: send the conversation plus the user message to the LLM and check the response. If the response is a tool call request, execute the corresponding tool, append the result to the conversation, and request the LLM again; only when a response no longer contains a tool call does it break out of the loop and show the final result to the user.

This loop can be further configured: for example, limiting the maximum number of tool calls or adding a timeout. But the example adds no limits, so the model can call tools indefinitely.

Accumulated history messages in the conversation loop

tool call is a structured output capability offered by mainstream large models today: instead of returning only natural language text, the model returns a JSON object declaring which function it wants to call and what arguments to pass. The harness receives this object, actually executes the corresponding local function, and appends the result as a new message to the conversation history. The model itself has no file system or terminal access—its ability to "read and write files" is entirely the harness acting on its behalf. This is also why the clearer the tool descriptions and parameter schemas are written, the more accurate the model's tool calls become—the model can only rely on this text to decide when to call and what values to pass.

context window refers to the token limit a model can receive in a single inference, including the system prompt, tool definitions, all history messages, and the current user input. It has two key characteristics: first, it's billed by token and usually has a hard cap; second, the model's attention to very long contexts degrades—information in the middle is easily overlooked, a phenomenon the industry often calls "lost in the middle." This explains why stuffing every rule into the prompt can actually be harmful: it not only crowds out space for the actual task but also dilutes the signal strength of genuinely important instructions. Making trade-offs within this fixed budget on every turn is the core constraint of harness design.

Tool definitions: the read, write, and execute trio

In tools.py, the author defines four core tools: read (read file content and return it as UTF-8), write (write to a file), edit (find-and-replace based editing, requiring the old string to appear exactly once in the file), and bash (execute terminal commands and return output). In addition, a web search tool is included. Each tool has a description, parameters, and a flag for whether approval is required. The author specifically notes that the open-source harness Pi uses exactly these four tools—read, write, edit, and bash—and strongly recommends trying Pi's local open-source solution.

Structure of tool function definitions

find-and-replace editing is currently the most mainstream way for coding agents to modify files. Compared with rewriting the whole file, it only has the model output the replaced fragment, greatly saving output tokens and reducing the risk of accidentally changing unrelated code. Requiring the old string to appear "exactly once" in the file is an important safety check: zero occurrences means the model's understanding of the file content is outdated, while multiple occurrences make it impossible to determine which spot to change. In both cases, the tool should return an error message rather than silently executing; when the model sees the error, it will re-read the file and try again, forming a self-correction loop.

The Essence of Skills: Cleverly Organized Prompts

Many people assume a skill is some complex mechanism, but the video puts it plainly: a skill is just a prompt, only placed in a separate file. The specific approach: put only pointers in skill.md, such as "to write test cases, read this file; to fix bugs, read that file; to commit code, look here." After the model reads these pointers in the master prompt, it proactively initiates read tool calls to load the corresponding files and then follows the steps inside.

Why split them out? Because if you stuff all the details into skill.md, the context balloons rapidly and model performance actually drops. The author mentions that some no-ops—such as "don't make mistakes" or "you are a senior engineer"—only take up context window space and contribute nothing to performance. Modern models are already smart enough; they don't need persona wrapping, only a clear statement of what specifically to do.

Discovery and loading logic of skills.md

Progressive disclosure is the general principle behind this pointer-style skill design: layer information and load the next layer only when needed. The first layer is a short index in the main prompt (a few dozen tokens), the second layer is the specific skill file being referenced, and the third layer is any reference materials or scripts that file may further reference. This way, even if an agent mounts dozens of skills, under normal circumstances it only occupies a small amount of context for the index. Anthropic's Agent Skills and the plugin mechanisms of many open-source harnesses follow this idea; the cost is that the model must proactively initiate read calls, so the recognizability of the index description directly determines whether a skill can be triggered correctly.

A Common Pitfall: Repeatedly Injecting the Master Prompt

During the demo, the author discovers a typical mistake of his own: the skills text is fixed after the first load, causing the same content to be repeatedly stuffed into context on every subsequent turn. Since the conversation history itself also accumulates, and the master prompt reappears every turn, the context snowballs. This is one of the most easily overlooked problems when building an agent. The fix is to inject it only once at the start of the conversation and rely on the history afterward.

The Golden Rule of Debugging Agents: Print What You Send to the LLM

The video ends with a very practical tip: when building an agent, always print out the complete input ultimately sent to the LLM. If the agent misbehaves, the problem is very likely in the context—either it's mixed with confusing irrelevant information, or it's missing key instructions, or the same content is being sent repeatedly. Staring only at tool call results won't reveal the root cause.

The author also personally role-plays the LLM, showing the prompt content he received: system prompt, tool descriptions, skills pointers, rules (such as "read the relevant source file before modifying anything"), and the user request "I want to improve my todo.py." This shift in perspective lets you intuitively feel how much information the LLM actually processes on each turn.

Build It Yourself vs. Use an Off-the-Shelf Solution

If you don't want to write a harness from scratch, the author recommends the open-source Pi, describing it as very effective and supporting mechanisms like skills, grill me, and hand off—suitable for scenarios where you don't want to use Claude Code or Cursor. Still, understanding the underlying loop and context management logic will make configuring any tool smoother. After all, the model is hard to change, but every detail of the harness is under your control.

#AI coding agent#Claude Code#Cursor#harness#context window#tool call#prompt engineering#LLM agent
Share:

Related articles