
Elekto MCP for SQL Server
io.github.elekto-com-brv2.3.2更新于 Oct 4, 2026
Read-only SQL Server introspection and querying: schema, definitions, dependencies and data.
概览
只读的 SQL Server 内省与查询:架构、定义、依赖关系和数据。
- 功能
- 通过 stdio 提供对 SQL Server 2017+ 数据库的只读访问。工具可列出数据库、架构、表、视图、存储过程和函数;返回表与视图的列结构、DDL 定义、依赖图和表引用;分析列数据概况;诊断重复、未使用和缺失的索引;比较两个已配置数据库的架构;并执行带筛选、分组、排序、采样和分页的 SELECT 查询,且限制返回行数。
- 适用场景
- 适合让助手在不授予写权限的前提下探索或记录现有 SQL Server 数据库、回答关于其结构或数据的问题,或比较架构。适用于开发与探索场景,且数据库内容可能被发送给 LLM 服务商。
- 运行要求
- 在用户机器上运行的本地进程;需要 .NET 10 运行时或 SDK(dnx 需要 SDK)。连接来自 JSON 连接文件、appsettings.json 或 web.config 的 ConnectionStrings,或 MCP_SQL_CONNECTIONS 环境变量;凭据可用 %{VARIABLE_NAME} 环境变量引用。需要能访问 SQL Server 的网络。
安装
在 SourceWeft 中
- 打开 控制台中的 Elekto MCP for SQL Server,将其添加到工作区。
- 为需要使用其工具的对话启用该服务。
Desktop only,通过 STDIO。 STDIO 服务会启动本地进程,因此需要 SourceWeft 桌面宿主。
其他 MCP 客户端
参照 仓库 中的启动说明。
README
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 and 2022). 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:
- The AI agent calls tools on this server to read data from your SQL Server database.
- 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.
- 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.
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_rowsto 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. Altouht 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.
Available Tools
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:
Everything else — every other tool, every other field — is unchanged.
What changed in 2.1.0
Nothing changes shape: arrays are still arrays and objects keep every field they had. A few values now say "unknown" instead of passing a guess for a fact, which is worth knowing if you parse them:
What changed in 2.2.0
No tool result changes shape. What changes is how the server starts and how it is packaged:
The process no longer exits with code 1 when the configuration is missing or unreadable. Anything that relied on that exit code should read a tool's answer instead. The README also gained setup instructions for Claude Code and Codex.
What changed in 2.3.0
No tool result changes shape; what changes is what the tools say about themselves, which is what an agent chooses them by:
What changed in 2.3.1
Nothing changes shape. generate_dependency_dot now says which way its arrows point, what it returns
besides the DOT text, how to render it and when another tool fits better. The server is listed in
the MCP Registry as "Elekto MCP for SQL Server", and each release now also appears under the
repository's GitHub Releases.
What changed in 2.3.2
Nothing changes shape. When no connection is configured, the guidance returned to the agent now
tells it to agree with the user before writing anything, and never to write a password into the
connections file or anywhere else, using %{VARIABLE} in its place. It also points to connections
the project may already keep where this server does not look (spring.datasource.url in
application.properties or application.yml, or a sqlserver:// or mssql:// URL in a .env
file), for the agent to show the user rather than for the server to parse.
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:
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:
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:
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:
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
As a .NET global tool (recommended)
Requires .NET 10 Runtime or SDK.
Upgrade to a newer version:
After installation the elekto-mcp-sql command is available on PATH.
Use it directly in .mcp.json — no path needed:
Zero-config: if your project already has a
ConnectionStringssection inappsettings.json,web.configorApp.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:
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)
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:
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):
Full format (with options):
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
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_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:
- 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:
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:
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:
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:
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:
This adds the server to ~/.codex/config.toml (%USERPROFILE%\.codex\config.toml on Windows),
so it applies to every project:
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:
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:
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):
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).
Recommended: local connections file (zero-config)
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:
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:
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 (\\\\):
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
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.
Running the tests
From the repository root:
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 namedElektoMcpTest, 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:
- The
ELEKTO_MCP_SQL_CONN_TESTenvironment 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. - LocalDB, only on Windows and only if the
(localdb)\MSSQLLocalDBinstance answers. - A disposable container started through Testcontainers
from the
mcr.microsoft.com/mssql/server:2022-latestimage. 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:
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:
Recommended permissions
Everything the tools read, with no permission to change anything:
On SQL Server 2022 and later the last grant can be narrowed to the permission the index DMVs actually need:
None of these lets the login change data or schema. 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: only SELECT on tables and views. DML and procedure/function execution are not supported.
query_tablebuilds SQL internally from validated parameters. Identifiers (table, schema, columns) are validated against a regular expression before being composed into SQL.- The WHERE clause is accepted as free text (necessary for flexibility), but DML is impossible
since the command is always built as
SELECT TOP n ... FROM [t] WHERE .... max_query_rowscaps the maximum number of rows returned per database (default 10,000). Thetopparameter inquery_tableis always clamped to this value, and the result says so viatop_requestedandtruncatedrather 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.
来源:README.md,提交 661cb54
工具
0版本历史
1- v2.3.2最新Oct 4, 2026

