This project demonstrates how to integrate Spring AI's support for MCP (Model Context Protocol) within Spring Boot applications, covering both server-side and client-side implementations. MCP is a standard that streamlines the management of contextual interactions in AI models, enabling consistent integration with external data sources and tools.
public interface Geocoder {
GeoCodeResult geocode(String city) throws Exception;
}
public record GeoCodeResult(double latitude, double longitude) {}
public interface TimeZoneService {
Optional<TimeZone> getTimeZoneFromLocation(double latitude, double longitude) throws Exception;
}
public record TimeZone(
String id,
String name,
int rawOffset,
int dstSavings
) {}
@Bean
CommandLineRunner runner(final ChatClient.Builder chatClientBuilder, List<ToolCallback> 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);
}
}
};
}
shell
cd geocoder
mvn spring-boot:run
shell
cd timezone
mvn spring-boot:run
shell
cd mcp-host
mvn spring-boot:run
This project showcases how to integrate Spring AI's support for MCP within Spring Boot applications, covering both server-side and client-side implementations.