连接到多个 MCP 服务器
crewai-tools 中的 MCPServerAdapter 允许你同时连接到多个 MCP 服务器。当你的代理需要访问分布在不同服务或环境中的工具时,这很有用。适配器会聚合所有指定服务器的工具,并将它们提供给你的 CrewAI 代理。
要连接到多个服务器,你需要向 MCPServerAdapter 提供一个服务器参数字典列表。列表中的每个字典都应定义一个 MCP 服务器的参数。
列表中每个服务器支持的传输类型包括 stdio、sse 和 streamable-http。
from crewai import Agent, Task, Crew, Processfrom crewai_tools import MCPServerAdapterfrom mcp import StdioServerParameters # Needed for Stdio example
# Define parameters for multiple MCP serversserver_params_list = [ # Streamable HTTP Server { "url": "http://localhost:8001/mcp", "transport": "streamable-http" }, # SSE Server { "url": "http://localhost:8000/sse", "transport": "sse" }, # StdIO Server StdioServerParameters( command="python3", args=["servers/your_stdio_server.py"], env={"UV_PYTHON": "3.12", **os.environ}, )]
try: with MCPServerAdapter(server_params_list) as aggregated_tools: print(f"Available aggregated tools: {[tool.name for tool in aggregated_tools]}")
multi_server_agent = Agent( role="Versatile Assistant", goal="Utilize tools from local Stdio, remote SSE, and remote HTTP MCP servers.", backstory="An AI agent capable of leveraging a diverse set of tools from multiple sources.", tools=aggregated_tools, # All tools are available here verbose=True, )
... # Your other agent, tasks, and crew code here
except Exception as e: print(f"Error connecting to or using multiple MCP servers (Managed): {e}") print("Ensure all MCP servers are running and accessible with correct configurations.")使用上下文管理器(with 语句)时,MCPServerAdapter 会负责配置好所有 MCP 服务器连接的生命周期(启动和停止)。这简化了资源管理,并确保在上下文退出时所有连接都被正确关闭。