A comprehensive Model Context Protocol (MCP) server for interacting with SQL Server databases
Project description
SQL Server MCP Server
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
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Make your changes
- Add tests for your changes
- Run the test suite (
pytest) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - 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
- ๐ Documentation: Check the docs/ directory for detailed documentation
- ๐ Bug Reports: Create a GitHub issue
- ๐ก Feature Requests: Create a GitHub issue
- ๐ฌ Discussions: Join our GitHub Discussions
- ๐ง Email: Contact us at support@your-org.com
๐ Acknowledgments
- Model Context Protocol for the MCP specification
- pyodbc for SQL Server connectivity
- Pydantic for data validation
- Click for CLI framework
- Rich for beautiful terminal output
๐ Project Status
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
9001fb25a8c2dbd2bc0b228faa96575d056b75e6428903ac3036467c06be04b1
|
|
| MD5 |
8547780a581ff543cd790ce5888cf3d0
|
|
| BLAKE2b-256 |
3947a9097080516d6c483f7a6413e772c2bf2a2d38bbc11d26b0a23fc3436e1b
|
File details
Details for the file sqlserver_mcp_server-1.0.0-py3-none-any.whl.
File metadata
- Download URL: sqlserver_mcp_server-1.0.0-py3-none-any.whl
- Upload date:
- Size: 65.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
dd969f878c0ca3abeeae96e3cfeb0dbcc9c1e1c1dde17a7cf7c85749870932ac
|
|
| MD5 |
4f25878948c1ef2fc7b6bffbf18d54a5
|
|
| BLAKE2b-256 |
29e0b968c1a174049bfcc5aef8a793b88b4755f62d6a62c632d4bb38921d0156
|