MCPRUNNER/templateMCP
If you are the rightful owner of templateMCP and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to dayong@mcphub.com.
This template provides a starting point for building Model Context Protocol (MCP) servers in C#.
Template MCP Server
A basic C# API template for creating Model Context Protocol (MCP) servers, based on the mssqlMCP architecture and using the same packages and versions.
Overview
This template provides a starting point for building MCP servers in C# that can integrate with VS Code and GitHub Copilot. It includes the core infrastructure, dependency injection setup, and example tools following the same patterns as the mssqlMCP project.
Features
- MCP Server Implementation: Built with ModelContextProtocol.AspNetCore (v0.1.0-preview.13)
- Dual Transport Support: HTTP and Stdio transports
- Structured Logging: Using Serilog with console and file output
- Dependency Injection: Clean architecture with separation of concerns
- CORS Support: Configurable cross-origin resource sharing
- Sample Tools: Example MCP tools demonstrating the pattern
Prerequisites
- .NET 9.0 SDK or later
- Visual Studio Code (optional, for Copilot integration)
Project Structure
templateMCP/
├── Configuration/ # Configuration providers
├── Extensions/ # Service collection extensions
├── Interfaces/ # Service interfaces
├── Models/ # Data models
├── Tools/ # MCP tool implementations
├── Logs/ # Log files (generated at runtime)
├── appsettings.json # Application configuration
├── appsettings.Development.json # Development configuration
├── Program.cs # Application entry point
└── templateMCP.csproj # Project file
Getting Started
1. Installation
Clone or download this template to your local machine.
2. Configuration
Configure your settings in appsettings.json:
- Connection Strings: Update the database connection string if needed
- CORS Settings: Configure allowed origins, methods, and headers
- Logging: Adjust Serilog settings as needed
3. Environment Variables
Set the transport type using an environment variable:
# For HTTP transport (default)
$env:TEMPLATE_MCP_TRANSPORT = "Http"
# For Stdio transport (for VS Code integration)
$env:TEMPLATE_MCP_TRANSPORT = "Stdio"
Note: The transport type determines how logging is configured:
- HTTP mode: Reads logging configuration from
appsettings.json - Stdio mode: Programmatically configures logging to stderr to prevent JSON-RPC interference
4. Build and Run
# Restore dependencies
dotnet restore
# Build the project
dotnet build
# Run the application
dotnet run
The server will start on http://localhost:5000 by default (HTTP mode).
Available MCP Tools
This template includes three sample tools:
- template_initialize_connection: Initializes a connection
- template_get_sample_data: Returns sample data
- template_execute_operation: Executes a sample operation
Example Usage
{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": "template_get_sample_data",
"arguments": {
"connectionName": "DefaultConnection"
}
}
}
Creating Your Own Tools
To create your own MCP tools:
- Create a Tool Class in the
Tools/folder:
[McpServerToolType]
public class MyCustomTools
{
[McpServerTool(Name = "my_custom_tool"), Description("Description of my tool.")]
public async Task<string> MyCustomTool(string parameter)
{
// Your implementation here
return JsonSerializer.Serialize(result);
}
}
- Register the Tool in
Program.cs:
builder.Services.AddMcpServer().WithHttpTransport()
.WithTools<SampleTools>()
.WithTools<MyCustomTools>(); // Add your tool
Package Dependencies
This template uses the same packages and versions as mssqlMCP:
- ModelContextProtocol.AspNetCore: 0.1.0-preview.13
- Microsoft.Data.SqlClient: 6.0.2
- Microsoft.Data.Sqlite: 9.0.5
- Serilog.AspNetCore: 9.0.0
- Dapper: 2.1.66
- Testing: xUnit 2.6.6, Moq 4.20.70, Microsoft.NET.Test.Sdk 17.9.0
Architecture
graph TD
A[VS Code/Copilot] -->|MCP Protocol| B[MCP Server]
B --> C[Tools Layer]
C --> D[SampleTools]
D --> E[Service Layer]
E --> F[SampleService]
E --> G[ConfigurationProvider]
E --> H[LoggingConfigurationService]
style A fill:#e1f5ff
style B fill:#fff4e1
style C fill:#e8f5e9
style D fill:#e8f5e9
style E fill:#f3e5f5
style F fill:#f3e5f5
style G fill:#f3e5f5
style H fill:#f3e5f5
This template follows a clean architecture pattern:
- Program.cs: Application entry point with DI configuration and transport-aware logging
- Tools/: MCP tool implementations decorated with
[McpServerToolType] - Services/: Business logic separated from MCP protocol handling
- Interfaces/: Service contracts
- Configuration/: Configuration providers
- Extensions/: Service registration extensions
- Models/: Data models
Key Design Decisions
- Transport-Aware Logging: The application detects the transport mode (HTTP/Stdio) before configuring Serilog, ensuring proper stdout/stderr separation
- Error Handling: Global exception middleware with graceful handling of
OperationCanceledExceptionfor clean shutdowns - Middleware Ordering: Error handling middleware is placed first to catch all exceptions before responses are started
Integration with VS Code
To use this MCP server with VS Code and Copilot:
-
Build the project first:
dotnet build -
Create a
.vscode/mcp.jsonfile in your workspace:{ "servers": { "templateMCP": { "command": "dotnet", "args": [ "c:\\path\\to\\templateMCP\\bin\\Debug\\net9.0\\templateMCP.dll" ], "env": { "TEMPLATE_MCP_TRANSPORT": "Stdio" } } } }Important: Use the pre-built DLL path instead of
dotnet runto avoid build output interfering with the MCP protocol. -
Restart VS Code to load the MCP server
Troubleshooting Stdio Mode
If you see "Failed to parse message" warnings in the Output window:
- Ensure you're running the built DLL (not
dotnet run) - The template automatically routes logs to stderr in Stdio mode
- Build warnings and stdout messages will interfere with JSON-RPC communication
- Check
Logs/folder for detailed application logs
Logging
Logs are written to:
- Console/Stderr: Real-time logging output
- In HTTP mode: Logs to stdout (console)
- In Stdio mode: Logs to stderr only (to avoid interfering with JSON-RPC on stdout)
- File:
Logs/templateMCP-YYYY-MM-DD.txt(daily rolling files, retained for 30 days)
Log levels can be configured in appsettings.json under the Serilog section. In Stdio mode, the template programmatically configures logging to prevent stdout contamination.
CORS Configuration
CORS settings in appsettings.json can be customized for production:
{
"Cors": {
"AllowedOrigins": ["https://your-domain.com"],
"AllowedMethods": ["GET", "POST"],
"AllowedHeaders": ["Content-Type", "Authorization"],
"AllowCredentials": true
}
}
Next Steps
- Customize the Tools: Modify
Tools/SampleTools.csor create new tool classes - Add Services: Create services in the
Services/folder for business logic - Add Models: Define your data models in the
Models/folder - Configure Database: Update connection strings for your database
- Add Authentication: Implement API key authentication following the mssqlMCP pattern
Reference Implementation
This template is based on the mssqlMCP project, which provides a comprehensive example of:
- Multi-tier API key authentication
- Connection string encryption
- Database metadata retrieval
- SQL Server integration
- Advanced security features
Refer to the mssqlMCP repository for advanced patterns and implementations.
License
This template follows the MIT License pattern.
Contributing
Contributions and improvements are welcome! Feel free to submit pull requests or open issues.