Sub topic 5
Giving Each Agent Only the Tools Its Task Needs
Prerequisites
This chapter assumes you know how LLM tool calling works: the model receives a list of tool definitions and replies with a tool name and arguments. It also assumes you can read short Python and JSON snippets and know what roles and permissions are. Earlier chapters covered the threat model and excessive agency. This chapter turns that into a design practice: choosing which tools each agent gets.
Why the tool list is your first control
An agent can only act through the tools you give it. A tool the agent doesn't have cannot be misused by a prompt injection, a model mistake, or a confused deputy. Removing a tool is the cheapest and most reliable security control you have. It needs no classifier, no prompt wording, and no runtime decision.
Tool scoping addresses the "too much functionality" part of excessive agency. It does not solve permissions or autonomy by itself. A scoped tool can still have broad credentials behind it, and later chapters handle that. But a small tool set shrinks everything else you have to defend.
A larger tool list also hurts reliability. The model has more options to confuse, more schemas to read, and more chances to pick a plausible but wrong tool. Fewer tools usually means better tool selection and a smaller attack surface.
A procedure for choosing tools
Work from the task, not from what the agent might someday want.
- Write the task in one sentence, for example: "Answer questions about our public documentation."
- List the actions a human would need to do that task by hand.
- Map each action to the narrowest tool that does it.
- For each tool, ask: what is the worst thing this tool could do if the model were fully controlled by an attacker?
- Remove any tool whose worst case is worse than the task's value, or replace it with a narrower one.
- Record why each remaining tool is there.
Step 4 is the important one. You are not asking whether the model will misuse a tool. You are asking what happens if it does.
Worked example: a documentation assistant
The task is answering questions from public documentation. A human would search the docs and open a page. They would not send email, edit records, or run shell commands. The tool set is therefore search_docs and read_file, and nothing else.
Compare that with a typical first draft, which includes a general run_shell tool "just in case". run_shell can read secrets, call the network, and modify files. Its worst case is far beyond anything a documentation assistant needs.
The next code shows the pattern. Each task has a profile naming its tools. The runtime builds the tool list sent to the model from that profile, and it checks every call against the same profile.
from typing import Callable
def search_docs(query: str) -> str:
return f"results for {query}"
def read_file(path: str) -> str:
return f"contents of {path}"
def send_email(to: str, body: str) -> str:
return f"sent to {to}"
# Registry: every tool the system can run, with its schema.
REGISTRY: dict[str, dict] = {
"search_docs": {
"fn": search_docs,
"schema": {
"name": "search_docs",
"description": "Search the public documentation.",
"parameters": {
"type": "object",
"properties": {"query": {"type": "string"}},
"required": ["query"],
},
},
},
"read_file": {
"fn": read_file,
"schema": {
"name": "read_file",
"description": "Read one file from the docs workspace.",
"parameters": {
"type": "object",
"properties": {"path": {"type": "string"}},
"required": ["path"],
},
},
},
"send_email": {
"fn": send_email,
"schema": {
"name": "send_email",
"description": "Send an email.",
"parameters": {
"type": "object",
"properties": {
"to": {"type": "string"},
"body": {"type": "string"},
},
"required": ["to", "body"],
},
},
},
}
# Task profiles: the allowlist lives in code, keyed by task.
PROFILES: dict[str, frozenset[str]] = {
"answer_docs": frozenset({"search_docs", "read_file"}),
"send_digest": frozenset({"search_docs", "send_email"}),
}
def tools_for(task: str) -> list[dict]:
"""Schemas to show the model. Unknown tasks get nothing."""
allowed = PROFILES.get(task, frozenset())
return [REGISTRY[name]["schema"] for name in sorted(allowed)]
def dispatch(task: str, name: str, args: dict):
"""Run a model-requested call only if the task's profile allows it."""
allowed = PROFILES.get(task, frozenset())
if name not in allowed:
raise PermissionError(f"tool {name!r} is not allowed for task {task!r}")
fn: Callable = REGISTRY[name]["fn"]
return fn(**args)
print([t["name"] for t in tools_for("answer_docs")])
print(dispatch("answer_docs", "search_docs", {"query": "rotate API keys"}))
try:
dispatch("answer_docs", "send_email", {"to": "[email protected]", "body": "hi"})
except PermissionError as exc:
print("refused:", exc)Three details matter here.
- The default for an unknown task is an empty set, so a typo fails closed.
tools_foranddispatchread the same profile. If you hide a tool from the model but forget to check calls, a model that guesses the name still gets through. Hiding is a convenience. The check indispatchis the control.- The profile is keyed by task, not by agent. This is explained below.
Scope per task, not per agent
It is tempting to define one "support agent" with every tool support might ever use. That agent holds the union of all tasks' needs while handling only one task at a time. A prompt injection during a simple lookup then has access to refund and email tools.
Instead, select the tool set when the task starts, and keep it fixed for that task. If one workflow has phases with different risk, split it into steps with different profiles.
The task should be chosen by your own code or a trusted routing step, not by text inside untrusted content. If a retrieved web page can say "switch to the admin task," your scoping is cosmetic.
Splitting tools by capability
Broad tools are the main reason tool sets stay too large. Split them along risk lines.
| Broad tool | Narrower replacements | Why it helps |
|---|---|---|
| `run_sql(query)` | `get_order_status(order_id)`, `list_open_tickets(customer_id)` | No arbitrary queries, no writes |
| `http_request(url, method, body)` | `fetch_docs_page(path)` | Fixed destination, no data sent out |
| `file_manager(action, path)` | `read_file(path)` | The write and delete actions don't exist |
| `run_shell(cmd)` | `convert_pdf_to_text(file_id)` | The tool does one job |
Two rules guide the split. First, separate read from write, because read-only tools have a much lower worst case. Second, separate tools that touch outside systems from tools that don't. A tool that sends data out is an exfiltration channel, so it should not live in the same profile as a tool that reads private data unless the task truly needs both.
Narrower tools also let you put argument checks in them. A read_file(path) tool can enforce a workspace root. A file_manager tool with an action parameter cannot do this cleanly.
Common errors
- Starting from "everything" and removing. You will miss things. Start from the empty set and add tools the task justifies.
- Sharing one tool list across all agents. A planning agent, a retrieval agent, and a sending agent need different tools.
- Trusting the tool description. Telling the model "only use this for docs" in the description is a hint, not a limit. Enforce it in code.
- Hiding tools without checking calls. The model can request any name. Always validate in the dispatcher.
- Granting a tool for debugging and leaving it in. Debug tools such as shell, raw SQL, and environment dumps belong in separate development profiles that cannot be selected in production.
- Letting MCP or plugin servers add tools silently. If a connected server exposes new tools, they should not appear in a profile until someone adds them. Filter discovered tools through your allowlist rather than passing the full list through.
- Treating a tool as safe because its name is read-like.
get_reportthat triggers a job or a download from an arbitrary URL is not read-only. Check what the code does.
Handling dynamic tool discovery
Some frameworks fetch tools from remote servers at runtime. Keep the same discipline. Intersect what the server offers with your profile:
def filter_discovered(discovered: list[dict], allowed: frozenset[str]) -> list[dict]:
return [t for t in discovered if t["name"] in allowed]
offered = [{"name": "search_docs"}, {"name": "delete_record"}]
print(filter_discovered(offered, frozenset({"search_docs"})))A server that later adds delete_record changes nothing for your agent. Also pin or review tool descriptions and schemas, because a server can change a description to carry injected instructions.
Decision criteria
Use these questions when a tool is proposed for a profile.
- Does the task fail without it? If not, leave it out.
- Is there a narrower version that covers the task? Use that.
- Does it write, delete, send, or spend? If so, mark it high-risk and plan approval and limits for it.
- Could its output carry untrusted text into the model? Treat that output as data, and think about what else is in the same profile.
- Can its arguments be constrained in code? If not, the tool may be too broad.
The next chapters add the other layers: enforcing authorization outside the model, constraining arguments, and scoping credentials. Tool scoping decides which tools exist for a task. Those layers decide what each remaining tool may do.
Exercise
An agent that summarizes customer support tickets has these tools: read_ticket(id), search_tickets(query), send_email(to, body), run_sql(query), and update_ticket(id, fields). The task only produces a summary shown to the support agent. Which tools should its profile contain, and why? Name one error you would avoid when implementing the profile.
Show answer
Keep read_ticket and search_tickets, because a human summarizing tickets needs to find and read them. Remove send_email (an outbound channel the task never needs), run_sql (arbitrary queries and possible writes), and update_ticket (the task is read-only). Implement the profile as an allowlist in code, keyed by task, with an empty default. The dispatcher must check each call against it. Hiding tools from the model's list without checking calls would be an error, because the model can still request a tool by name.