rag-debug-mcp
# rag-debug-mcp
面向 **PostgreSQL / PgVector** 企业级 RAG 系统的**只读检索排障 MCP Server**(基于 TypeScript + `@modelcontextprotocol/sdk` + `Zod` + `pg`)。
[](https://github.com/smileVgamer/rag-debug-mcp/actions/workflows/ci.yml)
[](./LICENSE)
[](https://nodejs.org/)
当企业知识库问答出现**漏召回、多租户过滤后 Top-K 退化、切片边界截断表格**时,开发者不再需要反复切到数据库客户端手写 SQL 与解析执行计划——在 **Claude Code / Cursor / Antigravity** 中直接用自然语言提问,即可透视全链路检索明细。
---
## 效果演示

---
## 核心架构与只读安全链路

---
## 提供的 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)
```bash
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`)加入:
```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` 冲突)与种子数据脚本:
```bash
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 会话)
```text
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`)。
---
## 本地开发与校验命令
```bash
npm run lint # ESLint 检查
npm run typecheck # TypeScript strict 类型校验
npm run test:coverage # Vitest 单元测试 + MCP InMemoryTransport 协议测试
npm run build # 编译输出至 dist/
```
## License
[MIT](./LICENSE)
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.