背景
随着人工智能技术的爆发式增长,企业级应用对AI大模型的分析、推理、生成等能力需求日益迫切。然而,传统模型面临“数据孤岛”困境:大量关键业务数据分散在本地系统、专有数据库或第三方服务中,难以通过简单的提示词直接注入模型,导致模型理解受限、决策质量不足。更严峻的是,对于涉及隐私或合规要求的数据(如企业财务信息、医疗记录等),直接暴露给云端模型存在显著安全风险。如何打破数据壁垒,同时确保敏感信息的安全可控,成为AI落地的核心挑战。
在此背景下,模型上下文协议(MCP)应运而生。这一由Anthropic开源的开放协议,为AI模型与外部数据/工具提供了“标准化桥梁”,通过统一的接口规范,使模型能够动态调用本地文件、数据库、API等资源,实现“上下文感知”的智能交互。MCP的核心价值在于:
- 标准化集成:告别“一对一”定制开发,通过协议对接即可连接任意兼容MCP的数据源或工具,大幅降低生态构建成本。
- 安全与灵活性:支持本地部署,数据无需离境,兼顾隐私合规与实时访问需求。
- 智能体赋能:为AI Agent提供“手脚”,使其能自主执行查询、分析、操作等复杂任务流。
而Spring AI作为Java生态中领先的AI开发框架,通过深度集成MCP协议,为开发者提供了企业级解决方案:其模块化架构、对同步/异步通信的支持、以及与Spring Boot的无缝融合,使得构建本地MCP客户端与服务端变得高效且可靠。无论是快速搭建文件系统的本地数据中台,还是构建与业务系统(如CRM、ERP)的实时联动,Spring AI的声明式配置、注解驱动开发模式极大降低了技术门槛。
本文将聚焦于“本地MCP服务建设”实战,详细讲解如何基于Spring AI框架,从零开始搭建MCP客户端与服务端,实现模型与本地资源的的安全交互。通过案例演示,读者将掌握如何通过标准化协议突破数据孤岛,构建既安全可控又具备动态扩展能力的AI应用,为业务智能化升级提供可落地的技术路径。
一、环境准备
1.1 基础环境要求
- JDK:17+(推荐 JDK 21)
- Spring Boot:3.4.5(3.x.x 系列)
- Spring Framework:6.2.6(6.x.x 系列)
- Spring AI:1.0.0-M7+(M6 之前版本存在已知问题)
二、模块架构
2.1 核心模块
三、代码实现
3.1 MCP 客户端
Maven 依赖配置
pom.xml
<dependencies> <!-- Spring AI Starter --> <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-starter-mcp-client-webflux</artifactId> </dependency> <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-starter-model-openai</artifactId> </dependency> <!-- WebFlux 支持 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency> </dependencies> <!-- 打包配置 --> <build> <finalName>${appname}</finalName> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <executions> <execution> <goals><goal>repackage</goal></goals> </execution> </executions> </plugin> </plugins> </build>
Controller示例
McpClientController.java
@RestController @RequestMapping("/service") publicclassMcpClientController { privatefinal ChatClient chatClient; publicMcpClientController(ChatClient.Builder builder, ToolCallbackProvider tools){ this.chatClient = builder.defaultToolCallbacks(tools).build(); } @GetMapping("/query/currentTime/{country}") Flux<String> queryCurrentTime(@PathVariable String country){ returnthis.chatClient .prompt(new PromptTemplate("调用本地工具查询国家{country}当前时间") .create(Map.of("country", country))) .stream() .content(); } }
3.2 MCP 服务端
工具类实现
DateTimeTool.java
@Service publicclassDateTimeTool { privatestaticfinal Map<String, String> COUNTRY_MAP = Map.of( "c1", "2020-02-01 12:00:00", "c2", "2020-02-01 13:00:00" ); @Tool(description = "国家时间查询工具") public String getCurrentDateTimeByCountry(String country){ return COUNTRY_MAP.getOrDefault(country, LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)); } }
服务配置
McpServerApplication.java
@SpringBootApplication publicclassMcpServerApplication { publicstaticvoidmain(String[] args){ SpringApplication.run(McpServerApplication.class, args); } @Bean public ToolCallbackProvider tools(DateTimeTool tool){ return MethodToolCallbackProvider.builder() .toolObjects(tool) .build(); } }
四、关键配置
4.1 客户端配置(application.properties)
application.properties
# 日志调试 logging.level.org.springframework.ai=DEBUG logging.level.io.modelcontextprotocol=DEBUG # OpenAI 配置 spring.ai.openai.base-url=${AI_BASE_URL} spring.ai.openai.api-key=${API_KEY} spring.ai.openai.chat.options.model=qwen-plus # MCP 客户端配置 spring.ai.mcp.client.toolcallback.enabled=true spring.ai.mcp.client.request-timeout=60s spring.ai.mcp.client.root-change-notification=true spring.ai.mcp.client.stdio.servers-configuration=classpath:mcp-service.json
4.2 服务端启动配置(mcp-service.json)
mcp-service.json
{ "mcpServers": { "my-mcp-service": { "command": "java", "args": [ "-Dspring.ai.mcp.server.stdio=true", "-Dspring.main.web-application-type=none", "-Dspring.main.banner-mode=off", "-Dlogging.pattern.console=", "-jar", "/home/admin/app/target/my-mcp-service.jar" ] } } }
重要提示:必须禁用控制台输出,避免污染 stdio 输入流!
五、部署方案
5.1 打包配置(assembly.xml)
<assembly> <id>release</id> <formats><format>tar.gz</format></formats> <includeBaseDirectory>false</includeBaseDirectory> <fileSets> <!-- Client 打包 --> <fileSet> <directory>../mcp-client/target/</directory> <includes><include>*.jar</include></includes> </fileSet> <!-- Server 打包 --> <fileSet> <directory>../mcp-service/target/</directory> <includes><include>*.jar</include></includes> </fileSet> </fileSets> </assembly>
整合 client/server 生成统一部署jar包,支持通过docker进行标准化部署。
六、注意事项
1.构建要求:
- Maven 版本需与构建环境匹配;
- 使用指定 JDK:
baseline.jdk=ajdk-21;
2.协议兼容:
- 确保 stdio 通道纯净,避免日志污染;
- 服务端需禁用 Web 上下文:
-Dspring.main.web-application-type=none;
3.异常处理:
- 关注 stdio 通道的异常日志;
- 建议超时设置 ≥60 秒:
spring.ai.mcp.client.request-timeout=60s。
来源 | 阿里云开发者公众号
作者 | 轻飏