Skip to main content
Glama
MSSQL MCP Server

MSSQL MCP Server

by val-mzn
README.md
# MSSQL MCP Server

A Model Context Protocol (MCP) server for SQL Server database integration that provides comprehensive database interaction capabilities through AI assistants like Claude Desktop and VS Code with GitHub Copilot.

## Features

This MCP server provides the following tools for interacting with SQL Server databases:

### šŸ”§ Core Database Tools

- **`test_connection`** - Test the database connection to ensure proper connectivity
- **`execute_query`** - Execute custom SQL queries on the database
- **`get_database_schema`** - Get a complete overview of the database schema

### šŸ“Š Database Discovery Tools

- **`get_database_tables`** - List all tables in the database with schema information
- **`get_database_views`** - List all views in the database
- **`get_database_procedures`** - List all stored procedures
- **`get_database_functions`** - List all user-defined functions
- **`get_database_triggers`** - List all triggers in the database
- **`search_database_objects`** - Search for database objects by name across all object types

### šŸ” Table Analysis Tools

- **`get_table_info`** - Get detailed information about a specific table (columns, data types, constraints, descriptions)
- **`get_table_indexes`** - Retrieve all indexes for a specific table
- **`get_table_constraints`** - Get all constraints (primary keys, foreign keys, check constraints) for a table
- **`get_table_stats`** - Get table statistics including row count, size, and space usage

## Installation

1. Clone the repository:
```bash
git clone <repository-url>
cd mssql-mcp
```

2. Install dependencies:
```bash
npm install
```

3. Build the project:
```bash
npm run build
```

## Configuration

### Environment Variables

Create a `.env` file in the project root with your SQL Server connection details:

```env
DB_USER=your_username
DB_PASSWORD=your_password
DB_SERVER=localhost
DB_DATABASE=your_database_name
```

### MCP Configuration File

The `mcp-config.json` file contains the server configuration for the MCP client:

```json
{
  "servers": {
    "mssql-mcp": {
      "command": "node",
      "args": ["path/to/your/project/dist/server.js"],
      "env": {
        "DB_USER": "your_username",
        "DB_PASSWORD": "your_password", 
        "DB_SERVER": "localhost",
        "DB_DATABASE": "your_database_name"
      }
    }
  }
}
```

## Quick Start

### For Claude Desktop

1. **Install and build the MCP server** (see Installation section above)

2. **Locate Claude Desktop's configuration file:**
   - **Windows:** `%APPDATA%\Claude\claude_desktop_config.json`
   - **macOS:** `~/Library/Application Support/Claude/claude_desktop_config.json`
   - **Linux:** `~/.config/Claude/claude_desktop_config.json`

3. **Add the server configuration** to Claude's config file:
```json
{
  "mcpServers": {
    "mssql-mcp": {
      "command": "node",
      "args": ["C:\\path\\to\\your\\project\\dist\\server.js"],
      "env": {
        "DB_USER": "your_username",
        "DB_PASSWORD": "your_password",
        "DB_SERVER": "localhost",
        "DB_DATABASE": "your_database_name"
      }
    }
  }
}
```

4. **Restart Claude Desktop** to load the new MCP server

5. **Verify the connection** by asking Claude to test the database connection:
   ```
   Can you test the database connection using the mssql tools?
   ```

### For VS Code with GitHub Copilot

1. **Install and build the MCP server** (see Installation section above)

2. **Enable MCP in VS Code:**
   - Open the Extensions panel in VS Code
   - Look for MCP-related extensions or GitHub Copilot settings
   - Ensure MCP integration is enabled

3. **Create or locate the MCP configuration file:**
   - Create `mcp.json` in your VS Code user directory: `C:\Users\<username>\AppData\Roaming\Code\User\mcp.json`
   - If the file already exists, you can add the server configuration to the existing file

4. **Add the server configuration** to your `mcp.json` file:
```json
{
  "servers": {
    "mssql-mcp": {
      "command": "node",
      "args": ["./dist/server.js"],
      "cwd": "C:\\path\\to\\your\\mssql-mcp\\project",
      "env": {
        "DB_USER": "your_username",
        "DB_PASSWORD": "your_password",
        "DB_SERVER": "localhost",
        "DB_DATABASE": "your_database_name"
      }
    }
  }
}
```
**Important:**:
- Replace `C:\\path\\to\\your\\mssql-mcp\\project` with the actual absolute path to your project directory.
- Replace the environment variables in the `env` section with your actual database credentials:

5. **Start the MSSQL-MCP server in VS Code:**
   - Open the Extensions panel in VS Code (Ctrl+Shift+X)
   - Find the MCP server management section
   - Start or enable the mssql-mcp server from the list of configured servers
   - Verify the server status shows as "Running" or "Connected"

6. **Test the connection** by asking GitHub Copilot to interact with your database:
   ```
   Can you test the database connection using the mssql tools?
   ```

## Usage Examples

Once configured, you can interact with your SQL Server database through natural language:

### Basic Database Exploration
```
"What tables are available in the database?"
"Show me the structure of the Users table"
"List all stored procedures in the database"
```

### Data Analysis
```
"How many rows are in the Orders table?"
"What are the indexes on the Products table?"
"Show me the constraints for the Customers table"
```

### Custom Queries
```
"Execute a query to find all customers from France"
"Get the top 10 most recent orders"
"Show me sales data for the last month"
```

### Schema Analysis
```
"Give me an overview of the entire database schema"
"Search for any objects containing 'user' in their name"
"What triggers exist in the database?"
```

## Development

### Project Structure
```
ā”œā”€ā”€ src/
│   ā”œā”€ā”€ server.ts      # Main MCP server setup
│   ā”œā”€ā”€ database.ts    # Database connection management
│   └── tools.ts       # Tool definitions and implementations
ā”œā”€ā”€ dist/              # Compiled JavaScript output
ā”œā”€ā”€ package.json
ā”œā”€ā”€ tsconfig.json
ā”œā”€ā”€ mcp-config.json    # MCP server configuration
└── .env              # Environment variables (create this)
```

### Running in Development
```bash
# Build and start the server
npm run build
npm start

# Or build in watch mode during development
npx tsc --watch
```

### Adding New Tools

To add new database tools, edit `src/tools.ts` and follow the existing pattern:

```typescript
server.registerTool(
  "your_tool_name",
  {
    title: "Your Tool Title",
    description: "Description of what your tool does",
    inputSchema: {
      // Define your input parameters using Zod schema
      parameter: z.string().describe("Parameter description"),
    },
  },
  async ({ parameter }) => {
    // Tool implementation
    try {
      const connection = getDbConnection();
      const result = await connection.request().query("YOUR SQL");
      
      return {
        content: [
          {
            type: "text",
            text: JSON.stringify(result.recordset, null, 2),
          },
        ],
      };
    } catch (error) {
      return {
        content: [
          {
            type: "text",
            text: `Error: ${error instanceof Error ? error.message : "Unknown error"}`,
          },
        ],
      };
    }
  }
);
```

## Security Considerations

- **Environment Variables:** Never commit your `.env` file or actual database credentials to version control
- **SQL Injection:** The server uses parameterized queries where possible to prevent SQL injection
- **Access Control:** Ensure the database user has only the necessary permissions for your use case
- **Network Security:** Use secure connections and proper firewall configurations for production deployments

## Troubleshooting

### Common Issues

1. **Connection Errors:**
   - Verify database server is running and accessible
   - Check firewall settings
   - Confirm SQL Server authentication mode allows your connection type

2. **Permission Errors:**
   - Ensure the database user has necessary permissions for the operations you're trying to perform
   - Check if the user can access system views for metadata queries

3. **MCP Client Not Recognizing Server:**
   - Verify the path to the compiled server (`dist/server.js`) is correct
   - Check that all dependencies are installed
   - Restart the MCP client after configuration changes