Repository navigation
Add stdio support for EverythingServer sample (continues #950) #1880
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
851e43c
290ef2f
966502b
f5cd3dc
738bf9c
5a080c1
54b0d19
03d0cc6
6b4e24c
91d1b4c
295a97f
7fab1bc
672e361
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
|
||
| <PropertyGroup> | ||
| <TargetFramework>net9.0</TargetFramework> | ||
| <Nullable>enable</Nullable> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
| <!-- This sample demonstrates the Sampling feature, which SEP-2577 deprecates (MCP9005) but | ||
| which continues to work. Suppress the deprecation warning for this project only. --> | ||
| <NoWarn>$(NoWarn);MCP9005</NoWarn> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <ProjectReference Include="..\..\src\ModelContextProtocol\ModelContextProtocol.csproj" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,212 @@ | ||
| using EverythingServer.Core.Prompts; | ||
| using EverythingServer.Core.Resources; | ||
| using EverythingServer.Core.Tools; | ||
| using Microsoft.Extensions.AI; | ||
| using Microsoft.Extensions.DependencyInjection; | ||
| using ModelContextProtocol; | ||
| using ModelContextProtocol.Protocol; | ||
| using ModelContextProtocol.Server; | ||
| using System.Collections.Concurrent; | ||
|
|
||
| namespace EverythingServer.Core; | ||
|
|
||
| /// <summary> | ||
| /// Extension methods for configuring the EverythingServer MCP handlers. | ||
| /// </summary> | ||
| public static class EverythingServerExtensions | ||
| { | ||
| /// <summary> | ||
| /// Adds all the tools, prompts, resources, and handlers for the EverythingServer. | ||
| /// </summary> | ||
| /// <param name="builder">The MCP server builder.</param> | ||
| /// <param name="subscriptions">The subscriptions dictionary to use for managing resource subscriptions.</param> | ||
| /// <returns>The MCP server builder for chaining.</returns> | ||
| public static IMcpServerBuilder AddEverythingMcpHandlers( | ||
| this IMcpServerBuilder builder, | ||
| ConcurrentDictionary<string, ConcurrentDictionary<string, byte>> subscriptions) | ||
| { | ||
| // Configure server implementation details with icons and website | ||
| builder.Services.Configure<McpServerOptions>(options => | ||
| { | ||
| options.ServerInfo = new Implementation | ||
| { | ||
| Name = "Everything Server", | ||
| Version = "1.0.0", | ||
| Title = "MCP Everything Server", | ||
| Description = "A comprehensive MCP server demonstrating tools, prompts, resources, sampling, and all MCP features", | ||
| WebsiteUrl = "https://github.com/modelcontextprotocol/csharp-sdk", | ||
| Icons = [ | ||
| new Icon | ||
| { | ||
| Source = "https://raw.githubusercontent.com/microsoft/fluentui-emoji/62ecdc0d7ca5c6df32148c169556bc8d3782fca4/assets/Gear/Flat/gear_flat.svg", | ||
| MimeType = "image/svg+xml", | ||
| Sizes = ["any"], | ||
| Theme = "light" | ||
| }, | ||
| new Icon | ||
| { | ||
| Source = "https://raw.githubusercontent.com/microsoft/fluentui-emoji/62ecdc0d7ca5c6df32148c169556bc8d3782fca4/assets/Gear/3D/gear_3d.png", | ||
| MimeType = "image/png", | ||
| Sizes = ["256x256"] | ||
| } | ||
| ] | ||
| }; | ||
| }); | ||
|
|
||
| return builder | ||
| .WithTools<AddTool>() | ||
| .WithTools<AnnotatedMessageTool>() | ||
| .WithTools([ | ||
| // EchoTool with complex icon configuration demonstrating multiple icons, | ||
| // MIME types, size specifications, and theme preferences | ||
| McpServerTool.Create( | ||
| typeof(EchoTool).GetMethod(nameof(EchoTool.Echo))!, | ||
| options: new McpServerToolCreateOptions | ||
| { | ||
| Icons = [ | ||
| // High-resolution PNG icon for light theme | ||
| new Icon | ||
| { | ||
| Source = "https://raw.githubusercontent.com/microsoft/fluentui-emoji/62ecdc0d7ca5c6df32148c169556bc8d3782fca4/assets/Loudspeaker/Flat/loudspeaker_flat.svg", | ||
| MimeType = "image/svg+xml", | ||
| Sizes = ["any"], | ||
| Theme = "light" | ||
| }, | ||
| // 3D icon for dark theme | ||
| new Icon | ||
| { | ||
| Source = "https://raw.githubusercontent.com/microsoft/fluentui-emoji/62ecdc0d7ca5c6df32148c169556bc8d3782fca4/assets/Loudspeaker/3D/loudspeaker_3d.png", | ||
| MimeType = "image/png", | ||
| Sizes = ["256x256"], | ||
| Theme = "dark" | ||
| }, | ||
| // WebP format for modern browsers | ||
| // Demonstrates Data URI representation with the smallest possible valid WebP image (1x1 pixel). | ||
| // This will appear as a white box when rendered by a browser at 32x32 | ||
| new Icon | ||
| { | ||
| Source = "data:image/webp;base64,UklGRiQAAABXRUJQVlA4IBgAAAAwAQCdASoBAAEAAwA0JaQAA3AA/vuUAAA=", | ||
| MimeType = "image/webp", | ||
| Sizes = ["32x32"] | ||
| } | ||
| ] | ||
| }) | ||
| ]) | ||
| .WithTools<LongRunningTool>() | ||
| .WithTools<PrintEnvTool>() | ||
| .WithTools<SampleLlmTool>() | ||
| .WithTools<TinyImageTool>() | ||
| .WithPrompts<ComplexPromptType>() | ||
| .WithPrompts<SimplePromptType>() | ||
| .WithResources<SimpleResourceType>() | ||
| .WithSubscribeToResourcesHandler(async (ctx, ct) => | ||
| { | ||
| var sessionId = ctx.Server.SessionId ?? "stdio"; | ||
|
|
||
| if (!subscriptions.TryGetValue(sessionId, out var sessionSubscriptions)) | ||
| { | ||
| sessionSubscriptions = new ConcurrentDictionary<string, byte>(); | ||
| subscriptions[sessionId] = sessionSubscriptions; | ||
| } | ||
|
|
||
| if (ctx.Params?.Uri is { } uri) | ||
| { | ||
| sessionSubscriptions.TryAdd(uri, 0); | ||
|
|
||
| await ctx.Server.SampleAsync([ | ||
| new ChatMessage(ChatRole.System, "You are a helpful test server"), | ||
| new ChatMessage(ChatRole.User, $"Resource {uri}, context: A new subscription was started"), | ||
| ], | ||
| chatOptions: new ChatOptions | ||
| { | ||
| MaxOutputTokens = 100, | ||
| Temperature = 0.7f, | ||
| }, | ||
| cancellationToken: ct); | ||
| } | ||
|
|
||
| return new EmptyResult(); | ||
| }) | ||
| .WithUnsubscribeFromResourcesHandler(async (ctx, ct) => | ||
| { | ||
| var sessionId = ctx.Server.SessionId ?? "stdio"; | ||
|
|
||
| if (subscriptions.TryGetValue(sessionId, out var sessionSubscriptions)) | ||
| { | ||
| if (ctx.Params?.Uri is { } uri) | ||
| { | ||
| sessionSubscriptions.TryRemove(uri, out _); | ||
| } | ||
| } | ||
| return new EmptyResult(); | ||
| }) | ||
| .WithCompleteHandler(async (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 is ResourceTemplateReference rtr) | ||
| { | ||
| var resourceId = rtr.Uri?.Split("/").Last(); | ||
|
|
||
| if (resourceId is null) | ||
| { | ||
| return new CompleteResult(); | ||
| } | ||
|
|
||
| var values = exampleCompletions["resourceId"].Where(id => id.StartsWith(argument.Value)); | ||
|
|
||
| return new CompleteResult | ||
| { | ||
| Completion = new Completion { Values = [.. values], HasMore = false, Total = values.Count() } | ||
| }; | ||
| } | ||
|
|
||
| if (@ref is PromptReference pr) | ||
| { | ||
| 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 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 McpProtocolException("Missing required argument 'level'", McpErrorCode.InvalidParams); | ||
| } | ||
|
|
||
| // The SDK updates the LoggingLevel field of the IMcpServer | ||
|
|
||
| await ctx.Server.SendNotificationAsync("notifications/message", new | ||
| { | ||
| Level = "debug", | ||
| Logger = "test-server", | ||
| Data = $"Logging level set to {ctx.Params.Level}", | ||
| }, cancellationToken: ct); | ||
|
|
||
| return new EmptyResult(); | ||
| }); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| # EverythingServer.Core | ||
|
|
||
| This is the core library containing all the shared MCP server handlers (tools, prompts, resources) used by both the HTTP and stdio implementations of the EverythingServer sample. | ||
|
|
||
| ## What's Inside | ||
|
|
||
| This library contains: | ||
|
|
||
| - **Tools**: Various example tools demonstrating different MCP capabilities | ||
| - `AddTool`: Simple addition operation | ||
| - `AnnotatedMessageTool`: Returns annotated messages | ||
| - `EchoTool`: Echoes input back to the client | ||
| - `LongRunningTool`: Demonstrates long-running operations with progress reporting | ||
| - `PrintEnvTool`: Prints environment variables | ||
| - `SampleLlmTool`: Example LLM sampling integration | ||
| - `TinyImageTool`: Returns image content | ||
|
|
||
| - **Prompts**: Example prompts showing argument handling | ||
| - `SimplePromptType`: Basic prompt example | ||
| - `ComplexPromptType`: Prompt with multiple arguments | ||
|
|
||
| - **Resources**: Example resources with subscriptions | ||
| - `SimpleResourceType`: Dynamic resource with URI template matching | ||
|
|
||
| - **Background Services**: For managing subscriptions and logging | ||
| - `SubscriptionMessageSender`: Sends periodic updates to subscribed resources | ||
| - `LoggingUpdateMessageSender`: Sends periodic logging messages at different levels | ||
|
|
||
| - **Extension Method**: `AddEverythingMcpHandlers` to configure all handlers in one call | ||
|
|
||
| ## Usage | ||
|
|
||
| Reference this project from your MCP server implementation (HTTP or stdio) and call the extension method: | ||
|
|
||
| ```csharp | ||
| builder.Services | ||
| .AddMcpServer() | ||
| .WithHttpTransport() // or WithStdioServerTransport() | ||
| .AddEverythingMcpHandlers(subscriptions); | ||
| ``` | ||
|
|
||
| See the `EverythingServer.Http` and `EverythingServer.Stdio` projects for complete examples. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,7 +2,7 @@ | |
| using System.ComponentModel; | ||
| using System.Text.Json; | ||
|
|
||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Could we avoid returning the entire process environment from this sample tool? It can expose secrets such as access tokens, connection strings, or cloud credentials to any MCP client that can invoke it. This tool predates the split, but the new stdio server makes it available over that transport too. Please consider safe allowlisted or redacted output, or clearly making this tool unsafe and opt-in. |
||
| namespace EverythingServer.Tools; | ||
| namespace EverythingServer.Core.Tools; | ||
|
|
||
| [McpServerToolType] | ||
| public class PrintEnvTool | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Could the subscription remain valid when the client does not advertise sampling, or could this code roll back the URI if
SampleAsyncfails? The URI is added beforeSampleAsync, which throws when sampling is unsupported. The request then fails, but the subscription remains and the background sender continues notifying it. Since sampling is optional and separate from subscribing, please consider guarding the sample or rolling back on failure.