An MCP server for Text2SQL: transforms natural language into SQL using graph schema understanding.
QueryWeaver (Text2SQL) MCP Server
QueryWeaver is an open-source MCP server for Text2SQL. It converts plain-English questions into SQL by using graph-powered schema understanding. The server is designed to help query databases in natural language and produce both SQL and results.
๐ ๏ธ Key Features
Text2SQL: transforms natural language into SQL
Graph-powered schema understanding
Returns SQL and query results
Topics: falkordb, semantic-layer, text2sql
๐ Use Cases
Ask databases natural-language questions
Generate SQL from question text using a graph schema layer
โก Developer Benefits
Integrates as an MCP server
Uses schema understanding to support SQL generation
โ ๏ธ Limitations
Description does not specify supported database engines, authentication, or schema prerequisites.
QueryWeaver is an open-source Text2SQL tool that converts plain-English questions into SQL using graph-powered schema understanding. It helps you ask databases natural-language questions and returns SQL and results.
Connect and ask questions:
new-qw-ui-gif
Get Started
Docker
๐ก Recommended for evaluation purposes (Local Python or Node are not required)
APP_ENV=development is what makes the login work on the plain-HTTP
http://localhost:5000 this command serves. Drop it (or set anything else)
when you put QueryWeaver behind HTTPS, so the session cookie is marked
Secure. See Application environment.
Note: QueryWeaver supports multiple AI providers. You can use OPENAI_API_KEY, GEMINI_API_KEY, ANTHROPIC_API_KEY, or AZURE_API_KEY. See the AI/LLM configuration section for details.
For a full list of configuration options, consult .env.example.
Memory TTL (optional)
QueryWeaver stores per-user conversation memory in FalkorDB. By default these graphs persist indefinitely. Set MEMORY_TTL_SECONDS to apply a Redis TTL (in seconds) so idle memory graphs are automatically cleaned up.
bash
# Expire memory graphs after 1 week of inactivity
MEMORY_TTL_SECONDS=604800
The TTL is refreshed on every user interaction, so active users keep their memory.
MCP server: host or connect (optional)
QueryWeaver includes optional support for the Model Context Protocol (MCP). You can either have QueryWeaver expose an MCP-compatible HTTP surface (so other services can call QueryWeaver as an MCP server), or configure QueryWeaver to call an external MCP server for model/context services.
What QueryWeaver provides
The app registers MCP operations focused on Text2SQL flows:
list_databases
connect_database
database_schema
query_database
To disable the built-in MCP endpoints set DISABLE_MCP=true in your .env or environment (default: MCP enabled).
Configuration
DISABLE_MCP โ disable QueryWeaver's built-in MCP HTTP surface. Set to true to disable. Default: false (MCP enabled).
Examples
Disable the built-in MCP when running with Docker:
bash
docker run -p 5000:5000 -it --env DISABLE_MCP=true falkordb/queryweaver
Calling the built-in MCP endpoints (example)
The MCP surface is exposed as HTTP endpoints.
Server Configuration
Below is a minimal example mcp.json client configuration that targets a local QueryWeaver instance exposing the MCP HTTP surface at /mcp.
QueryWeaver exposes a small REST API for managing graphs (database schemas) and running Text2SQL queries. All endpoints that modify or access user-scoped data require authentication. In the browser the app uses a signed session cookie established by OAuth or email/password; for CLI and scripts you can use an API token (see tokens routes or the web UI to create one).
Core endpoints
GET /graphs โ list available graphs for the authenticated user
GET /graphs/{graph_id}/data โ return nodes/links (tables, columns, foreign keys) for the graph
POST /graphs โ upload or create a graph (JSON payload or file upload)
POST /graphs/{graph_id} โ run a Text2SQL chat query against the named graph (streaming response)
Authentication
Add an Authorization header: Authorization: Bearer <API_TOKEN>
Three separate credentials
QueryWeaver keeps its three kinds of "login" independent of one another, so a
failure in one never looks like a failure in another:
Credential
What it proves
Where it lives
Depends on FalkorDB?
Browser login
Who is using the app
Signed session cookie, established once by OAuth or a password
No, once the process is running
API token
A script may act as a user
Token node in the Organizations graph, sent as Authorization: Bearer โฆ
Yes
Data-source connection
Access to your database
Supplied per request, never stored
No (it is your own database)
Because the browser login is a signed cookie, staying logged in costs no database
round trip and survives a FalkorDB outage in an already-running process โ you
keep your session and only the operations that genuinely need the graph fail.
Requests that supply an API token explicitly are always checked against the
database and are answered with 503 (not 401) when it cannot be reached, so
clients retry instead of re-authenticating.
Note the scope: this is about staying logged in, not about booting. QueryWeaver
still connects to FalkorDB at startup and will not start without it, so a restart
during an outage is not covered.
A browser login lasts 24 hours by default; set BROWSER_SESSION_TTL_HOURS to
change that. Logging out clears the session cookie. No API token is issued to
the browser, so there is none to revoke โ tokens are created explicitly from the
tokens API and revoked there. (A legacy api_token cookie left over from an
older release is cleared and revoked on logout too.)
Email signup is verified before the account exists
Signing up with an email address and password does not create an account. The
submitted details are parked, a six-digit confirmation code is mailed to the
address, and the account โ and the session โ come into being only when that code
is typed back into the signup form. So an address the registrant does not
control never becomes an account at all, and there is no half-real user for the
rest of the system to reason about.
A code rather than an emailed link, because the code has to come back to the
session that submitted the form. A link can be opened by anyone who receives it:
a stranger could submit your address with a password of their choosing, and your
single click would create an account they knew the password to. Nobody can be
signed up by someone else here, because the person who fills in the form is the
only one who ever holds both halves.
The code is single-use, expires after 15 minutes and tolerates only a handful of
wrong guesses before the pending signup is discarded โ a short code is only safe
while the number of attempts is small. It is also only redeemable in the browser
that submitted the form: each submission mints a ticket that stays in that
browser's session, and a code presented without its ticket is refused. Entering
it signs the browser in directly: the password was chosen minutes earlier, and
asking for it again would prove nothing. A code can be re-sent from the same
screen, subject to a per-address rate limit; the send budget is per pending
signup, so it starts over once the pending signup expires and an address can
always be signed up again later. Typing a code that has expired is not one of
the wrong guesses and does not discard anything โ the pending signup is left
where it is so the same screen can send a fresh code.
In development, a message with no mail server configured is written to the
application log instead of being sent, so the flow can be completed by copying
the code out of the log. This needs APP_ENV=development โ anywhere else an
unconfigured process refuses the send rather than logging the code and
reporting success. Set MAIL_SERVER (plus MAIL_PORT, MAIL_USERNAME,
MAIL_PASSWORD, MAIL_DEFAULT_SENDER) to send for real; any provider with an
SMTP endpoint works. EMAIL_VERIFICATION_TTL_MINUTES,
EMAIL_VERIFICATION_MAX_ATTEMPTS, EMAIL_VERIFICATION_RESEND_SECONDS and
EMAIL_VERIFICATION_MAX_SENDS tune the lifetime and the limits. See
.env.example for the full list.
The trade-off of a signed session cookie is that it cannot be revoked from
the server before it expires: the TTL bounds the damage, and rotating
FASTAPI_SECRET_KEY invalidates every browser login at once. API tokens keep
their server-side record and so can still be revoked individually and
immediately. Shorten BROWSER_SESSION_TTL_HOURS if you need a tighter window.
Query a graph (POST) โ run a chat-based Text2SQL request
The POST /graphs/{graph_id} endpoint accepts a JSON body with at least a chat field (an array of messages). The endpoint streams processing steps and the final SQL back as server-sent-message chunks delimited by a special boundary used by the frontend. For simple scripting you can call it and read the final JSON object from the streamed messages.
Example payload:
json
{"chat":["How many users signed up last month?"],"result":[],"instructions":"Prefer PostgreSQL compatible SQL"}
import requests
import json
url = 'https://app.queryweaver.ai/graphs/my_database'
headers = {'Authorization': f'Bearer {TOKEN}', 'Content-Type': 'application/json'}
with requests.post(url, headers=headers, json={"chat": ["Count orders last week"]}, stream=True) as r:
# The server yields JSON objects delimited by a message boundary string
boundary = '|||FALKORDB_MESSAGE_BOUNDARY|||'
buffer = ''for chunk in r.iter_content(decode_unicode=True, chunk_size=1024):
buffer += chunk
while boundary in buffer:
part, buffer = buffer.split(boundary, 1)
ifnot part.strip():
continue
obj = json.loads(part)
print('STREAM:', obj)
Notes & tips
Graph IDs are namespaced per-user. When calling the API directly use the plain graph id (the server will namespace by the authenticated user). For uploaded files the database field determines the saved graph id.
The streaming response includes intermediate reasoning steps, follow-up questions (if the query is ambiguous or off-topic), and the final SQL. The frontend expects the boundary string |||FALKORDB_MESSAGE_BOUNDARY||| between messages.
For destructive SQL (INSERT/UPDATE/DELETE etc) the service will include a confirmation step in the stream; the frontend handles this flow. If you automate destructive operations, ensure you handle confirmation properly (see the ConfirmRequest model in the code).
Python SDK
The QueryWeaver Python SDK allows you to use Text2SQL functionality directly in your Python applications without running a web server.
Installation
bash
# SDK only (minimal dependencies)
pip install queryweaver
# With server dependencies (FastAPI, etc.)
pip install queryweaver[server]
# Development (includes testing tools)
pip install queryweaver[dev]
Quick Start
python
import asyncio
from queryweaver import QueryWeaver
asyncdefmain():
# Initialize with FalkorDB connection
qw = QueryWeaver(falkordb_url="redis://localhost:6379")
# Connect a PostgreSQL or MySQL database
conn = await qw.connect_database("postgresql://user:pass@host:5432/mydb")
print(f"Connected: {conn.database_id}") # "mydb"# Convert natural language to SQL and execute โ pass the database_id# returned by connect_database (un-prefixed; namespacing is internal).
result = await qw.query(conn.database_id, "Show me all customers from NYC")
print(result.sql_query) # SELECT * FROM customers WHERE city = 'NYC'print(result.results) # [{"id": 1, "name": "Alice", "city": "NYC"}, ...]print(result.ai_response) # "Found 42 customers from NYC..."await qw.close()
asyncio.run(main())
Context Manager
python
asyncwith QueryWeaver(falkordb_url="redis://localhost:6379") as qw:
conn = await qw.connect_database("postgresql://user:pass@host/mydb")
result = await qw.query(conn.database_id, "Count orders by status")
# close() runs automatically, awaiting any in-flight background memory writes.
Multiple Instances
Multiple QueryWeaver instances can run side-by-side in the same process.
Each holds its own FalkorDB connection and passes it explicitly through
every call, so there is no shared global state to collide over.
python
asyncwith QueryWeaver(falkordb_url="redis://host-a:6379", user_id="tenant_a") as a, \
QueryWeaver(falkordb_url="redis://host-b:6379", user_id="tenant_b") as b:
sales = await a.connect_database("postgresql://user:pass@host-a/sales")
ops = await b.connect_database("postgresql://user:pass@host-b/ops")
await a.query(sales.database_id, "Show top customers")
await b.query(ops.database_id, "Count open tickets")
Available Methods
Method
Description
connect_database(db_url)
Connect PostgreSQL/MySQL and load schema
query(database, question)
Convert natural language to SQL and execute
get_schema(database)
Retrieve database schema (tables and relationships)
list_databases()
List all connected databases
delete_database(database)
Remove database from FalkorDB
refresh_schema(database)
Re-sync schema after database changes
execute_confirmed(database, sql)
Execute confirmed destructive operations
Advanced Query Options
For multi-turn conversations, custom instructions, or per-request LLM overrides:
python
from queryweaver import QueryWeaver, QueryRequest
request = QueryRequest(
question="Show their recent orders",
chat_history=["Show all customers from NYC"],
result_history=["Found 42 customers..."],
instructions="Use created_at for date filtering",
# Optional per-request LLM overrides โ bypass env-based config
custom_api_key="sk-...",
custom_model="openai/gpt-4.1",
)
result = await qw.query("mydb", request)
result = await qw.query("mydb", "Delete inactive users")
if result.requires_confirmation:
print(f"Destructive SQL: {result.sql_query}")
# Execute after user confirms
confirmed = await qw.execute_confirmed("mydb", result.sql_query)
Requirements
Python 3.12+
FalkorDB instance (local or remote)
OpenAI or Azure OpenAI API key (for LLM)
Target SQL database (PostgreSQL or MySQL)
Development
Follow these steps to run and develop QueryWeaver from source.
Prerequisites
Python 3.12+
uv (Python package manager)
A FalkorDB instance (local or remote)
Node.js and npm (for the React frontend)
Install and configure
Quickstart (recommended for development):
bash
# Clone the repo
git clone https://github.com/FalkorDB/QueryWeaver.git
cd QueryWeaver
# Install dependencies (backend + frontend) and start the dev server
make install
make run-dev
If you prefer to set up manually or need a custom environment, use uv:
bash
# Install Python (backend) and frontend dependencies
uv sync# Create a local environment filecp .env.example .env# Edit .env with your values (set APP_ENV=development for local development)
Run the app locally
bash
uv run uvicorn api.index:app --host 0.0.0.0 --port 5000 --reload
Alternatively, the repository provides Make targets for running the app:
bash
make run-dev # development server (reload, debug-friendly)
make run-prod # production mode (ensure frontend build if needed)
Frontend build (when needed)
The frontend is a modern React + Vite app in app/. Build before production runs or after frontend changes:
bash
make install # installs backend and frontend deps
make build-prod # builds the frontend into app/dist/# or manuallycd app
npm ci
npm run build
OAuth configuration
QueryWeaver supports Google and GitHub OAuth. Create OAuth credentials for each provider and paste the client IDs/secrets into your .env file.
Google: set authorized origin and callback http://localhost:5000/login/google/authorized
GitHub: set homepage and callback http://localhost:5000/login/github/authorized
Environment-specific OAuth settings
For production/staging deployments, session cookies are HTTPS-only by default. Only an APP_ENV that reads as development once trimmed and lower-cased turns that off, so a deployment that forgets the variable still gets secure cookies. Set APP_ENV=development for plain-HTTP local runs, otherwise the browser drops the cookie and you get OAuth CSRF state mismatch errors.
The signed session cookie is the browser's only credential. An api_token is never written to a browser cookie - a bearer token in a cookie sits on disk in clear text for its whole lifetime - so programmatic clients fetch one from the tokens API instead. Sessions issued before this change keep working: the legacy api_token cookie is still accepted, just no longer handed out.
bash
# For production/staging (HTTPS-only session cookies - also the default)
APP_ENV=production
# For development (allows HTTP session cookies)
APP_ENV=development
Important: If you're getting "mismatching_state: CSRF Warning!" errors on a plain-HTTP environment, ensure APP_ENV is set to development.
AI/LLM configuration
QueryWeaver supports multiple AI providers. Set one API key and QueryWeaver auto-detects which provider to use.
Quick note: many tests require FalkorDB to be available. Use the included helper to run a test DB in Docker if needed.
Prerequisites
Install dev dependencies: uv sync
Start FalkorDB (see make docker-falkordb)
Install Playwright browsers: uv run playwright install
Quick commands
Recommended: prepare the development/test environment using the Make helper (installs dependencies and Playwright browsers):
bash
# Prepare development/test environment (installs deps and Playwright browsers)
make setup-dev
Alternatively, you can run the E2E-specific setup script and then run tests manually:
bash
# Prepare E2E test environment (installs browsers and other setup)
./setup_e2e_tests.sh
# Run all tests
make test# Run unit tests only (faster)
make test-unit
# Run E2E tests (headless)
make test-e2e
# Run E2E tests with a visible browser for debugging
make test-e2e-headed
Test types
Unit tests: focus on individual modules and utilities. Run with make test-unit or uv run python -m pytest tests/ -k "not e2e".
End-to-end (E2E) tests: run via Playwright and exercise UI flows, OAuth, file uploads, schema processing, chat queries, and API endpoints. Use make test-e2e.
See tests/e2e/README.md for full E2E test instructions.
CI/CD
GitHub Actions run unit and E2E tests on pushes and pull requests. Failures capture screenshots and artifacts for debugging.
Troubleshooting
FalkorDB connection issues: start the DB helper make docker-falkordb or check network/host settings.
Playwright/browser failures: install browsers with uv run playwright install and ensure system deps are present.
Missing environment variables: copy .env.example and fill required values.
OAuth "mismatching_state: CSRF Warning!" errors: Session cookies are HTTPS-only unless APP_ENV reads as development once trimmed and lower-cased. Set APP_ENV=development for plain-HTTP environments; use production or staging (or leave the variable out entirely) for HTTPS deployments.
Project layout (high level)
api/ โ FastAPI backend
app/ โ React + Vite frontend
tests/ โ unit and E2E tests
License
Licensed under the GNU Affero General Public License (AGPL). See LICENSE.