Last active 1750778636

basic_dotnet_mcp_server.cs Raw
1/*
2dotnet add package ModelContextProtocol --prerelease
3dotnet add package ModelContextProtocol.AspNetCore --prerelease
4dotnet add package Microsoft.Extensions.Hosting
5*/
6
7using ModelContextProtocol.Server;
8using System.ComponentModel;
9
10var builder = WebApplication.CreateBuilder(args);
11builder.Services.AddMcpServer()
12 .WithHttpTransport()
13 .WithToolsFromAssembly();
14var app = builder.Build();
15
16// validate Authorization header on incoming requests
17app.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
28app.MapMcp();
29
30app.Run("http://localhost:3001");
31
32[McpServerToolType]
33public static class EchoTool
34{
35 [McpServerTool, Description("Echoes the message back to the client.")]
36 public static string Echo(string message) => $"Yo! You said '{message}'";
37}
38
39// Add a strongly-typed response class for weather
40public record WeatherResponse(string City, int Temperature, int Humidity, string Condition);
41
42[McpServerToolType]
43public static class WeatherTool
44{
45 [McpServerTool, Description("Returns weather data as a typed object; framework will serialize to JSON.")]
46 public static WeatherResponse GetWeather(string? city)
47 {
48 string cityName = city ?? string.Empty;
49 int temperature = cityName.Length;
50 int humidity = temperature * 5;
51 var conditions = new[] { "Sunny", "Cloudy", "Rainy", "Windy" };
52 string condition = conditions[temperature % conditions.Length];
53 return new WeatherResponse(cityName, temperature, humidity, condition);
54 }
55}
56
57