可流式傳輸的 HTTP MCP 伺服器

可流式傳輸的 HTTP 傳輸允許 MCP 伺服器作為獨立程序執行,使用 HTTP POST 和 GET 請求處理多個客戶端連線,並可選地透過 Server-Sent Events (SSE) 流式傳輸多個伺服器訊息。它取代了 SSE 傳輸。

這些伺服器是隨規範版本 2025-03-26 引入的,非常適合需要通知客戶端工具、資源或提示的動態更改的應用程式。

設定 spring.ai.mcp.server.protocol=STREAMABLE 屬性
使用 可流式傳輸的 HTTP 客戶端 連線到可流式傳輸的 HTTP 伺服器。

可流式傳輸的 HTTP WebMVC 伺服器

使用 spring-ai-starter-mcp-server-webmvc 依賴項

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

並將 spring.ai.mcp.server.protocol 屬性設定為 STREAMABLE

  • 使用 Spring MVC 可流式傳輸傳輸的完整 MCP 伺服器功能

  • 支援工具、資源、提示、完成、日誌記錄、進度、ping、根更改功能

  • 持久連線管理

可流式傳輸的 HTTP WebFlux 伺服器

使用 spring-ai-starter-mcp-server-webflux 依賴項

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

並將 spring.ai.mcp.server.protocol 屬性設定為 STREAMABLE

  • 使用 WebFlux 可流式傳輸傳輸的響應式 MCP 伺服器

  • 支援工具、資源、提示、完成、日誌記錄、進度、ping、根更改功能

  • 非阻塞、持久連線管理

配置屬性

通用屬性

所有公共屬性都以 spring.ai.mcp.server 為字首

財產 描述 預設值

enabled

啟用/停用可流式傳輸的 MCP 伺服器

true

協議

MCP 伺服器協議

必須設定為 STREAMABLE 才能啟用可流式傳輸伺服器

tool-callback-converter

啟用/停用Spring AI ToolCallbacks到MCP工具規範的轉換

true

name

用於識別的伺服器名稱

mcp-server

version

伺服器版本

1.0.0

instructions

客戶端互動的可選指令

null

型別

伺服器型別(同步/非同步)

SYNC

capabilities.resource

啟用/停用資源能力

true

capabilities.tool

啟用/停用工具能力

true

capabilities.prompt

啟用/停用提示能力

true

capabilities.completion

啟用/停用完成能力

true

資源更改通知

啟用資源更改通知

true

提示更改通知

啟用提示更改通知

true

工具更改通知

啟用工具更改通知

true

tool-response-mime-type

每個工具名稱的響應 MIME 型別

-

request-timeout

請求超時持續時間

20秒

MCP註解屬性

MCP伺服器註解提供了一種使用Java註解實現MCP伺服器處理程式的宣告性方法。

伺服器mcp-annotations屬性以 spring.ai.mcp.server.annotation-scanner 為字首

財產 描述 預設值

enabled

啟用/停用MCP伺服器註解的自動掃描

true

可流式傳輸的 HTTP 屬性

所有可流式傳輸的 HTTP 屬性都以 spring.ai.mcp.server.streamable-http 為字首

財產 描述 預設值

mcp-endpoint

自定義 MCP 端點路徑

/mcp

keep-alive-interval

連線保持活動間隔

null(停用)

disallow-delete

禁止刪除操作

功能和能力

MCP 伺服器支援四種主要功能型別,可以單獨啟用或停用

  • 工具 - 透過 spring.ai.mcp.server.capabilities.tool=true|false 啟用/停用工具功能

  • 資源 - 透過 spring.ai.mcp.server.capabilities.resource=true|false 啟用/停用資源功能

  • 提示 - 透過 spring.ai.mcp.server.capabilities.prompt=true|false 啟用/停用提示功能

  • 完成 - 透過 spring.ai.mcp.server.capabilities.completion=true|false 啟用/停用完成功能

所有功能預設啟用。停用功能將阻止伺服器向客戶端註冊和公開相應的功能。

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

工具

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

  • 變更通知支援

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

  • 透過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;
}

自動配置將自動檢測並註冊所有來自以下來源的工具回撥:

  • 單個 ToolCallback bean

  • ToolCallback bean列表

  • ToolCallbackProvider bean

工具按名稱去重,使用每個工具名稱的第一次出現。

透過將 tool-callback-converter 設定為 false,可以停用所有工具回撥的自動檢測和註冊。

工具上下文支援

支援 ToolContext,允許將上下文資訊傳遞給工具呼叫。它包含一個位於 exchange 鍵下的 McpSyncServerExchange 例項,可透過 McpToolUtils.getMcpExchange(toolContext) 訪問。請參閱此示例,演示 exchange.loggingNotification(…​)exchange.createMessage(…​)

資源

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

  • 靜態和動態資源規範

  • 可選的變更通知

  • 支援資源模板

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

  • 透過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);
}

提示

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

  • 變更通知支援

  • 模板版本控制

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

  • 透過Spring bean自動生成提示規範

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

完成

提供了一種標準化方式,供伺服器向客戶端公開完成能力。

  • 支援同步和非同步完成規範

  • 透過Spring bean自動註冊

@Bean
public List<McpServerFeatures.SyncCompletionSpecification> myCompletions() {
    var completion = new McpServerFeatures.SyncCompletionSpecification(
        new McpSchema.PromptReference(
					"ref/prompt", "code-completion", "Provides code completion suggestions"),
        (exchange, request) -> {
            // Implementation that returns completion suggestions
            return new McpSchema.CompleteResult(List.of("python", "pytorch", "pyside"), 10, true);
        }
    );

    return List.of(completion);
}

日誌記錄

提供了一種標準化方式,讓伺服器向客戶端傳送結構化日誌訊息。在工具、資源、提示或完成呼叫處理程式中,使用提供的 McpSyncServerExchange/McpAsyncServerExchange exchange 物件傳送日誌訊息。

(exchange, request) -> {
        exchange.loggingNotification(LoggingMessageNotification.builder()
            .level(LoggingLevel.INFO)
            .logger("test-logger")
            .data("This is a test log message")
            .build());
}

在 MCP 客戶端上,您可以註冊日誌消費者來處理這些訊息。

mcpClientSpec.loggingConsumer((McpSchema.LoggingMessageNotification log) -> {
    // Handle log messages
});

進度

提供了一種標準化方式,讓伺服器向客戶端傳送進度更新。在工具、資源、提示或完成呼叫處理程式中,使用提供的 McpSyncServerExchange/McpAsyncServerExchange exchange 物件傳送進度通知。

(exchange, request) -> {
        exchange.progressNotification(ProgressNotification.builder()
            .progressToken("test-progress-token")
            .progress(0.25)
            .total(1.0)
            .message("tool call in progress")
            .build());
}

Mcp 客戶端可以接收進度通知並相應地更新其 UI。為此,它需要註冊一個進度消費者。

mcpClientSpec.progressConsumer((McpSchema.ProgressNotification progress) -> {
    // Handle progress notifications
});

根列表更改

當根更改時,支援 listChanged 的客戶端會發送根更改通知。

  • 支援監控根更改

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

  • 透過 Spring Bean 進行可選註冊

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

Ping

用於伺服器驗證其客戶端是否仍然活躍的 Ping 機制。在工具、資源、提示或完成呼叫處理程式中,使用提供的 McpSyncServerExchange/McpAsyncServerExchange exchange 物件傳送 ping 訊息。

(exchange, request) -> {
        exchange.ping();
}

保持連線

伺服器可以選擇性地定期向連線的客戶端傳送 ping 以驗證連線健康狀況。

預設情況下,保持連線是停用的。要啟用保持連線,請在您的配置中設定 keep-alive-interval 屬性。

spring:
  ai:
    mcp:
      server:
        streamable-http:
          keep-alive-interval: 30s
目前,對於可流式傳輸的 HTTP 伺服器,保持連線機制僅適用於偵聽來自伺服器的訊息 (SSE) 連線。

使用示例

可流式傳輸的 HTTP 伺服器配置

# Using spring-ai-starter-mcp-server-streamable-webmvc
spring:
  ai:
    mcp:
      server:
        protocol: STREAMABLE
        name: streamable-mcp-server
        version: 1.0.0
        type: SYNC
        instructions: "This streamable server provides real-time notifications"
        resource-change-notification: true
        tool-change-notification: true
        prompt-change-notification: true
        streamable-http:
          mcp-endpoint: /api/mcp
          keep-alive-interval: 30s

使用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,自動配置將合併它們。

© . This site is unofficial and not affiliated with VMware.