Skip to main content
Glama
oliverhubtech-source

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 客户端都可以访问这些工具)。

  • 将审计日志持久化到进程之外(目前仅在内存中)。

Related MCP Connectors

Related MCP Servers

  • F
    license
    Not graded
    quality
    D
    maintenance
    Provides 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
    -
  • F
    license
    Not graded
    quality
    D
    maintenance
    Enables AI assistants to query SQL databases safely with read-only access, allowing schema discovery and SELECT queries while blocking writes and DDL operations.
    -
  • A
    license
    Not graded
    quality
    D
    maintenance
    Enables LLM clients to query SQL databases via natural language with read-only, AST-validated, and capped queries, ensuring safety guarantees.
    2
    MIT
  • A
    license
    Not graded
    quality
    B
    maintenance
    Provides read-only access to databases for MCP-compatible AI tools, allowing schema exploration and SELECT queries without exposing credentials or risking data changes.
    60 npm
    3
    MIT