@cloudbase/cloudbase-mcp 2.3.0 → 2.4.0-alpha.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
@@ -101,6 +101,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
101
101
  Object.defineProperty(exports, "__esModule", ({ value: true }));
102
102
  exports.CloudRunService = void 0;
103
103
  exports.codeToZip = codeToZip;
104
+ exports.parseObjectToDiffConfigItem = parseObjectToDiffConfigItem;
104
105
  const archiver_1 = __importDefault(__webpack_require__(99133));
105
106
  const fs_extra_1 = __webpack_require__(21605);
106
107
  const path_1 = __importDefault(__webpack_require__(39902));
@@ -269,7 +270,7 @@ class CloudRunService {
269
270
  /**
270
271
  * 上传部署包
271
272
  */
272
- const zipFile = await codeToZip(targetPath, { installDependency: true });
273
+ const zipFile = await codeToZip(targetPath, { installDependency: (serverConfig === null || serverConfig === void 0 ? void 0 : serverConfig.InstallDependency) !== undefined ? serverConfig.InstallDependency : true });
273
274
  await (0, utils_1.upload)({
274
275
  url: uploadUrl,
275
276
  file: zipFile,
@@ -285,8 +286,14 @@ class CloudRunService {
285
286
  if (await this._checkFunctionExist(serverName)) {
286
287
  // 更新
287
288
  const serverDetail = await this.detail({ serverName });
288
- const _serverConfig = Object.assign(Object.assign(Object.assign({}, ((serverDetail === null || serverDetail === void 0 ? void 0 : serverDetail.ServerConfig) || {})), serverConfig), ((serverDetail === null || serverDetail === void 0 ? void 0 : serverDetail.ServerConfig.Tag) === 'function:' ? { Port: 3000 } : {}) // 函数型不能指定端口,需要固定为3000
289
+ const _serverConfig = Object.assign(Object.assign(Object.assign({}, serverConfig), { OpenAccessTypes: ['OA', 'PUBLIC', 'MINIAPP'] }), ((serverDetail === null || serverDetail === void 0 ? void 0 : serverDetail.ServerConfig.Tag) === 'function:' ? { Port: 3000 } : {}) // 函数型不能指定端口,需要固定为3000
289
290
  );
291
+ if ((serverDetail === null || serverDetail === void 0 ? void 0 : serverDetail.ServerConfig.Tag) === 'function:') {
292
+ deployInfo.BuildPacks = {
293
+ LanguageVersion: '20.18',
294
+ RepoLanguage: 'Node.js'
295
+ };
296
+ }
290
297
  deployInfo.ReleaseType = 'FULL';
291
298
  return this._upsertFunction(false, {
292
299
  name: serverName,
@@ -314,7 +321,13 @@ class CloudRunService {
314
321
  RepoLanguage: 'Node.js'
315
322
  };
316
323
  }
317
- const _serverConfig = Object.assign(Object.assign(Object.assign({ OpenAccessTypes: ['OA', 'PUBLIC'], Cpu: 0, Mem: 0, MinNum: 0, MaxNum: 0, PolicyDetails: [], EnvParams: JSON.stringify({}), InitialDelaySeconds: 0, CustomLogs: '', HasDockerfile: true, CreateTime: '', EnvId: envConfig.EnvId, ServerName: serverName, Port: type === 'container' ? 80 : 3000, Dockerfile: 'Dockerfile', BuildDir: '' }, serverConfig), (type === 'function' ? { Port: 3000 } : {})), { Tag: type === 'container' ? '' : 'function:' });
324
+ const _serverConfig = Object.assign(Object.assign(Object.assign({ OpenAccessTypes: ['OA', 'PUBLIC', 'MINIAPP'],
325
+ // Cpu: 0,
326
+ // Mem: 0,
327
+ MinNum: 0,
328
+ // MaxNum: 0,
329
+ // PolicyDetails: [],
330
+ EnvParams: JSON.stringify({}), InitialDelaySeconds: 0, CustomLogs: '', HasDockerfile: true, CreateTime: '', EnvId: envConfig.EnvId, ServerName: serverName, Port: type === 'container' ? 80 : 3000, Dockerfile: 'Dockerfile', BuildDir: '' }, serverConfig), (type === 'function' ? { Port: 3000 } : {})), { Tag: type === 'container' ? '' : 'function:' });
318
331
  return this._upsertFunction(true, {
319
332
  name: serverName,
320
333
  deployInfo,
@@ -348,11 +361,12 @@ class CloudRunService {
348
361
  _upsertFunction(isNew, data) {
349
362
  const { name, deployInfo, serverConfig } = data;
350
363
  const envConfig = this.environment.lazyEnvironmentConfig;
364
+ const Items = parseObjectToDiffConfigItem(serverConfig);
351
365
  return this.tcbrService.request(isNew ? 'CreateCloudRunServer' : 'UpdateCloudRunServer', {
352
366
  EnvId: envConfig.EnvId,
353
367
  ServerName: name,
354
368
  DeployInfo: deployInfo,
355
- ServerConfig: serverConfig
369
+ Items,
356
370
  });
357
371
  }
358
372
  }
@@ -425,6 +439,63 @@ async function codeToZip(cwd, options) {
425
439
  await archive.finalize();
426
440
  return bufferPromise;
427
441
  }
442
+ /**
443
+ * 提交参数变化映射
444
+ */
445
+ const SUBMIT_DIFF_MAP = {
446
+ Cpu: 'CpuSpecs',
447
+ Mem: 'MemSpecs',
448
+ OpenAccessTypes: 'AccessTypes',
449
+ EnvParams: 'EnvParam',
450
+ CustomLogs: 'LogPath'
451
+ };
452
+ /**
453
+ * 将 object 参数转为 [{key:"Port", IntValue:80}] 的格式,并且剔除空字符串
454
+ */
455
+ function parseObjectToDiffConfigItem(data) {
456
+ const kvs = Object.entries(data);
457
+ const Items = [];
458
+ kvs.forEach(([k, v]) => {
459
+ const Key = SUBMIT_DIFF_MAP[k] || k;
460
+ if ([
461
+ 'CustomLogs',
462
+ 'EnvParams',
463
+ 'CreateTime',
464
+ 'Dockerfile',
465
+ 'BuildDir',
466
+ 'LogType',
467
+ 'LogSetId',
468
+ 'LogTopicId',
469
+ 'LogParseType',
470
+ 'Tag',
471
+ 'InternalAccess',
472
+ 'InternalDomain',
473
+ 'OperationMode',
474
+ 'SessionAffinity'
475
+ ].includes(k)) {
476
+ !!v && Items.push({ Key, Value: v });
477
+ }
478
+ else if (['MinNum', 'MaxNum', 'InitialDelaySeconds', 'Port'].includes(k)) {
479
+ Items.push({ Key, IntValue: v });
480
+ }
481
+ else if (['HasDockerfile'].includes(k)) {
482
+ Items.push({ Key, BoolValue: v });
483
+ }
484
+ else if (['Cpu', 'Mem'].includes(k)) {
485
+ Items.push({ Key, FloatValue: v });
486
+ }
487
+ else if (['OpenAccessTypes', 'EntryPoint', 'Cmd'].includes(k)) {
488
+ Items.push({ Key, ArrayValue: v });
489
+ }
490
+ else if (['PolicyDetails'].includes(k)) {
491
+ Items.push({ Key, PolicyDetails: v });
492
+ }
493
+ else if (['TimerScale'].includes(k)) {
494
+ Items.push({ Key, TimerScale: v });
495
+ }
496
+ });
497
+ return Items;
498
+ }
428
499
 
429
500
 
430
501
  /***/ }),
@@ -1678,6 +1749,7 @@ function registerEnvTools(server) {
1678
1749
  Channels: ['dcloud', 'iotenable', 'tem', 'scene_module'] // Filter special channels
1679
1750
  }
1680
1751
  });
1752
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
1681
1753
  // Transform response format to match original listEnvs() format
1682
1754
  if (result && result.EnvList) {
1683
1755
  result = { EnvList: result.EnvList };
@@ -1689,6 +1761,7 @@ function registerEnvTools(server) {
1689
1761
  // Fallback to original method if format is unexpected
1690
1762
  (0, logger_js_1.debug)('Unexpected response format, falling back to listEnvs()');
1691
1763
  result = await cloudbaseList.env.listEnvs();
1764
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
1692
1765
  }
1693
1766
  }
1694
1767
  catch (error) {
@@ -1697,10 +1770,12 @@ function registerEnvTools(server) {
1697
1770
  try {
1698
1771
  const cloudbaseList = await (0, cloudbase_manager_js_1.getCloudBaseManager)({ cloudBaseOptions, requireEnvId: true });
1699
1772
  result = await cloudbaseList.env.listEnvs();
1773
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
1700
1774
  }
1701
1775
  catch (fallbackError) {
1702
1776
  (0, logger_js_1.debug)('降级到 listEnvs() 也失败:', fallbackError);
1703
- return { content: [{ type: "text", text: "获取环境列表时出错: " + (fallbackError instanceof Error ? fallbackError.message : String(fallbackError)) }]
1777
+ return {
1778
+ content: [{ type: "text", text: "获取环境列表时出错: " + (fallbackError instanceof Error ? fallbackError.message : String(fallbackError)) }]
1704
1779
  };
1705
1780
  }
1706
1781
  }
@@ -1708,14 +1783,17 @@ function registerEnvTools(server) {
1708
1783
  case "info":
1709
1784
  const cloudbaseInfo = await getManager();
1710
1785
  result = await cloudbaseInfo.env.getEnvInfo();
1786
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
1711
1787
  break;
1712
1788
  case "domains":
1713
1789
  const cloudbaseDomains = await getManager();
1714
1790
  result = await cloudbaseDomains.env.getEnvAuthDomains();
1791
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
1715
1792
  break;
1716
1793
  case "hosting":
1717
1794
  const cloudbaseHosting = await getManager();
1718
1795
  result = await cloudbaseHosting.hosting.getWebsiteConfig();
1796
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
1719
1797
  break;
1720
1798
  default:
1721
1799
  throw new Error(`不支持的查询类型: ${action}`);
@@ -1773,9 +1851,11 @@ function registerEnvTools(server) {
1773
1851
  switch (action) {
1774
1852
  case "create":
1775
1853
  result = await cloudbase.env.createEnvDomain(domains);
1854
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
1776
1855
  break;
1777
1856
  case "delete":
1778
1857
  result = await cloudbase.env.deleteEnvDomain(domains);
1858
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
1779
1859
  break;
1780
1860
  default:
1781
1861
  throw new Error(`不支持的操作类型: ${action}`);
@@ -23413,6 +23493,8 @@ exports.getEnvId = getEnvId;
23413
23493
  exports.resetCloudBaseManagerCache = resetCloudBaseManagerCache;
23414
23494
  exports.getCloudBaseManager = getCloudBaseManager;
23415
23495
  exports.createCloudBaseManagerWithOptions = createCloudBaseManagerWithOptions;
23496
+ exports.extractRequestId = extractRequestId;
23497
+ exports.logCloudBaseResult = logCloudBaseResult;
23416
23498
  const manager_node_1 = __importDefault(__webpack_require__(95492));
23417
23499
  const auth_js_1 = __webpack_require__(77291);
23418
23500
  const interactive_js_1 = __webpack_require__(3461);
@@ -23575,6 +23657,39 @@ function createCloudBaseManagerWithOptions(cloudBaseOptions) {
23575
23657
  });
23576
23658
  return manager;
23577
23659
  }
23660
+ /**
23661
+ * Extract RequestId from result object
23662
+ */
23663
+ function extractRequestId(result) {
23664
+ if (!result || typeof result !== 'object') {
23665
+ return undefined;
23666
+ }
23667
+ // Try common RequestId field names
23668
+ if ('RequestId' in result && result.RequestId) {
23669
+ return String(result.RequestId);
23670
+ }
23671
+ if ('requestId' in result && result.requestId) {
23672
+ return String(result.requestId);
23673
+ }
23674
+ if ('request_id' in result && result.request_id) {
23675
+ return String(result.request_id);
23676
+ }
23677
+ return undefined;
23678
+ }
23679
+ /**
23680
+ * Log CloudBase manager call result with RequestId
23681
+ */
23682
+ function logCloudBaseResult(logger, result) {
23683
+ if (!logger) {
23684
+ return;
23685
+ }
23686
+ const requestId = extractRequestId(result);
23687
+ logger({
23688
+ type: 'capiResult',
23689
+ requestId,
23690
+ result,
23691
+ });
23692
+ }
23578
23693
 
23579
23694
 
23580
23695
  /***/ }),
@@ -23695,6 +23810,7 @@ async function _promptAndSetEnvironmentId(autoSelectSingle, server) {
23695
23810
  Channels: ['dcloud', 'iotenable', 'tem', 'scene_module'] // Filter special channels
23696
23811
  }
23697
23812
  });
23813
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server?.logger, envResult);
23698
23814
  // Transform response format to match original listEnvs() format
23699
23815
  if (envResult && envResult.EnvList) {
23700
23816
  envResult = { EnvList: envResult.EnvList };
@@ -23706,6 +23822,7 @@ async function _promptAndSetEnvironmentId(autoSelectSingle, server) {
23706
23822
  // Fallback to original method if format is unexpected
23707
23823
  (0, logger_js_1.debug)('Unexpected response format, falling back to listEnvs()');
23708
23824
  envResult = await cloudbase.env.listEnvs();
23825
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server?.logger, envResult);
23709
23826
  }
23710
23827
  }
23711
23828
  catch (error) {
@@ -23713,6 +23830,7 @@ async function _promptAndSetEnvironmentId(autoSelectSingle, server) {
23713
23830
  // Fallback to original method on error
23714
23831
  try {
23715
23832
  envResult = await cloudbase.env.listEnvs();
23833
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server?.logger, envResult);
23716
23834
  }
23717
23835
  catch (fallbackError) {
23718
23836
  (0, logger_js_1.debug)('降级到 listEnvs() 也失败:', fallbackError);
@@ -33514,6 +33632,7 @@ function registerSecurityRuleTools(server) {
33514
33632
  EnvId: envId,
33515
33633
  },
33516
33634
  });
33635
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
33517
33636
  }
33518
33637
  else if (resourceType === "function") {
33519
33638
  // 查询云函数安全规则
@@ -33524,6 +33643,7 @@ function registerSecurityRuleTools(server) {
33524
33643
  EnvId: envId,
33525
33644
  },
33526
33645
  });
33646
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
33527
33647
  }
33528
33648
  else if (resourceType === "storage") {
33529
33649
  // 查询存储安全规则
@@ -33534,6 +33654,7 @@ function registerSecurityRuleTools(server) {
33534
33654
  EnvId: envId,
33535
33655
  },
33536
33656
  });
33657
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
33537
33658
  }
33538
33659
  else if (resourceType === "sqlDatabase") {
33539
33660
  // TODO: 考虑是否有支持指定其他 instance、schema 的需求
@@ -33549,6 +33670,7 @@ function registerSecurityRuleTools(server) {
33549
33670
  RoleIdentityList: ["allUser"],
33550
33671
  },
33551
33672
  });
33673
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
33552
33674
  }
33553
33675
  else {
33554
33676
  throw new Error(`不支持的资源类型: ${resourceType}`);
@@ -33625,6 +33747,7 @@ function registerSecurityRuleTools(server) {
33625
33747
  Rule: rule,
33626
33748
  },
33627
33749
  });
33750
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
33628
33751
  }
33629
33752
  else {
33630
33753
  result = await cloudbase.commonService().call({
@@ -33635,6 +33758,7 @@ function registerSecurityRuleTools(server) {
33635
33758
  AclTag: aclTag,
33636
33759
  },
33637
33760
  });
33761
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
33638
33762
  }
33639
33763
  }
33640
33764
  else if (resourceType === "function") {
@@ -33651,6 +33775,7 @@ function registerSecurityRuleTools(server) {
33651
33775
  Rule: rule,
33652
33776
  },
33653
33777
  });
33778
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
33654
33779
  }
33655
33780
  else if (resourceType === "storage") {
33656
33781
  if (aclTag === "CUSTOM") {
@@ -33665,6 +33790,7 @@ function registerSecurityRuleTools(server) {
33665
33790
  Rule: rule,
33666
33791
  },
33667
33792
  });
33793
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
33668
33794
  }
33669
33795
  else {
33670
33796
  result = await cloudbase.commonService().call({
@@ -33675,6 +33801,7 @@ function registerSecurityRuleTools(server) {
33675
33801
  AclTag: aclTag,
33676
33802
  },
33677
33803
  });
33804
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
33678
33805
  }
33679
33806
  }
33680
33807
  else if (resourceType === "sqlDatabase") {
@@ -33707,6 +33834,7 @@ function registerSecurityRuleTools(server) {
33707
33834
  PolicyList: policyList,
33708
33835
  },
33709
33836
  });
33837
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
33710
33838
  function getRowPermission(policy) {
33711
33839
  return {
33712
33840
  READONLY: [
@@ -38353,6 +38481,7 @@ function registerSQLDatabaseTools(server) {
38353
38481
  },
38354
38482
  },
38355
38483
  });
38484
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
38356
38485
  return {
38357
38486
  content: [
38358
38487
  {
@@ -38416,6 +38545,7 @@ function registerSQLDatabaseTools(server) {
38416
38545
  },
38417
38546
  },
38418
38547
  });
38548
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
38419
38549
  return {
38420
38550
  content: [
38421
38551
  {
@@ -48544,7 +48674,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true }));
48544
48674
  exports.cloudBaseRequest = cloudBaseRequest;
48545
48675
  const auth_1 = __webpack_require__(23506);
48546
48676
  const http_request_1 = __webpack_require__(72088);
48547
- const SUPPORT_REGIONS = ['ap-shanghai', 'ap-guangzhou'];
48677
+ const SUPPORT_REGIONS = ['ap-shanghai', 'ap-guangzhou', 'ap-singapore'];
48548
48678
  async function cloudBaseRequest(options) {
48549
48679
  // const url = 'https://tcb-admin.tencentcloudapi.com/admin'
48550
48680
  const { config, params = {}, method = 'POST', headers = {} } = options;
@@ -48558,11 +48688,11 @@ async function cloudBaseRequest(options) {
48558
48688
  let internalRegionEndpoint = '';
48559
48689
  if (finalRegion) {
48560
48690
  if (SUPPORT_REGIONS.includes(finalRegion)) {
48561
- internetRegionEndpoint = `${finalRegion}.tcb-api.tencentcloudapi.com`;
48562
- internalRegionEndpoint = `internal.${finalRegion}.tcb-api.tencentcloudapi.com`;
48691
+ internetRegionEndpoint = `${envId}.${finalRegion}.tcb-api.tencentcloudapi.com`;
48692
+ internalRegionEndpoint = `${envId}.internal.${finalRegion}.tcb-api.tencentcloudapi.com`;
48563
48693
  }
48564
48694
  else {
48565
- console.warn('当前仅支持上海,广州地域,其他地域默认解析到固定域名(上海地域)');
48695
+ console.warn('当前仅支持上海,广州,新加坡地域,其他地域默认解析到固定域名(上海地域)');
48566
48696
  internetRegionEndpoint = `tcb-api.tencentcloudapi.com`;
48567
48697
  internalRegionEndpoint = `internal.tcb-api.tencentcloudapi.com`;
48568
48698
  }
@@ -53484,6 +53614,7 @@ const fs_1 = __importDefault(__webpack_require__(29021));
53484
53614
  const os_1 = __importDefault(__webpack_require__(21820));
53485
53615
  const path_1 = __importDefault(__webpack_require__(39902));
53486
53616
  const winston_1 = __importDefault(__webpack_require__(555));
53617
+ const cloud_mode_js_1 = __webpack_require__(89684);
53487
53618
  // Use require for winston-daily-rotate-file to avoid webpack bundling issues
53488
53619
  // Handle both CommonJS and ES module exports
53489
53620
  const DailyRotateFileModule = __webpack_require__(55622);
@@ -53535,16 +53666,18 @@ if (shouldUseConsole()) {
53535
53666
  stderrLevels: ['error', 'warn', 'info', 'debug'], // All logs go to stderr
53536
53667
  }));
53537
53668
  }
53538
- // File transport with daily rotation
53539
- transports.push(new DailyRotateFile({
53540
- dirname: logDir,
53541
- filename: 'cloudbase-mcp-%DATE%.log',
53542
- datePattern: 'YYYY-MM-DD',
53543
- format: winston_1.default.format.combine(winston_1.default.format.timestamp({ format: 'YYYY-MM-DDTHH:mm:ss.SSSZ' }), logFormat),
53544
- maxFiles: '30d', // Keep logs for 30 days
53545
- maxSize: '20m', // Max file size before rotation
53546
- zippedArchive: false, // Don't compress old logs
53547
- }));
53669
+ if (!(0, cloud_mode_js_1.isCloudMode)()) {
53670
+ // File transport with daily rotation
53671
+ transports.push(new DailyRotateFile({
53672
+ dirname: logDir,
53673
+ filename: 'cloudbase-mcp-%DATE%.log',
53674
+ datePattern: 'YYYY-MM-DD',
53675
+ format: winston_1.default.format.combine(winston_1.default.format.timestamp({ format: 'YYYY-MM-DDTHH:mm:ss.SSSZ' }), logFormat),
53676
+ maxFiles: '30d', // Keep logs for 30 days
53677
+ maxSize: '20m', // Max file size before rotation
53678
+ zippedArchive: false, // Don't compress old logs
53679
+ }));
53680
+ }
53548
53681
  // Create winston logger instance
53549
53682
  const logger = winston_1.default.createLogger({
53550
53683
  level: getLogLevel(),
@@ -87083,6 +87216,7 @@ function registerFunctionTools(server) {
87083
87216
  const cloudbase = await getManager();
87084
87217
  if (action === "list") {
87085
87218
  const result = await cloudbase.functions.getFunctionList(limit, offset);
87219
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
87086
87220
  return {
87087
87221
  content: [
87088
87222
  {
@@ -87097,6 +87231,7 @@ function registerFunctionTools(server) {
87097
87231
  throw new Error("获取函数详情时,name 参数是必需的");
87098
87232
  }
87099
87233
  const result = await cloudbase.functions.getFunctionDetail(name, codeSecret);
87234
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
87100
87235
  return {
87101
87236
  content: [
87102
87237
  {
@@ -87178,6 +87313,7 @@ function registerFunctionTools(server) {
87178
87313
  functionRootPath: processedRootPath,
87179
87314
  force
87180
87315
  });
87316
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
87181
87317
  return {
87182
87318
  content: [
87183
87319
  {
@@ -87225,6 +87361,7 @@ function registerFunctionTools(server) {
87225
87361
  // 使用闭包中的 cloudBaseOptions
87226
87362
  const cloudbase = await getManager();
87227
87363
  const result = await cloudbase.functions.updateFunctionCode(updateParams);
87364
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
87228
87365
  return {
87229
87366
  content: [
87230
87367
  {
@@ -87265,6 +87402,7 @@ function registerFunctionTools(server) {
87265
87402
  // 使用闭包中的 cloudBaseOptions
87266
87403
  const cloudbase = await getManager();
87267
87404
  const result = await cloudbase.functions.updateFunctionConfig(funcParam);
87405
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
87268
87406
  return {
87269
87407
  content: [
87270
87408
  {
@@ -87293,6 +87431,7 @@ function registerFunctionTools(server) {
87293
87431
  // 使用闭包中的 cloudBaseOptions
87294
87432
  const cloudbase = await getManager();
87295
87433
  const result = await cloudbase.functions.invokeFunction(name, params);
87434
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
87296
87435
  return {
87297
87436
  content: [
87298
87437
  {
@@ -87333,6 +87472,7 @@ function registerFunctionTools(server) {
87333
87472
  }
87334
87473
  const cloudbase = await getManager();
87335
87474
  const result = await cloudbase.functions.getFunctionLogsV2({ name, offset, limit, startTime, endTime, requestId, qualifier });
87475
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
87336
87476
  return {
87337
87477
  content: [
87338
87478
  {
@@ -87370,6 +87510,7 @@ function registerFunctionTools(server) {
87370
87510
  endTime,
87371
87511
  logRequestId: requestId
87372
87512
  });
87513
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
87373
87514
  return {
87374
87515
  content: [
87375
87516
  {
@@ -87408,6 +87549,7 @@ function registerFunctionTools(server) {
87408
87549
  throw new Error("创建触发器时,triggers 参数是必需的");
87409
87550
  }
87410
87551
  const result = await cloudbase.functions.createFunctionTriggers(name, triggers);
87552
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
87411
87553
  return {
87412
87554
  content: [
87413
87555
  {
@@ -87422,6 +87564,7 @@ function registerFunctionTools(server) {
87422
87564
  throw new Error("删除触发器时,triggerName 参数是必需的");
87423
87565
  }
87424
87566
  const result = await cloudbase.functions.deleteFunctionTrigger(name, triggerName);
87567
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
87425
87568
  return {
87426
87569
  content: [
87427
87570
  {
@@ -90155,19 +90298,20 @@ class EnvService {
90155
90298
  });
90156
90299
  }
90157
90300
  getCos() {
90301
+ const internalEndpoint = this.environment.cloudBaseContext.isInternalEndpoint();
90158
90302
  const { secretId, secretKey, token } = this.environment.getAuthConfig();
90159
90303
  const cosConfig = {
90160
90304
  SecretId: secretId,
90161
90305
  SecretKey: secretKey,
90162
90306
  SecurityToken: token,
90163
- Domain: constant_1.USE_INTERNAL_ENDPOINT ? "{Bucket}.cos-internal.{Region}.tencentcos.cn" /* COS_ENDPOINT.INTERNAL */ : "{Bucket}.cos.{Region}.tencentcos.cn" /* COS_ENDPOINT.PUBLIC */,
90307
+ Domain: internalEndpoint ? "{Bucket}.cos-internal.{Region}.tencentcos.cn" /* COS_ENDPOINT.INTERNAL */ : "{Bucket}.cos.{Region}.tencentcos.cn" /* COS_ENDPOINT.PUBLIC */,
90164
90308
  };
90165
90309
  if (constant_1.COS_SDK_PROTOCOL) {
90166
90310
  cosConfig.Protocol = (constant_1.COS_SDK_PROTOCOL.endsWith(':')
90167
90311
  ? constant_1.COS_SDK_PROTOCOL.toLowerCase()
90168
90312
  : constant_1.COS_SDK_PROTOCOL.toLowerCase() + ':');
90169
90313
  }
90170
- if (constant_1.USE_INTERNAL_ENDPOINT) {
90314
+ if (internalEndpoint) {
90171
90315
  cosConfig.Protocol = 'http:';
90172
90316
  }
90173
90317
  return new cos_nodejs_sdk_v5_1.default(cosConfig);
@@ -100394,7 +100538,7 @@ function parseEnabledPlugins() {
100394
100538
  * await server.connect(transport);
100395
100539
  */
100396
100540
  async function createCloudBaseMcpServer(options) {
100397
- const { name = "cloudbase-mcp", version = "1.0.0", enableTelemetry = true, cloudBaseOptions, cloudMode = false, ide, } = options ?? {};
100541
+ const { name = "cloudbase-mcp", version = "1.0.0", enableTelemetry = true, cloudBaseOptions, cloudMode = false, ide, logger, } = options ?? {};
100398
100542
  // Enable cloud mode if specified
100399
100543
  if (cloudMode) {
100400
100544
  (0, cloud_mode_js_1.enableCloudMode)();
@@ -100424,6 +100568,10 @@ async function createCloudBaseMcpServer(options) {
100424
100568
  if (ide) {
100425
100569
  server.ide = ide;
100426
100570
  }
100571
+ // Store logger in server instance for tools to access
100572
+ if (logger) {
100573
+ server.logger = logger;
100574
+ }
100427
100575
  // Enable telemetry if requested
100428
100576
  if (enableTelemetry) {
100429
100577
  (0, tool_wrapper_js_1.wrapServerWithTelemetry)(server);
@@ -106747,6 +106895,7 @@ function registerDataModelTools(server) {
106747
106895
  Name: name,
106748
106896
  },
106749
106897
  });
106898
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
106750
106899
  // 只保留基础字段,过滤掉冗余信息,并简化Schema
106751
106900
  let simplifiedSchema = null;
106752
106901
  // 解析并简化Schema
@@ -106885,6 +107034,7 @@ function registerDataModelTools(server) {
106885
107034
  Action: "DescribeDataSourceList",
106886
107035
  Param: listParams,
106887
107036
  });
107037
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
106888
107038
  const models = result.Data?.Rows || [];
106889
107039
  // 只保留基础字段,list操作不返回Schema
106890
107040
  const simplifiedModels = models.map((model) => ({
@@ -106921,6 +107071,7 @@ function registerDataModelTools(server) {
106921
107071
  Name: name,
106922
107072
  },
106923
107073
  });
107074
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
106924
107075
  if (!result.Data) {
106925
107076
  throw new Error(`数据模型 ${name} 不存在`);
106926
107077
  }
@@ -107125,6 +107276,7 @@ classDiagram
107125
107276
  EnvId: currentEnvId,
107126
107277
  },
107127
107278
  });
107279
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
107128
107280
  const taskId = result.Data?.TaskId;
107129
107281
  if (!taskId) {
107130
107282
  return {
@@ -107155,6 +107307,7 @@ classDiagram
107155
107307
  TaskId: taskId,
107156
107308
  },
107157
107309
  });
107310
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, statusResult);
107158
107311
  status = statusResult.Data?.Status || "init";
107159
107312
  }
107160
107313
  // 返回最终结果
@@ -114885,8 +115038,10 @@ function registerHostingTools(server) {
114885
115038
  files,
114886
115039
  ignore
114887
115040
  });
115041
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
114888
115042
  // 获取环境信息
114889
115043
  const envInfo = await cloudbase.env.getEnvInfo();
115044
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, envInfo);
114890
115045
  const staticDomain = envInfo.EnvInfo?.StaticStorages?.[0]?.StaticDomain;
114891
115046
  const accessUrl = staticDomain ? `https://${staticDomain}/${cloudPath || ''}` : "";
114892
115047
  // Send deployment notification to CodeBuddy IDE
@@ -114960,6 +115115,7 @@ function registerHostingTools(server) {
114960
115115
  cloudPath,
114961
115116
  isDir
114962
115117
  });
115118
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
114963
115119
  return {
114964
115120
  content: [
114965
115121
  {
@@ -114990,6 +115146,7 @@ function registerHostingTools(server) {
114990
115146
  marker,
114991
115147
  maxKeys
114992
115148
  });
115149
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
114993
115150
  return {
114994
115151
  content: [
114995
115152
  {
@@ -115055,6 +115212,7 @@ function registerHostingTools(server) {
115055
115212
  domain,
115056
115213
  certId
115057
115214
  });
115215
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
115058
115216
  break;
115059
115217
  case "delete":
115060
115218
  if (!domain) {
@@ -115063,6 +115221,7 @@ function registerHostingTools(server) {
115063
115221
  result = await cloudbase.hosting.deleteHostingDomain({
115064
115222
  domain
115065
115223
  });
115224
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
115066
115225
  break;
115067
115226
  case "check":
115068
115227
  if (!domains || domains.length === 0) {
@@ -115071,6 +115230,7 @@ function registerHostingTools(server) {
115071
115230
  result = await cloudbase.hosting.tcbCheckResource({
115072
115231
  domains
115073
115232
  });
115233
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
115074
115234
  break;
115075
115235
  case "modify":
115076
115236
  if (!domain || domainId === undefined || !domainConfig) {
@@ -115081,6 +115241,7 @@ function registerHostingTools(server) {
115081
115241
  domainId,
115082
115242
  domainConfig
115083
115243
  });
115244
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
115084
115245
  break;
115085
115246
  default:
115086
115247
  throw new Error(`不支持的操作类型: ${action}`);
@@ -130215,6 +130376,7 @@ function registerInviteCodeTools(server) {
130215
130376
  Action: 'ActivateInviteCode',
130216
130377
  Param: { InviteCode, EnvId }
130217
130378
  });
130379
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
130218
130380
  return {
130219
130381
  content: [
130220
130382
  {
@@ -134861,7 +135023,7 @@ class TelemetryReporter {
134861
135023
  const nodeVersion = process.version; // Node.js版本
134862
135024
  const arch = os_1.default.arch(); // 系统架构
134863
135025
  // 从构建时注入的版本号获取MCP版本信息
134864
- const mcpVersion = process.env.npm_package_version || "2.3.0" || 0;
135026
+ const mcpVersion = process.env.npm_package_version || "2.4.0-alpha.0" || 0;
134865
135027
  return {
134866
135028
  userAgent: `${osType} ${osRelease} ${arch} ${nodeVersion} CloudBase-MCP/${mcpVersion}`,
134867
135029
  deviceId: this.deviceId,
@@ -179459,6 +179621,7 @@ exports.sleep = sleep;
179459
179621
  exports.upperCaseStringFisrt = upperCaseStringFisrt;
179460
179622
  exports.upperCaseObjKey = upperCaseObjKey;
179461
179623
  exports.fetchTemplates = fetchTemplates;
179624
+ exports.successLog = successLog;
179462
179625
  const archiver_1 = __importDefault(__webpack_require__(99133));
179463
179626
  const crypto_1 = __importDefault(__webpack_require__(55511));
179464
179627
  const fs_extra_1 = __importDefault(__webpack_require__(21605));
@@ -179737,6 +179900,10 @@ const getCompleteTimeRange = (timeRange) => {
179737
179900
  };
179738
179901
  };
179739
179902
  exports.getCompleteTimeRange = getCompleteTimeRange;
179903
+ function successLog(msg) {
179904
+ // 空格,兼容中文字符编码长度问题
179905
+ console.log(`${msg}`);
179906
+ }
179740
179907
 
179741
179908
 
179742
179909
  /***/ }),
@@ -185334,7 +185501,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
185334
185501
  return (mod && mod.__esModule) ? mod : { "default": mod };
185335
185502
  };
185336
185503
  Object.defineProperty(exports, "__esModule", ({ value: true }));
185337
- exports.downloadWebTemplate = downloadWebTemplate;
185338
185504
  exports.getClaudePrompt = getClaudePrompt;
185339
185505
  exports.registerRagTools = registerRagTools;
185340
185506
  const adm_zip_1 = __importDefault(__webpack_require__(30283));
@@ -185352,6 +185518,58 @@ const KnowledgeBaseIdMap = {
185352
185518
  scf: "scfsczskzyws_4bdc",
185353
185519
  miniprogram: "xcxzskws_25d8",
185354
185520
  };
185521
+ // ============ 缓存配置 ============
185522
+ const CACHE_BASE_DIR = path.join(os.homedir(), ".cloudbase-mcp");
185523
+ const CACHE_META_FILE = path.join(CACHE_BASE_DIR, "cache-meta.json");
185524
+ const DEFAULT_CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 默认 24 小时
185525
+ // 支持环境变量 CLOUDBASE_MCP_CACHE_TTL_MS 控制缓存过期时间(毫秒)
185526
+ const parsedCacheTTL = process.env.CLOUDBASE_MCP_CACHE_TTL_MS
185527
+ ? parseInt(process.env.CLOUDBASE_MCP_CACHE_TTL_MS, 10)
185528
+ : NaN;
185529
+ const CACHE_TTL_MS = Number.isNaN(parsedCacheTTL) || parsedCacheTTL < 0
185530
+ ? DEFAULT_CACHE_TTL_MS
185531
+ : parsedCacheTTL;
185532
+ if (!Number.isNaN(parsedCacheTTL) && parsedCacheTTL >= 0) {
185533
+ (0, logger_js_1.debug)("[cache] Using TTL from CLOUDBASE_MCP_CACHE_TTL_MS", {
185534
+ ttlMs: CACHE_TTL_MS,
185535
+ });
185536
+ }
185537
+ else {
185538
+ (0, logger_js_1.debug)("[cache] Using default TTL", { ttlMs: CACHE_TTL_MS });
185539
+ }
185540
+ // 共享的下载 Promise,防止并发重复下载
185541
+ let resourceDownloadPromise = null;
185542
+ // 检查缓存是否可用(未过期)
185543
+ async function canUseCache() {
185544
+ try {
185545
+ const content = await fs.readFile(CACHE_META_FILE, "utf8");
185546
+ const meta = JSON.parse(content);
185547
+ if (!meta.timestamp) {
185548
+ (0, logger_js_1.debug)("[cache] cache-meta missing timestamp, treating as invalid", {
185549
+ ttlMs: CACHE_TTL_MS,
185550
+ });
185551
+ return false;
185552
+ }
185553
+ const ageMs = Date.now() - meta.timestamp;
185554
+ const isValid = ageMs <= CACHE_TTL_MS;
185555
+ (0, logger_js_1.debug)("[cache] evaluated cache meta", {
185556
+ timestamp: meta.timestamp,
185557
+ ageMs,
185558
+ ttlMs: CACHE_TTL_MS,
185559
+ valid: isValid,
185560
+ });
185561
+ return isValid;
185562
+ }
185563
+ catch (error) {
185564
+ (0, logger_js_1.debug)("[cache] failed to read cache meta, treating as miss", { error });
185565
+ return false;
185566
+ }
185567
+ }
185568
+ // 更新缓存时间戳
185569
+ async function updateCache() {
185570
+ await fs.mkdir(CACHE_BASE_DIR, { recursive: true });
185571
+ await fs.writeFile(CACHE_META_FILE, JSON.stringify({ timestamp: Date.now() }, null, 2), "utf8");
185572
+ }
185355
185573
  // 安全 JSON.parse
185356
185574
  function safeParse(str) {
185357
185575
  try {
@@ -185378,31 +185596,141 @@ function safeStringify(obj) {
185378
185596
  return "";
185379
185597
  }
185380
185598
  }
185381
- // Download and extract web template, return extract directory path
185382
- // Always downloads and overwrites existing template
185599
+ // OpenAPI 文档 URL 列表
185600
+ const OPENAPI_SOURCES = [
185601
+ {
185602
+ name: "mysqldb",
185603
+ description: "MySQL RESTful API - 云开发 MySQL 数据库 HTTP API",
185604
+ url: "https://docs.cloudbase.net/openapi/mysqldb.v1.openapi.yaml",
185605
+ },
185606
+ {
185607
+ name: "functions",
185608
+ description: "Cloud Functions API - 云函数 HTTP API",
185609
+ url: "https://docs.cloudbase.net/openapi/functions.v1.openapi.yaml",
185610
+ },
185611
+ {
185612
+ name: "auth",
185613
+ description: "Authentication API - 身份认证 HTTP API",
185614
+ url: "https://docs.cloudbase.net/openapi/auth.v1.openapi.yaml",
185615
+ },
185616
+ {
185617
+ name: "cloudrun",
185618
+ description: "CloudRun API - 云托管服务 HTTP API",
185619
+ url: "https://docs.cloudbase.net/openapi/cloudrun.v1.openapi.yaml",
185620
+ },
185621
+ {
185622
+ name: "storage",
185623
+ description: "Storage API - 云存储 HTTP API",
185624
+ url: "https://docs.cloudbase.net/openapi/storage.v1.openapi.yaml",
185625
+ },
185626
+ ];
185383
185627
  async function downloadWebTemplate() {
185384
- const baseDir = path.join(os.homedir(), ".cloudbase-mcp");
185385
- const zipPath = path.join(baseDir, "web-cloudbase-project.zip");
185386
- const extractDir = path.join(baseDir, "web-template");
185628
+ const zipPath = path.join(CACHE_BASE_DIR, "web-cloudbase-project.zip");
185629
+ const extractDir = path.join(CACHE_BASE_DIR, "web-template");
185387
185630
  const url = "https://static.cloudbase.net/cloudbase-examples/web-cloudbase-project.zip";
185388
- await fs.mkdir(baseDir, { recursive: true });
185389
- // Download zip to specified path (overwrite)
185390
185631
  const response = await fetch(url);
185391
185632
  if (!response.ok) {
185392
185633
  throw new Error(`下载模板失败,状态码: ${response.status}`);
185393
185634
  }
185394
185635
  const buffer = Buffer.from(await response.arrayBuffer());
185395
185636
  await fs.writeFile(zipPath, buffer);
185396
- // Clean and recreate extract directory
185397
185637
  await fs.rm(extractDir, { recursive: true, force: true });
185398
185638
  await fs.mkdir(extractDir, { recursive: true });
185399
185639
  const zip = new adm_zip_1.default(zipPath);
185400
185640
  zip.extractAllTo(extractDir, true);
185641
+ (0, logger_js_1.debug)("[downloadResources] webTemplate 下载完成");
185401
185642
  return extractDir;
185402
185643
  }
185403
- async function prepareKnowledgeBaseWebTemplate() {
185404
- const extractDir = await downloadWebTemplate();
185405
- return collectSkillDescriptions(path.join(extractDir, ".claude", "skills"));
185644
+ async function downloadOpenAPI() {
185645
+ const baseDir = path.join(CACHE_BASE_DIR, "openapi");
185646
+ await fs.mkdir(baseDir, { recursive: true });
185647
+ const results = [];
185648
+ await Promise.all(OPENAPI_SOURCES.map(async (source) => {
185649
+ try {
185650
+ const response = await fetch(source.url);
185651
+ if (!response.ok) {
185652
+ (0, logger_js_1.warn)(`[downloadOpenAPI] Failed to download ${source.name}`, {
185653
+ status: response.status,
185654
+ });
185655
+ return;
185656
+ }
185657
+ const content = await response.text();
185658
+ const filePath = path.join(baseDir, `${source.name}.openapi.yaml`);
185659
+ await fs.writeFile(filePath, content, "utf8");
185660
+ results.push({
185661
+ name: source.name,
185662
+ description: source.description,
185663
+ absolutePath: filePath,
185664
+ });
185665
+ }
185666
+ catch (error) {
185667
+ (0, logger_js_1.warn)(`[downloadOpenAPI] Failed to download ${source.name}`, {
185668
+ error,
185669
+ });
185670
+ }
185671
+ }));
185672
+ (0, logger_js_1.debug)("[downloadOpenAPI] openAPIDocs 下载完成", {
185673
+ successCount: results.length,
185674
+ total: OPENAPI_SOURCES.length,
185675
+ });
185676
+ return results;
185677
+ }
185678
+ // 实际执行下载所有资源的函数(webTemplate 和 openAPI 并发下载)
185679
+ async function _doDownloadResources() {
185680
+ // 并发下载 webTemplate 和 openAPIDocs
185681
+ const [webTemplateDir, openAPIDocs] = await Promise.all([
185682
+ // 下载 web 模板
185683
+ downloadWebTemplate(),
185684
+ // 并发下载所有 OpenAPI 文档
185685
+ downloadOpenAPI(),
185686
+ ]);
185687
+ (0, logger_js_1.debug)("[downloadResources] 所有资源下载完成");
185688
+ return { webTemplateDir, openAPIDocs };
185689
+ }
185690
+ // 下载所有资源(带缓存和共享 Promise 机制)
185691
+ async function downloadResources() {
185692
+ const webTemplateDir = path.join(CACHE_BASE_DIR, "web-template");
185693
+ const openAPIDir = path.join(CACHE_BASE_DIR, "openapi");
185694
+ // 检查缓存是否有效
185695
+ if (await canUseCache()) {
185696
+ try {
185697
+ // 检查两个目录都存在
185698
+ await Promise.all([fs.access(webTemplateDir), fs.access(openAPIDir)]);
185699
+ const files = await fs.readdir(openAPIDir);
185700
+ if (files.length > 0) {
185701
+ (0, logger_js_1.debug)("[downloadResources] 使用缓存");
185702
+ return {
185703
+ webTemplateDir,
185704
+ openAPIDocs: OPENAPI_SOURCES.map((source) => ({
185705
+ name: source.name,
185706
+ description: source.description,
185707
+ absolutePath: path.join(openAPIDir, `${source.name}.openapi.yaml`),
185708
+ })).filter((item) => files.includes(`${item.name}.openapi.yaml`)),
185709
+ };
185710
+ }
185711
+ }
185712
+ catch {
185713
+ // 缓存无效,需要重新下载
185714
+ }
185715
+ }
185716
+ // 如果已有下载任务在进行中,共享该 Promise
185717
+ if (resourceDownloadPromise) {
185718
+ (0, logger_js_1.debug)("[downloadResources] 共享已有下载任务");
185719
+ return resourceDownloadPromise;
185720
+ }
185721
+ // 创建新的下载任务
185722
+ (0, logger_js_1.debug)("[downloadResources] 开始新下载任务");
185723
+ await fs.mkdir(CACHE_BASE_DIR, { recursive: true });
185724
+ resourceDownloadPromise = _doDownloadResources()
185725
+ .then(async (result) => {
185726
+ await updateCache();
185727
+ (0, logger_js_1.debug)("[downloadResources] 缓存已更新");
185728
+ return result;
185729
+ })
185730
+ .finally(() => {
185731
+ resourceDownloadPromise = null;
185732
+ });
185733
+ return resourceDownloadPromise;
185406
185734
  }
185407
185735
  // Get CLAUDE.md prompt content
185408
185736
  // Priority: 1. From downloaded template, 2. Fallback to embedded constant
@@ -185526,23 +185854,15 @@ async function registerRagTools(server) {
185526
185854
  };
185527
185855
  }
185528
185856
  });
185529
- let skills = [];
185530
185857
  let openapis = [];
185531
- // 知识库检索
185532
- try {
185533
- skills = await prepareKnowledgeBaseWebTemplate();
185534
- }
185535
- catch (error) {
185536
- (0, logger_js_1.warn)("[searchKnowledgeBase] Failed to prepare web template", {
185537
- error,
185538
- });
185539
- }
185540
- // OpenAPI 文档准备
185858
+ let skills = [];
185541
185859
  try {
185542
- openapis = await prepareOpenAPIDocs();
185860
+ const { webTemplateDir, openAPIDocs } = await downloadResources();
185861
+ openapis = openAPIDocs;
185862
+ skills = await collectSkillDescriptions(path.join(webTemplateDir, ".claude", "skills"));
185543
185863
  }
185544
185864
  catch (error) {
185545
- (0, logger_js_1.warn)("[searchKnowledgeBase] Failed to prepare OpenAPI docs", {
185865
+ (0, logger_js_1.warn)("[downloadResources] Failed to download resources", {
185546
185866
  error,
185547
185867
  });
185548
185868
  }
@@ -185709,65 +186029,6 @@ function extractDescriptionFromFrontMatter(content) {
185709
186029
  .match(/^(?:decsription|description)\s*:\s*(.*)$/m);
185710
186030
  return match ? match[1].trim() : null;
185711
186031
  }
185712
- // OpenAPI 文档 URL 列表
185713
- const OPENAPI_SOURCES = [
185714
- {
185715
- name: "mysqldb",
185716
- description: "MySQL RESTful API - 云开发 MySQL 数据库 HTTP API",
185717
- url: "https://docs.cloudbase.net/openapi/mysqldb.v1.openapi.yaml",
185718
- },
185719
- {
185720
- name: "functions",
185721
- description: "Cloud Functions API - 云函数 HTTP API",
185722
- url: "https://docs.cloudbase.net/openapi/functions.v1.openapi.yaml",
185723
- },
185724
- {
185725
- name: "auth",
185726
- description: "Authentication API - 身份认证 HTTP API",
185727
- url: "https://docs.cloudbase.net/openapi/auth.v1.openapi.yaml",
185728
- },
185729
- {
185730
- name: "cloudrun",
185731
- description: "CloudRun API - 云托管服务 HTTP API",
185732
- url: "https://docs.cloudbase.net/openapi/cloudrun.v1.openapi.yaml",
185733
- },
185734
- {
185735
- name: "storage",
185736
- description: "Storage API - 云存储 HTTP API",
185737
- url: "https://docs.cloudbase.net/openapi/storage.v1.openapi.yaml",
185738
- },
185739
- ];
185740
- // 下载并准备 OpenAPI 文档
185741
- async function prepareOpenAPIDocs() {
185742
- const baseDir = path.join(os.homedir(), ".cloudbase-mcp", "openapi");
185743
- await fs.mkdir(baseDir, { recursive: true });
185744
- const results = [];
185745
- await Promise.all(OPENAPI_SOURCES.map(async (source) => {
185746
- try {
185747
- const response = await fetch(source.url);
185748
- if (!response.ok) {
185749
- (0, logger_js_1.warn)(`[prepareOpenAPIDocs] Failed to download ${source.name}`, {
185750
- status: response.status,
185751
- });
185752
- return;
185753
- }
185754
- const content = await response.text();
185755
- const filePath = path.join(baseDir, `${source.name}.openapi.yaml`);
185756
- await fs.writeFile(filePath, content, "utf8");
185757
- results.push({
185758
- name: source.name,
185759
- description: source.description,
185760
- absolutePath: filePath,
185761
- });
185762
- }
185763
- catch (error) {
185764
- (0, logger_js_1.warn)(`[prepareOpenAPIDocs] Failed to download ${source.name}`, {
185765
- error,
185766
- });
185767
- }
185768
- }));
185769
- return results;
185770
- }
185771
186032
  async function collectSkillDescriptions(rootDir) {
185772
186033
  const result = [];
185773
186034
  async function walk(dir) {
@@ -191065,20 +191326,25 @@ function callSuccessCallback(callback, result) {
191065
191326
  /***/ }),
191066
191327
 
191067
191328
  /***/ 65607:
191068
- /***/ ((__unused_webpack_module, exports) => {
191329
+ /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
191069
191330
 
191070
191331
  "use strict";
191071
191332
 
191072
191333
  Object.defineProperty(exports, "__esModule", ({ value: true }));
191073
191334
  exports.CloudBaseContext = void 0;
191335
+ const constant_1 = __webpack_require__(40762);
191074
191336
  class CloudBaseContext {
191075
- constructor({ secretId = '', secretKey = '', token = '', proxy = '', region = '', envType = '' }) {
191337
+ constructor({ secretId = '', secretKey = '', token = '', proxy = '', region = '', envType = '', useInternalEndpoint = undefined }) {
191076
191338
  this.secretId = secretId;
191077
191339
  this.secretKey = secretKey;
191078
191340
  this.token = token;
191079
191341
  this.proxy = proxy;
191080
191342
  this.region = region;
191081
191343
  this.envType = envType;
191344
+ this.useInternalEndpoint = useInternalEndpoint;
191345
+ }
191346
+ isInternalEndpoint() {
191347
+ return this.useInternalEndpoint !== undefined ? this.useInternalEndpoint : constant_1.USE_INTERNAL_ENDPOINT;
191082
191348
  }
191083
191349
  }
191084
191350
  exports.CloudBaseContext = CloudBaseContext;
@@ -200560,11 +200826,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
200560
200826
  };
200561
200827
  Object.defineProperty(exports, "__esModule", ({ value: true }));
200562
200828
  exports.wrapServerWithTelemetry = wrapServerWithTelemetry;
200563
- const telemetry_js_1 = __webpack_require__(45880);
200564
- const logger_js_1 = __webpack_require__(13039);
200829
+ const os_1 = __importDefault(__webpack_require__(21820));
200565
200830
  const cloudbase_manager_js_1 = __webpack_require__(3431);
200566
200831
  const cloud_mode_js_1 = __webpack_require__(89684);
200567
- const os_1 = __importDefault(__webpack_require__(21820));
200832
+ const logger_js_1 = __webpack_require__(13039);
200833
+ const telemetry_js_1 = __webpack_require__(45880);
200568
200834
  /**
200569
200835
  * 生成 GitHub Issue 创建链接
200570
200836
  * @param toolName 工具名称
@@ -200605,7 +200871,7 @@ ${envIdSection}
200605
200871
  ## 环境信息
200606
200872
  - 操作系统: ${os_1.default.type()} ${os_1.default.release()}
200607
200873
  - Node.js版本: ${process.version}
200608
- - MCP 版本:${process.env.npm_package_version || "2.3.0" || 0}
200874
+ - MCP 版本:${process.env.npm_package_version || "2.4.0-alpha.0" || 0}
200609
200875
  - 系统架构: ${os_1.default.arch()}
200610
200876
  - 时间: ${new Date().toISOString()}
200611
200877
  - 请求ID: ${requestId}
@@ -200643,10 +200909,13 @@ function createWrappedHandler(name, handler, server) {
200643
200909
  let requestId;
200644
200910
  try {
200645
200911
  (0, logger_js_1.debug)(`开始执行工具: ${name}`, { args: sanitizeArgs(args) });
200912
+ server.logger?.({ type: 'beforeToolCall', toolName: name, args: sanitizeArgs(args) });
200646
200913
  // 执行原始处理函数
200647
200914
  const result = await handler(args);
200648
200915
  success = true;
200649
- (0, logger_js_1.debug)(`工具执行成功: ${name}`, { duration: Date.now() - startTime });
200916
+ const duration = Date.now() - startTime;
200917
+ (0, logger_js_1.debug)(`工具执行成功: ${name}`, { duration });
200918
+ server.logger?.({ type: 'afterToolCall', toolName: name, args: sanitizeArgs(args), result: result, duration });
200650
200919
  return result;
200651
200920
  }
200652
200921
  catch (error) {
@@ -200657,6 +200926,7 @@ function createWrappedHandler(name, handler, server) {
200657
200926
  error: errorMessage,
200658
200927
  duration: Date.now() - startTime
200659
200928
  });
200929
+ server.logger?.({ type: 'errorToolCall', toolName: name, args: sanitizeArgs(args), message: errorMessage, duration: Date.now() - startTime });
200660
200930
  // 生成 GitHub Issue 创建链接
200661
200931
  const issueLink = await generateGitHubIssueLink(name, errorMessage, args, server.cloudBaseOptions, {
200662
200932
  requestId: (typeof error === 'object' && error && 'requestId' in error) ? error.requestId : '',
@@ -203497,6 +203767,7 @@ class StorageService {
203497
203767
  * 获取 COS 配置
203498
203768
  */
203499
203769
  getCos(parallel = 20) {
203770
+ const internalEndpoint = this.environment.cloudBaseContext.isInternalEndpoint();
203500
203771
  const { secretId, secretKey, token, proxy } = this.environment.getAuthConfig();
203501
203772
  const cosProxy = process.env.TCB_COS_PROXY;
203502
203773
  const cosConfig = {
@@ -203505,14 +203776,14 @@ class StorageService {
203505
203776
  SecretKey: secretKey,
203506
203777
  Proxy: cosProxy || proxy,
203507
203778
  SecurityToken: token,
203508
- Domain: constant_1.USE_INTERNAL_ENDPOINT ? "{Bucket}.cos-internal.{Region}.tencentcos.cn" /* COS_ENDPOINT.INTERNAL */ : "{Bucket}.cos.{Region}.tencentcos.cn" /* COS_ENDPOINT.PUBLIC */,
203779
+ Domain: internalEndpoint ? "{Bucket}.cos-internal.{Region}.tencentcos.cn" /* COS_ENDPOINT.INTERNAL */ : "{Bucket}.cos.{Region}.tencentcos.cn" /* COS_ENDPOINT.PUBLIC */,
203509
203780
  };
203510
203781
  if (constant_1.COS_SDK_PROTOCOL) {
203511
203782
  cosConfig.Protocol = (constant_1.COS_SDK_PROTOCOL.endsWith(':')
203512
203783
  ? constant_1.COS_SDK_PROTOCOL.toLowerCase()
203513
203784
  : constant_1.COS_SDK_PROTOCOL.toLowerCase() + ':');
203514
203785
  }
203515
- if (constant_1.USE_INTERNAL_ENDPOINT) {
203786
+ if (internalEndpoint) {
203516
203787
  cosConfig.Protocol = 'http:';
203517
203788
  }
203518
203789
  // COSSDK 默认开启 KeepAlive,这里提供关闭的方式
@@ -208561,6 +208832,7 @@ async function getDatabaseInstanceId(getManager) {
208561
208832
  function registerDatabaseTools(server) {
208562
208833
  // 获取 cloudBaseOptions,如果没有则为 undefined
208563
208834
  const cloudBaseOptions = server.cloudBaseOptions;
208835
+ const logger = server.logger;
208564
208836
  // 创建闭包函数来获取 CloudBase Manager
208565
208837
  const getManager = () => (0, cloudbase_manager_js_1.getCloudBaseManager)({ cloudBaseOptions });
208566
208838
  // readNoSqlDatabaseStructure
@@ -208608,6 +208880,7 @@ checkIndex: 检查索引是否存在`),
208608
208880
  MgoOffset: offset,
208609
208881
  MgoLimit: limit,
208610
208882
  });
208883
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
208611
208884
  return {
208612
208885
  content: [
208613
208886
  {
@@ -208628,6 +208901,7 @@ checkIndex: 检查索引是否存在`),
208628
208901
  throw new Error("检查集合时必须提供 collectionName");
208629
208902
  }
208630
208903
  const result = await cloudbase.database.checkCollectionExists(collectionName);
208904
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
208631
208905
  return {
208632
208906
  content: [
208633
208907
  {
@@ -208649,6 +208923,7 @@ checkIndex: 检查索引是否存在`),
208649
208923
  throw new Error("查看集合详情时必须提供 collectionName");
208650
208924
  }
208651
208925
  const result = await cloudbase.database.describeCollection(collectionName);
208926
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
208652
208927
  return {
208653
208928
  content: [
208654
208929
  {
@@ -208669,6 +208944,7 @@ checkIndex: 检查索引是否存在`),
208669
208944
  throw new Error("获取索引列表时必须提供 collectionName");
208670
208945
  }
208671
208946
  const result = await cloudbase.database.describeCollection(collectionName);
208947
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
208672
208948
  return {
208673
208949
  content: [
208674
208950
  {
@@ -208689,6 +208965,7 @@ checkIndex: 检查索引是否存在`),
208689
208965
  throw new Error("检查索引时必须提供 collectionName 和 indexName");
208690
208966
  }
208691
208967
  const result = await cloudbase.database.checkIndexExists(collectionName, indexName);
208968
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
208692
208969
  return {
208693
208970
  content: [
208694
208971
  {
@@ -208749,6 +209026,7 @@ updateCollection: 更新集合`),
208749
209026
  const cloudbase = await getManager();
208750
209027
  if (action === "createCollection") {
208751
209028
  const result = await cloudbase.database.createCollection(collectionName);
209029
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
208752
209030
  return {
208753
209031
  content: [
208754
209032
  {
@@ -208768,6 +209046,7 @@ updateCollection: 更新集合`),
208768
209046
  throw new Error("更新集合时必须提供 options");
208769
209047
  }
208770
209048
  const result = await cloudbase.database.updateCollection(collectionName, updateOptions);
209049
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
208771
209050
  return {
208772
209051
  content: [
208773
209052
  {
@@ -208844,6 +209123,7 @@ updateCollection: 更新集合`),
208844
209123
  Tag: instanceId,
208845
209124
  },
208846
209125
  });
209126
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
208847
209127
  return {
208848
209128
  content: [
208849
209129
  {
@@ -208921,6 +209201,7 @@ deleteCollection: 删除数据`),
208921
209201
  collectionName,
208922
209202
  documents,
208923
209203
  getManager,
209204
+ logger,
208924
209205
  });
208925
209206
  return {
208926
209207
  content: [
@@ -208945,6 +209226,7 @@ deleteCollection: 删除数据`),
208945
209226
  isMulti,
208946
209227
  upsert,
208947
209228
  getManager,
209229
+ logger,
208948
209230
  });
208949
209231
  return {
208950
209232
  content: [
@@ -208964,6 +209246,7 @@ deleteCollection: 删除数据`),
208964
209246
  query,
208965
209247
  isMulti,
208966
209248
  getManager,
209249
+ logger,
208967
209250
  });
208968
209251
  return {
208969
209252
  content: [
@@ -208977,7 +209260,7 @@ deleteCollection: 删除数据`),
208977
209260
  throw new Error(`不支持的操作类型: ${action}`);
208978
209261
  });
208979
209262
  }
208980
- async function insertDocuments({ collectionName, documents, getManager, }) {
209263
+ async function insertDocuments({ collectionName, documents, getManager, logger, }) {
208981
209264
  try {
208982
209265
  const cloudbase = await getManager();
208983
209266
  const instanceId = await getDatabaseInstanceId(getManager);
@@ -208991,6 +209274,7 @@ async function insertDocuments({ collectionName, documents, getManager, }) {
208991
209274
  Tag: instanceId,
208992
209275
  },
208993
209276
  });
209277
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(logger, result);
208994
209278
  return JSON.stringify({
208995
209279
  success: true,
208996
209280
  requestId: result.RequestId,
@@ -209006,7 +209290,7 @@ async function insertDocuments({ collectionName, documents, getManager, }) {
209006
209290
  }, null, 2);
209007
209291
  }
209008
209292
  }
209009
- async function updateDocuments({ collectionName, query, update, isMulti, upsert, getManager, }) {
209293
+ async function updateDocuments({ collectionName, query, update, isMulti, upsert, getManager, logger, }) {
209010
209294
  try {
209011
209295
  const cloudbase = await getManager();
209012
209296
  const instanceId = await getDatabaseInstanceId(getManager);
@@ -209022,6 +209306,7 @@ async function updateDocuments({ collectionName, query, update, isMulti, upsert,
209022
209306
  Tag: instanceId,
209023
209307
  },
209024
209308
  });
209309
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(logger, result);
209025
209310
  return JSON.stringify({
209026
209311
  success: true,
209027
209312
  requestId: result.RequestId,
@@ -209039,7 +209324,7 @@ async function updateDocuments({ collectionName, query, update, isMulti, upsert,
209039
209324
  }, null, 2);
209040
209325
  }
209041
209326
  }
209042
- async function deleteDocuments({ collectionName, query, isMulti, getManager, }) {
209327
+ async function deleteDocuments({ collectionName, query, isMulti, getManager, logger, }) {
209043
209328
  try {
209044
209329
  const cloudbase = await getManager();
209045
209330
  const instanceId = await getDatabaseInstanceId(getManager);
@@ -209053,6 +209338,7 @@ async function deleteDocuments({ collectionName, query, isMulti, getManager, })
209053
209338
  Tag: instanceId,
209054
209339
  },
209055
209340
  });
209341
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(logger, result);
209056
209342
  return JSON.stringify({
209057
209343
  success: true,
209058
209344
  requestId: result.RequestId,
@@ -214946,6 +215232,7 @@ const IDE_TYPES = [
214946
215232
  "qoder", // Qoder AI编辑器
214947
215233
  "antigravity", // Google Antigravity AI编辑器
214948
215234
  "vscode", // Visual Studio Code
215235
+ "kiro", // Kiro AI编辑器
214949
215236
  ];
214950
215237
  // IDE到文件的映射关系
214951
215238
  // 注意:以 "/" 结尾的路径表示目录,会包含该目录下的所有文件
@@ -214979,6 +215266,7 @@ const IDE_FILE_MAPPINGS = {
214979
215266
  qoder: [".qoder/rules/"],
214980
215267
  antigravity: [".agent/rules/"],
214981
215268
  vscode: [".vscode/mcp.json", ".vscode/settings.json"],
215269
+ kiro: [".kiro/settings/mcp.json", ".kiro/steering/"],
214982
215270
  };
214983
215271
  // 所有IDE配置文件的完整列表 - 通过IDE_FILE_MAPPINGS计算得出
214984
215272
  const ALL_IDE_FILES = Array.from(new Set(Object.values(IDE_FILE_MAPPINGS).flat()));
@@ -215005,6 +215293,7 @@ const IDE_DESCRIPTIONS = {
215005
215293
  qoder: "Qoder AI编辑器",
215006
215294
  antigravity: "Google Antigravity AI编辑器",
215007
215295
  vscode: "Visual Studio Code",
215296
+ kiro: "Kiro AI编辑器",
215008
215297
  };
215009
215298
  // INTEGRATION_IDE 环境变量值到 IDE 类型的映射
215010
215299
  const INTEGRATION_IDE_MAPPING = {
@@ -215028,6 +215317,7 @@ const INTEGRATION_IDE_MAPPING = {
215028
215317
  Qoder: "qoder",
215029
215318
  Antigravity: "antigravity",
215030
215319
  VSCode: "vscode",
215320
+ Kiro: "kiro",
215031
215321
  };
215032
215322
  // 根据 INTEGRATION_IDE 环境变量获取默认 IDE 类型
215033
215323
  function getDefaultIDEFromEnv() {
@@ -215250,7 +215540,7 @@ function registerSetupTools(server) {
215250
215540
  title: "下载项目模板",
215251
215541
  description: `自动下载并部署CloudBase项目模板。⚠️ **MANDATORY FOR NEW PROJECTS** ⚠️
215252
215542
 
215253
- **CRITICAL**: This tool MUST be called FIRST when starting a new project.\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- 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\n特别说明:\n- rules 模板会自动包含当前 mcp 版本号信息(版本号:${ true ? "2.3.0" : 0}),便于后续维护和版本追踪\n- 下载 rules 模板时,如果项目中已存在 README.md 文件,系统会自动保护该文件不被覆盖(除非设置 overwrite=true)`,
215543
+ **CRITICAL**: This tool MUST be called FIRST when starting a new project.\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- 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\n特别说明:\n- rules 模板会自动包含当前 mcp 版本号信息(版本号:${ true ? "2.4.0-alpha.0" : 0}),便于后续维护和版本追踪\n- 下载 rules 模板时,如果项目中已存在 README.md 文件,系统会自动保护该文件不被覆盖(除非设置 overwrite=true)`,
215254
215544
  inputSchema: {
215255
215545
  template: zod_1.z
215256
215546
  .enum(["react", "vue", "miniprogram", "uniapp", "rules"])
@@ -226352,6 +226642,7 @@ class CloudService {
226352
226642
  this.cloudBaseContext = context;
226353
226643
  }
226354
226644
  get baseUrl() {
226645
+ const internalEndpoint = this.cloudBaseContext.isInternalEndpoint();
226355
226646
  const tcb = process.env.TCB_BASE_URL || 'https://tcb.tencentcloudapi.com';
226356
226647
  const urlMap = {
226357
226648
  tcb,
@@ -226365,7 +226656,7 @@ class CloudService {
226365
226656
  const intranetUrlMap = Object.keys(urlMap).map((service) => ({
226366
226657
  [service]: `https://${service}.internal.tencentcloudapi.com`,
226367
226658
  })).reduce((acc, cur) => (Object.assign(Object.assign({}, acc), cur)), {});
226368
- if (constant_1.USE_INTERNAL_ENDPOINT) {
226659
+ if (internalEndpoint) {
226369
226660
  return intranetUrlMap[this.service];
226370
226661
  }
226371
226662
  if (urlMap[this.service]) {
@@ -233159,6 +233450,7 @@ function registerGatewayTools(server) {
233159
233450
  name,
233160
233451
  path
233161
233452
  });
233453
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
233162
233454
  return {
233163
233455
  content: [
233164
233456
  {
@@ -269998,7 +270290,7 @@ class CloudBase {
269998
270290
  }
269999
270291
  constructor(config = {}) {
270000
270292
  this.cloudBaseConfig = {};
270001
- let { secretId, secretKey, token, envId, proxy, region, envType } = config;
270293
+ let { secretId, secretKey, token, envId, proxy, region, envType, useInternalEndpoint } = config;
270002
270294
  // config 中传入的 secretId secretkey 必须同时存在
270003
270295
  if ((secretId && !secretKey) || (!secretId && secretKey)) {
270004
270296
  throw new Error('secretId and secretKey must be a pair');
@@ -270010,7 +270302,8 @@ class CloudBase {
270010
270302
  envId,
270011
270303
  envType,
270012
270304
  proxy,
270013
- region
270305
+ region,
270306
+ useInternalEndpoint
270014
270307
  };
270015
270308
  // 初始化 context
270016
270309
  this.context = new context_1.CloudBaseContext(this.cloudBaseConfig);
@@ -270065,6 +270358,9 @@ class CloudBase {
270065
270358
  getManagerConfig() {
270066
270359
  return this.cloudBaseConfig;
270067
270360
  }
270361
+ get isInternalEndpoint() {
270362
+ return this.context.isInternalEndpoint();
270363
+ }
270068
270364
  }
270069
270365
  module.exports = CloudBase;
270070
270366
 
@@ -272143,6 +272439,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true }));
272143
272439
  exports.FunctionService = void 0;
272144
272440
  const fs_1 = __importDefault(__webpack_require__(29021));
272145
272441
  const path_1 = __importDefault(__webpack_require__(39902));
272442
+ const lodash_1 = __importDefault(__webpack_require__(2543));
272146
272443
  const packer_1 = __webpack_require__(5147);
272147
272444
  const error_1 = __webpack_require__(40430);
272148
272445
  const utils_1 = __webpack_require__(62358);
@@ -272389,20 +272686,96 @@ class FunctionService {
272389
272686
  });
272390
272687
  return data;
272391
272688
  }
272689
+ /**
272690
+ * 列出所有函数
272691
+ * @param {IListFunctionOptions} options
272692
+ * @returns {Promise<Record<string, string>[]>}
272693
+ */
272694
+ async listAllFunctions(options) {
272695
+ const allFunctions = [];
272696
+ let currentOffset = 0;
272697
+ const pageSize = 20;
272698
+ const { envId } = options;
272699
+ while (true) {
272700
+ try {
272701
+ const res = await this.scfService.request('ListFunctions', {
272702
+ Namespace: envId,
272703
+ Limit: pageSize,
272704
+ Offset: currentOffset
272705
+ });
272706
+ const { Functions = [], TotalCount } = res;
272707
+ if (Functions.length === 0) {
272708
+ break;
272709
+ }
272710
+ allFunctions.push(...Functions);
272711
+ // 检查是否已获取所有函数
272712
+ if (allFunctions.length >= TotalCount || Functions.length < pageSize) {
272713
+ break;
272714
+ }
272715
+ currentOffset += pageSize;
272716
+ }
272717
+ catch (error) {
272718
+ throw new error_1.CloudBaseError(`获取函数列表失败: ${error.message}`);
272719
+ }
272720
+ }
272721
+ // 格式化数据
272722
+ const data = [];
272723
+ allFunctions.forEach(func => {
272724
+ const { FunctionId, FunctionName, Runtime, AddTime, ModTime, Status } = func;
272725
+ data.push({
272726
+ FunctionId,
272727
+ FunctionName,
272728
+ Runtime,
272729
+ AddTime,
272730
+ ModTime,
272731
+ Status
272732
+ });
272733
+ });
272734
+ return data;
272735
+ }
272392
272736
  /**
272393
272737
  * 删除云函数
272394
272738
  * @param {string} name 云函数名称
272395
272739
  * @param {string} qualifier 需要删除的版本号,不填默认删除函数下全部版本。
272396
272740
  * @returns {Promise<IResponseInfo>}
272397
272741
  */
272398
- async deleteFunction(name, qualifier) {
272742
+ async deleteFunction({ name }) {
272743
+ var _a;
272399
272744
  const { namespace } = this.getFunctionConfig();
272400
- return this.scfService.request('DeleteFunction', {
272745
+ // 检测是否绑定了 API 网关
272746
+ const accessService = this.environment.getAccessService();
272747
+ const res = await accessService.getAccessList({
272748
+ name
272749
+ });
272750
+ // 删除绑定的 API 网关
272751
+ if (((_a = res === null || res === void 0 ? void 0 : res.APISet) === null || _a === void 0 ? void 0 : _a.length) > 0) {
272752
+ await accessService.deleteAccess({
272753
+ name
272754
+ });
272755
+ }
272756
+ await this.scfService.request('DeleteFunction', {
272401
272757
  FunctionName: name,
272402
- Namespace: namespace,
272403
- Qualifier: qualifier
272758
+ Namespace: namespace
272404
272759
  });
272405
272760
  }
272761
+ /**
272762
+ * 批量删除云函数
272763
+ * @param {Object} options
272764
+ * @param {string[]} options.names 云函数名称列表
272765
+ * @returns {Promise<void>}
272766
+ */
272767
+ async batchDeleteFunctions({ names }) {
272768
+ const promises = names.map(name => (async () => {
272769
+ try {
272770
+ await this.deleteFunction({ name });
272771
+ (0, utils_1.successLog)(`[${name}] 函数删除成功!`);
272772
+ }
272773
+ catch (e) {
272774
+ throw new error_1.CloudBaseError(e.message);
272775
+ }
272776
+ })());
272777
+ await Promise.all(promises);
272778
+ }
272406
272779
  /**
272407
272780
  * 获取云函数详细信息
272408
272781
  * @param {string} name 云函数名称
@@ -272437,13 +272810,35 @@ class FunctionService {
272437
272810
  }
272438
272811
  catch (e) {
272439
272812
  data.VpcConfig = {
272440
- vpc: '',
272441
- subnet: ''
272813
+ vpc: 'VpcId',
272814
+ subnet: 'SubnetId'
272442
272815
  };
272443
272816
  }
272444
272817
  }
272445
272818
  return data;
272446
272819
  }
272820
+ /**
272821
+ * 批量获取云函数详细信息
272822
+ * @param {Object} options
272823
+ * @param {string[]} options.names 云函数名称列表
272824
+ * @param {string} options.envId 环境 ID
272825
+ * @param {string} options.codeSecret
272826
+ * @returns {Promise<IFunctionInfo[]>}
272827
+ */
272828
+ async batchGetFunctionsDetail({ names, envId, codeSecret }) {
272829
+ const data = [];
272830
+ const promises = names.map(name => (async () => {
272831
+ try {
272832
+ const info = await this.getFunctionDetail(name, codeSecret);
272833
+ data.push(info);
272834
+ }
272835
+ catch (e) {
272836
+ throw new error_1.CloudBaseError(`${name} 获取信息失败:${e.message}`);
272837
+ }
272838
+ })());
272839
+ await Promise.all(promises);
272840
+ return data;
272841
+ }
272447
272842
  /**
272448
272843
  * 获取函数日志
272449
272844
  * @deprecated 请使用 getFunctionLogsV2 代替
@@ -272540,6 +272935,33 @@ class FunctionService {
272540
272935
  const res = await this.tcbService.request('GetFunctionLogDetail', params);
272541
272936
  return res;
272542
272937
  }
272938
+ /**
272939
+ * 获取函数的完整调用日志
272940
+ * 该方法会自动完成两步操作:1. 获取日志请求ID列表。 2. 根据ID列表获取每条日志的详细内容。
272941
+ * @param {IFunctionLogOptionsV2} options - 查询选项
272942
+ * @returns {Promise<IFunctionLogDetailRes[]>} 返回包含完整日志详情的数组
272943
+ */
272944
+ async getCompleteFunctionLogs(options) {
272945
+ // 调用 getFunctionLogsV2 获取日志请求ID列表
272946
+ const { name } = options;
272947
+ const logs = await this.getFunctionLogsV2(options);
272948
+ // 如果没有日志,直接返回空数组
272949
+ if (logs.LogList.length === 0) {
272950
+ return [];
272951
+ }
272952
+ const detailPromises = logs.LogList.map(async (log) => {
272953
+ // 对每一个日志ID,调用 getFunctionLogDetail
272954
+ const res = await this.getFunctionLogDetail({
272955
+ logRequestId: log.RequestId,
272956
+ startTime: options.startTime,
272957
+ endTime: options.endTime
272958
+ });
272959
+ return Object.assign(Object.assign({}, res), { RetCode: log.RetCode, FunctionName: name });
272960
+ });
272961
+ // 并发执行所有详情查询,等待它们全部完成
272962
+ const detailedLogs = await Promise.all(detailPromises);
272963
+ return detailedLogs;
272964
+ }
272543
272965
  /**
272544
272966
  * 更新云函数配置
272545
272967
  * @param {ICloudFunction} func 云函数配置
@@ -272675,6 +273097,28 @@ class FunctionService {
272675
273097
  throw new error_1.CloudBaseError(`[${name}] 调用失败:\n${e.message}`);
272676
273098
  }
272677
273099
  }
273100
+ /**
273101
+ * 批量调用云函数
273102
+ * @param {IFunctionBatchOptions} options
273103
+ * @returns {Promise<IFunctionInvokeRes[]>}
273104
+ */
273105
+ async batchInvokeFunctions(options) {
273106
+ const { functions, envId, log = false } = options;
273107
+ const promises = functions.map(func => (async () => {
273108
+ try {
273109
+ const result = await this.invokeFunction(func.name, func.params);
273110
+ if (log) {
273111
+ (0, utils_1.successLog)(`[${func.name}] 调用成功\n响应结果:\n`);
273112
+ console.log(result);
273113
+ }
273114
+ return result;
273115
+ }
273116
+ catch (e) {
273117
+ throw new error_1.CloudBaseError(`${func.name} 函数调用失败:${e.message}`);
273118
+ }
273119
+ })());
273120
+ return Promise.all(promises);
273121
+ }
272678
273122
  /**
272679
273123
  * 复制云函数
272680
273124
  * @param {string} name 云函数名称
@@ -272717,12 +273161,34 @@ class FunctionService {
272717
273161
  TriggerDesc: item.config
272718
273162
  };
272719
273163
  });
272720
- return this.scfService.request('BatchCreateTrigger', {
272721
- FunctionName: name,
272722
- Namespace: namespace,
272723
- Triggers: JSON.stringify(parsedTriggers),
272724
- Count: parsedTriggers.length
272725
- });
273164
+ try {
273165
+ return await this.scfService.request('BatchCreateTrigger', {
273166
+ FunctionName: name,
273167
+ Namespace: namespace,
273168
+ Triggers: JSON.stringify(parsedTriggers),
273169
+ Count: parsedTriggers.length
273170
+ });
273171
+ }
273172
+ catch (e) {
273173
+ throw new error_1.CloudBaseError(`[${name}] 创建触发器失败:${e.message}`, {
273174
+ action: e.action,
273175
+ code: e.code
273176
+ });
273177
+ }
273178
+ }
273179
+ // 批量部署函数触发器
273180
+ async batchCreateTriggers(options) {
273181
+ const { functions, envId } = options;
273182
+ const promises = functions.map(func => (async () => {
273183
+ try {
273184
+ await this.createFunctionTriggers(func.name, func.triggers);
273185
+ (0, utils_1.successLog)(`[${func.name}] 创建云函数触发器成功!`);
273186
+ }
273187
+ catch (e) {
273188
+ throw new error_1.CloudBaseError(e.message);
273189
+ }
273190
+ })());
273191
+ await Promise.all(promises);
272726
273192
  }
272727
273193
  /**
272728
273194
  * 删除云函数触发器
@@ -272732,12 +273198,50 @@ class FunctionService {
272732
273198
  */
272733
273199
  async deleteFunctionTrigger(name, triggerName) {
272734
273200
  const { namespace } = this.getFunctionConfig();
272735
- return this.scfService.request('DeleteTrigger', {
272736
- FunctionName: name,
272737
- Namespace: namespace,
272738
- TriggerName: triggerName,
272739
- Type: 'timer'
273201
+ try {
273202
+ await this.scfService.request('DeleteTrigger', {
273203
+ FunctionName: name,
273204
+ Namespace: namespace,
273205
+ TriggerName: triggerName,
273206
+ Type: 'timer'
273207
+ });
273208
+ (0, utils_1.successLog)(`[${name}] 删除云函数触发器 ${triggerName} 成功!`);
273209
+ }
273210
+ catch (e) {
273211
+ throw new error_1.CloudBaseError(`[${name}] 删除触发器失败:${e.message}`);
273212
+ }
273213
+ }
273214
+ async batchDeleteTriggers(options) {
273215
+ const { functions, envId } = options;
273216
+ const promises = functions.map(func => (async () => {
273217
+ try {
273218
+ func.triggers.forEach(async (trigger) => {
273219
+ await this.deleteFunctionTrigger(func.name, trigger.name);
273220
+ });
273221
+ }
273222
+ catch (e) {
273223
+ throw new error_1.CloudBaseError(e.message);
273224
+ }
273225
+ })());
273226
+ await Promise.all(promises);
273227
+ }
273228
+ /**
273229
+ * 下载云函数代码
273230
+ * @param {IFunctionCodeOptions} options
273231
+ * @returns {Promise<void>}
273232
+ */
273233
+ async downloadFunctionCode(options) {
273234
+ const { destPath, envId, functionName, codeSecret } = options;
273235
+ // 检验路径是否存在
273236
+ (0, utils_1.checkFullAccess)(destPath, true);
273237
+ // 获取下载链接
273238
+ const { Url } = await this.scfService.request('GetFunctionAddress', {
273239
+ FunctionName: functionName,
273240
+ Namespace: envId,
273241
+ CodeSecret: codeSecret
272740
273242
  });
273243
+ // 下载文件
273244
+ return (0, utils_1.downloadAndExtractRemoteZip)(Url, destPath);
272741
273245
  }
272742
273246
  /**
272743
273247
  * 获取云函数代码下载 链接
@@ -272763,6 +273267,68 @@ class FunctionService {
272763
273267
  throw new error_1.CloudBaseError(`[${functionName}] 获取函数代码下载链接失败:\n${e.message}`);
272764
273268
  }
272765
273269
  }
273270
+ // 函数绑定文件层
273271
+ async attachLayer(options) {
273272
+ const { envId, functionName, layerName, layerVersion, codeSecret } = options;
273273
+ let { Layers = [] } = await this.getFunctionDetail(functionName, codeSecret);
273274
+ Layers = Layers.map(item => lodash_1.default.pick(item, ['LayerName', 'LayerVersion']));
273275
+ // 新加的文件层添加到最后
273276
+ Layers.push({
273277
+ LayerName: layerName,
273278
+ LayerVersion: layerVersion
273279
+ });
273280
+ const res = await this.scfService.request('UpdateFunctionConfiguration', {
273281
+ Layers,
273282
+ Namespace: envId,
273283
+ FunctionName: functionName
273284
+ });
273285
+ return res;
273286
+ }
273287
+ // 函数解绑文件层
273288
+ async unAttachLayer(options) {
273289
+ const { envId, functionName, layerName, layerVersion, codeSecret } = options;
273290
+ let { Layers } = await this.getFunctionDetail(functionName, codeSecret);
273291
+ Layers = Layers.map(item => lodash_1.default.pick(item, ['LayerName', 'LayerVersion']));
273292
+ const index = Layers.findIndex(item => item.LayerName === layerName && item.LayerVersion === layerVersion);
273293
+ if (index === -1) {
273294
+ throw new error_1.CloudBaseError('层不存在');
273295
+ }
273296
+ // 删除指定的层
273297
+ Layers.splice(index, 1);
273298
+ const apiParams = {
273299
+ Namespace: envId,
273300
+ FunctionName: functionName,
273301
+ Layers: Layers.length > 0 ? Layers : [{
273302
+ LayerName: '',
273303
+ LayerVersion: 0
273304
+ }]
273305
+ };
273306
+ return this.scfService.request('UpdateFunctionConfiguration', apiParams);
273307
+ }
273308
+ // 更新云函数层
273309
+ async updateFunctionLayer(options) {
273310
+ const { envId, functionName, layers } = options;
273311
+ return this.scfService.request('UpdateFunctionConfiguration', {
273312
+ Layers: layers,
273313
+ Namespace: envId,
273314
+ FunctionName: functionName
273315
+ });
273316
+ }
273317
+ // 下载文件层 ZIP 文件
273318
+ async downloadLayer(options) {
273319
+ const { name, version, destPath } = options;
273320
+ const res = await this.scfService.request('GetLayerVersion', {
273321
+ LayerName: name,
273322
+ LayerVersion: version
273323
+ });
273324
+ const url = res === null || res === void 0 ? void 0 : res.Location;
273325
+ const zipPath = path_1.default.join(destPath, `${name}-${version}.zip`);
273326
+ if ((0, utils_1.checkFullAccess)(zipPath)) {
273327
+ throw new error_1.CloudBaseError(`文件已存在:${zipPath}`);
273328
+ }
273329
+ // 下载文件
273330
+ return (0, utils_1.downloadAndExtractRemoteZip)(url, destPath);
273331
+ }
272766
273332
  // 创建文件层版本
272767
273333
  async createLayer(options) {
272768
273334
  const { env } = this.getFunctionConfig();
@@ -272835,7 +273401,7 @@ class FunctionService {
272835
273401
  Limit: limit,
272836
273402
  Offset: offset,
272837
273403
  SearchKey: searchKey,
272838
- SearchSrc: `TCB_${env}`
273404
+ // SearchSrc: `TCB_${env}`
272839
273405
  };
272840
273406
  if (runtime) {
272841
273407
  param.CompatibleRuntime = runtime;
@@ -273164,12 +273730,18 @@ __decorate([
273164
273730
  __decorate([
273165
273731
  (0, utils_1.preLazy)()
273166
273732
  ], FunctionService.prototype, "listFunctions", null);
273733
+ __decorate([
273734
+ (0, utils_1.preLazy)()
273735
+ ], FunctionService.prototype, "listAllFunctions", null);
273167
273736
  __decorate([
273168
273737
  (0, utils_1.preLazy)()
273169
273738
  ], FunctionService.prototype, "deleteFunction", null);
273170
273739
  __decorate([
273171
273740
  (0, utils_1.preLazy)()
273172
273741
  ], FunctionService.prototype, "getFunctionDetail", null);
273742
+ __decorate([
273743
+ (0, utils_1.preLazy)()
273744
+ ], FunctionService.prototype, "batchGetFunctionsDetail", null);
273173
273745
  __decorate([
273174
273746
  (0, utils_1.preLazy)()
273175
273747
  ], FunctionService.prototype, "getFunctionLogs", null);
@@ -273179,6 +273751,9 @@ __decorate([
273179
273751
  __decorate([
273180
273752
  (0, utils_1.preLazy)()
273181
273753
  ], FunctionService.prototype, "getFunctionLogDetail", null);
273754
+ __decorate([
273755
+ (0, utils_1.preLazy)()
273756
+ ], FunctionService.prototype, "getCompleteFunctionLogs", null);
273182
273757
  __decorate([
273183
273758
  (0, utils_1.preLazy)()
273184
273759
  ], FunctionService.prototype, "updateFunctionConfig", null);
@@ -273188,6 +273763,9 @@ __decorate([
273188
273763
  __decorate([
273189
273764
  (0, utils_1.preLazy)()
273190
273765
  ], FunctionService.prototype, "invokeFunction", null);
273766
+ __decorate([
273767
+ (0, utils_1.preLazy)()
273768
+ ], FunctionService.prototype, "batchInvokeFunctions", null);
273191
273769
  __decorate([
273192
273770
  (0, utils_1.preLazy)()
273193
273771
  ], FunctionService.prototype, "copyFunction", null);
@@ -273200,6 +273778,18 @@ __decorate([
273200
273778
  __decorate([
273201
273779
  (0, utils_1.preLazy)()
273202
273780
  ], FunctionService.prototype, "getFunctionDownloadUrl", null);
273781
+ __decorate([
273782
+ (0, utils_1.preLazy)()
273783
+ ], FunctionService.prototype, "attachLayer", null);
273784
+ __decorate([
273785
+ (0, utils_1.preLazy)()
273786
+ ], FunctionService.prototype, "unAttachLayer", null);
273787
+ __decorate([
273788
+ (0, utils_1.preLazy)()
273789
+ ], FunctionService.prototype, "updateFunctionLayer", null);
273790
+ __decorate([
273791
+ (0, utils_1.preLazy)()
273792
+ ], FunctionService.prototype, "downloadLayer", null);
273203
273793
  __decorate([
273204
273794
  (0, utils_1.preLazy)()
273205
273795
  ], FunctionService.prototype, "createLayer", null);