【从零搭建】AI大模型之ReactAgent智能体对接MCP实战

目录

一、AI大模型MCP协议介绍和服务端项目搭建

[1.1 什么是MCP协议?](#1.1 什么是MCP协议?)

[1.2 为什么需要MCP协议?](#1.2 为什么需要MCP协议?)

[1.3 MCP架构设计](#1.3 MCP架构设计)

[1.4 案例实战:创建MCP Server项目](#1.4 案例实战:创建MCP Server项目)

[1.5 关键配置说明](#1.5 关键配置说明)

[1.6 注意事项](#1.6 注意事项)

二、掌握@McpTool注解开发AI工具,实现计算器和天气查询工具的标准化注册

[2.1 什么是@McpTool注解?](#2.1 什么是@McpTool注解?)

[2.2 工具开发规范](#2.2 工具开发规范)

[2.3 案例实战一:计算器工具开发](#2.3 案例实战一:计算器工具开发)

[2.4 案例实战二:天气查询工具开发](#2.4 案例实战二:天气查询工具开发)

[2.5 工具自动注册流程](#2.5 工具自动注册流程)

[2.6 注意事项](#2.6 注意事项)

[三、MCP Client客户端项目创建和MCP配置实战](#三、MCP Client客户端项目创建和MCP配置实战)

[3.1 什么是MCP Client?](#3.1 什么是MCP Client?)

[3.2 整体调用链路](#3.2 整体调用链路)

[3.3 案例实战:创建MCP Client项目](#3.3 案例实战:创建MCP Client项目)

[四、使用Spring AI Alibaba Agent Framework构建ReactAgent智能体,整合MCP工具实现智能问答](#四、使用Spring AI Alibaba Agent Framework构建ReactAgent智能体,整合MCP工具实现智能问答)

[4.1 什么是ReactAgent?](#4.1 什么是ReactAgent?)

[4.2 案例实战:构建ReactAgent服务](#4.2 案例实战:构建ReactAgent服务)

五、ReactAgent智能体整合MCP全流程测试实战

[5.1 项目启动测试步骤](#5.1 项目启动测试步骤)

[5.2 ReactAgent智能体整合MCP测试验证](#5.2 ReactAgent智能体整合MCP测试验证)

[5.3 注意事项](#5.3 注意事项)


一、AI大模型MCP协议介绍和服务端项目搭建

1.1 什么是MCP协议?

  • 核心定义:**MCP(Model Context Protocol)**是由Anthropic公司推出的AI工具标准化协议

  • 简单说,MCP就像一个"AI工具的USB接口",让不同的AI模型可以用统一的方式调用各种工具

  • 打个比方:

    • 以前每个AI平台有自己的工具接口,就像手机充电线,安卓用Type-C,苹果用Lightning

    • MCP协议就像统一的充电标准,所有AI都用同一种方式调用工具

1.2 为什么需要MCP协议?

  • 需求背景

    • 协议不统一:不同AI平台的工具接口各异,适配成本高

    • 工具描述混乱:JSON Schema描述不规范,AI理解困难

    • 调试困难:工具调用出错时,难以定位问题

  • MCP协议的核心价值:

    • 标准化协议:统一AI工具接口规范

    • 自动发现:服务端自动注册工具,客户端自动发现

    • 类型安全:强类型参数定义,减少运行时错误

    • 跨平台:一次开发,多平台复用

1.3 MCP架构设计

1.4 案例实战:创建MCP Server项目

  • 项目结构

ai/

├── pom.xml # 父工程

├── mcp-server/ # MCP服务端

│ ├── pom.xml

│ └── src/main/

│ ├── java/

│ └── resources/

└── mcp-client/ # MCP客户端

├── pom.xml

└── src/main/

  • 父工程pom.xml核心配置
XML 复制代码
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.5.3</version>
        <relativePath/>
    </parent>

    <properties>
        <maven.compiler.source>21</maven.compiler.source>
        <maven.compiler.target>21</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring-ai.version>1.1.2</spring-ai.version>
        <spring-ai-alibaba.version>1.1.2.0</spring-ai-alibaba.version>
    </properties>

    <repositories>
        <repository>
            <id>aliyun-maven</id>
            <name>aliyun-maven</name>
            <url>https://maven.aliyun.com/repository/central</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>aliyun</id>
            <name>aliyun</name>
            <url>https://maven.aliyun.com/repository/public</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>aliyun-spring</id>
            <name>aliyun-spring</name>
            <url>https://maven.aliyun.com/repository/spring</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

    <dependencyManagement>
        <dependencies>
            <!-- Spring AI BOM -->
            <dependency>
                <groupId>org.springframework.ai</groupId>
                <artifactId>spring-ai-bom</artifactId>
                <version>${spring-ai.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!-- Spring AI Alibaba Extensions BOM(优先,覆盖 dashscope 版本为 1.1.2.1) -->
            <dependency>
                <groupId>com.alibaba.cloud.ai</groupId>
                <artifactId>spring-ai-alibaba-extensions-bom</artifactId>
                <version>1.1.2.1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!-- Spring AI Alibaba BOM -->
            <dependency>
                <groupId>com.alibaba.cloud.ai</groupId>
                <artifactId>spring-ai-alibaba-bom</artifactId>
                <version>${spring-ai-alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    

    <!-- 配置插件仓库 -->
    <pluginRepositories>
        <pluginRepository>
            <id>aliyun-plugin</id>
            <name>aliyun-plugin</name>
            <url>https://maven.aliyun.com/repository/public</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>
  • mcp-server模块pom.xml
XML 复制代码
<parent>
        <groupId>net.xdclass</groupId>
        <artifactId>mcp-demo</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>mcp-server</artifactId>
    <name>MCP Server</name>
    <description>MCP Server - 提供工具服务的独立部署模块</description>

    <dependencies>
        <!-- Spring Boot Starter Web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Spring AI MCP Server WebMvc Starter (包含 @Tool 注解支持) -->
        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-starter-mcp-server-webmvc</artifactId>
        </dependency>

        <!-- Spring AI Alibaba DashScope Starter -->
        <dependency>
            <groupId>com.alibaba.cloud.ai</groupId>
            <artifactId>spring-ai-alibaba-starter-dashscope</artifactId>
        </dependency>

        <!-- Lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <annotationProcessorPaths>
                        <path>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </path>
                    </annotationProcessorPaths>
                </configuration>
            </plugin>
        </plugins>
    </build>
  • application.yml配置
XML 复制代码
server:
  port: ${SERVER_PORT:8090}

spring:
  application:
    name: xd-mcp-server

  mvc:
    async:
      request-timeout: -1  # SSE长连接保持,不超时

  ai:
    dashscope:
      api-key: ${DASHSCOPE_API_KEY:sk-6xxxxxxxxxxxxxxxxxxxxff873fc}
      chat:
        options:
          model: ${AI_MODEL:qwen-max}
    mcp:
      server:
        enabled: true
        name: xdclass-mcp-server
        version: 1.0.0
        type: SYNC
#        区别说明:
#        STREAMABLE - 有状态,服务端仍维护session
#        STATELESS - 真正无状态,请求间不维护任何会话,专为云原生/Serverless设计
        protocol: STATELESS  # 无状态模式,完美适配FC/Serverless环境 https://www.spring-doc.cn/spring-ai/1.1.0/api_mcp_mcp-stateless-server-boot-starter-docs.html

        stateless:
          mcp-endpoint: /mcp  # 无状态HTTP端点
        annotation-scanner:
          enabled: true
  • 启动类
java 复制代码
@SpringBootApplication
public class McpServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(McpServerApplication.class, args);
    }
}

1.5 关键配置说明

配置项 说明
mcp.server.enabled 启用MCP服务端
mcp.server.type SYNC同步模式 / ASYNC异步模式
mcp.server.protocol STATELESS无状态 / STREAMABLE有状态
annotation-scanner.enabled 启用@McpTool注解扫描

1.6 注意事项

  • 端口隔离:MCP Server建议独立端口部署,与业务服务分离

  • 无状态模式 :STATELESS模式适合云原生/Serverless环境,无需维护会话

  • SSE超时 :设置request-timeout: -1避免长连接被中断

二、掌握@McpTool注解开发AI工具,实现计算器和天气查询工具的标准化注册

2.1 什么是@McpTool注解?

  • 核心定义:@McpTool是Spring AI MCP提供的工具注册注解,用于将Java方法标记为MCP工具

  • 简单说,就像给方法贴一个"AI可调用"的标签,AI就能自动发现并使用这个方法

  • 相关注解:

    • @McpTool:标记工具方法,定义name和description

    • @McpToolParam:标记参数,定义参数描述

2.2 工具开发规范

  • 命名规范:

    • 工具名使用下划线命名法,如calculator_add、weather_get_current

    • 描述要清晰说明工具用途,AI根据描述决定是否调用

  • 参数设计:

    • 每个参数都要有description描述

    • 参数类型使用基本类型或简单对象

  • 返回值:

    • 支持基本类型、Map、自定义对象

    • 返回值会被自动序列化为JSON

2.3 案例实战一:计算器工具开发

  • 需求:提供加减乘除、幂运算、开方等数学计算能力

  • 代码实现

java 复制代码
import lombok.extern.slf4j.Slf4j;
import org.springaicommunity.mcp.annotation.McpTool;
import org.springaicommunity.mcp.annotation.McpToolParam;
import org.springframework.stereotype.Component;

/**
 * 计算器工具
 * 提供基本的数学运算功能
 */
@Component
@Slf4j
public class CalculatorTool {

    /**
     * 加法运算
     */
    @McpTool(name = "calculator_add", description = "执行两个数字的加法运算")
    public double add(
            @McpToolParam(description = "第一个数字") double a,
            @McpToolParam(description = "第二个数字") double b) {
        log.info("执行加法运算:{} + {}", a, b);
        return a + b;
    }

    /**
     * 减法运算
     */
    @McpTool(name = "calculator_subtract", description = "执行两个数字的减法运算")
    public double subtract(
            @McpToolParam(description = "被减数") double a,
            @McpToolParam(description = "减数") double b) {
        log.info("执行减法运算:{} - {}", a, b);
        return a - b;
    }

    /**
     * 乘法运算
     */
    @McpTool(name = "calculator_multiply", description = "执行两个数字的乘法运算")
    public double multiply(
            @McpToolParam(description = "第一个数字") double a,
            @McpToolParam(description = "第二个数字") double b) {
        log.info("执行乘法运算:{} * {}", a, b);
        return a * b;
    }

    /**
     * 除法运算
     */
    @McpTool(name = "calculator_divide", description = "执行两个数字的除法运算")
    public double divide(
            @McpToolParam(description = "被除数") double a,
            @McpToolParam(description = "除数") double b) {
        if (b == 0) {
            throw new IllegalArgumentException("除数不能为零");
        }
        log.info("执行除法运算:{} / {}", a, b);
        return a / b;
    }

    /**
     * 幂运算
     */
    @McpTool(name = "calculator_power", description = "计算一个数的幂次方")
    public double power(
            @McpToolParam(description = "底数") double base,
            @McpToolParam(description = "指数") double exponent) {
        log.info("执行幂运算:{} ^ {}", base, exponent);
        return Math.pow(base, exponent);
    }

    /**
     * 平方根
     */
    @McpTool(name = "calculator_sqrt", description = "计算一个数的平方根")
    public double sqrt(
            @McpToolParam(description = "要计算平方根的数字") double value) {
        if (value < 0) {
            throw new IllegalArgumentException("不能计算负数的平方根");
        }
        log.info("执行平方根运算:sqrt({})", value);
        return Math.sqrt(value);
    }
}

2.4 案例实战二:天气查询工具开发

  • 需求:提供当前天气、天气预报、空气质量查询能力

  • 代码实现

java 复制代码
package net.xdclass.tool;

import lombok.extern.slf4j.Slf4j;
import org.springaicommunity.mcp.annotation.McpTool;
import org.springaicommunity.mcp.annotation.McpToolParam;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;


/**
 * 天气工具
 * 提供天气查询相关功能(模拟数据)
 */
@Slf4j
@Component
public class WeatherTool {

    private final Random random = new Random();

    /**
     * 获取指定城市的天气信息
     */
    @McpTool(name = "weather_get_current", description = "获取指定城市的当前天气信息")
    public Map<String, Object> getCurrentWeather(
            @McpToolParam(description = "城市名称,如:北京、上海、广州") String city) {

        log.info("mcp-sever getCurrentWeather 被调用 v1-------");
        Map<String, Object> weather = new HashMap<>();
        weather.put("city", city);
        weather.put("temperature", 15 + random.nextInt(20));
        weather.put("humidity", 40 + random.nextInt(40));
        weather.put("windSpeed", 5 + random.nextInt(15));
        weather.put("condition", getRandomCondition());
        weather.put("updateTime", LocalDateTime.now().toString());
        log.info("获取当前天气信息:{}", weather);
        return weather;
    }

    /**
     * 获取未来几天的天气预报
     */
    @McpTool(name = "weather_get_forecast", description = "获取指定城市未来几天的天气预报")
    public Map<String, Object> getWeatherForecast(
            @McpToolParam(description = "城市名称,如:北京、上海、广州") String city,
            @McpToolParam(description = "预报天数,1-7天") int days) {
        log.info("mcp-sever getWeatherForecast 被调用-------");
        if (days < 1 || days > 7) {
            throw new IllegalArgumentException("预报天数必须在1-7天之间");
        }

        Map<String, Object> forecast = new HashMap<>();
        forecast.put("city", city);
        forecast.put("days", days);

        List<Map<String, Object>> dailyForecasts = new ArrayList<>();
        for (int i = 0; i < days; i++) {
            Map<String, Object> dayWeather = new HashMap<>();
            dayWeather.put("day", i + 1);
            dayWeather.put("date", LocalDate.now().plusDays(i).toString());
            dayWeather.put("highTemp", 20 + random.nextInt(15));
            dayWeather.put("lowTemp", 10 + random.nextInt(10));
            dayWeather.put("condition", getRandomCondition());
            dailyForecasts.add(dayWeather);
        }
        forecast.put("forecast", dailyForecasts);
        log.info("获取天气预报:{}", forecast);
        return forecast;
    }

    private String getRandomCondition() {
        String[] conditions = {"晴", "多云", "阴", "小雨", "中雨", "雷阵雨"};
        return conditions[random.nextInt(conditions.length)];
    }
}

2.5 工具自动注册流程

2.6 注意事项

  • 工具命名 :使用模块_动作格式,如calculator_add、weather_get_current

  • 描述质量:描述越清晰,AI调用越准确

  • 异常处理:工具内部应处理异常,返回友好错误信息

  • 日志记录:每次工具调用都应记录日志,便于调试

三、MCP Client客户端项目创建和MCP配置实战

3.1 什么是MCP Client?

  • 核心定义:MCP Client是连接AI模型和MCP Server的桥梁,负责工具发现和调用

  • 简单说,MCP Client就像一个"翻译官":

    • 向MCP Server询问有哪些工具可用

    • 把AI的工具调用请求转发给Server

    • 把工具执行结果返回给AI

3.2 整体调用链路

3.3 案例实战:创建MCP Client项目

  • pom.xml依赖配置
XML 复制代码
    <dependencies>
        <!-- Spring Boot Starter Web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Spring Boot Starter WebFlux (for HTTP Client) -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>

        <!-- Spring AI Alibaba DashScope Starter -->
        <dependency>
            <groupId>com.alibaba.cloud.ai</groupId>
            <artifactId>spring-ai-alibaba-starter-dashscope</artifactId>
        </dependency>

        <!-- Spring AI MCP Client Starter -->
        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-starter-mcp-client</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba.cloud.ai</groupId>
            <artifactId>spring-ai-alibaba-agent-framework</artifactId>
            <version>1.1.2.0</version>
        </dependency>

        <!-- Netty DNS Resolver for macOS -->
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-resolver-dns-native-macos</artifactId>
            <classifier>osx-aarch_64</classifier>
            <scope>runtime</scope>
        </dependency>

        <!-- Lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <annotationProcessorPaths>
                        <path>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </path>
                    </annotationProcessorPaths>
                </configuration>
            </plugin>
        </plugins>
    </build>
  • application.yml配置
XML 复制代码
server:
  port: ${SERVER_PORT:8082}

spring:
  application:
    name: mcp-client
  ai:
    dashscope:
      api-key: ${DASHSCOPE_API_KEY:sk-6fcxxxxxxxxxxxxxxxxxxd0f77}
      chat:
        options:
          model: ${AI_MODEL:qwen-max}
    retry:
      max-attempts: 3
      initial-interval: 2000
      max-interval: 10000
      multiplier: 2
    mcp:
      client:
        enabled: true
        type: SYNC
        request-timeout: 60s
        toolcallback:
          enabled: true
        # 使用Streamable HTTP连接(无状态,适合FC环境)
        streamable-http:
          connections:
            mcp-server:
              url: http://127.0.0.1:8090
              endpoint: /mcp
  • 启动类
java 复制代码
@SpringBootApplication
public class McpClientApplication {
    public static void main(String[] args) {
        // 禁用JDK HTTP Client内部连接池,防止SSE重连时异常
        System.setProperty("jdk.httpclient.connectionPoolSize", "0");
        System.setProperty("jdk.httpclient.keepalive.timeout", "0");
        SpringApplication.run(McpClientApplication.class, args);
    }
}
  • controller控制类
java 复制代码
/**
 * MCP Client REST API 控制器
 * 通过 McpAgentService / ReactAgentService 驱动 AI 智能体,自动识别并调用 MCP Server 中的工具
 */
@Slf4j
@RestController
@RequestMapping("/api/mcp")
@RequiredArgsConstructor
public class ClientController {

    private final ReactAgentService reactAgentService;

    /**
     * ReactAgent 单次调用接口(无会话记忆)
     * 示例:GET /api/mcp/react?message=5加上10等于多少
     */
    @GetMapping("/react")
    public ResponseEntity<Map<String, Object>> reactChat(@RequestParam String message) {
        log.info("收到 ReactAgent 请求 (GET): {}", message);

        String response = reactAgentService.chat(message);

        Map<String, Object> result = new HashMap<>();
        result.put("message", message);
        result.put("response", response);
        return ResponseEntity.ok(result);
    }
}

四、使用Spring AI Alibaba Agent Framework构建ReactAgent智能体,整合MCP工具实现智能问答

4.1 什么是ReactAgent?

  • 核心定义:ReactAgent是基于ReAct(Reasoning + Acting)模式的智能体框架

  • 简单说,ReactAgent会"边思考边行动":

    • Reasoning:分析用户问题,决定需要调用哪些工具

    • Acting:执行工具调用,获取结果

    • 循环迭代 :根据结果继续思考,直到得出最终答案

4.2 案例实战:构建ReactAgent服务

  • 添加依赖【已经有了】
XML 复制代码
<!-- Spring AI Alibaba Agent Framework -->
<dependency>
    <groupId>com.alibaba.cloud.ai</groupId>
    <artifactId>spring-ai-alibaba-agent-framework</artifactId>
    <version>1.1.2.0</version>
</dependency>
  • ReactAgentService实现
java 复制代码
package net.xdclass.service;


import com.alibaba.cloud.ai.graph.agent.ReactAgent;
import com.alibaba.cloud.ai.graph.checkpoint.savers.MemorySaver;
import com.alibaba.cloud.ai.graph.exception.GraphRunnerException;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.stereotype.Service;

/**
 * ReactAgent 智能体服务
 * 基于 Spring AI Alibaba Agent Framework,集成 MCP 工具,支持多轮会话记忆
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ReactAgentService {

    private final ChatModel chatModel;
    private final ToolCallbackProvider mcpToolCallbackProvider;

    private ReactAgent reactAgent;

    private static final String SYSTEM_PROMPT = """
            你是一个集成了MCP工具的智能服务助手,拥有强大的工具调用能力。
            
            你当前可以使用以下类型的工具:
            - 数学计算:加法、减法、乘法、除法、幂运算、开方
            - 天气查询:当前天气、多日天气预报、空气质量指数
            
            工作原则:
            1. 对于需要计算或查询的问题,优先调用相关工具获取准确结果
            2. 对于多步骤复杂问题,请分步骤推理并依次调用工具
            3. 工具调用结果需整合后再给出最终回答
            4. 如果问题不需要工具,直接回答即可
            """;

    /**
     * 初始化 ReactAgent(Spring 容器启动后执行)
     * MCP 工具在此时已由 spring-ai-starter-mcp-client 自动加载完毕
     */
    @PostConstruct
    public void init() {
        ToolCallback[] toolCallbacks = mcpToolCallbackProvider.getToolCallbacks();

        log.info("===== ReactAgent 初始化开始 =====");
        log.info("加载 {} 个 MCP 工具:", toolCallbacks.length);
        for (ToolCallback tc : toolCallbacks) {
            log.info("  - [{}] {}", tc.getToolDefinition().name(), tc.getToolDefinition().description());
        }

        reactAgent = ReactAgent.builder()
                .name("mcp-react-agent")
                .model(chatModel)
                .tools(toolCallbacks)
                .systemPrompt(SYSTEM_PROMPT)
                .saver(new MemorySaver())  // 基于内存的会话状态存储
                .build();

        log.info("===== ReactAgent 初始化完成 =====");
    }

    /**
     * 无会话单次调用
     *
     * @param userMessage 用户输入
     * @return AI 最终响应文本
     */
    public String chat(String userMessage) {
        log.info("===== ReactAgent 单次调用开始 =====");
        log.info("用户输入: {}", userMessage);

        try {
            AssistantMessage response = reactAgent.call(userMessage);
            String content = response.getText();
            log.info("AI 响应: {}", content);
            log.info("===== ReactAgent 单次调用完成 =====");
            return content;
        } catch (GraphRunnerException e) {
            log.error("ReactAgent 调用失败: {}", e.getMessage(), e);
            throw new RuntimeException("ReactAgent 执行异常: " + e.getMessage(), e);
        }
    }
}

五、ReactAgent智能体整合MCP全流程测试实战

5.1 项目启动测试步骤

  • 先启动Server服务端,再启动Client客户端,观察日志加载的tool工具是否齐全

5.2 ReactAgent智能体整合MCP测试验证

  • 简单计算测试

GET http://localhost:8082/api/mcp/react?message=计算100除以5的结果

  • 复杂计算测试(多步骤推理)

GET http://localhost:8082/api/mcp/react?message=计算2的10次方再开平方

  • 天气查询测试

GET http://localhost:8082/api/mcp/react?message=上海今天天气怎么样,未来3天天气如何

5.3 注意事项

  • 初始化时机 :使用@PostConstruct确保MCP工具加载完成后再初始化Agent

  • 系统提示词:清晰描述Agent能力和工作原则,提升调用准确率

  • 异常处理 :捕获GraphRunnerException,返回友好错误信息

相关推荐
百度Geek说28 分钟前
研发Loop的上下文优化与多Agent协作实践
人工智能
七夜zippoe37 分钟前
Nexent 模型配置:4 字段与 9 个槽位
数据库·人工智能·模型·nexent
硅农程序猿42 分钟前
SOC 物理实现: RTL2GDS 系列(二)—Innovus 初始化
人工智能·嵌入式硬件·硬件架构
梦想很大很大1 小时前
一句“你好”用了 5671 Token:我在 Workrun 中追查 Agent 隐性成本的过程
前端·人工智能·后端
SimonKing1 小时前
AI Assistant被"隐藏"了?别慌,IDEA 2026.3 这波是换了个脑子
java·后端·程序员
诗句藏于尽头1 小时前
游戏《完美神话》-使用Ai-agent进行修复已停服游戏到本地成功部署以及GM端网页完整教程
人工智能·学习·游戏
依晨照旧1 小时前
从 MQ 积压查出 4000 个线程:不是泄漏,是事件总线的设计代价
人工智能
Resean02231 小时前
SpringMVC 6+源码分析(九)异常处理
java·spring·springmvc
geats人山人海1 小时前
现代c++4.1
java·开发语言·c++