Stop Using GPT Just to Write Code—Turn Your Spring Boot Service into an AI‑Callable Tool

Java developers should move beyond using GPT for code generation and instead expose existing Spring Boot services as secure, auditable AI tools, covering permission checks, data desensitization, tool descriptions, system prompts, and comprehensive logging to safely integrate GPT into business workflows.

LuTiao Programming
LuTiao Programming
LuTiao Programming
Stop Using GPT Just to Write Code—Turn Your Spring Boot Service into an AI‑Callable Tool

Why "GPT write Java code" is no longer the focus

AI can do more than generate Controllers, Services, DTOs or tests. The next step is to let GPT invoke existing Java business capabilities as tools.

Java backend opportunity: expose business capabilities as AI‑callable tools

Traditional Java backends expose APIs to front‑ends, mini‑programs, admin panels or third‑party systems. AI agents become a new caller that decides, based on user intent, whether to invoke a tool. Therefore services must wrap existing capabilities into AI‑understandable tools (e.g., order lookup, logistics status, membership level, coupon validity, ticket creation).

Safety, controllability and auditability are essential. Spring AI 2.0 provides a composable tool‑calling architecture with MCP support and annotations @McpTool, @McpResource, @McpPrompt to expose Spring‑managed beans as AI tools.

If GPT can safely call Java services for orders, users, inventory or tickets, how should a Java backend be designed?

Designing an order‑query tool

Assume an existing Spring Boot e‑commerce service:

@Service
@RequiredArgsConstructor
public class OrderQueryService {
    private final OrderRepository orderRepository;
    private final LogisticsClient logisticsClient;

    public OrderDetailResponse getOrderDetail(Long orderId) {
        Order order = orderRepository.findById(orderId)
            .orElseThrow(() -> new BusinessException("订单不存在"));
        LogisticsInfo logisticsInfo = logisticsClient.query(order.getTrackingNo());
        return OrderDetailResponse.from(order, logisticsInfo);
    }
}

Wrap it as an AI‑callable tool:

@Component
@RequiredArgsConstructor
public class OrderAiTools {
    private final OrderQueryService orderQueryService;

    @McpTool(name = "get_order_detail", description = "根据订单ID查询订单状态、支付状态、发货状态和物流信息")
    public OrderDetailResponse getOrderDetail(Long orderId) {
        return orderQueryService.getOrderDetail(orderId);
    }
}

Write explicit tool descriptions for the model

@McpTool(
    name = "get_order_detail",
    description = """
    根据订单ID查询订单详情。
    适用于用户询问订单状态、发货状态、物流进度、支付状态时调用。
    该工具只用于查询,不会修改订单。
    返回内容包括订单状态、支付状态、发货状态、物流状态和预计送达时间。
    不要用该工具处理退款、取消订单、修改地址等操作。
    """
)
public OrderDetailResponse getOrderDetail(Long orderId) {
    return orderQueryService.getOrderDetail(orderId);
}

Enforce permissions in code

Tools must verify the current user and ensure the order belongs to that user:

@Component
@RequiredArgsConstructor
public class OrderAiTools {
    private final OrderQueryService orderQueryService;
    private final CurrentUserService currentUserService;

    @McpTool(name = "get_my_order_detail", description = "查询当前登录用户自己的订单详情,只允许查询本人订单")
    public OrderDetailResponse getMyOrderDetail(Long orderId) {
        Long currentUserId = currentUserService.getCurrentUserId();
        return orderQueryService.getOrderDetailForUser(currentUserId, orderId);
    }
}

Service‑level validation:

public OrderDetailResponse getOrderDetailForUser(Long userId, Long orderId) {
    Order order = orderRepository.findById(orderId)
        .orElseThrow(() -> new BusinessException("订单不存在"));
    if (!order.getUserId().equals(userId)) {
        throw new BusinessException("无权查看该订单");
    }
    LogisticsInfo logisticsInfo = logisticsClient.query(order.getTrackingNo());
    return OrderDetailResponse.from(order, logisticsInfo);
}

System prompt to bound GPT behavior

你是一个电商订单客服助手。
你可以帮助用户查询自己的订单状态、支付状态、发货状态和物流进度。
当用户询问订单问题时,如果需要真实订单信息,请调用 get_my_order_detail 工具。
你必须遵守以下规则:
1. 只能查询当前登录用户自己的订单。
2. 不要编造订单状态。
3. 如工具返回订单不存在或无权限,请礼貌说明无法查询。
4. 对于退款、取消订单、修改地址等请求,只能说明需要转人工或创建工单,不能直接执行。
5. 不要输出用户手机号、完整地址、支付流水号等敏感信息。
6. 如信息不足,请要求用户补充订单ID。
7. 回复要简短、清楚,适合客服场景。

Return desensitized DTOs

Define a lightweight response that excludes private fields:

public record AiOrderDetailResponse(
    Long orderId,
    String orderStatus,
    String paymentStatus,
    String deliveryStatus,
    String logisticsStatus,
    String estimatedArrivalTime,
    Boolean delayed
) {}

public AiOrderDetailResponse toAiResponse(Order order, LogisticsInfo logisticsInfo) {
    return new AiOrderDetailResponse(
        order.getId(),
        order.getStatus().name(),
        order.getPaymentStatus().name(),
        order.getDeliveryStatus().name(),
        logisticsInfo.getStatusText(),
        logisticsInfo.getEstimatedArrivalTime(),
        logisticsInfo.isDelayed()
    );
}

Audit logging of tool calls

Record each GPT‑initiated tool call with user, tool name, arguments, result, timestamp and conversation ID.

@Entity
@Table(name = "ai_tool_call_log")
@Getter
@Setter
public class AiToolCallLog {
    @Id
    private UUID id;
    private String conversationId;
    private Long userId;
    private String toolName;
    private String argumentsJson;
    private Boolean success;
    private String errorMessage;
    private Instant createdAt;
}
@Service
@RequiredArgsConstructor
public class AiToolAuditService {
    private final AiToolCallLogRepository repository;

    public void recordSuccess(String conversationId, Long userId, String toolName, String argumentsJson) {
        AiToolCallLog log = new AiToolCallLog();
        log.setId(UUID.randomUUID());
        log.setConversationId(conversationId);
        log.setUserId(userId);
        log.setToolName(toolName);
        log.setArgumentsJson(argumentsJson);
        log.setSuccess(true);
        log.setCreatedAt(Instant.now());
        repository.save(log);
    }
}

Never let GPT execute high‑risk actions directly

Operations such as canceling orders, issuing refunds, changing addresses or deleting data must be mediated through low‑risk tools that create human‑review tasks.

@McpTool(
    name = "create_refund_review_task",
    description = "为当前用户的订单创建退款审核工单。该工具不会直接退款,只会创建人工审核任务。适用于用户要求退款、取消订单、售后处理等场景。"
)
public ReviewTaskResponse createRefundReviewTask(CreateRefundReviewRequest request) {
    return reviewTaskService.createRefundReviewTask(request);
}

Workflow example:

用户提出诉求 → GPT 查询订单 → GPT 判断可能需要售后 → Java 创建审核工单 → 人工客服确认 → 系统执行退款或拒绝

Minimal viable implementation

Select a low‑risk query capability (e.g., order lookup).

Wrap the existing Service with Spring AI / MCP annotations to expose it as a tool.

Implement permission checks that bind the current user to the data.

Return a desensitized DTO tailored for AI consumption.

Log every tool invocation for auditability.

Completing these steps yields a backend that can be safely called by GPT, providing real business value while maintaining security, data privacy and traceability.

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.

Spring BootsecurityGPTAudit LoggingJava BackendAI Tool Calling
LuTiao Programming
Written by

LuTiao Programming

LuTiao Programming is a friendly community offering free programming lessons. We inspire learners to explore new ideas and technologies and quickly acquire job-ready skills.

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.