Skip to main content
Glama
querywise-mcp

querywise-mcp

by kosminus

querywise-mcp

An MCP server (and a CLI) that lets an LLM query your databases in natural language through a business semantic layer — glossary, metric definitions, data dictionary, knowledge base, and example queries — grounded against your real schema.

It's a refactor of QueryWise (a full-stack text-to-SQL app) into a headless tool: no web UI, no Postgres requirement. The metadata store is an embedded SQLite + sqlite-vec database, so the server runs from a single file.

Two ways to use it

  1. As an MCP server — Claude (or any MCP client) calls the tools. The recommended loop is: get_semantic_context(connection, question) → the model writes a read-only SELECT → run_sql(connection, sql). The client's own model does the reasoning; the server provides grounded context + safe execution.

  2. As a CLI — querywise ask <connection> "<question>" runs the full server-side NL→SQL pipeline (compose → validate → execute → interpret). This path needs an LLM provider key (or local Ollama).

The semantic layer, connectors, and execution are shared by both.

Related MCP server: db-connector

Install

python3 -m venv .venv && source .venv/bin/activate
pip install -e .                 # core (SQLite store, sqlite-vec, Postgres + SQLite targets)
pip install -e ".[llm]"          # + Anthropic/OpenAI for `ask` and cloud embeddings
pip install -e ".[bigquery,databricks]"   # + extra target connectors

Configuration is via environment variables / .env (see .env.example). Zero config works for keyword-only operation; add a key (or Ollama) to unlock embeddings and the ask pipeline.

Quick start (zero external infra)

querywise init                                   # create ~/.querywise/querywise.db
querywise connections add shop \
    --connector-type sqlite -c /path/to/app.db   # introspects + embeds
querywise context shop "revenue by segment"      # see the grounded context
querywise sql shop "SELECT ..."                  # run read-only SQL
querywise ask shop "what is total revenue by segment?"   # full pipeline (needs LLM)

Run as an MCP server

querywise serve            # stdio (for Claude Desktop / Claude Code / Cursor)
querywise serve --http     # Streamable HTTP on MCP_HOST:MCP_PORT (default 127.0.0.1:8077)

Register with Claude

First make sure the store the server will read is initialized (and optionally seeded):

querywise init                          # create ~/.querywise/querywise.db
querywise seed-sample                   # optional: zero-infra IFRS-9 sample → connection "ifrs-db"

Use an absolute command path. MCP clients launch the server with a minimal PATH, so the bare querywise-mcp often won't resolve. Point at the entry point inside your venv, e.g. /path/to/.venv/bin/querywise-mcp.

The server won't read your repo .env. It runs from the client's working directory, so pass everything it needs (DATABASE_URL, provider keys, model) in the env block below.

Claude Desktop — edit ~/Library/Application Support/Claude/claude_desktop_config.json (macOS), then fully quit and reopen Claude Desktop:

{
  "mcpServers": {
    "querywise": {
      "command": "/path/to/.venv/bin/querywise-mcp",
      "env": {
        "DEFAULT_LLM_PROVIDER": "ollama",
        "DATABASE_URL": "sqlite+aiosqlite:////Users/me/.querywise/querywise.db"
      }
    }
  }
}

Claude Code — one command:

claude mcp add querywise /path/to/.venv/bin/querywise-mcp \
  -e DEFAULT_LLM_PROVIDER=ollama \
  -e DATABASE_URL=sqlite+aiosqlite:////Users/me/.querywise/querywise.db
# verify: claude mcp list   (or /mcp inside a session)

Note the four slashes in the SQLite URL — sqlite+aiosqlite:// (scheme) plus the absolute path /Users/me/....

Why DEFAULT_LLM_PROVIDER? It's a server setting, not your chat model. Claude is the client LLM — it calls the granular tools and writes the answer, so it needs no provider config. The server only uses a provider for two things: embeddings (semantic search over your metadata — optional; degrades to keyword-only without one) and the all-in-one ask/generate_sql tools (which run their own LLM). Set it to ollama for key-free local embeddings, or to anthropic/openai (with the matching *_API_KEY in env) if you want to call the server-side ask tool. Omit it entirely to run keyword-only.

MCP surface

Tools (25): list_connections, create_connection, test_connection, introspect_connection, delete_connection, list_tables, describe_table, get_semantic_context, run_sql, generate_sql, ask, query_history, glossary/metric/dictionary/sample-query/knowledge management (list_*/add_*/delete_*, plus add_knowledge_url).

Query paths — the four tools people mix up:

Tool(s)

LLM key?

What it does

get_semantic_context + run_sql

No

Server grounds the question; the client writes the SELECT; run it read-only.

generate_sql

Yes

Server writes SQL from the question but does not execute — review, then run_sql.

ask

Yes

Full pipeline: ground → generate → execute → interpret, returns a Markdown answer.

Resource: querywise://{connection}/schema — the cached schema as text. Prompt: text_to_sql(connection, question) — scaffolds the ground→write→run loop.

connection accepts a connection name or id everywhere.

Connectors

Target

Notes

SQLite

Read-only (mode=ro), zero infra. Great for local files + demos.

PostgreSQL

asyncpg, read-only transaction.

BigQuery

optional extra; service-account JSON in the connection string.

Databricks

optional extra; Unity Catalog or Hive metastore.

All execution is read-only: a static SQL blocklist (DDL/DML/admin/injection) plus connector-level read-only enforcement.

How the semantic layer works

For each question the context builder selects minimal relevant context via a hybrid of (1) vector similarity over embeddings, (2) keyword matching, and (3) foreign-key expansion, then resolves glossary terms, metrics, dictionary value-mappings, knowledge excerpts, and example queries into a structured prompt block. Embeddings are stored as float32 BLOBs and searched with sqlite-vec's vec_distance_cosine; if the extension can't load, search transparently falls back to in-process cosine. With no embedding provider, it degrades to keyword-only matching.

Building the semantic layer

The glossary, metrics, value dictionaries, sample queries, and knowledge docs are populated through the MCP management tools — so you can build them conversationally from an MCP client like Claude, no CLI required. Asking Claude to "add a glossary term active customer defined as … with SQL …" calls add_glossary_term; the same goes for add_metric, add_dictionary_entry, add_sample_query, and add_knowledge / add_knowledge_url (and the matching list_* / delete_* tools to review or remove them). For a ready-made example, querywise seed-sample loads the bundled IFRS 9 banking layer.

Architecture

MCP client (Claude/…)  ──stdio/http──┐
CLI (`querywise ask`)  ──in-process──┤
                                     ▼
                          server.py / cli.py
                                     │
        ┌────────────────┬──────────┴───────────┬──────────────┐
        ▼                ▼                      ▼              ▼
   semantic/        services/               llm/          connectors/
 context builder   query pipeline      agents+providers  PG/SQLite/BQ/DBX
        │                │                      │              │
        └──────── db/ (SQLite + sqlite-vec metadata store) ────┘

Development

ruff check src/
python -m compileall src/

The metadata schema is created on startup (db/init.py) — no migration tool. Switching embedding providers/dimensions clears now-incompatible vectors automatically.

Available Tools

25 tools
add_dictionary_entryA

Map a coded column value to its business meaning (e.g. stage '1' -> 'Performing').

Use so grounding and generation can interpret enum-like codes. Requires the connection to be introspected first so the column can be resolved. Returns the new entry's id.

Inputs: connection (required), table_name (required), column_name (required), raw_value (required), +2 more.

add_glossary_termA

Define a business glossary term that maps business language to a SQL expression.

Use to teach the semantic layer phrases like 'active customer' so future grounding and generation apply them consistently. For a named, reusable aggregate (a KPI) use add_metric instead. Returns the new term's id.

Inputs: connection (required), term (required), definition (required), sql_expression (required), +1 more.

add_knowledgeA

Import a document you provide (plain text or HTML) as searchable business knowledge.

Use when you already have the content; to fetch it from a web page instead, use add_knowledge_url. The content is chunked and embedded for semantic retrieval during grounding. Returns the document id and chunk count.

Inputs: connection (required), title (required), content (required), source_url.

add_knowledge_urlA

Fetch a web page server-side and import its content as searchable business knowledge.

Use to ingest documentation by URL; to import content you already have, use add_knowledge. Performs an outbound HTTP GET (follows redirects, 30s timeout), then chunks and embeds the page. Returns the document id and chunk count.

Inputs: connection (required), url (required), title.

add_metricA

Define a metric: a named, reusable SQL aggregate (a KPI).

Use for quantitative measures like revenue or default rate so grounding and generation can reuse them; for phrase-to-SQL mappings use add_glossary_term instead. Returns the new metric's id and name.

Inputs: connection (required), metric_name (required), display_name (required), sql_expression (required), +3 more.

add_sample_queryA

Save a validated natural-language -> SQL example to improve future generation.

Use to capture good question/SQL pairs for this connection; they are reused as few-shot examples by generate_sql and ask. Returns the new example's id.

Inputs: connection (required), natural_language (required), sql_query (required), description.

askA
Read-only

Answer a natural-language question end-to-end via the server pipeline.

Builds context, generates SQL, validates, executes it (read-only), and interprets the results. This is the fully automated path and requires an LLM provider. Use it when you want a finished answer rather than raw rows; use the get_semantic_context + run_sql path for manual control, or generate_sql to get SQL without executing. Returns a Markdown report (summary, highlights, executed SQL, metadata, follow-ups, and a data preview).

Inputs: connection (required), question (required). Returns: result

create_connectionA

Register a new target database connection (credentials encrypted at rest).

Use once per database before introspecting or querying it. This only stores the connection — it does NOT verify connectivity or read the schema; follow with test_connection, then introspect_connection. Returns the created connection's id and metadata.

Inputs: name (required), connector_type (required), connection_string (required), default_schema, +2 more.

delete_connectionA
DestructiveIdempotent

Permanently delete a connection and all its cached schema + semantic metadata.

Removes the connection plus its glossary, metrics, dictionary, sample queries, and knowledge. Destructive and not reversible — use only to retire a database you no longer query. Returns {deleted: true}.

Inputs: connection (required).

delete_glossary_termA
DestructiveIdempotent

Delete one business glossary term by its id.

Destructive and not reversible. Look up ids with list_glossary. Returns {deleted} indicating whether a matching term was removed.

Inputs: term_id (required).

delete_knowledgeA
DestructiveIdempotent

Delete one knowledge document (and its chunks) by id.

Destructive and not reversible. Look up ids with list_knowledge. Returns {deleted} indicating whether a matching document was removed.

Inputs: doc_id (required).

delete_metricA
DestructiveIdempotent

Delete one metric definition by its id.

Destructive and not reversible. Look up ids with list_metrics. Returns {deleted} indicating whether a matching metric was removed.

Inputs: metric_id (required).

describe_tableA
Read-only

Describe one cached table in detail, including its foreign-key relationships.

Returns columns (with defaults/comments), outgoing foreign keys, and incoming references from other tables. Use when you need a single table's keys to write a join; for a list of all tables use list_tables. Reads the cache (introspect first). Raises if the table is not found.

Inputs: connection (required), table_name (required).

generate_sqlA
Read-only

Translate a natural-language question into SQL via the server LLM, without executing it.

Requires an LLM provider to be configured. Use when you want to review or edit the SQL before running it with run_sql. For zero-key operation, use get_semantic_context and write the SQL yourself; to also execute and interpret in one step, use ask. Returns the generated SQL plus supporting details.

Inputs: connection (required), question (required).

get_semantic_contextA
Read-only

Assemble grounded, SQL-ready context for a question.

Returns the relevant tables/columns, foreign keys, business glossary, metric definitions, value dictionaries, knowledge excerpts, and example queries as formatted text. This is the recommended first step of the lightweight path: take the result, write a read-only SELECT yourself, then call run_sql. Needs no LLM key. For a fully automated answer instead, use ask.

Inputs: connection (required), question (required). Returns: result

introspect_connectionA
Idempotent

Read the target database's structure (tables, columns, foreign keys) and cache it.

Run once per connection before querying, and again after the schema changes. Idempotent — re-running refreshes the cache. The cache is what list_tables, describe_table, and get_semantic_context read from. Returns counts of cached objects plus the number of embeddings generated.

Inputs: connection (required), generate_embeddings.

list_connectionsA
Read-only

List all configured database connections (id, name, type, limits).

Call this first to discover which databases exist and to get the name or id that every other tool's connection argument accepts. Read-only; returns an empty list when nothing is configured yet (add one with create_connection).

Inputs: no named parameters. Returns: result

list_glossaryA
Read-only

List the business glossary terms defined for a connection.

Returns each term, its plain-language definition, the SQL expression that implements it, and related tables. Glossary terms map business language (e.g. 'active customer') to SQL. Add with add_glossary_term; for numeric KPIs see list_metrics. Read-only.

Inputs: connection (required). Returns: result

list_knowledgeA
Read-only

List the knowledge documents imported for a connection.

Returns each document's title, source URL, and chunk count. Knowledge docs are searchable business context (policies, data dictionaries, runbooks) used during grounding. Add with add_knowledge or add_knowledge_url. Read-only.

Inputs: connection (required). Returns: result

list_metricsA
Read-only

List the metric definitions for a connection.

Returns each metric's name, display name, SQL aggregate expression, and dimensions. Metrics are named, reusable KPIs. Add with add_metric; for phrase-to-SQL term mappings see list_glossary. Read-only.

Inputs: connection (required). Returns: result

list_sample_queriesA
Read-only

List saved example natural-language -> SQL pairs for a connection.

These validated pairs are used as few-shot examples that steer SQL generation. Add with add_sample_query. Read-only.

Inputs: connection (required). Returns: result

list_tablesA
Read-only

List a connection's cached tables, each with its columns.

Returns name, type, comment, row-count estimate, and per-column details (type, nullability, primary key). Reads the cache from introspect_connection (run that first if the result is empty). Use for a schema-wide overview; for one table's foreign keys and relationships, use describe_table. Read-only.

Inputs: connection (required). Returns: result

query_historyA
Read-only

List recent query executions for a connection, newest first.

Returns each execution's question, final SQL, status, row count, and timestamp. Use to review or reuse previously run queries. Read-only.

Inputs: connection (required), limit. Returns: result

run_sqlA
Read-only

Execute a read-only SQL SELECT against the target database and return the rows.

Use to run SQL you wrote from get_semantic_context. Enforces read-only: rejects INSERT/UPDATE/DELETE/DDL and other unsafe statements; results are row-limited per the connection's max_rows. Returns columns, rows, row_count, truncated, and execution_time_ms. To have the server write the SQL for you, use generate_sql or ask.

Inputs: connection (required), sql (required).

test_connectionA
Read-only

Check that a configured connection can be reached and authenticated.

Use after create_connection to validate credentials and network access before introspecting. Read-only: opens and closes a probe connection without reading the schema (use introspect_connection for that). Returns {success, message}.

Inputs: connection (required).

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.2/5.0

    Scored across 25 tools

    Disambiguation5/5

    Each tool targets a distinct resource or pipeline stage: connection setup, schema introspection, context assembly, SQL generation, execution, and end-to-end asking are clearly separated. The add/list/delete groups for glossary, metrics, knowledge, and sample queries are also unambiguous, with descriptions cross-referencing alternatives.

    Naming Consistency4/5

    Most tools follow a predictable verb_noun pattern (list_*, add_*, delete_*, create_connection). Minor deviations like 'ask', 'query_history', and 'get_semantic_context' break the pattern slightly but remain understandable.

    Tool Count3/5

    25 tools is on the heavy side for a single server, even though the domain spans connection management, SQL querying, and semantic metadata CRUD. Each tool appears justified, but the set could plausibly be split into configuration and querying sub-servers.

    Completeness4/5

    The core lifecycle is well covered: connections can be created/tested/introspected/deleted, SQL can be generated/run/reviewed, and most semantic resources have add/list/delete. Notable missing operations are deleting sample queries and listing/deleting dictionary entries, leaving small management gaps.

    Maintenance

    ActivityInactive
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      A
      quality
      B
      maintenance
      Natural language to SQL engine with multi-connector support (PostgreSQL, MySQL, Snowflake, BigQuery, DuckDB), document QA, semantic caching, and self-hosted MCP server.
      9
      31 PyPI
      5
      -
    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables AI assistants to query business databases directly via natural language, with enforced read-only access and secure query limits. Supports SQLite and PostgreSQL, and works with any OpenAI-compatible model.
      0
      ISC
    • F
      license
      Not graded
      quality
      D
      maintenance
      Enables natural-language querying of SQLite databases through a governed semantic layer, with citations and typed abstention for PII or uncertified data.
      -