rag-debug-mcp
Provides read-only diagnostic tools for PostgreSQL/PgVector RAG systems, including retrieval inspection with vector/FTS/RRF ranking, adjacent chunk context viewing, and EXPLAIN analysis of vector queries with pre-filtering.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@rag-debug-mcp Why isn’t the redline clause in the top 5 results for tenant acme?"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
rag-debug-mcp
面向 PostgreSQL / PgVector 企业级 RAG 系统的只读检索排障 MCP Server(基于 TypeScript + @modelcontextprotocol/sdk + Zod + pg)。
当企业知识库问答出现漏召回、多租户过滤后 Top-K 退化、切片边界截断表格时,开发者不再需要反复切到数据库客户端手写 SQL 与解析执行计划——在 Claude Code / Cursor / Antigravity 中直接用自然语言提问,即可透视全链路检索明细。
效果演示

Related MCP server: pg-readonly-mcp
核心架构与只读安全链路
提供的 3 个只读诊断工具(Strict MVP)
Tool 名称 | 核心用途 | 关键参数 | 典型排障收益 |
| 透视向量检索 + PG 原生 FTS / CJK 2-gram + RRF 融合排名 |
| 一眼看出目标切片是向量没召回、还是被误排在后面,以及每阶段耗时明细 ( |
| 按 |
| 自动诊断 Markdown 表格跨块劈断、首行缺失标题等切片质量问题 |
| 对带 Pre-filtering 条件的检索执行 |
| 自动检测是否命中 HNSW 索引 或退化为 |
五重只读安全护栏(Zero-Write Guarantee)
数据库原生只读事务:所有工具查询强制在
BEGIN TRANSACTION READ ONLY与SET LOCAL statement_timeout内执行,结束自动释放连接。AST / 关键字守卫 (
src/security/sqlGuard.ts):剥离注释与字符串字面量后仅允许单条SELECT/WITH/EXPLAIN,严格拦截多语句;拼接及INSERT/UPDATE/DELETE/DROP/ALTER/GRANT/pg_sleep等危险语句。标识符白名单校验:
RAG_TABLE仅允许/^[a-zA-Z_][a-zA-Z0-9_]*$/,杜绝表名注入。强制 LIMIT 上限钳制:硬限制单次扫描
top_k <= 50,防止大表扫描拖垮数据库。上下文窗口防撑爆裁剪:自动压缩空白并按
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
Available Tools
3 toolsexplain_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
Scored across 3 tools
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.
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.
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.
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
Related MCP Connectors
Deterministic safety, correctness & cost gate that vets Postgres SQL before your AI agent runs it.
Query PostgreSQL databases in plain English — LLM-generated, safety-validated SQL.
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.
Related MCP Servers
- AlicenseNot gradedqualityCmaintenanceEnables 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
- AlicenseAqualityBmaintenanceEnables 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.4MIT
- AlicenseAqualityBmaintenanceEnables 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.6MIT
- AlicenseNot gradedqualityCmaintenanceEnables natural-language exploration of PostgreSQL schemas, SQL generation and validation, query performance analysis, index recommendations, and anomaly detection with read-only security controls.MIT