MCP Server Boot Starter

Spring AI MCP(模型上下文协议)服务器启动器为在 Spring Boot 应用程序中设置 MCP 服务器提供自动配置。它使 MCP 服务器功能与 Spring Boot 的自动配置系统无缝集成。

The Spring AI MCP (Model Context Protocol) Server Boot Starter provides auto-configuration for setting up an MCP server in Spring Boot applications. It enables seamless integration of MCP server capabilities with Spring Boot’s auto-configuration system.

MCP 服务器启动器提供:

The MCP Server Boot Starter offers:

  • MCP 服务器组件的自动配置

  • Automatic configuration of MCP server components

  • 支持同步和异步操作模式

  • Support for both synchronous and asynchronous operation modes

  • Multiple transport layer options

  • 灵活的工具、资源和提示规范

  • Flexible tool, resource, and prompt specification

  • Change notification capabilities

Starters

Spring AI 自动配置、启动器模块的工件名称发生了重大变化。请参阅 upgrade notes 以获取更多信息。

There has been a significant change in the Spring AI auto-configuration, starter modules' artifact names. Please refer to the upgrade notes for more information.

根据您的传输要求选择以下启动器之一:

Choose one of the following starters based on your transport requirements:

Standard MCP Server

通过 STDIO 服务器传输支持完整的 MCP 服务器功能。

Full MCP Server features support with STDIO server transport.

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-mcp-server-spring-boot-starter</artifactId>
</dependency>
  • 适用于命令行和桌面工具

  • Suitable for command-line and desktop tools

  • 无需额外的 Web 依赖项

  • No additional web dependencies required

启动器激活 McpServerAutoConfiguration 自动配置,负责:

The starter activates the McpServerAutoConfiguration auto-configuration responsible for:

  • 配置基本服务器组件

  • Configuring the basic server components

  • 处理工具、资源和提示规范

  • Handling tool, resource, and prompt specifications

  • 管理服务器功能和更改通知

  • Managing server capabilities and change notifications

  • 提供同步和异步服务器实现

  • Providing both sync and async server implementations

WebMVC Server Transport

通过基于 Spring MVC 的 SSE (Server-Sent Events)服务器传输和可选的 STDIO 传输,全面支持 MCP 服务器功能。

Full MCP Server features support with SSE (Server-Sent Events) server transport based on Spring MVC and an optional STDIO transport.

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

启动器激活 McpWebMvcServerAutoConfigurationMcpServerAutoConfiguration 自动配置以提供:

The starter activates the McpWebMvcServerAutoConfiguration and McpServerAutoConfiguration auto-configurations to provide:

  • 使用 Spring MVC ( WebMvcSseServerTransportProvider ) 的基于 HTTP 的传输

  • HTTP-based transport using Spring MVC (WebMvcSseServerTransportProvider)

  • Automatically configured SSE endpoints

  • 可选 STDIO 传输(通过设置 spring.ai.mcp.server.stdio=true 启用)

  • Optional STDIO transport (enabled by setting spring.ai.mcp.server.stdio=true)

  • 包含 spring-boot-starter-webmcp-spring-webmvc 依赖项

  • Included spring-boot-starter-web and mcp-spring-webmvc dependencies

WebFlux Server Transport

支持完整的 MCP 服务器功能,通过基于 Spring WebFlux 的 SSE (Server-Sent Events)服务器传输和一个可选的 STDIO 传输。

Full MCP Server features support with SSE (Server-Sent Events) server transport based on Spring WebFlux and an optional STDIO transport.

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-mcp-server-webflux</artifactId>
</dependency>

启动器激活 McpWebFluxServerAutoConfigurationMcpServerAutoConfiguration 自动配置以提供:

The starter activates the McpWebFluxServerAutoConfiguration and McpServerAutoConfiguration auto-configurations to provide:

  • 使用 Spring WebFlux 的响应式传输( WebFluxSseServerTransportProvider

  • Reactive transport using Spring WebFlux (WebFluxSseServerTransportProvider)

  • 自动配置的响应式 SSE 端点

  • Automatically configured reactive SSE endpoints

  • 可选 STDIO 传输(通过设置 spring.ai.mcp.server.stdio=true 启用)

  • Optional STDIO transport (enabled by setting spring.ai.mcp.server.stdio=true)

  • 包含 spring-boot-starter-webfluxmcp-spring-webflux 依赖项

  • Included spring-boot-starter-webflux and mcp-spring-webflux dependencies

Configuration Properties

所有属性都以 spring.ai.mcp.server 为前缀:

All properties are prefixed with spring.ai.mcp.server:

Property Description Default

enabled

Enable/disable the MCP server

true

stdio

Enable/disable stdio transport

false

name

Server name for identification

mcp-server

version

Server version

1.0.0

instructions

Optional instructions to provide guidance to the client on how to interact with this server

null

type

Server type (SYNC/ASYNC)

SYNC

capabilities.resource

Enable/disable resource capabilities

true

capabilities.tool

Enable/disable tool capabilities

true

capabilities.prompt

Enable/disable prompt capabilities

true

capabilities.completion

Enable/disable completion capabilities

true

resource-change-notification

Enable resource change notifications

true

prompt-change-notification

Enable prompt change notifications

true

tool-change-notification

Enable tool change notifications

true

tool-response-mime-type

(optional) response MIME type per tool name. For example spring.ai.mcp.server.tool-response-mime-type.generateImage=image/png will associate the image/png mime type with the generateImage() tool name

-

sse-message-endpoint

Custom SSE Message endpoint path for web transport to be used by the client to send messages

/mcp/message

sse-endpoint

Custom SSE endpoint path for web transport

/sse

base-url

Optional URL prefix. For example base-url=/api/v1 means that the client should access the sse endpont at /api/v1 + sse-endpoint and the message endpoint is /api/v1 + sse-message-endpoint

-

request-timeout

Duration to wait for server responses before timing out requests. Applies to all requests made through the client, including tool calls, resource access, and prompt operations.

20 seconds

Sync/Async Server Types

  • Synchronous Server - 使用 McpSyncServer 实现的默认服务器类型。它专为应用程序中直接的请求-响应模式而设计。要启用此服务器类型,请在配置中设置 spring.ai.mcp.server.type=SYNC 。激活后,它会自动处理同步工具规范的配置。

  • Synchronous Server - The default server type implemented using McpSyncServer. It is designed for straightforward request-response patterns in your applications. To enable this server type, set spring.ai.mcp.server.type=SYNC in your configuration. When activated, it automatically handles the configuration of synchronous tool specifications.

  • @s0 - 异步服务器实现使用 @s1,并针对非阻塞操作进行了优化。要启用此服务器类型,请使用 @s2 配置您的应用程序。此服务器类型会自动设置具有内置 Project Reactor 支持的异步工具规范。

  • Asynchronous Server - The asynchronous server implementation uses McpAsyncServer and is optimized for non-blocking operations. To enable this server type, configure your application with spring.ai.mcp.server.type=ASYNC. This server type automatically sets up asynchronous tool specifications with built-in Project Reactor support.

Server Capabilities

MCP 服务器支持四种主要功能类型,可以单独启用或禁用:

The MCP Server supports four main capability types that can be individually enabled or disabled:

  • @s3 - 使用 @s4 启用/禁用工具功能

  • Tools - Enable/disable tool capabilities with spring.ai.mcp.server.capabilities.tool=true|false

  • @s5 - 使用 @s6 启用/禁用资源功能

  • Resources - Enable/disable resource capabilities with spring.ai.mcp.server.capabilities.resource=true|false

  • @s7 - 使用 @s8 启用/禁用提示功能

  • Prompts - Enable/disable prompt capabilities with spring.ai.mcp.server.capabilities.prompt=true|false

  • @s9 - 使用 @s10 启用/禁用完成功能

  • Completions - Enable/disable completion capabilities with spring.ai.mcp.server.capabilities.completion=true|false

所有功能默认启用。禁用某个功能将阻止服务器注册并向客户端公开相应的功能。

All capabilities are enabled by default. Disabling a capability will prevent the server from registering and exposing the corresponding features to clients.

Transport Options

MCP 服务器支持三种传输机制,每种机制都有其专用的启动器:

The MCP Server supports three transport mechanisms, each with its dedicated starter:

  • 标准输入/输出 (STDIO) - @s11

  • Standard Input/Output (STDIO) - spring-ai-starter-mcp-server

  • Spring MVC (服务器发送事件) - @s12

  • Spring MVC (Server-Sent Events) - spring-ai-starter-mcp-server-webmvc

  • Spring WebFlux (反应式 SSE) - @s13

  • Spring WebFlux (Reactive SSE) - spring-ai-starter-mcp-server-webflux

Features and Capabilities

MCP 服务器启动器允许服务器向客户端公开工具、资源和提示。它根据服务器类型,自动将注册为 Spring bean 的自定义功能处理程序转换为同步/异步规范:

The MCP Server Boot Starter allows servers to expose tools, resources, and prompts to clients. It automatically converts custom capability handlers registered as Spring beans to sync/async specifications based on server type:

Tools

允许服务器公开可由语言模型调用的工具。MCP 服务器启动器提供:

Allows servers to expose tools that can be invoked by language models. The MCP Server Boot Starter provides:

  • Change notification support

  • Spring AI Tools 会根据服务器类型自动转换为同步/异步规范

  • Spring AI Tools are automatically converted to sync/async specifications based on server type

  • 通过 Spring bean 自动进行工具规范:

  • Automatic tool specification through Spring beans:

@Bean
public ToolCallbackProvider myTools(...) {
    List<ToolCallback> tools = ...
    return ToolCallbackProvider.from(tools);
}

或使用低级 API:

or using the low-level API:

@Bean
public List<McpServerFeatures.SyncToolSpecification> myTools(...) {
    List<McpServerFeatures.SyncToolSpecification> tools = ...
    return tools;
}

自动配置将自动检测并注册所有工具回调来源:* 单个 ToolCallback bean * ToolCallback bean 列表 * ToolCallbackProvider bean

The auto-configuration will automatically detect and register all tool callbacks from: * Individual ToolCallback beans * Lists of ToolCallback beans * ToolCallbackProvider beans

工具将按名称去重,使用每个工具名称的首次出现。

Tools are de-duplicated by name, with the first occurrence of each tool name being used.

Tool Context Support

以下是使用Gemini将这段文字翻译成中文的结果:支持 ToolContext ,允许将上下文信息传递给工具调用。它在 exchange 键下包含一个 McpSyncServerExchange 实例,可通过 McpToolUtils.getMcpExchange(toolContext) 访问。请参阅此 example 演示 exchange.loggingNotification(…​)exchange.createMessage(…​)

The ToolContext is supported, allowing contextual information to be passed to tool calls. It contains an McpSyncServerExchange instance under the exchange key, accessible via McpToolUtils.getMcpExchange(toolContext). See this example demonstrating exchange.loggingNotification(…​) and exchange.createMessage(…​).

Resource Management

以下是使用 Gemini 翻译的中文文本:提供了一种标准化的方式,让服务器向客户端公开资源。

Provides a standardized way for servers to expose resources to clients.

  • 使用Gemini将这段文字翻译成中文:静态和动态资源规范

  • Static and dynamic resource specifications

  • Optional change notifications

  • Support for resource templates

  • 好的,这是用Gemini翻译的文本:自动转换同步/异步资源规范。

  • Automatic conversion between sync/async resource specifications

  • 好的,这是用Gemini翻译的中文版本:通过Spring beans自动进行资源规范:

  • Automatic resource specification through Spring beans:

@Bean
public List<McpServerFeatures.SyncResourceSpecification> myResources(...) {
    var systemInfoResource = new McpSchema.Resource(...);
    var resourceSpecification = new McpServerFeatures.SyncResourceSpecification(systemInfoResource, (exchange, request) -> {
        try {
            var systemInfo = Map.of(...);
            String jsonContent = new ObjectMapper().writeValueAsString(systemInfo);
            return new McpSchema.ReadResourceResult(
                    List.of(new McpSchema.TextResourceContents(request.uri(), "application/json", jsonContent)));
        }
        catch (Exception e) {
            throw new RuntimeException("Failed to generate system info", e);
        }
    });

    return List.of(resourceSpecification);
}

Prompt Management

以下是使用Gemini将这段文字翻译成中文的几种方式,具体取决于上下文和所需的正式程度:主要推荐:* 提供一种标准化的方式,使服务器能够向客户端暴露提示模板。 (这个翻译最准确,保留了原文的结构和含义。)其他可接受的翻译(根据语境):* 为服务器向客户端公开提示模板提供了一种标准化方法。 (略微更口语化,但意思相近。)* 服务器可以利用这种标准化的方式向客户端公开提示模板。 (强调了“利用”这个动作。)* 它为服务器向客户端暴露提示模板提供了一种标准化的机制。 (将“way”翻译成“机制”,有时更技术化。)选择哪个翻译取决于:* 受众: 如果是技术专家,第一个翻译是最合适的。如果是非技术人员,更口语化的翻译可能更好。* 文档类型: 这是一个API文档、技术规范还是一个产品描述?* 上下文: 这句话出现在一个更大的段落中,它与前后句子的衔接是否流畅?总结来说,我最推荐的翻译是:提供一种标准化的方式,使服务器能够向客户端暴露提示模板。因为它既准确又符合技术语境。

Provides a standardized way for servers to expose prompt templates to clients.

  • Change notification support

  • Template versioning

  • 好的,以下是用 Gemini 翻译的这段文字的中文版本:同步/异步提示规范之间的自动转换

  • Automatic conversion between sync/async prompt specifications

  • 通过 Spring bean 自动指定提示:

  • Automatic prompt specification through Spring beans:

@Bean
public List<McpServerFeatures.SyncPromptSpecification> myPrompts() {
    var prompt = new McpSchema.Prompt("greeting", "A friendly greeting prompt",
        List.of(new McpSchema.PromptArgument("name", "The name to greet", true)));

    var promptSpecification = new McpServerFeatures.SyncPromptSpecification(prompt, (exchange, getPromptRequest) -> {
        String nameArgument = (String) getPromptRequest.arguments().get("name");
        if (nameArgument == null) { nameArgument = "friend"; }
        var userMessage = new PromptMessage(Role.USER, new TextContent("Hello " + nameArgument + "! How can I assist you today?"));
        return new GetPromptResult("A personalized greeting message", List.of(userMessage));
    });

    return List.of(promptSpecification);
}

Completion Management

为服务器提供了一种标准化的方式,向客户端公开完成能力。

Provides a standardized way for servers to expose completion capabilities to clients.

  • 支持同步和异步完成规范

  • Support for both sync and async completion specifications

  • 通过 Spring bean 自动注册:

  • Automatic registration through Spring beans:

@Bean
public List<McpServerFeatures.SyncCompletionSpecification> myCompletions() {
    var completion = new McpServerFeatures.SyncCompletionSpecification(
        "code-completion",
        "Provides code completion suggestions",
        (exchange, request) -> {
            // Implementation that returns completion suggestions
            return new McpSchema.CompletionResult(List.of(
                new McpSchema.Completion("suggestion1", "First suggestion"),
                new McpSchema.Completion("suggestion2", "Second suggestion")
            ));
        }
    );

    return List.of(completion);
}

Root Change Consumers

当根目录更改时,支持 RootChange ( listChanged ) 的客户端会发送根目录更改通知。

When roots change, clients that support listChanged send a Root Change notification.

  • 支持监控根目录更改

  • Support for monitoring root changes

  • 为响应式应用程序自动转换为异步消费者

  • Automatic conversion to async consumers for reactive applications

  • 可选的 Spring bean 注册

  • Optional registration through Spring beans

@Bean
public BiConsumer<McpSyncServerExchange, List<McpSchema.Root>> rootsChangeHandler() {
    return (exchange, roots) -> {
        logger.info("Registering root resources: {}", roots);
    };
}

Usage Examples

Standard STDIO Server Configuration

# Using spring-ai-starter-mcp-server
spring:
  ai:
    mcp:
      server:
        name: stdio-mcp-server
        version: 1.0.0
        type: SYNC

WebMVC Server Configuration

# Using spring-ai-starter-mcp-server-webmvc
spring:
  ai:
    mcp:
      server:
        name: webmvc-mcp-server
        version: 1.0.0
        type: SYNC
        instructions: "This server provides weather information tools and resources"
        sse-message-endpoint: /mcp/messages
        capabilities:
          tool: true
          resource: true
          prompt: true
          completion: true

WebFlux Server Configuration

# Using spring-ai-starter-mcp-server-webflux
spring:
  ai:
    mcp:
      server:
        name: webflux-mcp-server
        version: 1.0.0
        type: ASYNC  # Recommended for reactive applications
        instructions: "This reactive server provides weather information tools and resources"
        sse-message-endpoint: /mcp/messages
        capabilities:
          tool: true
          resource: true
          prompt: true
          completion: true

Creating a Spring Boot Application with MCP Server

@Service
public class WeatherService {

    @Tool(description = "Get weather information by city name")
    public String getWeather(String cityName) {
        // Implementation
    }
}

@SpringBootApplication
public class McpServerApplication {

    private static final Logger logger = LoggerFactory.getLogger(McpServerApplication.class);

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

	@Bean
	public ToolCallbackProvider weatherTools(WeatherService weatherService) {
		return MethodToolCallbackProvider.builder().toolObjects(weatherService).build();
	}
}

自动配置将自动把工具回调注册为 MCP 工具。您可以有多个 bean 产生 ToolCallbacks。自动配置将合并它们。

The auto-configuration will automatically register the tool callbacks as MCP tools. You can have multiple beans producing ToolCallbacks. The auto-configuration will merge them.

Example Applications