Agent Tools, Function Calling and Tool Registries
Tools turn a model that can only talk into an agent that can look things up and get things done, under your control.
A tool is a capability you describe to a model: a name, an explanation and the arguments it accepts. The model can ask for a tool to be used. Your code decides whether to run it, runs it and sends back the result. That request-and-result exchange is called tool calling or function calling.
What you will learn: what makes something a tool, how one call works message by message, how tool, function and API calls differ, how agents find and choose tools, and how to build a registry that many agents can share.
Prerequisites: What Is an AI Agent? Anatomy and Goals. Basic Python and JSON help with the examples.
What is a tool?
A language model reads text and writes text. It cannot, by itself, check today's stock level, send a message or add two long columns reliably. A tool closes that gap. You tell the model what exists, and the model replies with a structured request when it wants one used.
Imagine a new colleague on their first day with a list of services: "To find an order, give me the order number. To refund, give me the order number and amount, and expect me to ask a manager." The list is the tool definitions. The colleague does not get the database password. They get a controlled way to ask.
| Kind of tool | Examples | Typical risk |
|---|---|---|
| Retrieve information | Search documents, look up a record, read a calendar | Showing data the user may not see |
| Compute | Calculator, run a query, execute code in a sandbox | Unsafe code or very costly queries |
| Change something | Create a ticket, update a record, send an email | Wrong or repeated actions |
| Involve a person | Ask for approval, hand over a case | Unclear requests that waste time |
| Call another agent | Delegate research to a specialist | Lost context and compounding errors |
One tool call, step by step
1. The definition
Most model APIs accept a list of tools, each with a name, a description and a JSON Schema for the arguments. The exact field names differ by provider. This is the shape used by the Claude API:
{
"name": "get_order",
"description": "Look up one order by id. Returns status and total. Read only.",
"input_schema": {
"type": "object",
"properties": {
"order_id": {"type": "string", "description": "Order number, such as A17"}
},
"required": ["order_id"]
}
}
2. The model's request
Instead of a normal answer, the response says it stopped in order to use a tool, and includes a block like this:
{"type": "tool_use", "id": "toolu_01", "name": "get_order",
"input": {"order_id": "A17"}}
3. Your result
Your program runs the function and sends the outcome back, linked to the request by its id:
{"role": "user", "content": [
{"type": "tool_result", "tool_use_id": "toolu_01",
"content": "{\"status\": \"shipped\", \"total\": 42.5}"}
]}
When something fails, send a result that says so (this API has an is_error flag) with a message the model can act on. "Order A71 was not found; check the number with the customer" is useful. A raw stack trace is noise and may leak details. See the tool use documentation for the full protocol.
The arguments are model output. They can be wrong, invented or steered by hostile text the model read earlier. Validate them and check permission every time, exactly as you would for input from a web form.
Tool calling, function calling and API calling
The terms overlap, and people use them loosely. A useful way to separate them:
| Term | Who initiates | What it means |
|---|---|---|
| Function calling | Model requests, your code runs | The model returns a function name and arguments that match a schema you supplied |
| Tool calling | Model requests, your code or the provider runs | The wider idea: your functions, plus provider-hosted tools such as web search or code execution |
| API calling | Any program | Ordinary software sending a request to a service; no model needed |
| Protocol tool call | Model requests, a protocol client forwards | The tool lives on a separate server, for example through MCP |
A single tool call often wraps one or more API calls. Resist mapping every API endpoint to its own tool. Endpoints are designed for programmers who read documentation; tools should be designed for a model choosing among options in a few sentences. "Find the customer's open orders" is usually a better tool than three low-level endpoints the model has to stitch together. Design advice is in Designing Tool Schemas and Contracts.
When a tool is the wrong answer
If a step always happens, in the same order, with arguments you already know, call the function yourself in code and put the result in the context. You save a model round trip, remove a chance of error and make testing simpler. Offer a tool when the model's judgment is needed to decide whether to use it or what to pass.
Discovery, selection and ranking
With five tools, send them all. With two hundred, definitions fill the context window, cost money on every call and make similar tools hard to tell apart. You then need to narrow the list before the model sees it.
| Method | How it narrows | Strength | Weakness |
|---|---|---|---|
| Static sets | Each agent or workflow stage has a fixed list | Predictable and easy to test | Needs upkeep |
| Rules and tags | Match task category to tags | Transparent | Misses unusual wording |
| Semantic search | Compare the task with tool descriptions | Handles varied language | Can pick look-alikes |
| Search tool | The model first calls a "find tools" tool | Scales to large catalogs | Extra step and delay |
| Routing to specialists | Pick an agent, which owns a few tools | Clear ownership | Routing errors; more parts |
Start with static sets. Move to dynamic selection only when measurements show the model choosing badly or definitions costing too much. When you do, log which tools were offered as well as which was chosen. A wrong choice is often really a missing candidate.
Help the model choose
- Give each tool a verb-and-object name:
search_orders, notorders2. - Say what it does, when to use it, when not to, and what it returns.
- State side effects plainly: "Read only" or "Moves money".
- Make neighboring tools visibly different, or merge them.
- Use enumerations and required fields so wrong calls fail early.
Build a reusable tool registry
A registry is one place where tools are defined, together with the facts needed to govern them. Agents ask it what they may use, and calls pass through it. This compact version builds the schema from the function signature, filters by permission, ranks by tag overlap and validates arguments before running anything. It uses only the standard library.
"""A small tool registry: register, discover, rank, validate and dispatch."""
import inspect
import re
TYPES = {str: "string", int: "integer", float: "number", bool: "boolean"}
REGISTRY = {}
def tool(*, scope, risk, tags):
"""Register a function. The schema comes from its signature and docstring."""
def wrap(fn):
params = inspect.signature(fn).parameters
schema = {
"type": "object",
"properties": {n: {"type": TYPES[p.annotation]} for n, p in params.items()},
"required": [n for n, p in params.items() if p.default is p.empty],
"additionalProperties": False,
}
REGISTRY[fn.__name__] = {
"name": fn.__name__, "description": inspect.getdoc(fn),
"input_schema": schema, "scope": scope, "risk": risk,
"tags": set(tags), "run": fn,
}
return fn
return wrap
@tool(scope="orders:read", risk="low", tags=["order", "status", "delivery"])
def get_order(order_id: str):
"""Look up one order by id. Returns status and total. Read only."""
return {"order_id": order_id, "status": "shipped", "total": 42.5}
@tool(scope="orders:write", risk="high", tags=["refund", "money", "order"])
def refund_order(order_id: str, amount: float):
"""Refund money on an order. Changes records and moves money."""
return {"order_id": order_id, "refunded": amount}
@tool(scope="docs:read", risk="low", tags=["policy", "help", "refund", "returns"])
def search_policies(query: str, limit: int = 3):
"""Search published help and policy articles. Read only."""
return [{"title": "Returns policy", "query": query}][:limit]
def discover(task, scopes, limit=2):
"""Filter by permission first, then rank by overlap with the task."""
words = set(re.findall(r"[a-z]+", task.lower()))
allowed = [t for t in REGISTRY.values() if t["scope"] in scopes]
scored = sorted(allowed, key=lambda t: (-len(words & t["tags"]), t["name"]))
return [t for t in scored if words & t["tags"]][:limit]
def call(name, args, scopes):
spec = REGISTRY.get(name)
if spec is None or spec["scope"] not in scopes:
return {"error": f"tool {name!r} is not available"}
schema = spec["input_schema"]
missing = [k for k in schema["required"] if k not in args]
extra = [k for k in args if k not in schema["properties"]]
if missing or extra:
return {"error": f"missing {missing}, unexpected {extra}"}
for key, value in args.items():
want = schema["properties"][key]["type"]
ok = {"string": str, "integer": int, "number": (int, float), "boolean": bool}[want]
if not isinstance(value, ok) or (want != "boolean" and isinstance(value, bool)):
return {"error": f"{key} must be a {want}"}
return {"result": spec["run"](**args)}
if __name__ == "__main__":
reader = {"orders:read", "docs:read"}
agent = reader | {"orders:write"}
task = "Customer asks for a refund on an order that arrived late"
print("read-only user:", [t["name"] for t in discover(task, reader)])
print("refund agent: ", [t["name"] for t in discover(task, agent)])
print(call("get_order", {"order_id": "A17"}, reader))
print(call("refund_order", {"order_id": "A17", "amount": 5.0}, reader))
print(call("refund_order", {"order_id": "A17", "amount": "5"}, agent))
print(call("refund_order", {"order_id": "A17"}, agent))
Output:
read-only user: ['get_order', 'search_policies']
refund agent: ['refund_order', 'get_order']
{'result': {'order_id': 'A17', 'status': 'shipped', 'total': 42.5}}
{'error': "tool 'refund_order' is not available"}
{'error': 'amount must be a number'}
{'error': "missing ['amount'], unexpected []"}
Notice four behaviors. The read-only user is never even offered the refund tool. A direct attempt to call it is still refused, because offering and calling are checked separately. A text amount is rejected instead of silently converted. A missing argument produces a message precise enough for the model to correct itself.
Full JSON Schema validation, per-record authorization (may this user refund this order?), approval rules for risky tools, timeouts, idempotency keys, rate limits, audit records, versions and an owner for each tool. The permission scope shown here is only the first gate.
What to record for each tool
| Field | Why it matters |
|---|---|
| Name, description, input schema | What the model sees and what calls are checked against |
| Output shape and size limit | Keeps huge results from flooding the context |
| Owner and support contact | Someone answers when it breaks |
| Required permission and risk level | Drives access and approval decisions |
| Side effects and retry safety | Prevents duplicate actions after a timeout |
| Timeout and rate limit | Protects the service behind the tool |
| Version and status | Allows safe change and retirement |
| Test cases | Shows the tool and its description still work |
Between the request and the function
In production the "check and run" step grows into a small pipeline. Keeping it in one shared layer means every agent gets the same protections.
- Parse the request and reject unknown tools.
- Validate types, ranges, formats and unexpected fields.
- Authorize using the end user's identity and the specific record.
- Apply policy: limits, business hours, approval thresholds.
- Execute with a timeout, and an idempotency key for anything that changes state.
- Shape the result: return needed fields, trim long lists, remove secrets.
- Record who, what, when, outcome and duration.
Each step has its own page: Reliable Tool Execution and Error Recovery, Tool Permissions, Approvals and Abuse Risks and Tool Testing and Observability.
Results are context too
A tool that returns two thousand rows can cost more than every other part of a run and bury the facts that matter. Return the smallest useful answer: selected fields, a count, the first few matches and a way to ask for more. Mark the source and the time of the data. Remember that results containing text from outside your organization, such as web pages, emails or uploaded files, may carry instructions aimed at the model. Treat them as data and limit what the agent can do after reading them: see Prompt Injection Attacks and Defenses.
Changing tools without breaking agents
A description is part of your prompt. Editing one sentence can change which tool the model picks across many tasks. So treat tool changes like code changes: version them, review them and run an evaluation set that includes tasks where the right behavior is to call nothing. Adding a new optional argument is usually safe. Renaming a tool, changing units or changing what a field means is not. Run old and new versions side by side while callers move over.
What to measure
| Signal | What it tells you |
|---|---|
| Selection accuracy on test tasks | Whether descriptions are clear and distinct |
| Invalid-argument rate per tool | A confusing schema or missing guidance |
| Error and timeout rate | Health of the service behind the tool |
| Calls per completed task | Loops, or a tool that returns too little |
| Tokens in definitions and results | Where context and cost are going |
| Unused tools | Candidates for removal |
Worked example: choosing tools for a support agent
An illustrative team begins with fourteen endpoint-shaped tools and sees the agent fetch the wrong records. They redesign around the questions customers ask.
| Before | After | Reason |
|---|---|---|
| get_customer, list_orders, get_order, get_shipment | find_order_status | One question, one call, one compact answer |
| create_refund, update_ledger, notify_customer | request_refund | The service keeps the steps consistent; the agent cannot skip one |
| search_kb, search_faq, search_policy | search_help with a source filter | No guessing between look-alikes |
| A general run_sql tool | Removed | Too broad to authorize or test |
The lesson generalizes: fewer, task-shaped tools with narrow authority tend to be easier for the model and safer for you. Confirm it with your own measurements.
Ask a person to choose the right tool using only the names and descriptions the model sees. If they hesitate between two, the model has the same problem. Fix the wording before changing models.
Tool design checklist
- The name and description say what the tool does and when to use it
- Arguments are typed, constrained and validated in code
- Permission is checked for the user and the specific record
- Side effects are declared and safe against retries
- Errors tell the model what to do next
- Results are small, labeled and free of secrets
- The tool has an owner, a version and tests
- Agents are offered only the tools their task needs
Frequently asked questions
Does the model run my function?
With your own tools, no. The model returns a request and your application runs it. Some providers also offer hosted tools that run on their side; check each provider's documentation for what runs where.
How many tools can an agent have?
There is no single good number. Accuracy and cost depend on the model and on how distinct the tools are. Measure selection accuracy as you add them.
Is function calling the same as structured output?
Both ask the model to follow a schema. Structured output shapes the final answer; a function call asks your program to do something and expects a result.
Do I need MCP to use tools?
No. Define tools directly in your application. A protocol helps when several applications need to share the same integrations.
References and further reading
- Tool use with Claude (documentation)
- JSON Schema
- Model Context Protocol specification
- ReAct: Synergizing Reasoning and Acting in Language Models (paper)
Next steps
Designing Tool Schemas and Contracts
Write definitions that models use correctly.
Reliable Tool Execution and Error Recovery
Timeouts, retries and safe repeats.
What Is MCP? Hosts, Clients, Servers and Capabilities
Share tools across applications.