Skip to content

Commit a148f44

Browse files
committed
Code review feedback
1 parent cceb695 commit a148f44

File tree

3 files changed

+32
-60
lines changed

3 files changed

+32
-60
lines changed

samples/QuickstartClient/Program.cs

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ [var script] when Directory.Exists(script) || (File.Exists(script) && script.End
1919
_ => ("dotnet", "run --project ../../../../QuickstartWeatherServer --no-build")
2020
};
2121

22-
var mcpClient = await McpClientFactory.CreateAsync(new()
22+
await using var mcpClient = await McpClientFactory.CreateAsync(new()
2323
{
2424
Id = "demo-client",
2525
Name = "Demo Client",
@@ -37,7 +37,7 @@ [var script] when Directory.Exists(script) || (File.Exists(script) && script.End
3737
Console.WriteLine($"Connected to server with tools: {tool.Name}");
3838
}
3939

40-
var anthropicClient = new AnthropicClient(new APIAuthentication(builder.Configuration["ANTHROPIC_API_KEY"]))
40+
using var anthropicClient = new AnthropicClient(new APIAuthentication(builder.Configuration["ANTHROPIC_API_KEY"]))
4141
.Messages
4242
.AsBuilder()
4343
.UseFunctionInvocation()
@@ -47,7 +47,7 @@ [var script] when Directory.Exists(script) || (File.Exists(script) && script.End
4747
{
4848
MaxOutputTokens = 1000,
4949
ModelId = "claude-3-5-sonnet-20241022",
50-
Tools = [.. tools.Cast<AITool>()]
50+
Tools = [.. tools]
5151
};
5252

5353
while (true)
@@ -66,13 +66,11 @@ [var script] when Directory.Exists(script) || (File.Exists(script) && script.End
6666
break;
6767
}
6868

69-
var response = await anthropicClient.GetResponseAsync(query, options);
69+
var response = anthropicClient.GetStreamingResponseAsync(query, options);
7070

71-
foreach (var message in response.Messages)
71+
await foreach (var message in response)
7272
{
73-
Console.WriteLine(message.Text);
73+
Console.Write(message.Text);
7474
}
75+
Console.WriteLine();
7576
}
76-
77-
anthropicClient.Dispose();
78-
await mcpClient.DisposeAsync();
Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,21 @@
1-
using Microsoft.Extensions.Hosting;
2-
using Microsoft.Extensions.Logging;
1+
using Microsoft.Extensions.DependencyInjection;
2+
using Microsoft.Extensions.Hosting;
33
using ModelContextProtocol;
4+
using System.Net.Http.Headers;
45

56
var builder = Host.CreateEmptyApplicationBuilder(settings: null);
67

7-
//builder.Logging.ClearProviders();
8-
//builder.Logging.AddFilter("Microsoft", LogLevel.Warning); // Adjust the log level as needed
9-
108
builder.Services.AddMcpServer()
119
.WithStdioServerTransport()
1210
.WithToolsFromAssembly();
1311

12+
builder.Services.AddSingleton(_ =>
13+
{
14+
var client = new HttpClient() { BaseAddress = new Uri("https://api.weather.gov") };
15+
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("weather-tool", "1.0"));
16+
return client;
17+
});
18+
1419
var app = builder.Build();
1520

1621
await app.RunAsync();
Lines changed: 15 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
using ModelContextProtocol.Server;
22
using System.ComponentModel;
3-
using System.Net.Http.Headers;
3+
using System.Net.Http.Json;
44
using System.Text.Json;
55

66
namespace QuickstartWeatherServer.Tools;
@@ -10,75 +10,44 @@ public static class WeatherTools
1010
{
1111
[McpServerTool, Description("Get weather alerts for a US state.")]
1212
public static async Task<string> GetAlerts(
13+
HttpClient client,
1314
[Description("The US state to get alerts for.")] string state)
1415
{
15-
using HttpClient client = GetWeatherClient();
16-
17-
var response = await client.GetAsync($"/alerts/active/area/{state}");
18-
19-
if (!response.IsSuccessStatusCode)
20-
{
21-
return "Failed to retrieve alerts.";
22-
}
23-
24-
var json = await response.Content.ReadAsStringAsync();
25-
var jsonElement = JsonSerializer.Deserialize<JsonElement>(json);
16+
var jsonElement = await client.GetFromJsonAsync<JsonElement>($"/alerts/active/area/{state}");
2617
var alerts = jsonElement.GetProperty("features").EnumerateArray();
2718

2819
if (!alerts.Any())
2920
{
3021
return "No active alerts for this state.";
3122
}
3223

33-
// Process the alerts and return a formatted string
34-
var alertMessages = new List<string>();
35-
foreach (var alert in alerts)
24+
return string.Join("\n--\n", alerts.Select(alert =>
3625
{
3726
JsonElement properties = alert.GetProperty("properties");
38-
alertMessages.Add($"""
27+
return $"""
3928
Event: {properties.GetProperty("event").GetString()}
4029
Area: {properties.GetProperty("areaDesc").GetString()}
4130
Severity: {properties.GetProperty("severity").GetString()}
4231
Description: {properties.GetProperty("description").GetString()}
4332
Instruction: {properties.GetProperty("instruction").GetString()}
44-
""");
45-
}
46-
return string.Join("\n---\n", alertMessages);
33+
""";
34+
}));
4735
}
4836

4937
[McpServerTool, Description("Get weather forecast for a location.")]
5038
public static async Task<string> GetForecast(
39+
HttpClient client,
5140
[Description("Latitude of the location.")] double latitude,
5241
[Description("Longitude of the location.")] double longitude)
5342
{
54-
using HttpClient client = GetWeatherClient();
55-
var response = await client.GetAsync($"/points/{latitude},{longitude}");
56-
if (!response.IsSuccessStatusCode)
57-
{
58-
return "Failed to retrieve forecast.";
59-
}
60-
61-
var json = await response.Content.ReadAsStringAsync();
62-
var jsonElement = JsonSerializer.Deserialize<JsonElement>(json);
43+
var jsonElement = await client.GetFromJsonAsync<JsonElement>($"/points/{latitude},{longitude}");
6344
var periods = jsonElement.GetProperty("properties").GetProperty("periods").EnumerateArray();
64-
// Process the forecast and return a formatted string
65-
var forecastMessages = new List<string>();
66-
foreach (var period in periods)
67-
{
68-
forecastMessages.Add($"""
69-
{period.GetProperty("name").GetString()}
70-
Temperature: {period.GetProperty("temperature").GetInt32()}°F
71-
Wind: {period.GetProperty("windSpeed").GetString()} {period.GetProperty("windDirection").GetString()}
72-
Forecast: {period.GetProperty("detailedForecast").GetString()}
73-
""");
74-
}
75-
return string.Join("\n---\n", forecastMessages);
76-
}
7745

78-
private static HttpClient GetWeatherClient()
79-
{
80-
var client = new HttpClient() { BaseAddress = new Uri("https://api.weather.gov") };
81-
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("weather-tool", "1.0"));
82-
return client;
46+
return string.Join("\n---\n", periods.Select(period => $"""
47+
{period.GetProperty("name").GetString()}
48+
Temperature: {period.GetProperty("temperature").GetInt32()}°F
49+
Wind: {period.GetProperty("windSpeed").GetString()} {period.GetProperty("windDirection").GetString()}
50+
Forecast: {period.GetProperty("detailedForecast").GetString()}
51+
"""));
8352
}
8453
}

0 commit comments

Comments
 (0)