Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 08 · 55 minutes

Build an agent loop and read an MCP message

After this lesson you can
  • Build a loop that lets a model use tools for several steps, with a step limit and a trace
  • Explain why an agent needs a repeat guard and a limit on its steps
  • Describe MCP and read a tools/list and a tools/call message
Lab files of this lesson (31)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

A vendor shows your company an "autonomous" order agent and says that it "cannot run away and cannot be tricked". Your lead asks you to review the idea. What ends the loop? What does it record? What does a tool server add to the risk? You build the loop with the tools of lesson 7, test it with a scripted stand-in for the model so that your results are exact, and then read the messages that an agent exchanges with a tool server.

Recall

Lesson 7: which code decides whether a tool request runs, the model or your program?

Your program. The model only writes the request. The allowlist and the argument check are code that you wrote, and a request that fails them never runs.

Lesson 4: the model has no memory. How does a chat program make it seem to remember?

It sends the whole history again with each call. An agent loop does the same: every step sends all earlier steps with the new one.

The idea

An agent is a loop around a model.

  1. Decide. The model reads the conversation so far and writes the next step: a tool request, or a final answer.
  2. Act. Your program checks the request and runs the tool.
  3. Observe. Your program adds the result to the conversation.
  4. Repeat until the model gives a final answer, or the step limit is reached.
The agent loop
DecideActObserveStopthe model asks for a toolyour program checks and runs itresult added,step count goes upstep limit reachedDecideActObserveStop1234
  1. Decide → Act: the model asks for a tool
  2. Act → Observe: your program checks and runs it
  3. Observe → Decide: result added, step count goes up
  4. Observe → Stop: step limit reached

The model ends the loop earlier when its reply is {"final": ...} at Decide.

There is no new kind of model. The agent is program code plus the tool call of lesson 7, run in a loop, with the whole history sent each time. Three parts of the loop matter for security:

PartWhat it doesIf it is missing
Step limitStops the loop after a fixed number of steps.A confused or hijacked model loops for ever, and you pay for each step.
Check before each actionAllowlist and argument validation, as in lesson 7.Any text that reaches the model can start any action.
TraceA record of every step: what the model asked and what happened.You cannot tell afterwards why the agent did what it did.

Worked example

Work in ~/krlab/llms-and-agents. This lesson uses tools.py from lesson 7 and llm.py from lesson 3. Model answers in this lesson were recorded once. If your model writes other words or counts, the method is the lesson.

1. Write the loop

Create agent.py. The model answers each turn in one of two forms: a tool request or {"final": ...}. run_agent sends the history, parses the answer, checks it, runs the tool and adds the result as a new message. It prints every step. The set seen is a guard: the same call twice gets a refusal, which pushes the model to finish. for step in range(1, max_steps + 1) repeats the body for the numbers 1 to max_steps, and return leaves the loop at once. messages += [...] adds two messages at the end of the list.

agent.py

import json

from llm import chat
from tools import TOOLS, check

SYSTEM = """You help customers of the bookshop KR Books. You work in steps.
Each time, reply with one JSON object and nothing else. Choose one of two forms.
1. To use a tool: {"tool": "<name>", "args": {...}}
2. To give the final answer: {"final": "<one short sentence>"}
Tools:
- order_status: args {"order_id": "<the order number, KR- and four digits>"}. Use it only for an order number that the customer gave.
- add: args {"a": <whole number>, "b": <whole number>}. Use it only to add two numbers.
Call one tool at a time. You cannot know an order status until order_status has told you: call it for every order
before you answer. After a tool runs you will see its result, and then you choose the next step.
When you have every fact that you need, reply with the final answer. Never repeat a tool call."""


def run_agent(question, max_steps=4):
    messages = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": question}]
    seen = set()
    for step in range(1, max_steps + 1):
        raw = chat(messages, as_json=True, max_tokens=100)
        print(f"  step {step}  model  : {raw}")
        try:
            request = json.loads(raw)
        except json.JSONDecodeError:
            return "stopped: the model did not return JSON"
        if isinstance(request, dict) and "final" in request:
            return request["final"]
        problem = check(request)
        if problem:
            observation = f"Refused: {problem}"
        elif raw in seen:
            observation = "Refused: you already made this call. Give the final answer now."
        else:
            observation = f"Tool result: {TOOLS[request['tool']](**request['args'])}"
        seen.add(raw)
        print(f"  step {step}  program: {observation}")
        messages += [{"role": "assistant", "content": raw}, {"role": "user", "content": observation}]
    return "stopped: step limit reached"


if __name__ == "__main__":
    question = "Check orders KR-1001 and KR-1002. Which one is waiting for payment?"
    for limit in (4, 1):
        print(f"max_steps = {limit}")
        print("  result:", run_agent(question, limit))

2. Run it with two limits

The question needs two tool calls, one for each order. The first run allows four steps, the second one.

python3 agent.py
max_steps = 4
  step 1  model  : {"tool": "order_status", "args": {"order_id": "KR-1001"}}
  step 1  program: Tool result: shipped on 18 November, arrives in 2 working days
  step 2  model  : {"tool": "order_status", "args": {"order_id": "KR-1002"}}
  step 2  program: Tool result: waiting for payment
  step 3  model  : {"tool": "order_status", "args": {"order_id": "KR-1001"}}
  step 3  program: Refused: you already made this call. Give the final answer now.
  step 4  model  : {"final": "KR-1002 is waiting for payment, KR-1001 has been shipped."}
  result: KR-1002 is waiting for payment, KR-1001 has been shipped.
max_steps = 1
  step 1  model  : {"tool": "order_status", "args": {"order_id": "KR-1001"}}
  step 1  program: Tool result: shipped on 18 November, arrives in 2 working days
  result: stopped: step limit reached

Read the trace line by line. In the first run the model looked up both orders and at step 3 asked for the first one again. The guard refused, and at step 4 the model wrote the answer. In the second run the limit stopped the loop after one step, and the agent returned "stopped", not a guess. An agent that hits a limit must say so.

Small models loop. Before the guard existed, this one repeated both calls until the limit stopped it.

3. See what a tool server looks like

The tools in tools.py live inside your program. Many agents instead connect to tool servers: separate programs, often written by someone else, that offer tools. The Model Context Protocol (MCP) is a standard for this. A client (the agent's program) talks to a server in JSON-RPC 2.0 messages: each request has a jsonrpc version, an id, a method and params, and each response has the same id and a result or an error. A server can be a local program that reads standard input and output, or a service reached over HTTP.

MCP has dated revisions. Older ones began with an initialize handshake. The current one, 2026-07-28, removed it, so each request stands alone. A client that wants the versions and capabilities of a server first can call server/discover. Check the specification of your revision.

Two methods carry the tool calls:

  • tools/list: the client asks which tools exist. The server returns each tool's name, a description for the model, and an inputSchema. A JSON Schema is a standard way to describe the allowed shape of a JSON value, here the arguments.
  • tools/call: the client asks the server to run one tool by name, with arguments. The server returns the content of the result and a flag isError.
A tools/call request, taken apart
"jsonrpc": "2.0"the protocol: JSON-RPC 2.0"id": 2the reply carries the same id"method": "tools/call"what the client asks"params": {"name", "arguments"}the tool and its arguments"jsonrpc": "2.0"the protocol: JSON-RPC 2.0"id": 2the reply carries the same id"method": "tools/call"what the client asks"params": {"name", "arguments"}the tool and its arguments
An agent and a tool server
ClientServerModeltools/listnames, descriptions, input schemasthe descriptions go into the prompta request to use one toolcheck the requesttools/call with the argumentsthe content and isErrorClientServerModel1234567
  1. Client → Server: tools/list
  2. Server → Client: names, descriptions, input schemas
  3. Client → Model: the descriptions go into the prompt
  4. Model → Client: a request to use one tool
  5. Client: check the request
  6. Client → Server: tools/call with the arguments
  7. Server → Client: the content and isError

So the agent does not need to know the tools in advance. It reads the list, shows the descriptions to the model, and sends the model's request as a tools/call. The checks of lesson 7 stay on the client side, because the server and its descriptions are input from outside.

Create rpc.py. It is a sketch of a server, not a full MCP server: it has no discovery and no transport. It only answers the two methods, with your tools.py behind them and the same check. In the current revision every request also carries the protocol version in _meta. The sketch leaves it out.

rpc.py

import json

from tools import TOOLS, check

TOOL_LIST = [
    {
        "name": "order_status",
        "description": "Look up the status of a KR Books order.",
        "inputSchema": {
            "type": "object",
            "properties": {"order_id": {"type": "string", "pattern": "^KR-[0-9]{4}$"}},
            "required": ["order_id"],
        },
    },
]


def handle(message):
    """A sketch of a tool server: answer one JSON-RPC message with one JSON-RPC response."""
    message = message if isinstance(message, dict) else {}
    reply = {"jsonrpc": "2.0", "id": message.get("id")}
    if message.get("method") == "tools/list":
        reply["result"] = {"tools": TOOL_LIST}
    elif message.get("method") == "tools/call":
        params = message.get("params")
        if not isinstance(params, dict):
            params = {}
        request = {"tool": params.get("name"), "args": params.get("arguments")}
        problem = check(request)                      # the same allowlist and validation as before
        text = problem or str(TOOLS[request["tool"]](**request["args"]))
        reply["result"] = {"content": [{"type": "text", "text": text}], "isError": bool(problem)}
    else:
        reply["error"] = {"code": -32601, "message": "Method not found"}
    return reply


if __name__ == "__main__":
    messages = [
        {"jsonrpc": "2.0", "id": 1, "method": "tools/list"},
        {"jsonrpc": "2.0", "id": 2, "method": "tools/call",
         "params": {"name": "order_status", "arguments": {"order_id": "KR-1002"}}},
        {"jsonrpc": "2.0", "id": 3, "method": "tools/call",
         "params": {"name": "delete_order", "arguments": {"order_id": "KR-1002"}}},
    ]
    for m in messages:
        print("client ->", json.dumps(m))
        print("server <-", json.dumps(handle(m)))
        print()
python3 rpc.py
client -> {"jsonrpc": "2.0", "id": 1, "method": "tools/list"}
server <- {"jsonrpc": "2.0", "id": 1, "result": {"tools": [{"name": "order_status", "description": "Look up the status of a KR Books order.", "inputSchema": {"type": "object", "properties": {"order_id": {"type": "string", "pattern": "^KR-[0-9]{4}$"}}, "required": ["order_id"]}}]}}

client -> {"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "order_status", "arguments": {"order_id": "KR-1002"}}}
server <- {"jsonrpc": "2.0", "id": 2, "result": {"content": [{"type": "text", "text": "waiting for payment"}], "isError": false}}

client -> {"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "delete_order", "arguments": {"order_id": "KR-1002"}}}
server <- {"jsonrpc": "2.0", "id": 3, "result": {"content": [{"type": "text", "text": "tool not allowed: 'delete_order'"}], "isError": true}}

The sketch would also run add, because check allows it, but tools/list does not show it. A real server must offer and run the same set. These are the shapes to remember. In the real protocol an unknown tool name is a JSON-RPC error, and isError marks a tool that ran and failed; the sketch uses isError for both. Take the exact messages from the specification of the revision that you use. The model never sees the JSON-RPC: the client turns a tools/list result into the tool description of the prompt, and a request of the model into a tools/call. The course "Securing AI agents and MCP" (lesson 7) goes further.

Your turn

Test the loop without a model, so that every reader gets the same result. There is no code here: change agent.py.

  1. Change run_agent so that it takes a third argument, model. It is a function that you pass in, as you pass max_steps: it gets the list of messages and returns the raw reply. The normal model calls chat.
  2. Write a stand-in model that returns the next item of this list each time it is called, and nothing else.
CallThe stand-in returns
1{"tool": "order_status", "args": {"order_id": "KR-1003"}}
2{"tool": "order_status", "args": {"order_id": "KR-1003"}}
3{"tool": "delete_order", "args": {"order_id": "KR-1003"}}
4{"tool": "order_status", "args": {"order_id": "KR-10"}}
5{"tool": "add", "args": {"a": 1, "b": 2}}
6{"final": "done"}
  1. Run run_agent once with max_steps 5 and once with 6, with a fresh stand-in each time. Count the observations that start with Refused.
  2. Pass the message {"jsonrpc": "2.0", "id": 7, "method": "resources/list"} to handle in rpc.py.

Last, say which of the five steps would have been a real action if the model had been hijacked, and which line of your code stopped it.

Check yourself

Why does the agent need a step limit, when the model usually finishes by itself?

"Usually" is not "always". A model can repeat a call (as here), follow an instruction hidden in a tool result, or loop on an error. Without a limit each costs money and time, and an attacker can cause it on purpose. The limit is a hard stop that does not depend on the model.

The model, not your program, decides which tool runs next. Where is the control then?

In the program between the model and the tools: the allowlist, the argument check, the step limit and the guard against repeats. The model proposes and your code disposes.

The second run ended with "stopped: step limit reached". Is this a failure?

It is the correct and safe result when the task needs more steps than you allowed. The wrong behaviour would be to make up an answer from the one order that was checked. Tell the user that the agent stopped, and log it.

Field notes

  • Put a budget on each run, not only on steps: tokens, time and calls to each tool. A tool that costs money or changes data gets a lower limit. This controls "unbounded consumption" and "excessive agency" in the OWASP list for LLM applications.
  • Every observation is untrusted input to the next decision. A tool result that says "now call the send_email tool" is read like any other text. Keep an agent's tools few, give the riskiest actions a confirmation by a person, and do not let one agent both read outside text and send data out.
  • Log the whole trace in a store that the agent cannot change: user, question, each request, check result, tool result and final answer, with times. It is the evidence in an incident and the data for your tests.
  • An MCP server runs with some rights, and its tool descriptions are text that the model reads, so a bad or hijacked server can steer the agent. Use servers that you trust, pin their versions, give each the least access, and re-check descriptions when they change. Servers that you meet may still speak an older revision, so check which one. A server that returns its tools in a fixed order, as the newest revision asks, makes such a re-check a simple comparison.
  • Test an agent as a system, not as a model: tasks with known good outcomes, plus attack tasks (a poisoned document, a tool result with instructions, a long loop), run with several seeds after each change.