querywise-mcp
querywise-mcp is an MCP server that lets you query databases in natural language through a business semantic layer, with tools for connection management, schema exploration, semantic context retrieval, safe SQL execution, and knowledge base curation.
Connection Management
Add, list, test, and delete database connections (PostgreSQL, SQLite, BigQuery, Databricks, MySQL, Snowflake)
Introspect and cache schemas (tables, columns, foreign keys), optionally building vector embeddings for semantic search
Schema Exploration
List all cached tables and columns for a connection
Get detailed info on a single table including foreign keys
Natural Language → SQL Querying
get_semantic_context— Retrieve grounded context (schema, glossary, metrics, knowledge, examples) to inform SQL writing (no LLM key required)run_sql— Safely execute read-only SQL queries with built-in protections against DDL/DMLgenerate_sql— Generate SQL from a natural language question without executing it (requires LLM provider)ask— Full end-to-end pipeline: ground context → generate SQL → validate → execute → interpret, returning a Markdown report (requires LLM provider)query_history— View recent query executions for a connection
Business Semantic Layer Management
Glossary: Define business terms with SQL expressions (e.g. "active customer")
Metrics: Add named, reusable SQL aggregate metrics with optional dimensions
Value Dictionaries: Map raw column values to business meanings (e.g. stage
1→Performing)Sample Queries: Store validated NL→SQL pairs for few-shot prompting
Knowledge Base: Import plain text, HTML documentation, or fetch URLs as searchable business knowledge
Deployment
Runs as an MCP server via stdio or HTTP for use with Claude or other MCP clients
Also usable as a CLI for initialization, connection setup, context inspection, and the full NL→SQL pipeline
Allows querying Databricks via Unity Catalog or Hive metastore.
Supports Hive metastore integration as part of the Databricks connector.
Allows querying PostgreSQL databases with read-only transactions and semantic context.
Allows querying SQLite databases in read-only mode with a business semantic layer.
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
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-onlySELECT→run_sql(connection, sql). The client's own model does the reasoning; the server provides grounded context + safe execution.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 connectorsConfiguration 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 barequerywise-mcpoften 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 theenvblock 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 |
| No | Server grounds the question; the client writes the |
| Yes | Server writes SQL from the question but does not execute — review, then |
| 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 ( |
PostgreSQL |
|
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 toolsadd_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.
askARead-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_connectionADestructiveIdempotent
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_termADestructiveIdempotent
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_knowledgeADestructiveIdempotent
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_metricADestructiveIdempotent
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_tableARead-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_sqlARead-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_contextARead-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_connectionAIdempotent
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_connectionsARead-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_glossaryARead-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_knowledgeARead-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_metricsARead-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_queriesARead-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_tablesARead-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_historyARead-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_sqlARead-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_connectionARead-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
Scored across 25 tools
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.
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.
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.
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
Related MCP Connectors
The grounded data layer for any LLM: governed SQL, metrics, lineage and catalog over your data.
Ask business questions in plain English. Get instant answers from your database, no SQL needed.
Build a semantic layer of reusable metrics and query it in plain words. Share models with your team.
Ask questions in plain language, get answers from your business database. No SQL required.
Related MCP Servers
- FlicenseAqualityBmaintenanceNatural language to SQL engine with multi-connector support (PostgreSQL, MySQL, Snowflake, BigQuery, DuckDB), document QA, semantic caching, and self-hosted MCP server.931 PyPI5-
- AlicenseNot gradedqualityCmaintenanceEnables 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.0ISC
- FlicenseNot gradedqualityDmaintenanceEnables natural-language querying of SQLite databases through a governed semantic layer, with citations and typed abstention for PII or uncertified data.-
- AlicenseBqualityBmaintenanceEnables AI agents to safely describe, query, and compute metrics across SQL databases using open-format semantic models, custom context, and skills, with read-only and dialect-checked execution.1Apache 2.0