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
推荐服务器
Baidu Map
百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
Playwright MCP Server
一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。
Magic Component Platform (MCP)
一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。
Audiense Insights MCP Server
通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。
VeyraX
一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。
graphlit-mcp-server
模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。
Kagi MCP Server
一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。
e2b-mcp-server
使用 MCP 通过 e2b 运行代码。
Neon MCP Server
用于与 Neon 管理 API 和数据库交互的 MCP 服务器
Exa MCP Server
模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。