Simple definition#
Tool calling (also called function calling) lets an LLM ask your application to run a function. You describe the available tools; the model replies with “call get_order with {"orderId": "8812"}”; your code runs it and sends the result back; the model continues.
The mechanics#
sequenceDiagram
participant App as Application
participant LLM as LLM
participant API as Order API
App->>LLM: messages + tool definitions [get_order, refund_order]
LLM-->>App: tool_call: get_order({"orderId":"8812"})
App->>App: validate args, check user may read order 8812
App->>API: GET /orders/8812
API-->>App: {"status":"delivered","total":42.00}
App->>LLM: messages + tool_result(call_id, {...})
LLM-->>App: "Your order 8812 was delivered on 28 October."
- The app sends the conversation plus tool definitions.
- The model returns either text (done) or one or more tool calls with JSON arguments.
- The app executes the calls and appends tool results (with the call ID).
- The app calls the model again. Repeat until the model answers with text.
Frameworks such as Spring AI run this loop for you.
Defining a tool#
A tool definition has a name, a description and a JSON Schema for its parameters. The model chooses tools based almost entirely on the description.
{
"name": "get_order_status",
"description": "Get the current status, items and delivery estimate of a customer's order. Use when the customer asks where their order is or what it contains. Requires the order number, e.g. 'A-10293'.",
"input_schema": {
"type": "object",
"properties": {
"orderId": { "type": "string", "pattern": "^A-[0-9]{5}$", "description": "Order number, e.g. A-10293" }
},
"required": ["orderId"]
}
}
Designing good tools#
| Principle | Good | Bad |
|---|---|---|
| Clear purpose | search_policies(query, country) |
do_action(type, payload) |
| Describe when to use it | “Use when the customer asks about returns…” | “Policy tool” |
| Task-level, not API-level | schedule_meeting(attendees, duration, window) |
list_calendars, get_events, create_event exposed raw |
| Few, typed parameters | Enums, formats, required fields | Free-form strings for everything |
| Concise, relevant results | Return the fields the model needs | Dump a 5,000-token raw API response |
| Helpful errors | “Order not found. Order numbers look like A-12345.” | Stack trace or “error 500” |
| Idempotent writes | Accept an idempotency key | Double refunds on retry |
| Consistent naming | crm_get_contact, crm_update_contact |
Mixed styles |
Parallel and sequential calls#
flowchart LR
subgraph Parallel["Parallel — independent"]
Q1["'Weather in Paris and London?'"] --> P1["get_weather Paris"]
Q1 --> P2["get_weather London"]
end
subgraph Sequential["Sequential — dependent"]
Q2["'Refund my last order'"] --> S1["get_last_order"] --> S2["refund_order(id from S1)"]
end
Models can return several independent calls in one response; execute them concurrently to save time.
Controlling tool use#
- Tool choice:
auto(model decides),required/any(must call a tool), a specific tool (forced), ornone. - Return direct: some tools’ results go straight to the user without another model call (Spring AI’s
returnDirect). - Tool context: pass data such as tenant ID or user ID to the tool without exposing it to the model (Spring AI’s
ToolContext).
Error handling#
| Error | Handling |
|---|---|
| Invalid arguments | Validate against the schema; return a clear error so the model can correct itself |
| Business error (not found, not allowed) | Return a short, explanatory message, not an exception dump |
| Transient failure (timeout, 503) | Retry in the tool with backoff; after that, tell the model it failed |
| Repeated failure | Stop the loop after N attempts; escalate |
| Hallucinated tool or parameter | Reject and list valid options |
Security#
Tool calling is where an LLM’s mistakes or a prompt injection become real actions.
flowchart LR
TC["Tool call from LLM"] --> V["Validate schema<br/>and business rules"]
V --> AZ{"Authorised for<br/>THIS user?"}
AZ -->|"no"| DENY["Deny, tell model"]
AZ -->|"yes"| RISK{"Risky / irreversible?"}
RISK -->|"yes"| HITL["Ask human to approve"]
RISK -->|"no"| EXEC["Execute with<br/>user's scoped credentials"]
HITL -->|"approved"| EXEC
EXEC --> AUD["Audit log"]
AUD --> RES["Result to model<br/>treated as untrusted data"]
- Least privilege: the agent acts with the user’s permissions (delegated OAuth tokens), not a superuser service account.
- Authorise every call in the tool, using identity from the session — never from model-supplied arguments.
- Human approval for payments, deletions, external emails, permission changes.
- Tool results are untrusted — a web page or email returned by a tool can contain injected instructions.
- Rate limits and budgets per tool and per session.
- Audit every call: who, what, arguments, result.
See AI security for prompt injection and excessive agency.
Scaling to many tools#
Each tool definition consumes context tokens and makes selection harder. With dozens or hundreds of tools:
- Group tools into specialised agents (see multi-agent systems).
- Tool search / dynamic loading: retrieve only the relevant tool definitions for each request (like RAG over tools).
- Consolidate fine-grained API calls into task-level tools.
- Expose tools through MCP so they are reusable across agents and applications.
Common mistakes#
Review questions#
How does function calling work? The application sends tool definitions (name, description, JSON Schema) with the prompt. The model may respond with a structured tool call. The application validates and executes it, sends back the result, and the model continues until it produces a final answer. The model never executes code itself.
What makes a good tool definition? A clear, specific name; a description of what it does and when to use it; a minimal, typed schema with formats and enums; compact, relevant results; helpful error messages; idempotent writes.
How do you secure tool calls? Validate arguments, authorise each call against the authenticated user (not model-supplied identity), use least-privilege delegated credentials, require human approval for risky actions, treat tool outputs as untrusted, rate-limit, and audit everything.
What do you do when an agent has too many tools? Consolidate into task-level tools, load tool definitions dynamically by relevance, or split into specialised sub-agents, each with a small tool set.
What is the difference between tool calling and MCP? Tool calling is the model capability to request a function call. MCP is a protocol that standardises how applications discover and invoke tools (and resources and prompts) provided by external servers, so tools can be reused across clients.
Summary#
- The LLM proposes tool calls; the application validates, authorises and executes them.
- Tool definitions are prompts: clear names, descriptions, schemas and results.
- Run independent calls in parallel; bound loops; return helpful errors.
- Security: least privilege, per-call authorisation, human approval for risky actions, audit.
References#
- Anthropic, Tool use with Claude.
- OpenAI, Function calling.
- Anthropic, Writing effective tools for agents, 2025.