Skip to content

How to Build Your Own Coding Agent

Build a functional coding agent with Python or Go to automate codebase navigation, surgical file editing, and guarded shell command execution in a loop.

Tuan Tran Van
7 min read
Contents (9 sections)
  1. Step 1 — Build the conversation loop
  2. Step 2 — Define your first tool and handle the tool_use signal
  3. Step 3 — Complete the file read, write, and edit tools
  4. Step 4 — Give the agent shell access behind an approval gate
  5. Step 5 — Run the agent on a real repo and verify the result
  6. Minimal tool set reference
  7. Troubleshooting
  8. Next step
  9. References

You will finish with a working coding agent that reads your files, edits them, and runs shell commands on its own, driven by a ReAct (Reason, Act, Observe) loop.

It reads files to see what it is working with, decides what to do next, and runs commands to reach the goal — without you stepping through each action.

You need Python 3.10 or higher, an Anthropic API key in ANTHROPIC_API_KEY, and a terminal. The examples below use Claude Sonnet 5 as the reasoning model.

The complete sample project for this guide is on GitHub: camnangai-public-sources/coding-agent-demo.

A minimal coding agent running in a terminal, assembled from three parts: a language model, a loop, and a set of tools

Step 1 — Build the conversation loop

Pick one — skip the others.

The conversation loop: the history is sent to the model, the model replies, the reply is appended to the history, and it repeats

Python Implementation

python
import anthropic
import sys
 
client = anthropic.Anthropic()
MODEL = "claude-sonnet-5"
 
def run_agent(user_message, conversation_history=None):
    if conversation_history is None:
        conversation_history = []
 
    conversation_history.append({"role": "user", "content": user_message})
 
    while True:
        with client.messages.stream(
            model=MODEL,
            max_tokens=4096,
            system="You are a helpful coding assistant.",
            messages=conversation_history
        ) as stream:
            for event in stream:
                if event.type == "content_block_delta" and event.delta.type == "text_delta":
                    sys.stdout.write(event.delta.text)
                    sys.stdout.flush()
 
            final_message = stream.get_final_message()
            conversation_history.append({"role": "assistant", "content": final_message.content})
 
            if final_message.stop_reason != "tool_use":
                break
            # Tool handling logic follows in Step 2

Go Implementation

go
package main
 
import (
    "context"
    "fmt"
    "github.com/anthropics/anthropic-sdk-go"
)
 
func (a *Agent) Run(ctx context.Context) error {
    conversation := []anthropic.MessageParam{}
    for {
        userInput, ok := a.getUserMessage() // Implementation uses bufio.Scanner
        if !ok { break }
 
        conversation = append(conversation, anthropic.NewUserMessage(anthropic.NewTextBlock(userInput)))
 
        message, err := a.client.Messages.New(ctx, anthropic.MessageNewParams{
            Model:     "claude-sonnet-5",
            MaxTokens: 4096,
            Messages:  conversation,
        })
        if err != nil { return err }
 
        conversation = append(conversation, message.ToParam())
        fmt.Printf("Claude: %s\n", message.Content[0].Text)
    }
    return nil
}

This loop is the heartbeat of the agent. It keeps multi-turn state by carrying the conversation and environment across every interaction.

Step 2 — Define your first tool and handle the tool_use signal

Define a tool schema so the model can interact with the file system.

The ReAct tool cycle: the model emits a tool_use signal, the client executes the tool, and the tool_result goes back so the model can keep reasoning

json
{
  "name": "read_file",
  "description": "Read the contents of a file at the given path.",
  "input_schema": {
    "type": "object",
    "properties": {
      "path": { "type": "string", "description": "The path to the file to read" }
    },
    "required": ["path"]
  }
}

Add a safety function that prevents directory traversal using .resolve():

python
from pathlib import Path
WORKSPACE = Path.cwd().resolve()
 
def resolve_workspace_path(path_str: str) -> Path:
    resolved = (WORKSPACE / path_str).resolve()
    if resolved != WORKSPACE and WORKSPACE not in resolved.parents:
        raise ValueError(f"Path escapes workspace: {path_str}")
    return resolved

Intercept the tool_use signal in your loop to extract the tool metadata:

python
if final_message.stop_reason == "tool_use":
    for block in final_message.content:
        if block.type == "tool_use":
            tool_id = block.id
            tool_name = block.name
            tool_input = block.input
            # Execute tool_name logic here

Explicit schema definitions let the model reason about its environment and work out exactly when it needs an external function to make progress.

A terminal printing the executing-tool line for read_file with its path argument, followed by the contents of main.py with line numbers

Step 3 — Complete the file read, write, and edit tools

Implement tools for listing and modifying files. Use surgical editing for existing code.

python
def list_files(path="."):
    safe_path = resolve_workspace_path(path)
    return [str(p.relative_to(WORKSPACE)) for p in safe_path.rglob("*") if p.is_file()]
 
def write_file(path, content):
    safe_path = resolve_workspace_path(path)
    safe_path.write_text(content)
    return f"Successfully wrote to {path}"
 
def edit_file(path, old_string, new_string):
    safe_path = resolve_workspace_path(path)
    content = safe_path.read_text()
 
    if content.count(old_string) != 1:
        return f"Error: Found {content.count(old_string)} occurrences of target string. Edits must be unique."
 
    new_content = content.replace(old_string, new_string)
    safe_path.write_text(new_content)
    return f"Successfully edited {path}"

Surgical editing cuts use and prevents accidental code corruption, because the agent makes precise updates instead of rewriting whole files.

Step 4 — Give the agent shell access behind an approval gate

Add shell execution so the agent can run tests, install dependencies, and verify the environment.

The safety boundary for shell access: the agent proposes a command, a human approval gate sits in between, and a subprocess is not a sandbox

python
import subprocess
 
def run_bash(command):
    # Mandatory Approval Gate
    confirm = input(f"Execute command? [y/N]: {command} ")
    if confirm.lower() != 'y':
        return "Command aborted by user."
 
    try:
        result = subprocess.run(
            command, shell=True, capture_output=True, text=True, timeout=60
        )
        return result.stdout + result.stderr
    except subprocess.TimeoutExpired:
        return "Error: Command timed out after 60 seconds"

WARNING: A subprocess gives you process isolation, not a security sandbox. Running untrusted code can corrupt your system or exfiltrate data. Never run this in an environment holding sensitive secrets without a restricted container.

Step 5 — Run the agent on a real repo and verify the result

Give it a task that exercises the full ReAct loop: "Implement a Fibonacci function in a new file and run the tests."

Update the to enforce a four-stage verification loop:

  1. Inspect: Review existing code and project constraints.
  2. Plan: State a brief plan before taking any action.
  3. Verify: Review the diff and run the relevant tests or build commands.
  4. Report: Declare completion only after every check passes.

The agent reads each tool_result to observe its own success or failure. When a test fails, it sees the error in the history and attempts a fix on its own.

The agent reads CLAUDE.md and test_main.py, uses edit_file to add a /health endpoint, asks for approval to run pytest, and finishes with both tests passing

Minimal tool set reference

ToolPurposeLogic principle
read_fileRetrieve file content.Context discipline: load only the data you need into the window.
write_fileCreate or overwrite a file.Workspace restriction: check the parent path to prevent traversal.
edit_fileSurgical text replacement.Precision: require exactly one match to avoid ambiguous corruption.
list_filesMap the project structure.Stable facts: establish the repo layout as a baseline for reasoning.
run_bashExecute shell commands or tests.Environmental feedback: use stdout and stderr to drive the ReAct cycle.

Troubleshooting

SymptomCauseFix
"Path escapes workspace"Malicious or hallucinated relative paths, such as ../../.Use resolve_workspace_path with .resolve() and parent validation.
Agent loops on a failing toolVague error messages leave the model unable to spot its mistake.Return specific "expected X, found Y" strings to guide the next turn.
Context bloat or high latencyFull file reads on large sources burn tokens.Add line-range offsets, or prefer surgical edits over full writes.

Next step

Add to manage large repository state. Without it, a long-running agent accumulates irrelevant noise until it becomes an expensive typist. Create a CLAUDE.md memory file in the project root to hold persistent architectural conventions, and read up on context engineering before you scale the loop further.

References

Check yourself

Three quick questions to see whether the main ideas stuck.

  1. What sits at the core of a coding agent?
  2. How should the agent change an existing file?
  3. How should shell access be added safely?

Share this article

AI glossary