Skip to main content
Glama

rag-debug-mcp

面向 PostgreSQL / PgVector 企业级 RAG 系统的只读检索排障 MCP Server(基于 TypeScript + @modelcontextprotocol/sdk + Zod + pg)。

CI License: MIT Node.js

当企业知识库问答出现漏召回、多租户过滤后 Top-K 退化、切片边界截断表格时,开发者不再需要反复切到数据库客户端手写 SQL 与解析执行计划——在 Claude Code / Cursor / Antigravity 中直接用自然语言提问,即可透视全链路检索明细。


效果演示

rag-debug-mcp 排障演示


Related MCP server: pg-readonly-mcp

核心架构与只读安全链路

架构图


提供的 3 个只读诊断工具(Strict MVP)

Tool 名称

核心用途

关键参数

典型排障收益

inspect_retrieval

透视向量检索 + PG 原生 FTS / CJK 2-gram + RRF 融合排名

query, top_k(1-20), tenant_id, collection_name, doc_status, rrf_k

一眼看出目标切片是向量没召回、还是被误排在后面,以及每阶段耗时明细 (embed_ms / vector_ms / keyword_ms)

view_chunk_context

按 chunk_id 查看同版本前后相邻切片窗口

chunk_id, window(0-5), tenant_id

自动诊断 Markdown 表格跨块劈断、首行缺失标题等切片质量问题

explain_vector_query

对带 Pre-filtering 条件的检索执行 EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)

query, tenant_id, collection_name, top_k(1-50), analyze

自动检测是否命中 HNSW 索引 或退化为 Seq Scan,统计 rows_removed_by_filter 并给出 hnsw.iterative_scan 调优建议


五重只读安全护栏(Zero-Write Guarantee)

  1. 数据库原生只读事务:所有工具查询强制在 BEGIN TRANSACTION READ ONLY 与 SET LOCAL statement_timeout 内执行,结束自动释放连接。

  2. AST / 关键字守卫 (src/security/sqlGuard.ts):剥离注释与字符串字面量后仅允许单条 SELECT / WITH / EXPLAIN,严格拦截多语句 ; 拼接及 INSERT/UPDATE/DELETE/DROP/ALTER/GRANT/pg_sleep 等危险语句。

  3. 标识符白名单校验:RAG_TABLE 仅允许 /^[a-zA-Z_][a-zA-Z0-9_]*$/,杜绝表名注入。

  4. 强制 LIMIT 上限钳制:硬限制单次扫描 top_k <= 50,防止大表扫描拖垮数据库。

  5. 上下文窗口防撑爆裁剪:自动压缩空白并按 RAG_MAX_SNIPPET_CHARS(默认 280)裁剪长文本片段,保留原文长度元数据。


1 分钟快速接入(Claude Code / Cursor / Antigravity)

git clone https://github.com/smileVgamer/rag-debug-mcp.git
cd rag-debug-mcp
npm install && npm run build

在客户端的 MCP 配置文件(如 .mcp.json / mcp_config.json)加入:

{
  "mcpServers": {
    "rag-debug-mcp": {
      "command": "node",
      "args": ["/abs/path/to/rag-debug-mcp/dist/index.js"],
      "env": {
        "DATABASE_URL": "postgres://postgres:<your-password>@127.0.0.1:5432/xwagent",
        "RAG_TABLE": "t_knowledge_vector",
        "EMBEDDING_API_URL": "https://dashscope.aliyuncs.com/compatible-mode/v1/embeddings",
        "EMBEDDING_API_KEY": "${EMBEDDING_API_KEY}",
        "EMBEDDING_MODEL": "text-embedding-v4",
        "EMBEDDING_DIMENSIONS": "1536"
      }
    }
  }
}

提示:若未设置 EMBEDDING_API_KEY,服务会自动切换至 deterministic_fallback 模式生成归一化向量,便于纯离线跑通结构诊断与 EXPLAIN 索引校验。


一键本地 Demo 环境(无需外部 Key)

项目自带独立 Docker PgVector 容器(端口 5433,不与本地 5432 冲突)与种子数据脚本:

docker compose -f docker-compose.demo.yml up -d
npm run build
DATABASE_URL=postgres://postgres:postgres@127.0.0.1:5433/rag_demo npm run seed:demo

真实联调输出样例(源自真实 Stdio 会话)

TOOLS: inspect_retrieval, view_chunk_context, explain_vector_query
INSPECT_RETRIEVAL: mode=remote_api hits=5 top1=2105345454081384448 (LEG_合同起草与审批管理办法_V2.3.md) rrf=0.093074 total_ms=394
VIEW_CHUNK_CONTEXT: found=true chunks=2 diagnostics=[]
EXPLAIN_VECTOR_QUERY: root=Limit hnsw=false exec_ms=0.36 indexes=[]

在真实法务条款排查案例中,chunk_index=2(仅在附则顺带提及“红线条款”)在单路向量排第 1(0.6351),而包含完整五类红线条款的 chunk_index=0 在单路向量仅排第 2(0.6059);借助 inspect_retrieval 可清晰验证 PG FTS + CJK 2-gram(Rank 1)如何通过 RRF 将权威切片拉升至第一名(rrf=0.093074)。


本地开发与校验命令

npm run lint           # ESLint 检查
npm run typecheck      # TypeScript strict 类型校验
npm run test:coverage  # Vitest 单元测试 + MCP InMemoryTransport 协议测试
npm run build          # 编译输出至 dist/

License

MIT

Available Tools

3 tools
explain_vector_queryExplain PgVector Query PlanA

在只读事务中对带 Pre-filtering 条件的向量检索 SQL 执行 EXPLAIN ANALYZE(FORMAT JSON),解析是否命中 HNSW 索引、过滤淘汰行数与缓存块命中,给出针对性索引调优建议。

Inputs: query (required), top_k, analyze, tenant_id, +2 more.

inspect_retrievalInspect Hybrid Retrieval & RRFA

只读排查 PostgreSQL/PgVector 企业级 RAG 检索链路:对比单路向量检索分数与关键词/FTS 分数、展示 RRF 融合排名及多租户 Pre-filtering 结果和耗时,定位漏召回或排序偏低问题。

Inputs: query (required), rrf_k, top_k, tenant_id, +2 more.

view_chunk_contextView Chunk Neighbor ContextB

根据 chunk_id 只读查看同一文档版本号内前后相邻窗口切片,并自动诊断 Markdown 表格跨块劈断、段落截断或标题层级缺失等切片边界问题。

Inputs: chunk_id (required), window, tenant_id.

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    A3.9/5.0

    Scored across 3 tools

    Disambiguation5/5

    Each tool targets a clearly distinct concern: retrieval scoring/fusion diagnostics, chunk-boundary context inspection, and SQL query-plan analysis. An agent can easily choose between them based on whether the problem is recall/ranking, chunking, or index performance.

    Naming Consistency5/5

    All three names follow a consistent snake_case verb_object pattern (inspect_retrieval, view_chunk_context, explain_vector_query). No convention mixing or vague verbs.

    Tool Count4/5

    Three tools is on the lean side but each covers a distinct, necessary step in a focused read-only RAG debugging workflow. The scope is narrow enough that this is reasonable rather than padding.

    Completeness4/5

    The core debugging loop is covered: diagnose retrieval scores, inspect chunk boundaries, and analyze the query plan. Minor gaps exist (e.g., no way to list documents or discover chunk_ids without another tool), but agents can work around these via inspect_retrieval output.

    Maintenance

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables agents to safely inspect a PostgreSQL database read-only: discovering schemas and tables, running guarded SELECT/EXPLAIN queries, and getting plan summaries with index suggestions. Access is constrained by schema allowlists, denied-column redaction, row caps, and a JSON-lines audit trail.
      MIT
    • A
      license
      A
      quality
      B
      maintenance
      Enables AI assistants to discover allowed PostgreSQL schemas, run parameterized SELECT queries, and inspect query plans safely through parser-checked read-only transactions, timeouts, row caps, and role-based access controls.
      4
      MIT
    • A
      license
      A
      quality
      B
      maintenance
      Enables AI assistants to explore PostgreSQL schemas and run safe, read-only queries in plain English. It applies SQL validation, row limits, and read-only sessions to prevent writes and unsafe operations.
      6
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables natural-language exploration of PostgreSQL schemas, SQL generation and validation, query performance analysis, index recommendations, and anomaly detection with read-only security controls.
      MIT