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.

BeginnerIntermediateExpert · 13 min read · Last updated:

In short

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.

Beginner What a tool is and how a call works

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 toolExamplesTypical risk
Retrieve informationSearch documents, look up a record, read a calendarShowing data the user may not see
ComputeCalculator, run a query, execute code in a sandboxUnsafe code or very costly queries
Change somethingCreate a ticket, update a record, send an emailWrong or repeated actions
Involve a personAsk for approval, hand over a caseUnclear requests that waste time
Call another agentDelegate research to a specialistLost context and compounding errors

One tool call, step by step

DescribeApp sends the request plus tool definitions
RequestModel names a tool and arguments
CheckApp validates and authorizes
RunApp executes the real function
ReturnResult goes back; model continues
↺ The model may request more tools before it gives a final answer
The model never touches your systems. Everything passes through your code.

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.

A request is not a command

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:

TermWho initiatesWhat it means
Function callingModel requests, your code runsThe model returns a function name and arguments that match a schema you supplied
Tool callingModel requests, your code or the provider runsThe wider idea: your functions, plus provider-hosted tools such as web search or code execution
API callingAny programOrdinary software sending a request to a service; no model needed
Protocol tool callModel requests, a protocol client forwardsThe 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.

Intermediate Finding and choosing tools well

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.

All registered toolsEverything the organization offers
Permission filterOnly what this user and agent may use
Relevance rankingTags, keywords or embeddings against the task
Short listA handful of clearly different options
Model choicePicks a tool, or answers without one
Order matters: filter by permission first, so ranking never surfaces a forbidden tool.
MethodHow it narrowsStrengthWeakness
Static setsEach agent or workflow stage has a fixed listPredictable and easy to testNeeds upkeep
Rules and tagsMatch task category to tagsTransparentMisses unusual wording
Semantic searchCompare the task with tool descriptionsHandles varied languageCan pick look-alikes
Search toolThe model first calls a "find tools" toolScales to large catalogsExtra step and delay
Routing to specialistsPick an agent, which owns a few toolsClear ownershipRouting 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, not orders2.
  • 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.

What a real registry adds

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

FieldWhy it matters
Name, description, input schemaWhat the model sees and what calls are checked against
Output shape and size limitKeeps huge results from flooding the context
Owner and support contactSomeone answers when it breaks
Required permission and risk levelDrives access and approval decisions
Side effects and retry safetyPrevents duplicate actions after a timeout
Timeout and rate limitProtects the service behind the tool
Version and statusAllows safe change and retirement
Test casesShows the tool and its description still work
Expert Running tools at scale

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.

  1. Parse the request and reject unknown tools.
  2. Validate types, ranges, formats and unexpected fields.
  3. Authorize using the end user's identity and the specific record.
  4. Apply policy: limits, business hours, approval thresholds.
  5. Execute with a timeout, and an idempotency key for anything that changes state.
  6. Shape the result: return needed fields, trim long lists, remove secrets.
  7. 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

SignalWhat it tells you
Selection accuracy on test tasksWhether descriptions are clear and distinct
Invalid-argument rate per toolA confusing schema or missing guidance
Error and timeout rateHealth of the service behind the tool
Calls per completed taskLoops, or a tool that returns too little
Tokens in definitions and resultsWhere context and cost are going
Unused toolsCandidates 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.

BeforeAfterReason
get_customer, list_orders, get_order, get_shipmentfind_order_statusOne question, one call, one compact answer
create_refund, update_ledger, notify_customerrequest_refundThe service keeps the steps consistent; the agent cannot skip one
search_kb, search_faq, search_policysearch_help with a source filterNo guessing between look-alikes
A general run_sql toolRemovedToo 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.

Expert tip

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

Next steps