跳到主要内容

MCP 工具接入

什么是 MCP

MCP(Model Context Protocol)是模型上下文协议,让 Agent 可以标准化地接入外部工具和服务。

安装依赖

pip install langchain-mcp-adapters mcp

远程 MCP 服务接入

高德地图 MCP 示例

from langchain_mcp_adapters.client import MultiServerMCPClient

# 配置
mcp_config = {
"amap-maps": {
"transport": "stdio",
"command": "npx",
"args": ["-y", "@amap/amap-maps-mcp-server"],
"env": {
"AMAP_MAPS_API_KEY": os.getenv("AMAP_MAPS_API_KEY")
}
}
}

# 创建客户端
client = MultiServerMCPClient(mcp_config)
tools = await client.get_tools()
print(f"成功加载 {len(tools)} 个工具: {[t.name for t in tools]}")

# 创建 Agent
agent = create_agent(llm, tools)

HTTP 传输配置

MCP_CONFIG = {
"weather": {
"transport": "streamable_http",
"url": "http://localhost:8000/mcp"
}
}

配置格式对比

特性标准 MCP 配置MultiServerMCPClient 配置
顶层结构{"mcpServers": {...}}{"server_name": {...}}
服务器配置嵌套在 stdio 字段中直接在服务器对象中
command 位置server.stdio.commandserver.command
args 位置server.stdio.argsserver.args
适用场景Claude DesktopLangChain

常用 MCP 服务器

  • @amap/amap-maps-mcp-server - 高德地图
  • @modelcontextprotocol/server-filesystem - 文件系统
  • @modelcontextprotocol/server-github - GitHub
  • @modelcontextprotocol/server-brave-search - 搜索
# 安装 MCP 服务器
npx -y @amap/amap-maps-mcp-server