使用说明
MCP天气演示
人工智能聊天机器人使用模型上下文协议(MCP)与Gemini和天气API集成。
建筑
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Gemini │ ◄───► │ MCP Server │ ◄───► │ Weather │
│ Client │ MCP │ (Go) │ HTTP │ API │
└─────────────┘ └─────────────┘ └─────────────┘
先决条件
- 转到1.21+
- Node.js(用于
env-cmd和just) - API密钥(见下文)
设置
1.安装工具
# Install env-cmd (environment variable manager)
npm install -g env-cmd
# Install just (command runner)
# Windows: Download from https://github.com/casey/just/releases
# Or use: cargo install just
2.获取API密钥
天气API:
- 注册地址: WeatherAPI.com
- 从仪表板获取API密钥
Gemini API:
- 首选 谷歌AI工作室
- 点击“获取API密钥”
- 复制您的密钥
3.配置环境
创建 .env 项目根目录中的文件:
WEATHER_API_KEY=your_weather_api_key_here
GEMINI_API_KEY=your_gemini_api_key_here
4.安装Go依赖项
go mod download
运行项目
选项1:使用Just(推荐)
# List available commands
just -l
# Run MCP server only
just mcp
# Run Gemini chat client
just cli
选项2:手动命令
终端1-启动MCP服务器:
env-cmd -f .env go run cmd/server/main.go mcp
终端2-启动Gemini客户端:
env-cmd -f .env go run cmd/server/main.go gemini
用法
Gemini客户端运行后,尝试以下命令:
You: What's the weather in Tokyo?
You: What's the AQI in Delhi?
You: Get weather for London
You: exit
测试MCP服务器
使用MCP检查器直接测试服务器:
npx @modelcontextprotocol/inspector http://localhost:8085
项目结构
mcp-demo/
├── cmd/
│ └── server/
│ ├── main.go # Main entry point
│ └── pkg/functions/
│ └── weather.go # Weather tool implementation
├── pkg/
│ └── weather/
│ └── main.go # Weather API client
├── .env # API keys (create this)
├── justfile # Task runner commands
└── go.mod # Go dependencies
运作原理
- MCP服务器 通过HTTP(端口8085)公开天气工具
- Gemini客户端 连接到MCP服务器并发现可用工具
- 当你询问天气时,双子座:
- 决定使用
get_weather工具 - 使用城市名称调用MCP服务器
- MCP服务器从Weather API获取数据
- 将结构化数据返回给Gemini
- Gemini格式化自然语言响应
- 决定使用
故障排除
“未设置GEMINI_API_KEY”
- 确保
.env文件存在并具有密钥 - 确认您正在使用
env-cmd -f .env跑步时
“无法连接到MCP服务器”
- 确保MCP服务器在端口8085上运行
- 检查是否有其他进程正在使用该端口
“配方无法运行,因为找不到外壳”
- 添加
set shell := ["powershell.exe", "-c"]到顶部justfile