spring-ai mcp server实战

本文主要研究一下如何使用spring-ai-starter-mcp-server进行自定义mcp server

步骤

pom.xml

复制代码
        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-starter-mcp-server-webmvc</artifactId>
        </dependency>

定义prompts/list方法

复制代码
    /**
     * 必须是list的形式注入才能识别到
     * @return
     */
    @Bean
    public List<McpServerFeatures.SyncPromptSpecification> syncPromptSpecList() {
        return Arrays.asList(demoPromptSpec());
    }

    public McpServerFeatures.SyncPromptSpecification demoPromptSpec() {
        var syncPromptSpecification = new McpServerFeatures.SyncPromptSpecification(
                new McpSchema.Prompt("greeting", "description", List.of(
                        new McpSchema.PromptArgument("name", "description", true)
                )),
                (exchange, request) -> {
                    // Prompt implementation
                    return new McpSchema.GetPromptResult("description", Collections.emptyList());
                }
        );
        return syncPromptSpecification;
    }

定义resources/list方法

复制代码
    /**
     * 必须是list的形式注入才能识别到,自动识别然后实现resources/list接口
     * @return
     */
    @Bean
    public List<McpServerFeatures.SyncResourceSpecification> resourceSpecList() {
        return listResource();
    }

定义resources/read方法

复制代码
    public List<McpServerFeatures.SyncResourceSpecification> resourceSpecList() {
        return Arrays.asList(new McpServerFeatures.SyncResourceSpecification(new McpSchema.Resource("mysql://table1/meta", "table1", "meta data", "text/plain", null), (exchange, request) -> {
            // Resource read implementation
            McpSchema.ResourceContents contents = new McpSchema.TextResourceContents(
                    "meta1", "text/plain", "meta"
            );
            return new McpSchema.ReadResourceResult(Arrays.asList(contents));
        }));
    }

定义tools/list方法

复制代码
    @Bean
    public ToolCallbackProvider dbTools(DemoService demoService) {
        return MethodToolCallbackProvider.builder().toolObjects(demoService).build();
    }

定义tool/call方法

复制代码
@Service
public class DemoService {
	
	@Tool(description = "demo tool query")
	public String query(String param1) {
		return "hello" + param1;
	}
}

源码

syncTools

org/springframework/ai/mcp/server/autoconfigure/McpServerAutoConfiguration.java

复制代码
	@Bean
	@ConditionalOnProperty(prefix = McpServerProperties.CONFIG_PREFIX, name = "type", havingValue = "SYNC",
			matchIfMissing = true)
	public List<McpServerFeatures.SyncToolSpecification> syncTools(ObjectProvider<List<ToolCallback>> toolCalls,
			List<ToolCallback> toolCallbacksList, McpServerProperties serverProperties) {

		List<ToolCallback> tools = new ArrayList<>(toolCalls.stream().flatMap(List::stream).toList());

		if (!CollectionUtils.isEmpty(toolCallbacksList)) {
			tools.addAll(toolCallbacksList);
		}

		return this.toSyncToolSpecifications(tools, serverProperties);
	}

syncTools这一部分把ToolCallback转为SyncToolSpecifications注册到spring中

mcpSyncServer

org/springframework/ai/mcp/server/autoconfigure/McpServerAutoConfiguration.java

复制代码
	@Bean
	@ConditionalOnProperty(prefix = McpServerProperties.CONFIG_PREFIX, name = "type", havingValue = "SYNC",
			matchIfMissing = true)
	public McpSyncServer mcpSyncServer(McpServerTransportProvider transportProvider,
			McpSchema.ServerCapabilities.Builder capabilitiesBuilder, McpServerProperties serverProperties,
			ObjectProvider<List<SyncToolSpecification>> tools,
			ObjectProvider<List<SyncResourceSpecification>> resources,
			ObjectProvider<List<SyncPromptSpecification>> prompts,
			ObjectProvider<BiConsumer<McpSyncServerExchange, List<McpSchema.Root>>> rootsChangeConsumers,
			List<ToolCallbackProvider> toolCallbackProvider) {

		McpSchema.Implementation serverInfo = new Implementation(serverProperties.getName(),
				serverProperties.getVersion());

		// Create the server with both tool and resource capabilities
		SyncSpecification serverBuilder = McpServer.sync(transportProvider).serverInfo(serverInfo);

		List<SyncToolSpecification> toolSpecifications = new ArrayList<>(tools.stream().flatMap(List::stream).toList());

		List<ToolCallback> providerToolCallbacks = toolCallbackProvider.stream()
			.map(pr -> List.of(pr.getToolCallbacks()))
			.flatMap(List::stream)
			.filter(fc -> fc instanceof ToolCallback)
			.map(fc -> (ToolCallback) fc)
			.toList();

		toolSpecifications.addAll(this.toSyncToolSpecifications(providerToolCallbacks, serverProperties));

		if (!CollectionUtils.isEmpty(toolSpecifications)) {
			serverBuilder.tools(toolSpecifications);
			capabilitiesBuilder.tools(serverProperties.isToolChangeNotification());
			logger.info("Registered tools: " + toolSpecifications.size() + ", notification: "
					+ serverProperties.isToolChangeNotification());
		}

		List<SyncResourceSpecification> resourceSpecifications = resources.stream().flatMap(List::stream).toList();
		if (!CollectionUtils.isEmpty(resourceSpecifications)) {
			serverBuilder.resources(resourceSpecifications);
			capabilitiesBuilder.resources(false, serverProperties.isResourceChangeNotification());
			logger.info("Registered resources: " + resourceSpecifications.size() + ", notification: "
					+ serverProperties.isResourceChangeNotification());
		}

		List<SyncPromptSpecification> promptSpecifications = prompts.stream().flatMap(List::stream).toList();
		if (!CollectionUtils.isEmpty(promptSpecifications)) {
			serverBuilder.prompts(promptSpecifications);
			capabilitiesBuilder.prompts(serverProperties.isPromptChangeNotification());
			logger.info("Registered prompts: " + promptSpecifications.size() + ", notification: "
					+ serverProperties.isPromptChangeNotification());
		}

		rootsChangeConsumers.ifAvailable(consumer -> {
			serverBuilder.rootsChangeHandler((exchange, roots) -> {
				consumer.accept(exchange, roots);
			});
			logger.info("Registered roots change consumer");
		});

		serverBuilder.capabilities(capabilitiesBuilder.build());

		return serverBuilder.build();
	}

mcpSyncServer会把注入的List、List、List、List设置到serverBuilder的tools、resources、prompts中

小结

spring ai mcp server通过McpServerAutoConfiguration把托管给spring的List、List、List、List设置到serverBuilder的tools、resources、prompts中。如果代码要自定义resources、prompts,直接注入List、List即可。tools的话,在托管bean的方法中注解@Tool就可以。

doc

相关推荐
云知谷1 小时前
【C++基本功】C++适合做什么,哪些领域适合哪些领域不适合?
c语言·开发语言·c++·人工智能·团队开发
rit84324992 小时前
基于MATLAB实现基于距离的离群点检测算法
人工智能·算法·matlab
不吃凉粉3 小时前
Android Studio USB串口通信
android·ide·android studio
初学小刘3 小时前
深度学习:从图片数据到模型训练(十分类)
人工智能·深度学习
zhangphil3 小时前
android studio设置大内存,提升编译速度
android·android studio
递归不收敛3 小时前
大语言模型(LLM)入门笔记:嵌入向量与位置信息
人工智能·笔记·语言模型
编程乐学4 小时前
安卓非原创--基于Android Studio 实现的天气预报App
android·ide·android studio·课程设计·大作业·天气预报·安卓大作业
之墨_4 小时前
【大语言模型】—— 自注意力机制及其变体(交叉注意力、因果注意力、多头注意力)的代码实现
人工智能·语言模型·自然语言处理
从孑开始5 小时前
ManySpeech.MoonshineAsr 使用指南
人工智能·ai·c#·.net·私有化部署·语音识别·onnx·asr·moonshine
涛涛讲AI5 小时前
一段音频多段字幕,让音频能够流畅自然对应字幕 AI生成视频,扣子生成剪映视频草稿
人工智能·音视频·语音识别