MCP 客户端注释

MCP 客户端注释提供了一种声明式方式,利用 Java 注释实现 MCP 客户端处理器。 这些注释简化了服务器通知和客户端作的处理。spring-doc.cadn.net.cn

所有MCP客户端注释必须包含客户端参数将处理器与特定的MCP客户端连接关联。这客户端必须与你应用属性中配置的连接名称匹配。

客户端注释

@McpLogging

@McpLogging注释处理来自MCP服务器的日志消息通知。spring-doc.cadn.net.cn

基本用途

@Component
public class LoggingHandler {

    @McpLogging(clients = "my-mcp-server")
    public void handleLoggingMessage(LoggingMessageNotification notification) {
        System.out.println("Received log: " + notification.level() +
                          " - " + notification.data());
    }
}

具有个别参数

@McpLogging(clients = "my-mcp-server")
public void handleLoggingWithParams(LoggingLevel level, String logger, String data) {
    System.out.println(String.format("[%s] %s: %s", level, logger, data));
}

@McpSampling

@McpSampling注释处理来自MCP服务器的LLM完成采样请求。spring-doc.cadn.net.cn

同步实现

@Component
public class SamplingHandler {

    @McpSampling(clients = "llm-server")
    public CreateMessageResult handleSamplingRequest(CreateMessageRequest request) {
        // Process the request and generate a response
        String response = generateLLMResponse(request);

        return CreateMessageResult.builder()
            .role(Role.ASSISTANT)
            .content(new TextContent(response))
            .model("gpt-4")
            .build();
    }
}

异步实现

@Component
public class AsyncSamplingHandler {

    @McpSampling(clients = "llm-server")
    public Mono<CreateMessageResult> handleAsyncSampling(CreateMessageRequest request) {
        return Mono.fromCallable(() -> {
            String response = generateLLMResponse(request);

            return CreateMessageResult.builder()
                .role(Role.ASSISTANT)
                .content(new TextContent(response))
                .model("gpt-4")
                .build();
        }).subscribeOn(Schedulers.boundedElastic());
    }
}

@McpElicitation

@McpElicitation注释处理引出请求以收集用户的额外信息。spring-doc.cadn.net.cn

基本用途

@Component
public class ElicitationHandler {

    @McpElicitation(clients = "interactive-server")
    public ElicitResult handleElicitationRequest(ElicitRequest request) {
        // Present the request to the user and gather input
        Map<String, Object> userData = presentFormToUser(request.requestedSchema());

        if (userData != null) {
            return new ElicitResult(ElicitResult.Action.ACCEPT, userData);
        } else {
            return new ElicitResult(ElicitResult.Action.DECLINE, null);
        }
    }
}

与用户互动

@McpElicitation(clients = "interactive-server")
public ElicitResult handleInteractiveElicitation(ElicitRequest request) {
    Map<String, Object> schema = request.requestedSchema();
    Map<String, Object> userData = new HashMap<>();

    // Check what information is being requested
    if (schema != null && schema.containsKey("properties")) {
        Map<String, Object> properties = (Map<String, Object>) schema.get("properties");

        // Gather user input based on schema
        if (properties.containsKey("name")) {
            userData.put("name", promptUser("Enter your name:"));
        }
        if (properties.containsKey("email")) {
            userData.put("email", promptUser("Enter your email:"));
        }
        if (properties.containsKey("preferences")) {
            userData.put("preferences", gatherPreferences());
        }
    }

    return new ElicitResult(ElicitResult.Action.ACCEPT, userData);
}

异步引发

@McpElicitation(clients = "interactive-server")
public Mono<ElicitResult> handleAsyncElicitation(ElicitRequest request) {
    return Mono.fromCallable(() -> {
        // Async user interaction
        Map<String, Object> userData = asyncGatherUserInput(request);
        return new ElicitResult(ElicitResult.Action.ACCEPT, userData);
    }).timeout(Duration.ofSeconds(30))
      .onErrorReturn(new ElicitResult(ElicitResult.Action.CANCEL, null));
}

@McpProgress

@McpProgress注释处理长期运行作的进度通知。spring-doc.cadn.net.cn

基本用途

@Component
public class ProgressHandler {

    @McpProgress(clients = "my-mcp-server")
    public void handleProgressNotification(ProgressNotification notification) {
        double percentage = notification.progress() * 100;
        System.out.println(String.format("Progress: %.2f%% - %s",
            percentage, notification.message()));
    }
}

具有个别参数

@McpProgress(clients = "my-mcp-server")
public void handleProgressWithDetails(
        String progressToken,
        double progress,
        Double total,
        String message) {

    if (total != null) {
        System.out.println(String.format("[%s] %.0f/%.0f - %s",
            progressToken, progress, total, message));
    } else {
        System.out.println(String.format("[%s] %.2f%% - %s",
            progressToken, progress * 100, message));
    }

    // Update UI progress bar
    updateProgressBar(progressToken, progress);
}

客户特定进展

@McpProgress(clients = "long-running-server")
public void handleLongRunningProgress(ProgressNotification notification) {
    // Track progress for specific server
    progressTracker.update("long-running-server", notification);

    // Send notifications if needed
    if (notification.progress() >= 1.0) {
        notifyCompletion(notification.progressToken());
    }
}

@McpToolListChanged

@McpToolListChanged注释处理服务器工具列表变化时的通知。spring-doc.cadn.net.cn

基本用途

@Component
public class ToolListChangedHandler {

    @McpToolListChanged(clients = "tool-server")
    public void handleToolListChanged(List<McpSchema.Tool> updatedTools) {
        System.out.println("Tool list updated: " + updatedTools.size() + " tools available");

        // Update local tool registry
        toolRegistry.updateTools(updatedTools);

        // Log new tools
        for (McpSchema.Tool tool : updatedTools) {
            System.out.println("  - " + tool.name() + ": " + tool.description());
        }
    }
}

异步处理

@McpToolListChanged(clients = "tool-server")
public Mono<Void> handleAsyncToolListChanged(List<McpSchema.Tool> updatedTools) {
    return Mono.fromRunnable(() -> {
        // Process tool list update asynchronously
        processToolListUpdate(updatedTools);

        // Notify interested components
        eventBus.publish(new ToolListUpdatedEvent(updatedTools));
    }).then();
}

客户端专用工具更新

@McpToolListChanged(clients = "dynamic-server")
public void handleDynamicServerToolUpdate(List<McpSchema.Tool> updatedTools) {
    // Handle tools from a specific server that frequently changes its tools
    dynamicToolManager.updateServerTools("dynamic-server", updatedTools);

    // Re-evaluate tool availability
    reevaluateToolCapabilities();
}

@McpResourceListChanged

@McpResourceListChanged注释处理服务器资源列表变化时的通知。spring-doc.cadn.net.cn

基本用途

@Component
public class ResourceListChangedHandler {

    @McpResourceListChanged(clients = "resource-server")
    public void handleResourceListChanged(List<McpSchema.Resource> updatedResources) {
        System.out.println("Resources updated: " + updatedResources.size());

        // Update resource cache
        resourceCache.clear();
        for (McpSchema.Resource resource : updatedResources) {
            resourceCache.register(resource);
        }
    }
}

与资源分析合作

@McpResourceListChanged(clients = "resource-server")
public void analyzeResourceChanges(List<McpSchema.Resource> updatedResources) {
    // Analyze what changed
    Set<String> newUris = updatedResources.stream()
        .map(McpSchema.Resource::uri)
        .collect(Collectors.toSet());

    Set<String> removedUris = previousUris.stream()
        .filter(uri -> !newUris.contains(uri))
        .collect(Collectors.toSet());

    if (!removedUris.isEmpty()) {
        handleRemovedResources(removedUris);
    }

    // Update tracking
    previousUris = newUris;
}

@McpPromptListChanged

@McpPromptListChanged注释处理服务器提示列表变化时的通知。spring-doc.cadn.net.cn

基本用途

@Component
public class PromptListChangedHandler {

    @McpPromptListChanged(clients = "prompt-server")
    public void handlePromptListChanged(List<McpSchema.Prompt> updatedPrompts) {
        System.out.println("Prompts updated: " + updatedPrompts.size());

        // Update prompt catalog
        promptCatalog.updatePrompts(updatedPrompts);

        // Refresh UI if needed
        if (uiController != null) {
            uiController.refreshPromptList(updatedPrompts);
        }
    }
}

异步处理

@McpPromptListChanged(clients = "prompt-server")
public Mono<Void> handleAsyncPromptUpdate(List<McpSchema.Prompt> updatedPrompts) {
    return Flux.fromIterable(updatedPrompts)
        .flatMap(prompt -> validatePrompt(prompt))
        .collectList()
        .doOnNext(validPrompts -> {
            promptRepository.saveAll(validPrompts);
        })
        .then();
}

Spring Boot 集成

通过 Spring Boot 自动配置,客户端处理器会自动被检测并注册:spring-doc.cadn.net.cn

@SpringBootApplication
public class McpClientApplication {
    public static void main(String[] args) {
        SpringApplication.run(McpClientApplication.class, args);
    }
}

@Component
public class MyClientHandlers {

    @McpLogging(clients = "my-server")
    public void handleLogs(LoggingMessageNotification notification) {
        // Handle logs
    }

    @McpSampling(clients = "my-server")
    public CreateMessageResult handleSampling(CreateMessageRequest request) {
        // Handle sampling
    }

    @McpProgress(clients = "my-server")
    public void handleProgress(ProgressNotification notification) {
        // Handle progress
    }
}

自动配置将:spring-doc.cadn.net.cn

  1. 用MCP客户端注释扫描豆子spring-doc.cadn.net.cn

  2. 制定合适的规范spring-doc.cadn.net.cn

  3. 向MCP客户端注册spring-doc.cadn.net.cn

  4. 支持同步和异步实现spring-doc.cadn.net.cn

  5. 用客户端专用处理器处理多个客户端spring-doc.cadn.net.cn

配置属性

配置客户端注释扫描器和客户端连接:spring-doc.cadn.net.cn

spring:
  ai:
    mcp:
      client:
        type: SYNC  # or ASYNC
        annotation-scanner:
          enabled: true
        # Configure client connections - the connection names become clients values
        sse:
          connections:
            my-server:  # This becomes the clients
              url: http://localhost:8080
            tool-server:  # Another clients
              url: http://localhost:8081
        stdio:
          connections:
            local-server:  # This becomes the clients
              command: /path/to/mcp-server
              args:
                - --mode=production
客户端注释中的参数必须与配置中定义的连接名称相匹配。在上述例子中,有效客户端值为:“我的服务器”,“工具服务器”“本地服务器”.

MCP客户端的使用

注释处理程序会自动与MCP客户端集成:spring-doc.cadn.net.cn

@Autowired
private List<McpSyncClient> mcpClients;

// The clients will automatically use your annotated handlers based on clients
// No manual registration needed - handlers are matched to clients by name

对于每个MCP客户端连接,处理程序与匹配客户端当相应事件发生时,会自动注册并被调用。spring-doc.cadn.net.cn