AS·168
Tool Calling
Letting a model act through your code safely: how tool (function) calling works as a message protocol, writing function schemas models use well (names, descriptions, parameter types, enums, examples), the tool-use loop with parallel calls, tool discovery and dynamic tool selection for large toolsets, authorization as a server-side concern (the model is never the principal, scopes, confirmation for side effects, confused-deputy risks), argument validation and normalisation, execution with timeouts, cancellation and sandboxing, retries with idempotency keys and backoff, error handling that the model can act on, result shaping and size limits, observability, a complete runnable tool executor in Python, and the same patterns in Java (Spring AI), TypeScript, Go and Rust.
Start here: letting a model ask your code to act
A model can only produce text. Tool calling lets it produce a request instead: "call refund_order with these arguments". Your code decides whether to run it, runs it, and hands the result back so the model can continue.
The loop
- You send the conversation plus a list of tools, each with a name, a description and a JSON Schema for its arguments.
- The model replies either with text, or with a tool call:
{"name": "refund_order", "input": {"order_id": "A101", "amount": 450, "reason": "late"}}. - Your code validates the call, checks permissions, runs the function with a timeout, and returns the result (or a helpful error).
- The model reads the result and either calls another tool or answers the user.
The crucial point: the model proposes; your code disposes. Treat every tool call like input from an untrusted user.
What can go wrong, measured
The lab sent ten realistic tool calls (the kinds of mistakes models make, from a scripted stand-in, since no capable model runs here) to a refund tool, first with the arguments passed straight to the function, then through a defended harness:
| Call | No defences | Defended harness |
|---|---|---|
amount sent as "200" (a string) |
crash | rejected with a clear message |
reason invented ("customer_angry") |
refund issued | rejected: not an allowed value |
| another customer's order | refund issued | rejected: not authorised |
| ₹1,500, over the approval limit | error (by luck) | sent for human approval |
| timeout, then the model retries | refunded twice | refunded once (idempotency key) |
Without defences, three refunds that shouldn't have happened went through. With schema validation, authorisation from your own records (never from the model), approval thresholds and idempotency keys, none did.
How deep to go in tool calling
Volume 17 defines six mastery levels; for tool calling they look like this:
| Level | You can… |
|---|---|
| L1 | explain the tool-use loop and why the model never executes anything itself |
| L2 | define tools and run the loop with a model API |
| L3 | design schemas, error messages and results that models use well |
| L4 | debug wrong tool choice, bad arguments, loops and timeouts from traces |
| L5 | design authorisation, approvals, idempotency and sandboxing for a tool suite |
| L6 | operate tool platforms across teams with registries, audits and per-tool SLOs |
What tool calling is
A model can only emit tokens. Tool calling (function calling) is a protocol in which:
- The application sends the model a list of tools: name, description and a JSON Schema for parameters.
- The model, instead of (or before) answering, emits a tool call: a structured request with a tool name and JSON arguments.
- The application (not the model) validates and executes the call, and sends the result back as a tool-result message.
- The model continues: answers, or calls more tools.
The model never executes anything. Your code decides what runs, with what permissions. That separation is the foundation of tool safety.
Providers expose this with slightly different message shapes (tool_use / tool_result content blocks, tool_calls with ids, function-call parts), but the concepts are identical; frameworks and gateways normalise them.
Function schemas that models use well
The tool definition is a prompt: the model decides when and how to call a tool from its name, description and parameter schema.
{
"name": "search_orders",
"description": "Search the current customer's orders. Use when the user asks about an order's status, delivery or contents. Returns at most 10 orders, newest first. Does not return payment details.",
"input_schema": {
"type": "object",
"properties": {
"order_id": {"type": "string", "description": "Exact order id like 'A17' if the user gave one"},
"status": {"type": "string", "enum": ["pending", "shipped", "delivered", "cancelled", "any"],
"description": "Filter by status; use 'any' if not specified"},
"placed_after": {"type": "string", "format": "date", "description": "ISO date; only if the user mentions a time range"}
},
"required": ["status"],
"additionalProperties": false
}
}
Guidelines:
- Names: verb_noun, specific (
search_orders,create_refund), consistent across tools; avoid near-duplicates the model will confuse. - Descriptions: what it does, when to use it and when not to, what it returns, limits and side effects. This is usually the highest-leverage text for tool accuracy.
- Parameters: precise types, enums for closed sets, formats and units in descriptions, few required fields, sensible defaults handled in code.
- Coarse-grained, task-shaped tools beat thin wrappers over every REST endpoint:
get_customer_overview(customer_id)returning the relevant joined view is better than making the model chain five low-level calls. - Few tools in context: dozens of overlapping tools degrade selection; group, prune, or discover dynamically (below).
- Examples: some APIs accept input examples; otherwise include a short example in the description for tricky formats.
- Strict mode: providers can enforce that arguments match the schema (chapter 167); still validate.
The tool-use loop
import json, time, uuid
from typing import Callable, Literal
from pydantic import BaseModel, Field, ValidationError
class Tool:
def __init__(self, name: str, description: str, args_model: type[BaseModel], fn: Callable,
scopes: set[str], side_effects: bool = False, timeout_s: float = 5.0, idempotent: bool = True):
self.name, self.description, self.args_model, self.fn = name, description, args_model, fn
self.scopes, self.side_effects, self.timeout_s, self.idempotent = scopes, side_effects, timeout_s, idempotent
def schema(self):
return {"name": self.name, "description": self.description,
"input_schema": self.args_model.model_json_schema()}
class SearchOrders(BaseModel):
status: Literal["pending", "shipped", "delivered", "cancelled", "any"] = "any"
order_id: str | None = Field(default=None, pattern=r"^[A-Z]\d{1,6}$")
class CreateRefund(BaseModel):
order_id: str = Field(pattern=r"^[A-Z]\d{1,6}$")
amount_minor: int = Field(gt=0, le=5_000_000)
reason: str = Field(min_length=3, max_length=200)
ORDERS = {"A17": {"customer": "c42", "status": "shipped", "total_minor": 249900, "eta": "2026-10-27"},
"B03": {"customer": "c99", "status": "pending", "total_minor": 99900}}
def search_orders(ctx, args: SearchOrders):
rows = [dict(id=k, **{f: v for f, v in o.items() if f != "customer"})
for k, o in ORDERS.items() if o["customer"] == ctx["customer_id"]] # tenant scoping in code
if args.order_id: rows = [r for r in rows if r["id"] == args.order_id]
if args.status != "any": rows = [r for r in rows if r["status"] == args.status]
return rows[:10]
def create_refund(ctx, args: CreateRefund):
order = ORDERS.get(args.order_id)
if not order or order["customer"] != ctx["customer_id"]:
raise PermissionError("order not found for this customer") # don't reveal other tenants' data
if args.amount_minor > order["total_minor"]:
raise ValueError(f"amount exceeds order total {order['total_minor']}")
return {"refund_id": f"R-{uuid.uuid4().hex[:8]}", "status": "submitted"}
TOOLS = {t.name: t for t in [
Tool("search_orders", "Search the current customer's orders by id or status.", SearchOrders, search_orders,
scopes={"orders:read"}),
Tool("create_refund", "Submit a refund request for one of the customer's orders. Requires user confirmation.",
CreateRefund, create_refund, scopes={"refunds:write"}, side_effects=True, idempotent=False),
]}
The executor is where validation, authorisation, confirmation, timeouts, retries and auditing live:
import concurrent.futures as cf
POOL = cf.ThreadPoolExecutor(max_workers=8)
AUDIT = []
class ToolError(Exception):
def __init__(self, code, message, retryable=False):
super().__init__(message); self.code, self.retryable = code, retryable
def execute_tool_call(call, ctx, confirm: Callable[[str, dict], bool]):
"""call = {"id", "name", "input"}; ctx = authenticated user context (never from the model)."""
started = time.monotonic()
tool = TOOLS.get(call["name"])
try:
if tool is None:
raise ToolError("unknown_tool", f"No tool named {call['name']}. Available: {sorted(TOOLS)}")
if not tool.scopes <= ctx["scopes"]: # authorisation
raise ToolError("forbidden", f"The user is not allowed to use {tool.name}.")
try:
args = tool.args_model.model_validate(call["input"]) # argument validation
except ValidationError as e:
raise ToolError("invalid_arguments", e.json(include_url=False)[:600])
if tool.side_effects and not confirm(tool.name, args.model_dump()): # human approval
raise ToolError("declined", "The user declined this action. Ask how they'd like to proceed.")
future = POOL.submit(tool.fn, ctx, args)
try:
result = future.result(timeout=tool.timeout_s) # timeout
except cf.TimeoutError:
future.cancel()
raise ToolError("timeout", f"{tool.name} timed out after {tool.timeout_s}s", retryable=tool.idempotent)
except PermissionError as e:
raise ToolError("not_found", str(e))
except ValueError as e:
raise ToolError("rejected", str(e))
content, is_error = json.dumps(result, default=str)[:8000], False # cap result size
except ToolError as e:
content, is_error = json.dumps({"error": e.code, "message": str(e), "retryable": e.retryable}), True
AUDIT.append({"tool": call["name"], "user": ctx["user_id"], "input": call["input"], "error": is_error,
"ms": round(1000 * (time.monotonic() - started))})
return {"type": "tool_result", "tool_use_id": call["id"], "content": content, "is_error": is_error}
def run_agent_turn(llm, messages, ctx, confirm, max_steps=6):
"""Generic loop: call the model; execute any tool calls; feed results back; stop on a final answer."""
tools = [t.schema() for t in TOOLS.values()]
for _ in range(max_steps):
reply = llm(messages, tools) # {"text": ..., "tool_calls": [...]}
messages.append({"role": "assistant", "content": reply})
if not reply.get("tool_calls"):
return reply["text"]
results = [execute_tool_call(c, ctx, confirm) for c in reply["tool_calls"]] # could run in parallel
messages.append({"role": "user", "content": results})
return "I couldn't finish this within the step limit; here's what I found so far."
A scripted fake model shows the flow, including a validation error the model recovers from:
script = iter([
{"text": "", "tool_calls": [{"id": "t1", "name": "search_orders", "input": {"order_id": "a17"}}]}, # bad id format
{"text": "", "tool_calls": [{"id": "t2", "name": "search_orders", "input": {"order_id": "A17"}}]}, # corrected
{"text": "Order A17 has shipped and should arrive on 27 October.", "tool_calls": []},
])
fake_llm = lambda messages, tools: next(script)
ctx = {"user_id": "u1", "customer_id": "c42", "scopes": {"orders:read"}}
answer = run_agent_turn(fake_llm, [{"role": "user", "content": "Where's my order A17?"}], ctx, confirm=lambda n, a: False)
answer, [a["error"] for a in AUDIT] # final answer; audit shows one failed then one successful call
Tool discovery
Static tool lists work for a handful of tools. Larger systems need discovery:
- Per-request tool selection: include only tools relevant to the current task (route by intent, user role or product area).
- Tool search: give the model a
search_tools(query)meta-tool over a catalogue (embedding search over tool descriptions), returning full definitions only for matches; keeps context small with hundreds of tools. - Protocol-based discovery: MCP servers advertise their tools, resources and prompts to clients at runtime (chapter 172).
- Versioning: tool names and schemas are an API: version them, deprecate gracefully, and evaluate tool-selection accuracy when you change descriptions.
Authorisation
The most important rule: the model is never the principal. Every tool call executes on behalf of an authenticated user (or service) with that principal's permissions, enforced in your code.
- Derive identity and tenant from the session, never from model-provided arguments (a
customer_idargument is an injection target; scope queries server-side, assearch_ordersdoes above). - Least privilege: each tool gets narrow credentials (read-only database user, scoped API tokens), not a god-mode service account.
- Scopes per tool: check the user's permissions before execution; tools the user can't use shouldn't even be offered.
- Confirmation for consequential actions: payments, deletions, sending messages, changing permissions, irreversible operations. Show the exact action and arguments; require explicit approval (human-in-the-loop, chapter 169, 171).
- Confused deputy: the agent has more access than an attacker who controls some input (a document, an email, a web page). Indirect prompt injection (chapter 176) tries to make the model call tools against the user's interests. Defences: authorisation per call, confirmations, restricting which tools are available when untrusted content is in context, output-destination allowlists.
- Audit every call: who, what, arguments, result, timing.
Validation and normalisation
Treat arguments like any untrusted API input:
- Schema validation (types, enums, ranges, patterns) with clear error messages.
- Semantic checks: the order exists and belongs to the user; dates are in range; the refund doesn't exceed the total.
- Normalisation: trim strings, canonicalise case and formats, resolve relative dates against the user's time zone, map synonyms to enum values.
- Injection-safe execution: parameterised SQL, no shell string concatenation, URL allowlists for fetch tools, path canonicalisation and confinement for file tools.
Execution: timeouts, cancellation, sandboxing
- Timeouts on every call (per tool), plus an overall turn deadline; propagate cancellation to downstream calls.
- Concurrency: models can request several independent calls at once (parallel tool calls); run them concurrently with a bounded pool, preserving result order by id.
- Sandboxing for powerful tools: code execution in isolated containers/microVMs (gVisor, Firecracker, managed code sandboxes) with no network or an allowlist, CPU/memory/time limits, ephemeral filesystems; browser tools in isolated profiles.
- Resource limits and rate limits per user and per tool, to contain loops and abuse (chapter 176).
Retries and idempotency
- Retry transient failures (timeouts, 429/503) with exponential backoff and jitter, a small maximum, and only for idempotent operations or with idempotency keys (chapter 70's pattern): pass a key derived from the tool-call id so a retried "create refund" doesn't create two refunds.
- Don't blindly retry deterministic failures (validation errors, permission denied): return them to the model so it can change course.
- Distinguish retries by the executor (transparent, for transient errors) from retries by the model (it reads an error and tries different arguments).
- Circuit breakers on failing downstream services (chapter 67) so agents don't hammer them.
import random
def with_retries(fn, *, attempts=3, base=0.2, retry_on=(TimeoutError, ConnectionError)):
for i in range(attempts):
try:
return fn()
except retry_on:
if i == attempts - 1: raise
time.sleep(base * 2 ** i * (0.5 + random.random())) # exponential backoff with jitter
def refund_with_idempotency(api, tool_call_id, args):
key = f"refund-{tool_call_id}" # same key on every retry of this call
return with_retries(lambda: api.post("/refunds", json=args, headers={"Idempotency-Key": key}))
Error handling the model can act on
Tool errors go back to the model as results, so they must be informative and safe:
- Structured: an error code, a human-readable message, whether retrying might help, and what to do instead ("order_id must look like 'A17'; ask the user if unsure").
- Safe: no stack traces, secrets, internal hostnames or other tenants' data.
- Distinguish "not found" from "forbidden" carefully: often return the same message for both to avoid revealing existence.
- Bound the loop: step limits, repeated-identical-call detection, and a graceful final message when stuck.
Result shaping
- Return only what the model needs, in a compact, consistent structure (selected fields, not full API payloads): smaller context, lower cost, less distraction, less data exposure.
- Cap sizes; paginate (
next_cursor) or summarise large results; for documents return snippets and ids. - Mark untrusted content: results containing external text (emails, web pages, user-generated content) can carry prompt injections; label them as data (chapter 176).
- Include units, time zones and ids that later calls need.
Tool calling across stacks
# Python: Anthropic SDK tool-use loop (other providers' SDKs are analogous)
import anthropic
client = anthropic.Anthropic()
tools = [TOOLS["search_orders"].schema()]
messages = [{"role": "user", "content": "Where's my order A17?"}]
while True:
resp = client.messages.create(model="claude-sonnet-5-5", max_tokens=1024, tools=tools, messages=messages)
messages.append({"role": "assistant", "content": resp.content})
calls = [b for b in resp.content if b.type == "tool_use"]
if resp.stop_reason != "tool_use" or not calls:
break
messages.append({"role": "user", "content": [
execute_tool_call({"id": c.id, "name": c.name, "input": c.input}, ctx, confirm=lambda n, a: False)
for c in calls]})
// Java: Spring AI — annotate methods as tools; the framework builds schemas and runs the loop
@Component
class OrderTools {
private final OrderService orders;
OrderTools(OrderService orders) { this.orders = orders; }
@Tool(description = "Search the current customer's orders by id or status")
List<OrderView> searchOrders(@ToolParam(description = "Order id like A17", required = false) String orderId,
@ToolParam(description = "pending|shipped|delivered|cancelled|any") String status,
ToolContext ctx) {
String customerId = (String) ctx.getContext().get("customerId"); // from the session, not the model
return orders.search(customerId, orderId, status);
}
}
String answer = chatClient.prompt().user(question).tools(orderTools)
.toolContext(Map.of("customerId", session.customerId())).call().content();
// TypeScript: Vercel AI SDK — tools with Zod schemas; the SDK runs multi-step loops
import { generateText, tool, stepCountIs } from "ai";
import { z } from "zod";
const { text } = await generateText({
model,
tools: {
searchOrders: tool({
description: "Search the current customer's orders by id or status",
inputSchema: z.object({ orderId: z.string().regex(/^[A-Z]\d{1,6}$/).optional(),
status: z.enum(["pending", "shipped", "delivered", "cancelled", "any"]) }),
execute: async ({ orderId, status }) => orders.search(session.customerId, orderId, status),
}),
},
stopWhen: stepCountIs(5),
prompt: "Where's my order A17?",
});
// Go: define the schema, dispatch by name, validate, run with context deadlines
type SearchOrdersArgs struct {
OrderID string `json:"order_id,omitempty"`
Status string `json:"status"`
}
func execute(ctx context.Context, user User, name string, raw json.RawMessage) (string, bool) {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second); defer cancel()
switch name {
case "search_orders":
var a SearchOrdersArgs
if err := json.Unmarshal(raw, &a); err != nil || !validStatus(a.Status) {
return `{"error":"invalid_arguments","message":"status must be pending|shipped|delivered|cancelled|any"}`, true
}
rows, err := orders.Search(ctx, user.CustomerID, a.OrderID, a.Status) // scoped by the session's user
if err != nil { return `{"error":"unavailable","retryable":true}`, true }
b, _ := json.Marshal(rows); return string(b), false
}
return `{"error":"unknown_tool"}`, true
}
// Rust: rig / async-openai style — a typed tool with serde args and a JSON Schema
#[derive(Deserialize, JsonSchema)]
struct SearchOrdersArgs { order_id: Option<String>, status: Status }
impl Tool for SearchOrders {
const NAME: &'static str = "search_orders";
type Args = SearchOrdersArgs; type Output = Vec<OrderView>; type Error = ToolError;
async fn definition(&self, _prompt: String) -> ToolDefinition {
ToolDefinition { name: Self::NAME.into(), description: "Search the current customer's orders".into(),
parameters: serde_json::to_value(schemars::schema_for!(SearchOrdersArgs)).unwrap() }
}
async fn call(&self, args: Self::Args) -> Result<Self::Output, Self::Error> {
tokio::time::timeout(Duration::from_secs(5), self.orders.search(&self.customer_id, args)).await?
}
}
Lab: a defended tool harness
Setup. Python with jsonschema (Draft 2020-12) and SQLite; a refund_order tool over an orders table (A100 ₹900 and A101 ₹450 belong to cust-1, B200 ₹1,200 to cust-2); the conversation's user is cust-1. Substitute, stated plainly: no capable model runs on the lab machine, so the tool calls come from a scripted stand-in that emits ten calls modelled on common real failure modes. The model's choices are scripted; everything the harness does is real code.
The tool's schema (437 characters, sent with every request):
{"name": "refund_order", "description": "Refund part or all of a customer's order. Amount in rupees.",
"input_schema": {"type": "object", "additionalProperties": false,
"required": ["order_id", "amount", "reason"],
"properties": {"order_id": {"type": "string", "pattern": "^[A-Z][0-9]{3}$"},
"amount": {"type": "integer", "minimum": 1, "maximum": 5000},
"reason": {"type": "string", "enum": ["damaged", "late", "wrong_item", "other"]}}}}
Experiment 1: ten calls, with and without defences
| Call | Arguments passed straight to the function | Defended harness |
|---|---|---|
| valid | refunded ₹450 | refunded ₹450 |
amount "200" (string) |
crash: TypeError: unsupported operand… |
amount: '200' is not of type 'integer' |
missing reason |
crash | 'reason' is a required property |
invented reason: "customer_angry" |
refunded ₹100 | not one of ['damaged', 'late', 'wrong_item', 'other'] |
unknown tool issue_voucher |
crash | unknown_tool: Available tools: refund_order. |
extra skip_checks: true |
crash | Additional properties are not allowed ('skip_checks' was unexpected) |
hallucinated order A999 |
order_not_found | order_not_found, "Ask the customer to check the order number." |
| A101 again (already fully refunded) | exceeds_order_total | exceeds_order_total, "Only 0 rupees remain refundable on A101." |
| another customer's order B200 | refunded ₹300 | not_authorised |
| ₹1,500 on A100 | rejected only because it exceeded the total | needs_approval: over ₹1,000 needs a human |
Refunds table afterwards: undefended [A101 ₹450, A100 ₹100, B200 ₹300]; defended [A101 ₹450].
The defences, in the order the harness applies them:
- Allow-list of tool names.
- Schema validation with
additionalProperties: false, enums and ranges; errors returned as one readable line the model can fix. - Authorisation from the database: the order's owner must be the authenticated user. The model's view of who the user is doesn't count.
- Policy gates: amounts over ₹1,000 return
needs_approvalinstead of executing. - Execution in a worker with a 1-second timeout.
- Business-rule errors from the tool itself (not found, over total) phrased as instructions.
Note the undefended "over approval limit" row: it was blocked only by a coincidence of the data. Safety that depends on luck isn't a control.
Experiment 2: timeouts and retries
The payment step was made slow (1.5 s) so the harness timed out at 1.0 s while the refund still completed in the background; the model then retried.
| Retry behaviour | First call | Retry | Refunds recorded |
|---|---|---|---|
| a new key per call | timeout | refunded | 2 (₹600) |
| the same idempotency key for the logical operation | timeout | already_done |
1 (₹300) |
A timeout tells you nothing about whether the work happened. The harness should mint the idempotency key when the model first proposes an operation and reuse it for any retry of that operation (and the tool must store keys transactionally with the effect), so "safe to retry" in the timeout message is true.
Try it yourself
- Add a
get_orderread-only tool and require the model to call it beforerefund_order; enforce the order in the harness. - Log every call (arguments, decision, latency, result) as a span, and write the query that finds the most common validation error.
- Return a
needs_approvalticket ID, and implement the approval endpoint that executes the stored call exactly once. - With any capable model you can access, give it this tool and 50 customer messages, and count each failure type from the table.
Revision sheet: tool calling
Key ideas
- The model emits structured call requests; the application validates, authorises, executes and returns results; the loop repeats until a final answer.
- Tool definitions: clear name, description of when to use it, strict JSON Schema (enums, ranges,
additionalProperties: false), examples where useful; few, well-separated tools beat many overlapping ones. - Authorisation uses the authenticated user's identity and your data, never model-supplied identity; least privilege per tool and per user.
- Policy gates: human approval for irreversible, high-value or external actions; dry-run modes.
- Execution: timeouts, cancellation, sandboxes for code, rate limits, budgets per conversation.
- Idempotency keys for side-effecting tools; retries only with the same key.
- Errors: short, specific, actionable; results: shaped and truncated to what the model needs.
- Parallel tool calls, tool search/discovery for large catalogues, and protocols (MCP, chapter 172) for reuse.
Numbers to remember
- Lab: undefended harness issued 2 wrong refunds out of 10 calls and crashed on 4; defended: 0 wrong refunds, 0 crashes.
- Lab: timeout + retry without idempotency → 2 refunds; with → 1.
Pitfalls
- Passing model arguments straight to functions.
- Trusting identity, role or permissions stated in the conversation.
- Retrying side-effecting calls without idempotency.
- Returning huge raw results (whole tables, HTML) into the context.
- Tools with vague, overlapping descriptions.
Glossary
- Tool / function calling: model-generated structured requests to run code.
- Allow-list: the set of tools and arguments the harness permits.
- Human-in-the-loop approval: a person confirms a proposed action before it runs.
- Idempotency key: an identifier that makes repeated requests have one effect.
- Sandbox: an isolated environment for executing untrusted code.