Sub topic 11
Building the tool-calling loop
This chapter assumes you can call an LLM API with tools, you have a connected ClientSession from the earlier chapters, and you have the to_llm_tools helper that converts MCP tool definitions into the model's tool format.
What the loop does
The model can't run tools itself. It returns a request to call a tool, and your application runs the call and reports the result. The loop repeats this exchange until the model replies with plain text.
The code
import anthropic
llm = anthropic.Anthropic()
MODEL = "your-model-id" # replace with a model available to your account
MAX_STEPS = 10
def to_llm_tools(mcp_tools):
return [
{
"name": t.name,
"description": t.description or "",
"input_schema": t.inputSchema,
}
for t in mcp_tools
]
async def run_turn(session, user_text):
tools = to_llm_tools((await session.list_tools()).tools)
messages = [{"role": "user", "content": user_text}]
for _ in range(MAX_STEPS):
response = llm.messages.create(
model=MODEL, max_tokens=1024, tools=tools, messages=messages
)
messages.append({"role": "assistant", "content": response.content})
if response.stop_reason != "tool_use":
return "".join(b.text for b in response.content if b.type == "text")
results = []
for block in response.content:
if block.type != "tool_use":
continue
result = await session.call_tool(block.name, block.input)
text = "\n".join(c.text for c in result.content if c.type == "text")
results.append(
{
"type": "tool_result",
"tool_use_id": block.id,
"content": text,
"is_error": bool(result.isError),
}
)
messages.append({"role": "user", "content": results})
raise RuntimeError("Tool loop did not finish within MAX_STEPS")How it works
- List the tools once per turn.
list_toolsreturns the current definitions, andto_llm_toolsrenames the fields for the model API. - Send the full history. The model has no memory between calls. Every request carries all earlier messages, including tool results.
- Append the assistant message unchanged. It must keep its
tool_useblocks, because each result refers back to one by ID. - Check
stop_reason. Any value other thantool_usemeans the model is done, so the loop returns the text. - Run every requested tool. A single response can contain several
tool_useblocks. Answer all of them in one user message. - Match IDs. Each
tool_resultcarries thetool_use_idof the block it answers. If an ID is missing or wrong, the API rejects the request.
Common mistakes
- Dropping the assistant message before sending results. The API then sees results with no matching request.
- Sending one
tool_resultmessage per tool instead of one message holding all of them. - Passing
result.contentobjects straight to the model. Convert them to text first, as the code does. - Treating
isErroras an exception. It is data. Pass it to the model so it can correct its arguments or try something else.
Exercise
The model returns two tool_use blocks in one response. How many messages should the loop append to messages before the next model call, and what must each tool_result contain to match its request?
Show answer
Append two messages in total. One is the assistant message holding both tool_use blocks. The other is a single user message holding two tool_result blocks. Each tool_result must carry the tool_use_id of the block it answers, plus its content and the error flag.