Metadata-Version: 2.4
Name: askql
Version: 0.25.0
Summary: Safe natural-language-to-SQL: validated, read-only queries across many SQL engines.
Author: askql maintainers
License: MIT
Project-URL: Homepage, https://github.com/TestAutomationArchitect/askql
Project-URL: Source, https://github.com/TestAutomationArchitect/askql
Project-URL: Changelog, https://github.com/TestAutomationArchitect/askql/blob/main/CHANGELOG.md
Keywords: sql,nl2sql,text-to-sql,llm,guardrails,read-only,database
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Database
Classifier: Topic :: Software Development :: Libraries
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: sqlglot>=23.0
Requires-Dist: pyyaml>=6.0
Provides-Extra: postgres
Requires-Dist: psycopg[binary]>=3.1; extra == "postgres"
Provides-Extra: redshift
Requires-Dist: psycopg2-binary>=2.9; extra == "redshift"
Provides-Extra: oracle
Requires-Dist: python-oracledb>=2.0; extra == "oracle"
Provides-Extra: mssql
Requires-Dist: pymssql>=2.2; extra == "mssql"
Provides-Extra: tsql
Requires-Dist: pymssql>=2.2; extra == "tsql"
Provides-Extra: jdbc
Requires-Dist: JayDeBeApi>=1.2; extra == "jdbc"
Requires-Dist: JPype1>=1.5; extra == "jdbc"
Provides-Extra: llm
Requires-Dist: anthropic>=0.40; extra == "llm"
Provides-Extra: llm-aws
Requires-Dist: anthropic[bedrock]>=0.40; extra == "llm-aws"
Provides-Extra: llm-vertex
Requires-Dist: anthropic[vertex]>=0.40; extra == "llm-vertex"
Provides-Extra: llm-openai
Requires-Dist: openai>=1.40; extra == "llm-openai"
Provides-Extra: embeddings
Requires-Dist: sentence-transformers>=2.2; extra == "embeddings"
Provides-Extra: api
Requires-Dist: fastapi>=0.110; extra == "api"
Requires-Dist: pydantic>=2.0; extra == "api"
Requires-Dist: uvicorn[standard]>=0.27; extra == "api"
Provides-Extra: mcp
Requires-Dist: mcp>=1.2; extra == "mcp"
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: ruff<0.18,>=0.17.5; extra == "dev"
Requires-Dist: mypy>=1.10; extra == "dev"
Requires-Dist: httpx>=0.27; extra == "dev"
Requires-Dist: types-PyYAML>=6.0; extra == "dev"
Dynamic: license-file

# askql — governed natural-language data access, for humans and AI agents

Turn a plain-English question into a **validated, read-only SQL** answer against your real
database — and get back not just rows, but **proof the query was correct, authorized, and
defensible.** Self-hosted. Nothing leaves your perimeter. Any SQL engine.

> **Correct *and* defensible.** Most tools optimize one: a raw LLM writes plausible SQL (often
> wrong, always ungoverned); a BI tool is governed but can't answer a novel question. askql does
> both — it grounds the question in your data's real meaning, and it can't be talked into running
> anything unsafe.

## Ground · Govern · Prove

Three things happen on every request. All three ship today.

- **Ground** — *understand what you're asking.* A per-database graph of your schema with join paths
  **proven against the data** (not guessed from names), business-term glossary, and the real values
  your columns hold. This is what turns "how many active customers" into the *right* SQL instead of
  a confident wrong one.
- **Govern** — *guard the execution.* Every query is parsed and checked by an **AST validator** (the
  single source of truth): read-only, no DDL/DML, no `SELECT *` on a bare table, sensitive columns
  blocked, a row cap and timeout enforced — then run through a least-privilege, rolled-back
  connection. The safety is *structural*: an agent can't prompt-inject its way past it.
- **Prove** — *record what happened.* Every query returns a **decision envelope** — what was decided
  (allow / allow-with-masking / deny), which controls applied, which tables and sensitive columns
  were touched, and an `evidence_id` that matches the audit log. Every answer is auditable.

---

## 30 seconds

```bash
pip install "askql[postgres]"          # or [oracle] [mssql] [redshift] [jdbc] … + [mcp] [llm]

askql init --dialect postgres          # scaffold config/ + docs/ + .env (auto-discovered from here)
#   edit .env + config/databases.yaml  # credentials + host:port/db + schemas

askql doctor                            # 10-point connectivity/health check
askql test-db                           # per-dialect smoke battery (incl. read-only check)

# build the grounding — with join paths PROVEN against the data:
askql scrape --include-views --build-graph --infer-fks --verify-edges --sample-values
askql learn ./saved_sql --examples      # (optional) mine real SQL for join paths + examples
askql bootstrap --dry-run               # (optional) draft domain rules from views + data profiling
askql model validate                    # is the grounding internally consistent?

# ask — with the reasoning and the governance decision exposed:
askql ask "how many active customers are there" --explain
```

`--explain` shows the question coverage, the tables selected, which glossary terms / examples fired,
and the governance decision + `evidence_id`. No LLM key? Generation falls back to your IDE agent
(Copilot / Claude Code) — the safety pipeline is identical.

> **Windows / restricted networks:** if the `askql` launcher errors (exit 126), use `python -m askql …`
> — shim-free and identical. Behind a corporate index, add `--index-url <your-mirror>`. If antivirus
> blocks a driver's binary wheel (e.g. psycopg2) on write into the venv, inherit the system driver
> instead: `python -m venv .venv --system-site-packages` then `pip install "askql==X.Y.Z" --no-deps`.

---

## Your AI agent is the UI

`askql init --agent copilot` (or `claude`, `cursor`; repeatable) writes instructions that teach
an IDE agent the askql workflow. The agent gets context, explores when the context is incomplete,
writes SQL, validates it, executes it and answers in a fixed shape. It never bypasses validation.
The files go to `.github/instructions/`, `.claude/skills/askql/` or `.cursor/rules/`.

askql ships an **MCP server** — nine governed, read-only tools an agent (Claude Desktop, Cursor,
VS Code, or any MCP client) drives directly: `list_tables`, `describe_table`, `search_columns`,
`column_values`, `compress_schema`, `validate_sql`, `query`, `check_freshness`, `ask`.
`search_columns` finds a column anywhere in the catalog, not just in the question's schema slice.
`column_values` returns a column's most frequent real values from a bounded sample, so the agent
filters on exact literals instead of guessing. It refuses sensitive columns and can be turned off
with `exploration_values: block`.

```bash
pip install "askql[mcp]"
askql-mcp                                # stdio server; point your MCP client's command here
#   (bound to one database + identity via T2S_DATABASE / T2S_MCP_USER)
```

Every tool runs through the *same* validator + RBAC + read-only executor + audit as the CLI, and
`query`/`ask` return the decision envelope. So an agent can explore the schema and run SQL — and
**cannot** run a `DELETE`, exceed its row cap, or touch a schema its identity isn't scoped to. The
`mcp` SDK is a lazily-imported opt-in extra: orgs that disallow MCP can ignore it entirely.

---

## How it's different

| | raw LLM agent | traditional BI tool | bare semantic layer | **askql** |
|---|:---:|:---:|:---:|:---:|
| Answers a novel NL question | ✅ *(often wrong)* | ❌ | ❌ | ✅ *grounded* |
| Knows your business definitions | ❌ | in-tool only | schema only | ✅ glossary + values + rules |
| **Join paths proven against the data** | ❌ | ❌ | ❌ | ✅ `--verify-edges` |
| **Unsafe SQL blocked before execution** | ❌ | n/a | ❌ | ✅ AST validator |
| **Survives prompt injection** | ❌ | n/a | ❌ | ✅ structural, not prompt-based |
| **Every answer carries provable evidence** | ❌ | ❌ | ❌ | ✅ decision envelope + audit |
| Works through your agents (MCP) | ✅ | ❌ | ❌ | ✅ |
| Runs on your real DB, real dialect | ✅ | ✅ | definitions only | ✅ Oracle/MSSQL/Redshift/PG/… |
| Open, reviewable, git-native context | ❌ | ❌ | partial | ✅ plain YAML/MD |
| Self-hosted; no data leaves your perimeter | depends | ✅ | ✅ | ✅ |

---

## The grounding is yours — reviewable, versioned, in git

Everything that makes answers accurate is **plain files you own**, not state locked in a UI:
`schema-graph.<db>.json`, `glossary.<db>.yaml`, `examples.<db>.yaml`, `corrections.<db>.yaml`,
`docs/domain-rules.<db>.md`, `synonyms.yaml`. Review changes in a PR; roll them back like code.

```bash
askql model                 # one summary of every grounding layer for a database
askql model validate        # catches silent accuracy-killers (0-edge graph, glossary→missing table…)
askql model explain "vip"   # how a term resolves — glossary hit? column? a real sampled value?
askql knowledge check       # run your examples / rules SQL / glossary against the live data
```

Curated knowledge can be wrong in a way nothing else catches. A documented join on the wrong key
still runs, but every joined value comes back NULL. `askql knowledge check` runs every example
and every `sql` block in your domain rules (read-only, row-capped). It reports queries that fail,
return 0 rows or return an all-NULL column, and probes each join on its own to flag one that
matches nothing. It also lists glossary tables and hint columns missing from the schema graph.
At query time, `ask()` adds a `data_warnings` entry when every column taken from a LEFT-joined
table is NULL in all the rows returned.

The grounding **improves with use**: `askql feedback` captures a confirmed example or a *correction*
("‘active’ means `status='A'`, not `'ACTIVE'`"), and `askql learn` turns your existing SQL into
proven join paths and labelled examples.

---

## Safety is measured, not asserted

```bash
askql eval                                  # 68-case adversarial red-team; exits non-zero on any escape
askql eval --accuracy --cases cases.json    # score generated SQL by result-match against gold answers
```

- Only `SELECT` (+ `UNION`/`INTERSECT`/`EXCEPT`). No DDL/DML or procedural code — even hidden in a CTE.
- No `SELECT *` on a bare table/view; explicit columns (`COUNT(*)` is fine). Row limit required on the
  outer query + capped (an aggregate with no `GROUP BY` returns one row and needs none).
- No system schemas or data-dictionary views, no sensitive columns (SSN, PASSWORD, …), no dangerous
  functions, no SQL smuggled in as a string argument, no DB links, no row locks.
- No side effects that survive a rollback (sequence advances, advisory/named locks), no whole-row
  serialization (`row_to_json(t)`) unless the role sees PII in full.
- Read-only session, rollback, timeout, and an audit record — on every query. Callers can lower the
  row cap and timeout, never raise them.

**You decide how strict.** Style-level rules are configurable per deployment — `allow`, `warn` (runs,
but the finding is returned and audited) or `block` — in `config/settings.yaml`:

```yaml
security:
  comments: block          # SQL comments / optimizer hints
  select_star: block       # SELECT * over a bare table or view
  row_limit: block         # missing / over-cap outer row limit
  cartesian_join: block    # CROSS JOIN, JOIN without ON
  dictionary_views: block  # unqualified DBA_ / V$ / PG_ / STL_ objects
  catalog_metadata: allow  # ALL_TAB_COLUMNS, SVV_COLUMNS, ...
  row_generator: block     # CONNECT BY without PRIOR
  row_lock: block          # FOR UPDATE / locking hints
allowed_package_functions:  # extra read-only Oracle package calls (dbms_random.* is built in)
  - utl_raw.bit_and
```

Writes, multiple statements, system schemas, SQL hidden in strings, network/file/exec functions, DB
links and sensitive columns are **never** configurable. An RBAC role can tighten these rules, never
loosen them, and `askql model validate` flags every relaxed rule.

The red-team is a **CI gate** (safety is a test that fails the build on a regression). The accuracy
harness gives you a *number* for your own question set. A **quality lint** runs on every generated
query: 17 rules for shapes that hide wrong answers, such as `NOT IN` over a nullable subquery,
`COUNT(*)` across a fan-out join, a join on part of a key, or Oracle `ROWNUM` before an aggregate.
`fix` findings make `ask()` regenerate the SQL, and `lint_rules` in settings re-grades or turns off
any rule. To steer generation the same way up front, `askql init --sql-standards` adds editable
house SQL standards to the prompt. Each accuracy case is scored **correct / wrong /
inconclusive**, with a reason:
- An answer with extra or reordered columns still matches the gold rows; set `match: strict` for
  exact equality, or `key_columns` to compare only the columns that identify the answer.
- `expected_sql` can list several equally valid gold queries.
- Gold queries run with a higher row cap (`--gold-max-rows`), so a capped "list all" answer is
  checked against the complete result.

---

## Bring your own model — any provider

Generation is pluggable; the safety pipeline is identical regardless. Set `T2S_LLM_PROVIDER`:
`anthropic` · `bedrock` (Claude on AWS) · `vertex` (Claude on GCP) · `openai` · `azure-openai` ·
`openai-compatible` (vLLM / Ollama / LM Studio / any self-hosted, **works air-gapped**) · `custom`
(your gateway) · *unset* → **BYO-LLM** (your IDE agent generates; no backend key). Nothing is locked
to one vendor, and no question or schema is sent anywhere you didn't configure.

---

## Also available

- **REST API** (`askql-api`) — run askql as a service so clients hold no drivers, JVM, or
  credentials; they call HTTP and get the same validator + RBAC + audit. `/validate`, `/compress`,
  `/query`, `/ask` (with `execute: false` for a dry run and `previous_question`/`previous_sql` for
  follow-ups).
- **Conversational follow-ups** — `askql ask --follow-up "now only last quarter"` refines your
  previous question; `askql ask --no-execute` prints validated SQL without running it. The MCP `ask`
  tool takes the same options.
- **Schema exploration before generation** — with `exploration: auto` (or `on`, or
  `askql ask --explore on`, or `exploration` on the MCP `ask` tool and REST `/ask`), the model can
  search every column in the catalog, open tables and read
  real column values before writing SQL. It then adds up to `exploration_max_tables` tables to the
  slice. This helps on large schemas where the right table or column isn't in the top-ranked slice.
  It's bounded (`exploration_max_steps` tool calls), read-only and RBAC-scoped, and never shows
  sensitive columns. It works with Anthropic and OpenAI-compatible providers, and `--explain` shows
  every tool call. Off by default because it costs extra LLM calls.
- **Docker image** — bundles a JRE so the universal JDBC transport works with no local Java/native
  drivers. Mount `config/`, `.env`, and vendor jars at runtime.
- **Python library** — `from askql import validate, compress, execute_sql_text, ask` — typed
  (`py.typed`), optional deps imported lazily, everything config-injectable.

```python
from askql import validate, ask, Settings

r = validate("SELECT id, name FROM app.users LIMIT 10", settings=Settings(dialect="postgres"))
assert r.ok, r.errors
result = ask("how many active users this week")  # needs an LLM provider configured
print(result["sql"], result["decision"]["evidence_id"])
```

---

## Access control (optional)

With an identity present (`$T2S_USER` / `--user`) and `config/access-control.yaml`, a role decides
which **environments**, **schemas**, **PII mode** (blocked / masked / full), **row cap**, and
**rate limit** apply — enforced by the executor and surfaced in the decision envelope. With no
identity it's single-user read-only mode — except for `prod` databases, which are refused until an
identity and a role exist. `pii=masked` redacts sensitive **values** (`***`) at the
executor — the model can't reveal what it never receives.

---

## Docs

| | |
|---|---|
| [ARCHITECTURE.md](ARCHITECTURE.md) | Design + the security hardenings over the source playbook |
| [CLAUDE.md](CLAUDE.md) | Operating instructions for the AI agent driving askql |
| [SHIPPING.md](SHIPPING.md) | Package / ship / install (wheel · internal index · Docker) |
| [CHANGELOG.md](CHANGELOG.md) | Release history |

**Read-only by construction.** askql executes only read-only `SELECT` through a least-privilege
connection; point it at whatever environment your access policy permits. MIT licensed.
