
MCP SQL Agent
An AI-powered SQLite assistant that converts natural language to SQL queries with full schema awareness, enabling users to interact with databases using conversational language.
README
MCP Database Assistant
An AI-powered multi-database assistant built with OpenAI's GPT models and Model Context Protocol (MCP). This project demonstrates how to create an intelligent database query interface that can understand natural language requests and execute SQL queries with full schema awareness across MySQL, Oracle, and SQLite databases.
🌟 Key Features
- 🤖 AI-Powered SQL Assistant - Natural language to SQL query conversion using OpenAI GPT-4o
- 🔧 Model Context Protocol Integration - Seamless tool calling and context management
- 🗄️ Multi-Database Support - Works with MySQL, Oracle, and SQLite databases
- 🌐 Modern Web Interface - Clean, responsive chat interface with real-time query processing
- 📊 Schema Discovery - Automatic database structure exploration and validation
- 🔍 Smart Search - Find tables and columns by keywords
- 💾 Session Management - Persistent chat history during browser sessions
- ⚡ Real-time Processing - Async handling for fast query execution
- 🛡️ Safe Query Execution - Protected SQL execution with error handling
- 🔄 Dual API Support - Multiple endpoint formats for different frontend requirements
📋 Prerequisites
- Python 3.12+ (specified in
.python-version
) - OpenAI API Key - Get one from OpenAI Platform
- Database - One of the following:
- SQLite database file (
.db
) - MySQL server with accessible database
- Oracle database with proper connection string
- SQLite database file (
🚀 Installation
1. Install uv (in case you haven't installed it yet)
macOS/Linux:
curl -LsSf https://astral.sh/uv/install.sh | sh
Windows:
powershell -c "irm https://astral.sh/uv/install.ps1 | iex"
Alternative (via pip):
pip install uv
2. Clone and Setup Project
git clone https://github.com/sharansahu/mcp-sql
cd mcp-sql
# Create virtual environment and install dependencies
uv sync
3. Environment Configuration
Create a .env
file in the project root with your database configuration:
For SQLite:
# OpenAI Configuration
OPENAI_API_KEY=your_openai_api_key_here
# Database Configuration
DB_TYPE=sqlite
DB_PATH=./dod_synthetic.db
For MySQL:
# OpenAI Configuration
OPENAI_API_KEY=your_openai_api_key_here
# Database Configuration
DB_TYPE=mysql
DB_HOST=localhost
DB_PORT=3306
DB_NAME=your_database_name
DB_USER=your_username
DB_PASSWORD=your_password
For Oracle:
# OpenAI Configuration
OPENAI_API_KEY=your_openai_api_key_here
# Database Configuration
DB_TYPE=oracle
DB_USER=your_username
DB_PASSWORD=your_password
DB_DSN=hostname:port/service_name
📁 Project Structure
mcp-database-assistant/
├── README.md # Project documentation
├── mcp_client.py # Flask web application (main entry point)
├── servers/ # MCP server implementations
│ ├── mcp_server_sqlite.py # SQLite MCP server with database tools
│ ├── mcp_server_mysql.py # MySQL MCP server with database tools
│ └── mcp_server_oracle.py # Oracle MCP server with database tools
├── dod_synthetic.db # Sample SQLite database (if using SQLite)
├── pyproject.toml # Project dependencies and configuration
├── .env # Environment variables (create this)
├── .python-version # Python version specification
├── static/ # Web interface files
│ ├── index.html # Main web interface
│ ├── script.js # Frontend JavaScript
│ └── styles.css # Interface styling
├── .gitignore # Git ignore file
└── .venv/ # Virtual environment (created by uv)
🎯 Usage
Web Interface (Recommended)
-
Start the Flask application:
uv run python mcp_client.py
-
Access the web interface: Open your browser and go to: http://localhost:10000
-
Start querying:
- Type natural language questions about your database
- Example: "Show me all tables in the database"
- Example: "Find personnel who worked on tank maintenance in the last 90 days"
- Example: "What's the structure of the users table?"
💡 Example Queries
The AI assistant can handle various types of database queries:
Schema Exploration
- "What tables are available in this database?"
- "Describe the structure of the personnel table"
- "Search for tables related to maintenance"
- "Show me the schema for all tables"
Data Analysis
- "How many records are in each table?"
- "Show me the first 5 personnel records"
- "Find all equipment of type 'tank'"
- "What are the column names in the orders table?"
Complex Queries
- "Show personnel who performed maintenance on tanks in the last 90 days"
- "What's the average number of maintenance tasks per person?"
- "List equipment that hasn't been maintained recently"
- "Find the top 10 customers by order value"
🛠️ Database Tools
The MCP servers provide several powerful tools for database interaction:
get_schema()
- Get complete database schema with sample datalist_tables()
- List all available tablesdescribe_table(table_name)
- Detailed table information including columns and sample datasearch_tables(keyword)
- Find tables/columns by keywordquery_data(sql)
- Execute SQL queries safely
📡 API Endpoints
The Flask app provides several REST API endpoints:
GET /
- Serve the main web interfacePOST /api/query
- Process natural language queries (returns detailed status)POST /api/chat
- Alternative query endpoint (returns simplified response)POST /api/clear
- Clear chat session historyGET /api/history
- Retrieve chat historyGET /health
- Health check endpoint
🔍 How It Works
- Database Type Detection - System loads appropriate MCP server based on
DB_TYPE
environment variable - User Input - Natural language query via web interface
- Schema Discovery - AI explores database structure using MCP tools
- Query Generation - AI generates appropriate SQL based on schema and database type
- Safe Execution - SQL query executed with proper error handling
- Result Formatting - Results formatted and returned to user
- Session Management - Conversation history maintained for context
🔧 Database-Specific Features
SQLite
- File-based database support
- Full schema introspection
- Sample data preview
MySQL
- Connection pooling
- UTF-8 support with proper collation
- Primary key detection
- Row count and sample data
Oracle
- Case-sensitive table/column handling (uppercase)
- ROWNUM-based pagination
- Primary key constraint detection
- User schema awareness
🚨 Troubleshooting
Common Issues
"Invalid DB_TYPE" error
- Ensure
DB_TYPE
is set to one of:sqlite
,mysql
, ororacle
- Check that your
.env
file is properly formatted
"No module named 'openai'"
uv sync # Reinstall dependencies
"OPENAI_API_KEY not found"
- Ensure your
.env
file exists and contains your API key - Check that the API key is valid and has sufficient credits
Database connection errors
- SQLite: Verify the
DB_PATH
points to your database file - MySQL: Check
DB_HOST
,DB_PORT
,DB_NAME
,DB_USER
, andDB_PASSWORD
- Oracle: Verify
DB_USER
,DB_PASSWORD
, andDB_DSN
format
Web interface not loading
- Check that Flask is running on the correct port (10000)
- Verify static files are in the
static/
directory
Database-Specific Issues
MySQL Connection Issues:
- Ensure MySQL server is running
- Verify user has proper permissions
- Check firewall settings if connecting remotely
Oracle Connection Issues:
- Verify Oracle Instant Client is installed
- Check TNS names configuration
- Ensure service name in DSN is correct
Debug Mode
Run with additional logging:
FLASK_DEBUG=True uv run python mcp_client.py
🛡️ Security Considerations
- Never commit your
.env
file with real credentials - Use environment variables or secure vaults in production
- Implement proper database user permissions
- Consider SQL injection protection (built into the MCP tools)
- Use HTTPS in production environments
🚀 Deployment
Local Development
The current setup is optimized for local development with the Flask development server.
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
推荐服务器

Baidu Map
百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
Playwright MCP Server
一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。
Magic Component Platform (MCP)
一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。
Audiense Insights MCP Server
通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

VeyraX
一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。
graphlit-mcp-server
模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。
Kagi MCP Server
一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

e2b-mcp-server
使用 MCP 通过 e2b 运行代码。
Neon MCP Server
用于与 Neon 管理 API 和数据库交互的 MCP 服务器
Exa MCP Server
模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。