大模型应用开发Spring AI实战-Stdio方式实现MCP服务调用

上一篇文章分享了大模型应用开发Spring AI实战-开发自己的MCP应用今天这篇文章我来分享大模型应用开发Spring AI实战-Stdio方式实现MCP服务调用。通过实际代码案例,逐步掌握Java生态下的AI大模型应用产品开发。

AI专栏软件环境

  • IntelliJ IDEA2024.3.5
  • JDK 17.0.13
  • Spring AI 1.0.0-SNAPSHOT
  • Spring Boot 3.4.4
  • Spring 6.2.5
  • 通义千问大模型

我们先看本篇文章对应的项目结构,请看下图

text 复制代码
    spring-ai-lab08
    │  pom.xml
    │  
    ├─spring-ai-mcp-client-stdio
    │  │  pom.xml
    │  │  
    │  └─src
    │      ├─main
    │      │  ├─java
    │      │  │  └─cn
    │      │  │      └─itbeien
    │      │  │          └─mcp
    │      │  │              └─client
    │      │  │                  │  McpClientStdioBoot.java
    │      │  │                  │  
    │      │  │                  └─controller
    │      │  │                          AiController.java
    │      │  │                          
    │      │  └─resources
    │      │          application.properties
    │      │          mcp-servers-config.json
    │      │          
    │      └─test
    │          └─java
    └─spring-ai-mcp-server-stdio
        │  pom.xml
        │  
        └─src
            ├─main
            │  ├─java
            │  │  └─cn
            │  │      └─ibeien
            │  │          └─mcp
            │  │              └─server
            │  │                  │  McpServerStdioBoot.java
            │  │                  │  
            │  │                  ├─config
            │  │                  │      AppConfig.java
            │  │                  │      
            │  │                  └─service
            │  │                          McpService.java
            │  │                          
            │  └─resources
            │          application.properties
            │          
            └─test
                └─java

完整代码在文章最后,如果觉得本篇文章对你有用,记得点赞、关注、收藏哦。你的支持是我持续更新的动力!

1 MCP(Model Context Protocol)通信机制

Java MCP传输方式有STDIO和SSE两种

  • STDIO方式是基于进程间通信,MCP Client和MCP Server运行在同一主机,主要用于本地集成、命令行工具等场景。
  • SSE方式是基于HTTP协议,MCP Client远程调用MCP Server提供的SSE服务。实现客户端和服务端远程通信。

2 代码实现

2.1 MCP客户端实现

2.1.1 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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>cn.itbeien.ai</groupId>
        <artifactId>spring-ai-labs</artifactId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../../pom.xml</relativePath>
    </parent>

    <artifactId>spring-ai-mcp-client-stdio</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</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</artifactId>
        </dependency>
      <!--  <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-zhipuai-spring-boot-starter</artifactId>
            <version>${springai.version}</version>
        </dependency>-->
        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-openai-spring-boot-starter</artifactId>
            <version>${springai.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-mcp</artifactId>
        </dependency>
    </dependencies>

</project>

2.1.2 Mcp Server配置信息

通过以下配置使用STDIO方式调用MCP服务端功能

json 复制代码
{
  "mcpServers": {
    "stdio-mcp-server": {
           "command": "java",
           "args": [
               "-Dspring.ai.mcp.server.stdio=true",
               "-Dspring.main.web-application-type=none",
               "-Dport=8080",
               "-jar",
               "E:\\github\\programmer-guide\\ai-labs-master\\spring-ai-labs\\spring-ai-lab08\\spring-ai-mcp-server-stdio\\target\\spring-ai-mcp-server-stdio-1.0-SNAPSHOT.jar"
             ],
           "env": {}
         }
     }
}

2.1.3 MCP客户端与大模型集成

java 复制代码
package cn.itbeien.mcp.client.controller;

import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.prompt.Prompt;
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;

import java.util.ArrayList;
import java.util.List;

/**
 * @author itbeien
 * 项目网站:https://www.itbeien.cn
 * 公众号:贝恩聊架构
 * 全网同名,欢迎小伙伴们关注
 * Java/AI学习社群
 * Copyright© 2025 itbeien
 */
@RestController
@RequestMapping("/ai")
@RequiredArgsConstructor
public class AiController {

    // 自定义人设,来与用户进行角色扮演 提示词
    private final static String systemPrompt = "你是智能天气助手,请回答与天气相关的问题,用户在询问天气情况时必须要求给出哪个城市和哪一天";

    // 历史消息列表
    static List<Message> historyMessage = new ArrayList<>(List.of(new SystemMessage(systemPrompt)));

    private final ChatModel chatModel;

    private final ToolCallbackProvider tools;

    // 历史消息列表的最大长度
    static int maxLen = 1;
    @GetMapping("/chat")
    String generation(@RequestParam("prompt") String userInput) {
        return this.chatModel.call(userInput);
    }


    @GetMapping("/fcChat")
    String fcChat(@RequestParam("prompt") String userInput) {
        Prompt prompt = new Prompt(new UserMessage(userInput));
        return ChatClient.create(chatModel)
                .prompt(prompt)
                .system(systemPrompt)
                .tools(tools)
                .call()
                .content();
    }
}

2.1.4 MCP客户端配置

properties 复制代码
server.port=9090
spring.ai.mcp.client.enabled=true
spring.ai.mcp.client.stdio.root-change-notification=false
spring.ai.mcp.client.stdio.servers-configuration=classpath:/mcp-servers-config.json
spring.ai.mcp.client.toolcallback.enabled=true

spring.ai.openai.api-key=${DASHSCOPE_API_KEY}
spring.ai.openai.base-url=https://dashscope.aliyuncs.com
spring.ai.openai.chat.enabled=true
spring.ai.openai.chat.options.model=qwen-plus
spring.ai.openai.chat.completions-path=/compatible-mode/v1/chat/completions

2.2 MCP服务端实现

2.2.1 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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>cn.itbeien.ai</groupId>
        <artifactId>spring-ai-labs</artifactId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../../pom.xml</relativePath>
    </parent>

    <artifactId>spring-ai-mcp-server-stdio</artifactId>

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>3.4.4</version> <!-- 使用与Spring Boot版本相匹配的插件版本 -->
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

2.2.2 配置信息

properties 复制代码
spring.ai.mcp.server.stdio=true
spring.main.banner-mode=off
spring.main.web-application-type=none
logging.pattern.console=

2.2.3 注册MCP服务

java 复制代码
package cn.ibeien.mcp.server.config;

import cn.ibeien.mcp.server.service.McpService;
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;

/**
 * @author itbeien
 * 项目网站:https://www.itbeien.cn
 * 公众号:贝恩聊架构
 * 全网同名,欢迎小伙伴们关注
 * Java/AI/支付系统/SAAS多租户基础技术平台学习社群
 * Copyright© 2025 itbeien
 */
@Configuration
public class AppConfig {
    @Bean
    public ToolCallbackProvider weatherTools(McpService mcpService) {
        return  MethodToolCallbackProvider.builder().toolObjects(mcpService).build();
    }

}

3 单元测试

​ 启动MCP客户端程序,MCP服务端不用启动。当你向大模型提问"深圳今天的天气" 时Spring AI MCP client会通过预先配置好的mcp-servers-config.json通过STDIO方式和服务端spring-ai-mcp-server-stdio-1.0-SNAPSHOT.jar进行通信,MCP服务端返回天气信息。

以上就是今天大模型应用开发Spring AI实战-Stdio方式实现MCP服务调用全部内容,文章最后有源码下载地址

4 源码地址

贝恩聊架构-AI专栏,SpringBoot3专栏系列文章、资料和源代码会同步到以下地址,代码和资料每周都会同步更新

该仓库地址主要用于存放贝恩聊架构-SpringBoot3专栏、贝恩聊架构-AI专栏、基于企业级支付系统学习微服务整体技术栈所有资料和源码

Gitee:gitee.com/itbeien/pro...

Github:github.com/itbeien/pro...

相关推荐
IT_陈寒14 分钟前
Element Plus 2.10.0 重磅发布!新增Splitter组件
前端·人工智能·后端
jndingxin14 分钟前
OpenCV CUDA模块图像处理------创建一个模板匹配(Template Matching)对象函数createTemplateMatching()
图像处理·人工智能·opencv
盛寒40 分钟前
N元语言模型 —— 一文讲懂!!!
人工智能·语言模型·自然语言处理
有梦想的攻城狮43 分钟前
spring中的@RabbitListener注解详解
java·后端·spring·rabbitlistener
weixin_177297220691 小时前
家政小程序开发——AI+IoT技术融合,打造“智慧家政”新物种
人工智能·物联网
Java水解1 小时前
MySQL DQL全面解析:从入门到精通
后端·mysql
Aurora_NeAr1 小时前
Apache Spark详解
大数据·后端·spark
程序员岳焱1 小时前
Java 程序员成长记(二):菜鸟入职之 MyBatis XML「陷阱」
java·后端·程序员
hello早上好1 小时前
BeanFactory 实现
后端·spring·架构
我命由我123451 小时前
Spring Boot 项目集成 Redis 问题:RedisTemplate 多余空格问题
java·开发语言·spring boot·redis·后端·java-ee·intellij-idea