Add EverythingServer sample (#151)

This commit is contained in:
Aaron Powell 2025-04-05 05:48:53 +11:00 • committed by GitHub
commit 01410df5ad
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
14 changed files with 620 additions and 1 deletions

View file

@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<OutputType>Exe</OutputType>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\ModelContextProtocol\ModelContextProtocol.csproj" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,43 @@
using Microsoft.Extensions.DependencyInjection;
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);
}
}
}

View file

@ -0,0 +1,194 @@
using EverythingServer;
using EverythingServer.Prompts;
using EverythingServer.Tools;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using ModelContextProtocol;
using ModelContextProtocol.Protocol.Types;
using ModelContextProtocol.Server;
var builder = Host.CreateApplicationBuilder(args);
builder.Logging.AddConsole(consoleLogOptions =>
{
// Configure all logs to go to stderr
consoleLogOptions.LogToStandardErrorThreshold = LogLevel.Trace;
});
HashSet<string> subscriptions = [];
var _minimumLoggingLevel = LoggingLevel.Debug;
builder.Services
.AddMcpServer()
.WithStdioServerTransport()
.WithTools<AddTool>()
.WithTools<AnnotatedMessageTool>()
.WithTools<EchoTool>()
.WithTools<LongRunningTool>()
.WithTools<PrintEnvTool>()
.WithTools<SampleLlmTool>()
.WithTools<TinyImageTool>()
.WithPrompts<ComplexPromptType>()
.WithPrompts<SimplePromptType>()
.WithListResourceTemplatesHandler((ctx, ct) =>
{
return Task.FromResult(new ListResourceTemplatesResult
{
ResourceTemplates =
[
new ResourceTemplate { Name = "Static Resource", Description = "A static resource with a numeric ID", UriTemplate = "test://static/resource/{id}" }
]
});
})
.WithReadResourceHandler((ctx, ct) =>
{
var uri = ctx.Params?.Uri;
if (uri is null || !uri.StartsWith("test://static/resource/"))
{
throw new NotSupportedException($"Unknown resource: {uri}");
}
int index = int.Parse(uri["test://static/resource/".Length..]) - 1;
if (index < 0 || index >= ResourceGenerator.Resources.Count)
{
throw new NotSupportedException($"Unknown resource: {uri}");
}
var resource = ResourceGenerator.Resources[index];
if (resource.MimeType == "text/plain")
{
return Task.FromResult(new ReadResourceResult
{
Contents = [new TextResourceContents
{
Text = resource.Description!,
MimeType = resource.MimeType,
Uri = resource.Uri,
}]
});
}
else
{
return Task.FromResult(new ReadResourceResult
{
Contents = [new BlobResourceContents
{
Blob = resource.Description!,
MimeType = resource.MimeType,
Uri = resource.Uri,
}]
});
}
})
.WithSubscribeToResourcesHandler(async (ctx, ct) =>
{
var uri = ctx.Params?.Uri;
if (uri is not null)
{
subscriptions.Add(uri);
await ctx.Server.RequestSamplingAsync([
new ChatMessage(ChatRole.System, "You are a helpful test server"),
new ChatMessage(ChatRole.User, $"Resource {uri}, context: A new subscription was started"),
],
options: new ChatOptions
{
MaxOutputTokens = 100,
Temperature = 0.7f,
},
cancellationToken: ct);
}
return new EmptyResult();
})
.WithUnsubscribeFromResourcesHandler((ctx, ct) =>
{
var uri = ctx.Params?.Uri;
if (uri is not null)
{
subscriptions.Remove(uri);
}
return Task.FromResult(new EmptyResult());
})
.WithGetCompletionHandler((ctx, ct) =>
{
var exampleCompletions = new Dictionary<string, IEnumerable<string>>
{
{ "style", ["casual", "formal", "technical", "friendly"] },
{ "temperature", ["0", "0.5", "0.7", "1.0"] },
{ "resourceId", ["1", "2", "3", "4", "5"] }
};
if (ctx.Params is not { } @params)
{
throw new NotSupportedException($"Params are required.");
}
var @ref = @params.Ref;
var argument = @params.Argument;
if (@ref.Type == "ref/resource")
{
var resourceId = @ref.Uri?.Split("/").Last();
if (resourceId is null)
{
return Task.FromResult(new CompleteResult());
}
var values = exampleCompletions["resourceId"].Where(id => id.StartsWith(argument.Value));
return Task.FromResult(new CompleteResult
{
Completion = new Completion { Values = [..values], HasMore = false, Total = values.Count() }
});
}
if (@ref.Type == "ref/prompt")
{
if (!exampleCompletions.TryGetValue(argument.Name, out IEnumerable<string>? value))
{
throw new NotSupportedException($"Unknown argument name: {argument.Name}");
}
var values = value.Where(value => value.StartsWith(argument.Value));
return Task.FromResult(new CompleteResult
{
Completion = new Completion { Values = [..values], HasMore = false, Total = values.Count() }
});
}
throw new NotSupportedException($"Unknown reference type: {@ref.Type}");
})
.WithSetLoggingLevelHandler(async (ctx, ct) =>
{
if (ctx.Params?.Level is null)
{
throw new McpException("Missing required argument 'level'");
}
_minimumLoggingLevel = ctx.Params.Level;
await ctx.Server.SendNotificationAsync("notifications/message", new
{
Level = "debug",
Logger = "test-server",
Data = $"Logging level set to {_minimumLoggingLevel}",
}, cancellationToken: ct);
return new EmptyResult();
})
;
builder.Services.AddSingleton(subscriptions);
builder.Services.AddHostedService<SubscriptionMessageSender>();
builder.Services.AddHostedService<LoggingUpdateMessageSender>();
builder.Services.AddSingleton<Func<LoggingLevel>>(_ => () => _minimumLoggingLevel);
await builder.Build().RunAsync();

View file

@ -0,0 +1,22 @@
using EverythingServer.Tools;
using Microsoft.Extensions.AI;
using ModelContextProtocol.Server;
using System.ComponentModel;
namespace EverythingServer.Prompts;
[McpServerPromptType]
public class ComplexPromptType
{
[McpServerPrompt(Name = "complex_prompt"), Description("A prompt with arguments")]
public static IEnumerable<ChatMessage> ComplexPrompt(
[Description("Temperature setting")] int temperature,
[Description("Output style")] string? style = null)
{
return [
new ChatMessage(ChatRole.User,$"This is a complex prompt with arguments: temperature={temperature}, style={style}"),
new ChatMessage(ChatRole.Assistant, "I understand. You've provided a complex prompt with temperature and style arguments. How would you like me to proceed?"),
new ChatMessage(ChatRole.User, [new DataContent(TinyImageTool.MCP_TINY_IMAGE)])
];
}
}

View file

@ -0,0 +1,11 @@
using ModelContextProtocol.Server;
using System.ComponentModel;
namespace EverythingServer.Prompts;
[McpServerPromptType]
public class SimplePromptType
{
[McpServerPrompt(Name = "simple_prompt"), Description("A prompt without arguments")]
public static string SimplePrompt() => "This is a simple prompt without arguments";
}

View file

@ -0,0 +1,37 @@
using ModelContextProtocol.Protocol.Types;
using System;
using System.Collections.Generic;
using System.Linq;
namespace EverythingServer;
static class ResourceGenerator
{
private static readonly List<Resource> _resources = Enumerable.Range(1, 100).Select(i =>
{
var uri = $"test://static/resource/{i}";
if (i % 2 != 0)
{
return new Resource
{
Uri = uri,
Name = $"Resource {i}",
MimeType = "text/plain",
Description = $"Resource {i}: This is a plaintext resource"
};
}
else
{
var buffer = System.Text.Encoding.UTF8.GetBytes($"Resource {i}: This is a base64 blob");
return new Resource
{
Uri = uri,
Name = $"Resource {i}",
MimeType = "application/octet-stream",
Description = Convert.ToBase64String(buffer)
};
}
}).ToList();
public static IReadOnlyList<Resource> Resources => _resources;
}

View file

@ -0,0 +1,23 @@
using Microsoft.Extensions.Hosting;
using ModelContextProtocol;
using ModelContextProtocol.Server;
internal class SubscriptionMessageSender(IMcpServer server, HashSet<string> subscriptions) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
foreach (var uri in subscriptions)
{
await server.SendNotificationAsync("notifications/resource/updated",
new
{
Uri = uri,
}, cancellationToken: stoppingToken);
}
await Task.Delay(5000, stoppingToken);
}
}
}

View file

@ -0,0 +1,11 @@
using ModelContextProtocol.Server;
using System.ComponentModel;
namespace EverythingServer.Tools;
[McpServerToolType]
public class AddTool
{
[McpServerTool(Name = "add"), Description("Adds two numbers.")]
public static string Add(int a, int b) => $"The sum of {a} and {b} is {a + b}";
}

View file

@ -0,0 +1,56 @@
using ModelContextProtocol.Protocol.Types;
using ModelContextProtocol.Server;
using System.ComponentModel;
namespace EverythingServer.Tools;
[McpServerToolType]
public class AnnotatedMessageTool
{
public enum MessageType
{
Error,
Success,
Debug,
}
[McpServerTool(Name = "annotatedMessage"), Description("Generates an annotated message")]
public static IEnumerable<Content> AnnotatedMessage(MessageType messageType, bool includeImage = true)
{
List<Content> contents = messageType switch
{
MessageType.Error => [new()
{
Type = "text",
Text = "Error: Operation failed",
Annotations = new() { Audience = [Role.User, Role.Assistant], Priority = 1.0f }
}],
MessageType.Success => [new()
{
Type = "text",
Text = "Operation completed successfully",
Annotations = new() { Audience = [Role.User], Priority = 0.7f }
}],
MessageType.Debug => [new()
{
Type = "text",
Text = "Debug: Cache hit ratio 0.95, latency 150ms",
Annotations = new() { Audience = [Role.Assistant], Priority = 0.3f }
}],
_ => throw new ArgumentOutOfRangeException(nameof(messageType), messageType, null)
};
if (includeImage)
{
contents.Add(new()
{
Type = "image",
Data = TinyImageTool.MCP_TINY_IMAGE.Split(",").Last(),
MimeType = "image/png",
Annotations = new() { Audience = [Role.User], Priority = 0.5f }
});
}
return contents;
}
}

View file

@ -0,0 +1,11 @@
using ModelContextProtocol.Server;
using System.ComponentModel;
namespace EverythingServer.Tools;
[McpServerToolType]
public class EchoTool
{
[McpServerTool(Name = "echo"), Description("Echoes the message back to the client.")]
public static string Echo(string message) => $"Echo: {message}";
}

View file

@ -0,0 +1,39 @@
using ModelContextProtocol;
using ModelContextProtocol.Protocol.Messages;
using ModelContextProtocol.Protocol.Types;
using ModelContextProtocol.Server;
using System.ComponentModel;
namespace EverythingServer.Tools;
[McpServerToolType]
public class LongRunningTool
{
[McpServerTool(Name = "longRunningOperation"), Description("Demonstrates a long running operation with progress updates")]
public static async Task<string> LongRunningOperation(
IMcpServer server,
RequestContext<CallToolRequestParams> context,
int duration = 10,
int steps = 5)
{
var progressToken = context.Params?.Meta?.ProgressToken;
var stepDuration = duration / steps;
for (int i = 1; i <= steps + 1; i++)
{
await Task.Delay(stepDuration * 1000);
if (progressToken is not null)
{
await server.SendNotificationAsync("notifications/progress", new
{
Progress = i,
Total = steps,
progressToken
});
}
}
return $"Long running operation completed. Duration: {duration} seconds. Steps: {steps}.";
}
}

View file

@ -0,0 +1,18 @@
using ModelContextProtocol.Server;
using System.ComponentModel;
using System.Text.Json;
namespace EverythingServer.Tools;
[McpServerToolType]
public class PrintEnvTool
{
private static readonly JsonSerializerOptions options = new()
{
WriteIndented = true
};
[McpServerTool(Name = "printEnv"), Description("Prints all environment variables, helpful for debugging MCP server configuration")]
public static string PrintEnv() =>
JsonSerializer.Serialize(Environment.GetEnvironmentVariables(), options);
}

View file

@ -0,0 +1,42 @@
using ModelContextProtocol.Protocol.Types;
using ModelContextProtocol.Server;
using System.ComponentModel;
namespace EverythingServer.Tools;
[McpServerToolType]
public class SampleLlmTool
{
[McpServerTool(Name = "sampleLLM"), Description("Samples from an LLM using MCP's sampling feature")]
public static async Task<string> SampleLLM(
IMcpServer server,
[Description("The prompt to send to the LLM")] string prompt,
[Description("Maximum number of tokens to generate")] int maxTokens,
CancellationToken cancellationToken)
{
var samplingParams = CreateRequestSamplingParams(prompt ?? string.Empty, "sampleLLM", maxTokens);
var sampleResult = await server.RequestSamplingAsync(samplingParams, cancellationToken);
return $"LLM sampling result: {sampleResult.Content.Text}";
}
private static CreateMessageRequestParams CreateRequestSamplingParams(string context, string uri, int maxTokens = 100)
{
return new CreateMessageRequestParams()
{
Messages = [new SamplingMessage()
{
Role = Role.User,
Content = new Content()
{
Type = "text",
Text = $"Resource {uri} context: {context}"
}
}],
SystemPrompt = "You are a helpful test server.",
MaxTokens = maxTokens,
Temperature = 0.7f,
IncludeContext = ContextInclusion.ThisServer
};
}
}

File diff suppressed because one or more lines are too long