Day 6: Resources – data as context
Goal: Offer and read resources and resource templates, deliver text and binary data, set cache hints, fend off path attacks, and use resources as context in the host · Duration: about 3 h · Prerequisite: Day 5
Where we start
# on cp1, in ~/mcpa/tag05
jq -r '.["1"].titel' betriebsbuch.jsonExpected: Ollama neu gestartet
# on cp1, in ~/mcpa/tag05
grep -c "def zustimmung" host.pyExpected: 1
If something is missing, work through Day 5, Drills 1 to 4 – today’s
host builds on host.py, leitstand.py,
handbuch.py, and betriebsbuch.py from Day
5.
Introduction
Tools do something when the model wants them to. Often, though, a model simply needs knowledge: the operating thresholds, the content of a configuration file, the last lines of a log. That is what MCP’s second primitive is for: resources. A resource is a piece of data with an address (URI) that a server offers for reading – comparable to a file, except that the server decides what is behind it.
The most important difference from tools: resources are
application-controlled. The model does not call them;
the host decides which data it gives the model – automatically, because
the server marks it as important, or because the human selects it. Today
you build a server with resources (protokolle, logs), read
them by hand and with the SDK, and let the host load matching resources
into the context on its own.
Today you learn:
- to offer fixed resources and resource templates (URI templates according to RFC 6570),
- to use the methods
resources/list,resources/templates/list, andresources/read, - to deliver text (
text) and binary data (blob, Base64) and to specify the MIME type, - to set annotations for resources
(
audience,priority) and cache hints (ttlMs,cacheScope), - to fend off path attacks (path traversal) in templates,
- to link to resources from a tool
(
resource_link), - to use resources as context in the host.
Background
The picture for today: the information folder in the hotel room
Yesterday the guest ordered services – those were tools. Today it is about something else: knowledge. In every good hotel room there is an information folder: house rules, breakfast times, the Wi-Fi password. The guest does not have to order anything to read it.
- Every sheet in the folder has an address, such as “information folder / breakfast” – that is the URI of a resource.
- Some sheets are forms with a blank: “menu of restaurant ___”. Whoever fills in a name gets the matching sheet. That is a resource template.
- The front desk (the host) decides which sheets it puts out for the guest right at check-in – “application-controlled”. The provider can mark a sheet as “important for the guest”; whether the front desk puts it out is the front desk’s decision.
- The sheet says how long it is valid: “as of today, valid for one week” – those are the caching hints.
- A guest who asks for “menu of ../../director’s office” gets nothing – the folder contains only what belongs in the folder.
The terms
| Term | Meaning | in the picture |
|---|---|---|
| Resource | data with a URI that a server offers for reading | sheet in the information folder |
| URI | address of a resource,
e.g. config://leitstand/grenzwerte |
tab divider |
| Template | family of resources with a placeholder,
e.g. log://{datei} |
form with a blank |
text / blob |
content as characters or as Base64-encoded bytes | printed sheet / attached file |
| Annotations | audience, priority – for whom and how
important |
stamp “important for the guest” |
ttlMs, cacheScope |
how long and for whom a result is valid | “valid until …” |
| Path traversal | breaking out of a directory with ../ |
asking for a sheet from the director’s office |
resource_link |
link to a resource instead of its content | “see sheet 3 in the folder” |
Remember: The model orders tools, the front desk puts out resources. Tool when something is done; resource when data is read.
Resources and URIs
Every resource has a URI – an address such as
config://leitstand/grenzwerte or
file:///etc/hostname. The server may choose the scheme
before :// freely; common ones are file:// for
files, https:// for content that also exists on the web,
and custom schemes such as config:// or
log://. A resource also has a name, optionally
a title and description, the MIME
type (mimeType, for example
text/plain, application/json,
image/png), and optionally the size in bytes
(size).
A server with resources reports the capability resources
in server/discover, with two switches:
listChanged (it can report changes to the list) and
subscribe (you can watch individual resources). You use
both in Day 9.
The methods
| Method | Purpose | Result |
|---|---|---|
resources/list |
all fixed resources | resources (+ nextCursor for pages) |
resources/templates/list |
all templates | resourceTemplates with uriTemplate |
resources/read |
read one resource, parameter uri |
contents: list with text
or blob |
Templates describe whole families of resources, for
example log://{datei}. The syntax is RFC
6570: {name} is a placeholder. The client fills in
a value and reads log://syslog. This way a server does not
have to list a thousand log files individually.
resources/read returns a list contents,
because a URI can have several parts (for example a directory). Each
part has uri, mimeType, and either
text (characters) or
blob (binary data, Base64-encoded – that
is, converted to text so it fits into JSON).
If a resource does not exist, the server responds with the protocol
error -32602 (formerly
-32002). It must not simply return an empty
contents list.
Lists can be long. Then a server splits them into
pages: the response carries nextCursor,
and the client requests the next page with
"cursor": "<value>". The cursor is opaque – the
client only passes it on. The same applies to tools/list
and prompts/list.
Annotations and caching
Resources (and content blocks) can carry annotations:
audience– whom the data is intended for:["user"],["assistant"](the model), or both,priority– importance from0.0(unimportant) to1.0(indispensable),lastModified– time of the last change (ISO 8601).
A host can use them to decide which resources it gives the model automatically. These, too, are hints from the server; the host decides.
Since 2026-07-28, the results of server/discover,
tools/list, prompts/list,
resources/list, resources/templates/list, and
resources/read carry two mandatory fields for
caching:
ttlMs– for how many milliseconds a client may consider the result fresh (0= not at all),cacheScope–publicif the result is the same for all callers and may be cached in a shared cache, orprivateif it applies only to this caller (for example because it depends on their permissions).
A client with a cache then does not ask again every time. The Python
SDK has one built in. Results of tools/call do not have
these fields – tool calls are never cached.
Paths in templates
A template such as log://{datei} invites a classic
attack: path traversal. Whoever reads
log://../../etc/passwd gets out of /var/log if
the server simply appends the value to a path. The specification
requires servers to validate and sanitize paths. By
default, the Python SDK checks values of template parameters for such
patterns (setting resource_security); Drill 4 shows
this.
Links instead of content
Instead of large content, a tool can return links:
content blocks of type resource_link with uri,
name, and mimeType. The host then decides
whether to read the resource. This saves space in the conversation and
lets the host control what the model gets to see. Alternatively, a tool
can embed the content directly (content type resource).
Drill 1: The server protokolle
Where you are: on cp1, in the directory
~/mcpa/tag06.What you have afterwards:
protokolle.py(logs) with three resources, one template, and one tool.
Step 1 – Create the directory and change into it.
# on cp1
mkdir -p ~/mcpa/tag06# on cp1
cd ~/mcpa/tag06Step 2 – Write the server.
# on cp1, in ~/mcpa/tag06
nano protokolle.pyimport gzip
import json
from pathlib import Path
from mcp.server import MCPServer
from mcp.server.caching import CacheHint
from mcp.server.mcpserver.exceptions import ResourceNotFoundError
from mcp.types import Annotations, ResourceLink, ToolAnnotations
LOGS = Path("/var/log")
mcp = MCPServer(
name="protokolle",
version="1.0.0",
instructions="Lesezugriff auf Logdateien und Grenzwerte des Rechners. Logs sind Ressourcen unter log://.",
cache_hints={
"resources/list": CacheHint(ttl_ms=300_000, scope="public"),
"resources/read": CacheHint(ttl_ms=10_000, scope="private"),
},
)
@mcp.resource(
"config://leitstand/grenzwerte",
title="Grenzwerte",
description="Schwellen, ab denen der Betrieb handeln muss",
mime_type="application/json",
annotations=Annotations(audience=["assistant"], priority=0.9),
)
def grenzwerte() -> str:
return json.dumps({"speicher_warnung_prozent": 85, "speicher_kritisch_prozent": 95}, ensure_ascii=False)
@mcp.resource("system://os-release", title="Betriebssystem", mime_type="text/plain")
def os_release() -> str:
return Path("/etc/os-release").read_text()
@mcp.resource("system://os-release.gz", title="Betriebssystem (gepackt)", mime_type="application/gzip")
def os_release_gz() -> bytes:
return gzip.compress(Path("/etc/os-release").read_bytes())
@mcp.resource("log://{datei}", title="Logdatei", description="Die letzten 20 Zeilen einer Datei in /var/log", mime_type="text/plain")
def logdatei(datei: str) -> str:
pfad = LOGS / datei
if not pfad.is_file():
raise ResourceNotFoundError(f"Keine Logdatei {datei} in /var/log.")
return "\n".join(pfad.read_text(errors="replace").splitlines()[-20:])
@mcp.tool(title="Logs finden", annotations=ToolAnnotations(read_only_hint=True, open_world_hint=False))
def logs_finden(stichwort: str) -> list[ResourceLink]:
"""Findet lesbare Logdateien in /var/log, deren Name das Stichwort enthält, und verweist auf sie."""
treffer = []
for pfad in sorted(LOGS.glob(f"*{stichwort}*")):
if pfad.is_file() and pfad.stat().st_size > 0:
treffer.append(ResourceLink(type="resource_link", uri=f"log://{pfad.name}", name=pfad.name, mime_type="text/plain"))
return treffer
if __name__ == "__main__":
mcp.run()What is new:
from mcp.server.caching import CacheHint– cache hints.cache_hints={…}in the constructor sets them per method: the list of resources may be cached for five minutes (300_000milliseconds;_only separates the digits for readability) and shared for everyone (public), read content for ten seconds and only for the caller (private).@mcp.resource("config://leitstand/grenzwerte", …)registers a fixed resource with this URI (grenzwerte= thresholds). The function’s return value is the content:strbecomestext,bytesbecomesblob.mime_typesets the MIME type.annotations=Annotations(audience=["assistant"], priority=0.9)says: intended for the model and very important.json.dumps(…)returns the thresholds as JSON text, matchingapplication/json.system://os-releasereturns the content of/etc/os-releaseas text,system://os-release.gzthe same file compressed withgzip.compress(…)as bytes – a binary resource.@mcp.resource("log://{datei}", …)– the curly braces turn it into a template. The value for{datei}(file) arrives as the function parameterdatei.LOGS / dateiappends a name to a path with/(pathlib).pfad.is_file()checks whether it is a file; otherwiseraise ResourceNotFoundError(…)– the SDK turns this into the error-32602.read_text(errors="replace")reads the file and replaces bytes that are not valid text instead of aborting.splitlines()[-20:]takes the last 20 lines,"\n".join(…)joins them again.
logs_finden(find logs) is a tool that returns links.LOGS.glob(f"*{stichwort}*")searches for names containing the keyword (*= any characters). For each non-empty file (st_size > 0) aResourceLinkis created with typeresource_link, URI, name, and MIME type.
Remember: A fixed resource is a sheet, a template is a form with a blank. The return type decides:
strbecomestext,bytesbecomesblob.
Save your progress? Sign up for free
Drill 2: List resources
Where you are: on cp1, in
~/mcpa/tag06.What you have afterwards: nine responses in
r.outand an overview of resources and templates.
Step 1 – Nine requests in one file. Each line is a complete JSON-RPC request: listing, reading text, binary data, logs, two error cases, two attacks and one tool call.
# on cp1, in ~/mcpa/tag06
nano r.jsonl{"jsonrpc":"2.0","id":1,"method":"resources/list","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}
{"jsonrpc":"2.0","id":2,"method":"resources/templates/list","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}
{"jsonrpc":"2.0","id":3,"method":"resources/read","params":{"uri":"config://leitstand/grenzwerte","_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}
{"jsonrpc":"2.0","id":4,"method":"resources/read","params":{"uri":"system://os-release.gz","_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}
{"jsonrpc":"2.0","id":5,"method":"resources/read","params":{"uri":"log://dpkg.log","_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}
{"jsonrpc":"2.0","id":6,"method":"resources/read","params":{"uri":"log://gibtsnicht.log","_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}
{"jsonrpc":"2.0","id":7,"method":"resources/read","params":{"uri":"log://..%2F..%2Fetc%2Fpasswd","_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}
{"jsonrpc":"2.0","id":8,"method":"resources/read","params":{"uri":"log://../../etc/passwd","_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}
{"jsonrpc":"2.0","id":9,"method":"tools/call","params":{"name":"logs_finden","arguments":{"stichwort":"dpkg"},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}Step 2 – Send all requests to the server. The
responses go into r.out; the following drills only read
from this file.
# on cp1, in ~/mcpa/tag06
(cat r.jsonl; sleep 5) | uv run python protokolle.py 2>/dev/null > r.out| Part | Meaning |
|---|---|
(cat r.jsonl; sleep 5) |
first print all requests, then wait five seconds so the server can answer before the input ends |
\| uv run python protokolle.py |
the requests go to the server as standard input |
2>/dev/null |
discard the server’s messages |
> r.out |
write the responses to a file |
Step 3 – The list of fixed resources.
# on cp1, in ~/mcpa/tag06
jq -c 'select(.id==1) | .result | {ttlMs, cacheScope, uris: [.resources[].uri]}' r.outselect(.id==1)takes only the response to request 1.[.resources[].uri]collects the URIs of all resources into a new list.
Expected:
{"ttlMs":300000,"cacheScope":"public","uris":["config://leitstand/grenzwerte","system://os-release","system://os-release.gz"]}
Step 4 – The template.
# on cp1, in ~/mcpa/tag06
jq -c 'select(.id==2) | .result.resourceTemplates[0] | {uriTemplate, mimeType}' r.outExpected:
{"uriTemplate":"log://{datei}","mimeType":"text/plain"}
The list contains only the three fixed resources.
The log files are not listed individually but as one
template – this way a client learns that
log://<anything> exists without the server having to
enumerate all files. ttlMs and cacheScope come
from your cache_hints. Also look at the annotations of the
thresholds with jq 'select(.id==1)' r.out.
Remember: The list names the sheets, the template names the form. Whoever wants to know all log files needs no directory – only the template.
Save your progress? Sign up for free
Drill 3: Read text and binary data
Where you are: on cp1, in
~/mcpa/tag06.What you have afterwards: read content – once as text, once as Base64.
Step 1 – Read text.
# on cp1, in ~/mcpa/tag06
jq -c 'select(.id==3) | .result | {ttlMs, cacheScope, text: .contents[0].text}' r.outExpected:
{"ttlMs":10000,"cacheScope":"private","text":"{\"speicher_warnung_prozent\": 85, \"speicher_kritisch_prozent\": 95}"}
The thresholds with their cache fields.
Step 2 – Extract the blob. The compressed file
arrives as Base64 text. -r prints it without quotation
marks, > writes it to a file:
# on cp1, in ~/mcpa/tag06
jq -r 'select(.id==4) | .result.contents[0].blob' r.out > os.b64Step 3 – Base64 back into bytes.
# on cp1, in ~/mcpa/tag06
base64 -d os.b64 > os.gz-d(decode) converts Base64 text back into the original bytes – here a gzip file.
Step 4 – Decompress and look.
# on cp1, in ~/mcpa/tag06
gunzip -c os.gz-cwrites the decompressed content to the screen and leavesos.gzin place.
Expected (excerpt – the first three lines):
PRETTY_NAME="Ubuntu 24.04.5 LTS"
NAME="Ubuntu"
VERSION_ID="24.04"
Step 5 – A log via the template. Request 5 read
log://dpkg.log, the package manager’s log:
# on cp1, in ~/mcpa/tag06
jq -r 'select(.id==5) | .result.contents[0].text' r.outExpected (excerpt – the last three of the 20 lines; your log lines are different):
2026-11-28 09:17:23 status config-files containerd:amd64 2.2.1-0ubuntu1~24.04.4
2026-11-28 09:17:24 status not-installed containerd:amd64 <none>
2026-11-28 09:17:24 startup packages configure
The text comes as text, the compressed file as
blob. For text, ttlMs is 10,000 and
private – just as cache_hints specifies for
resources/read.
Remember: Binary data travels as Base64 in the field
blob. You get back in two steps:base64 -d, then the right tool for the format.
Save your progress? Sign up for free
Drill 4: Errors and an attack
Where you are: on cp1, in
~/mcpa/tag06.What you have afterwards: three rejected reads – two of them attempts to break out of
/var/log.
# on cp1, in ~/mcpa/tag06
jq -c 'select(.id >= 6 and .id <= 8) | {id, error}' r.outExpected (order may differ):
{"id":6,"error":{"code":-32602,"message":"Keine Logdatei gibtsnicht.log in /var/log.","data":{"uri":"log://gibtsnicht.log"}}}
{"id":7,"error":{"code":-32602,"message":"Unknown resource: log://..%2F..%2Fetc%2Fpasswd","data":{"uri":"log://..%2F..%2Fetc%2Fpasswd"}}}
{"id":8,"error":{"code":-32602,"message":"Unknown resource: log://../../etc/passwd","data":{"uri":"log://../../etc/passwd"}}}
- Request 6 asks for a file that does not exist. Your message from
ResourceNotFoundError(“Keine Logdatei … in /var/log.”, “No log file … in /var/log.”) comes back as a protocol error-32602, with the URI indata– unlike tools, where execution errors areisError: true. - Requests 7 and 8 try to break out of
/var/logwith../../– once in plain text, once with%2F, the URL encoding of/. In both cases your function never even runs: the SDK’s path check recognizes the pattern, and to the client it looks as if the resource did not exist. It does not even learn that a security check fired.
Still, do not rely on this alone. A second check in your own code –
resolve the path with resolve() and verify that it is still
under /var/log – costs one line and also protects you if
someone changes the SDK setting.
Remember: A missing resource is a protocol error
-32602, notisError. And every path from a template is checked – by the SDK and preferably also in your own code.
Save your progress? Sign up for free
Drill 5: Links from a tool
Where you are: on cp1, in
~/mcpa/tag06.What you have afterwards: a tool result with
resource_link.
# on cp1, in ~/mcpa/tag06
jq -c 'select(.id==9) | .result.content' r.outExpected:
[{"mimeType":"text/plain","name":"dpkg.log","type":"resource_link","uri":"log://dpkg.log"}]
The tool did not return the content but a link to
log://dpkg.log. A host can display it, read it, or give it
to the model as a hint – depending on how much space there is in the
conversation and whether it wants to release the content.
Remember: A tool may point to a sheet instead of copying it. Whether to read it is the front desk’s decision.
Save your progress? Sign up for free
Drill 6: Read resources with the SDK
Where you are: on cp1, in
~/mcpa/tag06.What you have afterwards:
lesen.py(read), a small client for templates and resources.
Step 1 – Write the client.
# on cp1, in ~/mcpa/tag06
nano lesen.pyimport asyncio
from mcp import Client, StdioServerParameters
server = StdioServerParameters(command="uv", args=["run", "python", "protokolle.py"])
async def main() -> None:
async with Client(server) as client:
vorlagen = await client.list_resource_templates()
print("Vorlage:", vorlagen.resource_templates[0].uri_template)
inhalt = await client.read_resource("log://dpkg.log")
zeilen = inhalt.contents[0].text.splitlines()
print(len(zeilen), "Zeilen, letzte:", zeilen[-1])
asyncio.run(main())Step 2 – Run it.
# on cp1, in ~/mcpa/tag06
uv run python lesen.py 2>/dev/nulllist_resource_templates() sends
resources/templates/list, read_resource(uri)
sends resources/read. The result has the field
contents as in Drill 3.
Expected:
Vorlage: log://{datei}
20 Zeilen, letzte: 2026-11-28 09:17:24 startup packages configure
Remember:
read_resource(uri)is to resources whatcall_toolis to tools – just without arguments other than the address.
Save your progress? Sign up for free
Drill 7: Resources as context in the host
Where you are: on cp1, in
~/mcpa/tag06.What you have afterwards: a host that loads important resources on its own and gives them to the model.
Step 1 – Fetch files from Day 5.
# on cp1, in ~/mcpa/tag06
cp ../tag05/leitstand.py ../tag05/handbuch.py ../tag05/betriebsbuch.py ../tag05/betriebsbuch.json .Step 2 – Write the host.
# on cp1, in ~/mcpa/tag06
nano host.pyimport 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"]),
"protokolle": StdioServerParameters(command="uv", args=["run", "python", "protokolle.py"]),
}
VERTRAUT = {"leitstand", "handbuch", "betriebsbuch", "protokolle"}
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 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)},
{"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 5, this changes:
SERVERandVERTRAUTcontain the serverprotokolle.kontext_laden(load context) goes through all servers, lists their resources (list_resources()), and reads those that are explicitly marked for the model ("assistant" in a.audience) and as important (priority >= 0.8).(a.priority or 0)uses 0 if no priority is given.hasattr(c, "text")skips binary content that a language model cannot read.systemanweisung(system prompt) receives the loaded context and appends it after “Kontext:” (“Context:”).mainloads the context before the first conversation and prints it for checking.
Step 3 – Ask.
# on cp1, in ~/mcpa/tag06
uv run python host.py "Ist die Platte schon im Warnbereich?" 2>>server.logExpected (excerpt without the first line with the tool list; the wording varies):
[host] Kontext: [protokolle: Grenzwerte] {"speicher_warnung_prozent": 85, "speicher_kritisch_prozent": 95}
[runde 1] Modell will leitstand__speicher mit {"pfad": "/", "einheit": "GB"}
[runde 1] Ergebnis: {
"pfad": "/",
"gesamt": 76.4,
"frei": 59.9,
"einheit": "GB",
"belegt_prozent": 21.6
}
[modell] Nein, die Platte ist nicht im Warnbereich.
Der aktuelle Zustand der Platte ist wie folgt:
- Gesamter Speicher: 76,4 GB
- Freier Speicher: 59,9 GB
- Belegung: 21,6 % (belegt)
Der Warnbereich wird bei einer Belegung von 85 % erreicht, und der kritische Wert liegt bei 95 %. Derzeit liegt die Belegung weit unter dem Warnwert.
The model combines two sources: the resource with the thresholds that the host loaded in advance, and the tool that it called itself. It did not have to request the thresholds – that is exactly what “application-controlled” means. Compare with Day 4, Challenge: there the number 85 % was in a tool result, and the model wrongly interpreted it as a measured value. Here it is clearly labeled as a threshold.
Remember: The front desk puts out important sheets in advance; the model only orders what it has to measure. That way it does not confuse a threshold with a measured value.
Save your progress? Sign up for free
If it doesn’t work
Unknown resource: log://…for a file that exists: the name contains a character that the SDK’s path check classifies as suspicious, such as a slash. Subdirectories of/var/log(log://apt/history.log) therefore cannot be read through this template.PermissionErrorinserver.log: the file belongs to root, and your user may not read it. The client sees only a generic error message. For such cases aResourceErrorwith an understandable message is worthwhile.base64: invalid input: You usedjqwithout-r; then there are quotation marks around the Base64 text.- The context is empty: No resource meets the
condition in
kontext_laden. Check inprotokolle.pywhetherAnnotations(audience=["assistant"], priority=0.9)is set.
Exercise: Uptime as a resource (15 min)
Add a resource system://uptime with the MIME type
text/plain to protokolle.py that returns the
content of /proc/uptime. Read it with a
resources/read request.
Solution
@mcp.resource("system://uptime", title="Laufzeit", mime_type="text/plain")
def uptime() -> str:
return Path("/proc/uptime").read_text()
The request is a line like request 3 in r.jsonl, only
with "uri":"system://uptime". The response contains two
numbers in contents[0].text: uptime and idle time in
seconds.
Save your progress? Sign up for free
Challenge: Tool or resource? (10 min)
For each case, decide whether you would offer it as a tool or as a resource, and justify it: (a) the list of on-call numbers, (b) “restart service”, (c) the current free disk space, (d) the configuration file of a service.
Solution
- Resource: fixed knowledge that the host passes along when needed; changes rarely (easy to cache).
- Tool: an action with an effect that the model triggers and the human approves.
- Both are defensible: as a tool if the model should
decide on its own when to measure; as a resource with a short
ttlMsif the host wants to pass the value along regularly. In this course it is a tool, because the value should be correct at the moment of the question.
- Both are defensible: as a tool if the model should
decide on its own when to measure; as a resource with a short
- Resource (via a template for many services): data for reading, selected by the host or the human.
Rule of thumb: Tool if something is done or computed; resource if data is read.
Save your progress? Sign up for free
Checkpoint
# on cp1, in ~/mcpa/tag06
jq -r 'select(.id==2) | .result.resourceTemplates[0].uriTemplate' r.outExpected: log://{datei}
# on cp1, in ~/mcpa/tag06
jq -c 'select(.id==8) | .error.code' r.outExpected: -32602
# on cp1, in ~/mcpa/tag06
grep -c kontext_laden host.pyExpected: 2
Exam questions
1. Who typically controls which resources are made available to a model?
- the model, by calling
resources/read
- the model, by calling
- the application (the host), for example based on annotations or the human’s selection
- the server, by embedding resources in responses to
tools/call
- the server, by embedding resources in responses to
- nobody – all resources are loaded automatically
2. A client reads a resource that does not exist. What does a server respond after 2026-07-28?
-32002Resource not found
-32602Invalid params
- a result with an empty
contentslist
- a result with an empty
isError: true
3. How does resources/read transfer the
content of a PNG file?
- as
textwith the content of the file
- as
- as
blob, Base64-encoded, withmimeTypeimage/png
- as
- not at all, resources are text only
- as
resource_link
- as
4. What does cacheScope: "public" mean
in a response to resources/list?
- The list is publicly available on the internet.
- The result is the same for all callers and may be cached in a shared cache across authorization contexts.
- The client must not store the result at all.
- The server is reachable without sign-in.
5. A server offers the template
datei://{pfad}. What is the most important security
measure?
- Pass the path unchanged to
open()so all files are reachable.
- Pass the path unchanged to
- Resolve the path and check that it lies within the allowed directory; reject breakout attempts.
- Only set
cacheScope: "private".
- Only set
- Offer the template in
tools/listinstead ofresources/templates/list.
- Offer the template in
Solutions
- B. Resources are application-controlled; tools are controlled by the model.
- B. Since 2026-07-28 it is
-32602;-32002was the old code, and an empty list is explicitly forbidden. - B. Binary data comes Base64-encoded in
blob. - B.
publicallows shared caches;privateapplies only to the caller. - B. Path traversal is the typical vulnerability of path templates.
Interview Note
“When do you use a resource instead of a tool?” – Resources for data that is read and used as context, tools for actions and computations. The difference is not only technical: resources are controlled by the application, tools by the model. This also decides who determines which data gets into the conversation – an important lever for data protection and for the size of the context.
Enterprise Note
Resources are a convenient way to connect internal knowledge –
manuals, configurations, logs. That is exactly why they belong in the
permission check: a server that offers log://{datei} needs
a list of allowed files, not a path check alone. cacheScope
is not a detail here: whatever depends on the caller’s permissions is
private; otherwise it ends up in a shared cache and is
served to others.
Summary
- Resources are data with a URI that a server offers for reading; they are application-controlled.
resources/listreturns fixed resources,resources/templates/listtemplates according to RFC 6570,resources/readthe content astextor Base64blobincontents.- Missing resources: protocol error
-32602(formerly-32002), never an emptycontentslist. - The annotations
audience,priority,lastModifiedhelp the host decide;ttlMs/cacheScopecontrol caching; long lists come in pages withnextCursor. - Templates with paths must be protected against path traversal.
- Tools can link to resources (
resource_link) or embed them (resource).
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.resource("<uri>", title=…, mime_type=…, annotations=…) |
fixed resource | return str → text, bytes →
blob |
@mcp.resource("log://{datei}") |
template; {datei} becomes a function parameter |
RFC 6570 |
Annotations(audience=[…], priority=…) |
hints for the host | user, assistant; 0.0–1.0 |
MCPServer(cache_hints={"<method>": CacheHint(ttl_ms=…, scope=…)}) |
cache hints per method | public/private |
raise ResourceNotFoundError("…") |
resource missing → -32602 |
– |
ResourceLink(type="resource_link", uri=…, name=…, mime_type=…) |
link from a tool | – |
client.list_resources() ·
client.list_resource_templates() ·
client.read_resource(uri) |
SDK calls | – |
resources/list · resources/templates/list
· resources/read |
methods | cursor for pages, uri |
nano <file> |
create a file | Ctrl+O save, Ctrl+X quit |
base64 -d <file> ·
gunzip -c <file> |
convert Base64 back · decompress to the screen | -c file stays in place |
jq '[.resources[].uri]' |
collect values in a list | – |
jq 'select(.id >= 6 and .id <= 8)' |
select a range | – |