1. 主流LLM Agents开发框架概述
在当今AI技术快速发展的背景下,大型语言模型(LLM)的应用开发已经成为技术热点。作为开发者,选择合适的开发框架可以事半功倍。本文将深入分析8种主流的LLM Agents开发框架,并重点介绍它们与MCP Server的集成方法。
提示:MCP Server是一种通用的工具调用协议,它允许LLM Agent通过标准化接口访问各种外部工具和服务,极大扩展了Agent的能力边界。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 8大框架详解与MCP集成方案
2.1 OpenAI Agents SDK
OpenAI官方推出的轻量级Agent开发框架,源自内部实验项目Swarm。其特点是简单易用、专注核心功能,支持转交(Handoffs)和护栏(Guardrails)等特色功能。
集成MCP Server的关键步骤:
- 创建MCP Server实例
- 将Server实例传入Agent构造函数
- 运行Agent并自动调用工具
python复制import asyncio, os
from agents import Agent, Runner, AsyncOpenAI, OpenAIChatCompletionsModel, RunConfig
from agents.mcp import MCPServerStdio
async def main():
search_server = MCPServerStdio(
params={
"command": "npx",
"args": ["-y", "@mcptools/mcp-tavily"],
"env": {**os.environ}
}
)
await search_server.connect()
agent = Agent(
name="助手Agent",
instructions="你是一个具有网页搜索能力的助手,必要时使用搜索工具获取信息。",
mcp_servers=[search_server],
)
result = await Runner.run(agent, "Llama4.0发布了吗?",run_config=RunConfig(tracing_disabled=True))
print(result.final_output)
await search_server.cleanup()
if __name__ == "__main__":
asyncio.run(main())
注意事项:
- 远程MCP Server可设置cache_tools_list=True启用工具列表缓存
- 调用invalidate_tools_cache()手动使缓存失效
2.2 LangGraph
来自LangChain的强大框架,将任务过程建模为有状态的Graph结构,适合构建复杂Agentic系统。
集成特点:
- 使用MultiServerMCPClient支持多Server连接
- 通过get_tools()方法获取工具集
- 可结合LangGraph的Graph结构精确控制工具调用时机
python复制import asyncio, os
from langchain_mcp_adapters.client import MultiServerMCPClient
from langchain_core.messages import SystemMessage, HumanMessage
from langchain_openai import ChatOpenAI
from dotenv import load_dotenv
from langgraph.prebuilt import create_react_agent
load_dotenv()
model = ChatOpenAI(model="gpt-4o-mini")
async def run_agent():
async with MultiServerMCPClient(
{
"tavily": {
"command": "npx",
"args": ["-y", "@mcptools/mcp-tavily"],
"env": {**os.environ}
}
}
) as client:
agent = create_react_agent(model, client.get_tools())
system_message = SystemMessage(content=(
"你是一个具有网页搜索能力的助手,必要时使用搜索工具获取信息。"
))
agent_response = await agent.ainvoke({"messages": [system_message, HumanMessage(content="Llama4.0发布了吗?")]})
return agent_response["messages"][-1].content
if __name__ == "__main__":
response = asyncio.run(run_agent())
print("\n最终回答:", response)
2.3 LlamaIndex
最初专注RAG应用的框架,现已发展为全能的企业级RAG+Agent开发平台。
集成要点:
- 使用BasicMCPClient连接Server
- 通过McpToolSpec封装工具
- 支持远程SSE模式连接
python复制from llama_index.tools.mcp import McpToolSpec,BasicMCPClient
import asyncio
from llama_index.llms.openai import OpenAI
from llama_index.core.agent import ReActAgent
import os
llm = OpenAI(model="gpt-4o-mini")
async def main():
mcp_client = BasicMCPClient("npx", ["-y", "@mcptools/mcp-tavily"], env={**os.environ})
mcp_tool = McpToolSpec(client=mcp_client)
tools = await mcp_tool.to_tool_list_async()
agent = ReActAgent.from_tools(
tools,
llm=llm,
verbose=True,
system_prompt="你是一个具有网页搜索能力的助手,必要时使用搜索工具获取信息。"
)
response = await agent.aquery("Llama4.0发布了吗?")
print(response)
if __name__ == "__main__":
asyncio.run(main())
2.4 AutoGen 0.4+
微软开发的企业级多Agent框架,0.4版本开放了底层API,支持分布式多Agent系统。
集成方式:
- 使用StdioServerParams配置Server
- 通过mcp_server_tools获取工具集
- 结合RoutedAgent实现工具路由
python复制from autogen_ext.tools.mcp import StdioServerParams, mcp_server_tools
async def get_mcp_tools():
server_params = StdioServerParams(
command="npx",
args = [
"-y",
"@mcptools/mcp-tavily",
],env={**os.environ}
)
tools = await mcp_server_tools(server_params)
return tools
class ToolUseAgent(RoutedAgent):
pass
async def main():
runtime = SingleThreadedAgentRuntime()
mcp_tools = await get_mcp_tools()
tools = [*mcp_tools]
await ToolUseAgent.register(runtime, "my_agent", lambda: ToolUseAgent(tools))
message = Message('Llama4.0发布了吗?')
response = await runtime.send_message(message, AgentId("my_agent", "default"))
2.5 Pydantic AI
基于Pydantic的框架,强调结构化输出和类型验证,简洁易用。
集成特点:
- 类似OpenAI Agents SDK的简洁API
- 支持run_mcp_servers上下文管理器
- 可切换MCPServerHTTP连接远程Server
python复制from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerStdio
import os
server = MCPServerStdio(
'npx',
["-y", "@mcptools/mcp-tavily"],
env={**os.environ}
)
agent = Agent(
name="助手Agent",
system_prompt="你是一个具有网页搜索能力的助手,必要时使用搜索工具获取信息。",
model='openai:gpt-4o-mini',
mcp_servers=[server])
async def main():
async with agent.run_mcp_servers():
result = await agent.run('"Llama4.0发布了吗?')
print(result.data)
if __name__ == "__main__":
import asyncio
asyncio.run(main())
2.6 SmolAgents
Hugging Face开发的轻量级框架,基于生成代码的工具调用(CodeAgent)。
集成要点:
- 使用ToolCollection.from_mcp加载工具
- 支持trust_remote_code参数
- 简洁的ToolCallingAgent接口
python复制from smolagents import ToolCollection, CodeAgent
from smolagents.agents import ToolCallingAgent
from smolagents import tool, LiteLLMModel
from mcp import StdioServerParameters
import os
model = LiteLLMModel(model_id="gpt-4o-mini")
server_parameters = StdioServerParameters(
command="npx",
args=["-y", "@mcptools/mcp-tavily"],
env={**os.environ},
)
with ToolCollection.from_mcp(server_parameters, trust_remote_code=True) as tool_collection:
agent = ToolCallingAgent(tools=[*tool_collection.tools], model=model)
response = agent.run("llama4.0发布了吗?")
print(response)
2.7 Camel
专注于多Agent角色扮演的框架,内置多种角色抽象和组件。
集成特点:
- 使用MCPClient连接Server
- 通过MCPToolkit封装工具
- 内置将工具发布为MCP Server的功能
python复制import asyncio
from mcp.types import CallToolResult
from camel.toolkits.mcp_toolkit import MCPToolkit, MCPClient
import os
from camel.agents import ChatAgent
async def run_example():
mcp_client = MCPClient(
command_or_url="npx",
args=["-y", "@mcptools/mcp-tavily"],
env={**os.environ}
)
await mcp_client.connect()
mcp_toolkit = MCPToolkit(servers=[mcp_client])
tools = mcp_toolkit.get_tools()
try:
agent = ChatAgent(system_message='根据任务描述,使用网页搜索工具获取信息。',
tools=tools)
response = await agent.astep("llama4.0发布了吗?")
print("Response:", response.msgs[0].content)
except Exception as e:
print(f"Error during agent execution: {e}")
finally:
await mcp_client.disconnect()
if __name__ == "__main__":
asyncio.run(run_example())
2.8 CrewAI
专注于多Agent团队协作的框架,采用角色扮演设计。
当前集成状态:
- 官方MCP支持正在开发中(PR #2496)
- 可暂时使用第三方适配器
- 通过MCPAdapt和CrewAIAdapter桥接
python复制import os
from crewai import Agent, Crew, Task # type: ignore
from mcp import StdioServerParameters
from mcpadapt.core import MCPAdapt
from mcpadapt.crewai_adapter import CrewAIAdapter
with MCPAdapt(
StdioServerParameters(
command="npx",
args=["-y", "@mcptools/mcp-tavily"],
env={**os.environ}
),
CrewAIAdapter(),
) as tools:
print(f"Tools: {tools}")
agent = Agent(
role="MyAgent",goal="根据任务描述,使用网页搜索工具获取信息。",backstory="你是一个中文搜索助手",
tools=tools,llm='gpt-4o-mini',
)
task = Task(
description="llama4.0的最新消息",agent=agent,expected_output="消息列表")
task.execute_sync()
3. 框架选择建议与学习路径
3.1 框架选型考量因素
选择框架时需要考虑以下关键因素:
| 因素 | 轻量级框架 | 企业级框架 |
|---|---|---|
| 学习曲线 | 平缓(如OpenAI SDK) | 陡峭(如AutoGen) |
| 功能复杂度 | 基础Agent功能 | 多Agent协作、分布式 |
| 适用场景 | 简单任务自动化 | 复杂业务流程 |
| 社区支持 | 依赖官方文档 | 丰富的社区资源 |
3.2 学习路径建议
对于初学者,建议按照以下路径逐步深入:
- 从OpenAI Agents SDK或Pydantic AI开始,理解基础Agent概念
- 尝试LangGraph或LlamaIndex,掌握工作流设计
- 学习AutoGen或CrewAI,构建复杂多Agent系统
- 根据项目需求选择特定框架深入
3.3 常见问题排查
- 连接MCP Server失败
- 检查命令路径和环境变量
- 确认MCP工具包已正确安装
- 验证网络连接(远程Server情况)
- 工具调用无响应
- 检查Agent的system_prompt是否明确工具使用条件
- 确认模型有足够上下文理解工具用途
- 测试工具独立运行是否正常
- 多Agent协作问题
- 明确各Agent的职责边界
- 设计清晰的消息传递协议
- 使用框架提供的调试工具追踪消息流
4. 实战经验分享
在实际项目中集成MCP Server时,有几个关键点需要注意:
-
工具版本管理
MCP Server调用的工具应该保持版本稳定,避免频繁更新导致Agent行为不一致。建议在项目中固定工具版本。 -
权限控制
对于敏感工具,应该实现细粒度的权限控制。可以在MCP Server层面添加权限验证层,或者使用框架提供的权限机制。 -
性能监控
工具调用可能成为性能瓶颈,建议实现:
- 调用耗时监控
- 失败率统计
- 自动重试机制
- 测试策略
Agent系统测试应该包括:
- 单元测试:单个工具功能
- 集成测试:工具与Agent交互
- 场景测试:完整业务流程
- 调试技巧
- 启用框架的详细日志
- 使用中间件捕获请求/响应
- 构建最小可复现案例隔离问题
随着MCP协议的不断成熟,各框架的集成方式也在持续优化。建议定期查看框架官方文档,了解最新的最佳实践。对于生产系统,还应该考虑实现自动化部署和回滚机制,确保Agent系统的稳定运行。
