# sqlserver-mcp
An MCP (Model Context Protocol) server exposing SQL Server's curated system
stored procedures, functions, DMVs/DMFs, and catalog views (master/msdb/
sandbox databases) β scaffolded by [mcpify](https://github.com/guercheLE/mcpify)
from a synthetic OpenAPI representation (see `docs/sqlserver-eda-openapi-pipeline/`),
then hand-wired to a real TDS connection (via [`tiberius`](https://github.com/prisma/tiberius))
instead of mcpify's default HTTP client, since these operations describe SQL
objects, not HTTP endpoints.
[](https://github.com/sponsors/guerchele)
Building and maintaining this took real ideation, time, design effort, and compute (including LLM usage) to get right. If it's useful to you, consider [sponsoring its development](https://github.com/sponsors/guerchele) β any amount helps keep it going. π
Exposes exactly 3 tools β `search`, `get`, `call` β backed by an embedded
semantic database (`mcp_store.db`, one per supported SQL Server version β
2017, 2019, 2022, and 2025; run `versions` or see
[`docs/SCHEMA_VERSIONS.md`](docs/SCHEMA_VERSIONS.md) for the full list),
so an LLM never needs the full catalog surface in context.
## Guided workflows (MCP prompts)
Beyond the 3 tools, the server also exposes MCP **prompts** β guided,
multi-step instructions for common SQL Server operational tasks, so a
calling LLM doesn't have to re-derive the right order of `search`/`get`/`call`
calls, the gotchas, and the verification steps from scratch every session.
Start with `sqlserver`, a master menu that routes to the right
sub-workflow below (and delegates the whole thing to an isolated sub-task, if
your MCP client supports one, to keep the tool-call trace out of the main
conversation):
| Prompt | Covers |
|---|---|
| `sqlserver-schema-exploration` | Databases/schemas/tables/views/columns/types/triggers |
| `sqlserver-indexes-constraints` | Indexes, foreign keys, check constraints, compression estimates |
| `sqlserver-security-provisioning` | Login/user/role provisioning |
| `sqlserver-sql-agent-jobs` | SQL Agent job/step/schedule setup |
| `sqlserver-server-administration` | Server/database config, renaming, disk usage, linked servers |
| `sqlserver-performance-diagnostics` | Wait stats, query plans, transactions, I/O, resource governor, In-Memory OLTP/columnstore health, OS-level pressure |
| `sqlserver-blocking-and-locks` | Diagnosing a blocking chain, and β only with explicit confirmation β killing the blocking session |
| `sqlserver-index-tuning-recommendations` | Finding missing-index candidates and, only with explicit confirmation, creating the index |
Every prompt is phrased to search for the operation it needs rather than
naming an `operationId` directly, since object availability can differ
across the four supported engine versions. Prompts that can mutate anything
(SQL Agent jobs, security, killing a session, creating an index) require the
calling LLM to get explicit user confirmation before acting. See
[`docs/mcp-prompts-workflow-plan.md`](docs/mcp-prompts-workflow-plan.md) for
the full design rationale.
## Install
```bash
cargo install sqlserver-mcp --locked # from crates.io
# or, from a checkout:
cargo build --release
```
Prebuilt binaries and installers for each release are on the
[Releases page](https://github.com/guercheLE/sqlserver-mcp-rs/releases), and a
container image is published to `ghcr.io/guerchele/sqlserver-mcp-rs`.
## Compatibility
The server talks TDS 7.3+ to the instance; the catalog it searches is chosen
with `SQLSERVER_API_VERSION` (default `2025`) and should match the engine
version you connect to, since object availability differs between versions.
| SQL Server | `SQLSERVER_API_VERSION` | `sql_server` auth | `windows` auth | `azure_ad` auth |
|---|---|:---:|:---:|:---:|
| 2025 | `2025` (default) | β
| β
ΒΉ | β
|
| 2022 | `2022` | β
| β
ΒΉ | β
|
| 2019 | `2019` | β
| β
ΒΉ | β Β² |
| 2017 | `2017` | β
| β
ΒΉ | β Β² |
- `sql_server` auth requires the instance to run in Mixed Mode.
- ΒΉ Only when `sqlserver-mcp` itself runs on Windows (NTLM/SSPI via
`tiberius`'s native binding). On Linux/macOS it fails at connect time.
- Β² Microsoft Entra ID (Azure AD) authentication for on-premises/Linux
instances is a SQL Server 2022 engine feature.
| Host OS for `sqlserver-mcp` | Status |
|---|---|
| Linux x86_64 | Tested in CI, prebuilt binary, container image |
| macOS Apple silicon | Tested in CI, prebuilt binary |
| Windows x86_64 | Prebuilt binary; the only host where `windows` auth works |
| Others (e.g. Linux aarch64, macOS Intel) | Build from source with `cargo install` |
Azure SQL Database / Managed Instance are not a target of the bundled
catalogs (they are built from on-premises engine EDA output); the closest
match is `SQLSERVER_API_VERSION=2025`, but expect objects that don't exist there.
## Setup
```bash
cargo run -- setup
```
Interactively collects the SQL Server host and the credentials your chosen auth method needs, then lets you persist them as a `.env` file, a `config.json` file, or a ready-to-run CLI invocation.
## Configuration
| Env var | Purpose |
|---|---|
| `SQLSERVER_URL` | SQL Server host, or `host:port`. |
| `SQLSERVER_AUTH_METHOD` | One of `sql_server` / `windows` / `azure_ad` β see `docs/sqlserver-eda-openapi-pipeline/README.md`'s `securitySchemes` documentation for what each instance/version supports. |
| `SQLSERVER_USERNAME` / `..._PASSWORD` | `sql_server`/`windows` auth β checked before the OS keychain/encrypted-file fallback. |
| `SQLSERVER_CLIENT_ID` / `..._CLIENT_SECRET` / `..._TENANT_ID` | `azure_ad` auth (client-credentials grant against `https://database.windows.net/.default`). |
| `SQLSERVER_SQL_PORT` | TDS port when `URL` has no `:port` suffix (default `1433`). |
| `SQLSERVER_TRUST_SERVER_CERT` | Trust the server's TLS cert without CA verification (default `true` β a local/dev instance's self-signed cert; set `false` for a production CA-signed cert). |
| `SQLSERVER_POOL_MAX_SIZE` | Max pooled SQL Server connections (default `10`). |
| `SQLSERVER_API_VERSION` | Which bundled catalog to search: `2017` / `2019` / `2022` / `2025` (default `2025`). Match it to the engine version. |
| `SQLSERVER_DEFAULT_DATABASE` | Fallback database for a `call` that passes no `execution_database` (unset: the login's current database). |
| `SQLSERVER_LOG_LEVEL` | Log verbosity (`trace`/`debug`/`info`/`warn`/`error`). |
| `SQLSERVER_READ_ONLY` | Defaults to `true`. T-SQL has no session-level "read only" setting the way PostgreSQL does, so this is enforced by object classification instead: `call` refuses any operation whose catalog type isn't `VIEW` or a `*_FUNCTION` kind β SQL Server itself guarantees both can't write (a view is only ever a `SELECT`, and functions are language-level prohibited from having side effects), independent of what the connecting login's actual grants allow. Stored procedures, and any operation whose classification is missing/unrecognized, are rejected outright rather than assumed safe. Set to `false` to allow `call` to invoke stored procedures. |
See `.env.example` for the full list of supported variables.
Windows Authentication (`windows`) only works when this server itself runs on
Windows β `tiberius`'s NTLM/SSPI binding is a native-Windows feature; on
Linux/macOS (this pipeline's primary target, see `docs/sqlserver-eda-openapi-pipeline/docker-compose.yml`)
it fails with a clear error at connection time. Use `sql_server` or
`azure_ad` there instead.
## Minimum SQL Server permissions
Create a dedicated login rather than connecting as `sa`; the server can never
do more than that login is granted, independently of `SQLSERVER_READ_ONLY`.
For the default read-only mode (catalog views, DMVs/DMFs and functions):
```sql
USE master;
CREATE LOGIN sqlserver_mcp WITH PASSWORD = '<strong password>', CHECK_POLICY = ON;
GRANT VIEW SERVER STATE TO sqlserver_mcp; -- server-scoped DMVs (waits, sessions, plans)
GRANT VIEW ANY DEFINITION TO sqlserver_mcp; -- metadata of every object in sys.* catalog views
GRANT CONNECT ANY DATABASE TO sqlserver_mcp; -- query sys.* views in each user database
USE msdb;
CREATE USER sqlserver_mcp FOR LOGIN sqlserver_mcp;
ALTER ROLE SQLAgentReaderRole ADD MEMBER sqlserver_mcp; -- SQL Agent job/schedule metadata
```
Notes:
- Without `VIEW ANY DEFINITION`, catalog views silently return only the
objects the login owns or has some permission on, which looks like
"missing" rows rather than an error.
- On 2022+, `VIEW SERVER STATE` can be narrowed to `VIEW SERVER PERFORMANCE
STATE` (and `VIEW SERVER SECURITY STATE` for security DMVs) if you want the
smallest grant.
- Database-scoped DMVs (`sys.dm_db_*`) inside a user database need
`VIEW DATABASE STATE` there (2022+: `VIEW DATABASE PERFORMANCE STATE`).
With `SQLSERVER_READ_ONLY=false` (stored procedures allowed), grant only what
the workflows you use need, e.g. `EXECUTE` on specific procedures,
`ALTER ANY LOGIN` / membership in `securityadmin` for login provisioning, or
`SQLAgentOperatorRole` in `msdb` to manage SQL Agent jobs. Avoid `sysadmin`.
## Connecting from an MCP client
Most clients (Claude Desktop, Claude Code, Cursor, VS Code) accept the same
`mcpServers` shape. Stdio, with a SQL login:
```json
{
"mcpServers": {
"sqlserver": {
"command": "sqlserver-mcp",
"args": ["start"],
"env": {
"SQLSERVER_URL": "db.example.internal:1433",
"SQLSERVER_AUTH_METHOD": "sql_server",
"SQLSERVER_USERNAME": "sqlserver_mcp",
"SQLSERVER_PASSWORD": "<password>",
"SQLSERVER_API_VERSION": "2022",
"SQLSERVER_TRUST_SERVER_CERT": "false"
}
}
}
}
```
Instead of putting the password in the client config, run
`sqlserver-mcp setup` once: credentials are then read from the OS keychain
(or the encrypted-file fallback) and the `env` block only needs the URL,
auth method and version.
Microsoft Entra ID (2022/2025), using a service principal:
```json
"env": {
"SQLSERVER_URL": "db.example.internal",
"SQLSERVER_AUTH_METHOD": "azure_ad",
"SQLSERVER_CLIENT_ID": "<app id>",
"SQLSERVER_CLIENT_SECRET": "<secret>",
"SQLSERVER_TENANT_ID": "<tenant id>"
}
```
Local Docker instance (self-signed certificate, the one case where
`SQLSERVER_TRUST_SERVER_CERT=true` is appropriate):
```bash
SQLSERVER_URL=localhost:1433 SQLSERVER_AUTH_METHOD=sql_server \
SQLSERVER_USERNAME=sa SQLSERVER_PASSWORD='<password>' \
SQLSERVER_TRUST_SERVER_CERT=true SQLSERVER_API_VERSION=2022 \
sqlserver-mcp search "list databases and their sizes"
```
Over HTTP (several clients, or another container), start
`sqlserver-mcp http --host 127.0.0.1 --port 3000` and point the client at
`http://127.0.0.1:3000/mcp`. The HTTP transport has no authentication of its
own: keep it on loopback or behind an authenticating reverse proxy. See
[SECURITY.md](SECURITY.md).
## Usage
### Terminal Client (default)
```bash
sqlserver-mcp search "create an issue"
sqlserver-mcp get <operationId>
sqlserver-mcp call <operationId> --args '{"key":"value"}'
```
### Harness Server
```bash
sqlserver-mcp start # stdio transport (default)
sqlserver-mcp http --host 127.0.0.1 --port 3000 # HTTP transport
```
## Docker
```bash
# Stdio: the MCP client launches this one-off process and owns its stdin/stdout pipes
docker compose run --rm -T sqlserver-mcp
# HTTP: a long-running network endpoint published on http://localhost:3000
docker compose up sqlserver-mcp-http
```
Run these commands from the repository root. Docker Compose automatically discovers `docker-compose.yml`; `sqlserver-mcp` and `sqlserver-mcp-http` are service names inside that file, not filenames. Writing `docker compose -f docker-compose.yml ...` is equivalent, but `-f` is only needed when the file has another name or location, or when combining multiple Compose files.
Both services read configuration from a local `.env` file (copy `.env.example`) and persist credentials and configuration under `~/.sqlserver-mcp` on the host. For stdio, `-T` disables pseudo-TTY allocation so MCP JSON-RPC stays on raw stdin/stdout, and `--rm` removes the one-off container when the client exits.
Stdio is a process transport, not a listening service: the MCP client must start the server and communicate through that exact child process's stdin/stdout. This is useful when an MCP client is configured to launch `docker compose run --rm -T sqlserver-mcp`, in local scripts or CI that directly exchange MCP messages with the process, or in a custom image where your application launches the generated server's `start` subcommand as a child process. Merely putting the application and server in the same imageβor starting the stdio container separately with `docker compose up`βdoes not connect their streams. One stdio server process normally serves one client. Use HTTP when independently started applications, multiple clients, another container, or a remote machine need to connect over the network.
## Testing
```bash
cargo test
```
## Coverage
```bash
bash scripts/coverage.sh # writes target/coverage/html/index.html (requires cargo-llvm-cov)
```
## Profiling
```bash
bash scripts/profile.sh # clean CPU profiling via samply
bash scripts/profile-heap.sh # separate heap profiling via dhat-rs
```
Both scripts profile a repeated in-process `search "test query"` workload so
the one-time embedding-model startup cost is amortized. `profile.sh` uses 3
warmups and 250 measured iterations; `profile-heap.sh` uses 1 warmup and 5
measured iterations. Override these defaults with `PROFILE_QUERY`,
`PROFILE_WARMUPS`, `PROFILE_ITERATIONS`, `PROFILE_HEAP_WARMUPS`, and
`PROFILE_HEAP_ITERATIONS`.
The scripts default `SQLSERVER_URL=localhost` and
`SQLSERVER_AUTH_METHOD=sql_server` when those variables are unset. This is
safe for the profiling workload because `search` reads only the embedded
catalog and does not connect to SQL Server.
`profile/bottleneck-report.md` combines the largest coverage gaps with the
hottest CPU functions in one small text file. CPU profiling deliberately uses
an ordinary release build; DHAT allocator instrumentation is enabled only by
`profile-heap.sh`, so it cannot distort Samply's CPU samples. Requires
[samply](https://github.com/mstange/samply) (`cargo install samply`).
---
Generated by mcpify β do not hand-edit generated files; re-run mcpify against an updated OpenAPI spec instead.