@cloudbase/cloudbase-mcp 2.25.2 → 2.25.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -461,15 +461,20 @@ async function prepareAuthEnvironment(params) {
461
461
  if (setupContext.createFreeEnvAttempted) {
462
462
  envSetupActions.push("create_free_env");
463
463
  }
464
+ // Surface the user-facing notice emitted at checkAndCreateFreeEnv entry.
465
+ // Informational only — no confirm required. Prepend to the final message so
466
+ // the user knows an automatic free-env creation was attempted.
467
+ const userNotice = createResult.userNotice?.trim() || "";
464
468
  if (createResult.success && createResult.envId) {
465
469
  await cloudbase_manager_js_1.envManager.setEnvId(createResult.envId);
470
+ const successMessage = `当前已登录,已自动创建并绑定环境: ${createResult.envId}`;
466
471
  return {
467
472
  currentEnvId: createResult.envId,
468
473
  envStatus: "READY",
469
474
  envCandidates: [],
470
475
  envSetupStatus: "AUTO_CREATED",
471
476
  envSetupActions: dedupeActions(envSetupActions),
472
- message: `当前已登录,已自动创建并绑定环境: ${createResult.envId}`,
477
+ message: userNotice ? `${userNotice}\n${successMessage}` : successMessage,
473
478
  nextStep: (0, tool_result_js_1.buildAuthNextStep)("status", {
474
479
  suggestedArgs: { action: "status" },
475
480
  }),
@@ -488,6 +493,9 @@ async function prepareAuthEnvironment(params) {
488
493
  message: "环境创建失败,请稍后重试或手动创建环境。",
489
494
  helpUrl: "https://buy.cloud.tencent.com/lowcode?buyType=tcb&channel=mcp",
490
495
  });
496
+ const failureMessage = userNotice
497
+ ? `${userNotice}\n${createFailure.message}`
498
+ : createFailure.message;
491
499
  return {
492
500
  currentEnvId: null,
493
501
  envStatus: "NONE",
@@ -495,7 +503,7 @@ async function prepareAuthEnvironment(params) {
495
503
  envSetupStatus: "ACTION_REQUIRED",
496
504
  envSetupActions: dedupeActions(envSetupActions),
497
505
  envSetupFailure: createFailure,
498
- message: createFailure.message,
506
+ message: failureMessage,
499
507
  nextStep: (0, tool_result_js_1.buildAuthNextStep)("status", {
500
508
  suggestedArgs: { action: "status" },
501
509
  }),
@@ -817,6 +825,297 @@ function buildEnvQueryErrorMessage(error, action) {
817
825
  function normalizeOptionalToolBoolean(value) {
818
826
  return typeof value === "boolean" ? value : undefined;
819
827
  }
828
+ /**
829
+ * 解析用于询价的 region。与 cloudbase-manager.ts 一致:
830
+ * cloudBaseOptions.region → TCB_REGION → 'ap-shanghai'。
831
+ */
832
+ function resolvePricingRegion(cloudBaseOptions) {
833
+ return ((typeof cloudBaseOptions?.region === "string" && cloudBaseOptions.region) ||
834
+ process.env.TCB_REGION ||
835
+ "ap-shanghai");
836
+ }
837
+ /**
838
+ * 从 describeBaasPackageList 查询某个 packageId 的人类可读套餐名。
839
+ * 失败时返回 undefined,调用方降级为只显示 packageId。
840
+ */
841
+ async function fetchPackageTitle(manager, packageId) {
842
+ try {
843
+ const result = await manager.env.describeBaasPackageList({
844
+ TargetAction: "new",
845
+ Source: "qcloud",
846
+ });
847
+ const packageList = result?.PackageList || [];
848
+ const matched = packageList.find((item) => item?.BillTags === packageId || item?.PackageName === packageId);
849
+ if (matched) {
850
+ return (matched.PackageTitle || matched.PackageName || matched.BillTags);
851
+ }
852
+ return undefined;
853
+ }
854
+ catch (error) {
855
+ (0, logger_js_1.debug)("fetchPackageTitle failed", { packageId, error });
856
+ return undefined;
857
+ }
858
+ }
859
+ /**
860
+ * 查询环境的当前计费/套餐信息(PackageName、PackageId、Region、到期时间、PayMode)。
861
+ * 失败时返回 undefined。
862
+ */
863
+ async function fetchEnvBillingSummary(manager, envId) {
864
+ try {
865
+ // describeBillingInfo 返回 EnvBillingInfoList;从中挑出 envId 对应项
866
+ const billingResult = await manager.env.describeBillingInfo({ EnvId: envId });
867
+ const billingList = billingResult?.EnvBillingInfoList ||
868
+ billingResult?.Response?.EnvBillingInfoList ||
869
+ billingResult?.Data?.EnvBillingInfoList ||
870
+ [];
871
+ const matched = Array.isArray(billingList)
872
+ ? billingList.find((item) => item?.EnvId === envId) ?? billingList[0]
873
+ : undefined;
874
+ if (!matched) {
875
+ return undefined;
876
+ }
877
+ return {
878
+ packageName: matched.PackageName,
879
+ packageId: matched.PackageId,
880
+ region: matched.Region,
881
+ expireTime: matched.ExpireTime,
882
+ payMode: matched.PayMode,
883
+ isAutoRenew: matched.IsAutoRenew,
884
+ };
885
+ }
886
+ catch (error) {
887
+ (0, logger_js_1.debug)("fetchEnvBillingSummary failed", { envId, error });
888
+ return undefined;
889
+ }
890
+ }
891
+ /**
892
+ * 询价新购价格。失败时返回 { error }。
893
+ */
894
+ async function calculateCreatePrice(manager, params) {
895
+ try {
896
+ const priceResult = await manager.env.calculatePackageCreatePrice({
897
+ packageId: params.packageId,
898
+ region: params.region,
899
+ period: params.period,
900
+ });
901
+ return { priceResult };
902
+ }
903
+ catch (error) {
904
+ const message = error instanceof Error ? error.message : String(error);
905
+ (0, logger_js_1.debug)("calculatePackageCreatePrice failed", { params, error });
906
+ return { error: message };
907
+ }
908
+ }
909
+ /**
910
+ * 询价续费价格。失败时返回 { error }。
911
+ */
912
+ async function calculateRenewPrice(manager, envId, period) {
913
+ try {
914
+ const priceResult = await manager.env.calculatePackageRenewPrice({
915
+ envId,
916
+ period,
917
+ });
918
+ return { priceResult };
919
+ }
920
+ catch (error) {
921
+ const message = error instanceof Error ? error.message : String(error);
922
+ (0, logger_js_1.debug)("calculatePackageRenewPrice failed", { envId, period, error });
923
+ return { error: message };
924
+ }
925
+ }
926
+ /**
927
+ * 询价变配价格(含退款)。失败时返回 { error }。
928
+ */
929
+ async function calculateModifyPrice(manager, envId, newPackageId) {
930
+ try {
931
+ const priceResult = await manager.env.calculatePackageModifyPrice({
932
+ envId,
933
+ newPackageId,
934
+ });
935
+ return { priceResult };
936
+ }
937
+ catch (error) {
938
+ const message = error instanceof Error ? error.message : String(error);
939
+ (0, logger_js_1.debug)("calculatePackageModifyPrice failed", { envId, newPackageId, error });
940
+ return { error: message };
941
+ }
942
+ }
943
+ /**
944
+ * 把 PriceResult 格式化为人类可读的价格摘要。
945
+ * 返回 { summary, detail }:summary 是一行短语,detail 是多行明细。
946
+ */
947
+ function formatPriceSection(priceResult) {
948
+ if (!priceResult || typeof priceResult !== "object") {
949
+ return { summary: "询价返回为空", detail: "" };
950
+ }
951
+ const currency = priceResult.Currency === "USD" ? "$" : "¥";
952
+ const realTotalCost = Number(priceResult.RealTotalCost);
953
+ const totalCost = Number(priceResult.TotalCost);
954
+ const unitPrice = Number(priceResult.Price);
955
+ const timeSpan = priceResult.TimeSpan;
956
+ const TimeUnit = priceResult.TimeUnit || "";
957
+ const refund = priceResult.Refund ? Number(priceResult.Refund) : undefined;
958
+ const lines = [];
959
+ let summary = "";
960
+ if (Number.isFinite(realTotalCost) && realTotalCost > 0) {
961
+ summary = `预计实付 ${currency}${realTotalCost}`;
962
+ lines.push(`- 实付总价: ${currency}${realTotalCost}`);
963
+ }
964
+ else if (Number.isFinite(totalCost) && totalCost > 0) {
965
+ summary = `预计费用 ${currency}${totalCost}`;
966
+ lines.push(`- 总价: ${currency}${totalCost}`);
967
+ }
968
+ if (Number.isFinite(totalCost) && totalCost > 0 && totalCost !== realTotalCost) {
969
+ lines.push(`- 原价: ${currency}${totalCost}`);
970
+ }
971
+ if (Number.isFinite(unitPrice) && unitPrice > 0) {
972
+ lines.push(`- 单价: ${currency}${unitPrice}`);
973
+ }
974
+ if (timeSpan !== undefined && TimeUnit) {
975
+ lines.push(`- 时长: ${timeSpan} ${TimeUnit}`);
976
+ }
977
+ if (refund !== undefined && Number.isFinite(refund) && refund > 0) {
978
+ lines.push(`- 退款: ${currency}${refund}(变配降级时退回差价)`);
979
+ if (summary) {
980
+ summary += `,退款 ${currency}${refund}`;
981
+ }
982
+ else {
983
+ summary = `退款 ${currency}${refund}`;
984
+ }
985
+ }
986
+ if (priceResult.Formula && typeof priceResult.Formula === "string") {
987
+ lines.push(`- 计价公式: ${priceResult.Formula}`);
988
+ }
989
+ return {
990
+ summary: summary || "询价返回缺少总价字段",
991
+ detail: lines.join("\n"),
992
+ };
993
+ }
994
+ /**
995
+ * 构建释放方式说明。manageEnv 当前未提供 destroy action,
996
+ * 指向控制台让用户手动销毁。
997
+ */
998
+ function buildReleaseMethodHint() {
999
+ return {
1000
+ method: "手动销毁",
1001
+ consoleUrl: "https://console.cloud.tencent.com/tcb",
1002
+ note: '环境创建后可随时销毁以停止计费。当前 manageEnv 未提供 destroy action,请前往控制台手动销毁,或调用 manageEnv(action="listPackages") 查看其他套餐。',
1003
+ };
1004
+ }
1005
+ /**
1006
+ * manageEnv 涉及计费的官方文档链接。来源:腾讯云开发 CloudBase 公开文档。
1007
+ * 任何 confirm 消息展示这些链接前不需要再次校验 URL 真实性。
1008
+ */
1009
+ const MANAGE_ENV_DOC_LINKS = {
1010
+ // 包年包月套餐说明(个人版 / 标准版 / 企业版 / 企业高级版)
1011
+ package: "https://cloud.tencent.com/document/product/876/39093",
1012
+ // 计费能力项说明
1013
+ billingItems: "https://cloud.tencent.com/document/product/876/120713",
1014
+ // 资源点价格文档
1015
+ resourcePointPrice: "https://cloud.tencent.com/document/product/876/127357",
1016
+ // 预付费计费与到期释放(费用中心通用)
1017
+ prepayExpiry: "https://cloud.tencent.com/document/product/555/9618",
1018
+ };
1019
+ /**
1020
+ * 把文档链接渲染为多行 markdown 列表文本。
1021
+ * filter 不传时全部展示。
1022
+ */
1023
+ function renderDocLinksBlock(filter) {
1024
+ const labels = {
1025
+ package: "包年包月套餐说明",
1026
+ billingItems: "计费能力项说明",
1027
+ resourcePointPrice: "资源点价格文档",
1028
+ prepayExpiry: "预付费计费与到期释放(费用中心通用)",
1029
+ };
1030
+ const entries = (filter ?? Object.keys(MANAGE_ENV_DOC_LINKS))
1031
+ .map((k) => `- [${labels[k]}](${MANAGE_ENV_DOC_LINKS[k]})`)
1032
+ .join("\n");
1033
+ return `参考文档:\n${entries}`;
1034
+ }
1035
+ /**
1036
+ * 资源清单详细描述(对应控制台购买页"资源清单"段)。
1037
+ */
1038
+ function buildResourceListText() {
1039
+ return "资源清单:\n- 云开发环境 ×1(含 云数据库 / 云函数 / 云存储 / 静态托管 / 身份认证 等基础资源)";
1040
+ }
1041
+ /**
1042
+ * 计费项披露(对应控制台购买页"计费项"段)。
1043
+ * 此处为静态披露,调用方在 confirm 消息中拼接即可。
1044
+ */
1045
+ function buildBillingItemsText() {
1046
+ return "计费项:\n- 数据库容量/调用 · 云函数调用/资源/流量 · 存储读写/CDN · 网关/认证/API 调用 · QPS 超限按量 · 日志";
1047
+ }
1048
+ /**
1049
+ * 计费方式披露(对应控制台购买页"计费方式"段)。
1050
+ * 针对用户传入的 packageId 判断套餐类型:
1051
+ * - 含 free/activity/trial/试用 等关键字视为免费体验版
1052
+ * - 其余视为付费套餐
1053
+ */
1054
+ function buildBillingModeText(packageId) {
1055
+ const id = (packageId || "").toLowerCase();
1056
+ const isFree = id.includes("free") ||
1057
+ id.includes("activity") ||
1058
+ id.includes("trial") ||
1059
+ id.includes("试用") ||
1060
+ id.includes("体验");
1061
+ if (isFree) {
1062
+ return ("计费方式:\n- 免费体验版(每月赠送约 3000 资源点 ≈ 3 元,0 元开通)\n" +
1063
+ "- 付费套餐:个人版 / 标准版 / 企业版 / 企业高级版");
1064
+ }
1065
+ return ("计费方式:\n- 付费套餐:个人版 / 标准版 / 企业版 / 企业高级版\n" +
1066
+ "- 免费体验版通过 auth 工具自动创建;本次 manageEnv(create) 不会创建免费版");
1067
+ }
1068
+ /**
1069
+ * 资源释放方式详细说明(对应控制台购买页"资源释放方式"段)。
1070
+ * - 免费版:1 个月有效期 + 免费续期 + 停服(保留数据) + 1~7天回收站 + 释放(数据不可恢复)
1071
+ * - 付费版:到期未续费 → 停服(保留数据) + 1~7天可回收站找回 + 释放(数据不可恢复)
1072
+ * 任何时候都可在控制台主动销毁、关闭按量、退订加购资源。
1073
+ */
1074
+ function buildReleaseMethodDetailText(packageId) {
1075
+ const id = (packageId || "").toLowerCase();
1076
+ const isFree = id.includes("free") ||
1077
+ id.includes("activity") ||
1078
+ id.includes("trial") ||
1079
+ id.includes("试用") ||
1080
+ id.includes("体验");
1081
+ const lines = ["资源释放方式:\n- 可随时在控制台销毁环境、关闭按量、退订加购资源"];
1082
+ if (isFree) {
1083
+ lines.push("- 免费体验版:有效期 1 个月,到期可免费续期 1 个月;未续期则停服(保留数据)→1~7天回收站→释放(数据不可恢复)");
1084
+ }
1085
+ else {
1086
+ lines.push("- 付费套餐到期未续费:停服(保留数据)→1~7天可回收站找回→释放(数据不可恢复)");
1087
+ lines.push("- 主动销毁:随时生效;销毁前请确保已迁移或备份数据");
1088
+ }
1089
+ return lines.join("\n");
1090
+ }
1091
+ /**
1092
+ * 预计费用披露段:把询价结果 + 周期说明 + 超额按量说明组合成人类可读文本。
1093
+ */
1094
+ function buildPricingDisclosureText(packageId, priceSection, priceError, period) {
1095
+ const id = (packageId || "").toLowerCase();
1096
+ const isFree = id.includes("free") ||
1097
+ id.includes("activity") ||
1098
+ id.includes("trial") ||
1099
+ id.includes("试用") ||
1100
+ id.includes("体验");
1101
+ const lines = ["预计费用:"];
1102
+ if (isFree) {
1103
+ lines.push(`- 免费体验版:本次开通 0 元;超免费额度后需升级为付费套餐(免费版不支持开按量)`);
1104
+ lines.push("- 实际单价以资源点价格文档为准(3000 资源点 ≈ 3 元)");
1105
+ }
1106
+ else {
1107
+ lines.push(`- 付费套餐:${priceSection?.summary ?? (priceError ? `⚠️ 询价失败(${priceError}),请前往控制台确认` : "询价返回为空")}`);
1108
+ if (priceSection?.detail) {
1109
+ lines.push(priceSection.detail);
1110
+ }
1111
+ if (priceError && priceSection) {
1112
+ lines.push(`- ⚠️ 部分明细缺失:${priceError}`);
1113
+ }
1114
+ lines.push(`- 计费周期:约 ${period} 个月(包年包月),到期可续费或变配`);
1115
+ lines.push("- 超额可另开按量(次日结算),详细计费项以官方文档为准");
1116
+ }
1117
+ return lines.join("\n");
1118
+ }
820
1119
  function resolveToolAuthOptions(server, overrides) {
821
1120
  return (0, auth_js_1.resolveAuthOptions)({
822
1121
  ...overrides,
@@ -1645,7 +1944,7 @@ function registerEnvTools(server) {
1645
1944
  if (server.ide !== 'wxide') {
1646
1945
  server.registerTool?.("envDomainManagement", {
1647
1946
  title: "CloudBase 环境域名管理(安全域名 / CORS 白名单)",
1648
- description: "管理 CloudBase 环境的安全域名(安全域名 / CORS 白名单),支持添加和删除操作。(原工具名:createEnvDomain/deleteEnvDomain,为兼容旧AI规则可继续使用这些名称)当浏览器 Web 应用需要从本地 Vite / dev server 直接访问 CloudBase 资源时,应先用 queryEnv(action=domains) 检查当前实际浏览器 origin 对应的 host:port 是否已在白名单中,再按该实际值添加。新增或删除后通常需要继续轮询 queryEnv(action=domains) 确认状态收敛;安全域名一般约 10 分钟生效。⚠️ 重要:此工具仅用于 CORS/请求来源验证,不涉及 SSL 证书。如需绑定自定义域名供公网 HTTPS 访问,请使用 manageGateway(action=\"bindCustomDomain\")。",
1947
+ description: "管理 CloudBase 环境的安全域名(安全域名 / CORS 白名单),支持添加和删除操作。(原工具名:createEnvDomain/deleteEnvDomain,为兼容旧AI规则可继续使用这些名称)当浏览器 Web 应用需要从本地 Vite / dev server 直接访问 CloudBase 资源时,应先用 queryEnv(action=domains) 检查当前实际浏览器 origin 对应的 host:port 是否已在白名单中,再按该实际值添加。新增或删除后通常需要继续轮询 queryEnv(action=domains) 确认状态收敛;安全域名一般约 10 分钟生效。⚠️ 重要:此工具仅用于 CORS/请求来源验证,不涉及 SSL 证书。自定义域名公网 HTTPS:先 queryGateway(listCustomDomains);已有域名则 manageGateway(createRoute) 显式传 domain(无需证书);仅首次绑定新域名才用 bindCustomDomain(需 certificateId)。",
1649
1948
  inputSchema: {
1650
1949
  action: zod_1.z
1651
1950
  .enum(["create", "delete"])
@@ -1769,10 +2068,92 @@ function registerEnvTools(server) {
1769
2068
  // CreateEnv (Manager SDK / Cloud API) accepts Alias, PackageId, Resources, Period, etc.
1770
2069
  // It does NOT accept Region — region is determined by account/package, not this call.
1771
2070
  if (!confirmed) {
2071
+ // 查询套餐名和预计费用(失败降级,不阻塞 confirm 流程)
2072
+ const packageTitle = packageId
2073
+ ? await fetchPackageTitle(cloudbase, packageId)
2074
+ : undefined;
2075
+ const pricingRegion = resolvePricingRegion(cloudBaseOptions);
2076
+ const priceProbe = packageId
2077
+ ? await calculateCreatePrice(cloudbase, {
2078
+ packageId,
2079
+ region: pricingRegion,
2080
+ period: duration,
2081
+ })
2082
+ : { error: "缺少 packageId,无法询价" };
2083
+ const priceSection = priceProbe.priceResult
2084
+ ? formatPriceSection(priceProbe.priceResult)
2085
+ : null;
2086
+ const releaseMethod = buildReleaseMethodHint();
2087
+ // 组合多段披露文案(对照控制台购买页确认对话框)
2088
+ const messageLines = [];
2089
+ messageLines.push("即将为你开通云开发环境");
2090
+ messageLines.push("本操作会创建腾讯云开发环境资源。");
2091
+ messageLines.push("为付费套餐后才会产生费用;免费体验版不会立即扣费(每月赠送约 3000 资源点 ≈ 3 元)。");
2092
+ messageLines.push("请核对以下配置信息后传入 confirm=\"yes\":");
2093
+ messageLines.push(`- 别名: ${alias ?? "(未提供)"}`);
2094
+ messageLines.push(`- 套餐: ${packageId ?? "(未提供)"}` +
2095
+ (packageTitle ? `(${packageTitle})` : ""));
2096
+ messageLines.push(`- 资源类型: ${resolvedResources.join(", ")}`);
2097
+ messageLines.push(`- 时长: ${duration} 个月`);
2098
+ messageLines.push("- 说明: CreateEnv 不接受 Region 入参,环境地域由账号与套餐侧决定。");
2099
+ messageLines.push("");
2100
+ // 资源清单 / 计费项 / 计费方式
2101
+ messageLines.push(buildResourceListText());
2102
+ messageLines.push(buildBillingItemsText());
2103
+ messageLines.push(buildBillingModeText(packageId));
2104
+ messageLines.push("");
2105
+ // 预计费用
2106
+ messageLines.push(buildPricingDisclosureText(packageId, priceSection, priceProbe.error, duration));
2107
+ messageLines.push("");
2108
+ // 资源释放方式
2109
+ messageLines.push(buildReleaseMethodDetailText(packageId));
2110
+ messageLines.push("");
2111
+ // 文档链接
2112
+ messageLines.push(renderDocLinksBlock([
2113
+ "package",
2114
+ "billingItems",
2115
+ "resourcePointPrice",
2116
+ "prepayExpiry",
2117
+ ]));
2118
+ messageLines.push("");
2119
+ // 已知晓声明
2120
+ messageLines.push("☐ 我已知晓将创建付费资源及计费规则,确认按上述配置开通。");
2121
+ messageLines.push(`(如需取消或修改,请勿传 confirm="yes",改传其他参数重试)`);
1772
2122
  return (0, tool_result_js_1.buildJsonToolResult)({
1773
2123
  ok: false,
1774
2124
  code: "CONFIRM_REQUIRED",
1775
- message: `创建环境需要您确认。请确认以下配置信息后传入 confirm="yes":\n别名: ${alias}\n套餐: ${packageId}\n资源类型: ${resolvedResources.join(", ")}\n时长: ${duration} 个月\n说明: CreateEnv 不接受 Region;环境地域由账号与套餐侧决定。`,
2125
+ message: messageLines.join("\n"),
2126
+ package_info: packageTitle
2127
+ ? { packageId, packageTitle }
2128
+ : packageId
2129
+ ? { packageId, packageTitle: null }
2130
+ : undefined,
2131
+ pricing: priceSection
2132
+ ? {
2133
+ summary: priceSection.summary,
2134
+ currency: priceProbe.priceResult?.Currency,
2135
+ realTotalCost: priceProbe.priceResult?.RealTotalCost,
2136
+ totalCost: priceProbe.priceResult?.TotalCost,
2137
+ timeSpan: priceProbe.priceResult?.TimeSpan,
2138
+ timeUnit: priceProbe.priceResult?.TimeUnit,
2139
+ inquiryRegion: pricingRegion,
2140
+ }
2141
+ : priceProbe.error
2142
+ ? { inquiryFailed: true, error: priceProbe.error }
2143
+ : undefined,
2144
+ release_method: {
2145
+ ...releaseMethod,
2146
+ detail: buildReleaseMethodDetailText(packageId),
2147
+ docLinks: [
2148
+ MANAGE_ENV_DOC_LINKS.package,
2149
+ MANAGE_ENV_DOC_LINKS.prepayExpiry,
2150
+ ],
2151
+ },
2152
+ doc_links: MANAGE_ENV_DOC_LINKS,
2153
+ confirmation_acknowledgement: {
2154
+ text: "我已知晓将创建付费资源及计费规则",
2155
+ required: true,
2156
+ },
1776
2157
  next_step: {
1777
2158
  tool: "manageEnv",
1778
2159
  action: "create",
@@ -1808,10 +2189,91 @@ function registerEnvTools(server) {
1808
2189
  if (!envId || !packageId) {
1809
2190
  throw new Error("变更套餐时 envId 和 packageId 为必填参数");
1810
2191
  }
2192
+ // 查询当前套餐名 + 新套餐名 + 询价(失败降级)
2193
+ const [currentBilling, newPackageTitle] = await Promise.all([
2194
+ fetchEnvBillingSummary(cloudbase, envId),
2195
+ fetchPackageTitle(cloudbase, packageId),
2196
+ ]);
2197
+ const priceProbe = await calculateModifyPrice(cloudbase, envId, packageId);
2198
+ const priceSection = priceProbe.priceResult
2199
+ ? formatPriceSection(priceProbe.priceResult)
2200
+ : null;
2201
+ const releaseMethod = buildReleaseMethodHint();
2202
+ const messageLines = [];
2203
+ messageLines.push(`变更环境 ${envId} 的套餐需要您确认。变配后不会立即重新计费,但会触发差价结算或退款。`);
2204
+ messageLines.push("请核对后传入 confirm=\"yes\":");
2205
+ messageLines.push(`- 当前套餐: ${currentBilling?.packageName ?? currentBilling?.packageId ?? "(未知)"}` +
2206
+ (currentBilling?.packageId && currentBilling.packageName
2207
+ ? `(${currentBilling.packageId})`
2208
+ : ""));
2209
+ if (currentBilling?.expireTime) {
2210
+ messageLines.push(`- 当前到期时间: ${currentBilling.expireTime}`);
2211
+ }
2212
+ messageLines.push(`- 新套餐: ${packageId}` +
2213
+ (newPackageTitle ? `(${newPackageTitle})` : ""));
2214
+ messageLines.push("");
2215
+ if (priceSection) {
2216
+ messageLines.push(`预计费用变化:${priceSection.summary}(差价/退款以账单为准)`);
2217
+ if (priceSection.detail) {
2218
+ messageLines.push(priceSection.detail);
2219
+ }
2220
+ }
2221
+ else if (priceProbe.error) {
2222
+ messageLines.push(`预计费用变化:⚠️ 询价失败(${priceProbe.error}),请前往控制台确认价格`);
2223
+ }
2224
+ else {
2225
+ messageLines.push("预计费用变化:询价返回为空,请前往控制台确认价格");
2226
+ }
2227
+ messageLines.push("");
2228
+ // 资源释放方式(变配不影响存续,但与到期/销毁规则相同)
2229
+ messageLines.push(buildReleaseMethodDetailText(packageId));
2230
+ messageLines.push("");
2231
+ // 文档链接(变配与套餐/计费/到期都相关)
2232
+ messageLines.push(renderDocLinksBlock(["package", "prepayExpiry"]));
2233
+ messageLines.push("");
2234
+ messageLines.push("☐ 我已知晓变配将触发差价结算或退款,确认按上述配置变更。");
2235
+ messageLines.push(`(如需取消或修改,请勿传 confirm="yes")`);
1811
2236
  return (0, tool_result_js_1.buildJsonToolResult)({
1812
2237
  ok: false,
1813
2238
  code: "CONFIRM_REQUIRED",
1814
- message: `变更环境 ${envId} 的套餐为 ${packageId} 可能产生费用变化。请确认后传入 confirm="yes"。`,
2239
+ message: messageLines.join("\n"),
2240
+ env_id: envId,
2241
+ current_package: currentBilling
2242
+ ? {
2243
+ packageId: currentBilling.packageId,
2244
+ packageName: currentBilling.packageName,
2245
+ expireTime: currentBilling.expireTime,
2246
+ payMode: currentBilling.payMode,
2247
+ }
2248
+ : undefined,
2249
+ new_package: {
2250
+ packageId,
2251
+ packageTitle: newPackageTitle ?? null,
2252
+ },
2253
+ pricing: priceSection
2254
+ ? {
2255
+ summary: priceSection.summary,
2256
+ currency: priceProbe.priceResult?.Currency,
2257
+ realTotalCost: priceProbe.priceResult?.RealTotalCost,
2258
+ totalCost: priceProbe.priceResult?.TotalCost,
2259
+ refund: priceProbe.priceResult?.Refund,
2260
+ }
2261
+ : priceProbe.error
2262
+ ? { inquiryFailed: true, error: priceProbe.error }
2263
+ : undefined,
2264
+ release_method: {
2265
+ ...releaseMethod,
2266
+ detail: buildReleaseMethodDetailText(packageId),
2267
+ docLinks: [MANAGE_ENV_DOC_LINKS.prepayExpiry],
2268
+ },
2269
+ doc_links: {
2270
+ package: MANAGE_ENV_DOC_LINKS.package,
2271
+ prepayExpiry: MANAGE_ENV_DOC_LINKS.prepayExpiry,
2272
+ },
2273
+ confirmation_acknowledgement: {
2274
+ text: "我已知晓变配将触发差价结算或退款",
2275
+ required: true,
2276
+ },
1815
2277
  next_step: {
1816
2278
  tool: "manageEnv",
1817
2279
  action: "modifyPlan",
@@ -1841,10 +2303,87 @@ function registerEnvTools(server) {
1841
2303
  if (!envId) {
1842
2304
  throw new Error("续费环境时 envId 为必填参数");
1843
2305
  }
2306
+ // 查询当前套餐名 + 到期时间 + 询价(失败降级)
2307
+ const [currentBilling, priceProbe] = await Promise.all([
2308
+ fetchEnvBillingSummary(cloudbase, envId),
2309
+ calculateRenewPrice(cloudbase, envId, duration),
2310
+ ]);
2311
+ const priceSection = priceProbe.priceResult
2312
+ ? formatPriceSection(priceProbe.priceResult)
2313
+ : null;
2314
+ const releaseMethod = buildReleaseMethodHint();
2315
+ const currentPackageId = currentBilling?.packageId;
2316
+ const messageLines = [];
2317
+ messageLines.push(`续费环境 ${envId} 需要您确认。续费按当前套餐类型计算,延长到期时间。`);
2318
+ messageLines.push("请核对后传入 confirm=\"yes\":");
2319
+ messageLines.push(`- 当前套餐: ${currentBilling?.packageName ?? currentBilling?.packageId ?? "(未知)"}` +
2320
+ (currentBilling?.packageId && currentBilling.packageName
2321
+ ? `(${currentBilling.packageId})`
2322
+ : ""));
2323
+ if (currentBilling?.expireTime) {
2324
+ messageLines.push(`- 当前到期时间: ${currentBilling.expireTime}`);
2325
+ }
2326
+ messageLines.push(`- 续费时长: ${duration} 个月`);
2327
+ messageLines.push("");
2328
+ if (priceSection) {
2329
+ messageLines.push(`预计费用:${priceSection.summary}`);
2330
+ if (priceSection.detail) {
2331
+ messageLines.push(priceSection.detail);
2332
+ }
2333
+ }
2334
+ else if (priceProbe.error) {
2335
+ messageLines.push(`预计费用:⚠️ 询价失败(${priceProbe.error}),请前往控制台确认价格`);
2336
+ }
2337
+ else {
2338
+ messageLines.push("预计费用:询价返回为空,请前往控制台确认价格");
2339
+ }
2340
+ messageLines.push("");
2341
+ // 资源释放方式
2342
+ messageLines.push(buildReleaseMethodDetailText(currentPackageId));
2343
+ messageLines.push("");
2344
+ // 文档链接(续费主要看预付费与到期释放)
2345
+ messageLines.push(renderDocLinksBlock(["prepayExpiry"]));
2346
+ messageLines.push("");
2347
+ messageLines.push("☐ 我已知晓续费将延长当前套餐的到期时间,确认按上述配置续费。");
2348
+ messageLines.push(`(如需取消或修改,请勿传 confirm="yes")`);
1844
2349
  return (0, tool_result_js_1.buildJsonToolResult)({
1845
2350
  ok: false,
1846
2351
  code: "CONFIRM_REQUIRED",
1847
- message: `续费环境 ${envId},时长: ${duration} 个月,可能产生费用。请确认后传入 confirm="yes"。`,
2352
+ message: messageLines.join("\n"),
2353
+ env_id: envId,
2354
+ current_package: currentBilling
2355
+ ? {
2356
+ packageId: currentBilling.packageId,
2357
+ packageName: currentBilling.packageName,
2358
+ expireTime: currentBilling.expireTime,
2359
+ payMode: currentBilling.payMode,
2360
+ isAutoRenew: currentBilling.isAutoRenew,
2361
+ }
2362
+ : undefined,
2363
+ pricing: priceSection
2364
+ ? {
2365
+ summary: priceSection.summary,
2366
+ currency: priceProbe.priceResult?.Currency,
2367
+ realTotalCost: priceProbe.priceResult?.RealTotalCost,
2368
+ totalCost: priceProbe.priceResult?.TotalCost,
2369
+ timeSpan: priceProbe.priceResult?.TimeSpan,
2370
+ timeUnit: priceProbe.priceResult?.TimeUnit,
2371
+ }
2372
+ : priceProbe.error
2373
+ ? { inquiryFailed: true, error: priceProbe.error }
2374
+ : undefined,
2375
+ release_method: {
2376
+ ...releaseMethod,
2377
+ detail: buildReleaseMethodDetailText(currentPackageId),
2378
+ docLinks: [MANAGE_ENV_DOC_LINKS.prepayExpiry],
2379
+ },
2380
+ doc_links: {
2381
+ prepayExpiry: MANAGE_ENV_DOC_LINKS.prepayExpiry,
2382
+ },
2383
+ confirmation_acknowledgement: {
2384
+ text: "我已知晓续费将延长当前套餐的到期时间",
2385
+ required: true,
2386
+ },
1848
2387
  next_step: {
1849
2388
  tool: "manageEnv",
1850
2389
  action: "renew",
@@ -2233,7 +2772,7 @@ ${envIdSection}
2233
2772
  ## 环境信息
2234
2773
  - 操作系统: ${os_1.default.type()} ${os_1.default.release()}
2235
2774
  - Node.js版本: ${process.version}
2236
- - MCP 版本:${process.env.npm_package_version || "2.25.2" || 0}
2775
+ - MCP 版本:${process.env.npm_package_version || "2.25.4" || 0}
2237
2776
  - 系统架构: ${os_1.default.arch()}
2238
2777
  - 时间: ${new Date().toISOString()}
2239
2778
  - 请求ID: ${requestId}
@@ -2314,7 +2853,7 @@ function createWrappedHandler(name, handler, server) {
2314
2853
  requestId: (typeof error === 'object' && error && 'requestId' in error) ? error.requestId : '',
2315
2854
  ide: server.ide || process.env.INTEGRATION_IDE || ''
2316
2855
  });
2317
- const mcpVersion = true ? "2.25.2" : 0;
2856
+ const mcpVersion = true ? "2.25.4" : 0;
2318
2857
  const requestIdSuffix = requestId ? `\n🆔 RequestId: ${requestId}` : '';
2319
2858
  const enhancedErrorMessage = `${errorMessage}${requestIdSuffix}\n\n📦 CloudBase MCP v${mcpVersion}\n🔗 遇到问题?请复制以下链接到浏览器打开\n即可自动携带错误详情快速创建 GitHub Issue:\n${issueLink}`;
2320
2859
  // 创建新的错误对象,保持原有的错误类型但更新消息
@@ -7301,6 +7840,7 @@ const QUERY_GATEWAY_ACTIONS = [
7301
7840
  "listRoutes",
7302
7841
  "getRoute",
7303
7842
  "listCustomDomains",
7843
+ "getPrivilege",
7304
7844
  ];
7305
7845
  const MANAGE_GATEWAY_ACTIONS = [
7306
7846
  "createRoute",
@@ -7308,7 +7848,11 @@ const MANAGE_GATEWAY_ACTIONS = [
7308
7848
  "deleteRoute",
7309
7849
  "bindCustomDomain",
7310
7850
  "deleteCustomDomain",
7851
+ "enableService",
7852
+ "authSwitch",
7311
7853
  ];
7854
+ /** DomainType of the environment default HTTP service (gateway) domain. */
7855
+ const HTTP_SERVICE_DOMAIN_TYPE = "HTTPSERVICE";
7312
7856
  const UPSTREAM_RESOURCE_TYPES = [
7313
7857
  "SCF",
7314
7858
  "WEB_SCF",
@@ -7345,21 +7889,19 @@ function registerGatewayTools(server) {
7345
7889
  return (0, json_content_js_1.jsonContent)(buildErrorEnvelope(error));
7346
7890
  }
7347
7891
  };
7348
- const listHttpServiceRoutes = async (domain) => {
7892
+ const listHttpServiceRoutes = async (options) => {
7893
+ const filters = [];
7894
+ if (options?.domain) {
7895
+ filters.push({ Name: "Domain", Values: [options.domain] });
7896
+ }
7897
+ if (options?.domainType) {
7898
+ filters.push({ Name: "DomainType", Values: [options.domainType] });
7899
+ }
7349
7900
  const cloudbase = await getManager();
7350
7901
  const result = await cloudbase.env.describeHttpServiceRoute({
7351
7902
  EnvId: await resolveEnvId(),
7352
7903
  Limit: 1000,
7353
- ...(domain
7354
- ? {
7355
- Filters: [
7356
- {
7357
- Name: "Domain",
7358
- Values: [domain],
7359
- },
7360
- ],
7361
- }
7362
- : {}),
7904
+ ...(filters.length ? { Filters: filters } : {}),
7363
7905
  });
7364
7906
  (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
7365
7907
  return result;
@@ -7398,15 +7940,49 @@ function registerGatewayTools(server) {
7398
7940
  : {}),
7399
7941
  };
7400
7942
  };
7943
+ const pickUsableDefaultDomain = (domains) => {
7944
+ const candidates = domains.filter((item) => item.IsDefault === true && item.Domain);
7945
+ return (candidates.find((item) => item.Enable !== false && item.Status === "SUCCESS") ??
7946
+ candidates.find((item) => item.Enable !== false) ??
7947
+ candidates[0]);
7948
+ };
7949
+ const getGatewayPrivilege = async () => {
7950
+ const cloudbase = await getManager();
7951
+ const result = await cloudbase
7952
+ .commonService("tcb", "2018-06-08")
7953
+ .call({
7954
+ Action: "DescribeCloudBaseGWPrivilege",
7955
+ Param: {
7956
+ ServiceId: await resolveEnvId(),
7957
+ },
7958
+ });
7959
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
7960
+ return result ?? {};
7961
+ };
7962
+ const buildPrivilegeDescription = (privilege) => {
7963
+ const serviceStatus = privilege.EnableService === true ? "已开启" : "未开启";
7964
+ const authStatus = privilege.EnableAuth === undefined
7965
+ ? "未知"
7966
+ : privilege.EnableAuth === true
7967
+ ? "已开启"
7968
+ : "未开启";
7969
+ return `HTTP 网关${serviceStatus},访问鉴权${authStatus}`;
7970
+ };
7401
7971
  const resolveDefaultHttpDomain = async () => {
7402
- const routeInfo = await listHttpServiceRoutes();
7403
- const domains = routeInfo.Domains ?? [];
7404
- const defaultCandidates = domains.filter((item) => item.IsDefault === true && item.Domain);
7405
- const preferred = defaultCandidates.find((item) => item.Enable !== false && item.Status === "SUCCESS") ??
7406
- defaultCandidates.find((item) => item.Enable !== false) ??
7407
- defaultCandidates[0];
7972
+ // Match console DescribeHTTPServiceRoute usage: filter DomainType=HTTPSERVICE.
7973
+ // Envs often also expose an IsDefault STATIC_STORE domain (*.tcloudbaseapp.com);
7974
+ // that is NOT the default HTTP access entry (*.{region}.app.tcloudbase.com).
7975
+ const httpServiceRoutes = await listHttpServiceRoutes({
7976
+ domainType: HTTP_SERVICE_DOMAIN_TYPE,
7977
+ });
7978
+ // Always re-filter client-side: some SDKs/mocks may ignore Filters.
7979
+ let preferred = pickUsableDefaultDomain((httpServiceRoutes.Domains ?? []).filter((item) => item.DomainType === HTTP_SERVICE_DOMAIN_TYPE));
7980
+ if (!preferred?.Domain) {
7981
+ const allRoutes = await listHttpServiceRoutes();
7982
+ preferred = pickUsableDefaultDomain((allRoutes.Domains ?? []).filter((item) => item.DomainType === HTTP_SERVICE_DOMAIN_TYPE));
7983
+ }
7408
7984
  if (!preferred?.Domain) {
7409
- throw new Error("环境默认 HTTP 访问域名未就绪或未开通。请先在控制台开通 HTTP 访问服务,或用 queryGateway(action=\"listRoutes\") 确认 Domains 中是否存在 IsDefault=true 的域名;也可以显式传入 domain 后重试 createRoute/updateRoute/deleteRoute。");
7985
+ throw new Error("环境默认 HTTP 访问域名未就绪或未开通。请先在控制台开通 HTTP 访问服务,或用 queryGateway(action=\"listRoutes\") 确认 Domains 中是否存在 DomainType=HTTPSERVICE 且 IsDefault=true 的域名(形如 *.{region}.app.tcloudbase.com);不要使用静态托管域名(*.tcloudbaseapp.com)。也可以显式传入 domain 后重试 createRoute/updateRoute/deleteRoute。");
7410
7986
  }
7411
7987
  return preferred.Domain;
7412
7988
  };
@@ -7502,7 +8078,7 @@ function registerGatewayTools(server) {
7502
8078
  }, `已获取 ${customDomains.length} 个自定义域名`);
7503
8079
  }
7504
8080
  case "listRoutes": {
7505
- const result = await listHttpServiceRoutes(input.domain);
8081
+ const result = await listHttpServiceRoutes({ domain: input.domain });
7506
8082
  const routes = flattenRoutes(result);
7507
8083
  return buildEnvelope({
7508
8084
  action: input.action,
@@ -7517,7 +8093,7 @@ function registerGatewayTools(server) {
7517
8093
  if (!input.routeId && !input.targetName && !input.path) {
7518
8094
  throw new Error("action=getRoute 时至少需要提供 routeId、targetName 或 path");
7519
8095
  }
7520
- const result = await listHttpServiceRoutes(input.domain);
8096
+ const result = await listHttpServiceRoutes({ domain: input.domain });
7521
8097
  const normalizedPath = input.path
7522
8098
  ? normalizeAccessPath(input.path)
7523
8099
  : undefined;
@@ -7564,6 +8140,28 @@ function registerGatewayTools(server) {
7564
8140
  },
7565
8141
  ]);
7566
8142
  }
8143
+ case "getPrivilege": {
8144
+ const privilege = await getGatewayPrivilege();
8145
+ const enableService = privilege.EnableService === true;
8146
+ const enableAuth = privilege.EnableAuth === true;
8147
+ return buildEnvelope({
8148
+ action: input.action,
8149
+ enableService,
8150
+ enableAuth,
8151
+ raw: privilege,
8152
+ }, buildPrivilegeDescription(privilege) +
8153
+ (enableService
8154
+ ? ""
8155
+ : ";若路由创建成功但访问报 HTTPSERVICE_NONACTIVATED(403),请先开启 HTTP 网关"), enableService
8156
+ ? undefined
8157
+ : [
8158
+ {
8159
+ tool: "manageGateway",
8160
+ action: "enableService",
8161
+ reason: "开启 HTTP 网关总开关(EnableService),开启后路由即可通过默认域访问",
8162
+ },
8163
+ ]);
8164
+ }
7567
8165
  default:
7568
8166
  throw new Error(`不支持的操作类型: ${input.action}`);
7569
8167
  }
@@ -7594,6 +8192,28 @@ function registerGatewayTools(server) {
7594
8192
  throw err;
7595
8193
  }
7596
8194
  (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
8195
+ // 探测 HTTP 网关总开关:未开启时提示 HTTPSERVICE_NONACTIVATED 风险并引导开启。
8196
+ // 探测失败不阻断路由创建结果,仅追加弱提示。
8197
+ let privilegeHint = "";
8198
+ let privilegeNextActions = [];
8199
+ try {
8200
+ const privilege = await getGatewayPrivilege();
8201
+ if (privilege.EnableService !== true) {
8202
+ privilegeHint =
8203
+ "⚠️ HTTP 网关总开关未开启,路由创建成功后访问仍将返回 HTTPSERVICE_NONACTIVATED(403);请先调用 manageGateway(action=\"enableService\", enable=true) 开启,再等待 30 秒到 3 分钟访问。";
8204
+ privilegeNextActions = [
8205
+ {
8206
+ tool: "manageGateway",
8207
+ action: "enableService",
8208
+ reason: "开启 HTTP 网关总开关(EnableService),否则访问路由会报 HTTPSERVICE_NONACTIVATED(403)",
8209
+ },
8210
+ ];
8211
+ }
8212
+ }
8213
+ catch {
8214
+ privilegeHint =
8215
+ "(无法确认 HTTP 网关开关状态;若访问报 HTTPSERVICE_NONACTIVATED,请用 queryGateway(action=\"getPrivilege\") 查询后用 manageGateway(action=\"enableService\") 开启)";
8216
+ }
7597
8217
  return buildEnvelope({
7598
8218
  action: input.action,
7599
8219
  model: "httpServiceRoute",
@@ -7616,7 +8236,12 @@ function registerGatewayTools(server) {
7616
8236
  : payload.resolved.enablePathTransmission === false
7617
8237
  ? ";路径透传关闭(网关会剥掉触发路径前缀后再转发给后端)"
7618
8238
  : ";路径透传未显式设置(平台默认 false,会剥掉触发路径前缀)") +
7619
- `。注意:路由配置传播通常需要等待 30 秒到 3 分钟,请勿立即访问。该操作只创建网关入口,不会自动放开上游权限;若上游是云函数且需要匿名或浏览器直接访问,请继续检查函数资源权限。`, routeMutationNextActions(payload.resolved.upstreamResourceName));
8239
+ `。注意:路由配置传播通常需要等待 30 秒到 3 分钟,请勿立即访问。该操作只创建网关入口,不会自动放开上游权限;若上游是云函数且需要匿名或浏览器直接访问,请继续检查函数资源权限。` +
8240
+ (privilegeHint ? ` ${privilegeHint}` : ""), [
8241
+ ...privilegeNextActions,
8242
+ ...(routeMutationNextActions(payload.resolved.upstreamResourceName) ??
8243
+ []),
8244
+ ]);
7620
8245
  }
7621
8246
  case "updateRoute": {
7622
8247
  const cloudbase = await getManager();
@@ -7707,6 +8332,60 @@ function registerGatewayTools(server) {
7707
8332
  raw: result,
7708
8333
  }, "自定义域名删除成功");
7709
8334
  }
8335
+ case "enableService": {
8336
+ if (typeof input.enable !== "boolean") {
8337
+ throw new Error('action=enableService 时必须提供 enable 参数(boolean),如 enable=true 开启 HTTP 网关总开关、enable=false 关闭;禁止省略或传非布尔值。');
8338
+ }
8339
+ const cloudbase = await getManager();
8340
+ const result = await cloudbase.access.switchAuth(input.enable);
8341
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
8342
+ const serviceText = input.enable ? "开启" : "关闭";
8343
+ return buildEnvelope({
8344
+ action: input.action,
8345
+ enable: input.enable,
8346
+ raw: result,
8347
+ }, `HTTP 网关总开关${serviceText}成功`, [
8348
+ {
8349
+ tool: "queryGateway",
8350
+ action: "getPrivilege",
8351
+ reason: "复核 HTTP 网关总开关与访问鉴权状态",
8352
+ },
8353
+ ]);
8354
+ }
8355
+ case "authSwitch": {
8356
+ if (typeof input.enable !== "boolean") {
8357
+ throw new Error('action=authSwitch 时必须提供 enable 参数(boolean),如 enable=true 开启访问鉴权、enable=false 关闭;禁止省略或传非布尔值。');
8358
+ }
8359
+ const cloudbase = await getManager();
8360
+ const result = await cloudbase
8361
+ .commonService("tcb", "2018-06-08")
8362
+ .call({
8363
+ Action: "ModifyCloudBaseGWPrivilege",
8364
+ Param: {
8365
+ ServiceId: await resolveEnvId(),
8366
+ EnableService: input.enable,
8367
+ Options: [
8368
+ {
8369
+ Key: "authswitch",
8370
+ Value: input.enable ? "true" : "false",
8371
+ },
8372
+ ],
8373
+ },
8374
+ });
8375
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
8376
+ const serviceText = input.enable ? "开启" : "关闭";
8377
+ return buildEnvelope({
8378
+ action: input.action,
8379
+ enable: input.enable,
8380
+ raw: result,
8381
+ }, `HTTP 访问服务鉴权${serviceText}成功`, [
8382
+ {
8383
+ tool: "queryGateway",
8384
+ action: "getPrivilege",
8385
+ reason: "复核 HTTP 网关总开关与访问鉴权状态",
8386
+ },
8387
+ ]);
8388
+ }
7710
8389
  default:
7711
8390
  throw new Error(`不支持的操作类型: ${input.action}`);
7712
8391
  }
@@ -7715,11 +8394,15 @@ function registerGatewayTools(server) {
7715
8394
  title: "查询 CloudBase 网关",
7716
8395
  description: "CloudBase HTTP 网关统一只读入口(Domain/Route)。查询域名下路径路由及其上游:" +
7717
8396
  "WEB_SCF/SCF=云函数,CBR=云托管,STATIC_STORE=静态托管,LH=轻量应用服务器。" +
7718
- "主键为 Domain + Path;listRoutes / getRoute / listCustomDomains。",
8397
+ "主键为 Domain + Path;listRoutes / getRoute / listCustomDomains / getPrivilege。" +
8398
+ "getPrivilege 查询 HTTP 网关总开关(enableService)与访问鉴权(enableAuth)状态。" +
8399
+ "实现自定义域名访问前,先 listCustomDomains:若已有自定义域名,优先 createRoute 挂路由(无需证书 ID);仅在没有可用自定义域名时才 bindCustomDomain。",
7719
8400
  inputSchema: {
7720
8401
  action: zod_1.z
7721
8402
  .enum(QUERY_GATEWAY_ACTIONS)
7722
- .describe("只读操作类型:listRoutes、getRoute、listCustomDomains"),
8403
+ .describe("只读操作类型:listRoutes、getRoute、listCustomDomains、getPrivilege。" +
8404
+ "getPrivilege 无需其他参数,直接返回 HTTP 网关总开关与访问鉴权状态。" +
8405
+ "自定义域名访问场景先 listCustomDomains 确认是否已有域名可复用。"),
7723
8406
  targetName: zod_1.z
7724
8407
  .string()
7725
8408
  .optional()
@@ -7742,18 +8425,25 @@ function registerGatewayTools(server) {
7742
8425
  }, async (input) => withEnvelope(() => handleQueryGateway(input)));
7743
8426
  server.registerTool?.("manageGateway", {
7744
8427
  title: "管理 CloudBase 网关",
7745
- description: "CloudBase HTTP 网关统一写入口(Domain/Route)。createRoute/updateRoute/deleteRoute 把域名下的 path 转到上游;未传 domain 时用 IsDefault 默认域名。" +
8428
+ description: "CloudBase HTTP 网关统一写入口(Domain/Route)。createRoute/updateRoute/deleteRoute 把域名下的 path 转到上游;未传 domain 时用 DomainType=HTTPSERVICE 的 IsDefault 默认 HTTP 域名(形如 *.{region}.app.tcloudbase.com),不会使用静态托管 CDN 域名(*.tcloudbaseapp.com,DomainType=STATIC_STORE)。" +
8429
+ "这是网关默认域上的路径路由,不是 STATIC_STORE 上游绑定;STATIC_STORE 上游必须显式传 upstreamResourceType=STATIC_STORE。" +
8430
+ "创建后可用 queryGateway(action=\"listRoutes\") 核对 Domain / DomainType / Path / UpstreamResourceType。" +
7746
8431
  "上游类型只用一个参数 upstreamResourceType(也可写在 route.upstreamResourceType,route 优先):" +
7747
8432
  "WEB_SCF=HTTP云函数,SCF=Event云函数,CBR=云托管,STATIC_STORE=静态托管,LH=轻量应用服务器;" +
7748
8433
  "配合 targetName 或 route.serviceName(云函数名/云托管服务名/静态托管实例名,常见 staticstore)。" +
7749
8434
  "createRoute 只建网关入口,不改上游权限。" +
7750
8435
  "enablePathTransmission:默认 false 剥触发路径前缀;true 透传完整路径(CBR 多路由、WEB_SCF 自管子路径常需 true;STATIC_STORE 自定义触发路径映射站点根通常 false)。" +
7751
- "⚠️ SSL 自定义域名用 bindCustomDomain;CORS/安全域名用 envDomainManagement。",
8436
+ "⚠️ 自定义域名访问:若环境已有自定义域名(先 queryGateway listCustomDomains),优先 createRoute 并显式传入该 domain,无需 certificateId;" +
8437
+ "仅首次绑定全新自定义域名时用 bindCustomDomain(需 certificateId)。CORS/安全域名用 envDomainManagement。" +
8438
+ "enableService/authSwitch:HTTP 网关总开关与访问鉴权开关;createRoute 后若访问报 HTTPSERVICE_NONACTIVATED,通常是总开关未开启(用 queryGateway getPrivilege 查询、enableService 开启)。",
7752
8439
  inputSchema: {
7753
8440
  action: zod_1.z
7754
8441
  .enum(MANAGE_GATEWAY_ACTIONS)
7755
- .describe("写操作:createRoute/updateRoute/deleteRoute 管理路由;bindCustomDomain/deleteCustomDomain 管理自定义域名。" +
7756
- "createRoute/updateRoute 必须提供 upstreamResourceType。"),
8442
+ .describe("写操作:createRoute/updateRoute/deleteRoute 管理路由;bindCustomDomain/deleteCustomDomain 管理自定义域名;" +
8443
+ "enableService/authSwitch 开关 HTTP 网关总开关与访问鉴权(需配合 enable 参数)。" +
8444
+ "createRoute/updateRoute 必须提供 upstreamResourceType。" +
8445
+ "已有自定义域名时优先 createRoute(domain=已有域名) 实现访问,不必再次 bindCustomDomain / 传入 certificateId;" +
8446
+ "bindCustomDomain 仅用于首次绑定新域名。"),
7757
8447
  targetName: zod_1.z
7758
8448
  .string()
7759
8449
  .optional()
@@ -7807,11 +8497,20 @@ function registerGatewayTools(server) {
7807
8497
  domain: zod_1.z
7808
8498
  .string()
7809
8499
  .optional()
7810
- .describe("域名。省略时自动使用环境 IsDefault 默认 HTTP 域名;自定义域名场景请显式传入"),
8500
+ .describe("域名。省略时自动使用环境 DomainType=HTTPSERVICE 的 IsDefault 默认 HTTP 域名(*.{region}.app.tcloudbase.com),不会回退到静态托管 CDN 域名(*.tcloudbaseapp.com,DomainType=STATIC_STORE);也不是 STATIC_STORE 上游绑定。" +
8501
+ "可用 queryGateway(action=\"listRoutes\") 核对实际 Domain / DomainType。" +
8502
+ "已有自定义域名时请显式传入该域名并 createRoute/updateRoute/deleteRoute,即可实现自定义域名访问且无需证书 ID;" +
8503
+ "仅 bindCustomDomain 时表示要新绑定的域名。"),
7811
8504
  certificateId: zod_1.z
7812
8505
  .string()
7813
8506
  .optional()
7814
- .describe("证书 ID。bindCustomDomain 时必填"),
8507
+ .describe("证书 ID。仅首次 bindCustomDomain 必填。" +
8508
+ "在已有自定义域名上 createRoute / updateRoute / deleteRoute 不需要 certificateId。"),
8509
+ enable: zod_1.z
8510
+ .boolean()
8511
+ .optional()
8512
+ .describe("开关目标状态(仅 enableService / authSwitch 使用,必填):" +
8513
+ "enable=true 开启,enable=false 关闭。省略或非布尔值会返回参数错误。"),
7815
8514
  },
7816
8515
  annotations: {
7817
8516
  readOnlyHint: false,
@@ -9848,6 +10547,22 @@ function buildLoginConfigNextStep(loginMethods) {
9848
10547
  },
9849
10548
  };
9850
10549
  }
10550
+ /**
10551
+ * 短信验证码默认通道提示:开启 phone 登录后即可用云开发默认短信通道收发验证码,
10552
+ * 不需要配置短信签名/模板/自定义 Provider。仅当需要自定义模板、签名或更换短信服务商时,
10553
+ * 才需要配置 SmsVerificationConfig / 自定义短信通道。
10554
+ */
10555
+ function buildSmsHint(loginMethods) {
10556
+ if (!loginMethods.phone) {
10557
+ return undefined;
10558
+ }
10559
+ return {
10560
+ defaultChannelReady: true,
10561
+ message: "短信验证码登录已开启,可直接使用云开发默认短信通道收发验证码,无需配置短信签名/模板/自定义 Provider。" +
10562
+ "前端调用 auth.getVerification({ phone_number }) 发送验证码、auth.signInWithSms({ verificationInfo, verificationCode, phoneNum }) 登录。" +
10563
+ "仅当需要自定义短信模板/签名或更换短信服务商时,才需要配置 SmsVerificationConfig 或接入自定义短信通道。",
10564
+ };
10565
+ }
9851
10566
  function extractProviders(value) {
9852
10567
  const payload = normalizePlainObject(value, "providersResult");
9853
10568
  const providers = payload?.Providers ?? payload?.ProviderList ?? payload?.Data ?? [];
@@ -9964,6 +10679,31 @@ function registerAppAuthTools(server) {
9964
10679
  return (0, json_content_js_1.jsonContent)(buildErrorEnvelope(error));
9965
10680
  }
9966
10681
  };
10682
+ // Best-effort inventory read used to verify whether CreateApiKey really produced a new key.
10683
+ // A failure here must not block key creation, so it returns null to mark "unknown"
10684
+ // rather than an empty list, which would be indistinguishable from "no keys exist".
10685
+ const listApiKeyRecords = async (cloudbase, keyType) => {
10686
+ try {
10687
+ const result = await cloudbase.env.describeApiKeyList({
10688
+ KeyType: keyType,
10689
+ PageNumber: 1,
10690
+ PageSize: 50,
10691
+ });
10692
+ return extractApiKeyList(result);
10693
+ }
10694
+ catch {
10695
+ return null;
10696
+ }
10697
+ };
10698
+ const listApiKeyIds = async (cloudbase, keyType) => {
10699
+ const records = await listApiKeyRecords(cloudbase, keyType);
10700
+ if (records === null) {
10701
+ return null;
10702
+ }
10703
+ return new Set(records
10704
+ .map((item) => (typeof item.KeyId === "string" ? item.KeyId : null))
10705
+ .filter((item) => item !== null));
10706
+ };
9967
10707
  const describePublishableKey = async (cloudbase, envId) => {
9968
10708
  const result = await cloudbase.env.describeApiKeyList({ KeyType: "publish_key", PageNumber: 1, PageSize: 10 });
9969
10709
  return {
@@ -10003,12 +10743,14 @@ function registerAppAuthTools(server) {
10003
10743
  const loginMethods = buildLoginMethods(result);
10004
10744
  const nextStep = buildLoginConfigNextStep(loginMethods);
10005
10745
  const webSdkHint = buildWebSdkHint(loginMethods);
10746
+ const smsHint = buildSmsHint(loginMethods);
10006
10747
  return buildSupabaseLikeAuthResponse({
10007
10748
  success: true,
10008
10749
  envId,
10009
10750
  loginMethods,
10010
10751
  ...(nextStep ? { next_step: nextStep } : {}),
10011
10752
  ...(webSdkHint ? { webSdkHint } : {}),
10753
+ ...(smsHint ? { smsHint } : {}),
10012
10754
  });
10013
10755
  }
10014
10756
  case "listProviders": {
@@ -10084,7 +10826,7 @@ function registerAppAuthTools(server) {
10084
10826
  }));
10085
10827
  server.registerTool?.("manageAppAuth", {
10086
10828
  title: "管理 CloudBase 应用认证配置",
10087
- description: "CloudBase 应用侧认证配置写入口。用于修改登录方式、provider、client 配置,确保 publishable key,以及创建或删除 API key、自定义登录密钥。⚠️ 本工具为管理端配置工具,不执行用户登录。当任务要求编写客户端登录代码时(例如「用 JS SDK 登录」),应先通过本工具完成配置(如启用 usernamePassword、获取 publishable key),再在项目代码中编写 @cloudbase/js-sdk 客户端登录代码(如 auth.signInWithPassword()),而非使用本工具完成登录。若前端要接受普通用户名样式标识符,应先执行 action=patchLoginStrategy 并传入 patch={ usernamePassword: true },再实现对应前端登录逻辑。",
10829
+ description: "CloudBase 应用侧认证配置写入口。用于修改登录方式、provider、client 配置,确保 publishable key,以及创建或删除 API key、自定义登录密钥。⚠️ 本工具为管理端配置工具,不执行用户登录。当任务要求编写客户端登录代码时(例如「用 JS SDK 登录」),应先通过本工具完成配置(如启用 usernamePassword、获取 publishable key),再在项目代码中编写 @cloudbase/js-sdk 客户端登录代码(如 auth.signInWithPassword()),而非使用本工具完成登录。若前端要接受普通用户名样式标识符,应先执行 action=patchLoginStrategy 并传入 patch={ usernamePassword: true },再实现对应前端登录逻辑。⚠️ 短信验证码登录(patch={ phone: true })使用云开发默认短信通道,开启后即可收发验证码,不需要配置短信签名/模板/自定义 Provider;仅当需要自定义模板/签名或更换短信服务商时才需配置 SmsVerificationConfig 或自定义短信通道。⚠️ action=createApiKey 返回体中的 created 字段表示是否真正新建:created=false 说明复用了环境中已存在的 key,此时 keyName/expireIn 入参不会生效,返回的 keyName/expireAt 均为服务端真实值,并会附带 warnings,切勿把它当作临时凭证分发。",
10088
10830
  inputSchema: {
10089
10831
  action: zod_1.z.enum(MANAGE_APP_AUTH_ACTIONS),
10090
10832
  patch: zod_1.z
@@ -10109,8 +10851,16 @@ function registerAppAuthTools(server) {
10109
10851
  .enum(APP_AUTH_KEY_TYPES)
10110
10852
  .optional()
10111
10853
  .describe("createApiKey 时的 API key 类型,默认 publish_key"),
10112
- keyName: zod_1.z.string().optional().describe("createApiKey 时的 API key 名称"),
10113
- expireIn: zod_1.z.number().int().min(0).optional().describe("createApiKey 时的有效期,单位秒;0 表示不过期"),
10854
+ keyName: zod_1.z
10855
+ .string()
10856
+ .optional()
10857
+ .describe("createApiKey 时的 API key 名称;服务端可能忽略该值(如 publish_key 每环境唯一时),返回体中的 keyName 一律为服务端实际存储的名称"),
10858
+ expireIn: zod_1.z
10859
+ .number()
10860
+ .int()
10861
+ .min(0)
10862
+ .optional()
10863
+ .describe("createApiKey 时的有效期,单位秒;0 表示不过期。复用已有 key 时该值不生效,此时返回体会带 created=false 与 warnings"),
10114
10864
  keyId: zod_1.z.string().optional().describe("deleteApiKey 时的 API key 唯一标识"),
10115
10865
  },
10116
10866
  annotations: {
@@ -10142,12 +10892,14 @@ function registerAppAuthTools(server) {
10142
10892
  const loginMethods = buildLoginMethods(confirmed);
10143
10893
  const nextStep = buildLoginConfigNextStep(loginMethods);
10144
10894
  const webSdkHint = buildWebSdkHint(loginMethods);
10895
+ const smsHint = buildSmsHint(loginMethods);
10145
10896
  return buildSupabaseLikeAuthResponse({
10146
10897
  success: true,
10147
10898
  envId,
10148
10899
  loginMethods,
10149
10900
  ...(nextStep ? { next_step: nextStep } : {}),
10150
10901
  ...(webSdkHint ? { webSdkHint } : {}),
10902
+ ...(smsHint ? { smsHint } : {}),
10151
10903
  });
10152
10904
  }
10153
10905
  case "addProvider": {
@@ -10235,6 +10987,7 @@ function registerAppAuthTools(server) {
10235
10987
  }
10236
10988
  case "createApiKey": {
10237
10989
  const effectiveKeyType = keyType ?? "publish_key";
10990
+ const before = await listApiKeyIds(cloudbase, effectiveKeyType);
10238
10991
  const result = await cloudbase.env.createApiKey({
10239
10992
  KeyType: effectiveKeyType,
10240
10993
  ...(keyName ? { KeyName: keyName } : {}),
@@ -10242,19 +10995,44 @@ function registerAppAuthTools(server) {
10242
10995
  });
10243
10996
  (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
10244
10997
  const createApiKeyResult = normalizePlainObject(result, "createApiKeyResult") ?? {};
10998
+ const resultKeyId = typeof createApiKeyResult.KeyId === "string" ? createApiKeyResult.KeyId : null;
10999
+ const created = before === null || resultKeyId === null ? null : !before.has(resultKeyId);
11000
+ // The backend is the only source of truth for the stored name / expiry:
11001
+ // re-read the key record instead of echoing back the request parameters.
11002
+ const serverRecord = resultKeyId
11003
+ ? (await listApiKeyRecords(cloudbase, effectiveKeyType))?.find((item) => item.KeyId === resultKeyId) ?? null
11004
+ : null;
11005
+ const keyNameSource = serverRecord ?? createApiKeyResult;
11006
+ const resolvedKeyName = getNonEmptyString(keyNameSource.Name) ??
11007
+ getNonEmptyString(keyNameSource.KeyName) ??
11008
+ null;
11009
+ const resolvedExpireAt = getNonEmptyString(serverRecord?.ExpireAt) ??
11010
+ getNonEmptyString(createApiKeyResult.ExpireAt) ??
11011
+ null;
11012
+ const resolvedCreatedAt = getNonEmptyString(serverRecord?.CreateAt) ??
11013
+ getNonEmptyString(createApiKeyResult.CreateAt) ??
11014
+ null;
11015
+ const warnings = [];
11016
+ if (created === false) {
11017
+ warnings.push(`keyType=${effectiveKeyType} 未创建新的 key,返回的是环境中已存在的 key(keyId=${resultKeyId})。若该类型每个环境唯一,请改用 action=ensurePublishableKey 语义理解此结果。`);
11018
+ }
11019
+ if (keyName && resolvedKeyName !== null && resolvedKeyName !== keyName) {
11020
+ warnings.push(`请求的 keyName="${keyName}" 未生效,服务端实际存储的名称为 "${resolvedKeyName}"。`);
11021
+ }
11022
+ if (typeof expireIn === "number" && created === false) {
11023
+ warnings.push(`请求的 expireIn=${expireIn} 未生效,返回的 key 使用其原有过期时间 ${resolvedExpireAt ?? "unknown"}。请勿将其视为临时凭证。`);
11024
+ }
10245
11025
  return {
10246
11026
  success: true,
10247
11027
  envId,
10248
11028
  keyType: effectiveKeyType,
10249
- keyId: typeof result.KeyId === "string" ? result.KeyId : null,
10250
- keyName: typeof result.Name === "string"
10251
- ? result.Name
10252
- : typeof createApiKeyResult.KeyName === "string"
10253
- ? createApiKeyResult.KeyName
10254
- : keyName ?? null,
10255
- apiKey: typeof result.ApiKey === "string" ? result.ApiKey : null,
10256
- expireAt: typeof result.ExpireAt === "string" ? result.ExpireAt : null,
10257
- createdAt: typeof result.CreateAt === "string" ? result.CreateAt : null,
11029
+ keyId: resultKeyId,
11030
+ keyName: resolvedKeyName,
11031
+ apiKey: typeof createApiKeyResult.ApiKey === "string" ? createApiKeyResult.ApiKey : null,
11032
+ expireAt: resolvedExpireAt,
11033
+ createdAt: resolvedCreatedAt,
11034
+ ...(typeof created === "boolean" ? { created } : {}),
11035
+ ...(warnings.length > 0 ? { warnings } : {}),
10258
11036
  };
10259
11037
  }
10260
11038
  case "deleteApiKey": {
@@ -10356,7 +11134,7 @@ class TelemetryReporter {
10356
11134
  const nodeVersion = process.version; // Node.js版本
10357
11135
  const arch = os_1.default.arch(); // 系统架构
10358
11136
  // 从构建时注入的版本号获取MCP版本信息
10359
- const mcpVersion = process.env.npm_package_version || "2.25.2" || 0;
11137
+ const mcpVersion = process.env.npm_package_version || "2.25.4" || 0;
10360
11138
  return {
10361
11139
  userAgent: `${osType} ${osRelease} ${arch} ${nodeVersion} CloudBase-MCP/${mcpVersion}`,
10362
11140
  deviceId: this.deviceId,
@@ -10868,7 +11646,7 @@ const TRIGGER_SCHEMA = zod_1.z.object({
10868
11646
  const CREATE_FUNCTION_SCHEMA = zod_1.z.object({
10869
11647
  name: zod_1.z.string().describe("函数名称"),
10870
11648
  type: zod_1.z.enum(["Event", "HTTP"]).optional().describe("函数类型"),
10871
- protocolType: zod_1.z.enum(["HTTP", "WS"]).optional().describe("HTTP 云函数协议类型"),
11649
+ protocolType: zod_1.z.enum(["WS"]).optional().describe("HTTP 函数访问协议,当前仅支持 WebSockets,取值为 WS(配合 protocolParams.wsParams 使用)。普通 HTTP 函数不要传此字段;传其他值(如 HTTP)会报 InvalidParameterValue.ProtocolType。"),
10872
11650
  protocolParams: zod_1.z
10873
11651
  .object({
10874
11652
  wsParams: zod_1.z
@@ -12337,6 +13115,68 @@ function isSchemaDdlRisk(risk, sql) {
12337
13115
  function buildLocalMigrationFileHint(version, name) {
12338
13116
  return `migrations/${version}_${name}.sql`;
12339
13117
  }
13118
+ /** How many recent migration records to scan when verifying a freshly pushed version. */
13119
+ const MIGRATION_VERIFY_LIMIT = 100;
13120
+ /**
13121
+ * Collect every migration version mentioned anywhere in a migration-list API response.
13122
+ * The response shape is not strongly typed, so walk it generically and pick up any
13123
+ * `Version` / `MigrationVersion` string field instead of guessing a single container key.
13124
+ */
13125
+ function collectMigrationVersions(value, found = new Set()) {
13126
+ if (Array.isArray(value)) {
13127
+ for (const item of value) {
13128
+ collectMigrationVersions(item, found);
13129
+ }
13130
+ return found;
13131
+ }
13132
+ if (value && typeof value === "object") {
13133
+ for (const [key, child] of Object.entries(value)) {
13134
+ if ((key === "Version" || key === "MigrationVersion") && typeof child === "string" && child.trim()) {
13135
+ found.add(child.trim());
13136
+ }
13137
+ else {
13138
+ collectMigrationVersions(child, found);
13139
+ }
13140
+ }
13141
+ }
13142
+ return found;
13143
+ }
13144
+ /** Brief retries before concluding a pushed migration never landed (Push can be async). */
13145
+ const MIGRATION_VERIFY_ATTEMPTS = 4;
13146
+ const MIGRATION_VERIFY_DELAY_MS = 1500;
13147
+ /**
13148
+ * Confirm a pushed migration version is present in the remote migration history.
13149
+ *
13150
+ * `PushPGUserMigrations` can return a TaskId without the migration actually being
13151
+ * applied, so the raw API response is not sufficient evidence of success. Retries
13152
+ * briefly to tolerate async application, then returns `true`/`false` when the
13153
+ * history could be read, or `null` when verification itself failed (in which case
13154
+ * the caller must not claim the migration is applied).
13155
+ */
13156
+ async function verifyMigrationApplied(context, version, cloudBaseOptions) {
13157
+ let lastError;
13158
+ let sawSuccessfulList = false;
13159
+ for (let attempt = 1; attempt <= MIGRATION_VERIFY_ATTEMPTS; attempt++) {
13160
+ try {
13161
+ const history = await callPgMigrationApi(context, "ListPGUserMigrations", { Limit: MIGRATION_VERIFY_LIMIT }, cloudBaseOptions);
13162
+ sawSuccessfulList = true;
13163
+ if (collectMigrationVersions(history).has(version)) {
13164
+ return { applied: true };
13165
+ }
13166
+ }
13167
+ catch (error) {
13168
+ lastError = error instanceof Error ? error.message : String(error);
13169
+ // Keep retrying: a transient list failure should not immediately fail verification.
13170
+ }
13171
+ if (attempt < MIGRATION_VERIFY_ATTEMPTS) {
13172
+ await sleep(MIGRATION_VERIFY_DELAY_MS);
13173
+ }
13174
+ }
13175
+ if (sawSuccessfulList) {
13176
+ return { applied: false };
13177
+ }
13178
+ return { applied: null, error: lastError };
13179
+ }
12340
13180
  const MIGRATION_VERSION_REQUIRED_MESSAGE = "migrationVersion is required (14-digit UTC timestamp YYYYMMDDHHMMSS). " +
12341
13181
  "Decide the version first, write local file migrations/<version>_<migrationName>.sql, " +
12342
13182
  "then call planMigration/applyMigration with the same migrationVersion and migrationName.";
@@ -13209,6 +14049,49 @@ async function handleApplyMigration(args, context, deps, cloudBaseOptions) {
13209
14049
  }
13210
14050
  try {
13211
14051
  const result = await callPgMigrationApi(context, "PushPGUserMigrations", params, cloudBaseOptions);
14052
+ // PushPGUserMigrations may return a TaskId without the migration having taken
14053
+ // effect. Confirm against the remote history before reporting success, so callers
14054
+ // never get a false-positive success for a silently dropped migration.
14055
+ const verification = await verifyMigrationApplied(context, version, cloudBaseOptions);
14056
+ if (verification.applied === false) {
14057
+ return buildPgToolResult({
14058
+ success: false,
14059
+ errorCode: "MIGRATION_NOT_APPLIED",
14060
+ data: {
14061
+ migrationVersion: version,
14062
+ migrationName: args.migrationName,
14063
+ localFileHint,
14064
+ apiResult: result,
14065
+ verified: false,
14066
+ },
14067
+ message: `PushPGUserMigrations returned without error, but migrationVersion=${version} is not present in the remote migration history, ` +
14068
+ "so the migration did NOT take effect. Do not assume the schema change is applied. " +
14069
+ "Re-check the SQL and migrationVersion, inspect the migration with action=migrationDetail, and retry action=applyMigration. " +
14070
+ "If the schema change is urgent you may fall back to action=execute with allowDdlViaExecute=true, but that bypasses migration history.",
14071
+ nextActions: [
14072
+ buildNextAction(MANAGE_PG_DATABASE, "listMigrations", "Inspect the remote migration history to confirm the migration is missing.", { action: "listMigrations", limit: 20 }),
14073
+ buildNextAction(MANAGE_PG_DATABASE, "migrationDetail", "Inspect the backend record for this migrationVersion to find why it was not applied.", { action: "migrationDetail", migrationVersion: version }),
14074
+ ],
14075
+ });
14076
+ }
14077
+ if (verification.applied === null) {
14078
+ return buildPgToolResult({
14079
+ success: false,
14080
+ errorCode: "MIGRATION_VERIFICATION_FAILED",
14081
+ data: {
14082
+ migrationVersion: version,
14083
+ migrationName: args.migrationName,
14084
+ localFileHint,
14085
+ apiResult: result,
14086
+ verified: null,
14087
+ },
14088
+ message: `PushPGUserMigrations was submitted, but verifying migrationVersion=${version} against the remote history failed: ${verification.error}. ` +
14089
+ "The migration may or may not have been applied — verify with action=listMigrations before running any dependent SQL.",
14090
+ nextActions: [
14091
+ buildNextAction(MANAGE_PG_DATABASE, "listMigrations", "Manually verify whether the remote migration history records this migrationVersion.", { action: "listMigrations", limit: 20 }),
14092
+ ],
14093
+ });
14094
+ }
13212
14095
  return buildPgToolResult({
13213
14096
  success: true,
13214
14097
  data: {
@@ -13216,11 +14099,9 @@ async function handleApplyMigration(args, context, deps, cloudBaseOptions) {
13216
14099
  migrationName: args.migrationName,
13217
14100
  localFileHint,
13218
14101
  apiResult: result,
14102
+ verified: true,
13219
14103
  },
13220
- message: `Migrations applied via PushPGUserMigrations. Ensure local file ${localFileHint} exists and matches.`,
13221
- nextActions: [
13222
- buildNextAction(MANAGE_PG_DATABASE, "listMigrations", "Verify the remote migration history records the same migrationVersion.", { action: "listMigrations", limit: 20 }),
13223
- ],
14104
+ message: `Migrations applied via PushPGUserMigrations and verified present in the remote migration history. Ensure local file ${localFileHint} exists and matches.`,
13224
14105
  });
13225
14106
  }
13226
14107
  catch (error) {
@@ -13499,7 +14380,7 @@ function registerPGDatabaseTools(server, providedDeps) {
13499
14380
  inputSchema: {
13500
14381
  action: zod_1.z
13501
14382
  .enum(MANAGE_ACTIONS)
13502
- .describe("操作类型:execute=执行已确认的写入 SQL(DML/GRANT/RLS;schema DDL 默认拒绝,需 allowDdlViaExecute=true);dryRun=只分析 SQL 风险不执行;planMigration=预览迁移计划(需 migrationName + migrationVersion + sql);applyMigration=应用迁移,建表/改 schema 首选(需 migrationName + migrationVersion + sql + confirm=true);listMigrations=查询已应用的 Migration 列表(可传 limit/offset 分页);migrationDetail=查看单条 Migration 详情(需 migrationVersion);rollbackMigration=回滚最近 N 条 Migration(需 lastN + confirm=true);repairMigration=修复 Migration 历史记录(需 migrationVersion + migrationName + repairStatus + repairReason)"),
14383
+ .describe("操作类型:execute=执行已确认的写入 SQL(DML/GRANT/RLS;schema DDL 默认拒绝,需 allowDdlViaExecute=true);dryRun=只分析 SQL 风险不执行;planMigration=预览迁移计划(需 migrationName + migrationVersion + sql);applyMigration=应用迁移,建表/改 schema 首选(需 migrationName + migrationVersion + sql + confirm=true;成功返回前会自动校验该 migrationVersion 已落入远端迁移历史,未落库时返回 success=false 且 errorCode=MIGRATION_NOT_APPLIED);listMigrations=查询已应用的 Migration 列表(可传 limit/offset 分页);migrationDetail=查看单条 Migration 详情(需 migrationVersion);rollbackMigration=回滚最近 N 条 Migration(需 lastN + confirm=true);repairMigration=修复 Migration 历史记录(需 migrationVersion + migrationName + repairStatus + repairReason)"),
13503
14384
  sql: zod_1.z
13504
14385
  .string()
13505
14386
  .optional()
@@ -14735,7 +15616,7 @@ function registerSetupTools(server) {
14735
15616
  server.registerTool("downloadTemplate", {
14736
15617
  title: "下载项目模板",
14737
15618
  description: `自动下载并部署CloudBase项目模板。
14738
- **Note**: Call this tool when the user requests to create a new project using a CloudBase template.\n\n支持的模板:\n- react: React + CloudBase 全栈应用模板\n- vue: Vue + CloudBase 全栈应用模板\n- miniprogram: 微信小程序 + 云开发模板 \n- uniapp: UniApp + CloudBase 跨端应用模板\n- rules: 只包含AI编辑器配置文件(包含Cursor、WindSurf、CodeBuddy等所有主流编辑器配置),适合在已有项目中补充AI编辑器配置\n\n支持的IDE类型:\n- all: 下载所有IDE配置\n- cursor: Cursor AI编辑器\n- 其他IDE类型见下方列表\n\n注意:如果未传入 ide 参数且无法从环境变量检测到 IDE,将提示错误并要求传入 ide 参数\n- windsurf: WindSurf AI编辑器\n- codebuddy: CodeBuddy AI编辑器\n- claude-code: Claude Code AI编辑器\n- cline: Cline AI编辑器\n- gemini-cli: Gemini CLI\n- opencode: OpenCode AI编辑器\n- qwen-code: 通义灵码\n- baidu-comate: 百度Comate\n- openai-codex-cli: OpenAI Codex CLI\n- augment-code: Augment Code\n- github-copilot: GitHub Copilot\n- roocode: RooCode AI编辑器\n- tongyi-lingma: 通义灵码\n- trae: Trae AI编辑器\n- qoder: Qoder AI编辑器\n- antigravity: Google Antigravity AI编辑器\n- vscode: Visual Studio Code\n- kiro: Kiro AI编辑器\n- aider: Aider AI编辑器\n\n特别说明:\n- rules 模板会自动包含当前 mcp 版本号信息(版本号:${ true ? "2.25.2" : 0}),便于后续维护和版本追踪\n- 下载 rules 模板时,如果项目中已存在 README.md 文件,系统会自动保护该文件不被覆盖(除非设置 overwrite=true)`,
15619
+ **Note**: Call this tool when the user requests to create a new project using a CloudBase template.\n\n支持的模板:\n- react: React + CloudBase 全栈应用模板\n- vue: Vue + CloudBase 全栈应用模板\n- miniprogram: 微信小程序 + 云开发模板 \n- uniapp: UniApp + CloudBase 跨端应用模板\n- rules: 只包含AI编辑器配置文件(包含Cursor、WindSurf、CodeBuddy等所有主流编辑器配置),适合在已有项目中补充AI编辑器配置\n\n支持的IDE类型:\n- all: 下载所有IDE配置\n- cursor: Cursor AI编辑器\n- 其他IDE类型见下方列表\n\n注意:如果未传入 ide 参数且无法从环境变量检测到 IDE,将提示错误并要求传入 ide 参数\n- windsurf: WindSurf AI编辑器\n- codebuddy: CodeBuddy AI编辑器\n- claude-code: Claude Code AI编辑器\n- cline: Cline AI编辑器\n- gemini-cli: Gemini CLI\n- opencode: OpenCode AI编辑器\n- qwen-code: 通义灵码\n- baidu-comate: 百度Comate\n- openai-codex-cli: OpenAI Codex CLI\n- augment-code: Augment Code\n- github-copilot: GitHub Copilot\n- roocode: RooCode AI编辑器\n- tongyi-lingma: 通义灵码\n- trae: Trae AI编辑器\n- qoder: Qoder AI编辑器\n- antigravity: Google Antigravity AI编辑器\n- vscode: Visual Studio Code\n- kiro: Kiro AI编辑器\n- aider: Aider AI编辑器\n\n特别说明:\n- rules 模板会自动包含当前 mcp 版本号信息(版本号:${ true ? "2.25.4" : 0}),便于后续维护和版本追踪\n- 下载 rules 模板时,如果项目中已存在 README.md 文件,系统会自动保护该文件不被覆盖(除非设置 overwrite=true)`,
14739
15620
  inputSchema: {
14740
15621
  template: zod_1.z
14741
15622
  .enum(["react", "vue", "miniprogram", "uniapp", "rules"])
@@ -15662,6 +16543,17 @@ async function checkAndCreateFreeEnv(cloudbase, context) {
15662
16543
  hasInitTcbError: !!newContext.initTcbError,
15663
16544
  initTcbError: newContext.initTcbError
15664
16545
  });
16546
+ // User-facing notice emitted at the entry: inform the user that an automatic
16547
+ // free-env creation is being attempted. Informational only — no confirm.
16548
+ // Built once up-front so every return path can surface the same notice.
16549
+ const userNotice = [
16550
+ "系统检测到您当前没有可用的 CloudBase 环境,将自动尝试为您创建一个免费环境。",
16551
+ "创建依据:通过 NewUser / ReturningUser / BaasFree 等优惠活动资格检查;",
16552
+ "环境别名:ai-native(默认);",
16553
+ "费用说明:该环境为免费活动赠送,创建过程不会产生费用;如不符合免费条件,将引导您前往购买页;",
16554
+ "流程说明:此为自动流程,无需您确认;创建成功后将自动绑定到当前会话。"
16555
+ ].join("\n");
16556
+ (0, logger_js_1.debug)('[env-setup] User notice prepared:', { userNotice });
15665
16557
  try {
15666
16558
  // Step 1: Query promotional activities
15667
16559
  (0, logger_js_1.debug)('[env-setup] Checking promotional activity eligibility...');
@@ -15701,7 +16593,8 @@ async function checkAndCreateFreeEnv(cloudbase, context) {
15701
16593
  };
15702
16594
  return {
15703
16595
  success: false,
15704
- context: newContext
16596
+ context: newContext,
16597
+ userNotice
15705
16598
  };
15706
16599
  }
15707
16600
  (0, logger_js_1.debug)('[env-setup] User is eligible for free environment, attempting to create...');
@@ -15766,7 +16659,8 @@ async function checkAndCreateFreeEnv(cloudbase, context) {
15766
16659
  };
15767
16660
  return {
15768
16661
  success: false,
15769
- context: newContext
16662
+ context: newContext,
16663
+ userNotice
15770
16664
  };
15771
16665
  }
15772
16666
  // Report create success
@@ -15780,7 +16674,8 @@ async function checkAndCreateFreeEnv(cloudbase, context) {
15780
16674
  return {
15781
16675
  success: true,
15782
16676
  envId: envId.trim(), // Ensure no whitespace
15783
- context: newContext
16677
+ context: newContext,
16678
+ userNotice
15784
16679
  };
15785
16680
  }
15786
16681
  catch (createErr) {
@@ -15839,7 +16734,8 @@ async function checkAndCreateFreeEnv(cloudbase, context) {
15839
16734
  });
15840
16735
  return {
15841
16736
  success: false,
15842
- context: newContext
16737
+ context: newContext,
16738
+ userNotice
15843
16739
  };
15844
16740
  }
15845
16741
  }
@@ -15860,7 +16756,8 @@ async function checkAndCreateFreeEnv(cloudbase, context) {
15860
16756
  });
15861
16757
  return {
15862
16758
  success: false,
15863
- context: newContext
16759
+ context: newContext,
16760
+ userNotice
15864
16761
  };
15865
16762
  }
15866
16763
  }
@@ -18601,6 +19498,7 @@ const QUERY_ACTIONS = [
18601
19498
  "describeTaskStatus",
18602
19499
  "getInstanceInfo",
18603
19500
  "describeInstance",
19501
+ "getConnectionInfo",
18604
19502
  ];
18605
19503
  const MANAGE_ACTIONS = [
18606
19504
  "provisionMySQL",
@@ -18608,6 +19506,17 @@ const MANAGE_ACTIONS = [
18608
19506
  "runStatement",
18609
19507
  "initializeSchema",
18610
19508
  ];
19509
+ function sanitizeInstanceInfo(instanceInfo) {
19510
+ return {
19511
+ exists: instanceInfo.exists,
19512
+ envId: instanceInfo.envId,
19513
+ instanceId: instanceInfo.instanceId,
19514
+ schema: instanceInfo.schema,
19515
+ rawStatus: instanceInfo.rawStatus,
19516
+ status: instanceInfo.status,
19517
+ ...(instanceInfo.clusterId ? { clusterId: instanceInfo.clusterId } : {}),
19518
+ };
19519
+ }
18611
19520
  function buildNextAction(tool, action, reason, suggestedArgs) {
18612
19521
  return {
18613
19522
  tool,
@@ -19056,11 +19965,12 @@ async function handleDescribeTaskStatus(args, context) {
19056
19965
  }
19057
19966
  async function handleGetInstanceInfo(context) {
19058
19967
  const instanceInfo = await getSqlInstanceInfo(context);
19968
+ const sanitized = sanitizeInstanceInfo(instanceInfo);
19059
19969
  return buildSqlToolResult({
19060
19970
  success: true,
19061
- data: instanceInfo,
19971
+ data: sanitized,
19062
19972
  message: instanceInfo.exists
19063
- ? "Resolved current SQL database instance context."
19973
+ ? "Resolved current SQL database instance context (lifecycle only; connection credentials are omitted). Prefer SDK or runQuery/runStatement for app data access. Use getConnectionInfo only for explicit TCP migration."
19064
19974
  : "No SQL database instance is currently available for this environment.",
19065
19975
  nextActions: instanceInfo.exists
19066
19976
  ? undefined
@@ -19069,6 +19979,33 @@ async function handleGetInstanceInfo(context) {
19069
19979
  ],
19070
19980
  });
19071
19981
  }
19982
+ async function handleGetConnectionInfo(context) {
19983
+ const instanceInfo = await getSqlInstanceInfo(context);
19984
+ if (!instanceInfo.exists) {
19985
+ return buildSqlToolResult({
19986
+ success: false,
19987
+ errorCode: "MYSQL_NOT_CREATED",
19988
+ data: sanitizeInstanceInfo(instanceInfo),
19989
+ message: "No MySQL instance exists for the current environment, so connection details cannot be returned.",
19990
+ nextActions: [
19991
+ buildNextAction(MANAGE_MYSQL_DATABASE, "provisionMySQL", "Provision MySQL before requesting connection details.", { action: "provisionMySQL", confirm: true }),
19992
+ ],
19993
+ });
19994
+ }
19995
+ return buildSqlToolResult({
19996
+ success: true,
19997
+ data: {
19998
+ ...sanitizeInstanceInfo(instanceInfo),
19999
+ // Full backend passthrough for explicit TCP migration only (may include credentials).
20000
+ clusterDetail: instanceInfo.clusterDetail,
20001
+ createResult: instanceInfo.createResult,
20002
+ },
20003
+ message: "Returned raw MySQL connection/cluster payload for explicit TCP migration only. Prefer CloudBase SDK or queryMysqlDatabase(runQuery)/manageMysqlDatabase(runStatement) for normal app CRUD — do not treat this as the default data path.",
20004
+ nextActions: [
20005
+ buildNextAction(QUERY_MYSQL_DATABASE, "runQuery", "Prefer platform-delegated read-only SQL instead of embedding TCP credentials in app code.", { action: "runQuery", sql: "SELECT 1" }),
20006
+ ],
20007
+ });
20008
+ }
19072
20009
  async function handleProvisionMySQL(args, context) {
19073
20010
  if (args.confirm !== true) {
19074
20011
  return buildSqlToolResult({
@@ -19086,7 +20023,7 @@ async function handleProvisionMySQL(args, context) {
19086
20023
  existing.status === "RUNNING") {
19087
20024
  return buildSqlToolResult({
19088
20025
  success: true,
19089
- data: existing,
20026
+ data: sanitizeInstanceInfo(existing),
19090
20027
  message: "A SQL database instance already exists for the current environment.",
19091
20028
  nextActions: existing.status === "READY"
19092
20029
  ? [
@@ -19419,11 +20356,11 @@ function registerSQLDatabaseTools(server) {
19419
20356
  };
19420
20357
  server.registerTool?.(QUERY_MYSQL_DATABASE, {
19421
20358
  title: "查询 CloudBase MySQL 数据库状态或执行只读 SQL",
19422
- description: "查询 CloudBase MySQL 数据库信息。支持执行只读 SQL、查询 MySQL 开通结果、查询 MySQL 任务状态,以及获取当前实例上下文信息。",
20359
+ description: "查询 CloudBase MySQL 数据库信息。支持执行只读 SQL、查询 MySQL 开通结果、查询 MySQL 任务状态,以及获取当前实例生命周期上下文。标准 getInstanceInfo/describeInstance 不返回连接凭据;仅 getConnectionInfo 透传原始连接/集群载荷(含可能的凭据),且仅用于显式 TCP 迁移。业务 CRUD 优先使用 SDK 或 runQuery/runStatement。",
19423
20360
  inputSchema: {
19424
20361
  action: zod_1.z
19425
20362
  .enum(QUERY_ACTIONS)
19426
- .describe("runQuery=execute read-only SQL; describeCreateResult=query CreateMySQL result; describeTaskStatus=query MySQL task status; getInstanceInfo=get current SQL instance context; describeInstance=alias of getInstanceInfo"),
20363
+ .describe("runQuery=execute read-only SQL; describeCreateResult=query CreateMySQL result; describeTaskStatus=query MySQL task status; getInstanceInfo=get lifecycle context without connection credentials; describeInstance=alias of getInstanceInfo; getConnectionInfo=passthrough raw connection/cluster payload including possible credentials (TCP migration exception only)"),
19427
20364
  sql: zod_1.z
19428
20365
  .string()
19429
20366
  .optional()
@@ -19459,6 +20396,8 @@ function registerSQLDatabaseTools(server) {
19459
20396
  case "getInstanceInfo":
19460
20397
  case "describeInstance":
19461
20398
  return handleGetInstanceInfo(context);
20399
+ case "getConnectionInfo":
20400
+ return handleGetConnectionInfo(context);
19462
20401
  default:
19463
20402
  throw new Error(`Unsupported SQL query action: ${args.action}`);
19464
20403
  }