mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 01:59:20 +08:00
feat: 新增mcp server
This commit is contained in:
+9
-4
@@ -17,6 +17,7 @@ import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.access.AccessDeniedHandler;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
import top.xyquan.ecomdmbbackend.common.filter.JwtAuthenticationFilter;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.security.AgentMcpAuthenticationFilter;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.api.filter.ApiKeyAuthenticationFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
@@ -30,11 +31,14 @@ public class SecurityConfig {
|
||||
|
||||
private final JwtAuthenticationFilter jwtAuthenticationFilter;
|
||||
private final ApiKeyAuthenticationFilter apiKeyAuthenticationFilter;
|
||||
private final AgentMcpAuthenticationFilter agentMcpAuthenticationFilter;
|
||||
|
||||
public SecurityConfig(JwtAuthenticationFilter jwtAuthenticationFilter,
|
||||
ApiKeyAuthenticationFilter apiKeyAuthenticationFilter) {
|
||||
ApiKeyAuthenticationFilter apiKeyAuthenticationFilter,
|
||||
AgentMcpAuthenticationFilter agentMcpAuthenticationFilter) {
|
||||
this.jwtAuthenticationFilter = jwtAuthenticationFilter;
|
||||
this.apiKeyAuthenticationFilter = apiKeyAuthenticationFilter;
|
||||
this.agentMcpAuthenticationFilter = agentMcpAuthenticationFilter;
|
||||
}
|
||||
|
||||
@Bean
|
||||
@@ -62,10 +66,11 @@ public class SecurityConfig {
|
||||
.exceptionHandling(exceptions -> exceptions
|
||||
.authenticationEntryPoint(new CustomAuthenticationEntryPoint())
|
||||
.accessDeniedHandler(committedSafeAccessDeniedHandler()))
|
||||
// 两个自定义 Filter 均锚定到 UsernamePasswordAuthenticationFilter;
|
||||
// 后注册的执行更靠前,故先注册 JWT、再注册 ApiKey,保证 /api/open/** 先走 ApiKey
|
||||
// 自定义 Filter 均锚定 UsernamePasswordAuthenticationFilter;后注册的执行更靠前
|
||||
// 顺序意图:/mcp 先 Agent,/api/open 先 ApiKey,其余走 JWT
|
||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.addFilterBefore(apiKeyAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
.addFilterBefore(apiKeyAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.addFilterBefore(agentMcpAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
|
||||
return http.build();
|
||||
}
|
||||
|
||||
+2
@@ -33,6 +33,8 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
return false;
|
||||
}
|
||||
return uri.startsWith("/api/open/")
|
||||
|| uri.equals("/mcp")
|
||||
|| uri.startsWith("/mcp/")
|
||||
|| uri.startsWith("/api/channel/pdd/auth/callback")
|
||||
|| uri.startsWith("/channel/pdd/auth/callback");
|
||||
}
|
||||
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.bi;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.bi.model.BiKpiSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.bi.model.BiProductOverviewSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.bi.model.BiRankItemSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.bi.model.BiShopOverviewSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.bi.model.BiWorkbenchFinanceSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.productoverview.model.vo.ProductOverviewVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.model.vo.ShopOverviewStatisticsVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchFinanceSliceVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchKpiItemVO;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* BI 胖 VO → Agent 瘦视图(防腐映射,不承载用例编排)。
|
||||
*/
|
||||
public final class BiMcpSlimMapper {
|
||||
|
||||
private BiMcpSlimMapper() {
|
||||
}
|
||||
|
||||
public static BiWorkbenchFinanceSlimVO toFinanceSlim(WorkbenchFinanceSliceVO full,
|
||||
String startDate,
|
||||
String endDate,
|
||||
Long shopId,
|
||||
String platformCode) {
|
||||
List<BiKpiSlimVO> kpis = full == null || full.getFinance() == null || full.getFinance().getKpis() == null
|
||||
? Collections.emptyList()
|
||||
: full.getFinance().getKpis().stream().map(BiMcpSlimMapper::toKpi).collect(Collectors.toList());
|
||||
return BiWorkbenchFinanceSlimVO.builder()
|
||||
.startDate(startDate)
|
||||
.endDate(endDate)
|
||||
.shopId(shopId)
|
||||
.platformCode(platformCode)
|
||||
.kpis(kpis)
|
||||
.build();
|
||||
}
|
||||
|
||||
public static BiShopOverviewSlimVO toShopSlim(ShopOverviewStatisticsVO full) {
|
||||
if (full == null) {
|
||||
return BiShopOverviewSlimVO.builder().build();
|
||||
}
|
||||
List<BiRankItemSlimVO> top10 = full.getProductSalesTop10() == null
|
||||
? Collections.emptyList()
|
||||
: full.getProductSalesTop10().stream()
|
||||
.map(i -> BiRankItemSlimVO.builder()
|
||||
.id(i.getProductId())
|
||||
.name(i.getProductName())
|
||||
.code(i.getProductCode())
|
||||
.orderCount(i.getOrderCount())
|
||||
.salesAmount(i.getSalesAmount())
|
||||
.build())
|
||||
.collect(Collectors.toList());
|
||||
return BiShopOverviewSlimVO.builder()
|
||||
.shopId(full.getShopId())
|
||||
.shopName(full.getShopName())
|
||||
.totalSalesAmount(full.getTotalSalesAmount())
|
||||
.totalOrderCount(full.getTotalOrderCount())
|
||||
.averageOrderValue(full.getAverageOrderValue())
|
||||
.totalPromotionFee(full.getTotalPromotionFee())
|
||||
.averageFeeRatio(full.getAverageFeeRatio())
|
||||
.totalNetProfitAfterTax(full.getTotalNetProfitAfterTax())
|
||||
.totalROI(full.getTotalROI())
|
||||
.monthOverMonthGrowth(full.getMonthOverMonthGrowth())
|
||||
.orderCountAchievementRate(full.getOrderCountAchievementRate())
|
||||
.salesAmountAchievementRate(full.getSalesAmountAchievementRate())
|
||||
.refundAmount(full.getRefundAmount())
|
||||
.productSalesTop10(top10)
|
||||
.build();
|
||||
}
|
||||
|
||||
public static BiProductOverviewSlimVO toProductSlim(ProductOverviewVO full) {
|
||||
if (full == null) {
|
||||
return BiProductOverviewSlimVO.builder().build();
|
||||
}
|
||||
List<BiRankItemSlimVO> top10 = full.getSpecSalesTop10() == null
|
||||
? Collections.emptyList()
|
||||
: full.getSpecSalesTop10().stream()
|
||||
.map(i -> BiRankItemSlimVO.builder()
|
||||
.id(i.getSkuId())
|
||||
.name(i.getSkuName())
|
||||
.code(i.getSkuCode())
|
||||
.orderCount(i.getOrderCount())
|
||||
.salesAmount(i.getSalesAmount())
|
||||
.build())
|
||||
.collect(Collectors.toList());
|
||||
return BiProductOverviewSlimVO.builder()
|
||||
.productId(full.getProductId())
|
||||
.productName(full.getProductName())
|
||||
.totalSalesAmount(full.getTotalSalesAmount())
|
||||
.totalOrderCount(full.getTotalOrderCount())
|
||||
.averageFeeRatio(full.getAverageFeeRatio())
|
||||
.totalNetProfitAfterTax(full.getTotalNetProfitAfterTax())
|
||||
.totalROI(full.getTotalROI())
|
||||
.monthOverMonthGrowth(full.getMonthOverMonthGrowth())
|
||||
.orderCountAchievementRate(full.getOrderCountAchievementRate())
|
||||
.salesAmountAchievementRate(full.getSalesAmountAchievementRate())
|
||||
.specSalesTop10(top10)
|
||||
.build();
|
||||
}
|
||||
|
||||
private static BiKpiSlimVO toKpi(WorkbenchKpiItemVO k) {
|
||||
return BiKpiSlimVO.builder()
|
||||
.label(k.getLabel())
|
||||
.value(k.getValue())
|
||||
.unit(k.getUnit())
|
||||
.changePct(k.getChangePct())
|
||||
.yoyChangePct(k.getYoyChangePct())
|
||||
.amountYuan(k.getAmountYuan())
|
||||
.sub(k.getSub())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.bi.model;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/** 工作台 KPI 瘦项。 */
|
||||
@Data
|
||||
@Builder
|
||||
public class BiKpiSlimVO {
|
||||
private String label;
|
||||
private String value;
|
||||
private String unit;
|
||||
private BigDecimal changePct;
|
||||
private BigDecimal yoyChangePct;
|
||||
private BigDecimal amountYuan;
|
||||
private String sub;
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.bi.model;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
|
||||
/** 商品概览瘦视图(给 Agent)。 */
|
||||
@Data
|
||||
@Builder
|
||||
public class BiProductOverviewSlimVO {
|
||||
private Long productId;
|
||||
private String productName;
|
||||
private BigDecimal totalSalesAmount;
|
||||
private Integer totalOrderCount;
|
||||
private BigDecimal averageFeeRatio;
|
||||
private BigDecimal totalNetProfitAfterTax;
|
||||
private BigDecimal totalROI;
|
||||
private BigDecimal monthOverMonthGrowth;
|
||||
private BigDecimal orderCountAchievementRate;
|
||||
private BigDecimal salesAmountAchievementRate;
|
||||
private List<BiRankItemSlimVO> specSalesTop10;
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.bi.model;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/** 排行瘦项(商品或规格)。 */
|
||||
@Data
|
||||
@Builder
|
||||
public class BiRankItemSlimVO {
|
||||
private Long id;
|
||||
private String name;
|
||||
private String code;
|
||||
private Integer orderCount;
|
||||
private BigDecimal salesAmount;
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.bi.model;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
|
||||
/** 店铺概览瘦视图(给 Agent)。 */
|
||||
@Data
|
||||
@Builder
|
||||
public class BiShopOverviewSlimVO {
|
||||
private Long shopId;
|
||||
private String shopName;
|
||||
private BigDecimal totalSalesAmount;
|
||||
private Integer totalOrderCount;
|
||||
private BigDecimal averageOrderValue;
|
||||
private BigDecimal totalPromotionFee;
|
||||
private BigDecimal averageFeeRatio;
|
||||
private BigDecimal totalNetProfitAfterTax;
|
||||
private BigDecimal totalROI;
|
||||
private BigDecimal monthOverMonthGrowth;
|
||||
private BigDecimal orderCountAchievementRate;
|
||||
private BigDecimal salesAmountAchievementRate;
|
||||
private BigDecimal refundAmount;
|
||||
private List<BiRankItemSlimVO> productSalesTop10;
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.bi.model;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
|
||||
/** 工作台经营概览瘦视图(给 Agent)。 */
|
||||
@Data
|
||||
@Builder
|
||||
public class BiWorkbenchFinanceSlimVO {
|
||||
private String startDate;
|
||||
private String endDate;
|
||||
private Long shopId;
|
||||
private String platformCode;
|
||||
private List<BiKpiSlimVO> kpis;
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.common;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* MCP 入参日期解析(yyyy-MM-dd),与具体业务域无关。
|
||||
*/
|
||||
public final class McpDateSupport {
|
||||
|
||||
private McpDateSupport() {
|
||||
}
|
||||
|
||||
public static LocalDate parseDate(String raw, String fieldName) {
|
||||
if (raw == null || raw.isBlank()) {
|
||||
throw new BusinessException(fieldName + " 不能为空");
|
||||
}
|
||||
try {
|
||||
return LocalDate.parse(raw.trim());
|
||||
} catch (DateTimeParseException e) {
|
||||
throw new BusinessException(fieldName + " 格式须为 yyyy-MM-dd");
|
||||
}
|
||||
}
|
||||
|
||||
public static List<LocalDate> toDateRange(String startDate, String endDate) {
|
||||
LocalDate start = parseDate(startDate, "startDate");
|
||||
LocalDate end = parseDate(endDate, "endDate");
|
||||
if (end.isBefore(start)) {
|
||||
throw new BusinessException("endDate 不能早于 startDate");
|
||||
}
|
||||
return List.of(start, end);
|
||||
}
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.application;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.bi.BiMcpSlimMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.bi.model.BiProductOverviewSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.bi.model.BiShopOverviewSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.bi.model.BiWorkbenchFinanceSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.common.McpDateSupport;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.productoverview.model.dto.ProductOverviewQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.productoverview.service.BiProductOverviewService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.model.dto.ShopOverviewQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.service.BiShopOverviewService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.dto.WorkbenchQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.service.BiWorkbenchService;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* BI MCP 用例编排:组装查询、调用 BI Service、裁剪为瘦视图。
|
||||
*/
|
||||
@Service
|
||||
public class BiMcpFacade {
|
||||
|
||||
private final BiWorkbenchService biWorkbenchService;
|
||||
private final BiShopOverviewService biShopOverviewService;
|
||||
private final BiProductOverviewService biProductOverviewService;
|
||||
|
||||
public BiMcpFacade(BiWorkbenchService biWorkbenchService,
|
||||
BiShopOverviewService biShopOverviewService,
|
||||
BiProductOverviewService biProductOverviewService) {
|
||||
this.biWorkbenchService = biWorkbenchService;
|
||||
this.biShopOverviewService = biShopOverviewService;
|
||||
this.biProductOverviewService = biProductOverviewService;
|
||||
}
|
||||
|
||||
public BiWorkbenchFinanceSlimVO workbenchFinance(String startDate,
|
||||
String endDate,
|
||||
String platformCode,
|
||||
Long shopId,
|
||||
BigDecimal taxRate) {
|
||||
List<LocalDate> range = McpDateSupport.toDateRange(startDate, endDate);
|
||||
WorkbenchQueryDTO query = new WorkbenchQueryDTO();
|
||||
query.setDateRange(range);
|
||||
query.setPlatformCode(blankToNull(platformCode));
|
||||
query.setShopId(shopId);
|
||||
if (taxRate != null) {
|
||||
query.setTaxRate(taxRate);
|
||||
}
|
||||
return BiMcpSlimMapper.toFinanceSlim(
|
||||
biWorkbenchService.financeSlice(query),
|
||||
range.get(0).toString(),
|
||||
range.get(range.size() - 1).toString(),
|
||||
shopId,
|
||||
query.getPlatformCode());
|
||||
}
|
||||
|
||||
public BiShopOverviewSlimVO shopOverview(Long shopId,
|
||||
String startDate,
|
||||
String endDate,
|
||||
BigDecimal taxRate) {
|
||||
ShopOverviewQueryDTO query = new ShopOverviewQueryDTO();
|
||||
query.setShopId(shopId);
|
||||
query.setDateRange(McpDateSupport.toDateRange(startDate, endDate));
|
||||
if (taxRate != null) {
|
||||
query.setTaxRate(taxRate);
|
||||
}
|
||||
return BiMcpSlimMapper.toShopSlim(biShopOverviewService.getShopOverview(query));
|
||||
}
|
||||
|
||||
public BiProductOverviewSlimVO productOverview(Long productId,
|
||||
String startDate,
|
||||
String endDate,
|
||||
Long shopId,
|
||||
BigDecimal taxRate) {
|
||||
ProductOverviewQueryDTO query = new ProductOverviewQueryDTO();
|
||||
query.setProductId(productId);
|
||||
List<LocalDate> range = McpDateSupport.toDateRange(startDate, endDate);
|
||||
query.setStartDate(range.get(0));
|
||||
query.setEndDate(range.get(range.size() - 1));
|
||||
query.setShopId(shopId);
|
||||
if (taxRate != null) {
|
||||
query.setTaxRate(taxRate);
|
||||
}
|
||||
return BiMcpSlimMapper.toProductSlim(biProductOverviewService.getProductOverview(query));
|
||||
}
|
||||
|
||||
private static String blankToNull(String value) {
|
||||
return value == null || value.isBlank() ? null : value.trim();
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* Agent 访问 MCP 的独立凭证配置(与 JWT / Open API Key 分离)。
|
||||
*/
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "ecom.agent.mcp")
|
||||
public class AgentMcpProperties {
|
||||
|
||||
/**
|
||||
* Bearer token;为空则拒绝所有 /mcp 请求。
|
||||
*/
|
||||
private String bearerToken = "";
|
||||
|
||||
/**
|
||||
* Agent 绑定的公司 ID(BI 等读模型按租户隔离);为空则业务 tool 会失败。
|
||||
*/
|
||||
private Long companyId;
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.security;
|
||||
|
||||
import lombok.Getter;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
|
||||
/**
|
||||
* MCP Agent 鉴权结果,写入 SecurityContext 供 /mcp 放行。
|
||||
*/
|
||||
@Getter
|
||||
public class AgentMcpAuthentication implements Authentication {
|
||||
|
||||
private final AgentMcpPrincipal principal;
|
||||
private boolean authenticated = true;
|
||||
|
||||
public AgentMcpAuthentication(AgentMcpPrincipal principal) {
|
||||
this.principal = principal;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<? extends GrantedAuthority> getAuthorities() {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getCredentials() {
|
||||
return "agent-mcp-token";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getDetails() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getPrincipal() {
|
||||
return principal;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAuthenticated() {
|
||||
return authenticated;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
|
||||
this.authenticated = isAuthenticated;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return principal.clientName();
|
||||
}
|
||||
|
||||
public Long getCompanyId() {
|
||||
return principal.companyId();
|
||||
}
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.security;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.config.AgentMcpProperties;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
|
||||
/**
|
||||
* Agent MCP 鉴权:仅处理 /mcp,校验独立 Bearer,与 JWT / Open API Key 分离。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class AgentMcpAuthenticationFilter extends OncePerRequestFilter {
|
||||
|
||||
private static final String MCP_PATH = "/mcp";
|
||||
|
||||
private final AgentMcpProperties properties;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public AgentMcpAuthenticationFilter(AgentMcpProperties properties, ObjectMapper objectMapper) {
|
||||
this.properties = properties;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean shouldNotFilter(@NonNull HttpServletRequest request) {
|
||||
String uri = request.getRequestURI();
|
||||
if (uri == null) {
|
||||
return true;
|
||||
}
|
||||
return !(uri.equals(MCP_PATH) || uri.startsWith(MCP_PATH + "/"));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(
|
||||
@NonNull HttpServletRequest request,
|
||||
@NonNull HttpServletResponse response,
|
||||
@NonNull FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
try {
|
||||
String configured = properties.getBearerToken();
|
||||
if (!StringUtils.hasText(configured)) {
|
||||
writeUnauthorized(response, "MCP 凭证未配置");
|
||||
return;
|
||||
}
|
||||
|
||||
String provided = extractBearer(request);
|
||||
if (!StringUtils.hasText(provided) || !tokenEquals(configured, provided)) {
|
||||
writeUnauthorized(response, "MCP 凭证无效或缺失");
|
||||
return;
|
||||
}
|
||||
|
||||
AgentMcpPrincipal principal = new AgentMcpPrincipal("agent-mcp", properties.getCompanyId());
|
||||
SecurityContextHolder.getContext().setAuthentication(new AgentMcpAuthentication(principal));
|
||||
filterChain.doFilter(request, response);
|
||||
} finally {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
}
|
||||
|
||||
private String extractBearer(HttpServletRequest request) {
|
||||
String authorization = request.getHeader("Authorization");
|
||||
if (StringUtils.hasText(authorization) && authorization.startsWith("Bearer ")) {
|
||||
return authorization.substring(7).trim();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 常量时间比较,降低侧信道风险。 */
|
||||
private static boolean tokenEquals(String expected, String actual) {
|
||||
byte[] a = expected.getBytes(StandardCharsets.UTF_8);
|
||||
byte[] b = actual.getBytes(StandardCharsets.UTF_8);
|
||||
return MessageDigest.isEqual(a, b);
|
||||
}
|
||||
|
||||
private void writeUnauthorized(HttpServletResponse response, String message) throws IOException {
|
||||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
response.setContentType("application/json;charset=UTF-8");
|
||||
response.getWriter().write(objectMapper.writeValueAsString(ApiResponse.fail(40101, message)));
|
||||
}
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.security;
|
||||
|
||||
/**
|
||||
* MCP Agent 认证主体(m2m);companyId 绑定租户数据范围。
|
||||
*/
|
||||
public record AgentMcpPrincipal(String clientName, Long companyId) {
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.tools;
|
||||
|
||||
import org.springaicommunity.mcp.annotation.McpTool;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* MCP 连通性探测 Tool;无业务编排。
|
||||
*/
|
||||
@Component
|
||||
public class AgentMcpHealthTools {
|
||||
|
||||
@McpTool(name = "mcp_ping", description = "探测 MCP 服务是否可用,返回固定 ok。")
|
||||
public Map<String, String> ping() {
|
||||
return Map.of("status", "ok", "server", "ecom-dmb-mcp");
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.tools;
|
||||
|
||||
import org.springaicommunity.mcp.annotation.McpTool;
|
||||
import org.springaicommunity.mcp.annotation.McpToolParam;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.bi.model.BiProductOverviewSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.bi.model.BiShopOverviewSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.bi.model.BiWorkbenchFinanceSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.application.BiMcpFacade;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* BI MCP Tool 入口:仅暴露 @McpTool,用例交给 {@link BiMcpFacade}。
|
||||
*/
|
||||
@Component
|
||||
public class BiMcpTools {
|
||||
|
||||
private final BiMcpFacade biMcpFacade;
|
||||
|
||||
public BiMcpTools(BiMcpFacade biMcpFacade) {
|
||||
this.biMcpFacade = biMcpFacade;
|
||||
}
|
||||
|
||||
@McpTool(
|
||||
name = "bi_workbench_finance",
|
||||
description = "查询工作台经营概览 KPI(销售额、单量、净利、费比等),按日期范围;可选平台/店铺筛选。租户取自 MCP 绑定的 companyId。")
|
||||
public BiWorkbenchFinanceSlimVO workbenchFinance(
|
||||
@McpToolParam(description = "开始日期 yyyy-MM-dd", required = true) String startDate,
|
||||
@McpToolParam(description = "结束日期 yyyy-MM-dd", required = true) String endDate,
|
||||
@McpToolParam(description = "平台编码,可选", required = false) String platformCode,
|
||||
@McpToolParam(description = "店铺 ID,可选", required = false) Long shopId,
|
||||
@McpToolParam(description = "税率,默认 0.04", required = false) BigDecimal taxRate) {
|
||||
return biMcpFacade.workbenchFinance(startDate, endDate, platformCode, shopId, taxRate);
|
||||
}
|
||||
|
||||
@McpTool(
|
||||
name = "bi_shop_overview",
|
||||
description = "查询单店经营概览摘要:销售额、单量、净利、ROI、目标达成率,以及商品销量 Top10。")
|
||||
public BiShopOverviewSlimVO shopOverview(
|
||||
@McpToolParam(description = "店铺 ID", required = true) Long shopId,
|
||||
@McpToolParam(description = "开始日期 yyyy-MM-dd", required = true) String startDate,
|
||||
@McpToolParam(description = "结束日期 yyyy-MM-dd", required = true) String endDate,
|
||||
@McpToolParam(description = "税率,默认 0.04", required = false) BigDecimal taxRate) {
|
||||
return biMcpFacade.shopOverview(shopId, startDate, endDate, taxRate);
|
||||
}
|
||||
|
||||
@McpTool(
|
||||
name = "bi_product_overview",
|
||||
description = "查询单商品经营概览摘要:销售额、单量、净利、ROI、目标达成率,以及规格销量 Top10;可选限定店铺。")
|
||||
public BiProductOverviewSlimVO productOverview(
|
||||
@McpToolParam(description = "商品 ID", required = true) Long productId,
|
||||
@McpToolParam(description = "开始日期 yyyy-MM-dd", required = true) String startDate,
|
||||
@McpToolParam(description = "结束日期 yyyy-MM-dd", required = true) String endDate,
|
||||
@McpToolParam(description = "店铺 ID,可选", required = false) Long shopId,
|
||||
@McpToolParam(description = "税率,默认 0.04", required = false) BigDecimal taxRate) {
|
||||
return biMcpFacade.productOverview(productId, startDate, endDate, shopId, taxRate);
|
||||
}
|
||||
}
|
||||
+14
@@ -5,6 +5,7 @@ import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.security.AgentMcpAuthentication;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.api.context.OpenApiContextHolder;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.api.security.OpenApiAuthentication;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.api.security.OpenApiPrincipal;
|
||||
@@ -57,6 +58,19 @@ public class CurrentUserContext {
|
||||
.build();
|
||||
}
|
||||
|
||||
if (authentication instanceof AgentMcpAuthentication agentMcpAuthentication) {
|
||||
Long companyId = agentMcpAuthentication.getCompanyId();
|
||||
if (companyId == null) {
|
||||
throw new BusinessException("MCP 未绑定公司,请配置 ecom.agent.mcp.company-id");
|
||||
}
|
||||
return TokenPayload.builder()
|
||||
.userId("0")
|
||||
.companyId(companyId)
|
||||
.isSuper(false)
|
||||
.companyRole("owner")
|
||||
.build();
|
||||
}
|
||||
|
||||
if (authentication.getCredentials() == null) {
|
||||
throw new BusinessException("用户未登录 - Token信息为空");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user