KacaSQL
by halovina
README.md
# KacaSQL
> **See through your database with AI — without ever breaking it**.Strict read-only, multi-connection Model Context Protocol (MCP) server for **PostgreSQL** and **MySQL**, purpose-built for backend developers.
<img src="https://github.com/halovina/kacasql/actions/workflows/ci.yml/badge.svg" alt="CI" width="80" />
*Kaca* means **glass** in Indonesian: your AI coding assistant can clearly inspect schemas, relationships, indexes, sample data, and query execution plans—while a strict read-only barrier keeps your data untouchable.
---
## Key Features (PostgreSQL & MySQL)
- **2-Layer Strict Read-Only Enforcement**:
1. **AST Validation (**`sqlglot`**)**: Dialect-aware (`postgres` & `mysql`) validation blocking multi-statement SQL, DML/DDL, write-CTEs (`WITH ... DELETE`), `SELECT INTO` / `INTO OUTFILE`, `LOAD DATA INFILE`, `FOR UPDATE`, and dangerous DB functions (`pg_read_file`, `set_config`, `dblink*`, `LOAD_FILE`, `GET_LOCK`, `BENCHMARK`, etc.).
2. **Database Session Guard**: Every query runs inside a strict read-only transaction (`BEGIN TRANSACTION READ ONLY` + `statement_timeout` on PostgreSQL; `START TRANSACTION READ ONLY` + `max_execution_time` on MySQL) and always ends in `ROLLBACK`.
- **Multi-Engine & Multi-Connection by Design**: Connect to PostgreSQL and MySQL across `local`, `staging`, and `prod-replica` in a single server using declarative YAML + lazy connection pooling (`psycopg` v3 async & `aiomysql`).
- **Zero Credential Leakage**: DSNs are loaded lazily from environment variables and scrubbed from all logs and error responses.
- **Context-Window & PII Protection**: Automatic glob-based PII masking (`*password*`, `*token*`, `nik`, etc.), configurable hard row caps, and long-cell truncation.
- **9 Focused Backend-Dev Tools + 1 Resource + 2 Prompts**: Lean surface area so LLMs pick the right tool every time.
---
## Available MCP Primitives
### Tools
| Tool | Purpose |
| --- | --- |
| `list_connections` | List configured connections (engine, environment, mode, description — never credentials) |
| `list_schemas` | List schemas with table & view counts |
| `list_tables` | List tables/views with estimated row counts, sizes, and comments |
| `search_schema` | Search tables & columns across schemas by keyword (e.g. `tenant_id`) |
| `describe_table` | Full technical inspection: columns, types, defaults, PKs, indexes, constraints, FKs, comments |
| `get_table_relationships` | Map outbound & inbound foreign keys |
| `get_table_sample` | Fetch 1–20 sample rows with automatic PII masking & truncation |
| `execute_read_query` | Run a validated single `SELECT` query with timeout, row cap, and PII masking |
| `explain_query` | Inspect `EXPLAIN (FORMAT JSON)` / `ANALYZE` plans safely inside a rolled-back read-only transaction |
### Resource & Prompts
- **Resource**: `db://{connection_id}/overview` — Database engine version, active extensions/plugins, server timezone, and schemas.
- **Prompts**: `debug-slow-query`, `explore-table-context`.
---
## Quick Start
### 1. Clone and install dependencies with `uv`
```bash
git clone https://github.com/halovina/kacasql.git
cd kacasql
uv sync
```
### 2. Configure connections
Copy the example config and export your DSN environment variable(s):
```bash
cp config/connections.example.yaml connections.yaml
export LOCAL_PG_DSN="postgresql://readonly_user:password@localhost:5432/mydb"
```
### 3. Connect KacaSQL to Your MCP Client
> **Tip (macOS / Linux GUI apps):** Desktop apps like Antigravity IDE and Claude Desktop often do not inherit `~/.local/bin` in `PATH`. Run `which uv` in your terminal and use the full path (for example `/Users/<you>/.local/bin/uv`) as `"command"` if `"uv"` cannot be found.
#### Option A: Antigravity IDE
1. Open (or create) your global Antigravity MCP config file:
- **macOS / Linux**: `~/.gemini/config/mcp_config.json`
2. Add the `kacasql` server under `"mcpServers"`:
```json
{
"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"
}
}
}
}
```
3. Verify the connection in Antigravity IDE via **Additional Options (**`...`**) > MCP Servers** — you should see `kacasql` connected with all 9 tools available.
#### Option B: Claude Desktop
1. Open (or create) your Claude Desktop config file:
- **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
- **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
- **Linux**: `~/.config/Claude/claude_desktop_config.json`*(In Claude Desktop, you can also open **Settings > Developer > Edit Config**.)*
2. Add the `kacasql` server under `"mcpServers"`:
```json
{
"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"
}
}
}
}
```
3. **Quit and reopen Claude Desktop** completely (Cmd+Q on macOS) so it loads the new MCP server.
4. Click the tools icon in the chat input to verify `kacasql` tools are active.
#### Multi-Connection Example (`env`)
If your `connections.yaml` defines multiple databases (`local_pg`, `staging_pg`, `prod_replica_pg`), simply pass each referenced `dsn_env` variable in the `"env"` block:
```json
"env": {
"KACASQL_CONFIG": "/absolute/path/to/kacasql/connections.yaml",
"LOCAL_PG_DSN": "postgresql://kacasql:kacasql_dev_password@localhost:5439/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"
}
```
#### Example Prompts to Try
Once connected, try asking your AI assistant:
- *"List all configured database connections in KacaSQL."*
- *"Search the schema on* `local_pg` *for any table with a* `tenant_id` *column."*
- *"Describe the* `orders` *table and show its inbound & outbound relationships."*
- *"Show 5 sample rows from* `users` *— verify that sensitive columns are masked."*
- *"Run EXPLAIN ANALYZE on* `SELECT * FROM orders WHERE tenant_id = 101` *and suggest index improvements."*
#### Troubleshooting
- `spawn uv ENOENT` **/ command not found**: Replace `"uv"` with the full binary path returned by `which uv` (e.g. `/Users/<your-user>/.local/bin/uv`).
- **Config file not found**: Make sure `KACASQL_CONFIG` points to an absolute path and that `connections.yaml` exists (copy from `config/connections.example.yaml`).
- **Inspecting logs**: KacaSQL emits all logs and JSON audit entries strictly to `stderr` (never `stdout`). You can test startup manually via:
```bash
KACASQL_CONFIG=./connections.yaml uv run kacasql --log-level DEBUG
```
---
## Development & Testing
### Unit Tests (no database required)
```bash
uv run pytest tests/unit/
```
### Integration Tests (Docker PostgreSQL 16 + MySQL 8.4)
```bash
docker compose -f docker/docker-compose.yml up -d --wait
KACASQL_TEST_PG_DSN="postgresql://kacasql:kacasql_dev_password@localhost:5439/ecommerce" \
KACASQL_TEST_MYSQL_DSN="mysql://kacasql:kacasql_dev_password@127.0.0.1:3309/ecommerce" \
uv run pytest -v
```
---
## Roadmap
- **Phase 1 (Done)**: PostgreSQL Adapter, Strict Read-Only, Multi-Connection, Backend Developer toolset.
- **Phase 2 (Done)**: MySQL Adapter (`MySQLAdapter` via `aiomysql`), MySQL AST guardrails & Docker MySQL 8 integration tests.
- **Phase 3 (Planned)**: Modular toolsets (`dba`, `analytics`), optional semantic context YAML, opt-in controlled Write/DDL mode (`dry_run`, `max_affected_rows`, `WHERE` guardrails), & Streamable HTTP transport.
## License
MIT — see [LICENSE](./LICENSE).
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues