Skip to content
MCPA · Chapter 7 of 21 Day 5: Tools in detail – lifecycle, errors, consent, handles

Day 5: Tools in detail – lifecycle, errors, consent, handles

Goal: Know the full lifecycle of a tool call, write error messages a model can keep working with, run state-changing tools only with consent, and model state with handles instead of sessions · Duration: about 3 h · Prerequisite: Day 4

Where we start

# on cp1, in ~/mcpa/tag04
uv run python host.py "Wie viel Prozent der Platte sind belegt?" 2>>server.log | head -1

Expected:

[host] 4 Werkzeuge von 2 Servern: leitstand__speicher, leitstand__dienst, leitstand__groesste_dateien, handbuch__handbuch_suche

If host.py or handbuch.py is missing, create it as in Day 4, Drills 1 to 3.

Introduction

So far your tools have only read. In operations, though, tools should also do things: create an entry, restart a service, close a ticket. That makes every weakness in the flow expensive. A model that gives up or guesses on an error delivers wrong answers; a host that runs state-changing tools without asking does damage.

So today you build in three things every serious deployment needs: error messages a model can learn from, human consent before state-changing calls, and a tool with state – an operations log (betriebsbuch) whose entries get a number you can use to find them later. Along the way you learn how MCP still knows state without sessions.

Today you learn:

  • the steps in the lifecycle of a tool call and who is responsible for each,
  • what the model sees on an expected error (ToolError) and on a crash,
  • what an error message looks like that lets a model correct itself,
  • how a host asks for consent before state-changing tools and why it must not rely on annotations for this,
  • how handles carry state across several calls without sessions,
  • what idempotent means and why it matters for retries.

Background

The picture for today: ordering services in a hotel

Since Day 4 your host has been the front desk of a hotel. The servers are outside service providers: maintenance, the library and, from today, the front desk’s log book. Each provider offers services – those are the tools. The guest (the model) picks from the list and fills in the order slip; the front desk passes it on.

Today three rules of a good hotel are added:

  • The guest’s signature: Anything that changes something or costs money is only carried out once the human has signed. For “just looking something up” the front desk skips this – but only for providers it has checked itself.
  • Helpful feedback: “Doesn’t work” helps nobody. “Room 7 does not exist, we have 1 and 2” does – the guest can order again with that.
  • The claim ticket: Whoever hands in laundry gets a ticket with a number. Later they collect their things with that number. The front desk does not have to remember the guest – the number carries the state. That is a handle.

The terms

Term Meaning in the picture
Tool function a server offers and the model can call service you can order
Annotation the server’s hint about behavior (readOnlyHint …) the provider’s note on the price list
Consent the human confirms a call that changes something the guest’s signature
ToolError expected error with an explanation for the model helpful feedback
Crash unexpected error, details only in the log “doesn’t work”, the cause in the back office
Handle identifier that later calls pass as an argument claim ticket
idempotent running it several times has the effect of running it once “check out room 1” – the second time it is already checked out

Remember: The front desk believes a provider’s price list only if it has checked the provider itself. Everything else needs the guest’s signature.

The lifecycle of a tool call

From discovery to result, a tool always passes through the same stations:

Station What happens Responsible
Discover tools/list returns names, descriptions, schemas client, server
Select The model decides whether a tool helps, and which one model
Build arguments The model fills in the arguments according to the inputSchema model
Check Does the tool exist? May it run without asking? Do the arguments fit? host; the server checks the arguments in any case
Consent For state-changing tools, the human decides human, via the host
Execute tools/call, the server does its work server
Result content, structuredContent or isError: true with an explanation server
Pass on Result or error goes back into the conversation host
Correct The model reads the error and tries something else model

The specification explicitly requires a human in the loop for tools: hosts should show which tools exist, show before a call which tool is about to run with which arguments, and ask for confirmation where changes are involved. And they should return execution errors to the model so it can correct itself.

What the model sees on errors

The Python SDK distinguishes three cases:

  • ToolError – an error you anticipated. You raise it with raise ToolError("…"). The result has isError: true, and your message is in content, prefixed by the SDK with “Error executing tool <name>:”.
  • Crash – any other exception, such as a FileNotFoundError that nobody caught. The model then sees only “Error executing tool <name>”. The actual cause is in the server’s log. This is intentional: internal details such as paths, table names, or credentials should not leak out through an error message.
  • MCPError – a protocol error that goes back as a JSON-RPC error with a code. You rarely need this yourself.

This gives you a rule: Errors a model can do something with, you catch and report as ToolError. A good message answers three questions: What went wrong? Why? What should the caller do instead? “Eintrag 7 gibt es nicht. Vorhandene Nummern: 1, 2.” (“Entry 7 does not exist. Existing numbers: 1, 2.”) is a good message. “Error executing tool eintrag_lesen” is not.

State without sessions: handles

Since 2026-07-28, MCP no longer has sessions. A server must not remember “who” is talking to it, and every request must be understandable on its own. Still, many workflows need state: a shopping cart is filled, a maintenance window is opened and later closed, an entry is created and later extended.

The specification recommends handles for this: a tool that creates something returns an identifier – a number or a random string – and later tools receive this identifier as a perfectly normal argument. The state lives on the server (in a file or database), the reference to it lives in the conversation. Two rules apply to handles:

  • The server checks on every call whether the handle is valid and whether the caller may use it.
  • If the handle acts like a key – whoever knows it can do something with it – it must be opaque and hard to guess, that is random and long, not a sequential number.

Today’s operations log uses simple numbers because it is only a lab and everyone may read all entries. In Days 12 and 13 the question of who is calling is added.

Idempotence

A tool is idempotent if calling it several times with the same arguments has no more effect than calling it once. “Delete entry 1” is idempotent: the second time it is already gone, nothing else happens. “Create entry” is not: every call creates another entry. This matters when a connection drops and a client retries a call – without sessions it does not know whether the first one arrived. The idempotentHint annotation tells the host whether that is safe.

Consent: whom does the host believe?

Annotations such as readOnlyHint are an obvious way to decide whether the host has to ask. But they come from the server – and a malicious server can present a delete tool as “read-only”. The host in Drill 4 therefore combines two conditions: a tool runs without asking only if it is marked read-only and comes from a server on the host’s own trust list. Everything else asks the human.

Drill 1: The operations log

Where you are: on cp1, in the directory ~/mcpa/tag05.

What you have afterwards: betriebsbuch.py, a server with three tools to create, read, and delete entries.

Step 1 – Create the directory. Every day gets its own directory so the states of earlier days are kept.

# on cp1
mkdir -p ~/mcpa/tag05
  • -p creates missing parent directories as well and reports no error if the directory already exists.
# on cp1
cd ~/mcpa/tag05

Step 2 – Fetch the servers of earlier days. Copy the control room and the manual here; today you change the control room, the Day 3 version stays untouched.

# on cp1, in ~/mcpa/tag05
cp ~/mcpa/tag03/leitstand.py ~/mcpa/tag04/handbuch.py .

cp with several sources and a directory at the end (. = here) copies all sources there.

Step 3 – Write the server. Create the file in nano:

# on cp1, in ~/mcpa/tag05
nano betriebsbuch.py
~/mcpa/tag05/betriebsbuch.py new file
import json
from datetime import datetime
from pathlib import Path
from typing import Annotated

from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
from mcp.types import ToolAnnotations
from pydantic import BaseModel, Field

DATEI = Path(__file__).with_name("betriebsbuch.json")

mcp = MCPServer(
    name="betriebsbuch",
    version="1.0.0",
    instructions="Betriebsbuch des Labors: Einträge zu Störungen und Wartungen anlegen, lesen und löschen.",
)


class Eintrag(BaseModel):
    id: int = Field(description="Nummer des Eintrags; damit liest oder löscht man ihn später")
    zeit: str
    titel: str
    text: str


def laden() -> dict[str, dict]:
    return json.loads(DATEI.read_text()) if DATEI.exists() else {}


def speichern(daten: dict[str, dict]) -> None:
    DATEI.write_text(json.dumps(daten, ensure_ascii=False, indent=2))


@mcp.tool(
    title="Eintrag anlegen",
    annotations=ToolAnnotations(read_only_hint=False, destructive_hint=False, idempotent_hint=False, open_world_hint=False),
)
def eintrag_anlegen(
    titel: Annotated[str, Field(min_length=3, max_length=80)],
    text: Annotated[str, Field(max_length=2000)],
) -> Eintrag:
    """Legt einen neuen Eintrag im Betriebsbuch an und liefert ihn mit seiner Nummer (id)."""
    daten = laden()
    neue_id = max((int(k) for k in daten), default=0) + 1
    eintrag = Eintrag(id=neue_id, zeit=datetime.now().isoformat(timespec="seconds"), titel=titel, text=text)
    daten[str(neue_id)] = eintrag.model_dump()
    speichern(daten)
    return eintrag


@mcp.tool(title="Eintrag lesen", annotations=ToolAnnotations(read_only_hint=True, open_world_hint=False))
def eintrag_lesen(id: int) -> Eintrag:
    """Liefert einen Eintrag des Betriebsbuchs anhand seiner Nummer (id)."""
    daten = laden()
    if str(id) not in daten:
        vorhanden = ", ".join(daten) or "keine"
        raise ToolError(f"Eintrag {id} gibt es nicht. Vorhandene Nummern: {vorhanden}.")
    return Eintrag(**daten[str(id)])


@mcp.tool(
    title="Eintrag löschen",
    annotations=ToolAnnotations(read_only_hint=False, destructive_hint=True, idempotent_hint=True, open_world_hint=False),
)
def eintrag_loeschen(id: int) -> str:
    """Löscht einen Eintrag des Betriebsbuchs endgültig."""
    daten = laden()
    if daten.pop(str(id), None) is None:
        return f"Eintrag {id} war schon gelöscht oder gab es nie."
    speichern(daten)
    return f"Eintrag {id} gelöscht."


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

The new parts:

  • Path(__file__).with_name("betriebsbuch.json") – the path to the data file, in the same directory as the program. __file__ is the path of the running Python file, with_name replaces the file name. This way the server finds its data no matter which directory it is started from.
  • from mcp.server.mcpserver.exceptions import ToolError – the exception for expected errors.
  • laden() (load) reads the JSON file into a dictionary (key = number as text, value = entry) or returns an empty one if the file does not exist yet. speichern() (save) writes it back; indent=2 indents so humans can read the file.
  • eintrag_anlegen (create entry) – the annotations say: changes something (read_only_hint=False), but destroys nothing (destructive_hint=False, it only adds), is not idempotent (idempotent_hint=False). min_length=3 and max_length limit title and text. max((int(k) for k in daten), default=0) + 1 takes the highest existing number plus one; default=0 covers an empty log. datetime.now().isoformat(timespec="seconds") returns the time in the format 2026-11-28T10:53:36. eintrag.model_dump() turns the Pydantic object into a dictionary for saving. What comes back is the whole entry including its number – the handle.
  • eintrag_lesen (read entry) – read-only. If the number does not exist, raise ToolError(…) reports this with the list of existing numbers. ", ".join(daten) or "keine" yields "keine" (“none”) if the list is empty. Eintrag(**daten[str(id)]) builds the object from the stored dictionary; ** passes its fields as named arguments.
  • eintrag_loeschen (delete entry) – destructive (destructive_hint=True) and idempotent (idempotent_hint=True). daten.pop(str(id), None) removes the entry and returns it – or None if it did not exist. In that case this is not an error but a normal response: the goal “entry 1 is gone” has been reached.

Remember: A tool that creates something returns the claim ticket. All later tools get it as a perfectly normal argument.

Save your progress? Sign up for free

Drill 2: Error messages that help

Where you are: on cp1, in the directory ~/mcpa/tag05.

What you have afterwards: leitstand.py in version 1.2.0, which explains what to do when given a wrong path.

In Day 4, Drill 6, the model called speicher with the path /cp1 and got back only “Error executing tool speicher” – a crash, because nobody caught the FileNotFoundError. Now the control room should give feedback the guest can use to order again.

Step 1 – Open the file.

# on cp1, in ~/mcpa/tag05
nano leitstand.py

Step 2 – Change three places. This is what the file looks like afterwards; the green lines are new or changed:

~/mcpa/tag05/leitstand.py changes in green
import shutil
import subprocess
from typing import Annotated, Literal

from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
from mcp.types import ToolAnnotations
from pydantic import BaseModel, Field

mcp = MCPServer(
    name="leitstand",
    version="1.2.0",
    instructions="Werkzeuge für den Betrieb der Labor-Rechner: Plattenplatz, Laufzeit, Dienste.",
)


class Speicher(BaseModel):
    """Belegung eines Dateisystems."""

    pfad: str
    gesamt: float = Field(description="Größe des Dateisystems in der gewählten Einheit")
    frei: float = Field(description="Freier Platz in der gewählten Einheit")
    einheit: Literal["GB", "MB"]
    belegt_prozent: float = Field(ge=0, le=100)


class Dienst(BaseModel):
    """Zustand eines systemd-Dienstes."""

    name: str
    aktiv: bool
    zustand: str = Field(description="ActiveState von systemd, z. B. active, inactive, failed")
    seit: str | None = Field(default=None, description="Zeitpunkt des letzten Zustandswechsels")


@mcp.tool(
    title="Plattenplatz",
    annotations=ToolAnnotations(read_only_hint=True, open_world_hint=False),
)
def speicher(
    pfad: Annotated[str, Field(description="Verzeichnis, dessen Dateisystem geprüft wird")] = "/",
    einheit: Literal["GB", "MB"] = "GB",
) -> Speicher:
    """Liefert Größe, freien Platz und Belegung des Dateisystems unter einem Pfad."""
    teiler = 1024**3 if einheit == "GB" else 1024**2
    try:
        nutzung = shutil.disk_usage(pfad)
    except FileNotFoundError:
        raise ToolError(
            f"Den Pfad {pfad} gibt es auf diesem Rechner nicht. Das Werkzeug misst immer auf dem Rechner, "
            "auf dem der Server läuft; der Rechnername gehört nicht in den Pfad. "
            "Rufe das Werkzeug erneut mit pfad=/ auf, um das Wurzeldateisystem zu messen."
        ) from None
    return Speicher(
        pfad=pfad,
        gesamt=round(nutzung.total / teiler, 1),
        frei=round(nutzung.free / teiler, 1),
        einheit=einheit,
        belegt_prozent=round(nutzung.used / nutzung.total * 100, 1),
    )


@mcp.tool(
    title="Dienststatus",
    annotations=ToolAnnotations(read_only_hint=True, open_world_hint=False),
)
def dienst(
    name: Annotated[str, Field(pattern=r"^[a-zA-Z0-9@._-]+$", max_length=64, description="Name der systemd-Unit, z. B. ollama")],
) -> Dienst:
    """Liefert den Zustand eines systemd-Dienstes auf diesem Rechner."""
    ausgabe = subprocess.run(
        ["systemctl", "show", name, "--property=ActiveState,StateChangeTimestamp"],
        capture_output=True, text=True, check=True,
    ).stdout
    werte = dict(zeile.split("=", 1) for zeile in ausgabe.strip().splitlines())
    return Dienst(
        name=name,
        aktiv=werte["ActiveState"] == "active",
        zustand=werte["ActiveState"],
        seit=werte.get("StateChangeTimestamp") or None,
    )


@mcp.tool(title="Größte Dateien", annotations=ToolAnnotations(read_only_hint=True))
def groesste_dateien(
    verzeichnis: str,
    anzahl: Annotated[int, Field(ge=1, le=20)] = 5,
) -> list[str]:
    """Listet die größten Dateien unterhalb eines Verzeichnisses, größte zuerst."""
    ausgabe = subprocess.run(
        ["find", verzeichnis, "-xdev", "-type", "f", "-printf", "%s %p\n"],
        capture_output=True, text=True,
    ).stdout
    zeilen = sorted(ausgabe.splitlines(), key=lambda z: int(z.split(" ", 1)[0]), reverse=True)
    return [z.split(" ", 1)[1] for z in zeilen[:anzahl]]


if __name__ == "__main__":
    mcp.run()
  • Line 6: ToolError is the exception for expected errors.
  • Line 12: the version goes up to 1.2.0 because the behavior changes.
  • Lines 46–53: try: … except FileNotFoundError: catches exactly this error; all others remain crashes.
  • The message answers the three questions: what (the path does not exist), why (the host name does not belong in the path), what to do (call again with pfad=/).
  • Python joins two strings in parentheses written directly after each other into one; this keeps the line readable.
  • from None suppresses the reference to the original exception in the log – it is expected here.

Step 3 – Check. diff compares your file with the Day 3 version:

# on cp1, in ~/mcpa/tag05
diff ~/mcpa/tag03/leitstand.py leitstand.py

diff shows the differences between two files: < precedes lines of the first file, > lines of the second; 5a6 means “after line 5 of the first file, line 6 of the second is added”, 11c12 “line 11 was changed to line 12”.

Expected:

5a6
> from mcp.server.mcpserver.exceptions import ToolError
11c12
<     version="1.1.0",
---
>     version="1.2.0",
45c46,53
<     nutzung = shutil.disk_usage(pfad)
---
>     try:
>         nutzung = shutil.disk_usage(pfad)
>     except FileNotFoundError:
>         raise ToolError(
>             f"Den Pfad {pfad} gibt es auf diesem Rechner nicht. Das Werkzeug misst immer auf dem Rechner, "
>             "auf dem der Server läuft; der Rechnername gehört nicht in den Pfad. "
>             "Rufe das Werkzeug erneut mit pfad=/ auf, um das Wurzeldateisystem zu messen."
>         ) from None

Exactly the three changes, nothing else.

Remember: A good error message says what went wrong, why, and what the caller should do instead – then the model can order again.

Save your progress? Sign up for free

Drill 3: The host with consent

Where you are: on cp1, in the directory ~/mcpa/tag05.

What you have afterwards: host.py, which connects three servers and asks before state-changing calls.

Create the host anew:

# on cp1, in ~/mcpa/tag05
nano host.py
~/mcpa/tag05/host.py new file
import asyncio
import json
import sys
from contextlib import AsyncExitStack

import httpx
from mcp import Client, StdioServerParameters

OLLAMA = "http://localhost:11434/api/chat"
MODELL = "qwen3:4b-instruct"

SERVER = {
    "leitstand": StdioServerParameters(command="uv", args=["run", "python", "leitstand.py"]),
    "handbuch": StdioServerParameters(command="uv", args=["run", "python", "handbuch.py"]),
    "betriebsbuch": StdioServerParameters(command="uv", args=["run", "python", "betriebsbuch.py"]),
}
VERTRAUT = {"leitstand", "handbuch", "betriebsbuch"}


async def werkzeuge_sammeln(clients: dict[str, Client]) -> tuple[list[dict], dict[str, tuple[str, str]], set[str]]:
    """Fragt alle Server nach ihren Werkzeugen und übersetzt sie ins Format von Ollama."""
    fuer_modell: list[dict] = []
    zuordnung: dict[str, tuple[str, str]] = {}
    ohne_rueckfrage: set[str] = set()
    for servername, client in clients.items():
        for tool in (await client.list_tools()).tools:
            voller_name = f"{servername}__{tool.name}"
            zuordnung[voller_name] = (servername, tool.name)
            nur_lesend = tool.annotations is not None and tool.annotations.read_only_hint is True
            if servername in VERTRAUT and nur_lesend:
                ohne_rueckfrage.add(voller_name)
            fuer_modell.append({
                "type": "function",
                "function": {
                    "name": voller_name,
                    "description": tool.description or "",
                    "parameters": tool.input_schema,
                },
            })
    return fuer_modell, zuordnung, ohne_rueckfrage


def zustimmung(name: str, argumente: dict) -> bool:
    """Fragt den Menschen, ob ein Werkzeug laufen darf."""
    antwort = input(f"[host] {name} mit {json.dumps(argumente, ensure_ascii=False)} ausführen? [j/N] ")
    return antwort.strip().lower() == "j"


def systemanweisung(clients: dict[str, Client]) -> str:
    """Baut die Anweisung für das Modell aus den instructions der Server."""
    zeilen = [f"- {name}: {c.instructions}" for name, c in clients.items() if c.instructions]
    return (
        "Du bist ein Betriebsassistent auf dem Rechner cp1. Die Werkzeuge wirken auf diesem Rechner. "
        "Benutze so viele Werkzeuge wie nötig und erfinde keine Werte.\nVerbundene Server:\n"
        + "\n".join(zeilen)
    )


async def modell_fragen(http: httpx.AsyncClient, verlauf: list[dict], werkzeuge: list[dict]) -> dict:
    """Schickt das bisherige Gespräch samt Werkzeugen an Ollama und liefert die Antwort-Nachricht."""
    antwort = await http.post(OLLAMA, json={
        "model": MODELL, "stream": False, "messages": verlauf, "tools": werkzeuge,
    }, timeout=300)
    antwort.raise_for_status()
    return antwort.json()["message"]


async def main(frage: str) -> None:
    async with AsyncExitStack() as stapel:
        clients = {
            name: await stapel.enter_async_context(Client(parameter))
            for name, parameter in SERVER.items()
        }
        werkzeuge, zuordnung, ohne_rueckfrage = await werkzeuge_sammeln(clients)
        print(f"[host] {len(werkzeuge)} Werkzeuge von {len(clients)} Servern:", ", ".join(zuordnung))

        http = await stapel.enter_async_context(httpx.AsyncClient())
        verlauf: list[dict] = [
            {"role": "system", "content": systemanweisung(clients)},
            {"role": "user", "content": frage},
        ]

        for runde in range(1, 6):
            nachricht = await modell_fragen(http, verlauf, werkzeuge)
            verlauf.append(nachricht)
            aufrufe = nachricht.get("tool_calls") or []
            if not aufrufe:
                print(f"[modell] {nachricht['content']}")
                return
            for aufruf in aufrufe:
                name = aufruf["function"]["name"]
                argumente = aufruf["function"]["arguments"]
                print(f"[runde {runde}] Modell will {name} mit {json.dumps(argumente, ensure_ascii=False)}")
                if name not in zuordnung:
                    ergebnis_text = f"Unbekanntes Werkzeug: {name}"
                elif name not in ohne_rueckfrage and not zustimmung(name, argumente):
                    ergebnis_text = "Der Mensch hat diesen Aufruf abgelehnt. Führe ihn nicht noch einmal aus."
                else:
                    servername, werkzeug = zuordnung[name]
                    ergebnis = await clients[servername].call_tool(werkzeug, argumente)
                    ergebnis_text = "\n".join(b.text for b in ergebnis.content if b.type == "text")
                    if ergebnis.is_error:
                        ergebnis_text = "FEHLER: " + ergebnis_text
                print(f"[runde {runde}] Ergebnis: {ergebnis_text[:120]}")
                verlauf.append({"role": "tool", "tool_name": name, "content": ergebnis_text})
        print("[host] Abbruch nach 5 Runden ohne Antwort")


if __name__ == "__main__":
    asyncio.run(main(" ".join(sys.argv[1:])))

Compared with Day 4, four things have changed:

  • Three servers. SERVER now starts leitstand.py from the current directory and has gained the operations log.
  • Trust list. VERTRAUT (trusted) is a set ({…} with values without a colon) of the servers whose annotations the host believes. It belongs to the host, not to the servers.
  • werkzeuge_sammeln additionally returns the set ohne_rueckfrage (without asking). A tool goes into it if it comes from a trusted server and read_only_hint is set. tool.annotations is not None and tool.annotations.read_only_hint is True checks both without crashing on missing annotations; is True explicitly requires True – a missing value (None) does not count as “read-only”.
  • zustimmung (consent) asks on the console with input(…). Only a j (for “ja”, yes; case does not matter, spaces removed) counts as yes; everything else, including Enter, is no – a safe default.

In the loop, elif name not in ohne_rueckfrage and not zustimmung(name, argumente): checks – if a call is rejected, the model gets, instead of a result, the message “Der Mensch hat diesen Aufruf abgelehnt. Führe ihn nicht noch einmal aus.” (“The human rejected this call. Do not run it again.”) That way it knows it should neither fix an error nor try again.

Remember: The trust list belongs to the front desk, not to the providers. Only “read-only” and “trusted” together allow a call without a signature.

Save your progress? Sign up for free

Drill 4: An entry with consent

Where you are: on cp1, in the directory ~/mcpa/tag05.

What you have afterwards: entry 1 in the operations log.

Step 1 – Ask the host, with a signature.

# on cp1, in ~/mcpa/tag05
echo j | uv run python host.py "Lege im Betriebsbuch einen Eintrag an: Titel Ollama neu gestartet, Text Dienst hing nach Update, Neustart um 11 Uhr." 2>>server.log
  • 2>>server.log appends the servers’ messages (standard error) to a log file so they do not clutter the output.
  • echo j | answers the question in advance: the j waits on standard input and is read by input(). This makes the drill repeatable. In real use you type the answer yourself – leave out echo j | and answer when the question appears.

Expected (the wording of the answer differs):

[host] 7 Werkzeuge von 3 Servern: leitstand__speicher, leitstand__dienst, leitstand__groesste_dateien, handbuch__handbuch_suche, betriebsbuch__eintrag_anlegen, betriebsbuch__eintrag_lesen, betriebsbuch__eintrag_loeschen
[runde 1] Modell will betriebsbuch__eintrag_anlegen mit {"titel": "Ollama neu gestartet", "text": "Dienst hing nach Update, Neustart um 11 Uhr."}
[host] betriebsbuch__eintrag_anlegen mit {"titel": "Ollama neu gestartet", "text": "Dienst hing nach Update, Neustart um 11 Uhr."} ausführen? [j/N] [runde 1] Ergebnis: {
  "id": 1,
  "zeit": "2026-11-28T10:53:36",
  "titel": "Ollama neu gestartet",
  "text": "Dienst hing nach Update, Neu
[modell] Eintrag erfolgreich angelegt:

- **ID:** 1
- **Titel:** Ollama neu gestartet
- **Text:** Dienst hing nach Update, Neustart um 11 Uhr.

Der Eintrag ist nun im Betriebsbuch gespeichert und kann bei Bedarf abgerufen werden.

Step 2 – Look at what was stored.

# on cp1, in ~/mcpa/tag05
cat betriebsbuch.json

Expected (the time differs):

{
  "1": {
    "id": 1,
    "zeit": "2026-11-28T10:53:36",
    "titel": "Ollama neu gestartet",
    "text": "Dienst hing nach Update, Neustart um 11 Uhr."
  }
}

The host asked before running the tool – because eintrag_anlegen is not marked read-only. Because the answer came via echo, the result appears directly after the question on the same line. The model extracted title and text from your sentence and filled the fields according to the schema. The file betriebsbuch.json shows the stored entry with number 1 – the handle you use to address it from now on.

Remember: Services that change something only run after the signature. The claim ticket is in the result and in the server’s file – not in the front desk’s memory.

Save your progress? Sign up for free

Drill 5: Rejected

Where you are: on cp1, in the directory ~/mcpa/tag05.

What you have afterwards: proof that a rejected call is not executed.

Step 1 – Ask for a deletion and say no.

# on cp1, in ~/mcpa/tag05
echo n | uv run python host.py "Lösche Eintrag 1 aus dem Betriebsbuch." 2>>server.log

Expected:

[host] 7 Werkzeuge von 3 Servern: leitstand__speicher, leitstand__dienst, leitstand__groesste_dateien, handbuch__handbuch_suche, betriebsbuch__eintrag_anlegen, betriebsbuch__eintrag_lesen, betriebsbuch__eintrag_loeschen
[runde 1] Modell will betriebsbuch__eintrag_loeschen mit {"id": 1}
[host] betriebsbuch__eintrag_loeschen mit {"id": 1} ausführen? [j/N] [runde 1] Ergebnis: Der Mensch hat diesen Aufruf abgelehnt. Führe ihn nicht noch einmal aus.
[modell] Der Aufruf wurde abgelehnt, daher werde ich keinen weiteren Vorgang durchführen.

Step 2 – Is the entry still there?

# on cp1, in ~/mcpa/tag05
jq length betriebsbuch.json

jq length counts the keys of the object in the file – that is, the entries.

Expected:

1

The model chose the right tool with the right handle; the human said no. The server never received a request, and the entry is still there (1). The model accepts the rejection and does not try again – the host’s clear message takes care of that.

Remember: Without a signature the order never reaches the provider. Tell the model clearly that it was rejected – otherwise it places the same order again.

Save your progress? Sign up for free

Drill 6: Errors the model learns from

Where you are: on cp1, in the directory ~/mcpa/tag05.

What you have afterwards: two responses of the model to errors – one with a wrong handle, one with a wrong path.

Step 1 – a handle that does not exist.

# on cp1, in ~/mcpa/tag05
uv run python host.py "Was steht im Betriebsbuch in Eintrag 7?" 2>>server.log

Expected (excerpt – without the first line with the tool list, which looks like the one in Drill 4):

[runde 1] Modell will betriebsbuch__eintrag_lesen mit {"id": 7}
[runde 1] Ergebnis: FEHLER: Error executing tool eintrag_lesen: Eintrag 7 gibt es nicht. Vorhandene Nummern: 1.
[modell] Eintrag 7 existiert nicht. Das Betriebsbuch enthält derzeit nur den Eintrag mit der Nummer 1.

Reading needs no consent – eintrag_lesen is read-only and the operations log is trusted. The message of the ToolError reaches the model in full, with the SDK’s prefix in front. Because it names the existing numbers, the model can give a helpful answer instead of guessing.

Step 2 – the wrong path from Day 4, now with a good message. As in Day 4, you remove the system prompt so the model makes the mistake again:

# on cp1, in ~/mcpa/tag05
cp host.py host_ohne.py
# on cp1, in ~/mcpa/tag05
nano host_ohne.py

In main, find the list verlauf and delete exactly this one line in it (Ctrl+K cuts the line under the cursor in nano):

            {"role": "system", "content": systemanweisung(clients)},

Afterwards only the line with "role": "user" is left there. Save with Ctrl+O and quit with Ctrl+X.

# on cp1, in ~/mcpa/tag05
uv run python host_ohne.py "Wie viel Prozent der Platte von cp1 sind belegt?" 2>>server.log

Expected (excerpt without the tool list; the wording varies):

[runde 1] Modell will leitstand__speicher mit {"pfad": "/cp1", "einheit": "GB"}
[runde 1] Ergebnis: FEHLER: Error executing tool speicher: Den Pfad /cp1 gibt es auf diesem Rechner nicht. Das Werkzeug misst immer auf dem 
[modell] Der Pfad `/cp1` existiert nicht auf dem Rechner. Um den Zustand der Platte zu ermitteln, müssen wir das Wurzeldateisystem (`/`) prüfen, da das Werkzeug nur auf dem lokalen System arbeitet. Ich werde daher die Speicherinformationen für das Wurzeldateisystem abrufen.

Compare with Day 4: instead of “Möglicherweise existiert das Verzeichnis nicht” (“The directory may not exist”), the model has now understood what was wrong and what would be right. It even announces the right call – but does not make it, and ends its answer instead. This is a typical weakness of small models; larger models usually call the tool a second time right away in this situation. What counts for you as a developer: the message has done its part. With the system prompt (host.py) the mistake does not happen in the first place.

Remember: An error message is a text for the model. The clearer it says what to do, the better the model corrects itself.

Save your progress? Sign up for free

Drill 7: Idempotent delete

Where you are: on cp1, in the directory ~/mcpa/tag05.

What you have afterwards: proof that deleting twice does not trigger an error – and a restored operations log.

You talk to the server directly, without a host and without consent – as if a client had repeated the same call after a dropped connection.

Step 1 – Back up the log. The experiment deletes entry 1; afterwards you restore it.

# on cp1, in ~/mcpa/tag05
cp betriebsbuch.json betriebsbuch.sicher

Step 2 – Two identical requests in one file. The same call eintrag_loeschen with id 1 twice; only the request number differs:

# on cp1, in ~/mcpa/tag05
nano loeschen.jsonl
~/mcpa/tag05/loeschen.jsonl new file
{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"eintrag_loeschen","arguments":{"id":1},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}
{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"eintrag_loeschen","arguments":{"id":1},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}

Step 3 – Send both requests one after the other. This is the only longer command of the day: it plays a client that repeats its request after three seconds.

# on cp1, in ~/mcpa/tag05
(sed -n 1p loeschen.jsonl; sleep 3; sed -n 2p loeschen.jsonl; sleep 3) | uv run python betriebsbuch.py 2>/dev/null | jq -c '{id, text: .result.content[0].text}'
Part Meaning
( … ) the commands in parentheses run one after the other, their output forms one stream
sed -n 1p loeschen.jsonl print only line 1 (-n suppresses normal output, 1p prints line 1)
sleep 3 wait three seconds – two deletions in the same file at the same moment could get in each other’s way
\| uv run python betriebsbuch.py the stream goes to the server as standard input
2>/dev/null discard the server’s messages
\| jq -c '{id, text: …}' from each response only the number and text, compact on one line

Expected:

{"id":1,"text":"Eintrag 1 gelöscht."}
{"id":2,"text":"Eintrag 1 war schon gelöscht oder gab es nie."}

Step 4 – The log is empty.

# on cp1, in ~/mcpa/tag05
cat betriebsbuch.json

Expected:

{}

Both calls succeed (isError is not set), the second has no further effect. That is exactly what idempotentHint: true means: a client may safely retry the call. If the second call reported an error, a client would have to be able to tell whether its first attempt arrived – without a session it cannot.

Step 5 – Restore the log.

# on cp1, in ~/mcpa/tag05
cp betriebsbuch.sicher betriebsbuch.json

Remember: An idempotent tool reports success the second time, not an error. Only then may a client without a session safely repeat a call.

Save your progress? Sign up for free

If it doesn’t work

  • EOFError: EOF when reading a line: The host wanted consent, but there was no input – for example because you redirected the output and forgot echo j |. Start the host directly in the terminal and answer yourself.
  • The model creates the entry twice: Small models sometimes bundle duplicate calls. Because eintrag_anlegen is not idempotent, two entries are created – that is exactly why the host asks. Say no the second time.
  • Error executing tool … without further explanation: An exception occurred in the tool that is not a ToolError. The cause is in server.log.
  • jq: error … betriebsbuch.json: The file is missing because Drill 4 did not run. laden() copes without the file, jq does not.

Exercise: List entries (20 min)

Add a read-only tool eintraege_auflisten (list entries) to the operations log that returns number and title of all entries. How do you have to annotate it so the host calls it without asking? Ask the host “Welche Einträge gibt es im Betriebsbuch?” (“Which entries are in the operations log?”).

Solution

Before if __name__ in betriebsbuch.py:

@mcp.tool(title="Einträge auflisten", annotations=ToolAnnotations(read_only_hint=True, open_world_hint=False))
def eintraege_auflisten() -> list[str]:
    """Listet alle Einträge des Betriebsbuchs mit Nummer und Titel."""
    return [f"{k}: {v['titel']}" for k, v in laden().items()]

read_only_hint=True is enough because the operations log is in VERTRAUT. The host now reports eight tools and calls betriebsbuch__eintraege_auflisten without asking; the answer names “1: Ollama neu gestartet”.

Save your progress? Sign up for free

Challenge: A server that pretends to be harmless (15 min)

In betriebsbuch.py, change the annotation of eintrag_loeschen to read_only_hint=True and ask “Lösche Eintrag 1 aus dem Betriebsbuch.” (“Delete entry 1 from the operations log.”) – without echo. What happens? What would you have to change in the host so this lie no longer fools it?

Solution

The host deletes without asking: the tool is marked read-only, and the server is in VERTRAUT. The trust list only protects against foreign servers, not against your own server that is annotated wrongly. Two countermeasures:

  • Remove the server from VERTRAUT – then the host asks for every tool of the operations log.
  • Maintain approvals per tool instead of per server, for example a set {"betriebsbuch__eintrag_lesen", "leitstand__speicher", …} that a human has reviewed. Annotations then only help with the display.

Afterwards, restore read_only_hint=False and copy the operations log back from betriebsbuch.sicher if the entry was deleted.

Save your progress? Sign up for free

Checkpoint

# on cp1, in ~/mcpa/tag05
jq -r '.["1"].titel' betriebsbuch.json

.["1"] accesses the key "1"; the bracket notation is needed because the key starts with a digit.

Expected: Ollama neu gestartet

# on cp1, in ~/mcpa/tag05
grep -c "ToolError" leitstand.py betriebsbuch.py

Expected:

leitstand.py:2
betriebsbuch.py:2
# on cp1, in ~/mcpa/tag05
grep -c "def zustimmung" host.py

Expected: 1

Exam questions

1. A tool is supposed to create a customer and extend the record later. How do you model the state in MCP 2026-07-28?

    1. via the session identifier Mcp-Session-Id
    1. the tool returns an identifier that later calls pass along as an argument
    1. the server remembers the last client
    1. via notifications/initialized

2. A tool fails because an external service does not respond. What should the server return?

    1. a JSON-RPC error -32603
    1. a result with isError: true and an explanation the model can keep working with
    1. an empty result
    1. nothing at all, the client detects the timeout

3. Which statement about human consent is correct?

    1. MCP forbids tools that change something.
    1. The server must ask the human for consent itself.
    1. Before calls, hosts should show what is about to run with which arguments, and ask for confirmation for changes.
    1. Consent is only needed for tools with openWorldHint: true.

4. What does idempotentHint: true mean?

    1. The tool only reads.
    1. Multiple calls with the same arguments have no more effect than one.
    1. The tool always returns the same result.
    1. The tool must not be retried.

5. A handle grants access to an operation without any further checks. How should it be designed?

    1. as a sequential number so it is easy to remember
    1. opaque and hard to guess; the server checks it on every call
    1. as a copy of the session identifier
    1. it should contain the user name in plain text

Solutions

  1. B. Without sessions, handles carry the state as a normal argument; A and D no longer exist since 2026-07-28.
  2. B. A failure during execution is an execution error; the explanation allows the model to correct itself or to let the human know.
  3. C. Consent is the host’s job; MCP does not require it from the server.
  4. B. Idempotent means: no additional effect on repetition. An idempotent tool may well change things (deleting is idempotent).
  5. B. Guessable handles would be an entry point for attackers; the server still has to check them every time.

Interview Note

“How do you handle errors in MCP tools?” – Distinguish three levels: protocol errors (malformed request, unknown tool) as JSON-RPC errors; expected execution errors as isError: true with a message that says what was wrong and what to do; unexpected crashes with a neutral message to the outside and all details in the log. This way the model learns from errors without internal information leaking out.

Enterprise Note

Consents are part of the audit: who approved which state-changing call, and when? A central host therefore logs the question, tool, arguments, decision, and result. For tools with a large impact – production systems, money, personal data – a click in the chat is often not enough; there, approvals are tied to existing processes (ticket, four-eyes principle, maintenance window), and the tool checks on the server side whether the approval exists.

Summary

  • Lifecycle: discover → select → arguments → check → consent → execute → result → pass on → correct; the server always checks arguments, the host decides on consent.
  • The server reports expected errors as ToolError (isError: true with an explanation); on crashes the model sees only a neutral message, the details are in the log.
  • Good error messages say what was wrong, why, and what to do instead – then the model can correct itself or help the human.
  • The host asks before state-changing calls; whether a tool is “read-only” it believes only for servers on its own trust list – or, better, a reviewed list of individual tools.
  • State without sessions: handles as arguments; checked on every call, opaque if they grant access.
  • Idempotent tools may be retried safely.

Commands at a glance

For review: all commands and SDK calls of this day with the parameters you used.

Command / call What it does Parameters
raise ToolError("…") expected error: isError: true with your message from None without the original exception
try: … except FileNotFoundError: catch a specific exception –
ToolAnnotations(read_only_hint, destructive_hint, idempotent_hint, open_world_hint) describe behavior hints, not trustworthy
Field(min_length=…, max_length=…) limit the length of strings –
Path(__file__).with_name("…") file next to the program –
objekt.model_dump() · Klasse(**dict) Pydantic object ↔︎ dictionary –
input("…") asks on the console reads one line from stdin
echo j \| uv run python host.py "…" answers the question in advance –
nano <file> create or change a file Ctrl+K cut line, Ctrl+O save, Ctrl+X quit
diff <old> <new> differences between two files < old, > new
cp <source> <target> copy a file (back up, restore) several sources + directory
sed -n 1p <file> only line 1 -n no normal output, p print
jq length · jq -r '.["1"].titel' number of keys · field of a key starting with a digit –

Contents

More