{"id":"09907fff-414b-46f1-8717-57bb52d69e77","slug":"sql-server-mcp","kind":"mcp","name":"sql-server-mcp","summary":"Model Context Protocol (MCP) server for MS SQL Server. Enables LLMs and AI agents (Cursor, Copilot, Claude) to safely explore schemas and execute read-only queries with advanced SQL injection protecti","owner":"az-coder-123","repoUrl":"https://github.com/az-coder-123/sql-server-mcp","license":"MIT","licenseTier":"permissive","trust":"community","stars":4,"match":null,"fewStars":true,"format":"mcp","createdAt":null,"addedAt":"2026-10-14T05:10:21.503Z","logoUrl":"https://avatars.githubusercontent.com/u/226820260?u=7d50c7c04a51a1e217413d07ae0ad531a92e9afd&v=4","linkOnly":false,"collection":null,"skillPath":null,"categories":["databases","cloud-infra","memory-knowledge"],"tags":["ai-agent","data-tools","llm","sql","sql-server"],"runtime":"node","local":true,"cloudCapable":false,"cloudCapability":"unknown","cloudReadyOnPlatform":false,"needsApiKey":false,"reviewed":false,"syncedAt":"2026-10-14T10:22:00.378Z","sample":false,"url":"https://conduits.dev/tools/sql-server-mcp","language":"TypeScript","transports":["stdio"],"install":{"npm":"sql-server-mcp"},"requirements":{"env":[],"upstreamMayCharge":false},"tools":null,"readme":"# SQL Server MCP\n\nAn 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.\n\n<div align=\"center\">\n\n![TypeScript](https://img.shields.io/badge/TypeScript-007ACC?logo=typescript&logoColor=white)\n![Node.js](https://img.shields.io/badge/Node.js-339933?logo=node.js&logoColor=white)\n![SQL Server](https://img.shields.io/badge/SQL%20Server-CC2927?logo=microsoftsqlserver&logoColor=white)\n![MCP](https://img.shields.io/badge/MCP-Protocol-blue)\n\n</div>\n\n---\n\n## Features\n\n- **29 built-in tools** for comprehensive database analysis and management\n- **Read-only by design** — uses `db_datareader` role, blocks all destructive SQL\n- **SQL injection protection** — AST-based query validation + keyword blocklist\n- **Automatic row limits** — prevents memory overflow with smart `TOP N` injection\n- **AI-friendly errors** — structured error responses with actionable suggestions\n- **Schema caching** — 1-hour TTL metadata cache reduces redundant DB calls\n- **Unicode/Vietnamese support** — full NVARCHAR UTF-8 passthrough\n- **Dual transport** — `stdio` (default) for local AI tools, `HTTP/SSE` for web clients\n- **Data analysis** — table statistics, index information, and column distribution\n- **Data export** — export table data to JSON or CSV format\n- **Complete schema understanding** — views, constraints, stored procedures, and server info\n- **Security auditing** — user management and permission analysis\n- **Enhanced profiling** — detailed column distribution with pattern recognition\n- **Dependency mapping** — full dependency analysis for tables and columns\n- **Schema management** — comprehensive schema organization and analysis\n- **Data quality validation** — integrity checks and comprehensive profiling\n- **Documentation automation** — generate schema documentation and ER diagrams\n\n---\n\n## Available Tools\n\n### Database & Schema (3 tools)\n| Tool | Description |\n|---|---|\n| `list_databases` | List all user-accessible databases on the SQL Server instance |\n| `list_schemas` | List all schemas in database with table and view counts |\n| `list_tables` | List tables and views in a specific schema |\n\n### Schema Exploration (5 tools)\n| Tool | Description |\n|---|---|\n| `describe_table` | Get column details: name, type, nullable, PK, description |\n| `get_table_relationships` | Get foreign key mappings for a table (guides JOINs) |\n| `search_tables` | Search tables/columns/descriptions by keyword |\n| `get_view_definition` | Get SQL definition of a view along with referenced tables |\n| `list_constraints` | List all constraints (PK, FK, Unique, Check) for a table |\n\n### Data Analysis (6 tools)\n| Tool | Description |\n|---|---|\n| `get_table_statistics` | Get table statistics including row count, size, and timestamps |\n| `get_table_indexes` | Get all indexes for a table with column details |\n| `analyze_table` | Analyze table data to get distribution statistics for each column |\n| `get_column_distribution` | Get detailed distribution statistics for a specific column with pattern recognition |\n| `list_stored_procedures` | List all stored procedures and functions with parameters |\n| `get_procedure_definition` | Get full SQL definition of a stored procedure or function |\n\n### Dependencies & Usage (2 tools)\n| Tool | Description |\n|---|---|\n| `get_table_dependencies` | Get full dependency map for a table (what it depends on and what depends on it) |\n| `get_column_usage` | Get detailed usage information for a specific column (views, procedures, foreign keys, indexes) |\n\n### Data Quality (2 tools)\n| Tool | Description |\n|---|---|\n| `validate_data_integrity` | Validate data integrity for a table (FK violations, duplicates, null violations) |\n| `get_data_profile` | Get comprehensive data profile for a table including quality metrics |\n\n### Documentation (3 tools)\n| Tool | Description |\n|---|---|\n| `generate_schema_documentation` | Generate comprehensive schema documentation with tables, views, columns, and relationships |\n| `create_entity_relationship_diagram` | Create entity relationship diagram in Mermaid, PlantUML, or DOT format |\n| `generate_api_documentation` | Generate REST API documentation from database schema with inferred endpoints and schemas |\n\n### Migration & Comparison (2 tools)\n| Tool | Description |\n|---|---|\n| `create_migration_scripts` | Generate migration scripts for schema changes with up/down migrations |\n| `compare_schemas` | Compare two schemas to identify differences in tables, views, and procedures |\n\n### Server & System (1 tool)\n| Tool | Description |\n|---|---|\n| `get_server_info` | Get SQL Server information including version, edition, and status |\n\n### Security & Users (2 tools)\n| Tool | Description |\n|---|---|\n| `list_users` | List all database users and their roles |\n| `get_user_permissions` | Get detailed permissions for a specific user |\n\n### Data Export & Query (3 tools)\n| Tool | Description |\n|---|---|\n| `execute_read_query` | Execute a validated read-only SELECT query |\n| `export_table_data` | Export table data to JSON or CSV format |\n| `clear_cache` | Clear the metadata cache to force fresh data |\n\n---\n\n## Quick Start\n\n### 1. Install\n\n```bash\ngit clone https://github.com/az-coder-123/sql-server-mcp.git\ncd sql-server-mcp\nnpm install\nnpm run build\n```\n\n### 2. Configure\n\nCopy the environment template and fill in your SQL Server credentials:\n\n```bash\ncp .env.example .env\n```\n\nEdit `.env`:\n\n```dotenv\nDB_HOST=localhost\nDB_PORT=1433\nDB_NAME=MyDatabase\nDB_USER=readonly_user\nDB_PASSWORD=your_password\nDB_ENCRYPT=true\nDB_TRUST_SERVER_CERT=false\n```\n\n> **Important:** The `DB_USER` should have the `db_datareader` role only. The server blocks all write operations at the code level, but defense-in-depth at the database level is strongly recommended.\n\n### 3. Run\n\n```bash\n# stdio mode (default — for AI tools)\nnpm start\n\n# Development mode (with hot reload)\nnpm run dev\n\n# HTTP/SSE mode (for web clients)\nMCP_TRANSPORT=http npm start\n```\n\n---\n\n## Integration with AI Tools\n\n### GitHub Copilot (VS Code)\n\nCreate `.vscode/mcp.json` in your project:\n\n```json\n{\n  \"servers\": {\n    \"sql-server-mcp\": {\n      \"type\": \"stdio\",\n      \"command\": \"node\",\n      \"args\": [\"/path/to/sql-server-mcp/dist/index.js\"],\n      \"env\": {\n        \"DB_SERVER\": \"localhost\",\n        \"DB_DATABASE\": \"MyDatabase\",\n        \"DB_USER\": \"readonly_user\",\n        \"DB_PASSWORD\": \"${input:dbPassword}\"\n      }\n    }\n  }\n}\n```\n\n> VS Code will securely prompt for the password at runtime via `${input:dbPassword}`.\n\n### Cursor\n\nCreate `.cursor/mcp.json`:\n\n```json\n{\n  \"mcpServers\": {\n    \"sql-server-mcp\": {\n      \"command\": \"node\",\n      \"args\": [\"/path/to/sql-server-mcp/dist/index.js\"],\n      \"env\": {\n        \"DB_SERVER\": \"localhost\",\n        \"DB_DATABASE\": \"MyDatabase\",\n        \"DB_USER\": \"readonly_user\",\n        \"DB_PASSWORD\": \"your_password\"\n      }\n    }\n  }\n}\n```\n\n### Cline (VS Code Extension)\n\n1. Open Cline settings in VS Code\n2. Go to **MCP Servers** → **Add Server**\n3. Select **Command (stdio)**\n4. Enter:\n   - **Command:** `node`\n   - **Args:** `/path/to/sql-server-mcp/dist/index.js`\n   - **Env:** `DB_SERVER=localhost`, `DB_DATABASE=MyDatabase`, `DB_USER=readonly_user`, `DB_PASSWORD=your_password`\n\n### Claude Desktop\n\nAdd to `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS) or `%AppData%\\Claude\\claude_desktop_config.json` (Windows):\n\n```json\n{\n  \"mcpServers\": {\n    \"sql-server-mcp\": {\n      \"command\": \"node\",\n      \"args\": [\"/path/to/sql-server-mcp/dist/index.js\"],\n      \"env\": {\n        \"DB_SERVER\": \"localhost\",\n        \"DB_DATABASE\": \"MyDatabase\",\n        \"DB_USER\": \"readonly_user\",\n        \"DB_PASSWORD\": \"your_password\"\n      }\n    }\n  }\n}\n```\n\n### Claude Code (CLI)\n\n```bash\nclaude --mcp-config ./mcp-config.json \"Show me all tables in database\"\n```\n\nWhere `mcp-config.json` uses the same `mcpServers` format as Claude Desktop above.\n\n---\n\n## Configuration Reference\n\nAll settings are configured via environment variables (or `.env` file):\n\n| Variable | Default | Description |\n|---|---|---|\n| `DB_HOST` | `localhost` | SQL Server hostname or IP |\n| `DB_PORT` | `1433` | SQL Server port |\n| `DB_NAME` | `master` | Default database |\n| `DB_USER` | — | SQL Server login username |\n| `DB_PASSWORD` | — | SQL Server login password |\n| `DB_ENCRYPT` | `true` | Enable TLS encryption |\n| `DB_TRUST_SERVER_CERT` | `false` | Trust self-signed certificates |\n| `MCP_TRANSPORT` | `stdio` | Transport mode: `stdio` or `http` |\n| `MCP_HTTP_PORT` | `3000` | HTTP server port (when `MCP_TRANSPORT=http`) |\n| `QUERY_ROW_LIMIT` | `100` | Max rows returned per query (auto-injected) |\n| `QUERY_TIMEOUT_MS` | `30000` | Query timeout in milliseconds |\n| `PAYLOAD_MAX_BYTES` | `1048576` | Max response payload size (1MB) |\n| `SCHEMA_CACHE_TTL_SECONDS` | `3600` | How long schema metadata is cached |\n\n---\n\n## Security\n\nThis server is designed for **read-only** database access with multiple layers of protection:\n\n1. **Database-level:** Uses a `db_datareader`-only account with `readOnlyIntent` connection flag\n2. **Query validation:** AST-based parsing via `node-sql-parser` (with regex fallback for T-SQL edge cases)\n3. **Keyword blocklist:** `INSERT`, `UPDATE`, `DELETE`, `DROP`, `EXEC`, `TRUNCATE`, `ALTER`, `CREATE`, `GRANT`, `REVOKE`, `MERGE` and more\n4. **Multi-statement blocking:** Semicolons outside string literals are rejected\n5. **Row limiting:** Automatic `TOP N` injection prevents memory exhaustion\n6. **Payload truncation:** Responses exceeding 1MB are truncated with a warning\n7. **Connection timeout:** 30-second hard timeout on all queries\n\n---\n\n## Project Structure\n\n```\nsql-server-mcp/\n├── src/\n│   ├── index.ts                          # Server entry point, tool registration, transport\n│   ├── config/database.ts                   # Connection pool, env vars\n│   ├── tools/\n│   │   ├── schemaTools.ts                 # list_databases, list_tables, describe_table, relationships, search\n│   │   ├── schemaManagementTools.ts        # list_schemas\n│   │   ├── queryTools.ts                  # execute_read_query\n│   │   ├── tableStatisticsTools.ts          # get_table_statistics\n│   │   ├── tableIndexTools.ts             # get_table_indexes\n│   │   ├── tableAnalysisTools.ts          # analyze_table\n│   │   ├── columnTools.ts                # get_column_distribution\n│   │   ├── storedProcedureTools.ts          # list_stored_procedures\n│   │   ├── exportTools.ts                 # export_table_data\n│   │   ├── viewTools.ts                   # get_view_definition\n│   │   ├── constraintTools.ts              # list_constraints\n│   │   ├── serverInfoTools.ts             # get_server_info\n│   │   ├── procedureDefinitionTools.ts     # get_procedure_definition\n│   │   ├── userTools.ts                   # list_users, get_user_permissions\n│   │   ├── dependencyTools.ts            # get_table_dependencies\n│   │   ├── usageTools.ts                 # get_column_usage\n│   │   ├── dataIntegrityTools.ts         # validate_data_integrity\n│   │   ├── dataProfileTools.ts          # get_data_profile\n│   │   ├── documentationTools.ts         # generate_schema_documentation\n│   │   ├── apiDocumentationTools.ts     # generate_api_documentation\n│   │   ├── migrationTools.ts            # create_migration_scripts\n│   │   ├── schemaComparisonTools.ts     # compare_schemas\n│   │   └── diagramTools.ts              # create_entity_relationship_diagram\n│   ├── types/index.ts                     # Shared TypeScript interfaces\n│   ├── utils/\n│   │   ├── sqlValidator.ts                # AST + regex query validation, TOP injection\n│   │   └── errorMapper.ts                 # SQL error code → AI-friendly messages\n│   └── cache/schemaCache.ts              # In-memory TTL cache\n├── tests/                                # Unit tests (vitest)\n├── dist/                                 # Compiled output (npm run build)\n├── .env.example                          # Environment variable template\n└── package.json\n```\n\n---\n\n## Development\n\n```bash\n# Install dependencies\nnpm install\n\n# Run in dev mode (hot reload)\nnpm run dev\n\n# Run tests\nnpm test\n\n# Build for production\nnpm run build\n```\n\n---\n\n## License\n\nISC"}