跳到主要内容
极客日志极客日志面向AI+效率的开发者社区
首页博客GitHub 精选镜像工具UI配色美学隐私政策关于联系
搜索内容 / 工具 / 仓库 / 镜像...⌘K搜索
注册
博客列表
JavaAIjava

Spring AI 开发 MCP Server 和 MCP Client(SSE 方式)

综述由AI生成基于 Spring AI 框架开发 Model Context Protocol (MCP) Server 和 Client 的完整流程,采用 SSE 传输方式。内容涵盖工程初始化、依赖配置、工具类定义、服务端与客户端代码实现及连接测试。通过 Chatbox 工具和自定义 Java Client 两种方式验证了 MCP 服务的可用性,展示了如何集成大模型调用本地工具。

t ag发布于 2026/2/6更新于 2026/6/35.5K 浏览
Spring AI 开发 MCP Server 和 MCP Client(SSE 方式)

一、概述

MCP 架构图

[图片:MCP 架构图]

MCP 生命周期

[图片:MCP 生命周期]

二、创建 MCP SERVER 的 java 工程

生成初始化工程代码

访问网址:https://start.spring.io/ 填写基本信息→添加依赖项

选择 Server

解压后用 IDEA 打开

修改 pom.xml 文件

把 spring-ai-starter-mcp-server 依赖改为 spring-ai-starter-mcp-server-webmvc

完整 pom.xml 内容

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.5.8</version>
        <relativePath/>
    </parent>
    <groupId>com.example</groupId>
    test-mcp-server
    0.0.1-SNAPSHOT
    test-mcp-server
    Demo project for Spring Boot
    
        17
        1.1.2
    
    
        
            org.springframework.ai
            spring-ai-starter-mcp-server-webmvc
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    
    
        
            
                org.springframework.ai
                spring-ai-bom
                ${spring-ai.version}
                pom
                import
            
        
    
    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

<artifactId>
</artifactId>
<version>
</version>
<name>
</name>
<description>
</description>
<properties>
<java.version>
</java.version>
<spring-ai.version>
</spring-ai.version>
</properties>
<dependencies>
<dependency>
<groupId>
</groupId>
<artifactId>
</artifactId>
</dependency>
<dependency>
<groupId>
</groupId>
<artifactId>
</artifactId>
<scope>
</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>
</groupId>
<artifactId>
</artifactId>
<version>
</version>
<type>
</type>
<scope>
</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>
</groupId>
<artifactId>
</artifactId>
</plugin>
</plugins>
</build>
</project>

定义服务类 MathTool

package com.example.tool;

import org.springframework.ai.tool.annotation.Tool;

public class MathTool {
    @Tool(description = "两个数字相加")
    public static int addNumbers(int a, int b) {
        return a + b;
    }

    @Tool(description = "两个数字相减")
    public static int subtractNumbers(int a, int b) {
        return a - b;
    }
}

通过配置类的方式把 MathTool 注入到 Spring 容器中

创建 config 包,在下面创建 McpConfig 类

package com.example.test_mcp_server.config;

import com.example.tool.MathTool;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.ai.tool.method.MethodToolCallbackProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class McpConfig {
    @Bean
    public ToolCallbackProvider mathTool() {
        return MethodToolCallbackProvider.builder().toolObjects(new MathTool()).build();
    }
}

修改配置文件 application.yaml

配置内容为:

server:
  port: 8080
spring:
  application:
    name: math_mcp_server
  ai:
    mcp:
      server:
        enabled: true
        name: test_mcp_server
        version: 1.0.0
        sse-endpoint: /api/v1/sse
        sse-message-endpoint: /api/v1/mcp
        capabilities:
          tool: true
logging:
  level:
    # 查看 MCP 详细日志
    io.modelcontextprotocol: TRACE
    org.springframework.ai.mcp: TRACE

启动服务

启动成功,并提示注册了两个 Tool

三、如何使用 MCP Server

方式一:使用 Chatbox 连接 MCP Server

设置 AI 模型提供方

这里选择智谱的 ChatGLM6B,API 密钥去智谱官网申请,点击检查。

配置 MCP 服务器

点击左侧的 MCP,添加服务器。

配置信息后点击测试。

编写的两个工具成功显示。

注意:必须点测试,这样才能完成服务端的初始化连接

服务端日志会显示连接状态。

点击保存。

使用 MCP Server

按 ECS 键退出设置,点击新对话,可以看到刚才添加的 MCP 服务。

输入'运维小兵的计算服务有哪些功能',AI 给的回复很好的总结了工具的功能。

问:8 加 7 等于几,工具成功调用。

服务端日志内容显示调用过程。

测试完毕,符合预期。

方式二:开发一个 Client 来连接 Server

创建 java 工程

跟创建 MCP Server 类似,改下 Artifact 名字。

添加 Client 的依赖。

保存工程文件,解压后用 IDEA 打开。

修改 pom.xml,添加核心依赖
<properties>
    <java.version>17</java.version>
    <spring-ai.version>1.1.2</spring-ai.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- 调用智谱系列大模型的依赖 -->
    <dependency>
        <groupId>org.springframework.ai</groupId>
        <artifactId>spring-ai-starter-model-zhipuai</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.ai</groupId>
        <artifactId>spring-ai-starter-mcp-client-webflux</artifactId>
    </dependency>
</dependencies>
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-bom</artifactId>
            <version>${spring-ai.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
配置 application.yaml
server:
  port: 8081
spring:
  application:
    name: test-mcp-client
  ai:
    zhipuai:
      # 智谱官网创建 API Key,配置到机器的环境变量 ZHIPU_KEY
      api-key: ${ZHIPU_KEY}
      base-url: "https://open.bigmodel.cn/api/paas"
    chat:
      options:
        model: glm-4-flash
    mcp:
      client:
        sse:
          connections:
            server1:
              # 填写 MCP Server 的地址
              url: http://localhost:8080
              sse-endpoint: /api/v1/sse
创建 Controller

ConnectMcpServer.java

package com.example.test_mcp_client.controller;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.tool.ToolCallbackProvider;
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;

@RestController
@RequestMapping("/mcp")
public class ConnectMcpServer {
    private final ChatClient chatClient;

    public ConnectMcpServer(ChatClient.Builder builder, ToolCallbackProvider toolCallbackProvider) {
        this.chatClient = builder
                .defaultToolCallbacks(toolCallbackProvider.getToolCallbacks())
                .build();
    }

    @GetMapping("/test")
    public String test(@RequestParam(name = "query") String query) {
        return chatClient.prompt()
                .system("你是一个有用的 AI 助手")
                .user(query)
                .call()
                .content();
    }
}
启动 Client 服务

服务启动成功。

SERVER 端完成初始化。

访问接口进行测试

GET http://localhost:8081/mcp/test?query=8 加 6 等于几

查看 SERVER 日志,调用成功。

四、资料

Spring AI 官网:https://docs.spring.io/spring-ai/reference/index.html

目录

  1. 一、概述
  2. MCP 架构图
  3. MCP 生命周期
  4. 二、创建 MCP SERVER 的 java 工程
  5. 生成初始化工程代码
  6. 修改 pom.xml 文件
  7. 定义服务类 MathTool
  8. 通过配置类的方式把 MathTool 注入到 Spring 容器中
  9. 修改配置文件 application.yaml
  10. 启动服务
  11. 三、如何使用 MCP Server
  12. 方式一:使用 Chatbox 连接 MCP Server
  13. 设置 AI 模型提供方
  14. 配置 MCP 服务器
  15. 使用 MCP Server
  16. 方式二:开发一个 Client 来连接 Server
  17. 创建 java 工程
  18. 修改 pom.xml,添加核心依赖
  19. 配置 application.yaml
  20. 创建 Controller
  21. 启动 Client 服务
  22. 访问接口进行测试
  23. 四、资料
  • 💰 8折买阿里云服务器限时8折了解详情
  • Magick API 一键接入全球大模型注册送1000万token查看
  • 🤖 一键搭建Deepseek满血版了解详情
  • 一键打造专属AI 智能体了解详情
极客日志微信公众号二维码

微信扫一扫,关注极客日志

微信公众号「极客日志V2」,在微信中扫描左侧二维码关注。展示文案:极客日志V2 zeeklog

更多推荐文章

查看全部
  • whisper.cpp 性能优化与编译配置指南
  • C++ 实现电子词典系统
  • PyCharm 中 Copilot 与 Claude 插件不可用问题排查
  • Linux 下 C/C++ 调试器 GDB/Cgdb 实战指南
  • LLM 应用开发实战:实现流式响应与高效落地
  • BaseCTF Week3 Web 与 Misc 部分解题报告
  • 12 个程序员高含金量证书详解与职业价值分析
  • FPGA 核心解析:从原理到应用场景详解
  • FreeRTOS 退避算法核心逻辑与实现
  • ChatGPT Prompt Hacker 技巧:优化简历通过 AI 筛选
  • 使用 100 行代码构建 Mini AI Agent 实战指南
  • 注意力机制与 Transformer 模型实战指南
  • 线性动态规划入门:四道经典例题实战解析
  • 2025年AI领域年度总结:DeepSeek R1开源与Manus商业化路径
  • openGauss 向量数据库能力与 RAG 应用场景解析
  • JavaScript 内置对象实战:String、Number 与 Array
  • Python 深浅拷贝详解:原理、实现与适用场景
  • Spring Boot Web 三大核心交互案例:表单、AJAX 及 JSON
  • 企业级黑词分析组件:双面板交互与进度监控实现
  • 微服务容器化与云原生部署:Docker + Kubernetes 实战

相关免费在线工具

  • Keycode 信息

    查找任何按下的键的javascript键代码、代码、位置和修饰符。 在线工具,Keycode 信息在线工具,online

  • Escape 与 Native 编解码

    JavaScript 字符串转义/反转义;Java 风格 \uXXXX(Native2Ascii)编码与解码。 在线工具,Escape 与 Native 编解码在线工具,online

  • JavaScript / HTML 格式化

    使用 Prettier 在浏览器内格式化 JavaScript 或 HTML 片段。 在线工具,JavaScript / HTML 格式化在线工具,online

  • JavaScript 压缩与混淆

    Terser 压缩、变量名混淆,或 javascript-obfuscator 高强度混淆(体积会增大)。 在线工具,JavaScript 压缩与混淆在线工具,online

  • RSA密钥对生成器

    生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online

  • Mermaid 预览与可视化编辑

    基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online