Skip to content
This repository was archived by the owner on Apr 8, 2025. It is now read-only.

Commit 27c1519

Browse files
authored
Updating to align with quickstart sample (#221)
1 parent 0e679f9 commit 27c1519

File tree

2 files changed

+36
-54
lines changed

2 files changed

+36
-54
lines changed

quickstart/client.mdx

+10-12
Original file line numberDiff line numberDiff line change
@@ -1384,7 +1384,7 @@ cd QuickstartClient
13841384

13851385
Then, add the required dependencies to your project:
13861386
```bash
1387-
dotnet add package ModelContextProtocol --preview
1387+
dotnet add package ModelContextProtocol --prerelease
13881388
dotnet add package Anthropic.SDK
13891389
dotnet add package Microsoft.Extensions.Hosting
13901390
```
@@ -1423,10 +1423,10 @@ var (command, arguments) = args switch
14231423
_ => throw new NotSupportedException("An unsupported server script was provided. Supported scripts are .py, .js, or .csproj")
14241424
};
14251425
1426-
var mcpClient = await McpClientFactory.CreateAsync(new()
1426+
await using var mcpClient = await McpClientFactory.CreateAsync(new()
14271427
{
1428-
Id = "demo-client",
1429-
Name = "Demo Client",
1428+
Id = "demo-server",
1429+
Name = "Demo Server",
14301430
TransportType = TransportTypes.StdIo,
14311431
TransportOptions = new()
14321432
{
@@ -1455,7 +1455,7 @@ This configures a MCP client that will connect to a server that is provided as a
14551455
Now let's add the core functionality for processing queries and handling tool calls:
14561456

14571457
```csharp
1458-
IChatClient anthropicClient = new AnthropicClient(new APIAuthentication(builder.Configuration["ANTHROPIC_API_KEY"]))
1458+
using IChatClient anthropicClient = new AnthropicClient(new APIAuthentication(builder.Configuration["ANTHROPIC_API_KEY"]))
14591459
.Messages
14601460
.AsBuilder()
14611461
.UseFunctionInvocation()
@@ -1465,7 +1465,7 @@ var options = new ChatOptions
14651465
{
14661466
MaxOutputTokens = 1000,
14671467
ModelId = "claude-3-5-sonnet-20241022",
1468-
Tools = [.. tools.Cast<AITool>()]
1468+
Tools = [.. tools]
14691469
};
14701470
14711471
while (true)
@@ -1484,16 +1484,14 @@ while (true)
14841484
break;
14851485
}
14861486
1487-
var response = await anthropicClient.GetResponseAsync(query, options);
1487+
var response = anthropicClient.GetStreamingResponseAsync(query, options);
14881488
1489-
foreach (var message in response.Messages)
1489+
await foreach (var message in response)
14901490
{
1491-
Console.WriteLine(message.Text);
1491+
Console.Write(message.Text);
14921492
}
1493+
Console.WriteLine();
14931494
}
1494-
1495-
anthropicClient.Dispose();
1496-
await mcpClient.DisposeAsync();
14971495
```
14981496

14991497
## Key Components Explained

quickstart/server.mdx

+26-42
Original file line numberDiff line numberDiff line change
@@ -1450,7 +1450,7 @@ After creating the project, add NuGet package for the Model Context Protocol SDK
14501450

14511451
```bash
14521452
# Add the Model Context Protocol SDK NuGet package
1453-
dotnet add package ModelContextProtocol --preview
1453+
dotnet add package ModelContextProtocol --prerelease
14541454
# Add the .NET Hosting NuGet package
14551455
dotnet add package Microsoft.Extensions.Hosting
14561456
```
@@ -1461,14 +1461,24 @@ Now let’s dive into building your server.
14611461
Open the `Program.cs` file in your project and replace its contents with the following code:
14621462

14631463
```csharp
1464+
using Microsoft.Extensions.DependencyInjection;
14641465
using Microsoft.Extensions.Hosting;
14651466
using ModelContextProtocol;
1467+
using System.Net.Http.Headers;
14661468

14671469
var builder = Host.CreateEmptyApplicationBuilder(settings: null);
1470+
14681471
builder.Services.AddMcpServer()
14691472
.WithStdioServerTransport()
14701473
.WithToolsFromAssembly();
14711474

1475+
builder.Services.AddSingleton(_ =>
1476+
{
1477+
var client = new HttpClient() { BaseAddress = new Uri("https://api.weather.gov") };
1478+
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("weather-tool", "1.0"));
1479+
return client;
1480+
});
1481+
14721482
var app = builder.Build();
14731483

14741484
await app.RunAsync();
@@ -1485,7 +1495,7 @@ Next, define a class with the tool execution handlers for querying and convertin
14851495
```csharp
14861496
using ModelContextProtocol.Server;
14871497
using System.ComponentModel;
1488-
using System.Net.Http.Headers;
1498+
using System.Net.Http.Json;
14891499
using System.Text.Json;
14901500

14911501
namespace QuickstartWeatherServer.Tools;
@@ -1495,71 +1505,45 @@ public static class WeatherTools
14951505
{
14961506
[McpServerTool, Description("Get weather alerts for a US state.")]
14971507
public static async Task<string> GetAlerts(
1508+
HttpClient client,
14981509
[Description("The US state to get alerts for.")] string state)
14991510
{
1500-
using HttpClient client = GetWeatherClient();
1501-
1502-
var response = await client.GetAsync($"/alerts/active/area/{state}");
1503-
1504-
var json = await response.Content.ReadAsStringAsync();
1505-
var jsonElement = JsonSerializer.Deserialize<JsonElement>(json);
1511+
var jsonElement = await client.GetFromJsonAsync<JsonElement>($"/alerts/active/area/{state}");
15061512
var alerts = jsonElement.GetProperty("features").EnumerateArray();
15071513

15081514
if (!alerts.Any())
15091515
{
15101516
return "No active alerts for this state.";
15111517
}
15121518

1513-
// Process the alerts and return a formatted string
1514-
var alertMessages = new List<string>();
1515-
foreach (var alert in alerts)
1519+
return string.Join("\n--\n", alerts.Select(alert =>
15161520
{
15171521
JsonElement properties = alert.GetProperty("properties");
1518-
alertMessages.Add($"""
1522+
return $"""
15191523
Event: {properties.GetProperty("event").GetString()}
15201524
Area: {properties.GetProperty("areaDesc").GetString()}
15211525
Severity: {properties.GetProperty("severity").GetString()}
15221526
Description: {properties.GetProperty("description").GetString()}
15231527
Instruction: {properties.GetProperty("instruction").GetString()}
1524-
""");
1525-
}
1526-
return string.Join("\n---\n", alertMessages);
1528+
""";
1529+
}));
15271530
}
15281531

15291532
[McpServerTool, Description("Get weather forecast for a location.")]
15301533
public static async Task<string> GetForecast(
1534+
HttpClient client,
15311535
[Description("Latitude of the location.")] double latitude,
15321536
[Description("Longitude of the location.")] double longitude)
15331537
{
1534-
using HttpClient client = GetWeatherClient();
1535-
var response = await client.GetAsync($"/points/{latitude},{longitude}");
1536-
if (!response.IsSuccessStatusCode)
1537-
{
1538-
return "Failed to retrieve forecast.";
1539-
}
1540-
1541-
var json = await response.Content.ReadAsStringAsync();
1542-
var jsonElement = JsonSerializer.Deserialize<JsonElement>(json);
1538+
var jsonElement = await client.GetFromJsonAsync<JsonElement>($"/points/{latitude},{longitude}");
15431539
var periods = jsonElement.GetProperty("properties").GetProperty("periods").EnumerateArray();
1544-
// Process the forecast and return a formatted string
1545-
var forecastMessages = new List<string>();
1546-
foreach (var period in periods)
1547-
{
1548-
forecastMessages.Add($"""
1549-
{period.GetProperty("name").GetString()}
1550-
Temperature: {period.GetProperty("temperature").GetInt32()}°F
1551-
Wind: {period.GetProperty("windSpeed").GetString()} {period.GetProperty("windDirection").GetString()}
1552-
Forecast: {period.GetProperty("detailedForecast").GetString()}
1553-
""");
1554-
}
1555-
return string.Join("\n---\n", forecastMessages);
1556-
}
15571540

1558-
private static HttpClient GetWeatherClient()
1559-
{
1560-
var client = new HttpClient() { BaseAddress = new Uri("https://api.weather.gov") };
1561-
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("weather-tool", "1.0"));
1562-
return client;
1541+
return string.Join("\n---\n", periods.Select(period => $"""
1542+
{period.GetProperty("name").GetString()}
1543+
Temperature: {period.GetProperty("temperature").GetInt32()}°F
1544+
Wind: {period.GetProperty("windSpeed").GetString()} {period.GetProperty("windDirection").GetString()}
1545+
Forecast: {period.GetProperty("detailedForecast").GetString()}
1546+
"""));
15631547
}
15641548
}
15651549
```

0 commit comments

Comments
 (0)