Spring AI 1.0.0-M7实战:手把手教你用@Tool注解快速打造一个MCP Server

发布时间:2026/6/25 0:24:09

Spring AI 1.0.0-M7实战:手把手教你用@Tool注解快速打造一个MCP Server Spring AI 1.0.0-M7实战用Tool注解构建MCP Server的深度指南在当今AI技术快速发展的背景下如何将传统Java服务无缝接入AI生态成为开发者面临的新挑战。Spring AI框架的MCPModel Context Protocol功能提供了一种优雅的解决方案让Java开发者能够以声明式的方式将现有服务快速转化为AI可调用的工具。本文将带您深入探索如何利用Spring AI 1.0.0-M7版本中的Tool注解构建一个功能完备的MCP Server。1. MCP Server基础架构搭建1.1 环境准备与依赖配置构建MCP Server首先需要确保开发环境满足基本要求。Spring AI 1.0.0-M7需要Spring Boot 3.x和JDK 17及以上版本的支持。以下是Maven项目中的关键依赖配置properties java.version17/java.version spring-ai.version1.0.0-M7/spring-ai.version /properties dependencies dependency groupIdorg.springframework.ai/groupId artifactIdspring-ai-starter-mcp-server-webflux/artifactId /dependency /dependencies dependencyManagement dependencies dependency groupIdorg.springframework.ai/groupId artifactIdspring-ai-bom/artifactId version${spring-ai.version}/version typepom/type scopeimport/scope /dependency /dependencies /dependencyManagement注意如果项目同时需要Web和WebFlux支持建议添加相应的Spring Boot Starter依赖。1.2 核心注解解析Tool与ToolParamSpring AI通过Tool和ToolParam注解实现了服务方法的AI工具化转换。这两个注解是构建MCP Server的核心Tool标注在方法级别表示该方法将作为AI可调用的工具description属性提供工具的功能描述这对AI理解工具用途至关重要ToolParam标注在方法参数上描述参数的含义和用途以下是一个简单的EchoService实现示例Service public class EchoService { Tool(description Returns the input message unchanged) public String echo(ToolParam(description The message to echo) String message) { return message; } }2. 高级工具配置与集成2.1 多工具注册与管理实际项目中我们通常需要注册多个服务作为AI工具。Spring AI提供了灵活的配置方式Configuration public class ToolConfiguration { Bean public ToolCallbackProvider toolProvider(EchoService echoService, CalculatorService calculatorService, WeatherService weatherService) { return MethodToolCallbackProvider.builder() .toolObjects(echoService, calculatorService, weatherService) .build(); } }这种配置方式支持同时注册多个服务类自动扫描类中所有Tool标注的方法为每个工具生成详细的元数据描述2.2 工具版本控制与分组对于复杂系统工具版本管理和分组是重要需求。Spring AI允许通过Tool注解的额外属性实现这些功能Service public class AdvancedEchoService { Tool(description Echo service with timestamp, version 1.1, group utility) public String echoWithTimestamp(ToolParam String message) { return String.format([%s] %s, LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME), message); } }3. MCP Server扩展功能3.1 Prompt管理除了工具调用MCP Server还支持Prompt管理可以预定义常用提示模板Configuration public class PromptConfiguration { Bean public ListMcpServerFeatures.SyncPromptSpecification systemPrompts() { var greetingPrompt new McpSchema.Prompt( greeting, Generates a personalized greeting message, List.of(new McpSchema.PromptArgument(name, The name to greet, false)) ); return List.of( new McpServerFeatures.SyncPromptSpecification( greetingPrompt, (exchange, request) - { String name (String) request.arguments().getOrDefault(name, there); String message String.format(Hello %s! How can I assist you today?, name); return new McpSchema.GetPromptResult( Personalized greeting, List.of(new McpSchema.PromptMessage( McpSchema.Role.USER, new McpSchema.TextContent(message) )) ); } ) ); } }3.2 资源管理MCP Server可以管理各类资源如文件、API端点等Configuration public class ResourceConfiguration { Bean public ListMcpServerFeatures.SyncResourceSpecification systemResources() { var logResource new McpSchema.Resource( file:///var/log/app.log, Application Logs, The main application log file, text/plain, new McpSchema.Annotations(List.of(McpSchema.Role.SYSTEM), 0.8) ); return List.of( new McpServerFeatures.SyncResourceSpecification( logResource, (exchange, request) - { try { String logContent Files.readString(Paths.get(/var/log/app.log)); return new McpSchema.ReadResourceResult( List.of(new McpSchema.TextResourceContents( request.uri(), text/plain, logContent )) ); } catch (IOException e) { throw new RuntimeException(Failed to read log file, e); } } ) ); } }4. 客户端交互与测试4.1 单元测试策略完善的测试是保证MCP Server质量的关键。以下是针对工具调用的测试示例SpringBootTest class McpServerIntegrationTest { Autowired private WebTestClient webTestClient; Test void testEchoTool() { webTestClient.post() .uri(/tools/call) .contentType(MediaType.APPLICATION_JSON) .bodyValue( { tool: echo, parameters: { message: test message } } ) .exchange() .expectStatus().isOk() .expectBody() .jsonPath($.result).isEqualTo(test message); } }4.2 客户端集成模式MCP Server支持多种客户端集成方式集成方式协议适用场景配置复杂度WebFluxHTTP/REST远程调用中等SSEServer-Sent Events实时数据流较高Stdio标准输入输出本地调试低以下是SSE方式客户端配置示例# application.yml spring: ai: mcp: client: sse: connections: local-server: url: http://localhost:80805. 性能优化与最佳实践5.1 工具设计原则设计高效的AI工具需要考虑以下因素功能单一性每个工具应专注于完成一个明确的任务描述准确性工具和参数的description属性要清晰准确性能考量避免在工具方法中执行耗时操作错误处理提供有意义的错误信息返回给AI模型5.2 监控与日志完善的监控能帮助及时发现系统问题Aspect Component public class ToolMonitoringAspect { private static final Logger logger LoggerFactory.getLogger(ToolMonitoringAspect.class); Around(annotation(org.springframework.ai.mcp.annotation.Tool)) public Object monitorToolExecution(ProceedingJoinPoint joinPoint) throws Throwable { String toolName ((MethodSignature)joinPoint.getSignature()).getMethod() .getAnnotation(Tool.class).name(); long startTime System.currentTimeMillis(); try { Object result joinPoint.proceed(); long duration System.currentTimeMillis() - startTime; logger.info(Tool {} executed in {} ms, toolName, duration); return result; } catch (Exception e) { logger.error(Tool {} execution failed, toolName, e); throw e; } } }在实际项目中我们团队发现最常出现的问题是工具描述不够准确导致AI模型无法正确调用。建议在开发过程中使用client.listTools()方法定期检查工具元数据是否符合预期。

相关新闻