Day 7: Prompts and completion
Goal: Offer prompt templates with arguments, use them in the host as slash commands, and have arguments for prompts and resource templates completed · Duration: about 2.5 h · Prerequisite: Day 6
Where we start
# on cp1, in ~/mcpa/tag06
jq -r 'select(.id==2) | .result.resourceTemplates[0].uriTemplate' r.outExpected: log://{datei}
# on cp1, in ~/mcpa/tag06
grep -c kontext_laden host.pyExpected: 2
If something is missing, work through Day 6, Drills 1, 2, and 7 –
today you need all five server files and the host from
~/mcpa/tag06.
Introduction
The third primitive on the server side is prompts:
ready-made templates for tasks that come up again and again – an
incident report, a shift handover, a code review according to house
rules. A server offers them, a human selects them, for example as the
command /stoerungsbericht (incident report) in the chat.
The template fills itself with the human’s input and starts a
conversation with exactly the instructions the team has defined for this
task.
Prompts are user-controlled – neither the model nor
the host uses them on its own. So that the human can fill them in
conveniently, there is completion: while the human
types, the client asks the server for matching values, for example all
services starting with ss. Today you build both and extend
the host with slash commands.
Today you learn:
- what prompts are, how they are structured, and who controls them,
- the methods
prompts/listandprompts/getwith arguments and messages, - to build templates with several messages (
user,assistant), - the method
completion/completefor arguments of prompts and resource templates, - to offer prompts in the host as slash commands,
- how the SDK and the specification differ on missing required arguments.
Background
The picture for today: forms at the front desk
Some things in a hotel always run the same way: the damage report, the handover to the night shift, the complaint. For these, the front desk keeps forms – sheets with blanks and a fixed procedure. A provider can supply the front desk with such forms; but the front desk only fills one in and hands it on when a human picks it.
- A prompt is such a form: name, blanks (arguments), required fields and the text that finally goes to the guest (the model).
- Some forms even give the guest the first sentence of their
answer – a message with the role
assistant. - The filling aid next to the form – “room 1…: 101,
102, 103” – is completion (
completion/complete). It suggests values while the human types. - In the host a form becomes a slash command:
/stoerungsbericht dienst=ollama.
The terms
| Term | Meaning | in the picture |
|---|---|---|
| Prompt | named template with arguments, returns messages | form |
| Argument | value the human fills in, required or optional | blank in the form |
Message user / assistant |
text as the human or as the start of the model’s answer | instruction / preprinted first sentence |
prompts/list / prompts/get |
list forms / fill one in | form rack / filled-in form |
| Completion | suggestions for an argument while typing | filling aid |
| user-controlled | only a human triggers the prompt | only the guest reaches for the form |
Remember: The model picks tools, the front desk picks resources, the human picks prompts.
What a prompt is
A prompt in MCP is a named template with arguments
that returns a list of messages when retrieved. Each
message has a role – user or assistant – and
content: text, image, audio, a link to a resource
(resource_link), or an embedded resource
(resource). With a message of the role
assistant, a template can even give the model the beginning
of its answer.
| Method | Purpose | Result |
|---|---|---|
prompts/list |
which templates exist | prompts with name, title,
description, arguments (each
name, description, required) |
prompts/get |
fill a template, parameters name,
arguments |
description, messages |
A server with prompts reports the capability prompts
(with listChanged). If a required argument is missing or
the name does not exist, the specification requires the protocol error
-32602; for errors in the server,
-32603.
Who controls what – once more
| Primitive | controlled by | typically in the host |
|---|---|---|
| Tools | model | automatically, with consent for changes |
| Resources | application | context, attachments, file selection |
| Prompts | human | slash commands, menus, buttons |
So a prompt is not an “instruction the server slips to the model”. It only takes effect when a human selects it. Still, its text comes from the server: a host should show the human what a template sends to the model.
Completion
completion/complete returns suggestions for one
argument. The request names:
ref– what the argument refers to:{"type": "ref/prompt", "name": "<prompt>"}or{"type": "ref/resource", "uri": "<template>"}(the template),argument–nameand thevaluetyped so far,- optionally
context.arguments– values of other arguments that are already fixed.
The response contains completion.values (at most 100
suggestions), optionally total (how many there are in
total) and hasMore (whether there are more than were
returned). A server with completion reports the capability
completions. Because clients can call the method on every
keystroke, servers should limit it (rate limiting) and
respond quickly.
Drill 1: The server vorlagen
Where you are: on cp1, in the directory
~/mcpa/tag07.What you have afterwards:
vorlagen.py(templates) with two prompts, one resource template, and one completion.
Step 1 – Create the directory and change into it.
# on cp1
mkdir -p ~/mcpa/tag07# on cp1
cd ~/mcpa/tag07Step 2 – Write the server.
# on cp1, in ~/mcpa/tag07
nano vorlagen.pyimport subprocess
from pathlib import Path
from mcp.server import MCPServer
from mcp.server.mcpserver import AssistantMessage, UserMessage
from mcp.types import Completion, PromptReference, ResourceTemplateReference
mcp = MCPServer(
name="vorlagen",
version="1.0.0",
instructions="Vorlagen für wiederkehrende Aufgaben im Betrieb: Störungsberichte und Schichtübergaben.",
)
@mcp.prompt(title="Störungsbericht", description="Erstellt einen Störungsbericht zu einem Dienst")
def stoerungsbericht(dienst: str, beobachtung: str = "keine Angabe") -> list:
"""Erstellt einen Störungsbericht zu einem Dienst."""
return [
UserMessage(
f"Erstelle einen kurzen Störungsbericht zum Dienst {dienst}. Beobachtung des Menschen: {beobachtung}.\n"
"Prüfe zuerst mit den Werkzeugen den Zustand des Dienstes und die Zuständigkeit im Handbuch. "
"Gliederung: Dienst, Zustand, Zuständig, Nächster Schritt. Höchstens sechs Zeilen."
),
AssistantMessage("Ich prüfe zuerst den Zustand des Dienstes und die Zuständigkeit."),
]
@mcp.prompt(title="Schichtübergabe")
def uebergabe() -> str:
"""Fasst den Zustand des Rechners für die Übergabe an die nächste Schicht zusammen."""
return "Fasse für die Schichtübergabe zusammen: Plattenbelegung, Zustand von ollama, offene Einträge im Betriebsbuch."
@mcp.resource("log://{datei}", mime_type="text/plain")
def logdatei(datei: str) -> str:
return "\n".join((Path("/var/log") / datei).read_text(errors="replace").splitlines()[-20:])
def dienste() -> list[str]:
ausgabe = subprocess.run(
["systemctl", "list-units", "--type=service", "--no-legend", "--plain", "--all"],
capture_output=True, text=True,
).stdout
return sorted(zeile.split()[0].removesuffix(".service") for zeile in ausgabe.splitlines() if zeile.strip())
@mcp.completion()
async def vervollstaendigen(ref, argument, context) -> Completion | None:
if isinstance(ref, PromptReference) and ref.name == "stoerungsbericht" and argument.name == "dienst":
treffer = [d for d in dienste() if d.startswith(argument.value)]
return Completion(values=treffer[:100], total=len(treffer), has_more=len(treffer) > 100)
if isinstance(ref, ResourceTemplateReference) and argument.name == "datei":
namen = sorted(p.name for p in Path("/var/log").iterdir() if p.is_file() and p.name.startswith(argument.value))
return Completion(values=namen[:100], total=len(namen), has_more=len(namen) > 100)
return None
if __name__ == "__main__":
mcp.run()The new building blocks:
from mcp.server.mcpserver import AssistantMessage, UserMessage– classes for messages with the roleuserorassistant.from mcp.types import Completion, PromptReference, ResourceTemplateReference– the result of a completion and the two kinds ofref.@mcp.prompt(title=…, description=…)registers a prompt. As with tools, the function parameters become arguments:dienst(service) without a default value is required (required: true),beobachtung(observation) with a default value is not.stoerungsberichtreturns a list of two messages: a task for the model (UserMessage) and a beginning of its answer (AssistantMessage). This guarantees that the model starts with the check.uebergabe(handover) returns only a text; the SDK turns it into a message with the roleuser.@mcp.resource("log://{datei}")– a template as in Day 6 (here without validation, only as a target for completion).dienste()(services) callssystemctl list-units --type=service --no-legend --plain --all: all service units (--type=service), including inactive ones (--all), without header and footer lines (--no-legend) and without symbols at the start of the line (--plain).zeile.split()[0]is the unit name,removesuffix(".service")removes the suffix.@mcp.completion()registers one function for all completions. It receivesref,argument, andcontextand decides itself what it is responsible for:isinstance(ref, PromptReference) and ref.name == "stoerungsbericht" and argument.name == "dienst"– the argumentdienstof the incident report: services whose name starts with what was typed (startswith(argument.value)).isinstance(ref, ResourceTemplateReference) and argument.name == "datei"– the argumentdateiof the log template: files in/var/log.values=treffer[:100]limits to 100 suggestions,totalgives the total number,has_moresays whether the list was cut off.return Nonefor everything else: no suggestions.
Remember: Function parameters without a default become required fields of the form. One single completion function decides for itself which field it makes suggestions for.
Save your progress? Sign up for free
Drill 2: Prompts by hand
Where you are: on cp1, in
~/mcpa/tag07.What you have afterwards: the responses to seven requests in
p.out.
Step 1 – Seven requests in one file.
# on cp1, in ~/mcpa/tag07
nano p.jsonl{"jsonrpc":"2.0","id":1,"method":"server/discover","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}
{"jsonrpc":"2.0","id":2,"method":"prompts/list","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}
{"jsonrpc":"2.0","id":3,"method":"prompts/get","params":{"name":"stoerungsbericht","arguments":{"dienst":"ollama","beobachtung":"Antworten dauern über eine Minute"},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}
{"jsonrpc":"2.0","id":4,"method":"prompts/get","params":{"name":"stoerungsbericht","arguments":{},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}
{"jsonrpc":"2.0","id":5,"method":"completion/complete","params":{"ref":{"type":"ref/prompt","name":"stoerungsbericht"},"argument":{"name":"dienst","value":"ss"},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}
{"jsonrpc":"2.0","id":6,"method":"completion/complete","params":{"ref":{"type":"ref/resource","uri":"log://{datei}"},"argument":{"name":"datei","value":"dp"},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}
{"jsonrpc":"2.0","id":7,"method":"prompts/get","params":{"name":"uebergabe","_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}Step 2 – Send them to the server. As in Day 6: all
requests at once, the responses go into p.out.
# on cp1, in ~/mcpa/tag07
(cat p.jsonl; sleep 5) | uv run python vorlagen.py 2>/dev/null > p.out| Part | Meaning |
|---|---|
(cat p.jsonl; sleep 5) |
print the requests, then wait five seconds so all responses arrive |
\| uv run python vorlagen.py |
to the server as standard input |
2>/dev/null |
discard the server’s messages |
> p.out |
responses into a file |
Step 3 – The server’s capabilities.
# on cp1, in ~/mcpa/tag07
jq -c 'select(.id==1) | .result.capabilities' p.outExpected:
{"completions":{},"prompts":{"listChanged":true},"resources":{"listChanged":true,"subscribe":true},"tools":{"listChanged":true}}
Step 4 – The list of prompts.
# on cp1, in ~/mcpa/tag07
jq -c 'select(.id==2) | .result.prompts[] | {name, title, arguments}' p.out.result.prompts[]prints each prompt on its own,{name, title, arguments}only these three fields.
Expected:
{"name":"stoerungsbericht","title":"Störungsbericht","arguments":[{"name":"dienst","required":true},{"name":"beobachtung","required":false}]}
{"name":"uebergabe","title":"Schichtübergabe","arguments":[]}
The server now also reports completions. The list of
prompts shows the arguments with their required flag – enough for a host
to build a form or a command with input assistance.
Step 5 – The filled template.
# on cp1, in ~/mcpa/tag07
jq -c 'select(.id==3) | .result.messages[] | {role, text: .content.text}' p.outExpected:
{"role":"user","text":"Erstelle einen kurzen Störungsbericht zum Dienst ollama. Beobachtung des Menschen: Antworten dauern über eine Minute.\nPrüfe zuerst mit den Werkzeugen den Zustand des Dienstes und die Zuständigkeit im Handbuch. Gliederung: Dienst, Zustand, Zuständig, Nächster Schritt. Höchstens sechs Zeilen."}
{"role":"assistant","text":"Ich prüfe zuerst den Zustand des Dienstes und die Zuständigkeit."}
Two messages with the arguments filled in. A host appends them to the conversation as if the human had written the first and the model had started the second.
Remember:
prompts/listshows the blanks,prompts/getreturns the filled-in form as a list of messages.
Save your progress? Sign up for free
Drill 3: A missing required argument
Where you are: on cp1, in
~/mcpa/tag07.What you have afterwards: the error for a prompt without a required argument.
# on cp1, in ~/mcpa/tag07
jq -c 'select(.id==4)' p.outExpected:
{"jsonrpc":"2.0","id":4,"error":{"code":-32603,"message":"Internal server error"}}
Request 4 calls stoerungsbericht without
dienst. SDK 2.3.0 responds with -32603
(Internal error) and a meaningless message; its log contains
ValueError: Missing required arguments: {'dienst'}. For
missing required arguments, however, the specification requires
-32602 (Invalid params) – that is the
answer that counts in the exam. A client should therefore check required
arguments beforehand: prompts/list tells
it which ones exist.
Remember: If a required field is missing, the specification demands
-32602. A good client checks the required fields before handing in the form.
Save your progress? Sign up for free
Drill 4: Completion
Where you are: on cp1, in
~/mcpa/tag07.What you have afterwards: suggestions for a prompt argument and for a resource template.
# on cp1, in ~/mcpa/tag07
jq -c 'select(.id==5 or .id==6) | {id, completion: .result.completion}' p.outExpected (your services and files may differ):
{"id":5,"completion":{"hasMore":false,"total":3,"values":["ssh","sshd","sshd-keygen"]}}
{"id":6,"completion":{"hasMore":false,"total":1,"values":["dpkg.log"]}}
- Request 5 has
"ref":{"type":"ref/prompt","name":"stoerungsbericht"}and"argument":{"name":"dienst","value":"ss"}– the response names all services starting withss. - Request 6 has
"ref":{"type":"ref/resource","uri":"log://{datei}"}– for resource templates theuriis the template itself, not a finished address.
A chat program would show these values as a list below the input field while you type.
Remember: The filling aid knows two kinds of forms: prompts (
ref/prompt) and resource templates (ref/resourcewith the template asuri).
Save your progress? Sign up for free
Drill 5: Prompts in the host
Where you are: on cp1, in
~/mcpa/tag07.What you have afterwards: a host that treats input starting with
/as a prompt template.
Step 1 – Fetch files.
# on cp1, in ~/mcpa/tag07
cp ../tag06/leitstand.py ../tag06/handbuch.py ../tag06/betriebsbuch.py ../tag06/betriebsbuch.json ../tag06/protokolle.py .Step 2 – Write the host.
# on cp1, in ~/mcpa/tag07
nano host.pyimport asyncio
import json
import shlex
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"]),
"protokolle": StdioServerParameters(command="uv", args=["run", "python", "protokolle.py"]),
"vorlagen": StdioServerParameters(command="uv", args=["run", "python", "vorlagen.py"]),
}
VERTRAUT = {"leitstand", "handbuch", "betriebsbuch", "protokolle", "vorlagen"}
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"
async def kontext_laden(clients: dict[str, Client]) -> str:
"""Liest alle Ressourcen, die ein Server ausdrücklich für das Modell markiert hat."""
teile: list[str] = []
for servername, client in clients.items():
for ressource in (await client.list_resources()).resources:
a = ressource.annotations
if a is not None and a.audience and "assistant" in a.audience and (a.priority or 0) >= 0.8:
inhalt = await client.read_resource(ressource.uri)
text = "".join(c.text for c in inhalt.contents if hasattr(c, "text"))
teile.append(f"[{servername}: {ressource.title or ressource.name}] {text}")
return "\n".join(teile)
def systemanweisung(clients: dict[str, Client], kontext: str) -> str:
"""Baut die Anweisung für das Modell aus den instructions der Server und dem geladenen Kontext."""
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)
+ "\nKontext:\n"
+ kontext
)
async def vorlage_holen(clients: dict[str, Client], eingabe: str) -> list[dict]:
"""Wandelt "/name schluessel=wert ..." in die Nachrichten einer Prompt-Vorlage um."""
name, *paare = shlex.split(eingabe[1:])
argumente = dict(paar.split("=", 1) for paar in paare)
for client in clients.values():
if any(p.name == name for p in (await client.list_prompts()).prompts):
vorlage = await client.get_prompt(name, argumente)
return [{"role": m.role, "content": m.content.text} for m in vorlage.messages]
raise SystemExit(f"Keine Vorlage {name}")
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))
kontext = await kontext_laden(clients)
print(f"[host] Kontext: {kontext}")
http = await stapel.enter_async_context(httpx.AsyncClient())
verlauf: list[dict] = [
{"role": "system", "content": systemanweisung(clients, kontext)},
]
if frage.startswith("/"):
verlauf += await vorlage_holen(clients, frage)
print(f"[host] Vorlage: {verlauf[1]['content'][:100]}")
else:
verlauf.append({"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:])))New compared with Day 6:
import shlex– splits a line like the shell does, so values in quotation marks may contain spaces.- The server
vorlagenhas been added. vorlage_holen(fetch template) takes input such as/stoerungsbericht dienst=ollama "beobachtung=…":eingabe[1:]drops the slash,shlex.splitsplits the rest.name, *paare = …takes the first word as the name, the rest as a list.dict(paar.split("=", 1) for paar in paare)turnsschluessel=wert(key=value) into a dictionary.- For each client,
list_prompts()checks whether it has a template with this name;get_prompt(name, argumente)fills it. - The messages are converted into Ollama’s format:
rolestays, the text content becomescontent. raise SystemExit(…)ends the program with a message if no server knows the template.
- In
main,if frage.startswith("/"):decides whether the input is a template or a normal question.verlauf += …appends all messages of the template.
Step 3 – Incident report via the template.
# on cp1, in ~/mcpa/tag07
echo n | uv run python host.py '/stoerungsbericht dienst=ollama "beobachtung=Antworten dauern über eine Minute"' 2>>server.logThe single quotes on the outside pass the whole line to the host as
one argument; the double quotes inside keep the
observation together for shlex. echo n rejects
a possible write attempt (see below).
Expected (excerpt without the first two lines with the tool list and the context; order and wording vary):
[host] Vorlage: Erstelle einen kurzen Störungsbericht zum Dienst ollama. Beobachtung des Menschen: Antworten dauern
[runde 1] Modell will handbuch__handbuch_suche mit {"stichwort": "ollama"}
[runde 1] Ergebnis: Dienst für das Sprachmodell auf cp1. Zuständig: Team KI-Plattform. Bei Störung: sudo systemctl restart ollama.
[runde 2] Modell will leitstand__dienst mit {"name": "ollama"}
[runde 2] Ergebnis: {
"name": "ollama",
"aktiv": true,
"zustand": "active",
"seit": "Sat 2026-11-28 09:28:50 UTC"
}
[runde 3] Modell will protokolle__logs_finden mit {"stichwort": "ollama"}
[runde 3] Ergebnis:
[modell] Dienst: ollama
Zustand: aktiv, seit 09:28:50 UTC
Zuständig: Team KI-Plattform
Nächster Schritt: Keine Störung beobachtet. Logdateien nicht gefunden – kein weiterer Schritt notwendig.
The template determined the flow: the model checks state and responsibility, searches for logs on its own initiative, and sticks to the prescribed structure. Three tools in three rounds – all read-only, so without asking.
In some runs the model also wants to write the report to the
operations log. Then a question like this appears, and
echo n rejects it:
[runde 2] Modell will betriebsbuch__eintrag_anlegen mit {"titel": "Störung ollama", "text": "Beobachtung: Antworten dauern über eine Minute. Dienst ollama ist aktiv (seit 09:28:50 UTC). Zuständig: Team KI-Plattform. Nächster Schritt: Dienst neu starten mit sudo systemctl restart ollama."}
[host] betriebsbuch__eintrag_anlegen mit {…} ausführen? [j/N]
Nobody had asked for that. Good thing the host asks – a model that “helpfully” writes something is one of the most common surprises when operating with agents.
Remember: A form fixes the procedure but does not replace the signature: even inside a template the host asks before every call that changes something.
Save your progress? Sign up for free
If it doesn’t work
Keine Vorlage stoerungsbericht(“no template”): The servervorlagenis missing fromSERVER, orvorlagen.pyis not in the current directory.ValueError: dictionary update sequence element #0 has length 1: An argument without=. Write every argument asschluessel=wert.EOFError: EOF when reading a line: The model wanted to change something, and there was no answer to the question. Start withecho n |or answer yourself.-32603 Internal server erroronprompts/get: Usually a required argument is missing (Drill 3).
Exercise: The shift handover (15 min)
Start the template uebergabe via the host (without
arguments). Which tools does the model use? Do you let it write an entry
to the operations log if it asks?
Solution
# on cp1, in ~/mcpa/tag07
echo n | uv run python host.py /uebergabe 2>>server.logIn the output, watch for the lines with Modell will
(“model wants” – which tool) and the last line with
[modell] (the answer).
The template names three topics – disk usage, state of ollama, open
entries – and for these the model typically calls
leitstand__speicher, leitstand__dienst, and
betriebsbuch__eintrag_lesen or (with the exercise from Day
5) eintraege_auflisten. If the host asks for write access,
echo n rejects it: a handover should report, not
change.
Save your progress? Sign up for free
Challenge: Completion with context (15 min)
A prompt vergleich(dienst_a, dienst_b) (comparison)
should suggest for dienst_b only services that have not
already been chosen as dienst_a. Which field of the request
do you use, and what would the condition in the function
vervollstaendigen look like?
Solution
The optional field context.arguments of the request
contains the values of arguments that are already fixed, for example
{"dienst_a": "ollama"}. In the function:
if isinstance(ref, PromptReference) and ref.name == "vergleich" and argument.name == "dienst_b":
schon = (context.arguments or {}).get("dienst_a") if context else None
treffer = [d for d in dienste() if d.startswith(argument.value) and d != schon]
return Completion(values=treffer[:100], total=len(treffer), has_more=len(treffer) > 100)
context can be missing (None), hence the
double safeguard.
Save your progress? Sign up for free
Checkpoint
# on cp1, in ~/mcpa/tag07
jq -r 'select(.id==2) | .result.prompts[].name' p.outExpected:
stoerungsbericht
uebergabe
# on cp1, in ~/mcpa/tag07
jq -c 'select(.id==5) | .result.completion.values' p.outExpected: a list of services starting with
ss, for example
["ssh","sshd","sshd-keygen"].
Exam questions
1. Who typically triggers the use of a prompt?
- the model, when it finds a suitable template
- the human, for example via a slash command
- the server on every
tools/call
- the server on every
- the client automatically at startup
2. What does prompts/get return?
- a JSON Schema for the model’s answer
- a list of messages with roles and content
- the text of the model’s answer
- a list of tools
3. A client calls prompts/get without a
required argument. Which response does the specification require?
-32601
-32602
-32603
- a result with
isError: true
- a result with
4. What is completion/complete for?
- to complete the model’s answer
- to provide suggestions for values of an argument of prompts or resource templates
- to finish a tool call
- to continue an interrupted answer
5. Which roles may the messages of a prompt have?
- only
user
- only
userandassistant
system,user, andtool
- any roles
Solutions
- B. Prompts are user-controlled.
- B. Messages with
role(user/assistant) andcontent(text, image, audio, resource). - B. Missing required arguments and unknown names are
-32602; SDK 2.3.0 deviates with-32603. - B. Completion helps fill in arguments, not generate text.
- B. The specification knows only
userandassistantfor prompt messages.
Interview Note
“Why prompts via MCP and not simply as text snippets in the chat program?” – Because they live where the knowledge is: the team that runs a service also maintains the template for its incident reports – together with the tools the template uses. Every MCP-capable host gets them automatically, with arguments and completion. Changes go out through a release of the server instead of through copies in ten programs.
Enterprise Note
Prompts are work instructions that a model executes – in substance, code. They belong in version control, in reviews, and in tests (“does the template return these messages for these arguments?”). And because a prompt strongly steers the model’s behavior, a host should show the human what a template sends before it is submitted – otherwise a manipulated prompt is a convenient way to slip foreign instructions to the model.
Summary
- Prompts are named templates with arguments;
prompts/getreturns messages with the rolesuserandassistant, whose content can be text, image, audio, or a resource. - Prompts are user-controlled; hosts offer them, for example, as slash commands.
- Missing required arguments and unknown prompts:
-32602according to the specification (SDK 2.3.0:-32603). completion/completereturns up to 100 suggestions for an argument of a prompt (ref/prompt) or a resource template (ref/resource), withtotalandhasMore;context.argumentscontains values already chosen.- Servers with completion report
completionsand should rate-limit the requests.
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 |
|---|---|---|
@mcp.prompt(title=…, description=…) |
registers a prompt; parameters become arguments | without default value = required |
UserMessage("…") ·
AssistantMessage("…") |
message with role user / assistant |
– |
@mcp.completion() |
one function for all completions | ref, argument, context |
Completion(values=…, total=…, has_more=…) |
result of the completion | at most 100 values |
PromptReference ·
ResourceTemplateReference |
kinds of ref |
ref/prompt · ref/resource |
client.list_prompts() ·
client.get_prompt(name, argumente) |
SDK calls | – |
prompts/list · prompts/get ·
completion/complete |
methods | name, arguments · ref,
argument, context |
systemctl list-units --type=service --no-legend --plain --all |
all services as a plain list | --all including inactive |
nano <file> |
create a file | Ctrl+O save, Ctrl+X quit |
shlex.split(…) |
split a line like the shell | quotation marks keep things together |
name, *rest = liste |
first element and the rest | – |
uv run python host.py '/<prompt> k=v "k2=w x"' |
start a template via the host | – |