Skip to main content

A comprehensive Model Context Protocol (MCP) server for interacting with SQL Server databases

Project description

SQL Server MCP Server

Python 3.8+ License: LGPL v3 MCP Protocol

A comprehensive Model Context Protocol (MCP) server for interacting with SQL Server databases. This server provides AI assistants with secure, efficient access to SQL Server databases through standardized MCP tools and resources.

โœจ Features

  • ๐Ÿ”— Database Connection Management: Secure connection pooling with Windows and SQL Server authentication
  • ๐Ÿ“Š Query Execution: Execute SQL queries with parameterized queries and multiple output formats
  • ๐Ÿ” Schema Inspection: Retrieve detailed database schema information including tables, columns, indexes, and relationships
  • ๐Ÿ“‹ Data Retrieval: Get table data with pagination, filtering, and sorting capabilities
  • ๐Ÿ–ฅ๏ธ CLI Interface: Full command-line interface for all MCP capabilities
  • ๐Ÿ›ก๏ธ Security: SQL injection prevention, secure authentication, and credential management
  • โšก Performance: Connection pooling, query optimization, and performance monitoring
  • ๐Ÿ“š Full MCP Protocol Compliance: Complete implementation of MCP protocol standards

๐Ÿš€ Installation

Prerequisites

  • Python 3.8 or higher
  • SQL Server instance (local or remote)
  • ODBC Driver 17 for SQL Server

Install from Source

git clone https://github.com/your-org/sqlserver-mcp-server.git
cd sqlserver-mcp-server
pip install -e .

Install Dependencies

pip install -r requirements.txt

๐Ÿƒโ€โ™‚๏ธ Quick Start

Start MCP Server

# Start the MCP server
python -m src.mcp_tools

# Or use the CLI entry point
sqlserver-mcp server

Use CLI Interface

# Connect to database
sqlserver-mcp connect --server "localhost" --database "master" --trusted-connection

# Execute query
sqlserver-mcp query --connection-id <connection-id> "SELECT * FROM sys.tables"

# List databases
sqlserver-mcp list-databases --connection-id <connection-id>

# Get table schema
sqlserver-mcp get-schema --connection-id <connection-id> --table "users"

๐Ÿ› ๏ธ MCP Tools

The server provides the following MCP tools:

Tool Description Parameters
create_connection Establish database connections server, database, authentication
execute_query Execute SQL queries query, database, timeout, parameters
get_schema Retrieve schema information database, table_name, include_relationships
get_table_data Get table data with pagination table_name, limit, offset, where_clause
list_databases List available databases include_system, include_metadata

๐Ÿ“– MCP Resources

The server provides the following MCP resources:

Resource Description URI
connection_status Real-time connection health and metrics mcp://sqlserver/connection_status
query_history Query execution history and statistics mcp://sqlserver/query_history

โš™๏ธ Configuration

Environment Variables

export SQLSERVER_MCP_LOG_LEVEL=INFO
export SQLSERVER_MCP_SERVER_HOST=127.0.0.1
export SQLSERVER_MCP_SERVER_PORT=8000

Configuration File

Create a config.json file in your project directory:

{
  "default_server": "localhost",
  "default_database": "master",
  "connection_timeout": 30,
  "pool_size": 10,
  "log_level": "INFO",
  "output_format": "table"
}

๐Ÿ“š Usage Examples

MCP Client Integration

import asyncio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

async def main():
    # Connect to SQL Server MCP Server
    server_params = StdioServerParameters(
        command="python",
        args=["-m", "src.mcp_tools"]
    )
    
    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            # Initialize the session
            await session.initialize()
            
            # Create a database connection
            result = await session.call_tool(
                "create_connection",
                {
                    "server": "localhost",
                    "database": "master",
                    "trusted_connection": True
                }
            )
            
            connection_id = result.content[0].text
            
            # Execute a query
            query_result = await session.call_tool(
                "execute_query",
                {
                    "query": "SELECT name FROM sys.databases",
                    "connection_id": connection_id
                }
            )
            
            print(query_result.content[0].text)

if __name__ == "__main__":
    asyncio.run(main())

CLI Examples

# Connect to SQL Server
sqlserver-mcp connect --server "localhost" --database "AdventureWorks" --trusted-connection

# List all databases
sqlserver-mcp list-databases --connection-id conn_123

# Get table schema
sqlserver-mcp get-schema --connection-id conn_123 --table "Person.Person" --include-relationships

# Execute parameterized query
sqlserver-mcp query --connection-id conn_123 "SELECT * FROM Person.Person WHERE BusinessEntityID = @id" --params '{"id": 1}'

# Get table data with pagination
sqlserver-mcp select --connection-id conn_123 --table "Person.Person" --limit 10 --offset 0

# Export query results to CSV
sqlserver-mcp query --connection-id conn_123 "SELECT * FROM Person.Person" --output-format csv > results.csv

๐Ÿงช Testing

The project includes comprehensive test coverage:

  • Contract Tests: Validate MCP protocol compliance
  • Integration Tests: Test with real SQL Server instances
  • Unit Tests: Test individual components
  • Performance Tests: Benchmark query execution and connection management

Running Tests

# Run all tests
pytest

# Run specific test categories
pytest tests/contract/     # Contract tests
pytest tests/integration/  # Integration tests  
pytest tests/unit/        # Unit tests
pytest tests/performance/ # Performance tests

# Run with coverage
pytest --cov=src --cov-report=html

๐Ÿ—๏ธ Architecture

The SQL Server MCP Server follows a modular architecture:

src/
โ”œโ”€โ”€ mcp_tools/          # MCP protocol implementation
โ”‚   โ”œโ”€โ”€ execute_query_tool.py
โ”‚   โ”œโ”€โ”€ get_schema_tool.py
โ”‚   โ”œโ”€โ”€ list_databases_tool.py
โ”‚   โ”œโ”€โ”€ get_table_data_tool.py
โ”‚   โ”œโ”€โ”€ create_connection_tool.py
โ”‚   โ””โ”€โ”€ mcp_server.py
โ”œโ”€โ”€ services/           # Business logic services
โ”‚   โ”œโ”€โ”€ connection_manager.py
โ”‚   โ”œโ”€โ”€ query_executor.py
โ”‚   โ”œโ”€โ”€ schema_service.py
โ”‚   โ””โ”€โ”€ data_service.py
โ”œโ”€โ”€ models/             # Data models
โ”‚   โ”œโ”€โ”€ connection.py
โ”‚   โ”œโ”€โ”€ query.py
โ”‚   โ”œโ”€โ”€ schema.py
โ”‚   โ””โ”€โ”€ data.py
โ”œโ”€โ”€ cli/                # Command-line interface
โ”‚   โ”œโ”€โ”€ connection_commands.py
โ”‚   โ”œโ”€โ”€ query_commands.py
โ”‚   โ”œโ”€โ”€ schema_commands.py
โ”‚   โ”œโ”€โ”€ data_commands.py
โ”‚   โ””โ”€โ”€ config_commands.py
โ””โ”€โ”€ lib/                # Shared utilities
    โ”œโ”€โ”€ config.py
    โ”œโ”€โ”€ logging.py
    โ”œโ”€โ”€ exceptions.py
    โ””โ”€โ”€ performance.py

๐Ÿ”ง Development

Setup Development Environment

# Clone the repository
git clone https://github.com/your-org/sqlserver-mcp-server.git
cd sqlserver-mcp-server

# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install development dependencies
pip install -e ".[dev]"

Code Quality

# Format code
black src/ tests/
isort src/ tests/

# Lint code
flake8 src/ tests/
mypy src/

# Run all quality checks
make lint

Testing

# Run all tests
pytest

# Run with coverage
pytest --cov=src --cov-report=html

# Run specific test categories
pytest tests/contract/     # Contract tests
pytest tests/integration/  # Integration tests
pytest tests/unit/        # Unit tests
pytest tests/performance/ # Performance tests

Building

# Build package
python -m build

# Install from built package
pip install dist/sqlserver_mcp_server-*.whl

๐Ÿ“‹ Roadmap

  • Support for additional database engines (PostgreSQL, MySQL)
  • Advanced query optimization and caching
  • Real-time database monitoring and alerts
  • Enhanced security features (encryption, audit logging)
  • Web-based administration interface
  • Docker containerization and Kubernetes support

๐Ÿค Contributing

We welcome contributions! Please see our Contributing Guide for details.

Development Workflow

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes
  4. Add tests for your changes
  5. Run the test suite (pytest)
  6. Commit your changes (git commit -m 'Add amazing feature')
  7. Push to the branch (git push origin feature/amazing-feature)
  8. Open a Pull Request

๐Ÿ“„ License

This project is licensed under the GNU Lesser General Public License v3.0 - see the LICENSE file for details.

๐Ÿ†˜ Support

๐Ÿ™ Acknowledgments

๐Ÿ“Š Project Status

GitHub last commit GitHub issues GitHub pull requests GitHub stars

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

sqlserver_mcp_server-1.0.0.tar.gz (102.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

sqlserver_mcp_server-1.0.0-py3-none-any.whl (65.7 kB view details)

Uploaded Python 3

File details

Details for the file sqlserver_mcp_server-1.0.0.tar.gz.

File metadata

  • Download URL: sqlserver_mcp_server-1.0.0.tar.gz
  • Upload date:
  • Size: 102.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.5

File hashes

Hashes for sqlserver_mcp_server-1.0.0.tar.gz
Algorithm Hash digest
SHA256 9001fb25a8c2dbd2bc0b228faa96575d056b75e6428903ac3036467c06be04b1
MD5 8547780a581ff543cd790ce5888cf3d0
BLAKE2b-256 3947a9097080516d6c483f7a6413e772c2bf2a2d38bbc11d26b0a23fc3436e1b

See more details on using hashes here.

File details

Details for the file sqlserver_mcp_server-1.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for sqlserver_mcp_server-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 dd969f878c0ca3abeeae96e3cfeb0dbcc9c1e1c1dde17a7cf7c85749870932ac
MD5 4f25878948c1ef2fc7b6bffbf18d54a5
BLAKE2b-256 29e0b968c1a174049bfcc5aef8a793b88b4755f62d6a62c632d4bb38921d0156

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page