Add EverythingServer sample (#151)
This commit is contained in:
parent
d21d933876
commit
01410df5ad
18 changed files with 620 additions and 1 deletions
|
|
@ -50,6 +50,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "QuickstartWeatherServer", "
|
||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "QuickstartClient", "samples\QuickstartClient\QuickstartClient.csproj", "{0D1552DC-E6ED-4AAC-5562-12F8352F46AA}"
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "QuickstartClient", "samples\QuickstartClient\QuickstartClient.csproj", "{0D1552DC-E6ED-4AAC-5562-12F8352F46AA}"
|
||||||
EndProject
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EverythingServer", "samples\EverythingServer\EverythingServer.csproj", "{17B8453F-AB72-99C5-E5EA-D0B065A6AE65}"
|
||||||
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ModelContextProtocol.AspNetCore", "src\ModelContextProtocol.AspNetCore\ModelContextProtocol.AspNetCore.csproj", "{37B6A5E0-9995-497D-8B43-3BC6870CC716}"
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ModelContextProtocol.AspNetCore", "src\ModelContextProtocol.AspNetCore\ModelContextProtocol.AspNetCore.csproj", "{37B6A5E0-9995-497D-8B43-3BC6870CC716}"
|
||||||
EndProject
|
EndProject
|
||||||
Global
|
Global
|
||||||
|
|
@ -94,6 +96,10 @@ Global
|
||||||
{0D1552DC-E6ED-4AAC-5562-12F8352F46AA}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
{0D1552DC-E6ED-4AAC-5562-12F8352F46AA}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
{0D1552DC-E6ED-4AAC-5562-12F8352F46AA}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
{0D1552DC-E6ED-4AAC-5562-12F8352F46AA}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
{0D1552DC-E6ED-4AAC-5562-12F8352F46AA}.Release|Any CPU.Build.0 = Release|Any CPU
|
{0D1552DC-E6ED-4AAC-5562-12F8352F46AA}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{17B8453F-AB72-99C5-E5EA-D0B065A6AE65}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{17B8453F-AB72-99C5-E5EA-D0B065A6AE65}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{17B8453F-AB72-99C5-E5EA-D0B065A6AE65}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{17B8453F-AB72-99C5-E5EA-D0B065A6AE65}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
{37B6A5E0-9995-497D-8B43-3BC6870CC716}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
{37B6A5E0-9995-497D-8B43-3BC6870CC716}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
{37B6A5E0-9995-497D-8B43-3BC6870CC716}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
{37B6A5E0-9995-497D-8B43-3BC6870CC716}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
{37B6A5E0-9995-497D-8B43-3BC6870CC716}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
{37B6A5E0-9995-497D-8B43-3BC6870CC716}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
|
@ -113,6 +119,7 @@ Global
|
||||||
{0C6D0512-D26D-63D3-5019-C5F7A657B28C} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8}
|
{0C6D0512-D26D-63D3-5019-C5F7A657B28C} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8}
|
||||||
{4653EB0C-8FC0-98F4-E9C8-220EDA7A69DF} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8}
|
{4653EB0C-8FC0-98F4-E9C8-220EDA7A69DF} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8}
|
||||||
{0D1552DC-E6ED-4AAC-5562-12F8352F46AA} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8}
|
{0D1552DC-E6ED-4AAC-5562-12F8352F46AA} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8}
|
||||||
|
{17B8453F-AB72-99C5-E5EA-D0B065A6AE65} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8}
|
||||||
{37B6A5E0-9995-497D-8B43-3BC6870CC716} = {A2F1F52A-9107-4BF8-8C3F-2F6670E7D0AD}
|
{37B6A5E0-9995-497D-8B43-3BC6870CC716} = {A2F1F52A-9107-4BF8-8C3F-2F6670E7D0AD}
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||||
|
|
|
||||||
18
samples/EverythingServer/EverythingServer.csproj
Normal file
18
samples/EverythingServer/EverythingServer.csproj
Normal 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>
|
||||||
43
samples/EverythingServer/LoggingUpdateMessageSender.cs
Normal file
43
samples/EverythingServer/LoggingUpdateMessageSender.cs
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
194
samples/EverythingServer/Program.cs
Normal file
194
samples/EverythingServer/Program.cs
Normal 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();
|
||||||
22
samples/EverythingServer/Prompts/ComplexPromptType.cs
Normal file
22
samples/EverythingServer/Prompts/ComplexPromptType.cs
Normal 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)])
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
11
samples/EverythingServer/Prompts/SimplePromptType.cs
Normal file
11
samples/EverythingServer/Prompts/SimplePromptType.cs
Normal 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";
|
||||||
|
}
|
||||||
37
samples/EverythingServer/ResourceGenerator.cs
Normal file
37
samples/EverythingServer/ResourceGenerator.cs
Normal 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;
|
||||||
|
}
|
||||||
23
samples/EverythingServer/SubscriptionMessageSender.cs
Normal file
23
samples/EverythingServer/SubscriptionMessageSender.cs
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
11
samples/EverythingServer/Tools/AddTool.cs
Normal file
11
samples/EverythingServer/Tools/AddTool.cs
Normal 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}";
|
||||||
|
}
|
||||||
56
samples/EverythingServer/Tools/AnnotatedMessageTool.cs
Normal file
56
samples/EverythingServer/Tools/AnnotatedMessageTool.cs
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
11
samples/EverythingServer/Tools/EchoTool.cs
Normal file
11
samples/EverythingServer/Tools/EchoTool.cs
Normal 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}";
|
||||||
|
}
|
||||||
39
samples/EverythingServer/Tools/LongRunningTool.cs
Normal file
39
samples/EverythingServer/Tools/LongRunningTool.cs
Normal 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}.";
|
||||||
|
}
|
||||||
|
}
|
||||||
18
samples/EverythingServer/Tools/PrintEnvTool.cs
Normal file
18
samples/EverythingServer/Tools/PrintEnvTool.cs
Normal 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);
|
||||||
|
}
|
||||||
42
samples/EverythingServer/Tools/SampleLlmTool.cs
Normal file
42
samples/EverythingServer/Tools/SampleLlmTool.cs
Normal 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
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
19
samples/EverythingServer/Tools/TinyImageTool.cs
Normal file
19
samples/EverythingServer/Tools/TinyImageTool.cs
Normal file
File diff suppressed because one or more lines are too long
|
|
@ -314,7 +314,7 @@ public static partial class McpServerBuilderExtensions
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Sets or sets the handler for subscribe to resources messages.
|
/// Sets the handler for subscribe to resources messages.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="builder">The builder instance.</param>
|
/// <param name="builder">The builder instance.</param>
|
||||||
/// <param name="handler">The handler.</param>
|
/// <param name="handler">The handler.</param>
|
||||||
|
|
@ -325,6 +325,18 @@ public static partial class McpServerBuilderExtensions
|
||||||
builder.Services.Configure<McpServerHandlers>(s => s.UnsubscribeFromResourcesHandler = handler);
|
builder.Services.Configure<McpServerHandlers>(s => s.UnsubscribeFromResourcesHandler = handler);
|
||||||
return builder;
|
return builder;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Sets the handler for setting the logging level.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="builder">The builder instance.</param>
|
||||||
|
/// <param name="handler">The handler.</param>
|
||||||
|
public static IMcpServerBuilder WithSetLoggingLevelHandler(this IMcpServerBuilder builder, Func<RequestContext<SetLevelRequestParams>, CancellationToken, Task<EmptyResult>> handler)
|
||||||
|
{
|
||||||
|
Throw.IfNull(builder);
|
||||||
|
builder.Services.Configure<McpServerHandlers>(s => s.SetLoggingLevelHandler = handler);
|
||||||
|
return builder;
|
||||||
|
}
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region Transports
|
#region Transports
|
||||||
|
|
|
||||||
|
|
@ -113,6 +113,7 @@ public sealed class McpServerHandlers
|
||||||
options.Capabilities.Prompts = promptsCapability;
|
options.Capabilities.Prompts = promptsCapability;
|
||||||
options.Capabilities.Resources = resourcesCapability;
|
options.Capabilities.Resources = resourcesCapability;
|
||||||
options.Capabilities.Tools = toolsCapability;
|
options.Capabilities.Tools = toolsCapability;
|
||||||
|
options.Capabilities.Logging = loggingCapability;
|
||||||
|
|
||||||
options.GetCompletionHandler = GetCompletionHandler ?? options.GetCompletionHandler;
|
options.GetCompletionHandler = GetCompletionHandler ?? options.GetCompletionHandler;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,55 @@
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using ModelContextProtocol.Protocol.Types;
|
||||||
|
using ModelContextProtocol.Server;
|
||||||
|
|
||||||
|
namespace ModelContextProtocol.Tests.Server;
|
||||||
|
public class McpServerLoggingLevelTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public void CanCreateServerWithLoggingLevelHandler()
|
||||||
|
{
|
||||||
|
var services = new ServiceCollection();
|
||||||
|
|
||||||
|
services.AddMcpServer()
|
||||||
|
.WithStdioServerTransport()
|
||||||
|
.WithSetLoggingLevelHandler((ctx, ct) =>
|
||||||
|
{
|
||||||
|
return Task.FromResult(new EmptyResult());
|
||||||
|
});
|
||||||
|
|
||||||
|
var provider = services.BuildServiceProvider();
|
||||||
|
|
||||||
|
provider.GetRequiredService<IMcpServer>();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void AddingLoggingLevelHandlerSetsLoggingCapability()
|
||||||
|
{
|
||||||
|
var services = new ServiceCollection();
|
||||||
|
|
||||||
|
services.AddMcpServer()
|
||||||
|
.WithStdioServerTransport()
|
||||||
|
.WithSetLoggingLevelHandler((ctx, ct) =>
|
||||||
|
{
|
||||||
|
return Task.FromResult(new EmptyResult());
|
||||||
|
});
|
||||||
|
|
||||||
|
var provider = services.BuildServiceProvider();
|
||||||
|
|
||||||
|
var server = provider.GetRequiredService<IMcpServer>();
|
||||||
|
|
||||||
|
Assert.NotNull(server.ServerOptions.Capabilities?.Logging);
|
||||||
|
Assert.NotNull(server.ServerOptions.Capabilities.Logging.SetLoggingLevelHandler);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ServerWithoutCallingLoggingLevelHandlerDoesNotSetLoggingCapability()
|
||||||
|
{
|
||||||
|
var services = new ServiceCollection();
|
||||||
|
services.AddMcpServer()
|
||||||
|
.WithStdioServerTransport();
|
||||||
|
var provider = services.BuildServiceProvider();
|
||||||
|
var server = provider.GetRequiredService<IMcpServer>();
|
||||||
|
Assert.Null(server.ServerOptions.Capabilities?.Logging);
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in a new issue