MCP工具连接与天气查询

该项目演示了如何使用Streamable HTTP Transport协议连接到MCP服务器,并通过代理调用MCP工具执行任务,如获取天气信息。

  • by Prachi-Jamdade
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 prachi-jamdade/mcp-crewai-demo

使用说明

MCP演示项目

本项目演示了如何使用Streamable HTTP传输协议连接到MCP服务器,以及代理如何调用MCP工具来执行检索天气信息等任务。

设置

  1. 克隆存储库并导航到项目文件夹:

    git clone <repo-url>
    
  2. 安装依赖项:

    uv add -r requirements.txt
    

    或

    pip install -r requirements.txt
    
  3. 配置环境变量:

    • 创建一个 .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 agent

2.发现和使用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工具来执行任务。