FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Tool Calling

How models propose typed actions while applications retain execution authority and validation.

Freshness: current•14 min read•LLM Application Engineering

Key Learning Outcomes

  • ✓Design tool contracts
  • ✓Validate arguments and authority
  • ✓Close the tool result loop
Full Technical Reference Document

Mental model

Tool calling splits every external action across a strict capability boundary: the language model emits a probabilistic, schema-shaped invocation intent (tool_name, call_id, and raw JSON arguments), while deterministic application code owns schema normalization, caller authorization, transactional idempotency, and execution. The model never executes side effects directly and never acts as an authority for permissions or tenant identity.

Model Emits Intent
Normalize & Validate Args
Enforce Server RBAC
Classify Side-Effect Tier
Idempotent Dispatch & Return
Conceptual teaching model synthesized from:Function CallingBuilding Effective AI AgentsModel Context Protocol Architecture and Tools Specification

Learning outcomes

  • Separate model-proposed tool invocation intents from deterministic runtime validation, authorization, and state mutation.
  • Apply canonical JSON Schema normalization (defaulting optional parameters, stripping unknown keys, and coercing safe types) before policy checks.
  • Classify operations into read-only, idempotent write, and irreversible mutation tiers with distinct approval and retry contracts.
  • Implement a production tool dispatch router with server-injected caller identity, idempotency keys, and bounded context-safe error formatting.

Theory

Under OpenAI Function Calling and the Model Context Protocol (MCP) tools specification, a model exposed to tool definitions emits structured tool_calls blocks rather than natural-language prose whenever external state or computation is required. Because tool names, descriptions, and parameter schemas sit inside the model's context window, Anthropic's agent engineering guidance emphasizes treating tool interfaces with the same rigor as human-facing API ergonomics: clear verb-noun names (lookup_invoice, not handle_data), mutually exclusive arguments, and concise docstrings prevent argument confusion across parallel calls.

Crucially, emitting a tool_call is merely a typed proposal. Before any downstream resource is touched, the runtime dispatch layer executes four sequential deterministic gates:

Texec(c)=Validateschema(c.args)∧AuthRBAC(usession,c.tool,c.target)∧TierGuard(c.tier)∧IdemLock(kc)T_{\text{exec}}(c) = \text{Validate}_{\text{schema}}(c.\text{args}) \land \text{Auth}_{\text{RBAC}}(u_{\text{session}}, c.\text{tool}, c.\text{target}) \land \text{TierGuard}(c.\text{tier}) \land \text{IdemLock}(k_c)

Here, cc is the model-emitted call, usessionu_{\text{session}} is the cryptographically verified caller principal (sourced strictly from the JWT or session store, never from c.argsc.\text{args}), TierGuard\text{TierGuard} enforces human confirmation for irreversible mutations, and kck_c is a deterministic idempotency key derived from workflow step, caller, and canonicalized payload hash.

Canonical JSON Schema Argument Normalization

Models frequently emit syntactically valid JSON that varies superficially across retries—for example, passing "limit": "25" instead of 25, omitting defaulted boolean flags, or supplying "email": "Alice@Example.com " with trailing whitespace. Canonicalization normalizes strings, applies explicit schema defaults, sorts keys deterministically, and rejects unknown fields (extra="forbid") before computing the idempotency key digest kc=SHA256(tool∥canonical_json(args))k_c = \text{SHA256}(\text{tool} \parallel \text{canonical\_json}(\text{args})). Without canonicalization, a transient network retry where the model swaps two dictionary keys generates a different hash and duplicates a side effect.

Side-Effect Classification and Quantified Blast Radius

Production routers partition registered tools into three operational tiers:

  1. Read-only (read): Pure lookups (get_order_status, search_kb) with zero external state mutation; safe for automatic retries with bounded timeouts and result truncation.
  2. Idempotent write (write_idempotent): State changes guarded by an idempotency token (create_draft_refund, upsert_ticket_tag); safe for automatic network retries only while reusing the exact stored key kck_c.
  3. Irreversible mutation (mutate_irreversible): External transfers, destructive deletes, or customer emails (send_wire_transfer, drop_table); never auto-retried blindly and gated behind an out-of-band approval token.

Consider a billing support agent processing 4,000 refund-related tool proposals per week. Suppose 3% (120 calls) experience transient gateway timeouts requiring retries, and 0.5% (20 calls) reflect prompt-injected or hallucinated duplicate actions. If an irreversible issue_refund tool lacks idempotency keys and human-in-the-loop (HITL) tier guards, a 3% retry rate produces up to 120 double-refund attempts per week; at a \$180 average order value, unprotected retries alone risk \$21,600 per week in duplicate payouts. Splitting the workflow into a read-only get_invoice, an idempotent draft_refund keyed by (tenant_id, invoice_id, workflow_step), and an out-of-band human sign-off for commit_refund cuts unintended payout risk to zero while preserving fast automated drafting.

Trade-offs

Engineering teams balance autonomy, latency, and safety when shaping tool schemas and dispatch policies.

Design AxisNarrow Typed Tools (e.g., draft_refund)Broad General Tools (e.g., run_sql / bash)Key Engineering Consequence
Argument ValidationStrict field enums, ranges, regexesFree-form code or query stringsNarrow schemas prevent malformed intents before execution
Authorization ScopeAction + resource granularity per toolCoarse sandbox or DB role permissionsNarrow tools align cleanly with least-privilege RBAC
Prompt Token FootprintHigher when > 25 tools are loadedCompact (1–2 tool definitions)Overloading tool manifests confuses selection; use scoped routing
Blast Radius on InjectionBounded to pre-approved schema actionsArbitrary read/write/exfiltration inside sandboxBroad tools demand OS-level microVM isolation and egress firewalls

When an application exposes dozens of tools, dynamic tool retrieval or stage-scoped tool subsets keep schema token count below 15% of the context budget and sharpen model selection accuracy.

Failure modes and misconceptions

  • Trusting model-supplied identity fields: Defining user_id: str in the tool schema allows indirect prompt injection or hallucination to query another customer's records (IDOR). Always strip identity parameters from the schema and inject caller_id exclusively from server session state.
  • Returning raw stack traces or multi-megabyte payloads: Injecting an uncapped 40,000-token database dump or raw SQL traceback back into the tool message pollutes context, explodes input billing, and leaks schema internals. Truncate oversized outputs cleanly and return structured, actionable error codes (retryable: true vs terminal: invalid_invoice).
  • Retrying non-idempotent HTTP POST endpoints on timeout: A client timeout proves only that the caller did not receive the response—not that the downstream service rolled back. Never retry mutate_irreversible operations without a server-enforced idempotency ledger.
  • Overlapping tool definitions ("tool soup"): Exposing search_users, find_customer, and lookup_account with near-identical descriptions degrades tool-selection accuracy and increases multi-turn recovery loops.
  • Ignoring parallel tool-call partial failures: When a model emits four parallel tool_calls, returning answers for only three or omitting a matching tool_call_id breaks provider protocol state and causes 400 validation errors on the next turn.

Decision scenario

A developer operations assistant helps engineers triage production alerts using Datadog metrics, Kubernetes pod logs, and PagerDuty incident escalations. Initially, the team wraps raw kubectl commands inside a single shell tool, resulting in noisy logs overflowing context windows and an accidental pod deletion during an alert storm. Replace the generic shell tool with three typed contracts: read-only query_pod_logs (capped at 100 tail lines and 4,000 chars), idempotent annotate_incident keyed by (incident_id, note_hash), and restart_deployment classified as mutate_irreversible requiring an explicit Slack approval token from an on-call SRE before execution. Validate all cluster and namespace names against an RBAC allowlist injected from SSO claims rather than model arguments.

Implementation example

This Python tool dispatch router enforces canonical Pydantic normalization, server-injected RBAC checks, side-effect tier guards, deterministic idempotency caching, and bounded tool result serialization.

python
import hashlib, json
from dataclasses import dataclass
from typing import Any, Callable, Literal
from pydantic import BaseModel, ConfigDict, Field
​
Tier = Literal["read", "write_idempotent", "mutate_irreversible"]
​
class RefundDraftArgs(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
invoice_id: str = Field(..., pattern=r"^inv_[a-zA-Z0-9]{6,20}$")
amount_cents: int = Field(..., gt=0, le=500000)
​
@dataclass(frozen=True)
class ToolSpec:
name: str; tier: Tier; schema: type[BaseModel]; scope: str
handler: Callable[[BaseModel, str, str], dict[str, Any]]
​
class ToolRouter:
def __init__(self, specs: list[ToolSpec], max_chars: int = 3500) -> None:
self._specs, self._idem, self._max_chars = {s.name: s for s in specs}, {}, max_chars
​
def dispatch(self, name: str, raw: dict[str, Any], caller_id: str,
scopes: set[str], approval: str | None = None) -> str:
spec = self._specs.get(name)
if not spec or spec.scope not in scopes:
return json.dumps({"error": "unknown_or_forbidden_tool", "retryable": False})
if spec.tier == "mutate_irreversible" and not approval:
return json.dumps({"error": "human_approval_required", "retryable": False})
canon = json.dumps(spec.schema.model_validate(raw).model_dump(), sort_keys=True)
key = hashlib.sha256(f"{caller_id}:{name}:{canon}".encode()).hexdigest()
if spec.tier != "read" and key in self._idem: return self._idem[key]
out = json.dumps(spec.handler(spec.schema.model_validate(raw), caller_id, key))[: self._max_chars]
if spec.tier != "read": self._idem[key] = out
return out

Knowledge check

Reflect before revealing the guide

Why must caller identity, side-effect idempotency keys, and RBAC authorization remain strictly outside the model's JSON argument schema?

Prerequisites & Related Concepts (7)

Private notes

0 words
Included In Free Course
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.