يوفر بروتوكول سياق النموذج (MCP) طريقة موحدة لوكلاء الذكاء الاصطناعي لتوفير سياق لنماذج اللغة الكبيرة من خلال التواصل مع خدمات خارجية تُعرف بخوادم MCP.يقدم CrewAI نهجين لتكامل MCP:
مثالية لخوادم HTTPS البعيدة وتكاملات MCP المتصلة من كتالوج CrewAI:
نسخ
اسأل الذكاء الاصطناعي
from crewai import Agentagent = Agent( role="Research Analyst", goal="Research and analyze information", backstory="Expert researcher with access to external tools", mcps=[ "https://mcp.exa.ai/mcp?api_key=your_key", # External MCP server "https://api.weather.com/mcp#get_forecast", # Specific tool from server "snowflake", # Connected MCP from catalog "stripe#list_invoices" # Specific tool from connected MCP ])# MCP tools are now automatically available to your agent!
from crewai import Agent, Task, Crew# Create agent with MCP tools using string referencesresearch_agent = Agent( role="Research Analyst", goal="Find and analyze information using advanced search tools", backstory="Expert researcher with access to multiple data sources", mcps=[ "https://mcp.exa.ai/mcp?api_key=your_key&profile=your_profile", "snowflake#run_query" ])# Create taskresearch_task = Task( description="Research the latest developments in AI agent frameworks", expected_output="Comprehensive research report with citations", agent=research_agent)# Create and run crewcrew = Crew(agents=[research_agent], tasks=[research_task])result = crew.kickoff()
from crewai import Agent, Task, Crewfrom crewai.mcp import MCPServerStdio, MCPServerHTTP, MCPServerSSE# Create agent with structured MCP configurationsresearch_agent = Agent( role="Research Analyst", goal="Find and analyze information using advanced search tools", backstory="Expert researcher with access to multiple data sources", mcps=[ # Local stdio server MCPServerStdio( command="python", args=["local_server.py"], env={"API_KEY": "your_key"}, ), # Remote HTTP server MCPServerHTTP( url="https://api.research.com/mcp", headers={"Authorization": "Bearer your_token"}, ), ])# Create taskresearch_task = Task( description="Research the latest developments in AI agent frameworks", expected_output="Comprehensive research report with citations", agent=research_agent)# Create and run crewcrew = Crew(agents=[research_agent], tasks=[research_task])result = crew.kickoff()
هذا كل شيء! يتم اكتشاف أدوات MCP تلقائياً وإتاحتها لوكيلك.
mcps=[ # Full server - get all available tools "https://mcp.example.com/api", # Specific tool from server using # syntax "https://api.weather.com/mcp#get_current_weather", # Server with authentication parameters "https://mcp.exa.ai/mcp?api_key=your_key&profile=your_profile"]
اربط خوادم MCP من كتالوج CrewAI أو أحضر خوادمك الخاصة. بمجرد الاتصال في حسابك، أشر إليها بالمعرف المختصر:
نسخ
اسأل الذكاء الاصطناعي
mcps=[ # Connected MCP - get all available tools "snowflake", # Specific tool from a connected MCP using # syntax "stripe#list_invoices", # Multiple connected MCPs "snowflake", "stripe", "github"]
صُمم تكامل MCP DSL ليكون مرناً ويتعامل مع الفشل بأناقة:
نسخ
اسأل الذكاء الاصطناعي
from crewai import Agentfrom crewai.mcp import MCPServerStdio, MCPServerHTTPagent = Agent( role="Resilient Agent", goal="Continue working despite server issues", backstory="Agent that handles failures gracefully", mcps=[ # String references "https://reliable-server.com/mcp", # Will work "https://unreachable-server.com/mcp", # Will be skipped gracefully "snowflake", # Connected MCP from catalog # Structured configs MCPServerStdio( command="python", args=["reliable_server.py"], # Will work ), MCPServerHTTP( url="https://slow-server.com/mcp", # Will timeout gracefully ), ])# Agent will use tools from working servers and log warnings for failing ones
جميع أخطاء الاتصال تُعالج بأناقة:
فشل الاتصال: تُسجل كتحذيرات، ويستمر الوكيل مع الأدوات المتاحة
أخطاء المهلة الزمنية: تنتهي الاتصالات بعد 30 ثانية (قابلة للتعديل)
أخطاء المصادقة: تُسجل بوضوح للتصحيح
إعدادات غير صالحة: تُرفع أخطاء التحقق عند إنشاء الوكيل
للسيناريوهات المعقدة التي تتطلب إدارة اتصال يدوية، استخدم فئة MCPServerAdapter من crewai-tools. استخدام مدير سياق Python (تعليمة with) هو النهج الموصى به لأنه يتعامل تلقائياً مع بدء وإيقاف الاتصال بخادم MCP.
يدعم MCPServerAdapter عدة خيارات إعداد لتخصيص سلوك الاتصال:
connect_timeout (اختياري): الحد الأقصى للوقت بالثواني لانتظار إنشاء اتصال بخادم MCP. القيمة الافتراضية 30 ثانية إذا لم تُحدد. هذا مفيد بشكل خاص للخوادم البعيدة التي قد يكون لها أوقات استجابة متغيرة.
نسخ
اسأل الذكاء الاصطناعي
# Example with custom connection timeoutwith MCPServerAdapter(server_params, connect_timeout=60) as tools: # Connection will timeout after 60 seconds if not established pass
نسخ
اسأل الذكاء الاصطناعي
from crewai import Agentfrom crewai_tools import MCPServerAdapterfrom mcp import StdioServerParameters # For Stdio Server# Example server_params (choose one based on your server type):# 1. Stdio Server:server_params=StdioServerParameters( command="python3", args=["servers/your_server.py"], env={"UV_PYTHON": "3.12", **os.environ},)# 2. SSE Server:server_params = { "url": "http://localhost:8000/sse", "transport": "sse"}# 3. Streamable HTTP Server:server_params = { "url": "http://localhost:8001/mcp", "transport": "streamable-http"}# Example usage (uncomment and adapt once server_params is set):with MCPServerAdapter(server_params, connect_timeout=60) as mcp_tools: print(f"Available tools: {[tool.name for tool in mcp_tools]}") my_agent = Agent( role="MCP Tool User", goal="Utilize tools from an MCP server.", backstory="I can connect to MCP servers and use their tools.", tools=mcp_tools, # Pass the loaded tools to your agent reasoning=True, verbose=True ) # ... rest of your crew setup ...
يوضح هذا النمط العام كيفية دمج الأدوات. للحصول على أمثلة محددة مصممة لكل نوع نقل، راجع الأدلة التفصيلية أدناه.
with MCPServerAdapter(server_params, connect_timeout=60) as mcp_tools: print(f"Available tools: {[tool.name for tool in mcp_tools]}") my_agent = Agent( role="MCP Tool User", goal="Utilize tools from an MCP server.", backstory="I can connect to MCP servers and use their tools.", tools=[mcp_tools["tool_name"]], # Pass the loaded tools to your agent reasoning=True, verbose=True ) # ... rest of your crew setup ...
تمرير قائمة أسماء الأدوات إلى منشئ MCPServerAdapter.
نسخ
اسأل الذكاء الاصطناعي
with MCPServerAdapter(server_params, "tool_name", connect_timeout=60) as mcp_tools: print(f"Available tools: {[tool.name for tool in mcp_tools]}") my_agent = Agent( role="MCP Tool User", goal="Utilize tools from an MCP server.", backstory="I can connect to MCP servers and use their tools.", tools=mcp_tools, # Pass the loaded tools to your agent reasoning=True, verbose=True ) # ... rest of your crew setup ...
لاستخدام أدوات MCPServer ضمن فئة CrewBase، استخدم طريقة get_mcp_tools. يجب توفير إعدادات الخادم عبر خاصية mcp_server_params. يمكنك تمرير إعداد واحد أو قائمة من إعدادات خوادم متعددة.
نسخ
اسأل الذكاء الاصطناعي
@CrewBaseclass CrewWithMCP: # ... define your agents and tasks config file ... mcp_server_params = [ # 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}, ) ] @agent def your_agent(self): return Agent(config=self.agents_config["your_agent"], tools=self.get_mcp_tools()) # get all available tools # ... rest of your crew setup ...
عندما تكون فئة الطاقم مزينة بـ @CrewBase، تُدار دورة حياة المحول نيابة عنك:
أول استدعاء لـ get_mcp_tools() ينشئ بكسل MCPServerAdapter مشتركاً يُعاد استخدامه من قبل كل وكيل في الطاقم.
يُغلق المحول تلقائياً بعد اكتمال .kickoff() بفضل خطاف ما بعد التشغيل الضمني المحقون من @CrewBase، لذا لا حاجة للتنظيف اليدوي.
إذا لم يتم تعريف mcp_server_params، يُرجع get_mcp_tools() ببساطة قائمة فارغة، مما يسمح لنفس مسارات الكود بالعمل مع أو بدون إعداد MCP.
هذا يجعل من الآمن استدعاء get_mcp_tools() من طرق وكلاء متعددة أو تفعيل MCP بشكل انتقائي لكل بيئة.
يمكن أن تكون عمليات نقل SSE عرضة لهجمات إعادة ربط DNS إذا لم تكن مؤمنة بشكل صحيح.
لمنع ذلك:
تحقق دائماً من رؤوس Origin على اتصالات SSE الواردة للتأكد من أنها تأتي من مصادر متوقعة
تجنب ربط الخوادم بجميع واجهات الشبكة (0.0.0.0) عند التشغيل محلياً - اربط فقط بـ localhost (127.0.0.1) بدلاً من ذلك
نفّذ مصادقة مناسبة لجميع اتصالات SSE
بدون هذه الحمايات، يمكن للمهاجمين استخدام إعادة ربط DNS للتفاعل مع خوادم MCP المحلية من مواقع ويب بعيدة.لمزيد من التفاصيل، راجع وثائق أمان نقل MCP من Anthropic.
الأوليات المدعومة: حالياً، يدعم MCPServerAdapter بشكل أساسي تكييف أدوات MCP.
لا يتم دمج أوليات MCP الأخرى مثل prompts أو resources مباشرة كمكونات CrewAI من خلال هذا المحول في هذا الوقت.
معالجة المخرجات: يعالج المحول عادةً المخرجات النصية الرئيسية من أداة MCP (مثل .content[0].text). قد تتطلب المخرجات المعقدة أو متعددة الوسائط معالجة مخصصة إذا لم تتناسب مع هذا النمط.