在其他地方查看文章:https://blog.liuzijian.com/post/spring-ai/2025/11/08/spring-ai-mcp-client/
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应用
- modelscope https://www.modelscope.cn/mcp/servers/@Joooook/12306-mcp
- github https://github.com/drfccv/mcp-server-12306
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