Intelligent Database DBA & Schema Migration Guardrail MCP Server
Provides DBA and schema migration guardrail tools for SQLite databases, including EXPLAIN QUERY PLAN analysis, schema and index inspection, rollback-safe DDL dry runs, optimal index suggestions, and demo database seeding.
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., "@Intelligent Database DBA & Schema Migration Guardrail MCP Server dry-run this migration and flag risky patterns: ALTER TABLE orders DROP COLUMN status;"
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.
Intelligent Database DBA & Schema Migration Guardrail MCP Server
An autonomous, production-grade Database Administrator (DBA) MCP Server built on the Model Context Protocol (MCP). It gives AI coding agents (Claude Desktop, Cursor, Windsurf, and custom MCP clients) database-internals expertise: query-plan decomposition, index coverage analysis, transactional migration guardrails, and DDL risk detection.
Architecture & Execution Flow
The server runs over standard I/O (stdio). stdout carries only JSON-RPC framing; operational logs go to stderr and server.log.
sequenceDiagram
autonumber
actor Agent as AI Agent
participant MCP as Stdio MCP Server
participant DB as SQLite Engine
participant Plan as EXPLAIN QUERY PLAN
participant Guard as Transaction Guardrail (SAVEPOINT / Rollback)
participant Out as Diagnostic Output
Agent->>MCP: tools/call (JSON-RPC over stdio)
MCP->>DB: Route request and validate parameters (Zod)
alt Query analysis: explain_query_plan / suggest_optimal_indexes
MCP->>DB: Execute SQL statement
DB->>Plan: EXPLAIN QUERY PLAN <sql>
Plan-->>DB: Scan tree (SCAN / SEARCH / TEMP B-TREE)
DB-->>MCP: Raw query-plan rows
MCP->>Out: Cost level, warnings, index recommendations
else Migration dry-run: dry_run_migration
MCP->>Guard: Candidate DDL statement
Guard->>DB: SAVEPOINT dry_run_migration
Guard->>DB: Execute candidate DDL
Guard->>Guard: Static risk scan (DROP / NOT NULL / TRUNCATE)
Guard->>DB: ROLLBACK TO SAVEPOINT dry_run_migration
Guard->>DB: RELEASE SAVEPOINT dry_run_migration
Guard->>Out: Risk level and rollback confirmation
end
Out-->>MCP: Markdown diagnostic document
MCP-->>Agent: Structured MCP tool responseThe SQLite engine is powered by better-sqlite3. By default it runs as an in-memory :memory: database, so no database file is created. Set the SQLITE_DB_PATH environment variable to open and inspect a real SQLite database file on disk. Every dry-run migration is executed inside a named savepoint and always rolled back.
Related MCP server: Postgres MCP Pro
Core DBA MCP Tools
The server registers 5 tools. All responses are returned as MCP text content containing Markdown.
1. explain_query_plan
Executes EXPLAIN QUERY PLAN on a SQL query, decomposes the scan tree, and flags full table scans, temporary B-tree sorts, correlated subqueries, and missing indexes.
Parameters
Name | Type | Required | Description |
|
| Yes | The SQL SELECT query to analyze. |
|
| No | Optional table to focus the analysis on. |
Example input
{
"sqlQuery": "SELECT * FROM orders WHERE user_id = 42 AND status = 'pending' ORDER BY created_at DESC"
}Example output
## Query Plan Analysis
**SQL:** `SELECT * FROM orders WHERE user_id = 42 AND status = 'pending' ORDER BY created_at DESC`
**Cost Level:** HIGH
**Full Table Scan Detected:** ❌ YES
**Index Scans Used:** ❌ NONE
### Raw EXPLAIN QUERY PLAN Output[3] parent=0 | SCAN orders [20] parent=0 | USE TEMP B-TREE FOR ORDER BY
### ⚠️ Warnings
- ⚠️ FULL TABLE SCAN detected on table "orders" — no suitable index found
- ⚠️ Temporary B-Tree sort detected — ORDER BY without supporting index
### 💡 Recommendations
- Consider adding an index on the WHERE/JOIN column(s) of table "orders"
- Add an index that covers the ORDER BY column(s) to avoid filesort
### 🚨 Tables Requiring Indexes
- **orders**: Run `suggest_optimal_indexes` with tableName="orders" for precise recommendations2. inspect_table_schema
Returns column types, nullability, default values, primary keys, foreign keys, index details, and a quantitative index-coverage percentage.
Parameters
Name | Type | Required | Description |
|
| Yes | The name of the table to inspect. |
Example input
{
"tableName": "orders"
}Example output
## Table Schema: `orders`
**Columns (7):**
id INTEGER NULLABLE 🔑 PK
user_id INTEGER NOT NULL
product_name TEXT NOT NULL
amount REAL NOT NULL
status TEXT NOT NULL DEFAULT 'pending'
created_at TEXT NOT NULL
shipped_at TEXT NULLABLE
**Primary Key(s):** id
**Foreign Keys:**
- user_id → users(id) ON DELETE NO ACTION
**Indexes (0):**
(no indexes)
**Index Coverage:** 14% of columns indexed
**Unindexed Columns:** user_id, product_name, amount, status, created_at, shipped_at
> ⚠️ 6 unindexed columns detected — query performance may suffer without targeted indexes3. dry_run_migration
Executes a DDL migration inside an isolated SAVEPOINT dry_run_migration, performs a static risk assessment, captures the resulting schema, and always rolls back. The database state is guaranteed to be unchanged.
Parameters
Name | Type | Required | Description |
|
| Yes | The DDL SQL statement to dry-run. It is fully rolled back. |
Guardrail policy matrix
Pattern | Severity | Risk |
| 🔴 CRITICAL | Fails on populated tables |
| 🔴 CRITICAL | Irreversible data loss |
| 🔴 CRITICAL | Irreversible data destruction |
| 🔴 CRITICAL | Unlogged row deletion |
| 🟠 DANGEROUS | Query performance regression |
| 🟠 DANGEROUS | May error when table is absent |
| 🟡 WARNING | Breaks dependent views, triggers, queries |
| 🟡 WARNING | Non-idempotent migration |
Example input
{
"migrationSql": "ALTER TABLE orders ADD COLUMN priority_score INTEGER NOT NULL"
}Example output
## Dry-Run Migration Report
**Migration SQL:**
```sql
ALTER TABLE orders ADD COLUMN priority_score INTEGER NOT NULLExecution Result: ❌ FAILED: Cannot add a NOT NULL column with default value NULL Transaction Rolled Back: ✅ YES — database state unchanged Execution Time: 2ms Risk Level: 🔴 CRITICAL
⚠️ Detected Issues
🔴 Adding NOT NULL column without DEFAULT will fail on non-empty tables
💡 Guardrail Recommendations
Add the column as nullable first, backfill data, then apply NOT NULL constraint
🚨 CRITICAL RISK: This migration has been blocked from production execution. Address all issues before applying.
A safe migration such as `ALTER TABLE orders ADD COLUMN discount REAL DEFAULT 0.0` returns `Risk Level: ✅ SAFE`, `Transaction Rolled Back: ✅ YES`, and executes successfully before being reverted.
---
### 4. `suggest_optimal_indexes`
Parses `WHERE` predicates, multi-table `JOIN` keys, and `ORDER BY` columns, then generates production-ready `CREATE INDEX IF NOT EXISTS` statements with performance rationale. At least one of `sqlQuery` or `tableName` must be provided.
**Parameters**
| Name | Type | Required | Description |
|------|------|----------|-------------|
| `sqlQuery` | `string` | Conditional | SQL query to analyze for index opportunities. |
| `tableName` | `string` | Conditional | Table name for coverage-based recommendations. |
**Example input**
```json
{
"tableName": "orders"
}Example output
## Index Optimization Recommendations
### Suggested Indexes for `orders`
- **user_id**: `CREATE INDEX IF NOT EXISTS idx_orders_user_id ON orders (user_id);`
- **product_name**: `CREATE INDEX IF NOT EXISTS idx_orders_product_name ON orders (product_name);`
- **amount**: `CREATE INDEX IF NOT EXISTS idx_orders_amount ON orders (amount);`
- **status**: `CREATE INDEX IF NOT EXISTS idx_orders_status ON orders (status);`
- **created_at**: `CREATE INDEX IF NOT EXISTS idx_orders_created_at ON orders (created_at);`
- **shipped_at**: `CREATE INDEX IF NOT EXISTS idx_orders_shipped_at ON orders (shipped_at);`
---
**6 index(es) recommended.** Apply them in a migration and re-run `explain_query_plan` to verify improvement.For a query input, the tool can additionally emit composite indexes (for example (user_id, status, created_at)) and JOIN-key indexes.
5. seed_demo_database
Initializes high-volume relational benchmark tables (users, orders, transactions) with realistic data that is intentionally unindexed, so the other DBA tools have a realistic workload to analyze.
Parameters
Name | Type | Required | Description |
|
| No | Rows per table. Integer from |
Example input
{
"rowCount": 1000
}Example output
## ✅ Demo Database Seeded Successfully
| Table | Rows | Indexes |
|-------|------|---------|
| users | 1000 | PRIMARY KEY only (intentionally unindexed) |
| orders | 3000 | PRIMARY KEY only (intentionally unindexed) |
| transactions | 2000 | PRIMARY KEY only (intentionally unindexed) |
**Next steps to test the DBA tools:**
1. Run `explain_query_plan` with `SELECT * FROM orders WHERE user_id = 42 AND status = 'pending'`
2. Run `suggest_optimal_indexes` with the same query
3. Run `dry_run_migration` with `ALTER TABLE orders ADD COLUMN discount REAL NOT NULL`orders receives 3x rowCount rows and transactions receives 2x rowCount rows.
Quick Start
Prerequisites
Node.js 20+
npm 9+
Install, build, and test
git clone https://github.com/thedailyhub31-blip/intelligent-db-dba-mcp-server.git
cd intelligent-db-dba-mcp-server
npm install
npm run build
npm testThe automated test harness connects to the compiled server over stdio and runs 10 checks:
Tool discovery
Demo database seeding
Table schema inspection
Full-table-scan detection
Index recommendations
Safe migration dry-run
Dangerous
NOT NULLmigration detectionCritical
DROP TABLEdetectionRollback verification
Multi-table JOIN plan analysis
AI Agent Integration
Claude Desktop
Add the server to your Claude Desktop configuration:
macOS:
~/Library/Application Support/Claude/claude_desktop_config.jsonWindows:
%APPDATA%\Claude\claude_desktop_config.json
{
"mcpServers": {
"intelligent-db-dba": {
"command": "node",
"args": [
"/absolute/path/to/intelligent-db-dba-mcp-server/dist/index.js"
]
}
}
}On Windows, use an absolute path such as C:\\Users\\<username>\\...\\dist\\index.js.
Cursor
In Settings → Features → MCP Servers → Add New MCP Server:
Name:
intelligent-db-dbaType:
commandCommand:
node <absolute-path-to-repo>/dist/index.js
Database Configuration (SQLITE_DB_PATH)
By default the server opens an in-memory :memory: SQLite database, which is ideal for the bundled demo tools. To inspect a real SQLite database file, pass the SQLITE_DB_PATH environment variable. When set, the server resolves the path and opens the file on disk with better-sqlite3; when omitted, it falls back to :memory:.
{
"mcpServers": {
"intelligent-db-dba": {
"command": "node",
"args": [
"/absolute/path/to/intelligent-db-dba-mcp-server/dist/index.js"
],
"env": {
"SQLITE_DB_PATH": "/path/to/database.db"
}
}
}
}On Windows, escape backslashes in the path (for example "SQLITE_DB_PATH": "C:\\data\\app.db"). The target file does not need to exist beforehand; better-sqlite3 creates it if it is missing.
Warning:
seed_demo_databasedrops and recreates theusers,orders, andtransactionstables. Do not run it against a production database file.
Project Structure
.
├── src/
│ ├── index.ts # MCP server, tool registration, request routing
│ ├── db/
│ │ ├── databaseEngine.ts # better-sqlite3 engine, plan analysis, schema inspection
│ │ └── migrationGuardrail.ts # SAVEPOINT dry-runs and DDL risk assessment
│ ├── tools/
│ │ └── dbaTools.ts # Zod schemas and tool handlers
│ └── utils/
│ └── logger.ts # stderr + server.log logging
├── scripts/
│ └── test-client.ts # 10-check MCP stdio test harness
├── package.json
├── tsconfig.json
├── LICENSE
└── README.mdTransaction Isolation and Guardrail Safety
Clean stdio framing — diagnostics are written to
stderrandserver.log;stdoutcarries only JSON-RPC.Deterministic rollback — every dry run is executed inside a named savepoint:
SAVEPOINT dry_run_migration; -- execute candidate DDL ROLLBACK TO SAVEPOINT dry_run_migration; RELEASE SAVEPOINT dry_run_migration;Static risk scanning — DDL is matched against destructive patterns before it is presented as safe.
License
Released under the MIT License.
Available Tools
5 toolsdry_run_migrationA
Executes a DDL migration inside an isolated SAVEPOINT, evaluates risks, then ALWAYS rolls back. Returns risk assessment and guardrail warnings.
Inputs: migrationSql (required).
explain_query_planA
Executes EXPLAIN QUERY PLAN on a SQL query and flags FULL TABLE SCANs, missing indexes, and high-cost operations.
Inputs: sqlQuery (required), tableName.
inspect_table_schemaA
Returns detailed schema info for a table: column types, nullability, primary keys, foreign keys, and index coverage metrics.
Inputs: tableName (required).
seed_demo_databaseB
Initializes the in-memory database with high-volume sample tables (users, orders, transactions) intentionally without indexes.
Inputs: rowCount.
suggest_optimal_indexesB
Analyzes a SQL query or table and generates precise CREATE INDEX recommendations with performance improvement rationale.
Inputs: sqlQuery, tableName.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 5 tools
Each tool targets a distinct action: plan explanation, schema inspection, migration dry-run, index suggestion, and demo seeding. There is mild conceptual overlap between explain_query_plan and suggest_optimal_indexes since both analyze query performance, but their outputs (diagnostics vs. CREATE INDEX recommendations) are clearly delineated.
All names use snake_case and begin with an action verb, forming a readable pattern. dry_run_migration deviates slightly as a compound modifier+noun rather than a clean verb_noun, but overall the convention is predictable.
Five tightly scoped tools, each filling a clear role in the query-optimization and migration-safety workflow. Nothing feels redundant or padded.
The guardrail workflow (inspect schema, dry-run migration, suggest indexes, explain plans) is coherent, but there is no way to list tables/indexes or actually apply a migration, and index recommendations cannot be executed or dropped. seed_demo_database is a demo aid rather than a true domain operation, leaving notable lifecycle gaps.
Maintenance
Related MCP Connectors
Deterministic safety, correctness & cost gate that vets Postgres SQL before your AI agent runs it.
Review your AI agent's database changes on your schema, with plain-language risk, before they run.
AI agents propose database changes as reviewable requests — no direct write access.
Safe, read-only Postgres and MySQL access for AI agents. Audit log + column-level controls.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceEnables AI assistants to safely explore, analyze, and maintain PostgreSQL databases with read-only mode by default, SQL injection prevention, query performance analysis, and optional write operations.67 npmApache 2.0
- AlicenseAqualityDmaintenanceEnables AI agents to analyze, optimize, and safely interact with PostgreSQL databases, including health checks, index recommendations, query planning, and SQL execution with read-only and production protection modes.15MIT
- AlicenseNot gradedqualityCmaintenanceEnables agents to safely inspect a PostgreSQL database read-only: discovering schemas and tables, running guarded SELECT/EXPLAIN queries, and getting plan summaries with index suggestions. Access is constrained by schema allowlists, denied-column redaction, row caps, and a JSON-lines audit trail.MIT
- AlicenseBqualityCmaintenanceEnables AI coding agents to perform deterministic database architecture audits and performance engineering for PostgreSQL and MySQL, covering migration analysis with schema health scoring, ESR-based composite index recommendations, N+1 query detection, EXPLAIN plan diagnosis, transaction and deadlock analysis, partitioning and archival design, and capacity or configuration tuning. It also generates phased Expand & Contract runbooks that turn blocking DDL into zero-downtime production migrations.8MIT