---
title: "Subscribe to resource updates in C#"
url: https://recursiveai.org/onemodelcontext/cookbook/subscribe-to-resource-updates/
description: "Listen for resource changes with OneModelContext, filter notifications by URI, read updated content, and close the listener with a runnable C# server."
version: "1.0.1"
---

# Subscribe to resource updates 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/subscribe-to-resource-updates/subscribe-to-resource-updates.zip)

Receive notifications when a resource changes, then read its updated content.

```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;

// Separate client; see setup below.
await using var client =
    await ContextClient.ConnectAsync(
    ContextTransport.Process("dotnet",
        ["run", "--no-build", "--", "serve"]));
await using var listener =
    await client.ListenAsync(new()
{
    ResourceSubscriptions = ["mem://status"]
});
using var timeout = new CancellationTokenSource(
    TimeSpan.FromSeconds(10));
await client.ReadResourceAsync("mem://status");
await foreach (var change in
    listener.ReadAllAsync(timeout.Token))
{
    Console.WriteLine(change.Uri);
    break;
}
```

Build the download first. Run this snippet in a separate client project, with the download folder as the working directory; it starts the built example as its server. The full program below needs no separate client project.

```text
mem://status
```

Unzip [the example](https://recursiveai.org/onemodelcontext/cookbook/subscribe-to-resource-updates/subscribe-to-resource-updates.zip), then `dotnet run`.

## The full program

The download runs both sides: a child process serves `mem://status`, and the client subscribes before its first read. That read releases the server’s update: it adds `mem://extra`, changes the status text from `before` to `after`, then notifies listeners. No external server or credentials are needed.

```csharp
using RecursiveAI.OneModelContext;
using RecursiveAI.OneModelContext.Protocol;
using System.Reflection;

if (args.Contains("serve"))
{
    var server = new ContextServer("changing-resource", "1.0");
    string text = "before";
    var read = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
    server.Resources.Add(new ResourceDefinition("mem://status", "Status"), (uri, _) =>
    {
        var result = new ReadResourceResult
        {
            Contents = [new TextResourceContents { Uri = uri, Text = text }]
        };
        read.TrySetResult();
        return ValueTask.FromResult(result);
    });
    var update = Task.Run(async () =>
    {
        await read.Task;
        server.Resources.Add(new ResourceDefinition("mem://extra", "Extra"), (uri, _) =>
            ValueTask.FromResult(new ReadResourceResult { Contents = [] }));
        text = "after";
        await server.NotifyResourceUpdatedAsync("mem://status");
    });
    await server.RunAsync(ContextTransport.Stdio());
    await update;
    return;
}
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10));
string assembly = Assembly.GetExecutingAssembly().Location;
await using var client = await ContextClient.ConnectAsync(
    ContextTransport.Process("dotnet", [assembly, "serve"]),
    new ContextClientOptions { Era = args.Contains("legacy") ? EraPreference.Legacy : EraPreference.Modern }, timeout.Token);
await using var subscription = await client.ListenAsync(new SubscriptionFilter
{
    ResourcesListChanged = true,
    ResourceSubscriptions = ["mem://status"]
}, timeout.Token);
// The first read releases the bundled server's update, after the listener exists.
await client.ReadResourceAsync("mem://status", timeout.Token);
int received = 0;
await foreach (var change in subscription.ReadAllAsync(timeout.Token))
{
    Console.WriteLine($"{change.Kind} {change.Uri}".TrimEnd());
    if (change.Kind == SubscriptionEventKind.ResourceUpdated)
    {
        var resource = await client.ReadResourceAsync(change.Uri!, timeout.Token);
        Console.WriteLine(((TextResourceContents)resource.Contents[0]).Text);
    }
    if (++received == 2) break;
}
await subscription.DisposeAsync();
Console.WriteLine($"Listener: {await subscription.Completion}");
```

```text
ResourcesListChanged
ResourceUpdated mem://status
after
Listener: Closed
```

The snippet at the top filters out list changes. The full program requests both resource-list changes and updates for one URI, reads the new content after the notification, then disposes the listener. Its cancellation token stops waiting if the expected events don’t arrive.

## Variations

**Talk to a legacy server.** Run `dotnet run -- legacy`. The example selects `EraPreference.Legacy` in `ContextClientOptions`; the same filter and read loop print the same output:

```text
ResourcesListChanged
ResourceUpdated mem://status
after
Listener: Closed
```

**Watch only the resource.** Replace the full program’s filter and event count with these values. The server still changes the resource list, but that event is not delivered to this listener.

```csharp
await using var subscription = await client.ListenAsync(new SubscriptionFilter
{
    ResourceSubscriptions = ["mem://status"]
}, timeout.Token);
```

Change the stopping condition to `if (++received == 1) break;`. It prints:

```text
ResourceUpdated mem://status
after
Listener: Closed
```

## Related recipes

- [Connect to a server](https://recursiveai.org/onemodelcontext/cookbook/connect-to-a-server/)
- [Talk to older servers](https://recursiveai.org/onemodelcontext/cookbook/talk-to-older-servers/)
- [Add tools at runtime](https://recursiveai.org/onemodelcontext/cookbook/add-tools-at-runtime/)

## The short answer

Call `ContextClient.ListenAsync` with a `SubscriptionFilter` containing the resource URIs you need. Consume `ReadAllAsync` with a cancellation token, re-read a resource when its update arrives, and dispose the `ContextSubscription` when you stop listening. Ask for resource-list changes separately if you also need to discover additions or removals.

For an MCP resource subscription (Model Context Protocol®), OneModelContext selects the wire behavior by the negotiated protocol era. Its [HTTP client documentation](https://recursiveai.org/onemodelcontext/docs/http-client/#subscriptions) states that `ListenAsync` opens `subscriptions/listen` on the modern revision and uses the GET stream and `resources/subscribe` on a legacy HTTP server. The example uses child-process streams so you can run it without setting up an HTTP service.

## How do I subscribe to resource updates in C#?

Connect the client, create the subscription, then begin the activity that can change the resource. The order matters: a notification is not a stored history of changes that happened before you subscribed. The fixture waits for the first resource read before issuing its change, and that read happens only after `ListenAsync` returns.

Use exact resource URIs in `ResourceSubscriptions`. In this example, `mem://status` is a server-defined identifier, not a file path or a web address to fetch. The server’s resource registration supplies the reader that returns its current text. If you change that identifier on the server, change the client filter too.

Consume events until your application has enough information, the subscription ends or cancellation is requested. The short example exits after the first update; the full program expects both a list change and a content update. In an application, route events to the component that owns the displayed data rather than leaving an unobserved background loop running after the screen has closed.

## What is the difference between resource updates and resource-list changes?

A resource update says that the content at a particular URI changed. It does not contain the replacement content. The full program handles `ResourceUpdated` by calling `ReadResourceAsync(change.Uri)` and printing the returned text. The notification identifies what to read; the read retrieves the current value.

A resource-list change says that the set of resources changed. Here, adding `mem://extra` produces `ResourcesListChanged`, while changing the text at `mem://status` produces `ResourceUpdated`. Watching a resource does not automatically ask for resource-list changes. The first variation shows how to exclude those events when you only care about a known URI.

Keep these paths distinct in your cache. A list notification can prompt rediscovery, while a content notification invalidates the cached value for one resource. Neither requires repeatedly polling an unchanged list. If you need every intermediate value, design that requirement into the resource itself; an update notification followed by a read gives you the value at read time, not an archive of each earlier value.

## How do resource subscriptions work with older servers?

The pinned docs distinguish the modern protocol revision, `2026-07-28`, from the legacy revisions. The modern subscription mechanism is `subscriptions/listen`. Legacy HTTP subscriptions use the GET notification stream together with `resources/subscribe`. The library also has a deprecated HTTP+SSE client fallback, but that is a transport fallback, not a replacement content feed.

The download’s `legacy` argument forces the client’s legacy era against the bundled server. It exercises the same application-facing listener API; the code that handles events does not need a second implementation. It does not exercise the HTTP fallback because the example uses a child process. When connecting to an existing HTTP server, use its documented endpoint and check that it supports the resource notifications you need.

## How do I stop listening for resource updates?

Cancel the read loop to stop waiting, and dispose the subscription to close it. `await using` ensures disposal also happens when your loop throws. The full program explicitly disposes before checking `Completion`, which reports `Closed` for this run.

Keep the client alive for as long as its subscriptions are needed. Disposing a client ends the connection; merely breaking out of an event loop does not express the lifetime of the whole client. A bounded cancellation token makes a missing notification visible instead of allowing a test or request to wait indefinitely.

Treat server-ended subscriptions and connection loss as different outcomes from your own deliberate closure. The [listener documentation](https://recursiveai.org/onemodelcontext/docs/http-limits/) describes the server and transport controls. Decide whether your application should reconnect or show stale data, rather than silently assuming that the last value is still current.
