MCP演示项目
本项目演示了如何使用Streamable HTTP传输协议连接到MCP服务器,以及代理如何调用MCP工具来执行检索天气信息等任务。
设置
- 克隆存储库并导航到项目文件夹:
git clone - 安装依赖项:
uv add -r requirements.txt或
pip install -r requirements.txt- 配置环境变量:
- 创建一个 .env 项目根目录中的文件。 - 添加您的API密钥(例如,用于OpenAI):
OPENAI_API_KEY=your-openai-key-here运作原理
1.连接到MCP服务器
该项目使用 MCPServerAdapter 通过Streamable HTTP连接到您的MCP服务器:
server_params = {
"url": "http://localhost:8082/weather/mcp",
"transport": "streamable-http"
}
with MCPServerAdapter(server_params) as tools:
# tools are now available for the agent2.发现和使用MCP工具
代理从MCP服务器发现可用工具(例如。, getWeatherForecast)并且可以通过传递所需的参数来调用它们:
weather_tool = next((tool for tool in tools if tool.name == "getWeatherForecast"), None)
result = weather_tool.run(
latitude=12.9716,
longitude=77.5946,
current_weather=True
)3.代理和任务执行
创建了一个可以访问MCP工具的代理。您定义了一个任务,描述代理应该做什么(例如,“获取班加罗尔的当前天气”):
http_agent = Agent(
role="Weather Forecaster",
goal="Provide current weather information for any city.",
tools=[weather_tool],
verbose=True,
)
http_task = Task(
description="Get the current weather in Bangalore using the getWeatherForecast tool.",
expected_output="Current weather details for Bangalore.",
agent=http_agent,
)机组人员执行任务并返回结果:
http_crew = Crew(
agents=[http_agent],
tasks=[http_task],
verbose=True,
process=Process.sequential
)
result = http_crew.kickoff()输出
总结
- 使用CrewAI通过流式HTTP传输连接到MCP服务器。
- 发现并使用MCP工具。
- 代理通过调用具有所需参数的MCP工具来执行任务。
