io.github.S-CurveLabs/sqlglass
OfficialThis server is an MCP tool that helps you write, check, and manage SQL Server/Azure SQL queries safely: it provides real schema info, read-only query execution, query analysis and linting, dry-run previews of writes, DDL script generation, and a versioned library of saved queries.
Schema exploration: list connections, refresh schema cache, list/describe/search tables, and find join paths between tables.
Query building & analysis: generate SELECTs from tables/columns/aggregates/filters, analyze what a query touches, format SQL, and translate between SQL dialects.
Linting: catch correctness, performance, and style issues, including unknown tables/columns when a cached schema is available.
Safe execution: run read-only SELECT/WITH queries with row caps, timeouts, and rollback; get estimated execution plans without executing the query.
Dry-run writes: preview what an UPDATE/DELETE/INSERT would change as a read-only SELECT, with affected-row counts; never actually writes.
DDL scripting: generate CREATE TABLE / PROCEDURE / VIEW scripts as text for human review, with undo scripts and notes.
Query library: save, list, retrieve, delete, lint, search, and version
.sqlquery files; find usages, rename tables/columns across queries, extract parameters, and restore snapshots.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@io.github.S-CurveLabs/sqlglass Show me the schema for the Customers table"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
sqlglass
An MCP server that gives GitHub Copilot (VS Code agent mode) — or any MCP client — what it lacks when writing SQL for SQL Server / Azure SQL: the real schema, a safe way to try a query, the optimizer's opinion of it, and a managed library of the queries you keep.
Area | Tools |
Schema (cached, works offline after first read) |
|
Build & check (no database needed) |
|
Execute, read-only |
|
Writes, as a dry run |
|
New objects, as script text |
|
Query library ( |
|
Read-only, in layers
Guard – the statement is tokenised; anything but
SELECT/WITH … SELECT(plusDECLARE/SET @var) is refused before a connection is opened. Because T-SQL needs no semicolons, any write/DDL/EXECkeyword anywhere outside a string, comment or[quoted name]rejects the batch — includingSELECT … INTO,OPENROWSET,sp_*/xp_*,WAITFOR.Transaction – every query runs with autocommit off and is always rolled back. The ODBC connection is opened read-only with
ApplicationIntent=ReadOnly.Limits – rows are capped (
max_rows, default 200) and queries time out (timeout_seconds, default 30).explain_queryusesSET SHOWPLAN_XML ON: the server compiles the query and executes nothing.Yours to add – point the connection at a login that only has
db_datareader(+GRANT SHOWPLANfor plans). That is the layer the server itself enforces; use it for anything that matters.
Values go in as bound parameters (params={"@Start": "2026-01-01"}), not pasted into SQL text.
Passwords are never stored: SQL-auth connections name an environment variable (password_env).
Related MCP server: sql-explorer-mcp
Writes and DDL: previewed and scripted, never executed
The server has no write mode. Instead:
preview_write turns one write statement into read-only SQL (plus a COUNT(*) of affected rows) and can run it:
UPDATE h SET h.Status = 'CLOSED' FROM dbo.PoHeader h JOIN dbo.Vendor v ON ... WHERE v.Country = 'US'
-- becomes
SELECT [h].[PoId], [h].[Status] AS [Status (current)], 'CLOSED' AS [Status (new)]
FROM dbo.PoHeader AS h JOIN dbo.Vendor AS v ON ... WHERE v.Country = 'US'UPDATE → key columns + a current/new pair per SET column (changed_only=true hides no-op rows, NULL-safe via EXCEPT);
DELETE → the rows that would go, plus which child tables reference them; INSERT → the rows that would be added under
the target's column names, plus NOT NULL columns left unsupplied. MERGE is refused with advice to split it. The generated
text must itself pass the read-only guard before it is returned. Triggers, cascades and constraint failures are not simulated.
build_create_table / build_procedure / build_view return DDL text (sql, undo_sql, notes) for a person to
review and run in SSMS. Checked against the cached schema: the name must be free, foreign keys must reference a real
primary/unique key with matching types (and get an index), constraints get conventional names, CREATE TABLE is wrapped
in IF OBJECT_ID(...) IS NULL. build_procedure(query="open-po-value-by-vendor") wraps a library query and turns its
header params into typed procedure parameters; every @variable must be declared. save_query(kind="script") keeps a
script in the library — versioned with the queries, never linted as a query, never runnable through the server.
Install
pip install sqlglass # or run it without installing: uvx sqlglassNeeds Python 3.11+ and a SQL Server ODBC driver. The legacy SQL Server driver that ships with Windows works for
Windows/SQL authentication; Azure SQL / Entra ID sign-in needs "ODBC Driver 18 for SQL Server". On Linux/macOS,
install unixODBC plus Microsoft's ODBC driver.
Copy sqlglass.example.toml to sqlglass.toml in your workspace (or in
%LOCALAPPDATA%\sqlglass\) and define your connections. Passwords never go in the file.
VS Code / Copilot. Add the server to the user-level %APPDATA%\Code\User\mcp.json so it works from every
window (a workspace .vscode/mcp.json only loads once you trust that workspace's MCP servers):
"sqlglass": {
"type": "stdio",
"command": "uvx",
"args": ["sqlglass"],
"env": { "SQLGLASS_WORKSPACE": "C:\\path\\to\\your\\project", "REPORTING_SQL_PASSWORD": "${input:reporting-sql-pwd}" }
}with a matching "inputs": [{ "id": "reporting-sql-pwd", "type": "promptString", "password": true, "description": "..." }].
VS Code asks for the password once and keeps it in its secret storage — never put the value in the file, and do not
rely on a user environment variable: a VS Code process started before the variable existed will never see it.
Verified 2026-09-21 with Copilot agent mode (GPT-5.6): list_tables → describe_table ×3 → build_select → lint_sql →
explain_query → run_query, 19 steps, results identical to a direct run.
Config lookup order: $SQLGLASS_CONFIG → $SQLGLASS_WORKSPACE\sqlglass.toml → .\sqlglass.toml → %LOCALAPPDATA%\sqlglass\sqlglass.toml.
Schema cache and snapshots live under %LOCALAPPDATA%\sqlglass\ (override with SQLGLASS_HOME).
The query library
A folder of plain .sql files; the id is the path without .sql. Each opens with a header:
-- name: Open POs by vendor
-- description: Open purchase-order value per vendor since a start date.
-- connection: erp
-- tags: purchasing, monthly
-- param: @StartDate date = '2026-01-01' | first order date to include
SELECT v.Name, SUM(l.Amount) AS OpenValue
FROM dbo.PoHeader AS h
JOIN dbo.Vendor AS v ON v.VendorId = h.VendorId
...
WHERE h.OrderDate >= @StartDateThe body does not declare its parameters — the server does that when running it (in SSMS, add the DECLAREs
yourself). Git is the history; on top of that every write through the server takes a snapshot first
(restore_snapshot undoes it), returns a diff, and supports dry_run.
find_usage("dbo.Vendor", "Name")– which saved queries break if this changes.rename_in_library– follow a table/column rename through every query, token-aware (strings/comments untouched).lint_libraryafterrefresh_schema– finds queries that reference tables/columns that no longer exist.
Lint rules
Correctness: join-without-on comma-join not-in-subquery left-join-filtered-in-where top-without-order-by
between-date-end undeclared-parameter unused-parameter parameter-declared-twice unused-cte
· Performance: non-sargable-predicate leading-wildcard-like select-star nolock distinct-over-join union-distinct
· Style: order-by-ordinal missing-schema-prefix unqualified-column
· With a cached schema: unknown-table unknown-column (with did-you-mean).
Layout
src/sqlglass/ — tsql/ (lexer, read-only guard, sqlglot analysis) → pure lint / refactor / builder / preview / ddl / plan
(SHOWPLAN XML summariser) / schema (model + cache + FK join paths) → engines/ (mssql over pyodbc, sqlite for
tests and local files) → library + snapshots → server.py (the tools).
Development
git clone https://github.com/S-CurveLabs/sqlglass; cd sqlglass
python -m venv .venv
.venv\Scripts\pip install -e .[dev]
.venv\Scripts\pytestEverything except the live SQL Server path runs against a SQLite fixture. To exercise engines/mssql.py, define a
connection and run set SQLGLASS_TEST_CONNECTION=<name> then pytest -m mssql.
Not built yet
A write mode (by design), reading existing procedure / view definitions from the database, MERGE previews, actual (post-execution) plans and STATISTICS IO,
Postgres/MySQL engines, SQL embedded in Power Query (Value.NativeQuery).
Available Tools
29 toolsanalyze_sqlBRead-only
What a query touches: tables/views, columns per table, CTEs, parameters and its output columns.
Inputs: sql (required).
build_create_tableARead-only
Generate a CREATE TABLE script (TEXT ONLY -- this server never runs DDL; the user reviews and runs it). Checked against the cached schema: the name must be free, foreign keys must point at a real primary/unique key with the same column types, FK columns get an index, constraints get conventional names, and the script is wrapped in IF OBJECT_ID(...) IS NULL so it can be re-run. Returns sql + undo_sql + notes.
name: "dbo.VendorScore" columns: [{"name": "VendorScoreId", "type": "int", "identity": true}, {"name": "VendorId", "type": "int", "nullable": false}, {"name": "Score", "type": "decimal(5,2)", "nullable": false, "default": "0", "description": "0-100"}] primary_key: ["VendorScoreId"] foreign_keys: [{"columns": ["VendorId"], "references": "dbo.Vendor"}] (ref_columns default to the parent's primary key) indexes: [{"columns": ["ScoredOn"], "include": ["Score"], "unique": false}]
Inputs: name (required), columns (required), indexes, connection, +3 more.
build_procedureARead-only
Generate a CREATE OR ALTER PROCEDURE script (TEXT ONLY -- never executed here) around a query. Give inline 'sql', or a library 'query' -- then its header params (name, type, default) become the procedure's parameters automatically. Every @variable in the body must be a typed parameter. params: [{"name": "@StartDate", "type": "date", "default": "'2026-01-01'", "description": "first order date"}] Returns sql + undo_sql + notes (including an EXEC example).
Inputs: name (required), sql, query, params, +1 more.
build_selectARead-only
Generate a SELECT from the cached schema: names validated, joins inferred from foreign keys (bridge tables added automatically), aliases assigned, GROUP BY derived. Returns SQL text only; nothing is executed.
tables: ["dbo.PoHeader", "dbo.Vendor"] (first = FROM; the rest are joined) columns: ["Vendor.Name", "PoHeader.OrderDate"] (Table.Column, or a bare Column when unambiguous) aggregates: [{"fn": "SUM", "column": "PoLine.Amount", "alias": "Total"}] fn: SUM COUNT COUNT_DISTINCT AVG MIN MAX filters: ["PoHeader.OrderDate >= @Start", "Vendor.Country = 'US'"] (ANDed; use @params for values) order_by: ["Total DESC"] top: 50 join_type: INNER | LEFT
Inputs: tables (required), top, columns, filters, +5 more.
build_viewARead-only
Generate a CREATE OR ALTER VIEW script (TEXT ONLY -- never executed here) from a SELECT or a library query. Refuses what a view cannot contain: parameters, DECLARE, ORDER BY without TOP.
Inputs: name (required), sql, query, description.
delete_queryADestructive
Remove a query from the library. Its text is kept in a snapshot, so restore_snapshot brings it back.
Inputs: query (required), dry_run.
describe_tableARead-only
Columns (type, nullability, identity/computed), primary key, indexes, foreign keys in both directions and row count of one table or view. Always do this before writing SQL against a table.
Inputs: table (required), connection.
explain_queryARead-only
Estimated execution plan, summarised: the expensive operators, scans on big tables, key lookups, sorts, implicit conversions, optimizer warnings and missing-index suggestions. The query is compiled, NOT executed, so this is safe on heavy queries. (SQL Server login needs the SHOWPLAN permission.)
Inputs: sql, query, params, connection.
extract_parameterB
Turn a hard-coded value in a saved query into a parameter: every occurrence of the literal ('2026-01-01', 100) becomes @param, and a '-- param:' header line is added with the old value as its default.
Inputs: param (required), query (required), literal (required), dry_run, +1 more.
find_join_pathBRead-only
How two tables relate: the shortest chain of declared foreign keys between them, as ready-to-use JOIN lines.
Inputs: to_table (required), from_table (required), connection.
find_usageARead-only
Impact analysis: which saved queries read a given table/view (and optionally a given column of it). Ask this before a table or column is changed, renamed or retired.
Inputs: table (required), column.
format_sqlARead-only
Pretty-print T-SQL in one canonical style. Normalises cosmetics (adds AS to aliases, rewrites '[x] = expr' aliases to 'expr AS [x]'); meaning is unchanged. Comments inside expressions may move.
Inputs: sql (required).
get_queryBRead-only
One saved query: header fields, parameters, the SQL, what tables it touches, and lint findings.
Inputs: query (required).
lint_libraryARead-only
Lint every saved query (against each query's cached connection schema when available). Catches queries broken by a schema change: run it after refresh_schema.
Inputs: min_severity.
lint_sqlBRead-only
Check a query for correctness traps (NOT IN + NULLs, LEFT JOIN turned INNER by WHERE, join without ON, TOP without ORDER BY), performance problems (functions on filtered columns, SELECT *, NOLOCK, leading-wildcard LIKE) and style. With a connection whose schema is cached, also verifies every table and column exists.
Inputs: sql (required), connection.
list_connectionsARead-only
List the configured database connections (from sqlglass.toml), which is the default, where the query library lives, and whether each connection has a cached schema.
Inputs: no named parameters.
list_queriesARead-only
Browse the saved-query library. 'search' matches id, name, description and the SQL text; 'tag' filters by tag.
Inputs: tag, search.
list_snapshotsARead-only
Before-images taken automatically ahead of every library write, newest first.
Inputs: no named parameters.
list_tablesARead-only
List tables and views with row counts and descriptions. Filter by schema name and/or a name pattern ('invoice'). For a big database prefer search_schema.
Inputs: limit, schema, pattern, connection.
preview_writeARead-only
Dry-run a write WITHOUT writing: converts one UPDATE / DELETE / INSERT into the read-only SELECT that shows what it would do, plus a COUNT(*) of affected rows. The write statement itself is never sent to the database. UPDATE -> key columns + each SET column as '[col (current)]' / '[col (new)]' (changed_only=true hides no-op rows) DELETE -> the rows that would be removed (and which child tables reference them) INSERT -> the rows that would be added, under the target's column names run=true also executes the preview (read-only, row-capped) and returns the affected-row count and first rows. This server cannot apply the write; hand the reviewed statement to the user to run themselves.
Inputs: sql (required), run, params, connection, +1 more.
profile_tableARead-only
Per-column row count, NULLs, distinct values, min and max, in one aggregate query. Use it to learn a column's grain and range before filtering or joining on it. Up to 15 columns per call.
Inputs: table (required), columns, connection.
refresh_schemaA
Re-read tables, views, columns, keys, indexes and foreign keys from the database into the local cache. Run this when a table or column seems to be missing, or after the database changed.
Inputs: connection.
rename_in_libraryA
Follow a database rename through every saved query, token-aware (strings and comments untouched). kind='table': old='dbo.Vendor', new='dbo.Supplier' kind='column': table='dbo.Vendor', old='Name', new='VendorName' (alias-qualified references, and bare ones in single-table queries; ambiguous bare references are reported, not changed). dry_run defaults to TRUE: review the diff, then call again with dry_run=false.
Inputs: new (required), old (required), kind (required), table, +1 more.
restore_snapshotADestructive
Put the queries in a snapshot back to how they were before that write ('latest' = undo the last write). The restore is itself snapshotted, so it can be undone too.
Inputs: dry_run, snapshot_id.
run_queryARead-only
Run a read-only query and return the first rows. Give either inline 'sql' or a library 'query' (id or name). params: {"@Start": "2026-01-01"}; library queries fall back to their header defaults. Anything but SELECT/WITH is refused before reaching the database. Rows are capped at the connection's max_rows (lower it with max_rows=); to look at big data, aggregate in SQL.
Inputs: sql, query, params, max_rows, +1 more.
sample_tableBRead-only
A few rows of a table or view, to see what the values actually look like.
Inputs: table (required), rows, columns, connection.
save_queryA
Save a query to the library as .sql (id may contain folders: 'purchasing/open-pos-by-vendor'). sql is the body only -- do not DECLARE the parameters in it; describe them in params: [{"name": "@Start", "type": "date", "default": "'2026-01-01'", "description": "first order date"}] Updating an existing query needs overwrite=true; header fields left empty keep their current value. kind='script' stores DDL text from build_create_table / build_procedure / build_view (e.g. id 'ddl/usp_open_pos'): kept and versioned with the queries, but never linted as a query and never executed.
Inputs: id (required), sql (required), kind, name, +6 more.
search_schemaARead-only
Find tables and columns whose name contains the text (or matches a * ? wildcard pattern), plus tables whose description mentions it. The way to locate data in an unfamiliar database.
Inputs: pattern (required), connection.
translate_sqlARead-only
Translate a query between dialects (tsql, postgres, mysql, sqlite, snowflake, bigquery, databricks, oracle, duckdb, redshift): TOP<->LIMIT, ISNULL/COALESCE, GETDATE, DATEADD, string functions, quoting.
Inputs: sql (required), to_dialect (required), from_dialect.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 29 tools
Every tool targets a distinct operation: schema discovery, query transformation, library management, DDL generation, and execution previews are cleanly separated. Even similar-looking tools like lint_sql vs lint_library or sample_table vs profile_table have clear boundaries. No two tools appear to do the same thing.
All tool names follow a consistent imperative verb_noun pattern in snake_case: list_*, build_*, lint_*, run_*, etc. Multi-word objects like find_join_path, rename_in_library, and preview_write are formatted the same way. There are no mixed casing styles or vague single-word verbs.
At 29 tools, this far exceeds the comfortable working set, and the server would likely overwhelm an agent when deciding which tool to invoke. Several groups could be consolidated or split into separate servers (e.g., schema exploration, query library, SQL transformation, DDL generation). Each tool is purposeful, but the aggregate surface is too large.
The domain is well covered: schema introspection, query authoring and analysis, query-library CRUD with snapshots/undo, DDL script generation, and read-only execution plus write previews. Minor gaps exist such as no builders for functions/indexes and no MERGE preview, but these are niche and workable. Overall there are no dead-end workflows for the stated purpose.
Related MCP Connectors
DBRE-grade SQL analysis inside any MCP client. No connection. No install. Paste a query.
SQL validation, formatting, parsing, metadata extraction, linting, and security analysis.
Query your org's data in natural language — read-only MCP access to SQL, NoSQL, files & warehouses.
Paid remote MCP for governed database query review, SQL simulation, approvals, and audits.
Related MCP Servers
- AlicenseAqualityBmaintenanceSQL Server MCP server with AST-based query validation, read-only safety, schema exploration, ER diagram generation, and DBA toolkit integration (First Responder Kit, DarlingData, sp_WhoIsActive).128MIT
- AlicenseNot gradedqualityFmaintenanceRead-only MCP server for SQL databases (SQL Server, Postgres, SQLite) with multi-server support and three-layer safety using AST validation and linting.MIT
- AlicenseNot gradedqualityDmaintenanceRead-only SQL Server MCP server enabling safe database queries, table listing, and schema inspection with built-in security protections.MIT
- FlicenseAqualityDmaintenanceEnables read-only exploration and querying of PostgreSQL or MySQL databases via MCP, with schema discovery, safe SQL validation, natural language to SQL conversion, and CSV export.112-