Skip to main content
Glama
mssql-mcp-server

mssql-mcp-server

by ethan3011

mssql-mcp-server

A read-only Model Context Protocol (MCP) server for Microsoft SQL Server. It lets an AI assistant such as Claude Code, Claude Desktop or Cursor list tables, describe columns and run SELECT queries against your database, and nothing else.

npx -y @ethan0921/mssql-mcp-server

Why

An assistant that can read the schema and the data answers questions about a database much better than one that guesses. Letting it write is a different matter, so this server is built to stay read-only, in three layers:

  1. Your login. Give the server a login that can only read (see Security model). This is the boundary that really holds.

  2. A statement check. Before anything reaches SQL Server, the query must start with SELECT or WITH, and statements that write data, change objects or permissions, control transactions, change the session or run server operations are refused anywhere in it.

  3. A rollback wrapper. Every query runs inside a transaction that is always rolled back, after success, errors, timeouts and the row limit alike.

It also keeps answers small and exact: compact JSON in column order, a row limit with a clear notice, timeouts, SQL Server error numbers and line numbers, and dates exactly as stored.

Related MCP server: Microsoft SQL Server MCP Server

Quick start

You need Node.js 18.19 or later and a SQL Server login (SQL Server authentication).

Claude Code

claude mcp add mssql \
  -e MSSQL_SERVER=sql.example.com \
  -e MSSQL_DATABASE=Sales \
  -e MSSQL_USER=mcp_reader \
  -e MSSQL_PASSWORD='change-me' \
  -- npx -y @ethan0921/mssql-mcp-server

On native Windows (not WSL), wrap npx in cmd /c, as Claude Code requires for npx servers there:

claude mcp add mssql -e MSSQL_SERVER=sql.example.com ... -- cmd /c npx -y @ethan0921/mssql-mcp-server

Claude Desktop

Add the server to claude_desktop_config.json (macOS: ~/Library/Application Support/Claude/, Windows: %APPDATA%\Claude\) and restart Claude Desktop:

{
  "mcpServers": {
    "mssql": {
      "command": "npx",
      "args": ["-y", "@ethan0921/mssql-mcp-server"],
      "env": {
        "MSSQL_SERVER": "sql.example.com",
        "MSSQL_DATABASE": "Sales",
        "MSSQL_USER": "mcp_reader",
        "MSSQL_PASSWORD": "change-me"
      }
    }
  }
}

Cursor

Put the same block in ~/.cursor/mcp.json (all projects) or .cursor/mcp.json (one project):

{
  "mcpServers": {
    "mssql": {
      "command": "npx",
      "args": ["-y", "@ethan0921/mssql-mcp-server"],
      "env": {
        "MSSQL_SERVER": "sql.example.com",
        "MSSQL_DATABASE": "Sales",
        "MSSQL_USER": "mcp_reader",
        "MSSQL_PASSWORD": "change-me"
      }
    }
  }
}

To run a local copy instead of the npm package, use "command": "node" and "args": ["/path/to/mssql-mcp-server/src/index.js"].

Configuration

All settings are environment variables.

Variable

Default

Meaning

MSSQL_SERVER

required

Host name or IP address. Use host\INSTANCE for a named instance (found through SQL Server Browser; MSSQL_PORT is then ignored).

MSSQL_PORT

1433

TCP port.

MSSQL_USER

required

SQL Server login.

MSSQL_PASSWORD

required

Password of that login.

MSSQL_DATABASE

the login's default database

Database to work in.

MSSQL_ENCRYPT

true

Encrypt the connection with TLS.

MSSQL_TRUST_SERVER_CERTIFICATE

false

Accept a server certificate that is not trusted, for example a self-signed one. Use only on networks you trust.

MSSQL_MAX_ROWS

200

Most rows one call returns, counted over all result sets. A query that returns more is stopped there.

MSSQL_REQUEST_TIMEOUT_MS

30000

Cancel a query that runs longer than this. 0 means no limit.

MSSQL_CONNECTION_TIMEOUT_MS

15000

Give up connecting after this long.

MSSQL_ROLLBACK_WRAPPER

true

Run every query inside a transaction that is always rolled back. See The rollback wrapper before turning it off.

Flags accept true/false, 1/0, yes/no and on/off. A missing or invalid setting does not stop the server; every tool call answers with what to fix instead.

The server connects on the first tool call, not at startup. If the database is unreachable, the call returns the error and the next call tries again. Logs go to stderr only; the user name and password are never logged.

Tools

The tool names and the query argument are the same as in 1.x, so existing client settings and permission allowlists keep working.

query_database

Runs one read-only query that starts with SELECT or WITH (CTEs and WITH XMLNAMESPACES).

Argument

Type

Meaning

query

string

The T-SQL query.

{ "query": "SELECT TOP (3) OrderId, OrderDate, Total FROM dbo.Orders ORDER BY OrderDate DESC" }
{"columns":["OrderId","OrderDate","Total"],"rows":[[10423,"2026-11-25T16:02:11.120",125.5],[10422,"2026-11-25T15:47:03.000",80],[10421,"2026-11-25T15:30:59.870",42.25]],"rowCount":3}

Rows are arrays in column order, so duplicate, unnamed and number-like column names keep their place. A batch that returns several result sets (for example SELECT 1 AS a SELECT 2 AS b) comes back as {"resultSets":[{"columns":...,"rows":...,"rowCount":...}, ...]}.

When the result has more rows than MSSQL_MAX_ROWS, the query is stopped and the answer starts with a notice:

{"truncated":true,"notice":"Only the first 200 rows are shown; the result has more. Add TOP, WHERE or GROUP BY to narrow it, or raise MSSQL_MAX_ROWS.","columns":["OrderId"],"rows":[[1],[2]],"rowCount":200}

Errors come back as tool errors with the SQL Server error number and line:

SQL Server error 207, line 1: Invalid column name 'Totl'.

list_tables

Lists the tables and views of the current database.

Argument

Type

Meaning

filter

string, optional

Keeps names whose table name or schema.name contains this text. % and _ work as LIKE wildcards.

{ "filter": "order" }
{"columns":["schema","name","type"],"rows":[["dbo","OrderLines","table"],["dbo","Orders","table"],["sales","OpenOrders","view"]],"rowCount":3}

describe_table

Describes one table or view of the current database: its type and MS_Description, and for each column the type with length or precision, nullability, default, primary key position, identity and MS_Description. Empty fields are left out.

Argument

Type

Meaning

table

string

Table or view name, best schema-qualified: dbo.Orders, [sales].[Order Lines].

{ "table": "dbo.Orders" }
{"schema":"dbo","name":"Orders","type":"table","description":"Customer orders","columns":[{"name":"OrderId","type":"int","nullable":false,"primaryKey":1,"identity":true},{"name":"OrderDate","type":"datetime2(3)","nullable":false,"default":"(sysdatetime())","description":"When the order was placed (local time)"},{"name":"Total","type":"decimal(12,2)","nullable":false},{"name":"Note","type":"nvarchar(max)","nullable":true}]}

How values are written

SQL Server type

Example in the output

datetime

"2026-11-26T10:20:30.123"

smalldatetime

"2026-11-26T10:20:00"

datetime2(7)

"2026-11-26T10:20:30.1234567" (as many fraction digits as the column's scale)

date

"2026-11-26"

time(7)

"10:20:30.1234567"

datetimeoffset(7)

"2026-11-26T10:20:30.1234567+09:00" (the stored offset is kept)

bigint

9223372036854775807 (every digit is kept)

bit

true / false

binary, varbinary, image

"0x0AFF"; values over 256 bytes are cut and end with ... (N bytes)

uniqueidentifier

"BEE4993C-4248-4623-823C-7B5209A7A621"

Types without an offset are written without a Z, because SQL Server does not store a time zone for them. Text values are returned in full, so select only the columns you need from wide tables. decimal, numeric and money values arrive from the driver as JavaScript numbers, so digits beyond about 15 to 17 significant digits are lost; CAST such a column to varchar when every digit matters.

Security model

A read-only login is the real boundary

The statement check and the rollback wrapper are extra layers. Neither can stop a login that is allowed to do more, for example through a function or a linked server, so give the server a login that can only read. Never use sa, a sysadmin login or db_owner.

-- On the server (master database)
CREATE LOGIN mcp_reader WITH PASSWORD = 'use-a-long-random-password', CHECK_POLICY = ON;

-- In each database the assistant may read
USE Sales;
CREATE USER mcp_reader FOR LOGIN mcp_reader;
ALTER ROLE db_datareader ADD MEMBER mcp_reader;  -- SELECT on every table and view
GRANT VIEW DEFINITION TO mcp_reader;             -- column defaults and MS_Description for describe_table

To hide sensitive tables or columns, DENY SELECT on them for this user.

What the statement check refuses

The check reads the query text before it is sent. Comments, 'strings', [names] and "names" are blanked out first, so words inside them never count. Then the query is refused unless:

  • its first word is SELECT or WITH (a leading ( or ; is fine),

  • no semicolon starts a second statement, and

  • none of these words appears outside comments, strings and quoted names:

Refused

Because it

INSERT UPDATE DELETE MERGE TRUNCATE INTO WRITETEXT UPDATETEXT

writes data (SELECT ... INTO creates a table)

CREATE ALTER DROP ADD GRANT REVOKE DENY

changes objects or permissions

EXEC EXECUTE

runs other code

BEGIN COMMIT ROLLBACK SAVE

controls transactions (BEGIN TRAN would leave a transaction open on a pooled connection)

ENABLE DISABLE

enables or disables triggers

SEND RECEIVE, END CONVERSATION, MOVE CONVERSATION, GET CONVERSATION

works with Service Broker

USE SET OPEN SETUSER REVERT

changes session state that would carry over to later queries on the pooled connection

DECLARE

declares variables or cursors, which a single query does not need

BACKUP RESTORE DUMP LOAD CHECKPOINT DBCC KILL RECONFIGURE SHUTDOWN

runs a server operation

RAISERROR

can write to the server error log (WITH LOG)

WAITFOR

keeps the connection busy while it waits

NEXT VALUE FOR

takes a sequence number, which a rollback does not give back

A bare END is allowed, because CASE ... END needs it.

T-SQL needs no semicolon between statements (SELECT 1 DELETE FROM t is two statements), so the check looks at every word, not only the first. A word counts only as a whole token. Letters, digits, _, @, # and $ glue characters into one name, so merge절, col1update, @delete and #insert are names and allowed. A leading digit does not glue: SQL Server reads 1UPDATE as the number 1 followed by UPDATE, and 1EUPDATE as the float 1E followed by UPDATE, so both are refused. A -- comment ends at a carriage return as well as a line feed, as it does in SQL Server.

DECLARE and SET are refused on purpose. A query here must start with SELECT or WITH, so variables are never needed, and DECLARE ... CURSOR GLOBAL would outlive the call. SET options such as SET NOEXEC ON, SET ROWCOUNT or SET TRANSACTION ISOLATION LEVEL would stay on the pooled connection and silently change later queries; SET NOEXEC ON would even stop the wrapper's rollback from running.

OPENQUERY(linked_server, 'query') is allowed when its query text passes the same check. OPENROWSET(BULK ...) (reading a file on the server) is allowed. Other OPENROWSET and OPENDATASOURCE calls open ad hoc connections and are refused; use a linked server instead.

If a column or alias happens to be named like a refused word, write it in brackets: [Disable], [Send].

The rollback wrapper

Every call runs inside a transaction that the server always rolls back, in a finally block that also runs after errors, timeouts and the row limit. If SQL Server has already rolled the transaction back itself (for example after a deadlock), that is detected and the connection goes back to the pool cleanly. So a change to data or objects that got past the check would still be undone on this server.

What it does not cover:

  • Work outside transactions. Session settings, server operations such as KILL or DBCC, and effects outside the database are not undone by a rollback. The statement check refuses these.

  • Linked servers. Reads through four-part names and OPENQUERY run fine inside the wrapper and do not turn it into an MSDTC transaction (tested on SQL Server 2022). That also means work done on the linked server is outside the local transaction, so the rollback cannot undo it there. Use a read-only login on the linked server too.

  • Sequences and identity values. A rollback does not give them back, which is why NEXT VALUE FOR is refused.

  • Memory-optimized tables. In an explicit transaction SQL Server wants an isolation level hint for them (error 41368). Add WITH (SNAPSHOT), turn on MEMORY_OPTIMIZED_ELEVATE_TO_SNAPSHOT for the database, or, as a last resort, set MSSQL_ROLLBACK_WRAPPER=false.

Limits

  • The check works on the query text. It cannot see what a view, function, CLR routine or linked server does when the query reads it.

  • OPENQUERY text is checked with T-SQL rules even when the linked server runs another database engine, which may read the text differently.

  • OPENROWSET(BULK ...) can read files on the database server when the login has the ADMINISTER BULK OPERATIONS permission. A read-only login does not have it.

  • A read can still be expensive or hold locks that block writers until it ends. MSSQL_REQUEST_TIMEOUT_MS bounds how long; pointing the server at a replica or a reporting copy avoids the problem.

  • Query results go to the assistant and to the model provider behind it. Keep data the assistant must not see out of reach of the login.

  • The password sits in your MCP client's configuration file. Protect that file like any other credential.

Troubleshooting

Symptom

What to check

Could not connect to SQL Server: Failed to connect to sql.example.com:1433 in 15000ms

Host, port and firewall. A named instance (host\INSTANCE) also needs SQL Server Browser (UDP 1434).

... self-signed certificate or certificate has expired

Install a trusted certificate on the server, or set MSSQL_TRUST_SERVER_CERTIFICATE=true on a network you trust.

Login failed for user '...'

User name and password, whether SQL Server authentication is enabled, and whether the login may open MSSQL_DATABASE.

Refused: DISABLE is not allowed ... write it as [DISABLE]

A column or alias is named like a refused word; put it in brackets.

"truncated":true

Narrow the query with TOP, WHERE or GROUP BY, or raise MSSQL_MAX_ROWS.

The query did not finish within 30000 ms and was cancelled

Narrow the query, or raise MSSQL_REQUEST_TIMEOUT_MS.

SQL Server error 41368

See memory-optimized tables under The rollback wrapper.

DeprecationWarning: Setting the TLS ServerName to an IP address in the log

Harmless. Use the host name from the server certificate in MSSQL_SERVER to avoid it.

The server is not configured: ...

A setting is missing or invalid; the message names it.

The server writes its log to stderr, which your MCP client shows in its MCP log.

Development

git clone https://github.com/ethan3011/mssql-mcp-server.git
cd mssql-mcp-server
npm install
npm test

npm test runs the unit tests (statement check, output format, settings) and starts the server over stdio without a database. To run the integration tests against a development database:

MSSQL_SERVER=sql.example.com MSSQL_USER=mcp_reader MSSQL_PASSWORD='change-me' MSSQL_DATABASE=Sales \
  npm run test:integration

They call every tool, check the row limit, a timeout and date output, and prove the rollback wrapper with #temp tables only. Every other statement is a small read.

File

Contents

src/index.js

Entry point (stdio).

src/server.js

Tool definitions.

src/guard.js

The statement check.

src/db.js

Connection pool, rollback wrapper, streaming and row limit.

src/format.js

JSON output and error messages.

src/datetimeoffset.js

Keeps the offset of datetimeoffset values, which the driver drops.

src/config.js

Environment variables.

Changelog

2.0.0

Breaking changes:

  • query_database returns compact JSON, {"columns":[...],"rows":[[...]],"rowCount":n}, instead of a pretty-printed array of row objects, and returns every result set of a batch instead of only the first.

  • Results stop at MSSQL_MAX_ROWS rows (default 200) with a notice.

  • list_tables returns schema, name and type, includes views, and takes an optional filter.

  • Dates are written as stored (see How values are written); 1.0.0 wrote every date in UTC with a Z and dropped the offset of datetimeoffset.

  • MSSQL_ENCRYPT now defaults to true and MSSQL_TRUST_SERVER_CERTIFICATE to false; 1.0.0 treated both as false unless they were set to true.

  • Requires Node.js 18.19 or later.

Security:

  • 1.0.0 only checked that the query started with SELECT, so SELECT 1; UPDATE ... and any statement after a first SELECT ran in full. 2.0.0 checks the whole query (see What the statement check refuses) and runs it in a transaction that is always rolled back. Upgrade from 1.0.0.

Added:

  • describe_table.

  • Queries that start with WITH (CTEs and WITH XMLNAMESPACES).

  • MSSQL_MAX_ROWS, MSSQL_REQUEST_TIMEOUT_MS, MSSQL_CONNECTION_TIMEOUT_MS and MSSQL_ROLLBACK_WRAPPER.

  • SQL Server error numbers and line numbers in errors.

  • Tests, and the MIT license.

Fixed:

  • A failed first connection no longer ends the process; the server connects on the first call and retries on the next.

  • An error on an idle pooled connection no longer ends the process.

  • The server version is read from package.json.

1.0.0

First release. It checked only the first word of the query.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      Provides read-only access to Microsoft SQL Server databases using Windows Authentication, enabling AI assistants to safely explore schemas and query data with built-in security controls.
      1
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables AI assistants to connect and query Microsoft SQL Server databases using natural language, executing read-only SQL queries for safe data inspection and analysis.
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables AI assistants to securely interact with Microsoft SQL Server databases to query data, inspect schemas, and retrieve metadata with read-only operations by default and optional write capabilities.
      1
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables AI assistants to explore SQL Server schemas, relationships, and execute safe SQL queries with read-only mode by default and optional write control.
      1
      MIT