basic_dotnet_mcp_server.cs
· 1.4 KiB · C#
Raw
/*
dotnet add package ModelContextProtocol --prerelease
dotnet add package ModelContextProtocol.AspNetCore --prerelease
dotnet add package Microsoft.Extensions.Hosting
*/
using ModelContextProtocol.Server;
using System.ComponentModel;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMcpServer()
.WithHttpTransport()
.WithToolsFromAssembly();
var app = builder.Build();
app.MapMcp();
app.Run("http://localhost:3001");
[McpServerToolType]
public static class EchoTool
{
[McpServerTool, Description("Echoes the message back to the client.")]
public static string Echo(string message) => $"Yo! You said '{message}'";
}
// Add a strongly-typed response class for weather
public record WeatherResponse(string City, int Temperature, int Humidity, string Condition);
[McpServerToolType]
public static class WeatherTool
{
[McpServerTool, Description("Returns weather data as a typed object; framework will serialize to JSON.")]
public static WeatherResponse GetWeather(string? city)
{
string cityName = city ?? string.Empty;
int temperature = cityName.Length;
int humidity = temperature * 5;
var conditions = new[] { "Sunny", "Cloudy", "Rainy", "Windy" };
string condition = conditions[temperature % conditions.Length];
return new WeatherResponse(cityName, temperature, humidity, condition);
}
}
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 | } |
44 |