@cloudbase/cloudbase-mcp 2.26.0 → 2.27.0

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
@@ -28452,6 +28452,7 @@ const manager_node_1 = __importDefault(__webpack_require__(95492));
28452
28452
  const auth_js_1 = __webpack_require__(77291);
28453
28453
  const logger_js_1 = __webpack_require__(13039);
28454
28454
  const tool_result_js_1 = __webpack_require__(9835);
28455
+ const site_map_js_1 = __webpack_require__(68107);
28455
28456
  // Timeout for envId auto-resolution flow.
28456
28457
  // 10 minutes (600 seconds) - matches InteractiveServer timeout
28457
28458
  const ENV_ID_TIMEOUT = 600000;
@@ -28476,7 +28477,7 @@ function createManagerFromLoginState(loginState, region) {
28476
28477
  envId: loginState.envId,
28477
28478
  token: loginState.token,
28478
28479
  proxy: process.env.http_proxy,
28479
- region: region ?? process.env.TCB_REGION ?? 'ap-shanghai',
28480
+ region: region ?? (0, site_map_js_1.resolveSiteAndRegion)().region,
28480
28481
  });
28481
28482
  }
28482
28483
  async function listAvailableEnvCandidates(options) {
@@ -28504,7 +28505,7 @@ async function listAvailableEnvCandidates(options) {
28504
28505
  if (!loginState?.secretId || !loginState?.secretKey) {
28505
28506
  return [];
28506
28507
  }
28507
- const region = cloudBaseOptions?.region ?? process.env.TCB_REGION ?? 'ap-shanghai';
28508
+ const region = (0, site_map_js_1.resolveSiteAndRegion)(cloudBaseOptions ?? {}).region;
28508
28509
  cloudbase = createManagerFromLoginState(loginState, region);
28509
28510
  }
28510
28511
  try {
@@ -28705,7 +28706,10 @@ function getCachedEnvId() {
28705
28706
  const databaseInstanceIdCache = new Map();
28706
28707
  function buildDatabaseInstanceIdCacheKey(options) {
28707
28708
  const envId = options?.envId ?? options?.cloudBaseOptions?.envId ?? process.env.CLOUDBASE_ENV_ID ?? 'unknown';
28708
- const region = options?.region ?? options?.cloudBaseOptions?.region ?? process.env.TCB_REGION ?? 'ap-shanghai';
28709
+ const region = (0, site_map_js_1.resolveSiteAndRegion)({
28710
+ site: options?.cloudBaseOptions?.site,
28711
+ region: options?.region ?? options?.cloudBaseOptions?.region,
28712
+ }).region;
28709
28713
  return `${region}:${envId}`;
28710
28714
  }
28711
28715
  function resetDatabaseInstanceIdCache() {
@@ -28811,11 +28815,11 @@ async function getCloudBaseManager(options = {}) {
28811
28815
  });
28812
28816
  }
28813
28817
  try {
28814
- // Region priority: explicit option > env var > ap-shanghai default
28815
- const fallbackRegion = cloudBaseOptions?.region ?? process.env.TCB_REGION ?? 'ap-shanghai';
28818
+ // Region priority: explicit option > TCB_REGION/TCB_SITE env > .cloudbase/project.json > ap-shanghai default
28819
+ const { region: fallbackRegion, site } = (0, site_map_js_1.resolveSiteAndRegion)(cloudBaseOptions ?? {});
28816
28820
  const loginState = authStrategy === 'ensure'
28817
- ? await (0, auth_js_1.getLoginState)({ region: fallbackRegion })
28818
- : await (0, auth_js_1.peekLoginState)();
28821
+ ? await (0, auth_js_1.getLoginState)({ region: fallbackRegion, site })
28822
+ : await (0, auth_js_1.peekLoginState)({ region: fallbackRegion, site });
28819
28823
  if (!loginState) {
28820
28824
  const authState = await (0, auth_js_1.getAuthProgressState)();
28821
28825
  if (authState.status === 'PENDING') {
@@ -28863,7 +28867,7 @@ async function getCloudBaseManager(options = {}) {
28863
28867
  }
28864
28868
  // envId priority: explicit option > envManager cache > loginState.envId
28865
28869
  const resolvedEnvId = finalEnvId || loginEnvId;
28866
- // region 直接使用 fallbackRegion(来自 cloudBaseOptions?.region ?? TCB_REGION ?? 'ap-shanghai')
28870
+ // region 直接使用 fallbackRegion(resolveSiteAndRegion 统一解析)
28867
28871
  // 不再通过 DescribeEnvs 查询 region,以兼容 STS 临时密钥场景
28868
28872
  const region = fallbackRegion;
28869
28873
  const manager = new manager_node_1.default({
@@ -28895,8 +28899,8 @@ function createCloudBaseManagerWithOptions(cloudBaseOptions) {
28895
28899
  hasSecretKey: !!cloudBaseOptions.secretKey,
28896
28900
  hasToken: !!cloudBaseOptions.token,
28897
28901
  });
28898
- // Region priority: explicit option > env var > ap-shanghai default
28899
- const region = cloudBaseOptions.region ?? process.env.TCB_REGION ?? 'ap-shanghai';
28902
+ // Region priority: explicit option > TCB_REGION/TCB_SITE env > .cloudbase/project.json > ap-shanghai default
28903
+ const region = (0, site_map_js_1.resolveSiteAndRegion)(cloudBaseOptions).region;
28900
28904
  const manager = new manager_node_1.default({
28901
28905
  ...cloudBaseOptions,
28902
28906
  proxy: cloudBaseOptions.proxy || process.env.http_proxy,
@@ -41808,424 +41812,6 @@ function done(stream, er, data) {
41808
41812
  })));
41809
41813
 
41810
41814
 
41811
- /***/ }),
41812
-
41813
- /***/ 9097:
41814
- /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
41815
-
41816
- "use strict";
41817
-
41818
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
41819
- if (k2 === undefined) k2 = k;
41820
- var desc = Object.getOwnPropertyDescriptor(m, k);
41821
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
41822
- desc = { enumerable: true, get: function() { return m[k]; } };
41823
- }
41824
- Object.defineProperty(o, k2, desc);
41825
- }) : (function(o, m, k, k2) {
41826
- if (k2 === undefined) k2 = k;
41827
- o[k2] = m[k];
41828
- }));
41829
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
41830
- Object.defineProperty(o, "default", { enumerable: true, value: v });
41831
- }) : function(o, v) {
41832
- o["default"] = v;
41833
- });
41834
- var __importStar = (this && this.__importStar) || (function () {
41835
- var ownKeys = function(o) {
41836
- ownKeys = Object.getOwnPropertyNames || function (o) {
41837
- var ar = [];
41838
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
41839
- return ar;
41840
- };
41841
- return ownKeys(o);
41842
- };
41843
- return function (mod) {
41844
- if (mod && mod.__esModule) return mod;
41845
- var result = {};
41846
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
41847
- __setModuleDefault(result, mod);
41848
- return result;
41849
- };
41850
- })();
41851
- Object.defineProperty(exports, "__esModule", ({ value: true }));
41852
- exports.registerDownloadTools = registerDownloadTools;
41853
- const crypto = __importStar(__webpack_require__(55511));
41854
- const fs = __importStar(__webpack_require__(29021));
41855
- const fsPromises = __importStar(__webpack_require__(79748));
41856
- const http = __importStar(__webpack_require__(81630));
41857
- const https = __importStar(__webpack_require__(55591));
41858
- const os = __importStar(__webpack_require__(21820));
41859
- const path = __importStar(__webpack_require__(33873));
41860
- const url_1 = __webpack_require__(79551);
41861
- const zod_1 = __webpack_require__(7552);
41862
- const remote_url_safety_js_1 = __webpack_require__(89192);
41863
- // 常量定义
41864
- const MAX_FILE_SIZE = 100 * 1024 * 1024; // 100MB
41865
- const MAX_REDIRECT_HOPS = 5;
41866
- const ALLOWED_CONTENT_TYPES = [
41867
- "text/",
41868
- "image/",
41869
- "application/json",
41870
- "application/xml",
41871
- "application/pdf",
41872
- "application/zip",
41873
- "application/x-zip-compressed"
41874
- ];
41875
- // 获取项目根目录
41876
- function getProjectRoot() {
41877
- // 优先级:环境变量 > 当前工作目录
41878
- return process.env.WORKSPACE_FOLDER_PATHS ||
41879
- process.env.PROJECT_ROOT ||
41880
- process.env.GITHUB_WORKSPACE ||
41881
- process.env.CI_PROJECT_DIR ||
41882
- process.env.BUILD_SOURCESDIRECTORY ||
41883
- process.cwd();
41884
- }
41885
- // 验证相对路径是否安全(不允许路径遍历)
41886
- function isPathSafe(relativePath) {
41887
- // 检查是否包含路径遍历操作
41888
- if (relativePath.includes('..') ||
41889
- relativePath.includes('~') ||
41890
- path.isAbsolute(relativePath)) {
41891
- return false;
41892
- }
41893
- // 检查路径是否规范化后仍然安全
41894
- const normalizedPath = path.normalize(relativePath);
41895
- if (normalizedPath.startsWith('..') ||
41896
- normalizedPath.startsWith('/') ||
41897
- normalizedPath.startsWith('\\')) {
41898
- return false;
41899
- }
41900
- return true;
41901
- }
41902
- // 计算最终下载路径
41903
- function calculateDownloadPath(relativePath) {
41904
- const projectRoot = getProjectRoot();
41905
- const finalPath = path.join(projectRoot, relativePath);
41906
- // 确保最终路径在项目根目录内
41907
- const normalizedProjectRoot = path.resolve(projectRoot);
41908
- const normalizedFinalPath = path.resolve(finalPath);
41909
- if (!normalizedFinalPath.startsWith(normalizedProjectRoot)) {
41910
- throw new Error('相对路径超出项目根目录范围');
41911
- }
41912
- return finalPath;
41913
- }
41914
- // 生成随机文件名
41915
- function generateRandomFileName(extension = '') {
41916
- const randomBytes = crypto.randomBytes(16);
41917
- const fileName = randomBytes.toString('hex');
41918
- return `${fileName}${extension}`;
41919
- }
41920
- // 获取安全的临时文件路径
41921
- function getSafeTempFilePath(fileName) {
41922
- return path.join(os.tmpdir(), fileName);
41923
- }
41924
- // 从 URL 或 Content-Disposition 获取文件扩展名
41925
- function getFileExtension(url, contentType, contentDisposition) {
41926
- let extension = "";
41927
- // 从 URL 获取扩展名
41928
- const urlPath = new url_1.URL(url).pathname;
41929
- const urlExt = path.extname(urlPath);
41930
- if (urlExt) {
41931
- extension = urlExt;
41932
- }
41933
- // 从 Content-Disposition 获取扩展名
41934
- if (contentDisposition) {
41935
- const filenameMatch = contentDisposition.match(/filename=["']?([^"']+)["']?/);
41936
- if (filenameMatch) {
41937
- const dispositionExt = path.extname(filenameMatch[1]);
41938
- if (dispositionExt) {
41939
- extension = dispositionExt;
41940
- }
41941
- }
41942
- }
41943
- // 从 Content-Type 获取扩展名
41944
- if (!extension && contentType) {
41945
- const mimeToExt = {
41946
- "text/plain": ".txt",
41947
- "text/html": ".html",
41948
- "text/css": ".css",
41949
- "text/javascript": ".js",
41950
- "image/jpeg": ".jpg",
41951
- "image/png": ".png",
41952
- "image/gif": ".gif",
41953
- "image/webp": ".webp",
41954
- "application/json": ".json",
41955
- "application/xml": ".xml",
41956
- "application/pdf": ".pdf",
41957
- "application/zip": ".zip",
41958
- "application/x-zip-compressed": ".zip"
41959
- };
41960
- extension = mimeToExt[contentType] || "";
41961
- }
41962
- return extension;
41963
- }
41964
- function isAllowedContentType(contentType) {
41965
- return ALLOWED_CONTENT_TYPES.some((allowedType) => contentType.startsWith(allowedType));
41966
- }
41967
- // 检查是否为可重试的网络错误
41968
- function isRetryableError(error) {
41969
- const retryableCodes = [
41970
- 'ECONNRESET',
41971
- 'ECONNREFUSED',
41972
- 'ETIMEDOUT',
41973
- 'ESOCKETTIMEDOUT',
41974
- 'ENOTFOUND',
41975
- 'EHOSTUNREACH',
41976
- 'ENETUNREACH',
41977
- 'ECONNABORTED'
41978
- ];
41979
- return retryableCodes.includes(error.code || '');
41980
- }
41981
- // 下载文件到指定路径(带重试逻辑)
41982
- async function downloadFileToPath(url, targetPath, retryCount = 0, redirectCount = 0) {
41983
- const MAX_RETRIES = 3;
41984
- const BASE_DELAY_MS = 1000; // 1秒基础延迟
41985
- if (redirectCount > MAX_REDIRECT_HOPS) {
41986
- throw new Error(`重定向次数超过 ${MAX_REDIRECT_HOPS} 次限制`);
41987
- }
41988
- const { requestUrl, requestOptions } = await (0, remote_url_safety_js_1.prepareSafeRemoteRequest)(url);
41989
- const client = requestUrl.protocol === "https:" ? https : http;
41990
- return new Promise((resolve, reject) => {
41991
- const request = client.get(requestUrl, requestOptions ?? {}, async (res) => {
41992
- // 处理重定向
41993
- if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
41994
- try {
41995
- const redirectUrl = new url_1.URL(res.headers.location, requestUrl).toString();
41996
- return resolve(await downloadFileToPath(redirectUrl, targetPath, retryCount, redirectCount + 1));
41997
- }
41998
- catch (error) {
41999
- return reject(error);
42000
- }
42001
- }
42002
- if (res.statusCode !== 200) {
42003
- reject(new Error(`HTTP Error: ${res.statusCode}`));
42004
- return;
42005
- }
42006
- const contentType = res.headers["content-type"] || "";
42007
- const contentLength = parseInt(res.headers["content-length"] || "0", 10);
42008
- if (!isAllowedContentType(contentType)) {
42009
- reject(new Error(`不允许的内容类型: ${contentType || "unknown"}`));
42010
- return;
42011
- }
42012
- // 文件大小检查
42013
- if (contentLength > MAX_FILE_SIZE) {
42014
- reject(new Error(`文件大小 ${contentLength} 字节超过 ${MAX_FILE_SIZE} 字节限制`));
42015
- return;
42016
- }
42017
- // 确保目标目录存在
42018
- const targetDir = path.dirname(targetPath);
42019
- try {
42020
- await fsPromises.mkdir(targetDir, { recursive: true });
42021
- }
42022
- catch (error) {
42023
- reject(new Error(`无法创建目标目录: ${error instanceof Error ? error.message : "未知错误"}`));
42024
- return;
42025
- }
42026
- // 创建写入流
42027
- const fileStream = fs.createWriteStream(targetPath);
42028
- let downloadedSize = 0;
42029
- res.on("data", (chunk) => {
42030
- downloadedSize += chunk.length;
42031
- if (downloadedSize > MAX_FILE_SIZE) {
42032
- fileStream.destroy();
42033
- fsPromises.unlink(targetPath).catch(() => { });
42034
- reject(new Error(`文件大小超过 ${MAX_FILE_SIZE} 字节限制`));
42035
- }
42036
- });
42037
- res.pipe(fileStream);
42038
- fileStream.on("finish", () => {
42039
- resolve({
42040
- filePath: targetPath,
42041
- contentType,
42042
- fileSize: downloadedSize,
42043
- });
42044
- });
42045
- fileStream.on("error", (error) => {
42046
- fsPromises.unlink(targetPath).catch(() => { });
42047
- reject(error);
42048
- });
42049
- });
42050
- request.on("error", async (error) => {
42051
- // 检查是否可重试
42052
- if (isRetryableError(error) && retryCount < MAX_RETRIES) {
42053
- const delay = BASE_DELAY_MS * Math.pow(2, retryCount); // 指数退避
42054
- console.warn(`下载失败 (${error.code}),${delay}ms 后重试 (${retryCount + 1}/${MAX_RETRIES})...`);
42055
- await new Promise((resolveDelay) => setTimeout(resolveDelay, delay));
42056
- try {
42057
- return resolve(await downloadFileToPath(url, targetPath, retryCount + 1, redirectCount));
42058
- }
42059
- catch (retryError) {
42060
- return reject(retryError);
42061
- }
42062
- }
42063
- reject(error);
42064
- });
42065
- });
42066
- }
42067
- // 下载文件到临时目录(保持向后兼容,带重试逻辑)
42068
- async function downloadFile(url, retryCount = 0, redirectCount = 0) {
42069
- const MAX_RETRIES = 3;
42070
- const BASE_DELAY_MS = 1000; // 1秒基础延迟
42071
- if (redirectCount > MAX_REDIRECT_HOPS) {
42072
- throw new Error(`重定向次数超过 ${MAX_REDIRECT_HOPS} 次限制`);
42073
- }
42074
- const { requestUrl, requestOptions } = await (0, remote_url_safety_js_1.prepareSafeRemoteRequest)(url);
42075
- const client = requestUrl.protocol === "https:" ? https : http;
42076
- return new Promise((resolve, reject) => {
42077
- const request = client.get(requestUrl, requestOptions ?? {}, async (res) => {
42078
- // 处理重定向
42079
- if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
42080
- try {
42081
- const redirectUrl = new url_1.URL(res.headers.location, requestUrl).toString();
42082
- return resolve(await downloadFile(redirectUrl, retryCount, redirectCount + 1));
42083
- }
42084
- catch (error) {
42085
- return reject(error);
42086
- }
42087
- }
42088
- if (res.statusCode !== 200) {
42089
- reject(new Error(`HTTP Error: ${res.statusCode}`));
42090
- return;
42091
- }
42092
- const contentType = res.headers["content-type"] || "";
42093
- const contentLength = parseInt(res.headers["content-length"] || "0", 10);
42094
- const contentDisposition = res.headers["content-disposition"];
42095
- if (!isAllowedContentType(contentType)) {
42096
- reject(new Error(`不允许的内容类型: ${contentType || "unknown"}`));
42097
- return;
42098
- }
42099
- // 文件大小检查
42100
- if (contentLength > MAX_FILE_SIZE) {
42101
- reject(new Error(`文件大小 ${contentLength} 字节超过 ${MAX_FILE_SIZE} 字节限制`));
42102
- return;
42103
- }
42104
- // 生成临时文件路径
42105
- const extension = getFileExtension(requestUrl.toString(), contentType, contentDisposition);
42106
- const fileName = generateRandomFileName(extension);
42107
- const filePath = getSafeTempFilePath(fileName);
42108
- // 创建写入流
42109
- const fileStream = fs.createWriteStream(filePath);
42110
- let downloadedSize = 0;
42111
- res.on("data", (chunk) => {
42112
- downloadedSize += chunk.length;
42113
- if (downloadedSize > MAX_FILE_SIZE) {
42114
- fileStream.destroy();
42115
- fsPromises.unlink(filePath).catch(() => { });
42116
- reject(new Error(`文件大小超过 ${MAX_FILE_SIZE} 字节限制`));
42117
- }
42118
- });
42119
- res.pipe(fileStream);
42120
- fileStream.on("finish", () => {
42121
- resolve({
42122
- filePath,
42123
- contentType,
42124
- fileSize: downloadedSize,
42125
- });
42126
- });
42127
- fileStream.on("error", (error) => {
42128
- fsPromises.unlink(filePath).catch(() => { });
42129
- reject(error);
42130
- });
42131
- });
42132
- request.on("error", async (error) => {
42133
- // 检查是否可重试
42134
- if (isRetryableError(error) && retryCount < MAX_RETRIES) {
42135
- const delay = BASE_DELAY_MS * Math.pow(2, retryCount); // 指数退避
42136
- console.warn(`下载失败 (${error.code}),${delay}ms 后重试 (${retryCount + 1}/${MAX_RETRIES})...`);
42137
- await new Promise((resolveDelay) => setTimeout(resolveDelay, delay));
42138
- try {
42139
- return resolve(await downloadFile(url, retryCount + 1, redirectCount));
42140
- }
42141
- catch (retryError) {
42142
- return reject(retryError);
42143
- }
42144
- }
42145
- reject(error);
42146
- });
42147
- });
42148
- }
42149
- function buildDownloadRemoteFileErrorMessage(url, error) {
42150
- const baseMessage = error instanceof Error ? error.message : String(error);
42151
- const suggestions = [];
42152
- if (/HTTP Error:\s*404/i.test(baseMessage)) {
42153
- suggestions.push("目标 URL 当前返回 404,说明资源链接已失效或路径不正确。");
42154
- suggestions.push("请先在浏览器中确认该链接可访问,再重新执行下载。");
42155
- }
42156
- if (/ENOTFOUND|ECONNRESET|ETIMEDOUT|socket hang up/i.test(baseMessage)) {
42157
- suggestions.push("下载过程中出现网络异常,系统已自动重试 3 次但均失败。");
42158
- suggestions.push("建议:1) 检查本地网络或代理设置;2) 该网站可能限频,请尝试更换其他图片源(如 Unsplash、Pexels);3) 稍后重试。");
42159
- }
42160
- if (suggestions.length === 0) {
42161
- suggestions.push("请检查 URL 是否可访问,以及目标资源是否允许直接下载。");
42162
- }
42163
- return `[downloadRemoteFile] ${baseMessage}\nURL: ${url}\n建议:${suggestions.join(" ")}`;
42164
- }
42165
- function registerDownloadTools(server) {
42166
- server.registerTool("downloadRemoteFile", {
42167
- title: "下载远程文件到指定路径",
42168
- description: "下载远程文件到项目根目录下的指定相对路径。例如:小程序的 Tabbar 等素材图片,必须使用 **png** 格式,可以从 Unsplash、wikimedia【一般选用 500 大小即可、Pexels、Apple 官方 UI 等资源中选择来下载。",
42169
- inputSchema: {
42170
- url: zod_1.z.string().describe("远程文件的 URL 地址"),
42171
- relativePath: zod_1.z.string().describe("相对于项目根目录的路径,例如:'assets/images/logo.png' 或 'docs/api.md'。不允许使用 ../ 等路径遍历操作。")
42172
- },
42173
- annotations: {
42174
- readOnlyHint: false,
42175
- destructiveHint: false,
42176
- idempotentHint: false,
42177
- openWorldHint: true,
42178
- category: "download"
42179
- }
42180
- }, async ({ url, relativePath }) => {
42181
- if (!isPathSafe(relativePath)) {
42182
- return {
42183
- content: [
42184
- {
42185
- type: "text",
42186
- text: JSON.stringify({
42187
- success: false,
42188
- error: "不安全的相对路径",
42189
- message: "相对路径包含路径遍历操作(../)或绝对路径,出于安全考虑已拒绝",
42190
- suggestion: "请使用项目根目录下的相对路径,例如:'assets/images/logo.png'"
42191
- }, null, 2)
42192
- }
42193
- ]
42194
- };
42195
- }
42196
- const targetPath = calculateDownloadPath(relativePath);
42197
- const projectRoot = getProjectRoot();
42198
- console.log(`📁 项目根目录: ${projectRoot}`);
42199
- console.log(`📁 相对路径: ${relativePath}`);
42200
- console.log(`📁 最终路径: ${targetPath}`);
42201
- let result;
42202
- try {
42203
- result = await downloadFileToPath(url, targetPath);
42204
- }
42205
- catch (error) {
42206
- throw new Error(buildDownloadRemoteFileErrorMessage(url, error));
42207
- }
42208
- return {
42209
- content: [
42210
- {
42211
- type: "text",
42212
- text: JSON.stringify({
42213
- success: true,
42214
- filePath: result.filePath,
42215
- relativePath: relativePath,
42216
- contentType: result.contentType,
42217
- fileSize: result.fileSize,
42218
- projectRoot: projectRoot,
42219
- message: "文件下载成功到指定路径",
42220
- note: `文件已保存到项目目录: ${relativePath}`
42221
- }, null, 2)
42222
- }
42223
- ]
42224
- };
42225
- });
42226
- }
42227
-
42228
-
42229
41815
  /***/ }),
42230
41816
 
42231
41817
  /***/ 9141:
@@ -83681,27 +83267,6 @@ function done(stream, er, data) {
83681
83267
  return stream.push(null);
83682
83268
  }
83683
83269
 
83684
- /***/ }),
83685
-
83686
- /***/ 21454:
83687
- /***/ ((__unused_webpack_module, exports) => {
83688
-
83689
- "use strict";
83690
-
83691
- Object.defineProperty(exports, "__esModule", ({ value: true }));
83692
- exports.isInternationalRegion = void 0;
83693
- exports.isValidRegion = isValidRegion;
83694
- const REGION = {
83695
- SHANGHAI: 'ap-shanghai',
83696
- SINGAPORE: 'ap-singapore',
83697
- };
83698
- const isInternationalRegion = (region) => region === REGION.SINGAPORE;
83699
- exports.isInternationalRegion = isInternationalRegion;
83700
- function isValidRegion(region) {
83701
- return Object.values(REGION).includes(region);
83702
- }
83703
-
83704
-
83705
83270
  /***/ }),
83706
83271
 
83707
83272
  /***/ 21605:
@@ -91460,8 +91025,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
91460
91025
  return (mod && mod.__esModule) ? mod : { "default": mod };
91461
91026
  };
91462
91027
  Object.defineProperty(exports, "__esModule", ({ value: true }));
91463
- exports.CUSTOM_IMAGE_RUNTIME = exports.MANAGE_FUNCTION_ACTIONS = exports.QUERY_FUNCTION_ACTIONS = exports.TRIGGER_CONFIG_EXAMPLES = exports.SUPPORTED_TRIGGER_TYPES = exports.DEFAULT_NODEJS_RUNTIME = exports.SUPPORTED_NODEJS_RUNTIMES = exports.RECOMMENDED_RUNTIMES = exports.DEFAULT_RUNTIME = exports.ALL_SUPPORTED_RUNTIMES = exports.SUPPORTED_RUNTIMES = void 0;
91028
+ exports.CUSTOM_IMAGE_RUNTIME = exports.LAYER_SOFT_WARN = exports.MANAGE_FUNCTION_ACTIONS = exports.QUERY_FUNCTION_ACTIONS = exports.TRIGGER_CONFIG_EXAMPLES = exports.SUPPORTED_TRIGGER_TYPES = exports.DEFAULT_NODEJS_RUNTIME = exports.SUPPORTED_NODEJS_RUNTIMES = exports.RECOMMENDED_RUNTIMES = exports.DEFAULT_RUNTIME = exports.ALL_SUPPORTED_RUNTIMES = exports.SUPPORTED_RUNTIMES = void 0;
91464
91029
  exports.formatRuntimeList = formatRuntimeList;
91030
+ exports.layerNameIncludesEnvId = layerNameIncludesEnvId;
91031
+ exports.buildCreateLayerNameWarning = buildCreateLayerNameWarning;
91465
91032
  exports.validateTimerCron = validateTimerCron;
91466
91033
  exports.pickManageFunctionName = pickManageFunctionName;
91467
91034
  exports.shouldInstallDependencyForFunction = shouldInstallDependencyForFunction;
@@ -91566,6 +91133,24 @@ exports.MANAGE_FUNCTION_ACTIONS = [
91566
91133
  "updateFunctionLayers",
91567
91134
  "incrementalDeployFunction", // 增量部署,需通过 pluginOptions.functions 注入实现
91568
91135
  ];
91136
+ /** Layer soft-warn copy — account-scoped SCF LayerName guidance (no hard fail). */
91137
+ exports.LAYER_SOFT_WARN = {
91138
+ createNameFormat: (envId) => `建议使用 {layerName}_${envId} 格式,当前名称可能与其他环境共享版本序列`,
91139
+ deleteVersion: "该层为账号级共享资源,删除版本会影响所有绑定该版本的环境的函数,请确认",
91140
+ bindShared: "层为账号级共享,绑定/解绑影响所有引用该层名的环境",
91141
+ accountLevelView: "返回账号级视图,含其他环境创建的层",
91142
+ };
91143
+ function layerNameIncludesEnvId(layerName, envId) {
91144
+ if (!envId)
91145
+ return true;
91146
+ return layerName.includes(envId);
91147
+ }
91148
+ function buildCreateLayerNameWarning(layerName, envId) {
91149
+ if (!envId || layerNameIncludesEnvId(layerName, envId)) {
91150
+ return undefined;
91151
+ }
91152
+ return exports.LAYER_SOFT_WARN.createNameFormat(envId);
91153
+ }
91569
91154
  const VPC_SCHEMA = zod_1.z.object({
91570
91155
  vpcId: zod_1.z
91571
91156
  .string()
@@ -91807,11 +91392,12 @@ function registerFunctionTools(server) {
91807
91392
  const cloudBaseOptions = server.cloudBaseOptions;
91808
91393
  const deployOverrides = server.pluginOptions?.functions;
91809
91394
  const getManager = () => (0, cloudbase_manager_js_1.getCloudBaseManager)({ cloudBaseOptions });
91810
- const buildEnvelope = (data, message, nextActions) => ({
91395
+ const buildEnvelope = (data, message, nextActions, warnings) => ({
91811
91396
  success: true,
91812
91397
  data,
91813
91398
  message,
91814
91399
  ...(nextActions?.length ? { nextActions } : {}),
91400
+ ...(warnings?.length ? { warnings } : {}),
91815
91401
  });
91816
91402
  const buildErrorEnvelope = (error, errorCode) => ({
91817
91403
  success: false,
@@ -92062,7 +91648,7 @@ function registerFunctionTools(server) {
92062
91648
  action: "createLayerVersion",
92063
91649
  reason: "发布新的层版本",
92064
91650
  },
92065
- ]);
91651
+ ], [exports.LAYER_SOFT_WARN.accountLevelView]);
92066
91652
  }
92067
91653
  case "listLayerVersions": {
92068
91654
  if (!input.layerName) {
@@ -92090,7 +91676,7 @@ function registerFunctionTools(server) {
92090
91676
  action: "attachLayer",
92091
91677
  reason: "将某个层版本绑定到函数",
92092
91678
  },
92093
- ]);
91679
+ ], [exports.LAYER_SOFT_WARN.accountLevelView]);
92094
91680
  }
92095
91681
  case "getLayerVersionDetail": {
92096
91682
  if (!input.layerName) {
@@ -92123,7 +91709,7 @@ function registerFunctionTools(server) {
92123
91709
  action: "deleteLayerVersion",
92124
91710
  reason: "删除该层版本",
92125
91711
  },
92126
- ]);
91712
+ ], [exports.LAYER_SOFT_WARN.accountLevelView]);
92127
91713
  }
92128
91714
  case "listFunctionTriggers": {
92129
91715
  if (!input.functionName) {
@@ -92639,6 +92225,8 @@ function registerFunctionTools(server) {
92639
92225
  if (!input.contentPath && !input.base64Content) {
92640
92226
  throw new Error("createLayerVersion 操作时,contentPath 和 base64Content 至少需要提供一个");
92641
92227
  }
92228
+ const envId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
92229
+ const nameWarning = buildCreateLayerNameWarning(input.layerName, envId);
92642
92230
  const cloudbase = await getManager();
92643
92231
  const result = await cloudbase.functions.createLayer({
92644
92232
  name: input.layerName,
@@ -92661,7 +92249,7 @@ function registerFunctionTools(server) {
92661
92249
  action: "listLayerVersions",
92662
92250
  reason: "查看该层的全部版本",
92663
92251
  },
92664
- ]);
92252
+ ], nameWarning ? [nameWarning] : undefined);
92665
92253
  }
92666
92254
  case "deleteLayerVersion": {
92667
92255
  if (!input.layerName) {
@@ -92688,7 +92276,7 @@ function registerFunctionTools(server) {
92688
92276
  action: "listLayerVersions",
92689
92277
  reason: "确认剩余层版本",
92690
92278
  },
92691
- ]);
92279
+ ], [exports.LAYER_SOFT_WARN.deleteVersion]);
92692
92280
  }
92693
92281
  case "attachLayer":
92694
92282
  case "detachLayer":
@@ -92698,6 +92286,7 @@ function registerFunctionTools(server) {
92698
92286
  }
92699
92287
  const cloudbase = await getManager();
92700
92288
  const envId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
92289
+ const bindWarnings = [exports.LAYER_SOFT_WARN.bindShared];
92701
92290
  if (input.action === "attachLayer") {
92702
92291
  if (!input.layerName) {
92703
92292
  throw new Error("attachLayer 操作时,layerName 参数是必需的");
@@ -92726,7 +92315,7 @@ function registerFunctionTools(server) {
92726
92315
  action: "listFunctionLayers",
92727
92316
  reason: "确认函数当前绑定层列表",
92728
92317
  },
92729
- ]);
92318
+ ], bindWarnings);
92730
92319
  }
92731
92320
  if (input.action === "detachLayer") {
92732
92321
  if (!input.layerName) {
@@ -92757,7 +92346,7 @@ function registerFunctionTools(server) {
92757
92346
  action: "listFunctionLayers",
92758
92347
  reason: "确认解绑后的层列表",
92759
92348
  },
92760
- ]);
92349
+ ], bindWarnings);
92761
92350
  }
92762
92351
  const normalizedLayers = normalizeManageLayers(input.layers);
92763
92352
  if (!normalizedLayers.length) {
@@ -92782,7 +92371,7 @@ function registerFunctionTools(server) {
92782
92371
  action: "listFunctionLayers",
92783
92372
  reason: "确认最新层顺序和绑定结果",
92784
92373
  },
92785
- ]);
92374
+ ], bindWarnings);
92786
92375
  }
92787
92376
  default:
92788
92377
  // incrementalDeployFunction:无默认实现,必须通过 pluginOptions 注入
@@ -92812,6 +92401,10 @@ function registerFunctionTools(server) {
92812
92401
  "\n- 示例:`queryFunctions(action=\"listFunctionLogs\", functionName=\"my-function\")`" +
92813
92402
  "\n- 如需查看日志详情:`queryFunctions(action=\"getFunctionLogDetail\", requestId=\"xxx\")`" +
92814
92403
  "\n\n**定时任务 / cron / 定时跑**:使用 `listFunctionTriggers` 查询函数的 timer 触发器配置。" +
92404
+ "\n\n**层(Layer)说明**:" +
92405
+ "\n- 层为 SCF 账号级共享命名空间:不同环境创建同名层会共享同一层的版本序列;删除某版本会影响所有绑定该版本的环境的函数" +
92406
+ "\n- 创建层必须用带环境标识的唯一层名,固定格式:`{layerName}_{当前envId}`(如 `common_cloud1-d9ghadgak3edf6b36`)。不要在不同环境使用相同裸层名,创建前先 `listLayers` 查重" +
92407
+ "\n- `listLayers` / `listLayerVersions` / `getLayerVersionDetail` 返回账号级视图,可能含其他环境创建的层" +
92815
92408
  "\n\n**区分 `queryLogs` 工具**:" +
92816
92409
  "\n- 本工具用于查询特定 CloudBase 云函数的执行日志" +
92817
92410
  "\n- `queryLogs` 工具用于搜索 CLS 日志服务(跨服务日志聚合)",
@@ -92824,9 +92417,9 @@ function registerFunctionTools(server) {
92824
92417
  "\n- `listFunctionLogs`: 查询 CloudBase 云函数执行日志(需要 functionName)" +
92825
92418
  "\n- `getFunctionLogDetail`: 获取日志详情(需要 requestId)" +
92826
92419
  "\n- `listFunctionLayers`: 列出函数绑定的层" +
92827
- "\n- `listLayers`: 列出所有层" +
92828
- "\n- `listLayerVersions`: 列出层的版本(注意:是 Versions 不是 Version)" +
92829
- "\n- `getLayerVersionDetail`: 获取层版本详情" +
92420
+ "\n- `listLayers`: 列出所有层(账号级视图,含其他环境创建的层)" +
92421
+ "\n- `listLayerVersions`: 列出层的版本(注意:是 Versions 不是 Version;账号级视图)" +
92422
+ "\n- `getLayerVersionDetail`: 获取层版本详情(账号级视图)" +
92830
92423
  "\n- `listFunctionTriggers`: 列出函数触发器(用于查看定时任务 / cron / timer 配置)" +
92831
92424
  "\n- `getFunctionDownloadUrl`: 获取函数代码下载地址"),
92832
92425
  functionName: zod_1.z
@@ -92853,7 +92446,11 @@ function registerFunctionTools(server) {
92853
92446
  qualifier: zod_1.z.string().optional().describe("函数版本别名,如 $LATEST、$DEFAULT。日志查询时可选"),
92854
92447
  runtime: zod_1.z.string().optional().describe("层查询的运行时筛选,如 Nodejs18.15"),
92855
92448
  searchKey: zod_1.z.string().optional().describe("层名称搜索关键字"),
92856
- layerName: zod_1.z.string().optional().describe("层名称。`listLayerVersions`、`getLayerVersionDetail` 操作必填"),
92449
+ layerName: zod_1.z
92450
+ .string()
92451
+ .optional()
92452
+ .describe("层名称。`listLayerVersions`、`getLayerVersionDetail` 操作必填。" +
92453
+ "层为账号级共享命名空间;推荐固定格式 `{layerName}_{当前envId}`(如 common_cloud1-d9ghadgak3edf6b36)"),
92857
92454
  layerVersion: zod_1.z.number().optional().describe("层版本号。`getLayerVersionDetail` 操作必填"),
92858
92455
  },
92859
92456
  annotations: {
@@ -92868,12 +92465,18 @@ function registerFunctionTools(server) {
92868
92465
  "如果要创建 cron 定时任务,先用 createFunction 创建函数,再用 createFunctionTrigger 创建 timer 触发器(支持7段cron表达式),deleteFunctionTrigger 删除触发器。" +
92869
92466
  "镜像部署(Runtime=CustomImage):先把代码经 zip→COS→CloudApp custom 构建→TCR 推镜像(这一阶段为裸腾讯云 API,本工具不覆盖)," +
92870
92467
  "再用 createFunction(func.runtime=\"CustomImage\", imageConfig) 基于 TCR 镜像创建 HTTP 函数;后续迭代用 updateFunctionCode + imageConfig 换镜像 tag。" +
92871
- "危险操作需要显式 confirm=true。",
92468
+ "危险操作需要显式 confirm=true。" +
92469
+ "\n\n**层(Layer)说明**:" +
92470
+ "\n- 层为 SCF 账号级共享命名空间:不同环境创建同名层会共享同一层的版本序列;删除某版本会影响所有绑定该版本的环境的函数" +
92471
+ "\n- 创建层必须用带环境标识的唯一层名,固定格式:`{layerName}_{当前envId}`(如 `common_cloud1-d9ghadgak3edf6b36`)。不要在不同环境使用相同裸层名,创建前先 `listLayers` 查重" +
92472
+ "\n- 相关 action:`createLayerVersion` / `deleteLayerVersion` / `attachLayer` / `detachLayer` / `updateFunctionLayers`(只读查询见 queryFunctions 的 listLayers / listLayerVersions / getLayerVersionDetail)",
92872
92473
  inputSchema: {
92873
92474
  action: zod_1.z
92874
92475
  .enum(exports.MANAGE_FUNCTION_ACTIONS)
92875
92476
  .describe("写操作类型,例如 createFunction、updateFunctionCode、incrementalDeployFunction、invokeFunction、deleteFunction、" +
92876
- "createFunctionTrigger(定时任务 / cron / timer)、deleteFunctionTrigger、attachLayer、detachLayer"),
92477
+ "createFunctionTrigger(定时任务 / cron / timer)、deleteFunctionTrigger、" +
92478
+ "createLayerVersion、deleteLayerVersion、attachLayer、detachLayer、updateFunctionLayers。" +
92479
+ "层名推荐固定格式 `{layerName}_{当前envId}`(如 common_cloud1-d9ghadgak3edf6b36)"),
92877
92480
  func: CREATE_FUNCTION_SCHEMA.optional().describe("createFunction 操作的函数配置"),
92878
92481
  functionRootPath: zod_1.z.string().optional().describe("创建或更新函数代码时默认推荐的本地目录方式。" +
92879
92482
  "必须是直接包含函数文件夹的目录绝对路径(如 /abs/path/cloudfunctions 或 /abs/path/functions)," +
@@ -92903,7 +92506,11 @@ function registerFunctionTools(server) {
92903
92506
  .describe("createFunctionTrigger 的触发器列表,用于定时跑 / 定时任务 / scheduled job。timer 触发器使用7段 cron 表达式(秒 分 时 日 月 星期 年)," +
92904
92507
  '如 "0 */5 * * * * *" 表示每5分钟执行一次'),
92905
92508
  triggerName: zod_1.z.string().optional().describe("deleteFunctionTrigger 的目标触发器名称"),
92906
- layerName: zod_1.z.string().optional().describe("层名称"),
92509
+ layerName: zod_1.z
92510
+ .string()
92511
+ .optional()
92512
+ .describe("层名称。创建层推荐固定格式 `{layerName}_{当前envId}`(如 common_cloud1-d9ghadgak3edf6b36);" +
92513
+ "不要跨环境复用裸层名。层为账号级共享命名空间"),
92907
92514
  layerVersion: zod_1.z.number().optional().describe("层版本号"),
92908
92515
  contentPath: zod_1.z.string().optional().describe("层内容路径,可为目录或 ZIP 文件"),
92909
92516
  base64Content: zod_1.z.string().optional().describe("层内容的 base64 编码"),
@@ -105446,7 +105053,6 @@ const mcp_js_1 = __webpack_require__(7011);
105446
105053
  const databaseNoSQL_js_1 = __webpack_require__(73903);
105447
105054
  const databasePG_js_1 = __webpack_require__(56473);
105448
105055
  const databaseSQL_js_1 = __webpack_require__(9782);
105449
- const download_js_1 = __webpack_require__(9097);
105450
105056
  const env_js_1 = __webpack_require__(622);
105451
105057
  const functions_js_1 = __webpack_require__(25936);
105452
105058
  const hosting_js_1 = __webpack_require__(37279);
@@ -105467,7 +105073,7 @@ const logs_js_1 = __webpack_require__(92322);
105467
105073
  const permissions_js_1 = __webpack_require__(76485);
105468
105074
  const cloud_mode_js_1 = __webpack_require__(89684);
105469
105075
  const logger_js_1 = __webpack_require__(13039);
105470
- const tencent_cloud_js_1 = __webpack_require__(21454);
105076
+ const site_map_js_1 = __webpack_require__(68107);
105471
105077
  const tool_result_js_1 = __webpack_require__(9835);
105472
105078
  const tool_wrapper_js_1 = __webpack_require__(71363);
105473
105079
  // 默认插件列表
@@ -105489,13 +105095,15 @@ const DEFAULT_PLUGINS = [
105489
105095
  "permissions",
105490
105096
  "logs",
105491
105097
  "agents",
105492
- "download",
105493
105098
  "capi",
105494
105099
  ];
105495
105100
  function registerDatabase(server) {
105496
- // Skip NoSQL database tools for international region (Singapore) as it doesn't support NoSQL DB
105497
- const region = server.cloudBaseOptions?.region || process.env.TCB_REGION;
105498
- if (!(0, tencent_cloud_js_1.isInternationalRegion)(region)) {
105101
+ // NoSQL 数据库按站点能力集合注册(国际站默认不支持 NoSQL)
105102
+ const { site } = (0, site_map_js_1.resolveSiteAndRegion)({
105103
+ site: server.cloudBaseOptions?.site,
105104
+ region: server.cloudBaseOptions?.region,
105105
+ });
105106
+ if (site_map_js_1.SITE_REGION_MAP[site].capabilities.noSql) {
105499
105107
  (0, databaseNoSQL_js_1.registerDatabaseTools)(server);
105500
105108
  }
105501
105109
  (0, dataModel_js_1.registerDataModelTools)(server);
@@ -105504,8 +105112,11 @@ function registerMysqlDatabase(server) {
105504
105112
  (0, databaseSQL_js_1.registerSQLDatabaseTools)(server);
105505
105113
  }
105506
105114
  function registerNoSQLDatabase(server) {
105507
- const region = server.cloudBaseOptions?.region || process.env.TCB_REGION;
105508
- if (!(0, tencent_cloud_js_1.isInternationalRegion)(region)) {
105115
+ const { site } = (0, site_map_js_1.resolveSiteAndRegion)({
105116
+ site: server.cloudBaseOptions?.site,
105117
+ region: server.cloudBaseOptions?.region,
105118
+ });
105119
+ if (site_map_js_1.SITE_REGION_MAP[site].capabilities.noSql) {
105509
105120
  (0, databaseNoSQL_js_1.registerDatabaseTools)(server);
105510
105121
  }
105511
105122
  }
@@ -105524,7 +105135,6 @@ const AVAILABLE_PLUGINS = {
105524
105135
  storage: { name: "storage", register: storage_js_1.registerStorageTools },
105525
105136
  setup: { name: "setup", register: setup_js_1.registerSetupTools },
105526
105137
  rag: { name: "rag", register: rag_js_1.registerRagTools },
105527
- download: { name: "download", register: download_js_1.registerDownloadTools },
105528
105138
  gateway: { name: "gateway", register: gateway_js_1.registerGatewayTools },
105529
105139
  "app-auth": { name: "app-auth", register: app_auth_js_1.registerAppAuthTools },
105530
105140
  permissions: { name: "permissions", register: permissions_js_1.registerPermissionTools },
@@ -116964,8 +116574,12 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
116964
116574
  return (mod && mod.__esModule) ? mod : { "default": mod };
116965
116575
  };
116966
116576
  Object.defineProperty(exports, "__esModule", ({ value: true }));
116967
- exports.CLOUDRUN_ACCESS_TYPES = exports.CLOUDRUN_SERVICE_TYPES = void 0;
116577
+ exports.CLOUDRUN_PACKAGE_TYPES = exports.CLOUDRUN_ACCESS_TYPES = exports.CLOUDRUN_SERVICE_TYPES = void 0;
116578
+ exports.queryCloudRunEnvStatus = queryCloudRunEnvStatus;
116579
+ exports.describeCloudRunEnvStatus = describeCloudRunEnvStatus;
116580
+ exports.ensureCloudRunEnvInitialized = ensureCloudRunEnvInitialized;
116968
116581
  exports.detectCloudRunDbNetworkRisk = detectCloudRunDbNetworkRisk;
116582
+ exports.extractCloudRunImageInfo = extractCloudRunImageInfo;
116969
116583
  exports.registerCloudRunTools = registerCloudRunTools;
116970
116584
  const child_process_1 = __webpack_require__(79646);
116971
116585
  const fs_1 = __importDefault(__webpack_require__(29021));
@@ -116980,24 +116594,31 @@ const cloudrun_config_js_1 = __webpack_require__(48266);
116980
116594
  exports.CLOUDRUN_SERVICE_TYPES = ['function', 'container'];
116981
116595
  // CloudRun access types
116982
116596
  exports.CLOUDRUN_ACCESS_TYPES = ['OA', 'PUBLIC', 'MINIAPP', 'VPC'];
116597
+ // CloudRun env package types (CreateCloudRunEnv.PackageType)
116598
+ exports.CLOUDRUN_PACKAGE_TYPES = ['Trial', 'Standard', 'Professional', 'Enterprise'];
116983
116599
  // Input schema for queryCloudRun tool
116984
116600
  const queryCloudRunInputSchema = {
116985
- action: zod_1.z.enum(['list', 'detail', 'templates', 'getDeployLog']).describe('查询操作类型:list=获取云托管服务列表(支持分页和筛选),detail=查询指定服务的详细信息(包含服务配置和最新部署状态),templates=获取可用的项目模板列表(用于初始化新项目),getDeployLog=获取指定服务最近一次或指定构建的部署日志'),
116601
+ action: zod_1.z.enum(['list', 'detail', 'templates', 'getDeployLog', 'envStatus']).describe('查询操作类型:list=获取云托管服务列表(支持分页和筛选),detail=查询指定服务的详细信息(包含服务配置和最新部署状态),templates=获取可用的项目模板列表(用于初始化新项目),getDeployLog=获取指定服务最近一次或指定构建的部署日志,envStatus=查询当前环境云托管是否已开通及开通状态(Status=creating开通中/normal已开通),用于initEnv之后轮询进度或deploy之前确认环境是否就绪'),
116986
116602
  // List operation parameters
116987
116603
  pageSize: zod_1.z.number().min(1).max(100).optional().default(10).describe('分页大小,控制每页返回的服务数量。取值范围:1-100,默认值:10。建议根据网络性能和显示需求调整'),
116988
116604
  pageNum: zod_1.z.number().min(1).optional().default(1).describe('页码,用于分页查询。从1开始,默认值:1。配合pageSize使用可实现分页浏览'),
116989
116605
  serverName: zod_1.z.string().optional().describe('服务名称筛选条件,支持模糊匹配。例如:输入"test"可匹配"test-service"、"my-test-app"等服务名称。留空则查询所有服务'),
116990
116606
  serverType: zod_1.z.enum(exports.CLOUDRUN_SERVICE_TYPES).optional().describe('服务类型筛选条件:function=函数型云托管(仅支持Node.js,有特殊的开发要求和限制,适合简单的API服务),container=容器型服务(推荐使用,支持任意语言和框架如Java/Go/Python/PHP/.NET等,适合大多数应用场景)'),
116607
+ envId: zod_1.z.string().optional().describe('环境 ID(action=envStatus 时使用;不传则使用当前配置的环境)。格式如 env-xxxxxx'),
116991
116608
  // Detail and log operation parameters
116992
116609
  detailServerName: zod_1.z.string().optional().describe('要查询详细信息或部署日志的服务名称。当action为detail或getDeployLog时建议提供,必须是已存在的服务名称。可通过list操作获取可用的服务名称列表'),
116993
116610
  buildId: zod_1.z.number().optional().describe('构建ID,仅在action=getDeployLog时使用。不传时默认返回最近一次部署的构建日志'),
116994
116611
  };
116995
116612
  // Input schema for manageCloudRun tool
116996
116613
  const ManageCloudRunInputSchema = {
116997
- 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智能体)'),
116998
- serverName: zod_1.z.string().describe('云托管服务名称,用于标识和管理服务。命名规则:支持大小写字母、数字、连字符和下划线,必须以字母开头,长度3-45个字符。在init操作中会作为在targetPath下创建的子目录名,在其他操作中作为目标服务名'),
116614
+ action: zod_1.z.enum(['init', 'download', 'run', 'deploy', 'delete', 'createAgent', 'updateConfig', 'initEnv']).describe('云托管服务管理操作类型:init=从模板初始化新的云托管项目代码(在targetPath目录下创建以serverName命名的子目录,支持多种语言和框架模板),download=从云端下载现有服务的代码到本地进行开发,run=在本地运行函数型云托管服务(用于开发和调试,仅支持函数型服务),deploy=将本地代码部署到云端云托管服务(支持函数型和容器型;传 imageUrl 时改为已有镜像部署,走 DeployType=image 容器型,targetPath 可省略;已存在服务会 Read-Merge-Write 保留远程 VpcConf/EnvParams/OpenAccessTypes),updateConfig=仅更新服务配置不重新上传代码(对齐控制台服务设置,走 SubmitServerConfigChangeDiff;不需要 targetPath),delete=删除指定的云托管服务(不可恢复,需要确认),createAgent=创建函数型Agent(基于函数型云托管开发AI智能体),initEnv=开通当前环境的云托管(异步创建云托管环境,幂等:已开通直接返回;适合新环境首次部署前使用)'),
116615
+ serverName: zod_1.z.string().describe('云托管服务名称,用于标识和管理服务。命名规则:支持大小写字母、数字、连字符和下划线,必须以字母开头,长度3-45个字符。在init操作中会作为在targetPath下创建的子目录名,在其他操作中作为目标服务名。initEnv 操作不需要此参数'),
116616
+ // InitEnv operation parameters
116617
+ envId: zod_1.z.string().optional().describe('环境 ID(action=initEnv 时使用;不传则使用当前配置的环境)。格式如 env-xxxxxx'),
116618
+ packageType: zod_1.z.enum(exports.CLOUDRUN_PACKAGE_TYPES).optional().default('Trial').describe('云托管环境套餐类型(action=initEnv 时使用):Trial=试用,Standard=标准,Professional=专业,Enterprise=企业。默认 Trial'),
116999
116619
  // Deploy operation parameters
117000
- targetPath: zod_1.z.string().optional().describe('本地代码路径,必须是绝对路径。在deploy操作中指定要部署的代码目录,在download操作中指定下载目标目录,在init操作中指定云托管服务的上级目录(会在该目录下创建以serverName命名的子目录)。updateConfig 不需要此参数。建议约定:项目根目录下的cloudrun/目录,例如:/Users/username/projects/my-project/cloudrun'),
116620
+ targetPath: zod_1.z.string().optional().describe('本地代码路径,必须是绝对路径。在deploy操作中指定要部署的代码目录,在download操作中指定下载目标目录,在init操作中指定云托管服务的上级目录(会在该目录下创建以serverName命名的子目录)。updateConfig 不需要此参数。建议约定:项目根目录下的cloudrun/目录,例如:/Users/username/projects/my-project/cloudrun。使用 imageUrl 部署已有镜像时此参数可省略'),
116621
+ imageUrl: zod_1.z.string().optional().describe('已有镜像部署(action=deploy 时使用):直接指定容器镜像地址,如 ccr.ccs.tencentyun.com/ns/img:v1 或公网 registry 地址。传入后走 DeployType="image"(容器型)部署,无需本地源码目录(targetPath 可省略)。支持:1) 公网匿名可拉取的镜像直填地址;2) 私有/需登录的镜像(如 ghcr.io)需先在本地 docker pull → docker tag/push 到腾讯云 CCR → 填入 CCR 地址。不传则维持源码构建(本地代码打包上传)。注意:无论哪种部署方式,环境都需先开通云托管(未开通时先调用 initEnv,Status=normal 后再部署)'),
117001
116622
  envParamsReplaceAll: zod_1.z.boolean().optional().default(false).describe('EnvParams 合并策略(deploy / updateConfig):false(默认)= 与远程按 key 合并(输入覆盖同名 key,远程其余 key 保留);true= 用输入 EnvParams 整包替换远程。仅当显式传入 EnvParams 时生效'),
117002
116623
  serverConfig: zod_1.z.object({
117003
116624
  OpenAccessTypes: zod_1.z.array(zod_1.z.enum(exports.CLOUDRUN_ACCESS_TYPES)).optional().describe('公网访问类型配置,控制服务的访问权限:OA=办公网访问,PUBLIC=公网访问(默认,可通过HTTPS域名访问),MINIAPP=小程序访问,VPC=VPC访问(仅同VPC内可访问)。可配置多个类型'),
@@ -117143,6 +116764,88 @@ function buildManageCloudRunErrorMessage(action, serverName, error) {
117143
116764
  }
117144
116765
  const CLOUDRUN_DB_ENV_KEY_PATTERN = /^(DATABASE_URL|DB_HOST|DB_PORT|DB_USER|DB_PASSWORD|DB_NAME|MYSQL_|POSTGRES_|PGHOST|PGPORT|PGUSER|PGPASSWORD|PGDATABASE|PG_|REDIS_|MONGO_|MONGODB_|SQLALCHEMY_DATABASE_URI|SPRING_DATASOURCE_)/i;
117145
116766
  const CLOUDRUN_DB_URL_PATTERN = /(mysql|mariadb|postgres|postgresql|mongodb(\+srv)?|redis|rediss):\/\//i;
116767
+ async function queryCloudRunEnvStatus(options) {
116768
+ const manager = await (0, cloudbase_manager_js_1.getCloudBaseManager)({ cloudBaseOptions: options.cloudBaseOptions });
116769
+ if (!manager?.commonService) {
116770
+ throw new Error("Current CloudBase Manager does not support commonService; cannot query CloudRun env status.");
116771
+ }
116772
+ return describeCloudRunEnvStatus(manager, options.envId);
116773
+ }
116774
+ /**
116775
+ * 核心实现:用已获取的 manager 查询云托管开通状态(供 initEnv/envStatus 及
116776
+ * ensureCloudRunEnvInitialized 复用,避免重复 getCloudBaseManager)。
116777
+ */
116778
+ async function describeCloudRunEnvStatus(manager, envId) {
116779
+ const result = await manager
116780
+ .commonService("tcbr", "2022-02-17")
116781
+ .call({
116782
+ Action: "DescribeEnvBaseInfo",
116783
+ Param: { EnvId: envId },
116784
+ });
116785
+ const data = (result ?? {});
116786
+ const baseInfo = (data.EnvBaseInfo ?? {}) ?? {};
116787
+ if (data.IsExist !== true) {
116788
+ return { isExist: false, status: "unopened", baseInfo };
116789
+ }
116790
+ const rawStatus = typeof baseInfo.Status === "string" ? baseInfo.Status : "";
116791
+ const status = rawStatus === "creating" || rawStatus === "normal"
116792
+ ? rawStatus
116793
+ : "unknown";
116794
+ return { isExist: true, status, baseInfo };
116795
+ }
116796
+ /**
116797
+ * 探测当前环境云托管(大租户)是否已初始化。
116798
+ *
116799
+ * 背景(2026-08-13 用户实测):新环境未调 CreateCloudRunEnv 初始化云托管时,
116800
+ * 直接 CreateCloudRunServer 会因"无大租户记录"被默认转入小租户,创建出小租户的
116801
+ * 服务和版本——这是错误路径。本函数在 deploy 创建新服务前用 tcbr DescribeEnvBaseInfo
116802
+ * 探测环境是否已开通云托管;未开通则抛错引导先初始化,而不是默默走到小租户路径。
116803
+ *
116804
+ * 实测(2026-08-13 真实凭据):tcbr 不存在 DescribeCloudRunEnv(单数)Action,调用
116805
+ * 恒返回 InvalidAction;正确的探测接口是 DescribeEnvBaseInfo。未开通云托管的环境返回
116806
+ * IsExist=false 且 EnvBaseInfo 为空结构(不抛错);已开通的环境(实测 ai-share-
116807
+ * d2guukyxybb63b206)返回 IsExist=true 且 EnvBaseInfo 含完整字段(Status="normal"、
116808
+ * PackageType/Region/EnvType/CreateTime 等已填充),两分支可明确区分。
116809
+ *
116810
+ * 双验证:DescribeCloudRunServers 未初始化与已初始化但无服务均返回 ServerList=[],
116811
+ * 无法区分,故不作为初始化判定依据。
116812
+ *
116813
+ * @returns 已初始化返回 true;探测到未初始化抛出带引导信息的 Error。
116814
+ */
116815
+ async function ensureCloudRunEnvInitialized(options) {
116816
+ const manager = await (0, cloudbase_manager_js_1.getCloudBaseManager)({ cloudBaseOptions: options.cloudBaseOptions });
116817
+ if (!manager?.commonService) {
116818
+ // 老 SDK 无 commonService 时退化为不拦截(保持既有行为,避免误伤)。
116819
+ return true;
116820
+ }
116821
+ try {
116822
+ const status = await describeCloudRunEnvStatus(manager, options.envId);
116823
+ if (!status.isExist) {
116824
+ throwCloudRunEnvNotInitialized(options.envId);
116825
+ }
116826
+ return true;
116827
+ }
116828
+ catch (error) {
116829
+ const msg = error instanceof Error ? error.message : String(error);
116830
+ // 错误兜底:未初始化/未开通类错误码。
116831
+ // 注意:裸 InvalidParameter 可能是普通参数错误,不拦截;仅当其带 Env/CloudRun
116832
+ // 上下文(疑似 "EnvironmentId not found / CloudRun Env 未开通")时才按未初始化处理。
116833
+ if (/ResourceNotFound|not.?initialized|未开通|未初始化/i.test(msg) ||
116834
+ /InvalidParameter.*(?:Env|CloudRun)/i.test(msg)) {
116835
+ throwCloudRunEnvNotInitialized(options.envId);
116836
+ }
116837
+ // 其他错误(网络/权限等)不拦截,让上层按原逻辑处理。
116838
+ return true;
116839
+ }
116840
+ }
116841
+ function throwCloudRunEnvNotInitialized(envId) {
116842
+ throw new Error(`当前环境(${envId})尚未初始化云托管(CloudRun Env)。` +
116843
+ `不能直接创建服务(CreateCloudRunServer 在无大租户记录时会默认创建到小租户,产生错误的小租户服务与版本)。\n` +
116844
+ `请先开通云托管环境,再重试部署:\n` +
116845
+ `- MCP:manageCloudRun(action="initEnv", envId="${envId}")(异步开通,幂等;开通完成后可用 queryCloudRun(action="envStatus", envId="${envId}") 查询 Status=normal)\n` +
116846
+ `- 或控制台:环境 → 云托管 → 开通(https://tcb.cloud.tencent.com/dev?envId=${envId}#/platform-run)\n` +
116847
+ `初始化完成后重新调用 manageCloudRun(action="deploy")。`);
116848
+ }
117146
116849
  /**
117147
116850
  * Detect likely TCP database/cache env usage without VpcConf.
117148
116851
  * Soft signal for AI agents — does not block deploy.
@@ -117239,6 +116942,36 @@ function normalizeCloudRunDomainUrl(input) {
117239
116942
  ? raw
117240
116943
  : `https://${raw}`;
117241
116944
  }
116945
+ /**
116946
+ * 从服务详情 / 最新部署记录中提取镜像信息(镜像部署时才有)。
116947
+ * 镜像部署(DeployType=image)的服务详情与部署记录通常会携带 ImageUrl 等字段;
116948
+ * 源码构建的服务无此字段,返回 undefined 表示无镜像信息。
116949
+ */
116950
+ function extractCloudRunImageInfo(serviceDetail, latestDeploy) {
116951
+ const candidates = [
116952
+ latestDeploy,
116953
+ serviceDetail?.ServerConfig,
116954
+ serviceDetail?.BaseInfo,
116955
+ serviceDetail,
116956
+ ];
116957
+ for (const source of candidates) {
116958
+ if (!source || typeof source !== "object")
116959
+ continue;
116960
+ const imageUrl = source.ImageUrl ??
116961
+ source.imageUrl ??
116962
+ (typeof source.ImageInfo === "string" ? source.ImageInfo : undefined) ??
116963
+ (typeof source.ImageInfo?.ImageUrl === "string" ? source.ImageInfo.ImageUrl : undefined);
116964
+ if (typeof imageUrl === "string" && imageUrl.trim()) {
116965
+ const deployType = typeof source.DeployType === "string"
116966
+ ? source.DeployType
116967
+ : typeof source.deployType === "string"
116968
+ ? source.deployType
116969
+ : undefined;
116970
+ return { imageUrl: imageUrl.trim(), ...(deployType ? { deployType } : {}) };
116971
+ }
116972
+ }
116973
+ return undefined;
116974
+ }
117242
116975
  function resolveCloudRunFallbackAccess(details) {
117243
116976
  const custom = normalizeCloudRunDomainUrl(details?.BaseInfo?.CustomDomainName);
117244
116977
  if (custom)
@@ -117269,7 +117002,7 @@ function registerCloudRunTools(server) {
117269
117002
  // Tool 1: Get CloudRun service information (read operations)
117270
117003
  server.registerTool("queryCloudRun", {
117271
117004
  title: "查询 CloudRun 服务信息",
117272
- description: "查询云托管服务信息,支持获取服务列表、查询服务详情、获取可用模板列表和部署日志。返回的服务信息包括服务名称、状态、访问类型、配置详情以及最近部署上下文。",
117005
+ description: "查询云托管服务信息,支持获取服务列表、查询服务详情、获取可用模板列表、获取部署日志以及查询环境云托管开通状态(envStatus)。返回的服务信息包括服务名称、状态、访问类型、配置详情以及最近部署上下文。",
117273
117006
  inputSchema: queryCloudRunInputSchema,
117274
117007
  annotations: {
117275
117008
  readOnlyHint: true,
@@ -117381,6 +117114,10 @@ function registerCloudRunTools(server) {
117381
117114
  data: {
117382
117115
  service: result,
117383
117116
  latestDeploy,
117117
+ // 若最新部署记录带镜像信息(镜像部署),透出便于展示
117118
+ ...(extractCloudRunImageInfo(result, latestDeploy)
117119
+ ? { imageInfo: extractCloudRunImageInfo(result, latestDeploy) }
117120
+ : {}),
117384
117121
  ...(deployRecordsWarning ? { deployRecordsWarning } : {})
117385
117122
  },
117386
117123
  message
@@ -117479,6 +117216,65 @@ function registerCloudRunTools(server) {
117479
117216
  ]
117480
117217
  };
117481
117218
  }
117219
+ case 'envStatus': {
117220
+ const envId = input.envId?.trim() || (await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions));
117221
+ if (!manager.commonService) {
117222
+ throw new Error("Current CloudBase Manager does not support commonService; cannot query CloudRun env status.");
117223
+ }
117224
+ let status;
117225
+ try {
117226
+ status = await describeCloudRunEnvStatus(manager, envId);
117227
+ }
117228
+ catch (error) {
117229
+ const baseMessage = error instanceof Error ? error.message : String(error);
117230
+ if (/ResourceNotFound|not.?initialized|未开通|未初始化/i.test(baseMessage) ||
117231
+ /InvalidParameter.*(?:Env|CloudRun)/i.test(baseMessage)) {
117232
+ status = { isExist: false, status: "unopened", baseInfo: {} };
117233
+ }
117234
+ else {
117235
+ throw new Error(`[queryCloudRun/envStatus] ${baseMessage}`);
117236
+ }
117237
+ }
117238
+ let message;
117239
+ if (!status.isExist) {
117240
+ message = `环境 ${envId} 尚未开通云托管。请先调用 manageCloudRun(action="initEnv", envId="${envId}") 开通(异步、幂等),或前往控制台 环境 → 云托管 → 开通;Status=normal 后即可 deploy。`;
117241
+ }
117242
+ else if (status.status === "creating") {
117243
+ message = `环境 ${envId} 云托管正在开通中(Status=creating)。请稍后重试 manageCloudRun(action="deploy"),或用本 action 再次查询直到 Status=normal。`;
117244
+ }
117245
+ else if (status.status === "normal") {
117246
+ message = `环境 ${envId} 云托管已开通(Status=normal),可直接 manageCloudRun(action="deploy")。`;
117247
+ }
117248
+ else {
117249
+ message = `环境 ${envId} 云托管状态未知(Status=${status.status ?? "unknown"}),请稍后重试。`;
117250
+ }
117251
+ return {
117252
+ content: [
117253
+ {
117254
+ type: "text",
117255
+ text: JSON.stringify({
117256
+ success: true,
117257
+ data: {
117258
+ envId,
117259
+ status: status.status,
117260
+ isExist: status.isExist,
117261
+ ...(status.isExist
117262
+ ? {
117263
+ envBaseInfo: {
117264
+ Status: status.baseInfo.Status ?? null,
117265
+ PackageType: status.baseInfo.PackageType ?? null,
117266
+ Region: status.baseInfo.Region ?? null,
117267
+ EnvType: status.baseInfo.EnvType ?? null,
117268
+ },
117269
+ }
117270
+ : {}),
117271
+ },
117272
+ message
117273
+ }, null, 2)
117274
+ }
117275
+ ]
117276
+ };
117277
+ }
117482
117278
  default:
117483
117279
  throw new Error(`Unsupported action: ${input.action}`);
117484
117280
  }
@@ -117488,7 +117284,7 @@ function registerCloudRunTools(server) {
117488
117284
  // Tool 2: Manage CloudRun services (write operations)
117489
117285
  server.registerTool("manageCloudRun", {
117490
117286
  title: "管理 CloudRun 服务",
117491
- description: "管理云托管服务,按开发顺序支持:初始化项目(可从模板开始,模板列表可通过 queryCloudRun 查询)、下载服务代码、本地运行(仅函数型服务)、部署代码、仅更新配置(updateConfig,无需重新上传代码)、删除服务。deploy 对已存在服务会先读取远程配置再合并(保留 VpcConf/EnvParams/OpenAccessTypes)。updateConfig 对齐控制台服务设置页。删除操作需要确认,建议设置force=true。",
117287
+ description: "管理云托管服务,按开发顺序支持:开通云托管环境(initEnv)、初始化项目(可从模板开始,模板列表可通过 queryCloudRun 查询)、下载服务代码、本地运行(仅函数型服务)、部署代码、仅更新配置(updateConfig,无需重新上传代码)、删除服务。deploy 支持两种方式:1) 源码构建(传入 targetPath,本地代码打包上传,默认路径);2) 已有镜像部署(传入 imageUrl,如 ccr.ccs.tencentyun.com/ns/img:v1,走 DeployType=image 容器型部署,targetPath 可省略)。deploy 对已存在服务会先读取远程配置再合并(保留 VpcConf/EnvParams/OpenAccessTypes)。updateConfig 对齐控制台服务设置页。删除操作需要确认,建议设置force=true。新环境首次部署前若提示未开通云托管,先调用 initEnv 开通(异步、幂等)。",
117492
117288
  inputSchema: ManageCloudRunInputSchema,
117493
117289
  annotations: {
117494
117290
  readOnlyHint: false,
@@ -117509,6 +117305,99 @@ function registerCloudRunTools(server) {
117509
117305
  targetPath = validateAndNormalizePath(input.targetPath);
117510
117306
  }
117511
117307
  switch (input.action) {
117308
+ case 'initEnv': {
117309
+ const envId = input.envId?.trim() || (await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions));
117310
+ const packageType = input.packageType || 'Trial';
117311
+ if (!manager.commonService) {
117312
+ throw new Error("Current CloudBase Manager does not support commonService; cannot initialize CloudRun env.");
117313
+ }
117314
+ // 幂等:先查当前开通状态,已开通 / 开通中不重复创建。
117315
+ let current;
117316
+ try {
117317
+ current = await describeCloudRunEnvStatus(manager, envId);
117318
+ }
117319
+ catch (error) {
117320
+ const baseMessage = error instanceof Error ? error.message : String(error);
117321
+ if (/ResourceNotFound|not.?initialized|未开通|未初始化/i.test(baseMessage) ||
117322
+ /InvalidParameter.*(?:Env|CloudRun)/i.test(baseMessage)) {
117323
+ current = { isExist: false, status: "unopened", baseInfo: {} };
117324
+ }
117325
+ else {
117326
+ throw new Error(`[manageCloudRun/initEnv] ${baseMessage}`);
117327
+ }
117328
+ }
117329
+ if (current.isExist && current.status === "normal") {
117330
+ return {
117331
+ content: [
117332
+ {
117333
+ type: "text",
117334
+ text: JSON.stringify({
117335
+ success: true,
117336
+ data: {
117337
+ envId,
117338
+ status: "normal",
117339
+ packageType: current.baseInfo.PackageType ?? packageType,
117340
+ created: false
117341
+ },
117342
+ message: `环境 ${envId} 已开通云托管(Status=normal),无需重复开通。可直接 manageCloudRun(action="deploy")。`
117343
+ }, null, 2)
117344
+ }
117345
+ ]
117346
+ };
117347
+ }
117348
+ if (current.isExist && current.status === "creating") {
117349
+ return {
117350
+ content: [
117351
+ {
117352
+ type: "text",
117353
+ text: JSON.stringify({
117354
+ success: true,
117355
+ data: {
117356
+ envId,
117357
+ status: "creating",
117358
+ created: false
117359
+ },
117360
+ message: `环境 ${envId} 云托管正在开通中(Status=creating),无需重复开通。请稍后用 queryCloudRun(action="envStatus", envId="${envId}") 查询,Status=normal 后即可 deploy。`
117361
+ }, null, 2)
117362
+ }
117363
+ ]
117364
+ };
117365
+ }
117366
+ // 未开通 → 发起异步开通(CreateCloudRunEnv 异步,不阻塞等待)。
117367
+ let createResult;
117368
+ try {
117369
+ createResult = await manager
117370
+ .commonService("tcbr", "2022-02-17")
117371
+ .call({
117372
+ Action: "CreateCloudRunEnv",
117373
+ Param: { EnvId: envId, PackageType: packageType },
117374
+ });
117375
+ }
117376
+ catch (error) {
117377
+ throw new Error(buildManageCloudRunErrorMessage('initEnv', envId, error));
117378
+ }
117379
+ const tranId = createResult?.TranId ??
117380
+ createResult?.Response?.TranId ??
117381
+ createResult?.tranId;
117382
+ return {
117383
+ content: [
117384
+ {
117385
+ type: "text",
117386
+ text: JSON.stringify({
117387
+ success: true,
117388
+ data: {
117389
+ envId,
117390
+ status: "creating",
117391
+ packageType,
117392
+ created: true,
117393
+ ...(tranId ? { tranId } : {})
117394
+ },
117395
+ message: `已发起云托管开通(异步,Status=creating)。请稍后用 queryCloudRun(action="envStatus", envId="${envId}") 查询状态,Status=normal 后即可 manageCloudRun(action="deploy")。`
117396
+ }, null, 2)
117397
+ }
117398
+ ]
117399
+ };
117400
+ }
117512
117401
  case 'createAgent': {
117513
117402
  if (!targetPath) {
117514
117403
  throw new Error("targetPath is required for createAgent operation");
@@ -117674,14 +117563,18 @@ for await (let x of res.textStream) {
117674
117563
  };
117675
117564
  }
117676
117565
  case 'deploy': {
117677
- if (!targetPath) {
117678
- throw new Error("targetPath is required for deploy operation");
117566
+ if (!targetPath && !input.imageUrl) {
117567
+ throw new Error("targetPath (source build) or imageUrl (existing image) is required for deploy operation");
117679
117568
  }
117680
117569
  // Determine service type - use input.serverType if provided, otherwise auto-detect
117681
117570
  let serverType;
117682
117571
  let remoteServerConfig = null;
117683
117572
  let existingService = false;
117684
- if (input.serverType) {
117573
+ if (input.imageUrl) {
117574
+ // Image deploy is always container type (SDK: DeployInfo={DeployType:"image", ImageUrl}).
117575
+ serverType = 'container';
117576
+ }
117577
+ else if (input.serverType) {
117685
117578
  serverType = input.serverType;
117686
117579
  }
117687
117580
  else {
@@ -117735,6 +117628,17 @@ for await (let x of res.textStream) {
117735
117628
  // New service create path
117736
117629
  }
117737
117630
  }
117631
+ // 新环境必须先初始化云托管(大租户),否则 CreateCloudRunServer 会默认
117632
+ // 创建小租户服务。仅创建新服务(非 existing)前探测一次。
117633
+ // (2026-08-13 用户实测:luapi-v2 因未初始化云托管被创建到小租户)
117634
+ if (!existingService) {
117635
+ const currentEnvId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
117636
+ await ensureCloudRunEnvInitialized({
117637
+ cloudBaseOptions,
117638
+ envId: currentEnvId,
117639
+ serverName: input.serverName,
117640
+ });
117641
+ }
117738
117642
  let mergedFromRemote = [];
117739
117643
  let effectiveServerConfig = input.serverConfig;
117740
117644
  if (existingService) {
@@ -117752,6 +117656,9 @@ for await (let x of res.textStream) {
117752
117656
  force: input.force,
117753
117657
  serverType: serverType,
117754
117658
  };
117659
+ if (input.imageUrl) {
117660
+ deployParams.imageUrl = input.imageUrl;
117661
+ }
117755
117662
  if (effectiveServerConfig && Object.keys(effectiveServerConfig).length > 0) {
117756
117663
  deployParams.serverConfig = effectiveServerConfig;
117757
117664
  }
@@ -117772,22 +117679,26 @@ for await (let x of res.textStream) {
117772
117679
  catch (error) {
117773
117680
  throw new Error(buildManageCloudRunErrorMessage('deploy', input.serverName, error));
117774
117681
  }
117775
- // Generate cloudbaserc.json configuration file
117682
+ // Generate cloudbaserc.json configuration file (source-build only; image deploy has no local project dir)
117776
117683
  const currentEnvId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
117777
- const cloudbasercPath = path_1.default.join(targetPath, 'cloudbaserc.json');
117778
- const cloudbasercContent = {
117779
- envId: currentEnvId,
117780
- cloudrun: {
117781
- name: input.serverName
117684
+ let cloudbasercGenerated = false;
117685
+ if (targetPath) {
117686
+ const cloudbasercPath = path_1.default.join(targetPath, 'cloudbaserc.json');
117687
+ const cloudbasercContent = {
117688
+ envId: currentEnvId,
117689
+ cloudrun: {
117690
+ name: input.serverName
117691
+ }
117692
+ };
117693
+ try {
117694
+ fs_1.default.writeFileSync(cloudbasercPath, JSON.stringify(cloudbasercContent, null, 2));
117695
+ cloudbasercGenerated = true;
117696
+ }
117697
+ catch (error) {
117698
+ (0, logger_js_1.debug)('cloudbaserc.json creation skipped:', error instanceof Error ? error : new Error(String(error)));
117782
117699
  }
117783
- };
117784
- const consoleUrl = `https://tcb.cloud.tencent.com/dev?envId=${currentEnvId}#/platform-run/service/detail?serverName=${input.serverName}&tabId=overview&envId=${currentEnvId}`;
117785
- try {
117786
- fs_1.default.writeFileSync(cloudbasercPath, JSON.stringify(cloudbasercContent, null, 2));
117787
- }
117788
- catch (error) {
117789
- (0, logger_js_1.debug)('cloudbaserc.json creation skipped:', error instanceof Error ? error : new Error(String(error)));
117790
117700
  }
117701
+ const consoleUrl = `https://tcb.cloud.tencent.com/dev?envId=${currentEnvId}#/platform-run/service/detail?serverName=${input.serverName}&tabId=overview&envId=${currentEnvId}`;
117791
117702
  let preferredAccessUrl;
117792
117703
  let preferredAccessUrls = [];
117793
117704
  let preferredAccessSource;
@@ -117824,7 +117735,7 @@ for await (let x of res.textStream) {
117824
117735
  }
117825
117736
  // Send deployment notification to CodeBuddy IDE
117826
117737
  try {
117827
- const projectName = path_1.default.basename(targetPath);
117738
+ const projectName = targetPath ? path_1.default.basename(targetPath) : input.serverName;
117828
117739
  await (0, notification_js_1.sendDeployNotification)(server, {
117829
117740
  deployType: 'cloudrun',
117830
117741
  url: preferredAccessUrl ?? "",
@@ -117854,9 +117765,11 @@ for await (let x of res.textStream) {
117854
117765
  data: {
117855
117766
  serviceName: input.serverName,
117856
117767
  status: 'deploying',
117857
- deployPath: targetPath,
117768
+ deployType: input.imageUrl ? 'image' : 'source',
117769
+ ...(targetPath ? { deployPath: targetPath } : {}),
117770
+ ...(input.imageUrl ? { imageUrl: input.imageUrl } : {}),
117858
117771
  serverType: serverType,
117859
- cloudbasercGenerated: true,
117772
+ cloudbasercGenerated,
117860
117773
  consoleUrl,
117861
117774
  ...(existingService
117862
117775
  ? {
@@ -117879,7 +117792,7 @@ for await (let x of res.textStream) {
117879
117792
  : {}),
117880
117793
  ...(warnings.length > 0 ? { warnings } : {}),
117881
117794
  },
117882
- message: `Triggered deployment for ${serverType} service '${input.serverName}' from ${targetPath}. You can follow the progress in ${consoleUrl}.${warningSuffix}`
117795
+ message: `Triggered deployment for ${serverType} service '${input.serverName}' ${input.imageUrl ? `from image ${input.imageUrl}` : `from ${targetPath}`}. You can follow the progress in ${consoleUrl}.${warningSuffix}`
117883
117796
  }, null, 2)
117884
117797
  }
117885
117798
  ]
@@ -122114,7 +122027,8 @@ function registerAppTools(server) {
122114
122027
  .optional()
122115
122028
  .describe("自定义部署命令。通常无需填写,默认自动生成 tcb hosting deploy 命令。" +
122116
122029
  "有 buildPath 时远端已 cd 到该目录,默认用 . 作为源码路径;无 buildPath 时默认用 dist。"),
122117
- ignore: zod_1.z.array(zod_1.z.string()).optional().describe("上传时忽略的文件/目录 glob 模式,例如 **/node_modules/**。"),
122030
+ ignore: zod_1.z.array(zod_1.z.string()).optional().describe("上传时忽略的文件/目录 glob 模式,例如 **/node_modules/**。\n" +
122031
+ "⚠️ 打包的是项目根目录(filePath)而非 buildPath 产物目录:若项目根含 target/(Rust)、.next/、dist-old/、build/ 等大构建产物,必须加进 ignore(如 **/target/**),否则整个目录被打进上传 zip(实证 54GB target → 34GB zip)。默认已排除 node_modules/.git/.DS_Store/**/target/**/.next/**/.next.bak/**。"),
122118
122032
  versionName: zod_1.z
122119
122033
  .string()
122120
122034
  .optional()
@@ -122134,6 +122048,17 @@ function registerAppTools(server) {
122134
122048
  if (!appService) {
122135
122049
  throw new Error("当前 manager 未提供 cloudAppService");
122136
122050
  }
122051
+ // 默认排除的大目录(2026-08-14 实证:ato 项目 target/ 54GB 被整个打进 zip)
122052
+ // tcb app deploy 打包的是项目根目录(localPath)而非 outputDir,必须排除构建产物
122053
+ const defaultPackIgnore = [
122054
+ "node_modules/**",
122055
+ ".git/**",
122056
+ ".DS_Store",
122057
+ "**/.DS_Store",
122058
+ "**/target/**",
122059
+ "**/.next/**",
122060
+ "**/.next.bak/**",
122061
+ ];
122137
122062
  // getUploadUrl — 获取预签名上传 URL(cloud mode 专用)
122138
122063
  if (action === "getUploadUrl") {
122139
122064
  if (!serviceName) {
@@ -122144,9 +122069,9 @@ function registerAppTools(server) {
122144
122069
  serviceName,
122145
122070
  });
122146
122071
  (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, cosInfoResult);
122147
- const defaultIgnore = ["node_modules/**", ".git/**", ".DS_Store", "**/.DS_Store"];
122072
+ const defaultIgnore = defaultPackIgnore;
122148
122073
  // eslint-disable-next-line max-len
122149
- const zipCmd = "zip -r upload.zip . -x 'node_modules/**' -x '.git/**' -x '.DS_Store' -x '**/.DS_Store'";
122074
+ const zipCmd = "zip -r upload.zip . -x 'node_modules/**' -x '.git/**' -x '.DS_Store' -x '**/.DS_Store' -x '**/target/**' -x '**/.next/**' -x '**/.next.bak/**'";
122150
122075
  const followupArgs = {
122151
122076
  action: "deployApp",
122152
122077
  serviceName,
@@ -122190,11 +122115,17 @@ function registerAppTools(server) {
122190
122115
  // 上传代码到 COS(仅本地模式需要,cloud mode 用 cosTimestamp 跳过)
122191
122116
  let cosTs = cosTimestamp;
122192
122117
  if (filePath && !cosTs) {
122118
+ // 默认排除大目录(2026-08-14 实证:ato 项目 target/ 54GB 被整个打进 zip)
122119
+ // 用户显式传 ignore 时合并,避免覆盖默认值
122120
+ const mergedIgnore = Array.from(new Set([
122121
+ ...defaultPackIgnore,
122122
+ ...(ignore ?? []),
122123
+ ]));
122193
122124
  const uploadResult = await appService.uploadCode({
122194
122125
  deployType: "static-hosting",
122195
122126
  serviceName,
122196
122127
  localPath: filePath,
122197
- ignore,
122128
+ ignore: mergedIgnore,
122198
122129
  });
122199
122130
  (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, uploadResult);
122200
122131
  cosTs = uploadResult.cosTimestamp;
@@ -131528,6 +131459,7 @@ module.exports = setup;
131528
131459
  "use strict";
131529
131460
 
131530
131461
  Object.defineProperty(exports, "__esModule", ({ value: true }));
131462
+ exports.assertTcbCloudRunActionAllowed = assertTcbCloudRunActionAllowed;
131531
131463
  exports.removeEmptyStringParams = removeEmptyStringParams;
131532
131464
  exports.buildCapiErrorMessage = buildCapiErrorMessage;
131533
131465
  exports.registerCapiTools = registerCapiTools;
@@ -131539,6 +131471,7 @@ const CLOUDBASE_CONTROL_PLANE_DOC_URL = "https://cloud.tencent.com/document/prod
131539
131471
  const CLOUDBASE_DEPENDENCY_API_DOC_URL = "https://cloud.tencent.com/document/product/876/34808";
131540
131472
  const ALLOWED_SERVICES = [
131541
131473
  "tcb",
131474
+ "tcbr",
131542
131475
  "scf",
131543
131476
  "sts",
131544
131477
  "cam",
@@ -131546,6 +131479,31 @@ const ALLOWED_SERVICES = [
131546
131479
  "cdn",
131547
131480
  "vpc",
131548
131481
  ];
131482
+ /**
131483
+ * tcb 旧版小租户云托管(CloudBase Run)API 族,统一禁用。
131484
+ *
131485
+ * 云托管一律走 tcbr 新逻辑(CreateCloudRunEnv / CreateCloudRunServer)。tcb 的
131486
+ * CreateCloudBaseRunResource 是 2018 旧小租户开通接口:在无大租户记录的环境上调用
131487
+ * 会把服务创建到小租户,产生错误的服务与版本(2026-08-13 用户实测,ATO 调研
131488
+ * efec7cc5 结论)。同族 Describe/Delete 一并拦截,避免 AI 误以为与 tcbr 环境相关。
131489
+ */
131490
+ const TCB_CLOUDRUN_FORBIDDEN_ACTIONS = [
131491
+ "CreateCloudBaseRunResource",
131492
+ "DescribeCloudBaseRunResource",
131493
+ "DeleteCloudBaseRunResource",
131494
+ ];
131495
+ const TCB_CLOUDRUN_FORBIDDEN_HINT = `云托管(CloudBase Run)统一走 tcbr 新逻辑(CreateCloudRunEnv / CreateCloudRunServer),` +
131496
+ `不要使用 tcb 旧小租户接口(${TCB_CLOUDRUN_FORBIDDEN_ACTIONS.join(" / ")})。` +
131497
+ `新环境请先初始化云托管:callCloudApi(service="tcbr", version="2022-02-17", action="CreateCloudRunEnv", params={EnvId:"..."}),` +
131498
+ `再通过 manageCloudRun(action="deploy") 创建服务;查询单个环境基础信息/是否已开通云托管用 callCloudApi(service="tcbr", version="2022-02-17", action="DescribeEnvBaseInfo", params={EnvId:"..."}),查询环境列表/资源信息用 DescribeCloudRunEnvs。`;
131499
+ /**
131500
+ * 拒绝 tcb 旧版小租户云托管 API。命中黑名单时抛出带 tcbr 引导的错误。
131501
+ */
131502
+ function assertTcbCloudRunActionAllowed(service, action) {
131503
+ if (service === "tcb" && TCB_CLOUDRUN_FORBIDDEN_ACTIONS.includes(action)) {
131504
+ throw new Error(`[${service}/${action}] 已禁用:${TCB_CLOUDRUN_FORBIDDEN_HINT}`);
131505
+ }
131506
+ }
131549
131507
  function levenshteinDistance(left, right) {
131550
131508
  const rows = left.length + 1;
131551
131509
  const cols = right.length + 1;
@@ -131621,7 +131579,7 @@ function formatTcbParamsTypeHint(action) {
131621
131579
  return `参数类型参考:\n\`\`\`ts\n${entry.paramsType}\n\`\`\``;
131622
131580
  }
131623
131581
  function buildCapiDocGuidance(service) {
131624
- if (service === "tcb" || service === "lowcode" || service === "scf") {
131582
+ if (service === "tcb" || service === "tcbr" || service === "lowcode" || service === "scf") {
131625
131583
  return `优先查阅 CloudBase API 概览 ${CLOUDBASE_CONTROL_PLANE_DOC_URL} 与云开发依赖资源接口指引 ${CLOUDBASE_DEPENDENCY_API_DOC_URL}。`;
131626
131584
  }
131627
131585
  return `请优先核对对应官方云 API 文档;若你的场景其实是通过 HTTP 协议直接集成 auth/functions/cloudrun/storage/mysqldb 等 CloudBase 业务 API,请优先使用 OpenAPI / Swagger 或 searchKnowledgeBase(mode="openapi"),不要继续猜测管控面 Action。`;
@@ -131711,15 +131669,21 @@ function registerCapiTools(server) {
131711
131669
  **云函数**: \`DescribeFunctions\`、\`CreateFunction\`、\`UpdateFunctionCode\`、\`DeleteFunction\`
131712
131670
  **数据库**: \`CreateMySQLInstance\`、\`DescribeMySQLInstances\`、\`DestroyMySQLInstance\`
131713
131671
 
131672
+ ⚠️ 云托管(CloudBase Run)统一走 tcbr service(CreateCloudRunEnv / CreateCloudRunServer / DescribeEnvBaseInfo / DescribeCloudRunEnvs,version="2022-02-17"),tcb 旧小租户接口 CreateCloudBaseRunResource 等已被禁用;部署请用 manageCloudRun。查询单个环境基础信息/是否已开通云托管用 DescribeEnvBaseInfo(EnvId 必填),查询环境列表及资源信息用 DescribeCloudRunEnvs(EnvId 可选过滤)。
131673
+
131714
131674
  销毁环境时,常见做法是至少带上 \`EnvId\` 和 \`BypassCheck: true\`,如果环境已经处于隔离期再按文档补 \`IsForce: true\`。`,
131715
131675
  inputSchema: {
131716
131676
  service: zod_1.z
131717
131677
  .enum(ALLOWED_SERVICES)
131718
- .describe("选择要访问的服务。可选:tcb、scf、sts、cam、lowcode、cdn、vpc。对于 tcb / scf / lowcode 等 CloudBase 管控面 Action,请优先查官方文档,不要直接猜测 Action。"),
131678
+ .describe("选择要访问的服务。可选:tcb、tcbr、scf、sts、cam、lowcode、cdn、vpc。对于 tcb / scf / lowcode 等 CloudBase 管控面 Action,请优先查官方文档,不要直接猜测 Action。云托管统一走 tcbr(version 需传 2022-02-17)。"),
131719
131679
  action: zod_1.z
131720
131680
  .string()
131721
131681
  .min(1)
131722
- .describe("具体 Action 名称,需符合对应服务的官方 API 定义。若不确定正确 Action,请先查官方文档;不要用近义词或历史命名进行猜测。tcb 常用 Action:环境管理 CreateEnv/ModifyEnv/DescribeEnvs/DestroyEnv、用户管理 CreateUser/ModifyUser/DescribeUserList/DeleteUsers、认证配置 EditAuthConfig、云函数 DescribeFunctions/CreateFunction、数据库 CreateMySQLInstance 等。"),
131682
+ .describe("具体 Action 名称,需符合对应服务的官方 API 定义。若不确定正确 Action,请先查官方文档;不要用近义词或历史命名进行猜测。tcb 常用 Action:环境管理 CreateEnv/ModifyEnv/DescribeEnvs/DestroyEnv、用户管理 CreateUser/ModifyUser/DescribeUserList/DeleteUsers、认证配置 EditAuthConfig、云函数 DescribeFunctions/CreateFunction、数据库 CreateMySQLInstance 等。tcbr 常用 Action:CreateCloudRunEnv(初始化云托管)、DescribeEnvBaseInfo(查询单个环境基础信息,EnvId 必填)、DescribeCloudRunEnvs(查询环境列表/资源信息,EnvId 可选过滤)、CreateCloudRunServer/DescribeCloudRunServers。"),
131683
+ version: zod_1.z
131684
+ .string()
131685
+ .optional()
131686
+ .describe("API 版本(可选)。缺省时按 service 使用 SDK 内置默认版本;tcbr 必须传 \"2022-02-17\"(否则请求缺少 X-TC-Version 会失败)。示例:service=\"tcbr\", version=\"2022-02-17\", action=\"CreateCloudRunEnv\", params={EnvId:\"env-xxx\",PackageType:\"Standard\"}。"),
131723
131687
  params: zod_1.z
131724
131688
  .record(zod_1.z.any())
131725
131689
  .optional()
@@ -131732,10 +131696,11 @@ function registerCapiTools(server) {
131732
131696
  openWorldHint: true,
131733
131697
  category: CATEGORY,
131734
131698
  },
131735
- }, async ({ service, action, params, }) => {
131699
+ }, async ({ service, action, params, version, }) => {
131736
131700
  if (!ALLOWED_SERVICES.includes(service)) {
131737
131701
  throw new Error(`Service ${service} is not allowed. Allowed services: ${ALLOWED_SERVICES.join(", ")}`);
131738
131702
  }
131703
+ assertTcbCloudRunActionAllowed(service, action);
131739
131704
  const cloudbase = await getManager();
131740
131705
  if (['1', 'true'].includes(process.env.CLOUDBASE_EVALUATE_MODE ?? '')) {
131741
131706
  if (service === 'lowcode') {
@@ -131764,7 +131729,7 @@ function registerCapiTools(server) {
131764
131729
  let result;
131765
131730
  try {
131766
131731
  const cleanedParams = params ? removeEmptyStringParams(params) : {};
131767
- result = await cloudbase.commonService(service).call({
131732
+ result = await cloudbase.commonService(service, version).call({
131768
131733
  Action: action,
131769
131734
  Param: cleanedParams,
131770
131735
  });
@@ -142390,7 +142355,7 @@ class TelemetryReporter {
142390
142355
  const arch = os_1.default.arch(); // 系统架构
142391
142356
  // Build-time injected version; guard for vitest / non-webpack runtimes.
142392
142357
  const mcpVersion = process.env.npm_package_version ||
142393
- ( true ? "2.26.0" : 0);
142358
+ ( true ? "2.27.0" : 0);
142394
142359
  return {
142395
142360
  userAgent: `${osType} ${osRelease} ${arch} ${nodeVersion} CloudBase-MCP/${mcpVersion}`,
142396
142361
  deviceId: this.deviceId,
@@ -218487,6 +218452,127 @@ TransportStream.prototype._nop = function _nop() {
218487
218452
  };
218488
218453
 
218489
218454
 
218455
+ /***/ }),
218456
+
218457
+ /***/ 68107:
218458
+ /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
218459
+
218460
+ "use strict";
218461
+
218462
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
218463
+ exports.SITE_IDS = exports.SITE_REGION_MAP = void 0;
218464
+ exports.isSiteId = isSiteId;
218465
+ exports.normalizeSite = normalizeSite;
218466
+ exports.getSite = getSite;
218467
+ exports.resolveSite = resolveSite;
218468
+ exports.resolveSiteAndRegion = resolveSiteAndRegion;
218469
+ const project_config_js_1 = __webpack_require__(68445);
218470
+ exports.SITE_REGION_MAP = {
218471
+ domestic: {
218472
+ id: "domestic",
218473
+ label: "国内站",
218474
+ authHost: "tcb.cloud.tencent.com",
218475
+ consoleHost: "tcb.cloud.tencent.com",
218476
+ defaultRegion: "ap-shanghai",
218477
+ regions: ["ap-shanghai", "ap-guangzhou", "ap-singapore"],
218478
+ capabilities: { noSql: true },
218479
+ },
218480
+ intl: {
218481
+ id: "intl",
218482
+ label: "国际站",
218483
+ authHost: "tcb.tencentcloud.com",
218484
+ consoleHost: "tcb.tencentcloud.com",
218485
+ defaultRegion: "ap-singapore",
218486
+ regions: ["ap-singapore"],
218487
+ capabilities: { noSql: false },
218488
+ },
218489
+ };
218490
+ exports.SITE_IDS = Object.keys(exports.SITE_REGION_MAP);
218491
+ function isSiteId(value) {
218492
+ return value === "domestic" || value === "intl";
218493
+ }
218494
+ function normalizeSite(value) {
218495
+ if (typeof value !== "string") {
218496
+ return undefined;
218497
+ }
218498
+ const normalized = value.trim().toLowerCase();
218499
+ if (normalized === "intl" || normalized === "international") {
218500
+ return "intl";
218501
+ }
218502
+ if (normalized === "domestic" || normalized === "cn") {
218503
+ return "domestic";
218504
+ }
218505
+ return undefined;
218506
+ }
218507
+ /**
218508
+ * 根据 region 与显式 site 解析站点。
218509
+ *
218510
+ * - 显式 site 优先(`domestic`/`intl`,兼容 `cn`/`international` 别名)
218511
+ * - 否则查 SITE_REGION_MAP:region 只属于一个站点时返回该站点
218512
+ * - 当 region 同时存在于多个站点(如 ap-singapore)时返回 `ambiguous`,由上层决定
218513
+ * - 未知 region 或未提供 region 时回退 domestic(全局默认)
218514
+ */
218515
+ function getSite(region, explicitSite) {
218516
+ const explicit = normalizeSite(explicitSite);
218517
+ if (explicit) {
218518
+ return explicit;
218519
+ }
218520
+ if (!region) {
218521
+ return "domestic";
218522
+ }
218523
+ const matches = exports.SITE_IDS.filter((site) => exports.SITE_REGION_MAP[site].regions.includes(region));
218524
+ if (matches.length === 1) {
218525
+ return matches[0];
218526
+ }
218527
+ if (matches.length > 1) {
218528
+ return "ambiguous";
218529
+ }
218530
+ return "domestic";
218531
+ }
218532
+ /**
218533
+ * 认证/路由场景下解析站点:歧义(如 ap-singapore 未配 site)时默认 intl,保持既有国际站行为。
218534
+ */
218535
+ function resolveSite(region, explicitSite) {
218536
+ const site = getSite(region, explicitSite);
218537
+ return site === "ambiguous" ? "intl" : site;
218538
+ }
218539
+ /**
218540
+ * 统一 site/region 解析入口(收敛各调用点分散的 region fallback)。
218541
+ *
218542
+ * 优先级:显式参数 > 环境变量(TCB_SITE/TCB_REGION)> 项目配置(.cloudbase/project.json)> 全局默认
218543
+ * (site=domestic, region=ap-shanghai)。
218544
+ *
218545
+ * 当仅指定 region 且该 region 在多个 site 的地域列表中都存在(如 ap-singapore)时,
218546
+ * 返回 site=intl 并标记 ambiguous=true(兼容既有国际站行为),调用方可用 ambiguous 提示用户显式指定 site。
218547
+ */
218548
+ function resolveSiteAndRegion(opts = {}) {
218549
+ const projectConfig = (0, project_config_js_1.readProjectConfig)();
218550
+ const explicitSite = normalizeSite(opts.site) ??
218551
+ normalizeSite(process.env.TCB_SITE) ??
218552
+ normalizeSite(projectConfig?.site);
218553
+ const explicitRegion = opts.region ?? process.env.TCB_REGION ?? projectConfig?.region;
218554
+ let site = explicitSite;
218555
+ let ambiguous = false;
218556
+ if (!site && explicitRegion) {
218557
+ const inferred = getSite(explicitRegion);
218558
+ if (inferred === "ambiguous") {
218559
+ site = "intl";
218560
+ ambiguous = true;
218561
+ }
218562
+ else if (inferred !== "domestic") {
218563
+ site = inferred;
218564
+ }
218565
+ }
218566
+ const resolvedSite = site ?? "domestic";
218567
+ const region = explicitRegion ?? exports.SITE_REGION_MAP[resolvedSite].defaultRegion;
218568
+ return {
218569
+ site: resolvedSite,
218570
+ region,
218571
+ ...(ambiguous ? { ambiguous: true } : {}),
218572
+ };
218573
+ }
218574
+
218575
+
218490
218576
  /***/ }),
218491
218577
 
218492
218578
  /***/ 68182:
@@ -218578,6 +218664,44 @@ function parseEffectsDef(_def, refs) {
218578
218664
  exports.parseEffectsDef = parseEffectsDef;
218579
218665
 
218580
218666
 
218667
+ /***/ }),
218668
+
218669
+ /***/ 68445:
218670
+ /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
218671
+
218672
+ "use strict";
218673
+
218674
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
218675
+ exports.readProjectConfig = readProjectConfig;
218676
+ const node_fs_1 = __webpack_require__(89971);
218677
+ const node_path_1 = __webpack_require__(26743);
218678
+ /**
218679
+ * 读取项目级配置 `.cloudbase/project.json`。
218680
+ *
218681
+ * 该文件是 site/region/envId 的可选持久化来源,让"打开项目即连对服务"
218682
+ * (对齐 Vercel `.vercel/project.json` 的三级回退)。读取失败/文件不存在
218683
+ * 返回 undefined,不阻塞调用方。
218684
+ */
218685
+ function readProjectConfig(cwd) {
218686
+ try {
218687
+ const projectRoot = cwd ?? process.env.WORKSPACE_FOLDER_PATHS ?? process.cwd();
218688
+ const configPath = (0, node_path_1.join)(projectRoot, ".cloudbase", "project.json");
218689
+ if (!(0, node_fs_1.existsSync)(configPath)) {
218690
+ return undefined;
218691
+ }
218692
+ const raw = (0, node_fs_1.readFileSync)(configPath, "utf-8");
218693
+ const parsed = JSON.parse(raw);
218694
+ if (!parsed || typeof parsed !== "object") {
218695
+ return undefined;
218696
+ }
218697
+ return parsed;
218698
+ }
218699
+ catch {
218700
+ return undefined;
218701
+ }
218702
+ }
218703
+
218704
+
218581
218705
  /***/ }),
218582
218706
 
218583
218707
  /***/ 68599:
@@ -223806,7 +223930,7 @@ ${envIdSection}
223806
223930
  ## 环境信息
223807
223931
  - 操作系统: ${os_1.default.type()} ${os_1.default.release()}
223808
223932
  - Node.js版本: ${process.version}
223809
- - MCP 版本:${process.env.npm_package_version || ( true ? "2.26.0" : 0)}
223933
+ - MCP 版本:${process.env.npm_package_version || ( true ? "2.27.0" : 0)}
223810
223934
  - 系统架构: ${os_1.default.arch()}
223811
223935
  - 时间: ${new Date().toISOString()}
223812
223936
  - 请求ID: ${requestId}
@@ -223887,7 +224011,7 @@ function createWrappedHandler(name, handler, server) {
223887
224011
  requestId: (typeof error === 'object' && error && 'requestId' in error) ? error.requestId : '',
223888
224012
  ide: server.ide || process.env.INTEGRATION_IDE || ''
223889
224013
  });
223890
- const mcpVersion = true ? "2.26.0" : 0;
224014
+ const mcpVersion = true ? "2.27.0" : 0;
223891
224015
  const requestIdSuffix = requestId ? `\n🆔 RequestId: ${requestId}` : '';
223892
224016
  const enhancedErrorMessage = `${errorMessage}${requestIdSuffix}\n\n📦 CloudBase MCP v${mcpVersion}\n🔗 遇到问题?请复制以下链接到浏览器打开\n即可自动携带错误详情快速创建 GitHub Issue:\n${issueLink}`;
223893
224017
  // 创建新的错误对象,保持原有的错误类型但更新消息
@@ -241107,7 +241231,7 @@ function registerSetupTools(server) {
241107
241231
  server.registerTool("downloadTemplate", {
241108
241232
  title: "下载项目模板",
241109
241233
  description: `自动下载并部署CloudBase项目模板。
241110
- **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.26.0" : 0}),便于后续维护和版本追踪\n- 下载 rules 模板时,如果项目中已存在 README.md 文件,系统会自动保护该文件不被覆盖(除非设置 overwrite=true)`,
241234
+ **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.27.0" : 0}),便于后续维护和版本追踪\n- 下载 rules 模板时,如果项目中已存在 README.md 文件,系统会自动保护该文件不被覆盖(除非设置 overwrite=true)`,
241111
241235
  inputSchema: {
241112
241236
  template: zod_1.z
241113
241237
  .enum(["react", "vue", "miniprogram", "uniapp", "rules"])
@@ -242537,7 +242661,7 @@ exports.getLoginState = getLoginState;
242537
242661
  exports.logout = logout;
242538
242662
  const toolbox_1 = __webpack_require__(25901);
242539
242663
  const logger_js_1 = __webpack_require__(13039);
242540
- const tencent_cloud_js_1 = __webpack_require__(21454);
242664
+ const site_map_js_1 = __webpack_require__(68107);
242541
242665
  const auth = toolbox_1.AuthSupervisor.getInstance({});
242542
242666
  const authProgressState = {
242543
242667
  status: "IDLE",
@@ -242786,6 +242910,98 @@ function resetAuthProgressState() {
242786
242910
  lastError: undefined,
242787
242911
  });
242788
242912
  }
242913
+ const LEGACY_SITE = "domestic";
242914
+ function isSlottedCredential(value) {
242915
+ if (!value || typeof value !== "object") {
242916
+ return false;
242917
+ }
242918
+ return "domestic" in value || "intl" in value;
242919
+ }
242920
+ async function readStoredCredentialRaw() {
242921
+ return toolbox_1.authStore.get("credential");
242922
+ }
242923
+ /**
242924
+ * 读取指定 site 槽位的原始凭证;旧格式(单槽 flat)视为 domestic 槽位。
242925
+ */
242926
+ async function readSiteCredentialRaw(site) {
242927
+ const raw = await readStoredCredentialRaw();
242928
+ if (!raw) {
242929
+ return undefined;
242930
+ }
242931
+ if (isSlottedCredential(raw)) {
242932
+ return raw[site];
242933
+ }
242934
+ return site === LEGACY_SITE ? raw : undefined;
242935
+ }
242936
+ /**
242937
+ * 将凭证写入指定 site 槽位,保留其他槽位数据。
242938
+ * base 缺省时读取当前存储;旧单槽数据会被迁移为 domestic 槽位(写回时升级分槽)。
242939
+ */
242940
+ async function writeSiteCredential(site, credential, base) {
242941
+ const current = base ?? (await readStoredCredentialRaw());
242942
+ const slotted = current && isSlottedCredential(current)
242943
+ ? { ...current }
242944
+ : { domestic: current ?? {} };
242945
+ slotted[site] = credential ?? {};
242946
+ await toolbox_1.authStore.set("credential", slotted);
242947
+ }
242948
+ /**
242949
+ * 确保存储已为分槽格式并返回槽位快照。
242950
+ * 用于登录前迁移旧单槽数据,避免 @cloudbase/toolbox 内部误命中旧凭证而跳过新站点登录。
242951
+ */
242952
+ async function ensureSlottedCredential() {
242953
+ const raw = await readStoredCredentialRaw();
242954
+ if (raw && isSlottedCredential(raw)) {
242955
+ return { ...raw };
242956
+ }
242957
+ const slotted = { domestic: raw ?? {} };
242958
+ await toolbox_1.authStore.set("credential", slotted);
242959
+ return slotted;
242960
+ }
242961
+ function isSlotTokenExpired(credential, gap = 120) {
242962
+ return (!!credential.accessTokenExpired &&
242963
+ Number(credential.accessTokenExpired) < Date.now() + gap * 1000);
242964
+ }
242965
+ /**
242966
+ * 读取并解析指定 site 的登录态,必要时走 refreshToken 续期(镜像 @cloudbase/toolbox 行为)。
242967
+ */
242968
+ async function resolveSiteLoginState(site) {
242969
+ const raw = await readSiteCredentialRaw(site);
242970
+ if (!raw) {
242971
+ return null;
242972
+ }
242973
+ const credential = (0, toolbox_1.resolveCredential)(raw);
242974
+ if (!credential?.secretId || !credential?.secretKey) {
242975
+ return null;
242976
+ }
242977
+ if (credential.refreshToken) {
242978
+ if (!isSlotTokenExpired(credential)) {
242979
+ return credential;
242980
+ }
242981
+ if (Date.now() < Number(credential.expired)) {
242982
+ try {
242983
+ const refreshed = await (0, toolbox_1.refreshTmpToken)(credential);
242984
+ await writeSiteCredential(site, refreshed ?? {});
242985
+ const resolved = (0, toolbox_1.resolveCredential)(refreshed ?? {});
242986
+ return resolved?.secretId ? resolved : null;
242987
+ }
242988
+ catch (e) {
242989
+ const code = e?.code;
242990
+ if (code === "AUTH_FAIL" || code === "InternalError.GetRoleError") {
242991
+ return null;
242992
+ }
242993
+ throw e;
242994
+ }
242995
+ }
242996
+ return null;
242997
+ }
242998
+ return credential;
242999
+ }
243000
+ function isUsableCredential(value) {
243001
+ return (!!value &&
243002
+ typeof value === "object" &&
243003
+ Object.keys(value).length > 0);
243004
+ }
242789
243005
  async function peekLoginState(options) {
242790
243006
  const envVarLoginState = normalizeLoginStateFromEnvVars(options);
242791
243007
  if (envVarLoginState) {
@@ -242807,14 +243023,25 @@ async function peekLoginState(options) {
242807
243023
  (0, logger_js_1.debug)("loginByApiSecret");
242808
243024
  return envVarLoginState;
242809
243025
  }
242810
- // 尝试从 toolbox 本地存储读取(包括项目级 API Key 凭证)
242811
- return auth.getLoginState();
243026
+ // 按 site 读取分槽凭证(缺省按 TCB_SITE/region 解析站点,默认 domestic)
243027
+ const site = (0, site_map_js_1.normalizeSite)(options?.site) ?? (0, site_map_js_1.resolveSite)(options?.region, process.env.TCB_SITE);
243028
+ const slotLoginState = await resolveSiteLoginState(site);
243029
+ if (slotLoginState) {
243030
+ return slotLoginState;
243031
+ }
243032
+ // 兼容旧单槽数据(视为 domestic),走 toolbox 读取/续期
243033
+ if (site === LEGACY_SITE) {
243034
+ return auth.getLoginState();
243035
+ }
243036
+ return null;
242812
243037
  }
242813
243038
  async function ensureLogin(options) {
242814
243039
  (0, logger_js_1.debug)("TENCENTCLOUD_SECRETID", { hasSecretId: !!process.env.TENCENTCLOUD_SECRETID });
242815
243040
  (0, logger_js_1.debug)("CLOUDBASE_API_KEY", { hasApiKey: !!getCloudBaseApiKeyFromEnv() });
242816
243041
  const loginState = await peekLoginState({
242817
243042
  ignoreEnvVars: options?.ignoreEnvVars,
243043
+ site: options?.site,
243044
+ region: options?.region,
242818
243045
  });
242819
243046
  if (!loginState) {
242820
243047
  const resolvedAuthOptions = resolveAuthOptions({
@@ -242830,21 +243057,31 @@ async function ensureLogin(options) {
242830
243057
  throw new Error(validationError);
242831
243058
  }
242832
243059
  const mode = resolvedAuthOptions.authMode;
243060
+ // 按显式 site > TCB_SITE > region 映射表解析站点(ap-singapore 歧义默认 intl,兼容既有国际站行为)
243061
+ const resolvedSite = (0, site_map_js_1.resolveSite)(options?.region, options?.site ?? process.env.TCB_SITE);
242833
243062
  const loginOptions = { flow: mode };
242834
243063
  if (mode === "web") {
242835
243064
  loginOptions.getAuthUrl =
242836
- options?.fromCloudBaseLoginPage && !(0, tencent_cloud_js_1.isInternationalRegion)(options?.region)
243065
+ options?.fromCloudBaseLoginPage && resolvedSite === "domestic"
242837
243066
  ? (url) => {
242838
243067
  const separator = url.includes("?") ? "&" : "?";
242839
243068
  const urlWithParam = `${url}${separator}allowNoEnv=true`;
242840
- return `https://tcb.cloud.tencent.com/login?_redirect_uri=${encodeURIComponent(urlWithParam)}`;
243069
+ return `https://${site_map_js_1.SITE_REGION_MAP.domestic.authHost}/login?_redirect_uri=${encodeURIComponent(urlWithParam)}`;
242841
243070
  }
242842
243071
  : (url) => {
242843
- if ((0, tencent_cloud_js_1.isInternationalRegion)(options?.region)) {
242844
- url = url.replace("cloud.tencent.com", "tencentcloud.com");
243072
+ let finalUrl = url;
243073
+ if (resolvedSite === "intl") {
243074
+ try {
243075
+ const parsed = new URL(url);
243076
+ parsed.host = site_map_js_1.SITE_REGION_MAP.intl.authHost;
243077
+ finalUrl = parsed.toString();
243078
+ }
243079
+ catch {
243080
+ finalUrl = url.replace("cloud.tencent.com", "tencentcloud.com");
243081
+ }
242845
243082
  }
242846
- const separator = url.includes("?") ? "&" : "?";
242847
- return `${url}${separator}allowNoEnv=true`;
243083
+ const separator = finalUrl.includes("?") ? "&" : "?";
243084
+ return `${finalUrl}${separator}allowNoEnv=true`;
242848
243085
  };
242849
243086
  }
242850
243087
  else {
@@ -242865,8 +243102,23 @@ async function ensureLogin(options) {
242865
243102
  }
242866
243103
  }
242867
243104
  (0, logger_js_1.debug)("beforeloginByWebAuth", { loginOptions });
243105
+ // 登录前迁移旧单槽数据为分槽格式,避免 toolbox 内部命中旧凭证而跳过新站点登录
243106
+ const slotsBefore = await ensureSlottedCredential();
242868
243107
  try {
242869
- await auth.loginByWebAuth(loginOptions);
243108
+ const loginResult = await auth.loginByWebAuth(loginOptions);
243109
+ // toolbox 将新凭证写入 flat 'credential',将其并入对应 site 槽位,保留其他槽位
243110
+ const newRaw = await readStoredCredentialRaw();
243111
+ let credentialToSlot = loginResult;
243112
+ if (isSlottedCredential(newRaw)) {
243113
+ credentialToSlot = newRaw[resolvedSite] ?? newRaw.domestic;
243114
+ }
243115
+ else if (newRaw) {
243116
+ credentialToSlot = newRaw;
243117
+ }
243118
+ if (isUsableCredential(credentialToSlot)) {
243119
+ const merged = { ...slotsBefore, [resolvedSite]: credentialToSlot };
243120
+ await toolbox_1.authStore.set("credential", merged);
243121
+ }
242870
243122
  resolveAuthProgressState();
242871
243123
  }
242872
243124
  catch (error) {
@@ -242875,6 +243127,8 @@ async function ensureLogin(options) {
242875
243127
  }
242876
243128
  const loginState = await peekLoginState({
242877
243129
  ignoreEnvVars: options?.ignoreEnvVars,
243130
+ site: options?.site,
243131
+ region: options?.region,
242878
243132
  });
242879
243133
  (0, logger_js_1.debug)("loginByWebAuth", { mode, hasLoginState: !!loginState });
242880
243134
  return loginState;
@@ -242887,11 +243141,19 @@ async function ensureLogin(options) {
242887
243141
  async function getLoginState(options) {
242888
243142
  return ensureLogin(options);
242889
243143
  }
242890
- async function logout() {
242891
- const cwd = process.env.WORKSPACE_FOLDER_PATHS || process.cwd();
242892
- const result = await auth.logout({ cwd });
243144
+ async function logout(options) {
243145
+ const site = (0, site_map_js_1.normalizeSite)(options?.site) ?? "domestic";
243146
+ const raw = await readStoredCredentialRaw();
243147
+ if (raw && isSlottedCredential(raw)) {
243148
+ const slotted = { ...raw };
243149
+ delete slotted[site];
243150
+ await toolbox_1.authStore.set("credential", slotted);
243151
+ }
243152
+ else if (site === LEGACY_SITE) {
243153
+ const cwd = process.env.WORKSPACE_FOLDER_PATHS || process.cwd();
243154
+ await auth.logout({ cwd });
243155
+ }
242893
243156
  resetAuthProgressState();
242894
- return result;
242895
243157
  }
242896
243158
 
242897
243159
 
@@ -275020,7 +275282,6 @@ function shouldRegisterTool(toolName) {
275020
275282
  'createFunction', // also involves local files
275021
275283
  // Download tools - local file downloads
275022
275284
  'downloadTemplate',
275023
- 'downloadRemoteFile',
275024
275285
  // Setup tools - local config file operations
275025
275286
  'setupEnvironmentId',
275026
275287
  // CloudRun tools - local file operations