mcp-sqlserver
A read-only MCP server for Microsoft SQL Server that lets AI assistants safely inspect databases, run SELECT queries, and perform DBA diagnostics without any data mutation.
Server management: List configured SQL Server connections (
list_servers) and run health checks (health_check).Schema discovery: Enumerate databases, schemas, tables, views, columns, foreign keys, indexes, constraints, and triggers.
Read-only querying: Execute parameterized SELECT/WITH queries with row limits and export results as CSV or JSON.
Stored procedure inspection: List procedures and view their parameters and T-SQL source without executing them.
Performance & DBA diagnostics: Get query plans, active queries, table stats, index usage, missing indexes, server/database info, wait stats, deadlocks, blocking chains, long transactions, space usage, backup history, and Query Store stats.
Developer utilities: Compare schemas between databases, generate code models (TypeScript/C#/SQL), generate INSERT scripts, create Mermaid ER diagrams, generate fake test data, and sample table rows.
Multi-server support: Target different configured servers via an optional
serverparameter.
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., "@mcp-sqlserver show me the users table schema"
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.
mcp-sqlserver
A powerful read-only Model Context Protocol (MCP) server for Microsoft SQL Server. Connects AI assistants (Claude, Gemini, Kiro, OpenAI, Copilot, Cursor) directly to your SQL Server databases with enterprise-grade security controls and zero data mutation risk.
35 tools across 6 categories: schema discovery, query execution, stored procedures, performance/DBA diagnostics, developer utilities, and server management.
Built on top of existing work: This project is built upon @tugberkgunver/mcp-sqlserver.
What makes this repository different:
Strict Read-Only Enforcement: All state-modifying tools (
execute_mutation,execute_ddl,execute_procedure,rebuild_index) have been removed from the server, guaranteeing zero risk of altering database tables, schemas, or data.Safe Production & Analytical Access: Specifically designed for secure database inspection, schema discovery, DBA diagnostics, code generation, and reporting without requiring elevated write or admin execution privileges.
Streamlined 35-Tool Suite: Focused toolset optimized for read queries, performance DMVs, ER diagram generation, schema comparisons, and test data script generation.
Changelog: See CHANGELOG.md for version history or GitHub Releases for detailed release notes.
What's New in v1.3
Multi-server support — Define dev/staging/prod servers in one config, switch with
serverparameterlist_serverstool — See all configured connections at a glancePer-server security — Each server gets its own security mode, row limits, and blocked databases
Backward compatible — Existing single-server configs work without any changes
Related MCP server: MSSQL Database MCP Server
What's New in v1.2
Read-only tools expansion — DBA diagnostics, code generation, ER diagrams, schema diff, data sampling, and export
SQL injection protection — All queries now use parameterized inputs and escaped identifiers
ISO date formatting — Dates display as
2025-01-27instead of raw JavaScript Date stringsStreamable HTTP transport — Host the MCP server remotely with
--http <port>Health check — Verify connection status and server responsiveness
Features
Server Management (1 tool)
Tool | Description / Purpose & Usage |
| Purpose: List all configured SQL Server connection instances and metadata (host, port, default database, auth type, security mode, max rows).Usage: Inspect available target environments (e.g., dev, staging, prod) before executing queries. |
Multi-server: Every tool accepts an optional
serverparameter to target a specific named server. Omit it to use the default server.
Schema Discovery (9 tools)
Tool | Description / Purpose & Usage |
| Purpose: Enumerate all accessible databases on the SQL Server instance.Usage: Discover database targets available on the server instance. Filtered by security allow/block lists. |
| Purpose: List all schemas (e.g. |
| Purpose: List tables along with row counts and total storage space in MB.Usage: Discover primary entities and volume sizes. Filter by schema to locate target tables. |
| Purpose: List all database views with creation and modification dates.Usage: Discover virtual tables and pre-aggregated views without scanning raw underlying tables. |
| Purpose: Retrieve full column schema (types, max length, precision, scale, nullability, identity, computed definitions, and default constraints).Usage: Inspect table column definitions to construct accurate SELECT queries and inspect data types. |
| Purpose: Retrieve foreign key relationships, referenced columns, and delete/update cascade rules.Usage: Inspect parent/child table relationships and foreign key constraints to build correct JOIN queries. |
| Purpose: List index metadata (clustered/nonclustered, uniqueness, primary keys, key columns, and included columns).Usage: Evaluate table indexing strategies and optimize WHERE/JOIN query execution paths. |
| Purpose: Retrieve PK, Unique, Check, Default, and Foreign Key constraints.Usage: Audit data validation rules, key constraints, and default column values defined on tables. |
| Purpose: Retrieve trigger definitions (INSTEAD OF / AFTER, event types, status, and full T-SQL code).Usage: Inspect automated database logic, audit tracking, and trigger side-effects safely. |
Query Execution (2 tools)
Tool | Description / Purpose & Usage |
| Purpose: Safely execute read-only SQL queries ( |
| Purpose: Execute a SELECT query and format output results as structured CSV or JSON.Usage: Export datasets for downstream reporting, analysis, or data pipeline consumption. |
Note: All write/mutation operations (
INSERT,UPDATE,DELETE,MERGE, DDL) have been removed.execute_querystrictly enforces read-onlySELECT/WITHstatements.
Stored Procedures (2 tools)
Tool | Description / Purpose & Usage |
| Purpose: List stored procedures in a database with creation and modification timestamps.Usage: Discover available stored procedures across database schemas. |
| Purpose: Retrieve parameter metadata (types, length, precision, direction, defaults) and full T-SQL source code of a stored procedure.Usage: Analyze stored procedure logic, parameters, and underlying query logic without risk of execution. |
Note: Stored procedure execution (
execute_procedure) has been removed to guarantee zero side-effects or state modifications.
Performance & DBA (15 tools)
Tool | Description / Purpose & Usage |
| Purpose: Retrieve estimated execution plan XML/text for a SELECT query using |
| Purpose: Monitor currently running requests on the server from |
| Purpose: Retrieve table storage statistics including row count, total/used/unused size in MB, and index fragmentation percentage.Usage: Evaluate table growth, storage allocation, and index fragmentation levels. |
| Purpose: Query |
| Purpose: Query |
| Purpose: Retrieve SQL Server instance diagnostics: version, edition, OS platform, CPU count, memory allocation, collation, and uptime.Usage: Inspect server environment specs and uptime diagnostics. |
| Purpose: Retrieve detailed database configuration: data/log file size (MB), status, recovery model, compatibility level, and object counts.Usage: Monitor database file allocation, recovery settings, and object counts. |
| Purpose: Retrieve top server wait statistics from |
| Purpose: Retrieve recent deadlock reports from the |
| Purpose: Show current active session blocking hierarchies.Usage: Identify blocked session IDs, blocking lead session IDs, wait times, blocked query text, and lead blocker query text. |
| Purpose: Show open transactions running longer than 5 seconds from |
| Purpose: Summarize top tables in a database by disk space usage (data MB, index MB, unused MB).Usage: Identify largest tables and manage storage capacity. |
| Purpose: Retrieve recent database backup history from |
| Purpose: Query Query Store DMVs (SQL Server 2016+) for top resource-consuming queries.Usage: Analyze historical query performance over the past 7 days ranked by CPU, duration, reads, writes, or executions. |
| Purpose: Perform a fast connection health check.Usage: Returns status (OK/FAILED), latency in ms, active user session count, server time, batch requests/sec, and product version. |
Note: Index rebuild (
rebuild_index) has been removed as it is a mutating DBA operation.
Developer Utilities (6 tools)
compare_schemas — Schema Diff
Compare two databases side-by-side. Shows tables, columns, and type differences — perfect for dev vs prod comparison.
Purpose: Detect structural differences between two databases without modifying either database.
Usage:
compare_schemas(source_database: "DevDB", target_database: "ProdDB", schema: "dbo")Output: Tables only in source/target, columns only in source/target, and column type/nullability differences.
generate_code — Code Generation
Generate typed code models or standard DDL from any table's schema:
Purpose: Instantly convert database table schemas into strongly typed application code models or DDL scripts.
Usage:
generate_code(table: "Products", language: "typescript")
generate_code(table: "Orders", language: "csharp")
generate_code(table: "Customers", language: "sql")Supported Languages:
TypeScript — interfaces with proper types (
number,string,Date,Buffer | null)C# — classes with nullable value types (
int?,DateTime?,decimal?)SQL —
CREATE TABLEscripts with full column definitions
generate_insert_scripts — Data Export as INSERT
Generate INSERT statements from existing table data — useful for migration scripts, seed data, or backing up small reference tables.
Purpose: Export existing table rows as executable SQL
INSERTstatements with parameterized value formatting.Usage:
generate_insert_scripts(table: "Categories", top: 10)Output: Formatted T-SQL script containing
INSERT INTO [schema].[table] (...) VALUES (...);statements.
generate_er_diagram — ER Diagram
Generate a Mermaid ER diagram from foreign key relationships. Paste the output into any Mermaid-compatible renderer (GitHub, Notion, VS Code, etc.).
Purpose: Visualize entity-relationship models and database structural diagrams directly from foreign key definitions.
Usage:
generate_er_diagram(database: "Northwind", schema: "dbo")Output:
generate_er_diagram(database: "Northwind")
→ erDiagram
Products }o--|| Categories : "CategoryID"
Products }o--|| Suppliers : "SupplierID"
Orders }o--|| Customers : "CustomerID"
...generate_test_data — Test Data Generation
Generate realistic INSERT statements with fake data based on column names and types. Smart heuristics for common patterns (email, phone, name, city, price, etc.).
Purpose: Create realistic T-SQL
INSERTtest data scripts for local development and mock testing.Usage:
generate_test_data(table: "Customers", count: 5)Output:
INSERT INTO [dbo].[Customers] (...) VALUES (N'Alice', N'user1@example.com', N'New York', ...);
sample_table — Random Sampling
Get a random sample of rows from any table using NEWID() — useful for AI assistants to understand data patterns without scanning entire tables.
Purpose: Fetch a representative random sample of table rows to understand data formats and values without table scans.
Usage:
sample_table(table: "Orders", count: 5)Security
Read-Only Architecture
This MCP server is built strictly for read-only database access. All state-modifying tools (execute_mutation, execute_ddl, execute_procedure, rebuild_index) have been removed from the server. AI assistants can safely discover schemas, query data, run DBA diagnostics, and generate code with zero risk of mutating database data or structures.
SQL Injection Protection
All user-provided values are passed as parameterized query inputs (@param). Object identifiers (database, schema, table names) are escaped using SQL Server bracket notation ([name] with ] → ]]).
Additional Security Features
Database and schema allow/block lists (
allowedDatabases,blockedDatabases,allowedSchemas,blockedSchemas)Automatic row count limits (configurable
maxRowCount, default1000)Blocked keyword detection (
xp_cmdshell,SHUTDOWN,DROP DATABASE,RECONFIGURE,sp_configure)Column-level data masking for PII protection
Strict
SELECT/WITHquery type validation
Data Masking
Mask sensitive columns in query results:
security:
maskColumns:
- pattern: "*.password"
mask: "***"
- pattern: "*.ssn"
mask: "XXX-XX-XXXX"
- pattern: "dbo.users.email"
mask: "***@***.***"Pattern format: [schema.]table.column (use * as wildcard)
Authentication
Method | Config | Requirements |
SQL Server |
|
|
Windows (NTLM) |
|
|
Windows (SSPI) |
| No credentials needed; requires |
Azure AD |
|
|
Windows Authentication
NTLM — Works out of the box, no extra packages:
connection:
host: YOUR_SERVER\SQLEXPRESS
authentication:
type: windows
user: YourUsername
password: YourPassword
domain: YOUR_DOMAIN
trustServerCertificate: trueSSPI / Integrated Security — Uses current Windows login session:
npm install msnodesqlv8connection:
host: YOUR_SERVER\SQLEXPRESS
authentication:
type: windows
trustServerCertificate: trueNote: When using
npx, optional dependencies likemsnodesqlv8may not be installed automatically. For SSPI, consider installing globally (npm install -g @tugberkgunver/mcp-sqlserver msnodesqlv8) or use NTLM mode instead.
Transport
stdio (Default)
Standard input/output transport — used by MCP clients like Claude Desktop, VS Code, Cursor, etc.
Streamable HTTP
For remote hosting or web integrations:
mcp-sqlserver --config mssql-mcp.yaml --http 3000This starts:
MCP endpoint:
http://localhost:3000/mcpHealth check:
http://localhost:3000/health→{"status":"ok","mode":"readonly"}
Includes CORS support for browser-based clients.
Quick Start
Install
npm install -g @tugberkgunver/mcp-sqlserverConfigure
Create mssql-mcp.yaml in your working directory:
connection:
host: localhost
port: 1433
database: MyDatabase
authentication:
type: sql
user: sa
password: YourPassword123
trustServerCertificate: true
security:
mode: readonly
maxRowCount: 1000
blockedDatabases:
- master
- msdb
- tempdb
- modelSee config.example.yaml for all options.
Multi-Server Configuration
Define multiple named servers to manage dev/staging/prod from a single config:
defaultServer: dev
connections:
dev:
host: dev-server.example.com
database: MyDatabase
authentication:
type: sql
user: sa
password: DevPass123
trustServerCertificate: true
security:
mode: readonly
maxRowCount: 5000
prod:
host: prod-server.example.com
database: MyDatabase
authentication:
type: sql
user: readonly_user
password: ProdReadOnly
security:
mode: readonly
blockedDatabases: [master, msdb, tempdb, model]
# Global security defaults (applied to all servers unless overridden)
security:
maxRowCount: 1000
blockedKeywords: [xp_cmdshell, SHUTDOWN, DROP DATABASE]Then use the server parameter in any tool call:
list_tables(server: "prod", database: "MyDatabase")
health_check(server: "dev")
compare_schemas(source_database: "DevDB", target_database: "StagingDB", server: "dev")MCP Client Configuration
{
"mcpServers": {
"mssql": {
"command": "npx",
"args": ["-y", "@tugberkgunver/mcp-sqlserver"],
"env": {
"MSSQL_HOST": "localhost",
"MSSQL_DATABASE": "MyDatabase",
"MSSQL_USER": "sa",
"MSSQL_PASSWORD": "YourPassword123"
}
}
}
}With a config file:
{
"mcpServers": {
"mssql": {
"command": "npx",
"args": ["-y", "@tugberkgunver/mcp-sqlserver", "--config", "/path/to/mssql-mcp.yaml"]
}
}
}Add to .vscode/mcp.json:
{
"servers": {
"mssql": {
"command": "npx",
"args": ["-y", "@tugberkgunver/mcp-sqlserver"],
"env": {
"MSSQL_HOST": "localhost",
"MSSQL_DATABASE": "MyDatabase",
"MSSQL_USER": "sa",
"MSSQL_PASSWORD": "YourPassword123"
}
}
}
}Add to ~/.cursor/mcp.json:
{
"mcpServers": {
"mssql": {
"command": "npx",
"args": ["-y", "@tugberkgunver/mcp-sqlserver"],
"env": {
"MSSQL_HOST": "localhost",
"MSSQL_DATABASE": "MyDatabase",
"MSSQL_USER": "sa",
"MSSQL_PASSWORD": "YourPassword123"
}
}
}
}Add to .kiro/settings/mcp.json:
{
"mcpServers": {
"mssql": {
"command": "npx",
"args": ["-y", "@tugberkgunver/mcp-sqlserver"],
"env": {
"MSSQL_HOST": "localhost",
"MSSQL_DATABASE": "MyDatabase",
"MSSQL_USER": "sa",
"MSSQL_PASSWORD": "YourPassword123"
}
}
}
}Add to ~/.gemini/settings.json:
{
"mcpServers": {
"mssql": {
"command": "npx",
"args": ["-y", "@tugberkgunver/mcp-sqlserver"],
"env": {
"MSSQL_HOST": "localhost",
"MSSQL_DATABASE": "MyDatabase",
"MSSQL_USER": "sa",
"MSSQL_PASSWORD": "YourPassword123"
}
}
}
}{
"mcpServers": {
"mssql": {
"command": "npx",
"args": ["-y", "@tugberkgunver/mcp-sqlserver"],
"env": {
"MSSQL_HOST": "localhost",
"MSSQL_DATABASE": "MyDatabase",
"MSSQL_USER": "sa",
"MSSQL_PASSWORD": "YourPassword123"
}
}
}
}Add to ~/.windsurf/mcp.json:
{
"mcpServers": {
"mssql": {
"command": "npx",
"args": ["-y", "@tugberkgunver/mcp-sqlserver"],
"env": {
"MSSQL_HOST": "localhost",
"MSSQL_DATABASE": "MyDatabase",
"MSSQL_USER": "sa",
"MSSQL_PASSWORD": "YourPassword123"
}
}
}
}On Windows, use cmd as the command wrapper:
{
"mcpServers": {
"mssql": {
"command": "cmd",
"args": ["/c", "npx", "-y", "@tugberkgunver/mcp-sqlserver", "--config", "path/to/config.yaml"]
}
}
}Environment Variables
Variable | Description |
| SQL Server hostname |
| SQL Server port (default: 1433) |
| Default database |
| SQL auth username |
| SQL auth password |
| Path to YAML config file |
Environment variables override config file values.
Development
git clone https://github.com/gunvertugberk/mcp-sqlserver.git
cd mcp-sqlserver
npm install
npm run build
npm start -- --config ./mssql-mcp.yamlLicense
MIT
Available Tools
35 toolscompare_schemasB
Compare schemas between two databases — shows tables, columns, and indexes that differ (useful for dev vs prod comparison)
Inputs: source_database (required), target_database (required), schema, server.
describe_procedureA
Get parameter information and source code for a stored procedure
Inputs: procedure (required), schema, server, database.
describe_tableA
Get detailed column information for a table or view (columns, types, defaults, nullability, identity, computed)
Inputs: table (required), schema, server, database.
execute_queryB
Execute a read-only SQL query (SELECT). Automatically applies row limits from configuration.
Inputs: sql (required), server, database.
export_queryB
Execute a SELECT query and return results as CSV or JSON format
Inputs: sql (required), format (required), server, database.
generate_codeB
Generate TypeScript interface, C# class, or CREATE TABLE script from a table's schema
Inputs: table (required), language (required), schema, server, +1 more.
generate_er_diagramB
Generate a Mermaid ER diagram from database foreign key relationships
Inputs: schema, server, database.
generate_insert_scriptsA
Generate INSERT statements from existing table data (for migration/seeding)
Inputs: table (required), top, schema, server, +1 more.
generate_test_dataB
Generate INSERT statements with realistic fake/test data based on table schema
Inputs: table (required), count, schema, server, +1 more.
get_active_queriesB
Show currently running queries on the server (from sys.dm_exec_requests)
Inputs: server.
get_backup_historyB
Get recent backup history for a database from msdb
Inputs: top, server, database.
get_blocking_chainsB
Show current blocking chains — which sessions are blocking others
Inputs: server.
get_constraintsB
Get constraints (PK, unique, check, default) for a table
Inputs: table (required), schema, server, database.
get_database_infoC
Get detailed database information: size, files, status, recovery model
Inputs: server, database.
get_deadlocksA
Get recent deadlock events from the system_health Extended Events session
Inputs: server.
get_foreign_keysC
Get foreign key relationships for a table
Inputs: table (required), schema, server, database.
get_indexesC
Get index information for a table
Inputs: table (required), schema, server, database.
get_index_usageC
Get index usage statistics: seeks, scans, lookups, and updates (from sys.dm_db_index_usage_stats)
Inputs: table (required), schema, server, database.
get_long_transactionsB
Show long-running open transactions that may be holding locks
Inputs: server.
get_missing_indexesC
Get missing index suggestions from SQL Server DMVs (sys.dm_db_missing_index_details)
Inputs: server, database.
get_query_planA
Get the estimated execution plan for a SQL query (without executing it)
Inputs: sql (required), server, database.
get_query_store_statsA
Get top resource-consuming queries from Query Store (SQL Server 2016+). Query Store must be enabled on the database.
Inputs: top, server, sort_by, database.
get_server_infoA
Get SQL Server instance information: version, edition, OS, memory, CPU
Inputs: server.
get_space_usageC
Get detailed disk space usage by table in a database
Inputs: top, server, database.
get_table_statsB
Get table statistics: row count, total size, index size, and fragmentation
Inputs: table (required), schema, server, database.
get_triggersB
Get triggers defined on a table
Inputs: table (required), schema, server, database.
get_wait_statsB
Get top server wait statistics — identifies performance bottlenecks (CPU, I/O, locks, etc.)
Inputs: top, server.
health_checkC
Check SQL Server connection health and basic responsiveness
Inputs: server.
list_databasesA
List all accessible databases on the SQL Server instance
Inputs: server.
list_proceduresA
List all stored procedures in a database, optionally filtered by schema
Inputs: schema, server, database.
list_schemasA
List all schemas in the current database
Inputs: server, database.
list_serversA
List all configured SQL Server connections and their details (host, database, auth type, security mode)
Inputs: no named parameters.
list_tablesA
List all tables in a database, optionally filtered by schema
Inputs: schema, server, database.
list_viewsA
List all views in a database, optionally filtered by schema
Inputs: schema, server, database.
sample_tableA
Get a random sample of rows from a table (useful for understanding data patterns)
Inputs: table (required), count, schema, server, +1 more.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 35 tools
Most tools target a distinct resource/action (e.g., list_tables vs describe_table vs get_indexes), and performance monitoring tools are separated by clear DMV-based descriptions. However, execute_query, export_query, and sample_table all execute or return query results, so an agent could sometimes confuse which one to use.
All tool names follow a consistent verb_noun snake_case pattern, such as list_tables, get_indexes, describe_procedure, and compare_schemas. There is no mixing of naming conventions or vague generic verbs.
With 35 tools, the surface is well beyond the typical well-scoped range and falls into the 25+ too-many category. While tools cover distinct areas, several could be consolidated or grouped into parameterized tools to reduce cognitive load.
The toolkit provides broad read-only coverage of SQL Server metadata, querying, schema generation, and performance monitoring, with no major dead ends for that scope. Missing write/DDL tools and user/permission introspection are notable but appear outside this server's read-only intent.
Related MCP Connectors
Query Postgres, MySQL, SQL Server, Oracle, BigQuery, ClickHouse and Redshift from your AI client.
Draxlr's remote MCP server connects AI assistants to your SQL databases and dashboards. Explore schemas, run read-only queries, manage saved queries and dashboards, and export results, all with row-level security so each user sees only their own data.
PostgreSQL, MySQL, and SQL Server in one session. 26 read-only MCP tools for AI agents.
Work with your database from AI tools: ask, export, approved changes, and scheduled jobs.
Related MCP Servers
- AlicenseAqualityDmaintenanceEnables AI assistants to interact with Microsoft SQL Server databases through query execution, schema discovery, CRUD operations, stored procedures, and data export with built-in safety controls.18Apache 2.0
- AlicenseNot gradedqualityDmaintenanceEnables AI assistants to securely interact with Microsoft SQL Server databases to query data, inspect schemas, and retrieve metadata with read-only operations by default and optional write capabilities.1MIT
- AlicenseNot gradedqualityDmaintenanceEnables AI assistants to interact with Microsoft SQL Server databases through a standardized interface. Supports executing SQL queries, browsing database schemas, and viewing table data with flexible authentication options for both local and Azure SQL databases.5MIT
- FlicenseCqualityDmaintenanceEnables AI assistants to analyze and query SQL Server databases, including schema discovery, health checks, and data retrieval.10-