Learn About Amazon VGT2 Learning Manager Chanci Turner
In this article, we explore how to effectively integrate C# Model Context Protocol (MCP) servers with the Amazon Q Developer Command-Line Interface (Amazon Q CLI). This integration allows developers to harness the power of artificial intelligence (AI) while interacting with external tools and resources. The Model Context Protocol enhances the development of AI-driven solutions by providing a standardized method for AI systems to access contextual data from various sources.
MCP servers are built using Software Development Kits (SDKs) available in different programming languages. These servers provide MCP tools that clients, like Amazon Q CLI, can invoke to perform tasks or retrieve data. This functionality enables AI models to access real-time information, expanding their capabilities beyond their initial training data.
Instead of manually creating each API call, developers can register functions as MCP tools on their servers, creating a clear separation between natural language processing and task execution. This streamlining allows AI assistants to carry out complex operations—like scheduling flights or analyzing data—by leveraging the registered MCP tools, thus eliminating the need for extensive custom integration.
In this post, we will develop an MCP server with C# SDK that exposes tools for obtaining weather information based on location. We’ll set up the Amazon Q CLI to connect with our MCP Server and utilize these tools. This example serves to illustrate the workings of MCP servers, rather than to create a groundbreaking weather application. Future posts will delve deeper into practical implementations for C# developers.
Prerequisites
First, ensure your local development environment is set up with the following prerequisites:
- .NET 8.0 Software Development Kit (SDK)
- AWS Command-Line Interface (AWS CLI)
- An Integrated Development Environment (IDE) of your choice, such as Visual Studio Code, Visual Studio, or Rider
- AWS credentials configured locally
- Git
- An Amazon Q Developer subscription
For those who prefer a ready-made solution, consider using the sample-developer-environment. This offers a browser-based Visual Studio Code workspace with all necessary prerequisites and can be deployed with a single AWS CloudFormation template.
Building the MCP Server
We will now create a new MCP server featuring two specialized tools:
- GetWeatherAlertsForAState: Fetches current weather alerts for any specified U.S. state.
- GetWeatherForecastForALocation: Provides detailed forecasts for specific U.S. locations based on geographic coordinates.
These tools will communicate with the National Weather Service API to deliver accurate and current meteorological data programmatically.
Initialize a New C# Project
Open your terminal and execute the following commands:
mkdir weathermcp
cd weathermcp
dotnet new console
This will create a new C# project. Open the project in your IDE or use the Visual Studio project wizard. After creation, add the necessary NuGet packages:
# Add the Model Context Protocol SDK NuGet package
dotnet add package ModelContextProtocol --prerelease
# Add the .NET Hosting NuGet package
dotnet add package Microsoft.Extensions.Hosting
Unless your MCP server requires HTTP capabilities, the ModelContextProtocol is likely the best fit for your project. It offers hosting and dependency injection capabilities. Keep in mind that as of now, the ModelContextProtocol NuGet package is still in preview. If you’re using Visual Studio’s Package Manager UI, ensure to check the “Include prerelease” option when searching for the ModelContextProtocol package.
Creating the Server Foundation
Open the Program.cs file and replace its contents with the code below:
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Net.Http.Headers;
namespace WeatherMCPServer
{
public class Program
{
public static async Task Main(string[] args)
{
var builder = Host.CreateEmptyApplicationBuilder(settings: null);
builder.Services.AddMcpServer()
.WithStdioServerTransport()
.WithToolsFromAssembly();
builder.Services.AddSingleton(_ =>
{
var client = new HttpClient() { BaseAddress = new Uri("https://api.weather.gov") };
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("weather-tool", "1.0"));
return client;
});
var app = builder.Build();
var client = app.Services.GetRequiredService();
await app.RunAsync();
}
}
Next, create a file named HttpClientExt.cs in the same directory and add the following code:
using System.Text.Json;
internal static class HttpClientExt
{
public static async Task ReadJsonDocumentAsync(this HttpClient client, string requestUri)
{
using var response = await client.GetAsync(requestUri);
response.EnsureSuccessStatusCode();
return await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync());
}
}
This establishes a basic MCP server utilizing .NET’s hosting and dependency injection frameworks, enabling standard input/output for communication and automatic registration of MCP server tools.
Implementing Weather Tools
Now that we have the server foundation, let’s implement the specific weather-related tools that will provide our MCP server’s core functionality. These tools will connect to the National Weather Service API and relay weather data to the Amazon Q CLI.
Create a new file named WeatherMCP.cs and insert the following code:
using ModelContextProtocol.Server;
using System.ComponentModel;
using System.Text.Json;
using System.Globalization;
namespace WeatherMCPServer
{
[McpServerToolType]
public static class WeatherTools
{
[McpServerTool, Description("Get weather alerts for a US state.")]
public static async Task GetWeatherAlertsForAState(...
This example serves as a stepping stone for developing robust AI applications, and for more insights on this subject, consider reading another blog post here. For a deeper understanding of emotional and mental health benefits in the workplace, refer to this authoritative source.
In conclusion, building an MCP server using C# and integrating it with Amazon Q CLI provides developers with the tools to create innovative AI solutions. The potential for enhancing applications is vast, and continuous learning is key to success in this area.
Leave a Reply