Spring AI集成MCP:从服务端到客户端

文章配图

随着Spring AI 1.1正式版的发布,模型上下文协议(MCP)的集成已成为Spring生态中AI开发的核心能力。Spring团队主导了MCP Java SDK的开发,并提供了专用的Boot Starter和注解编程模型,让开发者能够以Spring惯用的方式快速构建MCP服务端和客户端。下面带您从零开始,完整实践在Spring AI框架中集成MCP的全流程。

一、集成概览:Spring AI的MCP生态架构

Spring AI为MCP提供了全方位的支持,涵盖服务端和客户端两端,支持多种传输协议和部署模式。

Spring AI MCP的核心依赖

Spring AI 1.1提供了多款专用Starter,覆盖不同的使用场景和传输需求:

客户端Starter:

  • spring-ai-starter-mcp-client:核心客户端,支持stdio和基于HTTP的SSE
  • spring-ai-starter-mcp-client-webflux:基于WebFlux的响应式客户端

服务端Starter:

  • spring-ai-starter-mcp-server:核心服务端,支持stdio传输
  • spring-ai-starter-mcp-server-webmvc:基于Spring MVC的SSE服务端
  • spring-ai-starter-mcp-server-webflux:基于WebFlux的响应式服务端

二、方式一:基于注解的MCP服务端开发(推荐)

Spring AI 1.1推荐使用注解驱动的开发方式通过@McpTool、@McpResource、@McpPrompt等注解,将普通Spring Bean的方法暴露为MCP能力。

步骤1:添加Maven依赖

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

步骤2:实现工具服务

使用@McpTool注解标记方法,框架会自动将其注册为MCP工具:

@Service
public class WeatherService {

    @McpTool(description = "获取指定城市的实时天气信息")
    public String getWeather(
            @McpToolParam(description = "城市名称", required = true) String city) {

        return String.format("北京市当前天气:晴,温度25°C,湿度45%%");
    }

    @McpTool(description = "计算两个数字的数学运算")
    public double calculate(
            @McpToolParam(description = "第一个数字") double num1,
            @McpToolParam(description = "运算符 + - * /") String operator,
            @McpToolParam(description = "第二个数字") double num2) {
        switch (operator) {
            case "+": return num1 + num2;
            case "-": return num1 - num2;
            case "*": return num1 * num2;
            case "/": return num1 / num2;
            default: throw new IllegalArgumentException("不支持的运算符");
        }
    }
}

@McpTool注解的description属性会传递给AI模型,帮助模型理解工具的用途和调用时机。

步骤3:配置文件

spring:
  ai:
    mcp:
      server:
        name: my-weather-mcp-server
        version: 1.0.0
        protocol: STREAMABLE   
        sse-endpoint: /sse
        sse-message-endpoint: /mcp/messages

注意:使用spring-ai-starter-mcp-server-webmvc时,需要配置protocol: STREAMABLE以启用HTTP流式传输。

三、方式二:基于SSE的远程MCP服务端

对于需要远程部署、支持多客户端并发访问的场景,SSE(Server-Sent Events)模式是更合适的选择。与stdio模式不同,SSE模式将MCP服务器暴露为标准的HTTP端点。

依赖配置

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

服务端配置

spring:
  ai:
    mcp:
      server:
        name: remote-mcp-server
        version: 1.0.0
        stdio: false          
        type: ASYNC           
        sse-endpoint: /sse
        sse-message-endpoint: /mcp/messages
        capabilities:
          tool: true
          resource: true
          prompt: true

SSE模式下,客户端通过/sse端点建立长连接,服务器通过/mcp/messages端点接收消息,支持服务器主动推送实时通知和进度更新。

四、MCP客户端集成:连接与调用

步骤1:添加客户端依赖

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

步骤2:配置MCP服务器连接

创建src/main/resources/mcp-servers.json,配置需要连接的MCP服务:

{
  "mcpServers": {
    "weather-server": {
      "command": "java",
      "args": [
        "-jar",
        "-Dspring.ai.mcp.server.stdio=true",
        "-Dspring.main.web-application-type=none",
        "/path/to/your/mcp-server.jar"
      ]
    },
    "remote-sse-server": {
      "command": "npx",
      "args": [
        "mcp-remote",
        "https://remote-server/sse"
      ]
    }
  }
}

步骤3:配置客户端属性

spring:
  ai:
    mcp:
      client:
        enabled: true
        name: my-agent-mcp-client
        version: 1.0.0
        type: SYNC                    
        request-timeout: 30s
        toolcallback:
          enabled: true               
        stdio:
          servers-configuration: classpath:mcp-servers.json

步骤4:在ChatClient中使用MCP工具

通过ToolCallbackProvider将MCP工具注入到ChatClient中:

@Bean
public CommandLineRunner demo(ChatClient chatClient, ToolCallbackProvider mcpTools) {
    return args -> {
        String response = chatClient
            .prompt("北京今天的天气怎么样?")
            .tools(mcpTools)              
            .call()
            .content();
        System.out.println(response);
    };
}

MCP客户端会自动发现服务器提供的所有工具无需手动注册。框架通过tools/list请求在运行时获取工具列表,实现了动态工具发现。

五、Spring AI MCP的安全集成

在企业级部署中,MCP服务器的安全防护至关重要。Spring AI提供了与Spring Security的无缝集成,支持OAuth2认证。

添加安全依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-authorization-server</artifactId>
</dependency>

配置安全过滤器链

通过Spring Security的配置类,将MCP服务器同时配置为资源服务器(验证token)和授权服务器(颁发token):

@Configuration
@EnableWebSecurity
public class SecurityConfiguration {

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http
            .authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
            .oauth2ResourceServer(resource -> resource.jwt(Customizer.withDefaults()))
            .csrf(CsrfConfigurer::disable)
            .cors(Customizer.withDefaults())
            .build();
    }
}

客户端配置OAuth2

在mcp-servers.json中为远程服务配置认证头:

{
"mcpServers": {
"secure-remote-server": {
"command": "npx",
"args": [
"mcp-remote",
"https://secure-server/sse",
"--header",
"Authorization: Bearer ${MCP_ACCESS_TOKEN}"
]
}
}
}

六、集成模式对比与选型建议

维度 stdio模式 SSE/Streamable HTTP模式
部署方式 客户端启动服务器子进程 服务器独立部署为HTTP服务
通信机制 标准输入/输出 HTTP + Server-Sent Events
生命周期 客户端完全控制 服务器独立运行
多客户端 通常一对一 支持多客户端并发
安全要求 较低(本地通信) 需配置OAuth2等认证机制
适用场景 本地工具集成、IDE插件 分布式系统、云端部署

总结

Spring AI通过专用的Boot Starter、注解驱动的编程模型以及与Spring Security的深度集成为MCP协议提供了全方位的支持。

开发者可以选择基于stdio的本地进程通信实现轻量级工具集成,也可以选择基于SSE/Streamable HTTP的远程部署模式构建分布式AI系统。掌握这套集成方案将让您在使用Spring AI构建AI Agent应用时,能够以标准化、可扩展的方式接入各种外部工具和数据源。

联调阶段有个实用技巧:先把 MCP 服务端单独跑起来,用 curl 或 MCP Inspector 手动调用一次工具接口,确认返回结构符合 schema,再接客户端。服务端和客户端一起调,出了协议不匹配的问题两头查,效率低得多。另外注解方式适合工具数量少、变更不频繁的场景;工具一多,SSE 远程方式配合独立部署反而更好维护。

0

评论0

请先
显示验证码
没有账号?注册  忘记密码?