使用说明
使用LangChain和Milvus的MCP服务器
一个模型上下文协议(MCP)服务器实现,该服务器集成了LangChain和Milvus向量数据库,以支持智能代理工作流和语义搜索功能。
特点/特性
- MCP集成全面支持模型上下文协议,实现AI代理无缝通信
- LangChain 兼容性内置对LangChain工具和LangGraph代理的支持
- 灵活向量数据库针对不同文档类型和使用场景的可配置模式
- 多数据库支持向量数据库(Milvus)和表格数据库(MySQL)的抽象接口
- 动态模式创建支持自定义集合模式,字段可配置
- 智能搜索从自然语言查询中自动提取过滤器
- **RESTful API(Representational State Transfer(表述性状态转移)应用程序编程接口)**基于HTTP的MCP服务器,支持流式客户端
先决条件
- Python 3.12+
- Conda(推荐用于环境管理)
安装
1. 安装uv
Linux / Mac(注:此处为直接列出两个操作系统名称,无需翻译,若需解释性翻译,则可为“Linux系统 / Mac系统”)
curl -LsSf https://astral.sh/uv/install.sh | sh
Windows
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
2. 安装依赖项
uv sync
快速入门
以下是一个使用LangChain与MCP服务器的基本示例:
cd src
python main.py
from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client
from langgraph.prebuilt import create_react_agent
from langchain_mcp_adapters.tools import load_mcp_tools
async with streamablehttp_client("http://MCP_SERVER_ADDRESS:PORT/mcp/") as (read, write, _):
async with ClientSession(read, write) as session:
# Initialize the connection
await session.initialize()
# Load available tools from MCP server
tools = await load_mcp_tools(session)
# Create a reactive agent with the tools
agent = create_react_agent("openai:gpt-4.1", tools)
# Execute a query
response2 = await agent.ainvoke({
"messages": """please help find the total revenue for company: Singapore Airlines in year: 2024, you should search from vector database, the collection name is annual_report_0821"""
})
print(response2['messages'][-1].content)
配置
环境变量
创建一个 .env 在项目根目录中的文件:
# MCP Server Configuration
MCP_SERVER_HOST=localhost
MCP_SERVER_PORT=8000
# Vector Database Configuration
EMBEDDING_END_POINT=<FASTAPI_HOSTED_EMBEDDING_MODEL>
EMBEDDING_DIM=4096
DEFAULT_COLLECTION=documents
# Milvus Configuration
MILVUS_URL=localhost
MILVUS_DB_NAME=default
MILVUS_PW=your_milvus_password
# MySQL Configuration
MYSQL_HOST=localhost
MYSQL_PORT=3306
MYSQL_USER=your_mysql_user
MYSQL_PASSWORD=your_mysql_password
MYSQL_DATABASE=your_database_name
# OpenAI Configuration
OPENAI_API_KEY=your_openai_api_key_here
模式类型
该通用系统支持多种模式类型:
- 文档模式(或文档架构) (默认): 适用于各种文档类型的通用模式
- 年度报告架构/模板专门用于财务报告,支持按公司/年度筛选
- 自定义模式针对特定使用案例的用户自定义模式
使用不同的架构/模式
# Document schema (default)
vector_db = DatabaseFactory.create_vector_db(
"milvus",
collection_name="my_documents",
schema_type="document"
)
# Annual reports schema
vector_db = DatabaseFactory.create_vector_db(
"milvus",
collection_name="annual_reports",
schema_type="annual_report"
)
# Custom schema
custom_schema = SchemaFactory.create_custom_schema(
"custom_collection",
fields=[...], # Your custom fields
embedding_dim=4096
)
vector_db.set_custom_schema(custom_schema)
致谢
- 模型上下文协议 对于基础协议
- LangChain 针对AI代理框架及MCP适配器
- Milvus(米尔沃斯) 用于向量数据库功能