ChatQL MCP Server
Query SQL Server databases using natural language with OpenAI GPT models.
ChatQL MCP Server
A powerful Model Context Protocol (MCP) server that enables natural language querying of SQL Server databases. Transform your English questions into SQL queries automatically using OpenAI's GPT models, with intelligent schema awareness and query optimization.
๐ Perfect for developers using Cursor AI - Integrate directly into your development workflow for instant database insights, schema exploration, and data analysis without leaving your code editor.
๐๏ธ Database Support
Currently Supported:
- โ Microsoft SQL Server (2017+)
- โ SQL Server Express
- โ Azure SQL Database
Coming Soon:
- ๐ PostgreSQL (in development)
- ๐ MySQL/MariaDB (planned)
- ๐ SQLite (planned)
- ๐ Oracle Database (planned)
Note: This version is specifically designed for SQL Server. Support for additional database systems is actively being developed and will be available in future releases.
๐ Features
Core Database Capabilities
- ๐ฃ๏ธ Natural Language to SQL: Convert English questions to SQL queries automatically
- ๐ง Schema-Aware: Intelligent understanding of your database structure
- ๐ Multiple Query Methods: Natural language, direct SQL, and schema exploration
- ๐ Rich Results: Formatted results with explanations and query analysis
- ๐ก๏ธ Safety First: Built-in query validation and result limiting
- ๐ SELECT-Only Mode: Toggle between read-only and full database access
Developer Integration
- ๐ MCP Protocol: Native integration with Claude Desktop and Cursor AI
- ๐ป IDE Integration: Perfect for development workflows in Cursor
- โก High Performance: Connection pooling and query optimization
- ๐ฏ Professional Logging: Comprehensive logging and error handling
Perfect for Development Teams
- ๐ Rapid Prototyping: Get database insights without leaving your code editor
- ๐ Schema Exploration: Understand database structure while coding
- ๐ Data Debugging: Find data issues quickly during development
- ๐ Quick Analytics: Generate reports and insights on-demand
- ๐๏ธ Database Design: Understand relationships and optimize queries
๐ Quick Start
Prerequisites
- Python 3.8+
- SQL Server Express (or any SQL Server edition)
- ODBC Driver 17 for SQL Server
- OpenAI API Key (for natural language processing)
Installation
-
Clone the repository
git clone https://github.com/SyedRazaHasnain/chatql-mcp.git cd chatql-mcp
-
Create a virtual environment
python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate
-
Install dependencies
pip install -r requirements.txt
-
Configure environment
cp env.example .env
Edit
.env
with your configuration:# Database Configuration DB_SERVER=localhost\SQLEXPRESS DB_DATABASE=your_database_name DB_USERNAME= # Leave empty for Windows Auth DB_PASSWORD= # Leave empty for Windows Auth DB_DRIVER=ODBC Driver 17 for SQL Server # OpenAI Configuration OPENAI_API_KEY=your_openai_api_key_here
-
Connect to your AI client
Choose your preferred AI client:
- ๐ฅ๏ธ Claude Desktop - General use and data analysis
- ๐ป Cursor AI - Perfect for development workflows (Recommended for developers!)
No need to start the server manually - your AI client will launch it automatically!
๐ ๏ธ Available Tools
When connected via MCP, the server provides these powerful tools:
1. execute_natural_language_query
Transform natural language into SQL and execute queries.
Example:
Query: "Show me the top 10 customers by total order value"
2. execute_direct_sql_query
Execute SQL queries directly with safety validation.
Example:
SELECT TOP 10 CustomerName, SUM(OrderValue) as Total
FROM Customers c JOIN Orders o ON c.ID = o.CustomerID
GROUP BY CustomerName ORDER BY Total DESC
3. get_table_information
Get detailed schema information for any table.
4. list_database_tables
Explore all available tables in your database.
5. get_table_sample_data
Preview sample data from any table.
6. toggle_select_only_mode
๐
Toggle between SELECT-only (read-only) and full database access modes.
Example:
Enable SELECT-only mode: {"enabled": true}
Enable full access: {"enabled": false}
7. get_security_mode_status
๐
Check current security mode and available permissions.
๐ Example Queries
Here are some example natural language queries you can try:
๐ป Development Workflows (Perfect for Cursor)
- "Show me all database tables and their relationships"
- "What columns are in the users table?"
- "Give me sample data from the products table for testing"
- "Find users created in the last week for debugging"
- "Are there any foreign key constraints I should know about?"
- "Show me the schema for the orders table"
๐ Business Intelligence
- "What are our top 5 selling products this month?"
- "Show me customers who haven't ordered in the last 90 days"
- "What's the average order value by region?"
๐ Data Exploration
- "How many records are in the customers table?"
- "What are the different product categories we have?"
- "Show me all orders placed yesterday"
๐ Analytics
- "What's our monthly revenue trend for this year?"
- "Which sales rep has the highest performance?"
- "Find duplicate customer records"
๐ Debugging & Troubleshooting
- "Find orphaned records in the order_items table"
- "Show me users with missing email addresses"
- "What are the most common error codes in our logs table?"
- "Find products that have never been ordered"
โ๏ธ Configuration Options
Database Settings
DB_SERVER=localhost\SQLEXPRESS # SQL Server instance
DB_DATABASE=YourDatabase # Target database
DB_USERNAME= # Username (optional for Windows Auth)
DB_PASSWORD= # Password (optional for Windows Auth)
DB_DRIVER=ODBC Driver 17 for SQL Server
OpenAI Settings
OPENAI_API_KEY=sk-... # Your OpenAI API key
OPENAI_MODEL=gpt-4 # Model to use
OPENAI_MAX_TOKENS=2000 # Max tokens per request
Server Settings
MCP_SERVER_NAME=chatql-mcp-server
MCP_SERVER_VERSION=1.0.0
LOG_LEVEL=INFO # DEBUG, INFO, WARNING, ERROR
MAX_QUERY_RESULTS=100 # Limit query results
QUERY_TIMEOUT=30 # Query timeout in seconds
Security Settings
SELECT_ONLY_MODE=false # Start in SELECT-only mode
ALLOW_MODE_TOGGLE=true # Allow clients to toggle modes
๐ง Connecting with AI Clients
Supported MCP Clients
This server works with any MCP-compatible client:
- โ Claude Desktop - Official Anthropic desktop application
- โ Cursor AI - AI-powered code editor (Perfect for development!)
- โ Other MCP Clients - Any application supporting the MCP protocol
How MCP Connection Works
Your ChatQL server uses the Model Context Protocol (MCP) with stdio
communication:
- Client reads your config โ Finds your server details
- Client launches your server โ Runs
python server.py
as a subprocess - Communicates via stdin/stdout โ JSON messages over standard streams
- Your server stays running โ Processes requests until client closes
1. Find Claude Desktop Config File
For Windows Users (Step-by-Step):
- Press
Windows Key + R
(opens the Run dialog) - Type:
%APPDATA%
and press Enter - Look for the "Claude" folder and double-click it
- Find the file:
claude_desktop_config.json
- If the file doesn't exist, create it by right-clicking โ New โ Text Document
- Name it exactly:
claude_desktop_config.json
(not .txt!)
For Mac Users:
- Press
Cmd + Shift + G
(opens Go to Folder) - Type:
~/Library/Application Support/Claude/
- Find or create:
claude_desktop_config.json
2. Edit the Config File
Open the file with Notepad (Windows) or TextEdit (Mac) and add this:
{
"mcpServers": {
"chatql-mcp": {
"command": "python",
"args": ["C:/Users/YourUsername/Desktop/mcp/server.py"],
"env": {
"DB_SERVER": "localhost\\SQLEXPRESS",
"DB_DATABASE": "YourDatabase",
"OPENAI_API_KEY": "your-openai-api-key"
}
}
}
}
๐จ CRITICAL: Replace these with YOUR actual values:
C:/Users/YourUsername/Desktop/mcp/server.py
โ Your actual full path to server.pyYourDatabase
โ Your actual database nameyour-openai-api-key
โ Your actual OpenAI API key
๐ก How to find your server.py path:
- Navigate to your project folder (where you saved ChatQL)
- Right-click on
server.py
- Click "Properties" (Windows) or "Get Info" (Mac)
- Copy the full path and paste it in the config
3. Start Claude Desktop
- Save your configuration file (Ctrl+S)
- Close Claude Desktop completely (right-click system tray icon โ Exit)
- Reopen Claude Desktop (it will read your new config)
- Look for MCP tools in Claude's interface
4. Test Your Connection
Once Claude Desktop has restarted, try these test queries:
Natural Language Queries:
- "What tables are available in my database?"
- "Show me sample data from the customers table"
- "How many records are in each table?"
Direct SQL:
- "Execute this SQL: SELECT TOP 5 * FROM YourTable"
- "Get the schema information for the orders table"
5. Success Indicators
When Claude connects successfully, you'll see:
- ๐ง MCP tools listed in Claude's tool panel
- ๐ Rich database responses with formatted tables
- โก Fast query execution from your database
- ๐ก๏ธ Safety validations blocking dangerous queries
If connection fails, check:
- โ File path is correct in your config
- โ Python is in your PATH
- โ
All dependencies installed (
pip install -r requirements.txt
) - โ
Database connection works (check your
.env
file)
๐ฏ Cursor AI Integration (Developers)
Why Use ChatQL with Cursor?
Transform your development workflow by connecting your database directly to Cursor AI:
- ๐ Instant Schema Exploration - "Show me all tables in this database"
- ๐ Quick Data Analysis - "What are the most common user types in our system?"
- ๐ Debug Data Issues - "Find users who have orders but no email address"
- ๐๏ธ Database Design Help - "Show me the relationship between users and orders tables"
- โก Rapid Prototyping - Get sample data for testing without writing SQL
Setting Up with Cursor
1. Configure Cursor for MCP
Create or edit your Cursor settings file:
Windows: %APPDATA%\Cursor\User\settings.json
Mac: ~/Library/Application Support/Cursor/User/settings.json
Linux: ~/.config/Cursor/User/settings.json
Add the MCP configuration:
{
"mcp.servers": {
"chatql-mcp": {
"command": "python",
"args": ["C:/path/to/your/project/server.py"],
"env": {
"DB_SERVER": "localhost\\SQLEXPRESS",
"DB_DATABASE": "YourDatabase",
"OPENAI_API_KEY": "your-openai-api-key"
}
}
}
}
2. Development Workflow Examples
๐ Database Exploration During Development
Developer: "What tables do I have available?"
ChatQL: Shows all database tables with schemas
Developer: "Show me the structure of the users table"
ChatQL: Displays columns, data types, constraints, relationships
Developer: "Give me sample data from the orders table"
ChatQL: Returns formatted sample records
๐ Debugging Data Issues
Developer: "Find all users created in the last 7 days"
ChatQL: Converts to SQL and shows recent users
Developer: "Are there any orphaned records in order_items?"
ChatQL: Checks for referential integrity issues
Developer: "Show me users with duplicate email addresses"
ChatQL: Finds and displays duplicate data
๐ Quick Analytics for Features
Developer: "What's the distribution of user roles in our system?"
ChatQL: Groups and counts user roles
Developer: "Show me the average order value by month"
ChatQL: Generates time-based analytics
Developer: "Which products have never been ordered?"
ChatQL: Finds unused inventory
3. Cursor-Specific Benefits
- ๐ฏ Context-Aware: Cursor can see your code and database structure simultaneously
- โก Lightning Fast: No switching between database tools and your editor
- ๐ง Intelligent Queries: Cursor understands your codebase context for better questions
- ๐ Iterative Development: Ask follow-up questions based on query results
- ๐ Code Generation: Generate database-related code based on schema insights
4. Example Development Session
# Working on a user dashboard feature
Developer: "Show me the user table structure"
ChatQL: Returns user schema with all fields
Developer: "What's the relationship between users and their orders?"
ChatQL: Shows JOIN relationships and foreign keys
Developer: "Give me sample data for testing the dashboard"
ChatQL: Returns realistic test data
Developer: "How many users registered each month this year?"
ChatQL: Generates registration analytics
# Cursor can now suggest code based on this database knowledge!
Other MCP Clients
This server follows the standard MCP protocol and works with any MCP-compatible client.
๐ก๏ธ Security & Safety
Built-in Protections
- Query Validation: Dangerous operations (DROP, TRUNCATE) are blocked
- Result Limiting: Automatic limits prevent memory exhaustion
- Parameterized Queries: Protection against SQL injection
- Connection Pooling: Secure and efficient database connections
- SELECT-Only Mode: Toggle-able read-only mode for enhanced security
๐ SELECT-Only Mode
A powerful security feature that allows you to restrict database operations to read-only queries:
How It Works
- Enabled: Only SELECT queries are allowed, all INSERT, UPDATE, DELETE, CREATE, DROP, ALTER operations are blocked
- Disabled: All SQL operations are permitted (with standard safety validations)
- Toggle: Can be switched on/off from the client using the
toggle_select_only_mode
tool
Use Cases
- ๐ Data Exploration: Safe browsing of database contents without risk of modification
- ๐ Reporting & Analytics: Generate reports with zero risk of data corruption
- ๐ฅ Team Collaboration: Allow team members to explore data safely
- ๐งช Development: Test queries without affecting production data
- ๐ Learning: Perfect for learning SQL without database modification risks
Client Integration
In Claude Desktop or Cursor:
# Enable SELECT-only mode
Ask: "Enable SELECT-only mode for safety"
# Check current status
Ask: "What is the current security mode?"
# Disable SELECT-only mode
Ask: "Disable SELECT-only mode to allow full access"
Configuration Options:
# Start server in SELECT-only mode
SELECT_ONLY_MODE=true
# Disable mode toggle (force current mode)
ALLOW_MODE_TOGGLE=false
Security Indicators
- ๐ RESTRICTED: SELECT-only mode active
- โ UNRESTRICTED: Full access mode active
- โ BLOCKED: Operation blocked by security mode
Best Practices
- Start with SELECT-only mode enabled for new environments
- Use read-only database accounts when possible
- Never expose the server to the internet
- Store credentials securely using environment variables
- Regularly rotate API keys and database passwords
๐จ Troubleshooting
Database Connection Issues
Error: "Data source name not found"
# Install ODBC Driver 17 for SQL Server
# Download from Microsoft's official website
Error: "Login failed"
- Verify your credentials in
.env
- For Windows Auth, leave username/password empty
- Ensure SQL Server allows your authentication method
Error: "Named Pipes Provider error"
- Verify SQL Server is running
- Check server name (usually
localhost\SQLEXPRESS
) - Enable TCP/IP in SQL Server Configuration Manager
OpenAI API Issues
Error: "OpenAI API key not configured"
- Set
OPENAI_API_KEY
in your.env
file - Get an API key from https://platform.openai.com/
Error: Rate limiting
- The server handles rate limits gracefully
- Consider upgrading your OpenAI plan for higher limits
๐งช Development
Running Tests
# Tests coming soon!
python -m pytest
Code Style
# Format code
black .
# Check style
flake8 .
# Type checking
mypy .
๐ท๏ธ Version Management
This project uses a centralized versioning system with automated tools for contributors.
Quick Version Commands
# Check current version
python version_manager.py current
# Bump version for bug fixes (1.0.0 โ 1.0.1)
python version_manager.py bump patch
# Bump version for new features (1.0.1 โ 1.1.0)
python version_manager.py bump minor
# Bump version for breaking changes (1.1.0 โ 2.0.0)
python version_manager.py bump major
Semantic Versioning Guidelines
- PATCH (
1.0.1
) - Bug fixes, security patches - MINOR (
1.1.0
) - New features, database support additions - MAJOR (
2.0.0
) - Breaking changes, API modifications
Complete Release Workflow
- Make your changes and test thoroughly
- Update CHANGELOG.md with your changes under
[Unreleased]
- Bump version using the appropriate type:
python version_manager.py bump minor -m "Added PostgreSQL support"
- Push changes including tags:
git push origin master --tags
Version System Details
- โ
Single source of truth:
__version__.py
- โ Automatic git tagging: Creates annotated tags (v1.0.0, v1.1.0, etc.)
- โ Auto-commit: Commits version changes with proper messages
- โ No manual updates: All files automatically sync with central version
Advanced Options
# Set specific version
python version_manager.py set 1.2.3
# Skip git operations (for testing)
python version_manager.py bump patch --no-commit --no-tag
# Create tag with custom message
python version_manager.py tag -m "Hotfix release"
Note for Contributors: Always use the version manager script instead of manually editing version numbers. This ensures consistency across all project files.
๐ค Contributing
We welcome contributions! Please see CONTRIBUTING.md for details on:
- Setting up development environment
- Code standards and best practices
- Pull request process
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
๐ Acknowledgments
- Built with the Model Context Protocol (MCP)
- Powered by OpenAI GPT Models
- Uses SQLAlchemy for database connectivity
๐ Support
- ๐ Found a bug? Open an issue
- ๐ก Have a feature request? Start a discussion
- ๐ง Need help? Check our troubleshooting guide
Made with โค๏ธ by Raza Hasnain
Related Servers
CData ActiveCampaign Server
Access and manage ActiveCampaign data through the CData JDBC Driver.
Strapi MCP
An MCP server for Strapi CMS, providing access to content types and entries through the MCP protocol.
Mongo
A Model Context Protocol (MCP) server that enables LLMs to interact directly with MongoDB databases
Financial Datasets
Stock market API made for AI agents
Simple MySQL MCP Server
A simple MCP server for MySQL, demonstrating fundamental MCP protocol concepts. Requires a MySQL database connection configured via environment variables.
Gremlin
Interact with any Gremlin-compatible graph database using natural language, with support for schema discovery, complex queries, and data import/export.
MCP Oracle Database Server
A server for full integration with Oracle Database. Requires Oracle Instant Client libraries.
MCP Memory libSQL
A persistent memory system for MCP using libSQL, providing vector search and efficient knowledge storage.
Chroma
Embeddings, vector search, document storage, and full-text search with the open-source AI application database
JDBC-MCP
Enables AI assistants to interact with various databases through JDBC connections.