Tool calling: how LLM function calling works in production
Tool calling lets a model ask your code to run a function and send back the result. How the loop works, how to control it, and where the risk sits.
- Published
- Reading time
- 10 min read
In short
- Tool calling is a loop: the model returns a structured request to run a function, your code runs it, and you send the result back for the next turn.
- The model never executes anything. It proposes a tool name and arguments, and your code decides whether the call happens.
- Use strict schemas to stop malformed arguments, tool_choice to force or forbid a call, and an error result instead of an exception when a tool fails.
- Keep the tool list short. OpenAI suggests fewer than 20 functions per turn, and every definition is input you pay for on every request.
Tool calling, also called function calling, is the API feature that lets a model ask your application to run a function. You describe each tool with a name, a description, and a JSON Schema for its arguments. When the model decides a tool would help, it replies with a call instead of an answer. Your code runs the function, sends the result back, and the model continues.
Every agent is built on this loop. MCP standardizes how an application discovers tools from other systems. Tool calling is how the model asks to use one. The two are separate layers, and the security questions in this article apply whichever way the tools arrive.
How the tool calling loop works
The tool calling loop has five steps: send the request with tool definitions, receive a tool call, run the tool in your code, send the result back, and receive either a final answer or another tool call. It repeats until the model answers in text.
OpenAI's function calling guide lists those five steps, and every major provider follows the same shape with different field names.
- On the Claude API, a response that wants a tool ends with
stop_reason: "tool_use"and carries one or moretool_useblocks. Each has anid, aname, and aninputobject that matches the tool's schema. - On OpenAI's Responses API, the call arrives as a
function_callitem with acall_id. - Your reply references that identifier. Claude expects a
tool_resultblock with the matchingtool_use_id. OpenAI expects afunction_call_outputitem with the matchingcall_id.
The provider does not keep the loop's state for you. Each request carries the full conversation, including every earlier call and result. That is why tool-heavy agents get expensive: the history grows with each turn, and you pay for all of it again on the next one.
Defining a tool the model will use correctly
A tool definition has three parts: a name, a plain-language description, and a JSON Schema for the input. The description matters most, because it is the only thing the model reads when deciding whether this tool fits the request.
Anthropic's guidance calls detailed descriptions "by far the most important factor in tool performance" and suggests at least three or four sentences per tool. Say what the tool does, when to use it, when not to, and what it does not return. OpenAI calls the schema field parameters. Claude calls it input_schema. The content is the same JSON Schema.
Here is the loop with one read-only tool, written against the Claude API.
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
const tools: Anthropic.Tool[] = [
{
name: "get_order_status",
description:
"Look up the shipping status of one order by its ID. Read-only. " +
"Use it when the user asks where an order is. " +
"Returns status and carrier. Does not return payment details.",
input_schema: {
type: "object",
properties: {
order_id: { type: "string", description: "Order ID, for example A-10422" },
},
required: ["order_id"],
},
},
];
const messages: Anthropic.MessageParam[] = [
{ role: "user", content: "Where is order A-10422?" },
];
// Cap the loop. A model that keeps calling tools is a bug, not a feature.
for (let turn = 0; turn < 8; turn++) {
const response = await client.messages.create({
model: "claude-sonnet-5-5",
max_tokens: 1024,
tools,
messages,
});
messages.push({ role: "assistant", content: response.content });
if (response.stop_reason !== "tool_use") break;
const results: Anthropic.ToolResultBlockParam[] = [];
for (const block of response.content) {
if (block.type !== "tool_use") continue;
try {
// Your code, your permission checks. The model only proposed this call.
const output = await runTool(block.name, block.input);
results.push({ type: "tool_result", tool_use_id: block.id, content: JSON.stringify(output) });
} catch (err) {
results.push({ type: "tool_result", tool_use_id: block.id, content: String(err), is_error: true });
}
}
messages.push({ role: "user", content: results });
}Two details in that code are deliberate. The loop has a turn limit, and a failed tool becomes an error result instead of an exception that kills the request.
Parallel tool calls
A model can request several tool calls in a single turn when the calls do not depend on each other. You run them, then return every result together in the next message. Both OpenAI and Anthropic allow this by default and let you turn it off.
On OpenAI, setting parallel_tool_calls to false "ensures exactly zero or one tool is called." On Claude, the same switch is disable_parallel_tool_use inside tool_choice.
The ordering rules are strict on Claude. Tool results must immediately follow the assistant message that requested them, and in the reply, every tool_result block must come before any text. Break either rule and the request fails with a 400.
Keep parallel calls on for reads, such as fetching three records at once. Turn them off when one call's output should decide the next call, or when two calls write to the same thing. Parallel writes are where an agent creates a duplicate ticket or charges a card twice.
Forcing or forbidding a call with tool_choice
The tool_choice parameter controls whether the model may call a tool, must call one, must call a specific one, or must not call any. The default lets the model decide. The other settings exist for pipelines where a tool call is the whole point.
| Intent | OpenAI | Claude |
|---|---|---|
| Model decides (default) | "auto" | { "type": "auto" } |
| Must call some tool | "required" | { "type": "any" } |
| Must call this tool | { "type": "function", "name": "..." } | { "type": "tool", "name": "..." } |
| Must not call a tool | "none" | { "type": "none" } |
| Limit to a subset | Allowed tools | No tool_choice option; send fewer tools |
Forcing has side effects that are easy to miss. On Claude, a forced call skips thinking and produces no text before the tool_use block. Several current Claude models, including Claude Opus 5.5 and Claude Sonnet 5.5, reject forced tool use with a 400 error; Anthropic's suggested replacement is auto combined with strict schemas. Changing tool_choice between requests also invalidates cached message blocks, which matters if you depend on prompt caching.
Use forcing for extraction jobs where the output must land in one schema. For conversational agents, leave it on auto and steer with the system prompt.
Strict schemas stop malformed arguments
Strict mode makes the provider guarantee that tool arguments match your schema exactly, instead of matching it most of the time. Turn it on for every tool that writes or that feeds code expecting a fixed shape.
On OpenAI, strict: true comes with requirements: additionalProperties must be false on every object, and every field in properties must be listed as required. An optional field becomes a required field that accepts null. A schema that breaks these rules is rejected. On Claude, strict: true on a tool definition guarantees the input matches the schema, which removes missing parameters and type mismatches. Structured outputs covers the same grammar for final answers, and where it still fails.
Strict mode validates shape, not meaning. It guarantees that order_id is a string. It does not guarantee the order exists, or that the person in the conversation is allowed to see it. Those checks stay in your code.
What to return when a tool fails
When a tool fails, return the failure to the model as a result, not as an exception in your own process. The model can then retry with corrected arguments, try a different tool, or tell the user what went wrong.
On Claude, set is_error: true on the tool_result and put the message in content. Anthropic's docs recommend instructive errors over generic ones: "Rate limit exceeded. Retry after 60 seconds." gives the model something to act on, and "failed" does not. They also note that when a call is invalid, Claude will typically retry two or three times with corrections before apologizing to the user.
OpenAI's guide leaves the format to you. The output is usually a string, and for a function with no return value it suggests returning something like "success".
Write error messages for the model the way you would write them for a junior engineer on call: what happened, whether retrying helps, and what to try instead. Do not include stack traces or internal hostnames. Whatever you return goes into the context and may be shown to the user.
How many tools a model can handle
Selection accuracy and cost both get worse as the tool list grows. OpenAI's guide says to aim for "fewer than 20 functions available at the start of a turn at any one time," and calls that a soft suggestion. Treat it as a budget you have to justify exceeding.
Every definition is sent as input on every request. Claude also adds a tool-use system prompt whenever tools are present, a few hundred tokens depending on the model. Ten verbose tools can cost more than the user's question. A long list also invites the failure described in the context rot article: the model has more ways to pick the wrong tool.
Three ways to keep the list short:
- Consolidate. Anthropic suggests grouping related operations into one tool with an
actionparameter instead of separatecreate_pr,review_pr, andmerge_prtools. - Namespace. Prefix names by service, such as
github_list_prsandslack_send_message, so similar tools from different systems stay distinct. - Load tools on demand. Claude's tool search tool and the tool filtering in an MCP gateway both keep most definitions out of the prompt until a task needs them. Context engineering covers the general version of this problem.
Public benchmarks help you shortlist models. The Berkeley Function Calling Leaderboard, now at version 4, measures how accurately models call functions, including multi-turn and agentic tasks. Your own tools, with your own descriptions, are still the test that decides.
Where the risk sits in agent tool calling
The model chooses the arguments, and your code decides whether to act on them. Treat every tool call as a request from an untrusted client, because the text that shaped it may have come from a web page, an email, or another tool's output.
Anthropic's tool docs say this directly: tool results often carry content from sources outside your control, and an attacker who can influence that content can try to redirect the model. That is indirect prompt injection, and tool calling is where it turns from bad text into a bad action.
The controls that matter:
- Authorize each call as the end user. Check the user's permissions, not the agent's service account, before the tool touches data.
- Validate business rules in the tool. Amount limits, allowed recipients, and ownership checks belong in code the model cannot rewrite.
- Require confirmation for anything that writes, sends, pays, or deletes. Reads can run unattended.
- Record every call with its arguments, result, and the user it ran for. What to record on every request lists the fields, and agent observability covers tracing a whole run.
Infrastructure that sits in the loop should follow the same rule. Bifrost, an open-source AI gateway by Maxim AI that can also act as an MCP gateway, returns tool calls to your application by default instead of executing them. Its Agent Mode runs tools automatically only when they are on an explicit auto-execute list. That default is the right one for any layer between a model and your systems.
Frequently asked questions
What is the difference between tool calling and function calling?
They describe the same mechanism. OpenAI uses "function calling" and treats a function as one type of tool. Anthropic uses "tool use." "Tool calling" has become the umbrella term, covering functions you define, tools the provider runs for you such as web search, and tools exposed through MCP servers. In every case the model returns a structured request and something outside the model runs it.
Does the model execute the function itself?
No. The model only produces a tool name and arguments. Your application runs client tools and sends back the result. Some providers also offer server tools, such as Anthropic's web search and code execution, which run on the provider's infrastructure. Even then the model is not executing code itself; a system around it is, under rules that system enforces.
How do I force a model to call a specific tool?
Set tool_choice to name the tool: {"type": "function", "name": "..."} on OpenAI or {"type": "tool", "name": "..."} on Claude. Check model support first. Several current Claude models reject forced tool use with a 400 error, and Anthropic recommends auto with strict schemas instead. Forcing also suppresses any explanation text before the call.
Can a model call several tools at once?
Yes. Models can return several independent tool calls in one turn, and you return all the results together in the next message. Both OpenAI and Anthropic allow this by default. Disable it with parallel_tool_calls: false on OpenAI or disable_parallel_tool_use: true on Claude when calls depend on each other or write to shared state.
How many tools can I give a model?
There is no hard limit worth planning around, but accuracy and cost both degrade as the list grows. OpenAI suggests fewer than 20 functions available at the start of a turn. Above that, consolidate related operations, filter tools per task, or load definitions on demand through a tool search feature or a gateway, so the model sees only what the current task needs.
What should a tool return when it fails?
Return an error result, not an exception. On Claude, set is_error: true on the tool_result and explain what went wrong and what to try next, such as when to retry. The model can then correct its arguments or tell the user. Keep stack traces and internal details out, because the message enters the context and may reach the user.