Sub topic 13
Utilities: list-changed notifications, progress, cancellation, and logging
This chapter assumes you know the JSON-RPC message shapes (requests, responses, notifications), the initialization handshake, and how tools, resources, and prompts work. You should also be able to read basic async Python.
The core features cover what a server offers. The utilities cover how a long session behaves over time. A server's tool list can change, a call can take a minute, a user can give up on it, and a developer needs to see what happened. MCP handles all four with notifications, plus one small request for log levels.
Notifications are the common mechanism
A notification is a JSON-RPC message with a method but no id. The receiver never replies, and the sender never learns whether it was handled. This fits the utilities. A progress update that nobody reads does no harm, and a cancellation is a courtesy.
Every method name in this chapter follows the pattern notifications/..., except logging/setLevel, which is an ordinary request.
| Utility | Method | Sent by | Needs a declared capability |
|---|---|---|---|
| List changed | `notifications/tools/list_changed` and the `resources` and `prompts` equivalents | Server | Yes, `listChanged: true` |
| Resource updated | `notifications/resources/updated` | Server | Yes, `subscribe: true` |
| Progress | `notifications/progress` | Either side | No, but the request must carry a progress token |
| Cancellation | `notifications/cancelled` | Either side | No |
| Logging | `notifications/message` | Server | Yes, `logging: {}` |
| Set log level | `logging/setLevel` (request) | Client | Same `logging` capability |
List-changed notifications
A client usually calls tools/list once after initialization and caches the result. If the server later adds or removes a tool, the cache is stale. The server fixes this by announcing the change, and the client then asks again.
The server must declare this ability during initialization:
{
"capabilities": {
"tools": {"listChanged": true},
"resources": {"subscribe": true, "listChanged": true},
"prompts": {"listChanged": true}
}
}When something changes, the server sends a notification with no payload:
{"jsonrpc": "2.0", "method": "notifications/tools/list_changed"}The notification carries no data about what changed. The client has to call tools/list again and compare the result. This keeps the notification tiny and the list authoritative.
Resources add a second, finer mechanism. A client that sends resources/subscribe with a URI receives notifications/resources/updated when the content of that one resource changes. The notification includes the uri, and the client re-reads it with resources/read. Use list_changed when the set of items changes. Use updated when the contents of one item change.
When to emit list-changed
Typical reasons include:
- A tool becomes available after the user authenticates.
- A plugin or configuration file is loaded or removed.
- A resource directory gains a new file.
A server whose tool list never changes should not declare listChanged. Declaring it promises behavior you do not deliver, and clients may spend effort listening for it.
Progress reporting
A tool call that takes thirty seconds looks frozen without feedback. Progress notifications fix that, but only if the caller asks for them. The caller opts in by putting a progressToken in the request's _meta field:
{
"jsonrpc": "2.0",
"id": 7,
"method": "tools/call",
"params": {
"name": "slow_count",
"arguments": {"n": 5},
"_meta": {"progressToken": "job-7"}
}
}The token is a string or integer, and it must be unique among the active requests of that sender. While working, the server sends:
{
"jsonrpc": "2.0",
"method": "notifications/progress",
"params": {
"progressToken": "job-7",
"progress": 2,
"total": 5,
"message": "Step 2 of 5"
}
}The rules to remember:
progressmust increase with each notification. It does not have to be an integer.totalis optional, because many tasks do not know their size. Without it, a client can show a spinner and a count but not a percentage.messageis optional human-readable text.- Progress stops once the final response is sent. Notifications that arrive after a response refer to a finished request and should be ignored.
- Progress is not limited to tool calls. Any request can carry a token. It can also flow from client to server.
A server should not send updates at high frequency. A loop that reports every iteration of a million-row job floods the transport. Report on a time interval or at coarse milestones.
Cancellation
Either side can abandon a request it sent by notifying the other:
{
"jsonrpc": "2.0",
"method": "notifications/cancelled",
"params": {"requestId": 7, "reason": "User closed the panel"}
}requestId is the id of the request being cancelled. The receiver should stop the work, free any resources, and not send a response for that request. Because the notification travels asynchronously, a few edge cases follow from the protocol:
- Race with completion. The response may already be on the wire when the cancellation arrives. The sender of the cancel must tolerate receiving a normal response anyway. The receiver should ignore a cancellation for an unknown or finished request.
- Direction. You may only cancel requests that you issued earlier in the same session.
- Initialization. The
initializerequest must not be cancelled. - Side effects. Cancellation does not roll anything back. If a tool already wrote half a file, it stays written. Design tools so that stopping midway is safe.
Logging
Servers often need to tell the client what is going on without making it part of a tool result. The logging capability provides a structured channel for this. The server declares it:
{"capabilities": {"logging": {}}}The client may then choose a minimum severity:
{"jsonrpc": "2.0", "id": 3, "method": "logging/setLevel", "params": {"level": "warning"}}The server replies with an empty result, and from then on it sends only messages at that level or higher:
{
"jsonrpc": "2.0",
"method": "notifications/message",
"params": {
"level": "error",
"logger": "database",
"data": {"error": "Connection failed", "host": "db.internal"}
}
}The levels come from syslog (RFC 5424), from least to most severe: debug, info, notice, warning, error, critical, alert, emergency. The logger name is optional. The data field can be any JSON value.
Two cautions apply:
- Log messages go to the client, and the client may show them to a user or store them. Do not put secrets, tokens, or personal data in
data. - Protocol logging is separate from process logging. A stdio server must not print diagnostics to stdout, because stdout carries the JSON-RPC stream and stray text corrupts it. Write plain debugging output to stderr. Hosts typically capture stderr into their own log files.
Putting it together in Python
The official SDK exposes these utilities through the Context object that FastMCP injects into a tool when you add a parameter of that type.
import asyncio
from mcp.server.fastmcp import Context, FastMCP
mcp = FastMCP("utilities-demo")
@mcp.tool()
async def slow_count(n: int, ctx: Context) -> str:
"""Count to n, reporting progress and logging each step."""
for i in range(1, n + 1):
await ctx.info(f"Working on step {i}")
await ctx.report_progress(progress=i, total=n, message=f"Step {i} of {n}")
await asyncio.sleep(1)
return f"Counted to {n}"
if __name__ == "__main__":
mcp.run(transport="stdio")ctx.info sends a notifications/message at level info. ctx.report_progress sends notifications/progress only if the caller supplied a progress token, so the tool works the same whether or not anyone is watching. The message argument of report_progress needs a recent SDK release, so upgrade the mcp package if you get an error about it.
A client receives both streams by passing callbacks:
import asyncio
from mcp import ClientSession, StdioServerParameters, types
from mcp.client.stdio import stdio_client
async def on_progress(progress: float, total: float | None, message: str | None):
print(f"progress {progress}/{total}: {message}")
async def on_log(params: types.LoggingMessageNotificationParams):
print(f"[{params.level}] {params.data}")
async def main():
params = StdioServerParameters(command="python", args=["server.py"])
async with stdio_client(params) as (read, write):
async with ClientSession(read, write, logging_callback=on_log) as session:
await session.initialize()
await session.set_logging_level("info")
result = await session.call_tool(
"slow_count", {"n": 3}, progress_callback=on_progress
)
print(result.content)
asyncio.run(main())Save the server as server.py and run the client. You should see three log lines, three progress lines, and then the result.
Common errors
- Stale tool lists. A server changes its tools but never notifies, or notifies without declaring
listChanged. The model keeps calling a tool that no longer exists. - No progress appears. The request had no
_meta.progressToken, so the server had nothing to attach updates to. Progress is opt-in. - Progress goes backwards. Reporting a smaller
progressvalue than the previous one violates the protocol. Some clients drop it. - Corrupted stdio stream. A
print()in a stdio server writes to stdout and breaks framing. Usectx.info,loggingto stderr, orprint(..., file=sys.stderr). - Expecting a response after cancelling. After a cancel, the sender should not wait indefinitely for the result. Mark the request abandoned locally.
- Leaking data through logs. Treat every
notifications/messageas visible to the user.
Exercise
A client sends tools/call with id 12 and no _meta field. The server's tool reports progress through a context helper. What does the client receive while the tool runs, and why?
Show answer
It receives no notifications/progress messages. Progress is opt-in, and the client did not include a progressToken in meta, so the server has no token to attach updates to. The helper silently does nothing. The client still gets the final response with id 12. To get updates, the client would resend the call with "meta": {"progressToken": "some-unique-value"}.
Exercise
A server adds a new tool after startup and sends notifications/tools/list_changed. What must the client do next, and what should it never assume about the notification?
Show answer
The client must call tools/list again and replace its cached list with the result. It must not assume the notification says what changed, because the notification has no payload. It also should not assume the notification will arrive at all unless the server declared tools.listChanged as true during initialization.
Exercise
A stdio server needs to record a debugging message that should not reach the user's chat window. Where should it write, and why not stdout?
Show answer
It should write to stderr, which hosts usually capture in their own log files. Stdout carries the JSON-RPC stream, so any extra text there corrupts the message framing and can break the session. Messages sent through notifications/message are protocol logs and go to the client, so they are the wrong place for private debugging output.