spring ai 开发MCP服务器(stdio)
spring ai 开发MCP服务器(stdio)
一、什么是MCP(Model Context Protocol)
MCP(Model Context Protocol,模型上下文协议) ,2024年11月底,由 Anthropic 推出的一种开放标准,旨在统一大型语言模型(LLM)与外部数据源和工具之间的通信协议。MCP 的主要目的在于解决当前 AI 模型因数据孤岛限制而无法充分发挥潜力的难题,MCP 使得 AI 应用能够安全地访问和操作本地及远程数据,为 AI 应用提供了连接万物的接口。
spring ai 官网介绍 https://docs.spring.io/spring-ai/reference/1.0/api/mcp/mcp-overview.html
看到网上有很多node和python写的MCP服务器,我突发奇想,java是不是也可以写,就去研究了一下。
二、依赖及插件引入pom
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>3.4.4version>
<relativePath/>
parent>
<properties>
<java.version>17java.version>
<spring-ai.version>1.0.0-M7spring-ai.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.aigroupId>
<artifactId>spring-ai-starter-mcp-serverartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.aigroupId>
<artifactId>spring-ai-bomartifactId>
<version>${spring-ai.version}version>
<type>pomtype>
<scope>importscope>
dependency>
dependencies>
dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
plugin>
plugins>
build>
M7版本在我写博客的时候 webmvc和sse的功能似乎存在问题,并不能正常调用。JDK注意要使用17及以上的,官方的sdk就是需要17及以上的。
三、启动类编写注册工具
@SpringBootApplication
public class AiApplication {
public static void main(String[] args) {
SpringApplication.run(AiApplication.class, args);
}
//注册工具
@Bean
public ToolCallbackProvider CalculateTools (Calculate calculate) {
return MethodToolCallbackProvider.builder().toolObjects(calculate).build();
}
}
服务类
@Service
public class Calculate {
//工具示例
@Tool(description = "加法计算器")
public String add(
@ToolParam(description = "加数1", required = false) double a,
@ToolParam(description = "加数2", required = false) double b
) {
return String.valueOf(a + b);
}
}
yaml文件
spring:
ai:
mcp:
server:
name: stdio-mcp-server
version: 1.0.0
type: SYNC
这样一个简单的MCP服务端就完成了
直接maven打包
接下去用cherrystudio进行测试
https://cherry-ai.com/
根据cherry的官网先配置好MCP的环境
MCP服务器配置如下图所示
cherry似乎不会去读系统环境变量直接绝对路径使用就行
C:Users9651.jdkscorretto-17.0.14injava
-jar
-Dfile.encoding=UTF-8
E:owind-giti_mcp_server argeticode-0.0.1-SNAPSHOT.jar
选择刚刚配置的MCP服务器
结果:
这个MCP实现的是一个简单的加法功能,可以看到大模型正确的去调用了这个MCP