使用说明
MCP+语言链集成演示
概述
此项目演示了如何连接 MCP(模型上下文协议)服务器 到一个 朗链代理,使LLM能够通过标准化协议使用外部工具(web获取、文件系统访问等)。
设置
安装依赖项
pip install langchain langchain-openai langchain-mcp-adapters mcp python-dotenv mcp-server-fetch
环境变量
创建一个 .env 文件:
OPENAI_API_KEY=your-key-here
跑
python mcp_langchain.py
演示结果
MCP服务器连接和工具已加载
============================================================
MCP + LangChain Integration Demo
============================================================
[1] Connecting to MCP servers...
Configured: ['fetch']
[2] Loading tools from MCP servers...
Loaded 1 tool(s):
- fetch: Fetches a URL from the internet and optionally extracts its contents as markdown
[3] Creating LangChain ReAct agent with MCP tools...
Agent ready.
使用MCP功能的代理响应
查询1-Web API检查(实际用例:调试HTTP请求)
Query: Fetch https://httpbin.org/get and tell me what headers were sent.
Agent response:
- Accept: */*
- Accept-Encoding: gzip, deflate, br, zstd
- Host: httpbin.org
- User-Agent: ModelContextProtocol/1.0
- X-Amzn-Trace-Id: Root=1-699866a7-...
查询2--Web内容摘要(实际用例:研究助理)
Query: Fetch https://httpbin.org/html and summarize the content.
Agent response:
The content is an excerpt from Herman Melville's "Moby-Dick".
It tells the mournful story of Perth, an old blacksmith...
The narrative reflects on the tragic unraveling of Perth's life.
遇到的错误和解决方案
| 错误 | 原因 | 解决方法 |
|---|---|---|
NotImplementedError: MultiServerMCPClient cannot be used as a context manager |
API于更改 langchain-mcp-adapters 0.2.x-- async with 已删除 |
已切换到 client = MultiServerMCPClient(...) + await client.get_tools() |
command not found: /tmp/mcp_demo |
@modelcontextprotocol/server-filesystem npm包与npm 9.7.1不兼容(使用 npm: 协议链接) |
已删除文件系统服务器;使用过的 mcp-server-fetch (Python)工作可靠 |
create_react_agent 弃用警告 |
langgraph.prebuilt 将其移动到 langchain.agents |
非阻塞警告;准备就绪后可以更新导入 |
关键要点
MultiServerMCPClient在v0.2.x中 不 一个上下文管理器——只需实例化和await get_tools()mcp-server-fetch(Python)作为stdio MCP服务器开箱即用- 工具转换是自动的 —
get_tools()返回LangChain兼容BaseTool物体 - 代理正确地选择了调用
fetch用于查询和解释结果的工具