Integrating FastGPT Workflow with Spring AI MCP for Train Ticket AI Chatbot

This article demonstrates how to resolve AI hallucination in train‑ticket queries by cleaning data, building a Spring AI‑based Model Context Protocol (MCP) server with HTTP SSE in Java, exposing it as a tool, and seamlessly integrating the server into a FastGPT workflow to enable natural‑language train‑ticket assistance.

Ubiquitous Tech
Ubiquitous Tech
Ubiquitous Tech
Integrating FastGPT Workflow with Spring AI MCP for Train Ticket AI Chatbot

The article starts by recalling the previous FastGPT tutorial that used tool‑calling to query train‑ticket information from Tongcheng Travel. It points out that AI hallucination occurs because the model does not understand the business meaning of each field in the raw JSON response.

Two mitigation strategies are presented: (1) describe each field in the prompt, and (2) clean the data before feeding it to the model. The author chooses the second approach and shows a screenshot of the data‑cleaning code.

Next, the article describes how to replace the manual HTTP node in the FastGPT workflow with an MCP‑based service. It explains that MCP (Model Context Protocol) is an open protocol that standardises the interaction between LLMs and external tools, making it easier to integrate business systems via natural language.

Three ways to implement an MCP server are listed, and the author selects the HTTP SSE mode using Spring AI. The development environment requirements are listed (NodeJS, Java 17, SpringAI 1.0.0‑M7, LLMs such as gpt‑4.1, gpt‑4o, qwen3, and MCP client tools).

Project setup

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>cn.aijavapro</groupId>
    <artifactId>tongchenglvxing-huoche-mcp-server</artifactId>
    <version>1.0-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.4.2</version>
    </parent>
    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.ai</groupId>
                <artifactId>spring-ai-bom</artifactId>
                <version>1.0.0-M7</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-starter-mcp-server-webmvc</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.83</version>
        </dependency>
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.9.3</version>
        </dependency>
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.18.1</version>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.18</version>
        </dependency>
    </dependencies>
</project>

The application.yml configures the MCP server to use the SSE transport:

spring:
  ai:
    mcp:
      server:
        enabled: true
        name: tongchenglvxing-mcp-server
        version: 1.0.0
        type: ASYNC # recommended for reactive apps
        sse-endpoint: /sse
        sse-message-endpoint: /mcp/messages
      transport:
        mode: sse

Utility classes are added: HuochepiaoConstant stores the Tongcheng Travel API URLs and a pool of User‑Agent strings. HuochepiaoQueryResult holds either the result JSON or an error message.

The HTTP request helper HuochepiaoHttpRequestUtil uses OkHttpClient to (1) obtain city codes, (2) query the train‑ticket list, and (3) convert raw field names into readable Chinese labels (e.g., converting "type" codes to "高铁", seat class codes to "商务座", etc.). The core method getTrainTickList performs the three‑step workflow described in the article:

Request city‑code API to translate user‑provided station names.

Build the query payload with departure/arrival codes, date, and other parameters.

Send the request, validate the response, and transform the data structure into a clean JSON object.

The service class HuochepiaoQueryService is annotated with Spring AI @Tool to expose two tools to the LLM: get_current_system_time – returns the current timestamp. query_train_tickets_list – validates parameters, calls HuochepiaoHttpRequestUtil.getTrainTickList, and returns the structured result.

@Service
@Slf4j
public class HuochepiaoQueryService {
    @Tool(name = "get_current_system_time",
          description = "查询当前系统时间工具,它可以帮助你获取当前系统日期时间,返回格式为:yyyy-MM-dd hh:mm:ss,可用于火车票查询等需要时间验证的场景。")
    public String getCurrentSystemTime() {
        return DateUtil.formatDateTime(new Date());
    }

    @Tool(name = "query_train_tickets_list",
          description = "火车票车次列表查询功能,查询指定日期、出发地和目的地之间的火车票信息。输入用户提供的出发站出发城市、到达站到达城市、出发日期进行查询结果,返回包含车次列表、出发/到达站信息、座位类型及票价等详细信息。本工具提供中国境内火车票班次信息的全面查询服务,数据实时对接同程旅行网官方接口。 提供不同座位类型(商务座/一等座/二等座等)的实时票价")
    public HuochepiaoQueryResult queryTrainTicketsList(
            @ToolParam(description = "出发火车站名称或者出发城市名称。支持输入火车站全称(如北京西站)或城市名(如北京)") String depStationName,
            @ToolParam(description = "目的地火车站名称或者到城市名称。支持输入火车站全称(如北京西站)或城市名(如北京) ") String arrStationName,
            @ToolParam(description = "出发日期,格式为yyyy-MM-dd") String depDate) {
        if (!StringUtils.hasText(arrStationName) || !StringUtils.hasText(depStationName) || !StringUtils.hasText(depDate)) {
            HuochepiaoQueryResult result = new HuochepiaoQueryResult();
            result.setErrorMessage("参数不完整,请确保提供了depStationName、arrStationName、depDate");
            return result;
        }
        try {
            JSONObject resultData = HuochepiaoHttpRequestUtil.getTrainTickList(depStationName, arrStationName, depDate);
            HuochepiaoQueryResult result = new HuochepiaoQueryResult();
            result.setResultData(resultData);
            return result;
        } catch (Exception e) {
            log.error("获取火车票车次列表出现异常:{}", e.getMessage(), e);
            HuochepiaoQueryResult result = new HuochepiaoQueryResult();
            result.setErrorMessage("获取火车票车次列表出现异常");
            return result;
        }
    }
}

The Spring Boot entry point registers the service as a tool provider:

@SpringBootApplication
public class McpApplication {
    public static void main(String[] args) {
        SpringApplication.run(McpApplication.class, args);
    }
    @Bean
    public ToolCallbackProvider weatherTools(HuochepiaoQueryService huochepiaoQueryService) {
        return MethodToolCallbackProvider.builder().toolObjects(huochepiaoQueryService).build();
    }
}

After building the project, the author runs the server and uses the @modelcontextprotocol/inspector CLI tool to verify that the MCP endpoint (e.g., http://192.168.4.3:8080/sse) is reachable and that the two tools appear in the inspector UI.

With the MCP server running, the FastGPT workflow is updated:

Backup the existing workflow configuration.

Create a new “MCP Tool Set” in FastGPT and paste the server address.

Replace the original HTTP node that queried train tickets with a “MCP Tool” node that calls query_train_tickets_list.

Publish the workflow and test it by asking a natural‑language question such as “帮我查询上海到北京明天的火车票”。 The AI calls the MCP tool, receives the cleaned JSON, and returns a correct answer.

Screenshots throughout the article illustrate the inspector UI, the FastGPT tool‑set configuration, and the final AI response, confirming that the integration works as intended.

In the concluding section, the author summarises that the Spring AI MCP server, combined with FastGPT, enables a conversational train‑ticket assistant that understands user intent, avoids hallucination through data cleaning, and can be extended to other business domains.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaMCPSpring AIAI chatbotFastGPTHTTP SSE
Ubiquitous Tech
Written by

Ubiquitous Tech

A ubiquitous public account for pirate enthusiasts, regularly sharing curated experiences, tech learning, and growth insights. Currently publishing articles on AI RAG customer service, AI MCP technology, and open-source design. Personal free Knowledge Planet: Awakening New World Programmer.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.