Text-to-SQL & Business Intelligence Guardrail Local MCP Server
Provides read-only SQL query execution against MySQL databases, including schema discovery via MCP resources, AST-based SQL validation, EXPLAIN cost guardrails, automatic LIMIT injection, and PII redaction.
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
π‘οΈ Text-to-SQL & Business Intelligence Guardrail Local MCP Server
Enterprise-Grade, Schema-Aware AI Data Analyst Bridge with AST Security & Cost Guardrails
Empowering business stakeholders to query production databases in plain Englishβwith zero risk of destructive mutations, full-table scan lockups, or PII data leaks.
π Table of Contents
Related MCP server: MySQL ReadOnly MCP Server
π¨ The Problem Statement
In data-driven organizations, business managers and analysts face two major bottlenecks when extracting insights from relational databases:
The SQL & Schema Bottleneck: Non-technical stakeholders depend on data engineering teams for routine ad-hoc queries because they do not know SQL syntax or complex multi-table schemas.
The Enterprise AI Trust Gap: While Large Language Models (LLMs) can translate natural language into SQL, enterprise teams refuse to connect LLMs directly to production databases due to four critical vulnerabilities:
Destructive Mutations & Prompt Injection: A misunderstood prompt or adversarial injection could execute
DROP TABLE,DELETE,UPDATE, or stacked queries (; TRUNCATE TABLE).Database CPU & Memory Exhaustion: An unoptimized
SELECT *without aLIMITclause or an unindexed query triggering a full-table scan across millions of rows can lock production tables.Context Window Bloat: Dumping an entire 200-table schema into an LLM prompt wastes tokens, slows inference, and causes column-name hallucinations.
PII Data Leakage: Raw query results frequently expose sensitive Personally Identifiable Information (
email,phone,ssn,password_hash) to external model providers.
β How This Server Solves It
This MCP server acts as an intelligent security, performance, and privacy firewall between the AI assistant and your MySQL database:
Capability | Mechanism | Impact |
100% Read-Only Enforcement |
| Blocks all DML/DDL ( |
Runaway Query Protection | Programmatic AST | Automatically injects or caps |
Pre-Flight Cost Guardrails | Automated MySQL | Rejects queries triggering full-table scans ( |
Token-Efficient Discovery | Granular MCP Resources ( | Serves exact |
Zero-Leak PII Redaction | Result-set column interception | Automatically masks sensitive columns ( |
ποΈ System Architecture & Request Pipeline
End-to-End Interactive Flow
flowchart TB
subgraph ClientLayer ["π§π» Client & AI Analyst Layer"]
User(["π€ Business Analyst\n(Plain English Prompt)"])
Claude["π€ Claude Desktop\n(AI Data Analyst)"]
User <-->|"1. Ask Question /\n6. Visual Charts & Insights"| Claude
end
subgraph MCPLayer ["π‘οΈ FastMCP BI Guardrail Server (Async Python)"]
direction TB
Resource["π MCP Resources\ndb://schemas/list\ndb://schemas/{table_name}"]
subgraph GuardrailPipeline ["π 4-Stage Security & Performance Firewall"]
direction LR
AST["1οΈβ£ sqlglot AST Parser\nβ’ Allow SELECT/UNION only\nβ’ Block DDL/DML & SLEEP()\nβ’ Auto-inject LIMIT 100"]
Explain["2οΈβ£ EXPLAIN Cost Check\nβ’ Inspect Index Usage\nβ’ Block Full Scans > 50k rows"]
Pool["3οΈβ£ aiomysql Pool\nβ’ Lifespan Managed\nβ’ Async Non-Blocking I/O"]
Mask["4οΈβ£ PII Redactor\nβ’ Masks email, ssn,\n phone, credit_card"]
AST --> Explain --> Pool --> Mask
end
end
subgraph DBLayer ["ποΈ Data Storage Layer (Defense-in-Depth)"]
MySQL[("π¬ MySQL 8.0+ Database\nDedicated Read-Only User\n(GRANT SELECT ONLY)")]
end
Claude <-->|"2. Schema Discovery"| Resource
Claude -->|"3. Generated SQL\nexecute_readonly_sql()"| AST
Resource <-->|"SHOW CREATE TABLE\n+ 3 Masked Samples"| Pool
Pool <-->|"4. Execute Validated\nRead-Only Query"| MySQL
Mask -->|"5. Sanitized JSON Payload"| Claude
style ClientLayer fill:#1e1b4b,stroke:#6366f1,stroke-width:2px,color:#fff
style MCPLayer fill:#0f172a,stroke:#10b981,stroke-width:2px,color:#fff
style GuardrailPipeline fill:#1e293b,stroke:#f59e0b,stroke-width:1.5px,color:#fff
style DBLayer fill:#172554,stroke:#3b82f6,stroke-width:2px,color:#fffStep-by-Step Execution Lifecycle
[1] USER PROMPT βββΊ "Which region had the highest revenue last month, and are there outliers?"
[2] SCHEMA LOOKUP βββΊ Claude reads `db://schemas/list` βββΊ inspects `db://schemas/sales_orders`
[3] SQL GENERATION βββΊ Claude writes: `SELECT region, SUM(total_amount) FROM sales_orders GROUP BY region`
[4] AST GUARDRAIL βββΊ sqlglot verifies pure SELECT + rewrites query with `LIMIT 100`
[5] COST GUARDRAIL βββΊ MySQL `EXPLAIN` verifies index usage & safe row scan count (< 50,000)
[6] ASYNC EXECUTION βββΊ Pooled `aiomysql` connection runs query & redacts any PII columns
[7] BI DELIVERY βββΊ Claude receives clean JSON & renders an interactive revenue bar chartπ§ Core Technologies & Terminologies
Technology / Concept | Role in Architecture | Why It Matters |
MCP (Model Context Protocol) | Open protocol standardizing LLM-to-data integrations via Resources and Tools. | Decouples database security logic from the LLM client so any MCP-compatible AI can safely query data. |
FastMCP | High-level Python framework for building MCP servers over | Provides clean decorators ( |
AST (Abstract Syntax Tree) | Tree representation of syntactic SQL structure generated by | Unlike regex (which attackers bypass using comments like |
| Zero-dependency SQL parser, transpiler, and AST optimizer. | Parses MySQL dialect queries, blocks forbidden AST node types, and programmatically appends |
| Asynchronous MySQL client built on Python | Prevents database I/O from blocking the event loop, enabling high concurrency across simultaneous queries. |
Connection Pooling | Pre-warmed pool of reusable TCP database connections ( | Eliminates per-query TCP/TLS handshake latency and protects MySQL from connection exhaustion. |
| FastMCP startup/shutdown lifecycle hook. | Initializes the |
MySQL | Query optimizer execution plan diagnostic. | Exposes |
Defense-in-Depth | Multi-layered security posture. | Combines Python AST validation + |
π Project Structure
Text_to_SQL_Business_Intelligence_and_Guardrail_MCP_Server/
βββ .venv/ # Isolated Python virtual environment managed by uv
βββ src/ # Application source directory
β βββ main.py # FastMCP server, AST guardrails, EXPLAIN checks, and PII redaction
βββ .env # Local database credentials (gitignored β never commit!)
βββ .gitignore # Excludes .env, .venv, and Python cache artifacts
βββ pyproject.toml # Project metadata and locked dependencies
βββ README.md # Architecture and setup documentationβοΈ Prerequisites & Installation
1. System Requirements
Python 3.11+
MySQL Server 8.0+ & MySQL Workbench
uv(Fast Python package & environment manager)Node.js /
npx(Required for the MCP Inspector andmcp-remotebridge)
2. Clone & Install Dependencies
git clone https://github.com/<your-username>/<your-repo-name>.git
cd <your-repo-name>
# Install dependencies using uv
uv sync
# Or add packages directly:
uv add fastmcp sqlglot aiomysql pydantic python-dotenvπ Environment Configuration (.env)
Create a .env file in the root directory of the project. (Ensure .env is added to your .gitignore file.)
EXAMPLE
MYSQL_HOST=localhost
MYSQL_PORT=3306
MYSQL_USER=readonly_analyst
MYSQL_PASSWORD=ChangeMe123!
MYSQL_DATABASE=company_biVariable | Description |
| Hostname or IP address of your MySQL server ( |
| TCP port MySQL is listening on (default: |
| Dedicated MySQL user account configured with read-only ( |
| Password for the read-only MySQL account. |
| Target database schema exposed to the BI server. |
ποΈ Database Setup (MySQL Workbench)
Execute the following SQL script in MySQL Workbench to initialize a sample database, populate test records (including an email column to verify PII masking), and create a restricted read-only MySQL user:
-- 1. Create the target analytics database
CREATE DATABASE IF NOT EXISTS company_bi;
USE company_bi;
-- 2. Create a sample sales table with an indexed date column and a PII column
CREATE TABLE IF NOT EXISTS sales_orders (
order_id INT AUTO_INCREMENT PRIMARY KEY,
customer_name VARCHAR(100),
email VARCHAR(150),
region VARCHAR(50),
total_amount DECIMAL(10, 2),
order_date DATE,
INDEX idx_order_date (order_date)
);
-- 3. Insert sample records
INSERT INTO sales_orders (customer_name, email, region, total_amount, order_date) VALUES
('Aarav Sharma', 'aarav@example.com', 'North America', 14500.00, '2026-11-10'),
('Priya Patel', 'priya@example.com', 'Europe', 8200.50, '2026-11-12'),
('Rohan Verma', 'rohan@example.com', 'North America', 22000.00, '2026-11-15'),
('Sneha Nair', 'sneha@example.com', 'Asia Pacific', 4300.75, '2026-11-18');
-- 4. Create a strictly read-only database user (Defense-in-Depth)
CREATE USER IF NOT EXISTS 'readonly_analyst'@'localhost' IDENTIFIED BY 'ChangeMe123!';
GRANT SELECT ON company_bi.* TO 'readonly_analyst'@'localhost';
FLUSH PRIVILEGES;π Running & Testing the Server
Option A: Interactive Testing via FastMCP Dev & MCP Inspector
uv run fastmcp dev main.pyThis launches the browser-based MCP Inspector where you can:
Browse
db://schemas/listanddb://schemas/sales_ordersunder Resources to verify DDL retrieval and PII masking.Invoke
execute_readonly_sqlandexplain_query_planunder Tools to test valid aggregations and verify destructive queries are blocked.
Option B: Remote Streamable HTTP Server Mode
Ensure the entrypoint at the bottom of main.py is configured for HTTP transport:
if __name__ == "__main__":
mcp.run(transport="http", host="0.0.0.0", port=8000)Start the server:
uv run python main.pyYour remote MCP endpoint is now live at http://localhost:8000/mcp.
π₯οΈ Connecting to Claude Desktop
Add the server configuration to your claude_desktop_config.json:
Windows:
%APPDATA%\Claude\claude_desktop_config.jsonmacOS:
~/Library/Application Support/Claude/claude_desktop_config.json
{
"mcpServers": {
"mysql-bi-analyst": {
"command": "npx",
"args": [
"-y",
"mcp-remote",
"http://localhost:8000/mcp"
]
}
}
}Restart Claude Desktop completely and prompt:
"Inspect my database schema, calculate total revenue by region, and render a visual bar chart."
π§ͺ Security & Performance Guardrail Matrix
Test Case | Input SQL Query | Guardrail Action & Output |
Valid BI Aggregation |
| Rewrites AST to append |
Destructive Mutation |
|
|
Stacked SQL Injection |
|
|
Time-Based DoS Attack |
|
|
Unbounded Full Scan |
|
|
PII Column Query |
| Automatically masks sensitive fields: |
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelogβ¦
This server cannot be deployed
Maintenance
Related MCP Connectors
Safe, read-only Postgres and MySQL access for AI agents. Audit log + column-level controls.
Query Postgres, MySQL, SQL Server, Oracle, BigQuery, ClickHouse and Redshift from your AI client.
Query, explore, and manage your databases through natural conversation.
Query PostgreSQL databases in plain English β LLM-generated, safety-validated SQL.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceEnables natural language database operations on MySQL databases with AI integration, supporting CRUD operations, schema inspection, and audit logging with built-in security features including SQL injection protection and permission controls.MIT
- AlicenseAqualityDmaintenanceEnables AI assistants to safely query MySQL databases with read-only access, featuring SQL injection protection, connection pooling, and automatic query limits for secure database exploration.4MIT
- FlicenseNot gradedqualityDmaintenanceEnables AI assistants to securely interact with MySQL databases, including listing tables, viewing schemas, and executing read-only SQL queries through natural language.7-
- AlicenseNot gradedqualityDmaintenanceEnables AI tools to interact with MySQL databases through natural language, including schema browsing, queries, CRUD operations, with destructive actions gated behind user approval.64 npm1MIT