AI-Safe MCP Server for SQL
Source: Dev.to
Overview
Giving an AI direct database access sounds useful at first, but it quickly becomes dangerous. You want the model to inspect the schema, understand relationships, run queries, and help with analysis—yet you don’t want it to mutate data, execute unrestricted SQL, or return massive result sets because a prompt was vague.
ajan‑sql was created to address this problem. It is a small MCP server for SQL that provides AI clients with schema‑aware, read‑only SQL access behind a guard layer.
How It Works
- MCP server: Runs over
stdioand connects to a database viaDATABASE_URL. - Tools exposed:
list_tablesdescribe_tablelist_relationshipsrun_readonly_queryexplain_querysample_rows
- Schema resources:
schema://snapshotschema://table/{name}
The goal is simple: give LLMs useful database visibility without unsafe SQL execution.
Core Guard Rules
The server enforces read‑only, constrained queries:
- Allowed:
SELECTstatements only - Rejected:
INSERT,UPDATE,DELETEDROP,ALTER,TRUNCATE- Multi‑statement SQL
- SQL comments
- Defaults & Limits:
LIMIT 100applied automatically- Maximum query timeout: 5 seconds
- Maximum result size checks
These rules let the model inspect and analyze data while preventing any mutation.
Tools Detail
list_tables
Returns visible tables with metadata:
- Schema
- Table name
- Table comment
- Estimated row count
describe_table
Provides column‑level information:
- Columns, data types, nullability
- Default values
- Primary key metadata
- Unique constraints
- Foreign key references
- Index metadata
list_relationships
Lists foreign‑key relationships across the schema.
run_readonly_query
Executes guarded SELECT queries and returns:
- Normalized SQL
- Row count
- Execution duration
- Column metadata
- Result rows
explain_query
Runs EXPLAIN (FORMAT JSON) and returns:
- Query timing
- Raw plan
- Lightweight summary of the root plan node
sample_rows
Returns a limited sample from a table, optionally targeting specific columns.
Output Format
Each tool returns two fields:
content: short, human‑readable summarystructuredContent: machine‑friendly payload (e.g., JSON)
This dual format simplifies consumption by MCP‑compatible clients that prefer stable structured data over parsing free‑form text.
Installation
npm install -g ajan-sql