MariaDbMcpServer

tomkolovratnik/MariaDbMcpServer

3.2

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

The MariaDB MCP Server is a Model Context Protocol server that provides Claude with direct access to MariaDB/MySQL databases, built using C# and .NET 8.0.

Tools
10
Resources
0
Prompts
0

MariaDB MCP Server

A Model Context Protocol (MCP) server that provides Claude with direct access to MariaDB/MySQL databases. Built with C# and .NET 8.0, following SOLID principles for maintainability and extensibility.

📝 Note on MCP Implementation: This project uses a custom implementation of the Model Context Protocol. While an official ModelContextProtocol NuGet package exists (currently v0.4.0-preview.3), we opted for a custom implementation to maintain full control over the architecture and avoid dependencies on preview packages. We may consider migrating to the official SDK once it reaches a stable 1.0 release.

Features

  • 10 MCP Tools for database operations:

    • query - Execute SELECT queries with parameterization
    • insert - Insert single or multiple rows
    • update - Update data with WHERE clauses
    • delete - Delete data with required WHERE clauses
    • execute_ddl - Schema modifications (CREATE, ALTER, DROP)
    • call_procedure - Execute stored procedures
    • call_function - Call stored functions
    • begin_transaction, commit, rollback - Transaction management
  • 9 MCP Resources for metadata:

    • Schema introspection (tables, columns, indexes, foreign keys)
    • Stored procedures and functions discovery
    • Database version and charset information
  • Security Features:

    • Granular permissions (Insert, Update, Delete, Schema Changes)
    • SQL injection protection via parameterized queries
    • Required WHERE clauses for UPDATE/DELETE
    • DDL operation validation
  • Architecture:

    • SOLID principles throughout
    • Dependency Injection with Microsoft.Extensions
    • Extensible handler system
    • Configuration priority: User Secrets → Environment Variables → appsettings.json

Quick Start

Prerequisites

  • .NET 8.0 SDK or higher
  • MariaDB 10.3+ or MySQL 5.7+
  • Database connection credentials

Installation

Windows:

.\install.ps1

Linux/macOS:

chmod +x install.sh
./install.sh

The installer will:

  1. Verify .NET installation
  2. Build the project
  3. Configure database connection
  4. Test connectivity

Configure Claude

Claude Desktop:

Edit configuration file at:

  • Windows: %APPDATA%\Claude\claude_desktop_config.json
  • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
  • Linux: ~/.config/Claude/claude_desktop_config.json
{
  "mcpServers": {
    "mariadb": {
      "command": "dotnet",
      "args": [
        "run",
        "--project",
        "/absolute/path/to/MariaDbMcpServer/MariaDbMcpServer.csproj"
      ]
    }
  }
}

See for more examples.

Claude Code:

Place configuration in ~/.claude/mcp_settings.json or .claude/mcp_settings.json

Verify Installation

Restart Claude and ask:

What tables are in the database?

Usage Examples

Querying Data

"Show me all users in the database"

"Find orders with status 'pending' from the last 7 days"

"What's the total revenue grouped by month?"

Schema Inspection

"Describe the structure of the orders table"

"What are the foreign keys in the products table?"

"List all stored procedures"

Data Modification (if allowed)

"Add a new user named John with email john@example.com"

"Update order 123 status to 'shipped'"

"Delete test records from the users table where email contains 'test'"

See for more examples.

Configuration

The server supports multiple configuration methods with the following priority:

  1. Command-line arguments (highest)
  2. Environment variables
  3. User secrets
  4. appsettings.json (lowest)

Command-Line Arguments (Recommended for Testing)

# Basic usage with all parameters
dotnet run -- --server localhost --database mydb --user admin --password pass

# Short form
dotnet run -- -s localhost -d mydb -u admin -w pass

# With permissions
dotnet run -- -s localhost -d mydb -u admin -w pass --allow-insert --allow-update

# Test connection only
dotnet run -- -s localhost -d mydb -u admin -w pass --test-connection

# Show configuration without starting
dotnet run -- --dry-run

# Verbose logging
dotnet run -- --server localhost --database mydb --verbose

Available CLI options:

  • -s, --server - Database server
  • -p, --port - Database port
  • -d, --database - Database name
  • -u, --user - Database username
  • -w, --password - Database password
  • --allow-insert - Enable INSERT operations
  • --allow-update - Enable UPDATE operations
  • --allow-delete - Enable DELETE operations
  • --allow-schema-changes - Enable DDL operations
  • -c, --config - Custom config file path
  • --test-connection - Test and exit
  • --dry-run - Show config and exit
  • -v, --verbose - Verbose logging
  • --debug - Debug logging
  • --version - Show version
  • --help - Show help

User Secrets (Recommended for Development)

# Connection settings
dotnet user-secrets set "MariaDb:Server" "localhost"
dotnet user-secrets set "MariaDb:Port" "3306"
dotnet user-secrets set "MariaDb:Database" "your_database"
dotnet user-secrets set "MariaDb:UserId" "your_user"
dotnet user-secrets set "MariaDb:Password" "your_password"

# Permission flags
dotnet user-secrets set "MariaDb:AllowInsert" "true"
dotnet user-secrets set "MariaDb:AllowUpdate" "true"
dotnet user-secrets set "MariaDb:AllowDelete" "false"  # Use with caution!
dotnet user-secrets set "MariaDb:AllowSchemaChanges" "false"  # Production: keep false

Environment Variables (Recommended for Production)

export MariaDb__Server=localhost
export MariaDb__Database=mydb
export MariaDb__UserId=user
export MariaDb__Password=pass

Permission Levels

PermissionOperationsRisk LevelRecommendation
Read-onlySELECT queriesLowSafe for most use cases
AllowInsertINSERTMediumEnable if creating records
AllowUpdateUPDATEMediumEnable with care, requires WHERE
AllowDeleteDELETEHighEnable only when necessary
AllowSchemaChangesCREATE, ALTER, DROPCriticalDevelopment only

Production Deployment

Build Release Version

# Windows
.\build-release.ps1

# Linux/macOS
./build-release.sh

Creates self-contained executable in publish/ directory.

Run as Service

Linux (systemd):

sudo systemctl enable mariadb-mcp-server
sudo systemctl start mariadb-mcp-server

Windows (NSSM):

nssm install MariaDbMcpServer "C:\path\to\publish\MariaDbMcpServer.exe"
nssm start MariaDbMcpServer

Docker:

docker build -t mariadb-mcp-server .
docker run -e MariaDb__Server=host.docker.internal mariadb-mcp-server

See for detailed instructions.

Project Structure

MariaDbMcpServer/
├── Interfaces/          # Abstraction layer (DIP)
├── Handlers/
│   ├── Tools/          # Individual tool handlers (SRP)
│   └── Resources/      # Resource handlers (SRP)
├── Factories/          # Handler factories (OCP)
├── Mcp/                # MCP protocol implementation
├── Services/           # Business logic (MariaDbService)
├── Security/           # Permission validation
├── Models/             # Request/Response DTOs
└── appsettings.json    # Default configuration

Built with SOLID principles:

  • Single Responsibility: Each handler has one purpose
  • Open/Closed: Extensible via new handlers
  • Liskov Substitution: Interchangeable implementations
  • Interface Segregation: Focused interfaces
  • Dependency Inversion: Abstractions over concretions

Extending the Server

Add a New Tool

  1. Create handler implementing IMcpToolHandler:
public class MyToolHandler : BaseToolHandler
{
    public override string ToolName => "my_tool";
    public override string Description => "Does something";
    public override object InputSchema => new { /* schema */ };

    public override async Task<object?> ExecuteAsync(JsonElement arguments)
    {
        // Implementation
    }
}
  1. Register in Program.cs:
builder.Services.AddSingleton<IMcpToolHandler, MyToolHandler>();

No changes to MCP server needed!

Add a New Resource Handler

  1. Create handler implementing IMcpResourceHandler:
public class MyResourceHandler : IMcpResourceHandler
{
    public bool CanHandle(string resourcePath) => resourcePath.StartsWith("mydata/");
    public async Task<object?> GetResourceAsync(string resourcePath) { /* ... */ }
    public IEnumerable<ResourceInfo> GetAvailableResources() { /* ... */ }
}
  1. Register in Program.cs:
builder.Services.AddSingleton<IMcpResourceHandler, MyResourceHandler>();

Documentation

  • - Complete deployment guide
  • - Common issues and solutions
  • - Development guidelines and architecture
  • - Usage examples and test requests
  • - Configuration examples

Development

Build and Run

dotnet restore
dotnet build
dotnet run --project MariaDbMcpServer/MariaDbMcpServer.csproj

Run Tests

# Run all tests
dotnet test

# Run tests with detailed output
dotnet test --logger "console;verbosity=detailed"

# Run specific test class
dotnet test --filter "FullyQualifiedName~MariaDbConfigurationTests"

# Run tests with coverage (requires coverlet.collector)
dotnet test --collect:"XPlat Code Coverage"

Test Coverage:

  • MariaDbConfigurationTests - Configuration validation and connection string generation (10 tests)
  • PermissionValidatorTests - Permission validation logic (14 tests)
  • CommandLineParserTests - CLI argument parsing (23 tests)
  • QueryToolHandlerTests - Query tool handler logic (4 tests)
  • InsertToolHandlerTests - Insert tool handler logic (4 tests)

Code Structure

The project follows SOLID principles with clear separation of concerns. See for architectural details.

Security Best Practices

  1. Use Read-Only Access by Default

    • Only enable write permissions when necessary
    • Create dedicated database users with minimal privileges
  2. Never Commit Secrets

    • Use user secrets for development
    • Use environment variables for production
    • Never store passwords in configuration files
  3. Limit Schema Changes

    • Keep AllowSchemaChanges=false in production
    • Use database migrations for schema management
  4. Monitor Operations

    • Enable logging
    • Review database query logs
    • Set up alerts for suspicious activity
  5. Use SSL/TLS

    • Enable encrypted connections to database
    • Verify server certificates

Troubleshooting

Server Not Starting

# Check .NET version
dotnet --version

# Check configuration
dotnet user-secrets list --project MariaDbMcpServer

# Test database connection
mysql -h localhost -u your_user -p your_database

Not Appearing in Claude

  1. Verify configuration file location
  2. Check paths are absolute
  3. Validate JSON syntax
  4. Restart Claude completely

See for detailed solutions.

Requirements

  • .NET 8.0 SDK or higher
  • MariaDB 10.3+ or MySQL 5.7+
  • Windows, Linux, or macOS

NuGet Packages

  • Microsoft.Extensions.* (Configuration, DI, Hosting, Logging)
  • MySqlConnector 2.3.7

License

[Specify your license here]

Contributing

[Add contribution guidelines if open source]

Support

  • Issues:
  • Documentation: See docs/ directory
  • Examples: See examples/ directory

Future Roadmap

Official MCP SDK Migration

We are tracking the official ModelContextProtocol NuGet package and will evaluate migration once:

  • The package reaches a stable 1.0 release (currently 0.4.0-preview.3)
  • The MCP protocol stabilizes (next protocol release: November 25, 2025)
  • Migration benefits outweigh the costs of refactoring

Current advantages of custom implementation:

  • Full control over architecture and implementation
  • No dependencies on preview/unstable packages
  • SOLID principles maintained throughout
  • 100% test coverage (65/65 tests passing)
  • Production-ready and battle-tested

Changelog

Version 1.0.0

  • Initial release
  • 10 MCP tools for database operations
  • 9 MCP resources for metadata
  • SOLID architecture with custom MCP implementation
  • Comprehensive security features with Result pattern
  • Full documentation and examples
  • 65 unit tests (100% passing)

Acknowledgments


Quick Links: