Tool Calling: Letting the Model Call Your Functions
The shared foundation of agent orchestration, computer use and MCP. Both pipeline "orchestration" and "agent orchestration" are built on this layer.
Core concepts
- Tool definition: a name + a description + a JSON Schema for the parameters. The model only "decides which tool to call and with what arguments"; your code does the actual execution.
- Message loop: the model returns a tool call request → you execute it → you send the result back as a new message → the model continues, until it stops requesting tools.
- Parallel tool calls: one reply can contain several tool calls; you can run them concurrently and return all results at once.
- tool_choice: controls whether the model decides on its own, must call a specific tool, or must not call any tool.
- strict mode: set
strict: trueon a tool definition so arguments strictly match the schema (supported by both Anthropic and OpenAI).
How it works: one full message loop (Anthropic Messages API shape)
user: "Check the status of order 123"
assistant: [tool_use id=tu_1 name=get_order input={"order_id":"123"}] ← stop_reason = "tool_use"
user: [tool_result tool_use_id=tu_1 content="Shipped"] ← you execute and send back
assistant: "Order 123 has shipped." ← stop_reason = "end_turn"- Every
tool_resultmust be matched to its request bytool_use_id, or the API returns an error. - When a tool fails, don't throw an exception that breaks the loop. Send back
is_error: truewith the error message and let the model decide whether to retry or try something else. - The OpenAI Responses API uses
function_call/function_call_outputitems matched bycall_id; the principle is the same.
In practice: a minimal tool loop without a framework
python
import asyncio, json
MAX_STEPS = 8
TOOLS = {"get_order": get_order, "search_docs": search_docs} # your async functions
async def run_tool(block):
fn = TOOLS.get(block.name)
if fn is None:
return {"type": "tool_result", "tool_use_id": block.id, "is_error": True, "content": f"Unknown tool {block.name}"}
try:
result = await asyncio.wait_for(fn(**block.input), timeout=20)
return {"type": "tool_result", "tool_use_id": block.id, "content": json.dumps(result, ensure_ascii=False)}
except Exception as e: # send the error back to the model instead of breaking the loop
return {"type": "tool_result", "tool_use_id": block.id, "is_error": True, "content": str(e)}
async def agent(messages, tool_specs):
for step in range(MAX_STEPS):
resp = await client.messages.create(model=MODEL, max_tokens=2048, tools=tool_specs, messages=messages)
messages.append({"role": "assistant", "content": resp.content})
if resp.stop_reason != "tool_use":
return resp
calls = [b for b in resp.content if b.type == "tool_use"]
results = await asyncio.gather(*(run_tool(c) for c in calls)) # run in parallel
messages.append({"role": "user", "content": list(results)})
raise NeedHumanReview(f"Exceeded max steps {MAX_STEPS}")Key points: a max step count, a timeout per tool, errors sent back to the model, parallel execution, and a trace log entry for every step.
Common pitfalls
- Tool descriptions that are too terse: the model decides when to call a tool from its description. Spell out when to use it, when not to, and give argument format examples.
- Too many tools: dozens of tools lower selection accuracy and eat context. Group them by task, load them on demand, or narrow the set with a router first.
- Exposing dangerous operations directly as tools: delete, pay and send-message tools should go through human confirmation (see "human takeover").
- No max step count: the model gets stuck in a loop and cost runs away.
- Tool results that are too long: returning a whole HTML page blows up the context. Truncate or summarize first.
Common interview questions
- Draw the full tool calling message loop. What values can
stop_reasontake? - How do you execute parallel tool calls and return their results?
- How do you handle a tool failure? Why not just throw an exception?
- How do you stop an agent from looping forever and running up costs?
- How does tool calling relate to MCP? (MCP is a protocol for "exposing tools in a standard way"; the model still uses them through tool calling)
How it relates to my projects
- Browser Automation Agent: the minimal loop above is the agent's skeleton.
- Related knowledge base pages: Agent and Workflow Patterns, MCP.
Sources
- Anthropic Docs: Tool use with Claude — tool_use / tool_result, parallel calls,
is_error,tool_choice - Anthropic Docs: Structured outputs (strict tool use)
- OpenAI Docs: Function calling —
function_call/function_call_output,strict - Anthropic Engineering: Writing effective tools for agents — practical advice on tool design and descriptions
