Skip to content

Commit 6889563

Browse files
committed
Adding subscriptions
1 parent 061316b commit 6889563

2 files changed

Lines changed: 75 additions & 1 deletion

File tree

samples/EverythingServer/Program.cs

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,14 @@
33
using ModelContextProtocol.Protocol.Types;
44
using EverythingServer.Tools;
55
using EverythingServer;
6+
using ModelContextProtocol.Server;
7+
using Microsoft.Extensions.AI;
8+
using Microsoft.Extensions.DependencyInjection;
69

710
var builder = Host.CreateEmptyApplicationBuilder(settings: null);
811

12+
HashSet<string> subscriptions = [];
13+
914
builder.Services
1015
.AddMcpServer()
1116
.WithStdioServerTransport()
@@ -97,6 +102,43 @@
97102
});
98103
}
99104
})
105+
.WithSubscribeToResourcesHandler(async (ctx, ct) =>
106+
{
107+
var uri = ctx.Params?.Uri;
108+
109+
if (uri is not null)
110+
{
111+
subscriptions.Add(uri);
112+
113+
await ctx.Server.RequestSamplingAsync([
114+
new ChatMessage(ChatRole.System, "You are a helpful test server"),
115+
new ChatMessage(ChatRole.User, $"Resource {uri}, context: A new subscription was started"),
116+
],
117+
options: new ChatOptions
118+
{
119+
MaxOutputTokens = 100,
120+
Temperature = 0.7f,
121+
},
122+
cancellationToken: ct);
123+
}
124+
125+
return new EmptyResult();
126+
})
127+
.WithUnsubscribeFromResourcesHandler((ctx, ct) =>
128+
{
129+
var uri = ctx.Params?.Uri;
130+
if (uri is not null)
131+
{
132+
subscriptions.Remove(uri);
133+
}
134+
return Task.FromResult(new EmptyResult());
135+
})
100136
;
101137

102-
await builder.Build().RunAsync();
138+
builder.Services.AddHostedService(sp =>
139+
{
140+
var server = sp.GetRequiredService<IMcpServer>();
141+
return new SubscriptionMessageSender(server, subscriptions);
142+
});
143+
144+
await builder.Build().RunAsync();
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
using Microsoft.Extensions.Hosting;
2+
using ModelContextProtocol.Protocol.Types;
3+
using ModelContextProtocol.Server;
4+
using ModelContextProtocol.Protocol.Messages;
5+
6+
internal class SubscriptionMessageSender(IMcpServer server, HashSet<string> subscriptions) : IHostedService
7+
{
8+
public async Task StartAsync(CancellationToken cancellationToken)
9+
{
10+
while (!cancellationToken.IsCancellationRequested)
11+
{
12+
foreach (var uri in subscriptions)
13+
{
14+
await server.SendMessageAsync(new JsonRpcNotification
15+
{
16+
Method = "notifications/resource/updated",
17+
Params = new ResourceUpdatedNotificationParams
18+
{
19+
Uri = uri,
20+
}
21+
}, cancellationToken);
22+
}
23+
24+
await Task.Delay(5000, cancellationToken);
25+
}
26+
}
27+
28+
public Task StopAsync(CancellationToken cancellationToken)
29+
{
30+
return Task.CompletedTask;
31+
}
32+
}

0 commit comments

Comments
 (0)