Skip to content
A glowing lime central node connected by thin lines to smaller nodes on a dark background.
AI Agents

Your Agent Is Only as Safe as Its Tools

By Faraz ShahOct 15, 20264 min read

The model decides what to do. The tools are what actually does it. That makes the tool layer the real boundary of an agent, and it deserves the same care you'd give a public API, because that's what it is: an interface called by something you don't fully control.

I've built this layer for Clerify, an immigration-law platform, for TradeDojo, a trading coach, and in a smaller open-source form in agentic-rag-evals. The same few rules came up every time.

Treat model output like user input

Tool arguments come from a language model. They can be missing, malformed or plausible and wrong. So every tool declares a Pydantic model, its JSON schema is what the LLM sees, and the same model validates the arguments before anything runs.

python
class SearchArgs(BaseModel): query: str = Field(min_length=2) k: int = Field(default=3, ge=1, le=8) @dataclass class Tool: name: str description: str args_model: type[BaseModel] run: Callable[[BaseModel], dict[str, Any]] def schema(self) -> dict[str, Any]: return { "type": "function", "function": { "name": self.name, "description": self.description, "parameters": self.args_model.model_json_schema(), }, }

One class defines both the contract and the check, so they can't drift apart. Notice the limit on k as well. Bounds in the schema stop the model asking for a thousand results, and they cost one line.

Return errors to the model

When validation fails, don't raise. Return the error as the tool result. The model can read "k must be at most 8", correct itself and try again, which is often all the recovery you need. An exception ends the run and shows the user a failure for something the agent could have fixed.

Never let the model name the user

This is the rule I'd put first if I could only keep one. If a tool takes a user_id argument, the model chooses that value, and the model can be talked into choosing someone else's. Prompt injection then becomes a data leak.

In TradeDojo, the trader's id comes from agent state and never from tool arguments, so the model can't read another user's data even if it tries. The schema it sees has no such field. It isn't a rule the model is asked to follow. The capability doesn't exist.

python
# Risky: the model picks whose data to read def get_trades(user_id: str, limit: int): ... # Safer: identity comes from the server-side session def get_trades(state: AgentState, limit: int): return load_trades(state["user_id"], limit)
Don't ask the model to respect a boundary. Remove the argument that would let it cross one.

Build tools that can't do the dangerous thing

The calculator in agentic-rag-evals is a small example. Calling eval() on model output would be remote code execution with extra steps. Instead it walks the parsed syntax tree and accepts only numbers and arithmetic operators, so names, calls and attribute access are rejected by construction.

Clerify's filing agent applies the same idea at a larger scale. It drives a real browser on a government portal, so it has a navigation allow-list, a 60-step cap, cancellation, and a step log with token usage and run time. Those limits live in code, around the agent, where a clever prompt can't argue with them.

Cap every loop

An agent loop without a limit is a billing incident waiting to happen. Give it a hard maximum and a clear way out:

python
for _ in range(self.max_steps): msg = self.llm.complete(messages, self.tools.schemas()) if not msg.tool_calls: yield Step(kind="final", detail={"content": msg.content or ""}) return ... # run tools, append results yield Step( kind="final", detail={ "content": "I could not finish within the step limit.", "truncated": True, }, )

The user gets an honest answer instead of a spinner, and the truncated flag lets you count how often it happens.

Check citations after the model writes them

Models will happily cite a source that sounds right. So citations get filtered against what the tools really returned, and anything else is dropped:

python
citations = [ c for c in dict.fromkeys(_CITE.findall(final)) if c in retrieved ]

Keep tools plain, and let the registry do the rest

As tool counts grow, hand-kept lists stop working. In Clerify, one decorator registers each tool along with its UI widget tier and whether it needs confirmation. That covers 35 tools with no list to maintain, and the chat interface knows how to render each call and when to ask first.

Each tool there is a plain function with a thin agent wrapper, so the same code serves chat, voice and tests. That's what I'd copy first. Write the function as normal business logic, test it like normal business logic, and keep the agent-specific part as small as you can.

A checklist for your next tool

Are the arguments validated with bounds? Do errors go back to the model? Does identity come from the session and not from an argument? Is the worst case limited in code? Is there a step cap on the loop that calls it? Can you see afterwards what it did? If the answer to all six is yes, you can give the model far more freedom, because you no longer depend on it behaving well.

Keep reading

Related posts.

A stream of lime particles pausing at a thin glowing gate on a dark background.
AI Agents

5 min read

Agents That Know When to Stop and Ask

Some actions shouldn't happen without a person. How to pause an agent mid-run, wait as long as it takes, and resume from any worker, using LangGraph interrupts and checkpoints.

Read post
Rows of glowing lime dots on a dark background, with one dot left unlit below a threshold line.
RAG

6 min read

Your RAG Demo Needs a Failing Test

A new chunk size or prompt can quietly make answers worse, and nothing turns red. Here's how to make answer quality a merge check, with the harness from my open-source agent.

Read post