KacaSQL Docs • v1.1.0 • Open Source (MIT)

KacaSQL Documentation

Official guide for KacaSQL v1.1.0 — the strict read-only, multi-connection Model Context Protocol (MCP) server for PostgreSQL and MySQL with production guardrails. Safe enough to point directly at production read-replicas without risking writes, resource exhaustion, or data leaks.

Release v1.1.0 Engines PostgreSQL & MySQL Runtime Python 3.11+ / uvx Transport stdio (FastMCP) License MIT
Jump to section

Overview

Kaca means glass in Indonesian — transparent yet protective. KacaSQL sits between your AI coding assistant and your PostgreSQL or MySQL databases so the AI can inspect schemas, indexes, relationships, sample rows, and EXPLAIN plans while multi-layer read-only and performance guardrails guarantee your data and replicas stay safe.

What’s New in v1.1.0 — Production Guardrails & Performance Protection
  • Execution Resource Caps & Streaming Payload Truncation: Millisecond timeout_ms, hard max_payload_bytes (default 50 KB), and structured _meta truncation hints for LLM self-correction.
  • Granular Access Control: allowed_schemas and blocked_tables (exact, schema.table, and glob patterns) enforced across both discovery tools and sqlglot AST checks.
  • Full PII Protection (Column + Value Level): Glob column masking plus ReDoS-safe value-level regex presets (credit_card, jwt, id_nik, id_npwp, email) and custom patterns for free-text/JSONB columns.
  • EXPLAIN-First Full Table Scan Blocker: Automatically enabled on environment: prod to stop expensive full scans before execution, with a limit-aware exception for simple LIMIT peeks.
  • Privacy-First Local JSONL Audit Trail: Opt-in audit log with default SQL literal redaction, SHA-256 sql_hash, POSIX 0600 permissions, and size-capped rotation.
  • Declarative guardrails: YAML Block & CLI --version: 100% backward-compatible with v1.0 flat config fields.
Built for Backend Workflows

Instead of copy-pasting DDL snippets into chat or risking fragile system-prompt rules, KacaSQL exposes 9 focused MCP tools, 1 overview resource, and 2 debugging prompts over standard MCP stdio. Connections are pooled lazily (psycopg v3 async and aiomysql) for sub-second startup.

Prerequisites

Requirement Recommended Notes
uv / uvx Latest (astral.sh/uv) Runs KacaSQL directly from GitHub without cloning the repo.
Python Python 3.11+ Managed automatically by uvx if not already installed.
Database Engines PostgreSQL 12+ / MySQL 8.0+ Use a dedicated read-only database user for defense in depth.
MCP Client Antigravity IDE, Claude Desktop, Cursor Works with any MCP client supporting local stdio servers.

Quick Start (No Clone Required)

Get KacaSQL connected to your AI assistant in under 2 minutes using uvx. You only need a single YAML file and your MCP client's JSON config.

  1. 1

    Create connections.yaml

    Create a declarative config file (for example at ~/.config/kacasql/connections.yaml). Notice that credentials are never hardcoded in YAML — only the environment variable name (dsn_env) is referenced.

    ~/.config/kacasql/connections.yaml
    connections:
      local_pg:
        engine: postgres
        dsn_env: LOCAL_PG_DSN
        environment: local
        access_mode: read_only
        description: "Local PostgreSQL database"
  2. 2

    Connect KacaSQL to Your MCP Client

    Choose your AI coding client below and paste the server configuration under "mcpServers".

    macOS / Linux GUI PATH Tip

    Desktop GUI apps like Antigravity IDE and Claude Desktop often do not inherit ~/.local/bin in PATH. Run which uvx in your terminal and use the full binary path (e.g. /Users/<your-user>/.local/bin/uvx) as "command".

    Open or create ~/.gemini/config/mcp_config.json (macOS / Linux), add the kacasql entry pointing to release v1.1.0, then verify under Additional Options (...) → MCP Servers.

    ~/.gemini/config/mcp_config.json
    {
      "mcpServers": {
        "kacasql": {
          "command": "/Users/<your-user>/.local/bin/uvx",
          "args": [
            "--from",
            "git+https://github.com/halovina/kacasql.git@v1.1.0",
            "kacasql"
          ],
          "env": {
            "KACASQL_CONFIG": "/Users/<your-user>/.config/kacasql/connections.yaml",
            "KACASQL_AUDIT_LOG": "~/.kacasql/audit.jsonl",
            "LOCAL_PG_DSN": "postgresql://readonly_user:password@localhost:5432/mydb"
          }
        }
      }
    }

    Open Settings → Developer → Edit Config (or edit directly at ~/Library/Application Support/Claude/claude_desktop_config.json on macOS, %APPDATA%\Claude\claude_desktop_config.json on Windows, or ~/.config/Claude/claude_desktop_config.json on Linux).

    claude_desktop_config.json
    {
      "mcpServers": {
        "kacasql": {
          "command": "/Users/<your-user>/.local/bin/uvx",
          "args": [
            "--from",
            "git+https://github.com/halovina/kacasql.git@v1.1.0",
            "kacasql"
          ],
          "env": {
            "KACASQL_CONFIG": "/Users/<your-user>/.config/kacasql/connections.yaml",
            "KACASQL_AUDIT_LOG": "~/.kacasql/audit.jsonl",
            "LOCAL_PG_DSN": "postgresql://readonly_user:password@localhost:5432/mydb"
          }
        }
      }
    }

    Quit and reopen Claude Desktop completely (⌘ + Q on macOS), then click the tools icon in the chat input to confirm all 9 KacaSQL tools are active.

    Add KacaSQL to your global Cursor MCP file (~/.cursor/mcp.json) or project-level .cursor/mcp.json, then reload MCP servers in Cursor Settings.

    ~/.cursor/mcp.json
    {
      "mcpServers": {
        "kacasql": {
          "command": "/Users/<your-user>/.local/bin/uvx",
          "args": [
            "--from",
            "git+https://github.com/halovina/kacasql.git@v1.1.0",
            "kacasql"
          ],
          "env": {
            "KACASQL_CONFIG": "/Users/<your-user>/.config/kacasql/connections.yaml",
            "KACASQL_AUDIT_LOG": "~/.kacasql/audit.jsonl",
            "LOCAL_PG_DSN": "postgresql://readonly_user:password@localhost:5432/mydb"
          }
        }
      }
    }

    If you want to contribute or run KacaSQL directly from local source code:

    Terminal
    git clone https://github.com/halovina/kacasql.git
    cd kacasql
    uv sync
    cp config/connections.example.yaml connections.yaml

    Then point your MCP client to uv run:

    mcp_config.json (Local Source)
    {
      "mcpServers": {
        "kacasql": {
          "command": "/Users/<your-user>/.local/bin/uv",
          "args": ["run", "--directory", "/absolute/path/to/kacasql", "kacasql"],
          "env": {
            "KACASQL_CONFIG": "/absolute/path/to/kacasql/connections.yaml",
            "LOCAL_PG_DSN": "postgresql://readonly_user:password@localhost:5432/mydb"
          }
        }
      }
    }

Multi-Connection Environment Block

When your connections.yaml defines multiple targets (e.g. local_pg, staging_pg, prod_replica_pg, or MySQL instances), simply pass each referenced dsn_env variable inside the "env" block. Pools are initialized lazily on first use.

Multi-connection "env" block
"env": {
  "KACASQL_CONFIG": "/Users/<your-user>/.config/kacasql/connections.yaml",
  "KACASQL_AUDIT_LOG": "~/.kacasql/audit.jsonl",
  "LOCAL_PG_DSN": "postgresql://kacasql:kacasql_dev_password@localhost:5439/ecommerce",
  "LOCAL_MYSQL_DSN": "mysql://kacasql:kacasql_dev_password@127.0.0.1:3309/ecommerce",
  "STAGING_PG_DSN": "postgresql://readonly_user:secret@staging-db.internal:5432/app",
  "PROD_REPLICA_PG_DSN": "postgresql://readonly_user:secret@prod-replica.internal:5432/app"
}

First Prompts to Try

Once KacaSQL shows as connected, verify your setup with these prompts:

Prompt to Ask Your AI Assistant Expected KacaSQL Tool
"List all configured database connections in KacaSQL." list_connections
"Search the schema on local_pg for any table with a tenant_id column." search_schema
"Describe the orders table and show its inbound & outbound relationships." describe_table, get_table_relationships
"Show 5 sample rows from users — verify that sensitive columns and inline PII values are masked." get_table_sample
"Run EXPLAIN ANALYZE on SELECT * FROM orders WHERE tenant_id = 101 and suggest index improvements." explain_query

connections.yaml Configuration Reference

KacaSQL v1.1.0 introduces a declarative guardrails: block at both global defaults and per-connection levels, allowing tighter timeouts, payload caps, schema/table access control, EXPLAIN-first full-scan blocking, and column/value-level PII redaction on production replicas.

100% Backward Compatible with v1.0

Legacy v1.0 flat fields (query_timeout_sec, hard_max_rows, masked_columns) continue to work seamlessly alongside the v1.1 guardrails: block. Connection strings remain strictly dsn_env-only.

config/connections.example.yaml (v1.1+)
# Global defaults applied to all connections unless overridden
defaults:
  pool_min_size: 1
  pool_max_size: 4
  # Optional local JSONL audit trail (or set KACASQL_AUDIT_LOG env var)
  # audit_log_path: ~/.kacasql/audit.jsonl
  audit_redact_sql_literals: true
  audit_max_sql_chars: 2000
  audit_max_bytes: 10485760
  guardrails:
    timeout_ms: 15000
    default_max_rows: 50
    max_rows: 200
    max_cell_chars: 1000
    max_payload_bytes: 51200
    scan_row_threshold: 100000
    pii_value_presets:
      - "credit_card"
      - "jwt"
  masked_columns:
    - "*password*"
    - "*secret*"
    - "*token*"
    - "api_key*"
    - "credit_card*"
    - "nik"

connections:
  local_pg:
    engine: postgres
    dsn_env: LOCAL_PG_DSN
    environment: local
    access_mode: read_only
    description: "Local PostgreSQL database for backend development"

  local_mysql:
    engine: mysql
    dsn_env: LOCAL_MYSQL_DSN
    environment: local
    access_mode: read_only
    description: "Local MySQL 8 database for backend development"

  staging_pg:
    engine: postgres
    dsn_env: STAGING_PG_DSN
    environment: staging
    access_mode: read_only
    guardrails:
      timeout_ms: 10000
    description: "Staging database for integration debugging"

  prod_replica_pg:
    engine: postgres
    dsn_env: PROD_REPLICA_PG_DSN
    environment: prod
    access_mode: read_only
    description: "Production read-replica (strict read-only, EXPLAIN-first & PII masked)"
    guardrails:
      timeout_ms: 5000
      max_rows: 100
      max_payload_bytes: 51200
      block_full_table_scan: true   # defaults to true automatically for environment: prod
      scan_row_threshold: 100000
      allowed_schemas:
        - "public"
        - "analytics"
      blocked_tables:
        - "audit_logs"
        - "billing_tokens"
        - "private.*"
      custom_pii_columns:
        - "email"
        - "phone*"
        - "npwp"
        - "mother_maiden_name"
      pii_value_presets:
        - "credit_card"
        - "jwt"
        - "id_nik"
        - "id_npwp"
      custom_pii_value_patterns:
        - name: "internal_api_key"
          pattern: "kaca_live_[A-Za-z0-9]{24,}"

Configuration Field Reference

Field Scope Description
engine Connection Database engine: postgres or mysql.
dsn_env Connection Environment variable name holding the connection URI. Never returned to LLMs.
environment Connection Label such as local, dev, staging, or prod. Automatically enables block_full_table_scan when set to prod.
access_mode Connection Enforces strict read_only execution guardrails.
guardrails.timeout_ms Default / Override Millisecond query timeout enforced at session level (SET LOCAL statement_timeout in PG; SET SESSION max_execution_time in MySQL). Legacy query_timeout_sec still supported.
guardrails.default_max_rows / max_rows Default / Override Default row limit (50) and hard row ceiling (200) to prevent context-window flooding. Legacy hard_max_rows still supported.
guardrails.max_cell_chars Default / Override Maximum character length per returned cell (default 1000) before truncation.
guardrails.max_payload_bytes Default / Override Hard JSON payload size cap (default 51200 / 50 KB) via streaming row assembly with structured _meta truncation hints.
guardrails.block_full_table_scan Default / Override Pre-flight EXPLAIN guard. Defaults to true on environment: prod and false on non-prod (always explicitly overridable).
guardrails.scan_row_threshold Default / Override Estimated row threshold (default 100000) above which full table scans are blocked.
guardrails.allowed_schemas Default / Override Allowlist of schemas/databases permitted across discovery tools, overview resource, and SQL AST checks.
guardrails.blocked_tables Default / Override Denylist supporting exact names, schema.table, and glob patterns (e.g. audit_*, private.*).
masked_columns / guardrails.custom_pii_columns Default / Override Glob patterns for column-name PII masking (merged from global defaults + per-connection overrides), replaced with ***MASKED***.
guardrails.pii_value_presets Default / Override Built-in ReDoS-safe value-level regex redaction presets: credit_card, jwt, id_nik, id_npwp, email.
guardrails.custom_pii_value_patterns Default / Override List of { name, pattern } custom regex rules (validated fail-fast at config load) to redact sensitive tokens inside free-text or JSONB columns.
audit_log_path / audit_* Defaults Opt-in local JSONL audit trail (or KACASQL_AUDIT_LOG env var) with audit_redact_sql_literals (default true), audit_max_sql_chars (2000), and audit_max_bytes (10485760 / 10 MB).
pool_min_size / pool_max_size Default / Override Lazy async connection pool bounds (psycopg v3 / aiomysql).

Multi-Layer Security & Production Guardrails

Relying on prompt instructions like "please do not run DELETE" is not a security boundary. In v1.1.0, every query passing through KacaSQL clears deterministic AST, access-control, query-plan, session, and output guardrails before returning a single byte to the LLM:

01 • LAYER 1

AST & Access Control

sqlglot blocks writes, CTEs, risky funcs & enforces schema/table ACLs.

02 • LAYER 2

EXPLAIN-First Guard

Pre-flight plan check blocks full table scans above threshold (on by default in prod).

03 • LAYER 3

DB Session Guard

READ ONLY transaction + ms timeout_ms + forced ROLLBACK.

04 • OUTPUT

PII, Payload & Audit

Column + value PII redaction, 50 KB byte cap, _meta hints & JSONL audit.

Layer 1: Dialect-Aware AST Validation (sqlglot)

Parses SQL into an Abstract Syntax Tree for postgres or mysql rather than fragile regexes. Permits only a single read statement (SELECT, UNION, VALUES) and recursively rejects:

  • Multi-statement SQL (; chaining) and all DML/DDL
  • Write-CTEs (WITH deleted AS (DELETE ...))
  • SELECT INTO, INTO OUTFILE, LOAD DATA INFILE, FOR UPDATE
  • Dangerous functions: pg_read_file, set_config, dblink*, LOAD_FILE, GET_LOCK, BENCHMARK

Layer 3: Database Session Guard

Even if an edge-case query passed parsing, the database engine itself enforces read-only isolation and millisecond timeouts on every execution — including EXPLAIN ANALYZE:

  • PostgreSQL: BEGIN TRANSACTION READ ONLY + SET LOCAL statement_timeout (ms)
  • MySQL: START TRANSACTION READ ONLY + SET SESSION max_execution_time (ms)
  • Always Rolled Back: Every transaction unconditionally terminates with ROLLBACK
  • Zero Credential Leakage: DSNs are read lazily from env vars and scrubbed from all error responses and stderr logs

EXPLAIN-First Full Table Scan Blocker

To protect production read-replicas from runaway I/O, KacaSQL runs a lightweight pre-flight EXPLAIN (FORMAT JSON) (PostgreSQL) or EXPLAIN FORMAT=JSON (MySQL) before executing execute_read_query whenever block_full_table_scan is enabled.

  • Environment-Aware Default: Automatically enabled (true) when environment: prod, and false for local, dev, or staging (always explicitly overridable).
  • PostgreSQL Detection: Catches Seq Scan and Parallel Seq Scan (accounting for Workers Planned) exceeding scan_row_threshold (default 100,000), with a limit-aware exception so harmless peeks like SELECT * FROM orders LIMIT 5 (without filters or blocking sorts) are not falsely rejected.
  • MySQL Detection: Catches ALL and full index scans above scan_row_threshold.
  • Self-Correcting Error Hints: Blocked queries return a compact offending_scans summary and rewrite hint so the AI can immediately narrow predicates using indexed columns.

Granular Access Control (allowed_schemas & blocked_tables)

Restrict which schemas and tables an AI assistant is allowed to see or query using two-layer enforcement applied consistently across all discovery/inspection tools (list_schemas, list_tables, search_schema, describe_table, get_table_relationships, get_table_sample), db://{connection_id}/overview, and sqlglot AST table/schema checks.

Rules support exact table names (billing_tokens), schema-qualified names (private.billing_tokens), and glob patterns (audit_*, private.*), while safely ignoring local CTE aliases so legitimate queries with CTEs never trigger false positives.

Full PII Protection & Streaming Payload Caps

Column + Value-Level PII Redaction

Column names are matched against global masked_columns merged with per-connection custom_pii_columns and replaced with ***MASKED***. In addition, v1.1.0 scans string and JSONB values with ReDoS-safe presets (credit_card, jwt, id_nik, id_npwp, email) plus fail-fast validated custom_pii_value_patterns.

Streaming max_payload_bytes & _meta Hints

Result rows are assembled in a stream capped at max_payload_bytes (default 51200 / 50 KB), max_rows, and max_cell_chars. Whenever results are truncated, KacaSQL appends structured _meta metadata (truncation_reason, returned_rows, payload_bytes, hint) so the AI knows whether to project fewer columns, tighten WHERE, or lower LIMIT.

Privacy-First Local JSONL Audit Trail

Enable a persistent local audit log by setting defaults.audit_log_path in connections.yaml or passing KACASQL_AUDIT_LOG (e.g., ~/.kacasql/audit.jsonl) in your MCP client’s "env" block.

  • Default SQL Literal Redaction (audit_redact_sql_literals: true): Replaces string and numeric literals with placeholders via sqlglot AST before writing — preventing audit logs from becoming a shadow PII store — while recording a deterministic SHA-256 sql_hash.
  • Secure & Resilient File Handling: Enforces POSIX 0600 permissions, truncates oversized SQL strings at audit_max_sql_chars (default 2000), performs size-capped single-backup rotation at audit_max_bytes (default 10 MB), and fails safely without crashing tool calls on I/O errors.

MCP Primitives Reference

KacaSQL intentionally keeps a lean surface area of 9 backend-focused tools, 1 resource, and 2 prompts so AI models choose the right inspection step deterministically. Filter tools by category below:

Tool Name Category Purpose
list_connections Discovery List configured connections (engine, environment, access_mode, description — never hosts or credentials).
list_schemas Discovery List permitted non-system schemas/databases with table and view counts (filtered by allowed_schemas).
list_tables Discovery List permitted tables, views, and materialized views with estimated row counts, storage sizes, and comments.
search_schema Discovery Search permitted table and column names across schemas by keyword (e.g., find every table containing tenant_id).
describe_table Inspection Full technical inspection: columns, data types, defaults, primary keys, indexes, constraints, foreign keys, and comments.
get_table_relationships Inspection Map both outbound (references) and inbound (referenced by) foreign keys (automatically filters blocked tables).
get_table_sample Inspection Fetch 1–20 sample rows with column & value-level PII redaction, cell truncation, and max_payload_bytes cap.
execute_read_query Query Run a validated single SELECT query with AST, access control, EXPLAIN-first guard, ms timeout, row/payload caps, and PII masking.
explain_query Performance Inspect EXPLAIN (FORMAT JSON) or EXPLAIN ANALYZE plans safely inside a rolled-back read-only transaction.

Resource & Built-In Prompts

Resource · db://{connection_id}/overview

Provides instant database engine context to the AI: PostgreSQL or MySQL version, active extensions/plugins (such as pg_trgm, postgis, pgvector), server timezone, and permitted schemas.

Prompts · debug-slow-query & explore-table-context

Guided multi-step prompt workflows that instruct the AI to inspect indexes and run explain_query for optimization advice, or map out an unfamiliar table's schema and relationships end-to-end.

Troubleshooting

spawn uvx ENOENT or spawn uv ENOENT

GUI MCP clients on macOS and Linux often launch with a minimal system PATH that excludes ~/.local/bin. Find the exact path in your terminal with which uvx (or which uv) and put that absolute path into "command".

Config file not found

Ensure KACASQL_CONFIG in your client's "env" block uses an absolute path (avoid ~ or relative paths like ./connections.yaml) and that the file exists and is readable.

Inspecting Logs, CLI Version & Testing Startup Manually

KacaSQL emits all logs strictly to stderr (and optionally writes redacted JSONL audit entries to audit_log_path / KACASQL_AUDIT_LOG — never polluting MCP stdout). You can verify the installed version or test startup with verbose diagnostics from your terminal:

Check version & debug startup via terminal
uvx --from git+https://github.com/halovina/kacasql.git@v1.1.0 kacasql --version
KACASQL_CONFIG=./connections.yaml uv run kacasql --log-level DEBUG

Development & Testing

KacaSQL is open-source under the MIT license and verified with 112 automated tests (103 unit tests + 9 live Docker PostgreSQL 16 & MySQL 8.4 integration and multi-scenario stress tests).

Unit Tests (No Database Required)

Run unit test suite
uv run pytest tests/unit/

Integration & Multi-Scenario Stress Tests (Docker PostgreSQL 16 + MySQL 8.4)

Run full integration & stress suite
docker compose -f docker/docker-compose.yml up -d --wait
KACASQL_TEST_PG_DSN="postgresql://kacasql:kacasql_dev_password@127.0.0.1:5439/ecommerce" \
KACASQL_TEST_MYSQL_DSN="mysql://kacasql:kacasql_dev_password@127.0.0.1:3309/ecommerce" \
  uv run pytest -v -s
docker compose -f docker/docker-compose.yml down

Roadmap

  • DONE v1.0: PostgreSQL (psycopg v3 async) & MySQL (aiomysql) adapters, 2-layer strict read-only guardrails, multi-connection YAML, 9 backend developer MCP tools, and credential-safe DSN handling.
  • DONE v1.1: Production guardrails (guardrails: YAML block, millisecond timeout_ms, streaming max_payload_bytes + _meta hints, allowed_schemas & blocked_tables, column + value-level PII redaction, environment- & limit-aware EXPLAIN-first full-scan blocker, and privacy-first local JSONL audit trail).
  • PLANNED v1.2: AI Context Engineering & Smart Schema Discovery (get_schema_subgraph, fast TABLESAMPLE masked sampling, YAML Semantic Annotations / Data Dictionary, and structured EXPLAIN index advisor).
  • PLANNED v1.3: Built-in SSH Bastion Tunneling, SQLite (mode=ro) & Redis/Valkey read-only drivers, and MovaDB encrypted vault integration.
Contribute or Report an Issue

KacaSQL is open-source (MIT). Explore the source code, inspect the v1.1.0 release notes, or open pull requests on github.com/halovina/kacasql.