MCP+LangGraph+RAG研究代理演示
此repo显示了如何 将MCP工具附加到LangGraph中的OpenAI LLM,包括a RAG MCP服务器, 并作为一个研究助理代理协调一切。
该设置有意固执己见,并受到生产启发:
- 多个MCP服务器:
- MathServer (stdio) - ResearchServer (HTTP) - RAGServer (stdio,本地文档的矢量搜索)
- LangGraph代理:
- 用途 openai:gpt-4.1 作为推理引擎。 - 通过以下方式发现所有MCP工具 MultiServerMCPClient. - 将他们与法学硕士联系起来 model.bind_tools(tools). - 通过执行工具调用 ToolNode + tools_condition.
- 一个CLI,允许您端到端地查询系统。
______________________________________________________________________
1.架构概述
在高层次上:
+---------------------------+
| ResearchServer (HTTP) |
| - search_docs() |
| - get_paper_abstract() |
+-------------+-------------+
^
|
+---------------------------+ |
| MathServer (stdio) | |
| - add() | |
| - multiply() | |
| - compound_interest() | |
+-------------+-------------+ |
^ |
| |
+-------------+-------------+ |
| RAGServer (stdio) | |
| - index_corpus() | |
| - search_corpus() | |
+-------------+-------------+ |
^ |
| |
+-----+-------------------------+----------------------------+
| MultiServerMCPClient (langchain-mcp-adapters) |
| - Connects to all MCP servers |
| - Exposes tools to LangGraph / LangChain |
+----------------------+------------------------------------+
|
v
+------+-------+
| OpenAI LLM |
| openai:gpt-4.1
+------+-------+
|
model.bind_tools(tools)
|
v
+------+----------------------------+
| LangGraph StateGraph |
| - Node: LLM |
| - Node: ToolNode(MCP tools) |
| - Edge: tools_condition |
+-------------------+---------------+
|
v
CLI / Notebook代理的行为就像 研究副驾驶 这可以:
- 通过以下方式快速提取定义和上下文
ResearchServer. - 使用以下命令运行小计算
MathServer. - 通过以下方式在您的本地文档中提供基本答案
RAGServer.
______________________________________________________________________
2.文件夹结构
mcp-langgraph-rag-agent-demo/
├─ agent/
│ ├─ __init__.py
│ └─ graph_research_agent.py # LangGraph + MCP wiring
│
├─ mcp_servers/
│ ├─ data/
│ │ ├─ 001_mcp_intro.md # Sample docs indexed by RAG
│ │ ├─ 002_security_considerations.md
│ │ └─ 003_rag_playbook.md
│ ├─ math_server.py # MCP math tools (stdio)
│ ├─ research_server.py # MCP research tools (HTTP)
│ └─ rag_server.py # MCP RAG tools (stdio)
│
├─ scripts/
│ └─ run_agent.py # CLI entrypoint
│
├─ .env.example # Template for OpenAI key
├─ requirements.txt
└─ README.md______________________________________________________________________
3.快速入门
3.1先决条件
- python 3.10+
- 用于的OpenAI API密钥
gpt-4.1(或在中更新型号名称graph_research_agent.py). - 能够安装Python依赖项(请参阅
requirements.txt).
3.2安装依赖项
git clone
cd mcp-langgraph-rag-agent-demo
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
pip install -r requirements.txt创建您的 .env:
cp .env.example .env
# Then edit .env and paste your OPENAI_API_KEY3.3启动HTTP研究MCP服务器
在 端子1:
cd mcp_servers
python research_server.py您应该看到日志,表明它正在监听 http://0.0.0.0:8000/mcp.
数学和RAG服务器由MCP客户端通过stdio自动启动,因此您可以 不 需要手动运行它们。
3.4运行LangGraph代理
在 终端2 (位于回购根目录):
python scripts/run_agent.py您应该看到:
✅ MCP + LangGraph + RAG agent is ready.
Type 'exit' or 'quit' to stop.现在聊天:
You: What is MCP and why is it useful for connecting internal tools?
You: Search our docs for security considerations and summarise three key points.
You: Use RAG to find anything about RAG Playbook and explain it simply.
You: If each query saves 3 minutes for 50 researchers per week, how many hours do we save in a year?代理将决定何时调用以下工具:
search_docs(HTTP MCP)index_corpus/search_corpus(RAG MCP)compound_interest或add/multiply(数学MCP)
______________________________________________________________________
4.MCP工具如何连接到OpenAI LLM
关键线路位于 agent/graph_research_agent.py:
from langchain_mcp_adapters.client import MultiServerMCPClient
from langgraph.prebuilt import ToolNode, tools_condition
from langgraph.graph import StateGraph, START, MessagesState
from langchain.chat_models import init_chat_model
async def build_mcp_tools():
client = MultiServerMCPClient(
{
"math": {
"command": "python",
"args": ["mcp_servers/math_server.py"],
"transport": "stdio",
},
"research": {
"url": "http://localhost:8000/mcp",
"transport": "streamable_http",
},
"rag": {
"command": "python",
"args": ["mcp_servers/rag_server.py"],
"transport": "stdio",
},
}
)
tools = await client.get_tools()
return tools
def make_llm_node(model, tools):
bound = model.bind_tools(tools)
def llm_node(state):
messages = state["messages"]
response = bound.invoke(messages)
return {**state, "messages": messages + [response]}
return llm_node
async def build_graph():
tools = await build_mcp_tools()
model = init_chat_model("openai:gpt-4.1")
builder = StateGraph(MessagesState)
builder.add_node("llm", make_llm_node(model, tools))
builder.add_node("tools", ToolNode(tools))
builder.add_edge(START, "llm")
builder.add_conditional_edges("llm", tools_condition)
builder.add_edge("tools", "llm")
return builder.compile()释义:
MultiServerMCPClient连接到 三台MCP服务器 并发现了他们的工具。tools = await client.get_tools()返回LangChain样式工具的平面列表。model.bind_tools(tools)告诉openai:gpt-4.1这些工具是可用的。ToolNode(tools)知道如何执行LLM发出的任何工具调用。tools_condition为图形布线:
- 如果LLM做到了 不 调用工具➜ end. - 如果它 做了 调用工具➜ go to ToolNode,运行它们,然后回到LLM。
______________________________________________________________________
5.详细介绍RAG MCP服务器
RAG服务器位于 mcp_servers/rag_server.py 并公开了两个工具:
index_corpus(reset: bool = False)search_corpus(query: str, top_k: int = 5)
语料库是 .md / .txt 文件下 mcp_servers/data/.
核心模式:
rag_index = RAGIndex()
@mcp.tool()
def index_corpus(reset: bool = False) -> str:
count = rag_index.build_index(reset=reset)
return f"Indexed {count} documents from {DATA_DIR}."
@mcp.tool()
def search_corpus(query: str, top_k: int = 5) -> str:
results = rag_index.search(query, top_k=top_k)
# Format into a compact text snippet for the LLM您可以替换实施 RAGIndex 与:
- FAISS、Elasticsearch或您的内部向量存储。
- 您自己的嵌入服务,而不是
sentence-transformers.
LangGraph接线 不 改变。
______________________________________________________________________
6.延长此回购
将其推向生产的一些想法:
- MCP服务器的身份验证和RBAC
- 为HTTP MCP服务器附加身份验证标头/令牌。 - 强制方法级权限(例如,谁可以调用 index_corpus).
- 每个用户的对话状态
- 添加a user_id 在该州。 - 将对话历史记录保存在数据库中,并在每个会话中重新加载。
- 结构化工具输出
- 从工具中返回JSON,并在LLM提示符中解析它。 - 在答案中明确附上引用和文档ID。
- 额外的MCP服务器
- Jira、GitHub、Databricks、内部REST API。 - 所有内容均通过同一途径访问 MultiServerMCPClient 图案。
______________________________________________________________________
7.故障排除
- ImportError:句子转换
- 安装它: pip install sentence-transformers - 或者替换掉嵌入逻辑 rag_server.py 为了你自己。
- 无法连接到研究服务器
- 确保 python mcp_servers/research_server.py 正在运行。 - 检查该端口 8000 是免费的。
- OpenAI身份验证错误
- 确认 OPENAI_API_KEY 存在于您的环境中。 - 在REPL中尝试一个简单的LangChain OpenAI调用来验证。
______________________________________________________________________
8.总结
此存储库是 模板 用于:
- 使用以下工具构建严肃的多工具代理 LangGraph.
- 通过以下方式展示这些工具 主控程序 (标准输入+HTTP)。
- 接地回答 检索增强生成 在你自己的文件。
- 保持编排干净:
model.bind_tools+ToolNode+tools_condition.
以它为起点,插入您自己的:
- 企业RAG堆栈
- 票务系统
- copula作业
- 您希望您的代理推理的任何其他内部服务。
