Spring AI(9)——MCP客户端

Spring AI的MCP客户端介绍

模型上下文协议 (MCP) 是一种标准化协议,使 AI 模型能够以结构化方式与外部工具和资源交互。 它支持多种传输机制,以便在不同环境中提供灵活性。

MCP Java SDK 提供模型上下文协议的 Java 实现,通过同步和异步通信模式实现与 AI 模型和工具的标准化交互。

Spring AI MCP通过 Spring Boot 集成扩展了 MCP Java SDK,同时提供了客户端和服务器Starters。 

MCP官网提供的java sdk:Overview - Model Context Protocol

Spring AI提供了两种客户端的开发:

  • 标准客户端

        通过STDIO(in-process) 和/或SSE(远程)访问MCP服务端。 SSE 连接使用基于 HttpClient 的传输实现。 与 MCP 服务器的每次连接都会创建一个新的 MCP 客户端实例。 可以选择SYNC或ASYNCMCP 客户端(注意:不能混合使用同步客户端和异步客户端)。 

  • WebFlux客户端

        提供与标准客户端类似的功能,但使用基于 WebFlux 的 SSE 传输实现。

SDTIO方式通信

导入jar

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

yml配置

application.yml


logging:
  level:
    org.springframework.ai: DEBUG
    io.modelcontextprotocol.client: DEBUG
    io.modelcontextprotocol.spec: DEBUG

spring:
  ai:
    zhipuai:
      api-key: 智谱大模型的apikey
      chat:
        options:
          model: glm-4-flash
          temperature: 0.7

    mcp:
      client:
        name: my-mcp-client
        version: 1.0.0
        request-timeout: 10s
        type: sync
        stdio:
          servers-configuration: classpath:mcp-servers-config.json




Claude Desktop 格式的MCP服务的JSON配置

mcp-servers-config.json

{
  "mcpServers": {
    "everything": {
      "command": "C:\\Program Files\\nodejs\\npx.cmd",
      "args": [
        "-y",
        "@modelcontextprotocol/server-everything@2025.4.28"
      ]
    }
  }
}

注意:application.yml和mcp-servers-config.json都放在项目的resources目录下

本例使用的MCP服务是server-everything,关于该mcp服务的介绍,可以参考博客:

LangChain4j(17)——MCP客户端-优快云博客

ChatClient对象中指定MCP服务器

注入MCP的同步客户端对象

    @Resource
    private List<McpSyncClient> mcpSyncClients;
    @Bean
    public ChatClient chatClient(ZhiPuAiChatModel chatModel) {
        return ChatClient
                .builder(chatModel)
                // 设置系统消息
                .defaultSystem("你是一个java架构师")
                // 指定工具
                .defaultTools(new MyTools())
                // 指定同步的MCP回调工具对象
                .defaultToolCallbacks(new SyncMcpToolCallbackProvider(mcpSyncClients))

                //配置日志相关的Advisor,需要开启日志级别以及配置 默认debug级别
                .defaultAdvisors(simpleLoggerAdvisor(),
                        MessageChatMemoryAdvisor.builder(chatMemory()).build()
                )
                .build();
    }

控制层方法

package com.renr.springainew.mcp;

import jakarta.annotation.Resource;
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.RestController;

/**
 * @Classname MspClientController
 * @Description TODO
 * @Date 2025-05-28 18:29
 * @Created by 老任与码
 */
@RestController
@RequestMapping("/mcp")
public class MspClientController {

    @Resource
    private ChatClient client;

    @GetMapping("/chat")
    public String chat(String message) {
        String answer = this.client.prompt("11加12等于多少").call().content();
        System.out.println(answer);
        return "success";
    }
}

执行结果

我们还打印了执行过程的一些日志,从日志中看出,内部调用了server-everyting服务的add方法。

Http SSE方式通信

修改yml配置

logging:
  level:
    org.springframework.ai: DEBUG
    io.modelcontextprotocol.client: DEBUG
    io.modelcontextprotocol.spec: DEBUG
spring:
  ai:
    zhipuai:
      api-key: XXXXXXXXX
      chat:
        options:
          model: glm-4-flash
          temperature: 0.7

    mcp:
      client:
        name: my-mcp-client
        version: 1.0.0
        request-timeout: 10s
        type: sync
        sse:
          connections:
            server1:
              url: http://localhost:3001
              sse-endpoint: /sse



以sse方式启动server-everyting服务

安装:

npm install -g @modelcontextprotocol/server-everything@2025.4.28

sse模式启动服务:

 找到服务的安装位置,执行如下命令:

注意:笔者按照server-everything中提供的sse方式启动后,mcp客户端无法连接。不确定是哪里的问题。

官方的启动方式:npx @modelcontextprotocol/server-everything sse

控制层方法不变,测试结果如下:

从输出日志可以看出,也调用了server-everything中的add函数。

WebFlux SSE方式通信 

只需要修改导入的jar为:

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

其他的配置和代码无需改动,本文不再演示。

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值