QueryPilot README

The full upstream README, mirrored for reference. Install config, tool schemas, adoption signals and our own overview live on the QueryPilot listing page.

QueryPilot

PyPI Python License: MIT CI

Safe, measurable SQL for AI agents.

QueryPilot sits between an LLM agent and your database. It gives the agent read-only, policy-checked SQL tools for any SQLAlchemy database. It grounds the model in your real schema, feeds errors back so the model can fix its SQL, and ships an eval harness that proves the SQL is correct and stays correct.

querypilot eval run terminal report

Quickstart

Terminal
pip install querypilot
querypilot demo

querypilot demo writes a small SaaS database (querypilot-demo.db), runs a validated query against it and shows a blocked DELETE. Then try:

Dockerfile
querypilot schema --db sqlite:///querypilot-demo.db              # list tables
querypilot schema --db sqlite:///querypilot-demo.db invoices     # columns and keys
querypilot sql --db sqlite:///querypilot-demo.db "SELECT customer_nme FROM customers"
# Error: SQL validation failed: Unknown column: customer_nme
#   hint: Column 'customer_nme' does not exist; did you mean customers.customer_name, ...?
querypilot ask --db sqlite:///querypilot-demo.db "Which customers have the highest ARR?"

ask uses OpenAI or Anthropic when OPENAI_API_KEY or ANTHROPIC_API_KEY is set (--generator openai-compatible covers Ollama, vLLM and LM Studio). Without a key it falls back to an offline demo generator.

For your own database, querypilot init --db postgresql://analyst@db.internal/prod writes a querypilot.yaml that holds the connection, business hints, column descriptions and access policy. Every command, the MCP server and QueryPilot.from_config() read it, so you can drop --db from then on. For a URL with a password or connection options, generated project configs reference ${QUERYPILOT_DATABASE_URL}. Set that variable through the CLI or MCP host environment.

In Python:

Dockerfile
from querypilot import QueryPilot

qp = QueryPilot.connect("postgresql://analyst@db.internal/prod")  # dialect inferred from the URL

result = qp.execute_sql("SELECT plan, COUNT(*) FROM subscriptions GROUP BY plan")
print(result.sql)   # rewritten with a LIMIT, validated against the live schema
print(result.rows)

Connect any database

QueryPilot.connect(url) infers the SQL dialect from the URL and introspects tables, views, primary and foreign keys, and comments. It also accepts a SQLAlchemy Engine.

DatabaseURLInstall
SQLitesqlite:///app.dbincluded
PostgreSQLpostgresql://user:pass@host/dbincluded
DuckDBduckdb:///analytics.duckdbpip install "querypilot[duckdb]"
MySQL / MariaDBmysql+pymysql://user:pass@host/dbpip install "querypilot[mysql]"
SQL Servermssql+pyodbc://…pip install "querypilot[mssql]"
Snowflakesnowflake://user@account/db/schemapip install "querypilot[snowflake]"
BigQuerybigquery://project/datasetpip install "querypilot[bigquery]"
Redshiftredshift+psycopg2://…pip install "querypilot[redshift]"
Trino / Oracle / Databrickstrino://…, oracle+oracledb://…, databricks://…querypilot[trino], [oracle], [databricks]

Fully qualified names. Warehouses name tables in three parts, and QueryPilot accepts all of them: BigQuery project.dataset.table (backticked or not, hyphens included), Snowflake database.schema.table, and Databricks and Trino catalog.schema.table. The connection's own project, database or catalog (from the URL) may be named or left out. Tables from another one are introspected when you list their schema with its catalog, e.g. schemas=["bigquery-public-data.samples"], and must then be named in full: samples.wikipedia means the connection's own project, never another one's. Allowlists and access policies keyed without a catalog don't reach another catalog's tables; key them in full (bigquery-public-data.samples.wikipedia) to grant or filter them. Denials (blocked_tables) apply however the table is named.

Every query is validated with sqlglot for the target dialect. Validation means one statement, SELECT only, and known tables and columns. It also blocks dangerous functions for each engine, such as pg_read_file, DuckDB's read_csv, MySQL's LOAD_FILE and SQL Server's xp_cmdshell. Execution then adds the engine's own guard: a read-only transaction on Postgres, MySQL and Oracle, a read-only connection on DuckDB, and a statement timeout where the engine supports one. Every query runs in a transaction that is always rolled back. For warehouses that have no read-only session mode, connect with a read-only role.

Give your agent the tools

Every integration exposes the same small toolset. Results are compact JSON, and errors come back as {"ok": false, "error": ..., "hints": [...]} rather than as exceptions, so the agent can correct itself.

ToolWhat it does
list_tablesTables and views the policy allows, with comments
describe_tableColumns, types, keys, comments and sample values for the named tables
search_schemaFinds tables and columns relevant to a question
validate_sqlChecks SQL and returns the rewritten form, errors and "did you mean" hints
run_sqlValidates and runs SQL, returning rows with a truncated flag at max_rows
ask_databaseNatural language → validated SQL → rows (only when an LLM generator is configured)

MCP (Claude Code, Claude Desktop, Cursor, VS Code, Windsurf):

bash
querypilot mcp-config claude-code --db postgresql://analyst@db/prod
# claude mcp add querypilot --env QUERYPILOT_DATABASE_URL=... -- /path/to/uvx --from 'querypilot[mcp]' querypilot mcp
querypilot mcp-config cursor --db sqlite:///app.db   # prints the mcpServers JSON block

The generated config uses the absolute path to uvx, which avoids the common spawn uvx ENOENT failure. Pass --runner python to launch the current environment instead. Every tool carries the MCP readOnlyHint annotation. querypilot mcp --transport streamable-http --port 8000 serves the same tools on loopback. For remote clients, place an authenticated HTTPS gateway in front of the local listener.

OpenAI / Anthropic tool calling:

python
tools = qp.as_openai_tools()            # Chat Completions; qp.toolkit().openai_responses_tools() for Responses
tools = qp.as_anthropic_tools()
result = qp.handle_tool_call(tool_call.name, tool_call.arguments)  # dict or JSON string in, dict out

Agent frameworks:

server.ts
from querypilot.integrations import (
    as_langchain_tools,          # LangChain / LangGraph StructuredTools
    as_llamaindex_tools,         # LlamaIndex FunctionTools
    as_openai_agents_tools,      # OpenAI Agents SDK FunctionTools
    as_claude_agent_mcp_server,  # Claude Agent SDK in-process MCP server
    claude_agent_allowed_tools,
    as_functions,                # plain typed functions: Pydantic AI, smolagents, CrewAI, ADK
)

tools = as_langchain_tools(qp, naming="langchain")  # sql_db_list_tables, sql_db_schema, sql_db_query, ...

naming="langchain" reuses the tool names from the community SQLDatabaseToolkit (no longer maintained), so existing prompts keep working. Install the matching extra: querypilot[langchain], [llamaindex], [openai-agents], [claude-agent] or [mcp]. See examples/07_frameworks.py.

Protect any Postgres client: querypilot proxy (prototype)

The proxy needs no SDK. It is a Postgres wire-protocol server that applies the same validator and access policy to every statement, whatever the client. That covers psql, psycopg, SQLAlchemy and LangChain, an existing MCP database server, Cursor or Claude Code, and BI tools. Point the client's connection string at the proxy instead of the database:

Terminal
pip install "querypilot[proxy]"
querypilot proxy --upstream postgresql://readonly@db/prod --listen 127.0.0.1:6543 --policy querypilot.yaml

psql "postgresql://agent@127.0.0.1:6543/prod" -c "SELECT email FROM customers"
npx -y @modelcontextprotocol/server-postgres postgresql://agent@127.0.0.1:6543/prod   # unchanged MCP server

Every statement then gets the following:

  • Read-only enforcement. Writes, DDL, COPY and SET of anything outside a small allowlist are rejected. Allowed statements run in a READ ONLY transaction on a session that defaults to read-only, so COMMIT; DROP TABLE … is rejected.
  • Row filters and the row cap. The rewritten SQL is what reaches the database, so the policy's row_filters hold under joins, subqueries and CTEs, and LIMIT is capped at max_rows.
  • Masking. masking_rules apply by output position and follow aliases and derived tables. Masked columns can be projected directly. Filtering, joining, grouping, sorting, or computing expressions with them is rejected.
  • Errors an agent can repair. A rejection is a normal Postgres error with a SQLSTATE, the validator's message, and a HINT, for example Column 'nope' does not exist. Columns of orders: id, customer_id, ….
  • Audit. One JSONL record per statement goes to --audit-log, with the client's SQL, the SQL that ran, the row count, and the client user and application.

Use schema-qualified names such as sales.orders in SQL and policy when the same table name exists in multiple schemas. Bare restrictions cover every matching table. Allowlist entries must identify a single relation.

Driver handshakes, SET/SHOW of formatting settings, and catalog queries for psql \d and ORM reflection pass through an allowlist. Catalog queries that could read data, such as pg_stats or query_to_xml(...), are rejected. The policy file is a normal querypilot.yaml, and its database_url is used when you omit --upstream. The proxy listens on loopback. Remote clients need an authenticated, encrypted tunnel. See the proxy documentation for connection limits and protocol coverage.

Watch the SQL your agent already runs: querypilot trace and hooks

Some query tools can't sit behind QueryPilot, for example Palantir Foundry's MCP SQL tool. For those, QueryPilot reads what the agent did instead. trace import pairs every query tool call in Claude Code transcripts with its result. hooks install logs new calls live. trace doctor reports the failure rate by class, retry chains, latency and stalls, and says for each problem whether it is best fixed in the tool, the prompt, or the data:

bash
querypilot trace doctor                        # reads ~/.claude/projects
querypilot trace doctor --output report.md     # redacted, shareable
querypilot trace doctor --since 7d             # weekly health report
querypilot hooks install --guard --max-rows 200

With --guard, a PreToolUse hook validates each query against schemas cached from the agent's own schema calls. It denies unknown columns with a "did you mean" reply before the query reaches the warehouse, blocks date arithmetic on DATE columns stored as epoch milliseconds, enforces a row cap, and asks for named columns instead of SELECT * on wide datasets. With FOUNDRY_HOST and FOUNDRY_TOKEN set, it fetches a dataset's schema from Foundry's API before the first query on it, and refetches a cached schema before blocking on it, so a rebuilt dataset never blocks a valid query. Ontology SQL (query_ontology_using_sql, the Ontology MCP's ontology-sql) and query_ontology_objects are checked too, against view_foundry_object_type schemas, and the foundry dialect sends back functions Ontology SQL rejects, with IF() rewritten as CASE WHEN. Foundry's tools are mapped by default; map any other with --tool NAME=SQL_FIELD[:DIALECT]. Recovered retry chains export to eval replay as a regression suite. See docs/trace.md and the first Foundry report.

Better SQL from the model

When QueryPilot writes the SQL itself (ask, ask_database, evals), it uses the techniques with the largest measured gains in the text-to-SQL literature. The sources and numbers are in docs/research/developer-needs.md.

  • Grounded schema. The prompt shows each table as compact DDL with primary keys, foreign-key join paths, and descriptions you configure. Sampling real values is opt-in. Set sample_values: 3 in querypilot.yaml, or pass sample_values=3 to QueryPilot.connect, after reviewing which database values can be shared with your model and tool clients. Sampling excludes blocked or masked columns and row-filtered tables. Treat returned values and database descriptions as untrusted data in downstream agents.
  • Your business rules. Pass hints= and descriptions= to connect(), or set them in querypilot.yaml, for definitions such as "revenue means paid invoices only".
  • Pruning only when needed. Below schema_token_budget (default 6000 tokens) the full schema is sent. Above it, QueryPilot sends the relevant tables plus the foreign-key bridge tables that join them.
  • A repair loop that converges. Validation errors get "did you mean" hints. Database errors are cleaned before they go back to the model. An empty result triggers one gentle review. Up to 3 attempts by default.
server.ts
from querypilot import AnthropicSQLGenerator, QueryPilot

qp = QueryPilot.connect(
    "duckdb:///analytics.duckdb",
    generator=AnthropicSQLGenerator(),
    hints=["Revenue means SUM(amount_cents) / 100 over invoices with status = 'paid'"],
    descriptions={"accounts.segment": "smb, midmarket or enterprise"},
)
answer = qp.ask("Revenue by segment last quarter")

Why QueryPilot exists

Read-only SQL access for agents is becoming a commodity. The hard part is making that access measurably reliable: proving the SQL the agent writes is correct, safe and fast, and that it doesn't regress.

QueryPilot can measure every change to your prompts, model or configuration against an execution-truth eval suite. You can write suites by hand, or generate them by replaying your audit log as a regression set. The queries that worked in production yesterday then have to keep working tomorrow.

Eval quickstart

From a clone of this repository (the bundled suites run against tests/fixtures/demo.db):

Terminal
pip install -e ".[eval]"
querypilot eval run \
    --suite suites/smoke.yaml \
    --generator demo \
    --report eval-out.json
querypilot eval check \
    --report eval-out.json \
    --baseline .eval/baseline.json \
    --threshold 0.9 \
    --require-safety 1.0

Sample output (abridged — see the full report at the top of this README):

text
QueryPilot Eval Report
Suite:     smoke
Generator: demo

Overall
  ✅  Pass rate                       3 / 3 (100%)
  ✅  Safety pass rate                0 / 0 (100%)
  ✅  Correctness                     3 / 3 (100%)
  ✅  P95 latency                     18 ms

✅ No threshold violations.

The bundled suites/smoke.yaml runs against a tiny SQLite fixture (tests/fixtures/demo.db) so the harness works end-to-end without an LLM key. In your own project, querypilot eval init scaffolds suites/ and .eval/. To benchmark a real generator, use --generator openai or --generator anthropic.

Audit-Log Replay

querypilot eval replay turns a JSONL audit log written by JSONLAuditSink into a BenchmarkSuite whose gold SQL is the SQL that previously executed. Re-running that suite gates accuracy regressions against your own production traffic — the unique-to-QueryPilot capability the eval positioning rests on.

bash
querypilot eval replay \
    --audit-jsonl audit.jsonl \
    --fixture-db sqlite:///tests/fixtures/demo.db \
    --output suites/replay.yaml
querypilot eval run --suite suites/replay.yaml --generator demo --report replay-out.json

Conservative defaults: only successful ask records, non-empty results, no active access policy. --include-failures, --include-masked, --include-empty relax each filter.

Compare models: cost per correct answer

Pick a model on a suite where models actually differ, and on what a right answer costs, not what a request costs. querypilot eval matrix runs several generators on one suite and ranks them on one leaderboard:

bash
querypilot eval matrix \
    --suite suites/bird_hard \
    --generators anthropic:claude-haiku-5-5,anthropic:claude-sonnet-5-5,openai-compatible:llama3.1 \
    --min-correctness 0.55 \
    --output-dir benchmarks/results/bird-hard

Every SuiteReport now carries cost_per_correct_usd (the run's total cost, failures included, divided by the answers that matched gold) and correct_per_dollar. A case's cost sums every model call it made, repairs included. When any case's usage or model price is unknown, both fields are null rather than a partial number. The leaderboard ranks entries that reach the correctness bar with 100% safety by cost per correct answer; the rest follow by correctness and are marked *. The bar is --min-correctness, else the suite's thresholds.correctness_rate; with neither, it ranks by pass rate as before. --output-dir writes one report JSON per generator plus leaderboard.md and leaderboard.json. Generators are written provider[:model]; all of them are built before any case runs, so a missing key fails fast.

A suite directory may mix databases, as querypilot eval import writes them, and is scored as one suite. To build the hard BIRD sample (100 simple, 80 moderate, 40 challenging) the same way every time:

server.ts
querypilot eval import --format bird --dataset ~/data/bird/dev \
    --output suites/bird_hard --sample simple=100,moderate=80,challenging=40 --seed 20261021

Imported cases are tagged with their difficulty, so the report's tag rollups show each bucket. .github/workflows/bird-weekly.yml runs this sample every Monday through Haiku 5.5 (with its default settings and with thinking off), Sonnet 5.5 (default and low effort) and the Haiku-to-Sonnet cascade, then posts the leaderboard to the run summary. It needs an ANTHROPIC_API_KEY repository secret.

CI Gate

querypilot eval check compares a SuiteReport JSON against thresholds and a committed baseline, exiting non-zero on regression. A sample GitHub Actions workflow ships at .github/workflows/eval.yml:

yaml
- run: querypilot eval run --suite suites/smoke.yaml --generator demo --report eval-out.json
- run: querypilot eval check --report eval-out.json --baseline .eval/baseline.json --threshold 0.9 --require-safety 1.0

QueryPilot's own CI gates three ways:

  • The repair loop, offline (eval.yml, every PR). --generator faults answers each SaaSPulse question with its gold SQL broken on the first attempt (a misspelled column, a table that doesn't exist, a function the database lacks, or a wrong-case literal that empties the result) and returns the gold when asked to repair. All 102 cases must pass, as in .eval/faults-baseline.json, so validation feedback, deterministic fixes, database-error feedback and the empty-result review are each measured on realistic queries, with no API key. Use it on your own suite: any case with gold_sql works.
  • Real models (eval-model.yml, on PRs that touch generation, validation or the benchmark, and on main). SaaSPulse with Claude Haiku, and with the Haiku-to-Sonnet cascade and a 3-sample vote, each on the precise questions and on the same questions phrased the way a business user asks them (benchmarks/saaspulse_natural). Safety must be 100%; correctness must meet the suite's floor and, once .eval/model-<name>.json is committed, stay within --tolerance 0.05 of it. Model runs vary, so with --tolerance the cases that flip are listed, not failed. It needs the ANTHROPIC_API_KEY repository secret (without it the run is skipped with a warning) and costs well under a dollar a run.
  • Real systems (integration.yml, every PR). Postgres 16 and Trino service containers: per-user db_role under row-level security, the Postgres proxy with psycopg and psql, Trino three-part names and its EXPLAIN-based cost guard, and the real BigQuery drivers with only the HTTP faked. Integration tests that skip fail the job.

When a regression is detected the output explains which cases regressed and how:

text
Regression detected.

Pass rate:
  baseline: 96%
  current:  89%

Failed cases (regression vs. baseline):
  - monthly_revenue_by_segment (was passing -> now result_mismatch)
  - top_customers_by_arr      (was passing -> now repair_failed)

Latency:
  baseline p95: 2100 ms
  current p95:  3800 ms  (+1700 ms)

Refresh the baseline on main after a deliberate change:

bash
querypilot eval run --suite suites/smoke.yaml --generator demo --report .eval/baseline.json
git commit -am "Refresh eval baseline"

Authoring a Suite

Suites are YAML or JSON. Each case carries a question, a gold SQL, and the schema/safety expectations for the candidate.

Dockerfile
name: saas_revenue_suite
fixture_db: sqlite:///fixtures/demo.db
fixture_dialect: sqlite

thresholds:
  pass_rate: 0.95
  safety_pass_rate: 1.0
  correctness_rate: 0.9
  max_p95_latency_ms: 5000
  max_avg_cost_usd: 0.01

comparison:
  ignore_row_order: true
  ignore_column_order: true
  float_tolerance: 0.001
  normalize_datetimes: true

cases:
  - id: top_customers_by_revenue
    question: "Top customers by revenue"
    gold_sql: |
      SELECT customer_name, revenue
      FROM customers
      ORDER BY revenue DESC
      LIMIT 100
    expected_tables: [customers]
    must_include: ["ORDER BY", "LIMIT"]
    must_not_contain: [DELETE, UPDATE, DROP]
    tags: [revenue, ranking]

  - id: blocks_drop_table
    sql: "DROP TABLE customers"
    should_pass: false
    expected_failure_kind: validation
    expected_error_contains: ["Only SELECT queries are allowed"]
    tags: [safety, ddl]

Result-set correctness is scored by executing both the gold and candidate SQL against the same fixture database and comparing rows. Order-insensitive by default; auto-flipped to order-sensitive when the gold SQL has a top-level ORDER BY.

Examples

Runnable, self-contained examples live in examples/. They all use the bundled demo SQLite fixture, so most need no API key:

ExampleShowsKey?
01_quickstart.pyconnect, execute_sql, offline ask(), validation risk levelNo
02_openai_tool_use.pyas_openai_tools() in an OpenAI tool-use loopOPENAI_API_KEY
03_anthropic_tool_use.pyas_anthropic_tools() in an Anthropic tool-use loopANTHROPIC_API_KEY
04_access_control.pyblocked columns, row filter, and maskingNo
05_custom_eval_suite/a custom YAML suite run with querypilot eval run/checkNo
06_mcp/run querypilot mcp + a paste-ready Claude MCP configNo
07_frameworks.pythe same tools in LangChain, OpenAI Agents SDK and Claude Agent SDKNo

See examples/README.md for setup and the full index.

LLM SQL Generation

For production-style natural-language SQL generation, plug in an LLM generator. QueryPilot still treats model output as an untrusted candidate: it validates, rewrites, and can ask the generator for a repair before execution.

Install optional provider dependencies:

Terminal
pip install "querypilot[openai]"      # or querypilot[anthropic], or querypilot[llm] for both

OpenAI:

server.ts
from querypilot import QueryPilot
from querypilot.generation import OpenAISQLGenerator

qp = QueryPilot.connect(
    "sqlite:///demo.db",
    generator=OpenAISQLGenerator(model="gpt-6.2-sol"),
)

Anthropic:

server.ts
from querypilot import QueryPilot
from querypilot.generation import AnthropicSQLGenerator

qp = QueryPilot.connect(
    "sqlite:///demo.db",
    generator=AnthropicSQLGenerator(model="claude-sonnet-4-20250514"),
)

Claude 5-family models (Haiku 5.5, Sonnet 5.5, Opus 5.5 and later) think by default, and thinking tokens count against max_tokens. QueryPilot gives those models a 16,000-token output cap instead of the 800 it uses for SQL alone; only tokens actually generated are billed. Tune them with effort and thinking:

python
AnthropicSQLGenerator(model="claude-haiku-5-5", effort="low", thinking="off")

effort is low to max and None keeps the model's default. thinking is "default" (send nothing), "adaptive" or "off". "off" is sent the way each model accepts it: between_tools on Sonnet 5.5, disabled elsewhere. It is refused for models that can't turn thinking off (Opus 5.5, Fable): use a lower effort there. A response cut off at max_tokens or refused comes back as a generation error that says so, not as invalid JSON. The same settings work as --effort / --thinking on ask, serve, mcp and eval run, as generator.effort / generator.thinking in querypilot.yaml, and as @ options on eval matrix entries (anthropic:claude-sonnet-5-5@low, anthropic:claude-haiku-5-5@low+nothink).

Prompt caching and free repairs

Every prompt now begins with the same block: the instructions, the schema DDL and the business rules. The question and any repair feedback come after it, so retries and repairs on the same schema resend identical leading text.

  • Anthropic: the schema block carries a cache_control breakpoint, so the instructions and schema are cached together. QueryPilot leaves the marker off when the block is shorter than the model's minimum cacheable length (512 tokens on Claude 5-family models, 1,024 to 4,096 on older ones). The schema stays in the user turn rather than the system prompt because it includes values and comments read from the database.
  • OpenAI and OpenAI-compatible endpoints: the shared block leads the input, so their automatic prefix caching applies.
  • Cost tracking: cache reads and writes are recorded in TokenUsage (cache_read_tokens, cache_write_tokens) and priced separately. For Anthropic models, reads cost 0.1× the input price (0.05× on Opus 5.5 and Sonnet 5.5) and writes cost 1.25×. OpenAI cached tokens are billed at the full input price until their discount is confirmed.
  • Reports: SuiteReport.cache_hit_rate is the share of prompt tokens read from the cache.

A misspelled column is fixed without calling the model. This applies when validation's only error is one unknown column and exactly one column in the query's tables is a close match, such as customer_nme → customer_name. QueryPilot renames the column in place and validates the query again, and the fix uses none of the attempt budget. It is audited as a repair_sql record with details.repair = "deterministic", and eval reports count these fixes. Ambiguous or distant names still go to the model with a "did you mean" hint.

Model cascade

A cascade sends each question to a cheap model first and calls the large one only when QueryPilot's own checks fail. Those checks are the validator, the database, the empty-result review and the result-shape checks, and they cost nothing:

yaml
generator:
  cascade:
    - {provider: anthropic, model: claude-haiku-5-5, max_attempts: 2}
    - {provider: anthropic, model: claude-sonnet-5-5, max_attempts: 2}
  escalate_on: [no_sql, validation, execution, empty, shape]   # the default: all five

Each tier has its own attempt budget; for a cascade, max_attempts replaces the client-wide max_generation_attempts. A question moves to the next tier when the current tier's last attempt ends in one of the escalate_on triggers:

  • no_sql: the model returned no SQL.
  • validation: the SQL still fails validation after repair.
  • execution: the database still rejects it after repair.
  • empty: the query returns no rows, even after the empty-result review.
  • shape: the result still looks wrong after a review (see below).

The next tier starts fresh from the question rather than repairing the cheap tier's SQL. If the cheap tier found a valid empty result and the large tier then fails, the empty result is returned.

QueryPilotAnswer.tier names the tier that produced the answer, and escalated and escalation_reason say whether and why the question moved up. ask and generate_sql audit records carry the same fields, and the FastAPI /ask and MCP ask_database responses include the tier.

You can also build a cascade in code with CascadeSQLGenerator([CascadeTier(cheap, max_attempts=2), CascadeTier(large)]).

To measure a cascade against a single model, use eval run --cascade anthropic:claude-haiku-5-5>anthropic:claude-sonnet-5-5, or add the same > form as an eval matrix entry. The report shows the escalation rate, the escalations by trigger, and the cost and answer count for each tier.

Result-shape checks. A query can run and return rows and still be wrong. QueryPilot flags three common signs:

  • a column that is NULL in every row (a join that matched nothing, the wrong column, or an aggregate over no rows);
  • exact duplicate rows when the question asks for one row per item ("each", "every", "per");
  • more rows than the largest table the query reads, for plain joins without aggregation (a join multiplying rows). Table sizes come from a COUNT(*) per table under the access policy, cached until refresh_schema.

A flagged result is handled like an empty one: the model gets one review with the issues, and a model that returns the same SQL keeps its answer. A cascade then escalates on shape, and the flagged result stays the fallback answer if everything after it fails. None of the 130 SaaSPulse gold queries is flagged. Turn the checks off with result_checks: false in querypilot.yaml or QueryPilot.connect(..., result_checks=False).

Multi-sample voting (off by default). When the first tier fails a question, voting draws a few fresh samples from that same tier before calling the next one:

yaml
generator:
  cascade: [...]
  voting: {samples: 3, temperature: 0.7}

Each sample is validated and run like any answer. Samples that fail validation, error in the database, return no rows or fail a shape check don't vote. The rest are grouped by result: rows compared without column names or order, floats rounded to 4 places. If the largest group holds a strict majority of the samples drawn, its shortest SQL answers and the question stays on the cheap tier. Otherwise, ties included, the question escalates as before. Samples run in parallel within the client's generation budget (at most 4 calls at once, 120 a minute). OpenAI-compatible endpoints and pre-GPT-5 OpenAI models sample at temperature; reasoning models and Anthropic models sample at their default, which already varies between calls.

QueryPilotAnswer.vote and the ask audit record report the vote (samples, valid, agreeing, selected), and each sample and the vote itself are audited. In code, use CascadeSQLGenerator(tiers, voting=VotingSettings(samples=3)). In evals, use eval run --cascade cheap>large --vote 3; the report adds the votes held, the answers a majority picked, and how many of them were correct. Voting has not yet been measured on BIRD, which is why it is off by default.

Metrics layer

Named metrics turn the model's job from writing joins into picking a metric and its dimensions, which small models do reliably. Define them in querypilot.yaml, in your database's dialect:

yaml
metrics:
  revenue:
    description: Paid invoice revenue in dollars
    sql: SUM(invoices.amount_cents) / 100.0
    table: invoices
    filters: ["invoices.status = 'paid'"]
    dimensions: [accounts.segment, invoices.paid_at]
    time_dimension: invoices.paid_at
  • Routing in ask: the metric definitions go into the cached prompt block after the schema. The model answers in one call: either a metric request ({"metric": {"name": "revenue", "dimensions": ["accounts.segment"], "filters": [...], "time_grain": "month", "limit": 10}}) or, when no metric fits, the SQL itself. A request that names an unknown metric or dimension goes back to the model with the valid options. Answers, ask audit records, eval cases and the FastAPI /ask response carry metric.
  • Compiler: querypilot.metrics.compile_metric turns a request into one SELECT for the target dialect with sqlglot. It joins dimension tables by following foreign keys from the introspected schema, and it refuses a join that would repeat the metric table's rows (one-to-many), since that would inflate the aggregate. Time grains are day, week, month, quarter and year. Filters are structured (=, !=, <, <=, >, >=, in, not in, between, is null, is not null), and values are quoted by the compiler.
  • Same checks as raw SQL: compiled SQL goes through the validator, the access policy (row filters, blocked columns, masking) and execution like any other query. Metrics that read a table the caller can't see are hidden from the prompt and the tools.
  • Tools: with metrics configured, the toolkit and the MCP server add list_metrics and query_metric (both read-only).
  • SDK: QueryPilot.connect(url, metrics={...}), qp.compile_metric({...}) and qp.query_metric({...}).
  • Drafting: querypilot metrics init drafts definitions from the verified store's most frequent aggregations: shared conditions become filters, and grouped or filtered columns become dimensions. Review the draft before pasting it in. querypilot metrics list checks that every metric and dimension compiles against the database.
  • Evals: a suite can carry its own metrics: section, or pass eval run --metrics querypilot.yaml. The report shows how many questions were answered through a metric and how many of those were correct.

Verified queries

Questions your team has already answered correctly don't need a model. A verified query store keeps approved question/SQL pairs in a SQLite file:

yaml
verified:
  path: .querypilot/verified.db
  examples: 0        # similar approved pairs added to the prompt as few-shot examples
Dockerfile
querypilot verified add --question "Top customers by revenue" \
    --sql "SELECT customer_name, revenue FROM customers ORDER BY revenue DESC"
querypilot verified import --audit-jsonl audit.jsonl        # successful asks, proposed for review
querypilot verified import --trace-chains recovered.jsonl  # from `trace doctor --export-replay`
querypilot verified list --status proposed
querypilot verified approve 3 4                            # or --all

add and approve validate the SQL with your full configuration first, and record who approved it, when, and a fingerprint of every table it reads (column names and types). Imports propose only successful, unmasked ask records with rows, and nothing is served until it is approved.

  • Exact hit: a question that matches an approved one, ignoring case, whitespace and punctuation, is answered with the stored SQL and no model call. The SQL still goes through validation, the access policy (blocked columns, row filters, masking) and execution. If it no longer validates or runs, the question goes to the model and a verified_query audit record says why. Answers and ask audit records carry verified_id.
  • Near hit: with examples: N, the N approved questions closest to the one asked are added to the prompt, after the cached schema block. Similarity comes from a local hashed n-gram embedding, so it costs nothing per call; pass VerifiedStore(path, embedder=...) to use another one. Few-shot examples stay off by default until they are measured on the hard suite.
  • Staleness: when a table an entry reads changes, the entry is stale. Stale entries are used only as examples, never served directly; verified list marks them and verified approve ID refreshes them. Entries that read a table the access policy hides are neither served nor shown.
  • Tools: with a store configured, the toolkit and the MCP server add find_verified_query (read-only). It returns the approved SQL for the exact question, if any, and the closest approved questions.
  • Evals: eval replay --verified PATH --fixture-db ... turns approved, fresh entries into a suite with their SQL as gold. eval run --verified PATH answers from the store, and the report shows the hit rate and the latency of cached answers next to generated ones.

In code: QueryPilot.connect(url, verified="verified.db", verified_examples=3), plus querypilot.verified.add_verified(qp, store, question, sql).

Local / open models

Any OpenAI-compatible endpoint — Ollama, vLLM, LM Studio, or llama.cpp's server — works through OpenAICompatibleSQLGenerator. It reuses the [openai] extra (no extra dependency) and talks the Chat Completions API, so you can benchmark open models at $0. The API key is optional (local servers ignore it), and cost reports show $0 while token counts still flow through when the server returns usage.

bash
ollama pull llama3.1
pip install "querypilot[openai]"
server.ts
from querypilot import QueryPilot
from querypilot.generation import OpenAICompatibleSQLGenerator

qp = QueryPilot.connect(
    "sqlite:///demo.db",
    generator=OpenAICompatibleSQLGenerator(
        model="llama3.1",
        base_url="http://localhost:11434/v1",  # Ollama's default; omit to use it
    ),
)

From the eval harness, add open models to the benchmark matrix with --generator openai-compatible:

bash
querypilot eval run \
    --suite suites/smoke.yaml \
    --generator openai-compatible \
    --model llama3.1 \
    --base-url http://localhost:11434/v1 \
    --report eval-out.json

--base-url also reads $QUERYPILOT_BASE_URL, and defaults to Ollama's http://localhost:11434/v1 when unset.

The safety loop is always:

text
question
  -> schema-scoped prompt
  -> model candidate SQL
  -> QueryPilot validation
  -> optional repair
  -> safe execution

Eval Harness (Library)

The CLI is a thin wrapper around run_suite, which is also usable directly:

Dockerfile
from querypilot import QueryPilot
from querypilot.evals import (
    BenchmarkCase,
    BenchmarkSuite,
    NullCostTracker,
    build_qp_factory,
    render_terminal,
    run_suite,
)
from querypilot.generation.sql_generator import DemoSQLGenerator

suite = BenchmarkSuite(
    name="adhoc",
    fixture_db="sqlite:///tests/fixtures/demo.db",
    cases=[
        BenchmarkCase(
            id="count_customers",
            question="Count of customers",
            gold_sql="SELECT COUNT(*) AS count FROM customers",
            expected_tables=["customers"],
        ),
    ],
)

qp_factory = build_qp_factory(
    database_url="sqlite:///tests/fixtures/demo.db",
    generator=DemoSQLGenerator(),
)

report = run_suite(
    suite,
    qp_factory=qp_factory,
    cost_tracker_factory=NullCostTracker,
)

print(render_terminal(report, color=False))

The returned SuiteReport is a Pydantic model with pass_rate, safety_pass_rate, correctness_rate, repair_rate, p50_latency_ms, p95_latency_ms, total_prompt_tokens, estimated_cost_usd, tag_rollups, failure_breakdown, threshold_violations, and the full per-case case_results list.

Safety Engine

QueryPilot validates SQL before execution with:

  • sqlglot parsing
  • single-statement enforcement
  • SELECT-only read-only policy
  • blocked keyword detection
  • known table checks
  • column checks where feasible
  • allowed/blocked table policy
  • automatic LIMIT insertion and max-row capping
  • SELECT * warnings or rejection
  • Cartesian join detection
  • structured policy checks
  • query fingerprints
  • risk levels: low, medium, high, critical

For PostgreSQL production use, connect QueryPilot with a dedicated least-privilege role that has only the required schema USAGE and table SELECT grants. QueryPilot requests a read-only transaction and applies a statement timeout, but application validation is not a replacement for database permissions.

Example:

Dockerfile
validation = qp.validate_sql("SELECT * FROM customers")

print(validation.valid)
print(validation.risk_level)
print(validation.query_fingerprint)
print(validation.policy_checks)

For stricter deployments:

server.ts
from querypilot.core.config import SafetyPolicy

qp = QueryPilot.connect(
    "sqlite:///demo.db",
    safety_policy=SafetyPolicy(
        allow_select_star=False,
        reject_cartesian_joins=True,
    ),
)

FastAPI Server

Run QueryPilot as a local safe SQL gateway:

Terminal
pip install "querypilot[server]"
querypilot serve --db sqlite:///demo.db --max-rows 100

Or use environment variables:

server.ts
export QUERYPILOT_DATABASE_URL=sqlite:///demo.db
querypilot serve

Endpoints:

  • GET /health
  • GET /schema
  • POST /search-schema
  • POST /ask
  • POST /generate-sql
  • POST /validate-sql
  • POST /execute-sql

Set QUERYPILOT_API_TOKEN to require a bearer token on the query and schema endpoints. The health endpoint stays available for readiness checks. The CLI binds to loopback, so use an authenticated HTTPS gateway for remote access.

Set a separate QUERYPILOT_ADMIN_TOKEN to enable GET /audit/recent. Add --eval-suite path/to/suite.yaml to enable POST /evals/run. Both routes require the administrator bearer token. The eval endpoint accepts an empty request and runs the configured suite against separate, existing SQLite fixture files. Keep the suite and fixtures under administrator control.

Public query responses omit policy internals and return caller SQL when a private row filter is applied. Use the audit ID to look up executed SQL and validation diagnostics through the admin endpoint.

HTTP request bodies are capped at 512 KiB, SQL at 64 KiB, and questions at 8 KiB. Built-in connectors enforce a 2 MiB result budget while collecting rows. Driver buffering varies. Each QueryPilot instance allows four concurrent generation calls and 120 per minute, including repairs.

Example:

Terminal
curl -X POST http://127.0.0.1:8000/validate-sql \
  -H "content-type: application/json" \
  -d '{"sql": "SELECT * FROM customers"}'

Audit Trail

QueryPilot records structured audit events for schema search, SQL generation, validation, execution, and full ask() flows.

Audit records can contain SQL literals and user questions. Limit access to stored records and configure retention for production logs.

Each audit record can include:

  • audit_id
  • timestamp
  • operation
  • question
  • original SQL
  • rewritten SQL
  • validation metadata
  • execution status
  • row count
  • execution time
  • error
  • actor/session/application/trace metadata

Use the default in-memory sink:

Dockerfile
from querypilot import QueryPilot
from querypilot.audit import AuditMetadata

qp = QueryPilot.connect(
    "sqlite:///demo.db",
    audit_metadata=AuditMetadata(
        actor="agent-1",
        session_id="session-1",
        app_name="analytics-agent",
    ),
)

result = qp.execute_sql("SELECT customer_name FROM customers")

print(result.audit_id)
print(qp.get_audit_records(limit=10))

Or persist JSONL audit events:

server.ts
from querypilot import QueryPilot
from querypilot.audit import JSONLAuditSink

qp = QueryPilot.connect(
    "sqlite:///demo.db",
    audit_sink=JSONLAuditSink("querypilot-audit.jsonl"),
)

Access Control

Read-only SQL is necessary but not enough. QueryPilot can also enforce column-level and row-level access policies before execution.

server.ts
from querypilot import QueryPilot
from querypilot.access import AccessPolicy, MaskingRule

qp = QueryPilot.connect(
    "sqlite:///demo.db",
    access_policy=AccessPolicy(
        blocked_columns={
            "customers": ["email"],
        },
        row_filters={
            "customers": "tenant_id = 42",
        },
        masking_rules={
            "customers": {
                "email": MaskingRule(mode="redact"),
            },
        },
    ),
)

What this does:

  • rejects SQL that selects blocked columns
  • rejects SQL outside an allowlist when allowed_columns is configured
  • injects required row filters such as tenant_id = 42
  • permits masked columns as direct projections and masks them before returning rows
  • records applied policy in the Python SDK results and in the audit trail

The server and MCP runtimes can also receive access policy JSON:

bash
querypilot serve \
  --database-url sqlite:///demo.db \
  --access-policy-json '{
    "row_filters": {"customers": "tenant_id = 42"},
    "blocked_columns": {"customers": ["ssn"]}
  }'

Per-user identity

One policy for every caller is fine for a single agent. For a team, each query should run as the person asking. Name the callers in querypilot.yaml and map them, or their groups, to policies:

yaml
identities:
  alice:
    token: ${ALICE_API_TOKEN}        # bearer token for the HTTP and MCP servers
    groups: [emea]
    attributes: {tenant_id: 1}
    db_role: analyst_emea            # optional: Postgres SET ROLE for her queries
  bob:
    token: ${BOB_API_TOKEN}
    groups: [emea]
    attributes: {tenant_id: 2}
access_policies:
  - name: emea
    groups: [emea]                   # or users: [alice]
    row_filters: {orders: "tenant_id = :user.tenant_id"}
    blocked_columns: {customers: [email]}
  • A caller's policy is the first rule that names them or one of their groups, applied on top of access_policy (blocked columns add up, allowed columns intersect, row filters are ANDed, the strictest mask wins).
  • With access_policies set, a caller no rule matches, or a request with no identity at all, gets the deny policy: no table is visible or readable.
  • :user.<attribute> in a row filter becomes a bind parameter (:qp_user_tenant_id) with the caller's value. Values are never written into the SQL text, so tenant_id: "1 OR 1=1" matches nothing. A filter that names an attribute the caller lacks refuses the query.
  • The audit record's actor is the resolved identity, never a name the request claims, and policy names the rule that applied (deny when none did).

Where the identity comes from:

RuntimeIdentity
Python SDKqp.as_user("alice") (looked up in identities) or qp.as_user(Identity(name=..., attributes=...))
CLIquerypilot sql --user alice ... (or QUERYPILOT_USER); ask, schema, verified and mcp take it too
FastAPIthe bearer token: an identity's token runs the request as that identity; the shared QUERYPILOT_API_TOKEN is an unidentified caller
MCP over HTTPthe bearer token; requests without a known token get 401
MCP over stdioquerypilot mcp --user alice: the server acts for whoever started it
querypilot proxythe Postgres user name; an identity with a token must send it as the password
python
qp = QueryPilot.from_config()          # with access_policies set, this client can read nothing
alice = qp.as_user("alice")            # her policy, attributes and database role
alice.ask("Revenue by month this year")

Running as the caller in the database. db_role makes Postgres run the caller's queries with SET LOCAL ROLE (in the proxy, SET ROLE for the session, which clients cannot reset), so the database's own row-level security applies on top of QueryPilot's policy. For Snowflake, Databricks or any other database, give the identity its own database_url, for example one carrying their OAuth token (${ALICE_SNOWFLAKE_URL}); their queries run on that connection while the schema comes from the shared one. In the proxy, identity attributes are session settings the proxy sets at connect time (set_config, which clients cannot call).

Verified queries are kept per policy. An entry added with querypilot verified add --user alice (or --policy emea) answers only callers under that policy; entries imported from audit logs keep the policy they were answered under. Entries without a policy answer everyone, and their SQL still runs under each caller's own policy.

Known gaps: the proxy's catalog queries (pg_catalog, information_schema) are not filtered per identity, so a client can list table names its policy hides. Foundry's trace hooks already run with each user's own FOUNDRY_TOKEN.

Warehouse cost guards

A row cap limits what comes back, not what gets scanned, and warehouses bill for the scan (BigQuery on-demand charges per byte read). Set a cap and every query is estimated by the warehouse before it runs:

yaml
cost_guard:
  max_bytes_scanned: 5 GB        # BigQuery, Snowflake, Databricks, Trino
  max_partitions_scanned: 2000   # Snowflake micro-partitions
  max_explain_cost: 1000000      # Redshift planner cost
  warehouse: AGENT_XS            # Snowflake: run on a dedicated small warehouse
  price_per_tib: 6.25            # BigQuery on-demand USD per TiB (the default)
  credits_per_hour: 1            # time-billed warehouses: cost = run time x credits x price
  price_per_credit: 3.0
EngineEstimateEnforced by
BigQuerydry run (free): bytes processedQueryPilot before the query runs, and maximum_bytes_billed on every job, so BigQuery itself refuses to bill past the cap
SnowflakeEXPLAIN USING JSON: partitions and bytes assignedQueryPilot; STATEMENT_TIMEOUT_IN_SECONDS as before, plus USE WAREHOUSE when warehouse is set
DatabricksEXPLAIN COST: the optimizer's size for each table readQueryPilot
RedshiftEXPLAIN: the top node's costQueryPilot
TrinoEXPLAIN (TYPE IO, FORMAT JSON): estimated bytes read per tableQueryPilot

A query over the cap is rejected before it runs, and the rejection is repair feedback, so the model narrows the query instead of failing:

text
Query would scan 48.0 GB; the cap is 5.0 GB. Filter on the partition column event_date of analytics.events (then user_id) to narrow it.

The partition and clustering columns come from the warehouse (BigQuery table metadata, Snowflake clustering keys). ask repairs from it like any database error; run_sql (MCP and the agent toolkit) returns it as {"ok": false, "error", "hints"}; execute_sql raises CostLimitError and writes the rejection to the audit log.

Where the guard is set: cost_guard: in querypilot.yaml, QueryPilot.connect(..., cost_guard={"max_bytes_scanned": "5 GB"}) in the SDK, and --max-bytes-scanned 5GB (or QUERYPILOT_MAX_BYTES_SCANNED) on any CLI command that connects, including querypilot mcp and serve.

Cost reporting. Each query's bytes scanned (BigQuery's billed job stats; elsewhere the estimate) and estimated warehouse cost are on the result, the audit record (bytes_scanned, warehouse_cost_usd, also for rejected queries), the run_sql and ask_database tool results and the FastAPI /ask response. querypilot eval run totals them in the report ("warehouse scanned", "warehouse cost", "cost guard rejected"), and querypilot trace doctor adds a warehouse section from tool results that carry them, with the largest scans and a finding when the guard rejected queries.

The BigQuery path is tested against the real google-cloud-bigquery and sqlalchemy-bigquery code with the HTTP faked (tests/test_drivers_contract.py): the dry run is a dry-run job (jobs.insert), the run carries maximumBytesBilled, and bytes processed and billed come from the job's statistics. The Trino path runs against a real Trino in CI.

Limits: an estimate that fails (a permissions error on EXPLAIN, for example) lets the query run, where BigQuery's job cap still applies. Databricks sizes are table-level statistics, so partition pruning does not shrink them; a table without statistics gives no estimate. Engines without an estimate (SQLite, Postgres, DuckDB, MySQL) run unguarded.

Current Scope

Shipped:

  • pip install querypilot, querypilot demo/schema/sql/ask/init/mcp-config, and a querypilot.yaml project config
  • connectors for SQLite and PostgreSQL built in, plus DuckDB, MySQL/MariaDB, SQL Server, Snowflake, BigQuery, Redshift, Trino, Oracle and Databricks through SQLAlchemy extras
  • dialect-aware SQL validation and rewriting (sqlglot), per-engine dangerous-function blocklists, and layered read-only execution
  • one agent toolkit exposed for MCP, OpenAI, Anthropic, LangChain, LlamaIndex, OpenAI Agents SDK, Claude Agent SDK and plain functions
  • grounded generation: keys, foreign keys, comments, policy-safe sample values, business hints, and threshold-gated schema pruning
  • OpenAI, Anthropic and OpenAI-compatible (Ollama, vLLM, LM Studio) generators with a repair loop for validation errors, database errors and empty results
  • column policies, row filters and result masking, per caller with identities and access_policies (identity attributes bound as parameters, Postgres SET ROLE, per-user connections)
  • warehouse cost guards: BigQuery dry runs and maximum_bytes_billed, EXPLAIN-based caps on Snowflake, Databricks, Redshift and Trino, repairable rejections, and bytes scanned and warehouse cost in audit records, eval reports and trace doctor
  • in-memory and JSONL audit logging
  • FastAPI server and MCP server runtimes
  • eval-driven harness: YAML/JSON suites, execution-truth correctness scoring, safety/repair/latency/cost metrics, per-tag rollups, failure-category breakdown, threshold violations, JSON and terminal reports
  • audit-log → regression suite (querypilot eval replay), CI regression gate (querypilot eval check), and querypilot eval init
  • the SaaSPulse contamination-proof benchmark (benchmarks/)

Roadmap

The ranked roadmap and the evidence behind it are in docs/roadmap.md and docs/research/developer-needs.md. Next up: multi-database MCP servers.