MCP主机项目
描述
该项目展示了如何在Spring Boot应用程序中集成Spring AI对MCP(模型上下文协议)的支持, 涵盖服务器端和客户端实现。
主控程序
MCP是一个标准,它简化了人工智能模型中上下文交互的管理,实现了一致的集成 使用外部数据源和工具。
并为客户端和服务器提供专用的Spring Boot启动器。
MCP客户端处理与MCP服务器的通信和连接管理。
在这个项目中,我们利用Spring AI构建MCP服务器,使其功能可供LLM使用。 请注意,需要使用支持TOOLS的模型;我们正在使用 Llama3.2 通过 Ollama.
模块
该项目由三个主要模块组成:
地理编码服务
- 端口: 8081
- 描述:提供给定城市的纬度和经度。
- 配置
public interface Geocoder {
GeoCodeResult geocode(String city) throws Exception;
}
public record GeoCodeResult(double latitude, double longitude) {}时区服务
- 端口: 8082
- 描述:提供给定纬度和经度的时区信息。
- 配置
public interface TimeZoneService {
Optional getTimeZoneFromLocation(double latitude, double longitude) throws Exception;
}
public record TimeZone(
String id,
String name,
int rawOffset,
int dstSavings
) {}MCP主机
- 描述:通过MCP客户端使用Geocoder和时区服务,并提供与LLM交互的控制台界面。
- 配置
@Bean
CommandLineRunner runner(final ChatClient.Builder chatClientBuilder, List toolCallbacks) {
final ChatClient agent = chatClientBuilder.build();
return args -> {
try (Scanner scanner = new Scanner(System.in)) {
while (true) {
System.out.print("\n\nEnter city (or type 'exit' to quit): ");
String city = scanner.nextLine();
if ("exit".equalsIgnoreCase(city)) {
break;
}
String queryTemplate = """
Please use the available tools to find the latitude and longitude for the city `{city}`. Once you have this information,
use the tools to determine and provide all the timezone details for that location in the same language.
""";
String systemTemplate = """
You are an AI assistant specialized in providing geographical information. Your task is to use the provided tools to gather and deliver accurate data.
""";
String llmResponse = agent
.prompt()
.advisors(new SimpleLoggerAdvisor())
.system(systemSpec -> systemSpec.text(systemTemplate))
.user(userSpec -> userSpec.text(queryTemplate).param("city", city))
.tools(toolCallbacks)
.call()
.content();
log.info("\n\n{}", llmResponse);
}
}
};
}运行项目
- 启动Geocoder服务:
cd geocoder
mvn spring-boot:run- 启动时区服务:
cd timezone
mvn spring-boot:run- 启动MCP主机:
cd mcp-host
mvn spring-boot:run用法
- 与MCP主机交互:
- 运行MCP主机应用程序。 - 在控制台中输入城市名称。 - 系统将提供输入城市的纬度、经度和时区信息。
插入图像
