README
ΒΆ
DB MCP Server
A robust implementation of the Database Model Context Protocol (DB MCP)
Features β’ Installation β’ Usage β’ Documentation β’ Contributing β’ License
π Overview
The DB MCP Server is a high-performance, feature-rich implementation of the Database Model Context Protocol designed to enable seamless integration between database operations and client applications like VS Code and Cursor. It provides a standardized communication layer allowing clients to discover and invoke database operations through a consistent, well-defined interface, simplifying database access and management across different environments.
β¨ Key Features
- Flexible Transport: Server-Sent Events (SSE) transport layer with robust connection handling
- Standard Messaging: JSON-RPC based message format for interoperability
- Dynamic Tool Registry: Register, discover, and invoke database tools at runtime
- Editor Integration: First-class support for VS Code and Cursor extensions
- Session Management: Sophisticated session tracking and persistence
- Structured Error Handling: Comprehensive error reporting for better debugging
- Performance Optimized: Designed for high throughput and low latency
π Installation
Prerequisites
- Go 1.18 or later
- MySQL or PostgreSQL (optional, for persistent sessions)
- Docker (optional, for containerized deployment)
Quick Start
# Clone the repository
git clone https://github.com/FreePeak/db-mcp-server.git
cd db-mcp-server
# Copy and configure environment variables
cp .env.example .env
# Edit .env with your configuration
# Option 1: Build and run locally
make build
./mcp-server
# Option 2: Using Docker
docker build -t db-mcp-server .
docker run -p 9090:9090 db-mcp-server
# Option 3: Using Docker Compose (with MySQL)
docker-compose up -d
Docker
# Build the Docker image
docker build -t db-mcp-server .
# Run the container
docker run -p 9090:9090 db-mcp-server
# Run with custom configuration
docker run -p 8080:8080 \
-e SERVER_PORT=8080 \
-e LOG_LEVEL=debug \
-e DB_TYPE=mysql \
-e DB_HOST=my-database-server \
db-mcp-server
# Run with Docker Compose (includes MySQL database)
docker-compose up -d
π§ Configuration
DB MCP Server can be configured via environment variables or a .env file:
| Variable | Description | Default |
|---|---|---|
SERVER_PORT |
Server port | 9092 |
TRANSPORT_MODE |
Transport mode (stdio, sse) | stdio |
LOG_LEVEL |
Logging level (debug, info, warn, error) | debug |
DB_TYPE |
Database type (mysql, postgres) | mysql |
DB_HOST |
Database host | localhost |
DB_PORT |
Database port | 3306 |
DB_USER |
Database username | iamrevisto |
DB_PASSWORD |
Database password | password |
DB_NAME |
Database name | revisto |
DB_ROOT_PASSWORD |
Database root password (for container setup) | root_password |
See .env.example for more configuration options.
π Usage
Integrating with Cursor Edit
DB MCP Server can be easily integrated with Cursor Edit by configuring the appropriate settings in your Cursor .configuration file .cursor/mcp.json:
{
"mcpServers": {
"db-mcp-server": {
"url": "http://localhost:9090/sse"
}
}
}
To use this integration in Cursor:
- Configure and start the DB MCP Server using one of the installation methods above
- Add the configuration to your Cursor settings
- Open Cursor and navigate to a SQL file
- Use the database panel to connect to your database through the MCP server
- Execute queries using Cursor's built-in database tools
The MCP Server will handle the database operations, providing enhanced capabilities beyond standard database connections:
- Better error reporting and validation
- Transaction management
- Parameter binding
- Security enhancements
- Performance monitoring
Custom Tool Registration (Server-side)
// Go example
package main
import (
"context"
"db-mcpserver/internal/mcp"
)
func main() {
// Create a custom database tool
queryTool := &mcp.Tool{
Name: "dbQuery",
Description: "Executes read-only SQL queries with parameterized inputs",
InputSchema: mcp.ToolInputSchema{
Type: "object",
Properties: map[string]interface{}{
"query": {
"type": "string",
"description": "SQL query to execute",
},
"params": {
"type": "array",
"description": "Query parameters",
"items": map[string]interface{}{
"type": "any",
},
},
"timeout": {
"type": "integer",
"description": "Query timeout in milliseconds (optional)",
},
},
Required: []string{"query"},
},
Handler: func(ctx context.Context, params map[string]interface{}) (interface{}, error) {
// Implementation...
return result, nil
},
}
// Register the tool
toolRegistry.RegisterTool(queryTool)
}
π Documentation
DB MCP Protocol
The server implements the DB MCP protocol with the following key methods:
- initialize: Sets up the session and returns server capabilities
- tools/list: Discovers available database tools
- tools/call: Executes a database tool
- editor/context: Updates the server with editor context
- cancel: Cancels an in-progress operation
For full protocol documentation, visit the MCP Specification and our database-specific extensions.
Tool System
The DB MCP Server includes a powerful tool system that allows clients to discover and invoke database tools. Each tool has:
- A unique name
- A description
- A JSON Schema for input validation
- A handler function that executes the tool's logic
Built-in Tools
The server currently includes four core database tools:
| Tool | Description |
|---|---|
dbQuery |
Executes read-only SQL queries with parameterized inputs |
dbExecute |
Performs data modification operations (INSERT, UPDATE, DELETE) |
dbTransaction |
Manages SQL transactions with commit and rollback support |
dbSchema |
Auto-discovers database structure and relationships with support for tables, columns, and relationships |
dbQueryBuilder |
Visual SQL query construction with syntax validation |
dbPerformanceAnalyzer |
Identifies slow queries and provides optimization suggestions |
Database Schema Explorer Tool
The MCP Server includes a powerful Database Schema Explorer tool (dbSchema) that auto-discovers your database structure and relationships:
// Get all tables in the database
{
"name": "dbSchema",
"arguments": {
"component": "tables"
}
}
// Get columns for a specific table
{
"name": "dbSchema",
"arguments": {
"component": "columns",
"table": "users"
}
}
// Get relationships for a specific table or all relationships
{
"name": "dbSchema",
"arguments": {
"component": "relationships",
"table": "orders"
}
}
// Get the full database schema
{
"name": "dbSchema",
"arguments": {
"component": "full"
}
}
The Schema Explorer supports both MySQL and PostgreSQL databases and automatically adapts to your configured database type.
Visual Query Builder Tool
The MCP Server includes a powerful Visual Query Builder tool (dbQueryBuilder) that helps you construct SQL queries with syntax validation:
// Validate a SQL query for syntax errors
{
"name": "dbQueryBuilder",
"arguments": {
"action": "validate",
"query": "SELECT * FROM users WHERE status = 'active'"
}
}
// Build a SQL query from components
{
"name": "dbQueryBuilder",
"arguments": {
"action": "build",
"components": {
"select": ["id", "name", "email"],
"from": "users",
"where": [
{
"column": "status",
"operator": "=",
"value": "active"
}
],
"orderBy": [
{
"column": "name",
"direction": "ASC"
}
],
"limit": 10
}
}
}
// Analyze a SQL query for potential issues and performance
{
"name": "dbQueryBuilder",
"arguments": {
"action": "analyze",
"query": "SELECT u.*, o.* FROM users u JOIN orders o ON u.id = o.user_id WHERE u.status = 'active' AND o.created_at > '2023-01-01'"
}
}
Example response from a query build operation:
{
"query": "SELECT id, name, email FROM users WHERE status = 'active' ORDER BY name ASC LIMIT 10",
"components": {
"select": ["id", "name", "email"],
"from": "users",
"where": [{
"column": "status",
"operator": "=",
"value": "active"
}],
"orderBy": [{
"column": "name",
"direction": "ASC"
}],
"limit": 10
},
"validation": {
"valid": true,
"query": "SELECT id, name, email FROM users WHERE status = 'active' ORDER BY name ASC LIMIT 10"
}
}
The Query Builder supports:
- SELECT statements with multiple columns
- JOIN operations (inner, left, right, full)
- WHERE conditions with various operators
- GROUP BY and HAVING clauses
- ORDER BY with sorting direction
- LIMIT and OFFSET for pagination
- Syntax validation and error suggestions
- Query complexity analysis
Performance Analyzer Tool
The MCP Server includes a powerful Performance Analyzer tool (dbPerformanceAnalyzer) that identifies slow queries and provides optimization suggestions:
// Get slow queries that exceed the configured threshold
{
"name": "dbPerformanceAnalyzer",
"arguments": {
"action": "getSlowQueries",
"limit": 5
}
}
// Get metrics for all tracked queries sorted by average duration
{
"name": "dbPerformanceAnalyzer",
"arguments": {
"action": "getMetrics",
"limit": 10
}
}
// Analyze a specific query for optimization opportunities
{
"name": "dbPerformanceAnalyzer",
"arguments": {
"action": "analyzeQuery",
"query": "SELECT * FROM orders JOIN users ON orders.user_id = users.id WHERE orders.status = 'pending'"
}
}
// Reset all collected performance metrics
{
"name": "dbPerformanceAnalyzer",
"arguments": {
"action": "reset"
}
}
// Set the threshold for identifying slow queries (in milliseconds)
{
"name": "dbPerformanceAnalyzer",
"arguments": {
"action": "setThreshold",
"threshold": 300
}
}
Example response from a performance analysis:
{
"query": "SELECT * FROM orders JOIN users ON orders.user_id = users.id WHERE orders.status = 'pending'",
"suggestions": [
"Avoid using SELECT * - specify only the columns you need",
"Verify that ORDER BY columns are properly indexed",
"Consider adding appropriate indexes for frequently queried columns"
]
}
Example response from getting slow queries:
{
"metrics": [
{
"query": "SELECT * FROM large_table WHERE status = ?",
"count": 15,
"totalDuration": "2.5s",
"minDuration": "120ms",
"maxDuration": "750ms",
"avgDuration": "166ms",
"lastExecuted": "2025-06-15T14:23:45Z"
},
{
"query": "SELECT order_id, SUM(amount) FROM order_items GROUP BY order_id",
"count": 8,
"totalDuration": "1.2s",
"minDuration": "110ms",
"maxDuration": "580ms",
"avgDuration": "150ms",
"lastExecuted": "2025-06-15T14:20:12Z"
}
],
"count": 2,
"threshold": "100ms"
}
The Performance Analyzer automatically tracks all query executions and provides:
- Identification of slow-performing queries
- Query execution metrics (count, min, max, average durations)
- Pattern-based query analysis
- Optimization suggestions
- Performance trend monitoring
- Configurable slow query thresholds
Editor Integration
The server includes support for editor-specific features through the editor/context method, enabling tools to be aware of:
- Current SQL file
- Selected query
- Cursor position
- Open database connections
- Database structure
πΊοΈ Roadmap
We're committed to expanding DB MCP Server's capabilities. Here's our planned development roadmap:
Q2 2025
- β Schema Explorer - Auto-discover database structure and relationships
- β Query Builder - Visual SQL query construction with syntax validation
- β Performance Analyzer - Identify slow queries and optimization opportunities
Q3 2025
- Data Visualization - Create charts and graphs from query results
- Model Generator - Auto-generate code models from database tables
- Multi-DB Support - Expanded support for NoSQL databases
Q4 2025
- Migration Manager - Version-controlled database schema changes
- Access Control - Fine-grained permissions for database operations
- Query History - Track and recall previous queries with execution metrics
Future Vision
- AI-Assisted Query Optimization - Smart recommendations for better performance
- Cross-Database Operations - Unified interface for heterogeneous database environments
- Real-Time Collaboration - Multi-user support for collaborative database work
- Extended Plugin System - Community-driven extension marketplace
π€ Contributing
Contributions are welcome! Here's how you can help:
- Fork the repository
- Create a feature branch:
git checkout -b new-feature - Commit your changes:
git commit -am 'Add new feature' - Push to the branch:
git push origin new-feature - Submit a pull request
Please make sure your code follows our coding standards and includes appropriate tests.
π License
This project is licensed under the MIT License - see the LICENSE file for details.
π§ Support & Contact
- For questions or issues, email mnhatlinh.doan@gmail.com
- Open an issue directly: Issue Tracker
- If DB MCP Server helps your work, please consider supporting: