LangChain MCP Adapters 安装与配置指南
langchain-mcp-adapters 项目地址: https://gitcode.com/gh_mirrors/la/langchain-mcp-adapters
1. 项目基础介绍
LangChain MCP Adapters
是一个开源项目,它提供了一个轻量级的包装器,使得 Anthropic Model Context Protocol (MCP)
工具能够与 LangChain
和 LangGraph
兼容使用。此项目主要用于将MCP工具转换为LangChain工具,并且可以连接到多个MCP服务器并从中加载工具。
主要编程语言:Python
2. 项目使用的关键技术和框架
- MCP (Model Context Protocol): 一种用于定义和访问模型上下文的协议。
- LangChain: 一个用于构建基于语言模型的应用程序的工具链。
- LangGraph: 一个用于创建和运行智能代理的框架。
- FastMCP: 用于实现MCP服务器的库。
3. 项目安装和配置的准备工作与详细步骤
准备工作
- 确保你的系统中已经安装了Python,建议使用Python 3.x版本。
- 安装pip,Python的包管理器,用于安装项目所需的依赖。
安装步骤
步骤 1: 克隆项目仓库
首先,需要从GitHub上克隆项目仓库到本地环境。
git clone https://github.com/langchain-ai/langchain-mcp-adapters.git
步骤 2: 安装依赖
进入项目目录,使用pip安装项目所需的依赖。
cd langchain-mcp-adapters
pip install -r requirements.txt
步骤 3: 配置MCP服务器
根据项目需求,你可能需要创建自己的MCP服务器。以下是一个简单的MCP服务器示例,它提供了加法和乘法工具。
# math_server.py
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("Math")
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two numbers"""
return a + b
@mcp.tool()
def multiply(a: int, b: int) -> int:
"""Multiply two numbers"""
return a * b
if __name__ == "__main__":
mcp.run(transport="stdio")
运行这个服务器,它将在标准输入输出上监听。
步骤 4: 配置客户端连接到MCP服务器
在客户端代码中,你需要配置连接到MCP服务器的参数,并创建一个会话。
from mcp.client.stdio import stdio_client
from mcp import ClientSession, StdioServerParameters
from langchain_mcp_adapters.tools import load_mcp_tools
# 创建服务器参数
server_params = StdioServerParameters(
command="python",
args=["/path/to/math_server.py"],
transport="stdio"
)
# 连接到服务器
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
tools = await load_mcp_tools(session)
确保将 /path/to/math_server.py
替换为你的MCP服务器脚本的实际路径。
以上步骤为LangChain MCP Adapters
的基础安装和配置流程。在实际使用中,你可能需要进一步配置和自定义以满足特定需求。
langchain-mcp-adapters 项目地址: https://gitcode.com/gh_mirrors/la/langchain-mcp-adapters