Java开发者必看:用MCP协议让AI模型实时查询天气,Claude秒变气象专家
嘿,重阳!纽约的3月周末(2026年3月7日晚9:30,估计你在家刷 AI 项目~),MCP(Model Context Protocol,模型上下文协议)是 Anthropic 推出的开放协议,专为 AI 模型(如 Claude)设计,让它们安全、可控地连接外部工具、数据源和 API。它像 AI 的“USB 接口”,支持动态工具发现、实时通信和权限控制。今天咱们来一场“Java 专属”实战教程:用 MCP 协议构建一个天气查询服务,让 Claude 等 AI 模型实时拉取天气数据,瞬间变身“气象专家”。基于 JDK 17+ 和 Solon 框架(轻量 Java Web 框架,5 行代码起步),全干货覆盖原理、代码和集成。走起!🚀
1. MCP 协议简介:为什么用它让 AI “触网”?
MCP 定义:MCP 是 Anthropic 开源的协议(GitHub:modelcontextprotocol),核心目标是标准化 AI 与外部世界的交互。它解决 AI “孤岛”问题:模型如 Claude 默认无网络访问,但通过 MCP,AI 可以“调用”外部服务,而不直接暴露 API 密钥或数据。
关键特性(表格速览):
| 特性 | 描述 | 益处 |
|---|---|---|
| 动态发现 | AI 自动扫描可用工具(服务端暴露端点)。 | 无需硬编码,易扩展。 |
| 实时双向通信 | WebSocket 支持,AI 发送请求,服务端推数据。 | 低延迟,如天气实时更新。 |
| 安全控制 | 权限验证、沙箱执行。 | 防滥用,适合企业。 |
| 跨模型兼容 | 支持 Claude、OpenAI、DeepSeek 等 LLM。 | 通用,不绑框架。 |
为什么天气查询?:天气 API(如高德、OpenWeatherMap)是经典外部工具。Claude 通过 MCP “调用”它,就能从“聊天机器人”变“气象专家”——用户问“纽约明天天气?”,Claude 查 API、分析趋势、建议穿衣。
前提准备:
- JDK 17+:HttpClient 支持。
- Solon 框架:轻量(<1MB),pip install 般的 Java Web。Maven 加依赖:
<dependency>
<groupId>org.noear</groupId>
<artifactId>solon.boot.jlhttp</artifactId>
<version>2.0.0</version>
</dependency>
- 天气 API:用高德天气(免费注册 Key:https://lbs.amap.com/api/webservice/guide/api/weatherinfo)。
- Claude API:Anthropic 账号 + Key(https://console.anthropic.com)。
2. MCP 协议原理:AI 如何“调用”天气服务?
MCP 架构分 Host(AI 侧) 和 Server(服务侧):
- Host:AI 模型(如 Claude)发起请求,发现工具、发送指令。
- Server:Java 服务暴露 MCP 端点,提供天气查询功能。
- 通信:HTTP/WS,JSON 格式。核心端点:
/mcp/discover(工具发现)、/mcp/execute(执行)。
天气查询流程(简化 PDR 循环):
- Claude 感知用户查询(“纽约天气”)。
- 决策:调用 MCP 工具“getWeather”。
- 行动:发请求到 Java Server,Server 查高德 API,返回 JSON。
- Claude 分析数据,生成响应(如“纽约晴转多云,建议带伞”)。
伪代码流程(Java Server 侧):
// MCP Server 核心
public class WeatherMcpServer {
// 发现端点:返回工具列表
@Get("/mcp/discover")
public Map<String, Object> discover() {
return Map.of("tools", List.of(
Map.of("name", "getWeather", "description", "查询实时天气",
"parameters", Map.of("city", "String", "extensions", "adcode"))
));
}
// 执行端点:AI 调用工具
@Post("/mcp/execute")
public Map<String, Object> execute(Map<String, Object> params) {
String city = (String) params.get("city");
// 调用高德 API 获取天气
String weather = queryWeatherApi(city);
return Map.of("result", weather);
}
}
3. Java 实战:5 步构建 MCP 天气服务
用 Solon 框架,5 行核心代码起步。完整项目 GitHub 示例见 灵感。
步骤1: 项目搭建
- Maven pom.xml 加 Solon 和 HttpClient 依赖。
- App.java 主类:
import org.noear.solon.Solon;
public class App {
public static void main(String[] args) {
Solon.start(App.class, args);
}
}
步骤2: 定义天气工具(WeatherService.java)
- 用 HttpClient 调用高德 API。
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;
public class WeatherService {
private static final String API_KEY = "你的高德Key"; // 替换你的 Key
private static final HttpClient client = HttpClient.newHttpClient();
public String getWeather(String city) throws Exception {
String url = String.format("https://restapi.amap.com/v3/weather/weatherInfo?city=%s&key=%s&extensions=all", city, API_KEY);
HttpRequest request = HttpRequest.newBuilder(URI.create(url)).GET().build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
return response.body(); // JSON 如 {"status":"1","forecasts":[...]}
}
}
步骤3: 实现 MCP Controller(McpController.java)
- 暴露 MCP 端点。
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Get;
import org.noear.solon.annotation.Post;
import org.noear.solon.annotation.Mapping;
import java.util.*;
@Controller
public class McpController {
private final WeatherService weatherService = new WeatherService();
@Get
@Mapping("/mcp/discover")
public Map<String, Object> discover() {
Map<String, Object> tool = new HashMap<>();
tool.put("name", "getWeather");
tool.put("description", "获取指定城市的实时天气和预报");
tool.put("parameters", Map.of("city", Map.of("type", "string", "description", "城市名或 adcode")));
return Map.of("tools", List.of(tool));
}
@Post
@Mapping("/mcp/execute")
public Map<String, Object> execute(Map<String, Object> request) throws Exception {
String toolName = (String) request.get("tool");
if ("getWeather".equals(toolName)) {
Map<String, Object> params = (Map<String, Object>) request.get("parameters");
String city = (String) params.get("city");
String result = weatherService.getWeather(city);
return Map.of("result", result);
}
return Map.of("error", "Unknown tool");
}
}
步骤4: 运行服务
java -jar your-app.jar启动,监听 8080 端口。- 测试发现:curl http://localhost:8080/mcp/discover → 返回工具 JSON。
- 测试执行:curl -X POST http://localhost:8080/mcp/execute -d ‘{“tool”:”getWeather”,”parameters”:{“city”:”New York”}}’ → 返回天气 JSON。
步骤5: 集成到 Claude(AI 侧)
- 用 Anthropic SDK(Maven 加 com.anthropic:anthropic-sdk:0.1.0)。
import com.anthropic.AnthropicClient;
import com.anthropic.models.Message;
public class ClaudeWeatherAgent {
private static final String API_KEY = "你的 Anthropic Key";
private static final String MCP_SERVER = "http://localhost:8080";
public static void main(String[] args) throws Exception {
AnthropicClient client = new AnthropicClient(API_KEY);
// Claude 调用 MCP
Message userMessage = Message.builder()
.role("user")
.content("纽约明天天气怎么样?用 MCP 查询。")
.build();
// 配置工具调用(Claude 支持 tools 参数)
Map<String, Object> toolConfig = Map.of(
"tools", List.of(Map.of("name", "getWeather", "server", MCP_SERVER))
);
// 发送请求(简化,实际用 SDK 的工具调用接口)
String response = client.messages().create(List.of(userMessage), "claude-3-opus-20240229", toolConfig);
System.out.println(response); // Claude 输出:基于天气数据的分析
}
}
- 输出示例:Claude 会调用 MCP,获取 {“forecasts”: [{“casts”: [{“dayweather”: “Sunny”, …}]},然后回复“纽约明天晴朗,气温 15-20°C,适合户外活动。”
4. 进阶优化:让 Claude “秒变专家”
- 多工具扩展:加“getForecast”工具,支持预报。
- 实时推送:用 WebSocket(Solon 支持)推天气警报。
- 安全:加 JWT 认证到 /mcp/execute。
- 部署:Docker 打包 Server,Claude 云集成。
- 性能:缓存天气数据(Redis),TTL 5min。
常见坑:
- API Key 泄露:用环境变量存储。
- 解析错误:高德 JSON 用 Jackson 解析。
- Claude 限额:测试用免费 Tier。
MCP 让 Java + AI 无缝融合,你的 Claude 现在是“气象达人”了!项目完整码见 GitHub 灵感仓库。 想扩展到股票查询或多 Agent?随时问!💪