MS SQL Server MCP Server
This server provides a secure, read-only (or write-enabled) MCP interface to Microsoft SQL Server, enabling querying, schema exploration, performance monitoring, and lock/deadlock analysis.
Query execution – Run read-only SQL (SELECT/WITH, temp-table batches, whitelisted EXEC) via
mssql_query; supports pagination and JSON/Markdown output.Database discovery – List databases, tables (with row counts/sizes), sample data, and test connectivity.
Schema introspection – Get table schemas, foreign-key relationships, views, stored procedures (with definitions/parameters), and search object definitions for text fragments.
Performance tuning – Analyze index usage, fragmentation (with rebuild/reorganize recommendations), top expensive queries (by CPU, duration, reads, etc.), overall performance health, and storage usage.
Lock & blocking analysis – View current locks, find blocking chains with lead blockers, and retrieve recent deadlock events from system_health.
Resource monitoring – Track CPU, memory, sessions, and top resource-consuming queries.
Security & compliance – Two-layer read-only enforcement, parameterized queries, audit logging, and blocking of dangerous server-level statements (even in write mode).
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@MS SQL Server MCP Server show me the top 5 customers by order amount"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
MS SQL Server MCP Server
A secure, read-only Model Context Protocol (MCP) server for Microsoft SQL Server with built-in performance monitoring and lock detection.
📦 npm: @piyapat/mssql-mcp-server
Requirements
Node.js 22 or newer. Raised from 18 in v2.0.2:
mssql12 depends ontedious20, which requires Node 22.SQL Server 2019 (15.x), 2022 (16.x), or 2025 (17.x) — all editions including Express. Azure SQL Database works for the query/schema tools; see the per-edition notes from
mssql_test_connection.
Related MCP server: mssql-explorer-mcp
Quick Start with npx
You can run this MCP server directly without installation using npx:
npx @piyapat/mssql-mcp-serverInstallation
Option 1: Use with npx (Recommended for Testing)
# Run directly with environment variables
MSSQL_SERVER=localhost \
MSSQL_DATABASE=mydb \
MSSQL_USER=readonly \
MSSQL_PASSWORD=password \
npx @piyapat/mssql-mcp-serverOption 2: Global Installation
# Install globally
npm install -g @piyapat/mssql-mcp-server
# Run
mssql-mcp-serverOption 3: Local Installation
# Clone and install
git clone https://github.com/PiyapatRag/mssql-mcp-server.git
cd mssql-mcp-server
npm install
npm run build
# Run
npm startConfiguration
Step 1: Create a .env file (Recommended)
Credentials live in a .env file — not hard-coded in the MCP client's JSON config:
cp .env.example .env
# then edit .env with your credentialsThe server looks for a .env file in this order (first found wins):
The path in
MSSQL_ENV_FILE(explicit override).envin the current working directory.envin the project root (next topackage.json)
Variables already set in the MCP client's "env" block always take precedence
over the .env file, and .env is git-ignored.
Step 2: Point Claude Desktop at the server
Edit your Claude Desktop config:
Windows: %APPDATA%\Claude\claude_desktop_config.json
macOS/Linux: ~/Library/Application Support/Claude/claude_desktop_config.json
With a .env in the project root, no credentials are needed in the JSON at all:
{
"mcpServers": {
"mssql": {
"command": "node",
"args": ["C:\\path\\to\\mssql-mcp-server\\build\\index.js"]
}
}
}If the .env lives somewhere else, pass only its path:
{
"mcpServers": {
"mssql": {
"command": "node",
"args": ["C:\\path\\to\\mssql-mcp-server\\build\\index.js"],
"env": {
"MSSQL_ENV_FILE": "C:\\secure\\location\\mssql.env"
}
}
}
}Setting variables directly in the "env" block still works (and overrides the
.env file) — useful for npx setups or running several servers against
different databases.
Environment Variables
Variable | Description | Default | Required |
| SQL Server hostname or IP |
| Yes |
| Database name | - | Yes |
| SQL Server username (or domain user when | - | Yes |
| Password | - | Yes |
| Windows/NTLM domain. When set, Windows Authentication is used instead of SQL authentication | - | No |
| SQL Server port |
| No |
| Encrypt the connection (true/false). Only a literal |
| No |
| Skip certificate validation (true/false). Opt-in — leave off in production |
| No |
|
|
| No |
| Comma-separated whitelist of stored procedures | - | No |
| Explicit path to a | - | No |
| Query timeout in ms |
| No |
| Max pooled connections |
| No |
| Log every tool call to stderr as one JSON line (tool, mode, truncated query, row counts, duration, outcome). Set |
| No |
| Return the driver's full error text to the client. Off by default: errors are capped to their first line so a failing query can't be used to map the schema. Full detail always goes to stderr |
| No |
Server Modes
Read-only mode (MSSQL_READ_ONLY=true, default)
mssql_query accepts only:
A single
SELECT/WITH...SELECTA multi-statement batch led by
DECLARE,INSERT, orCREATE TABLE #...that writes only to session-local#temptables /@tablevariables — e.g.INSERT INTO #t SELECT ...orCREATE TABLE #t (...); INSERT INTO #t ...; SELECT * FROM #t.CREATE INDEX ... ON #t,TRUNCATE/ALTER/DROP TABLE #tare also allowed inside such batches. Global##temptables are never allowed (they are visible to every session, so they count as persistent).EXECof a whitelisted procedure whose definition does not write to a persistent table
Everything else is rejected: writes/DDL on persistent objects, dynamic SQL,
EXEC inside batches (prevents bypassing the procedure whitelist), DBCC,
and stacked statements after a SELECT/WITH/EXEC.
Write mode (MSSQL_READ_ONLY=false)
INSERT / UPDATE / DELETE / DDL are permitted, but these are always blocked
regardless of mode:
xp_cmdshell, xp_reg* (read and write), xp_dirtree, xp_fileexist,
sp_OA*, sp_configure, RECONFIGURE, SHUTDOWN, KILL, DROP DATABASE,
ALTER DATABASE, RESTORE, BULK INSERT, CREATE ASSEMBLY,
CREATE/ALTER/DROP LOGIN/USER/CREDENTIAL/CERTIFICATE, ALTER SERVER,
ALTER SERVER ROLE/ALTER ROLE, sp_addrolemember/sp_addsrvrolemember/
sp_droprolemember, sp_addlinkedserver, EXECUTE AS, sp_executesql,
GRANT/DENY/REVOKE, OPENROWSET/OPENDATASOURCE/OPENQUERY, and the
server-side file readers fn_get_audit_file, fn_xe_file_target_read_file,
fn_trace_gettable, sp_readerrorlog/xp_readerrorlog.
⚠️ Use write mode only with a SQL login whose own permissions are equally limited — the database login remains the primary security boundary.
Key Features
Security First
✅ Two-layer read-only enforcement - A database read-only login (primary) plus an application-level allow-list (defense-in-depth). The app accepts
SELECT/WITH...SELECT,DECLAREbatches that write only to#temptables /@tablevariables, andEXECof whitelisted procedures whose definitions never write to a persistent table✅ Quote-aware SQL scanning - Comments and literals are removed in a single left-to-right pass that tracks quote state, so a
--or;hidden inside a string literal cannot smuggle a second statement past the analyzer✅ Parameterized queries - Built-in SQL injection protection
✅ SSL/TLS by default - Encryption and certificate validation are opt-out, not opt-in
✅ Streamed result paging - Rows are streamed and the read is cancelled one row past the requested page, so a large
SELECTcan't exhaust the server's memory✅ Audit trail - Every tool call is logged to stderr as one JSON line (
MSSQL_AUDIT_LOG)✅ Connection pooling - Optimized resource management
Performance Monitoring
📊 Real-time lock detection - Identify blocking and deadlock situations
📈 Resource usage tracking - CPU, memory, and query performance metrics
🔍 Top query analysis - Find resource-intensive queries
⚡ Session monitoring - Track active and blocked sessions
Database Exploration
🗂️ Schema introspection - Tables, columns, keys, and constraints
📝 Stored procedure analysis - View definitions and parameters
🔎 Intelligent querying - Natural language to SQL with Claude
Available Tools (19)
Core
Tool | Description |
| Execute SQL. Read-only validation by default; write mode via |
| Test connectivity; returns server/edition/version, database, login, and current mode. |
| All databases with state, recovery model, compatibility level. |
| Tables with row count and size (MB), optionally filtered by schema. |
| Preview rows from a table (default 10, max 100) — no SQL needed, injection-safe. |
Schema exploration
Tool | Description |
| Columns, data types, PK/FK per table. |
| Foreign-key graph: from/to table+column, delete/update actions. |
| Views with full SQL definitions. |
| Stored procedures with parameters and full definitions. |
| Search the source of all procs/views/functions/triggers for a text fragment — impact analysis for legacy systems. |
Performance & storage
Tool | Description |
| Index usage stats (seeks/scans/updates) + optimizer-suggested missing indexes. |
| Fragmentation per index with REBUILD (≥ 30%) / REORGANIZE (5–30%) recommendations and ready-to-run |
| Most expensive queries ranked by |
| Health check: top wait stats (benign waits filtered), memory counters (PLE, grants pending, total vs target), workload counters, plus rule-based tuning recommendations. |
| Largest tables by size + database file sizes. |
| Sessions, CPU, buffer cache, top queries by CPU. |
Locks, blocking & deadlocks
Supported on SQL Server 2019 (15.x), 2022 (16.x), and 2025 (17.x) — all editions
including Express. Output includes the detected server version/edition and warns
when running on an older version (best-effort). Requires VIEW SERVER STATE.
Version & edition compatibility:
Express | Standard | Enterprise / Developer / Eval | Azure SQL MI | Azure SQL DB | |
Query / schema / storage tools | ✅ | ✅ | ✅ | ✅ | ✅ |
| ✅ | ✅ | ✅ | ✅ | ✅ |
| ✅ | ✅ | ✅ | ✅ | ❌ (tool explains alternatives) |
| ✅ | ✅ | ✅ | ✅ | ⚠️ limited scope |
Rows/columns above apply to SQL Server 2019, 2022, and 2025. Older versions
(2016/2017) mostly work but are reported as best-effort in the tool output.
mssql_test_connection reports the detected edition class and its engine
limits (e.g. Express: 10 GB/database, ~1.4 GB buffer pool, 4 cores).
Tool | Description |
| Raw view of current locks and waits per session. |
| Blocking chains (victim ← blocker), lead-blocker identification incl. idle sessions holding open transactions, with SQL text of both sides. |
| Recent deadlock events from the built-in |
Claude Examples:
"Show me the top 10 customers by order count"
"Which tables are the largest, and which indexes are unused?"
"Which sessions are blocked right now, and who is the root blocker?"
"Were there any deadlocks last night, and which query caused them?"
"Find every stored procedure that references the CustomerOrders table"Security Setup
Read-only is enforced in two layers. The database login is the primary guard — even a write statement that reached the server cannot execute. The application-level allow-list (
classifyQueryin src/index.ts) is defense-in-depth: it accepts only read-only entry points and rejects everything else (writes, DDL, dynamic SQL, stacked queries). Because it allow-lists the leading keyword rather than blocking words, columns or aliases namedCreate,Update,CreatedDate, etc. are not blocked.
Create Read-Only SQL User (Recommended)
A ready-to-run script is provided at
scripts/create-readonly-login.sql — edit the
placeholders and run it as a sysadmin. It applies the least-privilege setup
below:
-- 1. Create login
CREATE LOGIN mcp_readonly WITH PASSWORD = 'SecurePassword123!';
-- 2. Switch to your database
USE YourDatabase;
-- 3. Create user
CREATE USER mcp_readonly FOR LOGIN mcp_readonly;
-- 4. Grant read permissions
ALTER ROLE db_datareader ADD MEMBER mcp_readonly;
-- 4b. Explicitly DENY writes (defense-in-depth)
ALTER ROLE db_denydatawriter ADD MEMBER mcp_readonly;
-- 5. Grant monitoring permissions
GRANT VIEW SERVER STATE TO mcp_readonly;
GRANT VIEW DATABASE STATE TO mcp_readonly;
GRANT VIEW DEFINITION TO mcp_readonly;
-- 6. Verify permissions
SELECT
dp.name AS DatabaseUser,
dp.type_desc,
r.name AS RoleName
FROM sys.database_principals dp
LEFT JOIN sys.database_role_members drm ON dp.principal_id = drm.member_principal_id
LEFT JOIN sys.database_principals r ON drm.role_principal_id = r.principal_id
WHERE dp.name = 'mcp_readonly';Development
Build
npm run buildWatch Mode
npm run devTesting Locally
# Set environment variables
export MSSQL_SERVER=localhost
export MSSQL_DATABASE=testdb
export MSSQL_USER=sa
export MSSQL_PASSWORD=password
# Run
npm startTroubleshooting
"command not found" Error with npx
If you get an error running with npx:
Ensure Node.js 22+ is installed:
node --versionClear npm cache:
npm cache clean --forceTry with full package name:
npx --package=@piyapat/mssql-mcp-server mssql-mcp-serverConnection Errors
Error: Login failed for user
-- Check authentication mode (must be Mixed Mode)
USE master;
GO
EXEC xp_instance_regread
N'HKEY_LOCAL_MACHINE',
N'Software\Microsoft\MSSQLServer\MSSQLServer',
N'LoginMode';
GO
-- Should return 2 for Mixed ModeError: Cannot connect to server
Verify SQL Server Browser service is running
Check firewall allows port 1433
Ensure TCP/IP protocol is enabled in SQL Server Configuration Manager
Permission Errors
-- Grant additional permissions if needed
USE YourDatabase;
GRANT EXECUTE TO mcp_readonly; -- If you need to call stored procedures
GRANT SHOWPLAN TO mcp_readonly; -- For execution plansReporting a Vulnerability
Please don't open a public issue for a security bug. Use GitHub private vulnerability reporting, or the maintainer address on the npm package page. Scope, response targets, and safe-harbor terms are in SECURITY.md.
The guard battery in
scripts/security-validation.mjs runs the real
compiled analyzer against ~100 attack cases and runs in CI — npm run test:security reproduces it locally.
Security Acknowledgements
🙏 Thank you to Kietgboiz17 (kietgboiz17@gmail.com) for the security review, vulnerability report, and red-teaming that hardened this project — including the read-only guard bypass fixed in 2.0.2 and the additional guard hardening in 2.0.3. See CHANGELOG.md and SECURITY_REVIEW.md.
Best Practices
Always use read-only accounts in production
Keep encryption on (
MSSQL_ENCRYPT=true,MSSQL_TRUST_CERT=false) — both are the defaultMonitor regularly - Set up regular monitoring checks
Limit result sets - Use maxRows; rows are streamed, so a page is all that is read
Index optimization - Monitor slow queries and add indexes
Regular maintenance - Keep statistics updated
Audit access - Keep
MSSQL_AUDIT_LOGon and retain the server's stderr log
Contributing
Contributions are welcome — see CONTRIBUTING.md for development setup, pull-request guidelines, and the release process. Version history is tracked in CHANGELOG.md.
License
MIT License - Feel free to use and modify for your needs.
Built With
@modelcontextprotocol/sdk - MCP SDK
mssql - SQL Server client for Node.js
Support
For issues:
Check the Troubleshooting section
Review SQL Server error logs
Verify Claude Desktop logs
Check database permissions
Built for Claude Desktop • Security First • Performance Focused
Available Tools
17 toolsmssql_analyze_indexesARead-only
Analyze index usage (seeks/scans/lookups/updates per index) and list potentially missing indexes suggested by the query optimizer. Optionally filter usage stats by table name.
Inputs: tableName, response_format.
mssql_analyze_storageARead-only
Analyze storage: largest tables by size (row count, total/used MB) and database file sizes. Useful for capacity planning and finding space hogs.
Inputs: topTables, response_format.
mssql_find_blockingARead-only
Find current blocking chains: which sessions are blocked, by whom, on what resource, and for how long. Identifies lead blockers (including idle sessions holding open transactions) with their SQL text. Supported: SQL Server 2019 (15.x), 2022 (16.x), 2025 (17.x) — all editions including Express. Requires VIEW SERVER STATE.
Inputs: response_format.
mssql_get_deadlocksARead-only
Retrieve recent deadlock events from the built-in system_health Extended Events session, including the full deadlock graph XML, victim sessions, and the queries involved. Source 'ring_buffer' (default, fast, recent events only) or 'file' (reads system_health .xel files, further back but slower). Supported: SQL Server 2019 (15.x), 2022 (16.x), 2025 (17.x) — all editions including Express. Requires VIEW SERVER STATE.
Inputs: source, maxEvents, response_format.
mssql_get_relationshipsARead-onlyIdempotent
Get foreign key relationships between tables: constraint name, from/to table and column, and delete/update actions. Optionally filter by table name (matches either side).
Inputs: tableName, response_format.
mssql_get_schemaARead-onlyIdempotent
Get database schema information including tables, columns, data types, primary keys, and foreign keys. Optionally filter by table name.
Inputs: tableName, response_format.
mssql_get_stored_proceduresARead-onlyIdempotent
List stored procedures in the database with their definitions and parameters. Optionally filter by procedure name.
Inputs: procedureName, response_format.
mssql_get_viewsARead-onlyIdempotent
List views in the database with their full SQL definitions. Optionally filter by view name to get a single view's definition.
Inputs: viewName, response_format.
mssql_index_fragmentationARead-only
Analyze index fragmentation and recommend maintenance: REBUILD (fragmentation ≥ 30%), REORGANIZE (5–30%), or OK (< 5%). Generates ready-to-run ALTER INDEX statements (ONLINE=ON suggested automatically on editions that support it). Small indexes below minPageCount are excluded since fragmentation there is harmless.
Inputs: tableName, minPageCount, response_format.
mssql_list_databasesARead-onlyIdempotent
List all databases on the SQL Server instance with state, recovery model, compatibility level, and creation date.
Inputs: response_format.
mssql_list_tablesARead-onlyIdempotent
List tables in the current database with schema, row count, and size in MB. Optionally filter by schema name.
Inputs: schemaName, response_format.
mssql_monitor_locksARead-only
Monitor database locks, blocking sessions, and potential deadlocks. Shows lock types, resources, and wait times.
Inputs: response_format.
mssql_monitor_usageBRead-only
Get database resource usage statistics including CPU, memory, active sessions, and top resource-consuming queries.
Inputs: topQueries, response_format.
mssql_performance_healthARead-only
Overall performance health check: top wait statistics (with benign waits filtered out), memory counters (Page Life Expectancy, memory grants pending, total vs target memory), workload counters (batch requests, compilations), and rule-based optimization recommendations (e.g. high CXPACKET → review MAXDOP, PAGEIOLATCH → check I/O and indexes, LCK_M → run mssql_find_blocking).
Inputs: response_format.
mssql_queryARead-onlyIdempotent
Execute a read-only SQL query against the MS SQL Server database. Accepts: a single SELECT / WITH...SELECT; a multi-statement batch led by DECLARE, INSERT, or CREATE TABLE # that writes ONLY to session-local #temp tables or @table variables (global ##temp is never allowed); or EXEC of a whitelisted stored procedure whose definition does not write to a persistent table. Writes to real tables, DDL on persistent objects, dynamic SQL, EXEC inside batches, and DBCC are blocked (server runs with MSSQL_READ_ONLY=true). Returns results as JSON or Markdown.
Inputs: query (required), offset, maxRows, response_format.
mssql_sample_dataARead-onlyIdempotent
Retrieve sample rows from a table (default 10, max 100). Safe way to preview data without writing SQL. Accepts 'table' or 'schema.table'.
Inputs: tableName (required), rows, response_format.
mssql_top_queriesARead-only
Find the most expensive queries from the plan cache, ranked by a chosen metric: cpu, duration, reads (logical I/O), writes, memory (grant size), or executions. Returns per-query totals and averages with the SQL text — the starting point for performance tuning.
Inputs: top, metric, response_format.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 17 tools
Most tools target a clear domain, but several overlap: mssql_monitor_locks overlaps with mssql_find_blocking and mssql_get_deadlocks, while mssql_monitor_usage, mssql_top_queries, and mssql_performance_health all touch performance metrics. Descriptions help clarify the boundaries, but an agent could still route locking or performance questions to the wrong tool.
The common mssql_ prefix and mostly verb-led names create a predictable pattern: get_*, list_*, analyze_*, monitor_*. However, a few tools use noun-phrase names instead of verb_noun, including mssql_index_fragmentation, mssql_top_queries, and mssql_performance_health, which is a minor consistency break.
At 17 tools, this server sits just above the typical 3-15 sweet spot, but the breadth of SQL Server administration and diagnostics justifies the count. Each tool covers a meaningful task area, though some performance and lock-related tools could potentially be consolidated.
The server provides strong read-only coverage: schema exploration, querying, sample data, index/storage analysis, performance health, blocking, and deadlock diagnostics. Minor gaps such as dedicated query-plan details or active session introspection prevent a perfect score, but no critical workflow appears missing.
Related MCP Connectors
2,000+ MCP servers read at source level. Know what one does before you connect. Free, no key.
A free, read-only remote MCP server with templates for a file-based business operating system.
Read-only MCP server for The Quiet Protocol's engines, benchmarks, proof, and business data.
Paid remote MCP for governed database query review, SQL simulation, approvals, and audits.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceRead-only SQL Server MCP server enabling safe database queries, table listing, and schema inspection with built-in security protections.MIT
- AlicenseNot gradedqualityDmaintenanceA read-only MCP server for exploring on-premises, multi-instance Microsoft SQL Server estates from AI clients, with read-only enforcement and Windows authentication support.Apache 2.0
- FlicenseAqualityCmaintenanceA read-only MCP server for Microsoft SQL Server that allows running SELECT queries and analyzing query performance with statistics.4-
- AlicenseAqualityDmaintenanceA read-only MCP server for browsing and querying SQL Server databases, providing tools to list schemas, tables, describe columns, and execute safe SELECT queries with validated parameters.15ISC