天气与城市人口数据助力代理利用自定义MCP工具
一个由OpenAI驱动的Strands人工智能代理,它结合了自定义的MCP(模型上下文协议)工具,提供天气预报、天气警报以及全球城市人口信息。
特点/特性
- OpenAI 集成通过Strands Agents SDK使用GPT-4o模型
- 定制MCP工具:
- 天气工具使用美国国家气象局API获取天气预报和活跃警报 - 通过坐标(纬度/经度)获取详细天气预报 - 按美国州代码查看当前生效的天气警报 - 城市人口查询工具使用OpenDataSoft GeoNames API获取全球城市的人口数据 - 获取全球任何城市的人口数据 - 比较城市之间的人口数量 - 搜索时可选择性地按国家过滤
- 交互式命令行界面(CLI)简洁的命令行界面,支持对话式输入
- 清洁输出仅显示最终代理响应,不显示详细日志
- MCP建筑事务所/公司展示了如何创建自定义MCP服务器工具并与Strands代理进行集成
建筑学
这个项目展示了:
- 使用FastMCP创建自定义MCP服务器工具
- 将多个MCP客户端连接到一个Strands代理
- 工具发现与自动集成
- 使用外部API调用的异步工具执行
安装
- 安装依赖项:
pip install 'strands-agents[openai]' mcp httpx- 设置您的OpenAI API密钥:
cp .env.example .env
# Edit .env and add your OpenAI API key配置
代理已配置在 city_population_weather_strand_agent.py 与;带有;和……一起
- 模型:
gpt-4o(可自定义为gpt-4o-mini、gpt-4-turbo或gpt-3.5-turbo) - 最大标记数(或最大令牌数)1500
- 温度0.7
使用方法
运行代理:
python city_population_weather_strand_agent.py示例交互:
Weather & City Population Strands Agent with OpenAI + MCP
============================================================
Ask about weather forecasts, alerts, and city populations!
Examples:
Weather:
- What's the weather forecast for NYC? (latitude: 40.7128, longitude: -74.0060)
- Are there any weather alerts in California?
- Get me the forecast for latitude 34.0522, longitude -118.2437
City Population (Worldwide):
- What is the population of New York?
- How many people live in Tokyo, Japan?
- Compare the populations of London and Paris
Type your question or 'exit' to quit
Connected to MCP servers:
- Weather tools: 2 tools
- City population tools: 2 tools
- Total: 4 tools available
You: What's the population of Tokyo?
Agent:
Tokyo, Japan has a population of approximately 13,960,000 people.
You: What's the weather forecast for San Francisco?
Agent:
Here's the weather forecast for San Francisco (latitude: 37.7749, longitude: -122.4194):
Tonight:
Temperature: 58°F
Wind: 10 mph W
Forecast: Partly cloudy with a low around 58. West wind around 10 mph.
You: exit
Goodbye!项目结构
weather-strands-agent-with-custom-mcp-tool/
├── city_population_weather_strand_agent.py # Main agent implementation
├── tools/
│ ├── __init__.py
│ ├── tool_weather.py # Weather MCP server tool
│ └── tool_city_population.py # City population MCP server tool
├── __init__.py
├── .env.example # Example environment configuration
├── .gitignore
└── README.mdMCP 工具
天气工具(tools/tool_weather.py)
get_forecast(latitude, longitude)获取坐标位置的天气预报get_alerts(state)获取美国某州(2字母代码)的实时天气警报- 数据来源:美国国家气象局API
城市人口工具(tools/tool_city_population.py)
get_city_population(city, country?)获取全球某城市的居民人口数量compare_city_populations(city1, city2, country1?, country2?)比较人口- 数据来源:OpenDataSoft GeoNames API,包含1000多个有人口数据的城市
它是如何运作的
- MCP 服务器工具每个工具都是一个作为子进程运行的FastMCP服务器
- MCP 客户端主代理创建MCP客户端以通过stdio连接到每个工具服务器
- 工具发现工具会自动被发现并提供给代理使用
- 代理执行OpenAI模型根据用户查询决定调用哪些工具
- 清洁输出一个自定义的响应处理程序确保只显示最终答案
API要求
- OpenAI API密钥对于代理模型是必需的(在...中设置)
.env) - 天气数据使用免费的美国国家气象局API(无需密钥)
- 人口数据使用免费的OpenDataSoft公共API(无需密钥)
许可证
麻省理工学院(MIT)
