Day 9: Subscriptions and progress
Goal: Subscribe to server changes with
subscriptions/listen, report and display the progress of long-running tools, and build clients that react to events · Duration: about 2 h · Prerequisite: Day 8
Where we start
# on worker1
grep -c schutz ~/mcpa/tag08/fern.pyExpected: 2
# on cp1
grep -c worker1 ~/mcpa/tag08/host.pyExpected: 2
If something is missing, work through Day 8, Drills 1, 6, and 7.
Today you need the uv project on worker1 and your experience with
curl from Day 8.
Introduction
So far the client has always asked and the server has answered. Sometimes, though, the server needs to report something: a resource has changed, a tool was added or removed, a long check run is 60 percent done. A host that never hears about this works with stale data, offers the model tools that no longer exist, or leaves the human waiting without feedback.
MCP has two ways to handle this. Progress belongs to
a single request: the client attaches a token to it, and the server
sends updates carrying that token along the way.
Subscriptions are a separate, long-running channel:
with subscriptions/listen, the client opens a data stream
and states exactly which events it wants to hear. Today you build the
server wache (watch) on worker1, which can do both. You
first watch the messages with curl and then write two
Python clients that react to them.
Today you learn:
- how progress notifications work with
progressTokenandnotifications/progress, - how
subscriptions/listenis structured: filter, acknowledgment, identifier, end without replay, - the events
notifications/resources/updatedandnotifications/tools/list_changed, - how a server adds and removes tools at runtime,
- why
resources/subscribeno longer exists in version 2026-07-28, - how a client subscribes, reloads, and displays progress with the SDK.
Background
The picture for today: messages back to the front desk
Until now the front desk (the host) ordered, and the provider (the server) delivered. Today the provider reports on its own – but only on two channels that the front desk opened beforehand:
- Progress is like a note “job 1 of 5 done” that the
laundry service attaches to a running order. It belongs to exactly this
order and carries its order number
(
progressToken). No number, no notes. Once the order is delivered, no more notes arrive. - A subscription is like a dedicated line to the front desk on which the provider announces: “The information folder threshold has changed” or “Our list of services is new”. When the line is set up, the front desk says exactly which announcements it wants to hear (filter). The first announcement is always the confirmation of what the provider will serve.
- The announcement only says that something changed – the front desk fetches the new folder itself.
- If the line breaks, nothing is replayed. The front desk sets up a new one and asks for everything again.
The terms
| Term | Meaning | In the picture |
|---|---|---|
progressToken |
token with which the client requests progress for a request | order number |
notifications/progress |
progress notification with progress,
total, message |
note “1 of 5 done” |
subscriptions/listen |
request that opens a long event stream | dedicated line |
Filter (params.notifications) |
which events the client wants to hear | “only these announcements, please” |
notifications/subscriptions/acknowledged |
first message: the served subset of the filter | confirmation of the line |
notifications/resources/updated |
a subscribed resource has changed | “information folder changed” |
notifications/tools/list_changed |
the tool list has changed | “list of services is new” |
Remember: Progress belongs to one request and needs a token. A subscription is a separate line with a filter. Both only report that something happens – the client has to reload.
Messages from the server – only on an open stream
In version 2026-07-28, a server cannot simply send something on its own. Every message from the server belongs to a client request and travels on that request’s response stream. Over HTTP, this is the SSE response to a POST; over stdio, it is lines on stdout that refer to the request. There are two kinds of such streams:
| Stream | opened by | ends | contains |
|---|---|---|---|
| Response to a normal request | for example tools/call |
with the response | progress, then the result |
| Subscription | subscriptions/listen |
when the client or server closes it | acknowledgment, then events |
The GET stream and the methods resources/subscribe and
resources/unsubscribe from older versions no longer exist.
They have been merged into subscriptions/listen.
Progress
If a client wants to be informed about the progress of a request, it
sets a progressToken in the request’s
_meta: a string or a number that is unique among its
in-flight requests. The server may then send
notifications/progress notifications with these fields:
| Field | Meaning |
|---|---|
progressToken |
the token from the request |
progress |
the progress so far; must increase with every notification |
total |
optional: the final value, if known |
message |
optional: a text for the human |
Without a token, the server sends no progress. After the response, no further notification arrives.
subscriptions/listen
The request names a filter in
params.notifications:
| Field | delivers |
|---|---|
toolsListChanged: true |
notifications/tools/list_changed |
promptsListChanged: true |
notifications/prompts/list_changed |
resourcesListChanged: true |
notifications/resources/list_changed |
resourceSubscriptions: [uri, …] |
notifications/resources/updated for exactly these
URIs |
The sequence is fixed:
- The first message on the stream is
notifications/subscriptions/acknowledged. It names the subset of the filter that the server actually serves. - Every message carries the key
io.modelcontextprotocol/subscriptionIdin_meta, with theidof the listen request. This lets a client tell several subscriptions apart. - The server sends only what is in the filter.
- If the stream breaks, there is no replay of missed events. The client opens a new subscription and reloads everything it cares about.
The events only contain the message that something
has changed, not the new content. For resources/updated,
the client reads the resource again with resources/read.
For list_changed, it requests the list again. Which events
a server supports at all is listed in its capabilities:
tools.listChanged, prompts.listChanged,
resources.listChanged, and
resources.subscribe.
Events and caching
On Day 6 you saw ttlMs and cacheScope: a
client may cache lists and resources for a while. An event from a
subscription invalidates the cached state. The SDK removes the affected
entries itself before your code reloads.
Drill 1: The server wache
Where you are: on worker1, in the terminal where the server ran yesterday.
What you have afterwards: the server
wacheon port 8001 with one resource, three tools, and a fourth that only exists in maintenance mode.
If the server from Day 8 is still running, stop it with
Ctrl+C. It does no harm, but this keeps the terminal
free.
# on worker1
mkdir -p ~/mcpa/tag09# on worker1
cd ~/mcpa/tag09# on worker1, in ~/mcpa/tag09
nano wache.pyimport json
from pathlib import Path
from typing import Annotated
import anyio
from mcp.server import MCPServer
from mcp.server.mcpserver import Context
from mcp.server.transport_security import TransportSecuritySettings
from mcp.types import ToolAnnotations
from pydantic import Field
mcp = MCPServer(
name="wache",
version="1.0.0",
instructions="Überwacht worker1: Grenzwert für die Plattenbelegung, Prüfläufe, Wartungsmodus.",
)
GRENZWERT = {"warnung_prozent": 85}
NOTIZEN: list[str] = []
@mcp.resource("config://wache/grenzwert", mime_type="application/json")
def grenzwert() -> str:
"""Aktueller Grenzwert für die Plattenbelegung."""
return json.dumps(GRENZWERT)
@mcp.tool(title="Grenzwert setzen", annotations=ToolAnnotations(read_only_hint=False, idempotent_hint=True))
async def grenzwert_setzen(prozent: Annotated[int, Field(ge=50, le=99)], ctx: Context) -> str:
"""Setzt den Grenzwert für die Warnung bei der Plattenbelegung."""
GRENZWERT["warnung_prozent"] = prozent
await ctx.notify_resource_updated("config://wache/grenzwert")
return f"Grenzwert jetzt {prozent} %"
@mcp.tool(title="Verzeichnisse prüfen", annotations=ToolAnnotations(read_only_hint=True))
async def pruefen(ctx: Context) -> list[str]:
"""Zählt die Dateien in fünf Systemverzeichnissen und meldet dabei den Fortschritt."""
verzeichnisse = ["/etc", "/usr/bin", "/usr/lib", "/usr/share", "/usr/include"]
ergebnis = []
for nummer, verzeichnis in enumerate(verzeichnisse, start=1):
anzahl = sum(1 for p in Path(verzeichnis).rglob("*") if p.is_file())
ergebnis.append(f"{verzeichnis}: {anzahl} Dateien")
await ctx.report_progress(nummer, len(verzeichnisse), f"{verzeichnis} geprüft")
await anyio.sleep(1)
return ergebnis
def wartungsnotiz(text: Annotated[str, Field(max_length=200)]) -> str:
"""Hält eine Notiz zur laufenden Wartung fest."""
NOTIZEN.append(text)
return f"Notiz {len(NOTIZEN)} gespeichert"
@mcp.tool(title="Wartungsmodus", annotations=ToolAnnotations(read_only_hint=False, idempotent_hint=True))
async def wartungsmodus(an: bool, ctx: Context) -> str:
"""Schaltet den Wartungsmodus ein oder aus. Im Wartungsmodus gibt es das Werkzeug wartungsnotiz."""
vorhanden = any(t.name == "wartungsnotiz" for t in await mcp.list_tools())
if an and not vorhanden:
mcp.add_tool(wartungsnotiz, title="Wartungsnotiz")
elif not an and vorhanden:
mcp.remove_tool("wartungsnotiz")
else:
return "Keine Änderung"
await ctx.notify_tools_changed()
return "Wartungsmodus " + ("an" if an else "aus")
schutz = TransportSecuritySettings(
enable_dns_rebinding_protection=True,
allowed_hosts=["worker1:8001", "172.16.0.228:8001"],
allowed_origins=[],
)
mcp.run(transport="streamable-http", host="0.0.0.0", port=8001, transport_security=schutz)Start the server:
# on worker1, in ~/mcpa/tag09
uv run python wache.pyExpected (the last line):
INFO: Uvicorn running on http://0.0.0.0:8001 (Press CTRL+C to quit)
What is new in wache.py:
ctx: Contextas a tool parameter: the SDK recognizes the typeContextand passes in an object for the current request when the tool is called. The parameter does not appear in the schema for the model.GRENZWERT(threshold) is a dictionary in the server’s memory. The resourceconfig://wache/grenzwertoutputs it as JSON (json.dumps). After a restart, it contains 85 again.grenzwert_setzen(set threshold) changes the value and then callsawait ctx.notify_resource_updated(uri). This tells all subscribers of that URI that it has changed. The annotations say: the tool changes something (read_only_hint=False), but calling it twice with the same arguments has the same effect as calling it once (idempotent_hint=True).pruefen(check) counts the files in five directories:enumerate(verzeichnisse, start=1)yields pairs of a running number (starting at 1) and a directory.Path(verzeichnis).rglob("*")walks recursively through all entries, andp.is_file()counts only files.sum(1 for …)counts the matches.await ctx.report_progress(nummer, len(verzeichnisse), "…")reports progress, final value, and a message. If the client did not send aprogressToken, the call does nothing.await anyio.sleep(1)slows the run down artificially so that you can see the notifications.
wartungsnotiz(maintenance note) is an ordinary function without@mcp.tool. So at first it is not a tool.wartungsmodus(an)(maintenance mode,an= on) turns it into one:await mcp.list_tools()returns the current tools;any(…)checks whetherwartungsnotizis already among them.mcp.add_tool(wartungsnotiz, title=…)registers the function as a tool at runtime – exactly like the decorator, just later.mcp.remove_tool("wartungsnotiz")removes it again.await ctx.notify_tools_changed()tells subscribers that the tool list has changed. If nothing changed, there is no notification.
allowed_origins=[]allows not a single web page. Requests withoutOrigin(curl, SDK) still get through, as on Day 8.port=8001, so thatwachecan run next to the control room from Day 8.
Remember:
ctx: Contextgives a tool the line to the front desk:report_progressfor progress,notify_resource_updatedandnotify_tools_changedfor subscribers.
Save your progress? Sign up for free
Drill 2: Progress with curl
Where you are: on cp1, in a second terminal.
What you have afterwards: a tool call with five progress notifications, and the same call without them.
Step 1 – Directory and headers.
# on cp1
mkdir -p ~/mcpa/tag09# on cp1
cd ~/mcpa/tag09# on cp1, in ~/mcpa/tag09
KOPF=(-H "Content-Type: application/json" -H "Accept: application/json, text/event-stream" -H "MCP-Protocol-Version: 2026-07-28")KOPF is the Bash array from Day 8 with the three fixed
headers.
Step 2 – The body with an order number.
# on cp1, in ~/mcpa/tag09
nano pruefen.json{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"pruefen","arguments":{},"_meta":{"progressToken":"lauf-1","io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}Next to the mandatory fields, _meta contains
"progressToken":"lauf-1". The client
chooses the name.
Step 3 – The call.
# on cp1, in ~/mcpa/tag09
curl -sN http://worker1:8001/mcp "${KOPF[@]}" -H "Mcp-Method: tools/call" -H "Mcp-Name: pruefen" --data @pruefen.json-N shows each notification immediately.
Expected (shortened, your numbers differ; about one second apart):
event: message
data: {"jsonrpc":"2.0","method":"notifications/progress","params":{"progressToken":"lauf-1","progress":1,"total":5,"message":"/etc geprüft"}}
event: message
data: {"jsonrpc":"2.0","method":"notifications/progress","params":{"progressToken":"lauf-1","progress":2,"total":5,"message":"/usr/bin geprüft"}}
...
event: message
data: {"jsonrpc":"2.0","method":"notifications/progress","params":{"progressToken":"lauf-1","progress":5,"total":5,"message":"/usr/include geprüft"}}
event: message
data: {"jsonrpc":"2.0","id":1,"result":{"content":[{"text":"/etc: 1478 Dateien","type":"text"},{"text":"/usr/bin: 983 Dateien","type":"text"},...],"isError":false,"resultType":"complete","structuredContent":{"result":["/etc: 1478 Dateien",...]},...}}
With the first notification, the server switched to SSE (Day 8). The
progress notifications are notifications without an id,
carrying the token lauf-1. progress rises from
1 to 5; total stays 5. The last message is the response
with id: 1. The SDK outputs a list of strings as several
text blocks in content and as a list under
structuredContent.result.
Step 4 – Without an order number. The same request
without progressToken:
# on cp1, in ~/mcpa/tag09
nano pruefen-ohne.json{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"pruefen","arguments":{},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}# on cp1, in ~/mcpa/tag09
curl -si http://worker1:8001/mcp "${KOPF[@]}" -H "Mcp-Method: tools/call" -H "Mcp-Name: pruefen" --data @pruefen-ohne.jsonExpected (excerpt – look for the line with
content-type and the line with jsonrpc; the
second is cut off on the right here):
content-type: application/json
{"jsonrpc":"2.0","id":1,"result":{"content":[{"text":"/etc: 1478 Dateien","type":"text"},{"text":"/u
No notifications, and because the run stays under 15 seconds, an ordinary JSON response. Same server code, but the client decides whether it wants progress.
Remember: No order number, no notes. With
progressTokenthe server switches to SSE and sends increasingprogressvalues before the actual response.
Save your progress? Sign up for free
Drill 3: A subscription with curl
Where you are: on cp1, in two terminals: in the second one (Drill 2) and in a third one that you open now with
ssh cp1.What you have afterwards: an open subscription stream that reports a change of the threshold and a changed tool list.
Step 1 – the bodies. In the second terminal you create three files. First the subscription:
# on cp1, in ~/mcpa/tag09
nano listen.json{"jsonrpc":"2.0","id":10,"method":"subscriptions/listen","params":{"notifications":{"toolsListChanged":true,"resourceSubscriptions":["config://wache/grenzwert"]},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}listen.json subscribes to changes of the tool list
(toolsListChanged) and of the resource
config://wache/grenzwert
(resourceSubscriptions). The id 10 becomes the
identifier of the subscription.
Then the call that sets the threshold to 90:
# on cp1, in ~/mcpa/tag09
nano grenzwert.json{"jsonrpc":"2.0","id":11,"method":"tools/call","params":{"name":"grenzwert_setzen","arguments":{"prozent":90},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}And the call that turns maintenance mode on:
# on cp1, in ~/mcpa/tag09
nano wartung.json{"jsonrpc":"2.0","id":12,"method":"tools/call","params":{"name":"wartungsmodus","arguments":{"an":true},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}Step 2 – listen. Also in the second terminal:
# on cp1, in ~/mcpa/tag09
curl -sN http://worker1:8001/mcp "${KOPF[@]}" -H "Mcp-Method: subscriptions/listen" --data @listen.jsonExpected (immediately):
event: message
data: {"jsonrpc":"2.0","method":"notifications/subscriptions/acknowledged","params":{"_meta":{"io.modelcontextprotocol/subscriptionId":10},"notifications":{"toolsListChanged":true,"resourceSubscriptions":["config://wache/grenzwert"]}}}
The acknowledgment names the filter being served – here everything
you asked for – and the identifier 10. After that, curl
just sits there: the stream is open and waiting for events.
Step 3 – change something. In the third terminal:
# on cp1, in the third terminal
cd ~/mcpa/tag09Each terminal has its own variables, so you create KOPF
here once more:
# on cp1, in the third terminal, in ~/mcpa/tag09
KOPF=(-H "Content-Type: application/json" -H "Accept: application/json, text/event-stream" -H "MCP-Protocol-Version: 2026-07-28")Now change the threshold:
# on cp1, in the third terminal, in ~/mcpa/tag09
curl -s http://worker1:8001/mcp "${KOPF[@]}" -H "Mcp-Method: tools/call" -H "Mcp-Name: grenzwert_setzen" --data @grenzwert.json | jq -c .result.contentExpected:
[{"text":"Grenzwert jetzt 90 %","type":"text"}]
And turn maintenance mode on:
# on cp1, in the third terminal, in ~/mcpa/tag09
curl -s http://worker1:8001/mcp "${KOPF[@]}" -H "Mcp-Method: tools/call" -H "Mcp-Name: wartungsmodus" --data @wartung.json | jq -c .result.contentExpected:
[{"text":"Wartungsmodus an","type":"text"}]
At the same time, two events appear in the second terminal:
event: message
data: {"jsonrpc":"2.0","method":"notifications/resources/updated","params":{"_meta":{"io.modelcontextprotocol/subscriptionId":10},"uri":"config://wache/grenzwert"}}
event: message
data: {"jsonrpc":"2.0","method":"notifications/tools/list_changed","params":{"_meta":{"io.modelcontextprotocol/subscriptionId":10}}}
notifications/resources/updatednames only theuri, not the new value.notifications/tools/list_changedhas no content at all apart from_meta.- Both carry the identifier 10.
End the subscription in the second terminal with Ctrl+C.
curl closes the connection, and the server cleans up the
subscription.
Remember: First the confirmation, then the announcements – each with the subscription’s identifier. An announcement names only the URI or “list changed”, never the new content.
Save your progress? Sign up for free
Drill 4: Filters and old ways
Where you are: on cp1, again in the second and third terminals, in
~/mcpa/tag09.What you have afterwards: proof that the server sends only what was subscribed to, and the responses to two outdated ways of subscribing.
Step 1 – subscribe to the threshold only. In the
second terminal you create a variant of listen.json without
toolsListChanged:
# on cp1, in ~/mcpa/tag09
nano listen-grenzwert.json{"jsonrpc":"2.0","id":10,"method":"subscriptions/listen","params":{"notifications":{"resourceSubscriptions":["config://wache/grenzwert"]},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}# on cp1, in ~/mcpa/tag09
curl -sN http://worker1:8001/mcp "${KOPF[@]}" -H "Mcp-Method: subscriptions/listen" --data @listen-grenzwert.jsonExpected: the acknowledgment, now with
"notifications":{"resourceSubscriptions":["config://wache/grenzwert"]}.
In the third terminal, you switch maintenance mode off. The file is
wartung.json with false instead of
true:
# on cp1, in the third terminal, in ~/mcpa/tag09
nano wartung-aus.json{"jsonrpc":"2.0","id":12,"method":"tools/call","params":{"name":"wartungsmodus","arguments":{"an":false},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}# on cp1, in the third terminal, in ~/mcpa/tag09
curl -s http://worker1:8001/mcp "${KOPF[@]}" -H "Mcp-Method: tools/call" -H "Mcp-Name: wartungsmodus" --data @wartung-aus.json | jq -c .result.contentExpected:
[{"text":"Wartungsmodus aus","type":"text"}]
The tool list has changed, but nothing appears in
the second terminal. This subscription did not ask for
toolsListChanged, and the server may only send what is in
the filter. End it with Ctrl+C.
Step 2 – the old ways. In the second terminal. First
the method of older versions, resources/subscribe:
# on cp1, in ~/mcpa/tag09
nano subscribe.json{"jsonrpc":"2.0","id":10,"method":"resources/subscribe","params":{"notifications":{"toolsListChanged":true,"resourceSubscriptions":["config://wache/grenzwert"]},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}# on cp1, in ~/mcpa/tag09
curl -s -w ' -> HTTP %{http_code}\n' http://worker1:8001/mcp "${KOPF[@]}" -H "Mcp-Method: resources/subscribe" --data @subscribe.jsonExpected:
{"jsonrpc":"2.0","id":10,"error":{"code":-32601,"message":"Method not found","data":"resources/subscribe"}} -> HTTP 404
Then a subscription that accepts only JSON:
# on cp1, in ~/mcpa/tag09
curl -s -o /dev/null -w 'HTTP %{http_code}\n' http://worker1:8001/mcp -H "Content-Type: application/json" -H "Accept: application/json" -H "MCP-Protocol-Version: 2026-07-28" -H "Mcp-Method: subscriptions/listen" --data @listen.jsonExpected:
HTTP 406
resources/subscribeno longer exists in version 2026-07-28:-32601with 404.- A subscription is an SSE stream. Anyone who accepts
only
application/jsongets 406.
Remember: The server sends only what is in the filter.
resources/subscribeno longer exists, and withouttext/event-streamthere is no dedicated line.
Save your progress? Sign up for free
Drill 5: A client that listens
Where you are: on cp1, in the second terminal (program) and in the third (changes).
What you have afterwards:
beobachter.py(observer), which subscribes and reloads the changed data on every event.
In the second terminal:
# on cp1, in ~/mcpa/tag09
nano beobachter.pyimport asyncio
from mcp import Client
from mcp.client.subscriptions import ResourceUpdated, ToolsListChanged
URL = "http://worker1:8001/mcp"
GRENZWERT = "config://wache/grenzwert"
async def main() -> None:
async with Client(URL) as client:
async with client.listen(tools_list_changed=True, resource_subscriptions=[GRENZWERT]) as abo:
print("Abonniert:", abo.honored.model_dump(by_alias=True, exclude_none=True), flush=True)
async for ereignis in abo:
if isinstance(ereignis, ResourceUpdated):
inhalt = await client.read_resource(ereignis.uri)
print(f"Geändert: {ereignis.uri} -> {inhalt.contents[0].text}", flush=True)
elif isinstance(ereignis, ToolsListChanged):
namen = [t.name for t in (await client.list_tools()).tools]
print("Neue Werkzeugliste:", namen, flush=True)
asyncio.run(main())# on cp1, in ~/mcpa/tag09
uv run python beobachter.pyfrom mcp.client.subscriptions import ResourceUpdated, ToolsListChanged– the events as Python classes.client.listen(tools_list_changed=True, resource_subscriptions=[GRENZWERT])opens the subscription. The parameters correspond to the fields of the filter.async withwaits until the acknowledgment has arrived and closes the stream when the block is left.abo.honoredis the served filter from the acknowledgment.model_dump(by_alias=True, exclude_none=True)outputs it with the JSON names and without empty fields.async for ereignis in abo:waits for the next event (ereignis). The loop ends when the server closes the stream cleanly. If the connection breaks, it raisesSubscriptionLost– a client would then have to subscribe again and reload.isinstance(ereignis, ResourceUpdated): the resource is read again withread_resource.isinstance(ereignis, ToolsListChanged): the tool list is fetched again withlist_tools.flush=Trueprints every line immediately, even when the output is redirected.
Expected:
Abonniert: {'toolsListChanged': True, 'resourceSubscriptions': ['config://wache/grenzwert']}
In the third terminal you set the threshold to 80 – with a copy of
grenzwert.json:
# on cp1, in the third terminal, in ~/mcpa/tag09
nano grenzwert80.json{"jsonrpc":"2.0","id":11,"method":"tools/call","params":{"name":"grenzwert_setzen","arguments":{"prozent":80},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}# on cp1, in the third terminal, in ~/mcpa/tag09
curl -s http://worker1:8001/mcp "${KOPF[@]}" -H "Mcp-Method: tools/call" -H "Mcp-Name: grenzwert_setzen" --data @grenzwert80.json | jq -c .result.contentExpected:
[{"text":"Grenzwert jetzt 80 %","type":"text"}]
Then turn maintenance mode on again:
# on cp1, in the third terminal, in ~/mcpa/tag09
curl -s http://worker1:8001/mcp "${KOPF[@]}" -H "Mcp-Method: tools/call" -H "Mcp-Name: wartungsmodus" --data @wartung.json | jq -c .result.contentExpected:
[{"text":"Wartungsmodus an","type":"text"}]
and in the second:
Geändert: config://wache/grenzwert -> {"warnung_prozent": 80}
Neue Werkzeugliste: ['grenzwert_setzen', 'pruefen', 'wartungsmodus', 'wartungsnotiz']
The observer reacted to each event with exactly one request and now
knows the new threshold and the new tool wartungsnotiz.
This is how a host keeps its tool list for the model up to date without
constantly asking. Stop the observer with Ctrl+C.
Remember: A good client listens and reloads:
client.listen(…)opens the line,read_resourceandlist_toolsfetch the new state.
Save your progress? Sign up for free
Drill 6: Display progress in the client
Where you are: on cp1, in the second terminal, in
~/mcpa/tag09.What you have afterwards:
fortschritt.py(progress), which shows a bar during the check run.
# on cp1, in ~/mcpa/tag09
nano fortschritt.pyimport asyncio
from mcp import Client
URL = "http://worker1:8001/mcp"
async def anzeigen(fortschritt: float, gesamt: float | None, nachricht: str | None) -> None:
"""Wird für jede Fortschrittsmeldung des Servers aufgerufen."""
balken = "#" * int(fortschritt) + "." * int((gesamt or fortschritt) - fortschritt)
print(f"[{balken}] {fortschritt:.0f}/{gesamt:.0f} {nachricht}", flush=True)
async def main() -> None:
async with Client(URL) as client:
ergebnis = await client.call_tool("pruefen", {}, progress_callback=anzeigen)
for zeile in ergebnis.structured_content["result"]:
print(zeile)
asyncio.run(main())# on cp1, in ~/mcpa/tag09
uv run python fortschritt.pycall_tool(…, progress_callback=anzeigen)makes the SDK put a uniqueprogressTokeninto the request and callanzeigen(display) for every matching notification. You do not have to take care of the token.anzeigenreceivesfortschritt(progress),gesamt(total, can beNone), andnachricht(message). The bar consists of#for completed and.for remaining steps.(gesamt or fortschritt)takesfortschrittifgesamtis missing.{fortschritt:.0f}prints a number without decimal places. According to the specification,progressandtotalare numbers that may also be fractional.ergebnis.structured_content["result"]is the list of result lines.
Expected (line by line, about one second apart, numbers differ):
[#....] 1/5 /etc geprüft
[##...] 2/5 /usr/bin geprüft
[###..] 3/5 /usr/lib geprüft
[####.] 4/5 /usr/share geprüft
[#####] 5/5 /usr/include geprüft
/etc: 1478 Dateien
/usr/bin: 983 Dateien
/usr/lib: 17398 Dateien
/usr/share: 25340 Dateien
/usr/include: 1493 Dateien
Remember:
progress_callbacktakes care of the order number for you: the SDK sets the token and calls your function for every notification.
Save your progress? Sign up for free
If it doesn’t work
curl: (7) Failed to connect to worker1 port 8001:wache.pyis not running. Check the terminal on worker1.Invalid Host header: You are addressing the server by a name that is not inallowed_hosts. Useworker1or172.16.0.228, each with:8001.- Nothing appears after subscribing, not even an
acknowledgment:
-Nis missing, andcurlis buffering the output. - No events even though something changed: Check in
the acknowledgment what is subscribed.
wartungsmodusonly notifies when something really changes (Keine Änderung, “no change”, means: no notification). HTTP 406onsubscriptions/listen: TheAcceptheader is missingtext/event-stream.KeyError: 'result'infortschritt.py: The tool failed withisError. Look for the error in the terminal on worker1.
Exercise: What does the server acknowledge? (10 min)
Use curl to subscribe to changes of the
prompt list and to the resource
config://wache/gibtsnicht (“does not exist”). The server
has no prompts, and the URI does not exist. What does the acknowledgment
say? Build the body as a copy of listen.json and let
curl stop after three seconds.
Solution
The body: promptsListChanged instead of
toolsListChanged, and the URI that does not exist:
# on cp1, in ~/mcpa/tag09
nano uebung.json{"jsonrpc":"2.0","id":10,"method":"subscriptions/listen","params":{"notifications":{"promptsListChanged":true,"resourceSubscriptions":["config://wache/gibtsnicht"]},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}# on cp1, in ~/mcpa/tag09
curl -sN --max-time 3 http://worker1:8001/mcp "${KOPF[@]}" -H "Mcp-Method: subscriptions/listen" --data @uebung.jsonExpected: an acknowledgment
notifications/subscriptions/acknowledged. Its
data: line contains in the field notifications
(excerpt):
{"promptsListChanged":true,"resourceSubscriptions":["config://wache/gibtsnicht"]}
The server acknowledges both. A subscription is a promise to send
events of this kind when they occur – not a guarantee
that the URI exists. For a URI that does not exist, an event simply
never arrives. A client checks whether a resource exists with
resources/read.
Save your progress? Sign up for free
Challenge: A host with an up-to-date tool list (20 min)
Your host from Day 8 queries the tools only once at the start. If
someone switches on maintenance mode during a conversation, the model
does not know wartungsnotiz. Sketch how you would build
subscriptions/listen into host.py so that the
model gets the current list before every round.
Solution
One possible solution in pseudocode:
veraltet = anyio.Event() or one flag per server
async def zuhoeren(client):
async with client.listen(tools_list_changed=True) as abo:
async for _ in abo:
set flag
at startup: start zuhoeren(client) as a background task for every client
(for example in an anyio task group next to the conversation loop)
before every modell_fragen(…):
if a flag is set:
werkzeuge, zuordnung, ohne_rueckfrage = await werkzeuge_sammeln(clients)
reset flag
Three points matter. The subscription runs in
parallel with the conversation. The event only says that
something has changed – you fetch the list again yourself. And you also
have to recompute ohne_rueckfrage (without follow-up
question), because a new tool might change something and then needs a
follow-up question. A server that adds tools at runtime is also a
security topic: a tool that looked harmless at startup can have a
different description after a list_changed (Day 11).
Save your progress? Sign up for free
Checkpoint
# on cp1, in ~/mcpa/tag09
curl -sN --max-time 3 http://worker1:8001/mcp "${KOPF[@]}" -H "Mcp-Method: subscriptions/listen" --data @listen.json | grep -c subscriptions/acknowledgedExpected: 1
# on cp1, in ~/mcpa/tag09
grep -c progress_callback fortschritt.pyExpected: 1
Afterwards, stop the server on worker1 with Ctrl+C.
Exam questions
1. In version 2026-07-28, how does a client find out that a resource has changed?
- with
resources/subscribeand a notification on the GET stream
- with
- via
subscriptions/listenwith the URI inresourceSubscriptions
- via
- by repeating
resources/readevery few seconds – there is no other way
- by repeating
- the server sends the changed resource unprompted as a new request
2. What is the first message on a
subscriptions/listen stream?
notifications/subscriptions/acknowledgedwith the served filter
- the response with
result: {}
- the response with
notifications/initialized
- the first event, if one is already pending
3. A client has subscribed only to
resourceSubscriptions. The tool list on the server changes.
What happens on the stream?
notifications/tools/list_changedarrives anyway
- nothing; the server sends only what was subscribed to
- the server closes the stream
- the server sends a
-32602error
- the server sends a
4. What does a client have to do to receive progress
notifications for a tools/call?
- send
notifications/progressto the server beforehand
- send
- set a
progressTokenin the request’s_meta
- set a
- set
logging/setLeveltoinfo
- set
- nothing; the server always sends them
5. A subscription stream breaks. What applies?
- The client sends
subscriptions/resumeand receives the missed events.
- The client sends
- On the next subscription, the server replays all events from the last five minutes.
- The client opens a new subscription and reloads the affected data.
- Subscriptions cannot break.
Solutions
- B.
resources/subscribeand the GET stream no longer exist. Polling would work, but it is not the intended way. - A. The acknowledgment always comes first and names the served subset.
- B. The server may only send event types that are in the filter.
- B. No token, no progress; the notifications carry the same token.
- C. No replay: subscribe again and reload.
Interview Note
“Why doesn’t resources/updated include the new content
right away?” – Because an event should be small and reliable. If a
resource changes ten times in one second, a single reload is enough for
the client. Many clients do not need the content immediately at all, and
the server checks access rights again on read anyway. The same pattern
applies to list_changed: “Something has changed, ask
again.” Because there is no replay, reloading after a disconnect is
necessary anyway – the same code covers both cases.
Enterprise Note
Subscriptions are long-lived HTTP connections. In production this
means: the proxy in front needs a read timeout above the server’s ping
interval and must not buffer SSE (Day 8). A server with many clients
needs a limit on concurrent subscriptions – the SDK allows 1024 per
process by default – and, with several instances behind a load balancer,
a shared event bus. If the resource changes on instance A, the event
must also reach the subscribers on instance B. The SDK has an interface
for this (SubscriptionBus), which you can implement with
Redis Pub/Sub, for example. Progress notifications, on the other hand,
are uncritical: they belong to the request and travel over the same
connection.
Summary
- Messages from the server travel only on a request’s response stream:
progress on the stream of the
tools/call, events on the stream ofsubscriptions/listen. - Progress: the client sets
progressTokenin_meta; the server sendsnotifications/progresswithprogressToken, increasingprogress, and optionallytotalandmessage. No token, no notifications. subscriptions/listenwith the filtertoolsListChanged,promptsListChanged,resourcesListChanged,resourceSubscriptions. Firstnotifications/subscriptions/acknowledged, every message withio.modelcontextprotocol/subscriptionId=idof the request, only what was subscribed to, no replay after a disconnect.- Events only say that something has changed; the client reloads.
resources/subscribe,resources/unsubscribe, and the GET stream have been dropped (-32601).- SDK:
ctx.report_progress,ctx.notify_resource_updated,ctx.notify_tools_changed,mcp.add_tool/remove_tool; in the clientclient.listen(…)andcall_tool(…, progress_callback=…).
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 |
|---|---|---|
ctx: Context |
tool receives the request context | does not appear in the schema |
await ctx.report_progress(n, gesamt, text) |
report progress | only takes effect with progressToken |
await ctx.notify_resource_updated(uri) |
notify subscribers of the URI | exact URI |
await ctx.notify_tools_changed() |
report a changed tool list | also notify_prompts_changed,
notify_resources_changed |
mcp.add_tool(funktion, title=…) ·
mcp.remove_tool(name) |
add · remove a tool at runtime | – |
client.listen(tools_list_changed=…, resource_subscriptions=[…]) |
open a subscription | abo.honored,
async for ereignis in abo |
ResourceUpdated · ToolsListChanged |
event classes in the client | ereignis.uri |
client.call_tool(name, args, progress_callback=f) |
call a tool with progress | f(fortschritt, gesamt, nachricht) |
subscriptions/listen |
method for subscriptions | params.notifications = filter |
"_meta":{"progressToken":"…"} |
request progress | string or number, unique |
curl -sN … --max-time 3 |
show a stream live, stop after 3 s | – |
nano <file> |
create a body or program | – |