sql-mcp-server
A secure MCP server for database access via FastMCP, supporting SQLite, PostgreSQL, MySQL, and MSSQL with safe-by-default SQL validation and multi-instance runtime.
README
sql-mcp-server
A secure Model Context Protocol (MCP) server that exposes database access to LLM clients via FastMCP.
Supported database providers:
- SQLite
- PostgreSQL
- MySQL
- Microsoft SQL Server (MSSQL)
Features
- Safe-by-default SQL validation middleware
- Read-only mode (
DB_READ_ONLY=true) enforced before execution - Single statement enforcement
- Forbidden keyword detection
- Granular opt-in for destructive statements (e.g. allow
DROPviaDB_ALLOW_DROP=true) - Automatic row limiting (
LIMIT/TOP) - Optional table allowlist (
DB_ALLOWED_TABLES) - Multi-instance runtime: expose several databases from a single MCP server
- MCP tools designed for schema exploration and safe querying
Project structure
src/sql_mcp_server/
main.py
config.py
errors.py
middleware/sql_validator.py
db/
tools/
Configuration
Copy .env.example to .env and update values.
Multi-instance setup
Set MCP_INSTANCES to a comma-separated list of prefixes (e.g. MCP_INSTANCES=CRM,ERP).
For every prefix, define the expected environment variables by upper-casing the prefix and
suffixing standard keys: CRM_DB_PROVIDER, CRM_DB_HOST, etc. Instance identifiers are
case-insensitive and available to tools via the instance_id parameter.
When MCP_INSTANCES is omitted, the server exposes a single default instance sourced
directly from the un-prefixed environment variables shown below.
SQLite
DB_PROVIDER=sqlite
SQLITE_PATH=./database.db
DB_READ_ONLY=true
DB_MAX_ROWS=100
PostgreSQL
DB_PROVIDER=postgres
DB_HOST=localhost
DB_PORT=5432
DB_USER=myuser
DB_PASSWORD=mypassword
DB_DATABASE=mydb
DB_READ_ONLY=true
DB_MAX_ROWS=100
MySQL
DB_PROVIDER=mysql
DB_HOST=localhost
DB_PORT=3306
DB_USER=myuser
DB_PASSWORD=mypassword
DB_DATABASE=mydb
DB_READ_ONLY=true
DB_MAX_ROWS=100
MSSQL
DB_PROVIDER=mssql
DB_HOST=localhost
DB_PORT=1433
DB_USER=myuser
DB_PASSWORD=mypassword
DB_DATABASE=mydb
DB_READ_ONLY=true
DB_MAX_ROWS=100
ℹ️ The MSSQL client applies
DB_QUERY_TIMEOUTvia the pyodbc connection timeout when provided; ensure the driver you select supports this property. ⚠️ Make sure to install a SQL Server ODBC driver (e.g.,msodbcsql17/msodbcsql18) before starting the MSSQL instance, otherwisepyodbccannot establish the connection.
Install
python -m venv .venv
.venv\\Scripts\\activate
pip install -e .
Run
sql-mcp-server
The server runs over stdio (FastMCP default) and can be wired to MCP-compatible clients.
Windsurf configuration (mcp_config.json)
Windsurf can launch this MCP server over stdio. You can configure it in:
~/.codeium/windsurf/mcp_config.json
The examples below use the "module" entrypoint (Option 2):
command: your venv Python executableargs:["-m", "sql_mcp_server.main"]
Common optional env fields
DB_READ_ONLY(optional, default:true)DB_MAX_ROWS(optional, default:100)DB_QUERY_TIMEOUT(optional, default:10seconds)DB_STATEMENT_TIMEOUT_MS(optional, default:DB_QUERY_TIMEOUT * 1000; caps statement execution time)DB_ALLOWED_TABLES(optional, comma-separated allowlist)DB_ALLOW_ALTER(optional, default:false; whentrue, the validator letsALTERstatements pass so you can evolve schemas without fully disabling keyword protection)DB_ALLOW_DROP(optional, default:false; set totrueonly when you intentionally need to runDROPstatements)ENABLE_QUERY_LOGS(optional, default:false; when enabled, SQL metadata is logged tologs/queries.logwith daily rotation)LOG_QUERY_BODIES(optional, default:false; whentrue, full SQL text is logged in addition to the hashed metadata—keep disabled in production)SQL_MCP_LOG_LEVEL(optional, default:INFO; override to reduce verbosity in production, e.g.WARNING)tokens.txt(project root) stores oneusername:token:scopesentry per line; scopes acceptr,w,a,d.
SQLite (Windsurf)
Required env fields:
DB_PROVIDER=sqliteSQLITE_PATH
{
"mcpServers": {
"sql-sqlite": {
"command": "c:\\dev\\code\\mcp\\sql_mcp_server\\.venv\\Scripts\\python.exe",
"args": ["-m", "sql_mcp_server.main"],
"disabled": false,
"env": {
"DB_PROVIDER": "sqlite",
"SQLITE_PATH": "./database.db",
"DB_READ_ONLY": "true",
"DB_MAX_ROWS": "100",
"DB_QUERY_TIMEOUT": "10",
"DB_ALLOWED_TABLES": ""
}
}
}
}
PostgreSQL (Windsurf)
Required env fields:
DB_PROVIDER=postgresDB_HOSTDB_PORT(optional, default driver-side; recommended to set)DB_USERDB_PASSWORDDB_DATABASE
{
"mcpServers": {
"sql-postgres": {
"command": "c:\\dev\\code\\mcp\\sql_mcp_server\\.venv\\Scripts\\python.exe",
"args": ["-m", "sql_mcp_server.main"],
"disabled": false,
"env": {
"DB_PROVIDER": "postgres",
"DB_HOST": "localhost",
"DB_PORT": "5432",
"DB_USER": "myuser",
"DB_PASSWORD": "mypassword",
"DB_DATABASE": "mydb",
"DB_READ_ONLY": "true",
"DB_MAX_ROWS": "100",
"DB_QUERY_TIMEOUT": "10",
"DB_ALLOWED_TABLES": ""
}
}
}
}
MySQL (Windsurf)
Required env fields:
DB_PROVIDER=mysqlDB_HOSTDB_PORT(optional, default driver-side; recommended to set)DB_USERDB_PASSWORDDB_DATABASE
{
"mcpServers": {
"sql-mysql": {
"command": "c:\\dev\\code\\mcp\\sql_mcp_server\\.venv\\Scripts\\python.exe",
"args": ["-m", "sql_mcp_server.main"],
"disabled": false,
"env": {
"DB_PROVIDER": "mysql",
"DB_HOST": "localhost",
"DB_PORT": "3306",
"DB_USER": "myuser",
"DB_PASSWORD": "mypassword",
"DB_DATABASE": "mydb",
"DB_READ_ONLY": "true",
"DB_MAX_ROWS": "100",
"DB_QUERY_TIMEOUT": "10",
"DB_ALLOWED_TABLES": ""
}
}
}
}
MSSQL (Windsurf)
Required env fields:
DB_PROVIDER=mssqlDB_HOSTDB_USERDB_PASSWORDDB_DATABASE
Optional env fields:
DB_PORT(optional; default:1433)DB_MSSQL_ODBC_DRIVER(optional; if unset the server will try:ODBC Driver 18 for SQL Server, thenODBC Driver 17 for SQL Server, thenSQL Server)DB_MSSQL_TRUST_SERVER_CERTIFICATE(optional; default:false; set totruefor local/dev when using a self-signed certificate)
{
"mcpServers": {
"sql-mssql": {
"command": "c:\\dev\\code\\mcp\\sql_mcp_server\\.venv\\Scripts\\python.exe",
"args": ["-m", "sql_mcp_server.main"],
"disabled": false,
"env": {
"DB_PROVIDER": "mssql",
"DB_HOST": "localhost",
"DB_PORT": "1433",
"DB_USER": "myuser",
"DB_PASSWORD": "mypassword",
"DB_DATABASE": "mydb",
"DB_MSSQL_ODBC_DRIVER": "ODBC Driver 17 for SQL Server",
"DB_MSSQL_TRUST_SERVER_CERTIFICATE": "true",
"DB_READ_ONLY": "true",
"DB_MAX_ROWS": "100",
"DB_ALLOWED_TABLES": ""
}
}
}
}
MCP tools
list_tables(instance_id?: str): List accessible tables for the selected instancedescribe_table(table: str, instance_id?: str): Columns for a specific tablerun_select(query: str, instance_id?: str): Execute a validated, safe SELECT queryrun_query(query: str, instance_id?: str): Execute a validated query (write statements allowed when the instance is not read-only)
When embedding the server, call sql_mcp_server.instances.shutdown_instance_registry() during teardown to close database connections cleanly.
Logging & privacy
- Log files live in
logs/and are rotated daily; they are created with0600permissions to avoid accidental exposure. - Query logs store only query length and a SHA-256 hash by default; enable them via
ENABLE_QUERY_LOGS=true, then turn onLOG_QUERY_BODIES=trueonly if you genuinely need the raw SQL for debugging. - Adjust
SQL_MCP_LOG_LEVELto reduce verbosity in production.
Authentication (API keys)
- Enable authentication by providing a
tokens.txtfile (by default located at the project root) with oneusername:token:scopesline per user. list_tablesanddescribe_tablerequire therscope.run_selectrequiresr.run_queryrequireswand will also demanda/dwhenever the statement contains ALTER or DROP operations allowed by the instance config.- Pass the token through the
api_keyparameter of each MCP tool call (or defineAPI_KEYin the client environment so FastMCP injects it automatically). - Use
python scripts/generate_api_key.py <username> --scopes rwadto append entries totokens.txt(use--fileto target another file or--stdoutto print without writing). Remove a user withpython scripts/remove_api_key.py <username>.
Security notes
- Always use a database user with the least privileges possible.
- Prefer DB-level read-only privileges in addition to middleware enforcement.
License
MIT
Recommended Servers
playwright-mcp
A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.
Magic Component Platform (MCP)
An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.
Audiense Insights MCP Server
Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.
VeyraX MCP
Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.
graphlit-mcp-server
The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.
Kagi MCP Server
An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.
E2B
Using MCP to run code via e2b.
Neon Database
MCP server for interacting with Neon Management API and databases
Exa Search
A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.
Qdrant Server
This repository is an example of how to create a MCP server for Qdrant, a vector search engine.