本项目是一个基于 Spring AI 框架构建的示例天气服务服务器,借助 Model Context Protocol (MCP) 协议,打造了一个基于 Spring Boot 的天气信息服务,具备基本的天气信息查询能力。
以下是项目所需的 Maven 依赖:
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-actuatorartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-log4j2artifactId>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.datgengroupId>
<artifactId>jackson-dataformat-csvartifactId>
dependency>
<dependency>
<groupId>org.modelmappergroupId>
<artifactId>modelmapperartifactId>
dependency>
dependencies>
执行以下命令下载所有依赖项并构建项目 JAR 文件:
mvn clean install
java -jar target/spring-ai-mcp-weather-server-0.0.1-SNAPSHOT.jar
启动后,服务器将在默认端口 8080
上运行,并提供 RESTful 接口。
http://localhost:8080/api/health
http://localhost:8080/weather?city=New%20York
spring-ai-mcp-weather-server/
├── src/main/java/
│ └── org.springframework.ai.mcp.sample.server/
│ ├── WeatherService.java # 天气查询业务逻辑实现类
│ └── WeatherController.java # 天气查询 RESTful 接口控制器
├── pom.xml # 项目依赖管理文件
└── README.md # 项目说明文档
项目提供了一个默认的 application.properties
文件,包含以下配置:
server.port=8080
logging.level.root=INFO
如果需要自定义配置,可以创建一个 application.yaml
或 application.properties
文件,并将其放入项目的 src/main/resources
目录。
package org.springframework.ai.mcp.sample.server;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
@Service
public class WeatherService {
public Map getWeather(String city) {
Map result = new HashMap<>();
try {
// 示例逻辑:返回假设计数据
if ("New York".equals(city)) {
result.put("temperature", 75);
result.put("condition", "晴朗");
result.put("humidity", 60);
result.put("windSpeed", 15);
} else {
result.put("error", "城市未找到");
}
} catch (Exception e) {
result.put("error", "服务异常");
}
return result;
}
}
package org.springframework.ai.mcp.sample.server;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class WeatherController {
private final WeatherService weatherService;
public WeatherController(WeatherService weatherService) {
this.weatherService = weatherService;
}
@GetMapping("/weather")
public Map getWeather(@RequestParam String city) {
return weatherService.getWeather(city);
}
}
当访问 /weather?city=New%20York
时,示例输出如下:
{
"temperature": 75,
"condition": "晴朗",
"humidity": 60,
"windSpeed": 15
}
WeatherService
类来支持更多城市或天气数据源。