Permite que los agentes LLM realicen diagnósticos de solo lectura en SQL Server utilizando Query Store, planes de ejecución y estadísticas de espera.
También conocido como deepeshd87/mcp-sql-querystore
- Stars
- 1
- Herramientas
- 6
- Descargas, 30 días
- 124
- Última versión
- 0.1.1
- Último commit
- 3 oct 2026
- Licencia
- MIT
¿Qué es sql-querystore MCP?
Permite que los agentes LLM realicen diagnósticos de solo lectura en SQL Server utilizando Query Store, planes de ejecución y estadísticas de espera. Expone 6 herramientas, como get_regressed_queries, get_query_execution_plan, analyze_parameter_sniffing.
Resumen generado a partir del README del proyecto
Acerca del MCP server de sql-querystore
Los administradores de bases de datos y desarrolladores pueden diagnosticar problemas de rendimiento de SQL Server directamente a través de un cliente de IA usando este MCP server de solo lectura. Se conecta a tu instancia de SQL Server para exponer datos de diagnóstico de Query Store, Dynamic Management Views y planes de ejecución. Al proporcionar a un LLM acceso a estas métricas específicas, puedes realizar triajes de rendimiento complejos sin tener que escribir consultas de diagnóstico manuales.
El servidor funciona como un servidor stdio y requiere tener instalado ODBC Driver 18 for SQL Server en el host. La seguridad se mantiene mediante un login de SQL dedicado con permisos VIEW DATABASE STATE, lo que garantiza que el agente no pueda acceder a las tablas de usuario ni modificar datos. Puedes configurar la conectividad mediante variables de entorno, incluyendo opciones para autenticación integrada o archivos de contraseñas para mantener las credenciales fuera de tus archivos de configuración.
Herramientas específicas permiten realizar análisis profundos, como get_regressed_queries para identificar caídas de rendimiento, analyze_parameter_sniffing para encontrar planes inestables y get_missing_index_impact para priorizar necesidades de indexación. La herramienta sweep_regressions incluso permite escanear todas las bases de datos con Query Store habilitado a la vez para encontrar los problemas más graves.
Qué puedes hacer con él
- 1Identificar consultas con regresiónPide a la IA que encuentre consultas que se hayan vuelto significativamente más lentas en comparación con un baseline previo.
- 2Analizar planes de ejecuciónSolicita un resumen de un plan de ejecución de una consulta específica para buscar advertencias o índices faltantes.
- 3Diagnosticar estadísticas de esperaDetermina si la lentitud de la base de datos es causada por cuellos de botella en CPU, memoria o IO.
- 4Detectar parameter sniffingEncuentra consultas que sufren de planes de ejecución inestables debido al parameter sniffing.
- 5Realizar barridos en múltiples bases de datosInstruye al agente para que escanee cada base de datos en línea en busca de las regresiones de rendimiento más severas.
Escrito a partir del README del proyecto. Cada caso de uso se verifica con una cita del mismo.
Cómo instalar sql-querystore MCP
Formatos verificados el 10 nov 2026Añadir a CursorAñadir a GooseInstalar sql-querystore MCP en Claude Code
$ claude mcp add mcp-sql-querystore -- uvx mcp-sql-querystoreInstalar sql-querystore MCP en Cursor
~/.cursor/mcp.json
{
"mcpServers": {
"mcp-sql-querystore": {
"command": "uvx",
"args": [
"mcp-sql-querystore"
]
}
}
}Instalar sql-querystore MCP en VS Code
.vscode/mcp.json
{
"servers": {
"mcp-sql-querystore": {
"type": "stdio",
"command": "uvx",
"args": [
"mcp-sql-querystore"
]
}
}
}Instalar sql-querystore MCP en VS Code CLI
$ code --add-mcp '{"name":"mcp-sql-querystore","type":"stdio","command":"uvx","args":["mcp-sql-querystore"]}'Instalar sql-querystore MCP en Claude Desktop
claude_desktop_config.json
{
"mcpServers": {
"mcp-sql-querystore": {
"command": "uvx",
"args": [
"mcp-sql-querystore"
]
}
}
}Instalar sql-querystore MCP en Codex
$ codex mcp add mcp-sql-querystore -- uvx mcp-sql-querystoreInstalar sql-querystore MCP en Codex config.toml
~/.codex/config.toml
[mcp_servers.mcp-sql-querystore] command = "uvx" args = ["mcp-sql-querystore"]
Instalar sql-querystore MCP en Gemini CLI
$ gemini mcp add -s user mcp-sql-querystore uvx -- mcp-sql-querystoreInstalar sql-querystore MCP en Gemini settings.json
~/.gemini/settings.json
{
"mcpServers": {
"mcp-sql-querystore": {
"command": "uvx",
"args": [
"mcp-sql-querystore"
]
}
}
}Herramientas de sql-querystore MCP 6
Detectado desde el READMEget_regressed_queriesget_query_execution_plananalyze_parameter_sniffingget_missing_index_impactget_wait_statssweep_regressions
| get_regressed_queries | — | |
| get_query_execution_plan | — | |
| analyze_parameter_sniffing | — | |
| get_missing_index_impact | — | |
| get_wait_stats | — | |
| sweep_regressions | — |
Verificaciones automáticas
Ejecutado 14 nov 2026Informe completo →Pasó nuestras verificaciones automáticas. Esto no es una auditoría de seguridad: lee el código y dale al servidor el acceso más limitado que necesite. Cómo funcionan las verificaciones
- Repositorio de origen vinculado y accesibledeepeshd87/mcp-sql-querystore is public and reachablegithub.com/deepeshd87/mcp-sql-querystore ↗Aprobado
- El paquete indica este repositorio como su origenmcp-sql-querystore names deepeshd87/mcp-sql-querystore as sourcepypi.org/project/mcp-sql-querystore/ ↗Aprobado
- Procedencia de la compilación (atestación de Sigstore)No build attestation published for this releaseNo verificado
- Licencia de código abierto (OSI)MITspdx.org/licenses/MIT.html ↗Aprobado
- Commit o lanzamiento en el último añoLast commit or release 2026-10-03github.com/deepeshd87/mcp-sql-querystore ↗Aprobado
- OpenSSF ScorecardNo verificado
- El nombre del paquete no es similar a un paquete popularNo popular package one edit away from mcp-sql-querystoreAprobado
- No hay avisos críticos en el paquete ni en sus dependencias31 resolved dependencies checked; no critical advisoryosv.dev ↗Aprobado
- Sin instrucciones ocultas para el modelo6 tool descriptions and the README read; no override phrases, credential paths or hidden charactersAprobado
- Las herramientas destructivas están etiquetadasNo tool named like delete, drop or execAprobado
- El endpoint remoto responde al handshake de MCPNo verificado
README
Ver en GitHubmcp-name: io.github.deepeshd87/mcp-sql-querystore
mcp-sql-querystore
Read-only MCP server exposing SQL Server Query Store diagnostics to LLM agents.
Six read-only diagnostic tools over Query Store, DMVs, and execution plans. The tools have been validated against a live SQL Server instance and are covered by a unit + integration test suite. Still validate against a non-prod instance of your own before pointing it at production, especially on SQL Server versions other than those noted under caveats.
Quickstart
-
Provision a read-only login. Run
provisioning/create_readonly_login.sqlagainst your instance (edit names first). This login's permissions are the read-only guarantee — see the security model below. -
Install.
pip install -e .in a virtual environment. ODBC Driver 18 for SQL Server must be installed on the host. -
Store the password outside the repo. Put it in a plain-text file somewhere the repo can't reach (not under the project folder):
# Windows PowerShell, UTF-8, password only, no quotes/newline New-Item -ItemType Directory -Force C:\Users\you\secrets | Out-Null Set-Content -NoNewline -Encoding utf8 C:\Users\you\secrets\mcp_sql.pwd 'your-password'Or skip the password entirely with integrated auth (
MCP_SQL_TRUSTED=yes) — preferred for CJIS/PCI. See Secret handling below for all options. -
Configure your MCP client. Copy the
sql-querystoreblock fromclaude_desktop_config.example.jsoninto your real Claude Desktop config (Windows:%APPDATA%\Claude\claude_desktop_config.json), then replace the placeholder paths, server name, andMCP_SQL_PWD_FILE. SetMCP_SQL_TRUST_CERT=yesonly for a self-signed/local cert; leave itnoagainst instances with proper certificates. -
Restart your MCP client and confirm the server shows as running.
Never commit your real config or your password file. .gitignore already
excludes *.pwd, .env, and claude_desktop_config.json.
Security model (read this first)
The read-only guarantee comes from the SQL login's permissions, not from any code in this repo:
- Provision a dedicated login with
VIEW DATABASE STATE(andVIEW SERVER STATEonly if you use server-scoped DMVs) and nothing else — nodb_datareader, noSELECTon user tables. Seeprovisioning/create_readonly_login.sql. - The keyword screen in
db.pyand the fixed SELECT-only query text are defense-in-depth, not the primary control. ApplicationIntent=ReadOnlyin the connection string only routes to a readable secondary in an availability group. On a standalone instance it does not make the session read-only. Do not rely on it for safety.- Credentials never belong in code. The simplest setup uses the
MCP_SQL_CONNECTION_STRINGenv var, but for CJIS/PCI environments prefer integrated auth or a file/secret-store-sourced password — see the Secret handling section below. - Every query is recorded via the audit logger — see Audit logging below. In a regulated environment, route that logger to a durable file or SIEM.
Setup
ODBC Driver 18 for SQL Server must be installed on the host. Install the package, then configure the connection via environment variables (see Secret handling for all options). The recommended form keeps the password in a file, not inline:
pip install -e .
# PowerShell — connection assembled from parts, password read from a file
$env:MCP_SQL_SERVER = "yourhost\INSTANCE"
$env:MCP_SQL_DATABASE = "master"
$env:MCP_SQL_UID = "mcp_readonly"
$env:MCP_SQL_PWD_FILE = "C:\path\to\your\secret.pwd"
$env:MCP_SQL_TRUST_CERT = "no" # "yes" only for a self-signed/local cert
python -m mcp_sql_querystore.server
Or use integrated auth with no stored password at all (MCP_SQL_TRUSTED=yes).
A full MCP_SQL_CONNECTION_STRING is also accepted for simple cases — see
Secret handling.
Register it with your MCP client (e.g. Claude Desktop) as an stdio server
invoking python -m mcp_sql_querystore.server; see
claude_desktop_config.example.json.
Tools
All tools are read-only and take a database_name (except sweep_regressions,
which can sweep all databases). Each returns JSON, or a structured error dict on
failure rather than raising.
- get_regressed_queries — compares a recent window against an earlier
baseline window per query and flags those worse by at least
regression_threshold. A real baseline-vs-recent comparison, not a top-CPU list. - get_query_execution_plan — returns compiled plans for a
query_idwith a compact JSON summary (missing indexes, warnings incl. implicit conversions, key lookups) and optional raw XML. - analyze_parameter_sniffing — finds queries with multiple compiled plans and ranks them by the ratio of slowest to fastest plan mean duration — the classic parameter-sniffing signature.
- get_missing_index_impact — scans recent plans containing missing-index recommendations, parses the impact score from the plan XML, and aggregates duplicate recommendations across queries, ranked by impact then recurrence.
- get_wait_stats — aggregates query wait time by wait category over a window, showing why queries are slow (CPU, blocking/locks, IO, memory) rather than which. De-duplicates flushed vs in-memory rows per Microsoft guidance.
- sweep_regressions — runs regression detection across all Query Store-enabled
online databases (or an explicit
database_nameslist) and returns the worst per database, ranked. One failing database does not abort the sweep; its error is collected and reported.
Example prompts
Once the server is connected to your MCP client, you drive the tools in plain
language. Name the target database in the prompt (except sweep_regressions,
which can scan all of them). Replace YourDB with your database name.
Wait stats — why queries are slow
- "What are the top wait categories in YourDB over the last week?"
- "Is YourDB waiting on CPU, memory, or IO?"
- "Show me wait stats for YourDB over the last 24 hours."
Execution plans
- "Get the execution plan for query_id 10 in YourDB and summarize it."
- "Does query_id 13 in YourDB have missing index recommendations?"
- "Are there implicit conversion warnings in query 12's plan in YourDB?"
Regression analysis
- "Check YourDB for CPU regressions over the last 24 hours."
- "Which queries in YourDB regressed by more than 30%?"
- "Find duration regressions in YourDB, ignoring anything with fewer than 10 executions."
Parameter sniffing
- "Check YourDB for parameter sniffing."
- "Which queries in YourDB have unstable plans?"
Missing indexes
- "What missing indexes does YourDB need most?"
- "Show me the top 10 index recommendations for YourDB by impact."
Multi-database sweep (no database name needed)
- "Sweep all my databases for CPU regressions."
- "Which database has the worst regressions this week?"
Combined — chaining tools in one turn
- "Find the biggest CPU regression in YourDB, pull its plan, and tell me why it might have regressed."
- "YourDB feels slow — diagnose it." (wait stats → regressions → plans)
- "Full performance triage of YourDB: wait stats, top regressions, and missing indexes."
Known caveats / TODO
- Version differences. Query Store column names assume SQL Server 2019+/2022 and Azure SQL MI. Verify against 2016/2017 if you target those.
- Regression semantics. Current logic uses execution-weighted averages. You
may prefer percentile-based comparison (Query Store doesn't store percentiles
directly, so that needs
*_stdevcolumns and assumptions). - Not time-windowed:
analyze_parameter_sniffingaggregates across all Query Store history; on busy databases consider adding arecent_hoursfilter like the other tools have. - Remaining hardening: connection retry with backoff, and version-aware column handling for mixed 2016/2017/2019/2022 fleets.
Secret handling
The connection string is resolved in this order, so the password need not sit in plaintext config:
MCP_SQL_CONNECTION_STRING— the full string (simplest; back-compat).MCP_SQL_CONNECTION_STRING_FILE— path to a file holding the full string (Docker/K8s secret-mount style).- Assembled from parts:
MCP_SQL_SERVER(+MCP_SQL_DATABASE,MCP_SQL_DRIVER,MCP_SQL_ENCRYPT,MCP_SQL_TRUST_CERT,MCP_SQL_EXTRA). Auth is either:- Integrated (preferred for CJIS/PCI — no password stored):
MCP_SQL_TRUSTED=yes. - SQL auth:
MCP_SQL_UIDplus the password fromMCP_SQL_PWD_FILE(a vault-mounted file),MCP_SQL_PWD_ENV(name of another env var), orMCP_SQL_PWD(direct; least preferred).
- Integrated (preferred for CJIS/PCI — no password stored):
Timeouts: MCP_SQL_CONNECT_TIMEOUT (default 10s) and MCP_SQL_QUERY_TIMEOUT
(default 30s, 0 disables).
Audit logging
Every query attempt is logged via the mcp_sql_querystore.audit logger: tool,
database, a 12-char hash of the SQL (not the text), row count, elapsed ms, and
outcome. Connection strings, SQL text, and parameter values are never logged.
Configure a handler for that logger to route the audit trail to a file or SIEM.
Testing
Unit tests (no database, safe in CI):
pip install -e ".[test]"
pytest
Integration tests (real instance, opt-in):
# set a working connection (any form above), then:
$env:MCP_SQL_TEST_DATABASE = "RAG"
$env:MCP_SQL_RUN_INTEGRATION = "1"
pytest tests/test_integration.py -v
Preguntas sobre sql-querystore MCP
¿Cómo agrego sql-querystore MCP a Claude Code?
Ejecuta claude mcp add mcp-sql-querystore -- uvx mcp-sql-querystore en tu terminal. Añade --scope user para que esté disponible en todos los proyectos.
¿Cómo agrego sql-querystore MCP a Cursor?
Abre ~/.cursor/mcp.json y añade el servidor en mcpServers, usando la configuración de Cursor que se muestra en la sección de instalación de arriba.
¿Qué herramientas proporciona sql-querystore MCP?
Expone 6 herramientas, incluidas get_regressed_queries, get_query_execution_plan, analyze_parameter_sniffing, get_missing_index_impact, get_wait_stats.
¿Es seguro usar este servidor en bases de datos de producción?
El servidor es de solo lectura, pero deberías validarlo primero en una instancia que no sea de producción, especialmente en versiones de SQL Server distintas a las mencionadas en las advertencias.
¿A qué tipo de información de diagnóstico puede acceder la IA?
El servidor proporciona herramientas para consultas con regresión, planes de ejecución, análisis de parameter sniffing, impacto de índices faltantes y estadísticas de espera.
¿El servidor registra información sensible como el texto SQL?
No, el registrador de auditoría guarda la herramienta, la base de datos, un hash del SQL, el recuento de filas y el tiempo transcurrido, pero nunca las cadenas de conexión, el texto SQL ni los valores de los parámetros.