Day 1 · · 2 min read
How tool calling actually works
The question
When a model “uses a tool”, who is actually doing the work? And what does the conversation look like on the wire?
The deep dive
Tool calling is a contract with three parts:
- You describe tools. Each one has a name, a description and a JSON Schema for its input.
- The model decides. If a tool would help, the reply stops with a structured
tool_useblock instead of plain text. - You execute and reply. Your code runs the function and sends back a
tool_resultthat references the call’s id. The model then continues.
The model never touches your system. It only produces JSON that matches a schema you gave it. Everything risky happens in your code, which is also where you put validation and permissions.
An agent is this loop running until the model stops asking for tools.
The build
A minimal weather tool, with the loop written out by hand:
const tools = [{
name: 'get_weather',
description: 'Current weather for a city.',
input_schema: {
type: 'object',
properties: { city: { type: 'string' } },
required: ['city'],
},
}];
let messages = [{ role: 'user', content: 'Do I need an umbrella in Leeds?' }];
while (true) {
const res = await client.messages.create({ model, max_tokens: 1024, tools, messages });
messages.push({ role: 'assistant', content: res.content });
if (res.stop_reason !== 'tool_use') break;
const results = await Promise.all(
res.content
.filter((b) => b.type === 'tool_use')
.map(async (b) => ({
type: 'tool_result',
tool_use_id: b.id,
content: JSON.stringify(await getWeather(b.input.city)),
})),
);
messages.push({ role: 'user', content: results });
}
Gotchas
- Descriptions are the prompt. A vague description gets vague tool choice. Say when not to use the tool, too.
- Return errors as results. If a tool fails, send the error text back as the
tool_result(marked as an error) so the model can recover, instead of throwing.
- Several calls can come in one turn. Handle every
tool_useblock, not just the first.