jeff revised this gist . Go to revision
1 file changed, 13 insertions
basic_dotnet_mcp_server.cs
@@ -13,6 +13,18 @@ builder.Services.AddMcpServer() | |||
13 | 13 | .WithToolsFromAssembly(); | |
14 | 14 | var app = builder.Build(); | |
15 | 15 | ||
16 | + | // validate Authorization header on incoming requests | |
17 | + | app.Use(async (context, next) => | |
18 | + | { | |
19 | + | if (!context.Request.Headers.TryGetValue("Authorization", out var auth) | |
20 | + | || auth != "Bearer hello-world") | |
21 | + | { | |
22 | + | context.Response.StatusCode = StatusCodes.Status401Unauthorized; | |
23 | + | return; | |
24 | + | } | |
25 | + | await next(); | |
26 | + | }); | |
27 | + | ||
16 | 28 | app.MapMcp(); | |
17 | 29 | ||
18 | 30 | app.Run("http://localhost:3001"); | |
@@ -41,3 +53,4 @@ public static class WeatherTool | |||
41 | 53 | return new WeatherResponse(cityName, temperature, humidity, condition); | |
42 | 54 | } | |
43 | 55 | } | |
56 | + |
jeff revised this gist . Go to revision
1 file changed, 43 insertions
basic_dotnet_mcp_server.cs(file created)
@@ -0,0 +1,43 @@ | |||
1 | + | /* | |
2 | + | dotnet add package ModelContextProtocol --prerelease | |
3 | + | dotnet add package ModelContextProtocol.AspNetCore --prerelease | |
4 | + | dotnet add package Microsoft.Extensions.Hosting | |
5 | + | */ | |
6 | + | ||
7 | + | using ModelContextProtocol.Server; | |
8 | + | using System.ComponentModel; | |
9 | + | ||
10 | + | var builder = WebApplication.CreateBuilder(args); | |
11 | + | builder.Services.AddMcpServer() | |
12 | + | .WithHttpTransport() | |
13 | + | .WithToolsFromAssembly(); | |
14 | + | var app = builder.Build(); | |
15 | + | ||
16 | + | app.MapMcp(); | |
17 | + | ||
18 | + | app.Run("http://localhost:3001"); | |
19 | + | ||
20 | + | [McpServerToolType] | |
21 | + | public static class EchoTool | |
22 | + | { | |
23 | + | [McpServerTool, Description("Echoes the message back to the client.")] | |
24 | + | public static string Echo(string message) => $"Yo! You said '{message}'"; | |
25 | + | } | |
26 | + | ||
27 | + | // Add a strongly-typed response class for weather | |
28 | + | public record WeatherResponse(string City, int Temperature, int Humidity, string Condition); | |
29 | + | ||
30 | + | [McpServerToolType] | |
31 | + | public static class WeatherTool | |
32 | + | { | |
33 | + | [McpServerTool, Description("Returns weather data as a typed object; framework will serialize to JSON.")] | |
34 | + | public static WeatherResponse GetWeather(string? city) | |
35 | + | { | |
36 | + | string cityName = city ?? string.Empty; | |
37 | + | int temperature = cityName.Length; | |
38 | + | int humidity = temperature * 5; | |
39 | + | var conditions = new[] { "Sunny", "Cloudy", "Rainy", "Windy" }; | |
40 | + | string condition = conditions[temperature % conditions.Length]; | |
41 | + | return new WeatherResponse(cityName, temperature, humidity, condition); | |
42 | + | } | |
43 | + | } |