Skip to content
← All writing
2026-04-15 · 11 min read agentllmclaudearchitecture

Build a Mini Agent: Three Truths About Tools, Loops, and Context

Build a working agent in under 50 lines, then discover the real complexity isn't in the loop -- it's in tool boundaries and context management.

What you'll get from this article

The internals of agent tools like Cursor and Claude Code look mysterious -- sophisticated orchestration, diff algorithms, context management. It feels like you'd need a mountain of infrastructure just to get something running.

But the core skeleton is surprisingly simple. This article breaks it down into three layers:

💡

Scope, up front

This article covers the agent's minimal closed loop -- the kind you can get running in under 50 lines of code. The real Claude Code tool system, permission sandbox, and error recovery are far more involved, but the skeleton is the same. Understand the skeleton first, and the complexity has somewhere to hang.


Background: what an agent actually is

Key Concept

Agent

An LLM system that can call tools, observe results, and decide its next step based on those results. Plain text generation is not an agent -- it has no observe-act loop. The essence of an agent: model produces output, tools execute, results feed back in, model gets asked again -- repeat until the task is done.

Turn those four steps into code and you have an agent. The three-layer skeleton below maps to the three places in those steps that are most prone to over-engineering:

The agent's three-layer skeleton

1. Tool layer
name -> function
→
2. Loop layer
while True
→
3. Context layer
L1/L2/L3 compression

Real-world complexity increases left to right


Layer one: the tool system is just a dictionary

Intuitively, a tool system should need a registry, schema validation, a dispatcher, async queues, retry logic -- it sounds like you're about to write a small framework.

In practice, a dictionary is enough. Names map to functions. Done.

def run_bash(command: str) -> str:
    return subprocess.run(command, shell=True, capture_output=True, text=True).stdout

def read_file(path: str) -> str:
    return open(path).read()

TOOLS_IMPL = {
    "bash": lambda input: run_bash(input["command"]),
    "read_file": lambda input: read_file(input["path"]),
}

That's it. Tool implementations never enter the main loop. The loop is only responsible for:

  1. Taking the tool_use blocks the model returns
  2. Looking up the name in the dictionary
  3. Feeding the result back
✅

What this buys you

Adding a new tool = writing a plain function + adding one line to the dictionary. Zero coupling. Tools don't need to know the loop exists, and the loop doesn't need to know what the tools are doing. If you remember one thing about this architecture, make it this.

The tool schema (what the model sees) is a separate declaration, decoupled from the implementation:

TOOLS = [
    {
        "name": "bash",
        "description": "Run a bash command",
        "input_schema": {
            "type": "object",
            "properties": {"command": {"type": "string"}},
            "required": ["command"],
        },
    },
]

Layer two: the main loop is just a while True

Intuitively, the main loop should need a state machine, transition tables, branches for every stop condition, interrupt handling -- how else could it reliably run multi-turn conversations?

In practice, a while True plus one if to decide whether to exit is the whole thing.

def agent_loop(query: str):
    messages = [{"role": "user", "content": query}]

    while True:
        response = client.messages.create(
            model=MODEL,
            system=SYSTEM,
            messages=messages,
            tools=TOOLS,
            max_tokens=8000,
        )

        messages.append({"role": "assistant", "content": response.content})

        # The model is done talking -- exit
        if response.stop_reason != "tool_use":
            return response

        # Otherwise, execute every tool_use block and feed the results back
        results = []
        for block in response.content:
            if block.type == "tool_use":
                output = TOOLS_IMPL[block.name](block.input)
                results.append({
                    "type": "tool_result",
                    "tool_use_id": block.id,
                    "content": output,
                })

        messages.append({"role": "user", "content": results})

That's all of it. Under 25 lines.

⚠️

This is not toy code

This is a genuinely working agent. Fill in MODEL, SYSTEM, and the tools, and it will execute tasks for you. Claude Code's skeleton is exactly this -- there's just a lot more wrapped around it.

There's a lovely detail here: tool results go back in under the user role. From the model's perspective, a tool result looks like the user speaking again. This design means the model never needs to treat "tools" as a special concept -- it just sees the conversation continuing.

Why is there no state machine? Because the LLM is the state machine

This is the most counterintuitive part. Traditional programs need state machines because code can't think -- you need state variables to tell the code what to do next.

But in an agent loop, "what to do next" is decided by the model itself:

The entire conversation history is the state. The model reads it on every turn and knows exactly where it is and what comes next. All the code has to do is obey: when the model says stop, stop; when the model says call a tool, call the tool.

💡

Another way to see it

In a traditional program, the code holds the baton and decides which function to call based on state. In an agent loop, the model holds the baton and the code just executes what it's told. That inversion of control is the fundamental reason the agent loop can be this simple.

One more thing worth noting: in this mini implementation, editing a file = having the model rewrite the whole file.

No AST, no patches, no partial updates. The model emits the complete new file contents and you overwrite the old one. It sounds brutal, but in the era of 200k-token contexts, it's vastly simpler than maintaining an elaborate diff system -- and less error-prone too.


Layer three: context compression has three tiers, not one

This layer is where the real complexity of agents lives -- and it's the one most often underestimated.

The intuitive understanding of "context compression" goes like this: once the conversation history gets long, send a prompt asking the LLM to summarize it. One tier, done.

In practice, production-grade agents use a three-tier defense, and L3 is only the last resort.

The three tiers of context compression

L1 Offload to disk
Write artifacts to disk, keep a reference in context

Cheapest, used most often

↓

L2 Subagent isolation
Subtasks get their own context, only conclusions return

Medium cost, for large self-contained work

↓

L3 History summarization
Prompt the LLM to compress the full history

Most expensive, last resort

L1: offloading to disk -- the most overlooked tier

When Claude or Doubao generates an HTML page, the full file contents never go into the conversation history. They write to disk, and the context keeps only a preview or a file reference.

Which means:

💡

Why this matters so much

Intuition says generated output must occupy context. In reality, disk is the agent's long-term memory; context is just short-term working memory. Once that clicks, your whole mental model of agent resources flips -- and that's the fundamental reason L1 matters more than L3.

L2: subagent isolation

Large self-contained work (say, "analyze these 20 files and find the bugs") gets handed to a subagent that runs with its own context and sends back only the conclusion.

What the main context sees is:

[call analyze_codebase]
[returns: "Found 3 issues: 1. xxx 2. xxx 3. xxx"]

Not the 30 rounds of tool_use/tool_result the subagent actually went through. Thirty rounds compressed into three lines.

The difference between L2 and L1: L1 handles artifacts (files, long outputs), while L2 handles process (exploration, search, trial and error). A single codebase search can produce thousands of lines of intermediate output, but the main task only needs the final conclusion. The subagent is the wall that keeps process noise out of the main context.

L3: whole-history compression

Only when L1 and L2 together can't keep things under control and the context is genuinely about to overflow do you prompt the LLM to summarize the conversation history. It's the final backstop, not the first line of defense.


Common questions

After reading the code above, a few questions tend to come up. Let's knock them out:

Q: What about dependencies between tools? Say tool B needs tool A's output.

No special handling required. After the model reads A's tool_result, it decides on its own to call B next, passing A's result as an argument. Tool dependencies live at the conversation level, not the code level.

Q: How do I call multiple tools concurrently?

Look at the for block in response.content section above -- the model can return multiple tool_use blocks in a single turn. Swap that for loop for asyncio.gather and you have concurrent execution. Nothing changes on the model side; it already supports asking for several tools at once.

Q: What happens when a tool fails?

Stuff the error message into the tool_result's content as a string. The model reads "the tool failed, here's why," then decides for itself whether to retry, try a different tool, or give up. Error recovery isn't a try/except in your code -- it's the model self-correcting within the conversation.

Q: What if the model never exits the loop?

Add a maximum turn limit, MAX_TURNS, and force-exit past it. This is the only hard control you genuinely need in code. Everything else, leave to the model.


Iron rules

⚡ Iron Rule #1

Agent complexity isn't in the loop -- it's in resource management outside the loop

Twenty-five lines of main loop is enough. Tool registration is a dictionary. The hard part is deciding what belongs in context, what goes to disk, and which tasks go to a subagent. Those decisions are where engineers earn their keep.

⚡ Iron Rule #2

Context is your most expensive resource -- offload, don't inline

Any artifact (files, long outputs, intermediate results) should go to disk by default, with only a reference left in context. L1 first, L2 second; L3 is a backstop, not standard practice.

⚡ Iron Rule #3

The tool layer must be fully decoupled from the loop

A tool is a plain function. It shouldn't know about the loop, the model, or the context. That way, adding a new capability costs you one function -- not an architecture change.


Closing

Back to that opening claim: the internals of Cursor and Claude Code look mysterious. Take them apart, and you find the genuinely hard part isn't the loop or the tool registry -- it's the single decision of when to move things out of context.

The 25-line main loop and the tool dictionary are written once and never touched again. But "what goes in context, what goes to disk, what goes to a subagent" -- that judgment call has to be remade for every new feature, and every scenario has a different optimal answer. That's why an agent engineer's battlefield isn't the loop.

This skeleton deliberately leaves a lot out: a permission system, streaming output, tool timeouts, the actual subagent implementation, multi-model coordination... Future articles will add them one at a time, and each addition will explain why it's needed and what breaks without it.

But first, burn this 50-line skeleton into your head -- everything complex that comes later is just an attachment hanging off of it.