Database Assistant MCP Server
Provides tools for exploring and querying MySQL databases, including schema discovery, safe query execution, natural language to SQL, and CSV export.
Provides natural language to SQL generation using OpenAI-compatible language models, enabling users to describe queries in plain English.
Provides tools for exploring and querying PostgreSQL databases, including schema discovery, safe query execution, natural language to SQL, and CSV export.
Click on "Deploy 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., "@Database Assistant MCP Server describe the customers table"
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.
Database Assistant MCP Server
A read-only MCP (Model Context Protocol) server for database exploration and querying. Connect any MCP-compatible client (AWS Kiro, Claude Desktop, etc.) to your PostgreSQL or MySQL database and explore schemas, run queries, generate SQL from natural language, and export results as CSV.
Features
Schema Discovery — List databases, schemas, tables, columns, constraints, indexes, and foreign key relationships
Safe Query Execution — AST-based SQL validation ensures only read-only queries run
Natural Language to SQL — Describe what you want in plain English and get a validated SQL query
CSV Export — Export any query result to a CSV file
Query Explanation — Run EXPLAIN ANALYZE to understand query performance
Pagination — Large results are paginated (100 rows/page) automatically
Audit Logging — Every query is logged with timestamp, execution time, and row count
Related MCP server: uniquery
Tools
Tool | Description |
| List all databases on the server |
| List schemas (filtered by allowlist) |
| Tables in a schema with types and row counts |
| Columns, types, constraints, and indexes |
| Foreign key tree (incoming + outgoing) |
| Quick N-row preview of a table |
| Check if a query is safe before running |
| Execute a validated read-only query |
| EXPLAIN ANALYZE with execution plan |
| Natural language → SQL (LLM-powered) |
| Execute query and save results as CSV |
Security
This server enforces strict read-only access:
AST-based validation — SQL is parsed into an abstract syntax tree using sqlglot, not regex
Blocked operations — INSERT, UPDATE, DELETE, DROP, ALTER, TRUNCATE, CREATE, GRANT, REVOKE, COPY, CALL
Single-statement only — Multi-statement queries (
;separated) are rejectedDangerous function blocking —
pg_read_file,lo_export,dblink,LOAD_FILE, etc.Automatic LIMIT — Queries without a LIMIT get one injected (default: 1000 rows max)
Query timeout — Enforced at the database level (default: 10 seconds)
Schema allowlist — Restrict access to specific schemas only
Generated SQL re-validation — LLM-generated queries pass through the same validator
Prerequisites
Python 3.10+
uv package manager
PostgreSQL or MySQL database
Setup
Clone and install dependencies:
cd /path/to/RDS
uv syncConfigure environment:
cp .env.example .env
# Edit .env with your database credentialsSeed a test database (optional):
psql -U postgres -f seed.sqlThis creates an ecommerce database with 50 tables and ~25,000 rows across customers, products, orders, analytics, support, and more.
Configuration
Set these environment variables (via .env file or system environment):
Variable | Required | Default | Description |
| Yes | — | Database hostname or RDS endpoint |
| No |
| Database port |
| Yes | — | Database name |
| Yes | — | Database user (use a read-only user) |
| Yes | — | Database password |
| No |
|
|
| No | (all) | Comma-separated schema allowlist |
| No |
| Max query execution time (seconds) |
| No |
| Maximum rows returned per query |
| No |
| Directory for CSV exports |
| No | — | LLM API endpoint (for |
| No | — | LLM API key (for |
| No |
| LLM model ID |
Usage
With AWS Kiro
Add to your Kiro MCP configuration:
{
"mcpServers": {
"database-assistant": {
"command": "/opt/homebrew/bin/uv",
"args": ["run", "--directory", "/path/to/database_mcp_server", "mcp_server.py"],
"env": {
"DB_HOST": "your-rds-endpoint.rds.amazonaws.com",
"DB_PORT": "5432",
"DB_NAME": "ecommerce",
"DB_USER": "readonly_user",
"DB_PASSWORD": "your_password",
"DB_TYPE": "postgresql",
"ALLOWED_SCHEMAS": "store"
}
}
}
}With Claude Desktop
Add to claude_desktop_config.json:
{
"mcpServers": {
"database-assistant": {
"command": "uv",
"args": ["run", "--directory", "/path/to/RDS", "mcp_server.py"]
}
}
}With MCP Inspector (for testing)
uv run mcp dev mcp_server.pyDirect stdio (for development)
uv run mcp_server.pyExample Workflows
Explore a database schema
User: What tables are in this database?
→ list_tables(schema="store")
User: Tell me about the orders table
→ describe_table(table="store.orders")
User: What relates to orders?
→ describe_relationships(table="store.orders")Query with natural language
User: Show me the top 10 customers by revenue this year
→ generate_sql(question="top 10 customers by total order revenue in 2024")
→ validate_sql(query="SELECT ...")
→ run_sql(query="SELECT ...")Export data
User: Export all orders from last month as CSV
→ generate_sql(question="all orders created in the last 30 days with customer name and total")
→ export_csv(query="SELECT ...")
→ Returns: /tmp/db_exports/export_20240715_143022_a1b2c3d4.csvArchitecture
MCP Client (Kiro / Claude Desktop)
│
▼ (stdio)
┌─────────────────────────────┐
│ mcp_server.py │ FastMCP server, 11 tools
├─────────────────────────────┤
│ sql/validator.py │ AST-based safety validation (sqlglot)
│ sql/generator.py │ NL→SQL via OpenAI-compatible LLM
│ db/schema.py │ Schema introspection service
│ db/connection.py │ Async connection pool (asyncpg/aiomysql)
│ export/csv_export.py │ CSV file generation
│ config.py │ Environment-based configuration
└─────────────────────────────┘
│
▼
PostgreSQL / MySQL / AWS RDSProject Structure
.
├── mcp_server.py # MCP server entry point with tool definitions
├── config.py # Configuration from environment variables
├── db/
│ ├── connection.py # Async connection manager with pooling
│ └── schema.py # Schema introspection service
├── sql/
│ ├── validator.py # SQL validation (sqlglot AST)
│ └── generator.py # LLM-based SQL generation
├── export/
│ └── csv_export.py # CSV export utility
├── seed.sql # Sample database (50 tables, 25k+ rows)
├── pyproject.toml # Dependencies and project metadata
├── .env.example # Environment variable template
└── .gitignoreCreating a Read-Only Database User
For production use, create a dedicated read-only user:
-- PostgreSQL
CREATE USER readonly_user WITH PASSWORD 'secure_password';
GRANT CONNECT ON DATABASE ecommerce TO readonly_user;
GRANT USAGE ON SCHEMA store TO readonly_user;
GRANT SELECT ON ALL TABLES IN SCHEMA store TO readonly_user;
ALTER DEFAULT PRIVILEGES IN SCHEMA store GRANT SELECT ON TABLES TO readonly_user;-- MySQL
CREATE USER 'readonly_user'@'%' IDENTIFIED BY 'secure_password';
GRANT SELECT ON ecommerce.* TO 'readonly_user'@'%';
FLUSH PRIVILEGES;Dependencies
mcp — Model Context Protocol SDK
sqlglot — SQL parser for validation
asyncpg — Async PostgreSQL driver
aiomysql — Async MySQL driver
openai — LLM API client (for SQL generation)
python-dotenv — Environment variable loading
pydantic — Data validation
License
MIT
Available Tools
11 toolsdescribe_relationshipsA
Show foreign key relationships for a table: both outgoing (this table references others) and incoming (others reference this table).
Inputs: table (required). Returns: result
describe_tableA
Get detailed table information: columns (name, type, nullable, default), constraints (PK, FK, unique), and indexes.
Inputs: table (required). Returns: result
explain_queryA
Run EXPLAIN ANALYZE on a SQL query to show the execution plan. Helps understand performance characteristics like index usage, sequential scans, and estimated costs.
Inputs: query (required). Returns: result
export_csvA
Execute a SQL query and export results as a CSV file. The query is validated for safety. Returns the file path of the generated CSV.
Inputs: query (required). Returns: result
generate_sqlA
Generate a SQL query from a natural language question. Uses the database schema as context and an LLM to produce a valid SELECT query. The generated query is validated for safety.
Inputs: question (required), schema. Returns: result
list_databasesA
List all available databases on the connected server.
Inputs: no named parameters. Returns: result
list_schemasA
List all schemas in the connected database. For PostgreSQL returns schema names, for MySQL returns databases.
Inputs: no named parameters. Returns: result
list_tablesA
List all tables in a schema with their types (BASE TABLE or VIEW) and approximate row counts.
Inputs: schema. Returns: result
run_sqlA
Execute a read-only SQL query. The query is validated for safety before execution. Supports pagination (100 rows per page). Returns columns, rows, row count, and execution time.
Inputs: query (required), page. Returns: result
sample_dataA
Get a quick preview of data in a table. Returns the first N rows to help understand data format and contents.
Inputs: table (required), limit. Returns: result
validate_sqlA
Check if a SQL query is safe to execute. Validates that it is read-only, single-statement, and contains no dangerous operations. Use before run_sql to preview validation.
Inputs: query (required). Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 11 tools
Each tool has a clearly distinct purpose covering schema browsing, querying, validation, and export. There is no overlap or ambiguity between tools.
All tool names follow a consistent verb_noun pattern using snake_case, making them predictable and easy to navigate.
11 tools provide comprehensive coverage for database exploration and safe querying without being excessive or sparse.
Covers essential CRUD-like operations for a read-only assistant, but lacks a direct row count tool and alternative export formats like JSON.
Maintenance
Related MCP Connectors
Query your org's data in natural language — read-only MCP access to SQL, NoSQL, files & warehouses.
Query your warehouse or a CSV with Claude/ChatGPT over MCP, governed by table-level ACL + audit.
Text-to-SQL MCP server: read-only queries on PostgreSQL, MySQL and SQL Server with your real schema
Query, explore, and manage your databases through natural conversation.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceEnables read-only interaction with SQL databases through MCP, providing database metadata exploration, sample data retrieval, and secure query execution. Supports MySQL with multiple transport options and built-in security features including SQL injection protection and data sanitization.16 npm5MIT
- FlicenseNot gradedqualityCmaintenanceEnables natural-language querying of Postgres and MongoDB databases in read-only mode, with PII masking and row/timeout guardrails, from any MCP client.-
- FlicenseAqualityCmaintenanceEnables read-only access to a PostgreSQL database, allowing users to inspect schema, generate SQL from natural language, and execute read-only queries via MCP.5-

sql-to-mcpofficial
AlicenseNot gradedqualityCmaintenanceEnables AI assistants to query PostgreSQL, MySQL, SQL Server, Oracle, and MongoDB databases through MCP with read-only, audited access.3AGPL 3.0