This is a proper Model Context Protocol (MCP) server implementation for the BuildWithAspire application. It provides dynamic tool discovery and execution capabilities for AI models through the standardized MCP protocol.
The Model Context Protocol (MCP) is an open standard that enables seamless integration between AI applications and external data sources/tools. It allows AI models to:
- Dynamically discover tools available from MCP servers
- Execute tools safely with proper user consent and validation
- Access real-time data and services through standardized interfaces
- Maintain security through controlled tool execution
This MCP server implements the Streamable HTTP transport from the official MCP C# SDK, which provides:
- Stateful sessions - Session state is maintained across requests via the
Mcp-Session-Idheader - Server-Sent Events (SSE) - For server-to-client notifications
- JSON-RPC 2.0 - Standard protocol for request/response messages
- Automatic session management - The SDK's
StatefulSessionManagerhandles session lifecycle
-
First request (no session ID):
POST / Content-Type: application/json {"jsonrpc":"2.0","id":"1","method":"initialize",...}Server responds with
Mcp-Session-Idheader containing a new session ID. -
Subsequent requests (with session ID):
POST / Content-Type: application/json Mcp-Session-Id: <session-id-from-first-request> {"jsonrpc":"2.0","id":"2","method":"tools/list",...}
Server reuses the existing session.
-
SSE notifications (optional):
GET / Mcp-Session-Id: <session-id>
Opens an SSE stream for server-to-client messages.
-
Session cleanup:
DELETE / Mcp-Session-Id: <session-id>
Explicitly closes the session (or wait for idle timeout).
- Idle Timeout: 2 hours (configurable in Program.cs)
- Max Idle Sessions: 10,000 (configurable in Program.cs)
- Session ID Format: Base64-URL-encoded random bytes (generated by SDK)
This MCP server provides several tool categories:
GetCurrentWeather()- Gets current weather informationGetWeatherForecast(maxDays)- Gets weather forecast for 1-10 daysConvertTemperature(temperature, fromUnit)- Converts between Celsius and Fahrenheit
GetCurrentDateTime()- Gets current date/time informationGetSystemInfo()- Gets system information (OS, .NET version, etc.)GenerateRandomNumber(min, max)- Generates random numbersEncodeToBase64(text)- Encodes text to Base64DecodeFromBase64(base64Text)- Decodes Base64 to plain text
Calculate(a, b, operation)- Basic arithmetic operationsSquareRoot(number)- Calculates square rootPower(baseNumber, exponent)- Raises to powerGenerateFibonacci(terms)- Generates Fibonacci sequenceIsPrime(number)- Checks if number is prime
- Implements proper MCP JSON-RPC 2.0 protocol
- Supports stdio transport for communication
- Provides tool discovery and execution capabilities
- Handles initialization and capability negotiation
IMcpClientinterface for interacting with MCP serversMcpClientimplementation that communicates via stdio- Integrated with
ChatServicefor AI-powered tool usage - Automatic detection of weather-related requests
When a user asks weather-related questions, the AI will:
- Detect weather keywords in the message
- Query the MCP server for appropriate weather data
- Include the real-time weather information in the AI response
- Provide accurate, up-to-date information
cd src/BuildWithAspire.MCPServer
echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{"tools":{}},"clientInfo":{"name":"test","version":"1.0"}}}' | dotnet runOnce the application is running:
# List available MCP tools
curl http://localhost:5000/mcp/tools
# Call a specific tool
curl -X POST http://localhost:5000/mcp/call/GetCurrentWeather \
-H "Content-Type: application/json" \
-d '{}'
# Test weather integration in chat
curl "http://localhost:5000/chat?message=What's the current weather?"{
"servers": {
"BuildWithAspire.MCPServer": {
"type": "stdio",
"command": "dotnet",
"args": [
"run",
"--project",
"path/to/BuildWithAspire.MCPServer"
]
}
}
}- Standards Compliant: Implements MCP specification correctly
- Type Safe: Uses C# with proper typing and validation
- Extensible: Easy to add new tools and capabilities
- Integrated: Works seamlessly with .NET Aspire architecture
- Secure: Proper error handling and input validation
The MCP server is integrated with the ChatService to provide enhanced AI capabilities:
// Weather-related messages automatically trigger MCP tool usage
"What's the weather like?"
// → Calls GetCurrentWeather() and includes real data in AI response
"Give me a 5-day forecast"
// → Calls GetWeatherForecast(5) and provides detailed forecast
"What's 15 degrees Celsius in Fahrenheit?"
// → Calls ConvertTemperature(15, "C") and provides conversionThis server implements the complete MCP specification:
- ✅ JSON-RPC 2.0 messaging
- ✅ Proper initialization handshake
- ✅ Tool discovery (
tools/list) - ✅ Tool execution (
tools/call) - ✅ Error handling and validation
- ✅ Capability negotiation
- ✅ Stdio transport support
The MCP architecture makes it easy to add:
- Database query tools
- File system operations
- API integrations
- Custom business logic
- External service connectors
This demonstrates the power of MCP: once the protocol is implemented, adding new capabilities is as simple as creating new [McpServerTool] methods.