CSharp-MCP-Server

nissynicolas/CSharp-MCP-Server

3.2

If you are the rightful owner of CSharp-MCP-Server 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.

A Model Context Protocol (MCP) server implementation in C# using the official MCP SDK, providing tools for file system management, text processing, and system information collection.

Tools
19
Resources
0
Prompts
0

C# MCP Server

A Model Context Protocol (MCP) server implementation in C# using the official MCP SDK. This server provides 18 comprehensive tools across three categories for file system management, text processing, and system information collection.

✨ Features

This MCP server includes 18 individual tools across three categories:

📁 File System Tools (3 tools)

  • ListDirectory: Browse directory contents with detailed file information
  • ReadFile: Read file contents with security checks and size limits
  • FileExists: Check if files or directories exist in the system

📝 Text Processing Tools (9 tools)

  • CountWords: Count the number of words in provided text
  • CountCharacters: Count total characters in text
  • CountLines: Count the number of lines in text
  • ToUpperCase: Convert text to uppercase
  • ToLowerCase: Convert text to lowercase
  • ReverseText: Reverse the provided text
  • TrimAndCleanWhitespace: Remove extra whitespace and trim text
  • ExtractWords: Extract words and return as comma-separated list
  • FindAndReplace: Find and replace text using regex patterns

🖥️ System Information Tools (7 tools)

  • GetOperatingSystemInfo: Get OS details, platform, and architecture
  • GetUserInfo: Get current user and machine information
  • GetRuntimeInfo: Get .NET runtime and version information
  • GetEnvironmentVariables: Get system environment variables (limited for security)
  • GetSystemPerformanceInfo: Get memory usage and system performance metrics
  • GetDirectoryInfo: Get current directory and special folder paths
  • GetNetworkInfo: Get hostname and network configuration details

🚀 Quick Start

Prerequisites

  • .NET 9.0 SDK or later
  • VS Code with MCP extensions or Cursor IDE (recommended)

Dependencies

  • ModelContextProtocol (0.4.0-preview.1) - Official MCP SDK for .NET
  • Microsoft.Extensions.Hosting (9.0.9) - For dependency injection and hosting

Build and Run

# Build the project
dotnet build

# Run the MCP server
dotnet run

The server communicates via JSON-RPC over stdin/stdout, making it compatible with any MCP client.

🛠️ Integration with IDEs

Cursor IDE (Recommended)

Add to your Cursor MCP configuration:

{
  "mcpServers": {
    "csharp-tools": {
      "command": "dotnet",
      "args": ["run", "--project", "path/to/CSharp-MCP-Server", "--no-build"],
      "cwd": "path/to/CSharp-MCP-Server"
    }
  }
}

VS Code

Install one of these MCP extensions:

  • Copilot MCP (automatalabs.copilot-mcp)
  • MCP-Client (m1self.mcp-client)
  • MCP Server Runner (zebradev.mcp-server-runner)

Then configure your server in the extension settings.

📚 Usage Examples

List All Available Tools

{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}

File System Operations

{
  "jsonrpc": "2.0", "id": 2, "method": "tools/call",
  "params": {
    "name": "ListDirectory",
    "arguments": {"path": "C:\\Users"}
  }
}

Text Processing

{
  "jsonrpc": "2.0", "id": 3, "method": "tools/call",
  "params": {
    "name": "CountWords", 
    "arguments": {"text": "Hello world, this is a test."}
  }
}

System Information

{
  "jsonrpc": "2.0", "id": 4, "method": "tools/call",
  "params": {
    "name": "GetOperatingSystemInfo",
    "arguments": {}
  }
}

🏗️ Project Structure

CSharp-MCP-Server/
├── 📁 .github/              # GitHub workflows and configurations
├── 📁 .vscode/              # VS Code settings and configurations
├── 📄 CSharpMcpServer.csproj # Project file with dependencies
├── 📄 Program.cs            # Application entry point with MCP SDK setup
├── 📄 FileSystemTools.cs    # File system operations (3 tools)
├── 📄 TextProcessorTools.cs # Text processing operations (9 tools)  
├── 📄 SystemInfoTools.cs    # System information collection (7 tools)
├── 📄 test-mcp.bat          # Testing script for Windows
└── 📄 README.md             # This documentation

🔧 Technical Implementation

This server follows the official MCP SDK patterns:

Key Features

  • 🔍 Attribute-based Discovery: Tools are automatically discovered using [McpServerToolType] and [McpServerTool] attributes
  • 💉 Dependency Injection: Built on Microsoft.Extensions.Hosting for robust dependency management
  • 📡 Standard IO Transport: Uses stdin/stdout for JSON-RPC communication
  • 🚀 Automatic Registration: WithToolsFromAssembly() automatically registers all annotated tools

Code Structure

Each tool category is implemented as a static class:

[McpServerToolType]
public static class FileSystemTools
{
    [McpServerTool, Description("Lists files and directories")]
    public static string ListDirectory(string path) { /* implementation */ }
}

Program.cs (Entry Point)

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var builder = Host.CreateEmptyApplicationBuilder(null);

builder.Services
    .AddMcpServer()
    .WithStdioServerTransport()
    .WithToolsFromAssembly();

var app = builder.Build();
await app.RunAsync();

🛡️ Security & Best Practices

  • 🔒 File Access: File operations respect system permissions and include size limits
  • 🔐 Environment Variables: Limited exposure of sensitive environment data
  • ✅ Input Validation: All tools include comprehensive parameter validation
  • ⚡ Resource Limits: Processing operations have reasonable size and time limits
  • 🚫 Error Handling: Graceful error handling with descriptive messages

🧪 Testing Your MCP Server

Manual Testing

# Test tools list
echo '{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}' | dotnet run

# Test a specific tool
echo '{"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "ListDirectory", "arguments": {"path": "."}}}' | dotnet run

Using the Test Script

# Windows
test-mcp.bat

🚀 Extending the Server

To add new tools:

  1. Add to existing classes or create new [McpServerToolType] classes
  2. Annotate methods with [McpServerTool] and [Description] attributes
  3. Document parameters using [Description] on parameters
  4. Automatic discovery - the MCP SDK will find and register new tools

Example New Tool

[McpServerTool, Description("Calculates the factorial of a number")]
public static long CalculateFactorial([Description("The number to calculate factorial for")] int number)
{
    if (number < 0) throw new ArgumentException("Number must be non-negative");
    if (number == 0) return 1;
    
    long result = 1;
    for (int i = 1; i <= number; i++)
    {
        result *= i;
    }
    return result;
}

🎯 Compatible MCP Clients

This server works with any MCP client that supports JSON-RPC over stdin/stdout:

  • ✅ Cursor IDE (Native MCP support)
  • ✅ VS Code (With MCP extensions)
  • ✅ Claude Desktop (With configuration)
  • ✅ Custom MCP clients (Following MCP specification)

📋 Requirements

  • Runtime: .NET 9.0 SDK or later
  • OS Support: Windows, macOS, and Linux
  • MCP Client: Any client supporting JSON-RPC over stdin/stdout
  • Development: Visual Studio Code or Cursor IDE recommended

📄 License

This project is available under the MIT License.

🔗 References


Built with ❤️ using the official MCP SDK for .NET