MCP SQL Agent
Utilizes .env files for configuration management of database connections and API keys
Uses Flask to create a web application interface with API endpoints for processing database queries and managing chat sessions
Provides tools for connecting to MySQL databases, executing SQL queries, exploring schema structure, and analyzing data with AI-assisted natural language processing
Integrates with OpenAI's GPT models to power natural language to SQL query conversion and database exploration capabilities
Enables interaction with SQLite databases through schema discovery, table exploration, and execution of natural language queries converted to SQL
Click on "Install Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@MCP SQL Agentshow me the top 5 customers by total order value"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
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
Related MCP server: GraphJin
π 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
π Installation
1. Install uv (in case you haven't installed it yet)
macOS/Linux:
curl -LsSf https://astral.sh/uv/install.sh | shWindows:
powershell -c "irm https://astral.sh/uv/install.ps1 | iex"Alternative (via pip):
pip install uv2. Clone and Setup Project
git clone https://github.com/sharansahu/mcp-sql
cd mcp-sql
# Create virtual environment and install dependencies
uv sync3. 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.dbFor 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_passwordFor 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.pyAccess 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_TYPEenvironment variableUser 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_TYPEis set to one of:sqlite,mysql, ororacleCheck that your
.envfile is properly formatted
"No module named 'openai'"
uv sync # Reinstall dependencies"OPENAI_API_KEY not found"
Ensure your
.envfile exists and contains your API keyCheck that the API key is valid and has sufficient credits
Database connection errors
SQLite: Verify the
DB_PATHpoints to your database fileMySQL: Check
DB_HOST,DB_PORT,DB_NAME,DB_USER, andDB_PASSWORDOracle: Verify
DB_USER,DB_PASSWORD, andDB_DSNformat
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
.envfile with real credentialsUse 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.
Available Tools
5 toolsdescribe_tableB
Get detailed information about a specific table including columns and sample data
| Name | Required | Description | Default |
|---|---|---|---|
| table_name | Yes |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries the full burden of behavioral disclosure. While it implies a read operation ('Get detailed information'), it doesn't specify whether this requires permissions, what happens if the table doesn't exist, whether it's cached or real-time, or any rate limits. The description is minimal and lacks crucial behavioral context.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is a single, efficient sentence with zero waste. It's front-loaded with the core purpose and includes key details (columns and sample data) without unnecessary elaboration.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the tool has an output schema (which should document return values), the description doesn't need to explain outputs. However, for a tool with no annotations and low schema coverage, the description is too minimalβit lacks behavioral context and parameter guidance, making it incomplete for safe and effective use by an AI agent.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 0%, so the schema provides no parameter details. The description doesn't add any parameter-specific information beyond implying 'table_name' is required. It doesn't explain what format the table name should be in, whether it's case-sensitive, or provide examples. Baseline 3 is appropriate as the description doesn't compensate for the low schema coverage.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool's purpose with specific verbs ('Get detailed information') and resources ('about a specific table'), and it specifies what information is included ('columns and sample data'). However, it doesn't explicitly distinguish this tool from its sibling 'get_schema', which might also provide schema information about tables.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description provides no guidance on when to use this tool versus alternatives like 'get_schema', 'list_tables', or 'query_data'. It doesn't mention prerequisites, exclusions, or specific contexts where this tool is preferred over siblings.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
get_schemaB
Get the complete database schema with table structures and sample data
| Name | Required | Description | Default |
|---|---|---|---|
No parameters | |||
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations provided, the description carries the full burden of behavioral disclosure. It states the tool retrieves schema and sample data, but doesn't cover critical aspects like whether this is a read-only operation, potential performance impacts, data freshness, or error handling. For a tool with zero annotation coverage, this leaves significant gaps in understanding its behavior.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is a single, efficient sentence that front-loads the core purpose ('Get the complete database schema') and adds specific details ('with table structures and sample data') without any wasted words. It's appropriately sized for a simple tool with no parameters.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the tool's simplicity (0 parameters, output schema exists), the description is minimally adequate. However, with no annotations and sibling tools present, it lacks context on when to use it versus alternatives and behavioral details. The output schema will cover return values, but the description doesn't fully address the tool's role in the broader context.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The tool has 0 parameters with 100% schema description coverage, so the schema fully documents the lack of inputs. The description adds no parameter information, which is appropriate here, but since there are no parameters to explain, it doesn't need to compensate for any gaps. Baseline 4 is assigned as per rules for 0 parameters.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool's purpose with a specific verb ('Get') and resource ('complete database schema'), including what it retrieves ('table structures and sample data'). However, it doesn't explicitly differentiate from sibling tools like 'describe_table' or 'list_tables', which likely provide overlapping or related schema information.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
No guidance is provided on when to use this tool versus alternatives such as 'describe_table', 'list_tables', or 'search_tables'. The description implies a comprehensive schema retrieval but doesn't specify use cases, prerequisites, or exclusions, leaving the agent to infer usage from context alone.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
list_tablesB
List all tables in the database
| Name | Required | Description | Default |
|---|---|---|---|
No parameters | |||
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries the full burden of behavioral disclosure. It states the action but doesn't cover aspects like pagination, sorting, rate limits, permissions required, or what the output includes (e.g., table names only or metadata). This leaves significant gaps for an agent to understand how to use it effectively.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is a single, clear sentence with no wasted words. It's front-loaded with the core action and resource, making it easy to parse quickly. Every word earns its place by conveying essential information.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the tool's simplicity (0 parameters, output schema exists), the description is minimally adequate. However, with no annotations and siblings like 'search_tables', it lacks context on when to use it versus alternatives. The output schema should cover return values, but behavioral aspects like performance or limitations are missing.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The tool has 0 parameters, and schema description coverage is 100%, so no parameter documentation is needed. The description doesn't add parameter details, but that's appropriate here, as there are no parameters to explain. A baseline of 4 is given for tools with no parameters.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the verb ('List') and resource ('all tables in the database'), making the purpose immediately understandable. However, it doesn't differentiate from sibling tools like 'search_tables' or 'describe_table', which could offer similar functionality with different scopes or details.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
No guidance is provided on when to use this tool versus alternatives like 'search_tables' (for filtered searches) or 'describe_table' (for detailed metadata). The description implies a broad listing but doesn't specify use cases, prerequisites, or exclusions.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
query_dataB
Execute SQL queries safely. Use get_schema() first to understand the database structure.
| Name | Required | Description | Default |
|---|---|---|---|
| sql | Yes |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions 'safely' but doesn't explain what that entails (e.g., read-only vs. write operations, error handling, or performance limits). This leaves significant gaps in understanding how the tool behaves beyond basic execution.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is highly concise with two sentences that are front-loaded and waste no words. Each sentence serves a clear purpose: stating the tool's function and providing a usage guideline.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the tool's complexity (executing arbitrary SQL queries) and the presence of an output schema (which handles return values), the description is minimally adequate. However, with no annotations and low parameter coverage, it lacks details on safety, constraints, and error handling that would be helpful for an AI agent.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The schema description coverage is 0%, so the description must compensate. It only implies that the 'sql' parameter is for SQL queries without adding details like supported syntax, constraints, or examples. This fails to adequately clarify the parameter's meaning beyond the basic schema.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the action ('Execute SQL queries') and resource ('database'), making the purpose understandable. However, it doesn't explicitly differentiate this tool from its siblings like 'describe_table' or 'search_tables', which also interact with database structures.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description provides clear guidance to 'Use get_schema() first to understand the database structure,' which helps the agent know when to use this tool in relation to a sibling. However, it doesn't specify when NOT to use it or mention alternatives like 'list_tables' for other purposes.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
search_tablesB
Search for tables or columns containing a specific keyword
| Name | Required | Description | Default |
|---|---|---|---|
| keyword | Yes |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries the full burden of behavioral disclosure. It states the tool searches for tables or columns by keyword but does not disclose critical behavioral traits such as whether the search is case-sensitive, if it returns partial matches, the format of results (e.g., list of table names, detailed metadata), pagination, rate limits, or authentication requirements. For a search tool with zero annotation coverage, this is a significant gap in transparency.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is a single, clear sentence: 'Search for tables or columns containing a specific keyword.' It is front-loaded with the core purpose, has no redundant or vague language, and efficiently conveys the essential information without waste. Every word earns its place, making it highly concise and well-structured.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the tool's moderate complexity (a search function with one parameter) and the presence of an output schema (which should cover return values), the description is minimally complete. It states what the tool does but lacks details on behavioral aspects like search behavior, result format, or error handling. With no annotations and low schema coverage, the description does not fully compensate, but the output schema may help, resulting in an adequate but incomplete overall context.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The input schema has one parameter ('keyword') with 0% description coverage, meaning the schema provides no semantic details. The description adds value by explaining that the keyword is used to 'search for tables or columns,' giving basic context. However, it does not specify constraints (e.g., minimum length, allowed characters), examples, or how the keyword is applied (e.g., exact match vs. substring), leaving the agent with incomplete guidance. This meets the baseline for minimal parameter semantics.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool's purpose: 'Search for tables or columns containing a specific keyword.' It specifies the verb ('search'), resource ('tables or columns'), and scope ('containing a specific keyword'), making the intent unambiguous. However, it does not explicitly differentiate from siblings like 'list_tables' (which might list all tables without searching) or 'describe_table' (which might describe a specific table), so it falls short of a perfect score.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description provides no guidance on when to use this tool versus alternatives. It does not mention siblings such as 'list_tables' (for listing all tables), 'describe_table' (for detailed info on a specific table), or 'query_data' (for querying data within tables), leaving the agent to infer usage context. This lack of explicit when-to-use or when-not-to-use instructions results in a low score.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
TDQS
Some tools have overlapping purposes that could cause confusion. 'describe_table' and 'get_schema' both provide table structure information, with 'get_schema' covering the entire database while 'describe_table' focuses on a specific table. 'list_tables' and 'search_tables' also overlap in table discovery functionality, though 'search_tables' adds keyword filtering.
All tool names follow a consistent verb_noun pattern with clear, descriptive names. The naming convention is uniform throughout: describe_table, get_schema, list_tables, query_data, and search_tables all use the same structure and are immediately understandable.
Five tools is a reasonable number for an SQL agent, providing core database interaction capabilities without being overwhelming. The count feels slightly lean but covers essential operations for exploring and querying databases, though additional tools for data manipulation might be expected.
The toolset covers exploration and querying well but lacks data manipulation operations. There are no tools for creating, updating, or deleting tables or records, which are common SQL operations. The surface is complete for read-only database interaction but incomplete for full database management.
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Related MCP Connectors
Ask data questions in natural language. Get SQL, insights, and charts from your databases.
Ask business questions in plain English. Get instant answers from your database, no SQL needed.
Explore, query, and inspect SQLite databases with ease. List tables, preview results, and view detβ¦
Your Supabase account in natural language: run SQL, apply migrations, manage tables, storage, edge f
Related MCP Servers
- AlicenseNot gradedqualityCmaintenanceEnables AI models to interact with SQLite Cloud databases, supporting SQL queries, schema management, and performance analysis.221MIT
- AlicenseNot gradedqualityAmaintenanceEnables AI assistants to query databases using natural language, with automatic schema discovery and SQL compilation.6,0023,157Apache 2.0
- AlicenseNot gradedqualityDmaintenanceEnables natural language querying of any SQL database by converting plain English questions into SQL queries, with auto-schema detection and safety features.3MIT
- AlicenseNot gradedqualityDmaintenanceEnables natural language querying of SQL databases using AI, supporting multiple database types and automatic schema discovery.1MIT
Appeared in Searches
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/sharansahu/mcp-sql'
If you have feedback or need assistance with the MCP directory API, please join our Discord server