Sub topic 7
The usual toolbox: read, search, edit, run
This chapter assumes you have read the earlier chapters on tool definitions and tool calls. You should know that a tool is a name, a description, and an input schema, and that the harness runs the function the model asks for. Here we look at which tools nearly every coding agent ships with, why those tools exist, and where each one goes wrong.
Four jobs, four kinds of tool
A coding agent works on a codebase it cannot see directly. Everything it knows comes from tool results. Almost every task reduces to four jobs:
- Read: look at the contents of a file.
- Search: find which files or lines matter, without reading everything.
- Edit: change or create files.
- Run: execute commands, such as tests, linters, builds, and git.
Products differ in tool names and schemas, but this set is stable. A typical harness may add a few extras, such as listing a directory, fetching a web page, or asking the user a question. The extras are variations on these four jobs.
Read tools
A read tool takes a path and returns text. The definition from earlier in this tutorial is typical: one required path string.
Three design choices matter here.
- Size limits. A single file can be larger than the whole context window. The
read_fileexample in the spine slices the text to 20,000 characters ([:20000]). That is a blunt limit, and the model cannot tell that the file was cut off unless the tool says so. - Ranges. Many harnesses add optional
offsetandlimit(orstart_lineandend_line) arguments. The model can then read lines 400 to 500 of a big file instead of the whole thing. - Line numbers. Some harnesses prefix each line with its number. That helps the model refer to exact locations and request ranges. It also means the model must not copy those prefixes into edits.
A better truncation message looks like this:
from pathlib import Path
MAX_CHARS = 20000
def read_file(path, offset=0):
text = Path(path).read_text()
chunk = text[offset:offset + MAX_CHARS]
if offset + MAX_CHARS < len(text):
chunk += (f"\n[truncated: showing characters {offset}-{offset + MAX_CHARS} "
f"of {len(text)}. Call again with offset={offset + MAX_CHARS}.]")
return chunkThe final line is text the model reads like any other result. It tells the model that more content exists and how to get it. A silent cut-off leads to confident answers about code the model never saw.
Search tools
Reading is cheap for one file and expensive for a repository. Search tools let the model locate things first. There are two common kinds:
| Tool | Question it answers | Typical backend |
|---|---|---|
| Name search (glob) | Which files have paths matching `**/*.py`? | File system walk |
| Content search (grep) | Which lines contain `def parse_config`? | `grep`, `ripgrep`, or a similar program |
Some products also offer symbol or semantic search, which uses a code index or embeddings. Those are optional. Plain text search is enough for many agents, because the model can run several searches in a row, refining each query from the last results.
Search results need limits too. A grep for import in a large repository can return thousands of lines. Good search tools cap the number of matches, return file paths with line numbers, and respect .gitignore so that node_modules and build output do not flood the results.
import subprocess
def grep(pattern, path=".", max_lines=100):
r = subprocess.run(
["grep", "-rn", "--exclude-dir=.git", "--exclude-dir=node_modules",
"-e", pattern, path],
capture_output=True, text=True, timeout=30,
)
lines = r.stdout.splitlines()
out = "\n".join(lines[:max_lines])
if len(lines) > max_lines:
out += f"\n[{len(lines) - max_lines} more matches omitted. Narrow the pattern or path.]"
return out or "no matches"Note two details. The command is passed as a list, not a shell string, so a pattern containing quotes or ; is treated as a pattern and not as shell syntax. And an empty result returns no matches, not an empty string. An empty tool result is ambiguous: the model cannot tell whether the tool failed or found nothing.
Edit tools
Edit tools are where agents either work well or corrupt your project. There are three common designs.
| Design | How the model expresses a change | Strength | Typical failure |
|---|---|---|---|
| Whole-file write | Sends the full new file contents | Simple to implement | Costs many output tokens, and the model may silently drop parts of a long file |
| String replacement | Sends `old_text` and `new_text` | Small, precise, easy to review | `old_text` does not match exactly, or matches more than once |
| Patch or diff | Sends a unified diff or similar | Compact for multi-location changes | Models often get line numbers or context lines wrong |
String replacement is the most common design in coding agents. The key rule is that the tool must refuse ambiguous edits instead of guessing:
from pathlib import Path
def edit_file(path, old_text, new_text):
p = Path(path)
text = p.read_text()
count = text.count(old_text)
if count == 0:
raise ValueError("old_text not found. Re-read the file and copy the text exactly.")
if count > 1:
raise ValueError(f"old_text appears {count} times. Include more surrounding lines to make it unique.")
p.write_text(text.replace(old_text, new_text))
return f"edited {path}"The agent loop from earlier chapters turns a raised exception into an error: ... tool result. That is the feedback mechanism doing its job: the model reads "appears 3 times" and retries with more context. The error messages are written for the model, so they should say what to do next.
Run tools
A run tool executes a shell command and returns its output. It is the most powerful tool and the most dangerous. It lets the agent run the test suite, but it also lets the agent run rm -rf, install packages, or send data over the network.
The run_command in the spine shows the minimum controls:
- A timeout (30 seconds there), so a hung process does not stall the loop.
- Merged
stdoutandstderr, because test failures often print to either. - Tail truncation (
[-5000:]), which keeps the end of the output. For commands, the end usually holds the summary and the final error, while the start holds banners and progress lines.
Real harnesses add more:
- Exit code. Including it, for example
exit code: 1, tells the model whether the command succeeded even when the output is empty. - Working directory. Each call may start fresh, so
cdin one call may not carry to the next. The model needs to know this, usually from the system prompt or tool description. - Background or long-running processes. A dev server never exits, so a plain blocking call times out. Some harnesses add a way to start a process and read its output later.
- Interactive programs. A command that waits for input, such as a prompt asking
Proceed? [y/N], will hang until the timeout. Tell the model to use non-interactive flags.
Running tests is the central use. The output of a failing test run is the strongest feedback the loop gets, and later chapters cover it in detail.
Matching tools to the context budget
Every result goes back into the message list, so every tool is also a context spending decision. The usual pattern is to move from cheap and broad to expensive and narrow:
- Search to find candidate files (a few hundred tokens).
- Read only the relevant ranges (hundreds to thousands of tokens).
- Edit with small replacements (tens of tokens).
- Run targeted tests, not the whole suite, when possible.
An agent that reads whole files first runs through its window quickly. An agent that searches first spends little to learn a lot.
Common failure modes
| Symptom in the trace | Likely cause | Fix |
|---|---|---|
| Model edits code that does not exist | It never read the file, or the read was truncated silently | Add truncation notices; require read before edit |
| Same grep repeated with small changes | Results are empty with no explanation, or too long and cut | Return `no matches`; report omitted counts |
| Edit fails repeatedly with "not found" | Line-number prefixes or tab/space differences copied into `old_text` | Strip prefixes in the tool; show exact whitespace guidance in the error |
| Command hangs for the full timeout | Interactive prompt or long-running server | Use non-interactive flags; add a background mode |
| Model claims tests pass but never ran them | No run tool call appears in the trace | Instruct it to run tests; check exit codes in results |
Tool descriptions are part of the design
The model chooses between tools by reading their descriptions. Two tools with vague, overlapping descriptions get confused. A good description says what the tool does, when to prefer it, and what it will not do. For example: "Search file contents for a regular expression. Use this to find where a symbol is defined or used. Does not read whole files; use read_file for that."
Fewer, clearer tools generally beat many similar ones. If the model has both grep and search_code with similar descriptions, it will pick between them unpredictably.
Exercise
An agent calls edit_file with an old_text that appears in three places in the file. The tool raises an error. Name two things the error message should tell the model, and explain why a tool that edited the first match instead would be worse.
Show answer
The message should say how many times old_text appears and tell the model to include more surrounding lines to make the text unique. Editing the first match would be worse because the model might have meant a different occurrence. The tool would report success, the wrong code would change, and nothing in the trace would signal the problem until tests failed later or never.
Exercise
A run_command call for the test suite returns 40,000 characters of output, and the harness keeps only the last 5,000. Why is keeping the tail usually better than keeping the head for command output, and what extra field would help the model tell success from failure when the output is empty?
Show answer
Test and build tools print progress and setup lines first, and the failure details and summary last, so the tail holds what the model needs. Including the exit code in the result lets the model tell success from failure even when there is no output.