MS

MSSQL MCP Server for Node.js with Zod

Deploy an MCP server for MSSQL Node.js with Zod validation, auto-detected single/multi DB configs, execute-SQL and schema tools plus optional Express endpoints.

Quick Install
npx -y @mihai-dulgheru/mssql-mcp-node

Overview

This MCP (Model Context Protocol) server implements a lightweight bridge between Microsoft SQL Server (MSSQL) and model-driven tooling. It exposes a set of MCP-compatible tools that let AI agents or other MCP clients inspect database schema, and execute parameterized SQL safely, while validating inputs with Zod. The project supports both single-database and multi-database configurations and can be run as a standalone process or mounted as optional Express endpoints.

The server is useful when you want controlled, schema-aware database access in an AI integration: you get typed validation for tool inputs, schema introspection to help model reasoning, and minimal wiring to plug into existing Node.js apps or MCP orchestration layers.

Features

  • Execute SQL queries with parameter validation backed by Zod
  • Schema introspection tool that lists databases, tables, columns, and types
  • Automatic detection/handling of single vs. multi-database configurations
  • Optional Express middleware endpoints for MCP requests
  • Minimal setup for Node.js projects (TypeScript / JavaScript)
  • Pluggable authentication (e.g., API token via header)
  • Simple JSON-based configuration and environment variable support

Installation / Configuration

Install the package from GitHub (or clone and install locally). Example using npm:

# Install as a dependency (if published) or clone repo and npm install
npm install mihai-dulgheru/mssql-mcp-node
# or if you cloned the repo:
git clone https://github.com/mihai-dulgheru/mssql-mcp-node
cd mssql-mcp-node
npm install

Basic environment-driven configuration (example .env):

# For a single DB
MSSQL_CONNECTION=Server=localhost;Database=MyDB;User Id=sa;Password=YourPass123;

# Or for multiple DBs (JSON string)
MSSQL_CONNECTIONS='{"primary":"Server=...;Database=PrimaryDB;...","analytics":"Server=...;Database=Analytics;..."}'

# Optional API key for simple auth
MCP_API_KEY=super-secret-token

Example minimal server (JavaScript/TypeScript):

import express from "express";
import { createMssqlMcpServer } from "mssql-mcp-node"; // package export
import { z } from "zod";

const app = express();

// Create server instance with validation and optional auth
const mcp = createMssqlMcpServer({
  // Accepts a connection string, or an object mapping names -> connection strings
  connections: process.env.MSSQL_CONNECTION || JSON.parse(process.env.MSSQL_CONNECTIONS || "{}"),
  // Simple API key auth (requests must include Authorization: Bearer <MCP_API_KEY>)
  apiKey: process.env.MCP_API_KEY,
  // Optionally override or extend Zod schemas for tools
  schemas: {
    executeSql: z.object({
      database: z.string().optional(), // optional when single DB
      sql: z.string().min(1),
      params: z.record(z.any()).optional()
    })
  }
});

// Mount MCP endpoints under /mcp
app.use("/mcp", mcp.expressRouter());

app.listen(3000, () => console.log("MSSQL MCP server listening on :3000"));

Configuration notes:

  • Single DB: pass a single connection string via connections or MSSQL_CONNECTION.
  • Multi DB: pass an object mapping names to connection strings via connections or MSSQL_CONNECTIONS.
  • Authentication: use apiKey or provide a custom auth middleware before the MCP router.

Available Tools / Resources

The server exposes MCP-compatible tools designed for safe database interactions. Common tools include:

  • execute-sql

    • Purpose: run a parameterized SQL statement and return rows/results.
    • Inputs (validated with Zod): database (optional if single DB), sql (string), params (object map).
    • Behavior: runs queries using mssql driver, sanitizes/parametrizes values, returns structured results.
  • schema

    • Purpose: introspect database metadata (databases, tables, columns, types).
    • Inputs: optional database name.
    • Output: JSON representation of schema useful for model grounding.
  • list-databases (when multi-db configured)

    • Purpose: return available database keys for multi-db setups.

Each tool includes JSON schema-like descriptions compatible with MCP tool manifests, making it straightforward to register these tools with model orchestration systems.

Use Cases

  • AI-assisted query generation: Provide an LLM with the schema tool output so it can generate correct SQL, then use execute-sql with parameter validation to run the query.

    • Flow: call schema -> LLM composes SQL -> call execute-sql (with SQL & params) -> return results.
  • Multi-tenant analytics: Configure multiple named connections and let agents select the correct database by name via the execute-sql database parameter.

  • Safe, validated API for apps: Mount the MCP endpoints in an existing Express app and protect them with an API key or custom middleware. This provides a typed, auditable layer for database access used by automated agents or external systems.

  • Debugging and exploration: Use the schema tool to discover table structures while developing new agent capabilities or analytics pipelines.

Examples

Execute a simple query (JSON RPC / MCP request payload example):

{
  "tool": "execute-sql",
  "input": {
    "database": "primary",
    "sql": "SELECT TOP 10 * FROM Users WHERE createdAt >= @since",
    "params": { "since": "2024-01-01" }
  }
}

Inspect schema for a database:

{
  "tool": "schema",
  "input": { "database": "analytics" }
}

Security and Best Practices

  • Always validate/whitelist which tools are exposed to external models.
  • Prefer parameterized queries over string interpolation. The server validates params with Zod and uses parameter binding.
  • Restrict access with API keys or integrate with your app’s auth middleware.
  • Limit returned row counts and execution timeouts for untrusted clients.

Troubleshooting

  • Connection issues: confirm the connection string, network reachability, and SQL Server authentication.
  • Multi-db config parsing: ensure MSSQL_CONNECTIONS is valid JSON when supplied via environment variable.
  • Validation errors: the server returns Zod-style validation messages when input does not meet the tool schema.

For full source, examples, and advanced configuration options, see the project repository on GitHub: https://github.com/mihai-dulgheru/mssql-mcp-node.