spring-ai 1.0.0 学习(十八)——MCP Server
上一篇学习了如何调用外部工具,这一篇我们看看如何将自己的服务发布为外部工具,供他人调用
最小化样例
与使用Mcp Client一样,分为三步,引入依赖,添加配置,修改代码
<dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-starter-mcp-server</artifactId></dependency><dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-starter-mcp-server-webflux</artifactId></dependency><dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-starter-mcp-server-webmvc</artifactId></dependency>
根据自身需要引入上述三个依赖之一,分别对应STDIO、WebFlux、Http模式
以http为例,在application文件中添加如下配置
# Using spring-ai-starter-mcp-server-webmvc
spring:ai:mcp:server:name: webmvc-mcp-serverversion: 1.0.0type: SYNCinstructions: "This server provides weather information tools and resources"sse-message-endpoint: /mcp/messagescapabilities: tool: true #是否开启工具resource: true #是否开启资源prompt: true #是否开启提示词completion: true #是否开启补全
instructions用来介绍当前服务器提供的功能
然后将想要暴露的服务上添加Tool注解
@Service
public class WeatherService {@Tool(description = "Get weather information by city name")public String getWeather(String cityName) {// Implementation}
}
之后将服务注册为ToolCallbackProvider
@SpringBootApplication
public class McpServerApplication {public static void main(String[] args) {SpringApplication.run(McpServerApplication.class, args);}@Beanpublic ToolCallbackProvider weatherTools(WeatherService weatherService) {return MethodToolCallbackProvider.builder().toolObjects(weatherService).build();}
}
然后就可以通过MCP Client进行调用了
进阶知识
内部原理
以http为例,spring-ai首先会将spring.ai.mcp.server相关配置注入McpServerProperties
然后根据McpServerProperties创建WebMvcSseServerTransportProvider,负责创建并管理会话
之后根据WebMvcSseServerTransportProvider、注册的ToolCallbackProvider等组件,创建McpSyncServer
McpSyncServer内部包含了服务器信息(如服务器介绍、支持的能力等)和具体的能力(如工具列表),在构造函数中,声明了一系列的请求及其处理器(例如工具相关请求tool/list和tool/call)
每当WebMvcSseServerTransportProvider收到会话请求,就会创建一个McpServerSession,并将McpSyncServer中声明的请求及处理器交给McpServerSession
McpServerSession根据请求路径选择相应的处理器进行处理