Tool calling: schemas, validation and the execution loop
Build LLM-backed product features end to end against a deterministic local mock: form well-formed chat requests, structure prompts and validated JSON outputs, stream and retry safely, ground answers in retrieved sources, call tools inside bounded agent loops, defend against prompt injection, and evaluate quality with reproducible checks instead of one-off demos. No API keys and no network calls are used anywhere in the course.
What you will be able to do
#- Execute model-requested tool calls through an allowlist registry with argument validation and structured errors.
- Trace a two-round tool loop against a scripted model and predict the final content and round count.
- Identify and replace execution patterns that turn model output into code or commands.
Overview
#Tools: the model asks, your code acts
A tool (also called a function) is a capability you expose to the model: a name, a description, and a typed argument schema. The model never runs anything. It emits a structured request, "call getWeather with city Lisbon", and your code decides whether and how to run it. This division of labor is the security boundary of every agentic system: interpretation lives in the model, authority lives in your code.
The loop
function runToolLoop(model, registry, question, maxRounds) {
const messages = [{ role: "user", content: question }];
for (let round = 1; round <= maxRounds; round++) {
const out = model(messages);
if (out.content) return { content: out.content, rounds: round };
const result = executeToolCall(out.toolCall, registry);
messages.push({ role: "assistant", content: "tool_request" });
messages.push({ role: "tool", content: result });
}
return { error: "max_rounds", rounds: maxRounds };
}
Each iteration: the model either answers or requests a tool; your code validates and executes the request; the result goes back into the conversation as a tool-role message; the model continues with that evidence. The loop needs an explicit maxRounds cap, because a model that keeps requesting tools otherwise loops indefinitely, burning tokens and time.
Validation is the security boundary
const TOOLS = {
getWeather: {
args: ["city"],
run: (args) => ({ city: args.city, tempC: 18, condition: "rainy" })
}
};
function executeToolCall(call, registry) {
const tool = registry[call.name];
if (!tool) return { error: "Unknown tool: " + call.name };
for (const arg of tool.args) {
if (typeof call.args?.[arg] !== "string" || call.args[arg].length === 0) {
return { error: "Missing argument: " + arg };
}
}
return tool.run(call.args);
}
Three checks happen before anything runs. The tool name must exist in your registry (an allowlist, not a blocklist). Arguments must match the declared schema. And the execution goes through your registered function, never through dynamic evaluation of model text. The broken version below is the single most dangerous pattern in tool-calling code:
// Never do this: model output becomes executable code or a command.
const result = eval("fetchWeather(" + JSON.stringify(out.toolCall.args) + ")");
const shell = "curl 'https://api.example.com/?city=" + out.toolCall.args.city + "'";
A malicious or merely confused model (or a malicious document it retrieved, see lesson 12) can steer interpolated strings. The registry pattern keeps the set of possible actions finite and reviewable.
Tool results are untrusted input
Whatever a tool returns enters the conversation as data the model will treat as evidence. That makes tool results an injection carrier: a compromised or spammed data source can insert instruction-like text that the next model turn may follow. Treat tool results the way lesson 12 treats retrieved documents: delimited, labeled as data, and never granted authority by proximity.
Side effects need more than validation
getWeather is read-only; a wrong call costs a wasted request. Tools that write (send email, issue refund, delete record) need the agent-loop protections of lesson 11: permission scopes per tool, confirmation or approval gates, idempotency keys for safe retries (lesson 7), and an audit trail of every call with its arguments and result. Design rule of thumb: the more irreversible the side effect, the smaller the set of callers allowed to request it, and the more human oversight between request and execution.
Designing the schema is prompt engineering
The tool's name, description and argument descriptions are prompt material: the model chooses tools based on them. Vague descriptions produce vague tool choices, which is why tool quality issues look like "the model picked the wrong function" and are fixed by sharpening descriptions and adding few-shot examples of correct calls. When a task needs multiple tools, keep them few and orthogonal; overlapping tools create choice ambiguity that no amount of prompting fully resolves.
Continue with ai-engineering-bounded-agents to wrap the tool loop in budgets, permissions and approval gates.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Implement
Implement executeToolCall(call, registry): return { error: "Unknown tool: <name>" } when the name is not in the registry; return { error: "Missing argument: <arg>" } for the first declared argument that is not a non-empty string; otherwise return tool.run(call.args).
starter.javascriptconst TOOLS = { getWeather: { args: ["city"], run: (args) => ({ city: args.city, tempC: 18, condition: "rainy" }) } }; function executeToolCall(call, registry) { // 1. Unknown name -> { error: "Unknown tool: <name>" } // 2. First declared arg that is not a non-empty string // -> { error: "Missing argument: <arg>" } // 3. Otherwise return tool.run(call.args). } console.log(JSON.stringify(executeToolCall({ name: "getWeather", args: { city: "Lisbon" } }, TOOLS)));Reveal the reference answer
reference.javascriptconst TOOLS = { getWeather: { args: ["city"], run: (args) => ({ city: args.city, tempC: 18, condition: "rainy" }) } }; function executeToolCall(call, registry) { const tool = registry[call.name]; if (!tool) return { error: "Unknown tool: " + call.name }; for (const arg of tool.args) { if (typeof call.args?.[arg] !== "string" || call.args[arg].length === 0) { return { error: "Missing argument: " + arg }; } } return tool.run(call.args); } console.log(JSON.stringify(executeToolCall({ name: "getWeather", args: { city: "Lisbon" } }, TOOLS)));Authored expected output: {"city":"Lisbon","tempC":18,"condition":"rainy"}
The call { name: "getWeather", args: { city: "Lisbon" } } passes the allowlist check and the argument check, so the registered function runs and returns the fixed mock weather. Every rejection is structured data, never an exception.
Exercise 2Test
Write assertions covering the two rejection paths: an unknown tool name returns the Unknown tool error, and a missing city argument returns the Missing argument error.
starter.javascriptfunction check(label, condition) { console.log(condition ? "PASS" : "FAIL"); } // Write two assertions against executeToolCall(call, TOOLS): // 1. { name: "getStockPrice", args: { ticker: "ACME" } } returns exactly // { error: "Unknown tool: getStockPrice" }. // 2. { name: "getWeather", args: {} } returns exactly // { error: "Missing argument: city" }.Reveal the reference answer
reference.javascriptfunction check(label, condition) { console.log(condition ? "PASS" : "FAIL"); } check("unknown tool rejected", JSON.stringify(executeToolCall({ name: "getStockPrice", args: { ticker: "ACME" } }, TOOLS)) === JSON.stringify({ error: "Unknown tool: getStockPrice" })); check("missing argument rejected", JSON.stringify(executeToolCall({ name: "getWeather", args: {} }, TOOLS)) === JSON.stringify({ error: "Missing argument: city" }));Authored expected output: PASS PASS
The rejection paths are the security-relevant behavior; asserting them pins the allowlist and schema checks against future refactors that might loosen them.
Exercise 3Predict
With the scripted mockAgentModel (round 1 requests getWeather for Lisbon, round 2 answers from the tool result) and maxRounds 3, predict the JSON returned by runToolLoop.
starter.javascriptconst TOOLS = { getWeather: { args: ["city"], run: (args) => ({ city: args.city, tempC: 18, condition: "rainy" }) } }; function executeToolCall(call, registry) { const tool = registry[call.name]; if (!tool) return { error: "Unknown tool: " + call.name }; for (const arg of tool.args) { if (typeof call.args?.[arg] !== "string" || call.args[arg].length === 0) { return { error: "Missing argument: " + arg }; } } return tool.run(call.args); } function mockAgentModel(messages) { // Scripted: with no tool result yet, request the weather tool. // After a tool result arrives, answer from it. const toolResults = messages.filter((m) => m.role === "tool"); if (toolResults.length === 0) { return { toolCall: { name: "getWeather", args: { city: "Lisbon" } } }; } const r = toolResults[toolResults.length - 1].content; return { content: r.city + ": " + r.tempC + "C, " + r.condition + "." }; } function runToolLoop(model, registry, question, maxRounds) { const messages = [{ role: "user", content: question }]; for (let round = 1; round <= maxRounds; round++) { const out = model(messages); if (out.content) return { content: out.content, rounds: round }; const result = executeToolCall(out.toolCall, registry); messages.push({ role: "assistant", content: "tool_request" }); messages.push({ role: "tool", content: result }); } return { error: "max_rounds", rounds: maxRounds }; } console.log(JSON.stringify(runToolLoop(mockAgentModel, TOOLS, "Weather in Lisbon?", 3)));Reveal the reference answer
reference.javascript// Predicted output: // // {"content":"Lisbon: 18C, rainy.","rounds":2} // // Trace: round 1, the model sees no tool message and returns a toolCall. // executeToolCall validates it and runs the mock, producing // { city: "Lisbon", tempC: 18, condition: "rainy" }, which is pushed as // a tool message. Round 2, the model reads that result and returns // content, so the loop returns with rounds 2. maxRounds 3 is unused.Authored expected output: {"content":"Lisbon: 18C, rainy.","rounds":2}
Round 1 emits a tool request; the mock tool result enters the conversation; round 2 reads it and answers. The loop returns on the first reply, so rounds is 2 and the maxRounds cap is never touched.
Exercise 4Debug
dangerousExecute builds a command string from model-supplied args and evals model-supplied JSON. Explain the two concrete dangers and rewrite it to use the registry with validation.
starter.javascriptfunction dangerousExecute(out) { // Anti-pattern 1: model output becomes executable code. const result = eval("mockFetchWeather(" + JSON.stringify(out.toolCall.args) + ")"); // Anti-pattern 2: model output is interpolated into a command string. const command = "curl 'https://api.example.com/weather?city=" + out.toolCall.args.city + "'"; return { result, command }; } const out = { toolCall: { name: "getWeather", args: { city: "Lisbon'; rm -rf /tmp/x; echo '" } } }; console.log(JSON.stringify(dangerousExecute(out)));Reveal the reference answer
reference.javascriptfunction safeExecute(out, registry) { const tool = registry[out.toolCall.name]; if (!tool) return { error: "Unknown tool: " + out.toolCall.name }; for (const arg of tool.args) { if (typeof out.toolCall.args?.[arg] !== "string" || out.toolCall.args[arg].length === 0) { return { error: "Missing argument: " + arg }; } } return { result: tool.run(out.toolCall.args) }; } // The malicious city string is now just data passed to a fixed function. // It can produce a wrong lookup at most; it cannot choose an action, // spawn a command, or execute code.Authored expected output: Execution goes through registry allowlist plus argument validation; no eval, no string-built commands
Interpolating model output into executable strings lets any upstream influence, including a poisoned document, choose the executed action. The registry keeps the action set finite and reviewed.
Exercise 5Explain
Knowledge check: in a tool-calling system, who executes the tool and who requests it?
starter.text// Choose the correct option.Reveal the reference answer
reference.textThe model requests a tool call by emitting structured output; your application code validates the request against an allowlist and schema, executes the registered function, and returns the result to the model as a tool message.Authored expected output: The model requests; your code validates and executes
Keeping authority in application code is what makes tool use auditable and bounded.
Common misconceptions
#- Myth: the model executes tools. Fact: the model only emits a structured request; your code validates and executes it, or not.
- Myth: tool results are trustworthy because they came from your own system. Fact: results enter the prompt as data and are an injection carrier; delimit and treat them as untrusted.
- Myth: one round is always enough. Fact: multi-step tasks need multiple rounds, which is why the loop needs an explicit maxRounds budget.
Follow-up practice
#- ai-engineering-bounded-agents
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.