Skip to content
Spring AI 文档版本 2.1.0-SNAPSHOT 源快照 256b453a 更新于 2026-10-16

MCP 客户端注解

MCP 客户端注解提供了一种用 Java 注解实现 MCP 客户端处理器的声明式方式。 这些注解简化了服务端通知与客户端侧操作的处理。

所有 MCP 客户端注解都必须包含一个 clients 参数,以便把处理器关联到某个特定的 MCP 客户端连接。clients 必须匹配你应用属性中配置的连接名。

客户端注解

@McpLogging

@McpLogging 注解处理来自 MCP 服务端的日志消息通知。

基本用法

java
@Component
public class LoggingHandler {

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

带独立参数

java
@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 补全的 sampling 请求。

同步实现

java
@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.ASSISTANT, response, "gpt-4")
            .build();
    }
}

异步实现

java
@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.ASSISTANT, response, "gpt-4")
                .build();
        }).subscribeOn(Schedulers.boundedElastic());
    }
}

@McpElicitation

@McpElicitation 注解处理用于向用户收集额外信息的 elicitation 请求。

基本用法

java
@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);
        }
    }
}

带用户交互

java
@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")) {
        @SuppressWarnings("unchecked")
        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);
}

异步 elicitation

java
@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 注解处理长时间运行操作的进度通知。

基本用法

java
@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()));
    }
}

带独立参数

java
@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);
}

客户端专有的进度

java
@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 注解在服务端工具列表变化时处理通知。

基本用法

java
@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());
        }
    }
}

异步处理

java
@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();
}

客户端专有的工具更新

java
@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 注解在服务端资源列表变化时处理通知。

基本用法

java
@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);
        }
    }
}

带资源分析

java
@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 注解在服务端提示词列表变化时处理通知。

基本用法

java
@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);
        }
    }
}

异步处理

java
@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 自动配置,客户端处理器会被自动检测并注册:

java
@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
    }
}

自动配置将会:

  1. 扫描带 MCP 客户端注解的 bean
  2. 创建合适的规格
  3. 把它们注册到 MCP 客户端
  4. 支持同步与异步两种实现
  5. 用客户端专有处理器处理多个客户端

配置属性

配置客户端注解扫描器与客户端连接:

yaml
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

注解中的 clients 参数必须匹配你配置中定义的连接名。在上面的示例中,有效的 clients 值会是:"my-server"、"tool-server" 和 "local-server"。

与 MCP 客户端一起使用

带注解的处理器会被自动集成到 MCP 客户端:

java
@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 客户端连接,带匹配 clients 的处理器会在相应事件发生时被自动注册并调用。

其他资源

BytesRouter 是社区翻译站点,所有译文仅供参考,一切以官方英文原文为准。