Spring Boot 项目引入 MCP 详细指南

发布于:2025-03-31 ⋅ 阅读:(18) ⋅ 点赞:(0)

在 Spring Boot 项目开发过程中,引入 MCP(具体功能根据实际情况而定)能够为项目增添强大的功能支持。本文将详细介绍如何在 Spring Boot 项目中引入 MCP,包括在 pom 文件中引入依赖、配置 application.properties 文件、通过配置类初始化 MCP tools 实例、编写业务处理类、生成 MCP 对外接口类以及通过测试类进行自测等步骤。

一、pom 引入依赖

在 Spring Boot 项目的 pom.xml 文件中,我们需要引入 MCP 相关的依赖。以下是引入依赖的具体代码:


 

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>3.2.3</version>

<relativePath/> <!-- lookup parent from repository -->

</parent>

<groupId>com.demo</groupId>

<artifactId>mcp-demo</artifactId>

<version>1.0-SNAPSHOT</version>

<packaging>pom</packaging>

<properties>

<java.version>17</java.version>

<guava.version>32.1.2-jre</guava.version>

<commons-collections4.version>4.4</commons-collections4.version>

<spring-ai.version>1.0.0-SNAPSHOT</spring-ai.version>

</properties>

<modules>

<module>mcp-demo-launcher</module>

</modules>

<dependencyManagement>

<dependencies>

<dependency>

<groupId>org.springframework.ai</groupId>

<artifactId>spring-ai-bom</artifactId>

<version>${spring-ai.version}</version>

<type>pom</type>

<scope>import</scope>

</dependency>

</dependencies>

</dependencyManagement>

<repositories>

<!-- Spring Milestone 仓库 -->

<repository>

<id>spring-milestones</id>

<name>Spring Milestones</name>

<url>https://repo.spring.io/milestone</url>

<snapshots>

<enabled>false</enabled>

</snapshots>

</repository>

<repository>

<id>spring-snapshots</id>

<name>Spring Snapshots</name>

<url>https://repo.spring.io/snapshot</url>

<releases>

<enabled>false</enabled>

</releases>

</repository>

</repositories>

<dependencies>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter</artifactId>

<exclusions>

<exclusion>

<artifactId>spring-boot-starter-logging</artifactId>

<groupId>org.springframework.boot</groupId>

</exclusion>

</exclusions>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-test</artifactId>

<scope>test</scope>

</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework.ai/spring-ai-core -->

<dependency>

<groupId>org.springframework.ai</groupId>

<artifactId>spring-ai-core</artifactId>

<version>${spring-ai.version}</version>

</dependency>

<!-- MCP 服务器支持 - WebMVC版本 -->

<dependency>

<groupId>org.springframework.ai</groupId>

<artifactId>spring-ai-starter-mcp-server-webmvc</artifactId>

<version>${spring-ai.version}</version>

</dependency>

<!-- Spring Web -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

<exclusions>

<exclusion>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-logging</artifactId>

</exclusion>

</exclusions>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-context</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-log4j2</artifactId>

</dependency>

</dependencies>

</project>

在上述代码中,重点关注加粗加绿的部分,这是新增的 MCP 相关依赖。spring-ai-starter-mcp-server-webmvc依赖提供了 MCP 服务器支持(WebMVC 版本),同时还引入了spring-ai-core等相关依赖,这些依赖将为项目使用 MCP 功能奠定基础。在实际项目中,你需要根据项目的实际情况对其他部分进行调整,例如项目的 groupId、artifactId、版本号以及其他依赖的版本等。

二、application.properties 文件增加 mcp 配置

在 Spring Boot 项目的application.properties文件中,我们需要增加 MCP 相关的配置。以下是具体的配置内容:


 

server.port=8080

spring.application.name=mcp-demo

spring.main.banner-mode=off

# MCP

spring.ai.mcp.server.enabled=true

spring.ai.mcp.server.resource-change-notification=true

spring.ai.mcp.server.prompt-change-notification=true

spring.ai.mcp.server.tool-change-notification=true

spring.ai.mcp.server.name=mcp-demo-service

spring.ai.mcp.server.version=1.0.0

spring.ai.mcp.server.type=SYNC

spring.ai.mcp.server.sse-message-endpoint=/mcp/messages

同样,加粗加绿的部分是新增的 MCP 配置。这些配置项用于启用 MCP 服务器,设置服务器名称、版本、类型以及相关通知功能等。spring.ai.mcp.server.enabled=true表示启用 MCP 服务器;spring.ai.mcp.server.name设置了服务器的名称;spring.ai.mcp.server.version设置了服务器的版本;spring.ai.mcp.server.type设置了服务器的类型为 SYNC 等。这些配置将影响 MCP 服务器在项目中的运行方式和功能特性,你可以根据项目需求进行调整。

三、通过配置类实现 MCP tools 实例初始化

接下来,我们需要通过配置类来实现 MCP tools 实例的初始化。以下是具体的代码实现:


 

@Configuration

public class McpServerConfig {

@Autowired

private ApplicationContext applicationContext;

@Bean

public ToolCallbackProvider autoRegisterTools() {

// 获取所有带有 @Component 注解且类名以 Facade 结尾的 bean

String[] beanNames = applicationContext.getBeanNamesForAnnotation(Component.class);

List<Object> facadeBeans = new ArrayList<>();

for (String beanName : beanNames) {

if (beanName.endsWith("Facade")) {

facadeBeans.add(applicationContext.getBean(beanName));

}

}

// 一次性构建所有 Facade

return MethodToolCallbackProvider.builder()

.toolObjects(facadeBeans.toArray())

.build();

}

}

上述代码实现了根据注解扫描自动构建 toolObjects 的功能。它会获取所有带有@Component注解且类名以Facade结尾的 bean,然后将这些 bean 作为工具对象进行一次性构建。此规则主要是为了适配mcp-facade-generator(插件详见:https://github.com/James-Zou/mcp-facade-generator)插件。如果不使用此插件,该规则可以根据项目需求进行调整。通过这种方式初始化 MCP tools 实例,能够方便地将项目中的业务处理类整合到 MCP 框架中,为后续的业务处理提供支持。

四、编写业务处理类

业务处理类是 Java 项目中正常的业务处理接口实现类。在引入 MCP 的项目中,我们需要对业务处理类进行一些特定的标注。以下是一个示例业务处理类:


 

@MCPService(packageName = "com.demo.mcp.web.facade")

@Service

public class WeatherService {

/**

* Get weather information by city name

* @return

*/

public String getWeather(String cityName) {

// Implementation

return String.format(

"{\"success\":true,\"data\":{\"city\":\"%s\",\"temperature\":\"25°C\",\"condition\":\"Sunny\"},\"message\":\"Success\",\"code\":\"200\"}",

cityName

);

}

}

在这个业务处理类中,标红的@MCPService注解是mcp-facade-generator插件提供的。这个注解用于将该业务处理类与 MCP 框架进行关联,packageName属性指定了相关的包名。在实际项目中,你可以根据业务需求编写具体的业务逻辑,这里的getWeather方法只是一个简单的示例,返回了一个固定格式的天气信息字符串。

五、生成 mcp 对外接口类

通过执行mvn compile命令,就可以生成 MCP 对外接口类。以下是生成的WeatherServiceFacade类的示例:


 

public class WeatherServiceFacade {

@Autowired

private WeatherService service;

@Tool(description = "Get weather information by city name")

public MCPResponse getWeather(MCPRequest request) {

try {

// 解析请求参数

java.lang.String cityName = request.getParameter("cityName", java.lang.String.class);

Object result = service.getWeather(cityName);

return MCPResponse.success(result);

} catch (Exception e) {

return MCPResponse.error(e.getMessage());

}

}

}

这个类是 MCP 对外暴露的接口类,它通过@Autowired注入了WeatherService业务处理类。@Tool注解描述了该接口的功能,即获取城市的天气信息。在getWeather方法中,它首先解析请求参数,然后调用WeatherService的getWeather方法获取结果,并将结果封装成MCPResponse返回。如果在处理过程中发生异常,则返回错误信息。通过生成这样的对外接口类,能够方便地与外部系统进行交互,提供 MCP 相关的服务。

六、通过测试类模拟 mcp 客户端自测

最后,我们可以通过编写测试类来模拟 MCP 客户端进行自测。以下是两个相关的测试类示例:


 

public class ClientSse {

public static void main(String[] args) {

var transport = new HttpClientSseClientTransport("http://localhost:19401");

new SampleClient(transport).run();

}

}


 

public class SampleClient {

private final McpClientTransport transport;

public SampleClient(McpClientTransport transport) {

this.transport = transport;

}

public void run() {

try {

var client = McpClient.sync(this.transport).build();

client.initialize();

client.ping();

// List and demonstrate tools

McpSchema.ListToolsResult toolsList = client.listTools();

log.info("Available Tools = " + toolsList);

// 调用 getWeather 接口

McpSchema.CallToolResult weatherResult = client.callTool(new McpSchema.CallToolRequest(

"getWeather",

Map.of("cityName", "北京")

));

// 打印完整的响应对象

log.info("Weather Result: {}", weatherResult);

// 获取响应内容

for (McpSchema.Content content : weatherResult.content()) {

if (content instanceof McpSchema.TextContent) {

McpSchema.TextContent textContent = (McpSchema.TextContent) content;

log.info("Weather Info: {}", textContent.text());

}

}

client.closeGracefully();

} catch (Exception e) {

log.error("Error calling weather service", e);

}

}

}

在ClientSse类中,它创建了一个HttpClientSseClientTransport对象,并通过SampleClient类来执行测试。SampleClient类中,首先初始化McpClient,然后通过ping方法测试连接,接着列出可用的工具并调用getWeather接口获取天气信息。在调用接口后,它打印完整的响应对象,并提取响应内容中的天气信息进行打印。如果在测试过程中发生异常,则记录错误信息。通过这样的测试类,我们可以验证 MCP 在项目中的功能是否正常,确保引入的 MCP 能够满足项目的需求。

通过以上六个步骤,我们详细介绍了在 Spring Boot 项目中引入 MCP 的全过程,包括依赖引入、配置、实例初始化、业务处理类编写、接口类生成以及测试等方面。希望这篇文档能够帮助你顺利在 Spring Boot 项目中引入并使用 MCP。

参考文档

- [Spring AI 文档](https://docs.spring.io/spring-ai/reference/index.html)
- [MCP Facade Generator](https://github.com/James-Zou/mcp-facade-generator)
- [MCP Springboot Server](https://github.com/James-Zou/mcp-springboot-server)