SpringBoot項(xiàng)目引入MCP的實(shí)現(xiàn)示例
在 Spring Boot 項(xiàng)目開發(fā)過程中,引入 MCP(具體功能根據(jù)實(shí)際情況而定)能夠?yàn)轫?xiàng)目增添強(qiáng)大的功能支持。本文將詳細(xì)介紹如何在 Spring Boot 項(xiàng)目中引入 MCP,包括在 pom 文件中引入依賴、配置 application.properties 文件、通過配置類初始化 MCP tools 實(shí)例、編寫業(yè)務(wù)處理類、生成 MCP 對外接口類以及通過測試類進(jìn)行自測等步驟。
一、pom 引入依賴
在 Spring Boot 項(xiàng)目的 pom.xml 文件中,我們需要引入 MCP 相關(guān)的依賴。以下是引入依賴的具體代碼:
<?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 服務(wù)器支持 - 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>
在上述代碼中,重點(diǎn)關(guān)注加粗加綠的部分,這是新增的 MCP 相關(guān)依賴。spring-ai-starter-mcp-server-webmvc依賴提供了 MCP 服務(wù)器支持(WebMVC 版本),同時(shí)還引入了spring-ai-core等相關(guān)依賴,這些依賴將為項(xiàng)目使用 MCP 功能奠定基礎(chǔ)。在實(shí)際項(xiàng)目中,你需要根據(jù)項(xiàng)目的實(shí)際情況對其他部分進(jìn)行調(diào)整,例如項(xiàng)目的 groupId、artifactId、版本號(hào)以及其他依賴的版本等。
二、application.properties 文件增加 mcp 配置
在 Spring Boot 項(xiàng)目的application.properties文件中,我們需要增加 MCP 相關(guān)的配置。以下是具體的配置內(nèi)容:
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 配置。這些配置項(xiàng)用于啟用 MCP 服務(wù)器,設(shè)置服務(wù)器名稱、版本、類型以及相關(guān)通知功能等。spring.ai.mcp.server.enabled=true表示啟用 MCP 服務(wù)器;spring.ai.mcp.server.name設(shè)置了服務(wù)器的名稱;spring.ai.mcp.server.version設(shè)置了服務(wù)器的版本;spring.ai.mcp.server.type設(shè)置了服務(wù)器的類型為 SYNC 等。這些配置將影響 MCP 服務(wù)器在項(xiàng)目中的運(yùn)行方式和功能特性,你可以根據(jù)項(xiàng)目需求進(jìn)行調(diào)整。
三、通過配置類實(shí)現(xiàn) MCP tools 實(shí)例初始化
接下來,我們需要通過配置類來實(shí)現(xiàn) MCP tools 實(shí)例的初始化。以下是具體的代碼實(shí)現(xiàn):
@Configuration public class McpServerConfig { @Autowired private ApplicationContext applicationContext; @Bean public ToolCallbackProvider autoRegisterTools() { // 獲取所有帶有 @Component 注解且類名以 Facade 結(jié)尾的 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)); } } // 一次性構(gòu)建所有 Facade return MethodToolCallbackProvider.builder() .toolObjects(facadeBeans.toArray()) .build(); } }
上述代碼實(shí)現(xiàn)了根據(jù)注解掃描自動(dòng)構(gòu)建 toolObjects 的功能。它會(huì)獲取所有帶有@Component注解且類名以Facade結(jié)尾的 bean,然后將這些 bean 作為工具對象進(jìn)行一次性構(gòu)建。此規(guī)則主要是為了適配mcp-facade-generator(插件詳見:https://github.com/James-Zou/mcp-facade-generator)插件。如果不使用此插件,該規(guī)則可以根據(jù)項(xiàng)目需求進(jìn)行調(diào)整。通過這種方式初始化 MCP tools 實(shí)例,能夠方便地將項(xiàng)目中的業(yè)務(wù)處理類整合到 MCP 框架中,為后續(xù)的業(yè)務(wù)處理提供支持。
四、編寫業(yè)務(wù)處理類
業(yè)務(wù)處理類是 Java 項(xiàng)目中正常的業(yè)務(wù)處理接口實(shí)現(xiàn)類。在引入 MCP 的項(xiàng)目中,我們需要對業(yè)務(wù)處理類進(jìn)行一些特定的標(biāo)注。以下是一個(gè)示例業(yè)務(wù)處理類:
@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 ); } }
在這個(gè)業(yè)務(wù)處理類中,標(biāo)紅的@MCPService注解是mcp-facade-generator插件提供的。這個(gè)注解用于將該業(yè)務(wù)處理類與 MCP 框架進(jìn)行關(guān)聯(lián),packageName屬性指定了相關(guān)的包名。在實(shí)際項(xiàng)目中,你可以根據(jù)業(yè)務(wù)需求編寫具體的業(yè)務(wù)邏輯,這里的getWeather方法只是一個(gè)簡單的示例,返回了一個(gè)固定格式的天氣信息字符串。
五、生成 mcp 對外接口類
通過執(zhí)行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 { // 解析請求參數(shù) 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()); } } }
這個(gè)類是 MCP 對外暴露的接口類,它通過@Autowired注入了WeatherService業(yè)務(wù)處理類。@Tool注解描述了該接口的功能,即獲取城市的天氣信息。在getWeather方法中,它首先解析請求參數(shù),然后調(diào)用WeatherService的getWeather方法獲取結(jié)果,并將結(jié)果封裝成MCPResponse返回。如果在處理過程中發(fā)生異常,則返回錯(cuò)誤信息。通過生成這樣的對外接口類,能夠方便地與外部系統(tǒng)進(jìn)行交互,提供 MCP 相關(guān)的服務(wù)。
六、通過測試類模擬 mcp 客戶端自測
最后,我們可以通過編寫測試類來模擬 MCP 客戶端進(jìn)行自測。以下是兩個(gè)相關(guān)的測試類示例:
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); // 調(diào)用 getWeather 接口 McpSchema.CallToolResult weatherResult = client.callTool(new McpSchema.CallToolRequest( "getWeather", Map.of("cityName", "北京") )); // 打印完整的響應(yīng)對象 log.info("Weather Result: {}", weatherResult); // 獲取響應(yīng)內(nèi)容 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類中,它創(chuàng)建了一個(gè)HttpClientSseClientTransport對象,并通過SampleClient類來執(zhí)行測試。SampleClient類中,首先初始化McpClient,然后通過ping方法測試連接,接著列出可用的工具并調(diào)用getWeather接口獲取天氣信息。在調(diào)用接口后,它打印完整的響應(yīng)對象,并提取響應(yīng)內(nèi)容中的天氣信息進(jìn)行打印。如果在測試過程中發(fā)生異常,則記錄錯(cuò)誤信息。通過這樣的測試類,我們可以驗(yàn)證 MCP 在項(xiàng)目中的功能是否正常,確保引入的 MCP 能夠滿足項(xiàng)目的需求。
通過以上六個(gè)步驟,我們詳細(xì)介紹了在 Spring Boot 項(xiàng)目中引入 MCP 的全過程,包括依賴引入、配置、實(shí)例初始化、業(yè)務(wù)處理類編寫、接口類生成以及測試等方面。希望這篇文檔能夠幫助你順利在 Spring Boot 項(xiàng)目中引入并使用 MCP。
參考文檔
- [Spring AI 文檔]
- [MCP Facade Generator]
- [MCP Springboot Server]
到此這篇關(guān)于SpringBoot項(xiàng)目引入MCP的實(shí)現(xiàn)示例的文章就介紹到這了,更多相關(guān)SpringBoot引入MCP內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 教你如何實(shí)現(xiàn)容器化 MCP Server
- 輕松開發(fā) Streamable HTTP MCP Server
- 在 VS Code 中,一鍵安裝 MCP Server!
- 從零開始開發(fā)一個(gè) MCP Server!
- VS?Code擴(kuò)展Code?Runner?MCP?Server來了
- Go語言開發(fā)實(shí)現(xiàn)查詢IP信息的MCP服務(wù)器
- 一文弄懂用Go實(shí)現(xiàn)MCP服務(wù)的示例代碼
- 一文帶你學(xué)會(huì)使用Go語言實(shí)現(xiàn)自己的MCP服務(wù)端
- .NET?MCP?文檔詳細(xì)指南
- 把 MCP Server 打包進(jìn) VS Code extension
相關(guān)文章
SpringCloud Gateway 路由配置定位原理分析
本節(jié)主要了解系統(tǒng)中的謂詞與配置的路由信息是如何進(jìn)行初始化關(guān)聯(lián)生成路由對象的。每個(gè)謂詞工廠中的Config對象又是如何被解析配置的2021-07-07springboot springmvc拋出全局異常的解決方法
這篇文章主要為大家詳細(xì)介紹了springboot springmvc拋出全局異常的解決方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06SpringBoot Admin健康檢查功能的實(shí)現(xiàn)
admin主要就是告訴運(yùn)維人員,服務(wù)出現(xiàn)異常,然后進(jìn)行通知(微信、郵件、短信、釘釘?shù)龋┛梢苑浅?焖偻ㄖ竭\(yùn)維人員,相當(dāng)報(bào)警功能,接下來通過本文給大家介紹SpringBoot Admin健康檢查的相關(guān)知識(shí),一起看看吧2021-06-06Java在PowerPoint幻燈片中創(chuàng)建散點(diǎn)圖的方法
散點(diǎn)圖是通過兩組數(shù)據(jù)構(gòu)成多個(gè)坐標(biāo)點(diǎn),考察坐標(biāo)點(diǎn)的分布,判斷兩變量之間是否存在某種關(guān)聯(lián)或總結(jié)坐標(biāo)點(diǎn)的分布模式,這篇文章主要介紹了Java如何在PowerPoint幻燈片中創(chuàng)建散點(diǎn)圖,需要的朋友可以參考下2023-04-04MyBatis批量插入/修改/刪除MySql數(shù)據(jù)
這篇文章主要給大家介紹了關(guān)于MyBatis批量插入/修改/刪除MySql數(shù)據(jù)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05Java 實(shí)用工具類Spring 的 StopWatch常用方法
StopWatch 是 Spring 框架中極其實(shí)用的開發(fā)輔助工具,它為性能分析和調(diào)試提供了輕量但強(qiáng)大的能力,使用簡單、無需復(fù)雜配置,本文給大家介紹Java 實(shí)用工具類Spring 的 StopWatch常用方法,感興趣的朋友一起看看吧2025-04-04