LangChain+Ollama+MCP服务器
将LangChain、Ollama和模型控制平面(MCP)服务器与多种智能工具相结合的强大集成。
特性
- LangChain集成:利用LangChain构建LLM应用程序
- Olama支持:使用当地Olama模型进行隐私和控制
- MCP服务器:通过以下方式实现模型控制平面 8个强大的工具:
- 计算器:执行算术运算(加、减、乘、除) - 天气:获取任何城市的天气信息(模拟数据用于演示) - 黄金价格:获取多种货币(美元、欧元、英镑、印度卢比)的实时市场黄金价格 - 电子邮件:向收件人发送主题和正文的电子邮件 - RAG(检索增强生成):上传文档并使用语义搜索进行查询 - 代码执行:通过输出捕获安全执行Python代码 - Web剪贴:从网页中提取文本和链接 - 文件操作:读取、写入、列出文件和目录
- 现代Web界面:具有深色模式和烤面包通知的漂亮响应式UI
- 交互式CLI:用户友好的命令行界面
- 示范模式:展示功能的预配置示例
- 交互式可视化:显示分步和动画流程的双选项卡web界面
- 文档智能:用于文档搜索的带矢量数据库的RAG系统
建筑
┌─────────────────────────────────────────────────────────┐
│ Main Application │
│ (main.py) │
└─────────────────┬───────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────┐
│ LangChain MCP Client │
│ (langchain_mcp_client.py) │
│ │
│ ┌──────────────┐ ┌───────────────┐ │
│ │ LangChain │◄─────────►│ MCP Wrapper │ │
│ │ + Ollama │ │ │ │
│ └──────────────┘ └───────┬───────┘ │
└────────────────────────────────────┼───────────────────┘
│
▼
┌─────────────────────────────────────────────────────────┐
│ MCP Server │
│ (mcp_server.py) │
│ │
│ ┌──────────┐ ┌────────┐ ┌─────────┐ ┌──────┐ │
│ │Calculator│ │Weather │ │GoldPrice│ │Email │ │
│ │ Tool │ │ Tool │ │ Tool │ │ Tool │ │
│ └──────────┘ └────────┘ └─────────┘ └──────┘ │
│ │
│ ┌──────────────────────────────────────────────┐ │
│ │ RAG Query Tool │ │
│ │ (Document Search & Retrieval) │ │
│ └────────────────┬─────────────────────────────┘ │
└───────────────────┼───────────────────────────────────┘
│
▼
┌────────────────────────┐
│ RAG System │
│ (rag_system.py) │
│ │
│ • Document Upload │
│ • Text Extraction │
│ • Chunking │
│ • Vector Search │
└──────────┬─────────────┘
│
▼
┌────────────────────────┐
│ ChromaDB │
│ (Vector Database) │
└────────────────────────┘先决条件
- Python 3.9+
- 奥拉玛 已安装并正在运行
- 从以下位置安装:https://ollama.ai/ - 拉一个模型: ollama pull llama3.2
安装
- 克隆存储库:
git clone
cd MCP_Server_Mahendran- 创建虚拟环境:
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate- 安装依赖项:
pip install -r requirements.txt- 确认Ollama正在运行:
ollama list用法
快速开始
运行主应用程序:
python main.py从以下选项中选择:
- 交互模式:实时提问
- 示范模式:请参阅预先配置的示例
交互模式
python main.py
# Select option 1
💬 You: What is 25 multiplied by 4?
# The assistant will use the calculator tool to compute the result
💬 You: What's the weather in Paris?
# The assistant will use the weather tool to fetch weather data
💬 You: Calculate 100 divided by 5
# Another calculation example示范模式
python main.py
# Select option 2
# Watch automated demonstrations of all features直接客户端使用
您还可以在自己的脚本中直接使用客户端:
import asyncio
from langchain_mcp_client import LangChainMCPClient
async def main():
client = LangChainMCPClient(model_name="llama3.2")
try:
await client.initialize()
result = await client.process_query("What is 15 + 27?")
print(result)
finally:
await client.cleanup()
asyncio.run(main())项目结构
MCP_Server_Mahendran/
├── main.py # Main CLI application
├── langchain_mcp_client.py # LangChain + Ollama + MCP integration
├── mcp_server.py # MCP server with 5 tools
├── rag_system.py # RAG system with ChromaDB
├── web_server.py # Flask web server
├── requirements.txt # Python dependencies
├── .gitignore # Git ignore rules
├── README.md # This file
├── RAG_README.md # Detailed RAG documentation
├── WEB_FRONTEND_README.md # Web interface documentation
├── templates/
│ └── index.html # Web frontend with RAG interface
├── visualization.html # Interactive flow visualization
├── uploads/ # Temporary upload directory
└── rag_db/ # ChromaDB vector databaseMCP工具
计算器工具
执行基本算术运算。
参数:
operation:“加”、“减”、“乘”或“除”a:第一个数字b:第二个数字
例子:
{
"tool": "calculator",
"arguments": {
"operation": "multiply",
"a": 25,
"b": 4
}
}天气工具
获取城市的天气信息(用于演示的模拟数据)。
参数:
city:城市名称(必填)units:“celsius”或“fahrenheit”(默认值:“celcius”)
例子:
{
"tool": "weather",
"arguments": {
"city": "Paris",
"units": "celsius"
}
}黄金价格工具
获取多种货币的实时市场黄金价格。
参数:
currency:“美元”、“欧元”、“英镑”或“印度卢比”(默认值:“USD”)
例子:
{
"tool": "gold_price",
"arguments": {
"currency": "USD"
}
}样本输出:
💰 Live Gold Price
────────────────────────────────
Price: USD 2,050.25 per troy ounce
24h Change: +0.75% (+USD 15.23)
Currency: USD
Updated: 2025-11-14 10:30:00
Market Status: 🟢 Open电子邮件工具
向收件人发送主题和正文的电子邮件(模拟演示)。
参数:
to:收件人电子邮件地址(必填)subject:电子邮件主题行(必填)body:电子邮件正文内容(必填)
例子:
{
"tool": "send_email",
"arguments": {
"to": "user@example.com",
"subject": "Gold Price Alert",
"body": "Current gold price is $2,050 per ounce"
}
}样本输出:
📧 Email Sent Successfully!
────────────────────────────────
To: user@example.com
Subject: Gold Price Alert
Sent: 2025-11-14 10:30:00
Message Preview:
Current gold price is $2,050 per ounce
Status: ✅ DeliveredRAG(检索增强生成)工具
使用语义相似性和自然语言查询搜索上传的文档。
参数:
query:问题或搜索查询(必填)n_results:要检索的相关文档数量(可选,默认值:3)
例子:
{
"tool": "rag_query",
"arguments": {
"query": "What does the document say about AI?",
"n_results": 3
}
}样本输出:
📚 RAG Query Results
────────────────────────────────
Query: What does the document say about AI?
Found: 3 relevant document(s)
Result #1 (Relevance: High)
────────────────────────────────
Artificial Intelligence (AI) is the simulation of human
intelligence processes by machines, especially computer systems...
Metadata: ai_guide.pdf | Length: 450 chars
────────────────────────────────
💡 Tip: You can use this information to answer your question!特征:
- 通过web界面上传文档(TXT、PDF、DOC、DOCX、JSON、MD、CSV)
- 基于向量嵌入的语义搜索
- 自动文档分块以实现更好的检索
- 相关性评分和排名
- ChromaDB矢量数据库,实现高效搜索
有关详细的RAG文档,请参阅 RAG_README.md
配置
改变Olama模型
在中编辑模型名称 main.py 或 langchain_mcp_client.py:
client = LangChainMCPClient(model_name="llama3.2") # Change to your preferred model可用型号(随附安装 ollama pull ):
- 骆驼3.2
- 骆驼3.1
- 密史脱拉风
- phi3
- 还有更多。..
添加自定义工具
要向MCP服务器添加新工具,请执行以下操作:
- 在中添加工具定义
mcp_server.py在list_tools()方法 - 将工具逻辑作为一种新方法来实现
- 在中添加工具处理程序
call_tool()方法
例子:
# In list_tools()
Tool(
name="my_custom_tool",
description="Description of what it does",
inputSchema={
"type": "object",
"properties": {
"param1": {
"type": "string",
"description": "Parameter description"
}
},
"required": ["param1"]
}
)
# Implement the tool
async def my_custom_tool(self, arguments: dict) -> list[TextContent]:
param1 = arguments.get("param1")
# Your logic here
return [TextContent(type="text", text=f"Result: {param1}")]
# In call_tool()
elif name == "my_custom_tool":
return await self.my_custom_tool(arguments)网络界面
启动Web服务器
启动支持RAG的漂亮web界面:
python web_server.py然后打开浏览器: http://localhost:5000
Web界面功能
✅ 交互式聊天
- 与AI代理实时对话
- 漂亮的渐变UI设计
- 消息历史和时间戳
✅ RAG文档上传
- 拖放文件上传
- 支持7种文件格式(TXT、PDF、DOC、DOCX、JSON、MD、CSV)
- 实时上传状态
- 数据库统计显示
✅ 工具集成
- 所有5个工具的快速操作按钮
- 带有示例的工具侧边栏
- 一键查询模板
✅ 会话管理
- 持续的对话
- 清除对话历史记录
- 每会话状态管理
有关详细的web界面文档,请参阅 WEB_FRONTEND_README.md
文档
该项目包括全面的文件:
- README.md (此文件)-主要项目文件
- RAG_README.md -完整的RAG系统指南
- 文件上传和管理 - 查询示例和最佳实践 - API文档 - 故障排除指南 - 高级使用模式
- WEB_FRONTEND_README.md -Web界面指南
- 快速启动说明 - API端点 - 自定义选项 - 部署指南
故障排除
Ollama连接问题
如果您遇到连接错误:
- 确保Ollama正在跑步:
ollama serve - 检查型号是否已安装:
ollama list - 如果需要,拉动模型:
ollama pull llama3.2
MCP服务器未启动
- 检查端口是否已在使用中
- 验证Python版本是否为3.9+
- 重新安装依赖关系:
pip install -r requirements.txt --force-reinstall
导入错误
确保您处于虚拟环境中:
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install -r requirements.txtRAG问题
未找到文档:
- 检查文档是否已上传:点击“🔄 刷新统计信息”
- 验证是否支持文件格式
- 检查服务器日志中的处理错误
上传失败:
- 确保文件小于16MB
- 检查是否支持文件扩展名
- 验证的磁盘空间
./rag_db目录
低相关性结果:
- 使用文档术语重新表述查询
- 上传更多相关文件
- 尝试请求更多结果(n_results=5)
有关RAG故障排除的详细信息,请参阅 RAG_README.md
发展
运行测试
# Add your tests here
pytest tests/代码的风格
黑色格式代码:
pip install black
black *.py贡献
- 分叉存储库
- 创建要素分支
- 进行更改
- 提交拉取请求
许可证
MIT许可证-您可以自由地将此项目用于任何目的。
致谢
支持
对于问题和疑问:
- 在GitHub上打开一个问题
- 检查上面的故障排除部分
- 查看Ollama文件:https://github.com/ollama/ollama
______________________________________________________________________
由以下材料制成❤️ 对于AI社区
