Skip to main content
Glama
sharansahu

MCP SQL Agent

by sharansahu

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

  1. Start the Flask application:

    uv run python mcp_client.py
  2. Access the web interface: Open your browser and go to: http://localhost:10000

  3. 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 data

  • list_tables() - List all available tables

  • describe_table(table_name) - Detailed table information including columns and sample data

  • search_tables(keyword) - Find tables/columns by keyword

  • query_data(sql) - Execute SQL queries safely

πŸ“‘ API Endpoints

The Flask app provides several REST API endpoints:

  • GET / - Serve the main web interface

  • POST /api/query - Process natural language queries (returns detailed status)

  • POST /api/chat - Alternative query endpoint (returns simplified response)

  • POST /api/clear - Clear chat session history

  • GET /api/history - Retrieve chat history

  • GET /health - Health check endpoint

πŸ” How It Works

  1. Database Type Detection - System loads appropriate MCP server based on DB_TYPE environment variable

  2. User Input - Natural language query via web interface

  3. Schema Discovery - AI explores database structure using MCP tools

  4. Query Generation - AI generates appropriate SQL based on schema and database type

  5. Safe Execution - SQL query executed with proper error handling

  6. Result Formatting - Results formatted and returned to user

  7. 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, or oracle

  • 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, and DB_PASSWORD

  • Oracle: Verify DB_USER, DB_PASSWORD, and DB_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.

Available Tools

5 tools
describe_tableB

Get detailed information about a specific table including columns and sample data

ParametersJSON Schema
NameRequiredDescriptionDefault
table_nameYes

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

B3.1/5.0
Behavior2/5

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.

Conciseness5/5

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.

Completeness3/5

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.

Parameters3/5

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.

Purpose4/5

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.

Usage Guidelines2/5

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

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

B3.2/5.0
Behavior2/5

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.

Conciseness5/5

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.

Completeness3/5

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.

Parameters4/5

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.

Purpose4/5

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.

Usage Guidelines2/5

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

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

B3.2/5.0
Behavior2/5

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.

Conciseness5/5

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.

Completeness3/5

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.

Parameters4/5

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.

Purpose4/5

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.

Usage Guidelines2/5

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.

ParametersJSON Schema
NameRequiredDescriptionDefault
sqlYes

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

B3.3/5.0
Behavior2/5

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.

Conciseness5/5

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.

Completeness3/5

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.

Parameters2/5

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.

Purpose4/5

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.

Usage Guidelines4/5

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

ParametersJSON Schema
NameRequiredDescriptionDefault
keywordYes

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

B3.1/5.0
Behavior2/5

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.

Conciseness5/5

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.

Completeness3/5

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.

Parameters3/5

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.

Purpose4/5

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.

Usage Guidelines2/5

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

B3.4/5.0
Disambiguation3/5

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.

Naming Consistency5/5

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.

Tool Count4/5

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.

Completeness3/5

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

ActivityInactive
ResponsivenessNo issues

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

Related MCP Servers

  • A
    license
    Not graded
    quality
    A
    maintenance
    Enables AI assistants to query databases using natural language, with automatic schema discovery and SQL compilation.
    6,002
    3,157
    Apache 2.0
  • A
    license
    Not graded
    quality
    D
    maintenance
    Enables natural language querying of any SQL database by converting plain English questions into SQL queries, with auto-schema detection and safety features.
    3
    MIT
  • A
    license
    Not graded
    quality
    D
    maintenance
    Enables natural language querying of SQL databases using AI, supporting multiple database types and automatic schema discovery.
    1
    MIT

Latest Blog Posts

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