使用说明
MCP RAG服务器——用LangGraph校正RAG
一 MCP(模型上下文协议)服务器 这暴露了a 纠正RAG 使用LangGraph、ChromaDB和本地LLM构建的管道 LM 工作室.索引本地文档,然后通过任何兼容MCP的客户端(VS Code Copilot代理模式、Claude Desktop等)查询它们。
特性
- 5个MCP工具 —
index_folder,ask_question,find_relevant_docs,summarize_document,index_status - 纠正RAG管道 --通过LangGraph进行查询重写、块分级、幻觉检查
- 本地优先 -使用LM Studio完全脱机运行(与OpenAI兼容的API,不需要云密钥)
- 色度数据库 向量存储——持久、进程内、不需要单独的服务器
- Docker支持 --只需一个命令即可启动整个堆栈
Docker部署
先决条件
- LM Studio在主机上运行,您的模型已加载,本地服务器已启动
(“本地服务器”选项卡→ 启动服务器,默认端口
1234) - Docker桌面已安装并正在运行
开始
docker compose up --build
MCP服务器启动于 http://localhost:8000/mcp (可流式传输http)。
ChromaDB指数保存在 chroma_data 重启之间的Docker卷。
覆盖模型
若要在不编辑文件的情况下使用其他模型,请设置 LLM_MODEL 开始前:
# Windows PowerShell
$env:LLM_MODEL="your-model-identifier"; docker compose up -d
# bash / macOS / Linux
LLM_MODEL=your-model-identifier docker compose up -d
索引文档和查询
容器运行后,使用客户端的MCP工具(例如VS Code .vscode/mcp.json 指向 http://localhost:8000/mcp):
index_folder→/app/sample_docs(或任何已安装的路径)ask_question→ 询问有关索引内容的任何问题
停止
docker compose down
要同时擦除索引并重新开始,请执行以下操作:
docker compose down; docker volume rm mcp-rag_chroma_data
在容器内运行测试
docker compose exec mcp-rag pytest tests/ -v
示例查询
以下查询用于根据所包含的验证RAG管道
sample_docs/ 语料库(霍比特人+ Later_edits.txt 虚构修正案)。
项目特定覆盖(Later_edits.txt 击败基础语料库)
这些查询展示了核心RAG用例:特定于项目的文档 压倒一切的常识。
查询: What colour is Smaug?
Smaug is black with bright pink polka dots.
(source: /app/sample_docs/Later_edits.txt)
查询: Tell me about the Eagles' Leader
The Lord of the Eagles, named Kevin, leads the group. He possesses a commercial
pilot's license issued by the Misty Mountains Aviation Authority. As part of his
community service agreement, he is obligated to rescue at least one wizard per
fiscal year. On days off he drives a Toyota Camry and enjoys playing sudoku.
(source: /app/sample_docs/Later_edits.txt)
从《霍比特人》文本中检索事实
查询: What did Thorin say to Bilbo before he died?
"Farewell, good thief. I go now to the halls of waiting to sit beside my
fathers, until the world is renewed..."
"No! There is more in you of good than you know, child of the kindly West.
Some courage and some wisdom, blended in measure. If more of us valued food
and cheer and song above hoarded gold, it would be a merrier world.
But sad or merry, I must leave it now. Farewell!"
(source: Chapter_18_THE_RETURN_JOURNEY.txt)
查询: Where is the travel to goblins' caves described?
Chapter 4 — "Over Hill and Under Hill" covers the company's journey through
the Misty Mountains, their capture during a storm, and their descent into
the goblin tunnels.
(source: Chapter_04_OVER_HILL_AND_UNDER_HILL.txt)
使用调试检索 find_relevant_docs
当 ask_question 返回“信息不足”,使用 find_relevant_docs
使用更具描述性的术语来检查向量存储实际检索的内容:
# Instead of the user's question phrasing:
find_relevant_docs("travel to goblins caves") # poor recall
# Try content-rich terms:
find_relevant_docs("goblins caves mountains captured dwarves hobbit") # hits Ch.4
需求
系统要求
| 要求 | 版本 | 注释 |
|---|---|---|
| python | 3.11.x | 必需。Python 3.12+可以工作;3.13/3.14是 不支持 由于缺少用于依赖的预构建车轮 |
| LM 工作室 | 最新 | 用于在上通过与OpenAI兼容的API运行本地LLM localhost:1234 |
| Docker&Docker编写 | 最新 | 可选,用于集装箱部署 |
⚠️ 重要提示: 该项目需要 Python 3.11Python 3.13和3.14(包括自由线程)
3.14t变体)不兼容,因为密钥依赖关系(chromadb,watchfiles,fastmcp)尚未为这些版本提供预构建的轮子,需要Rust编译器从源代码构建。
Python包
所有依赖项都列在 requirements.txt:
fastmcp # MCP server framework
langchain # LLM orchestration
langchain-community
langchain-openai # LM Studio / OpenAI-compatible LLM client
langchain-ollama # Ollama LLM integration (optional / bonus embeddings)
langgraph # Corrective RAG graph engine
chromadb # Vector store (in-process, no server)
chardet # File encoding auto-detection
unstructured # Document loaders
pypdf # PDF support
python-docx # Word document support
python-dotenv # Environment variable management
pyyaml # YAML config support
pytest # Testing
pytest-asyncio
pytest-mock
安装
1.安装Python 3.11
下载自 python.org 或通过 winget:
winget install Python.Python.3.11
2.克隆存储库
git clone <repo-url>
cd mcp-rag
3.创建虚拟环境
# Windows
py -3.11 -m venv .venv
.venv\Scripts\Activate.ps1
# macOS / Linux
python3.11 -m venv .venv
source .venv/bin/activate
4.安装依赖项
pip install -r requirements.txt
5.配置LM Studio
- 下载并安装 LM 工作室
- 加载模型--此项目使用
lmstudio-community/qwen2.5-7b-instruct-1m(7B、1M令牌上下文窗口) - 在端口上启动本地服务器
1234(默认): “本地服务器”选项卡→ 启动服务器 - 验证
LLM_MODEL在src/config.py与LM Studio中显示的模型标识符匹配
服务器在中公开了与OpenAI兼容的API
http://localhost:1234/v1. 不需要API密钥-lm-studio用作占位符值。
6.(可选)配置Olama嵌入物
对于奖金嵌入任务,请安装 奥拉玛 并拉动:
ollama pull nomic-embed-text
然后设置 EMBEDDING_PROVIDER = "ollama" 在 src/config.py.
配置
所有参数都集中在 src/config.py:
| 参数 | 默认值 | 说明 |
|---|---|---|
LLM_BASE_URL |
http://localhost:1234/v1 |
LM Studio API端点 |
LLM_MODEL |
lmstudio-community/qwen2.5-7b-instruct-1m |
型号名称如LM Studio所示 |
LLM_TEMPERATURE |
0.0 |
RAG的确定性输出 |
LLM_STRIP_THINKING_TAGS |
False |
设置 True 仅适用于DeepSeek R1风格的推理模型 <think> 标签 |
CHUNK_SIZE |
1200 |
每块字符数 |
CHUNK_OVERLAP |
150 |
相邻块之间的重叠(~12%) |
CHROMA_DB_PATH |
./chroma_db |
ChromaDB持久目录 |
TOP_K |
10 |
每次检索查询返回的块 |
MAX_RETRIEVE_RETRIES |
2 |
RAG图中的最大查询扩展循环 |
MAX_GENERATE_RETRIES |
1 |
幻觉检测的最大再生尝试 |
EMBEDDING_PROVIDER |
default |
default (ChromaDB内置)或 ollama (奖金) |
切换到其他LLM后端
服务器使用OpenAI兼容 ChatOpenAI 客户端,因此任何后端
说出OpenAI API格式开箱即用-只需设置两个环境
变量:
| 后端 | LLM_BASE_URL |
LLM_MODEL |
LLM_API_KEY |
|---|---|---|---|
| LM 工作室 (默认) | http://localhost:1234/v1 |
LM Studio UI中的型号名称 | lm-studio (忽略) |
| 奥拉玛 (本地) | http://localhost:11434/v1 |
例如。 llama3.2 |
ollama (忽略) |
| 开放人工智能 | https://api.openai.com/v1 |
例如。 gpt-4o-mini |
您的OpenAI API密钥 |
| 格罗克 | https://api.groq.com/openai/v1 |
例如。 llama-3.1-70b-versatile |
您的Groq API密钥 |
| Azure OpenAI | 你的Azure端点 | 部署名称 | 你的Azure API密钥 |
本地(stdio)--通过 .env 文件或环境:
LLM_BASE_URL=http://localhost:11434/v1
LLM_MODEL=llama3.2
LLM_API_KEY=ollama
python -m src.server
Docker——通过 docker-compose.yml 或环境变量覆盖:
# docker-compose.yml environment section
LLM_BASE_URL: https://api.openai.com/v1
LLM_MODEL: gpt-4o-mini
LLM_API_KEY: sk-...
或者在命令行中不编辑文件:
# Windows PowerShell
$env:LLM_BASE_URL="https://api.openai.com/v1"
$env:LLM_MODEL="gpt-4o-mini"
$env:LLM_API_KEY="sk-..."
docker compose up -d
注意
LLM_STRIP_THINKING_TAGS: 将其设置为True仅适用于以下型号 发出<think>…</think>推理块(DeepSeek R1、QwQ)。对于所有其他 型号(GPT、Llama、Qwen2.5、Mistral)将其保留为默认值False.
用法
启动MCP服务器(stdio,本地)
python -m src.server
连接到VS代码复制代理模式
选项A--stdio(本地venv,无Docker):
添加 .vscode/mcp.json:
{
"servers": {
"mcp-rag": {
"type": "stdio",
"command": "${workspaceFolder}/.venv/Scripts/python.exe",
"args": ["-m", "src.server"],
"cwd": "${workspaceFolder}"
}
}
}
选项B——HTTP(运行Docker容器):
{
"servers": {
"mcp-rag": {
"type": "http",
"url": "http://localhost:8000/mcp"
}
}
}
可用的MCP工具
| 工具 | 说明 |
|---|---|
index_folder |
为给定文件夹路径中的所有文档建立索引 |
ask_question |
提问——触发完整的纠正RAG流程 |
find_relevant_docs |
检索查询的前k个相关块 |
summarize_document |
总结特定的索引文档 |
index_status |
显示矢量索引的当前状态 |
运行测试
当地(推荐):
pytest tests/ -v
Docker容器内部:
docker compose exec mcp-rag pytest tests/ -v
项目结构
mcp-rag/
├── .github/
│ └── copilot-instructions.md
├── src/
│ ├── server.py # FastMCP server & tool definitions
│ ├── config.py # Configuration parameters
│ ├── indexer.py # Document loading, chunking, ChromaDB
│ ├── graph.py # LangGraph Corrective RAG pipeline
│ └── prompts.py # Prompt templates
├── tests/
│ ├── test_indexer.py
│ ├── test_graph.py
│ └── test_mcp_tools.py
├── sample_docs/
│ └── Hobbit/ # Hobbit chapters split by chapter for better source attribution
├── results/
│ ├── ARCHITECTURE.md # Detailed graph & design documentation
│ └── REPORT.md # Development history & lessons learned
├── .vscode/
│ └── mcp.json # VS Code MCP client configuration
├── .venv/ # Python 3.11 virtual environment (not committed)
├── docker-compose.yml
├── Dockerfile
└── requirements.txt
建筑
看 建筑.md 以获取校正RAG图、检索策略和MCP工具设计的详细分解。
许可证
麻省理工学院
