MCP DSL 集成
CrewAI 的 MCP DSL(领域特定语言)集成提供了连接代理与 MCP(Model Context Protocol)服务器的最简单方式。只需为代理添加一个 mcps 字段,CrewAI 就会自动处理所有复杂性。
使用 mcps 字段向代理添加 MCP 服务器:
from crewai import Agent
agent = Agent( role="Research Assistant", goal="Help with research and analysis tasks", backstory="Expert assistant with access to advanced research tools", mcps=[ "https://mcp.exa.ai/mcp?api_key=your_key&profile=research" ])
# MCP tools are now automatically available!# No need for manual connection management or tool configuration支持的引用格式
Section titled “支持的引用格式”外部 MCP 远程服务器
Section titled “外部 MCP 远程服务器”# Basic HTTPS server"https://api.example.com/mcp"
# Server with authentication"https://mcp.exa.ai/mcp?api_key=your_key&profile=your_profile"
# Server with custom path"https://services.company.com/api/v1/mcp"指定工具选择
Section titled “指定工具选择”使用 # 语法从服务器中选择特定工具:
# Get only the forecast tool from weather server"https://weather.api.com/mcp#get_forecast"
# Get only the search tool from Exa"https://mcp.exa.ai/mcp?api_key=your_key#web_search_exa"已连接的 MCP 集成
Section titled “已连接的 MCP 集成”从 CrewAI 目录连接 MCP 服务器,或者接入你自己的服务器。连接到账户后,可通过 slug 引用它们:
# Connected MCP with all tools"snowflake"
# Specific tool from a connected MCP"stripe#list_invoices"
# Multiple connected MCPsmcps=[ "snowflake", "stripe", "github"]下面是一个使用多个 MCP 服务器的完整示例:
from crewai import Agent, Task, Crew, Process
# Create agent with multiple MCP sourcesmulti_source_agent = Agent( role="Multi-Source Research Analyst", goal="Conduct comprehensive research using multiple data sources", backstory="""Expert researcher with access to web search, weather data, financial information, and academic research tools""", mcps=[ # External MCP servers "https://mcp.exa.ai/mcp?api_key=your_exa_key&profile=research", "https://weather.api.com/mcp#get_current_conditions",
# Connected MCPs from catalog "snowflake", "stripe#list_invoices", "github#search_repositories" ])
# Create comprehensive research taskresearch_task = Task( description="""Research the impact of AI agents on business productivity. Include current weather impacts on remote work, financial market trends, and recent academic publications on AI agent frameworks.""", expected_output="""Comprehensive report covering: 1. AI agent business impact analysis 2. Weather considerations for remote work 3. Financial market trends related to AI 4. Academic research citations and insights 5. Competitive landscape analysis""", agent=multi_source_agent)
# Create and execute crewresearch_crew = Crew( agents=[multi_source_agent], tasks=[research_task], process=Process.sequential, verbose=True)
result = research_crew.kickoff()print(f"Research completed with {len(multi_source_agent.mcps)} MCP data sources")工具命名与组织
Section titled “工具命名与组织”CrewAI 会自动处理工具命名,避免冲突:
# Original MCP server has tools: "search", "analyze"# CrewAI creates tools: "mcp_exa_ai_search", "mcp_exa_ai_analyze"
agent = Agent( role="Tool Organization Demo", goal="Show how tool naming works", backstory="Demonstrates automatic tool organization", mcps=[ "https://mcp.exa.ai/mcp?api_key=key", # Tools: mcp_exa_ai_* "https://weather.service.com/mcp", # Tools: weather_service_com_* "snowflake" # Tools: snowflake_* ])
# Each server's tools get unique prefixes based on the server name# This prevents naming conflicts between different MCP servers错误处理与稳定性
Section titled “错误处理与稳定性”MCP DSL 的设计目标是稳健且易用:
优雅处理服务器失败
Section titled “优雅处理服务器失败”agent = Agent( role="Resilient Researcher", goal="Research despite server issues", backstory="Experienced researcher who adapts to available tools", mcps=[ "https://primary-server.com/mcp", # Primary data source "https://backup-server.com/mcp", # Backup if primary fails "https://unreachable-server.com/mcp", # Will be skipped with warning "snowflake" # Connected MCP from catalog ])
# Agent will:# 1. Successfully connect to working servers# 2. Log warnings for failing servers# 3. Continue with available tools# 4. Not crash or hang on server failures所有 MCP 操作都内置超时:
- 连接超时:10 秒
- 工具执行超时:30 秒
- 发现超时:15 秒
# These servers will timeout gracefully if unresponsivemcps=[ "https://slow-server.com/mcp", # Will timeout after 10s if unresponsive "https://overloaded-api.com/mcp" # Will timeout if discovery takes > 15s]工具 schema 会缓存 5 分钟以提升性能:
# First agent creation - discovers tools from serveragent1 = Agent(role="First", goal="Test", backstory="Test", mcps=["https://api.example.com/mcp"])
# Second agent creation (within 5 minutes) - uses cached tool schemasagent2 = Agent(role="Second", goal="Test", backstory="Test", mcps=["https://api.example.com/mcp"]) # Much faster!只有在工具真正被使用时,才会建立工具连接:
# Agent creation is fast - no MCP connections made yetagent = Agent( role="On-Demand Agent", goal="Use tools efficiently", backstory="Efficient agent that connects only when needed", mcps=["https://api.example.com/mcp"])
# MCP connection is made only when a tool is actually executed# This minimizes connection overhead and improves startup performance与现有功能集成
Section titled “与现有功能集成”MCP 工具可与 CrewAI 的其他功能无缝协作:
from crewai.tools import BaseTool
class CustomTool(BaseTool): name: str = "custom_analysis" description: str = "Custom analysis tool"
def _run(self, **kwargs): return "Custom analysis result"
agent = Agent( role="Full-Featured Agent", goal="Use all available tool types", backstory="Agent with comprehensive tool access",
# All tool types work together tools=[CustomTool()], # Custom tools apps=["gmail", "slack"], # Platform integrations mcps=[ # MCP servers "https://mcp.exa.ai/mcp?api_key=key", "snowflake" ],