MCP到LangChain/LangGraph适配器
此项目提供了一个适配器,允许您在LangChain和LangGraph应用程序中使用MCP(多模式会话过程)服务器工具。使用此适配器,您可以将MCP的工具无缝集成到您的AI应用程序管道中。
目录
- 设置MCP服务器 - 连接到MCP服务器 - 在LangChain中使用MCP工具 - 在LangGraph中使用MCP工具
- MCP适配器 - MCPToolWrapper - 工具函数
- 基本用法 - 与LangChain代理商集成 - 与LangGraph代理集成
引言
MCP到LangChain/LangGraph适配器弥合了MCP服务器和LangChain/LangGraph之间的差距,MCP服务器通过标准化的接口提供各种工具,LangChain/LangGraph是构建具有大型语言模型的应用程序的流行框架。此适配器使您能够:
- 连接到MCP服务器
- 发现可用工具
- 将MCP工具转换为与LangChain兼容的工具
- 在LangChain代理、链和LangGraph代理中使用这些工具
安装
要使用此适配器,您需要安装必要的软件包:
# If using pipenv (recommended)
pipenv install mcp langchain langchain-openai langgraph python-dotenv
# If using pip
pip install mcp langchain langchain-openai langgraph python-dotenv设置API密钥
例如,使用OpenAI模型,您需要一个OpenAI API密钥。建议的设置方式是使用 .env 文件:
- 创建一个
.env项目根目录中的文件(基于.env.example):
OPENAI_API_KEY=your_actual_api_key_here- 在代码中加载环境变量:
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()或者,您可以直接在环境或代码中设置API密钥:
import os
os.environ["OPENAI_API_KEY"] = "your_api_key_here"入门指南
设置MCP服务器
在使用适配器之前,您需要运行MCP服务器。该适配器旨在与您提供的MCP服务器脚本配合使用。
- 创建基本的MCP服务器脚本(例如。,
simple_server.py):
import mcp
from mcp.server import expose
@expose()
def add(a: int, b: int) -> int:
"""Add two numbers and return the result."""
return a + b
@expose()
def get_weather(city: str) -> str:
"""
Get the current weather for a city.
Args:
city: The name of the city to get weather for
"""
# In a real application, you'd call a weather API here
return f"Weather in {city}: Sunny +11°C"
if __name__ == "__main__":
mcp.run(transport='stdio')此示例服务器公开了两个工具:
add:取两个整数并返回它们的和get_weather:获取城市名称并返回模拟天气报告
连接到MCP服务器
适配器将自动管理与MCP服务器的连接:
from mcp_langchain_adapter import MCPAdapter
# Create an adapter instance, pointing to your MCP server script
adapter = MCPAdapter("simple_server.py")
# Initialize the connection and get the list of available tools
tools = adapter.get_tools()
# Print the available tools
print(f"Found {len(tools)} tools:")
for tool in tools:
print(f"- {tool.name}: {tool.description}")在LangChain中使用MCP工具
一旦你有了这些工具,你就可以在LangChain应用程序中使用它们:
from langchain.agents import AgentExecutor, create_react_agent
from langchain.prompts import PromptTemplate
from langchain_openai import ChatOpenAI
# Initialize the language model
llm = ChatOpenAI(model="gpt-3.5-turbo")
# Create a prompt template for the agent
template = """Answer the following questions as best you can using the provided tools.
Available tools:
{tools}
Use the following format:
Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question
Begin!
Question: {input}
Thought: """
prompt_template = PromptTemplate.from_template(template)
# Create a LangChain agent with the MCP tools
agent = create_react_agent(llm, tools, prompt_template)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
# Run the agent
result = agent_executor.invoke({"input": "What is 5 + 7?"})
print(result["output"])在LangGraph中使用MCP工具
LangGraph为构建代理提供了一种更现代、更灵活的方法。以下是如何将我们的MCP工具与LangGraph一起使用:
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage
from langgraph.prebuilt import create_react_agent
from langgraph.checkpoint.memory import MemorySaver
# Initialize the language model
llm = ChatOpenAI(model="gpt-3.5-turbo")
# Create a memory saver for conversation history
memory = MemorySaver()
# Create a LangGraph react agent with the MCP tools
agent = create_react_agent(
llm,
tools,
prompt="You are a helpful AI assistant that can use tools to solve problems.",
checkpointer=memory
)
# Create the configuration with thread ID for memory
config = {"configurable": {"thread_id": "example-thread"}}
# Run the agent with a question
result = agent.invoke(
{"messages": [HumanMessage(content="What is 5 + 7?")]},
config
)
# Get the final answer
final_answer = result["messages"][-1].content
print(final_answer)
# Continue the conversation with a follow-up question
state = memory.get("example-thread")
messages = state["messages"] + [HumanMessage(content="What's the weather in London?")]
result = agent.invoke({"messages": messages}, config)
print(result["messages"][-1].content)api参考
MCP适配器
这 MCPAdapter 类管理到MCP服务器的连接,并将MCP工具转换为LangChain工具。
构造函数
MCPAdapter(server_script_path: str, env: Dict[str, str] = None)server_script_path:要运行的MCP服务器脚本的路径env:服务器进程的可选环境变量
方法
initialize():同步初始化与MCP服务器的连接get_tools() -> List[BaseTool]:获取所有可用的LangChain工具get_tool_names() -> List[str]:获取所有可用工具的名称get_tool_by_name(name: str) -> Optional[BaseTool]:按名称获取特定工具close() -> None:清理资源(异步方法)
MCPToolWrapper
这 MCPToolWrapper 类扩展了LangChain的 BaseTool 包装MCP工具:
MCPToolWrapper(
name: str,
description: str,
server_script_path: str,
env: Optional[Dict[str, str]] = None,
args_schema: Optional[Type[BaseModel]] = None
)name:工具名称description:工具说明server_script_path:MCP服务器脚本的路径env:服务器进程的可选环境变量args_schema:用于工具参数的可选Pydantic模型
工具函数
get_langchain_tools(server_script_path: str, env: Dict[str, str] = None) -> List[BaseTool]:从MCP服务器获取LangChain工具的便利功能
例子
基本用法
以下是如何使用适配器的完整示例:
from mcp_langchain_adapter import MCPAdapter
# Create an adapter instance
adapter = MCPAdapter("simple_server.py")
# Get all tools
tools = adapter.get_tools()
# Print information about the tools
print(f"Found {len(tools)} tools:")
for tool in tools:
print(f"- {tool.name}: {tool.description}")
# Use a specific tool
add_tool = adapter.get_tool_by_name("add")
if add_tool:
result = add_tool.run({"a": 5, "b": 7})
print(f"Result of add(5, 7): {result}")
# Use another tool
weather_tool = adapter.get_tool_by_name("get_weather")
if weather_tool:
result = weather_tool.run({"city": "London"})
print(f"Result of get_weather('London'): {result}")与LangChain代理商集成
有关与LangChain代理集成的完整示例,请参阅 example_agent_integration.py 文件。
主要特点:
- 连接到MCP服务器
- 检索可用工具
- 使用工具创建LangChain代理
- 使用不同类型的查询执行代理
与LangGraph代理集成
有关与LangGraph代理集成的完整示例,请参阅 example_langgraph_integration.py 文件。
主要特点:
- 连接到MCP服务器
- 检索可用工具
- 使用工具创建LangGraph反应代理
- 使用检查点管理对话历史记录
- 使用不同类型的查询执行代理
- 演示如何流式传输代理的思维过程
故障排除
常见问题
- MCP服务器连接问题
- 确保MCP服务器脚本的路径正确 - 检查服务器脚本是否具有运行的适当权限 - 确保服务器脚本正确实现MCP协议
- 工具执行错误
- 检查工具输入格式是否正确 - 确保MCP服务器中正确定义了该工具 - 在工具响应中查找错误消息
- LangChain/LangGraph集成问题
- 验证工具是否已正确转换为LangChain格式 - 检查代理是否配置正确 - 确保将正确格式的输入传递给代理 - 对于LangGraph问题,请检查线程ID和内存配置
调试
要调试连接问题,您可以在MCP服务器脚本中添加日志记录:
import logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("mcp_server.log"),
logging.StreamHandler()
]
)
# Rest of your MCP server code...贡献
欢迎为改进适配器做出贡献!以下是您可以做出贡献的一些方式:
- 报告错误和问题
- 添加新功能或改进现有功能
- 改进文档
- 编写测试
- 分享与不同LangChain/LangGraph组件集成的示例
请按照以下步骤进行贡献:
- 分叉存储库
- 创建要素分支
- 进行更改
- 提交拉取请求

