惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

酷 壳 – CoolShell
酷 壳 – CoolShell
aimingoo的专栏
aimingoo的专栏
Microsoft Security Blog
Microsoft Security Blog
NISL@THU
NISL@THU
T
Threatpost
T
The Exploit Database - CXSecurity.com
T
Threat Research - Cisco Blogs
S
Securelist
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
人人都是产品经理
人人都是产品经理
B
Blog RSS Feed
S
Secure Thoughts
MyScale Blog
MyScale Blog
O
OpenAI News
P
Palo Alto Networks Blog
美团技术团队
C
Cyber Attacks, Cyber Crime and Cyber Security
TaoSecurity Blog
TaoSecurity Blog
量子位
L
Lohrmann on Cybersecurity
G
GRAHAM CLULEY
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
T
Tailwind CSS Blog
Know Your Adversary
Know Your Adversary
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Simon Willison's Weblog
Simon Willison's Weblog
宝玉的分享
宝玉的分享
PCI Perspectives
PCI Perspectives
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
C
Cybersecurity and Infrastructure Security Agency CISA
T
Tenable Blog
I
InfoQ
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Microsoft Azure Blog
Microsoft Azure Blog
Recent Announcements
Recent Announcements
S
Security @ Cisco Blogs
S
Schneier on Security
B
Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
The Cloudflare Blog
AWS News Blog
AWS News Blog
IT之家
IT之家
V
Vulnerabilities – Threatpost
The Hacker News
The Hacker News
H
Heimdal Security Blog
I
Intezer
A
Arctic Wolf
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
H
Help Net Security
W
WeLiveSecurity

Liu Zijian's Blog | 一个技术博客

使用Certbot自动续签HTTPS证书 使用Filebeat采集Nginx日志到ES Python的协程 Python中的异常 Python中的类和对象 Python的函数 Python的数据结构,推导式、迭代器和生成器 Spring AI集成多模态模型 LangChain4j多模态 LangChain Tools工具使用 Python中的模块和包 Python全局环境和虚拟环境(venv) LangChain Prompt提示词工程 LangChain4j Tools工具使用 基于Dify搭建AI智能体应用 LangChain4j RAG检索增强生成 Spring AI实现MCP Server LangChain4j Prompt提示词工程 Spring AI使用知识库增强对话功能 Spring AI实现一个智能客服 Spring AI实现一个简单的对话机器人 实现MinIO数据的每日备份 自己实现一个DNS服务 简单理解AI智能体 大模型和大模型应用 LangChain开篇 LangChain4j开篇 一个解析Excel2007的POI工具类 DataPermissionInterceptor源码解读 TenantLineInnerInterceptor源码解读 BaseMultiTableInnerInterceptor源码解读 Spring AI开篇 SQL解析工具JSQLParser 芋道源码解读之多租户 芋道源码解读之数据权限 芋道源码解读开篇 Java实现将数据导出为Word文档 OA系统的天数该怎样计算 安装MySQL8 安装MySQL5.7 RockyLinux9环境下编译MySQL8 MySQL字符集及底层原理 Java实现LDAP登录 Docker Compose IPv4和IPv6 使用虚拟机安装一个K8s集群 使用GraalVM原生编译打包SpringBoot工程 Nginx防止目录穿越 Java线程的状态 Nginx防盗链设置 使用python将excel表格转换为SQL INSERT Redis的公共操作命令 Redis数据结构之Bitfleid Redis数据结构之Bitmap Redis数据结构之GEO Redis数据结构之Hash Redis数据结构之HyperLogLog Redis数据结构之List Redis数据结构之Set Redis数据结构之Stream Redis数据结构之String Redis数据结构之ZSet 使用python压缩图片 利用Python实现Hexo站点的持续集成 Nginx设置HTTPS监听 firewalld防火墙工具的使用 Linux信号(signal)机制 MySQL5.7x 主从复制 用IP自签发一个HTTPS证书 基于Hexo实现一个静态的个人博客 RockyLinux9环境下编译MySQL5.7 Docker离线安装 MySQL数据定义语言 Docker与联合文件系统 Docker的网络 Docker的镜像操作 MySQL存储过程 MyBatis-Plus开篇 MySQL变量 MySQL视图 MySQL事务 MySQL插入修改和删除 MySQL查询 MySQL系统命令 Docker的容器操作 Docker的安装和配置 Docker容器数据卷 浅谈OAuth2.0授权原理 JVM开篇 浅谈Linux(Unix)的I/O模型 一个通用的CloseableHttpClient工厂类 JUC可重入锁ReentrantLock JUC读写锁ReadWriteLock Java的单例 Java泛型 Java8的新特性 最近最少使用算法(LRU) MySQL函数 SpringBoot配置和启动 volatile作用分析
Spring AI集成MCP Client
Liu Zijian · 2025-11-08 · via Liu Zijian's Blog | 一个技术博客

未完待续

1.MCP概述

MCP(Model Context Protocol),即模型上下文协议,是一种开放标准,使大模型采用统一的标准化的方式与外部的工具和数据等进行通信交互。

之前提到,大模型可以通过Tools(Function calling)来实现一些获取信息和操作数据的功能,如果我们自定义好了一些公共的工具给别人用,例如提供实时日期信息、天气信息,股市交易信息、汇率信息等,想要开放给很多大模型来使用,如果没有标准化的接口,每产生一个大模型应用就要适配一次,MCP协议为解决这一问题而生,现在我们实现的工具只需要面向MCP接口协议进行开发,大模型也遵循MCP规范进行接入使用,这个问题就解决了,我们实现的服务就叫MCP服务端,大模型实现的就是MCP的客户端。

MCP协议产生于2024年,具体协议内容可见:https://modelcontextprotocol.io/docs/getting-started/intro

2.调用MCP

MCP调用方式有三种,SSE,streamable-http和Stdio,SSE和streamable-http以http方式调用部署好的远程MCP服务器上的MCP,Stdio是将MCP的源码下载到本地打成软件包,使用Spring AI驱动npx或uvx等命令来本地调用软件包中的MCP,其中常见的TypeScript编写的MCP需要由npx调用,Python编写的MCP需要由uvx调用,其他语言也有其他语言MCP的调用方式。

我使用的Spring AI 1.0.3版本不支持streamable-http,在远程调用modelscope时需要在modelscope上修改接口为SSE模式。从1.1.0版本开始支持了streamable-http

以部署在modelscope上面的12306-mcp为例,分别介绍SSE远程调用和Stdio模式本地调用。12306-mcp是一个查询铁路12306平台,返回列车订票信息的MCP应用

2.1 SSE调用MCP

pom中引入调用MCP需要的spring-ai-starter-mcp-client依赖

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.5.7</version>
</parent>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-bom</artifactId>
            <version>1.0.3</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

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

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

    <dependency>
        <groupId>org.springframework.ai</groupId>
        <artifactId>spring-ai-starter-model-deepseek</artifactId>
    </dependency>

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

    <!-- Lombok -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>

</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>21</source>
                <target>21</target>
                <encoding>UTF-8</encoding>
            </configuration>
        </plugin>
    </plugins>
</build>

application.yml中配置一个modelscope上面开放的MCP工具12306-mcp

spring:
  ai:
    mcp:
      client:
        enabled: true
        name: spring-ai-agent
        type: async
        sse:
          connections:
            12306-mcp:
              url: https://mcp.api-inference.modelscope.net/
              sse-endpoint: /********/sse

    deepseek:
      base-url: https://api.deepseek.com
      api-key: ${DEEP_SEEK_KEY}

logging:
  level:
    io.modelcontextprotocol: DEBUG
    org.springframework.ai.mcp: DEBUG

配置类中,将外部MCP工具ToolCallbackProvider注入并和ChatClient进行绑定

package org.example.config;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.deepseek.DeepSeekChatModel;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {

    @Bean
    public ChatClient chatClient(DeepSeekChatModel model, ChatMemory chatMemory, ToolCallbackProvider toolCallbackProvider) {
        return ChatClient.builder(model)
                .defaultAdvisors(
                        SimpleLoggerAdvisor.builder().build(),
                        MessageChatMemoryAdvisor.builder(chatMemory).build()
                )
                .defaultToolCallbacks(toolCallbackProvider)
                .build();
    }

}

对话接口和以往完全一样

package org.example.controller;

import jakarta.annotation.Resource;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

@RestController
@RequestMapping("ai")
public class ChatController {

    @Resource
    private ChatClient chatClient;

    //127.0.0.1:8080/ai/chat-stream?msg=你是谁&chatId=001
    @GetMapping(value = "chat-stream", produces = "text/html;charset=utf-8")
    public Flux<String> stream(String msg, String chatId) {

        return chatClient.prompt()
                .user(msg)
                .advisors(advisor -> advisor.param(ChatMemory.CONVERSATION_ID, chatId))
                .stream()
                .content();

    }
}

大模型已经能在对话中调用MCP了

2.2 Stdio调用MCP

因为是本地调用,所以需要先将这个MCP的源码clone并安装到本地,因为这个MCP是TS语言编写,因此还需要用npm将其安装到本地。

git clone https://github.com/Joooook/12306-mcp.git

cd 12306-mcp 

npm i

运行前,如未安装npx,还需要全局安装npx,用于被Spring AI驱动本地运行MCP

npm i -g npx

根据MCP的标准,Stdio模式将MCP按一定格式配置到JSON文件中

{
  "mcpServers": {
    "12306-mcp": {
      "args": [
        "-y",
        "12306-mcp"
      ],
      "command": "npx"
    }
  }
}

modelscope上面给出的JSON格式是Mac/Linux的,如果是Windows系统,需要修改:

{
  "mcpServers": {
    "12306-mcp": {
      "command": "cmd",
      "args": [
        "/c",
        "npx",
        "-y",
        "12306-mcp"
      ]
    }

  }
}

将配置文件放入类路径下,同application.yml放在一级,这里将这个json文件命名为mcp-server.json,并将配置放入spring ai

spring:
  ai:
    mcp:
      client:
        enabled: true
        name: spring-ai-agent
        type: sync
        stdio:
          servers-configuration: classpath:mcp-server.json
    deepseek:
      base-url: https://api.deepseek.com
      api-key: ${DEEP_SEEK_KEY}

logging:
  level:
    io.modelcontextprotocol: DEBUG
    org.springframework.ai.mcp: DEBUG

启动后,可见日志

2025-11-09T12:15:07.418+08:00  INFO 39432 --- [pool-5-thread-1] i.m.c.transport.StdioClientTransport     : STDERR Message received: 12306 MCP Server running on stdio @Joooook

运行起来是相同的效果

2.3 续:Streamable-HTTP调用MCP

2025年11月14日前后,Spring AI 1.0.0发布,支持了Streamable-HTTP方式,只需要修改版本号,然后做以下配置即可:

spring:
  ai:
    mcp:
      client:
        enabled: true
        name: spring-ai-agent
        type: async
        streamable-http:
          connections:
            12306-mcp:
              url: https://mcp.api-inference.modelscope.net/
              endpoint: /********/mcp