Last active 1750778636

Revision 29837b43bc901a0cc7bd2b3903740ae5b1e3a75d

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
16app.MapMcp();
17
18app.Run("http://localhost:3001");
19
20[McpServerToolType]
21public 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
28public record WeatherResponse(string City, int Temperature, int Humidity, string Condition);
29
30[McpServerToolType]
31public 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}
44