Skip to content

Commit b8954b3

Browse files
committed
Update to use a HttpClientFactory
1 parent c406230 commit b8954b3

2 files changed

Lines changed: 14 additions & 7 deletions

File tree

samples/ProtectedMCPServer/Program.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -81,11 +81,11 @@
8181
.WithTools<WeatherTools>()
8282
.WithHttpTransport();
8383

84-
builder.Services.AddSingleton(_ =>
84+
// Configure HttpClientFactory for weather.gov API
85+
builder.Services.AddHttpClient("WeatherApi", client =>
8586
{
86-
var client = new HttpClient() { BaseAddress = new Uri("https://api.weather.gov") };
87+
client.BaseAddress = new Uri("https://api.weather.gov");
8788
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("weather-tool", "1.0"));
88-
return client;
8989
});
9090

9191
var app = builder.Build();

samples/ProtectedMCPServer/Tools/WeatherTools.cs

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,18 @@ namespace ProtectedMCPServer.Tools;
99
[McpServerToolType]
1010
public sealed class WeatherTools
1111
{
12+
private readonly IHttpClientFactory _httpClientFactory;
13+
14+
public WeatherTools(IHttpClientFactory httpClientFactory)
15+
{
16+
_httpClientFactory = httpClientFactory;
17+
}
18+
1219
[McpServerTool, Description("Get weather alerts for a US state.")]
13-
public static async Task<string> GetAlerts(
14-
HttpClient client,
20+
public async Task<string> GetAlerts(
1521
[Description("The US state to get alerts for. Use the 2 letter abbreviation for the state (e.g. NY).")] string state)
1622
{
23+
var client = _httpClientFactory.CreateClient("WeatherApi");
1724
using var jsonDocument = await client.ReadJsonDocumentAsync($"/alerts/active/area/{state}");
1825
var jsonElement = jsonDocument.RootElement;
1926
var alerts = jsonElement.GetProperty("features").EnumerateArray();
@@ -37,11 +44,11 @@ public static async Task<string> GetAlerts(
3744
}
3845

3946
[McpServerTool, Description("Get weather forecast for a location.")]
40-
public static async Task<string> GetForecast(
41-
HttpClient client,
47+
public async Task<string> GetForecast(
4248
[Description("Latitude of the location.")] double latitude,
4349
[Description("Longitude of the location.")] double longitude)
4450
{
51+
var client = _httpClientFactory.CreateClient("WeatherApi");
4552
var pointUrl = string.Create(CultureInfo.InvariantCulture, $"/points/{latitude},{longitude}");
4653
using var jsonDocument = await client.ReadJsonDocumentAsync(pointUrl);
4754
var forecastUrl = jsonDocument.RootElement.GetProperty("properties").GetProperty("forecast").GetString()

0 commit comments

Comments
 (0)