@cloudbase/cloudbase-mcp 2.25.1 → 2.25.3

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.cjs CHANGED
@@ -2218,15 +2218,20 @@ async function prepareAuthEnvironment(params) {
2218
2218
  if (setupContext.createFreeEnvAttempted) {
2219
2219
  envSetupActions.push("create_free_env");
2220
2220
  }
2221
+ // Surface the user-facing notice emitted at checkAndCreateFreeEnv entry.
2222
+ // Informational only — no confirm required. Prepend to the final message so
2223
+ // the user knows an automatic free-env creation was attempted.
2224
+ const userNotice = createResult.userNotice?.trim() || "";
2221
2225
  if (createResult.success && createResult.envId) {
2222
2226
  await cloudbase_manager_js_1.envManager.setEnvId(createResult.envId);
2227
+ const successMessage = `当前已登录,已自动创建并绑定环境: ${createResult.envId}`;
2223
2228
  return {
2224
2229
  currentEnvId: createResult.envId,
2225
2230
  envStatus: "READY",
2226
2231
  envCandidates: [],
2227
2232
  envSetupStatus: "AUTO_CREATED",
2228
2233
  envSetupActions: dedupeActions(envSetupActions),
2229
- message: `当前已登录,已自动创建并绑定环境: ${createResult.envId}`,
2234
+ message: userNotice ? `${userNotice}\n${successMessage}` : successMessage,
2230
2235
  nextStep: (0, tool_result_js_1.buildAuthNextStep)("status", {
2231
2236
  suggestedArgs: { action: "status" },
2232
2237
  }),
@@ -2245,6 +2250,9 @@ async function prepareAuthEnvironment(params) {
2245
2250
  message: "环境创建失败,请稍后重试或手动创建环境。",
2246
2251
  helpUrl: "https://buy.cloud.tencent.com/lowcode?buyType=tcb&channel=mcp",
2247
2252
  });
2253
+ const failureMessage = userNotice
2254
+ ? `${userNotice}\n${createFailure.message}`
2255
+ : createFailure.message;
2248
2256
  return {
2249
2257
  currentEnvId: null,
2250
2258
  envStatus: "NONE",
@@ -2252,7 +2260,7 @@ async function prepareAuthEnvironment(params) {
2252
2260
  envSetupStatus: "ACTION_REQUIRED",
2253
2261
  envSetupActions: dedupeActions(envSetupActions),
2254
2262
  envSetupFailure: createFailure,
2255
- message: createFailure.message,
2263
+ message: failureMessage,
2256
2264
  nextStep: (0, tool_result_js_1.buildAuthNextStep)("status", {
2257
2265
  suggestedArgs: { action: "status" },
2258
2266
  }),
@@ -2574,6 +2582,297 @@ function buildEnvQueryErrorMessage(error, action) {
2574
2582
  function normalizeOptionalToolBoolean(value) {
2575
2583
  return typeof value === "boolean" ? value : undefined;
2576
2584
  }
2585
+ /**
2586
+ * 解析用于询价的 region。与 cloudbase-manager.ts 一致:
2587
+ * cloudBaseOptions.region → TCB_REGION → 'ap-shanghai'。
2588
+ */
2589
+ function resolvePricingRegion(cloudBaseOptions) {
2590
+ return ((typeof cloudBaseOptions?.region === "string" && cloudBaseOptions.region) ||
2591
+ process.env.TCB_REGION ||
2592
+ "ap-shanghai");
2593
+ }
2594
+ /**
2595
+ * 从 describeBaasPackageList 查询某个 packageId 的人类可读套餐名。
2596
+ * 失败时返回 undefined,调用方降级为只显示 packageId。
2597
+ */
2598
+ async function fetchPackageTitle(manager, packageId) {
2599
+ try {
2600
+ const result = await manager.env.describeBaasPackageList({
2601
+ TargetAction: "new",
2602
+ Source: "qcloud",
2603
+ });
2604
+ const packageList = result?.PackageList || [];
2605
+ const matched = packageList.find((item) => item?.BillTags === packageId || item?.PackageName === packageId);
2606
+ if (matched) {
2607
+ return (matched.PackageTitle || matched.PackageName || matched.BillTags);
2608
+ }
2609
+ return undefined;
2610
+ }
2611
+ catch (error) {
2612
+ (0, logger_js_1.debug)("fetchPackageTitle failed", { packageId, error });
2613
+ return undefined;
2614
+ }
2615
+ }
2616
+ /**
2617
+ * 查询环境的当前计费/套餐信息(PackageName、PackageId、Region、到期时间、PayMode)。
2618
+ * 失败时返回 undefined。
2619
+ */
2620
+ async function fetchEnvBillingSummary(manager, envId) {
2621
+ try {
2622
+ // describeBillingInfo 返回 EnvBillingInfoList;从中挑出 envId 对应项
2623
+ const billingResult = await manager.env.describeBillingInfo({ EnvId: envId });
2624
+ const billingList = billingResult?.EnvBillingInfoList ||
2625
+ billingResult?.Response?.EnvBillingInfoList ||
2626
+ billingResult?.Data?.EnvBillingInfoList ||
2627
+ [];
2628
+ const matched = Array.isArray(billingList)
2629
+ ? billingList.find((item) => item?.EnvId === envId) ?? billingList[0]
2630
+ : undefined;
2631
+ if (!matched) {
2632
+ return undefined;
2633
+ }
2634
+ return {
2635
+ packageName: matched.PackageName,
2636
+ packageId: matched.PackageId,
2637
+ region: matched.Region,
2638
+ expireTime: matched.ExpireTime,
2639
+ payMode: matched.PayMode,
2640
+ isAutoRenew: matched.IsAutoRenew,
2641
+ };
2642
+ }
2643
+ catch (error) {
2644
+ (0, logger_js_1.debug)("fetchEnvBillingSummary failed", { envId, error });
2645
+ return undefined;
2646
+ }
2647
+ }
2648
+ /**
2649
+ * 询价新购价格。失败时返回 { error }。
2650
+ */
2651
+ async function calculateCreatePrice(manager, params) {
2652
+ try {
2653
+ const priceResult = await manager.env.calculatePackageCreatePrice({
2654
+ packageId: params.packageId,
2655
+ region: params.region,
2656
+ period: params.period,
2657
+ });
2658
+ return { priceResult };
2659
+ }
2660
+ catch (error) {
2661
+ const message = error instanceof Error ? error.message : String(error);
2662
+ (0, logger_js_1.debug)("calculatePackageCreatePrice failed", { params, error });
2663
+ return { error: message };
2664
+ }
2665
+ }
2666
+ /**
2667
+ * 询价续费价格。失败时返回 { error }。
2668
+ */
2669
+ async function calculateRenewPrice(manager, envId, period) {
2670
+ try {
2671
+ const priceResult = await manager.env.calculatePackageRenewPrice({
2672
+ envId,
2673
+ period,
2674
+ });
2675
+ return { priceResult };
2676
+ }
2677
+ catch (error) {
2678
+ const message = error instanceof Error ? error.message : String(error);
2679
+ (0, logger_js_1.debug)("calculatePackageRenewPrice failed", { envId, period, error });
2680
+ return { error: message };
2681
+ }
2682
+ }
2683
+ /**
2684
+ * 询价变配价格(含退款)。失败时返回 { error }。
2685
+ */
2686
+ async function calculateModifyPrice(manager, envId, newPackageId) {
2687
+ try {
2688
+ const priceResult = await manager.env.calculatePackageModifyPrice({
2689
+ envId,
2690
+ newPackageId,
2691
+ });
2692
+ return { priceResult };
2693
+ }
2694
+ catch (error) {
2695
+ const message = error instanceof Error ? error.message : String(error);
2696
+ (0, logger_js_1.debug)("calculatePackageModifyPrice failed", { envId, newPackageId, error });
2697
+ return { error: message };
2698
+ }
2699
+ }
2700
+ /**
2701
+ * 把 PriceResult 格式化为人类可读的价格摘要。
2702
+ * 返回 { summary, detail }:summary 是一行短语,detail 是多行明细。
2703
+ */
2704
+ function formatPriceSection(priceResult) {
2705
+ if (!priceResult || typeof priceResult !== "object") {
2706
+ return { summary: "询价返回为空", detail: "" };
2707
+ }
2708
+ const currency = priceResult.Currency === "USD" ? "$" : "¥";
2709
+ const realTotalCost = Number(priceResult.RealTotalCost);
2710
+ const totalCost = Number(priceResult.TotalCost);
2711
+ const unitPrice = Number(priceResult.Price);
2712
+ const timeSpan = priceResult.TimeSpan;
2713
+ const TimeUnit = priceResult.TimeUnit || "";
2714
+ const refund = priceResult.Refund ? Number(priceResult.Refund) : undefined;
2715
+ const lines = [];
2716
+ let summary = "";
2717
+ if (Number.isFinite(realTotalCost) && realTotalCost > 0) {
2718
+ summary = `预计实付 ${currency}${realTotalCost}`;
2719
+ lines.push(`- 实付总价: ${currency}${realTotalCost}`);
2720
+ }
2721
+ else if (Number.isFinite(totalCost) && totalCost > 0) {
2722
+ summary = `预计费用 ${currency}${totalCost}`;
2723
+ lines.push(`- 总价: ${currency}${totalCost}`);
2724
+ }
2725
+ if (Number.isFinite(totalCost) && totalCost > 0 && totalCost !== realTotalCost) {
2726
+ lines.push(`- 原价: ${currency}${totalCost}`);
2727
+ }
2728
+ if (Number.isFinite(unitPrice) && unitPrice > 0) {
2729
+ lines.push(`- 单价: ${currency}${unitPrice}`);
2730
+ }
2731
+ if (timeSpan !== undefined && TimeUnit) {
2732
+ lines.push(`- 时长: ${timeSpan} ${TimeUnit}`);
2733
+ }
2734
+ if (refund !== undefined && Number.isFinite(refund) && refund > 0) {
2735
+ lines.push(`- 退款: ${currency}${refund}(变配降级时退回差价)`);
2736
+ if (summary) {
2737
+ summary += `,退款 ${currency}${refund}`;
2738
+ }
2739
+ else {
2740
+ summary = `退款 ${currency}${refund}`;
2741
+ }
2742
+ }
2743
+ if (priceResult.Formula && typeof priceResult.Formula === "string") {
2744
+ lines.push(`- 计价公式: ${priceResult.Formula}`);
2745
+ }
2746
+ return {
2747
+ summary: summary || "询价返回缺少总价字段",
2748
+ detail: lines.join("\n"),
2749
+ };
2750
+ }
2751
+ /**
2752
+ * 构建释放方式说明。manageEnv 当前未提供 destroy action,
2753
+ * 指向控制台让用户手动销毁。
2754
+ */
2755
+ function buildReleaseMethodHint() {
2756
+ return {
2757
+ method: "手动销毁",
2758
+ consoleUrl: "https://console.cloud.tencent.com/tcb",
2759
+ note: '环境创建后可随时销毁以停止计费。当前 manageEnv 未提供 destroy action,请前往控制台手动销毁,或调用 manageEnv(action="listPackages") 查看其他套餐。',
2760
+ };
2761
+ }
2762
+ /**
2763
+ * manageEnv 涉及计费的官方文档链接。来源:腾讯云开发 CloudBase 公开文档。
2764
+ * 任何 confirm 消息展示这些链接前不需要再次校验 URL 真实性。
2765
+ */
2766
+ const MANAGE_ENV_DOC_LINKS = {
2767
+ // 包年包月套餐说明(个人版 / 标准版 / 企业版 / 企业高级版)
2768
+ package: "https://cloud.tencent.com/document/product/876/39093",
2769
+ // 计费能力项说明
2770
+ billingItems: "https://cloud.tencent.com/document/product/876/120713",
2771
+ // 资源点价格文档
2772
+ resourcePointPrice: "https://cloud.tencent.com/document/product/876/127357",
2773
+ // 预付费计费与到期释放(费用中心通用)
2774
+ prepayExpiry: "https://cloud.tencent.com/document/product/555/9618",
2775
+ };
2776
+ /**
2777
+ * 把文档链接渲染为多行 markdown 列表文本。
2778
+ * filter 不传时全部展示。
2779
+ */
2780
+ function renderDocLinksBlock(filter) {
2781
+ const labels = {
2782
+ package: "包年包月套餐说明",
2783
+ billingItems: "计费能力项说明",
2784
+ resourcePointPrice: "资源点价格文档",
2785
+ prepayExpiry: "预付费计费与到期释放(费用中心通用)",
2786
+ };
2787
+ const entries = (filter ?? Object.keys(MANAGE_ENV_DOC_LINKS))
2788
+ .map((k) => `- [${labels[k]}](${MANAGE_ENV_DOC_LINKS[k]})`)
2789
+ .join("\n");
2790
+ return `参考文档:\n${entries}`;
2791
+ }
2792
+ /**
2793
+ * 资源清单详细描述(对应控制台购买页"资源清单"段)。
2794
+ */
2795
+ function buildResourceListText() {
2796
+ return "资源清单:\n- 云开发环境 ×1(含 云数据库 / 云函数 / 云存储 / 静态托管 / 身份认证 等基础资源)";
2797
+ }
2798
+ /**
2799
+ * 计费项披露(对应控制台购买页"计费项"段)。
2800
+ * 此处为静态披露,调用方在 confirm 消息中拼接即可。
2801
+ */
2802
+ function buildBillingItemsText() {
2803
+ return "计费项:\n- 数据库容量/调用 · 云函数调用/资源/流量 · 存储读写/CDN · 网关/认证/API 调用 · QPS 超限按量 · 日志";
2804
+ }
2805
+ /**
2806
+ * 计费方式披露(对应控制台购买页"计费方式"段)。
2807
+ * 针对用户传入的 packageId 判断套餐类型:
2808
+ * - 含 free/activity/trial/试用 等关键字视为免费体验版
2809
+ * - 其余视为付费套餐
2810
+ */
2811
+ function buildBillingModeText(packageId) {
2812
+ const id = (packageId || "").toLowerCase();
2813
+ const isFree = id.includes("free") ||
2814
+ id.includes("activity") ||
2815
+ id.includes("trial") ||
2816
+ id.includes("试用") ||
2817
+ id.includes("体验");
2818
+ if (isFree) {
2819
+ return ("计费方式:\n- 免费体验版(每月赠送约 3000 资源点 ≈ 3 元,0 元开通)\n" +
2820
+ "- 付费套餐:个人版 / 标准版 / 企业版 / 企业高级版");
2821
+ }
2822
+ return ("计费方式:\n- 付费套餐:个人版 / 标准版 / 企业版 / 企业高级版\n" +
2823
+ "- 免费体验版通过 auth 工具自动创建;本次 manageEnv(create) 不会创建免费版");
2824
+ }
2825
+ /**
2826
+ * 资源释放方式详细说明(对应控制台购买页"资源释放方式"段)。
2827
+ * - 免费版:1 个月有效期 + 免费续期 + 停服(保留数据) + 1~7天回收站 + 释放(数据不可恢复)
2828
+ * - 付费版:到期未续费 → 停服(保留数据) + 1~7天可回收站找回 + 释放(数据不可恢复)
2829
+ * 任何时候都可在控制台主动销毁、关闭按量、退订加购资源。
2830
+ */
2831
+ function buildReleaseMethodDetailText(packageId) {
2832
+ const id = (packageId || "").toLowerCase();
2833
+ const isFree = id.includes("free") ||
2834
+ id.includes("activity") ||
2835
+ id.includes("trial") ||
2836
+ id.includes("试用") ||
2837
+ id.includes("体验");
2838
+ const lines = ["资源释放方式:\n- 可随时在控制台销毁环境、关闭按量、退订加购资源"];
2839
+ if (isFree) {
2840
+ lines.push("- 免费体验版:有效期 1 个月,到期可免费续期 1 个月;未续期则停服(保留数据)→1~7天回收站→释放(数据不可恢复)");
2841
+ }
2842
+ else {
2843
+ lines.push("- 付费套餐到期未续费:停服(保留数据)→1~7天可回收站找回→释放(数据不可恢复)");
2844
+ lines.push("- 主动销毁:随时生效;销毁前请确保已迁移或备份数据");
2845
+ }
2846
+ return lines.join("\n");
2847
+ }
2848
+ /**
2849
+ * 预计费用披露段:把询价结果 + 周期说明 + 超额按量说明组合成人类可读文本。
2850
+ */
2851
+ function buildPricingDisclosureText(packageId, priceSection, priceError, period) {
2852
+ const id = (packageId || "").toLowerCase();
2853
+ const isFree = id.includes("free") ||
2854
+ id.includes("activity") ||
2855
+ id.includes("trial") ||
2856
+ id.includes("试用") ||
2857
+ id.includes("体验");
2858
+ const lines = ["预计费用:"];
2859
+ if (isFree) {
2860
+ lines.push(`- 免费体验版:本次开通 0 元;超免费额度后需升级为付费套餐(免费版不支持开按量)`);
2861
+ lines.push("- 实际单价以资源点价格文档为准(3000 资源点 ≈ 3 元)");
2862
+ }
2863
+ else {
2864
+ lines.push(`- 付费套餐:${priceSection?.summary ?? (priceError ? `⚠️ 询价失败(${priceError}),请前往控制台确认` : "询价返回为空")}`);
2865
+ if (priceSection?.detail) {
2866
+ lines.push(priceSection.detail);
2867
+ }
2868
+ if (priceError && priceSection) {
2869
+ lines.push(`- ⚠️ 部分明细缺失:${priceError}`);
2870
+ }
2871
+ lines.push(`- 计费周期:约 ${period} 个月(包年包月),到期可续费或变配`);
2872
+ lines.push("- 超额可另开按量(次日结算),详细计费项以官方文档为准");
2873
+ }
2874
+ return lines.join("\n");
2875
+ }
2577
2876
  function resolveToolAuthOptions(server, overrides) {
2578
2877
  return (0, auth_js_1.resolveAuthOptions)({
2579
2878
  ...overrides,
@@ -3402,7 +3701,7 @@ function registerEnvTools(server) {
3402
3701
  if (server.ide !== 'wxide') {
3403
3702
  server.registerTool?.("envDomainManagement", {
3404
3703
  title: "CloudBase 环境域名管理(安全域名 / CORS 白名单)",
3405
- 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\")。",
3704
+ 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)。",
3406
3705
  inputSchema: {
3407
3706
  action: zod_1.z
3408
3707
  .enum(["create", "delete"])
@@ -3526,10 +3825,92 @@ function registerEnvTools(server) {
3526
3825
  // CreateEnv (Manager SDK / Cloud API) accepts Alias, PackageId, Resources, Period, etc.
3527
3826
  // It does NOT accept Region — region is determined by account/package, not this call.
3528
3827
  if (!confirmed) {
3828
+ // 查询套餐名和预计费用(失败降级,不阻塞 confirm 流程)
3829
+ const packageTitle = packageId
3830
+ ? await fetchPackageTitle(cloudbase, packageId)
3831
+ : undefined;
3832
+ const pricingRegion = resolvePricingRegion(cloudBaseOptions);
3833
+ const priceProbe = packageId
3834
+ ? await calculateCreatePrice(cloudbase, {
3835
+ packageId,
3836
+ region: pricingRegion,
3837
+ period: duration,
3838
+ })
3839
+ : { error: "缺少 packageId,无法询价" };
3840
+ const priceSection = priceProbe.priceResult
3841
+ ? formatPriceSection(priceProbe.priceResult)
3842
+ : null;
3843
+ const releaseMethod = buildReleaseMethodHint();
3844
+ // 组合多段披露文案(对照控制台购买页确认对话框)
3845
+ const messageLines = [];
3846
+ messageLines.push("即将为你开通云开发环境");
3847
+ messageLines.push("本操作会创建腾讯云开发环境资源。");
3848
+ messageLines.push("为付费套餐后才会产生费用;免费体验版不会立即扣费(每月赠送约 3000 资源点 ≈ 3 元)。");
3849
+ messageLines.push("请核对以下配置信息后传入 confirm=\"yes\":");
3850
+ messageLines.push(`- 别名: ${alias ?? "(未提供)"}`);
3851
+ messageLines.push(`- 套餐: ${packageId ?? "(未提供)"}` +
3852
+ (packageTitle ? `(${packageTitle})` : ""));
3853
+ messageLines.push(`- 资源类型: ${resolvedResources.join(", ")}`);
3854
+ messageLines.push(`- 时长: ${duration} 个月`);
3855
+ messageLines.push("- 说明: CreateEnv 不接受 Region 入参,环境地域由账号与套餐侧决定。");
3856
+ messageLines.push("");
3857
+ // 资源清单 / 计费项 / 计费方式
3858
+ messageLines.push(buildResourceListText());
3859
+ messageLines.push(buildBillingItemsText());
3860
+ messageLines.push(buildBillingModeText(packageId));
3861
+ messageLines.push("");
3862
+ // 预计费用
3863
+ messageLines.push(buildPricingDisclosureText(packageId, priceSection, priceProbe.error, duration));
3864
+ messageLines.push("");
3865
+ // 资源释放方式
3866
+ messageLines.push(buildReleaseMethodDetailText(packageId));
3867
+ messageLines.push("");
3868
+ // 文档链接
3869
+ messageLines.push(renderDocLinksBlock([
3870
+ "package",
3871
+ "billingItems",
3872
+ "resourcePointPrice",
3873
+ "prepayExpiry",
3874
+ ]));
3875
+ messageLines.push("");
3876
+ // 已知晓声明
3877
+ messageLines.push("☐ 我已知晓将创建付费资源及计费规则,确认按上述配置开通。");
3878
+ messageLines.push(`(如需取消或修改,请勿传 confirm="yes",改传其他参数重试)`);
3529
3879
  return (0, tool_result_js_1.buildJsonToolResult)({
3530
3880
  ok: false,
3531
3881
  code: "CONFIRM_REQUIRED",
3532
- message: `创建环境需要您确认。请确认以下配置信息后传入 confirm="yes":\n别名: ${alias}\n套餐: ${packageId}\n资源类型: ${resolvedResources.join(", ")}\n时长: ${duration} 个月\n说明: CreateEnv 不接受 Region;环境地域由账号与套餐侧决定。`,
3882
+ message: messageLines.join("\n"),
3883
+ package_info: packageTitle
3884
+ ? { packageId, packageTitle }
3885
+ : packageId
3886
+ ? { packageId, packageTitle: null }
3887
+ : undefined,
3888
+ pricing: priceSection
3889
+ ? {
3890
+ summary: priceSection.summary,
3891
+ currency: priceProbe.priceResult?.Currency,
3892
+ realTotalCost: priceProbe.priceResult?.RealTotalCost,
3893
+ totalCost: priceProbe.priceResult?.TotalCost,
3894
+ timeSpan: priceProbe.priceResult?.TimeSpan,
3895
+ timeUnit: priceProbe.priceResult?.TimeUnit,
3896
+ inquiryRegion: pricingRegion,
3897
+ }
3898
+ : priceProbe.error
3899
+ ? { inquiryFailed: true, error: priceProbe.error }
3900
+ : undefined,
3901
+ release_method: {
3902
+ ...releaseMethod,
3903
+ detail: buildReleaseMethodDetailText(packageId),
3904
+ docLinks: [
3905
+ MANAGE_ENV_DOC_LINKS.package,
3906
+ MANAGE_ENV_DOC_LINKS.prepayExpiry,
3907
+ ],
3908
+ },
3909
+ doc_links: MANAGE_ENV_DOC_LINKS,
3910
+ confirmation_acknowledgement: {
3911
+ text: "我已知晓将创建付费资源及计费规则",
3912
+ required: true,
3913
+ },
3533
3914
  next_step: {
3534
3915
  tool: "manageEnv",
3535
3916
  action: "create",
@@ -3565,10 +3946,91 @@ function registerEnvTools(server) {
3565
3946
  if (!envId || !packageId) {
3566
3947
  throw new Error("变更套餐时 envId 和 packageId 为必填参数");
3567
3948
  }
3949
+ // 查询当前套餐名 + 新套餐名 + 询价(失败降级)
3950
+ const [currentBilling, newPackageTitle] = await Promise.all([
3951
+ fetchEnvBillingSummary(cloudbase, envId),
3952
+ fetchPackageTitle(cloudbase, packageId),
3953
+ ]);
3954
+ const priceProbe = await calculateModifyPrice(cloudbase, envId, packageId);
3955
+ const priceSection = priceProbe.priceResult
3956
+ ? formatPriceSection(priceProbe.priceResult)
3957
+ : null;
3958
+ const releaseMethod = buildReleaseMethodHint();
3959
+ const messageLines = [];
3960
+ messageLines.push(`变更环境 ${envId} 的套餐需要您确认。变配后不会立即重新计费,但会触发差价结算或退款。`);
3961
+ messageLines.push("请核对后传入 confirm=\"yes\":");
3962
+ messageLines.push(`- 当前套餐: ${currentBilling?.packageName ?? currentBilling?.packageId ?? "(未知)"}` +
3963
+ (currentBilling?.packageId && currentBilling.packageName
3964
+ ? `(${currentBilling.packageId})`
3965
+ : ""));
3966
+ if (currentBilling?.expireTime) {
3967
+ messageLines.push(`- 当前到期时间: ${currentBilling.expireTime}`);
3968
+ }
3969
+ messageLines.push(`- 新套餐: ${packageId}` +
3970
+ (newPackageTitle ? `(${newPackageTitle})` : ""));
3971
+ messageLines.push("");
3972
+ if (priceSection) {
3973
+ messageLines.push(`预计费用变化:${priceSection.summary}(差价/退款以账单为准)`);
3974
+ if (priceSection.detail) {
3975
+ messageLines.push(priceSection.detail);
3976
+ }
3977
+ }
3978
+ else if (priceProbe.error) {
3979
+ messageLines.push(`预计费用变化:⚠️ 询价失败(${priceProbe.error}),请前往控制台确认价格`);
3980
+ }
3981
+ else {
3982
+ messageLines.push("预计费用变化:询价返回为空,请前往控制台确认价格");
3983
+ }
3984
+ messageLines.push("");
3985
+ // 资源释放方式(变配不影响存续,但与到期/销毁规则相同)
3986
+ messageLines.push(buildReleaseMethodDetailText(packageId));
3987
+ messageLines.push("");
3988
+ // 文档链接(变配与套餐/计费/到期都相关)
3989
+ messageLines.push(renderDocLinksBlock(["package", "prepayExpiry"]));
3990
+ messageLines.push("");
3991
+ messageLines.push("☐ 我已知晓变配将触发差价结算或退款,确认按上述配置变更。");
3992
+ messageLines.push(`(如需取消或修改,请勿传 confirm="yes")`);
3568
3993
  return (0, tool_result_js_1.buildJsonToolResult)({
3569
3994
  ok: false,
3570
3995
  code: "CONFIRM_REQUIRED",
3571
- message: `变更环境 ${envId} 的套餐为 ${packageId} 可能产生费用变化。请确认后传入 confirm="yes"。`,
3996
+ message: messageLines.join("\n"),
3997
+ env_id: envId,
3998
+ current_package: currentBilling
3999
+ ? {
4000
+ packageId: currentBilling.packageId,
4001
+ packageName: currentBilling.packageName,
4002
+ expireTime: currentBilling.expireTime,
4003
+ payMode: currentBilling.payMode,
4004
+ }
4005
+ : undefined,
4006
+ new_package: {
4007
+ packageId,
4008
+ packageTitle: newPackageTitle ?? null,
4009
+ },
4010
+ pricing: priceSection
4011
+ ? {
4012
+ summary: priceSection.summary,
4013
+ currency: priceProbe.priceResult?.Currency,
4014
+ realTotalCost: priceProbe.priceResult?.RealTotalCost,
4015
+ totalCost: priceProbe.priceResult?.TotalCost,
4016
+ refund: priceProbe.priceResult?.Refund,
4017
+ }
4018
+ : priceProbe.error
4019
+ ? { inquiryFailed: true, error: priceProbe.error }
4020
+ : undefined,
4021
+ release_method: {
4022
+ ...releaseMethod,
4023
+ detail: buildReleaseMethodDetailText(packageId),
4024
+ docLinks: [MANAGE_ENV_DOC_LINKS.prepayExpiry],
4025
+ },
4026
+ doc_links: {
4027
+ package: MANAGE_ENV_DOC_LINKS.package,
4028
+ prepayExpiry: MANAGE_ENV_DOC_LINKS.prepayExpiry,
4029
+ },
4030
+ confirmation_acknowledgement: {
4031
+ text: "我已知晓变配将触发差价结算或退款",
4032
+ required: true,
4033
+ },
3572
4034
  next_step: {
3573
4035
  tool: "manageEnv",
3574
4036
  action: "modifyPlan",
@@ -3598,10 +4060,87 @@ function registerEnvTools(server) {
3598
4060
  if (!envId) {
3599
4061
  throw new Error("续费环境时 envId 为必填参数");
3600
4062
  }
4063
+ // 查询当前套餐名 + 到期时间 + 询价(失败降级)
4064
+ const [currentBilling, priceProbe] = await Promise.all([
4065
+ fetchEnvBillingSummary(cloudbase, envId),
4066
+ calculateRenewPrice(cloudbase, envId, duration),
4067
+ ]);
4068
+ const priceSection = priceProbe.priceResult
4069
+ ? formatPriceSection(priceProbe.priceResult)
4070
+ : null;
4071
+ const releaseMethod = buildReleaseMethodHint();
4072
+ const currentPackageId = currentBilling?.packageId;
4073
+ const messageLines = [];
4074
+ messageLines.push(`续费环境 ${envId} 需要您确认。续费按当前套餐类型计算,延长到期时间。`);
4075
+ messageLines.push("请核对后传入 confirm=\"yes\":");
4076
+ messageLines.push(`- 当前套餐: ${currentBilling?.packageName ?? currentBilling?.packageId ?? "(未知)"}` +
4077
+ (currentBilling?.packageId && currentBilling.packageName
4078
+ ? `(${currentBilling.packageId})`
4079
+ : ""));
4080
+ if (currentBilling?.expireTime) {
4081
+ messageLines.push(`- 当前到期时间: ${currentBilling.expireTime}`);
4082
+ }
4083
+ messageLines.push(`- 续费时长: ${duration} 个月`);
4084
+ messageLines.push("");
4085
+ if (priceSection) {
4086
+ messageLines.push(`预计费用:${priceSection.summary}`);
4087
+ if (priceSection.detail) {
4088
+ messageLines.push(priceSection.detail);
4089
+ }
4090
+ }
4091
+ else if (priceProbe.error) {
4092
+ messageLines.push(`预计费用:⚠️ 询价失败(${priceProbe.error}),请前往控制台确认价格`);
4093
+ }
4094
+ else {
4095
+ messageLines.push("预计费用:询价返回为空,请前往控制台确认价格");
4096
+ }
4097
+ messageLines.push("");
4098
+ // 资源释放方式
4099
+ messageLines.push(buildReleaseMethodDetailText(currentPackageId));
4100
+ messageLines.push("");
4101
+ // 文档链接(续费主要看预付费与到期释放)
4102
+ messageLines.push(renderDocLinksBlock(["prepayExpiry"]));
4103
+ messageLines.push("");
4104
+ messageLines.push("☐ 我已知晓续费将延长当前套餐的到期时间,确认按上述配置续费。");
4105
+ messageLines.push(`(如需取消或修改,请勿传 confirm="yes")`);
3601
4106
  return (0, tool_result_js_1.buildJsonToolResult)({
3602
4107
  ok: false,
3603
4108
  code: "CONFIRM_REQUIRED",
3604
- message: `续费环境 ${envId},时长: ${duration} 个月,可能产生费用。请确认后传入 confirm="yes"。`,
4109
+ message: messageLines.join("\n"),
4110
+ env_id: envId,
4111
+ current_package: currentBilling
4112
+ ? {
4113
+ packageId: currentBilling.packageId,
4114
+ packageName: currentBilling.packageName,
4115
+ expireTime: currentBilling.expireTime,
4116
+ payMode: currentBilling.payMode,
4117
+ isAutoRenew: currentBilling.isAutoRenew,
4118
+ }
4119
+ : undefined,
4120
+ pricing: priceSection
4121
+ ? {
4122
+ summary: priceSection.summary,
4123
+ currency: priceProbe.priceResult?.Currency,
4124
+ realTotalCost: priceProbe.priceResult?.RealTotalCost,
4125
+ totalCost: priceProbe.priceResult?.TotalCost,
4126
+ timeSpan: priceProbe.priceResult?.TimeSpan,
4127
+ timeUnit: priceProbe.priceResult?.TimeUnit,
4128
+ }
4129
+ : priceProbe.error
4130
+ ? { inquiryFailed: true, error: priceProbe.error }
4131
+ : undefined,
4132
+ release_method: {
4133
+ ...releaseMethod,
4134
+ detail: buildReleaseMethodDetailText(currentPackageId),
4135
+ docLinks: [MANAGE_ENV_DOC_LINKS.prepayExpiry],
4136
+ },
4137
+ doc_links: {
4138
+ prepayExpiry: MANAGE_ENV_DOC_LINKS.prepayExpiry,
4139
+ },
4140
+ confirmation_acknowledgement: {
4141
+ text: "我已知晓续费将延长当前套餐的到期时间",
4142
+ required: true,
4143
+ },
3605
4144
  next_step: {
3606
4145
  tool: "manageEnv",
3607
4146
  action: "renew",
@@ -29089,6 +29628,31 @@ function registerAppAuthTools(server) {
29089
29628
  return (0, json_content_js_1.jsonContent)(buildErrorEnvelope(error));
29090
29629
  }
29091
29630
  };
29631
+ // Best-effort inventory read used to verify whether CreateApiKey really produced a new key.
29632
+ // A failure here must not block key creation, so it returns null to mark "unknown"
29633
+ // rather than an empty list, which would be indistinguishable from "no keys exist".
29634
+ const listApiKeyRecords = async (cloudbase, keyType) => {
29635
+ try {
29636
+ const result = await cloudbase.env.describeApiKeyList({
29637
+ KeyType: keyType,
29638
+ PageNumber: 1,
29639
+ PageSize: 50,
29640
+ });
29641
+ return extractApiKeyList(result);
29642
+ }
29643
+ catch {
29644
+ return null;
29645
+ }
29646
+ };
29647
+ const listApiKeyIds = async (cloudbase, keyType) => {
29648
+ const records = await listApiKeyRecords(cloudbase, keyType);
29649
+ if (records === null) {
29650
+ return null;
29651
+ }
29652
+ return new Set(records
29653
+ .map((item) => (typeof item.KeyId === "string" ? item.KeyId : null))
29654
+ .filter((item) => item !== null));
29655
+ };
29092
29656
  const describePublishableKey = async (cloudbase, envId) => {
29093
29657
  const result = await cloudbase.env.describeApiKeyList({ KeyType: "publish_key", PageNumber: 1, PageSize: 10 });
29094
29658
  return {
@@ -29209,7 +29773,7 @@ function registerAppAuthTools(server) {
29209
29773
  }));
29210
29774
  server.registerTool?.("manageAppAuth", {
29211
29775
  title: "管理 CloudBase 应用认证配置",
29212
- description: "CloudBase 应用侧认证配置写入口。用于修改登录方式、provider、client 配置,确保 publishable key,以及创建或删除 API key、自定义登录密钥。⚠️ 本工具为管理端配置工具,不执行用户登录。当任务要求编写客户端登录代码时(例如「用 JS SDK 登录」),应先通过本工具完成配置(如启用 usernamePassword、获取 publishable key),再在项目代码中编写 @cloudbase/js-sdk 客户端登录代码(如 auth.signInWithPassword()),而非使用本工具完成登录。若前端要接受普通用户名样式标识符,应先执行 action=patchLoginStrategy 并传入 patch={ usernamePassword: true },再实现对应前端登录逻辑。",
29776
+ description: "CloudBase 应用侧认证配置写入口。用于修改登录方式、provider、client 配置,确保 publishable key,以及创建或删除 API key、自定义登录密钥。⚠️ 本工具为管理端配置工具,不执行用户登录。当任务要求编写客户端登录代码时(例如「用 JS SDK 登录」),应先通过本工具完成配置(如启用 usernamePassword、获取 publishable key),再在项目代码中编写 @cloudbase/js-sdk 客户端登录代码(如 auth.signInWithPassword()),而非使用本工具完成登录。若前端要接受普通用户名样式标识符,应先执行 action=patchLoginStrategy 并传入 patch={ usernamePassword: true },再实现对应前端登录逻辑。⚠️ action=createApiKey 返回体中的 created 字段表示是否真正新建:created=false 说明复用了环境中已存在的 key,此时 keyName/expireIn 入参不会生效,返回的 keyName/expireAt 均为服务端真实值,并会附带 warnings,切勿把它当作临时凭证分发。",
29213
29777
  inputSchema: {
29214
29778
  action: zod_1.z.enum(MANAGE_APP_AUTH_ACTIONS),
29215
29779
  patch: zod_1.z
@@ -29234,8 +29798,16 @@ function registerAppAuthTools(server) {
29234
29798
  .enum(APP_AUTH_KEY_TYPES)
29235
29799
  .optional()
29236
29800
  .describe("createApiKey 时的 API key 类型,默认 publish_key"),
29237
- keyName: zod_1.z.string().optional().describe("createApiKey 时的 API key 名称"),
29238
- expireIn: zod_1.z.number().int().min(0).optional().describe("createApiKey 时的有效期,单位秒;0 表示不过期"),
29801
+ keyName: zod_1.z
29802
+ .string()
29803
+ .optional()
29804
+ .describe("createApiKey 时的 API key 名称;服务端可能忽略该值(如 publish_key 每环境唯一时),返回体中的 keyName 一律为服务端实际存储的名称"),
29805
+ expireIn: zod_1.z
29806
+ .number()
29807
+ .int()
29808
+ .min(0)
29809
+ .optional()
29810
+ .describe("createApiKey 时的有效期,单位秒;0 表示不过期。复用已有 key 时该值不生效,此时返回体会带 created=false 与 warnings"),
29239
29811
  keyId: zod_1.z.string().optional().describe("deleteApiKey 时的 API key 唯一标识"),
29240
29812
  },
29241
29813
  annotations: {
@@ -29360,6 +29932,7 @@ function registerAppAuthTools(server) {
29360
29932
  }
29361
29933
  case "createApiKey": {
29362
29934
  const effectiveKeyType = keyType ?? "publish_key";
29935
+ const before = await listApiKeyIds(cloudbase, effectiveKeyType);
29363
29936
  const result = await cloudbase.env.createApiKey({
29364
29937
  KeyType: effectiveKeyType,
29365
29938
  ...(keyName ? { KeyName: keyName } : {}),
@@ -29367,19 +29940,44 @@ function registerAppAuthTools(server) {
29367
29940
  });
29368
29941
  (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
29369
29942
  const createApiKeyResult = normalizePlainObject(result, "createApiKeyResult") ?? {};
29943
+ const resultKeyId = typeof createApiKeyResult.KeyId === "string" ? createApiKeyResult.KeyId : null;
29944
+ const created = before === null || resultKeyId === null ? null : !before.has(resultKeyId);
29945
+ // The backend is the only source of truth for the stored name / expiry:
29946
+ // re-read the key record instead of echoing back the request parameters.
29947
+ const serverRecord = resultKeyId
29948
+ ? (await listApiKeyRecords(cloudbase, effectiveKeyType))?.find((item) => item.KeyId === resultKeyId) ?? null
29949
+ : null;
29950
+ const keyNameSource = serverRecord ?? createApiKeyResult;
29951
+ const resolvedKeyName = getNonEmptyString(keyNameSource.Name) ??
29952
+ getNonEmptyString(keyNameSource.KeyName) ??
29953
+ null;
29954
+ const resolvedExpireAt = getNonEmptyString(serverRecord?.ExpireAt) ??
29955
+ getNonEmptyString(createApiKeyResult.ExpireAt) ??
29956
+ null;
29957
+ const resolvedCreatedAt = getNonEmptyString(serverRecord?.CreateAt) ??
29958
+ getNonEmptyString(createApiKeyResult.CreateAt) ??
29959
+ null;
29960
+ const warnings = [];
29961
+ if (created === false) {
29962
+ warnings.push(`keyType=${effectiveKeyType} 未创建新的 key,返回的是环境中已存在的 key(keyId=${resultKeyId})。若该类型每个环境唯一,请改用 action=ensurePublishableKey 语义理解此结果。`);
29963
+ }
29964
+ if (keyName && resolvedKeyName !== null && resolvedKeyName !== keyName) {
29965
+ warnings.push(`请求的 keyName="${keyName}" 未生效,服务端实际存储的名称为 "${resolvedKeyName}"。`);
29966
+ }
29967
+ if (typeof expireIn === "number" && created === false) {
29968
+ warnings.push(`请求的 expireIn=${expireIn} 未生效,返回的 key 使用其原有过期时间 ${resolvedExpireAt ?? "unknown"}。请勿将其视为临时凭证。`);
29969
+ }
29370
29970
  return {
29371
29971
  success: true,
29372
29972
  envId,
29373
29973
  keyType: effectiveKeyType,
29374
- keyId: typeof result.KeyId === "string" ? result.KeyId : null,
29375
- keyName: typeof result.Name === "string"
29376
- ? result.Name
29377
- : typeof createApiKeyResult.KeyName === "string"
29378
- ? createApiKeyResult.KeyName
29379
- : keyName ?? null,
29380
- apiKey: typeof result.ApiKey === "string" ? result.ApiKey : null,
29381
- expireAt: typeof result.ExpireAt === "string" ? result.ExpireAt : null,
29382
- createdAt: typeof result.CreateAt === "string" ? result.CreateAt : null,
29974
+ keyId: resultKeyId,
29975
+ keyName: resolvedKeyName,
29976
+ apiKey: typeof createApiKeyResult.ApiKey === "string" ? createApiKeyResult.ApiKey : null,
29977
+ expireAt: resolvedExpireAt,
29978
+ createdAt: resolvedCreatedAt,
29979
+ ...(typeof created === "boolean" ? { created } : {}),
29980
+ ...(warnings.length > 0 ? { warnings } : {}),
29383
29981
  };
29384
29982
  }
29385
29983
  case "deleteApiKey": {
@@ -34238,6 +34836,17 @@ async function checkAndCreateFreeEnv(cloudbase, context) {
34238
34836
  hasInitTcbError: !!newContext.initTcbError,
34239
34837
  initTcbError: newContext.initTcbError
34240
34838
  });
34839
+ // User-facing notice emitted at the entry: inform the user that an automatic
34840
+ // free-env creation is being attempted. Informational only — no confirm.
34841
+ // Built once up-front so every return path can surface the same notice.
34842
+ const userNotice = [
34843
+ "系统检测到您当前没有可用的 CloudBase 环境,将自动尝试为您创建一个免费环境。",
34844
+ "创建依据:通过 NewUser / ReturningUser / BaasFree 等优惠活动资格检查;",
34845
+ "环境别名:ai-native(默认);",
34846
+ "费用说明:该环境为免费活动赠送,创建过程不会产生费用;如不符合免费条件,将引导您前往购买页;",
34847
+ "流程说明:此为自动流程,无需您确认;创建成功后将自动绑定到当前会话。"
34848
+ ].join("\n");
34849
+ (0, logger_js_1.debug)('[env-setup] User notice prepared:', { userNotice });
34241
34850
  try {
34242
34851
  // Step 1: Query promotional activities
34243
34852
  (0, logger_js_1.debug)('[env-setup] Checking promotional activity eligibility...');
@@ -34277,7 +34886,8 @@ async function checkAndCreateFreeEnv(cloudbase, context) {
34277
34886
  };
34278
34887
  return {
34279
34888
  success: false,
34280
- context: newContext
34889
+ context: newContext,
34890
+ userNotice
34281
34891
  };
34282
34892
  }
34283
34893
  (0, logger_js_1.debug)('[env-setup] User is eligible for free environment, attempting to create...');
@@ -34342,7 +34952,8 @@ async function checkAndCreateFreeEnv(cloudbase, context) {
34342
34952
  };
34343
34953
  return {
34344
34954
  success: false,
34345
- context: newContext
34955
+ context: newContext,
34956
+ userNotice
34346
34957
  };
34347
34958
  }
34348
34959
  // Report create success
@@ -34356,7 +34967,8 @@ async function checkAndCreateFreeEnv(cloudbase, context) {
34356
34967
  return {
34357
34968
  success: true,
34358
34969
  envId: envId.trim(), // Ensure no whitespace
34359
- context: newContext
34970
+ context: newContext,
34971
+ userNotice
34360
34972
  };
34361
34973
  }
34362
34974
  catch (createErr) {
@@ -34415,7 +35027,8 @@ async function checkAndCreateFreeEnv(cloudbase, context) {
34415
35027
  });
34416
35028
  return {
34417
35029
  success: false,
34418
- context: newContext
35030
+ context: newContext,
35031
+ userNotice
34419
35032
  };
34420
35033
  }
34421
35034
  }
@@ -34436,7 +35049,8 @@ async function checkAndCreateFreeEnv(cloudbase, context) {
34436
35049
  });
34437
35050
  return {
34438
35051
  success: false,
34439
- context: newContext
35052
+ context: newContext,
35053
+ userNotice
34440
35054
  };
34441
35055
  }
34442
35056
  }
@@ -40844,6 +41458,7 @@ const QUERY_ACTIONS = [
40844
41458
  "describeTaskStatus",
40845
41459
  "getInstanceInfo",
40846
41460
  "describeInstance",
41461
+ "getConnectionInfo",
40847
41462
  ];
40848
41463
  const MANAGE_ACTIONS = [
40849
41464
  "provisionMySQL",
@@ -40851,6 +41466,17 @@ const MANAGE_ACTIONS = [
40851
41466
  "runStatement",
40852
41467
  "initializeSchema",
40853
41468
  ];
41469
+ function sanitizeInstanceInfo(instanceInfo) {
41470
+ return {
41471
+ exists: instanceInfo.exists,
41472
+ envId: instanceInfo.envId,
41473
+ instanceId: instanceInfo.instanceId,
41474
+ schema: instanceInfo.schema,
41475
+ rawStatus: instanceInfo.rawStatus,
41476
+ status: instanceInfo.status,
41477
+ ...(instanceInfo.clusterId ? { clusterId: instanceInfo.clusterId } : {}),
41478
+ };
41479
+ }
40854
41480
  function buildNextAction(tool, action, reason, suggestedArgs) {
40855
41481
  return {
40856
41482
  tool,
@@ -41299,11 +41925,12 @@ async function handleDescribeTaskStatus(args, context) {
41299
41925
  }
41300
41926
  async function handleGetInstanceInfo(context) {
41301
41927
  const instanceInfo = await getSqlInstanceInfo(context);
41928
+ const sanitized = sanitizeInstanceInfo(instanceInfo);
41302
41929
  return buildSqlToolResult({
41303
41930
  success: true,
41304
- data: instanceInfo,
41931
+ data: sanitized,
41305
41932
  message: instanceInfo.exists
41306
- ? "Resolved current SQL database instance context."
41933
+ ? "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."
41307
41934
  : "No SQL database instance is currently available for this environment.",
41308
41935
  nextActions: instanceInfo.exists
41309
41936
  ? undefined
@@ -41312,6 +41939,33 @@ async function handleGetInstanceInfo(context) {
41312
41939
  ],
41313
41940
  });
41314
41941
  }
41942
+ async function handleGetConnectionInfo(context) {
41943
+ const instanceInfo = await getSqlInstanceInfo(context);
41944
+ if (!instanceInfo.exists) {
41945
+ return buildSqlToolResult({
41946
+ success: false,
41947
+ errorCode: "MYSQL_NOT_CREATED",
41948
+ data: sanitizeInstanceInfo(instanceInfo),
41949
+ message: "No MySQL instance exists for the current environment, so connection details cannot be returned.",
41950
+ nextActions: [
41951
+ buildNextAction(MANAGE_MYSQL_DATABASE, "provisionMySQL", "Provision MySQL before requesting connection details.", { action: "provisionMySQL", confirm: true }),
41952
+ ],
41953
+ });
41954
+ }
41955
+ return buildSqlToolResult({
41956
+ success: true,
41957
+ data: {
41958
+ ...sanitizeInstanceInfo(instanceInfo),
41959
+ // Full backend passthrough for explicit TCP migration only (may include credentials).
41960
+ clusterDetail: instanceInfo.clusterDetail,
41961
+ createResult: instanceInfo.createResult,
41962
+ },
41963
+ 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.",
41964
+ nextActions: [
41965
+ buildNextAction(QUERY_MYSQL_DATABASE, "runQuery", "Prefer platform-delegated read-only SQL instead of embedding TCP credentials in app code.", { action: "runQuery", sql: "SELECT 1" }),
41966
+ ],
41967
+ });
41968
+ }
41315
41969
  async function handleProvisionMySQL(args, context) {
41316
41970
  if (args.confirm !== true) {
41317
41971
  return buildSqlToolResult({
@@ -41329,7 +41983,7 @@ async function handleProvisionMySQL(args, context) {
41329
41983
  existing.status === "RUNNING") {
41330
41984
  return buildSqlToolResult({
41331
41985
  success: true,
41332
- data: existing,
41986
+ data: sanitizeInstanceInfo(existing),
41333
41987
  message: "A SQL database instance already exists for the current environment.",
41334
41988
  nextActions: existing.status === "READY"
41335
41989
  ? [
@@ -41662,11 +42316,11 @@ function registerSQLDatabaseTools(server) {
41662
42316
  };
41663
42317
  server.registerTool?.(QUERY_MYSQL_DATABASE, {
41664
42318
  title: "查询 CloudBase MySQL 数据库状态或执行只读 SQL",
41665
- description: "查询 CloudBase MySQL 数据库信息。支持执行只读 SQL、查询 MySQL 开通结果、查询 MySQL 任务状态,以及获取当前实例上下文信息。",
42319
+ description: "查询 CloudBase MySQL 数据库信息。支持执行只读 SQL、查询 MySQL 开通结果、查询 MySQL 任务状态,以及获取当前实例生命周期上下文。标准 getInstanceInfo/describeInstance 不返回连接凭据;仅 getConnectionInfo 透传原始连接/集群载荷(含可能的凭据),且仅用于显式 TCP 迁移。业务 CRUD 优先使用 SDK 或 runQuery/runStatement。",
41666
42320
  inputSchema: {
41667
42321
  action: zod_1.z
41668
42322
  .enum(QUERY_ACTIONS)
41669
- .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"),
42323
+ .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)"),
41670
42324
  sql: zod_1.z
41671
42325
  .string()
41672
42326
  .optional()
@@ -41702,6 +42356,8 @@ function registerSQLDatabaseTools(server) {
41702
42356
  case "getInstanceInfo":
41703
42357
  case "describeInstance":
41704
42358
  return handleGetInstanceInfo(context);
42359
+ case "getConnectionInfo":
42360
+ return handleGetConnectionInfo(context);
41705
42361
  default:
41706
42362
  throw new Error(`Unsupported SQL query action: ${args.action}`);
41707
42363
  }
@@ -84648,6 +85304,154 @@ exports.colors = {
84648
85304
  })));
84649
85305
 
84650
85306
 
85307
+ /***/ }),
85308
+
85309
+ /***/ 22435:
85310
+ /***/ ((__unused_webpack_module, exports) => {
85311
+
85312
+ "use strict";
85313
+
85314
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
85315
+ exports.rankGatewayAccessUrls = rankGatewayAccessUrls;
85316
+ exports.flattenHttpServiceRoutes = flattenHttpServiceRoutes;
85317
+ exports.filterRoutesByUpstream = filterRoutesByUpstream;
85318
+ exports.toAccessUrlEnvelope = toAccessUrlEnvelope;
85319
+ exports.resolveGatewayAccessUrls = resolveGatewayAccessUrls;
85320
+ exports.preferGatewayOrFallback = preferGatewayOrFallback;
85321
+ function normalizeAccessPath(path) {
85322
+ if (!path) {
85323
+ return "/";
85324
+ }
85325
+ return path.startsWith("/") ? path : `/${path}`;
85326
+ }
85327
+ function buildHttpsUrl(domain, path) {
85328
+ return `https://${domain}${normalizeAccessPath(path)}`;
85329
+ }
85330
+ /**
85331
+ * Rank gateway route URLs: custom domains (IsDefault !== true) before default domain.
85332
+ * Stable within each group; dedupe by full URL.
85333
+ */
85334
+ function rankGatewayAccessUrls(routes) {
85335
+ const mapped = routes
85336
+ .filter((route) => Boolean(route.Domain))
85337
+ .map((route) => {
85338
+ const path = normalizeAccessPath(route.Path);
85339
+ const isDefault = route.IsDefault === true;
85340
+ return {
85341
+ url: buildHttpsUrl(route.Domain, path),
85342
+ domain: route.Domain,
85343
+ path,
85344
+ isDefault,
85345
+ source: (isDefault
85346
+ ? "gateway.default"
85347
+ : "gateway.custom"),
85348
+ };
85349
+ });
85350
+ mapped.sort((a, b) => {
85351
+ if (a.isDefault === b.isDefault) {
85352
+ return 0;
85353
+ }
85354
+ return a.isDefault ? 1 : -1;
85355
+ });
85356
+ const seen = new Set();
85357
+ const deduped = [];
85358
+ for (const item of mapped) {
85359
+ if (seen.has(item.url)) {
85360
+ continue;
85361
+ }
85362
+ seen.add(item.url);
85363
+ deduped.push(item);
85364
+ }
85365
+ return deduped;
85366
+ }
85367
+ function flattenHttpServiceRoutes(result) {
85368
+ return (result.Domains ?? []).flatMap((domainItem) => (domainItem.Routes ?? []).map((route) => ({
85369
+ Domain: domainItem.Domain ?? "",
85370
+ IsDefault: domainItem.IsDefault,
85371
+ Path: typeof route.Path === "string" ? route.Path : undefined,
85372
+ UpstreamResourceType: typeof route.UpstreamResourceType === "string"
85373
+ ? route.UpstreamResourceType
85374
+ : undefined,
85375
+ UpstreamResourceName: typeof route.UpstreamResourceName === "string"
85376
+ ? route.UpstreamResourceName
85377
+ : undefined,
85378
+ })));
85379
+ }
85380
+ function filterRoutesByUpstream(routes, input) {
85381
+ const name = input.upstreamResourceName;
85382
+ const types = input.upstreamResourceTypes?.map((t) => String(t));
85383
+ return routes.filter((route) => {
85384
+ if (route.UpstreamResourceName !== name) {
85385
+ return false;
85386
+ }
85387
+ if (!types || types.length === 0) {
85388
+ return true;
85389
+ }
85390
+ return Boolean(route.UpstreamResourceType &&
85391
+ types.includes(String(route.UpstreamResourceType)));
85392
+ });
85393
+ }
85394
+ function toAccessUrlEnvelope(ranked) {
85395
+ if (ranked.length === 0) {
85396
+ return { accessUrls: [], routes: [] };
85397
+ }
85398
+ return {
85399
+ accessUrl: ranked[0].url,
85400
+ accessUrls: ranked.map((item) => item.url),
85401
+ accessUrlSource: ranked[0].source,
85402
+ routes: ranked,
85403
+ };
85404
+ }
85405
+ /**
85406
+ * Best-effort lookup of gateway access URLs for an upstream resource.
85407
+ * Never throws — returns empty lists on failure.
85408
+ */
85409
+ async function resolveGatewayAccessUrls(input) {
85410
+ try {
85411
+ const manager = await input.getManager();
85412
+ const result = await manager.env.describeHttpServiceRoute({
85413
+ EnvId: input.envId,
85414
+ Limit: 1000,
85415
+ });
85416
+ const flattened = flattenHttpServiceRoutes(result);
85417
+ const matched = filterRoutesByUpstream(flattened, {
85418
+ upstreamResourceName: input.upstreamResourceName,
85419
+ upstreamResourceTypes: input.upstreamResourceTypes,
85420
+ });
85421
+ return toAccessUrlEnvelope(rankGatewayAccessUrls(matched));
85422
+ }
85423
+ catch {
85424
+ return { accessUrls: [], routes: [] };
85425
+ }
85426
+ }
85427
+ /**
85428
+ * Merge ranked gateway URLs with a resource-native fallback URL.
85429
+ * Gateway custom/default always win over the fallback when present.
85430
+ */
85431
+ function preferGatewayOrFallback(input) {
85432
+ if (input.gateway.accessUrl) {
85433
+ const urls = [...input.gateway.accessUrls];
85434
+ if (input.fallbackUrl &&
85435
+ !urls.includes(input.fallbackUrl)) {
85436
+ urls.push(input.fallbackUrl);
85437
+ }
85438
+ return {
85439
+ accessUrl: input.gateway.accessUrl,
85440
+ accessUrls: urls,
85441
+ accessUrlSource: input.gateway.accessUrlSource,
85442
+ };
85443
+ }
85444
+ if (input.fallbackUrl) {
85445
+ return {
85446
+ accessUrl: input.fallbackUrl,
85447
+ accessUrls: [input.fallbackUrl],
85448
+ accessUrlSource: input.fallbackSource,
85449
+ };
85450
+ }
85451
+ return { accessUrls: [] };
85452
+ }
85453
+
85454
+
84651
85455
  /***/ }),
84652
85456
 
84653
85457
  /***/ 22573:
@@ -90059,6 +90863,7 @@ exports.registerFunctionTools = registerFunctionTools;
90059
90863
  const zod_1 = __webpack_require__(21614);
90060
90864
  const cloudbase_manager_js_1 = __webpack_require__(3431);
90061
90865
  const cloud_mode_js_1 = __webpack_require__(89684);
90866
+ const gateway_access_urls_js_1 = __webpack_require__(22435);
90062
90867
  const json_content_js_1 = __webpack_require__(4365);
90063
90868
  const logger_js_1 = __webpack_require__(13039);
90064
90869
  const fs_1 = __webpack_require__(29021);
@@ -90903,9 +91708,33 @@ function registerFunctionTools(server) {
90903
91708
  const message = func.type === "HTTP"
90904
91709
  ? `已创建 HTTP 函数 ${functionName}。如果后续需要通过 URL 访问,请显式调用 manageGateway(action="createRoute"),并把 upstreamResourceType="WEB_SCF" 一起传入,再按实际路径和鉴权需求创建访问入口。评测或其他外部调用方可能会以匿名身份访问,而且失败后不一定会把 EXCEED_AUTHORITY 再反馈给 AI;交付前请主动确认访问路径和函数安全规则,若已出现 EXCEED_AUTHORITY,请先调用 queryPermissions(action="getResourcePermission", resourceType="function", resourceId="${functionName}") 查看当前规则,再按需要使用 managePermissions(action="updateResourcePermission") 调整权限。`
90905
91710
  : `已创建函数 ${functionName}`;
91711
+ let accessUrl;
91712
+ let accessUrls = [];
91713
+ let accessUrlSource;
91714
+ if (func.type === "HTTP") {
91715
+ const envId = cloudBaseOptions?.envId ?? await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
91716
+ const gateway = await (0, gateway_access_urls_js_1.resolveGatewayAccessUrls)({
91717
+ envId,
91718
+ upstreamResourceName: functionName,
91719
+ upstreamResourceTypes: ["WEB_SCF", "SCF"],
91720
+ getManager: async () => {
91721
+ const manager = await getManager();
91722
+ if (!manager) {
91723
+ throw new Error("cloudbase manager unavailable");
91724
+ }
91725
+ return manager;
91726
+ },
91727
+ });
91728
+ accessUrl = gateway.accessUrl;
91729
+ accessUrls = gateway.accessUrls;
91730
+ accessUrlSource = gateway.accessUrlSource;
91731
+ }
90906
91732
  return buildEnvelope({
90907
91733
  action: input.action,
90908
91734
  functionName,
91735
+ ...(accessUrl ? { accessUrl } : {}),
91736
+ ...(accessUrls.length > 0 ? { accessUrls } : {}),
91737
+ ...(accessUrlSource ? { accessUrlSource } : {}),
90909
91738
  raw: result,
90910
91739
  }, message, nextActions);
90911
91740
  }
@@ -90944,11 +91773,33 @@ function registerFunctionTools(server) {
90944
91773
  throw wrapFunctionOperationError("updateFunctionCode", input.functionName, undefined, error);
90945
91774
  }
90946
91775
  (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, imageResult);
91776
+ const envId = cloudBaseOptions?.envId ?? await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
91777
+ const imageGatewayAccess = await (0, gateway_access_urls_js_1.resolveGatewayAccessUrls)({
91778
+ envId,
91779
+ upstreamResourceName: input.functionName,
91780
+ upstreamResourceTypes: ["WEB_SCF", "SCF"],
91781
+ getManager: async () => {
91782
+ const manager = await getManager();
91783
+ if (!manager) {
91784
+ throw new Error("cloudbase manager unavailable");
91785
+ }
91786
+ return manager;
91787
+ },
91788
+ });
90947
91789
  return buildEnvelope({
90948
91790
  action: input.action,
90949
91791
  functionName: input.functionName,
90950
91792
  deployMode: "image",
90951
91793
  imageUri: updateImageConfig.imageUri,
91794
+ ...(imageGatewayAccess.accessUrl
91795
+ ? { accessUrl: imageGatewayAccess.accessUrl }
91796
+ : {}),
91797
+ ...(imageGatewayAccess.accessUrls.length > 0
91798
+ ? { accessUrls: imageGatewayAccess.accessUrls }
91799
+ : {}),
91800
+ ...(imageGatewayAccess.accessUrlSource
91801
+ ? { accessUrlSource: imageGatewayAccess.accessUrlSource }
91802
+ : {}),
90952
91803
  raw: imageResult,
90953
91804
  }, `已将函数 ${input.functionName} 的镜像更新为 ${updateImageConfig.imageUri}。` +
90954
91805
  `部署后可用 queryFunctions(action="getFunctionDetail") 确认函数已就绪(Active)。`, [
@@ -90979,9 +91830,29 @@ function registerFunctionTools(server) {
90979
91830
  throw wrapFunctionOperationError("updateFunctionCode", input.functionName, processedRootPath, error);
90980
91831
  }
90981
91832
  (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
91833
+ const envId = cloudBaseOptions?.envId ?? await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
91834
+ const gatewayAccess = await (0, gateway_access_urls_js_1.resolveGatewayAccessUrls)({
91835
+ envId,
91836
+ upstreamResourceName: input.functionName,
91837
+ upstreamResourceTypes: ["WEB_SCF", "SCF"],
91838
+ getManager: async () => {
91839
+ const manager = await getManager();
91840
+ if (!manager) {
91841
+ throw new Error("cloudbase manager unavailable");
91842
+ }
91843
+ return manager;
91844
+ },
91845
+ });
90982
91846
  return buildEnvelope({
90983
91847
  action: input.action,
90984
91848
  functionName: input.functionName,
91849
+ ...(gatewayAccess.accessUrl ? { accessUrl: gatewayAccess.accessUrl } : {}),
91850
+ ...(gatewayAccess.accessUrls.length > 0
91851
+ ? { accessUrls: gatewayAccess.accessUrls }
91852
+ : {}),
91853
+ ...(gatewayAccess.accessUrlSource
91854
+ ? { accessUrlSource: gatewayAccess.accessUrlSource }
91855
+ : {}),
90985
91856
  raw: result,
90986
91857
  }, `已更新函数 ${input.functionName} 的代码`, [
90987
91858
  {
@@ -114238,7 +115109,9 @@ const path_1 = __importDefault(__webpack_require__(39902));
114238
115109
  const zod_1 = __webpack_require__(21614);
114239
115110
  const cloudbase_manager_js_1 = __webpack_require__(3431);
114240
115111
  const logger_js_1 = __webpack_require__(13039);
115112
+ const gateway_access_urls_js_1 = __webpack_require__(22435);
114241
115113
  const notification_js_1 = __webpack_require__(32720);
115114
+ const cloudrun_config_js_1 = __webpack_require__(48266);
114242
115115
  // CloudRun service types
114243
115116
  exports.CLOUDRUN_SERVICE_TYPES = ['function', 'container'];
114244
115117
  // CloudRun access types
@@ -114257,10 +115130,11 @@ const queryCloudRunInputSchema = {
114257
115130
  };
114258
115131
  // Input schema for manageCloudRun tool
114259
115132
  const ManageCloudRunInputSchema = {
114260
- action: zod_1.z.enum(['init', 'download', 'run', 'deploy', 'delete', 'createAgent']).describe('云托管服务管理操作类型:init=从模板初始化新的云托管项目代码(在targetPath目录下创建以serverName命名的子目录,支持多种语言和框架模板),download=从云端下载现有服务的代码到本地进行开发,run=在本地运行函数型云托管服务(用于开发和调试,仅支持函数型服务),deploy=将本地代码部署到云端云托管服务(支持函数型和容器型),delete=删除指定的云托管服务(不可恢复,需要确认),createAgent=创建函数型Agent(基于函数型云托管开发AI智能体)'),
115133
+ action: zod_1.z.enum(['init', 'download', 'run', 'deploy', 'delete', 'createAgent', 'updateConfig']).describe('云托管服务管理操作类型:init=从模板初始化新的云托管项目代码(在targetPath目录下创建以serverName命名的子目录,支持多种语言和框架模板),download=从云端下载现有服务的代码到本地进行开发,run=在本地运行函数型云托管服务(用于开发和调试,仅支持函数型服务),deploy=将本地代码部署到云端云托管服务(支持函数型和容器型;已存在服务会 Read-Merge-Write 保留远程 VpcConf/EnvParams/OpenAccessTypes),updateConfig=仅更新服务配置不重新上传代码(对齐控制台服务设置,走 SubmitServerConfigChangeDiff;不需要 targetPath),delete=删除指定的云托管服务(不可恢复,需要确认),createAgent=创建函数型Agent(基于函数型云托管开发AI智能体)'),
114261
115134
  serverName: zod_1.z.string().describe('云托管服务名称,用于标识和管理服务。命名规则:支持大小写字母、数字、连字符和下划线,必须以字母开头,长度3-45个字符。在init操作中会作为在targetPath下创建的子目录名,在其他操作中作为目标服务名'),
114262
115135
  // Deploy operation parameters
114263
- targetPath: zod_1.z.string().optional().describe('本地代码路径,必须是绝对路径。在deploy操作中指定要部署的代码目录,在download操作中指定下载目标目录,在init操作中指定云托管服务的上级目录(会在该目录下创建以serverName命名的子目录)。建议约定:项目根目录下的cloudrun/目录,例如:/Users/username/projects/my-project/cloudrun'),
115136
+ targetPath: zod_1.z.string().optional().describe('本地代码路径,必须是绝对路径。在deploy操作中指定要部署的代码目录,在download操作中指定下载目标目录,在init操作中指定云托管服务的上级目录(会在该目录下创建以serverName命名的子目录)。updateConfig 不需要此参数。建议约定:项目根目录下的cloudrun/目录,例如:/Users/username/projects/my-project/cloudrun'),
115137
+ envParamsReplaceAll: zod_1.z.boolean().optional().default(false).describe('EnvParams 合并策略(deploy / updateConfig):false(默认)= 与远程按 key 合并(输入覆盖同名 key,远程其余 key 保留);true= 用输入 EnvParams 整包替换远程。仅当显式传入 EnvParams 时生效'),
114264
115138
  serverConfig: zod_1.z.object({
114265
115139
  OpenAccessTypes: zod_1.z.array(zod_1.z.enum(exports.CLOUDRUN_ACCESS_TYPES)).optional().describe('公网访问类型配置,控制服务的访问权限:OA=办公网访问,PUBLIC=公网访问(默认,可通过HTTPS域名访问),MINIAPP=小程序访问,VPC=VPC访问(仅同VPC内可访问)。可配置多个类型'),
114266
115140
  Cpu: zod_1.z.number().positive().optional().describe('CPU规格配置,单位为核。可选值:0.25、0.5、1、2、4、8等。注意:内存规格必须是CPU规格的2倍(如CPU=0.25时内存=0.5,CPU=1时内存=2)。影响服务性能和计费'),
@@ -114299,7 +115173,7 @@ const ManageCloudRunInputSchema = {
114299
115173
  VpcConf: zod_1.z.object({
114300
115174
  VpcId: zod_1.z.string().describe('VPC网络ID,格式如 vpc-xxxxxxxx。必须与目标数据库/Redis 处于同一地域,并优先选择同一 VPC。禁止猜测或使用占位符;须来自数据库控制台、已有资源详情、callCloudApi 或用户确认。建议首次创建即配置;已存在服务也可在 deploy 时传入,部署后必须用 queryCloudRun detail 复核是否生效'),
114301
115175
  SubnetId: zod_1.z.string().describe('子网ID,格式如 subnet-xxxxxxxx。云托管实例将占用该子网 IP,需确保有足够可用 IP'),
114302
- }).optional().describe('VPC网络配置(实例出网/私有网络)。用于让云托管实例接入指定 VPC,从而内网访问 MySQL/PostgreSQL/Redis/CVM 等资源。与 OpenAccessTypes(外部如何访问本服务)是不同概念。TCP 连库场景必须配置。禁止猜测 VpcId/SubnetId,须来自数据库控制台、已有资源详情、callCloudApi 或用户确认。MCP 在创建时会将 VpcConf 映射为 SDK vpcInfo(CreateType=2);更新后必须用 queryCloudRun detail 复核 ServerConfig.VpcConf,未生效再走控制台网络设置或删建兜底'),
115176
+ }).optional().describe('VPC网络配置(实例出网/私有网络)。用于让云托管实例接入指定 VPC,从而内网访问 MySQL/PostgreSQL/Redis/CVM 等资源。与 OpenAccessTypes(外部如何访问本服务)是不同概念。TCP 连库场景必须配置。禁止猜测 VpcId/SubnetId,须来自数据库控制台、已有资源详情、callCloudApi 或用户确认。创建时映射为 SDK vpcInfo(CreateType=2);已存在服务可用 updateConfig 或 deploy(RMW 会保留未传入的远程 VpcConf)。部署/更新后必须用 queryCloudRun detail 复核 ServerConfig.VpcConf'),
114303
115177
  VolumesConf: zod_1.z.array(zod_1.z.object({
114304
115178
  VolumeName: zod_1.z.string().describe('存储卷名称'),
114305
115179
  VolumeType: zod_1.z.string().describe('存储卷类型,如CFS表示云文件存储'),
@@ -114309,7 +115183,7 @@ const ManageCloudRunInputSchema = {
114309
115183
  PublicAccess: zod_1.z.boolean().optional().describe('是否开启公网访问,true=开启公网访问,false=关闭公网访问'),
114310
115184
  PublicAccessPath: zod_1.z.string().optional().describe('公网访问路径配置')
114311
115185
  }).optional().describe('公网访问配置,用于控制服务的公网访问策略。可配置是否开启公网访问及访问路径'),
114312
- }).optional().describe('服务配置项,用于部署时设置服务的运行参数。包括资源规格、访问权限、环境变量、日志、网络等配置。不提供时使用默认配置'),
115186
+ }).optional().describe('服务配置项,用于 deploy / updateConfig。包括资源规格、访问权限、环境变量、日志、网络等。deploy 未提供时对已存在服务仍会从远程合并保留 VpcConf/EnvParams/OpenAccessTypes;updateConfig 至少需要一个配置字段'),
114313
115187
  // Init operation parameters
114314
115188
  template: zod_1.z.string().optional().default('helloworld').describe('项目模板标识符,用于指定初始化项目时使用的模板。可通过queryCloudRun的templates操作获取可用模板列表。常用模板:helloworld=Hello World示例,nodejs=Node.js项目模板,python=Python项目模板等'),
114315
115189
  // Run operation parameters (function services only)
@@ -114493,6 +115367,30 @@ function normalizeProcessLogText(logs) {
114493
115367
  })
114494
115368
  .join("\n");
114495
115369
  }
115370
+ function normalizeCloudRunDomainUrl(input) {
115371
+ if (typeof input !== "string" || !input.trim())
115372
+ return undefined;
115373
+ const raw = input.trim();
115374
+ return raw.startsWith("http://") || raw.startsWith("https://")
115375
+ ? raw
115376
+ : `https://${raw}`;
115377
+ }
115378
+ function resolveCloudRunFallbackAccess(details) {
115379
+ const custom = normalizeCloudRunDomainUrl(details?.BaseInfo?.CustomDomainName);
115380
+ if (custom)
115381
+ return { url: custom, source: "cloudrun.customDomain" };
115382
+ const defaultDomain = normalizeCloudRunDomainUrl(details?.BaseInfo?.DefaultDomainName);
115383
+ if (defaultDomain)
115384
+ return { url: defaultDomain, source: "cloudrun.defaultDomain" };
115385
+ const publicDomain = normalizeCloudRunDomainUrl(details?.BaseInfo?.PublicDomain) ??
115386
+ normalizeCloudRunDomainUrl(details?.AccessInfo?.PublicDomain);
115387
+ if (publicDomain)
115388
+ return { url: publicDomain, source: "cloudrun.publicDomain" };
115389
+ const internal = normalizeCloudRunDomainUrl(details?.BaseInfo?.InternalDomain);
115390
+ if (internal)
115391
+ return { url: internal, source: "cloudrun.internalDomain" };
115392
+ return {};
115393
+ }
114496
115394
  /**
114497
115395
  * Format CloudRun service info for display
114498
115396
  */
@@ -114726,7 +115624,7 @@ function registerCloudRunTools(server) {
114726
115624
  // Tool 2: Manage CloudRun services (write operations)
114727
115625
  server.registerTool("manageCloudRun", {
114728
115626
  title: "管理 CloudRun 服务",
114729
- description: "管理云托管服务,按开发顺序支持:初始化项目(可从模板开始,模板列表可通过 queryCloudRun 查询)、下载服务代码、本地运行(仅函数型服务)、部署代码、删除服务。部署可配置CPU、内存、实例数、访问类型等参数。删除操作需要确认,建议设置force=true。",
115627
+ description: "管理云托管服务,按开发顺序支持:初始化项目(可从模板开始,模板列表可通过 queryCloudRun 查询)、下载服务代码、本地运行(仅函数型服务)、部署代码、仅更新配置(updateConfig,无需重新上传代码)、删除服务。deploy 对已存在服务会先读取远程配置再合并(保留 VpcConf/EnvParams/OpenAccessTypes)。updateConfig 对齐控制台服务设置页。删除操作需要确认,建议设置force=true。",
114730
115628
  inputSchema: ManageCloudRunInputSchema,
114731
115629
  annotations: {
114732
115630
  readOnlyHint: false,
@@ -114917,6 +115815,8 @@ for await (let x of res.textStream) {
114917
115815
  }
114918
115816
  // Determine service type - use input.serverType if provided, otherwise auto-detect
114919
115817
  let serverType;
115818
+ let remoteServerConfig = null;
115819
+ let existingService = false;
114920
115820
  if (input.serverType) {
114921
115821
  serverType = input.serverType;
114922
115822
  }
@@ -114925,6 +115825,8 @@ for await (let x of res.textStream) {
114925
115825
  // First try to get existing service details
114926
115826
  const details = await cloudrunService.detail({ serverName: input.serverName });
114927
115827
  serverType = details.BaseInfo?.ServerType || 'container';
115828
+ remoteServerConfig = (details.ServerConfig || null);
115829
+ existingService = true;
114928
115830
  }
114929
115831
  catch (e) {
114930
115832
  // If service doesn't exist, determine by project structure
@@ -114958,20 +115860,40 @@ for await (let x of res.textStream) {
114958
115860
  }
114959
115861
  }
114960
115862
  }
115863
+ // When serverType was provided explicitly, still try to load remote config for RMW.
115864
+ if (!existingService) {
115865
+ try {
115866
+ const details = await cloudrunService.detail({ serverName: input.serverName });
115867
+ remoteServerConfig = (details.ServerConfig || null);
115868
+ existingService = true;
115869
+ }
115870
+ catch {
115871
+ // New service create path
115872
+ }
115873
+ }
115874
+ let mergedFromRemote = [];
115875
+ let effectiveServerConfig = input.serverConfig;
115876
+ if (existingService) {
115877
+ const mergedResult = (0, cloudrun_config_js_1.mergeCloudRunServerConfig)({
115878
+ remote: remoteServerConfig,
115879
+ input: input.serverConfig || {},
115880
+ envParamsReplaceAll: Boolean(input.envParamsReplaceAll),
115881
+ });
115882
+ effectiveServerConfig = mergedResult.merged;
115883
+ mergedFromRemote = mergedResult.mergedFromRemote;
115884
+ }
114961
115885
  const deployParams = {
114962
115886
  serverName: input.serverName,
114963
115887
  targetPath: targetPath,
114964
115888
  force: input.force,
114965
115889
  serverType: serverType,
114966
115890
  };
114967
- // Add server configuration if provided
114968
- if (input.serverConfig) {
114969
- deployParams.serverConfig = input.serverConfig;
115891
+ if (effectiveServerConfig && Object.keys(effectiveServerConfig).length > 0) {
115892
+ deployParams.serverConfig = effectiveServerConfig;
114970
115893
  }
114971
115894
  // Manager SDK create path prefers top-level vpcInfo (CreateCloudRunServer.VpcInfo).
114972
115895
  // Map serverConfig.VpcConf → vpcInfo so first-time create actually binds VPC.
114973
- // Update path still sends Items.VpcConf; platform may ignore VPC changes on existing services.
114974
- const vpcConf = input.serverConfig?.VpcConf;
115896
+ const vpcConf = effectiveServerConfig?.VpcConf;
114975
115897
  if (vpcConf?.VpcId?.trim() && vpcConf?.SubnetId?.trim()) {
114976
115898
  deployParams.vpcInfo = {
114977
115899
  VpcId: vpcConf.VpcId.trim(),
@@ -115002,47 +115924,46 @@ for await (let x of res.textStream) {
115002
115924
  catch (error) {
115003
115925
  (0, logger_js_1.debug)('cloudbaserc.json creation skipped:', error instanceof Error ? error : new Error(String(error)));
115004
115926
  }
115927
+ let preferredAccessUrl;
115928
+ let preferredAccessUrls = [];
115929
+ let preferredAccessSource;
115930
+ let verifiedConfigSnapshot;
115931
+ try {
115932
+ const serviceDetails = await cloudrunService.detail({
115933
+ serverName: input.serverName,
115934
+ });
115935
+ verifiedConfigSnapshot = (0, cloudrun_config_js_1.summarizeConfigSnapshot)(serviceDetails?.ServerConfig);
115936
+ const fallback = resolveCloudRunFallbackAccess(serviceDetails);
115937
+ const gateway = await (0, gateway_access_urls_js_1.resolveGatewayAccessUrls)({
115938
+ envId: currentEnvId,
115939
+ upstreamResourceName: input.serverName,
115940
+ upstreamResourceTypes: ["CBR"],
115941
+ getManager: async () => {
115942
+ const manager = await getManager();
115943
+ if (!manager) {
115944
+ throw new Error("cloudbase manager unavailable");
115945
+ }
115946
+ return manager;
115947
+ },
115948
+ });
115949
+ const preferred = (0, gateway_access_urls_js_1.preferGatewayOrFallback)({
115950
+ gateway,
115951
+ fallbackUrl: fallback.url,
115952
+ fallbackSource: fallback.source,
115953
+ });
115954
+ preferredAccessUrl = preferred.accessUrl;
115955
+ preferredAccessUrls = preferred.accessUrls;
115956
+ preferredAccessSource = preferred.accessUrlSource;
115957
+ }
115958
+ catch {
115959
+ // best-effort URL enrichment only
115960
+ }
115005
115961
  // Send deployment notification to CodeBuddy IDE
115006
115962
  try {
115007
- // Query service details to get access URL
115008
- let serviceUrl = "";
115009
- try {
115010
- const serviceDetails = await cloudrunService.detail({ serverName: input.serverName });
115011
- // Extract access URL from service details
115012
- // Priority: DefaultDomainName > CustomDomainName > PublicDomain > InternalDomain
115013
- const details = serviceDetails; // Use any to access dynamic properties
115014
- if (details?.BaseInfo?.DefaultDomainName) {
115015
- // DefaultDomainName is already a complete URL (e.g., https://...)
115016
- serviceUrl = details.BaseInfo.DefaultDomainName;
115017
- }
115018
- else if (details?.BaseInfo?.CustomDomainName) {
115019
- // CustomDomainName might be a domain without protocol
115020
- const customDomain = details.BaseInfo.CustomDomainName;
115021
- serviceUrl = customDomain.startsWith('http') ? customDomain : `https://${customDomain}`;
115022
- }
115023
- else if (details?.BaseInfo?.PublicDomain) {
115024
- serviceUrl = `https://${details.BaseInfo.PublicDomain}`;
115025
- }
115026
- else if (details?.BaseInfo?.InternalDomain) {
115027
- serviceUrl = `https://${details.BaseInfo.InternalDomain}`;
115028
- }
115029
- else if (details?.AccessInfo?.PublicDomain) {
115030
- serviceUrl = `https://${details.AccessInfo.PublicDomain}`;
115031
- }
115032
- else {
115033
- serviceUrl = ""; // URL not available
115034
- }
115035
- }
115036
- catch (detailErr) {
115037
- // If query fails, continue with empty URL
115038
- serviceUrl = "";
115039
- }
115040
- // Extract project name from targetPath
115041
115963
  const projectName = path_1.default.basename(targetPath);
115042
- // Send notification
115043
115964
  await (0, notification_js_1.sendDeployNotification)(server, {
115044
115965
  deployType: 'cloudrun',
115045
- url: serviceUrl,
115966
+ url: preferredAccessUrl ?? "",
115046
115967
  projectId: currentEnvId,
115047
115968
  projectName: projectName,
115048
115969
  consoleUrl: consoleUrl
@@ -115053,8 +115974,8 @@ for await (let x of res.textStream) {
115053
115974
  // Error is already logged in sendDeployNotification
115054
115975
  }
115055
115976
  const dbNetworkRisk = detectCloudRunDbNetworkRisk({
115056
- envParams: input.serverConfig?.EnvParams,
115057
- vpcConf: input.serverConfig?.VpcConf,
115977
+ envParams: effectiveServerConfig?.EnvParams,
115978
+ vpcConf: effectiveServerConfig?.VpcConf,
115058
115979
  });
115059
115980
  const warnings = dbNetworkRisk ? [dbNetworkRisk] : [];
115060
115981
  const warningSuffix = dbNetworkRisk
@@ -115073,6 +115994,25 @@ for await (let x of res.textStream) {
115073
115994
  serverType: serverType,
115074
115995
  cloudbasercGenerated: true,
115075
115996
  consoleUrl,
115997
+ ...(existingService
115998
+ ? {
115999
+ configMerge: {
116000
+ existingService: true,
116001
+ mergedFromRemote,
116002
+ appliedConfig: (0, cloudrun_config_js_1.summarizeConfigSnapshot)(effectiveServerConfig),
116003
+ ...(verifiedConfigSnapshot
116004
+ ? { verifiedAfterDeploy: verifiedConfigSnapshot }
116005
+ : {}),
116006
+ },
116007
+ }
116008
+ : {}),
116009
+ ...(preferredAccessUrl ? { accessUrl: preferredAccessUrl } : {}),
116010
+ ...(preferredAccessUrls.length > 0
116011
+ ? { accessUrls: preferredAccessUrls }
116012
+ : {}),
116013
+ ...(preferredAccessSource
116014
+ ? { accessUrlSource: preferredAccessSource }
116015
+ : {}),
115076
116016
  ...(warnings.length > 0 ? { warnings } : {}),
115077
116017
  },
115078
116018
  message: `Triggered deployment for ${serverType} service '${input.serverName}' from ${targetPath}. You can follow the progress in ${consoleUrl}.${warningSuffix}`
@@ -115081,6 +116021,125 @@ for await (let x of res.textStream) {
115081
116021
  ]
115082
116022
  };
115083
116023
  }
116024
+ case 'updateConfig': {
116025
+ if (!input.serverConfig || Object.keys(input.serverConfig).length === 0) {
116026
+ throw new Error("serverConfig with at least one field is required for updateConfig");
116027
+ }
116028
+ let remoteServerConfig = {};
116029
+ try {
116030
+ const details = await cloudrunService.detail({
116031
+ serverName: input.serverName,
116032
+ });
116033
+ remoteServerConfig = (details.ServerConfig ||
116034
+ {});
116035
+ }
116036
+ catch (error) {
116037
+ throw new Error(buildManageCloudRunErrorMessage("updateConfig", input.serverName, error));
116038
+ }
116039
+ // EnvParams on Diff replaces the whole blob — merge keys unless replaceAll.
116040
+ const dirty = { ...input.serverConfig };
116041
+ if (Object.prototype.hasOwnProperty.call(input.serverConfig, "EnvParams")) {
116042
+ const { merged } = (0, cloudrun_config_js_1.mergeCloudRunServerConfig)({
116043
+ remote: { EnvParams: remoteServerConfig.EnvParams },
116044
+ input: { EnvParams: input.serverConfig.EnvParams },
116045
+ envParamsReplaceAll: Boolean(input.envParamsReplaceAll),
116046
+ });
116047
+ if (merged.EnvParams !== undefined) {
116048
+ dirty.EnvParams = merged.EnvParams;
116049
+ }
116050
+ }
116051
+ let Items;
116052
+ try {
116053
+ Items = (0, cloudrun_config_js_1.parseServerConfigToDiffItems)(dirty);
116054
+ }
116055
+ catch (error) {
116056
+ throw new Error(buildManageCloudRunErrorMessage("updateConfig", input.serverName, error));
116057
+ }
116058
+ if (Items.length === 0) {
116059
+ return {
116060
+ content: [
116061
+ {
116062
+ type: "text",
116063
+ text: JSON.stringify({
116064
+ success: true,
116065
+ data: {
116066
+ serviceName: input.serverName,
116067
+ status: "noop",
116068
+ itemsCount: 0,
116069
+ appliedConfig: (0, cloudrun_config_js_1.summarizeConfigSnapshot)(dirty),
116070
+ verifiedConfig: (0, cloudrun_config_js_1.summarizeConfigSnapshot)(remoteServerConfig),
116071
+ },
116072
+ message: `No effective config changes for '${input.serverName}'.`,
116073
+ }, null, 2),
116074
+ },
116075
+ ],
116076
+ };
116077
+ }
116078
+ const currentEnvId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
116079
+ if (!manager.commonService) {
116080
+ throw new Error("Current CloudBase Manager does not support commonService; cannot call SubmitServerConfigChangeDiff.");
116081
+ }
116082
+ let diffResult;
116083
+ try {
116084
+ diffResult = await manager
116085
+ .commonService("tcbr", "2022-02-17")
116086
+ .call({
116087
+ Action: "SubmitServerConfigChangeDiff",
116088
+ Param: {
116089
+ EnvId: currentEnvId,
116090
+ ServerName: input.serverName,
116091
+ Items,
116092
+ },
116093
+ });
116094
+ }
116095
+ catch (error) {
116096
+ const msg = error instanceof Error ? error.message : String(error);
116097
+ if (/ResourceInUse|task|running|进行中/i.test(msg)) {
116098
+ throw new Error(buildManageCloudRunErrorMessage("updateConfig", input.serverName, new Error(`${msg} A deploy or config task may still be running. Wait, then retry; or use queryCloudRun(action="getDeployLog").`)));
116099
+ }
116100
+ throw new Error(buildManageCloudRunErrorMessage("updateConfig", input.serverName, error));
116101
+ }
116102
+ let verifiedConfig = (0, cloudrun_config_js_1.summarizeConfigSnapshot)(remoteServerConfig);
116103
+ try {
116104
+ const after = await cloudrunService.detail({
116105
+ serverName: input.serverName,
116106
+ });
116107
+ verifiedConfig = (0, cloudrun_config_js_1.summarizeConfigSnapshot)(after?.ServerConfig);
116108
+ }
116109
+ catch {
116110
+ // best-effort verify
116111
+ }
116112
+ const likelyRedeploy = (0, cloudrun_config_js_1.listLikelyRedeployFields)(dirty);
116113
+ const consoleUrl = `https://tcb.cloud.tencent.com/dev?envId=${currentEnvId}#/platform-run/service/detail?serverName=${input.serverName}&tabId=overview&envId=${currentEnvId}`;
116114
+ const taskId = diffResult?.TaskId ??
116115
+ diffResult?.Response?.TaskId ??
116116
+ diffResult?.taskId;
116117
+ const redeployHint = likelyRedeploy.length > 0
116118
+ ? ` Fields that often trigger redeploy-with-online-image: ${likelyRedeploy.join(", ")}.`
116119
+ : " Change may apply as a hot update (e.g. MinNum/MaxNum/AccessTypes).";
116120
+ return {
116121
+ content: [
116122
+ {
116123
+ type: "text",
116124
+ text: JSON.stringify({
116125
+ success: true,
116126
+ data: {
116127
+ serviceName: input.serverName,
116128
+ status: "configUpdating",
116129
+ itemsCount: Items.length,
116130
+ itemsKeys: Items.map((i) => i.Key),
116131
+ ...(taskId ? { taskId } : {}),
116132
+ appliedConfig: (0, cloudrun_config_js_1.summarizeConfigSnapshot)(dirty),
116133
+ verifiedConfig,
116134
+ likelyRedeployFields: likelyRedeploy,
116135
+ consoleUrl,
116136
+ },
116137
+ message: `Submitted config change for '${input.serverName}'.${redeployHint} Verify with queryCloudRun(action="detail"). Console: ${consoleUrl}`,
116138
+ }, null, 2),
116139
+ },
116140
+ ],
116141
+ };
116142
+ }
115084
116143
  case 'run': {
115085
116144
  if (!targetPath) {
115086
116145
  throw new Error("targetPath is required for run operation");
@@ -117768,6 +118827,7 @@ const zod_1 = __webpack_require__(21614);
117768
118827
  const cloudbase_manager_js_1 = __webpack_require__(3431);
117769
118828
  const json_content_js_1 = __webpack_require__(4365);
117770
118829
  const cloud_mode_js_1 = __webpack_require__(89684);
118830
+ const gateway_access_urls_js_1 = __webpack_require__(22435);
117771
118831
  const QUERY_APP_ACTIONS = ["listApps", "getApp", "listAppVersions", "getAppVersion", "getBuildLog"];
117772
118832
  const MANAGE_APP_ACTIONS = ["deployApp", "getUploadUrl", "deleteApp", "deleteAppVersion"];
117773
118833
  const APP_FRAMEWORKS = ["vue", "react", "next", "nuxt", "vite", "angular", "static"];
@@ -118144,6 +119204,8 @@ function registerAppTools(server) {
118144
119204
  let appInfo;
118145
119205
  let domain;
118146
119206
  let accessUrl;
119207
+ let accessUrls = [];
119208
+ let accessUrlSource;
118147
119209
  let accessUrlLookupWarning;
118148
119210
  try {
118149
119211
  appInfo = await appService.describeAppInfo({
@@ -118152,9 +119214,34 @@ function registerAppTools(server) {
118152
119214
  });
118153
119215
  (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, appInfo);
118154
119216
  ({ domain, accessUrl } = normalizeAccessUrlFromDomain(appInfo?.Domain));
119217
+ const envId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
119218
+ const gateway = await (0, gateway_access_urls_js_1.resolveGatewayAccessUrls)({
119219
+ envId,
119220
+ upstreamResourceName: serviceName,
119221
+ upstreamResourceTypes: ["STATIC_STORE"],
119222
+ getManager: async () => {
119223
+ const manager = await getManager();
119224
+ if (!manager) {
119225
+ throw new Error("cloudbase manager unavailable");
119226
+ }
119227
+ return manager;
119228
+ },
119229
+ });
119230
+ const preferred = (0, gateway_access_urls_js_1.preferGatewayOrFallback)({
119231
+ gateway,
119232
+ fallbackUrl: accessUrl,
119233
+ fallbackSource: "describeAppInfo.Domain",
119234
+ });
119235
+ accessUrl = preferred.accessUrl;
119236
+ accessUrls = preferred.accessUrls;
119237
+ accessUrlSource = preferred.accessUrlSource;
118155
119238
  }
118156
119239
  catch (error) {
118157
119240
  accessUrlLookupWarning = error instanceof Error ? error.message : String(error);
119241
+ if (accessUrl) {
119242
+ accessUrls = [accessUrl];
119243
+ accessUrlSource = "describeAppInfo.Domain";
119244
+ }
118158
119245
  }
118159
119246
  return (0, json_content_js_1.jsonContent)(buildEnvelope({
118160
119247
  action,
@@ -118163,7 +119250,8 @@ function registerAppTools(server) {
118163
119250
  buildId: BuildId,
118164
119251
  domain,
118165
119252
  accessUrl,
118166
- accessUrlSource: accessUrl ? "describeAppInfo.Domain" : undefined,
119253
+ accessUrls: accessUrls.length > 0 ? accessUrls : undefined,
119254
+ accessUrlSource,
118167
119255
  accessUrlLookupWarning,
118168
119256
  app: appInfo,
118169
119257
  upload: { cosTimestamp: cosTs },
@@ -119537,6 +120625,7 @@ const path_1 = __importDefault(__webpack_require__(39902));
119537
120625
  const zod_1 = __webpack_require__(21614);
119538
120626
  const cloudbase_manager_js_1 = __webpack_require__(3431);
119539
120627
  const cloud_mode_js_1 = __webpack_require__(89684);
120628
+ const gateway_access_urls_js_1 = __webpack_require__(22435);
119540
120629
  const notification_js_1 = __webpack_require__(32720);
119541
120630
  const tool_result_js_1 = __webpack_require__(9835);
119542
120631
  const HOSTING_CDN_SWITCH_VALUES = ['on', 'off'];
@@ -120072,9 +121161,48 @@ function registerHostingTools(server) {
120072
121161
  // StaticDomain there but not in DescribeStaticStore.
120073
121162
  const cdnFromStore = (store.CdnDomain ?? store.StaticDomain);
120074
121163
  const staticDomain = cdnFromStore || await resolveHostingStaticDomain(cloudbase, server.logger);
120075
- const accessUrl = buildHostingAccessUrl(staticDomain, input.cloudPath, input.localPath);
121164
+ const fallbackAccessUrl = buildHostingAccessUrl(staticDomain, input.cloudPath, input.localPath);
121165
+ const envId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
121166
+ const gatewayCandidates = Array.from(new Set([
121167
+ store.StaticStoreName,
121168
+ store.Name,
121169
+ store.StoreName,
121170
+ store.Bucket,
121171
+ "staticstore",
121172
+ ]
121173
+ .map((item) => (typeof item === "string" ? item.trim() : ""))
121174
+ .filter(Boolean)));
121175
+ let accessUrl = fallbackAccessUrl;
121176
+ let accessUrls = accessUrl ? [accessUrl] : [];
121177
+ let accessUrlSource = accessUrl
121178
+ ? "hosting.staticDomain"
121179
+ : undefined;
121180
+ for (const upstreamName of gatewayCandidates) {
121181
+ const gateway = await (0, gateway_access_urls_js_1.resolveGatewayAccessUrls)({
121182
+ envId,
121183
+ upstreamResourceName: upstreamName,
121184
+ upstreamResourceTypes: ["STATIC_STORE"],
121185
+ getManager: async () => {
121186
+ const manager = await getManager();
121187
+ if (!manager) {
121188
+ throw new Error("cloudbase manager unavailable");
121189
+ }
121190
+ return manager;
121191
+ },
121192
+ });
121193
+ const preferred = (0, gateway_access_urls_js_1.preferGatewayOrFallback)({
121194
+ gateway,
121195
+ fallbackUrl: fallbackAccessUrl || undefined,
121196
+ fallbackSource: "hosting.staticDomain",
121197
+ });
121198
+ if (preferred.accessUrl) {
121199
+ accessUrl = preferred.accessUrl;
121200
+ accessUrls = preferred.accessUrls;
121201
+ accessUrlSource = preferred.accessUrlSource;
121202
+ break;
121203
+ }
121204
+ }
120076
121205
  try {
120077
- const envId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
120078
121206
  let projectName = 'unknown';
120079
121207
  if (input.localPath) {
120080
121208
  try {
@@ -120109,6 +121237,8 @@ function registerHostingTools(server) {
120109
121237
  ignore: input.ignore,
120110
121238
  staticDomain,
120111
121239
  accessUrl,
121240
+ accessUrls,
121241
+ accessUrlSource,
120112
121242
  result,
120113
121243
  nextActions: uploadPrefix ? [buildFindFilesNextStep(uploadPrefix.replace(/^\/+/, ''))] : undefined,
120114
121244
  },
@@ -137205,7 +138335,7 @@ class TelemetryReporter {
137205
138335
  const nodeVersion = process.version; // Node.js版本
137206
138336
  const arch = os_1.default.arch(); // 系统架构
137207
138337
  // 从构建时注入的版本号获取MCP版本信息
137208
- const mcpVersion = process.env.npm_package_version || "2.25.1" || 0;
138338
+ const mcpVersion = process.env.npm_package_version || "2.25.3" || 0;
137209
138339
  return {
137210
138340
  userAgent: `${osType} ${osRelease} ${arch} ${nodeVersion} CloudBase-MCP/${mcpVersion}`,
137211
138341
  deviceId: this.deviceId,
@@ -148174,6 +149304,220 @@ function compileAsync(schema, meta, callback) {
148174
149304
  }
148175
149305
 
148176
149306
 
149307
+ /***/ }),
149308
+
149309
+ /***/ 48266:
149310
+ /***/ ((__unused_webpack_module, exports) => {
149311
+
149312
+ "use strict";
149313
+
149314
+ /**
149315
+ * CloudRun serverConfig merge (RMW) and DiffConfigItem helpers.
149316
+ * Aligns with console SubmitServerConfigChangeDiff field mapping.
149317
+ */
149318
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
149319
+ exports.CONFIG_FIELDS_LIKELY_REDEPLOY = void 0;
149320
+ exports.mergeCloudRunServerConfig = mergeCloudRunServerConfig;
149321
+ exports.assertCpuMemPair = assertCpuMemPair;
149322
+ exports.parseServerConfigToDiffItems = parseServerConfigToDiffItems;
149323
+ exports.summarizeConfigSnapshot = summarizeConfigSnapshot;
149324
+ exports.listLikelyRedeployFields = listLikelyRedeployFields;
149325
+ const SUBMIT_DIFF_MAP = {
149326
+ Cpu: "CpuSpecs",
149327
+ Mem: "MemSpecs",
149328
+ OpenAccessTypes: "AccessTypes",
149329
+ EnvParams: "EnvParam",
149330
+ CustomLogs: "LogPath",
149331
+ };
149332
+ const STRING_KEYS = new Set([
149333
+ "CustomLogs",
149334
+ "EnvParams",
149335
+ "CreateTime",
149336
+ "Dockerfile",
149337
+ "BuildDir",
149338
+ "LogType",
149339
+ "LogSetId",
149340
+ "LogTopicId",
149341
+ "LogParseType",
149342
+ "Tag",
149343
+ "InternalAccess",
149344
+ "InternalDomain",
149345
+ "OperationMode",
149346
+ "SessionAffinity",
149347
+ ]);
149348
+ const INT_KEYS = new Set(["MinNum", "MaxNum", "InitialDelaySeconds", "Port"]);
149349
+ const BOOL_KEYS = new Set(["HasDockerfile"]);
149350
+ const FLOAT_KEYS = new Set(["Cpu", "Mem"]);
149351
+ const ARRAY_KEYS = new Set(["OpenAccessTypes", "EntryPoint", "Cmd"]);
149352
+ function parseEnvParamsObject(raw) {
149353
+ if (!raw || !String(raw).trim()) {
149354
+ return {};
149355
+ }
149356
+ try {
149357
+ const value = JSON.parse(String(raw));
149358
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
149359
+ return {};
149360
+ }
149361
+ const out = {};
149362
+ for (const [k, v] of Object.entries(value)) {
149363
+ if (v === undefined || v === null)
149364
+ continue;
149365
+ out[k] = typeof v === "string" ? v : String(v);
149366
+ }
149367
+ return out;
149368
+ }
149369
+ catch {
149370
+ return {};
149371
+ }
149372
+ }
149373
+ function stringifyEnvParams(obj) {
149374
+ return JSON.stringify(obj);
149375
+ }
149376
+ function isCompleteVpcConf(vpc) {
149377
+ return Boolean(vpc?.VpcId?.trim() && vpc?.SubnetId?.trim());
149378
+ }
149379
+ /**
149380
+ * Merge remote ServerConfig with deploy/update input.
149381
+ * Explicit input wins for provided fields; EnvParams merges by key unless replaceAll.
149382
+ */
149383
+ function mergeCloudRunServerConfig(options) {
149384
+ const remote = options.remote || {};
149385
+ const input = options.input || {};
149386
+ const mergedFromRemote = [];
149387
+ const merged = { ...input };
149388
+ if (isCompleteVpcConf(input.VpcConf)) {
149389
+ merged.VpcConf = {
149390
+ VpcId: input.VpcConf.VpcId.trim(),
149391
+ SubnetId: input.VpcConf.SubnetId.trim(),
149392
+ ...(input.VpcConf.VpcCIDR ? { VpcCIDR: input.VpcConf.VpcCIDR } : {}),
149393
+ ...(input.VpcConf.SubnetCIDR ? { SubnetCIDR: input.VpcConf.SubnetCIDR } : {}),
149394
+ };
149395
+ }
149396
+ else if (isCompleteVpcConf(remote.VpcConf)) {
149397
+ merged.VpcConf = {
149398
+ VpcId: remote.VpcConf.VpcId.trim(),
149399
+ SubnetId: remote.VpcConf.SubnetId.trim(),
149400
+ ...(remote.VpcConf.VpcCIDR ? { VpcCIDR: remote.VpcConf.VpcCIDR } : {}),
149401
+ ...(remote.VpcConf.SubnetCIDR ? { SubnetCIDR: remote.VpcConf.SubnetCIDR } : {}),
149402
+ };
149403
+ mergedFromRemote.push("VpcConf");
149404
+ }
149405
+ else {
149406
+ delete merged.VpcConf;
149407
+ }
149408
+ const inputHasEnv = Object.prototype.hasOwnProperty.call(input, "EnvParams");
149409
+ const remoteEnv = parseEnvParamsObject(remote.EnvParams);
149410
+ const inputEnv = parseEnvParamsObject(input.EnvParams);
149411
+ if (options.envParamsReplaceAll && inputHasEnv) {
149412
+ merged.EnvParams = stringifyEnvParams(inputEnv);
149413
+ }
149414
+ else if (inputHasEnv || Object.keys(remoteEnv).length > 0) {
149415
+ const combined = options.envParamsReplaceAll
149416
+ ? { ...inputEnv }
149417
+ : { ...remoteEnv, ...inputEnv };
149418
+ if (Object.keys(remoteEnv).length > 0 && !options.envParamsReplaceAll) {
149419
+ const preserved = Object.keys(remoteEnv).filter((k) => !(k in inputEnv));
149420
+ if (preserved.length > 0) {
149421
+ mergedFromRemote.push("EnvParams");
149422
+ }
149423
+ }
149424
+ if (Object.keys(combined).length > 0 || inputHasEnv) {
149425
+ merged.EnvParams = stringifyEnvParams(combined);
149426
+ }
149427
+ }
149428
+ // Must be explicit so Manager SDK update path cannot wipe with OA/PUBLIC/MINIAPP defaults.
149429
+ if (Array.isArray(input.OpenAccessTypes) && input.OpenAccessTypes.length > 0) {
149430
+ merged.OpenAccessTypes = [...input.OpenAccessTypes];
149431
+ }
149432
+ else if (Array.isArray(remote.OpenAccessTypes) && remote.OpenAccessTypes.length > 0) {
149433
+ merged.OpenAccessTypes = [...remote.OpenAccessTypes];
149434
+ mergedFromRemote.push("OpenAccessTypes");
149435
+ }
149436
+ return { merged, mergedFromRemote };
149437
+ }
149438
+ function assertCpuMemPair(config) {
149439
+ const hasCpu = config.Cpu !== undefined && config.Cpu !== null;
149440
+ const hasMem = config.Mem !== undefined && config.Mem !== null;
149441
+ if (hasCpu !== hasMem) {
149442
+ throw new Error("Cpu and Mem must be provided together when updating CloudRun config (platform requires the pair).");
149443
+ }
149444
+ }
149445
+ /**
149446
+ * Convert serverConfig object to DiffConfigItem[] for SubmitServerConfigChangeDiff.
149447
+ */
149448
+ function parseServerConfigToDiffItems(data) {
149449
+ assertCpuMemPair(data);
149450
+ const Items = [];
149451
+ for (const [k, v] of Object.entries(data)) {
149452
+ if (v === undefined || v === null)
149453
+ continue;
149454
+ const Key = SUBMIT_DIFF_MAP[k] || k;
149455
+ if (STRING_KEYS.has(k)) {
149456
+ if (v !== "") {
149457
+ Items.push({ Key, Value: String(v) });
149458
+ }
149459
+ }
149460
+ else if (INT_KEYS.has(k)) {
149461
+ Items.push({ Key, IntValue: Number(v) });
149462
+ }
149463
+ else if (BOOL_KEYS.has(k)) {
149464
+ Items.push({ Key, BoolValue: Boolean(v) });
149465
+ }
149466
+ else if (FLOAT_KEYS.has(k)) {
149467
+ Items.push({ Key, FloatValue: Number(v) });
149468
+ }
149469
+ else if (ARRAY_KEYS.has(k)) {
149470
+ Items.push({ Key, ArrayValue: v });
149471
+ }
149472
+ else if (k === "PolicyDetails") {
149473
+ Items.push({ Key, PolicyDetails: v });
149474
+ }
149475
+ else if (k === "TimerScale") {
149476
+ Items.push({ Key, TimerScale: v });
149477
+ }
149478
+ else if (k === "VpcConf") {
149479
+ Items.push({ Key, VpcConf: v });
149480
+ }
149481
+ else if (k === "VolumesConf") {
149482
+ Items.push({ Key, VolumesConf: v });
149483
+ }
149484
+ else if (k === "PublicNetConf") {
149485
+ Items.push({ Key, PublicNetConf: v });
149486
+ }
149487
+ }
149488
+ return Items;
149489
+ }
149490
+ function summarizeConfigSnapshot(config) {
149491
+ const vpc = config?.VpcConf;
149492
+ const envKeys = Object.keys(parseEnvParamsObject(config?.EnvParams));
149493
+ return {
149494
+ hasVpcConf: isCompleteVpcConf(vpc),
149495
+ ...(vpc?.VpcId ? { vpcId: vpc.VpcId } : {}),
149496
+ ...(vpc?.SubnetId ? { subnetId: vpc.SubnetId } : {}),
149497
+ ...(Array.isArray(config?.OpenAccessTypes)
149498
+ ? { openAccessTypes: config.OpenAccessTypes }
149499
+ : {}),
149500
+ envParamKeys: envKeys,
149501
+ };
149502
+ }
149503
+ exports.CONFIG_FIELDS_LIKELY_REDEPLOY = [
149504
+ "VpcConf",
149505
+ "EnvParams",
149506
+ "Cpu",
149507
+ "Mem",
149508
+ "Port",
149509
+ "Dockerfile",
149510
+ "BuildDir",
149511
+ "VolumesConf",
149512
+ "LogType",
149513
+ "LogSetId",
149514
+ "LogTopicId",
149515
+ ];
149516
+ function listLikelyRedeployFields(config) {
149517
+ return exports.CONFIG_FIELDS_LIKELY_REDEPLOY.filter((k) => Object.prototype.hasOwnProperty.call(config, k));
149518
+ }
149519
+
149520
+
148177
149521
  /***/ }),
148178
149522
 
148179
149523
  /***/ 48303:
@@ -160875,6 +162219,68 @@ function isSchemaDdlRisk(risk, sql) {
160875
162219
  function buildLocalMigrationFileHint(version, name) {
160876
162220
  return `migrations/${version}_${name}.sql`;
160877
162221
  }
162222
+ /** How many recent migration records to scan when verifying a freshly pushed version. */
162223
+ const MIGRATION_VERIFY_LIMIT = 100;
162224
+ /**
162225
+ * Collect every migration version mentioned anywhere in a migration-list API response.
162226
+ * The response shape is not strongly typed, so walk it generically and pick up any
162227
+ * `Version` / `MigrationVersion` string field instead of guessing a single container key.
162228
+ */
162229
+ function collectMigrationVersions(value, found = new Set()) {
162230
+ if (Array.isArray(value)) {
162231
+ for (const item of value) {
162232
+ collectMigrationVersions(item, found);
162233
+ }
162234
+ return found;
162235
+ }
162236
+ if (value && typeof value === "object") {
162237
+ for (const [key, child] of Object.entries(value)) {
162238
+ if ((key === "Version" || key === "MigrationVersion") && typeof child === "string" && child.trim()) {
162239
+ found.add(child.trim());
162240
+ }
162241
+ else {
162242
+ collectMigrationVersions(child, found);
162243
+ }
162244
+ }
162245
+ }
162246
+ return found;
162247
+ }
162248
+ /** Brief retries before concluding a pushed migration never landed (Push can be async). */
162249
+ const MIGRATION_VERIFY_ATTEMPTS = 4;
162250
+ const MIGRATION_VERIFY_DELAY_MS = 1500;
162251
+ /**
162252
+ * Confirm a pushed migration version is present in the remote migration history.
162253
+ *
162254
+ * `PushPGUserMigrations` can return a TaskId without the migration actually being
162255
+ * applied, so the raw API response is not sufficient evidence of success. Retries
162256
+ * briefly to tolerate async application, then returns `true`/`false` when the
162257
+ * history could be read, or `null` when verification itself failed (in which case
162258
+ * the caller must not claim the migration is applied).
162259
+ */
162260
+ async function verifyMigrationApplied(context, version, cloudBaseOptions) {
162261
+ let lastError;
162262
+ let sawSuccessfulList = false;
162263
+ for (let attempt = 1; attempt <= MIGRATION_VERIFY_ATTEMPTS; attempt++) {
162264
+ try {
162265
+ const history = await callPgMigrationApi(context, "ListPGUserMigrations", { Limit: MIGRATION_VERIFY_LIMIT }, cloudBaseOptions);
162266
+ sawSuccessfulList = true;
162267
+ if (collectMigrationVersions(history).has(version)) {
162268
+ return { applied: true };
162269
+ }
162270
+ }
162271
+ catch (error) {
162272
+ lastError = error instanceof Error ? error.message : String(error);
162273
+ // Keep retrying: a transient list failure should not immediately fail verification.
162274
+ }
162275
+ if (attempt < MIGRATION_VERIFY_ATTEMPTS) {
162276
+ await sleep(MIGRATION_VERIFY_DELAY_MS);
162277
+ }
162278
+ }
162279
+ if (sawSuccessfulList) {
162280
+ return { applied: false };
162281
+ }
162282
+ return { applied: null, error: lastError };
162283
+ }
160878
162284
  const MIGRATION_VERSION_REQUIRED_MESSAGE = "migrationVersion is required (14-digit UTC timestamp YYYYMMDDHHMMSS). " +
160879
162285
  "Decide the version first, write local file migrations/<version>_<migrationName>.sql, " +
160880
162286
  "then call planMigration/applyMigration with the same migrationVersion and migrationName.";
@@ -161747,6 +163153,49 @@ async function handleApplyMigration(args, context, deps, cloudBaseOptions) {
161747
163153
  }
161748
163154
  try {
161749
163155
  const result = await callPgMigrationApi(context, "PushPGUserMigrations", params, cloudBaseOptions);
163156
+ // PushPGUserMigrations may return a TaskId without the migration having taken
163157
+ // effect. Confirm against the remote history before reporting success, so callers
163158
+ // never get a false-positive success for a silently dropped migration.
163159
+ const verification = await verifyMigrationApplied(context, version, cloudBaseOptions);
163160
+ if (verification.applied === false) {
163161
+ return buildPgToolResult({
163162
+ success: false,
163163
+ errorCode: "MIGRATION_NOT_APPLIED",
163164
+ data: {
163165
+ migrationVersion: version,
163166
+ migrationName: args.migrationName,
163167
+ localFileHint,
163168
+ apiResult: result,
163169
+ verified: false,
163170
+ },
163171
+ message: `PushPGUserMigrations returned without error, but migrationVersion=${version} is not present in the remote migration history, ` +
163172
+ "so the migration did NOT take effect. Do not assume the schema change is applied. " +
163173
+ "Re-check the SQL and migrationVersion, inspect the migration with action=migrationDetail, and retry action=applyMigration. " +
163174
+ "If the schema change is urgent you may fall back to action=execute with allowDdlViaExecute=true, but that bypasses migration history.",
163175
+ nextActions: [
163176
+ buildNextAction(MANAGE_PG_DATABASE, "listMigrations", "Inspect the remote migration history to confirm the migration is missing.", { action: "listMigrations", limit: 20 }),
163177
+ buildNextAction(MANAGE_PG_DATABASE, "migrationDetail", "Inspect the backend record for this migrationVersion to find why it was not applied.", { action: "migrationDetail", migrationVersion: version }),
163178
+ ],
163179
+ });
163180
+ }
163181
+ if (verification.applied === null) {
163182
+ return buildPgToolResult({
163183
+ success: false,
163184
+ errorCode: "MIGRATION_VERIFICATION_FAILED",
163185
+ data: {
163186
+ migrationVersion: version,
163187
+ migrationName: args.migrationName,
163188
+ localFileHint,
163189
+ apiResult: result,
163190
+ verified: null,
163191
+ },
163192
+ message: `PushPGUserMigrations was submitted, but verifying migrationVersion=${version} against the remote history failed: ${verification.error}. ` +
163193
+ "The migration may or may not have been applied — verify with action=listMigrations before running any dependent SQL.",
163194
+ nextActions: [
163195
+ buildNextAction(MANAGE_PG_DATABASE, "listMigrations", "Manually verify whether the remote migration history records this migrationVersion.", { action: "listMigrations", limit: 20 }),
163196
+ ],
163197
+ });
163198
+ }
161750
163199
  return buildPgToolResult({
161751
163200
  success: true,
161752
163201
  data: {
@@ -161754,11 +163203,9 @@ async function handleApplyMigration(args, context, deps, cloudBaseOptions) {
161754
163203
  migrationName: args.migrationName,
161755
163204
  localFileHint,
161756
163205
  apiResult: result,
163206
+ verified: true,
161757
163207
  },
161758
- message: `Migrations applied via PushPGUserMigrations. Ensure local file ${localFileHint} exists and matches.`,
161759
- nextActions: [
161760
- buildNextAction(MANAGE_PG_DATABASE, "listMigrations", "Verify the remote migration history records the same migrationVersion.", { action: "listMigrations", limit: 20 }),
161761
- ],
163208
+ message: `Migrations applied via PushPGUserMigrations and verified present in the remote migration history. Ensure local file ${localFileHint} exists and matches.`,
161762
163209
  });
161763
163210
  }
161764
163211
  catch (error) {
@@ -162037,7 +163484,7 @@ function registerPGDatabaseTools(server, providedDeps) {
162037
163484
  inputSchema: {
162038
163485
  action: zod_1.z
162039
163486
  .enum(MANAGE_ACTIONS)
162040
- .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)"),
163487
+ .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)"),
162041
163488
  sql: zod_1.z
162042
163489
  .string()
162043
163490
  .optional()
@@ -197301,7 +198748,7 @@ ${envIdSection}
197301
198748
  ## 环境信息
197302
198749
  - 操作系统: ${os_1.default.type()} ${os_1.default.release()}
197303
198750
  - Node.js版本: ${process.version}
197304
- - MCP 版本:${process.env.npm_package_version || "2.25.1" || 0}
198751
+ - MCP 版本:${process.env.npm_package_version || "2.25.3" || 0}
197305
198752
  - 系统架构: ${os_1.default.arch()}
197306
198753
  - 时间: ${new Date().toISOString()}
197307
198754
  - 请求ID: ${requestId}
@@ -197382,7 +198829,7 @@ function createWrappedHandler(name, handler, server) {
197382
198829
  requestId: (typeof error === 'object' && error && 'requestId' in error) ? error.requestId : '',
197383
198830
  ide: server.ide || process.env.INTEGRATION_IDE || ''
197384
198831
  });
197385
- const mcpVersion = true ? "2.25.1" : 0;
198832
+ const mcpVersion = true ? "2.25.3" : 0;
197386
198833
  const requestIdSuffix = requestId ? `\n🆔 RequestId: ${requestId}` : '';
197387
198834
  const enhancedErrorMessage = `${errorMessage}${requestIdSuffix}\n\n📦 CloudBase MCP v${mcpVersion}\n🔗 遇到问题?请复制以下链接到浏览器打开\n即可自动携带错误详情快速创建 GitHub Issue:\n${issueLink}`;
197388
198835
  // 创建新的错误对象,保持原有的错误类型但更新消息
@@ -213970,7 +215417,7 @@ function registerSetupTools(server) {
213970
215417
  server.registerTool("downloadTemplate", {
213971
215418
  title: "下载项目模板",
213972
215419
  description: `自动下载并部署CloudBase项目模板。
213973
- **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.1" : 0}),便于后续维护和版本追踪\n- 下载 rules 模板时,如果项目中已存在 README.md 文件,系统会自动保护该文件不被覆盖(除非设置 overwrite=true)`,
215420
+ **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.3" : 0}),便于后续维护和版本追踪\n- 下载 rules 模板时,如果项目中已存在 README.md 文件,系统会自动保护该文件不被覆盖(除非设置 overwrite=true)`,
213974
215421
  inputSchema: {
213975
215422
  template: zod_1.z
213976
215423
  .enum(["react", "vue", "miniprogram", "uniapp", "rules"])
@@ -231068,6 +232515,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true }));
231068
232515
  exports.registerGatewayTools = registerGatewayTools;
231069
232516
  const zod_1 = __webpack_require__(21614);
231070
232517
  const cloudbase_manager_js_1 = __webpack_require__(3431);
232518
+ const gateway_access_urls_js_1 = __webpack_require__(22435);
231071
232519
  const json_content_js_1 = __webpack_require__(4365);
231072
232520
  const QUERY_GATEWAY_ACTIONS = [
231073
232521
  "listRoutes",
@@ -231081,6 +232529,8 @@ const MANAGE_GATEWAY_ACTIONS = [
231081
232529
  "bindCustomDomain",
231082
232530
  "deleteCustomDomain",
231083
232531
  ];
232532
+ /** DomainType of the environment default HTTP service (gateway) domain. */
232533
+ const HTTP_SERVICE_DOMAIN_TYPE = "HTTPSERVICE";
231084
232534
  const UPSTREAM_RESOURCE_TYPES = [
231085
232535
  "SCF",
231086
232536
  "WEB_SCF",
@@ -231117,21 +232567,19 @@ function registerGatewayTools(server) {
231117
232567
  return (0, json_content_js_1.jsonContent)(buildErrorEnvelope(error));
231118
232568
  }
231119
232569
  };
231120
- const listHttpServiceRoutes = async (domain) => {
232570
+ const listHttpServiceRoutes = async (options) => {
232571
+ const filters = [];
232572
+ if (options?.domain) {
232573
+ filters.push({ Name: "Domain", Values: [options.domain] });
232574
+ }
232575
+ if (options?.domainType) {
232576
+ filters.push({ Name: "DomainType", Values: [options.domainType] });
232577
+ }
231121
232578
  const cloudbase = await getManager();
231122
232579
  const result = await cloudbase.env.describeHttpServiceRoute({
231123
232580
  EnvId: await resolveEnvId(),
231124
232581
  Limit: 1000,
231125
- ...(domain
231126
- ? {
231127
- Filters: [
231128
- {
231129
- Name: "Domain",
231130
- Values: [domain],
231131
- },
231132
- ],
231133
- }
231134
- : {}),
232582
+ ...(filters.length ? { Filters: filters } : {}),
231135
232583
  });
231136
232584
  (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
231137
232585
  return result;
@@ -231143,18 +232591,54 @@ function registerGatewayTools(server) {
231143
232591
  IsDefault: domainItem.IsDefault,
231144
232592
  ...route,
231145
232593
  })));
231146
- const buildRouteUrls = (routes) => Array.from(new Set(routes
231147
- .filter((route) => route.Domain && route.Path)
231148
- .map((route) => `https://${route.Domain}${normalizeAccessPath(String(route.Path))}`)));
232594
+ const buildRouteUrls = (routes) => {
232595
+ const candidates = routes.map((route) => ({
232596
+ Domain: route.Domain,
232597
+ Path: route.Path,
232598
+ IsDefault: route.IsDefault,
232599
+ UpstreamResourceType: route.UpstreamResourceType,
232600
+ UpstreamResourceName: route.UpstreamResourceName,
232601
+ }));
232602
+ return (0, gateway_access_urls_js_1.rankGatewayAccessUrls)(candidates).map((item) => item.url);
232603
+ };
232604
+ const buildAccessUrlFields = (routes) => {
232605
+ const candidates = routes.map((route) => ({
232606
+ Domain: route.Domain,
232607
+ Path: route.Path,
232608
+ IsDefault: route.IsDefault,
232609
+ UpstreamResourceType: route.UpstreamResourceType,
232610
+ UpstreamResourceName: route.UpstreamResourceName,
232611
+ }));
232612
+ const envelope = (0, gateway_access_urls_js_1.toAccessUrlEnvelope)((0, gateway_access_urls_js_1.rankGatewayAccessUrls)(candidates));
232613
+ return {
232614
+ ...(envelope.accessUrl ? { accessUrl: envelope.accessUrl } : {}),
232615
+ accessUrls: envelope.accessUrls,
232616
+ ...(envelope.accessUrlSource
232617
+ ? { accessUrlSource: envelope.accessUrlSource }
232618
+ : {}),
232619
+ };
232620
+ };
232621
+ const pickUsableDefaultDomain = (domains) => {
232622
+ const candidates = domains.filter((item) => item.IsDefault === true && item.Domain);
232623
+ return (candidates.find((item) => item.Enable !== false && item.Status === "SUCCESS") ??
232624
+ candidates.find((item) => item.Enable !== false) ??
232625
+ candidates[0]);
232626
+ };
231149
232627
  const resolveDefaultHttpDomain = async () => {
231150
- const routeInfo = await listHttpServiceRoutes();
231151
- const domains = routeInfo.Domains ?? [];
231152
- const defaultCandidates = domains.filter((item) => item.IsDefault === true && item.Domain);
231153
- const preferred = defaultCandidates.find((item) => item.Enable !== false && item.Status === "SUCCESS") ??
231154
- defaultCandidates.find((item) => item.Enable !== false) ??
231155
- defaultCandidates[0];
232628
+ // Match console DescribeHTTPServiceRoute usage: filter DomainType=HTTPSERVICE.
232629
+ // Envs often also expose an IsDefault STATIC_STORE domain (*.tcloudbaseapp.com);
232630
+ // that is NOT the default HTTP access entry (*.{region}.app.tcloudbase.com).
232631
+ const httpServiceRoutes = await listHttpServiceRoutes({
232632
+ domainType: HTTP_SERVICE_DOMAIN_TYPE,
232633
+ });
232634
+ // Always re-filter client-side: some SDKs/mocks may ignore Filters.
232635
+ let preferred = pickUsableDefaultDomain((httpServiceRoutes.Domains ?? []).filter((item) => item.DomainType === HTTP_SERVICE_DOMAIN_TYPE));
232636
+ if (!preferred?.Domain) {
232637
+ const allRoutes = await listHttpServiceRoutes();
232638
+ preferred = pickUsableDefaultDomain((allRoutes.Domains ?? []).filter((item) => item.DomainType === HTTP_SERVICE_DOMAIN_TYPE));
232639
+ }
231156
232640
  if (!preferred?.Domain) {
231157
- throw new Error("环境默认 HTTP 访问域名未就绪或未开通。请先在控制台开通 HTTP 访问服务,或用 queryGateway(action=\"listRoutes\") 确认 Domains 中是否存在 IsDefault=true 的域名;也可以显式传入 domain 后重试 createRoute/updateRoute/deleteRoute。");
232641
+ throw new Error("环境默认 HTTP 访问域名未就绪或未开通。请先在控制台开通 HTTP 访问服务,或用 queryGateway(action=\"listRoutes\") 确认 Domains 中是否存在 DomainType=HTTPSERVICE 且 IsDefault=true 的域名(形如 *.{region}.app.tcloudbase.com);不要使用静态托管域名(*.tcloudbaseapp.com)。也可以显式传入 domain 后重试 createRoute/updateRoute/deleteRoute。");
231158
232642
  }
231159
232643
  return preferred.Domain;
231160
232644
  };
@@ -231250,12 +232734,13 @@ function registerGatewayTools(server) {
231250
232734
  }, `已获取 ${customDomains.length} 个自定义域名`);
231251
232735
  }
231252
232736
  case "listRoutes": {
231253
- const result = await listHttpServiceRoutes(input.domain);
232737
+ const result = await listHttpServiceRoutes({ domain: input.domain });
231254
232738
  const routes = flattenRoutes(result);
231255
232739
  return buildEnvelope({
231256
232740
  action: input.action,
231257
232741
  routes,
231258
232742
  urls: buildRouteUrls(routes),
232743
+ ...buildAccessUrlFields(routes),
231259
232744
  total: result.TotalCount ?? routes.length,
231260
232745
  raw: result,
231261
232746
  }, `已获取 ${result.TotalCount ?? routes.length} 条 HTTP 路由`);
@@ -231264,7 +232749,7 @@ function registerGatewayTools(server) {
231264
232749
  if (!input.routeId && !input.targetName && !input.path) {
231265
232750
  throw new Error("action=getRoute 时至少需要提供 routeId、targetName 或 path");
231266
232751
  }
231267
- const result = await listHttpServiceRoutes(input.domain);
232752
+ const result = await listHttpServiceRoutes({ domain: input.domain });
231268
232753
  const normalizedPath = input.path
231269
232754
  ? normalizeAccessPath(input.path)
231270
232755
  : undefined;
@@ -231297,6 +232782,7 @@ function registerGatewayTools(server) {
231297
232782
  routes: matches,
231298
232783
  total: matches.length,
231299
232784
  urls,
232785
+ ...buildAccessUrlFields(matches),
231300
232786
  raw: result,
231301
232787
  }, matches.length === 0
231302
232788
  ? "未找到对应路由"
@@ -231350,6 +232836,11 @@ function registerGatewayTools(server) {
231350
232836
  upstreamResourceName: payload.resolved.upstreamResourceName,
231351
232837
  auth: payload.resolved.enableAuth ?? null,
231352
232838
  enablePathTransmission: payload.resolved.enablePathTransmission ?? null,
232839
+ accessUrl: `https://${payload.resolved.domain}${payload.resolved.path}`,
232840
+ accessUrls: [`https://${payload.resolved.domain}${payload.resolved.path}`],
232841
+ accessUrlSource: input.domain && input.domain === payload.resolved.domain
232842
+ ? "gateway.custom"
232843
+ : "gateway.default",
231353
232844
  raw: result,
231354
232845
  }, `已为目标 ${payload.resolved.upstreamResourceName} 在域名 ${payload.resolved.domain} 创建路由 ${payload.resolved.path}(${payload.resolved.upstreamResourceType})` +
231355
232846
  (payload.resolved.enablePathTransmission === true
@@ -231376,6 +232867,11 @@ function registerGatewayTools(server) {
231376
232867
  upstreamResourceName: payload.resolved.upstreamResourceName,
231377
232868
  auth: payload.resolved.enableAuth ?? null,
231378
232869
  enablePathTransmission: payload.resolved.enablePathTransmission ?? null,
232870
+ accessUrl: `https://${payload.resolved.domain}${payload.resolved.path}`,
232871
+ accessUrls: [`https://${payload.resolved.domain}${payload.resolved.path}`],
232872
+ accessUrlSource: input.domain && input.domain === payload.resolved.domain
232873
+ ? "gateway.custom"
232874
+ : "gateway.default",
231379
232875
  raw: result,
231380
232876
  }, `HTTP 路由更新成功(${payload.resolved.domain}${payload.resolved.path}` +
231381
232877
  (payload.resolved.enablePathTransmission === true
@@ -231451,11 +232947,13 @@ function registerGatewayTools(server) {
231451
232947
  title: "查询 CloudBase 网关",
231452
232948
  description: "CloudBase HTTP 网关统一只读入口(Domain/Route)。查询域名下路径路由及其上游:" +
231453
232949
  "WEB_SCF/SCF=云函数,CBR=云托管,STATIC_STORE=静态托管,LH=轻量应用服务器。" +
231454
- "主键为 Domain + Path;listRoutes / getRoute / listCustomDomains。",
232950
+ "主键为 Domain + Path;listRoutes / getRoute / listCustomDomains。" +
232951
+ "实现自定义域名访问前,先 listCustomDomains:若已有自定义域名,优先 createRoute 挂路由(无需证书 ID);仅在没有可用自定义域名时才 bindCustomDomain。",
231455
232952
  inputSchema: {
231456
232953
  action: zod_1.z
231457
232954
  .enum(QUERY_GATEWAY_ACTIONS)
231458
- .describe("只读操作类型:listRoutes、getRoute、listCustomDomains"),
232955
+ .describe("只读操作类型:listRoutes、getRoute、listCustomDomains。" +
232956
+ "自定义域名访问场景先 listCustomDomains 确认是否已有域名可复用。"),
231459
232957
  targetName: zod_1.z
231460
232958
  .string()
231461
232959
  .optional()
@@ -231478,18 +232976,23 @@ function registerGatewayTools(server) {
231478
232976
  }, async (input) => withEnvelope(() => handleQueryGateway(input)));
231479
232977
  server.registerTool?.("manageGateway", {
231480
232978
  title: "管理 CloudBase 网关",
231481
- description: "CloudBase HTTP 网关统一写入口(Domain/Route)。createRoute/updateRoute/deleteRoute 把域名下的 path 转到上游;未传 domain 时用 IsDefault 默认域名。" +
232979
+ description: "CloudBase HTTP 网关统一写入口(Domain/Route)。createRoute/updateRoute/deleteRoute 把域名下的 path 转到上游;未传 domain 时用 DomainType=HTTPSERVICE 的 IsDefault 默认 HTTP 域名(形如 *.{region}.app.tcloudbase.com),不会使用静态托管 CDN 域名(*.tcloudbaseapp.com,DomainType=STATIC_STORE)。" +
232980
+ "这是网关默认域上的路径路由,不是 STATIC_STORE 上游绑定;STATIC_STORE 上游必须显式传 upstreamResourceType=STATIC_STORE。" +
232981
+ "创建后可用 queryGateway(action=\"listRoutes\") 核对 Domain / DomainType / Path / UpstreamResourceType。" +
231482
232982
  "上游类型只用一个参数 upstreamResourceType(也可写在 route.upstreamResourceType,route 优先):" +
231483
232983
  "WEB_SCF=HTTP云函数,SCF=Event云函数,CBR=云托管,STATIC_STORE=静态托管,LH=轻量应用服务器;" +
231484
232984
  "配合 targetName 或 route.serviceName(云函数名/云托管服务名/静态托管实例名,常见 staticstore)。" +
231485
232985
  "createRoute 只建网关入口,不改上游权限。" +
231486
232986
  "enablePathTransmission:默认 false 剥触发路径前缀;true 透传完整路径(CBR 多路由、WEB_SCF 自管子路径常需 true;STATIC_STORE 自定义触发路径映射站点根通常 false)。" +
231487
- "⚠️ SSL 自定义域名用 bindCustomDomain;CORS/安全域名用 envDomainManagement。",
232987
+ "⚠️ 自定义域名访问:若环境已有自定义域名(先 queryGateway listCustomDomains),优先 createRoute 并显式传入该 domain,无需 certificateId;" +
232988
+ "仅首次绑定全新自定义域名时用 bindCustomDomain(需 certificateId)。CORS/安全域名用 envDomainManagement。",
231488
232989
  inputSchema: {
231489
232990
  action: zod_1.z
231490
232991
  .enum(MANAGE_GATEWAY_ACTIONS)
231491
232992
  .describe("写操作:createRoute/updateRoute/deleteRoute 管理路由;bindCustomDomain/deleteCustomDomain 管理自定义域名。" +
231492
- "createRoute/updateRoute 必须提供 upstreamResourceType。"),
232993
+ "createRoute/updateRoute 必须提供 upstreamResourceType。" +
232994
+ "已有自定义域名时优先 createRoute(domain=已有域名) 实现访问,不必再次 bindCustomDomain / 传入 certificateId;" +
232995
+ "bindCustomDomain 仅用于首次绑定新域名。"),
231493
232996
  targetName: zod_1.z
231494
232997
  .string()
231495
232998
  .optional()
@@ -231543,11 +233046,15 @@ function registerGatewayTools(server) {
231543
233046
  domain: zod_1.z
231544
233047
  .string()
231545
233048
  .optional()
231546
- .describe("域名。省略时自动使用环境 IsDefault 默认 HTTP 域名;自定义域名场景请显式传入"),
233049
+ .describe("域名。省略时自动使用环境 DomainType=HTTPSERVICE 的 IsDefault 默认 HTTP 域名(*.{region}.app.tcloudbase.com),不会回退到静态托管 CDN 域名(*.tcloudbaseapp.com,DomainType=STATIC_STORE);也不是 STATIC_STORE 上游绑定。" +
233050
+ "可用 queryGateway(action=\"listRoutes\") 核对实际 Domain / DomainType。" +
233051
+ "已有自定义域名时请显式传入该域名并 createRoute/updateRoute/deleteRoute,即可实现自定义域名访问且无需证书 ID;" +
233052
+ "仅 bindCustomDomain 时表示要新绑定的域名。"),
231547
233053
  certificateId: zod_1.z
231548
233054
  .string()
231549
233055
  .optional()
231550
- .describe("证书 ID。bindCustomDomain 时必填"),
233056
+ .describe("证书 ID。仅首次 bindCustomDomain 必填。" +
233057
+ "在已有自定义域名上 createRoute / updateRoute / deleteRoute 不需要 certificateId。"),
231551
233058
  },
231552
233059
  annotations: {
231553
233060
  readOnlyHint: false,