一文吃透 Spring AI Alibaba + MCP:服务端搭建 + 客户端调用全流程

简介: 掌握 Spring AI Alibaba 与 MCP 协议实战教程!本文详解 MCP 服务端搭建、客户端配置,教你封装本地工具为 MCP 服务,实现大模型安全调用外部接口,附完整代码与测试步骤,快速打通 AI 工具调用链路!

一、MCP概念介绍

MCP(Model Context Protocol,模型上下文协议)是 Anthropic 于 2024 年推出的AI 领域统一连接协议,被称为 “AI 的 USB-C 接口”,核心是让大模型(LLM)通过标准化方式安全、灵活地调用外部工具、数据库、API 与文件系统,打破数据孤岛。

从架构来看,MCP基于C/S(客户端-服务端)模式实现,因此要完成MCP调用,需分别搭建MCP服务端(暴露工具方法)和MCP客户端(调用服务端方法)。

本文将基于Spring Ai Alibaba生态,完整实现“本地方法封装为MCP服务 + 客户端调用MCP服务”的全流程,步骤清晰、可直接落地。

二、Spring AI MCP的介绍

Spring AI MCP 为模型上下文协议提供 Java 和 Spring 框架集成。它使 Spring AI 应用程序能够通过标准化的接口与不同的数据源和工具进行交互,支持同步和异步通信模式。整体架构如下:

mcp-local.png

三、搭建本地MCP服务端

1. 添加依赖

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

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

注意:

此处未使用常规的spring-boot-starter-web(内置Tomcat),因为spring-ai-starter-mcp-server-webflux与Tomcat存在冲突。使用spring-boot-starter会默认通过Netty启动服务,适配MCP服务端要求。

2. 配置服务端application.yml

server:
  port: 8088  # 服务端口,可自定义
  servlet:
    encoding:
      enabled: true
      force: true
      charset: UTF-8  # 避免中文乱码
spring:
  application:
    name: local-mcp-server # 服务端应用名称
  ai:
    mcp:
      server:  
        type: async  # 异步模式,提升调用性能
        name: local-mcp-server  # MCP服务名称
        version: 1.0.0  # 服务版本

3. 添加工具方法

创建工具类,将需要对外暴露的方法用@Tool注解标记,并将该类交给Spring容器管理:

@Service
public class WeatherService {
   

      /**
     * 根据城市名称获取天气信息
     * @param city 城市名称
     * @return 天气描述
     */
    @Tool(description = "根据城市名称获取天气信息")
    public String getWeatherByCity(String city) {
   
        return city + " 今天天气很好!";
    }
}

4. 添加MCP服务配置(McpServerConfig)

创建配置类,通过ToolCallbackProvider将工具类(WeatherService)封装为MCP服务:

@Configuration
public class McpServerConfig {
   

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

5. 启动mcp-server 服务

启动Spring Boot应用,查看控制台输出,确认服务启动成功(重点关注Netty启动信息):

2026-03-19T14:33:17.730+08:00  INFO 35517 --- [local-mcp-server] [           main] o.s.b.web.embedded.netty.NettyWebServer  : Netty started on port 8088 (http)
2026-03-19T14:33:17.734+08:00  INFO 35517 --- [local-mcp-server] [           main] com.jcq.server.McpServerApplication      : Started McpServerApplication in 1.198 seconds

可以看到服务使用netty成功启动,端口是8088

四、搭建MCP客户端

1. 添加依赖

client端正常配置spring-boot-starter-web,使用tomcat启动服务。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring AI Alibaba Agent Framework -->
<dependency>
    <groupId>com.alibaba.cloud.ai</groupId>
    <artifactId>spring-ai-alibaba-agent-framework</artifactId>
    <version>1.1.2.0</version>
</dependency>

<!-- DashScope ChatModel 支持(如果使用其他模型,请跳转 Spring AI 文档选择对应的 starter) -->
<dependency>
    <groupId>com.alibaba.cloud.ai</groupId>
    <artifactId>spring-ai-alibaba-starter-dashscope</artifactId>
    <version>1.1.2.0</version>
</dependency>
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-mcp-client</artifactId>
    <version>1.1.2</version>
</dependency>

2. 配置客户端application.yml

spring:
  application:
    name: spring-ai-alibaba-agent # 客户端应用名称
  ai:
    dashscope:
      api-key: ${
   AliQwen_API}  # 通义千问API密钥,建议通过环境变量配置,避免硬编码
    mcp:
      client:
        type: async  # 与服务端一致,异步调用
        request-timeout: 60s # 调用超时时间,可根据实际调整
        toolcallback:
          enabled: true # 启用工具回调,用于接收服务端响应
        sse: # mcp类型
          connections:
            local-mcp-server: # 这里表示mcp服务名称
              url: http://localhost:8088 # MCP服务端地址(对应服务端ip端口)

3. 编写测试接口

@RestController
public class McpClientController {
   

    @Resource
    private ToolCallbackProvider toolCallbackProvider;

      /**
     * 测试MCP服务调用:查询指定城市天气
     * 访问地址:http://localhost:8080/mcpTest(客户端端口默认8080,可自定义)
     */
    @GetMapping("mcpTest")
    private void mcpTest() throws GraphRunnerException {
   

          // 1. 初始化DashScope聊天模型(可替换为其他LLM模型)
        ChatModel chatModel = getChatModel();

          // 2. 获取MCP服务端暴露的工具方法
        ToolCallback[] toolCallbacks = toolCallbackProvider.getToolCallbacks();

        System.out.printf("""
                        =====Find the tools from spring ToolCallbackProvider=====
                        %s
                        """,
                JSON.toJSONString(toolCallbacks));

        // 3. 构建智能体并绑定mcp服务
        ReactAgent agent = ReactAgent.builder()
                .name("ip_search")
                .model(chatModel)
                .description("你是一个天气查询助手")
                .saver(new MemorySaver())
                .toolCallbackProviders(toolCallbackProvider)
                        .build();

        // 4. 配置运行参数
        RunnableConfig config = RunnableConfig.builder()
                .threadId("session")
                .build();

        // 5. 流式调用agent
        Flux<NodeOutput> stream = agent.stream("上海天气怎么样", config);
        StringBuffer answerString = new StringBuffer();
        stream.doOnNext(output -> {
   
                    if (output.node().equals("_AGENT_MODEL_")) {
   
                        answerString.append(((StreamingOutput<?>) output).message().getText());
                    }
                    else if (output.node().equals("_AGENT_TOOL_")) {
   
                        answerString.append("\nTool Call:").append(((ToolResponseMessage) ((StreamingOutput<?>) output).message()).getResponses().get(0)).append("\n");
                    }
                })
                .doOnComplete(() -> System.out.println(answerString))
                .doOnError(e -> System.err.println("Stream Processing Error: " + e.getMessage()))
                .blockLast();
    }

      /**
     * 初始化DashScope聊天模型(通义千问)
     * @return ChatModel 聊天模型实例
     */
    private static  ChatModel getChatModel() {
   
        DashScopeApi dashScopeApi = DashScopeApi.builder()
                .apiKey(System.getenv("AliQwen_API"))
                .build();

        return DashScopeChatModel.builder()
                .dashScopeApi(dashScopeApi)
                .build();
    }

}

4. 运行测试,查看结果

  1. 确保MCP服务端(8088端口)已启动;
  2. 启动MCP客户端,访问接口:http://localhost:8080/mcpTest
  3. 查看客户端控制台输出,若出现以下内容,说明MCP服务调用成功:
Tool Call:ToolResponse[id=call_b8f00f883a784fc1b35603, name=getWeatherByCity, responseData=[{
   "text":"\"上海 今天天气很好!\""}]]

五、总结

本文通过Spring Ai Alibaba,实现了MCP协议的本地服务落地,服务端获取天气逻辑后续可以替换为真实调用api接口。

欢迎大家关注我,下一篇文章我将介绍一下如何调用MCP市场上的公开服务,敬请期待~

目录
相关文章
|
13天前
|
人工智能 JSON 机器人
让龙虾成为你的“公众号分身” | 阿里云服务器玩Openclaw
本文带你零成本玩转OpenClaw:学生认证白嫖6个月阿里云服务器,手把手配置飞书机器人、接入免费/高性价比AI模型(NVIDIA/通义),并打造微信公众号“全自动分身”——实时抓热榜、AI选题拆解、一键发布草稿,5分钟完成热点→文章全流程!
11441 124
让龙虾成为你的“公众号分身” | 阿里云服务器玩Openclaw
|
2天前
|
人工智能 JSON 监控
Claude Code 源码泄露:一份价值亿元的 AI 工程公开课
我以为顶级 AI 产品的护城河是模型。读完这 51.2 万行泄露的源码,我发现自己错了。
3412 8
|
1天前
|
人工智能 数据可视化 安全
王炸组合!阿里云 OpenClaw X 飞书 CLI,开启 Agent 基建狂潮!(附带免费使用6个月服务器)
本文详解如何用阿里云Lighthouse一键部署OpenClaw,结合飞书CLI等工具,让AI真正“动手”——自动群发、生成科研日报、整理知识库。核心理念:未来软件应为AI而生,CLI即AI的“手脚”,实现高效、安全、可控的智能自动化。
1320 2
王炸组合!阿里云 OpenClaw X 飞书 CLI,开启 Agent 基建狂潮!(附带免费使用6个月服务器)
|
12天前
|
人工智能 IDE API
2026年国内 Codex 安装教程和使用教程:GPT-5.4 完整指南
Codex已进化为AI编程智能体,不仅能补全代码,更能理解项目、自动重构、执行任务。本文详解国内安装、GPT-5.4接入、cc-switch中转配置及实战开发流程,助你从零掌握“描述需求→AI实现”的新一代工程范式。(239字)
7431 139
|
2天前
|
云安全 供应链 安全
Axios投毒事件:阿里云安全复盘分析与关键防护建议
阿里云云安全中心和云防火墙第一时间响应
1143 0
|
3天前
|
人工智能 自然语言处理 数据挖掘
零基础30分钟搞定 Claude Code,这一步90%的人直接跳过了
本文直击Claude Code使用痛点,提供零基础30分钟上手指南:强调必须配置“工作上下文”(about-me.md+anti-ai-style.md)、采用Cowork/Code模式、建立标准文件结构、用提问式提示词驱动AI理解→规划→执行。附可复制模板与真实项目启动法,助你将Claude从聊天工具升级为高效执行系统。
|
2天前
|
人工智能 定位技术
Claude Code源码泄露:8大隐藏功能曝光
2026年3月,Anthropic因配置失误致Claude Code超51万行源码泄露,意外促成“被动开源”。代码中藏有8大未发布功能,揭示其向“超级智能体”演进的完整蓝图,引发AI编程领域震动。(239字)
2136 9
|
11天前
|
人工智能 并行计算 Linux
本地私有化AI助手搭建指南:Ollama+Qwen3.5-27B+OpenClaw阿里云/本地部署流程
本文提供的全流程方案,从Ollama安装、Qwen3.5-27B部署,到OpenClaw全平台安装与模型对接,再到RTX 4090专属优化,覆盖了搭建过程的每一个关键环节,所有代码命令可直接复制执行。使用过程中,建议优先使用本地模型保障隐私,按需切换云端模型补充功能,同时注重显卡温度与显存占用监控,确保系统稳定运行。
2541 9

热门文章

最新文章