How to Implement MCP Progress Notifications and Cancellation in ASP.NET Core 10 Using C# – Long-Running Tools, Timeouts and Error Handling (2026)
How to Implement MCP Progress Notifications and Cancellation in ASP.NET Core 10 Using C# – Long-Running Tools, Timeouts and Error Handling (2026)
A document-processing tool starts a batch of three files. The user needs to know whether it is working and needs a way to stop it. The server needs to release resources even if the connection closes before the result arrives. MCP progress notifications provide interim status. Cooperative cancellation and explicit deadlines bound the work.
This tutorial builds an ASP.NET Core 10 server and C# client using the official MCP C# SDK 2.3.1 and protocol revision 2026-07-28. The read-only batch uses built-in documents, so you can reproduce the success, cancellation and failure paths without a model provider, database, or external documents.
What are MCP progress notifications?
A progress notification is a one-way message that reports how far an active MCP request has advanced. The caller asks for progress by including an opaque string or integer in params._meta.progressToken. The token must be unique across active requests. A supporting server echoes the same token with a strictly increasing progress value, plus optional total and human-readable message. The server can choose to send no updates. The final tool result remains the source of truth for success. See the official progress specification.
How do you report MCP tool progress in C#?
On the client, pass an IProgress<ProgressNotificationValue> to CallToolAsync. The SDK includes a request token and routes matching updates back to that reporter. On the server, read the incoming token from the request context and call NotifyProgressAsync with the original token. Skip notifications when the token is absent. The same document-processing code works in both cases. Some MCP hosts do not display progress even when the server supports it. See the C# progress guide and McpClient API.
The request ID identifies the RPC. The progress token correlates interim updates. Treat both as scoped protocol values. Neither is a job ID, retry key, permission, or proof that an operation committed. Keep UI state keyed by operation so a late event cannot update a new request. When a total is unknown, display an indeterminate indicator or completed units. A changing total can make the percentage fall even while progress increases.
The following snippets show the message fields, omitting the HTTP envelope and other required metadata. The runnable client generates them through the SDK.
Progress versus logging
| Signal | Audience | Example |
|---|---|---|
| MCP progress | Requesting client or user | Processed two of three documents |
| Application logging | Server operators | Work deadline reached or slot released |
| Final tool result | Requesting client | Summary or tool error |
This sample uses server-side ILogger. That is separate from MCP logging notifications. Avoid logging every progress event or including file bodies, credentials, raw paths, or untrusted cancellation reason text. Use a trace ID for diagnostics and bounded metric labels. For very fine-grained work, coalesce updates by item count or elapsed time to limit network and UI overhead.
How does MCP cancellation work?
Cancellation asks an in-progress request to stop. In July 2026 Streamable HTTP, closing the request’s SSE response stream signals cancellation. The server treats the disconnect as cancellation of that request. With stdio, the client sends notifications/cancelled carrying the original request ID, with an optional reason. Legacy initialized Streamable HTTP through November 2025 also uses the explicit notification rather than interpreting an ordinary disconnect as cancellation. See the cancellation specification, Streamable HTTP binding, and SDK compatibility guide.
For the explicit notification, the ID must refer to an active request previously issued by the client. There is no RPC acknowledgment. A cancellation may race a result already sent. The caller should discard responses that arrive after it abandons the call. A server can ignore an unknown, completed, or noncancelable request. Ordinary tool handlers should not send server-side cancellation notifications. The modern spec uses those server notifications to terminate subscription streams, a different flow.
Does cancellation stop execution immediately?
No. The SDK exposes a CancellationToken to the tool. Application work stops when it checks the token or awaits an operation that observes it. Pass the token to delay, HTTP, and storage APIs that support it. Poll at reasonable boundaries in CPU-bound work. A library that ignores the token can keep running. Task.WhenAny can stop the waiter while leaving the underlying task active. See cooperative cancellation in .NET.
If a proxy buffers SSE or delays disconnect propagation, browser behavior and server cleanup timing can differ from a direct local call. Configure and test the proxy end to end. For July Streamable HTTP, request-scoped progress flows on the originating response stream. A separate subscription stream does not carry tool progress. A progress UI should tolerate missed events and never assume that seeing all steps means the final result arrived.
How do you handle timeouts?
Give the client a maximum waiting budget and the server its own maximum work budget. If the client deadline expires, the caller stops waiting and signals cancellation through the active transport. If the server deadline expires while the caller remains connected, the server can return a safe tool error. Keep the budgets distinct in logs and user messages.
This lab uses a three-second server work deadline and an eight-second normal client deadline. The special client-timeout scenario uses a 200 ms deadline to demonstrate abandonment. Neither budget extends when progress arrives. If you reset an idle timer after useful progress, keep a hard maximum deadline as well.
Create the ASP.NET Core 10 projects
Install .NET 10 SDK and use a terminal with OpenSSL for the lab secret. Pin the official HTTP server and Core client packages to SDK 2.3.1. The server package includes hosting and dependency injection. The Core package is enough for the terminal client. See the ASP.NET Core package, Core package, and SDK v2 release overview.
The example uses a loopback endpoint and random bearer key shared by the two terminal processes. It rejects browser Origin headers, checks the Host header, caps request bodies, and allows at most two concurrent batches per process. This is a local lab, not a remote authentication design. Use HTTPS, validated caller identity, and per-user authorization for a deployed service. For server fundamentals, see Build an MCP server in C#.
Implement the server and document batch
Configure the host and dependencies
Replace BatchServer/Program.cs. The host uses stateless Streamable HTTP with a single MCP endpoint. Dependency injection owns the shared concurrency gate and batch service. A global bound is a useful last line of defense, but production services also need limits per identity or tenant so one caller cannot fill every slot.
Process documents and report completed steps
Create DocumentBatch.cs. The built-in documents contain five, nine, and seven UTF-8 bytes. The artificial delay makes the cancellation and progress paths easy to see. Each stream is scoped with await using. It is disposed before reporting the completed step and is also disposed if a delay or read throws. The result remains in memory until all three documents finish. The tool never writes external state.
Bind the progress token and linked cancellation
Create BatchTools.cs. The tool validates the scenario and tries to acquire a slot without queueing. It builds a linked token from the incoming MCP cancellation and the server deadline. If both signals are present when the catch runs, request cancellation takes precedence. The timeout and simulated failure return safe errors, and the finally block releases the slot once. There is one result path and no detached background callback that could report after completion.
The tool uses an MCP tool error for a known failure, which can arrive within HTTP 200. An HTTP status applies to the transport, while isError applies to tool execution. If the request is canceled or the connection is gone, the caller may receive no final result at all. Application-wide error handling is a separate concern covered in the ASP.NET PB global exception handling guide.
Implement the C# client
Replace BatchClient/Program.cs. The client pins the July protocol. It uses an inline reporter so the scripted cancel case can signal cancellation after the first callback. A GUI should dispatch updates to its UI thread and keep that callback fast. The callback is optional. In quiet mode, the client sends no progress token through this overload and still receives the final summary.
The sample creates a separate cancellation source for user intent and another for the client deadline. This lets it report two different outcomes without parsing exception messages. Ctrl+C uses the same caller cancellation as the scripted test. A server-side deadline arrives through the tool-result path while the client’s eight-second budget is still active.
Run the tool and test its outcomes
Open two shells in the project root. Generate a random key and make the same value available to the client shell without recording it in source or logs. Keep the server on loopback.
| Scenario | Expected client behavior | Server-side evidence |
|---|---|---|
| normal | Progress 1/3 through 3/3, then summary | Completion and released slot |
| quiet | Same summary without progress | Completion and released slot |
| cancel | First update, then caller cancellation | Canceled request and released slot |
| client-timeout | Client stops waiting | Request cancellation once the transport detects it |
| timeout | Server-deadline tool error | Server budget warning and released slot |
| failure | Tool error after first completed document | Sample failure warning and released slot |
After testing cancel or timeout, run normal again and inspect the server’s slot release log. The client’s cancellation message only proves it stopped waiting. The server log confirms it observed cancellation and left the guarded section. To test network interruptions in your deployment, close the transport after receiving a progress event and inspect server traces. Repeat through the production reverse proxy, where buffering and timeout behavior can differ. Avoid using elapsed milliseconds as a hard test assertion.
Test batch behavior without a network
Put this code in BatchChecks/Program.cs and run dotnet run --project BatchChecks. It checks result bytes, increasing progress, the missing reporter path, cancellation after one update, and a partial failure. The loopback scenarios separately test the SDK and HTTP transport.
The projects compiled on Linux with .NET SDK 10.0.100 and MCP C# SDK 2.3.1. All five isolated checks passed. All six loopback scenarios produced the expected outcomes. Server logs recorded cancellation and slot release for both caller cancellation and the short client deadline. A final normal call succeeded. The tests used direct loopback HTTP. Legacy HTTP, stdio, and proxy behavior are documented here but were outside the executed tests.
Avoid partial writes, duplicate work, and retry storms
Progress is visibility, not a commit log. A tool can emit its last update and then fail before its result arrives. A client can lose the response after a real write commits. For a read-only operation, a bounded retry may be acceptable. For writes, use a durable operation ID and an idempotency key scoped to the caller and payload. Persist the operation outcome atomically with the write and let a retry query the existing result. Never use the progress token as an idempotency key.
For a service that writes staged output, use a transaction or temporary artifact with explicit promotion. Keep cleanup independent of an already canceled request token where appropriate, and bound asynchronous cleanup with a separate deadline. Log cleanup failures so operators can reconcile them. For work that should outlive an HTTP connection, design a durable job with explicit status, cancel and retention semantics. This request-scoped sample does not promise durable progress or resumption.
Deployment checklist
- Bound document count, total bytes, concurrency and work duration before allocating costly resources.
- Authorize work and any cancellation endpoint against the same caller or tenant. Use standard remote MCP authentication and transport security.
- Test SSE flushing, proxy idle timeouts, disconnect propagation and graceful shutdown.
- Record final outcome, latency, and cleanup status. Avoid document text, credentials, and raw request metadata in logs.
- Measure notification frequency and apply backpressure. Keep completion separate from UI progress.
- Add failure and cancellation tests at real I/O boundaries. For a deployment starting point, see Deploy ASP.NET Core 10 Web API to IIS.
Troubleshooting
| Symptom | Check | What to do |
|---|---|---|
| No progress events | Client supplied a token, handler can report, and proxy flushes SSE | Compare direct loopback with proxied requests and confirm the client registers a reporter |
| Progress appears only at the end | Proxy or middleware buffers the response | Check streaming behavior and ensure middleware does not collect the whole response |
| Cancel returns locally while server keeps working | Server has not observed disconnect, or downstream work ignores its token | Inspect server logs and propagate the token to every cancellable dependency |
| A second result appears after retry | First call may have finished despite lost response | Correlate durable operation state and use scoped idempotency for writes |
| Client times out before a useful error arrives | Client deadline is shorter than the server work deadline | Set deliberate budgets and distinguish them in logs |
| HTTP 401 or 403 in the lab | Bearer key, Host or Origin restriction | Match both keys and use the fixed loopback console endpoint |
Frequently asked questions
Can an MCP client cancel a running tool?
Yes, for a client and transport that support cancellation. Cancel the token passed to the SDK call. The July 2026 HTTP binding closes the request’s response stream, while stdio sends a cancellation notification. Actual cleanup still depends on the server and its dependencies honoring cancellation.
What happens if the client does not provide a progress token?
The tool still runs and returns its result. It skips progress notifications because there is no active token with which to correlate them.
Is the last progress update proof of success?
No. The final tool response confirms success for the caller. A durable write may need an operation status lookup if that response is lost.
How do you test MCP cancellation in ASP.NET Core?
Trigger cancellation after an observed progress event, assert the client stopped waiting, then verify the server logs and resource state. A repeat successful call helps verify the service remains usable. Include a separate deadline test and an explicit failure test.
Conclusion and further reading
Give progress updates a request scope, pass cancellation through to the work, and release resources on every exit path. The sample demonstrates those boundaries with three deterministic documents, a single terminal result, and separate caller and server deadlines.
- MCP progress, cancellation, and Streamable HTTP.
- Official C# SDK repository and C# progress guide.
- Cooperative cancellation in .NET.
Related follow-up topics include durable MCP jobs with tenant-scoped cancellation, testing SSE through IIS, and retry-safe tool writes with an operation ledger.
Comments
Post a Comment