连接生态系统:MCP 集成
连接生态系统:MCP集成
Section titled “连接生态系统:MCP集成”AI格局正在从孤立的模型转向互联的生态系统。**模型上下文协议(MCP)**已成为这种连接性的标准,作用就像AI应用程序的“USB-C端口”。在本章中,我们将探讨如何通过将CrewAI Agent连接到外部MCP服务器来增强它们。
什么是MCP?
Section titled “什么是MCP?”MCP是一个开放标准,它使AI模型能够以标准化方式与外部数据和工具进行交互。你无需为每个数据库、文件系统或API编写自定义集成代码,而是连接到一个“MCP服务器”,该服务器将这些资源暴露为即用型工具。
CrewAI将MCP工具视为任何其他工具(如SerperDevTool或FileReadTool)。这意味着你可以立即赋予你的Agent由更广泛的MCP社区提供的能力。
将MCP服务器用作工具
Section titled “将MCP服务器用作工具”为了将CrewAI与MCP服务器连接起来,我们使用crewai_tools包。该集成抽象了握手和协议协商的复杂性,将服务器的功能呈现为CrewAI兼容工具的列表。
连接传输方式
Section titled “连接传输方式”MCP支持不同的传输机制,具体取决于你的服务器运行位置。CrewAI支持三种主要方法:
- Stdio (Standard Input/Output)(Stdio(标准输入/输出)): 最适合直接以子进程形式运行本地服务器。
- SSE (Server-Sent Events)(SSE(服务器发送事件)): 适用于实时、单向的服务器通信。
- HTTP: 连接远程Web服务的标准。
通过Stdio连接(本地)
Section titled “通过Stdio连接(本地)”这是本地开发中最常见的设置。你将MCP服务器作为命令运行,CrewAI通过标准输入和输出与它通信。以下是如何连接到本地文件系统服务器:
from crewai import Agent, Task, Crewfrom crewai_tools import from_mcp
# 导入Stdio传输类from mcp import ClientSession, StdioServerParameters
# 定义连接参数# 在此示例中,我们假设你有一个MCP服务器可执行文件server_params = StdioServerParameters( command="npx", args=["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/folder"])
# 从MCP服务器创建工具列表mcp_tools = from_mcp(server_params)
# 将这些工具分配给一个Agentresearcher = Agent( role="Researcher", goal="Analyze files in the directory", backstory="You are an expert at data analysis.", tools=mcp_tools, verbose=True)通过HTTP/SSE连接(远程)
Section titled “通过HTTP/SSE连接(远程)”如果你的MCP服务器运行在远程机器或一个不同的本地端口上,你可以通过URL连接。这对于分布式架构来说是理想的选择。
# 通过HTTP连接到远程MCP服务器remote_mcp_tools = from_mcp("http://localhost:8080/mcp")
agent = Agent( role="Remote Analyst", goal="Query the remote database", backstory="...", tools=remote_mcp_tools)连接到多个服务器
Section titled “连接到多个服务器”Agent不限于单一的真相来源。你可以聚合来自多个MCP服务器的工具,并将它们与CrewAI的原生工具结合起来。想象一个Agent可以搜索网络(原生工具)、读取本地文件(MCP Stdio)并查询远程数据库(MCP HTTP)。
from crewai_tools import SerperDevTool
search_tool = SerperDevTool()filesystem_tools = from_mcp(fs_params) # 之前已定义database_tools = from_mcp("http://db-mcp:8000")
# 将所有工具组合成一个列表agent_tools = [search_tool] + filesystem_tools + database_tools
super_agent = Agent( role="Super Connected Agent", goal="Correlate web data with internal records", backstory="You have access to everywhere.", tools=agent_tools)安全注意事项
Section titled “安全注意事项”在集成MCP时,请记住你实际上是赋予LLM对连接系统的可执行访问权限。确保你的MCP服务器配置了最小权限原则——只暴露任务所需的特定目录或数据库表。