Skip to main content
Glama
asd369932
by asd369932

db-query-mcp

让 AI 助手安全查询 SQLite 数据库的 MCP Server —— 只读强制、SQL 校验、结果封顶。

为什么做这个

给 AI 接数据库,最大的风险不是"查不到",而是三件事:

  1. 误写 —— 模型把 SELECT 写成 UPDATE,或者 DROP TABLE 出现在"顺手清理"里

  2. 灌爆上下文 —— 一句 SELECT * FROM orders 拉回 200 万行,对话直接崩

  3. 读到不该读的 —— 路径没限制,db_path: ../../etc/passwd 之类的穿越

这个服务把这三条做成设计约束,而不是"提示词里提醒一句"。

Related MCP server: sqlite-analyst

三条安全边界

边界

实现

绕过尝试的结果

只读

① SQL 白名单前缀(SELECT/WITH/PRAGMA/EXPLAIN)② 写操作关键字黑名单(引号感知剥注释,防 DEL/**/ETE 混淆,且不会误伤字符串)③ PRAGMA 白名单 + 拒绝赋值/括号传参 ④ 路径 URI 转义 + mode=ro ⑤ PRAGMA query_only=ON

拒绝并返回原因,不执行

结果封顶

硬上限 500 行 + 单元格超 2000 字符截断

返回 truncated: true

路径限制

库文件必须位于 DB_QUERY_MCP_ROOT(默认当前目录)内

拒绝并列出允许目录

只读为什么需要这么多层 —— 对抗性测试与逐层隔离实验的真实教训:

  • URI 注入:不转义直接拼 f"file:{path}?mode=ro" 时,文件名里的 # 会被解析成 fragment,把 ?mode=ro 整段丢弃 → 连接偷偷变成读写模式。 必须 quote() 转义路径。

  • 两层各能拦什么(逐层隔离实测,每用例全新库):

    连接配置

    journal_mode=WAL

    user_version 写

    INSERT

    仅 mode=ro

    拦

    拦

    拦

    仅 query_only

    拦不住(文件真变 WAL)

    拦

    拦

    两层叠加(本实现)

    拦

    拦

    拦

    query_only 单独拦不住 journal_mode=WAL 是 SQLite 的 pragma 特性, 这正是两层都留的原因;行为由 test_each_layer_isolation 钉住。

  • 括号传参绕过:PRAGMA user_version(123) 是 SQLite 的合法语法, 但等号检查拦不住它。只有"名字参数"类 pragma(table_info 等)才允许 带括号。

  • 注释混淆与字符串误伤:DEL/**/ETE 在 SQLite 里等于 DELETE, 校验前必须剥注释;但剥注释必须引号感知 —— 字符串里的 '--x--' 不是注释,正则直接剥会破坏合法查询。实现用双视图扫描: 执行用 cleaned(注释删、字符串留),校验用 code_only(字符串遮蔽, 数据里的 DELETE/; 不会误判)。

这些点都是先被实际绕过、修复后才写进这段文档的(见 git 历史里的 fix(security) 提交和 TestSecurityRegressions 回归测试)。

安装

pip install -e .

配置(以 Claude Desktop 为例)

{
  "mcpServers": {
    "db-query": {
      "command": "db-query-mcp",
      "env": {
        "DB_QUERY_MCP_ROOT": "/path/to/your/databases"
      }
    }
  }
}

DB_QUERY_MCP_ROOT 支持多个目录,用 : 分隔(Linux/macOS)或 ;(Windows)。

工具

query

{
  "db_path": "data/app.db",
  "sql": "SELECT id, email FROM users WHERE created_at > '2026-01-01' LIMIT 50",
  "max_rows": 50
}

返回:

{
  "columns": ["id", "email"],
  "rows": [[1, "a@example.com"]],
  "row_count": 1,
  "truncated": false,
  "max_rows": 50
}

schema

不传 table:列出全部表和视图。 传 table:返回列定义(类型/非空/默认值/主键)和建表 SQL。

推荐工作流:先 schema 看结构,再写 query —— 这也是给模型的 instructions 里写明的。

会拒绝什么

[拒绝] 只允许 SELECT / WITH / PRAGMA / EXPLAIN 开头的只读查询     # UPDATE ...
[拒绝] 检测到写操作关键字: DROP(本服务只读)                       # SELECT 1; DROP TABLE x
[拒绝] 只允许单条语句,检测到多个分号
[拒绝] 路径不在允许的根目录内。允许: /home/me/data

测试

pip install -e ".[dev]"
pytest tests/ -v

License

MIT

Available Tools

2 tools
queryB

执行只读 SQL 查询(SELECT/WITH/PRAGMA/EXPLAIN)。返回 {columns, rows, row_count, truncated}。结果默认最多 500 行。

ParametersJSON Schema
NameRequiredDescriptionDefault
sqlYes
db_pathYes
max_rowsNo

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

B3.3/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries the full burden and does disclose useful traits: read-only enforcement, the permitted statement classes, and result truncation. However it omits error/permission behavior, and its claim of a 500-row default directly conflicts with the schema's max_rows default of 200, which undermines confidence in the stated limits.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Three compact sentences with no filler; the purpose leads, followed by return shape and the row cap. Every clause adds information an agent can act on.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

An output schema exists, so the description need not explain return values, yet it spends a sentence doing so. Combined with the unaddressed db_path parameter and the conflicting row-limit figure, the definition is adequate for a simple query tool but leaves gaps an agent would have to guess at.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must compensate for all three parameters (sql, db_path, max_rows). It says nothing about what db_path should contain or the SQL dialect/constraints, and its only parameter-adjacent claim (500-row default) contradicts the schema default of 200.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

States a specific verb and resource ('执行只读 SQL 查询') and narrows scope with an explicit statement whitelist (SELECT/WITH/PRAGMA/EXPLAIN), which is enough to separate it from the sibling schema tool. It stops short of explicitly naming the alternative, but the operation is unambiguous.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The allowed statement types imply when the tool applies (read-only data retrieval) and implicitly exclude writes, but there is no explicit when-to-use, when-not-to-use, or routing against the sibling 'schema' tool. Usage is inferable rather than stated.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

schemaC

列出数据库中的表和视图(schema 工具的一部分)。

ParametersJSON Schema
NameRequiredDescriptionDefault
tableNo
db_pathYes

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

C2.7/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full disclosure burden, yet it says nothing about the operation being read-only, whether results are paginated or truncated, or how the optional 'table' parameter alters behavior. It only restates the visible listing purpose, leaving the behavioral profile essentially empty.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness3/5

Is the description appropriately sized, front-loaded, and free of redundancy?

It is a single short sentence with the action front-loaded, which is efficient. However, the parenthetical '(part of the schema tool)' adds no information and consumes part of an already minimal description.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

An output schema exists, so return values need not be described, and the tool is a simple two-parameter read. Still, with no annotations and zero schema description coverage, the definition leaves parameter behavior and usage relative to 'query' unexplained, which is thin for even a simple discovery tool.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0% for both parameters, so the description must compensate and does not: neither 'db_path' nor the optional 'table' (default empty string) is explained, and it is unclear whether passing 'table' filters, scopes, or changes the output. This leaves an agent guessing about a required parameter.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description states a concrete verb+resource: listing the database's tables and views. It is clear what the tool returns, but it never contrasts itself with the sibling 'query' tool, so an agent must infer the read-only discovery role on its own. The parenthetical '(part of the schema tool)' is redundant self-reference rather than differentiation.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

There is no statement of when to call this tool versus the sibling 'query', no prerequisites, and no guidance on the relationship between the two. The only contextual hint, 'part of the schema tool', describes the tool itself rather than when to use it.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

  1. 2 tool updatesv0.1.0
    • First observedquery
    • First observedschema

TDQS

B3.1/5.0

Scored across 2 tools

Disambiguation5/5

The two tools have clearly distinct purposes: query executes read-only SQL, while schema lists tables and views. There is no overlap or ambiguity between them.

Naming Consistency3/5

"query" and "schema" are both simple lowercase single words, but one is an action verb and the other a resource noun, so they do not follow a consistent verb_noun pattern. The convention is mixed yet still readable.

Tool Count3/5

Two tools is quite thin for a database query server. The core operations are present, but many auxiliary capabilities (e.g., describe table, list databases) are missing.

Completeness3/5

The surface covers running read-only queries and listing tables/views, but lacks structured schema inspection (column types, keys) and other common database operations. Users can work around via PRAGMA queries, but it's a notable gap.

Maintenance

ActivityMaintained
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    D
    maintenance
    Enables AI assistants to explore and query SQLite databases through read-only tools, with defense-in-depth sandboxing preventing any data modifications.
    MIT
  • F
    license
    A
    quality
    C
    maintenance
    Enables AI agents to safely explore and query a SQLite database in read-only mode, allowing them to inspect schema and run analytical SQL queries without risking data modification.
    3
    -
  • F
    license
    A
    quality
    B
    maintenance
    Enables AI assistants to query SQLite databases using plain language, with strict read-only enforcement and column-level access control to prevent damage or unauthorized data reads.
    4
    -