MCP的SSE重连机制,低成本接入框架,快速上手

374 阅读7分钟

SSE 重连机制

[!TIP] MCP 的 SSE 连接,Client 侧和 Server 侧一段时间未传输数据会断开,或者 Server 侧挂掉重启后,Client 侧此时无法建立 SSE 连接。这里提供了一个自动重连机制,开箱即用,基本原理如下:定义两个线程池

  1. 定时任务线程池:定期 ping MCP Server 侧,若请求失败则记录至延时队列
  2. 异步线程池:从延时队列中拉取失败的 MCP Server 侧,建立连接

框架代码已提供至社区:github.com/alibaba/spr…

快速上手例子:github.com/GTyingzi/sp… 下的 mcp/client 目录下的 mcp-recovery-client 模块

快速上手

pom.xml

<properties>
    <!-- Spring AI Alibaba -->
    <spring-ai-alibaba.version>1.0.0.3-SNAPSHOT</spring-ai-alibaba.version>
</properties>

<dependencies>

    <dependency>
        <groupId>org.springframework.ai</groupId>
        <artifactId>spring-ai-autoconfigure-model-openai</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.ai</groupId>
        <artifactId>spring-ai-autoconfigure-model-chat-client</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

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

    <dependency>
        <groupId>com.alibaba.cloud.ai</groupId>
        <artifactId>spring-ai-alibaba-starter-mcp-recovery-client</artifactId>
        <version>${spring-ai-alibaba.version}</version>
    </dependency>

</dependencies>

application.yml

server:
  port: 19100

spring:
  application:
    name: mcp-recovery-client
  ai:
    openai:
      api-key: ${DASHSCOPEAPIKEY}
      base-url: https://dashscope.aliyuncs.com/compatible-mode
      chat:
        options:
          model: qwen-max
    mcp:
      client:
        enabled: false
        name: my-mcp-client
        version: 1.0.0
        request-timeout: 600s
        type: ASYNC  # or ASYNC for reactive applications
        sse:
          connections:
            server1:
              url: http://localhost:19000 # 本地

    alibaba:
      mcp:
        recovery:
          enabled: true
          delay: 5s
          stop: 10s

# 打印日志
logging:
  level:
    com:
      alibaba:
        cloud:
          ai:
            mcp:
              client: DEBUG
  • spring.ai.mcp.client.enabled: false:设为 false,取消 McpSyncClient 或 McpAsyncClient 配置

  • spring.ai.alibaba.mcp.recovery:重连配置

    • enabled:true 为启动,默认为 false
    • delay:MCP Client 侧多久 Ping 一次 MCP Server,默认为 5 秒
    • stop:MCP 关闭线程池的最大等待时间,默认为 10 秒

controller

package com.spring.ai.tutorial.mcp.client.controller;

import com.alibaba.cloud.ai.mcp.client.McpAsyncRecovery;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author yingzi
 * @since 2025/7/15
 */
@RestController
@RequestMapping("/time")
public class TimeController {

    private final ChatClient chatClient;

    private final McpAsyncRecovery mcpAsyncRecovery;

    public TimeController(ChatClient.Builder chatClientBuilder, McpAsyncRecovery mcpAsyncRecovery) {
        this.chatClient = chatClientBuilder.build();
        this.mcpAsyncRecovery = mcpAsyncRecovery;
    }

    @GetMapping("/chat")
    public String chatTime(@RequestParam(value = "query", defaultValue = "请告诉我现在北京时间几点了") String query) {
        return chatClient.prompt(query)
                .toolCallbacks(mcpAsyncRecovery.getToolCallback())
                .call()
                .content();
    }
}

效果

  1. 先启动 mcp-web-server 模块提供一个 MCP Server 服务,再启动 mcp-revoer-client
  2. 此时可以再 Client 侧看到 Checking MCP clients...;再 Server 侧看到接收 ping 的消息

重启 Server 侧,Client 侧可以看到重新建立了连接

此时再试下接口,MCP 连接是生效的

参考资料

After restarting the mcp server, the previous client will not automatically reconnect

往期资料

第一章内容

SpringAI(GA)的chat:快速上手+自动注入源码解读

SpringAI(GA):ChatClient调用链路解读

第二章内容

SpringAI的Advisor:快速上手+源码解读

SpringAI(GA):Sqlite、Mysql、Redis消息存储快速上手

第三章内容

SpringAI(GA):Tool工具整合—快速上手

SpringAI(GA):Tool源码+工具触发链路解读

第四章内容

SpringAI(GA):结构化输出的快速上手+源码解读

第五章内容

SpringAI(GA):内存、Redis、ES的向量数据库存储—快速上手

SpringAI(GA):向量数据库理论源码解读+Redis、Es接入源码

第六章内容

SpringAI(GA):RAG快速上手+模块化解读

SpringAI(GA):RAG下的ETL快速上手

SpringAI(GA):RAG下的ETL源码解读

第七章内容

SpringAI(GA):Nacos2下的分布式MCP

SpringAI(GA):Nacos3下的分布式MCP

SpringAI(GA):MCP源码解读

SpringAI(GA): SpringAI下的MCP源码解读

进阶:MCP服务鉴权案例

Spring AI Alibaba MCP Gateway GateWay无缝斜街存量应用转换 MCP 工具

第八章内容

SpringAI(GA): 多模型评估篇

第九章内容

SpringAI(GA):观测篇快速上手+源码解读

第十章内容

Spring AI Alibaba Graph:快速入门

Spring AI Alibaba Graph:多节点并行—快速上手

Spring AI Alibaba Graph:节点流式透传案例

Spring AI Alibaba Graph:分配MCP到指定节点

Spring AI Alibaba Graph:中断!人类反馈介入,流程丝滑走完~

可付费获取飞书云文档获得更好的观赏体验~ 感谢观众老爷们的支持

学习交流圈

你好,我是影子,曾先后在🐻、新能源、老铁就职,兼容Spring AI Alibaba开源社区的Committer。目前新建了一个交流群,一个人走得快,一群人走得远,另外,本人长期维护一套飞书云文档笔记,涵盖后端、大数据系统化的面试资料,可私信免费获取