ChatQL MCP Server

by syedrazahasnain

Not rated
GitHub

About

Query SQL Server databases using natural language with OpenAI GPT models.

Details

Author
syedrazahasnain
Categories
Database, Other, AI

Setup

Install ChatQL MCP Server in your MCP client (Claude Desktop, Cursor, Windsurf, and others).

Repository: https://github.com/syedrazahasnain/chatql-mcp

Follow the installation instructions in the repository README, then restart your MCP client.

A powerfulModel 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.

- βœ…Microsoft SQL Server(2017+)
- βœ…SQL Server Express
- βœ…Azure SQL Database

- πŸ”„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.

- πŸ—£οΈ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

- πŸ”Œ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

- πŸš€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

- Python 3.8+
- SQL Server Express(or any SQL Server edition)
- ODBC Driver 17for SQL Server
- OpenAI API Key(for natural language processing)

git clone https://github.com/SyedRazaHasnain/chatql-mcp.git cd chatql-mcp
python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate
# 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

- πŸ–₯️ 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!

When connected via MCP, the server provides these powerful tools:

Transform natural language into SQL and execute queries.

Query: "Show me the top 10 customers by total order value"

Execute SQL queries directly with safety validation.

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

Get detailed schema information for any table.

Explore all available tables in your database.

Toggle between SELECT-only (read-only) and full database access modes.

Enable SELECT-only mode: {"enabled": true} Enable full access: {"enabled": false}

Check current security mode and available permissions.

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"

- "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?"

- "How many records are in the customers table?"
- "What are the different product categories we have?"
- "Show me all orders placed yesterday"

- "What's our monthly revenue trend for this year?"
- "Which sales rep has the highest performance?"
- "Find duplicate customer records"

- "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"

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_API_KEY=sk-... # Your OpenAI API key OPENAI_MODEL=gpt-4 # Model to use OPENAI_MAX_TOKENS=2000 # Max tokens per request
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
SELECT_ONLY_MODE=false # Start in SELECT-only mode ALLOW_MODE_TOGGLE=true # Allow clients to toggle modes

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

Your ChatQL server uses theModel Context Protocol (MCP)withstdiocommunication:
- Client reads your config→ Finds your server details
- Client launches your server→ Runspython server.pyas a subprocess
- Communicates via stdin/stdout→ JSON messages over standard streams
- Your server stays running→ Processes requests until client closes
- PressWindows Key + R(opens the Run dialog)
- Type:%APPDATA%and press Enter
- Look for the "Claude" folderand 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!)
- PressCmd + Shift + G(opens Go to Folder)
- Type:~/Library/Application Support/Claude/
- Find or create:claude_desktop_config.json

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.py
- YourDatabase→Your actual database name
- your-openai-api-key→Your actual OpenAI API key
- Navigate to your project folder(where you saved ChatQL)
- Right-click onserver.py
- Click "Properties"(Windows) or "Get Info" (Mac)
- Copy the full pathand paste it in the config
- 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 toolsin Claude's interface

Once Claude Desktop has restarted, try these test queries:

- "What tables are available in my database?"
- "Show me sample data from the customers table"
- "How many records are in each table?"

- "Execute this SQL: SELECT TOP 5 FROM YourTable"
-
"Get the schema information for the orders table"*

When Claude connects successfully, you'll see:

- πŸ”§MCP tools listedin Claude's tool panel
- πŸ“ŠRich database responseswith formatted tables
- ⚑Fast query executionfrom your database
- πŸ›‘οΈSafety validationsblocking dangerous queries

- βœ…File path is correctin your config
- βœ…Python is in your PATH
- βœ…All dependencies installed(pip install -r requirements.txt)
- βœ…Database connection works(check your.envfile)

Transform your development workflowby 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

Create or edit your Cursor settings file:

Windows:%APPDATA%\Cursor\User\settings.jsonMac:~/Library/Application Support/Cursor/User/settings.jsonLinux:~/.config/Cursor/User/settings.json

{ "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" } } } }
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
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
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

- 🎯 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

# 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!

This server follows the standard MCP protocol and works with any MCP-compatible client.

- 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

A powerful security feature that allows you to restrict database operations to read-only queries:

- 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 thetoggle_select_only_modetool

- πŸ” 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

# 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"
# Start server in SELECT-only mode SELECT_ONLY_MODE=true # Disable mode toggle (force current mode) ALLOW_MODE_TOGGLE=false

- πŸ”’ RESTRICTED: SELECT-only mode active
- βœ… UNRESTRICTED: Full access mode active
- ❌ BLOCKED: Operation blocked by security mode

- 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

Error: "Data source name not found"

# Install ODBC Driver 17 for SQL Server # Download from Microsoft's official website

- 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 (usuallylocalhost\SQLEXPRESS)
- Enable TCP/IP in SQL Server Configuration Manager

Error: "OpenAI API key not configured"

- SetOPENAI_API_KEYin your.envfile
- Get an API key fromhttps://platform.openai.com/

No reviews yet β€” be the first

Sign in to leave a review

Use Google, GitHub, or an email account so ratings stay tied to real people.

Email sign in

No reviews posted yet.