页面加载中...
LangChain 社区有 200+ 现成工具,但 MCP 生态还不能直接用它们。这篇教程教你写一个通用适配层,一行代码把任何 LangChain Tool 变成 MCP Server。
LangChain 社区工具是目前最大的 Agent 工具集合——Google Search、Wikipedia、GitHub、SQL Database……但 MCP 才是 Agent 工具调用的未来标准。与其重写,不如桥接。
核心思路:LangChain Tool 有标准接口(_invoke 方法 + 参数 Schema),MCP Tool 也有标准接口(JSON Schema 参数 + 返回值)。写一个适配层做格式转换即可。
# langchain_mcp_adapter.py from fastmcp import FastMCP from langchain_core.tools import BaseTool from typing import Type import json def tool_to_mcp(lc_tool: BaseTool, mcp_server: FastMCP) -> None: """将 LangChain Tool 注册为 MCP Tool""" # 提取参数 Schema args_schema = lc_tool.args_schema if args_schema: schema_dict = args_schema.model_json_schema() properties = schema_dict.get("properties", {}) required = schema_dict.get("required", []) else: properties = {} required = [] # 生成 MCP 工具函数 tool_name = lc_tool.name tool_desc = lc_tool.description or "No description available" async def mcp_handler(**kwargs) -> str: try: result = lc_tool.invoke(kwargs) if isinstance(result, str): return result return json.dumps(result, ensure_ascii=False, default=str) except Exception as e: return f"Error: {str(e)}" # 注册到 MCP Server mcp_server.tool(name=tool_name, description=tool_desc)(mcp_handler)
from langchain_community.tools import ( DuckDuckGoSearchRun, WikipediaQueryRun, ) from langchain_community.utilities import WikipediaAPIWrapper mcp = FastMCP("langchain-tools") # 搜索工具 search = DuckDuckGoSearchRun() tool_to_mcp(search, mcp) # Wikipedia 工具 wiki = WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper()) tool_to_mcp(wiki, mcp) if __name__ == "__main__": mcp.run()
{ "mcpServers": { "langchain-tools": { "command": "python", "args": ["langchain_mcp_adapter.py"], "env": { "GOOGLE_API_KEY": "...", "GOOGLE_CSE_ID": "..." } } } }
不需要一次性暴露所有 200+ 工具。按场景打包:
# research_tools.py RESEARCH_TOOLS = [ DuckDuckGoSearchRun(), WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper()), ArxivQueryRun(), PubMedQueryRun(), ] mcp = FastMCP("research-tools") for tool in RESEARCH_TOOLS: tool_to_mcp(tool, mcp)
google-search-results 用于 SerpAPI)ainvoke 替代 invokeAgent 站点首选部署平台,零配置部署 Next.js,全球 CDN
立即体验 →