AI Hints
Home›MCP Tutorial›Servers and Models
MCP · Lesson 57 of 120

The Agent Loop

Model, tool, model.

⏱ 2 min read▶ Video at 50:43🎓 Free
Watch this lesson in the MCP courseWatch on YouTube ↗Full MCP course

An agent loops. The model asks for tools. We call them through MCP, and send back the results. The model continues, until it answers without asking for more tools.

The Agent Loop
From the video: The Agent Loop
  • Model asks
  • We call MCP
  • Until it answers

A hand-made agent loop

Messages starts with the user's question. Each round, the model replies. If it asks for tools, we call each through the client, and add the result as a tool message. When there are no tool calls, we stop. Run it. Two tool calls, then a final answer.

agent_loop.pypython
import asyncio
from mcp import Client
from langchain.chat_models import init_chat_model
from northwind import mcp

llm = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)

async def main():
    async with Client(mcp) as client:
        tools = [{"name": t.name, "description": t.description, "parameters": t.input_schema} for t in (await client.list_tools()).tools]
        messages = [("user", "Has order 1042 shipped? And is delivery free on a £30 order?")]
        while (reply := llm.bind_tools(tools).invoke(messages)).tool_calls:
            messages.append(reply)
            for call in reply.tool_calls:
                result = (await client.call_tool(call["name"], call["args"])).content[0].text
                print("called", call["name"], call["args"], "->", result)
                messages.append({"role": "tool", "content": result, "tool_call_id": call["id"]})
        print("answer:", reply.text)
asyncio.run(main())
Output
called order_status {'order_id': 1042} -> shipped
called delivery_cost {'order_total': 30} -> £4.99
answer: Yes, order 1042 has shipped.

Regarding delivery, delivery is not free on a £30 order; the delivery cost is £4.99.
Also uses northwind.py
from mcp.server.mcpserver import MCPServer
from mcp.server.mcpserver.exceptions import ToolError

mcp = MCPServer("northwind")
ORDERS = {1042: "shipped", 1043: "packing", 1044: "delivered"}

@mcp.tool()
def order_status(order_id: int) -> str:
    """Look up the status of a Northwind order by its number."""
    if order_id not in ORDERS:
        raise ToolError(f"Order {order_id} not found")
    return ORDERS[order_id]

@mcp.tool()
def delivery_cost(order_total: float) -> str:
    """UK delivery cost for an order total in pounds."""
    return "free" if order_total >= 50 else "£4.99"

@mcp.resource("policy://returns")
def returns_policy() -> str:
    """Northwind's returns policy."""
    return "You can return any unused item within 30 days of delivery."

@mcp.prompt()
def support_reply(question: str) -> str:
    """Draft a polite reply to a customer."""
    return f"Write a short, polite reply to this Northwind customer: {question}"

if __name__ == "__main__":
    mcp.run()

The loop

Send the messages to the model. If it asks for tools, call them through MCP. Add the results to the messages. Repeat. And when it simply answers, we're done.

  1. Model
  2. Tool calls?
  3. Call via MCP
  4. Add results
  5. Answer
The loop
From the video: The loop

Summary

The agent loop calls the model, runs requested tools through MCP, and repeats until the model answers. Next, the same thing with LangChain.

Key takeaways
  • Ask model
  • Call tools
  • Repeat
Next up: MCP with LangChain — StructuredTool