spring ai 开发MCP服务器(stdio)

06-01 1452阅读

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

        org.springframework.boot
        spring-boot-starter-parent
        3.4.4
         
    

        17
        1.0.0-M7
    
    
        
            org.springframework.ai
            spring-ai-starter-mcp-server
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    
    
        
            
                org.springframework.ai
                spring-ai-bom
                ${spring-ai.version}
                pom
                import
            
        
    
    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

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服务器配置如下图所示

spring ai 开发MCP服务器(stdio)

cherry似乎不会去读系统环境变量直接绝对路径使用就行

C:\Users\49651.jdks\corretto-17.0.14\bin\java

-jar

-Dfile.encoding=UTF-8

E:\owind-git\ai_mcp_server\target\aicode-0.0.1-SNAPSHOT.jar

选择刚刚配置的MCP服务器

spring ai 开发MCP服务器(stdio)

结果:

spring ai 开发MCP服务器(stdio)

这个MCP实现的是一个简单的加法功能,可以看到大模型正确的去调用了这个MCP

免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们。

目录[+]

取消
微信二维码
微信二维码
支付宝二维码