Skip to main content
Glama
kasirajan22

DotNet MCP Server Demo

by kasirajan22
README.md
# MCP Demo - .NET Web API with Model Context Protocol Server

This project demonstrates a simple .NET 8 Web API that implements a Model Context Protocol (MCP) server with Basic Authentication.

## Features

- **MCP Server Implementation**: Handles MCP protocol messages including initialization, tool calls, and resource management
- **Basic Authentication**: Simple username/password authentication for API endpoints
- **Sample Tools**: Includes example tools like time retrieval, echo, and calculator
- **RESTful API**: Standard REST endpoints for MCP operations
- **Swagger Documentation**: Auto-generated API documentation

## Prerequisites

- .NET 8.0 SDK or later
- Visual Studio 2022, VS Code, or any preferred IDE

## Getting Started

### 1. Restore Dependencies

```powershell
dotnet restore
```

### 2. Build the Project

```powershell
dotnet build
```

### 3. Run the Application

```powershell
dotnet run
```

The application will start on `https://localhost:5001` and `http://localhost:5000`.

### 4. Access Swagger UI

Open your browser and navigate to: `https://localhost:5001/swagger`

## Authentication

The API uses Basic Authentication with hardcoded credentials for demonstration:

- **Username**: `admin`
- **Password**: `password123`

### Using Basic Auth in HTTP Requests

Include the `Authorization` header with Base64 encoded credentials:

```
Authorization: Basic YWRtaW46cGFzc3dvcmQxMjM=
```

## API Endpoints

### MCP Endpoints (Require Authentication)

- `POST /api/mcp/message` - Handle MCP protocol messages
- `GET /api/mcp/tools` - Get available tools
- `GET /api/mcp/resources` - Get available resources

### Health Check (Public)

- `GET /api/mcp/health` - Health check endpoint

### Sample Endpoints

- `GET /api/weather` - Get weather data (requires authentication)
- `GET /api/weather/public` - Get public weather data (no authentication)

## MCP Protocol Usage

### Initialize the Server

```json
POST /api/mcp/message
{
  "jsonrpc": "2.0",
  "id": "1",
  "method": "initialize",
  "params": {
    "protocolVersion": "2024-11-05",
    "capabilities": {},
    "clientInfo": {
      "name": "Test Client",
      "version": "1.0.0"
    }
  }
}
```

### List Available Tools

```json
POST /api/mcp/message
{
  "jsonrpc": "2.0",
  "id": "2",
  "method": "tools/list"
}
```

### Call a Tool

```json
POST /api/mcp/message
{
  "jsonrpc": "2.0",
  "id": "3",
  "method": "tools/call",
  "params": {
    "name": "echo",
    "arguments": {
      "message": "Hello, MCP!"
    }
  }
}
```

### Calculate Tool Example

```json
POST /api/mcp/message
{
  "jsonrpc": "2.0",
  "id": "4",
  "method": "tools/call",
  "params": {
    "name": "calculate",
    "arguments": {
      "operation": "add",
      "a": 10,
      "b": 5
    }
  }
}
```

## Available Tools

1. **get_time**: Returns the current date and time
2. **echo**: Echoes back the provided message
3. **calculate**: Performs basic arithmetic operations (add, subtract, multiply, divide)

## Project Structure

```
MCPDemo/
├── Controllers/
│   ├── McpController.cs      # MCP protocol endpoints
│   └── WeatherController.cs  # Sample API endpoints
├── Models/
│   └── McpModels.cs         # MCP protocol data models
├── Services/
│   ├── BasicAuthenticationHandler.cs  # Basic auth implementation
│   └── McpServer.cs         # MCP server logic
├── Program.cs               # Application entry point
├── appsettings.json        # Configuration
└── MCPDemo.csproj          # Project file
```

## Security Considerations

⚠️ **Important**: This implementation uses hardcoded credentials for demonstration purposes only. In production:

1. Use proper user authentication with a database
2. Implement secure password hashing
3. Use HTTPS only
4. Consider JWT tokens instead of Basic Auth
5. Implement proper authorization policies
6. Add rate limiting and input validation

## Extending the Server

### Adding New Tools

1. Add the tool definition in `McpServer.GetToolsAsync()`
2. Implement the tool logic in `McpServer.ExecuteToolAsync()`
3. Define the input schema for the tool

### Adding New Resources

1. Add resource definitions in `McpServer.GetResourcesAsync()`
2. Implement resource reading logic in `HandleResourceReadAsync()`

## Testing with curl

### Health Check

```powershell
curl -X GET https://localhost:5001/api/mcp/health
```

### Get Tools (with auth)

```powershell
curl -X GET https://localhost:5001/api/mcp/tools -H "Authorization: Basic YWRtaW46cGFzc3dvcmQxMjM="
```

### Send MCP Message

```powershell
curl -X POST https://localhost:5001/api/mcp/message `
  -H "Content-Type: application/json" `
  -H "Authorization: Basic YWRtaW46cGFzc3dvcmQxMjM=" `
  -d '{
    "jsonrpc": "2.0",
    "id": "1",
    "method": "initialize",
    "params": {
      "protocolVersion": "2024-11-05",
      "capabilities": {},
      "clientInfo": {"name": "Test Client", "version": "1.0.0"}
    }
  }'
```

## License

This project is for demonstration purposes only.