MCP 服务器注释

MCP 服务器注释为使用 Java 注释实现 MCP 服务器功能提供了声明式方式。 这些注释简化了工具、资源、提示和完成处理程序的创建。spring-doc.cadn.net.cn

服务器注释

@McpTool

@McpTool注释标记方法为MCP工具实现,并自动生成JSON模式。spring-doc.cadn.net.cn

基本用途

@Component
public class CalculatorTools {

    @McpTool(name = "add", description = "Add two numbers together")
    public int add(
            @McpToolParam(description = "First number", required = true) int a,
            @McpToolParam(description = "Second number", required = true) int b) {
        return a + b;
    }
}

高级功能

@McpTool(name = "calculate-area",
         description = "Calculate the area of a rectangle",
         annotations = McpTool.McpAnnotations(
             title = "Rectangle Area Calculator",
             readOnlyHint = true,
             destructiveHint = false,
             idempotentHint = true
         ))
public AreaResult calculateRectangleArea(
        @McpToolParam(description = "Width", required = true) double width,
        @McpToolParam(description = "Height", required = true) double height) {

    return new AreaResult(width * height, "square units");
}

附请求上下文

工具可以访问高级作的请求上下文:spring-doc.cadn.net.cn

@McpTool(name = "process-data", description = "Process data with request context")
public String processData(
        McpSyncRequestContext context,
        @McpToolParam(description = "Data to process", required = true) String data) {

    // Send logging notification
    context.info("Processing data: " + data);

    // Send progress notification (using convenient method)
    context.progress(p -> p.progress(0.5).total(1.0).message("Processing..."));

    // Ping the client
    context.ping();

    return "Processed: " + data.toUpperCase();
}

动态模式支持

工具可以接受呼叫工具请求对于运行时模式处理:spring-doc.cadn.net.cn

@McpTool(name = "flexible-tool", description = "Process dynamic schema")
public CallToolResult processDynamic(CallToolRequest request) {
    Map<String, Object> args = request.arguments();

    // Process based on runtime schema
    String result = "Processed " + args.size() + " arguments dynamically";

    return CallToolResult.builder()
        .addTextContent(result)
        .build();
}

进展追踪

工具可以接收进度Tokens以跟踪长期运行的作:spring-doc.cadn.net.cn

@McpTool(name = "long-task", description = "Long-running task with progress")
public String performLongTask(
        McpSyncRequestContext context,
        @McpToolParam(description = "Task name", required = true) String taskName) {

    // Access progress token from context
    String progressToken = context.request().progressToken();

    if (progressToken != null) {
        context.progress(p -> p.progress(0.0).total(1.0).message("Starting task"));

        // Perform work...

        context.progress(p -> p.progress(1.0).total(1.0).message("Task completed"));
    }

    return "Task " + taskName + " completed";
}

@McpResource

@McpResource注释通过URI模板提供资源访问。spring-doc.cadn.net.cn

基本用途

@Component
public class ResourceProvider {

    @McpResource(
        uri = "config://{key}",
        name = "Configuration",
        description = "Provides configuration data")
    public String getConfig(String key) {
        return configData.get(key);
    }
}

使用 ReadResourceResult

@McpResource(
    uri = "user-profile://{username}",
    name = "User Profile",
    description = "Provides user profile information")
public ReadResourceResult getUserProfile(String username) {
    String profileData = loadUserProfile(username);

    return new ReadResourceResult(List.of(
        new TextResourceContents(
            "user-profile://" + username,
            "application/json",
            profileData)
    ));
}

附请求上下文

@McpResource(
    uri = "data://{id}",
    name = "Data Resource",
    description = "Resource with request context")
public ReadResourceResult getData(
        McpSyncRequestContext context,
        String id) {

    // Send logging notification using convenient method
    context.info("Accessing resource: " + id);

    // Ping the client
    context.ping();

    String data = fetchData(id);

    return new ReadResourceResult(List.of(
        new TextResourceContents("data://" + id, "text/plain", data)
    ));
}

@McpPrompt

@McpPrompt注释为 AI 互动生成提示消息。spring-doc.cadn.net.cn

基本用途

@Component
public class PromptProvider {

    @McpPrompt(
        name = "greeting",
        description = "Generate a greeting message")
    public GetPromptResult greeting(
            @McpArg(name = "name", description = "User's name", required = true)
            String name) {

        String message = "Hello, " + name + "! How can I help you today?";

        return new GetPromptResult(
            "Greeting",
            List.of(new PromptMessage(Role.ASSISTANT, new TextContent(message)))
        );
    }
}

附带可选参数

@McpPrompt(
    name = "personalized-message",
    description = "Generate a personalized message")
public GetPromptResult personalizedMessage(
        @McpArg(name = "name", required = true) String name,
        @McpArg(name = "age", required = false) Integer age,
        @McpArg(name = "interests", required = false) String interests) {

    StringBuilder message = new StringBuilder();
    message.append("Hello, ").append(name).append("!\n\n");

    if (age != null) {
        message.append("At ").append(age).append(" years old, ");
        // Add age-specific content
    }

    if (interests != null && !interests.isEmpty()) {
        message.append("Your interest in ").append(interests);
        // Add interest-specific content
    }

    return new GetPromptResult(
        "Personalized Message",
        List.of(new PromptMessage(Role.ASSISTANT, new TextContent(message.toString())))
    );
}

@McpComplete

@McpComplete注释为提示提供自动补全功能。spring-doc.cadn.net.cn

基本用途

@Component
public class CompletionProvider {

    @McpComplete(prompt = "city-search")
    public List<String> completeCityName(String prefix) {
        return cities.stream()
            .filter(city -> city.toLowerCase().startsWith(prefix.toLowerCase()))
            .limit(10)
            .toList();
    }
}

使用 CompleteRequest.CompleteArgument

@McpComplete(prompt = "travel-planner")
public List<String> completeTravelDestination(CompleteRequest.CompleteArgument argument) {
    String prefix = argument.value().toLowerCase();
    String argumentName = argument.name();

    // Different completions based on argument name
    if ("city".equals(argumentName)) {
        return completeCities(prefix);
    } else if ("country".equals(argumentName)) {
        return completeCountries(prefix);
    }

    return List.of();
}

与CompleteResult合作

@McpComplete(prompt = "code-completion")
public CompleteResult completeCode(String prefix) {
    List<String> completions = generateCodeCompletions(prefix);

    return new CompleteResult(
        new CompleteResult.CompleteCompletion(
            completions,
            completions.size(),  // total
            hasMoreCompletions   // hasMore flag
        )
    );
}

无状态实现与有状态实现

McpSyncRequestContextMcpAsync请求上下文对于一个兼容有状态和无状态作的统一接口:spring-doc.cadn.net.cn

public record UserInfo(String name, String email, int age) {}

@McpTool(name = "unified-tool", description = "Tool with unified request context")
public String unifiedTool(
        McpSyncRequestContext context,
        @McpToolParam(description = "Input", required = true) String input) {

    // Access request and metadata
    String progressToken = context.request().progressToken();

    // Logging with convenient methods
    context.info("Processing: " + input);

    // Progress notifications (Note client should set a progress token
    // with its request to be able to receive progress updates)
    context.progress(50); // Simple percentage

    // Ping client
    context.ping();

    // Check capabilities before using
    if (context.elicitEnabled()) {
        // Request user input (only in stateful mode)
        StructuredElicitResult<UserInfo> elicitResult = context.elicit(UserInfo.class);
        if (elicitResult.action() == ElicitResult.Action.ACCEPT) {
            // Use elicited data
        }
    }

    if (context.sampleEnabled()) {
        // Request LLM sampling (only in stateful mode)
        CreateMessageResult samplingResult = context.sample("Generate response");
        // Use sampling result
    }

    return "Processed with unified context";
}

简单作(无上下文)

对于简单的作,你可以完全省略上下文参数:spring-doc.cadn.net.cn

@McpTool(name = "simple-add", description = "Simple addition")
public int simpleAdd(
        @McpToolParam(description = "First number", required = true) int a,
        @McpToolParam(description = "Second number", required = true) int b) {
    return a + b;
}

轻量级无状态(使用 McpTransportContext)

对于无状态作,需要最少的传输上下文:spring-doc.cadn.net.cn

@McpTool(name = "stateless-tool", description = "Stateless with transport context")
public String statelessTool(
        McpTransportContext context,
        @McpToolParam(description = "Input", required = true) String input) {
    // Access transport-level context only
    // No bidirectional operations (roots, elicitation, sampling)
    return "Processed: " + input;
}
无状态服务器不支持双向作:

因此,以下方法McpSyncRequestContextMcpAsync请求上下文在无状态模式下,会被忽略。spring-doc.cadn.net.cn

按服务器类型进行方法过滤

MCP 注释框架自动根据服务器类型和方法特性过滤注释方法。这确保每个服务器配置只注册合适的方法。 每个过滤方法都会记录警告,以便调试。spring-doc.cadn.net.cn

同步过滤与异步过滤

同步服务器

同步服务器(配置为spring.ai.mcp.server.type=SYNC)使用以下条件的同步提供者:spring-doc.cadn.net.cn

@Component
public class SyncTools {

    @McpTool(name = "sync-tool", description = "Synchronous tool")
    public String syncTool(String input) {
        // This method WILL be registered on sync servers
        return "Processed: " + input;
    }

    @McpTool(name = "async-tool", description = "Async tool")
    public Mono<String> asyncTool(String input) {
        // This method will be FILTERED OUT on sync servers
        // A warning will be logged
        return Mono.just("Processed: " + input);
    }
}

异步服务器

异步服务器(配置为spring.ai.mcp.server.type=ASYNC)使用异步提供者,满足以下条件:spring-doc.cadn.net.cn

@Component
public class AsyncTools {

    @McpTool(name = "async-tool", description = "Async tool")
    public Mono<String> asyncTool(String input) {
        // This method WILL be registered on async servers
        return Mono.just("Processed: " + input);
    }

    @McpTool(name = "sync-tool", description = "Sync tool")
    public String syncTool(String input) {
        // This method will be FILTERED OUT on async servers
        // A warning will be logged
        return "Processed: " + input;
    }
}

有状态过滤与无状态过滤

有状态服务器

有状态服务器支持双向通信,并接受以下方法:spring-doc.cadn.net.cn

@Component
public class StatefulTools {

    @McpTool(name = "interactive-tool", description = "Tool with bidirectional operations")
    public String interactiveTool(
            McpSyncRequestContext context,
            @McpToolParam(description = "Input", required = true) String input) {

        // This method WILL be registered on stateful servers
        // Can use elicitation, sampling, roots
        if (context.sampleEnabled()) {
            var samplingResult = context.sample("Generate response");
            // Process sampling result...
        }

        return "Processed with context";
    }
}

无状态服务器

无状态服务器针对简单的请求-响应模式进行了优化,并且:spring-doc.cadn.net.cn

@Component
public class StatelessTools {

    @McpTool(name = "simple-tool", description = "Simple stateless tool")
    public String simpleTool(@McpToolParam(description = "Input") String input) {
        // This method WILL be registered on stateless servers
        return "Processed: " + input;
    }

    @McpTool(name = "context-tool", description = "Tool with transport context")
    public String contextTool(
            McpTransportContext context,
            @McpToolParam(description = "Input") String input) {
        // This method WILL be registered on stateless servers
        return "Processed: " + input;
    }

    @McpTool(name = "bidirectional-tool", description = "Tool with bidirectional context")
    public String bidirectionalTool(
            McpSyncRequestContext context,
            @McpToolParam(description = "Input") String input) {
        // This method will be FILTERED OUT on stateless servers
        // A warning will be logged
        return "Processed with sampling";
    }
}

过滤摘要

服务器类型 公认方法 滤波方法

同步状态spring-doc.cadn.net.cn

非反应性回报+双向语境spring-doc.cadn.net.cn

反应回波(单声道/流)spring-doc.cadn.net.cn

异步有状态spring-doc.cadn.net.cn

反应性回报(单向/通量)+双向上下文spring-doc.cadn.net.cn

非反应性回报spring-doc.cadn.net.cn

同步无状态spring-doc.cadn.net.cn

非反应性回报 + 无双向语境spring-doc.cadn.net.cn

响应式返回或双向上下文参数spring-doc.cadn.net.cn

异步无状态spring-doc.cadn.net.cn

反应性回波(单向/通量)+无双向上下文spring-doc.cadn.net.cn

非反应性回报或双向上下文参数spring-doc.cadn.net.cn

方法过滤的最佳实践:
  1. 保持方法与你的服务器类型保持一致——同步服务器用同步方法,异步服务器用异步方法spring-doc.cadn.net.cn

  2. 将有状态和无状态实现分为不同类别以便清晰spring-doc.cadn.net.cn

  3. 启动时检查日志是否有过滤方法警告spring-doc.cadn.net.cn

  4. 使用合适的语境 - McpSyncRequestContext/McpAsync请求上下文对于有状态的,McpTransportContext代表无国籍者spring-doc.cadn.net.cn

  5. 如果你支持有状态和无状态部署,可以测试这两种模式spring-doc.cadn.net.cn

异步支持

所有服务器注释都支持使用 Reactor 的异步实现:spring-doc.cadn.net.cn

@Component
public class AsyncTools {

    @McpTool(name = "async-fetch", description = "Fetch data asynchronously")
    public Mono<String> asyncFetch(
            @McpToolParam(description = "URL", required = true) String url) {

        return Mono.fromCallable(() -> {
            // Simulate async operation
            return fetchFromUrl(url);
        }).subscribeOn(Schedulers.boundedElastic());
    }

    @McpResource(uri = "async-data://{id}", name = "Async Data")
    public Mono<ReadResourceResult> asyncResource(String id) {
        return Mono.fromCallable(() -> {
            String data = loadData(id);
            return new ReadResourceResult(List.of(
                new TextResourceContents("async-data://" + id, "text/plain", data)
            ));
        }).delayElements(Duration.ofMillis(100));
    }
}

Spring Boot 集成

通过 Spring Boot 自动配置,带注释的豆子会自动检测并注册:spring-doc.cadn.net.cn

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

@Component
public class MyMcpTools {
    // Your @McpTool annotated methods
}

@Component
public class MyMcpResources {
    // Your @McpResource annotated methods
}

自动配置将: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

配置属性

配置服务器注释扫描器:spring-doc.cadn.net.cn

spring:
  ai:
    mcp:
      server:
        type: SYNC  # or ASYNC
        annotation-scanner:
          enabled: true