Labsco
dperussina logo

MS SQL MCP Server

β˜… 78

from dperussina

A bridge for AI assistants to directly query and explore Microsoft SQL Server databases.

πŸ”₯πŸ”₯πŸ”₯βœ“ VerifiedFreeNeeds API keys

MS SQL MCP Server 1.1

An easy-to-use bridge that lets AI assistants like Claude directly query and explore Microsoft SQL Server databases. No coding experience required!

What Does This Tool Do?

This tool allows AI assistants to:

  1. Discover tables in your SQL Server database
  2. View table structures (columns, data types, etc.)
  3. Execute read-only SQL queries safely
  4. Generate SQL queries from natural language requests

🌟 Why You Need This Tool

Bridge the Gap Between Your Data and AI

  • No Coding Required: Give Claude and other AI assistants direct access to your SQL Server databases without writing complex integration code
  • Maintain Control: All queries are read-only by default, ensuring your data remains safe
  • Private & Secure: Your database credentials stay local and are never sent to external services

Practical Benefits

  • Save Hours of Manual Work: No more copy-pasting data or query results to share with AI
  • Deeper Analysis: AI can navigate your entire database schema and provide insights across multiple tables
  • Natural Language Interface: Ask questions about your data in plain English
  • End the Context Limit Problem: Access large datasets that would exceed normal AI context windows

Perfect For

  • Data Analysts who want AI help interpreting SQL data without sharing credentials
  • Developers looking for a quick way to explore database structure through natural conversation
  • Business Analysts who need insights without SQL expertise
  • Database Administrators who want to provide controlled access to AI tools

πŸ“Š Example Use Cases

  1. Explore your database structure without writing SQL

    mcp_SQL_mcp_discover_database()
  2. Get detailed information about a specific table

    mcp_SQL_mcp_table_details({ tableName: "Customers" })
  3. Run a safe query

    mcp_SQL_mcp_execute_query({ sql: "SELECT TOP 10 * FROM Customers", returnResults: true })
  4. Find tables by name pattern

    mcp_SQL_mcp_discover_tables({ namePattern: "%user%" })
  5. Use pagination to navigate large result sets

    // First page
    mcp_SQL_mcp_execute_query({ 
      sql: "SELECT * FROM Users ORDER BY Username OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY", 
      returnResults: true 
    })
    
    // Next page
    mcp_SQL_mcp_execute_query({ 
      sql: "SELECT * FROM Users ORDER BY Username OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY", 
      returnResults: true 
    })
  6. Cursor-based pagination for optimal performance

    // First page
    mcp_SQL_mcp_execute_query({ 
      sql: "SELECT TOP 10 * FROM Users ORDER BY Username", 
      returnResults: true 
    })
    
    // Next page using the last value as cursor
    mcp_SQL_mcp_execute_query({ 
      sql: "SELECT TOP 10 * FROM Users WHERE Username > 'last_username' ORDER BY Username", 
      returnResults: true 
    })
  7. Ask natural language questions

    "Show me the top 5 customers with the most orders in the last month"

πŸ’‘ Real-World Applications

For Business Intelligence

  • Sales Performance Analysis: "Show me monthly sales trends for the past year and identify our top-performing products by region."
  • Customer Segmentation: "Analyze our customer base by purchase frequency, average order value, and geographical location."
  • Financial Reporting: "Create a quarterly profit and loss report comparing this year to last year."

For Database Management

  • Schema Optimization: "Help me identify tables with missing indexes by examining query performance data."
  • Data Quality Auditing: "Find all customer records with incomplete information or invalid values."
  • Usage Analysis: "Show me which tables are most frequently accessed and what queries are most resource-intensive."

For Development

  • API Exploration: "I'm building an API - help me analyze the database schema to design appropriate endpoints."
  • Query Optimization: "Review this complex query and suggest performance improvements."
  • Database Documentation: "Create comprehensive documentation of our database structure with explanations of relationships."

πŸ–₯️ Interactive Client Features

The bundled client provides an easy menu-driven interface:

  1. List available resources - See what information is available
  2. List available tools - See what actions you can perform
  3. Execute SQL query - Run a read-only SQL query
  4. Get table details - View structure of any table
  5. Read database schema - See all tables and their relationships
  6. Generate SQL query - Convert natural language to SQL

πŸ”Ž Advanced Query Capabilities

Table Discovery & Exploration

The MCP Server provides powerful tools for exploring your database structure:

  • Pattern-based table discovery: Find tables matching specific patterns

    mcp_SQL_mcp_discover_tables({ namePattern: "%order%" })
  • Schema overview: Get a high-level view of tables by schema

    mcp_SQL_mcp_execute_query({ 
      sql: "SELECT TABLE_SCHEMA, COUNT(*) AS TableCount FROM INFORMATION_SCHEMA.TABLES GROUP BY TABLE_SCHEMA" 
    })
  • Column exploration: Examine column metadata for any table

    mcp_SQL_mcp_table_details({ tableName: "dbo.Users" })

Pagination Techniques

The server supports multiple pagination methods for handling large datasets:

  1. Offset/Fetch Pagination: Standard SQL pagination using OFFSET and FETCH

    mcp_SQL_mcp_execute_query({ 
      sql: "SELECT * FROM Users ORDER BY Username OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY" 
    })
  2. Cursor-Based Pagination: More efficient for large datasets

    // Get first page
    mcp_SQL_mcp_execute_query({ 
      sql: "SELECT TOP 10 * FROM Users ORDER BY Username" 
    })
    
    // Get next page using last value as cursor
    mcp_SQL_mcp_execute_query({ 
      sql: "SELECT TOP 10 * FROM Users WHERE Username > 'last_username' ORDER BY Username" 
    })
  3. Count with Data: Retrieve total count alongside paginated data

    mcp_SQL_mcp_execute_query({ 
      sql: "WITH TotalCount AS (SELECT COUNT(*) AS Total FROM Users) SELECT TOP 10 u.*, t.Total FROM Users u CROSS JOIN TotalCount t ORDER BY Username" 
    })

Complex Joins & Relationships

Explore relationships between tables with join operations:

mcp_SQL_mcp_execute_query({ 
  sql: "SELECT u.Username, u.Email, r.RoleName FROM Users u JOIN UserRoles ur ON u.Username = ur.Username JOIN Roles r ON ur.RoleId = r.RoleId ORDER BY u.Username"
})

Analytical Queries

Run aggregations and analytical queries to gain insights:

mcp_SQL_mcp_execute_query({ 
  sql: "SELECT UserType, COUNT(*) AS UserCount, SUM(CASE WHEN IsActive = 1 THEN 1 ELSE 0 END) AS ActiveUsers FROM Users GROUP BY UserType"
})

Using SQL Server Features

The MCP server supports SQL Server-specific features:

  • Common Table Expressions (CTEs)
  • Window functions
  • JSON operations
  • Hierarchical queries
  • Full-text search (when configured in your database)

πŸ”— Integration Options

Claude Desktop Integration

Connect this tool directly to Claude Desktop in a few easy steps:

  1. Install Claude Desktop from anthropic.com
  2. Edit Claude's configuration file:
    • Location: ~/Library/Application Support/Claude/claude_desktop_config.json
    • Add this configuration:
{
    "mcpServers": {
        "mssql": {
            "command": "node",
            "args": [
                "/FULL/PATH/TO/mssql-mcp-server/server.mjs"
            ]
        }
    }
}
  1. Replace /FULL/PATH/TO/ with the actual path to where you cloned this repository
  2. Restart Claude Desktop
  3. Look for the tools icon in Claude Desktop - you can now use database commands directly!

Connecting with Cursor IDE

Cursor is an AI-powered code editor that can leverage this tool for advanced database interactions. Here's how to set it up:

Setup in Cursor

  1. Open Cursor IDE (download from cursor.sh if you don't have it)
  2. Start the MS SQL MCP Server using the HTTP/SSE transport:
    npm run start:sse
  3. Create a new workspace or open an existing project in Cursor
  4. Enter Cursor Settings
  5. Click MCP
  6. Add new MCP server
  7. Name your MCP server, select type: sse
  8. Enter server URL as: localhost:3333/sse (or the port you have it running on)

Using Database Commands in Cursor

Once connected, you can use MCP commands directly in Cursor's AI chat:

  1. Ask Claude in Cursor to explore your database:

    Can you show me the tables in my database?
  2. Execute specific queries:

    Query the top 10 records from the Customers table
  3. Generate and run complex queries:

    Find all orders from the last month with a value over $1000

Troubleshooting Cursor Connection

  • Make sure the MS SQL MCP Server is running with the HTTP/SSE transport
  • Check that the port is correct and matches what's in your .env file
  • Ensure your firewall isn't blocking the connection
  • If using a different IP/hostname, update the SERVER_URL in your .env file

πŸ”„ Transport Methods Explained

Option 1: stdio Transport (Default)

Best for: Using directly with Claude Desktop or the bundled client

npm start

Option 2: HTTP/SSE Transport

Best for: Network access or when used with web applications

npm run start:sse

πŸ›‘οΈ Security Features

  • Read-only by default: No risk of data modification
  • Private credentials: Database connection details stay in your .env file
  • SQL injection protection: Built-in validation for SQL queries

πŸ“š Understanding SQL Server Basics

If you're new to SQL Server, here are some key concepts:

  • Tables: Store your data in rows and columns
  • Schemas: Logical groupings of tables (like folders)
  • Queries: Commands to retrieve or analyze data
  • Views: Pre-defined queries saved for easy access

This tool helps you explore all of these without needing to be a SQL expert!

πŸ—οΈ Architecture & Core Modules

The MS SQL MCP Server is built with a modular architecture that separates concerns for maintainability and extensibility:

Core Modules

database.mjs - Database Connectivity

  • Manages SQL Server connection pooling
  • Provides query execution with retry logic and error handling
  • Handles database connections, transactions, and configuration
  • Includes utilities for sanitizing SQL and formatting errors

tools.mjs - Tool Registration

  • Registers all database tools with the MCP server
  • Implements tool validation and parameter checking
  • Provides core functionality for SQL queries, table exploration, and database discovery
  • Maps tool calls to database operations

resources.mjs - Database Resources

  • Exposes database metadata through resource endpoints
  • Provides schema information, table listings, and procedure documentation
  • Formats database structure information for AI consumption
  • Includes discovery utilities for database exploration

pagination.mjs - Results Navigation

  • Implements cursor-based pagination for large result sets
  • Provides utilities for generating next/previous page cursors
  • Transforms SQL queries to support pagination
  • Handles SQL Server's OFFSET/FETCH pagination syntax

errors.mjs - Error Handling

  • Defines custom error types for different failure scenarios
  • Implements JSON-RPC error formatting
  • Provides human-readable error messages
  • Includes middleware for global error handling

logger.mjs - Logging System

  • Configures Winston logging with multiple transports
  • Provides context-aware request logging
  • Handles log rotation and formatting
  • Captures uncaught exceptions and unhandled rejections

How These Modules Work Together

  1. When a tool call is received, the MCP server routes it to the appropriate handler in tools.mjs
  2. The tool handler validates parameters and constructs a database query
  3. The query is executed via functions in database.mjs, with possible pagination from pagination.mjs
  4. Results are formatted and returned to the client
  5. Any errors are caught and processed through errors.mjs
  6. All operations are logged via logger.mjs

This architecture ensures:

  • Clean separation of concerns
  • Consistent error handling
  • Comprehensive logging
  • Efficient database connection management
  • Scalable query execution

πŸ“ License

ISC