天气查询聊天机器人

基于Model Context Protocol (MCP)和Gemini的AI聊天机器人,集成了天气API,提供实时天气查询服务。

  • by achintya-7
  • Go
  • 本地部署
  • 更新于
在 GitHub 查看 achintya-7/mcp-demo

使用说明

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:

Gemini 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

运作原理

  1. MCP服务器 通过HTTP(端口8085)公开天气工具
  2. Gemini客户端 连接到MCP服务器并发现可用工具
  3. 当你询问天气时,双子座:
    • 决定使用 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