---
title: "Resume server-sent events after a disconnect in C#"
url: https://recursiveai.org/onemodelcontext/cookbook/resume-protocol-sse-stream-after-disconnect/
description: "Reconnect to a legacy Model Context Protocol® event stream with Last-Event-ID, and cap the retry delay and the number of resume attempts."
version: "1.0.1"
---

# Resume server-sent events after a disconnect in C#

**OneModelContext** is a free, open-source .NET SDK for the Model Context Protocol® from Recursive AI. MIT or Apache-2.0, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneModelContext) · [GitHub](https://github.com/recursive-ai-oss/onemodelcontext-csharp) · [Docs](https://recursiveai.org/onemodelcontext/docs/) · [Download example (.zip)](https://recursiveai.org/onemodelcontext/cookbook/resume-protocol-sse-stream-after-disconnect/resume-protocol-sse-stream-after-disconnect.zip)

Resume Model Context Protocol® (MCP) Streamable HTTP streams on servers that replay events, not arbitrary server-sent event endpoints. `EraPreference.Legacy` selects legacy negotiation: Streamable HTTP revisions from 2025-03-26 through 2025-11-25 support sessions and optional event replay.

```shell
dotnet add package RecursiveAI.OneModelContext
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using RecursiveAI.OneModelContext;

var retry = new HttpTransportOptions
{
    MaxResumeAttempts = 2,
    MaxRetryDelay =
        TimeSpan.FromSeconds(1)
};
// Pass the legacy URL as args[0].
var pipe = ContextTransport.Http(
    new Uri(args[0]), options: retry);
await using var client = await
    ModelContext.ConnectAsync(
        pipe, EraPreference.Legacy);
await client.ListToolsAsync();
Console.WriteLine("Tool list received.");
```

Prints `Tool list received.` after the server replies. In the zip’s local example it arrives on a resumed stream, without a second tool-list POST. To get a URL for `args[0]`, unzip the example and run `dotnet run -- serve`, then pass the printed URL to the snippet while the server is still running.

Unzip [the example](https://recursiveai.org/onemodelcontext/cookbook/resume-protocol-sse-stream-after-disconnect/resume-protocol-sse-stream-after-disconnect.zip), then `dotnet run`.

## The full program

The example serves a scripted 2025-11-25 endpoint on loopback. On the first tool-list POST it sends `id: 7`, `retry: 25`, and an empty `data:` field, then ends the response. The resume handler requires `Last-Event-ID: 7` and the original session ID. It sends event 8 with the result for the original request ID. The project references `Microsoft.AspNetCore.App` only to run the local fixture.

```csharp
using System.Text.Json;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Hosting;
using RecursiveAI.OneModelContext;

var builder = WebApplication.CreateBuilder();
builder.Logging.ClearProviders();
await using var fixture = builder.Build();
fixture.Urls.Add("http://" + System.Net.IPAddress.Loopback + ":0");
var requestId = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
int listPosts = 0;
fixture.MapPost("/protocol", async (HttpContext http) =>
{
    using var request = await JsonDocument.ParseAsync(http.Request.Body);
    var body = request.RootElement;
    if (!body.TryGetProperty("id", out var id))
        return Results.Accepted();
    if (body.GetProperty("method").GetString() == "initialize")
    {
        http.Response.Headers["Mcp-Session-Id"] = "local-session";
        return Results.Json(new { jsonrpc = "2.0", id = id.Clone(), result = new {
            protocolVersion = "2025-11-25", capabilities = new { tools = new { } },
            serverInfo = new { name = "Local", version = "1.0" }
        }});
    }
    Interlocked.Increment(ref listPosts);
    requestId.SetResult(id.GetRawText());
    // Remember event 7, then end the response without a JSON-RPC result.
    return Results.Text("id: 7\nretry: 25\ndata:\n\n", "text/event-stream");
});
fixture.MapGet("/protocol", async (HttpContext http) =>
{
    if (!http.Request.Headers.ContainsKey("Last-Event-ID"))
        return Results.StatusCode(405);
    if (http.Request.Headers["Last-Event-ID"] != "7" ||
        http.Request.Headers["Mcp-Session-Id"] != "local-session")
        return Results.BadRequest();
    Console.WriteLine("Resume GET: Last-Event-ID = 7");
    var id = await requestId.Task.WaitAsync(http.RequestAborted);
    var reply = $$$"""{"jsonrpc":"2.0","id":{{{id}}},"result":{"tools":[]}}""";
    return Results.Text($"id: 8\ndata: {reply}\n\n", "text/event-stream");
});
fixture.MapDelete("/protocol", () => Results.NoContent());
await fixture.StartAsync();
var endpoint = new Uri(new Uri(fixture.Urls.Single()), "/protocol");
if (args is ["serve"])
{
    Console.WriteLine(endpoint);
    await fixture.WaitForShutdownAsync();
    return;
}

var options = new HttpTransportOptions
{
    OpenListeningStream = false,
    MaxResumeAttempts = 2,
    MaxRetryDelay = TimeSpan.FromSeconds(1)
};
var transport = ContextTransport.Http(endpoint, options: options);
await using var client = await ModelContext.ConnectAsync(transport, era: EraPreference.Legacy);
await client.ListToolsAsync();
Console.WriteLine("Tool list received.");
Console.WriteLine($"Tool list POSTs: {listPosts}");
```

```text
Resume GET: Last-Event-ID = 7
Tool list received.
Tool list POSTs: 1
```

If the stream ends before a reply and there’s no event ID to resume from, a legacy request fails instead of being sent again as a new POST.

## Variations

To allow a single consecutive resume attempt instead of two, change this option; the demonstrated one-resume sequence still completes:

```csharp
MaxResumeAttempts = 1,
```

## Related recipes

- [Connect to older protocol servers](https://recursiveai.org/onemodelcontext/cookbook/talk-to-older-servers/)
- [Subscribe to resource updates](https://recursiveai.org/onemodelcontext/cookbook/subscribe-to-resource-updates/)
- [Limit HTTP client response size](https://recursiveai.org/onemodelcontext/cookbook/set-http-client-response-limits/)

---

## The short answer

The client resumes a dropped **legacy Streamable HTTP** stream with a GET carrying `Last-Event-ID` when it has an event ID to send. Set `MaxResumeAttempts` to bound consecutive resumes without progress and `MaxRetryDelay` to cap the wait. The server must understand the ID and be able to replay the events. This is not an automatic reconnect for every server-sent events endpoint.

## How do I reconnect to a server-sent events stream with Last-Event-ID?

Connect to the same Streamable HTTP endpoint. You don’t have to build the resume GET yourself: the transport sends it with the event ID it last received and the legacy session ID when there is one. A resume asks for what happened after that event. In the example, the GET receives event 8 carrying the answer to the original request, not a response to a new tool-list POST.

On the server, replay requires keeping events for a time. OneModelContext’s [server endpoint options](https://github.com/recursive-ai-oss/onemodelcontext-csharp/blob/d72d78c39c934697857be92dd8514efd4c415a88/src/RecursiveAI.OneModelContext/Hosting/StreamableHttpOptions.cs#L80-L85) include the number of events retained per legacy stream; old events are dropped. A reconnect after an event has fallen out of the replay history can’t recover it by simply raising the client’s retry count.

## Does an event stream retry indefinitely?

Not with the defaults here. The [transport options](https://recursiveai.org/onemodelcontext/docs/http-client/#limits-and-defaults) allow five consecutive resume attempts without another event arriving. When the server has sent no `retry` hint, the delay defaults to one second. The default maximum delay is 30 seconds even if the server suggests a longer wait. A stream that stops sending events or keep-alive comments is treated as broken after `StreamIdleTimeout`, which defaults to five minutes. The example ends its first HTTP response immediately instead of waiting for this timeout.

The [2026-07-28 revision](https://recursiveai.org/onemodelcontext/docs/http-client/#what-each-era-does-on-the-wire) has no session or event replay. Its transport can reissue an interrupted ordinary request as a new request with a new ID, up to `MaxReissues` (two by default). That distinction matters for tools with side effects: replay of a response doesn’t run the tool again, but a fresh request may. For `subscriptions/listen` on that revision, re-opening is the caller’s job.
