MCP集成服务

该项目展示了如何在Spring Boot应用中集成Spring AI对MCP(模型上下文协议)的支持,包括服务器端和客户端的实现,用于管理AI模型中的上下文交互。

  • by oalles
  • Java
  • 本地部署
  • 2 星标
  • 更新于
在 GitHub 查看 oalles/spring-ai-mcp-test

使用说明

MCP主机项目

描述

该项目展示了如何在Spring Boot应用程序中集成Spring AI对MCP(模型上下文协议)的支持, 涵盖服务器端和客户端实现。

主控程序

MCP是一个标准,它简化了人工智能模型中上下文交互的管理,实现了一致的集成 使用外部数据源和工具。

春季AI MCP 扩展 MCP Java SDK 并为客户端和服务器提供专用的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<TimeZone> 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<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);
         }
      }
   };
}

运行项目

  1. 启动Geocoder服务:

    cd geocoder
    mvn spring-boot:run
    
  2. 启动时区服务:

    cd timezone
    mvn spring-boot:run
    
  3. 启动MCP主机:

    cd mcp-host
    mvn spring-boot:run
    

用法

  1. 与MCP主机交互:
    • 运行MCP主机应用程序。
    • 在控制台中输入城市名称。
    • 系统将提供输入城市的纬度、经度和时区信息。

插入图像