无论是使用最新正式版的 Spring AI,还是最新正式版 Spring AI Alibaba,在实现自定义 MCP 服务器端和客户端的时候,一定要注意这两个问题,不然你会发现你的 MCP 服务器端能启动,但客户端就是连接不上,并且控制台也都是误报信息。
注意事项一
自定义 MCP 服务器端添加依赖时,如果是非标准 stdio 模式,当前项目一定要记得排除掉 spring-boot-starter-web 依赖:
复制<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
也就是说,你的 spring-ai-starter-mcp-server-webflux 依赖不能和 spring-boot-starter-web 依赖并存,以下是错误配置:
复制<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-starter-mcp-server-webflux</artifactId> </dependency>
因为当有 spring-boot-starter-web 依赖时会默认使用 tomcat 启动服务,这样项目虽然启动了,但 mcp service 服务并未启动,mcp service 服务是使用 netty 启动的,如下图所示:
图片
注意事项二
Spring AI 正式版之后,在使用客户端注册 MCP 工具时要使用 ToolCallbacks 而不是 Tools,如果在新版本中使用后者就会启动报错。
错误用法
复制@Bean public ChatClient chatClient(ChatModel chatModel, ToolCallbackProvider tools) { return ChatClient .builder(chatModel) .defaultTools(tools.getToolCallbacks()) .build(); }
或者以下方式也是错误的:
复制@Bean public ChatClient chatClient(ChatModel chatModel, ToolCallbackProvider tools) { return ChatClient .builder(chatModel) .defaultTools(tools) .build(); }
正确用法
复制@Bean public ChatClient chatClient(ChatModel chatModel, ToolCallbackProvider tools) { return ChatClient .builder(chatModel) .defaultToolCallbacks(tools.getToolCallbacks()) .build(); }
小结
在进行 Spring AI 或 Spring AI Alibaba 老项目升级时,或使用最新正式版框架时,一定要注意这两个问题,不然就会导致自定义的 MCP 服务能启动,但客户端就是连接不上的问题。