MCP Database Server
MCP 数据库服务器
支柱: 协议、互操作性与 API
状态: 第 1 个月 - 基础
用于向 LLM 客户端公开 schema、安全查询和存储过程的 Python MCP 服务器。
问题
LLM 需要查询企业数据库,而无需获得广泛的凭据或执行破坏性 SQL 的自由。
Related MCP server: DB Insights MCP Server
MVP
使用 FastMCP 的 MCP 服务器
列出允许的 schema
只读查询
存储过程允许列表
调用审计
架构
MCP 服务器(
mcp.server.MCPServer,通过@mcp.tool()注册的工具)Schema 注册表(表/列的允许列表,
db.py)只读授权器(
sqlite3.Connection.set_authorizer,security.py)审计日志(每次工具调用的内存跟踪,
audit.py)
图表
flowchart LR
A0[MCP client] --> A1[MCP server: list_tables / describe_table / run_readonly_query]
A1 --> A2[SQLite authorizer: allowlist + read-only]
A2 --> A3[SQLite: invoices]
A1 --> A4[Audit log]技术栈
Python
mcp(Model Context Protocol 官方 SDK)SQLite(标准库中的
sqlite3,使用set_authorizer进行访问控制)unittest
Docker Compose
如何运行
使用官方 MCP SDK 进行实际实现。访问控制不使用针对 SQL 的正则表达式(容易被绕过),而是使用 SQLite 自带的 set_authorizer,它会在任何行运行之前批准或拒绝每个读取的表/列以及每种语句类型。要运行 MCP 服务器:
python3.12 -m venv .venv && source .venv/bin/activate
pip install -e .
python -m mcp_database_server # sobe o servidor MCP via stdio
python -m unittest discover -s tests测试
test_security.py:授权器阻止 INSERT/UPDATE/DELETE/DROP/ALTER、ATTACH、允许列表之外的表(例如sqlite_master)以及堆叠语句(SELECT 1; DROP TABLE ...)。test_server.py:直接调用每个工具的逻辑(无协议),包括每次调用都会生成审计事件。test_integration.py:将python -m mcp_database_server作为真正的子进程启动,并通过mcp.client.stdio+ClientSession与之通信——证明服务器确实使用 MCP 协议,而不仅仅是 Python 函数能工作。
风险与决策
SQL 注入和过度授权:通过驱动级别的
set_authorizer解决,而不是正则表达式。单个 SQLite 连接不是线程安全的;MCP 服务器将每个工具调用分派到工作线程中,因此
ServerState.lock会序列化访问(这是在实现过程中发现并修复的真实 bug,由test_integration.py覆盖)。MCP 工具向 LLM 客户端返回带有清晰消息的
ValueError,而不是泄露堆栈跟踪。
后续步骤
当数据为真实数据时,通过 SQLAlchemy 将 SQLite 替换为 PostgreSQL。
添加按客户端的身份验证/允许列表(目前任何连接的 MCP 客户端都可以访问这些工具)。
将审计日志持久化到进程之外(目前仅在内存中)。
This server cannot be deployed
Maintenance
Related MCP Connectors
Safe, read-only Postgres and MySQL access for AI agents. Audit log + column-level controls.
Query 40 databases from Claude, ChatGPT, or Cursor — on any device. Read-only, encrypted, audited.
Query your org's data in natural language — read-only MCP access to SQL, NoSQL, files & warehouses.
Read-only finance and operations controls for AI agents with evidence and safe next actions.
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceProvides secure, read-only access to Microsoft SQL Server with multi-layer protection, enabling safe query execution, schema discovery, and SQL script analysis through natural language.2-
- FlicenseNot gradedqualityDmaintenanceEnables AI assistants to query SQL databases safely with read-only access, allowing schema discovery and SELECT queries while blocking writes and DDL operations.-
- AlicenseNot gradedqualityDmaintenanceEnables LLM clients to query SQL databases via natural language with read-only, AST-validated, and capped queries, ensuring safety guarantees.2MIT
- AlicenseNot gradedqualityBmaintenanceProvides read-only access to databases for MCP-compatible AI tools, allowing schema exploration and SELECT queries without exposing credentials or risking data changes.60 npm3MIT