csharp-sdk/samples/EverythingServer/LoggingUpdateMessageSender.cs
Tyler Kendrick 03e3094dcc
Fix and enhance cancellation operations across MCP Sessions. (#179)
* Propagate CancellationToken request cancellation to remote endpoint

* Refactor existing tests to have a shared base class

* Add cancellation tests

---------

Co-authored-by: Stephen Toub <stoub@microsoft.com>
2025-04-08 16:12:12 -04:00

42 lines
No EOL
1.5 KiB
C#

using Microsoft.Extensions.Hosting;
using ModelContextProtocol;
using ModelContextProtocol.Protocol.Types;
using ModelContextProtocol.Server;
namespace EverythingServer;
public class LoggingUpdateMessageSender(IMcpServer server, Func<LoggingLevel> getMinLevel) : BackgroundService
{
readonly Dictionary<LoggingLevel, string> _loggingLevelMap = new()
{
{ LoggingLevel.Debug, "Debug-level message" },
{ LoggingLevel.Info, "Info-level message" },
{ LoggingLevel.Notice, "Notice-level message" },
{ LoggingLevel.Warning, "Warning-level message" },
{ LoggingLevel.Error, "Error-level message" },
{ LoggingLevel.Critical, "Critical-level message" },
{ LoggingLevel.Alert, "Alert-level message" },
{ LoggingLevel.Emergency, "Emergency-level message" }
};
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
var newLevel = (LoggingLevel)Random.Shared.Next(_loggingLevelMap.Count);
var message = new
{
Level = newLevel.ToString().ToLower(),
Data = _loggingLevelMap[newLevel],
};
if (newLevel > getMinLevel())
{
await server.SendNotificationAsync("notifications/message", message, cancellationToken: stoppingToken);
}
await Task.Delay(15000, stoppingToken);
}
}
}