MCP 伺服器 Boot Starter

Spring AI MCP(模型上下文協議)伺服器 Boot Starter 為在 Spring Boot 應用程式中設定 MCP 伺服器提供自動配置。它實現了 MCP 伺服器功能與 Spring Boot 自動配置系統的無縫整合。

MCP 伺服器 Boot Starter 提供

  • MCP 伺服器元件的自動配置

  • 支援同步和非同步操作模式

  • 多種傳輸層選項

  • 靈活的工具、資源和 Prompt 規範

  • 更改通知功能

Starters

Spring AI 自動配置、starter 模組的 artifact 名稱發生了重大變化。請參閱升級說明以獲取更多資訊。

根據您的傳輸要求選擇以下 starter 之一

標準 MCP 伺服器

支援完整的 MCP 伺服器功能,並使用 STDIO 伺服器傳輸。

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-mcp-server</artifactId>
</dependency>
  • 適用於命令列和桌面工具

  • 無需額外的 Web 依賴項

該 starter 啟用負責以下功能的 McpServerAutoConfiguration 自動配置:

  • 配置基本伺服器元件

  • 處理工具、資源和 Prompt 規範

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

  • 提供同步和非同步伺服器實現

WebMVC 伺服器傳輸

支援完整的 MCP 伺服器功能,並使用基於 Spring MVC 的 SSE(Server-Sent Events)伺服器傳輸和可選的 STDIO 傳輸。

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

該 starter 啟用 McpWebMvcServerAutoConfigurationMcpServerAutoConfiguration 自動配置以提供

  • 使用 Spring MVC 的基於 HTTP 的傳輸 (WebMvcSseServerTransportProvider)

  • 自動配置的 SSE 端點

  • 可選的 STDIO 傳輸(透過設定 spring.ai.mcp.server.stdio=true 啟用)

  • 包含 spring-boot-starter-webmcp-spring-webmvc 依賴項

WebFlux 伺服器傳輸

支援完整的 MCP 伺服器功能,並使用基於 Spring WebFlux 的 SSE(Server-Sent Events)伺服器傳輸和可選的 STDIO 傳輸。

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

該 starter 啟用 McpWebFluxServerAutoConfigurationMcpServerAutoConfiguration 自動配置以提供

  • 使用 Spring WebFlux 的響應式傳輸 (WebFluxSseServerTransportProvider)

  • 自動配置的響應式 SSE 端點

  • 可選的 STDIO 傳輸(透過設定 spring.ai.mcp.server.stdio=true 啟用)

  • 包含 spring-boot-starter-webfluxmcp-spring-webflux 依賴項

配置屬性

所有屬性都帶有字首 spring.ai.mcp.server

屬性 描述 預設值

enabled

啟用/停用 MCP 伺服器

true

stdio

啟用/停用 stdio 傳輸

false

name

用於標識的伺服器名稱

mcp-server

version

伺服器版本

1.0.0

type

伺服器型別 (SYNC/ASYNC)

SYNC

resource-change-notification

啟用資源更改通知

true

prompt-change-notification

啟用 Prompt 更改通知

true

tool-change-notification

啟用工具更改通知

true

tool-response-mime-type

(可選)每個工具名稱的響應 MIME 型別。例如 spring.ai.mcp.server.tool-response-mime-type.generateImage=image/png 會將 image/png MIME 型別與 generateImage() 工具名稱關聯起來。

-

sse-message-endpoint

Web 傳輸自定義 SSE 訊息端點路徑,供客戶端傳送訊息使用

/mcp/message

sse-endpoint

Web 傳輸自定義 SSE 端點路徑

/sse

base-url

可選的 URL 字首。例如 base-url=/api/v1 意味著客戶端應該在 /api/v1 + sse-endpoint 訪問 sse 端點,訊息端點是 /api/v1 + sse-message-endpoint

-

同步/非同步伺服器型別

  • 同步伺服器 - 使用 McpSyncServer 實現的預設伺服器型別。它專為應用程式中的簡單請求-響應模式而設計。要啟用此伺服器型別,請在配置中設定 spring.ai.mcp.server.type=SYNC。啟用後,它會自動處理同步工具規範的配置。

  • 非同步伺服器 - 非同步伺服器實現使用 McpAsyncServer,並針對非阻塞操作進行了最佳化。要啟用此伺服器型別,請使用 spring.ai.mcp.server.type=ASYNC 配置您的應用程式。此伺服器型別會自動設定具有內建 Project Reactor 支援的非同步工具規範。

傳輸選項

MCP 伺服器支援三種傳輸機制,每種機制都有自己的專用 starter

  • 標準輸入/輸出 (STDIO) - spring-ai-starter-mcp-server

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

  • Spring WebFlux (響應式 SSE) - spring-ai-starter-mcp-server-webflux

功能和能力

MCP 伺服器 Boot Starter 允許伺服器向客戶端公開工具、資源和 Prompt。它會根據伺服器型別自動將註冊為 Spring bean 的自定義能力處理程式轉換為同步/非同步規範。

工具

允許伺服器公開可由語言模型呼叫的工具。MCP 伺服器 Boot Starter 提供:

  • 更改通知支援

  • 工具會根據伺服器型別自動轉換為同步/非同步規範

  • 透過 Spring bean 自動進行工具規範

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

或使用底層 API

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

資源管理

提供一種標準化方式供伺服器向客戶端公開資源。

  • 靜態和動態資源規範

  • 可選的更改通知

  • 支援資源模板

  • 同步/非同步資源規範之間的自動轉換

  • 透過 Spring bean 自動進行資源規範

@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 管理

提供一種標準化方式供伺服器向客戶端公開 Prompt 模板。

  • 更改通知支援

  • 模板版本控制

  • 同步/非同步 Prompt 規範之間的自動轉換

  • 透過 Spring bean 自動進行 Prompt 規範

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

Root 更改消費者

當根(roots)發生變化時,支援 listChanged 的客戶端會發送 Root 更改通知。

  • 支援監控根更改

  • 自動轉換為響應式應用程式的非同步消費者

  • 透過 Spring bean 進行可選註冊

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

使用示例

標準 STDIO 伺服器配置

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

WebMVC 伺服器配置

# Using spring-ai-starter-mcp-server-webmvc
spring:
  ai:
    mcp:
      server:
        name: webmvc-mcp-server
        version: 1.0.0
        type: SYNC
        sse-message-endpoint: /mcp/messages

WebFlux 伺服器配置

# 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
        sse-message-endpoint: /mcp/messages

建立帶有 MCP 伺服器的 Spring Boot 應用程式

@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 工具。您可以擁有多個生成 ToolCallbacks 的 bean。自動配置會將它們合併。

示例應用程式