AI工具调用服务

通过Spring AI的Model Context Protocol(MCP)功能实现Claude AI对外部工具(如天气查询)的调用。

  • by farrar142-examples
  • Kotlin
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 farrar142/spring-mcp-server-claude-desktop-example

使用说明

概述

此示例展示了如何利用Spring AI的模型上下文协议(MCP)功能在Claude AI中调用外部工具。

核心功能

MyTool.getWeather: 返回任意天气信息的工具方法 McpConfig.myTools: 将MyTool注册为ToolCallbackProvider

执行方法

  1. 运行Spring Boot应用程序
    ./gradlew bootRun
    
  2. 运行Claude桌面应用程序
  3. 在Claude Desktop设置中添加MCP服务器
    {
       "mcpServers": {
          "spring-ai-mcp-weather": {
             "command": "npx",
             "args": ["-y", "mcp-remote", "http://localhost:8080/mcp", "--allow-http"]
          }
       }
    }
    
  4. 重启 Claude Desktop
  5. 开始与Claude AI对话
    • 例:“今天首尔的天气怎么样?”

提交日志

  1. 使用Spring Initializr创建项目
    • 模型上下文协议服务器
    • Spring Web
  2. 将Spring AI版本更改为1.1.0-M1
    • 当前1.0.3版本不支持Streamable HTTP
    // build.gradle.kts
    extra["springAiVersion"] = "1.1.0-M1"
    
  3. application.yml 配置
    #application.yml
    spring:
     ai:
       mcp:
          server:
             protocol: STREAMABLE
             enabled: true
    
  4. 工具编写
    //MyTool.kt
    class MyTool {
       private val weathers = arrayOf("Sunny","Rainy","Cloudy")
       @Tool
       fun getWeather(location:String) = weathers.random()
    }
    
  5. 将Tool注册为Bean
    @Configuration
    class McpConfig {
        @Bean
        fun myTools(): ToolCallbackProvider = MethodToolCallbackProvider.builder().toolObjects(MyTool()).build()
    }
    
  6. 修改claude_desktop_config.json
    {
       "mcpServers": {
          "spring-ai-mcp-weather": {
             "command": "npx",
             "args": ["-y", "mcp-remote", "http://localhost:8080/mcp", "--allow-http"]
          }
       }
    }
    
    
  7. SpringBoot运行后重启Claude Desktop