AI模型交互协议天气示例

一个基于Spring Boot的AI模型交互协议(MCP)示例,展示了如何构建MCP服务器和客户端,实现天气预测和AI生成内容的功能。

  • by beligh-hamdi
  • Java
  • 本地部署
  • 更新于
在 GitHub 查看 beligh-hamdi/spring-ai-mcp-samples

使用说明

春季AI MCP天气示例

此存储库包含Spring AI模型上下文协议(MCP)博客文章的示例代码,演示了如何使用Spring Boot构建MCP服务器和客户端。

概述

模型上下文协议(MCP)规范了人工智能应用程序如何与外部工具和资源交互。这个例子展示了:

  • MCP气象服务器:一个Spring Boot服务器,将天气预报功能作为MCP工具公开
  • MCP天气客户端:一个连接到MCP服务器并使用LLM(Anthropic Claude)的Spring Boot AI应用程序

建筑

┌────────────────────────────────────────────────────────────┐
│                    MCP Weather Client                      │
│  ┌─────────────┐  ┌──────────────┐  ┌──────────────────┐   │
│  │  ChatClient │──│ MCP Client   │──│ Weather Server   │   │
│  │  (Claude)   │  │  Transport   │  │ (Streamable-HTTP)│   │
│  └─────────────┘  └──────────────┘  └──────────────────┘   │
│                           │                                │
│                   ┌──────────────┐  ┌──────────────────┐   │
│                   │ MCP Client   │──│  Brave Search    │   │
│                   │  Transport   │  │     (STDIO)      │   │
│                   └──────────────┘  └──────────────────┘   │
└────────────────────────────────────────────────────────────┘

演示的功能

MCP服务器功能

  • 工具:按坐标检索天气预报
  • 日志记录:发送给客户端的结构化日志消息
  • 进度跟踪:实时更新运营进度
  • 采样:从客户的LLM请求AI生成的内容

MCP客户端功能

  • 多服务器连接:同时连接到多个MCP服务器
  • 运输支持:流式HTTP和STDIO传输
  • 处理程序注释:处理服务器通知和请求
  • LLM集成:与Anthropic Claude无缝集成

先决条件

  • Java 17或更高版本
  • Maven 3.6+
  • 春季AI 1.1.0-SNAPSHOT
  • Node.js和NPM(用于可选的Brave Search集成)
  • Anthropic API密钥(用于客户)
  • 勇敢搜索API密钥(可选,用于网络搜索)

项目结构

spring-ai-mcp-samples/
├── ai-mcp-server/     # MCP Server implementation
│   ├── src/main/java/
│   │   └── .../server/
│   │       ├── McpServerApplication.java
│   │       └── WeatherService.java
│   └── pom.xml
├── ai-mcp-client/     # MCP Client implementation
│   ├── src/main/java/
│   │   └── .../client/
│   │       ├── McpClientApplication.java
│   │       └── McpClientHandlers.java
│   └── pom.xml
└── pom.xml                 # Parent POM

快速开始

1.配置Maven仓库

这两个项目都使用Spring AI快照。所需的存储库已在中配置 pom.xml 文件夹:

<repository>
    <id>central-portal-snapshots</id>
    <name>Central Portal Snapshots</name>
    <url>https://central.sonatype.com/repository/maven-snapshots/</url>
    <snapshots>
        <enabled>true</enabled>
    </snapshots>
</repository>

2.建设项目

# Build both server and client
mvn clean install -DskipTests

3.启动MCP气象服务器

cd mcp-weather-server
java -jar target/mcp-weather-server-0.0.1-SNAPSHOT.jar

服务器将在端口8080上启动,并通过Streamable HTTP传输公开天气预报工具。服务器日志将写入 ./mcp-weather-server/target/server.log 用于调试目的。

4.配置并启动MCP天气客户端

设置您的Anthropic API密钥:

export ANTHROPIC_API_KEY=your-api-key-here

(可选)为web搜索功能设置Brave Search API密钥:

export BRAVE_API_KEY=your-brave-api-key-here

启动客户端:

cd ai-mcp-client
java -jar target/ai-mcp-client-0.0.1-SNAPSHOT.jar

客户将:

  1. 连接到天气服务器
  2. 查询阿姆斯特丹的天气预报
  3. 接收人工智能生成的关于天气的诗(通过采样)
  4. 可选择在线搜索诗歌出版商(如果配置了Brave search)

MCP气象服务器详细信息

配置

服务器配置(application.properties):

# Server identification
spring.ai.mcp.server.name=ai-mcp-server

# Transport protocol (STREAMABLE or STDIO)
spring.ai.mcp.server.protocol=STREAMABLE

# Server port for Streamable-HTTP transport
spring.ai.mcp.server.port=8080

# Request timeout configuration
spring.ai.mcp.server.request-timeout=1h

# Logging configuration
logging.file.name=./ai-mcp-server/target/server.log

# Required for STDIO mode (must be uncommented when using STDIO)
# spring.main.web-application-type=none
# spring.main.banner-mode=off
# logging.pattern.console=

注意:使用STDIO传输时,必须禁用Spring Boot横幅和控制台日志模式,以防止干扰STDIO通信协议。

气象服务实施

这 WeatherService 类演示了高级MCP功能:

@McpTool(description = "Get the temperature for a specific location")
public String getTemperature(
    McpSyncServerExchange exchange,
    @McpToolParam(description = "The location latitude") double latitude,
    @McpToolParam(description = "The location longitude") double longitude,
    @McpProgressToken String progressToken)

主要特点:

  • 工具曝光: @McpTool 注释将该方法公开为MCP工具
  • 参数文档: @McpToolParam 提供参数说明
  • 进度跟踪: @McpProgressToken 启用进度更新
  • 服务器交换:访问客户端功能和双向通信

测试服务器

您可以使用以下方法独立测试服务器:

  1. MCP检查员:

    npx @modelcontextprotocol/inspector
    
    • 设置传输类型: Streamable HTTP
    • 网址: http://localhost:8080/mcp
    • 单击连接
  2. 克劳德桌面版 (STDIO模式): 添加到Claude桌面配置:

    {
      "mcpServers": {
        "spring-ai-mcp-weather": {
          "command": "java",
          "args": [
            "-Dspring.ai.mcp.server.stdio=true",
            "-Dspring.main.web-application-type=none",
            "-Dlogging.pattern.console=",
            "-jar",
            "/path/to/ai-mcp-server.jar"
          ]
        }
      }
    }
    

MCP天气客户端详细信息

配置

客户端配置(application.yml)连接到多个MCP服务器:

spring:
  ai:
    anthropic:
      api-key: ${ANTHROPIC_API_KEY}
    mcp:
      client:
        streamable-http:
          connections:
            my-weather-server:
              url: http://localhost:8080
        stdio:
          connections:
            brave-search:
              command: npx
              args: ["-y", "@modelcontextprotocol/server-brave-search"]

客户端处理程序

这 McpClientHandlers 类处理服务器通知:

@McpProgress(clients = "my-weather-server")
public void progressHandler(ProgressNotification notification) { }

@McpLogging(clients = "my-weather-server")
public void loggingHandler(LoggingMessageNotification message) { }

@McpSampling(clients = "my-weather-server")
public CreateMessageResult samplingHandler(CreateMessageRequest request) { }

聊天客户端集成

客户端使用Spring AI ChatClient 使用MCP工具:

chatClient.prompt(userPrompt)
    .toolContext(Map.of("progressToken", "token-" + new Random().nextInt()))
    .toolCallbacks(mcpToolProvider)
    .call()
    .content()

高级功能

双向人工智能通信

演示的最强大的功能是 采样,其中:

  1. 天气服务器请求客户端的LLM生成一首诗
  2. 客户端的处理程序使用其ChatClient处理请求
  3. 生成的诗返回到服务器
  4. 服务器将其合并到最终响应中

这创造了复杂的AI到AI交互,而不仅仅是简单的工具调用。

进度跟踪

服务器报告操作进度:

  • 0%-开始天气检索
  • 50%-开始人工智能采样
  • 100%-任务已完成

结构化日志记录

服务器发送结构化日志消息,客户端可用于:

  • 调试服务器操作
  • 审核跟踪
  • 监控仪表板

扩展示例

添加新工具

添加新方法 WeatherService 随着 @McpTool:

@McpTool(description = "Get weather forecast for multiple days")
public ForecastResponse getForecast(
    @McpToolParam(description = "Location latitude") double latitude,
    @McpToolParam(description = "Location longitude") double longitude,
    @McpToolParam(description = "Number of days") int days) {
    // Implementation
}

连接其他MCP服务器

在中添加新的服务器连接 application.yml:

spring:
  ai:
    mcp:
      client:
        stdio:
          connections:
            your-server:
              command: your-command
              args: [your-args]

自定义处理程序逻辑

为不同的服务器创建专门的处理程序:

@McpProgress(clients = {"weather-server", "database-server"})
public void multiServerProgressHandler(ProgressNotification notification) {
    // Handle progress from multiple servers
}

资源

支持

如有疑问和支持: