Skip to content
MCPA · Chapter 11 of 21 Day 9: Subscriptions and progress

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.py

Expected: 2

# on cp1
grep -c worker1 ~/mcpa/tag08/host.py

Expected: 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 progressToken and notifications/progress,
  • how subscriptions/listen is structured: filter, acknowledgment, identifier, end without replay,
  • the events notifications/resources/updated and notifications/tools/list_changed,
  • how a server adds and removes tools at runtime,
  • why resources/subscribe no 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:

  1. The first message on the stream is notifications/subscriptions/acknowledged. It names the subset of the filter that the server actually serves.
  2. Every message carries the key io.modelcontextprotocol/subscriptionId in _meta, with the id of the listen request. This lets a client tell several subscriptions apart.
  3. The server sends only what is in the filter.
  4. 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 wache on 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.py
~/mcpa/tag09/wache.py new file
import 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.py

Expected (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: Context as a tool parameter: the SDK recognizes the type Context and 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 resource config://wache/grenzwert outputs it as JSON (json.dumps). After a restart, it contains 85 again.
  • grenzwert_setzen (set threshold) changes the value and then calls await 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, and p.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 a progressToken, 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 whether wartungsnotiz is 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 without Origin (curl, SDK) still get through, as on Day 8.
  • port=8001, so that wache can run next to the control room from Day 8.

Remember: ctx: Context gives a tool the line to the front desk: report_progress for progress, notify_resource_updated and notify_tools_changed for 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
~/mcpa/tag09/pruefen.json new file
{"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
~/mcpa/tag09/pruefen-ohne.json new file
{"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.json

Expected (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 progressToken the server switches to SSE and sends increasing progress values 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
~/mcpa/tag09/listen.json new file
{"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
~/mcpa/tag09/grenzwert.json new file
{"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
~/mcpa/tag09/wartung.json new file
{"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.json

Expected (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/tag09

Each 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.content

Expected:

[{"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.content

Expected:

[{"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/updated names only the uri, not the new value.
  • notifications/tools/list_changed has 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
~/mcpa/tag09/listen-grenzwert.json new file
{"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.json

Expected: 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
~/mcpa/tag09/wartung-aus.json new file
{"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.content

Expected:

[{"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
~/mcpa/tag09/subscribe.json new file
{"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.json

Expected:

{"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.json

Expected:

HTTP 406
  • resources/subscribe no longer exists in version 2026-07-28: -32601 with 404.
  • A subscription is an SSE stream. Anyone who accepts only application/json gets 406.

Remember: The server sends only what is in the filter. resources/subscribe no longer exists, and without text/event-stream there 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.py
~/mcpa/tag09/beobachter.py new file
import 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.py
  • from 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 with waits until the acknowledgment has arrived and closes the stream when the block is left.
  • abo.honored is 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 raises SubscriptionLost – a client would then have to subscribe again and reload.
  • isinstance(ereignis, ResourceUpdated): the resource is read again with read_resource.
  • isinstance(ereignis, ToolsListChanged): the tool list is fetched again with list_tools.
  • flush=True prints 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
~/mcpa/tag09/grenzwert80.json new file
{"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.content

Expected:

[{"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.content

Expected:

[{"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_resource and list_tools fetch 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.py
~/mcpa/tag09/fortschritt.py new file
import 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.py
  • call_tool(…, progress_callback=anzeigen) makes the SDK put a unique progressToken into the request and call anzeigen (display) for every matching notification. You do not have to take care of the token.
  • anzeigen receives fortschritt (progress), gesamt (total, can be None), and nachricht (message). The bar consists of # for completed and . for remaining steps. (gesamt or fortschritt) takes fortschritt if gesamt is missing.
  • {fortschritt:.0f} prints a number without decimal places. According to the specification, progress and total are 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_callback takes 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.py is not running. Check the terminal on worker1.
  • Invalid Host header: You are addressing the server by a name that is not in allowed_hosts. Use worker1 or 172.16.0.228, each with :8001.
  • Nothing appears after subscribing, not even an acknowledgment: -N is missing, and curl is buffering the output.
  • No events even though something changed: Check in the acknowledgment what is subscribed. wartungsmodus only notifies when something really changes (Keine Änderung, “no change”, means: no notification).
  • HTTP 406 on subscriptions/listen: The Accept header is missing text/event-stream.
  • KeyError: 'result' in fortschritt.py: The tool failed with isError. 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
~/mcpa/tag09/uebung.json new file
{"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.json

Expected: 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/acknowledged

Expected: 1

# on cp1, in ~/mcpa/tag09
grep -c progress_callback fortschritt.py

Expected: 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?

    1. with resources/subscribe and a notification on the GET stream
    1. via subscriptions/listen with the URI in resourceSubscriptions
    1. by repeating resources/read every few seconds – there is no other way
    1. the server sends the changed resource unprompted as a new request

2. What is the first message on a subscriptions/listen stream?

    1. notifications/subscriptions/acknowledged with the served filter
    1. the response with result: {}
    1. notifications/initialized
    1. 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?

    1. notifications/tools/list_changed arrives anyway
    1. nothing; the server sends only what was subscribed to
    1. the server closes the stream
    1. the server sends a -32602 error

4. What does a client have to do to receive progress notifications for a tools/call?

    1. send notifications/progress to the server beforehand
    1. set a progressToken in the request’s _meta
    1. set logging/setLevel to info
    1. nothing; the server always sends them

5. A subscription stream breaks. What applies?

    1. The client sends subscriptions/resume and receives the missed events.
    1. On the next subscription, the server replays all events from the last five minutes.
    1. The client opens a new subscription and reloads the affected data.
    1. Subscriptions cannot break.

Solutions

  1. B. resources/subscribe and the GET stream no longer exist. Polling would work, but it is not the intended way.
  2. A. The acknowledgment always comes first and names the served subset.
  3. B. The server may only send event types that are in the filter.
  4. B. No token, no progress; the notifications carry the same token.
  5. 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 of subscriptions/listen.
  • Progress: the client sets progressToken in _meta; the server sends notifications/progress with progressToken, increasing progress, and optionally total and message. No token, no notifications.
  • subscriptions/listen with the filter toolsListChanged, promptsListChanged, resourcesListChanged, resourceSubscriptions. First notifications/subscriptions/acknowledged, every message with io.modelcontextprotocol/subscriptionId = id of 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 client client.listen(…) and call_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 –

Contents

More