RainYuY commented on code in PR #15406: URL: https://github.com/apache/dubbo/pull/15406#discussion_r2268633213
########## dubbo-plugin/dubbo-mcp/src/main/java/org/apache/dubbo/mcp/tool/DubboServiceToolRegistry.java: ########## @@ -0,0 +1,469 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.mcp.tool; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.LoggerCodeConstants; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; +import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.mcp.JsonSchemaType; +import org.apache.dubbo.mcp.McpConstant; +import org.apache.dubbo.mcp.annotations.McpToolParam; +import org.apache.dubbo.mcp.core.McpServiceFilter; +import org.apache.dubbo.mcp.util.TypeSchemaUtils; +import org.apache.dubbo.rpc.model.ProviderModel; +import org.apache.dubbo.rpc.model.ServiceDescriptor; +import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.MethodMeta; +import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta; +import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ServiceMeta; +import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Operation; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.BiFunction; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.modelcontextprotocol.server.McpAsyncServer; +import io.modelcontextprotocol.server.McpAsyncServerExchange; +import io.modelcontextprotocol.server.McpServerFeatures; +import io.modelcontextprotocol.spec.McpSchema; +import reactor.core.publisher.Mono; + +public class DubboServiceToolRegistry { + + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(DubboServiceToolRegistry.class); + + private final McpAsyncServer mcpServer; + private final DubboOpenApiToolConverter toolConverter; + private final DubboMcpGenericCaller genericCaller; + private final McpServiceFilter mcpServiceFilter; + private final Map<String, McpServerFeatures.AsyncToolSpecification> registeredTools = new ConcurrentHashMap<>(); + private final Map<String, Set<String>> serviceToToolsMapping = new ConcurrentHashMap<>(); + private final ObjectMapper objectMapper; + + public DubboServiceToolRegistry( + McpAsyncServer mcpServer, + DubboOpenApiToolConverter toolConverter, + DubboMcpGenericCaller genericCaller, + McpServiceFilter mcpServiceFilter) { + this.mcpServer = mcpServer; + this.toolConverter = toolConverter; + this.genericCaller = genericCaller; + this.mcpServiceFilter = mcpServiceFilter; + this.objectMapper = new ObjectMapper(); + } + + public int registerService(ProviderModel providerModel) { + ServiceDescriptor serviceDescriptor = providerModel.getServiceModel(); + List<URL> statedURLs = providerModel.getServiceUrls(); + + if (statedURLs == null || statedURLs.isEmpty()) { + return 0; + } + + try { + URL url = statedURLs.get(0); + int registeredCount = 0; + String serviceKey = getServiceKey(providerModel); + Set<String> toolNames = new HashSet<>(); + + Class<?> serviceInterface = serviceDescriptor.getServiceInterfaceClass(); + if (serviceInterface == null) { + return 0; + } + + Method[] methods = serviceInterface.getDeclaredMethods(); + boolean shouldRegisterServiceLevel = mcpServiceFilter.shouldExposeAsMcpTool(providerModel); + + for (Method method : methods) { + if (mcpServiceFilter.shouldExposeMethodAsMcpTool(providerModel, method)) { + McpServiceFilter.McpToolConfig toolConfig = + mcpServiceFilter.getMcpToolConfig(providerModel, method); + + String toolName = registerMethodAsTool(providerModel, method, url, toolConfig); + if (toolName != null) { + toolNames.add(toolName); + registeredCount++; + } + } + } + + if (registeredCount == 0 && shouldRegisterServiceLevel) { + Set<String> serviceToolNames = registerServiceLevelTools(providerModel, url); + toolNames.addAll(serviceToolNames); + registeredCount = serviceToolNames.size(); + } + + if (registeredCount > 0) { + serviceToToolsMapping.put(serviceKey, toolNames); + logger.info( + "Registered {} MCP tools for service: {}", + registeredCount, + serviceDescriptor.getInterfaceName()); + } + + return registeredCount; + + } catch (Exception e) { + logger.error( + LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION, + "", + "", + "Failed to register service as MCP tools: " + serviceDescriptor.getInterfaceName(), + e); + return 0; + } + } + + public void unregisterService(ProviderModel providerModel) { + String serviceKey = getServiceKey(providerModel); + Set<String> toolNames = serviceToToolsMapping.remove(serviceKey); + + if (toolNames == null || toolNames.isEmpty()) { + return; + } + + int unregisteredCount = 0; + for (String toolName : toolNames) { + try { + McpServerFeatures.AsyncToolSpecification toolSpec = registeredTools.remove(toolName); + if (toolSpec != null) { + mcpServer.removeTool(toolName).block(); + unregisteredCount++; + } + } catch (Exception e) { + logger.error( + LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION, + "", + "", + "Failed to unregister MCP tool: " + toolName, + e); + } + } + + if (unregisteredCount > 0) { + logger.info( + "Unregistered {} MCP tools for service: {}", + unregisteredCount, + providerModel.getServiceModel().getInterfaceName()); + } + } + + private String getServiceKey(ProviderModel providerModel) { + return providerModel.getServiceKey(); + } + + private String registerMethodAsTool( + ProviderModel providerModel, Method method, URL url, McpServiceFilter.McpToolConfig toolConfig) { + try { + String toolName = toolConfig.getToolName(); + if (toolName == null || toolName.isEmpty()) { + toolName = method.getName(); + } + + if (registeredTools.containsKey(toolName)) { + return null; + } + + String description = toolConfig.getDescription(); + if (description == null || description.isEmpty()) { + description = generateDefaultDescription(method, providerModel); + } + + McpSchema.Tool mcpTool = new McpSchema.Tool(toolName, description, generateToolSchema(method)); Review Comment: I believe asynchronous loading is not a suitable solution, as it may prevent the application from detecting the MCP server after startup. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
