Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,15 @@ DISCORD_BOT_TOKEN=
# Leave unset (or false) during normal development to avoid rate limits.
LANG2SQL_SYNC_COMMANDS=

# Optional comma-separated parent-channel IDs where non-admin guild members may
# ask DB questions. Empty means admin-only. Threads inherit the parent channel.
# Only positive numeric Discord IDs are accepted; malformed values fail startup.
LANG2SQL_DISCORD_QUERY_CHANNEL_IDS=

# Durable SQLite state for the Discord bot (sessions, audit, semantic reviews,
# encrypted credentials). Keep this file private and back it up with the key.
LANG2SQL_DATA_PATH=lang2sql_data.db

# OpenAI API key. Optional: when set, the agent uses gpt-4.1-mini. When unset,
# it falls back to the offline FakeLLM (deterministic canned tool cycles — fine
# for a smoke run, not for real answers).
Expand All @@ -22,6 +31,14 @@ LANG2SQL_LLM_BASE_URL=
# Model name as the server expects it (e.g. Qwen/Qwen3-14B-AWQ for vLLM).
LANG2SQL_LLM_MODEL=

# First-connect Enrich mode. "auto" runs one metadata-only LLM pass when a real
# OpenAI-compatible provider is configured; otherwise DB comments and physical
# names are used, plus a same-source Enrich cache when available. No mode
# samples raw rows.
# Use "metadata" to disable the LLM pass, or "llm" to require an attempted pass
# whose failure is reported explicitly while the deterministic catalog remains.
LANG2SQL_AUTO_METADATA_ENRICH=auto

# Fernet key used to encrypt stored secrets (DSNs / API keys) at rest. Optional:
# if unset, a key is auto-generated and persisted in the SQLite kv table. Set it
# in production so secrets decrypt across restarts and machines. Generate one:
Expand All @@ -39,6 +56,8 @@ LANG2SQL_SECRET_KEY=
# snowflake://user:pass@account/db/schema?warehouse=wh
# mysql+pymysql://user:pass@host/dbname
# duckdb:////absolute/path/to/file.duckdb
# oracle+oracledb://readonly_user:pass@localhost:1521/?service_name=FREEPDB1
# Oracle driver: uv sync --extra oracle (Thin mode, no Instant Client needed).
LANG2SQL_DB_URL=
# Optional default schema for the SQLAlchemy explorer.
LANG2SQL_DB_SCHEMA=
Expand All @@ -49,3 +68,10 @@ CLOUDFLARE_D1_ACCOUNT_ID=
CLOUDFLARE_D1_DATABASE_ID=
# API token with D1 read access (Account → API Tokens). Required for D1 queries.
CLOUDFLARE_API_TOKEN=

# Optional schema search. Use an OpenAI-compatible embeddings endpoint.
LANG2SQL_QDRANT_URL=
LANG2SQL_QDRANT_API_KEY=
LANG2SQL_EMBEDDING_URL=
LANG2SQL_EMBEDDING_MODEL=
LANG2SQL_EMBEDDING_API_KEY=
2 changes: 1 addition & 1 deletion .github/workflows/mcp-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,5 @@ jobs:
- uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python }}
- run: python -m pip install -e '.[mcp,tools]' pytest pytest-asyncio
- run: python -m pip install -e '.[mcp,tools,duckdb]' pytest pytest-asyncio
- run: python -m pytest -q
10 changes: 10 additions & 0 deletions docker/docker-compose-qdrant.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
services:
qdrant:
image: qdrant/qdrant:v1.18.3
ports:
- "127.0.0.1:6333:6333"
volumes:
- qdrant_data:/qdrant/storage

volumes:
qdrant_data:
32 changes: 13 additions & 19 deletions docs/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ One server process uses one DB connection and one fixed identity. Set the existi
`LANG2SQL_DB_URL` (and optionally `LANG2SQL_DB_SCHEMA`) or the existing D1 variables.
The server fails at startup if no connection is configured; it does not use the
CLI's stub DB. Configure a read-only source DB account. Metadata changes still
write to Lang2SQL's separate SQLite store.
write to the separate SQLite or Oracle metadata store.

Replace the paths below with absolute paths. The SQLite source database must
already exist. These commands register a server in the client; installation of
Expand Down Expand Up @@ -62,24 +62,18 @@ retain the existing federation semantics across teams within an organization.

| Name | Behavior |
|---|---|
| `explore_schema` | List tables or describe a table, including cached descriptions. |
| `run_sql` | Existing SQL validation, execution, audit and text result formatting. |
| `term_custom` | Existing org/team/user definitions; `list=true` reads effective definitions; registration/removal retains existing permissions. |
| `remember` | Save a note in this server process for the configured user. |
| `recall_memory` | Call the existing memory service. The default inject-all retriever returns all notes, not semantic search. |

Example client request: “Use Lang2SQL to inspect the schema and business
definitions, then calculate total revenue.” The agent should call
`term_custom({"list": true})` explicitly: the old harness's automatic system-prompt
injection does not run here. Notes are observations, not approved instructions.

`remember` notes are process-local and disappear on restart even when `--store` is
set. Business definitions and audits persist with `--store`. No new memory
algorithm, alias gate, graph experiment or extraction model is included.

`ask_user`, `enrich_schema`, `org_setup`, `ingest_doc` and `confirm_ingest` are not
advertised. The external agent asks the user directly. LLM-driven enrichment and
document ingestion remain available in existing frontends.
| `explore_schema` | Discover tables, views, column descriptions and keys. Pass `tables` to describe several objects together. |
| `resolve_business_terms` | Check all business terms in the question against the current scope. Pass an empty array for a fully specified request with no business terms. |
| `run_sql` | Pass the single-use `definition_check_id` returned by the latest successful check. Optionally validate ordered `expected_columns` and `expected_rows`. |
| `term_custom`, `context_candidates` | Browse confirmed definitions or stage a user-supplied definition for operator review. |
| `remember`, `recall_memory` | Store and retrieve notes for the current user and team. Provide a persistent metadata store to retain them across restarts. |
| `save_column_notes` | Save confirmed column descriptions using an administrator connection. |
| `calendar_interval_sql`, `fixed_decimal_sql`, `integer_ratio_sql` | Generate SQL for calendar intervals and exact numeric calculations in the supported dialect. |
| `search_schema` | Find candidate tables when the optional Qdrant index is configured. Verify their columns with `explore_schema`. |

Resolve terms again after each attempted query, including a failed query. If a business definition is missing, ask for the definition and scope. Use `lang2sql-tools decide-context` to approve or reject a staged candidate. For an approved Oracle view metric, operators can bind its contract with `lang2sql-tools bind-oracle-view`. The client then supplies the metric and date interval to `run_sql`.

Source queries are read-only by default. To let the operator-configured identity execute a single explicitly requested write, start the MCP process with `--allow-write` and a DB account with the necessary grants. The normal definition check also applies to writes. The separate `--admin` flag controls metadata administration.

## Protocol and limitations

Expand Down
3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ authors = [
{ name = "brain-crew", email = "ryan@brain-crew.com" },
]
dependencies = [
"aiohttp>=3.9,<4", # async Qdrant and embedding REST clients
"discord.py>=2.3,<3.0", # Phase 1 frontend transport
"cryptography>=42.0", # EncryptedSecrets at-rest encryption
"sqlalchemy>=2.0", # generic DB explorer (one adapter, many engines)
Expand All @@ -23,12 +24,14 @@ tools = ["jsonschema>=4.20,<5"]
mcp = ["mcp>=1.26,<2"]
# DB driver extras. The SQLAlchemyExplorer is dialect-agnostic; install only the
# drivers you connect to. Cloudflare D1 needs no driver (HTTP API via stdlib).
oracle = ["oracledb>=2.0,<4.0"]
postgres = ["psycopg[binary]>=3.2,<4.0"]
bigquery = ["sqlalchemy-bigquery>=1.11"]
snowflake = ["snowflake-sqlalchemy>=1.6"]
mysql = ["pymysql>=1.1"]
duckdb = ["duckdb-engine>=0.13"]
all-db = [
"oracledb>=2.0,<4.0",
"psycopg[binary]>=3.2,<4.0",
"sqlalchemy-bigquery>=1.11",
"snowflake-sqlalchemy>=1.6",
Expand Down
55 changes: 51 additions & 4 deletions src/lang2sql/adapters/db/d1_explorer.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,12 @@

import asyncio
import json
import math
import os
import urllib.request
from typing import Any, Callable

from ...core.ports.explorer import Column, Table
from ...core.ports.explorer import Column, QueryTimeoutUnsupportedError, Table

_API_ROOT = "https://api.cloudflare.com/client/v4"

Expand Down Expand Up @@ -73,9 +74,55 @@ async def describe_table(self, name: str) -> Table:
async def sample_rows(self, name: str, limit: int = 5) -> list[dict]:
return await self._query(f"SELECT * FROM {_ident(name)} LIMIT {int(limit)}")

async def execute(self, sql: str, limit: int = 1000) -> list[dict]:
rows = await self._query(sql)
return rows[: int(limit)]
async def execute(
self,
sql: str,
limit: int = 1000,
*,
timeout_seconds: float | None = None,
parameters: dict[str, object] | None = None,
) -> list[dict]:
if timeout_seconds is None:
if parameters:
raise ValueError(
"D1 raw reads accept positional SQL parameters only through its native adapter"
)
return (await self._query(sql))[:limit]
if not math.isfinite(timeout_seconds) or timeout_seconds <= 0:
raise ValueError("timeout_seconds must be a finite positive number")
# urllib's transport timeout cannot prove that D1 stopped server-side
# SQL. Refuse before sending until a verified server deadline exists.
raise QueryTimeoutUnsupportedError("D1 statement cancellation is not verified")

def governed_execution_supported(self) -> bool:
return False

async def catalog_metadata(self) -> dict[str, Any]:
"""Return declared SQLite PK/FK facts without sampling user data."""

tables: dict[str, Any] = {}
for table in await self.list_tables():
info = await self._query(f"PRAGMA table_info({_ident(table.name)})")
foreign_keys = await self._query(
f"PRAGMA foreign_key_list({_ident(table.name)})"
)
tables[table.name] = {
"primary_key": [row["name"] for row in info if row.get("pk")],
"foreign_keys": [
{
"columns": [row["from"]],
"referred_schema": "",
"referred_table": row["table"],
"referred_columns": [row["to"]],
}
for row in foreign_keys
],
"unique": [],
}
return {"tables": tables}

def quote_identifier(self, name: str) -> str:
return _ident(name)

# --- internals -------------------------------------------------------

Expand Down
44 changes: 42 additions & 2 deletions src/lang2sql/adapters/db/dsn_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from __future__ import annotations

from dataclasses import dataclass
from typing import Callable
from urllib.parse import quote_plus, urlsplit


Expand All @@ -23,7 +24,9 @@ class ConnectionSpec:

# Supported DB types in the wizard. Order matters — surfaces in the dropdown.
SUPPORTED_DB_TYPES: tuple[str, ...] = (
"sqlite",
"postgresql",
"oracle",
"mysql",
"snowflake",
"bigquery",
Expand All @@ -49,6 +52,29 @@ def build_postgresql(
return ConnectionSpec(dsn=dsn, extras={})


def build_oracle(
*, host: str, service_name: str, user: str, password: str
) -> ConnectionSpec:
from sqlalchemy.engine import URL

parsed = urlsplit("//" + host)
if not parsed.hostname or parsed.path or parsed.query or parsed.username:
raise ValueError("Oracle host must be a hostname with optional :port")
url = URL.create(
"oracle+oracledb",
username=user,
password=password,
host=parsed.hostname,
port=parsed.port or 1521,
query={"service_name": service_name},
)
return ConnectionSpec(dsn=url.render_as_string(hide_password=False), extras={})


def build_sqlite(*, path: str) -> ConnectionSpec:
return ConnectionSpec(dsn=f"sqlite:///{path}", extras={})


def build_mysql(
*, host: str, port: str, database: str, user: str, password: str
) -> ConnectionSpec:
Expand All @@ -75,7 +101,10 @@ def build_bigquery(*, project: str, dataset: str) -> ConnectionSpec:


def build_duckdb(*, path: str) -> ConnectionSpec:
return ConnectionSpec(dsn=f"duckdb:///{path}", extras={})
path = path.strip()
return ConnectionSpec(
dsn=path if path.startswith("duckdb:") else f"duckdb:///{path}", extras={}
)


def build_d1(*, account_id: str, database_id: str, api_token: str) -> ConnectionSpec:
Expand All @@ -89,6 +118,15 @@ def build_d1(*, account_id: str, database_id: str, api_token: str) -> Connection
# Field schemas surfaced by the Discord Modal layer. Each entry is
# (label, placeholder, required, masked).
FIELD_SCHEMA: dict[str, list[tuple[str, str, bool, bool]]] = {
"oracle": [
("host", "localhost:1521", True, False),
("service_name", "FREEPDB1", True, False),
("user", "readonly_user", True, False),
("password", "•••••", True, True),
],
"sqlite": [
("path", "/data/demo.db", True, False),
],
"postgresql": [
("host", "db.example.com", True, False),
("port", "5432", False, False),
Expand Down Expand Up @@ -125,7 +163,9 @@ def build_d1(*, account_id: str, database_id: str, api_token: str) -> Connection
}


_BUILDERS = {
_BUILDERS: dict[str, Callable[..., ConnectionSpec]] = {
"sqlite": build_sqlite,
"oracle": build_oracle,
"postgresql": build_postgresql,
"mysql": build_mysql,
"snowflake": build_snowflake,
Expand Down
40 changes: 35 additions & 5 deletions src/lang2sql/adapters/db/factory.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""build_explorer — turn a connection string into the right ExplorerPort.

This is what makes ``/connect`` trivial: the user (or env) gives one URL and the
The setup workflow (or an environment variable) supplies one URL and this
factory routes it. Cloudflare D1 has its own HTTP adapter; everything else with
a normal SQLAlchemy URL goes through the generic SQLAlchemy explorer.

Expand All @@ -14,6 +14,7 @@
from __future__ import annotations

import os
from pathlib import Path
from urllib.parse import urlsplit

from ...core.ports.explorer import ExplorerPort
Expand All @@ -26,6 +27,7 @@ def build_explorer(
*,
schema: str | None = None,
extras: dict | None = None,
allow_write: bool = False,
) -> ExplorerPort:
"""Route a connection string to the matching explorer adapter.

Expand All @@ -34,7 +36,8 @@ def build_explorer(
belong in the URL — currently ``d1_token`` for the D1 HTTP API. Raises
``ValueError`` on an empty/unparseable string.
"""
if not connection or not connection.strip():
connection = canonicalize_connection(connection)
if not connection:
raise ValueError("empty connection string")

scheme = urlsplit(connection).scheme.lower()
Expand All @@ -59,11 +62,38 @@ def build_explorer(
if scheme == "postgresql":
connection = "postgresql+psycopg" + connection[len("postgresql") :]

if scheme == "oracle":
connection = "oracle+oracledb" + connection[len("oracle") :]

# Anything else is assumed to be a SQLAlchemy URL (driver loaded lazily).
return SqlAlchemyExplorer(connection, schema=schema)
return SqlAlchemyExplorer(connection, schema=schema, allow_write=allow_write)


def canonicalize_connection(connection: str) -> str:
"""Freeze relative file-backed URLs before identity or execution uses them."""

def explorer_from_env() -> ExplorerPort | None:
value = connection.strip()
if not value:
return ""
scheme = urlsplit(value).scheme.lower()
if scheme == "postgresql":
value = "postgresql+psycopg" + value[len("postgresql") :]
scheme = "postgresql+psycopg"
if scheme.split("+", 1)[0] not in {"sqlite", "duckdb"}:
return value
from sqlalchemy.engine import make_url

url = make_url(value)
database = url.database
if not database or database == ":memory:":
return url.render_as_string(hide_password=False)
path = Path(database).expanduser()
if not path.is_absolute():
path = path.resolve(strict=False)
return url.set(database=str(path)).render_as_string(hide_password=False)


def explorer_from_env(*, allow_write: bool = False) -> ExplorerPort | None:
"""Build an explorer from environment, or ``None`` if nothing is configured.

Precedence: an explicit ``LANG2SQL_DB_URL`` wins; otherwise a pair of
Expand All @@ -72,7 +102,7 @@ def explorer_from_env() -> ExplorerPort | None:
url = os.environ.get("LANG2SQL_DB_URL")
if url:
schema = os.environ.get("LANG2SQL_DB_SCHEMA") or None
return build_explorer(url, schema=schema)
return build_explorer(url, schema=schema, allow_write=allow_write)

account = os.environ.get("CLOUDFLARE_D1_ACCOUNT_ID")
database = os.environ.get("CLOUDFLARE_D1_DATABASE_ID")
Expand Down
Loading
Loading