Sub topic 11
Building the tool-calling loop
This chapter assumes you can read async Python and have called an LLM API with tools before. It also assumes you have the server.py from the earlier chapter, with its add tool, and a working ClientSession that lists tools. You will now wire those pieces into a loop that lets a model call MCP tools until it has an answer.
What the loop does
The model never talks to an MCP server. Your host application sits between them and does four jobs on every pass:
- Send the conversation and the tool definitions to the model.
- Check whether the model asked for tools.
- If it did, run each requested tool through the MCP session.
- Append the results to the conversation and ask the model again.
The loop ends when the model replies without a tool request. It also ends, with an error, when it reaches a step limit you set.
The conversation state
The loop is stateful, and the state is a plain list called messages. The model sees only what is in that list, so each turn you must add two things:
- The assistant message exactly as the model returned it, including its
tool_useblocks. - A user message holding one
tool_resultblock pertool_useblock.
Each tool_result carries a tool_use_id that matches the id of the request it answers. If an id is missing or does not match, the API rejects the request.
Converting tools once
The previous chapter produced to_llm_tools. It maps name, description and inputSchema onto the Anthropic field names. Other providers wrap the same schema differently, so only this function changes if you switch models.
def to_llm_tools(mcp_tools):
return [
{
"name": t.name,
"description": t.description or "",
"input_schema": t.inputSchema,
}
for t in mcp_tools
]The loop in full
This script is complete. It launches server.py, runs one user turn through the loop and prints the answer. Set MODEL to a model ID your account can use, and set ANTHROPIC_API_KEY in your environment.
import asyncio
import anthropic
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
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")
async def main():
params = StdioServerParameters(command="python", args=["server.py"])
async with stdio_client(params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
print(await run_turn(session, "What is 2 + 3? Use the tool."))
asyncio.run(main())Reading the loop line by line
Listing tools once per turn
run_turn calls list_tools at the start, not on every pass. Tool lists rarely change mid-turn. If a server announces a change, refresh the list at the start of the next turn.
Appending the assistant message
The loop appends response.content before it checks stop_reason. The model needs to see its own tool_use blocks in later requests. If you keep only the text, the next request is invalid, because it contains tool_result blocks with no matching request.
The stop condition
stop_reason is "tool_use" when the model wants tools run. Any other value ends the loop. Typical other values are "end_turn" and "max_tokens". A max_tokens stop means the answer was cut off. The code above returns the partial text, so a production host should check for that case explicitly.
Several tool calls in one response
A model can request several tools in one response. The inner for loop handles each block in order and collects all results into a single user message. Do not send one user message per result. The API expects every result for an assistant turn together, in the message that follows it.
You can run independent calls concurrently with asyncio.gather. Sequential execution is simpler and keeps logs readable. Switch to concurrency only when tool latency is a measured problem.
Passing results back
An MCP result holds a list of content items, which can be text, images or embedded resources. This loop keeps only the text items and joins them. Any image or resource content is dropped silently. If your tools return other types, extend the conversion instead of discarding them.
isError is how an MCP server reports that the tool ran and failed, for example bad input or an upstream outage. Passing it as is_error tells the model the call failed, so it can retry with different arguments or explain the problem. A tool failure is not a protocol failure, and it should not stop your loop.
The step limit
MAX_STEPS protects you from a model that keeps calling tools. It might repeat the same failing call or chase a goal the tools cannot reach. Each pass costs tokens, because the whole message list is sent again, and the cost grows with every step. A limit of 10 suits small tasks, and you should raise it only when a real workflow needs more.
Raising RuntimeError is the bluntest option. Other choices include returning a message that says the task is incomplete, or making one last call with no tools so the model must summarize. Pick the behavior your users can recover from.
Common mistakes
| Symptom | Likely cause |
|---|---|
| API error about a `tool_result` with no matching `tool_use` | The assistant message was not appended, or the ids do not match |
| API error about missing results | Fewer `tool_result` blocks than `tool_use` blocks in the previous turn |
| Model ignores a tool's output | Result text is empty because the tool returned only non-text content |
| Loop stops after one pass with no answer | `stop_reason` was `max_tokens`, so the reply was cut off |
| Same call repeats until the limit | The error text gives the model nothing to correct, or the tool schema is unclear |
Checking your work
Run the script and you should see a final answer that mentions 5. To confirm the loop really ran, print block.name and block.input inside the inner loop. You should see one call to add with {"a": 2, "b": 3}. If the model answers without calling the tool, the loop still works. Make the prompt more explicit, or ask for a calculation the model cannot do reliably in its head.
Exercise
The model returns two tool_use blocks in one response, and your loop sends back two separate user messages, one tool_result each. What happens, and how do you fix it?
Show answer
The API rejects the second request, or the model sees an incomplete set of results for its previous turn. Every tool_result for one assistant turn must be in a single user message. Collect all results in a list inside the loop over blocks, then append one message with {"role": "user", "content": results} after the loop, as the example does.
Exercise
Why does the loop append the assistant message before checking stop_reason, and what breaks if you append only the text?
Show answer
The final turn needs the assistant message for history, and intermediate turns need it because the next request must contain the tool_use blocks that the tool_result blocks answer. With only the text, the tool_result ids refer to requests the model cannot see, and the API returns a validation error.
Exercise
A tool returns isError=True with the text "city not found". Should the loop stop? What should it send to the model?
Show answer
The loop should not stop. It sends a tool_result with the error text and is_error set to true. The model can then correct its arguments, try another tool, or tell the user. The step limit still bounds how many retries it can make.