Sponsored by Deepsite.site

SQL Server MCP Server for Claude Code

Created By
shakunvohradeltek7 months ago
MS SQL Server - MCP for Claude-Code
Content

SQL Server MCP Server for Claude Code

A Machine Comprehension Protocol (MCP) server that enables Claude Code to directly query Microsoft SQL Server databases.

Credits

This project is based on mssql_mcp_server by Richard Han. It has been adapted to use FreeTDS for improved cross-platform compatibility.

Prerequisites

  • Python 3.8 or higher
  • FreeTDS (installed by the setup script)
  • SQL Server instance accessible from your machine
  • One of the following operating systems:
    • Linux (Ubuntu, Debian, RedHat, CentOS, etc.)
    • macOS
    • Windows (via WSL - Windows Subsystem for Linux)

Installation

  1. Clone or download this repository:

    git clone https://github.com/your-username/mcp-server-for-sql.git
    cd mcp-server-for-sql
    
  2. Run the installation script:

    ./install_mssql_mcp_clean.sh
    

    This script will:

    • Detect your operating system
    • Check Python installation
    • Install FreeTDS
    • Create necessary MCP server scripts
    • Set up configuration files
  3. Configure SQL Server connection:

    ./configure_mcp.sh
    

    You'll be prompted to enter:

    • SQL Server hostname/IP and port (e.g., "myserver.database.azure.com,1433")
    • Database name
    • Username
    • Password
  4. Test the connection:

    ./test_tsql.sh
    

    This will verify that your connection details are correct and FreeTDS is working properly.

Usage with Claude Code

Once installed and configured, you can use the SQL Server MCP integration in Claude Code with:

mcp__mssql__execute_sql(query="SELECT * FROM YourTable")

Examples:

  • List all tables: mcp__mssql__execute_sql(query="SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'")
  • Count records: mcp__mssql__execute_sql(query="SELECT COUNT(*) AS Count FROM YourTable")
  • Query with filtering: mcp__mssql__execute_sql(query="SELECT * FROM Customers WHERE City='London'")

How It Works Behind the Scenes

MCP Architecture

  1. Configuration Setup:

    • The .mcp.json file defines the MCP server configuration
    • It specifies how Claude Code should launch and communicate with the server
    • Contains connection details for your SQL Server
  2. Claude Code Integration:

    • When you start Claude Code in the project directory, it detects the .mcp.json file
    • It registers the mcp__mssql__execute_sql tool for use in your session
  3. Query Execution Flow:

    When you run a query:

    1. You type: mcp__mssql__execute_sql(query="SELECT * FROM Customers")

    2. Claude sends a request to the MCP server:

      {
        "requestId": "123",
        "type": "CallToolRequest",
        "toolName": "execute_sql",
        "callId": "456",
        "parameters": {
          "query": "SELECT * FROM Customers"
        }
      }
      
    3. The MCP server:

      • Creates a temporary SQL file with your query
      • Executes it using FreeTDS's tsql utility
      • Parses the results into a structured format
      • Cleans up temporary files
    4. The server returns results to Claude:

      {
        "requestId": "123",
        "type": "CallToolResponse",
        "callId": "456",
        "result": {
          "rows": [
            {"CustomerID": "1", "Name": "John", "...": "..."},
            {"CustomerID": "2", "Name": "Jane", "...": "..."}
          ]
        }
      }
      
    5. Claude formats and displays the results in your conversation

Technical Implementation

  • FreeTDS Integration: Uses the FreeTDS tsql command-line tool to connect to SQL Server, providing broad compatibility across platforms
  • Security: Database credentials are stored only in your local configuration file, never sent as part of prompts
  • Error Handling: SQL errors are captured and returned as structured responses
  • Temporary File Management: Creates and cleans up temporary SQL files for each query

File Structure

  • install_mssql_mcp_clean.sh - Main installation script
  • mssql_mcp_server.py - Core MCP server implementation
  • run_mssql_mcp.py - Launcher script
  • configure_mcp.sh - Connection configuration script
  • test_tsql.sh - Connection testing script
  • .mcp.json - MCP configuration file (created during setup)

Troubleshooting

Connection Issues

  1. Check FreeTDS installation:

    tsql -C
    

    Should display FreeTDS version information.

  2. Verify SQL Server accessibility:

    • Ensure your firewall allows connections to the SQL Server port (typically 1433)
    • Check that the SQL Server allows remote connections
    • Verify your username and password are correct
  3. Check connection configuration:

    • Run ./configure_mcp.sh to update your connection details
    • Make sure server address includes the port (e.g., "server,1433")

MCP Server Issues

  1. Check log output: When running Claude Code, check the terminal for any error messages from the MCP server.

  2. Verify .mcp.json file: Ensure it contains the correct paths and environment variables.

  3. Test direct execution:

    python3 run_mssql_mcp.py
    

    The server should start without errors.

WSL-Specific Issues (Windows)

  1. Python and FreeTDS setup:

    sudo apt update
    sudo apt install -y python3-dev python3-pip freetds-bin freetds-dev
    
  2. Connecting to Windows SQL Server from WSL:

    • Use host.docker.internal or your Windows IP address as the server address
    • Ensure Windows Firewall allows connections on port 1433
  3. Temporary file issues: If you experience problems with temporary files in WSL, make sure the temp directory exists and is writable.

Advanced Configuration

Manual Editing of .mcp.json

You can directly edit the .mcp.json file to:

  • Change the Python executable path
  • Modify environment variables
  • Add additional configuration options

Example:

{
  "mcpServers": {
    "mssql": {
      "type": "stdio",
      "command": "python3",
      "args": ["/path/to/run_mssql_mcp.py"],
      "env": {
        "MSSQL_SERVER": "myserver.database.windows.net,1433",
        "MSSQL_DATABASE": "mydatabase",
        "MSSQL_USER": "myusername",
        "MSSQL_PASSWORD": "mypassword"
      }
    }
  }
}

Security Considerations

  • Use a database account with minimal necessary permissions
  • Consider using integrated security if available in your environment
  • Keep your .mcp.json file secure as it contains database credentials
  • Regularly review and update credentials

License

This project is open-source and freely available for use and modification.

Contributions

Contributions, bug reports, and feature requests are welcome! Please feel free to submit issues or pull requests to the original repository by Richard Han: mssql_mcp_server.

Recommend Servers
TraeBuild with Free GPT-4.1 & Claude 3.7. Fully MCP-Ready.
Baidu Map百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
Visual Studio Code - Open Source ("Code - OSS")Visual Studio Code
MiniMax MCPOfficial MiniMax Model Context Protocol (MCP) server that enables interaction with powerful Text to Speech, image generation and video generation APIs.
BlenderBlenderMCP connects Blender to Claude AI through the Model Context Protocol (MCP), allowing Claude to directly interact with and control Blender. This integration enables prompt assisted 3D modeling, scene creation, and manipulation.
Serper MCP ServerA Serper MCP Server
Amap Maps高德地图官方 MCP Server
WindsurfThe new purpose-built IDE to harness magic
Howtocook Mcp基于Anduin2017 / HowToCook (程序员在家做饭指南)的mcp server,帮你推荐菜谱、规划膳食,解决“今天吃什么“的世纪难题; Based on Anduin2017/HowToCook (Programmer's Guide to Cooking at Home), MCP Server helps you recommend recipes, plan meals, and solve the century old problem of "what to eat today"
CursorThe AI Code Editor
ChatWiseThe second fastest AI chatbot™
Zhipu Web SearchZhipu Web Search MCP Server is a search engine specifically designed for large models. It integrates four search engines, allowing users to flexibly compare and switch between them. Building upon the web crawling and ranking capabilities of traditional search engines, it enhances intent recognition capabilities, returning results more suitable for large model processing (such as webpage titles, URLs, summaries, site names, site icons, etc.). This helps AI applications achieve "dynamic knowledge acquisition" and "precise scenario adaptation" capabilities.
AiimagemultistyleA Model Context Protocol (MCP) server for image generation and manipulation using fal.ai's Stable Diffusion model.
MCP AdvisorMCP Advisor & Installation - Use the right MCP server for your needs
TimeA Model Context Protocol server that provides time and timezone conversion capabilities. This server enables LLMs to get current time information and perform timezone conversions using IANA timezone names, with automatic system timezone detection.
EdgeOne Pages MCPAn MCP service designed for deploying HTML content to EdgeOne Pages and obtaining an accessible public URL.
DeepChatYour AI Partner on Desktop
Tavily Mcp
Context7Context7 MCP Server -- Up-to-date code documentation for LLMs and AI code editors
Playwright McpPlaywright MCP server
Jina AI MCP ToolsA Model Context Protocol (MCP) server that integrates with Jina AI Search Foundation APIs.