Spring Boot 项目引入 MCP 详细指南

06-01 1160阅读

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

一、pom 引入依赖

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

 
 

4.0.0

org.springframework.boot

spring-boot-starter-parent

3.2.3

com.demo

mcp-demo

Spring Boot 项目引入 MCP 详细指南
(图片来源网络,侵删)

1.0-SNAPSHOT

pom

Spring Boot 项目引入 MCP 详细指南
(图片来源网络,侵删)

17

Spring Boot 项目引入 MCP 详细指南
(图片来源网络,侵删)

32.1.2-jre

4.4

1.0.0-SNAPSHOT

mcp-demo-launcher

org.springframework.ai

spring-ai-bom

${spring-ai.version}

pom

import

spring-milestones

Spring Milestones

https://repo.spring.io/milestone

false

spring-snapshots

Spring Snapshots

https://repo.spring.io/snapshot

false

org.springframework.boot

spring-boot-starter

spring-boot-starter-logging

org.springframework.boot

org.springframework.boot

spring-boot-starter-test

test

org.springframework.ai

spring-ai-core

${spring-ai.version}

org.springframework.ai

spring-ai-starter-mcp-server-webmvc

${spring-ai.version}

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

spring-boot-starter-logging

org.springframework

spring-context

org.springframework.boot

spring-boot-starter-log4j2

在上述代码中,重点关注加粗加绿的部分,这是新增的 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 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)
免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们。

目录[+]

取消
微信二维码
微信二维码
支付宝二维码