sqldb-mcp-server
This server is a read-only MCP gateway to SQL databases that lets LLMs safely inspect and query data, then export or document results.
Query databases (MSSQL, PostgreSQL, MySQL) using only SELECT statements, with automatic validation and row caps.
List available databases and set/select a default database per call.
List tables and describe table schemas (columns, indexes, keys, constraints, size/row stats).
Explain a SELECT query without executing it (returns the database's estimated execution plan).
Export query results to CSV or JSON files, streaming large datasets without row limits.
Save query SQL and results as a Markdown report for test evidence.
Paginate query results via skip/take (up to 100 rows per call) and get total row counts.
Use caching, configurable timeouts, and database allow-lists (exact names or regex) for secure access.
Enables read-only SQL database access to MySQL databases, supporting SELECT queries, table listing, schema description, query explanation, and export of results to CSV/JSON/Markdown.
Enables read-only SQL database access to PostgreSQL databases, supporting SELECT queries, table listing, schema description, query explanation, and export of results to CSV/JSON/Markdown.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@sqldb-mcp-server show me the first 10 users"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
@akrym1582/sqldb-mcp-server
A read-only Model Context Protocol (MCP) server that exposes SQL database access to LLMs.
Features
Multi-database – supports MSSQL, PostgreSQL, and MySQL
Read-only – only
SELECTstatements are allowed (enforced via AST-level SQL parsing with the correct dialect per DB type)LLM-optimised – results use a compact columnar format (column list + value rows) to reduce token usage
Pagination –
skip/takeparameters with automatic cap at 100 rowsTotal-count aware – every query result includes
meta.totalCountso the LLM knows how many rows existCaching – query / schema results are cached with a configurable TTL
File export – stream query results to CSV or JSON files without a row-count limit
Markdown evidence export – save SQL and query results as a Markdown report file for test evidence
Database selection – allow exact database names and regular-expression matches, then select a database per tool call
Seven MCP tools:
listDatabases,query,listTables,describeTable,explainQuery,exportQuery,saveQueryEvidence
Related MCP server: sqlite-mcp-server
Installation
From npm (recommended)
# Install globally
npm install -g @akrym1582/sqldb-mcp-server
# Or run directly with npx (no install needed)
npx @akrym1582/sqldb-mcp-serverFrom source
git clone https://github.com/akrym1582/sqldb-mcp-server.git
cd sqldb-mcp-server
npm install
npm run buildQuick Start
# 1. Install globally
npm install -g @akrym1582/sqldb-mcp-server
# 2. Configure environment variables (see below)
export DB_TYPE=postgresql
export DB_HOST=localhost
export DB_USER=myuser
export DB_PASSWORD=mypassword
export DB_NAME=mydb
# 3. Run
sqldb-mcp-serverOr use in your MCP client configuration (e.g. Claude Desktop claude_desktop_config.json):
{
"mcpServers": {
"sqldb": {
"command": "npx",
"args": ["-y", "@akrym1582/sqldb-mcp-server"],
"env": {
"DB_TYPE": "postgresql",
"DB_HOST": "localhost",
"DB_PORT": "5432",
"DB_USER": "myuser",
"DB_PASSWORD": "mypassword",
"DB_NAME": "mydb"
}
}
}
}Environment Variables
Variable | Default | Description |
|
| Database type: |
| – | Database server hostname |
|
| Database server port (default depends on |
| – | Database username |
| – | Database password |
| – | Allowed databases: comma-separated exact names and/or JavaScript regex literals (for example |
| first allowed database | Default database when a tool call omits |
|
| Enables encrypted DB connections. MSSQL trusts the server certificate. PostgreSQL tries SSL first and falls back to plain if SSL is unavailable. MySQL uses TLS with certificate verification disabled when enabled. |
|
| Query timeout in milliseconds (used by |
|
| Export query timeout in milliseconds (used by |
|
| Cache TTL in seconds |
Default ports by DB type
| Default |
|
|
|
|
|
|
MCP Tools
Every database-aware tool accepts an optional database string. If omitted, DB_DEFAULT is used, or otherwise the first exact/matched database in DB_NAME. A requested database must match the configured allow-list; arbitrary database access is rejected.
Regular-expression entries are resolved against databases visible to the configured user. When using regex-only PostgreSQL configuration, ensure the user has a connectable maintenance database (normally the database with the same name as the user); MSSQL and MySQL can enumerate databases without selecting one.
listDatabases
List the databases available to the MCP tools and identify the current default:
[
{ "name": "app", "isDefault": true },
{ "name": "tenant_42", "isDefault": false }
]query
Execute a SELECT SQL statement.
{
"sql": "SELECT id, name FROM users WHERE active = 1",
"database": "app",
"skip": 0,
"take": 10
}Response format (compact / token-efficient):
{
"meta": { "totalCount": 42, "returnedCount": 10, "skip": 0, "take": 10 },
"columns": ["id", "name"],
"rows": [[1, "Alice"], [2, "Bob"], ...]
}listTables
List all base tables in a selected database. Pass { "database": "app" }, or omit it to use the default.
[{ "schema": "dbo", "name": "users" }, ...]describeTable
Describe a table's columns, indexes, foreign keys, check constraints, and size statistics.
{ "database": "app", "table": "dbo.users" }explainQuery
Return the estimated execution plan for a SELECT query without executing it.
{ "database": "app", "sql": "SELECT * FROM orders WHERE status = 'open'" }exportQuery
Stream a SELECT query result to a file. Designed for large datasets – there is no row-count limit and results are written directly to disk using Node.js streams.
{
"sql": "SELECT * FROM large_table",
"database": "analytics",
"filepath": "/tmp/export.csv",
"format": "csv",
"options": { "delimiter": ",", "bom": false }
}format defaults to "csv" if omitted. "json" is also supported.
CSV options (all optional):
Option | Default | Description |
|
| Column separator |
|
| String to write for |
|
| Prepend UTF-8 BOM (useful for Excel) |
JSON options (all optional):
Option | Default | Description |
|
| Indent the output JSON |
Response format:
{
"filepath": "/tmp/export.csv",
"format": "csv",
"rowCount": 50000
}The tool uses a separate, longer-lived connection pool whose requestTimeout is controlled by EXPORT_QUERY_TIMEOUT (default 300 000 ms = 5 min). Increase this value for very large exports.
saveQueryEvidence
Execute a SELECT query and save the SQL plus the returned rows as a Markdown report file for test evidence.
{
"sql": "SELECT id, name FROM users LIMIT 10",
"database": "app",
"filepath": "/tmp/query-evidence.md"
}Response format:
{
"filepath": "/tmp/query-evidence.md",
"rowCount": 10,
"previewRows": [
{ "id": 1, "name": "Alice" },
{ "id": 2, "name": "Bob" }
]
}If an error occurs, the tool returns the error message text instead of a success payload.
Development
# Clone the repository
git clone https://github.com/akrym1582/sqldb-mcp-server.git
cd sqldb-mcp-server
# Install dependencies
npm install
# Configure environment
cp .env.example .env
# Edit .env with your DB credentials
# Run in dev mode (no compile step)
npm run dev
# Or build and run
npm run build
npm start
# Run unit tests
npm testProject Structure
src/
mcp/
server.ts # MCP server entry point
tools/
query.ts # query tool
listTables.ts # listTables tool
describeTable.ts # describeTable tool
explainQuery.ts # explainQuery tool
exportQuery.ts # exportQuery tool (streaming file export)
db/
index.ts # DB adapter factory (selects adapter from DB_TYPE)
types.ts # DB interfaces (including queryStream)
adapters/
mssql.ts # Microsoft SQL Server implementation
postgresql.ts # PostgreSQL implementation (pg + pg-cursor)
mysql.ts # MySQL implementation (mysql2)
utils/
row-result.ts # Compact columnar result format
sanitize.ts # AST-based SQL read-only validation (dialect-aware)
pagination.ts # skip/take normalisation
cache.ts # TTL in-memory cache
export-writer.ts # Streaming CSV / JSON file writer
__tests__/ # Unit testsAvailable Tools
7 toolsdescribeTableA
Describe a table: returns columns (name, type, nullability, primary key, identity), indexes, foreign keys, check constraints, and table-level size/row-count statistics.
Inputs: table (required), database.
explainQueryA
Return the estimated execution plan for a SELECT SQL query without actually executing it. The response format depends on the database engine (e.g. MSSQL, PostgreSQL, MySQL) and is returned as-is from the database driver.
Inputs: sql (required), database.
exportQueryA
Execute a read-only SELECT SQL query and stream the results to a file. Supports CSV and JSON output formats. Designed for large datasets – results are streamed directly to disk without a row-count limit. CSV options: delimiter (default ','), nullValue (default ''), bom (default false). JSON options: pretty (default false). Timeout is controlled by the EXPORT_QUERY_TIMEOUT environment variable (default: 300 s).
Inputs: sql (required), filepath (required), format, options, +1 more.
listDatabasesA
List databases available to the tools. isDefault identifies the database used when database is omitted.
Inputs: no named parameters.
listTablesA
List all base tables in the database, returning their schema and name.
Inputs: database.
queryA
Execute a read-only SELECT SQL query. Returns results in a compact column/row format to reduce token usage. Results are capped at 100 rows; use skip/take for pagination. The meta.totalCount field shows the total number of matching rows.
Inputs: sql (required), skip, take, database.
saveQueryEvidenceA
Execute a read-only SELECT SQL query and save the SQL plus the results as a Markdown report file. Returns the saved file path, the total number of rows fetched, and the first 10 rows as preview data.
Inputs: sql (required), filepath (required), database.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 7 tools
Most tools have clearly distinct purposes: listing databases/tables, describing a table, explaining a query, and executing a query. query, exportQuery, and saveQueryEvidence all execute SELECT statements, but their output destinations are sufficiently different that an agent can choose correctly.
The naming is mostly consistent camelCase verb_noun style: listDatabases, listTables, describeTable, explainQuery, exportQuery, saveQueryEvidence. The single exception is query, which lacks a verb prefix but is still clear and readable.
Seven tools is a well-scoped set for a read-only SQL database MCP server. Each tool covers a distinct need without excessive overlap or unnecessary bloat.
The core read-only database workflow is well covered: discover databases, list tables, describe schema, run queries, explain query plans, and export or save results. Minor gaps such as listing views or schemas are workaroundable and do not cause dead ends.
Maintenance
Related MCP Connectors
Text-to-SQL MCP server: read-only queries on PostgreSQL, MySQL and SQL Server with your real schema
Draxlr's remote MCP server connects AI assistants to your SQL databases and dashboards. Explore schemas, run read-only queries, manage saved queries and dashboards, and export results, all with row-level security so each user sees only their own data.
Hosted SQL Server MCP server for Claude, ChatGPT and Cursor, with each action switched per account.
Query your org's data in natural language — read-only MCP access to SQL, NoSQL, files & warehouses.
Related MCP Servers
- AlicenseNot gradedqualityCmaintenanceMCP server for safely exposing SQL Server database capabilities to LLM clients, with read-only mode, security features, and observability.29MIT
- AlicenseNot gradedqualityDmaintenanceA read-only MCP server that enables LLMs to safely explore and query any SQLite database via natural language. It exposes tools for listing tables, describing schemas, and executing SELECT/WITH queries with built-in safety guards like write prevention and row limits.MIT
- AlicenseNot gradedqualityCmaintenanceAn MCP server that provides safe, read-only SQL access for AI agents to query databases (PostgreSQL, MySQL, SQLite) with schema awareness and guardrails.6 npmMIT
- FlicenseNot gradedqualityBmaintenanceA configurable, database-agnostic MCP server that enables LLMs to safely interact with SQL databases through read-only operations and schema inspection.-