MCP DSL 통합
MCP DSL 통합 (MCP DSL Integration)
CrewAI의 MCP DSL(Domain Specific Language) 통합은 에이전트를 MCP(Model Context Protocol) 서버에 연결하는 가장 간단한 방법이에요. 에이전트에 mcps 필드만 추가하면 CrewAI가 모든 복잡성을 자동으로 처리해 줘요. 대부분의 MCP 사용 사례에서 권장되는 접근 방식이에요. 수동 연결 관리가 필요한 고급 시나리오는 MCPServerAdapter를 참조하세요.
출처: 문서
본문
Basic Usage (기본 사용법)
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
Supported Reference Formats (지원되는 참조 형식)
External MCP Remote Servers (외부 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"
Specific Tool Selection (특정 툴 선택)
# 구문으로 서버에서 특정 툴만 선택할 수 있어요:
# 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"
Connected MCP Integrations (연결된 MCP 통합)
CrewAI 카탈로그에서 MCP 서버를 연결하거나 직접 가져올 수 있어요. 계정에서 연결한 후에는 slug로 참조하세요:
# Connected MCP with all tools
"snowflake"
# Specific tool from a connected MCP
"stripe#list_invoices"
# Multiple connected MCPs
mcps=[
"snowflake",
"stripe",
"github"
]
Complete Example (전체 예시)
여러 MCP 서버를 사용하는 전체 예시예요:
from crewai import Agent, Task, Crew, Process
# Create agent with multiple MCP sources
multi_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 task
research_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 crew
research_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")
Tool Naming and Organization (툴 네이밍과 구성)
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
Error Handling and Resilience (에러 처리와 복원력)
MCP DSL은 견고하고 사용자 친화적으로 설계됐어요.
Graceful Server Failures (우아한 서버 실패)
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
Timeout Protection (타임아웃 보호)
모든 MCP 연산에는 내장 타임아웃이 있어요:
- Connection timeout: 10 seconds
- Tool execution timeout: 30 seconds
- Discovery timeout: 15 seconds
# These servers will timeout gracefully if unresponsive
mcps=[
"https://slow-server.com/mcp", # Will timeout after 10s if unresponsive
"https://overloaded-api.com/mcp" # Will timeout if discovery takes > 15s
]
Performance Features (성능 기능)
Automatic Caching (자동 캐싱)
툴 스키마는 성능 향상을 위해 5분간 캐시돼요:
# First agent creation - discovers tools from server
agent1 = Agent(role="First", goal="Test", backstory="Test",
mcps=["https://api.example.com/mcp"])
# Second agent creation (within 5 minutes) - uses cached tool schemas
agent2 = Agent(role="Second", goal="Test", backstory="Test",
mcps=["https://api.example.com/mcp"]) # Much faster!
On-Demand Connections (온디맨드 연결)
툴 연결은 툴이 실제로 사용될 때만 수립돼요:
# Agent creation is fast - no MCP connections made yet
agent = 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
Integration with Existing Features (기존 기능과의 통합)
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"
],
verbose=True,
max_iter=15
)
Best Practices (모범 사례)
1. 가능하면 특정 툴 사용
# Good - only get the tools you need
mcps=["https://weather.api.com/mcp#get_forecast"]
# Less efficient - gets all tools from server
mcps=["https://weather.api.com/mcp"]
2. 인증을 안전하게 처리
import os
# Store API keys in environment variables
exa_key = os.getenv("EXA_API_KEY")
exa_profile = os.getenv("EXA_PROFILE")
agent = Agent(
role="Secure Agent",
goal="Use MCP tools securely",
backstory="Security-conscious agent",
mcps=[f"https://mcp.exa.ai/mcp?api_key={exa_key}&profile={exa_profile}"]
)
3. 서버 실패에 대비
# Always include backup options
mcps=[
"https://primary-api.com/mcp", # Primary choice
"https://backup-api.com/mcp", # Backup option
"snowflake" # Connected MCP fallback
]
4. 설명적인 에이전트 역할 사용
agent = Agent(
role="Weather-Enhanced Market Analyst",
goal="Analyze markets considering weather impacts",
backstory="Financial analyst with access to weather data for agricultural market insights",
mcps=[
"https://weather.service.com/mcp#get_forecast",
"stripe#list_invoices"
]
)
Troubleshooting (문제 해결)
툴이 발견되지 않는 경우(No tools discovered):
# Check your MCP server URL and authentication
# Verify the server is running and accessible
mcps=["https://mcp.example.com/mcp?api_key=valid_key"]
연결 타임아웃(Connection timeouts):
# Server may be slow or overloaded
# CrewAI will log warnings and continue with other servers
# Check server status or try backup servers
인증 실패(Authentication failures):
# Verify API keys and credentials
# Check server documentation for required parameters
# Ensure query parameters are properly URL encoded
Advanced: MCPServerAdapter
수동 연결 관리가 필요한 복잡한 시나리오에서는 crewai-tools의 MCPServerAdapter 클래스를 사용하세요. Python 컨텍스트 매니저(with 문)를 사용하는 것이 권장되며, MCP 서버와의 연결 시작·중지를 자동으로 처리해 줘요.