mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-23 23:19:19 +08:00
feat: 新增mcp server
This commit is contained in:
@@ -2,7 +2,7 @@
|
||||
|
||||
> 文档目的:换机后续做时,先读本文再动手。
|
||||
> 日期:2026-08-17
|
||||
> 现状:后端 `Spring Boot 3.5.16` + MyBatis-Plus `3.5.8`;尚未引入 Spring AI / MCP。
|
||||
> 现状:后端 `Spring Boot 3.5.16` + MyBatis-Plus `3.5.8` + Spring AI MCP `1.1.8`(STREAMABLE `/mcp`);已有 BI 只读 tool。
|
||||
|
||||
---
|
||||
|
||||
@@ -50,16 +50,20 @@
|
||||
|
||||
- 依赖方向:`org.springframework.ai:spring-ai-starter-mcp-server-webmvc`
|
||||
- 协议:优先 **STREAMABLE** 或 **STATELESS**;**不要用已弃用的 SSE**
|
||||
- 端点示意:`/api/mcp`(具体以 Spring AI 配置为准)
|
||||
- 端点:`/mcp`(与 `/api/...` 业务接口前缀分开)
|
||||
- 鉴权:Agent **独立凭证**(Bearer / m2m),与浏览器 JWT、扩展 Open API Key 分开;Security 单独放行 MCP 路径
|
||||
|
||||
### 3.2 模块目录(拟定,未建)
|
||||
### 3.2 模块目录
|
||||
|
||||
```text
|
||||
modules/agent/mcp/
|
||||
config/ # MCP 与 Security 放行
|
||||
tools/ # @McpTool(product / order / shop / adfee…)
|
||||
support/ # 瘦 VO、分页裁剪、错误文案
|
||||
config/ # MCP 凭证与租户绑定
|
||||
security/ # Agent Bearer 鉴权
|
||||
tools/ # 薄 @McpTool 入口(非 REST /api)
|
||||
application/ # 用例编排 Facade
|
||||
adapter/
|
||||
common/ # 通用入参适配(日期等)
|
||||
bi/ # BI 瘦 VO 与映射(按业务域扩展)
|
||||
```
|
||||
|
||||
### 3.3 Python Agent(另仓/另目录,未建)
|
||||
@@ -147,10 +151,10 @@ Boot 4 = Spring Framework 7 + Jakarta EE 11 + **Jackson 3** + Security 7 等,
|
||||
## 6. 换机后续待办(建议顺序)
|
||||
|
||||
1. [x] Boot `3.2.3` → `3.5.16`,MyBatis-Plus → `3.5.8`(暂未上 3.5.9+,避免 IService 包路径迁移),编译通过
|
||||
2. [ ] 本地回归核心链路
|
||||
3. [ ] 引入 Spring AI 1.x BOM + `spring-ai-starter-mcp-server-webmvc`,配置 STREAMABLE/STATELESS
|
||||
4. [ ] Security:MCP 路径 + Agent 鉴权
|
||||
5. [ ] 落地 2~3 个只读 tool(如商品搜索、订单摘要)打通 LangGraph `get_tools()`
|
||||
2. [x] 本地回归核心链路(登录等接口冒烟通过)
|
||||
3. [x] 引入 Spring AI 1.1.8 BOM + `spring-ai-starter-mcp-server-webmvc`,配置 STREAMABLE `/mcp`
|
||||
4. [x] Security:`/mcp` 跳过 JWT + Agent Bearer(`ecom.agent.mcp.bearer-token` / `AGENT_MCP_TOKEN`);含探测 tool `mcp_ping`
|
||||
5. [x] 落地 BI 只读 tool:`bi_workbench_finance` / `bi_shop_overview` / `bi_product_overview`(瘦返回;租户 `ecom.agent.mcp.company-id`)
|
||||
6. [ ] 新建 Python LangGraph 工程,接 MCP HTTP
|
||||
|
||||
---
|
||||
|
||||
@@ -25,6 +25,8 @@
|
||||
<httpclient.version>4.5.14</httpclient.version>
|
||||
<!-- 拼多多 POP SDK(项目内 libs/repo,非 Maven Central) -->
|
||||
<pop-sdk.version>1.25.34</pop-sdk.version>
|
||||
<!-- Spring AI 1.x(Boot 3.5);MCP Server 用,暂不上 2.x/Boot4 -->
|
||||
<spring-ai.version>1.1.8</spring-ai.version>
|
||||
</properties>
|
||||
|
||||
<!-- 本地第三方 jar 仓库(拼多多等未上架中央仓库的 SDK) -->
|
||||
@@ -43,6 +45,13 @@
|
||||
<artifactId>httpclient</artifactId>
|
||||
<version>${httpclient.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.ai</groupId>
|
||||
<artifactId>spring-ai-bom</artifactId>
|
||||
<version>${spring-ai.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
@@ -64,6 +73,11 @@
|
||||
<artifactId>spring-boot-properties-migrator</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<!-- Agent 能力面:MCP Server(WebMVC / STREAMABLE) -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.ai</groupId>
|
||||
<artifactId>spring-ai-starter-mcp-server-webmvc</artifactId>
|
||||
</dependency>
|
||||
<!--MySQL数据库连接器-->
|
||||
<dependency>
|
||||
<groupId>com.mysql</groupId>
|
||||
|
||||
+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信息为空");
|
||||
}
|
||||
|
||||
@@ -43,6 +43,11 @@ ecom:
|
||||
license-key: ""
|
||||
online-revocation-check: false
|
||||
license-server-url: ""
|
||||
agent:
|
||||
mcp:
|
||||
# 仅本地联调;生产用 AGENT_MCP_TOKEN / AGENT_MCP_COMPANY_ID
|
||||
bearer-token: ${AGENT_MCP_TOKEN:dev-agent-mcp-token}
|
||||
company-id: ${AGENT_MCP_COMPANY_ID:1}
|
||||
|
||||
logging:
|
||||
level:
|
||||
|
||||
@@ -54,6 +54,17 @@ spring:
|
||||
# 与全量/增量 listener concurrency 同量级,避免长任务预取过多
|
||||
prefetch: 4
|
||||
default-requeue-rejected: false
|
||||
# Spring AI MCP Server(Agent 能力面;鉴权见 ecom.agent.mcp)
|
||||
ai:
|
||||
mcp:
|
||||
server:
|
||||
name: ecom-dmb-mcp
|
||||
version: 1.0.0
|
||||
protocol: STREAMABLE
|
||||
type: SYNC
|
||||
# 默认 SSE 已弃用;端点与文档约定一致
|
||||
streamable-http:
|
||||
mcp-endpoint: /mcp
|
||||
|
||||
# 订单统计读模型(汇总表已删,待重构前关闭写入与 miss 补算)
|
||||
# BI 日汇聚、License、系统初始化(合并为单一 ecom 根键,避免 DuplicateKeyException)
|
||||
@@ -76,6 +87,13 @@ ecom:
|
||||
admin-real-name: 超级管理员
|
||||
admin-phone: 13800000001
|
||||
admin-password: admin123
|
||||
# Agent → MCP 独立凭证(与浏览器 JWT、开放 API Key 分离)
|
||||
agent:
|
||||
mcp:
|
||||
# 为空则拒绝所有 MCP 请求;生产务必用环境变量覆盖
|
||||
bearer-token: ${AGENT_MCP_TOKEN:}
|
||||
# Agent 数据租户;BI tool 依赖此值
|
||||
company-id: ${AGENT_MCP_COMPANY_ID:}
|
||||
|
||||
# 导入任务 Redis Stream 队列(DB 为真相源,Redis 负责调度)
|
||||
import-task:
|
||||
|
||||
Reference in New Issue
Block a user