Tools: the contract between model and world
“The tool is the only thing that separates an opinion from a fact.”
Objective
Understand why a tool’s schema is an interface and not documentation, implement argument validation that survives a hallucinating model, and ensure that no tool error brings down the loop.
3.1 Three things around a function
A tool is a Python function with three things around it: a name, a description and an argument schema. The model never sees the code. It sees only this contract — and that is why the description matters as much as the implementation.
There is a temptation to treat the schema as a formality. It is not. The schema is what the model uses to decide whether to call the tool and how to fill in the arguments. A loose schema produces wrong calls; a tight schema produces right ones.
| Schema | Likely effect |
|---|---|
{"query": {"type": "string"}} | The model invents a different search format at every step |
{"query": {"type": "string", "description": "search term, no operators"}, "limit": {"type": "integer", "minimum": 1, "maximum": 20}} | The model uses a stable format and respects the limit |
Table 3.1. Effect of schema tightness on model behavior.
The second schema is not “prettier”. It eliminates an entire class of failures before they happen.
3.2 Validation before execution
The model is an untrusted source of input. It may omit a required field, send a string where an integer is expected, or invent a field that does not exist. Validating before executing is not paranoia — it is what prevents a hallucination from becoming a TypeError in the middle of your process.
Listing 3.1. Argument validation: rejects missing and extra fields.
def validate_args(schema: dict, args: dict) -> None:
for req in schema.get("required", []):
if req not in args:
raise PolicyError(f"missing required argument: {req}")
for key, value in args.items():
spec = schema.get("properties", {}).get(key)
if spec is None:
raise PolicyError(f"argument not declared in schema: {key}")
if spec.get("type") == "string" and not isinstance(value, str):
raise PolicyError(f"{key} should be a string, "
f"got {type(value).__name__}")
Notice the second check: rejecting undeclared fields. It seems too strict, but it is an important defense. Models sometimes “enrich” a call with extra fields that look harmless — and that, in a poorly written tool, end up becoming behavior parameters.
Why not just use
pydantic. You can, and should, in complex tools. The example above exists to show what the library does for you: checking that required fields are present, the type of each field and the absence of extra fields. If you usepydanticwithout knowing what it validates, when it lets something through you will not know whether it is your bug or your configuration.
3.3 Errors become observations, not exceptions
The golden rule for a tool inside an agent: never let an exception kill the loop.
Listing 3.2. Tool execution: every error comes back as a result.
def execute(name: str, args: dict) -> str:
tool = TOOLS.get(name)
if tool is None:
return json.dumps({"error": f"unknown tool: {name}"})
try:
validate_args(tool["schema"], args)
return tool["fn"](**args)
except PolicyError as exc:
return json.dumps({"error": f"policy: {exc}"})
except Exception as exc:
return json.dumps({"error": f"{type(exc).__name__}: {exc}"})
The reason is simple and profound: the agent can recover from an error it can see, but not from an error that brings down the process. If the tool fails and the error comes back as an observation, the model can try another approach. If the process dies, there is no agent at all.
Two design choices built into this code deserve attention.
First, the error is serialized as JSON. This gives the model a predictable structure ({"error": "..."}) instead of loose text, and makes inspecting the trace easier.
Second, the except Exception is broad on purpose. A tool can fail for any reason — nonexistent file, network timeout, permission denied, a genuine bug. The loop does not need to know which; it needs the error to get back to the model and the process to continue.
3.4 Truncate output at the source
There is a silent problem that affects every agent that executes commands: a tool that returns an entire 200 KB log is paying for 200 KB in every subsequent step, forever. The cost is not that of one call; it is that of all future calls in that session.
Listing 3.3. Truncation at the source.
def run_shell(command: str) -> str:
p = subprocess.run(command, shell=True, capture_output=True,
text=True, timeout=30)
out = (p.stdout + p.stderr).strip()
return out[:2000] if out else f"(no output, exit={p.returncode})"
The 2000-character limit is arbitrary; what matters is that it exists. Good truncation says that it truncated — something like out[:2000] + "
n...[truncated]"1 — so that the model knows it is looking at a fragment and can ask for something more specific.
Common pitfall
Truncating on the harness side, after the tool has already produced the whole string. It works for the context, but not for memory: a tool that reads a 50 MB file still allocates 50 MB before you cut it. Truncating at the source — with
head, with a SQLlimit, with chunked reads — is the only approach that solves both.
3.5 Name, description and what the model does with them
A thought exercise is worthwhile. Suppose you have two tools:
-
search(text: str)— “searches” -
search_documents(query: str, limit: int = 5)— “Searches indexed documents by title and body. Returns up tolimitresults ordered by relevance. Does not search the web.”
The second is chosen with far more precision, even if the implementation is similar. Three reasons:
-
The name describes the domain.
search_documentssays what is being searched;searchsays nothing. -
The description delimits the scope. “Does not search the web” keeps the model from trying to use the tool for news.
-
The default is explicit.
limit=5in the schema reduces the chance of the model inventing a value.
3.6 A note on tools that return binary data
If the tool produces an image, audio or a PDF, the result cannot be plain text. Modern protocols (including MCP, in Chapter 7) support typed content blocks: text, image, resource. The rule of thumb is to return a reference instead of content whenever possible — the file path and a summary of what it contains — and to embed the binary only when the model actually needs to process it. A 10 MB PDF in the agent’s history is 10 MB resent at every step.
Footnotes
-
In
minted, the literal text inside the string appears as written; in the real tool, the sequence is the backslash followed byn. ↩