MCP-DbServer

DashrathYadav/MCP-DbServer

3.1

If you are the rightful owner of MCP-DbServer and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to henry@mcphub.com.

MsDbServer is a Model Context Protocol (MCP) server designed to facilitate interaction between AI assistants and MySQL databases, enabling natural language queries and database introspection.

Tools
6
Resources
0
Prompts
0

MsDbServer - MySQL Database MCP Server

A powerful Model Context Protocol (MCP) server that provides MySQL database introspection capabilities for AI assistants like GitHub Copilot. Built with .NET 8 and the official Microsoft MCP SDK.

šŸŽÆ What is this?

MsDbServer is an MCP (Model Context Protocol) server that acts as a bridge between AI assistants and MySQL databases. It allows you to ask natural language questions about your database structure and get instant, detailed responses.

Example Usage with GitHub Copilot:

  • šŸ—£ļø "List all tables in my database"
  • šŸ—£ļø "Show me the structure of the users table"
  • šŸ—£ļø "What are the foreign key relationships?"
  • šŸ—£ļø "Execute this query: SELECT COUNT(*) FROM orders"

✨ Features

šŸ› ļø 6 Powerful Database Tools

ToolDescriptionExample
ListTablesGet all tables in database"Show me all tables"
DescribeTableDetailed table schema with columns, keys, indexes"Describe the users table"
ExecuteQueryRun SELECT queries safely (with limits)"Query the first 10 users"
GetDatabaseStatsDatabase size, table counts, statistics"Get database statistics"
GetSchemaInfoMultiple table schemas with pattern matching"Show tables starting with 'user'"
GetTableRelationshipsForeign key dependencies and relationships"Show table relationships"

šŸ”’ Safety Features

  • āœ… Query Restrictions - Only SELECT and WITH statements allowed
  • āœ… Row Limits - Maximum 1000 rows per query
  • āœ… Timeout Protection - 30-second query timeout
  • āœ… Input Validation - All inputs sanitized and validated

šŸ—ļø Technical Features

  • āœ… Built with Microsoft MCP SDK - Official ModelContextProtocol package
  • āœ… MySQL Support - Full MySQL database introspection
  • āœ… Async Operations - Non-blocking database operations
  • āœ… Rich Formatting - Beautiful, readable output
  • āœ… Error Handling - Comprehensive error messages
  • āœ… VS Code Integration - Works seamlessly with GitHub Copilot

šŸš€ Quick Start

Prerequisites

1. Clone and Setup

git clone https://github.com/your-username/MsDbServer.git
cd MsDbServer

2. Configure Database Connection

Edit MsDbServer/appsettings.json:

{
  "ConnectionStrings": {
    "DefaultConnection": "server=localhost;port=3306;database=your_database;user=your_user;password=your_password"
  }
}

3. Test the Server

cd MsDbServer
dotnet build
dotnet run

4. Setup VS Code Integration

Create .vscode/mcp.json in your project:

{
  "servers": {
    "MsDbServer": {
      "command": "dotnet",
      "args": ["run", "--project", "path/to/MsDbServer/MsDbServer.csproj"],
      "cwd": "${workspaceFolder}",
      "env": {
        "ConnectionStrings__DefaultConnection": "server=localhost;port=3306;database=your_database;user=your_user;password=your_password"
      }
    }
  }
}

šŸ“‹ Detailed Setup Instructions

Step 1: Install Prerequisites

  1. Install .NET 8 SDK

    # Windows (using winget)
    winget install Microsoft.DotNet.SDK.8
    
    # macOS (using brew)
    brew install dotnet
    
    # Or download from: https://dotnet.microsoft.com/download/dotnet/8.0
    
  2. Install Visual Studio Code

  3. Ensure MySQL Access

    • Have a MySQL database running
    • Know the connection details (host, port, database, username, password)

Step 2: Project Setup

  1. Clone the Repository

    git clone https://github.com/your-username/MsDbServer.git
    cd MsDbServer
    
  2. Configure Database Connection

    Option A: Edit appsettings.json

    {
      "ConnectionStrings": {
        "DefaultConnection": "server=your_host;port=3306;database=your_db;user=your_user;password=your_password"
      }
    }
    

    Option B: Use Environment Variables

    # Windows
    set ConnectionStrings__DefaultConnection=server=localhost;port=3306;database=your_db;user=your_user;password=your_password
    
    # Linux/macOS
    export ConnectionStrings__DefaultConnection="server=localhost;port=3306;database=your_db;user=your_user;password=your_password"
    
  3. Test the Connection

    cd MsDbServer
    dotnet build
    dotnet run
    

    You should see:

    info: Database connection test successful. Starting MCP server...
    

Step 3: VS Code Integration

  1. Create MCP Configuration

    Create .vscode/mcp.json in your workspace:

    {
      "servers": {
        "MsDbServer": {
          "command": "dotnet",
          "args": ["run", "--project", "MsDbServer/MsDbServer.csproj"],
          "cwd": "${workspaceFolder}",
          "env": {
            "ConnectionStrings__DefaultConnection": "server=localhost;port=3306;database=your_database;user=your_user;password=your_password"
          }
        }
      }
    }
    
  2. Open Workspace in VS Code

    code .
    
  3. Test with GitHub Copilot

    • Open GitHub Copilot Chat (Ctrl+Shift+I)
    • Try: "List all tables in the database"
    • Try: "Describe the users table"

šŸ’» Usage Examples

In GitHub Copilot Chat:

šŸ—£ļø List all tables in the database
šŸ“‹ Response: Shows all table names

šŸ—£ļø Describe the users table structure
šŸ“‹ Response: Detailed schema with columns, types, constraints

šŸ—£ļø Show me the first 5 records from the orders table
šŸ“‹ Response: Formatted table output

šŸ—£ļø What are the foreign key relationships in my database?
šŸ“‹ Response: Visual relationship mapping

šŸ—£ļø Get database statistics and table sizes
šŸ“‹ Response: Database overview with sizes and counts

Manual Testing (JSON-RPC):

# List all tables
echo '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"ListTables","arguments":{}}}' | dotnet run

# Describe a table
echo '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"DescribeTable","arguments":{"tableName":"users"}}}' | dotnet run

šŸ“ Project Structure

MsDbServer/
ā”œā”€ā”€ .vscode/
│   └── mcp.json              # VS Code MCP configuration
ā”œā”€ā”€ MsDbServer/
│   ā”œā”€ā”€ Program.cs            # Application entry point
│   ā”œā”€ā”€ DatabaseTools.cs     # 6 MCP tools implementation
│   ā”œā”€ā”€ IDatabaseService.cs  # Service interface & data models
│   ā”œā”€ā”€ MySqlDatabaseService.cs # MySQL implementation
│   ā”œā”€ā”€ appsettings.json     # Configuration
│   └── MsDbServer.csproj    # Project file
└── README.md                # This file

šŸ› ļø Development

Building

cd MsDbServer
dotnet build

Running

cd MsDbServer
dotnet run

Testing Tools

# Test ListTables
echo '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"ListTables","arguments":{}}}' | dotnet run

# Test DescribeTable
echo '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"DescribeTable","arguments":{"tableName":"your_table"}}}' | dotnet run

šŸ”§ Troubleshooting

Common Issues

  1. "Database connection test failed"

    • Check your connection string in appsettings.json
    • Verify MySQL server is running
    • Confirm database exists and credentials are correct
  2. "GitHub Copilot doesn't see the MCP server"

    • Ensure .vscode/mcp.json exists in your workspace
    • Restart VS Code after creating/editing MCP configuration
    • Check that GitHub Copilot and Copilot Chat extensions are installed and active
  3. "Build failed"

    • Ensure .NET 8 SDK is installed: dotnet --version
    • Try: dotnet restore then dotnet build
  4. "Permission denied" errors

    • Check file permissions
    • On Linux/macOS, you might need: chmod +x on script files

Debug Mode

# Run with detailed logging
dotnet run --configuration Debug

šŸ¤ Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature-name
  3. Make your changes
  4. Test thoroughly
  5. Submit a pull request

šŸ“„ License

This project is licensed under the MIT License - see the file for details.

šŸ™ Acknowledgments


šŸš€ Ready to explore your database with AI? Clone, configure, and start asking questions!

  • Dependency Injection - Proper service registration and lifetime management
  • Async/Await - All database operations are asynchronous
  • Comprehensive Error Handling - Proper error responses with meaningful messages
  • Structured Logging - Configurable logging with Microsoft.Extensions.Logging

šŸ—„ļø Database Support

  • MySQL - Full support for MySQL database introspection
  • Connection String Configuration - Configurable via appsettings.json
  • Safe Data Type Handling - Handles MySQL-specific data types and large values

Quick Start

Prerequisites

  • .NET 8.0 SDK or later
  • MySQL database (configured and accessible)
  • Visual Studio Code with GitHub Copilot (for testing)

Installation

  1. Clone or download the project
  2. Configure your database connection in appsettings.json
  3. Build and run the server
dotnet build
dotnet run

Configuration

Update appsettings.json with your MySQL connection string:

{
  "ConnectionStrings": {
    "DefaultConnection": "server=localhost;port=3306;database=your_database;user=your_user;password=your_password"
  }
}

VS Code Integration

Create or update .vscode/mcp.json in your workspace:

{
  "inputs": [],
  "servers": {
    "MsDbServer": {
      "type": "stdio",
      "command": "dotnet",
      "args": ["run", "--project", "path/to/MsDbServer.csproj"]
    }
  }
}

Usage Examples

Using with GitHub Copilot

Once configured, you can use the tools in GitHub Copilot:

  • "List all tables in the database"
  • "Describe the structure of the users table"
  • "Show me the schema for the orders table"
  • "Get database statistics and table sizes"
  • "Execute a query to show the first 10 users"
  • "Show me all tables that start with 'user'"
  • "What are the foreign key relationships for the orders table?"

Direct JSON-RPC Testing

# List all tables
echo '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"ListTables","arguments":{}}}' | dotnet run

# Describe a specific table
echo '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"DescribeTable","arguments":{"tableName":"users"}}}' | dotnet run

# Execute a query
echo '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"ExecuteQuery","arguments":{"query":"SELECT * FROM users LIMIT 5","maxRows":5}}}' | dotnet run

# Get database statistics
echo '{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"GetDatabaseStats","arguments":{}}}' | dotnet run

# Get schema for tables starting with 'user'
echo '{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"GetSchemaInfo","arguments":{"tablePattern":"user%"}}}' | dotnet run

# Get relationships for a specific table
echo '{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"GetTableRelationships","arguments":{"tableName":"orders"}}}' | dotnet run

PowerShell Testing

Use the included test script:

.\test-mcp.ps1

Sample Output

ListTables Response

Database Tables:
================
  addresses
  orders
  products
  users

DescribeTable Response

Table: default.users

Columns:
--------
  UserId bigint(19,0) NOT NULL IDENTITY PRIMARY KEY
  Username varchar(50) NOT NULL
  Email varchar(100) NULL
  CreatedDate datetime NOT NULL
    Default: CURRENT_TIMESTAMP

Primary Keys:
-------------
  UserId

Foreign Keys:
-------------
  (none)

Indexes:
--------
  IX_Users_Email: Email
  IX_Users_Username: Username

ExecuteQuery Response

Query: SELECT UserId, Username, Email FROM users LIMIT 3
Execution Time: 12.45ms
Rows: 3

-----------------------------------------------------------------------
UserId | Username     | Email
-----------------------------------------------------------------------
1      | john_doe     | john.doe@example.com
2      | jane_smith   | jane.smith@example.com
3      | bob_wilson   | bob.wilson@example.com
-----------------------------------------------------------------------

GetDatabaseStats Response

Database Statistics: rent_wizard
================================
Database Version: 8.0.35
Generated At: 2025-06-27 10:30:15 UTC

Overview:
---------
Total Tables: 6
Database Size: 2.4MB

Table Statistics:
-----------------
Table Name               Rows   Data Size Index Size  Columns Indexes
----------------------------------------------------------------------
users                    1,250     125.6KB    45.2KB        8       3
orders                     847      98.3KB    32.1KB       12       4
products                   156      23.4KB    12.8KB        9       2
addresses                  892      67.8KB    28.3KB        7       2
owners                      45       8.2KB     3.1KB        6       1
properties                 234      45.6KB    18.7KB       15       5

GetTableRelationships Response

Table Relationships (8 found)
=========================

Parent Table: users
Children:
  orders.UserId -> users.UserId
    Constraint: FK_orders_users
  addresses.UserId -> users.UserId
    Constraint: FK_addresses_users

Parent Table: products
Children:
  order_items.ProductId -> products.ProductId
    Constraint: FK_order_items_products

Dependency Summary:
------------------
orders depends on: users
addresses depends on: users
order_items depends on: products, orders

Project Structure

MsDbServer/
ā”œā”€ā”€ Program.cs                  # Application entry point and MCP server setup
ā”œā”€ā”€ IDatabaseService.cs         # Database service interface and models
ā”œā”€ā”€ MySqlDatabaseService.cs     # MySQL database implementation
ā”œā”€ā”€ DatabaseTools.cs           # MCP tools with [McpServerTool] attributes
ā”œā”€ā”€ appsettings.json           # Configuration file
└── MsDbServer.csproj          # Project file with dependencies

Dependencies

  • ModelContextProtocol (0.3.0-preview.1) - Microsoft MCP SDK
  • Microsoft.Extensions.Hosting (9.0.6) - Hosting infrastructure
  • MySql.Data (9.3.0) - MySQL connectivity

Migration from Manual Implementation

This project replaces a previous manual JSON-RPC implementation with the official Microsoft MCP SDK, providing:

  • Simplified Development - Attributes-based tool registration
  • Better Integration - Official SDK support and updates
  • Reduced Boilerplate - Automatic JSON-RPC handling
  • Future-Proof - Follows Microsoft's recommended patterns

License

This project is built for educational and development purposes.


Built with ā¤ļø using .NET 8 and the Microsoft MCP SDK