Skip to main content
Glama
Elekto MCP for SQL Server

Elekto MCP for SQL Server

Official

Elekto.Mcp.Sql

.NET NuGet NuGet Downloads License: GPL v3 CI elekto-com-br/elekto-mcp-sql MCP server

Read-only MCP server for SQL Server 2017+ introspection and querying (tested on 2019, 2022 and 2025). Exposes schema metadata, object definitions, and data queries via the MCP protocol (stdio), allowing GitHub Copilot (and other MCP clients, like Claude, etc.) to understand your database structure without storing credentials in the repository.

⚠️ Privacy and Data Security Warning

MCP servers act as a bridge between your local data and AI language models. When you use this server with an AI assistant (such as GitHub Copilot, Claude, or others), the following happens:

  1. The AI agent calls tools on this server to read data from your SQL Server database.

  2. The results — which may include table schemas, stored procedure definitions, or actual row data — are sent back to the AI agent and transmitted to the LLM provider's infrastructure for analysis.

  3. This means your data leaves your machine and is sent to a third-party service (Microsoft, Anthropic, OpenAI, etc.), subject to their respective terms of service and privacy policies.

The diagnostic tools read beyond your own queries. With VIEW SERVER STATE, get_active_requests returns the login, host name, program and SQL text of other sessions on the server, and find_cached_queries the text of every statement cached for the database, whoever ran it; query text and plans can carry the literal values and parameter values they were run or compiled with.

Before connecting this server to any database, carefully consider:

  • What data could be read? Does it include PII, financial records, trade secrets, or other sensitive information?

  • Who is the LLM provider and what are their data retention and privacy policies?

  • Are you authorized to share this data with that third party under applicable laws and regulations?

Recommendations:

  • Never connect to databases containing sensitive data unless you have explicitly assessed and accepted this risk.

  • Use database accounts with the minimum required privileges (read-only, restricted to specific schemas where possible).

  • Use max_query_rows to limit how much data can be returned in a single call.

  • Prefer databases with anonymized or synthetic data for development and exploration.

  • AI agents can be extremely creative in finding ways to execute a task. Although this server is designed to be read-only and to validate all inputs, there is always a risk of unintended consequences when exposing database access to an AI agent.

Regardless of the precautions you take, the responsibility for any consequences arising from the use of this tool rests entirely with you. This software is provided as is with no warranties of any kind.

Related MCP server: MSSQL MCP Python Server

Available Tools

Tool

Description

list_databases

Databases registered in the configuration

get_database_overview

High-level database summary (counts, size, connection metadata), and whether the login sees everything

check_permissions

What the connected login can and cannot see, the GRANT that completes it, and whether it could write

get_schema_summary

Aggregated metrics by schema (objects, rows, size)

list_schemas

Schemas in a database (excluding system schemas)

list_tables

User tables with schema, dates, approximate rows and estimated size; filterable by schema and name pattern

list_views

User views, filterable by schema and name pattern

find_columns

Every table and view holding a column whose name matches a pattern

list_procedures

User stored procedures (with basic complexity metrics)

list_functions

User-defined functions (with basic complexity metrics)

get_table_schema

Columns with unambiguous type declarations, all extended properties, PKs, FKs, checks, uniques and indexes with key order and declared key width

get_view_definition

DDL definition + columns of a view, with the same column detail

get_procedure_definition

CREATE PROCEDURE text

get_function_definition

CREATE FUNCTION text

get_dependency_graph

Object dependency edges (FK + SQL dependencies)

get_table_usage

References to a table across FKs and SQL modules

get_data_profile

Column profile (null ratio, distinct count, min/max, top values)

get_index_health

Duplicate/unused index diagnostics + missing-index suggestions + leftover hypothetical indexes

get_table_statistics

Optimizer statistics of a table: last update, sample, modifications and distance to the automatic update; a statistic's histogram and density vector, and where a value falls in it

get_optimizer_settings

Settings that change plans: compatibility level and cardinality estimator, statistics options, scoped configurations, Query Store state, server parallelism options and trace flags

list_query_store_regressions

Queries that got slower or heavier, vary the most or changed plan, comparing a recent window with the days before it, from the Query Store

find_query_store_queries

Query Store queries by part of their text or by the procedure, function or trigger that runs them, with their totals in a window

get_query_store_history

One query's Query Store history: SET options, up to 20 plans with their compile times, per plan and per day, hour or interval its executions, durations, CPU, reads and DOP, and each plan's waits by category over the window

find_cached_queries

This database's statements in SQL Server's plan cache, with their figures since each plan was cached (duration, CPU, reads, rows, DOP, memory grant, spills, recompilations) and the plan handle get_query_plan_summary takes; the source left where the Query Store is off

get_active_requests

What runs in the database now: each request with its wait and the resource waited on, the session blocking it and its current statement, and each blocking chain up to its head, even an idle session holding a transaction open from another database; shows other sessions' logins, host names and SQL text (see the warning above)

get_query_plan_summary

A Query Store plan, or a plan in the plan cache, summarized: compiled parameter values, statistics used, warnings, missing indexes and the costliest operators as a compact tree

get_estimated_plan

The plan SQL Server would compile now for a stored procedure, given values for its parameters, or for one SELECT, summarized as a Query Store plan is; nothing runs, though compiling can create and update statistics (see Limits and Security)

compare_schemas

Compares table/column structure between two configured databases

generate_dependency_dot

Graphviz DOT dependency graph with node metadata (node_kind)

query_table

SELECT from a table or view with filtering, grouping, secure aggregates, sorting, sampling and pagination

Investigating slow queries and changed plans

Since 2.4.0 the server has a set of tools for when a query got slow or its plan changed. They read what SQL Server already keeps: the Query Store, the plan cache, the requests running now, statistics and settings. None of them runs the query or changes data or schema, though compiling an estimated plan can create and update statistics (see Limits and Security).

Question

Tools

Which queries got slower or heavier, or changed plan?

list_query_store_regressions, then get_query_store_history for one of them: its plans and, per plan and per day or hour, its executions, durations, CPU, reads, DOP and waits

Where are the statements of a procedure, or of a text?

find_query_store_queries; where the Query Store is off, as it is by default before SQL Server 2022, find_cached_queries, which reads the plan cache

Why did it get this plan?

get_query_plan_summary, for a plan from either source: the parameter values it was compiled for, the statistics it used, warnings, missing indexes and the costliest operators

What was the optimizer told?

get_table_statistics (last update, sample, modifications, histogram, density) and get_optimizer_settings (compatibility level, cardinality estimator, scoped configurations, parallelism, trace flags)

Which plan would it get now, for these values?

get_estimated_plan, which compiles a procedure, or one SELECT, without running it

What runs now, and who blocks it?

get_active_requests, with each request's wait and each blocking chain up to its head

Which indexes are unused, duplicated or missing?

get_index_health

They need more than reading

The login of Recommended permissions reads everything else with db_datareader and VIEW DEFINITION. These tools need more:

Permission

Tools

VIEW DATABASE STATE in the database (2022+: VIEW DATABASE PERFORMANCE STATE)

The Query Store tools: list_query_store_regressions, find_query_store_queries, get_query_store_history and get_query_plan_summary with a plan_id

VIEW SERVER STATE (2022+: VIEW SERVER PERFORMANCE STATE), which implies the one above

find_cached_queries, get_active_requests, get_query_plan_summary with a plan_handle, and the unused and missing indexes of get_index_health

SHOWPLAN in the database

get_estimated_plan, which also needs EXECUTE on a procedure it compiles, or SELECT on what a query reads

Without one of them the tools that need it fail, saying which GRANT adds it or that a DENY refuses it, and check_permissions writes the script for that login and that server version. VIEW SERVER STATE lets the login see every session on the server, with its login, host name and SQL text: read the privacy warning at the top of this page before granting it.

Pair it with the Microsoft Learn MCP Server

These tools show what SQL Server did: the plans, statistics, waits and settings. What those mean, and what can be done about them, is in Microsoft's documentation: wait types, showplan operators and warnings, cardinality estimator versions, trace flags, Query Store hints, and how each of them differs from one version of SQL Server to the next. An agent that can read that documentation works from it, instead of from what it remembers, which may be outdated or wrong for your version. So we recommend running this server alongside the Microsoft Learn MCP Server, Microsoft's own, free and with no sign-in, at https://learn.microsoft.com/api/mcp. In Claude Code:

claude mcp add --transport http microsoft-learn https://learn.microsoft.com/api/mcp

In .mcp.json:

{
  "servers": {
    "microsoft-learn": {
      "type": "http",
      "url": "https://learn.microsoft.com/api/mcp"
    }
  }
}

It reads public documentation only, but what the agent searches for there goes to Microsoft, under the Microsoft Learn Terms of Use, and a search can carry names or text from your database: the privacy warning applies to it as well.

Caveat emptor

This server is offered in the hope that it will be useful, and we work to make what it reports correct, but nothing in it is guaranteed: caveat emptor. A summary leaves things out, the plan cache and the Query Store hold only what they kept, an estimated plan is not necessarily the one that will run, and an agent can misread any of it, however sure it sounds. Try a change (an index, a statistics update, a hint, a forced plan, a setting) where it is safe to, and measure it there, before it reaches production.

Whether to use this tool, and whether to act on what it shows or on what an agent concludes from it, are decisions of whoever makes them, and so are all their consequences, good and bad. The license says the same: the software comes without any warranty.

Release history

What changed in each version is in CHANGELOG.md, and each version's notes are also on its GitHub Release.

Upgrading from 1.x

Version 2.0.0 changes what the tools return and how their parameters are declared. Nothing needs reconfiguring — connection files, .mcp.json and the CLI arguments are unchanged — but anything that parses the output will notice:

Change

What to do

query_table returns an object, not an array

Read the rows from rows; check truncated

Failures return ok: false content instead of raising a tool error

Test for ok === false before treating the payload as data

Column results gained type_declaration, max_length_chars, is_persisted and extended_properties

Prefer type_declaration over max_length, which is bytes

description on a column is now an alias for extended_properties.MS_Description

Nothing; it still works

Optional tool parameters are no longer nullable

Nothing over MCP. Direct C# callers pass "" (or 0) instead of null

New: find_columns; list_tables and list_views take a name_pattern

Nothing; both are additive

Everything else — every other tool, every other field — is unchanged.

Reading the Results

Three things about the shape of what comes back are worth knowing before you rely on it.

Column types are reported twice, on purpose

sys.columns.max_length is documented in bytes. A nvarchar(250) column therefore reports 500, and reading that as characters is wrong by a factor of two — silently, because nothing downstream contradicts it. That raw value is still reported, for fidelity to the catalog, but never on its own:

{
  "column_name": "Tag1",
  "data_type": "nvarchar",
  "type_declaration": "nvarchar(250)",
  "max_length": 500,
  "max_length_chars": 250
}

Use type_declaration or max_length_chars. They cannot be misread.

Columns also carry extended_properties — every property, not only MS_Description — so an application's own conventions (display formats, units, masks) are visible, and is_persisted for computed columns.

query_table returns an envelope, not a bare array

A bare array of two rows cannot be told apart from a table that holds two rows. The result therefore states what it is:

{
  "table": { "schema": "Feeder", "name": "GenericSecurity" },
  "row_count": 100,
  "truncated": true,
  "top_applied": 100,
  "skip": 0,
  "max_query_rows": 10000,
  "rows": [ ... ]
}

truncated is measured rather than inferred: one row past the limit is fetched and discarded. top_requested appears only when max_query_rows overrode what was asked for.

Failures come back as content

An exception thrown from an MCP tool does not reach the caller — the host replaces it with a generic line. Failures are therefore returned as a normal result carrying ok: false:

{
  "ok": false,
  "tool": "query_table",
  "error": "'columns' looks like JSON: [\"Source\", \"Name\"]",
  "hint": "'columns' is a plain comma-separated string, not a JSON array or object.",
  "example": { "columns": "Source, Name, ReferenceDate" }
}

The trade-off is deliberate: the host no longer marks the call as an error, but the caller can read what went wrong and correct it. Successful results are unchanged and never carry an ok field.

What the login cannot see is left out without an error

SQL Server shows a login only the objects it holds some permission on (metadata visibility), and it filters the rest out silently. A login in db_datareader alone sees every table but not one procedure it cannot execute, and sees views without their text. Every catalog query then returns a normal, well-formed, short answer — "this database has 6 procedures" when it has 672.

Since the data cannot reveal that, the server checks the permissions that decide it and says so. get_database_overview, the tool to call first, carries:

"visibility": {
  "complete": false,
  "notes": [
    "The login lacks VIEW DEFINITION on the database. SQL Server then leaves out, without any error, every procedure, function and view the login holds no permission on, so their listings and counts may be short.",
    "756 of the 756 visible views, procedures and functions have their definition hidden from this login."
  ],
  "hint": "Call check_permissions for what this login is missing and the GRANT statements that fix it."
}

check_permissions then reports, for each group of tools, complete, partial or unavailable, the permission that is missing and the GRANT that adds it, in the syntax of the server's version. It also reports write_access: whether a role, a database permission or a schema- or object-level GRANT lets the login change anything, so that an account meant to be read-only can be checked rather than assumed.

Installation

Requires .NET 10 Runtime or SDK.

dotnet tool install -g Elekto.Mcp.Sql

Upgrade to a newer version:

dotnet tool update -g Elekto.Mcp.Sql

After installation the elekto-mcp-sql command is available on PATH. Use it directly in .mcp.json — no path needed:

{
  "servers": {
    "sql": {
      "type": "stdio",
      "command": "elekto-mcp-sql"
    }
  }
}

Zero-config: if your project already has a ConnectionStrings section in appsettings.json, web.config or App.config, the server picks it up automatically and no further configuration is required.

For Claude Code and Codex, see Claude Code Setup and Codex Setup.

Without installing (dnx)

The .NET 10 SDK (not the runtime alone) brings dnx, which downloads the package from NuGet and runs it, with no dotnet tool install:

{
  "servers": {
    "sql": {
      "type": "stdio",
      "command": "dnx",
      "args": ["Elekto.Mcp.Sql", "--yes"]
    }
  }
}

The package is listed among the MCP servers on nuget.org, whose MCP Server tab gives this configuration ready to paste into VS Code or Visual Studio.

From a local publish (air-gapped / corporate environments)

cd src
dotnet publish -c Release -o C:\Tools\Elekto.Mcp.Sql
{
  "servers": {
    "sql": {
      "type": "stdio",
      "command": "dotnet",
      "args": ["C:\\Tools\\Elekto.Mcp.Sql\\Elekto.Mcp.Sql.dll"]
    }
  }
}

Configuration

--connections <path>, when given, is used on its own and no other source is consulted.

Otherwise every source below is read and merged, so a database defined in one source and a database defined in another are both available. Where the same database name appears in more than one, the higher-priority source wins:

Priority

Source

1 (highest)

.elekto.mcp.sql.local.json in the working directory (project root)

2

ConnectionStrings in appsettings.Development.json

3

ConnectionStrings in appsettings.json

4

<connectionStrings> in App.config / web.config

5

.elekto.mcp.sql.local.json in the user's home directory (~)

6 (lowest)

MCP_SQL_CONNECTIONS environment variable (legacy compatibility)

Note that the home-directory file sits below the project's appsettings.json: it holds your defaults, and the project it is used in overrides them.

At startup the server logs every source that contributed to stderr, making it easy to diagnose which files are in effect.

Zero-config for existing .NET projects

If your project already has appsettings.json or web.config with a ConnectionStrings section, the server will pick them up automatically — no extra file needed.

Be Careful: the automatic discovery is convenient but may use a project connection too powerful for safe use with AI agents. If your existing connection strings have write permissions or access to sensitive data, consider using a separate connections file with read-only credentials and specifying it explicitly via --connections or by placing it in the project root.

Connection file format

The file is a JSON object mapping logical database names to their configurations.

Simple format (direct connection string):

{
  "MyDatabase": "Server=SQLSRV01\\INST;Database=MyDatabase;Integrated Security=SSPI"
}

Full format (with options):

{
  "MyDatabase": {
    "connection_string": "Server=SQLSRV01\\INST;Database=MyDatabase;Integrated Security=SSPI",
    "max_query_rows": 5000,
    "default_timeout_seconds": 30
  }
}

Both formats can be mixed in the same file. See sample-connections.json for a ready-to-use example.

The recommended location for the local file is the project root (auto-discovered) or ~ (shared across all projects). The file can hold credentials, so add .elekto.mcp.sql.local.json to your project's .gitignore, as this repository does.

Options per database

Option

Type

Default

Description

connection_string

string

required

SQL Server connection string

max_query_rows

integer

10 000

Maximum rows returned per query call

default_timeout_seconds

integer

30

SQL command timeout in seconds

Environment variable expansion in connection strings

Use %{VARIABLE_NAME} inside connection strings to avoid storing credentials in plain text. Variables are resolved from the process environment at server startup.

{
  "CRM": {
    "connection_string": "Server=SQLSRV01;Database=CRM;User Id=%{CRM_DB_USER};Password=%{CRM_DB_PASS}",
    "max_query_rows": 2000
  }
}

%{CRM_DB_USER} and %{CRM_DB_PASS} are replaced by the values of the corresponding OS environment variables. If a referenced variable does not exist, no connection is loaded and every tool names the missing variable (see When no connection is configured).

Fallback: MCP_SQL_CONNECTIONS environment variable

If --connections is not supplied, the server falls back to reading the MCP_SQL_CONNECTIONS environment variable, which must contain the JSON directly. This is provided for backward compatibility; the file-based approach is recommended.

When no connection is configured

The server starts even when it finds no connection, or when the configuration cannot be read (invalid JSON, a %{VARIABLE} that is not set, a --connections file that does not exist). An MCP client shows a server that exits at startup only as "failed", with the reason buried in a log; a server that answers can say what is missing. So it:

  • states the problem in its server instructions, which the client hands to the model as soon as it connects;

  • answers every tool with ok: false, what is wrong, the file to create, every place it looked and an example of the content:

{
  "ok": false,
  "tool": "list_databases",
  "error": "No database connection is configured: none of the places this server reads holds a connection string.",
  "hint": "Ask the user for a SQL Server connection string, preferably of a login that can only read, and save it in the file named in 'setup.file', with the shape shown in 'example'. ...",
  "example": {
    "MyDatabase": "Server=SQLSRV01;Database=MyDatabase;Integrated Security=True;TrustServerCertificate=True",
    "Reporting": { "connection_string": "...User Id=%{REPORTING_USER};Password=%{REPORTING_PASS}...", "max_query_rows": 5000 }
  },
  "setup": {
    "file": "C:\\Projects\\Risk\\.elekto.mcp.sql.local.json",
    "file_for_every_project": "C:\\Users\\YourName\\.elekto.mcp.sql.local.json",
    "searched": [ "C:\\Projects\\Risk\\.elekto.mcp.sql.local.json", "ConnectionStrings in C:\\Projects\\Risk\\appsettings.Development.json", "..." ],
    "notes": [ "..." ],
    "documentation": "https://github.com/elekto-com-br/elekto-mcp-sql#configuration"
  }
}
  • looks again on every call while nothing is loaded, so a connections file created afterwards (by you, or by the agent once you give it a connection string) is used by the next call, with no restart.

Once connections are loaded they are kept until the server restarts, so a change to a file already read needs a restart of the server (in Claude Code, /mcp and reconnect it; in Codex, start Codex again).

Claude Code Setup

Install the tool (see Installation) and register it with claude mcp add. Everything after -- is the command Claude Code runs:

dotnet tool install -g Elekto.Mcp.Sql
claude mcp add sql -- elekto-mcp-sql

Claude Code starts the server in the project directory, so the zero-config discovery works as it does in Visual Studio: a .elekto.mcp.sql.local.json, or the ConnectionStrings of appsettings.json / web.config, in the project is found with no arguments.

-s (--scope) chooses where the registration is kept:

Scope

Command

Applies to

local (default)

claude mcp add sql -- elekto-mcp-sql

This project, for you only (kept in ~/.claude.json)

user

claude mcp add -s user sql -- elekto-mcp-sql

Every project, for you

project

claude mcp add -s project sql -- elekto-mcp-sql

This project, for everyone who clones it (writes .mcp.json)

Registered with -s user, the server also starts in projects that have no database; there the tools say how to add a connection instead of failing (see When no connection is configured).

Other forms:

# An explicit connections file; no other source is read
claude mcp add sql -- elekto-mcp-sql --connections C:\Users\YourName\sql-connections.json

# Without installing the tool (needs the .NET 10 SDK, which brings dnx)
claude mcp add sql -- dnx Elekto.Mcp.Sql --yes

On Windows the installed command is a real executable (%USERPROFILE%\.dotnet\tools\elekto-mcp-sql.exe), so it needs no cmd /c wrapper, unlike servers started through npx.

Secrets. claude mcp add -e NAME=value stores the value in plain text in ~/.claude.json, or in .mcp.json with -s project, which is usually committed. For a password, write %{NAME} in the connection string and set NAME as an environment variable of your user account instead: Claude Code passes its environment on to the server.

Check the registration with claude mcp list (the server should show Connected), or with /mcp inside Claude Code, which also lists the tools and reconnects the server.

A .mcp.json written by hand for Claude Code uses the key mcpServers, where Visual Studio and VS Code use servers:

{
  "mcpServers": {
    "sql": {
      "type": "stdio",
      "command": "elekto-mcp-sql",
      "args": []
    }
  }
}

Codex Setup

Codex, OpenAI's coding agent (CLI, IDE extension and app), runs local MCP servers as well. Install the tool (see Installation) and register it with codex mcp add. Everything after -- is the command Codex runs:

dotnet tool install -g Elekto.Mcp.Sql
codex mcp add sql -- elekto-mcp-sql

This adds the server to ~/.codex/config.toml (%USERPROFILE%\.codex\config.toml on Windows), so it applies to every project:

[mcp_servers.sql]
command = "elekto-mcp-sql"

Codex starts the server in the project directory, so the zero-config discovery works here too. In a project with no database the tools say how to add a connection (see When no connection is configured).

To register the server for one project only, put the same table in .codex/config.toml at the project root instead. Codex reads that file only in projects marked as trusted.

codex mcp list and codex mcp get sql show the configuration. Unlike claude mcp list, they do not start the server, so a mistake in the command only shows when a Codex session starts.

Environment variables are not passed on

Unlike Claude Code, Codex starts an MCP server with a short list of environment variables of its own (such as HOME and PATH), not with all of yours. A %{VARIABLE} in a connection string is therefore not found unless the variable is listed in env_vars, which forwards it from your environment:

[mcp_servers.sql]
command = "elekto-mcp-sql"
env_vars = ["CRM_DB_USER", "CRM_DB_PASS"]

Without it the server still starts, and every tool names the variable it could not find.

codex mcp add --env NAME=value sets a value directly (the env table), but stores it in plain text in config.toml. Keep it for values that are not secret.

Other forms

An explicit connections file, with no other source read:

[mcp_servers.sql]
command = "elekto-mcp-sql"
args = ["--connections", 'C:\Users\YourName\sql-connections.json']

A Windows path goes in single quotes, which TOML takes literally. Inside double quotes the \U of C:\Users is read as an escape sequence and Codex refuses the whole file; with double quotes every backslash must be doubled. codex mcp add writes single quotes by itself.

Without installing the tool (needs the .NET 10 SDK, which brings dnx):

[mcp_servers.sql]
command = "dnx"
args = ["Elekto.Mcp.Sql", "--yes"]
startup_timeout_sec = 30

The first start downloads the package, which can take longer than Codex waits for a server by default; startup_timeout_sec gives it more time. The installed tool starts in under a second and needs no such setting.

If Codex runs inside WSL, it starts the server inside Linux, which cannot see the tool installed on Windows: install .NET and the tool in WSL as well. Integrated Security from Linux also needs Kerberos configured; a SQL Server login, with its password in a %{VARIABLE} listed in env_vars, is simpler there.

Visual Studio 2026 Setup (.mcp.json)

Create or edit .mcp.json at the solution root (or in your user profile for global use).

Drop a .elekto.mcp.sql.local.json file in the project root or in ~; the server finds it automatically. No arguments needed in .mcp.json:

{
  "servers": {
    "sql": {
      "type": "stdio",
      "command": "dotnet",
      "args": ["D:\\Tools\\Elekto.Mcp.Sql\\Elekto.Mcp.Sql.dll"]
    }
  }
}

Alternative: explicit path via --connections

Point the server to any file via --connections. Useful when the file lives outside the project tree or when you need to switch between profiles:

{
  "servers": {
    "sql": {
      "type": "stdio",
      "command": "dotnet",
      "args": [
        "D:\\Tools\\Elekto.Mcp.Sql\\Elekto.Mcp.Sql.dll",
        "--connections",
        "C:\\Users\\YourName\\sql-connections.json"
      ]
    }
  }
}

The connection file itself stays outside the repository, so credentials are never committed to source control.

Alternative: environment variable (legacy)

If you prefer not to use a file, you can still pass the JSON via an environment variable. Note that backslashes require double escaping inside JSON-within-JSON (\\\\):

{
  "servers": {
    "sql": {
      "type": "stdio",
      "command": "dotnet",
      "args": ["D:\\Tools\\Elekto.Mcp.Sql\\Elekto.Mcp.Sql.dll"],
      "env": {
        "MCP_SQL_CONNECTIONS": "{\"MyDb\": {\"connection_string\": \"Server=SQLSRV01\\\\INST;Database=MyDb;Integrated Security=SSPI\"}}"
      }
    }
  }
}

After saving .mcp.json, Copilot automatically restarts the server. Tools are disabled by default: enable them in the Copilot Chat tools panel.

Build and Publish

cd Elekto.Mcp.Sql\src
dotnet publish -c Release -o C:\Tools\Elekto.Mcp.Sql

Requires .NET 10 installed on the machine. The published directory is ~7 MB (NuGet dependencies). For internal use, this is preferred over self-contained (~81 MB).

dotnet pack also packs src/.mcp/server.json, which tells nuget.org how to start the server. The file in the repository carries $version$ where the version goes, and the pack writes the version being packed in its place, so there is nothing to update in it for a release.

Each tag also publishes the server to the MCP Registry as io.github.elekto-com-br/elekto-mcp-sql, once nuget.org has indexed the new version. The registry accepts the package as ours only if its README holds the line mcp-name: io.github.elekto-com-br/elekto-mcp-sql, which is why the comment at the top of this file must stay; CI fails if the packed README loses it.

Package versions are locked in src/packages.lock.json and tests/packages.lock.json. After changing a PackageReference, run dotnet restore and commit the lock files with it: CI and the release restore in locked mode, and fail when a lock file does not match its project.

Verifying a release

Releases after 2.3.2 carry the package on their GitHub Release, with a build provenance attestation that ties it to this repository's publish workflow and the release tag. To check it with the GitHub CLI:

gh release download vX.Y.Z --repo elekto-com-br/elekto-mcp-sql --pattern '*.nupkg'
gh attestation verify Elekto.Mcp.Sql.X.Y.Z.nupkg --repo elekto-com-br/elekto-mcp-sql

The copy that nuget.org serves also carries nuget.org's own repository signature, so it differs from the attested file; dotnet nuget verify checks that signature.

Running the tests

From the repository root:

dotnet test

The test project holds two kinds of tests:

  • Unit tests (such as ConnectionConfigTests) need nothing beyond the .NET SDK.

  • Integration tests (SchemaReaderTests) run against a real SQL Server. Each run creates a database named ElektoMcpTest, fills it with a small seed schema, and drops it at the end.

The integration tests look for a SQL Server in this order and use the first one found:

  1. The ELEKTO_MCP_SQL_CONN_TEST environment variable. If set, it must hold a connection string to a server the tests may use. The database named in it, if any, is ignored. The login needs permission to create and drop databases. If this server cannot be reached, the tests fail right away instead of trying the next options, since an explicit choice that does not work is an error worth seeing.

  2. LocalDB, only on Windows and only if the (localdb)\MSSQLLocalDB instance answers.

  3. A disposable container started through Testcontainers from the mcr.microsoft.com/mssql/server:2022-latest image. This needs Docker (rootless Docker works too). The container is started only when an integration test needs it, and it is removed when the run ends. The first run also downloads the image, which takes a while.

If none of these is available, the integration tests fail with a message listing what was tried and why each option did not work. The test output states which server was used.

Some of the integration tests run as restricted logins, to check what the tools say when SQL Server hides objects. The fixture creates those logins (ElektoMcpTest_*) and drops them at the end, which needs ALTER ANY LOGIN as well; a server that does not allow it reports those tests as skipped, with the reason.

Example, pointing the tests at an existing server:

export ELEKTO_MCP_SQL_CONN_TEST="Server=localhost,1433;User Id=sa;Password=<password>;TrustServerCertificate=True"
dotnet test

Do not point ELEKTO_MCP_SQL_CONN_TEST at a server where a database called ElektoMcpTest matters to anyone: the tests drop and recreate it.

To run only the unit tests, with no SQL Server at all:

dotnet test --filter "FullyQualifiedName!~SchemaReaderTests"

Everything the tools read, with no permission to change anything:

USE [YourDatabase];
CREATE USER [mcp_reader] FOR LOGIN [mcp_reader];  -- if the user does not exist yet
ALTER ROLE db_datareader ADD MEMBER [mcp_reader];  -- tables and views; also covers sys.sql_expression_dependencies
GRANT VIEW DEFINITION TO [mcp_reader];             -- procedures, functions, view text, complete dependencies
GRANT SHOWPLAN TO [mcp_reader];                    -- get_estimated_plan

USE master;
GRANT VIEW SERVER STATE TO [mcp_reader];           -- get_index_health: unused and missing indexes; the Query Store tools;
                                                   -- find_cached_queries, get_active_requests

VIEW SERVER STATE implies VIEW DATABASE STATE in every database, which is all the Query Store tools need. To give them that without the server permission, grant it in the database instead:

USE [YourDatabase];
GRANT VIEW DATABASE STATE TO [mcp_reader];         -- the Query Store tools

On SQL Server 2022 and later both can be narrowed to the performance half that the tools actually need. The server one covers get_index_health, the Query Store tools, find_cached_queries and get_active_requests:

USE master;
GRANT VIEW SERVER PERFORMANCE STATE TO [mcp_reader];

The database one covers the Query Store tools alone:

USE [YourDatabase];
GRANT VIEW DATABASE PERFORMANCE STATE TO [mcp_reader];

Without VIEW DEFINITION the Query Store tools still work, but SQL Server hides the name of every procedure, function and trigger the login holds no permission on, so their queries show object null with their object_id.

get_estimated_plan needs SHOWPLAN, and besides it the permission to run what it compiles: SELECT on what a query reads, or EXECUTE on a procedure. EXECUTE lets the login run that procedure too, outside this server, with every change the procedure makes, so it is not in the script above and check_permissions never suggests it. Grant it only on procedures where that is acceptable, or compile a procedure's statements one at a time as queries, which needs SELECT alone.

Permission

Without it

db_datareader (SELECT on the database)

Tables and views the login holds no grant on are left out; query_table fails on them and get_table_statistics cannot read their statistics. If the login is not in db_datareader, sys.sql_expression_dependencies also needs GRANT SELECT ON sys.sql_expression_dependencies

VIEW DEFINITION on the database

Procedures and functions are left out, view and module text is hidden, dependencies are incomplete

VIEW SERVER STATE (2022+: VIEW SERVER PERFORMANCE STATE)

get_index_health returns the duplicate indexes only; find_cached_queries, get_active_requests and get_query_plan_summary with a plan_handle fail, saying which GRANT adds it, or that a DENY refuses it. Without it SQL Server shows a login its own session alone, so get_active_requests fails rather than report nothing running

VIEW DATABASE STATE (2022+: VIEW DATABASE PERFORMANCE STATE), or VIEW SERVER STATE

The Query Store tools fail, saying which GRANT adds it

SHOWPLAN on the database (ALTER TRACE on the server implies it)

get_estimated_plan fails, saying which GRANT adds it, or that a DENY refuses it

get_optimizer_settings reads views open to every login on the versions tested. Microsoft's documentation asks for VIEW SERVER PERFORMANCE STATE on sys.configurations from SQL Server 2022 and for VIEW DATABASE STATE on the Query Store options, so a section a login cannot read comes back null, and visibility.unavailable carries SQL Server's error.

None of these lets the login change data or schema. Compiling, under SHOWPLAN as when running any query, can create and update statistics, which SQL Server keeps for itself. Run check_permissions against the database to see which are missing: it prints the statements for that login and that server version.

Limits and Security

  • Read-only: the tools only read, with SELECT on tables, views, the catalog and dynamic management views, plus two read-only DBCC commands: DBCC SHOW_STATISTICS ... WITH DENSITY_VECTOR, for the density vector in get_table_statistics, and DBCC TRACESTATUS(-1), for the global trace flags in get_optimizer_settings (and in get_table_statistics below compatibility level 130). No tool runs DML or executes a procedure: get_estimated_plan compiles a procedure, or one SELECT, under SET SHOWPLAN_XML ON, which returns the plan and runs nothing (but for a deterministic CLR function with constant arguments, which SQL Server evaluates while it compiles). It turns the setting on and off on its own connection, checks that it took effect before compiling anything and that it is off again before the connection goes back to the pool, and clears the pool when it cannot tell. It does all of that inside a transaction that changes nothing and is rolled back: SQL Server will not recover a session with an open transaction, so a connection that drops in between makes the call fail, where SqlClient would otherwise reconnect on a new session, without SHOWPLAN, and run it.

  • Compiling is not quite free of effects. Like running the statement would, it creates the statistics a column lacks and updates stale ones before using them, and SQL Server does so even for a login that can only read (with AUTO_UPDATE_STATISTICS_ASYNC on, it queues the update instead). That changes what later compilations see, the very thing a plan investigation looks at, so each answer of get_estimated_plan says which of these the database allows and lists the statistics whose last update came after the compilation began. The plan itself is neither cached nor recorded by the Query Store. A procedure that already has a plan in the plan cache is not compiled again: SQL Server answers with that plan, compiled for the values of the run that cached it, and the answer says so.

  • get_estimated_plan takes free text in two parameters. query is sent as written, so the same parser must read it as a single SELECT, without INTO; it is refused for the same reaches as where (OPENROWSET, OPENDATASOURCE, OPENQUERY, names in four parts, the functions below, NEXT VALUE FOR), for variables, local temporary tables (#name) and table variables, which do not exist where it is compiled, and beyond 32,768 characters. A global temporary table (##name) is accepted: every session sees it while the one that created it lasts. parameters is never sent at all: the parser reads it as the values of an EXEC, only literals are accepted, and each is converted to its parameter's declared type, refused if the conversion would change it, and passed as a typed parameter. A text parameter takes only a value in quotes: an EXEC reads 007 as a number and passes '7', and 0x41 as binary and passes 'A', so an unquoted value is refused rather than compiled for another one.

  • query_table builds SQL internally from validated parameters. Identifiers (table, schema, columns) are validated against a regular expression before being composed into SQL.

  • where and order_by are accepted as free text, for flexibility, but not as just any text. Before anything is sent, Microsoft's T-SQL parser (ScriptDom) must read where as one boolean expression and order_by as one ORDER BY list, and the assembled command as a single SELECT. Functions and subqueries are accepted; a second statement, a ;, a comment, OPENROWSET, OPENDATASOURCE, OPENQUERY, a name in four parts (server.database.schema.object, which SQL Server reads through a linked server, as whatever login that server maps to) and NEXT VALUE FOR are refused, and so is a clause longer than 16,384 characters. Up to 2.3.5 neither clause was checked (GHSA-g9cv-w79w-2hjh): either could close the clause it went into and append a statement of its own, which SQL Server ran whenever the login was allowed to.

  • The system functions that open a file or a URL at a path they are given are refused as well: sys.dm_os_file_exists, sys.dm_os_enumerate_filesystem, sys.fn_xe_file_target_read_file, sys.fn_get_audit_file and sys.fn_get_audit_file_v2, sys.fn_trace_gettable, sys.fn_dump_dblog and sys.fn_dump_dblog_xtp, sys.fn_filelog, sys.fn_full_dblog and sys.fn_ledger_retrieve_digests_from_url. Given a path such as \\host\share\file, SQL Server opens it on that host and signs in there as its service account, handing the host credentials to crack or relay. On SQL Server 2025, sys.dm_os_file_exists does so for a login with no server permission at all, and sys.fn_xe_file_target_read_file for one with the VIEW SERVER STATE that Recommended permissions suggests. So is sys.dm_exec_describe_first_result_set, which compiles a query text handed to it in a string, out of the parser's reach.

  • These functions are refused under any spelling SQL Server reads as theirs. SQL Server compares names under the database's collation, which can ignore spaces at the end of a name, invisible characters and emoji, and read full-width letters, and accented ones where the collation ignores accents, as plain letters. So, before it runs the command, query_table asks SQL Server, through sys.all_objects, whether it reads any name in where or order_by as one of them, and get_estimated_plan asks the same of every name in query before compiling it.

  • The parser checks the shape of the command, not what the login may do: what a query can read, and what the functions it calls do, is still up to the login's permissions. Keep the login read-only; check_permissions reports write_access.

  • max_query_rows caps the maximum number of rows returned per database (default 10,000). The top parameter in query_table is always clamped to this value, and the result says so via top_requested and truncated rather than quietly returning a short answer.

  • Even so, avoid exposing this server in untrusted environments or with sensitive data. Use firewalls and access policies to restrict who can execute queries via MCP. Use database accounts with the minimum required privileges (read-only) for all configured connections.

Available Tools

30 tools
check_permissionsCheck login permissionsA
Read-onlyIdempotent

Reports what the connected login can and cannot see in a database: identity, roles, effective permissions, server version and, for each group of tools, whether it sees everything ('complete'), only part ('partial') or nothing ('unavailable'), with the missing permission and the GRANT that adds it in this server version's syntax. Also reports 'write_access', so an account meant to be read-only can be verified rather than assumed. Call it when a listing looks short, a definition comes back hidden, get_database_overview reports incomplete visibility, or a tool fails with a permission error: SQL Server leaves out what a login cannot see without raising any error.

Inputs: database (required).

compare_schemasCompare two databasesA
Read-onlyIdempotent

Compares the table and column structure of two configured databases, such as development and production: tables present in only one, columns present in only one, and columns whose type or nullability differ, each with its type_declaration so a difference reads as 'nvarchar(250) vs nvarchar(50)'. Use it to check a migration or detect drift. It compares tables and columns only, not views, code, indexes or data; to see one differing table in full, call get_table_schema on each database.

Inputs: source_database (required), target_database (required), source_schema, target_schema.

find_cached_queriesFind statements in the plan cacheA
Read-onlyIdempotent

Lists this database's statements in SQL Server's plan cache, leaving out the queries this server sends to read the cache and the sessions, with what their runs cost since each plan was cached: per statement, when its plan was compiled and how many times (plan_generation_num), its last run, executions, total, average, maximum and last duration, CPU and logical reads, physical reads, rows, degree of parallelism, memory grant and spills, the query and plan hashes, the first 300 characters of the statement, and the plan_handle with the statement's offsets, which get_query_plan_summary takes. With object_name, the statements of that procedure, function or trigger, the variants SQL Server 2022+ keeps of a parameter-sensitive one included, and the totals SQL Server keeps for a procedure, scalar function or trigger. Use it when a query is slow and the Query Store is off, as it is by default before SQL Server 2022, or to see the plan in use now. The cache keeps no history: a plan evicted, recompiled or lost to a restart takes its figures with it, so where the Query Store is on use find_query_store_queries and get_query_store_history for what changed over days. Needs VIEW SERVER STATE (2022+: VIEW SERVER PERFORMANCE STATE).

Inputs: database (required), top, schema, order_by, +2 more.

find_columnsFind columns by nameA
Read-onlyIdempotent

Finds every table and, by default, every view holding a column whose name matches a pattern, with each column's type_declaration and nullability. Use it to answer 'which objects have this column?' before a rename, a widening or an impact review; to find objects by their own name use list_tables or list_views.

Inputs: database (required), column_pattern (required), schema, include_views.

find_query_store_queriesFind queries in the Query StoreA
Read-onlyIdempotent

Finds Query Store queries by part of their text or by the procedure, function or trigger that runs them; with neither, the ones that took the most time in the window. Returns each one's query_id, the first 300 characters of its text, its number of plans, its executions in the window with their total and average duration, CPU and logical reads, maximum duration and failed executions, and its last execution. The variants of a parameter-sensitive query (SQL Server 2022+) count under it. Use it to get the query_id that get_query_store_history takes; to find what got slower use list_query_store_regressions. Needs VIEW DATABASE STATE (2022+: VIEW DATABASE PERFORMANCE STATE), which VIEW SERVER STATE implies.

Inputs: database (required), top, days, schema, +2 more.

generate_dependency_dotDependency diagram (DOT)A
Read-onlyIdempotent

Generates a Graphviz DOT diagram of the dependencies between database objects: an arrow runs from each table, view, procedure or function to the object it depends on, through a foreign key or a reference in its code. Returns the DOT text in 'dot', ready for 'dot -Tsvg', and the same graph as 'nodes' (with node_kind) and 'edges' (with dependency_kind). Use it to draw the graph; for the edges alone use get_dependency_graph, and for what references a single table use get_table_usage. A whole database makes an unreadable diagram, so narrow it with schema. 'visibility' says when references from code are missing for lack of permission.

Inputs: database (required), schema.

get_active_requestsRequests running now and who blocks themA
Read-onlyIdempotent

Shows what runs in this database now: each request of a user session but this tool's own, with its status, command, start and elapsed time, CPU and reads, the current wait and the resource it waits on (for a parallel request, the blocked worker's), with the table and index where the catalog names them, the session blocking it, open transactions and when the oldest began, degree of parallelism, memory grant, the procedure and the current statement (300 characters), query_hash, and the plan_handle with the statement's offsets for get_query_plan_summary; plus each chain of blocking up to its head, the session that blocks without being blocked, which can be idle with a transaction left open, or in another database, with the last batch it sent. Use it when something is slow or stuck right now; for what ran before use find_cached_queries or the Query Store tools, such as find_query_store_queries. It shows other sessions' login, host name, program and SQL text, which can carry literal values. Needs VIEW SERVER STATE (2022+: VIEW SERVER PERFORMANCE STATE): without it SQL Server shows a login its own session alone, so the call fails, naming the GRANT that adds it or the DENY that refuses it, rather than report nothing running.

Inputs: database (required), top.

get_database_overviewDatabase overviewA
Read-onlyIdempotent

Summarizes one database: real name, server and instance, connected login, counts of tables, views, procedures, functions and schemas, and allocated size in MB. Use it after list_databases to size up a database before exploring it; for the same figures per schema use get_schema_summary. Counts cover only what the login can see: 'visibility.complete' is false when SQL Server hides objects, and check_permissions then says which GRANT is missing.

Inputs: database (required).

get_data_profileProfile column dataA
Read-onlyIdempotent

Profiles the columns of one table or view: null ratio, distinct count, minimum, maximum and most frequent values. Use it to learn how data is distributed without paging through rows with query_table. It reads actual row values and scans the table, so on a large table it can take a while; limit it to the columns you need.

Inputs: table (required), database (required), schema, columns, +1 more.

get_dependency_graphDependency graphA
Read-onlyIdempotent

Returns the dependency edges between database objects as data: foreign keys between tables, and references among views, procedures and functions. Use it to analyze dependencies programmatically; for a diagram use generate_dependency_dot, and for what references one table use get_table_usage. Fails, saying so, when the login cannot read sys.sql_expression_dependencies; without VIEW DEFINITION the module edges cover only modules the login can read.

Inputs: database (required), schema.

get_estimated_planEstimated plan of a procedure or a queryA
Read-onlyIdempotent

Compiles a stored procedure for the parameter values given, or one SELECT, under SET SHOWPLAN_XML ON, and summarizes the plan SQL Server would use now, as get_query_plan_summary does for a Query Store plan: per statement the estimated rows, cost and share of the whole, parallelism, the compiled parameter values, the statistics used, warnings, missing indexes and the costliest operators. Nothing runs (but for a deterministic CLR function with constant arguments, which SQL Server evaluates while compiling), and the plan is neither cached nor recorded by the Query Store; but compiling creates missing statistics and updates stale ones, as running would (with AUTO_UPDATE_STATISTICS_ASYNC the update is queued), and the answer names any it changed. When the procedure already has a plan in the plan cache, SQL Server returns that plan, compiled for the values of the run that cached it, and the answer says so (plan_from_cache). Use it to see the plan a procedure gets for given values, or how a rewrite or a hint changes a statement; for the plans that actually ran use get_query_store_history and get_query_plan_summary. A procedure that fills a temporary table with SELECT ... INTO and then reads it cannot be compiled without running: pass its statements in 'query' instead. Statements reading a temporary table or table variable are estimated as if it were empty, dynamic SQL is not compiled, and a CLR procedure has no plan to compile. Needs SHOWPLAN on the database, plus EXECUTE on the procedure or SELECT on what the query reads.

Inputs: database (required), query, schema, procedure, +3 more.

get_function_definitionUser function definitionA
Read-onlyIdempotent

Returns the CREATE FUNCTION text of one user-defined function. Use it to read or review a function found with list_functions; this server never executes functions. A function the login can see but not read comes back with definition null and definition_visible false.

Inputs: database (required), function (required), schema.

get_index_healthIndex healthA
Read-onlyIdempotent

Reports index health by schema: duplicate index candidates, unused indexes, missing-index suggestions, and hypothetical indexes, which the Database Engine Tuning Advisor leaves behind and no query uses. Two B-tree indexes are duplicates with the same keys in the same order, in the same directions or all reversed, the same included columns in any order and the same filter; each pair says whether each index is unique and whether it is clustered, and indexes behind primary keys and unique constraints are not compared. Use it when reviewing indexing or slow queries; for one table's indexes use get_table_schema. Unused and missing indexes come from server DMVs, which reset when SQL Server restarts; without VIEW SERVER STATE they come back null and 'visibility.unavailable' says why, while duplicates and hypothetical indexes are still reported.

Inputs: database (required), schema.

get_optimizer_settingsSettings that change query plansA
Read-onlyIdempotent

Reports the settings that change how SQL Server compiles queries in one database: the compatibility level and the cardinality estimator it implies, automatic and asynchronous statistics updates, forced parameterization, every database scoped configuration (MAXDOP, LEGACY_CARDINALITY_ESTIMATION, PARAMETER_SNIFFING and the rest) with whether it is the default, the Query Store state, and on the server max degree of parallelism, cost threshold for parallelism and the global trace flags. Use it when a plan changed, or differs between two servers; for one table's statistics use get_table_statistics. A section that cannot be read comes back null, and 'visibility' says why.

Inputs: database (required).

get_procedure_definitionStored procedure definitionA
Read-onlyIdempotent

Returns the CREATE PROCEDURE text of one stored procedure. Use it to read or review a procedure found with list_procedures; this server never executes procedures. A procedure the login can see but not read comes back with definition null and definition_visible false.

Inputs: database (required), procedure (required), schema.

get_query_plan_summaryExecution plan summaryA
Read-onlyIdempotent

Summarizes one execution plan instead of returning its XML, which can run to hundreds of thousands of characters: a Query Store plan by plan_id, or a plan in the plan cache by plan_handle, whole or the one statement its offsets pick out. Per statement (an IF or WHILE condition and each cursor operation count as one): estimated rows and cost, cardinality estimator version, whether the plan is parallel and why not when it is serial, memory grant, the parameter values the plan was compiled for, the statistics the optimizer used with their last update and modifications, the warnings, each with the operator it is on (implicit conversions, missing statistics or join predicates), missing-index suggestions, and the operators as a compact tree with object, index, seek, scan or lookup, predicates and join keys, estimated rows and share of the cost. Query Store and cached plans are estimated plans, so nothing measured at run time, such as spills, is in them. Use it with a plan_id from get_query_store_history or list_query_store_regressions, or a plan_handle from find_cached_queries or get_active_requests, and compare two plans of a query by summarizing each; for the statistics themselves use get_table_statistics. A plan_handle needs VIEW SERVER STATE (2022+: VIEW SERVER PERFORMANCE STATE).

Inputs: database (required), plan_id, statement, plan_handle, +3 more.

get_query_store_historyQuery Store history of one queryA
Read-onlyIdempotent

Returns the Query Store history of one query: its text (the first 4000 characters); the SET options it compiled with, such as ARITHABORT, which explain a query fast in SSMS and slow in the application; its plans (the 20 that ran most in the window, when it has more) with when each was first and last compiled and whether it is forced; and, per plan and per day, hour or Query Store interval, the executions (aborted and failed ones included, and also counted apart), average and maximum duration, average CPU, logical and physical reads, average and maximum DOP, and average rows, memory and tempdb, plus each plan's waits by category over the whole window. Use it with a query_id from list_query_store_regressions or find_query_store_queries; to see what a plan does use get_query_plan_summary with its plan_id. The Query Store keeps each plan's first and last compile time, not every recompilation.

Inputs: database (required), query_id (required), days, granularity.

get_schema_summarySchema summaryA
Read-onlyIdempotent

Summarizes each schema of a database: counts of tables, views, procedures and functions, approximate rows and estimated data and index size. Use it to see where a database's weight lies before exploring or planning a refactoring; for whole-database totals use get_database_overview, and for the tables of one schema use list_tables.

Inputs: database (required), schema.

get_table_schemaTable structureA
Read-onlyIdempotent

Returns the full structure of one table or view: columns with an unambiguous type_declaration (such as 'nvarchar(250)'), max_length_chars, every extended property, computed-column definitions and whether they are persisted; plus primary key, foreign keys, check and unique constraints, and indexes with key column order and declared key width, leaving hypothetical ones to get_index_health. Call it before query_table to learn exact column names and types; for a view's SQL text use get_view_definition. max_length is the raw sys.columns value in BYTES, so reason about text length with type_declaration or max_length_chars.

Inputs: table (required), database (required), schema.

get_table_statisticsTable statistics and histogramA
Read-onlyIdempotent

Lists the optimizer statistics of one table or indexed view: for each, its columns, when it was last updated, rows and rows sampled, modifications since then and how many remain before an automatic update (null for NORECOMPUTE, with automatic updates off, for hypothetical indexes, and for incremental or never-built statistics). With 'statistic', also that statistic's histogram and density vector; with 'value', where that value falls in the histogram, and only the steps around it. Use it when an estimate looks wrong or a plan changed, to see what the optimizer was told about the data without reading it; for the real distribution use get_data_profile, which scans the table, and for the settings that decide automatic updates use get_optimizer_settings. The contents need SELECT on the table; each statistic says whether the login could read them.

Inputs: table (required), database (required), value, schema, +1 more.

get_table_usageTable usageA
Read-onlyIdempotent

Lists everything that references one table: foreign keys to and from it, and the views, procedures and functions whose code uses it. Use it for impact analysis before changing a table; for the dependency graph of the whole database use get_dependency_graph. sql_module_usage is null when the login cannot read dependencies, and 'visibility' says when the list may be incomplete.

Inputs: table (required), database (required), schema.

get_view_definitionView definitionA
Read-onlyIdempotent

Returns the CREATE VIEW text of one view together with its columns, in the same detail as get_table_schema. Use it to see how a view derives its data; for the objects it reads from use get_dependency_graph. A view the login can see but not read comes back with definition null and definition_visible false, which check_permissions explains.

Inputs: view (required), database (required), schema.

list_databasesList configured databasesA
Read-onlyIdempotent

Lists the logical database names this server is configured to reach, with each one's row limit and command timeout. Call it first: every other tool, starting with get_database_overview, takes one of these names as its 'database' argument. It reads only the server's configuration and never connects to SQL Server; when nothing is configured it answers ok: false with the file to create, where the server looked and an example.

Inputs: no named parameters.

list_functionsList user functionsA
Read-onlyIdempotent

Lists the user-defined functions the login can see (scalar, inline table-valued and multi-statement table-valued), with the same complexity metrics and visibility flags as list_procedures. Use it to find functions; for one function's text use get_function_definition. SQL Server leaves out functions the login has no permission on without an error: get_database_overview says whether that happens, check_permissions why.

Inputs: database (required), schema.

list_proceduresList stored proceduresA
Read-onlyIdempotent

Lists the user stored procedures the login can see, with line count, join count and number of referenced objects as rough complexity metrics. Use it to find procedures and pick the complex ones; for one procedure's text use get_procedure_definition. definition_visible is false, and the metrics null, for a procedure whose text is hidden from the login; referenced_object_count is null when the login cannot read dependencies. SQL Server leaves out procedures the login has no permission on without an error: get_database_overview says whether that happens, check_permissions why.

Inputs: database (required), schema.

list_query_store_regressionsQuery Store regressions and plan changesA
Read-onlyIdempotent

Finds the queries that got slower or heavier, vary the most or changed plan, from the Query Store: it compares each query's recent window with the days before it, as SSMS's Regressed Queries and Queries With High Variation reports do, and returns per query the executions and the average and maximum of the metric in each window, their ratio, the plans used in each window, whether the dominant plan changed, the plans compiled in the recent window and the aborted or failed executions in it. The variants of a parameter-sensitive query (SQL Server 2022+) count under it. Use it first when a query or a process got slow; for one query's full history use get_query_store_history, and to find a query by its text or procedure use find_query_store_queries. Needs VIEW DATABASE STATE (2022+: VIEW DATABASE PERFORMANCE STATE), which VIEW SERVER STATE implies.

Inputs: database (required), top, metric, order_by, +3 more.

list_schemasList schemasA
Read-onlyIdempotent

Lists the user schemas of a database with their owners, leaving out system schemas. Use it to learn the names the 'schema' filter of the other tools accepts; for object counts and sizes per schema use get_schema_summary instead.

Inputs: database (required).

list_tablesList tablesA
Read-onlyIdempotent

Lists user tables with schema, approximate row count, data and index size in MB, and creation and modification dates. Use it to find tables by name or schema and to spot the large ones; to find tables by a column they hold use find_columns, and for one table's columns and keys use get_table_schema. Narrow large databases with schema and name_pattern.

Inputs: database (required), schema, name_pattern.

list_viewsList viewsA
Read-onlyIdempotent

Lists user views with their schema. Use it to find views by name or schema; for a view's columns and SQL text use get_view_definition, and for tables use list_tables. Narrow large databases with schema and name_pattern.

Inputs: database (required), schema, name_pattern.

query_tableQuery a table or viewA
Read-onlyIdempotent

Runs a SELECT on one table or view, with optional column list, filter, ordering, grouping, aggregates (COUNT, SUM, AVG, MIN, MAX), pagination and random sampling, and returns the rows in an object with row_count and a measured 'truncated' flag, so a short result is never mistaken for a complete one. Rows are capped by the database's max_query_rows. Call get_table_schema first for exact column names; for null ratios, distinct counts and frequent values use get_data_profile instead of paging through rows. Reads actual data; never runs INSERT, UPDATE, DELETE or procedures.

Inputs: table (required), database (required), top, skip, +7 more.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.4/5.0

    Scored across 30 tools

    Disambiguation5/5

    Despite 30 tools, each has a sharply distinct target/action pair, and descriptions explicitly route between near-neighbours (get_query_plan_summary vs get_estimated_plan, find_query_store_queries vs list_query_store_regressions, get_table_statistics vs get_data_profile, get_dependency_graph vs generate_dependency_dot vs get_table_usage). An agent can reliably pick the right tool from the guidance alone.

    Naming Consistency5/5

    Every name is snake_case verb_noun with a small, predictable verb vocabulary (list_, get_, find_, query_, check_, compare_, generate_) plus a resource noun. No mixed conventions or camelCase anywhere.

    Tool Count3/5

    The domain is genuinely broad (catalog exploration, statistics, Query Store, plan cache, plans, dependencies, comparison), so most tools earn their place, but 30 exceeds the well-scoped range and there is type-driven repetition (list_/get_definition for tables, views, procedures and functions separately). It feels heavy even if defensible.

    Completeness4/5

    Coverage is strong for a read-only inspection server: exploration, data reads, profiling, stats, index health, Query Store, plan cache, live requests, plan summaries and dependency analysis are all present, with permission fallbacks documented. Minor gaps remain (triggers cannot be listed or defined, no server-wide wait/CPU view, no index-definition or synonym/sequence tools).

    Maintenance

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      D
      maintenance
      MCP server providing read-only access to SQL Server databases for AI assistants, enabling schema exploration, query execution, and foreign key inference with token-efficient TOON responses.
      9
      1
      MIT
    • A
      license
      A
      quality
      B
      maintenance
      MCP server for Microsoft SQL Server that lets LLMs explore schema and execute read-only SELECT queries, with optional stored procedure execution when explicitly enabled.
      3
      64 npm
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables read-only querying and schema inspection of SQL Server databases from MCP clients, exposing tools to run guarded SELECT queries, list databases and tables, and describe table columns, types, defaults, and primary keys.
      MIT