SQL Server MCP
Allows GitHub Copilot to explore database schemas and execute read-only queries on SQL Server databases.
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., "@SQL Server MCP describe the Orders table in the Sales 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.
SQL Server MCP
An MCP (Model Context Protocol) server that connects AI assistants to Microsoft SQL Server databases. Enables AI tools like GitHub Copilot, Cursor, Cline, Claude Desktop, and Claude Code to explore database schemas and execute read-only queries safely.
Features
29 built-in tools for comprehensive database analysis and management
Read-only by design — uses
db_datareaderrole, blocks all destructive SQLSQL injection protection — AST-based query validation + keyword blocklist
Automatic row limits — prevents memory overflow with smart
TOP NinjectionAI-friendly errors — structured error responses with actionable suggestions
Schema caching — 1-hour TTL metadata cache reduces redundant DB calls
Unicode/Vietnamese support — full NVARCHAR UTF-8 passthrough
Dual transport —
stdio(default) for local AI tools,HTTP/SSEfor web clientsData analysis — table statistics, index information, and column distribution
Data export — export table data to JSON or CSV format
Complete schema understanding — views, constraints, stored procedures, and server info
Security auditing — user management and permission analysis
Enhanced profiling — detailed column distribution with pattern recognition
Dependency mapping — full dependency analysis for tables and columns
Schema management — comprehensive schema organization and analysis
Data quality validation — integrity checks and comprehensive profiling
Documentation automation — generate schema documentation and ER diagrams
Related MCP server: DBMCP
Available Tools
Database & Schema (3 tools)
Tool | Description |
| List all user-accessible databases on the SQL Server instance |
| List all schemas in database with table and view counts |
| List tables and views in a specific schema |
Schema Exploration (5 tools)
Tool | Description |
| Get column details: name, type, nullable, PK, description |
| Get foreign key mappings for a table (guides JOINs) |
| Search tables/columns/descriptions by keyword |
| Get SQL definition of a view along with referenced tables |
| List all constraints (PK, FK, Unique, Check) for a table |
Data Analysis (6 tools)
Tool | Description |
| Get table statistics including row count, size, and timestamps |
| Get all indexes for a table with column details |
| Analyze table data to get distribution statistics for each column |
| Get detailed distribution statistics for a specific column with pattern recognition |
| List all stored procedures and functions with parameters |
| Get full SQL definition of a stored procedure or function |
Dependencies & Usage (2 tools)
Tool | Description |
| Get full dependency map for a table (what it depends on and what depends on it) |
| Get detailed usage information for a specific column (views, procedures, foreign keys, indexes) |
Data Quality (2 tools)
Tool | Description |
| Validate data integrity for a table (FK violations, duplicates, null violations) |
| Get comprehensive data profile for a table including quality metrics |
Documentation (3 tools)
Tool | Description |
| Generate comprehensive schema documentation with tables, views, columns, and relationships |
| Create entity relationship diagram in Mermaid, PlantUML, or DOT format |
| Generate REST API documentation from database schema with inferred endpoints and schemas |
Migration & Comparison (2 tools)
Tool | Description |
| Generate migration scripts for schema changes with up/down migrations |
| Compare two schemas to identify differences in tables, views, and procedures |
Server & System (1 tool)
Tool | Description |
| Get SQL Server information including version, edition, and status |
Security & Users (2 tools)
Tool | Description |
| List all database users and their roles |
| Get detailed permissions for a specific user |
Data Export & Query (3 tools)
Tool | Description |
| Execute a validated read-only SELECT query |
| Export table data to JSON or CSV format |
| Clear the metadata cache to force fresh data |
Quick Start
1. Install
git clone https://github.com/az-coder-123/sql-server-mcp.git
cd sql-server-mcp
npm install
npm run build2. Configure
Copy the environment template and fill in your SQL Server credentials:
cp .env.example .envEdit .env:
DB_HOST=localhost
DB_PORT=1433
DB_NAME=MyDatabase
DB_USER=readonly_user
DB_PASSWORD=your_password
DB_ENCRYPT=true
DB_TRUST_SERVER_CERT=falseImportant: The
DB_USERshould have thedb_datareaderrole only. The server blocks all write operations at the code level, but defense-in-depth at the database level is strongly recommended.
3. Run
# stdio mode (default — for AI tools)
npm start
# Development mode (with hot reload)
npm run dev
# HTTP/SSE mode (for web clients)
MCP_TRANSPORT=http npm startIntegration with AI Tools
GitHub Copilot (VS Code)
Create .vscode/mcp.json in your project:
{
"servers": {
"sql-server-mcp": {
"type": "stdio",
"command": "node",
"args": ["/path/to/sql-server-mcp/dist/index.js"],
"env": {
"DB_SERVER": "localhost",
"DB_DATABASE": "MyDatabase",
"DB_USER": "readonly_user",
"DB_PASSWORD": "${input:dbPassword}"
}
}
}
}VS Code will securely prompt for the password at runtime via
${input:dbPassword}.
Cursor
Create .cursor/mcp.json:
{
"mcpServers": {
"sql-server-mcp": {
"command": "node",
"args": ["/path/to/sql-server-mcp/dist/index.js"],
"env": {
"DB_SERVER": "localhost",
"DB_DATABASE": "MyDatabase",
"DB_USER": "readonly_user",
"DB_PASSWORD": "your_password"
}
}
}
}Cline (VS Code Extension)
Open Cline settings in VS Code
Go to MCP Servers → Add Server
Select Command (stdio)
Enter:
Command:
nodeArgs:
/path/to/sql-server-mcp/dist/index.jsEnv:
DB_SERVER=localhost,DB_DATABASE=MyDatabase,DB_USER=readonly_user,DB_PASSWORD=your_password
Claude Desktop
Add to ~/Library/Application Support/Claude/claude_desktop_config.json (macOS) or %AppData%\Claude\claude_desktop_config.json (Windows):
{
"mcpServers": {
"sql-server-mcp": {
"command": "node",
"args": ["/path/to/sql-server-mcp/dist/index.js"],
"env": {
"DB_SERVER": "localhost",
"DB_DATABASE": "MyDatabase",
"DB_USER": "readonly_user",
"DB_PASSWORD": "your_password"
}
}
}
}Claude Code (CLI)
claude --mcp-config ./mcp-config.json "Show me all tables in database"Where mcp-config.json uses the same mcpServers format as Claude Desktop above.
Configuration Reference
All settings are configured via environment variables (or .env file):
Variable | Default | Description |
|
| SQL Server hostname or IP |
|
| SQL Server port |
|
| Default database |
| — | SQL Server login username |
| — | SQL Server login password |
|
| Enable TLS encryption |
|
| Trust self-signed certificates |
|
| Transport mode: |
|
| HTTP server port (when |
|
| Max rows returned per query (auto-injected) |
|
| Query timeout in milliseconds |
|
| Max response payload size (1MB) |
|
| How long schema metadata is cached |
Security
This server is designed for read-only database access with multiple layers of protection:
Database-level: Uses a
db_datareader-only account withreadOnlyIntentconnection flagQuery validation: AST-based parsing via
node-sql-parser(with regex fallback for T-SQL edge cases)Keyword blocklist:
INSERT,UPDATE,DELETE,DROP,EXEC,TRUNCATE,ALTER,CREATE,GRANT,REVOKE,MERGEand moreMulti-statement blocking: Semicolons outside string literals are rejected
Row limiting: Automatic
TOP Ninjection prevents memory exhaustionPayload truncation: Responses exceeding 1MB are truncated with a warning
Connection timeout: 30-second hard timeout on all queries
Project Structure
sql-server-mcp/
├── src/
│ ├── index.ts # Server entry point, tool registration, transport
│ ├── config/database.ts # Connection pool, env vars
│ ├── tools/
│ │ ├── schemaTools.ts # list_databases, list_tables, describe_table, relationships, search
│ │ ├── schemaManagementTools.ts # list_schemas
│ │ ├── queryTools.ts # execute_read_query
│ │ ├── tableStatisticsTools.ts # get_table_statistics
│ │ ├── tableIndexTools.ts # get_table_indexes
│ │ ├── tableAnalysisTools.ts # analyze_table
│ │ ├── columnTools.ts # get_column_distribution
│ │ ├── storedProcedureTools.ts # list_stored_procedures
│ │ ├── exportTools.ts # export_table_data
│ │ ├── viewTools.ts # get_view_definition
│ │ ├── constraintTools.ts # list_constraints
│ │ ├── serverInfoTools.ts # get_server_info
│ │ ├── procedureDefinitionTools.ts # get_procedure_definition
│ │ ├── userTools.ts # list_users, get_user_permissions
│ │ ├── dependencyTools.ts # get_table_dependencies
│ │ ├── usageTools.ts # get_column_usage
│ │ ├── dataIntegrityTools.ts # validate_data_integrity
│ │ ├── dataProfileTools.ts # get_data_profile
│ │ ├── documentationTools.ts # generate_schema_documentation
│ │ ├── apiDocumentationTools.ts # generate_api_documentation
│ │ ├── migrationTools.ts # create_migration_scripts
│ │ ├── schemaComparisonTools.ts # compare_schemas
│ │ └── diagramTools.ts # create_entity_relationship_diagram
│ ├── types/index.ts # Shared TypeScript interfaces
│ ├── utils/
│ │ ├── sqlValidator.ts # AST + regex query validation, TOP injection
│ │ └── errorMapper.ts # SQL error code → AI-friendly messages
│ └── cache/schemaCache.ts # In-memory TTL cache
├── tests/ # Unit tests (vitest)
├── dist/ # Compiled output (npm run build)
├── .env.example # Environment variable template
└── package.jsonDevelopment
# Install dependencies
npm install
# Run in dev mode (hot reload)
npm run dev
# Run tests
npm test
# Build for production
npm run buildLicense
ISC
Available Tools
49 toolsanalyze_normalization_levelB
Analyze normalization level of tables using heuristic approach (1NF, 2NF, 3NF detection)
Inputs: schema, tableName.
analyze_query_performanceB
Analyze query performance using execution statistics DMVs to find slow queries and bottlenecks
Inputs: topN, schema.
analyze_schema_change_impactB
Analyze impact of schema changes by finding all dependent objects
Inputs: tableName (required), schema.
analyze_tableC
Analyze table data to get distribution statistics for each column
Inputs: tableName (required), schema.
audit_user_permissionsC
Audit user permissions for security analysis and compliance
Inputs: userName.
backup_databaseB
Backup a SQL Server database to a .bak file with optional compression
Inputs: backupPath (required), databaseName (required), backupType, description.
check_database_connectionsA
Check active connections to a database (useful before restore)
Inputs: databaseName.
clear_cacheA
Clear the schema metadata cache to force fresh data from the database
Inputs: no named parameters.
compare_schemasA
Compare two schemas to identify differences in tables, views, and procedures
Inputs: sourceSchema, targetSchema, targetDatabase.
create_databaseA
Create a new SQL Server database with specified options
Inputs: databaseName (required), collation, maxSizeMB, fileGrowthMB, +1 more.
create_entity_relationship_diagramA
Create entity relationship diagram in Mermaid, PlantUML, or DOT format
Inputs: schema (required), format, includeViews.
create_migration_scriptsB
Generate migration scripts for schema changes with up/down migrations
Inputs: changes (required), schema.
describe_tableA
Get column details (name, type, PK, description) for a table
Inputs: tableName (required), schema.
detect_circular_dependenciesA
Detect circular dependencies in foreign key relationships
Inputs: schema.
disconnect_database_usersA
Disconnect all users from a database by setting access mode (useful before restore)
Inputs: databaseName (required), mode, rollbackImmediate.
execute_read_queryA
Execute a read-only SQL SELECT query (automatically validated and row-limited)
Inputs: sqlQuery (required).
export_table_dataB
Export table data to JSON or CSV format
Inputs: format (required), tableName (required), limit, schema, +1 more.
find_unused_stored_proceduresA
Find stored procedures that are not executed recently or never executed
Inputs: schema, unusedDays.
generate_api_documentationB
Generate REST API documentation from database schema with inferred endpoints and schemas
Inputs: schema, baseUrl, includeProcedures.
generate_schema_documentationB
Generate comprehensive schema documentation with tables, views, columns, and relationships
Inputs: schema, includeViews.
get_backup_file_listB
Get the list of data and log files contained in a backup file
Inputs: backupPath (required).
get_backup_headerA
Get backup metadata and header information from a .bak file
Inputs: backupPath (required).
get_column_distributionC
Get detailed distribution statistics for a specific column
Inputs: tableName (required), columnName (required), topN, schema, +1 more.
get_column_usageA
Get detailed usage information for a specific column (views, procedures, foreign keys, indexes)
Inputs: tableName (required), columnName (required), schema.
get_database_summaryB
Get comprehensive summary of a database including statistics, size, schemas, and last backup
Inputs: databaseName (required).
get_data_profileB
Get comprehensive data profile for a table including quality metrics
Inputs: tableName (required), schema, sampleSize.
get_procedure_definitionA
Get the full SQL definition of a stored procedure or function
Inputs: procedureName (required), schema.
get_server_infoA
Get SQL Server information including version, edition, and status
Inputs: no named parameters.
get_table_dependenciesB
Get full dependency map for a table (what it depends on and what depends on it)
Inputs: tableName (required), schema.
get_table_indexesB
Get all indexes for a table with column details
Inputs: tableName (required), schema.
get_table_relationshipsA
Get foreign key relationships for a table (helps with JOINs)
Inputs: tableName (required), schema.
get_table_statisticsC
Get table statistics including row count, size, and timestamps
Inputs: tableName (required), schema.
get_user_permissionsC
Get detailed permissions for a specific user
Inputs: userName (required), objectType.
get_view_definitionA
Get the SQL definition of a view along with referenced tables
Inputs: viewName (required), schema.
kill_database_sessionsB
Kill specific sessions connected to a database
Inputs: databaseName (required), sessionIds.
list_backupsA
List recent backup history from msdb, optionally filtered by database name
Inputs: databaseName.
list_constraintsA
List all constraints (PK, FK, Unique, Check) for a table or all tables
Inputs: schema, tableName.
list_databasesA
List all user-accessible databases on SQL Server instance
Inputs: no named parameters.
list_schemasA
List all schemas in database with table and view counts
Inputs: no named parameters.
list_stored_proceduresA
List all stored procedures and functions with parameters
Inputs: schema.
list_tablesC
List all tables and views in a database schema
Inputs: schema.
list_tables_allA
List all tables across all databases or in a specific database
Inputs: databaseFilter.
list_triggersB
List all triggers in the database with details and dependencies
Inputs: schema.
list_usersA
List all database users and their roles
Inputs: no named parameters.
restore_databaseB
Restore a SQL Server database from a .bak file
Inputs: backupPath (required), databaseName (required), fileMoves, withReplace, +1 more.
search_across_databasesB
Search for tables, columns, or procedures across all databases by keyword
Inputs: keyword (required), searchIn.
search_tablesB
Search for tables/columns/descriptions matching a keyword
Inputs: keyword (required).
suggest_index_optimizationsB
Analyze and suggest index improvements including missing, unused, and fragmented indexes
Inputs: topN, schema.
validate_data_integrityB
Validate data integrity for a table (FK violations, duplicates, null violations)
Inputs: tableName (required), schema, checkFK, checkNulls, +1 more.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 49 tools
Many tools have specific purposes, but there is overlap in analysis tools like analyze_table, get_column_distribution, and get_data_profile that could be confused. Similarly, list_tables and list_tables_all differ only in scope. Descriptions help clarify, but the large tool count creates ambiguity.
Tools consistently follow a snake_case verb_noun pattern (e.g., describe_table, list_tables, backup_database). Minor deviations include the 'all' suffix in list_tables_all and some verbs like 'check' vs 'disconnect' for similar operations, but overall the convention is consistent and readable.
With 49 tools, the server is over the typical threshold for a well-scoped MCP server. While the SQL Server domain is broad, many tools could be consolidated (e.g., multiple analysis and statistics tools). This heavy count may overwhelm agents and increase selection errors.
The server covers a wide range of operations including schema exploration, querying, performance analysis, documentation generation, and backup/restore. However, it lacks tools for DDL/DML operations (e.g., create table, update data) and provides no way to modify objects, limiting its usefulness for full database management.
Maintenance
Related MCP Connectors
Hosted SQL Server MCP server for Claude, ChatGPT and Cursor, with each action switched per account.
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.
Text-to-SQL MCP server: read-only queries on PostgreSQL, MySQL and SQL Server with your real schema
Cloud-hosted MCP server for secure AI access to enterprise data sources via CData Connect AI.
Related MCP Servers
- AlicenseBqualityDmaintenanceA powerful MCP server for Microsoft SQL Server that connects AI assistants directly to your SQL Server databases with enterprise-grade security controls.3840 npm3MIT
- AlicenseAqualityDmaintenanceMCP 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.91MIT
- AlicenseNot gradedqualityBmaintenanceAn MCP server that enables AI assistants to query and manage Microsoft SQL Server databases using natural language.117 npm5MIT
- AlicenseNot gradedqualityDmaintenanceCross-platform MCP server for SQL Server that enables AI assistants to explore schemas, relationships, and run read-only queries via natural language.1MIT