AI-Safe MCP Server for SQL

Published: (March 23, 2026 at 03:31 AM EDT)
2 min read
Source: Dev.to

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 stdio and connects to a database via DATABASE_URL.
  • Tools exposed:
    • list_tables
    • describe_table
    • list_relationships
    • run_readonly_query
    • explain_query
    • sample_rows
  • Schema resources:
    • schema://snapshot
    • schema://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: SELECT statements only
  • Rejected:
    • INSERT, UPDATE, DELETE
    • DROP, ALTER, TRUNCATE
    • Multi‑statement SQL
    • SQL comments
  • Defaults & Limits:
    • LIMIT 100 applied 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 summary
  • structuredContent: 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
0 views
Back to Blog

Related posts

Read more »