@cloudbase/cloudbase-mcp 2.8.0 → 2.10.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
@@ -1726,7 +1726,7 @@ function registerEnvTools(server) {
1726
1726
  // Get CLAUDE.md prompt content (skip for CodeBuddy IDE)
1727
1727
  let promptContent = "";
1728
1728
  const currentIde = server.ide || process.env.INTEGRATION_IDE;
1729
- if (currentIde !== "CodeBuddy") {
1729
+ if (currentIde !== "CodeBuddy" && process.env.CLOUDBASE_GUIDE_PROMPT !== "false") {
1730
1730
  try {
1731
1731
  promptContent = await (0, rag_js_1.getClaudePrompt)();
1732
1732
  }
@@ -1829,7 +1829,7 @@ function registerEnvTools(server) {
1829
1829
  });
1830
1830
  // Use commonService to call DescribeEnvs with filter parameters
1831
1831
  // Filter parameters match the reference conditions provided by user
1832
- result = await cloudbaseList.commonService("tcb").call({
1832
+ result = await cloudbaseList.commonService("tcb", "2018-06-08").call({
1833
1833
  Action: "DescribeEnvs",
1834
1834
  Param: {
1835
1835
  EnvTypes: ["weda", "baas"], // Include weda and baas (normal) environments
@@ -1912,7 +1912,7 @@ function registerEnvTools(server) {
1912
1912
  let responseText = JSON.stringify(result, null, 2);
1913
1913
  // For info action, append CLAUDE.md prompt content (skip for CodeBuddy IDE)
1914
1914
  const currentIde = server.ide || process.env.INTEGRATION_IDE;
1915
- if (action === "info" && currentIde !== "CodeBuddy") {
1915
+ if (action === "info" && currentIde !== "CodeBuddy" && process.env.CLOUDBASE_GUIDE_PROMPT !== "false") {
1916
1916
  try {
1917
1917
  const promptContent = await (0, rag_js_1.getClaudePrompt)();
1918
1918
  if (promptContent) {
@@ -23837,7 +23837,10 @@ async function getCloudBaseManager(options = {}) {
23837
23837
  return createCloudBaseManagerWithOptions(cloudBaseOptions);
23838
23838
  }
23839
23839
  try {
23840
- const loginState = await (0, auth_js_1.getLoginState)();
23840
+ // Get region from environment variable for auth URL
23841
+ // Note: At this point, cloudBaseOptions is undefined (checked above), so only use env var
23842
+ const region = process.env.TCB_REGION;
23843
+ const loginState = await (0, auth_js_1.getLoginState)({ region });
23841
23844
  const { envId: loginEnvId, secretId, secretKey, token } = loginState;
23842
23845
  let finalEnvId;
23843
23846
  if (requireEnvId) {
@@ -23862,12 +23865,17 @@ async function getCloudBaseManager(options = {}) {
23862
23865
  }
23863
23866
  // envId priority: envManager.cachedEnvId > envManager.getEnvId() > loginState.envId > undefined
23864
23867
  // Note: envManager.cachedEnvId has highest priority as it reflects user's latest environment switch
23868
+ // Region priority: process.env.TCB_REGION > undefined (use SDK default)
23869
+ // At this point, cloudBaseOptions is undefined (checked above), so only use env var if present
23870
+ // Reuse region variable declared above (line 259) for CloudBase initialization
23865
23871
  const manager = new manager_node_1.default({
23866
23872
  secretId,
23867
23873
  secretKey,
23868
23874
  envId: finalEnvId || loginEnvId,
23869
23875
  token,
23870
23876
  proxy: process.env.http_proxy,
23877
+ region,
23878
+ // REGION 国际站需要指定 region
23871
23879
  });
23872
23880
  return manager;
23873
23881
  }
@@ -23877,15 +23885,18 @@ async function getCloudBaseManager(options = {}) {
23877
23885
  }
23878
23886
  }
23879
23887
  /**
23880
- * 使用传入的 CloudBase 配置创建 manager,不使用缓存
23881
- * @param cloudBaseOptions 传入的 CloudBase 配置选项
23882
- * @returns CloudBase manager 实例
23888
+ * Create a manager with the provided CloudBase options, without using cache
23889
+ * @param cloudBaseOptions Provided CloudBase options
23890
+ * @returns CloudBase manager instance
23883
23891
  */
23884
23892
  function createCloudBaseManagerWithOptions(cloudBaseOptions) {
23885
- (0, logger_js_1.debug)('使用传入的 CloudBase 配置创建 manager:', cloudBaseOptions);
23893
+ (0, logger_js_1.debug)('Create manager with provided CloudBase options:', cloudBaseOptions);
23894
+ // Region priority: cloudBaseOptions.region > process.env.TCB_REGION > undefined (use SDK default)
23895
+ const region = cloudBaseOptions.region ?? process.env.TCB_REGION ?? undefined;
23886
23896
  const manager = new manager_node_1.default({
23887
23897
  ...cloudBaseOptions,
23888
23898
  proxy: cloudBaseOptions.proxy || process.env.http_proxy,
23899
+ region
23889
23900
  });
23890
23901
  return manager;
23891
23902
  }
@@ -24095,9 +24106,14 @@ async function _promptAndSetEnvironmentId(autoSelectSingle, options) {
24095
24106
  }
24096
24107
  // 1. 确保用户已登录
24097
24108
  (0, logger_js_1.debug)("[interactive] Step 1: Checking login state...");
24109
+ // Get region from server options or environment variable for auth URL
24110
+ // Note: serverCloudBaseOptions will be declared later (line 282), so we get it here first
24111
+ const serverCloudBaseOptionsForAuth = server?.cloudBaseOptions;
24112
+ const region = serverCloudBaseOptionsForAuth?.region || process.env.TCB_REGION;
24098
24113
  const loginState = await (0, auth_js_1.getLoginState)({
24099
24114
  fromCloudBaseLoginPage: options?.loginFromCloudBaseLoginPage,
24100
24115
  ignoreEnvVars: options?.ignoreEnvVars,
24116
+ region,
24101
24117
  });
24102
24118
  (0, logger_js_1.debug)("[interactive] Login state:", {
24103
24119
  hasLoginState: !!loginState,
@@ -24129,6 +24145,14 @@ async function _promptAndSetEnvironmentId(autoSelectSingle, options) {
24129
24145
  cloudBaseOptions: serverCloudBaseOptions,
24130
24146
  });
24131
24147
  (0, logger_js_1.debug)("[interactive] CloudBase manager obtained");
24148
+ // If envId is already set, return directly
24149
+ const envId = serverCloudBaseOptions?.envId || process.env.CLOUDBASE_ENV_ID;
24150
+ if (envId) {
24151
+ return {
24152
+ selectedEnvId: envId,
24153
+ cancelled: false,
24154
+ };
24155
+ }
24132
24156
  // Step 2.1: Check and initialize TCB service if needed
24133
24157
  // Check if retry is requested (from interactive server session data)
24134
24158
  // Ensure server is resolved if it's a Promise (CLI mode)
@@ -24202,7 +24226,7 @@ async function _promptAndSetEnvironmentId(autoSelectSingle, options) {
24202
24226
  let queryEnvSuccess = false;
24203
24227
  let queryEnvError;
24204
24228
  try {
24205
- // Use commonService to call DescribeEnvs with filter parameters
24229
+ // Use Service to call DescribeEnvs with filter parameters
24206
24230
  // Filter parameters match the reference conditions provided by user
24207
24231
  const queryParams = {
24208
24232
  EnvTypes: ["weda", "baas"], // Include weda and baas (normal) environments
@@ -24210,7 +24234,7 @@ async function _promptAndSetEnvironmentId(autoSelectSingle, options) {
24210
24234
  Channels: ["dcloud", "iotenable", "tem", "scene_module"], // Filter special channels
24211
24235
  };
24212
24236
  (0, logger_js_1.debug)("[interactive] DescribeEnvs params:", queryParams);
24213
- envResult = await cloudbase.commonService("tcb").call({
24237
+ envResult = await cloudbase.commonService("tcb", "2018-06-08").call({
24214
24238
  Action: "DescribeEnvs",
24215
24239
  Param: queryParams,
24216
24240
  });
@@ -24338,7 +24362,7 @@ async function _promptAndSetEnvironmentId(autoSelectSingle, options) {
24338
24362
  // Sometimes creation is async and env might not be immediately available
24339
24363
  (0, logger_js_1.debug)("[interactive] Verifying created environment exists in list...");
24340
24364
  try {
24341
- const verifyResult = await cloudbase.commonService("tcb").call({
24365
+ const verifyResult = await cloudbase.commonService("tcb", "2018-06-08").call({
24342
24366
  Action: "DescribeEnvs",
24343
24367
  Param: {
24344
24368
  EnvTypes: ["weda", "baas"],
@@ -24523,6 +24547,15 @@ async function _promptAndSetEnvironmentId(autoSelectSingle, options) {
24523
24547
  accountInfo.uin = String(loginState.uin);
24524
24548
  (0, logger_js_1.debug)("[interactive] Using UIN from loginState:", { uin: accountInfo.uin });
24525
24549
  }
24550
+ // Attach region from server options or environment variable fallback
24551
+ // Reuse serverCloudBaseOptions declared earlier (line 278)
24552
+ const currentServerCloudBaseOptions = server?.cloudBaseOptions;
24553
+ if (currentServerCloudBaseOptions?.region) {
24554
+ accountInfo.region = currentServerCloudBaseOptions.region;
24555
+ }
24556
+ else if (process.env.TCB_REGION) {
24557
+ accountInfo.region = process.env.TCB_REGION;
24558
+ }
24526
24559
  // Report display_env_selection event
24527
24560
  await telemetry_js_1.telemetryReporter.report('toolkit_env_setup', {
24528
24561
  step: 'display_env_selection',
@@ -33396,7 +33429,7 @@ async function checkAndInitTcbService(cloudbase, context) {
33396
33429
  uin: newContext.uin,
33397
33430
  tcbServiceChecked: newContext.tcbServiceChecked
33398
33431
  });
33399
- const checkResult = await cloudbase.commonService("tcb").call({
33432
+ const checkResult = await cloudbase.commonService("tcb", "2018-06-08").call({
33400
33433
  Action: "CheckTcbService",
33401
33434
  Param: {}
33402
33435
  });
@@ -33417,7 +33450,7 @@ async function checkAndInitTcbService(cloudbase, context) {
33417
33450
  (0, logger_js_1.debug)('[env-setup] TCB service not initialized, attempting to initialize...');
33418
33451
  (0, logger_js_1.debug)('[env-setup] InitTcb params:', { Source: "qcloud", Channel: "mcp" });
33419
33452
  try {
33420
- const initResult = await cloudbase.commonService("tcb").call({
33453
+ const initResult = await cloudbase.commonService("tcb", "2018-06-08").call({
33421
33454
  Action: "InitTcb",
33422
33455
  Param: {
33423
33456
  Source: "qcloud",
@@ -33505,7 +33538,7 @@ async function checkAndCreateFreeEnv(cloudbase, context) {
33505
33538
  (0, logger_js_1.debug)('[env-setup] DescribeUserPromotionalActivity params:', {
33506
33539
  Names: ["NewUser", "ReturningUser", "BaasFree"]
33507
33540
  });
33508
- const activityResult = await cloudbase.commonService("tcb").call({
33541
+ const activityResult = await cloudbase.commonService("tcb", "2018-06-08").call({
33509
33542
  Action: "DescribeUserPromotionalActivity",
33510
33543
  Param: {
33511
33544
  Names: ["NewUser", "ReturningUser", "BaasFree"]
@@ -33556,7 +33589,7 @@ async function checkAndCreateFreeEnv(cloudbase, context) {
33556
33589
  Source: "qcloud"
33557
33590
  };
33558
33591
  (0, logger_js_1.debug)('[env-setup] CreateFreeEnvByActivity params:', createParams);
33559
- const createResult = await cloudbase.commonService("tcb").call({
33592
+ const createResult = await cloudbase.commonService("tcb", "2018-06-08").call({
33560
33593
  Action: "CreateFreeEnvByActivity",
33561
33594
  Param: createParams
33562
33595
  });
@@ -33701,7 +33734,9 @@ async function checkAndCreateFreeEnv(cloudbase, context) {
33701
33734
  */
33702
33735
  async function getUinForTelemetry() {
33703
33736
  try {
33704
- const loginState = await (0, auth_js_1.getLoginState)();
33737
+ // Get region from environment variable for auth URL
33738
+ const region = process.env.TCB_REGION;
33739
+ const loginState = await (0, auth_js_1.getLoginState)({ region });
33705
33740
  // Try to extract UIN from loginState
33706
33741
  // Note: actual field name may vary, adjust based on actual response
33707
33742
  return loginState.uin || undefined;
@@ -35538,90 +35573,70 @@ function registerSecurityRuleTools(server) {
35538
35573
  },
35539
35574
  }, async ({ resourceType, resourceId }) => {
35540
35575
  const envId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
35541
- try {
35542
- const cloudbase = await getManager();
35543
- let result;
35544
- if (resourceType === "noSqlDatabase") {
35545
- // 查询数据库安全规则
35546
- result = await cloudbase.commonService().call({
35547
- Action: "DescribeSafeRule",
35548
- Param: {
35549
- CollectionName: resourceId,
35550
- EnvId: envId,
35551
- },
35552
- });
35553
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
35554
- }
35555
- else if (resourceType === "function") {
35556
- // 查询云函数安全规则
35557
- result = await cloudbase.commonService().call({
35558
- Action: "DescribeSecurityRule",
35559
- Param: {
35560
- ResourceType: "FUNCTION",
35561
- EnvId: envId,
35562
- },
35563
- });
35564
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
35565
- }
35566
- else if (resourceType === "storage") {
35567
- // 查询存储安全规则
35568
- result = await cloudbase.commonService().call({
35569
- Action: "DescribeStorageSafeRule",
35570
- Param: {
35571
- Bucket: resourceId,
35572
- EnvId: envId,
35573
- },
35574
- });
35575
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
35576
- }
35577
- else if (resourceType === "sqlDatabase") {
35578
- // TODO: 考虑是否有支持指定其他 instance、schema 的需求
35579
- const instanceId = "default";
35580
- const schema = envId;
35581
- const tableName = resourceId;
35582
- result = await cloudbase.commonService("lowcode").call({
35583
- Action: "DescribeDataSourceBasicPolicy",
35584
- Param: {
35585
- EnvId: envId,
35586
- ResourceType: "table",
35587
- ResourceId: `${instanceId}#${schema}#${tableName}`,
35588
- RoleIdentityList: ["allUser"],
35589
- },
35590
- });
35591
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
35592
- }
35593
- else {
35594
- throw new Error(`不支持的资源类型: ${resourceType}`);
35595
- }
35596
- return {
35597
- content: [
35598
- {
35599
- type: "text",
35600
- text: JSON.stringify({
35601
- success: true,
35602
- aclTag: result.AclTag,
35603
- rule: result.Rule ?? null,
35604
- raw: result,
35605
- message: "安全规则读取成功",
35606
- }, null, 2),
35607
- },
35608
- ],
35609
- };
35576
+ const cloudbase = await getManager();
35577
+ let result;
35578
+ if (resourceType === "noSqlDatabase") {
35579
+ result = await cloudbase.commonService().call({
35580
+ Action: "DescribeSafeRule",
35581
+ Param: {
35582
+ CollectionName: resourceId,
35583
+ EnvId: envId,
35584
+ },
35585
+ });
35586
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
35610
35587
  }
35611
- catch (error) {
35612
- return {
35613
- content: [
35614
- {
35615
- type: "text",
35616
- text: JSON.stringify({
35617
- success: false,
35618
- error: error.message,
35619
- message: "安全规则读取失败",
35620
- }, null, 2),
35621
- },
35622
- ],
35623
- };
35588
+ else if (resourceType === "function") {
35589
+ result = await cloudbase.commonService().call({
35590
+ Action: "DescribeSecurityRule",
35591
+ Param: {
35592
+ ResourceType: "FUNCTION",
35593
+ EnvId: envId,
35594
+ },
35595
+ });
35596
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
35597
+ }
35598
+ else if (resourceType === "storage") {
35599
+ result = await cloudbase.commonService().call({
35600
+ Action: "DescribeStorageSafeRule",
35601
+ Param: {
35602
+ Bucket: resourceId,
35603
+ EnvId: envId,
35604
+ },
35605
+ });
35606
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
35624
35607
  }
35608
+ else if (resourceType === "sqlDatabase") {
35609
+ const instanceId = "default";
35610
+ const schema = envId;
35611
+ const tableName = resourceId;
35612
+ result = await cloudbase.commonService("lowcode").call({
35613
+ Action: "DescribeDataSourceBasicPolicy",
35614
+ Param: {
35615
+ EnvId: envId,
35616
+ ResourceType: "table",
35617
+ ResourceId: `${instanceId}#${schema}#${tableName}`,
35618
+ RoleIdentityList: ["allUser"],
35619
+ },
35620
+ });
35621
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
35622
+ }
35623
+ else {
35624
+ throw new Error(`不支持的资源类型: ${resourceType}`);
35625
+ }
35626
+ return {
35627
+ content: [
35628
+ {
35629
+ type: "text",
35630
+ text: JSON.stringify({
35631
+ success: true,
35632
+ aclTag: result.AclTag,
35633
+ rule: result.Rule ?? null,
35634
+ raw: result,
35635
+ message: "安全规则读取成功",
35636
+ }, null, 2),
35637
+ },
35638
+ ],
35639
+ };
35625
35640
  });
35626
35641
  // 写入安全规则 Tool
35627
35642
  server.registerTool?.(exports.WRITE_SECURITY_RULE, {
@@ -35648,154 +35663,138 @@ function registerSecurityRuleTools(server) {
35648
35663
  category: "security-rule",
35649
35664
  },
35650
35665
  }, async ({ resourceType, resourceId, aclTag, rule }) => {
35651
- try {
35652
- const cloudbase = await getManager();
35653
- const envId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
35654
- let result;
35655
- if (resourceType === "noSqlDatabase") {
35656
- if (aclTag === "CUSTOM") {
35657
- if (!rule)
35658
- throw new Error("noSQL 数据库自定义安全规则(CUSTOM)必须提供 rule 字段");
35659
- result = await cloudbase.commonService().call({
35660
- Action: "ModifySafeRule",
35661
- Param: {
35662
- CollectionName: resourceId,
35663
- EnvId: envId,
35664
- AclTag: aclTag,
35665
- Rule: rule,
35666
- },
35667
- });
35668
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
35669
- }
35670
- else {
35671
- result = await cloudbase.commonService().call({
35672
- Action: "ModifyDatabaseACL",
35673
- Param: {
35674
- CollectionName: resourceId,
35675
- EnvId: envId,
35676
- AclTag: aclTag,
35677
- },
35678
- });
35679
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
35680
- }
35681
- }
35682
- else if (resourceType === "function") {
35683
- if (aclTag !== "CUSTOM")
35684
- throw new Error("云函数安全规则仅支持 CUSTOM 权限类别");
35666
+ const cloudbase = await getManager();
35667
+ const envId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
35668
+ let result;
35669
+ if (resourceType === "noSqlDatabase") {
35670
+ if (aclTag === "CUSTOM") {
35685
35671
  if (!rule)
35686
- throw new Error("云函数自定义安全规则(CUSTOM)必须提供 rule 字段");
35672
+ throw new Error("noSQL 数据库自定义安全规则(CUSTOM)必须提供 rule 字段");
35687
35673
  result = await cloudbase.commonService().call({
35688
- Action: "ModifySecurityRule",
35674
+ Action: "ModifySafeRule",
35689
35675
  Param: {
35690
- AclTag: aclTag,
35676
+ CollectionName: resourceId,
35691
35677
  EnvId: envId,
35692
- ResourceType: "FUNCTION",
35678
+ AclTag: aclTag,
35693
35679
  Rule: rule,
35694
35680
  },
35695
35681
  });
35696
35682
  (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
35697
35683
  }
35698
- else if (resourceType === "storage") {
35699
- if (aclTag === "CUSTOM") {
35700
- if (!rule)
35701
- throw new Error("存储自定义安全规则(CUSTOM)必须提供 rule 字段");
35702
- result = await cloudbase.commonService().call({
35703
- Action: "ModifyStorageSafeRule",
35704
- Param: {
35705
- Bucket: resourceId,
35706
- EnvId: envId,
35707
- AclTag: aclTag,
35708
- Rule: rule,
35709
- },
35710
- });
35711
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
35712
- }
35713
- else {
35714
- result = await cloudbase.commonService().call({
35715
- Action: "ModifyStorageSafeRule",
35716
- Param: {
35717
- Bucket: resourceId,
35718
- EnvId: envId,
35719
- AclTag: aclTag,
35720
- },
35721
- });
35722
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
35723
- }
35684
+ else {
35685
+ result = await cloudbase.commonService().call({
35686
+ Action: "ModifyDatabaseACL",
35687
+ Param: {
35688
+ CollectionName: resourceId,
35689
+ EnvId: envId,
35690
+ AclTag: aclTag,
35691
+ },
35692
+ });
35693
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
35724
35694
  }
35725
- else if (resourceType === "sqlDatabase") {
35726
- if (aclTag === "CUSTOM") {
35727
- throw new Error("SQL 数据库不支持自定义安全规则(CUSTOM");
35728
- }
35729
- const schema = envId;
35730
- const tableName = resourceId;
35731
- const instanceId = "default";
35732
- const resource = `${instanceId}#${schema}#${tableName}`;
35733
- const resourceType = "table";
35734
- const effect = "allow";
35735
- const policyList = [
35736
- "allUser",
35737
- "anonymousUser",
35738
- "externalUser",
35739
- "internalUser",
35740
- ].map((roleIdentity) => ({
35741
- RoleIdentity: roleIdentity,
35742
- ResourceType: resourceType,
35743
- ResourceId: resource,
35744
- RowPermission: [],
35745
- Effect: effect,
35746
- }));
35747
- policyList[0].RowPermission = getRowPermission(aclTag);
35748
- result = await cloudbase.commonService("lowcode").call({
35749
- Action: "BatchCreateResourcePolicy",
35695
+ }
35696
+ else if (resourceType === "function") {
35697
+ if (aclTag !== "CUSTOM")
35698
+ throw new Error("云函数安全规则仅支持 CUSTOM 权限类别");
35699
+ if (!rule)
35700
+ throw new Error("云函数自定义安全规则(CUSTOM)必须提供 rule 字段");
35701
+ result = await cloudbase.commonService().call({
35702
+ Action: "ModifySecurityRule",
35703
+ Param: {
35704
+ AclTag: aclTag,
35705
+ EnvId: envId,
35706
+ ResourceType: "FUNCTION",
35707
+ Rule: rule,
35708
+ },
35709
+ });
35710
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
35711
+ }
35712
+ else if (resourceType === "storage") {
35713
+ if (aclTag === "CUSTOM") {
35714
+ if (!rule)
35715
+ throw new Error("存储自定义安全规则(CUSTOM)必须提供 rule 字段");
35716
+ result = await cloudbase.commonService().call({
35717
+ Action: "ModifyStorageSafeRule",
35750
35718
  Param: {
35719
+ Bucket: resourceId,
35751
35720
  EnvId: envId,
35752
- PolicyList: policyList,
35721
+ AclTag: aclTag,
35722
+ Rule: rule,
35753
35723
  },
35754
35724
  });
35755
35725
  (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
35756
- function getRowPermission(policy) {
35757
- return {
35758
- READONLY: [
35759
- { Key: "all", Value: "r" },
35760
- { Key: "me", Value: "rw" },
35761
- ],
35762
- PRIVATE: [{ Key: "me", Value: "rw" }],
35763
- ADMINWRITE: [{ Key: "all", Value: "r" }],
35764
- ADMINONLY: [],
35765
- }[policy];
35766
- }
35767
35726
  }
35768
35727
  else {
35769
- throw new Error(`不支持的资源类型: ${resourceType}`);
35770
- }
35771
- return {
35772
- content: [
35773
- {
35774
- type: "text",
35775
- text: JSON.stringify({
35776
- success: true,
35777
- requestId: result.RequestId,
35778
- raw: result,
35779
- message: "安全规则写入成功",
35780
- }, null, 2),
35728
+ result = await cloudbase.commonService().call({
35729
+ Action: "ModifyStorageSafeRule",
35730
+ Param: {
35731
+ Bucket: resourceId,
35732
+ EnvId: envId,
35733
+ AclTag: aclTag,
35781
35734
  },
35782
- ],
35783
- };
35735
+ });
35736
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
35737
+ }
35784
35738
  }
35785
- catch (error) {
35786
- return {
35787
- content: [
35788
- {
35789
- type: "text",
35790
- text: JSON.stringify({
35791
- success: false,
35792
- error: error.message,
35793
- message: "安全规则写入失败",
35794
- }, null, 2),
35795
- },
35796
- ],
35797
- };
35739
+ else if (resourceType === "sqlDatabase") {
35740
+ if (aclTag === "CUSTOM") {
35741
+ throw new Error("SQL 数据库不支持自定义安全规则(CUSTOM)");
35742
+ }
35743
+ const schema = envId;
35744
+ const tableName = resourceId;
35745
+ const instanceId = "default";
35746
+ const resource = `${instanceId}#${schema}#${tableName}`;
35747
+ const resourceType = "table";
35748
+ const effect = "allow";
35749
+ const policyList = [
35750
+ "allUser",
35751
+ "anonymousUser",
35752
+ "externalUser",
35753
+ "internalUser",
35754
+ ].map((roleIdentity) => ({
35755
+ RoleIdentity: roleIdentity,
35756
+ ResourceType: resourceType,
35757
+ ResourceId: resource,
35758
+ RowPermission: [],
35759
+ Effect: effect,
35760
+ }));
35761
+ policyList[0].RowPermission = getRowPermission(aclTag);
35762
+ result = await cloudbase.commonService("lowcode").call({
35763
+ Action: "BatchCreateResourcePolicy",
35764
+ Param: {
35765
+ EnvId: envId,
35766
+ PolicyList: policyList,
35767
+ },
35768
+ });
35769
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
35770
+ function getRowPermission(policy) {
35771
+ return {
35772
+ READONLY: [
35773
+ { Key: "all", Value: "r" },
35774
+ { Key: "me", Value: "rw" },
35775
+ ],
35776
+ PRIVATE: [{ Key: "me", Value: "rw" }],
35777
+ ADMINWRITE: [{ Key: "all", Value: "r" }],
35778
+ ADMINONLY: [],
35779
+ }[policy];
35780
+ }
35798
35781
  }
35782
+ else {
35783
+ throw new Error(`不支持的资源类型: ${resourceType}`);
35784
+ }
35785
+ return {
35786
+ content: [
35787
+ {
35788
+ type: "text",
35789
+ text: JSON.stringify({
35790
+ success: true,
35791
+ requestId: result.RequestId,
35792
+ raw: result,
35793
+ message: "安全规则写入成功",
35794
+ }, null, 2),
35795
+ },
35796
+ ],
35797
+ };
35799
35798
  });
35800
35799
  }
35801
35800
 
@@ -38068,64 +38067,44 @@ function registerDownloadTools(server) {
38068
38067
  category: "download"
38069
38068
  }
38070
38069
  }, async ({ url, relativePath }) => {
38071
- try {
38072
- // 验证相对路径安全性
38073
- if (!isPathSafe(relativePath)) {
38074
- return {
38075
- content: [
38076
- {
38077
- type: "text",
38078
- text: JSON.stringify({
38079
- success: false,
38080
- error: "不安全的相对路径",
38081
- message: "相对路径包含路径遍历操作(../)或绝对路径,出于安全考虑已拒绝",
38082
- suggestion: "请使用项目根目录下的相对路径,例如:'assets/images/logo.png'"
38083
- }, null, 2)
38084
- }
38085
- ]
38086
- };
38087
- }
38088
- // 计算最终下载路径
38089
- const targetPath = calculateDownloadPath(relativePath);
38090
- const projectRoot = getProjectRoot();
38091
- console.log(`📁 项目根目录: ${projectRoot}`);
38092
- console.log(`📁 相对路径: ${relativePath}`);
38093
- console.log(`📁 最终路径: ${targetPath}`);
38094
- // 下载文件到指定路径
38095
- const result = await downloadFileToPath(url, targetPath);
38096
- return {
38097
- content: [
38098
- {
38099
- type: "text",
38100
- text: JSON.stringify({
38101
- success: true,
38102
- filePath: result.filePath,
38103
- relativePath: relativePath,
38104
- contentType: result.contentType,
38105
- fileSize: result.fileSize,
38106
- projectRoot: projectRoot,
38107
- message: "文件下载成功到指定路径",
38108
- note: `文件已保存到项目目录: ${relativePath}`
38109
- }, null, 2)
38110
- }
38111
- ]
38112
- };
38113
- }
38114
- catch (error) {
38070
+ if (!isPathSafe(relativePath)) {
38115
38071
  return {
38116
38072
  content: [
38117
38073
  {
38118
38074
  type: "text",
38119
38075
  text: JSON.stringify({
38120
38076
  success: false,
38121
- error: error.message,
38122
- message: "文件下载失败",
38123
- suggestion: "请检查相对路径是否正确,确保不包含 ../ 等路径遍历操作"
38077
+ error: "不安全的相对路径",
38078
+ message: "相对路径包含路径遍历操作(../)或绝对路径,出于安全考虑已拒绝",
38079
+ suggestion: "请使用项目根目录下的相对路径,例如:'assets/images/logo.png'"
38124
38080
  }, null, 2)
38125
38081
  }
38126
38082
  ]
38127
38083
  };
38128
38084
  }
38085
+ const targetPath = calculateDownloadPath(relativePath);
38086
+ const projectRoot = getProjectRoot();
38087
+ console.log(`📁 项目根目录: ${projectRoot}`);
38088
+ console.log(`📁 相对路径: ${relativePath}`);
38089
+ console.log(`📁 最终路径: ${targetPath}`);
38090
+ const result = await downloadFileToPath(url, targetPath);
38091
+ return {
38092
+ content: [
38093
+ {
38094
+ type: "text",
38095
+ text: JSON.stringify({
38096
+ success: true,
38097
+ filePath: result.filePath,
38098
+ relativePath: relativePath,
38099
+ contentType: result.contentType,
38100
+ fileSize: result.fileSize,
38101
+ projectRoot: projectRoot,
38102
+ message: "文件下载成功到指定路径",
38103
+ note: `文件已保存到项目目录: ${relativePath}`
38104
+ }, null, 2)
38105
+ }
38106
+ ]
38107
+ };
38129
38108
  });
38130
38109
  }
38131
38110
 
@@ -40381,52 +40360,35 @@ function registerSQLDatabaseTools(server) {
40381
40360
  category: CATEGORY,
40382
40361
  },
40383
40362
  }, async ({ sql }) => {
40384
- try {
40385
- const cloudbase = await getManager();
40386
- const envId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
40387
- // TODO: 考虑是否有支持指定其他 instance、schema 的需求
40388
- const schemaId = envId;
40389
- const instanceId = "default";
40390
- const result = await cloudbase.commonService("tcb").call({
40391
- Action: "RunSql",
40392
- Param: {
40363
+ const cloudbase = await getManager();
40364
+ const envId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
40365
+ const schemaId = envId;
40366
+ const instanceId = "default";
40367
+ const result = await cloudbase.commonService("tcb", "2018-06-08").call({
40368
+ Action: "RunSql",
40369
+ Param: {
40370
+ EnvId: envId,
40371
+ Sql: sql,
40372
+ DbInstance: {
40393
40373
  EnvId: envId,
40394
- Sql: sql,
40395
- DbInstance: {
40396
- EnvId: envId,
40397
- InstanceId: instanceId,
40398
- Schema: schemaId,
40399
- },
40374
+ InstanceId: instanceId,
40375
+ Schema: schemaId,
40400
40376
  },
40401
- });
40402
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
40403
- return {
40404
- content: [
40405
- {
40406
- type: "text",
40407
- text: JSON.stringify({
40408
- success: true,
40409
- message: "SQL query executed successfully",
40410
- result,
40411
- }, null, 2),
40412
- },
40413
- ],
40414
- };
40415
- }
40416
- catch (error) {
40417
- return {
40418
- content: [
40419
- {
40420
- type: "text",
40421
- text: JSON.stringify({
40422
- success: false,
40423
- error: error.message,
40424
- message: "SQL query execution failed",
40425
- }, null, 2),
40426
- },
40427
- ],
40428
- };
40429
- }
40377
+ },
40378
+ });
40379
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
40380
+ return {
40381
+ content: [
40382
+ {
40383
+ type: "text",
40384
+ text: JSON.stringify({
40385
+ success: true,
40386
+ message: "SQL query executed successfully",
40387
+ result,
40388
+ }, null, 2),
40389
+ },
40390
+ ],
40391
+ };
40430
40392
  });
40431
40393
  // executeWriteSQL
40432
40394
  server.registerTool?.("executeWriteSQL", {
@@ -40445,52 +40407,35 @@ function registerSQLDatabaseTools(server) {
40445
40407
  category: CATEGORY,
40446
40408
  },
40447
40409
  }, async ({ sql }) => {
40448
- try {
40449
- const cloudbase = await getManager();
40450
- const envId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
40451
- // TODO: 考虑是否有支持指定其他 instance、schema 的需求
40452
- const schemaId = envId;
40453
- const instanceId = "default";
40454
- const result = await cloudbase.commonService("tcb").call({
40455
- Action: "RunSql",
40456
- Param: {
40410
+ const cloudbase = await getManager();
40411
+ const envId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
40412
+ const schemaId = envId;
40413
+ const instanceId = "default";
40414
+ const result = await cloudbase.commonService("tcb", "2018-06-08").call({
40415
+ Action: "RunSql",
40416
+ Param: {
40417
+ EnvId: envId,
40418
+ Sql: sql,
40419
+ DbInstance: {
40457
40420
  EnvId: envId,
40458
- Sql: sql,
40459
- DbInstance: {
40460
- EnvId: envId,
40461
- InstanceId: instanceId,
40462
- Schema: schemaId,
40463
- },
40421
+ InstanceId: instanceId,
40422
+ Schema: schemaId,
40464
40423
  },
40465
- });
40466
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
40467
- return {
40468
- content: [
40469
- {
40470
- type: "text",
40471
- text: JSON.stringify({
40472
- success: true,
40473
- message: `SQL statement executed successfully. If you just created a table, make sure to check its security rule is set to a proper value by using \`${security_rule_js_1.WRITE_SECURITY_RULE}\` and \`${security_rule_js_1.READ_SECURITY_RULE}\` tools.`,
40474
- result,
40475
- }, null, 2),
40476
- },
40477
- ],
40478
- };
40479
- }
40480
- catch (error) {
40481
- return {
40482
- content: [
40483
- {
40484
- type: "text",
40485
- text: JSON.stringify({
40486
- success: false,
40487
- error: error.message,
40488
- message: "SQL statement execution failed",
40489
- }, null, 2),
40490
- },
40491
- ],
40492
- };
40493
- }
40424
+ },
40425
+ });
40426
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
40427
+ return {
40428
+ content: [
40429
+ {
40430
+ type: "text",
40431
+ text: JSON.stringify({
40432
+ success: true,
40433
+ message: `SQL statement executed successfully. If you just created a table, make sure to check its security rule is set to a proper value by using \`${security_rule_js_1.WRITE_SECURITY_RULE}\` and \`${security_rule_js_1.READ_SECURITY_RULE}\` tools.`,
40434
+ result,
40435
+ }, null, 2),
40436
+ },
40437
+ ],
40438
+ };
40494
40439
  });
40495
40440
  }
40496
40441
 
@@ -89128,12 +89073,12 @@ function registerFunctionTools(server) {
89128
89073
  // getFunctionList - 获取云函数列表或详情(推荐)
89129
89074
  server.registerTool?.("getFunctionList", {
89130
89075
  title: "查询云函数列表或详情",
89131
- description: "获取云函数列表或单个函数详情,通过 action 参数区分操作类型",
89076
+ description: "获取云函数列表或单个函数详情。通过 action 参数区分操作类型:list=获取函数列表(默认,无需额外参数),detail=获取函数详情(需要提供 name 参数指定函数名称)",
89132
89077
  inputSchema: {
89133
- action: zod_1.z.enum(["list", "detail"]).optional().describe("操作类型:list=获取函数列表(默认),detail=获取函数详情"),
89078
+ action: zod_1.z.enum(["list", "detail"]).optional().describe("操作类型:list=获取函数列表(默认,无需额外参数),detail=获取函数详情(需要提供 name 参数)"),
89134
89079
  limit: zod_1.z.number().optional().describe("范围(list 操作时使用)"),
89135
89080
  offset: zod_1.z.number().optional().describe("偏移(list 操作时使用)"),
89136
- name: zod_1.z.string().optional().describe("函数名称(detail 操作时必需)"),
89081
+ name: zod_1.z.string().optional().describe("要查询的函数名称。当 action='detail' 时,此参数为必填项,必须提供已存在的函数名称。可通过 action='list' 操作获取可用的函数名称列表"),
89137
89082
  codeSecret: zod_1.z.string().optional().describe("代码保护密钥(detail 操作时使用)")
89138
89083
  },
89139
89084
  annotations: {
@@ -89373,17 +89318,30 @@ function registerFunctionTools(server) {
89373
89318
  }
89374
89319
  }, async ({ name, params }) => {
89375
89320
  // 使用闭包中的 cloudBaseOptions
89376
- const cloudbase = await getManager();
89377
- const result = await cloudbase.functions.invokeFunction(name, params);
89378
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
89379
- return {
89380
- content: [
89381
- {
89382
- type: "text",
89383
- text: JSON.stringify(result, null, 2)
89384
- }
89385
- ]
89386
- };
89321
+ try {
89322
+ const cloudbase = await getManager();
89323
+ const result = await cloudbase.functions.invokeFunction(name, params);
89324
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
89325
+ return {
89326
+ content: [
89327
+ {
89328
+ type: "text",
89329
+ text: JSON.stringify(result, null, 2)
89330
+ }
89331
+ ]
89332
+ };
89333
+ }
89334
+ catch (error) {
89335
+ const errorMessage = (error instanceof Error ? error.message : String(error));
89336
+ if (errorMessage.includes("Function not found") ||
89337
+ errorMessage.includes("函数不存在")) {
89338
+ throw new Error(`${errorMessage}\n\n` +
89339
+ `Tip: "invokeFunction" can only call deployed cloud functions. ` +
89340
+ `For database operations (such as creating collections), ` +
89341
+ `please use the appropriate database tools instead.`);
89342
+ }
89343
+ throw error;
89344
+ }
89387
89345
  });
89388
89346
  // getFunctionLogs - 获取云函数日志(新版,参数直接展开)
89389
89347
  server.registerTool?.("getFunctionLogs", {
@@ -102398,6 +102356,7 @@ const invite_code_js_1 = __webpack_require__(44760);
102398
102356
  const security_rule_js_1 = __webpack_require__(7862);
102399
102357
  const cloud_mode_js_1 = __webpack_require__(89684);
102400
102358
  const logger_js_1 = __webpack_require__(13039);
102359
+ const tencet_cloud_js_1 = __webpack_require__(95018);
102401
102360
  const tool_wrapper_js_1 = __webpack_require__(71363);
102402
102361
  // 默认插件列表
102403
102362
  const DEFAULT_PLUGINS = [
@@ -102417,7 +102376,11 @@ const DEFAULT_PLUGINS = [
102417
102376
  "capi",
102418
102377
  ];
102419
102378
  function registerDatabase(server) {
102420
- (0, databaseNoSQL_js_1.registerDatabaseTools)(server);
102379
+ // Skip NoSQL database tools for international region (Singapore) as it doesn't support NoSQL DB
102380
+ const region = server.cloudBaseOptions?.region || process.env.TCB_REGION;
102381
+ if (!(0, tencet_cloud_js_1.isInternationalRegion)(region)) {
102382
+ (0, databaseNoSQL_js_1.registerDatabaseTools)(server);
102383
+ }
102421
102384
  (0, databaseSQL_js_1.registerSQLDatabaseTools)(server);
102422
102385
  (0, dataModel_js_1.registerDataModelTools)(server);
102423
102386
  }
@@ -108819,12 +108782,12 @@ function registerDataModelTools(server) {
108819
108782
  // 数据模型查询工具
108820
108783
  server.registerTool?.("manageDataModel", {
108821
108784
  title: "数据模型管理",
108822
- description: "数据模型查询工具,支持查询和列表数据模型(只读操作)。list操作返回基础信息(不含Schema),get操作返回详细信息(含简化的Schema,包括字段列表、格式、关联关系等),docs操作生成SDK使用文档",
108785
+ description: "数据模型查询工具,支持查询和列表数据模型(只读操作)。通过 action 参数区分操作类型:list=获取模型列表(不含Schema,可选 names 参数过滤),get=查询单个模型详情(含Schema字段列表、格式、关联关系等,需要提供 name 参数),docs=生成SDK使用文档(需要提供 name 参数)",
108823
108786
  inputSchema: {
108824
108787
  action: zod_1.z
108825
108788
  .enum(["get", "list", "docs"])
108826
- .describe("操作类型:get=查询单个模型(含Schema字段列表、格式、关联关系),list=获取模型列表(不含Schema),docs=生成SDK使用文档"),
108827
- name: zod_1.z.string().optional().describe("模型名称(get操作时必填)"),
108789
+ .describe("操作类型:get=查询单个模型(含Schema字段列表、格式、关联关系,需要提供 name 参数),list=获取模型列表(不含Schema,可选 names 参数过滤),docs=生成SDK使用文档(需要提供 name 参数)"),
108790
+ name: zod_1.z.string().optional().describe("要查询的数据模型名称。当 action='get' 或 action='docs' 时,此参数为必填项,必须提供已存在的数据模型名称。可通过 action='list' 操作获取可用的模型名称列表"),
108828
108791
  names: zod_1.z
108829
108792
  .array(zod_1.z.string())
108830
108793
  .optional()
@@ -108836,289 +108799,271 @@ function registerDataModelTools(server) {
108836
108799
  category: "database",
108837
108800
  },
108838
108801
  }, async ({ action, name, names, }) => {
108839
- try {
108840
- const cloudbase = await getManager();
108841
- let currentEnvId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
108842
- let result;
108843
- switch (action) {
108844
- case "get":
108845
- if (!name) {
108846
- throw new Error("获取数据模型需要提供模型名称");
108847
- }
108848
- try {
108849
- result = await cloudbase.commonService("lowcode").call({
108850
- Action: "DescribeBasicDataSource",
108851
- Param: {
108852
- EnvId: currentEnvId,
108853
- Name: name,
108854
- },
108855
- });
108856
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
108857
- // 只保留基础字段,过滤掉冗余信息,并简化Schema
108858
- let simplifiedSchema = null;
108859
- // 解析并简化Schema
108860
- if (result.Data.Schema) {
108861
- try {
108862
- const schema = JSON.parse(result.Data.Schema);
108863
- const properties = schema.properties || {};
108864
- // 提取用户定义的字段(排除系统字段)
108865
- const userFields = Object.keys(properties)
108866
- .filter((key) => !properties[key]["x-system"]) // 排除系统字段
108867
- .map((key) => {
108868
- const field = properties[key];
108869
- return parseFieldStructure(field, key, schema);
108870
- });
108871
- // 提取关联关系
108872
- const relations = userFields
108873
- .filter((field) => field.linkage)
108874
- .map((field) => ({
108875
- field: field.name,
108876
- type: field.format,
108877
- title: field.title,
108878
- targetModel: field.linkage.parentDataSourceName,
108879
- foreignKey: field.linkage.parentFieldKey,
108880
- displayField: field.linkage.parentFieldTitle,
108881
- }));
108882
- simplifiedSchema = {
108883
- userFields,
108884
- relations,
108885
- totalFields: Object.keys(properties).length,
108886
- userFieldsCount: userFields.length,
108887
- };
108888
- }
108889
- catch (e) {
108890
- simplifiedSchema = { error: "Schema解析失败" };
108891
- }
108802
+ const cloudbase = await getManager();
108803
+ let currentEnvId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
108804
+ let result;
108805
+ switch (action) {
108806
+ case "get":
108807
+ if (!name) {
108808
+ throw new Error("获取数据模型需要提供模型名称");
108809
+ }
108810
+ try {
108811
+ result = await cloudbase.commonService("lowcode").call({
108812
+ Action: "DescribeBasicDataSource",
108813
+ Param: {
108814
+ EnvId: currentEnvId,
108815
+ Name: name,
108816
+ },
108817
+ });
108818
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
108819
+ // 只保留基础字段,过滤掉冗余信息,并简化Schema
108820
+ let simplifiedSchema = null;
108821
+ // 解析并简化Schema
108822
+ if (result.Data.Schema) {
108823
+ try {
108824
+ const schema = JSON.parse(result.Data.Schema);
108825
+ const properties = schema.properties || {};
108826
+ // 提取用户定义的字段(排除系统字段)
108827
+ const userFields = Object.keys(properties)
108828
+ .filter((key) => !properties[key]["x-system"]) // 排除系统字段
108829
+ .map((key) => {
108830
+ const field = properties[key];
108831
+ return parseFieldStructure(field, key, schema);
108832
+ });
108833
+ // 提取关联关系
108834
+ const relations = userFields
108835
+ .filter((field) => field.linkage)
108836
+ .map((field) => ({
108837
+ field: field.name,
108838
+ type: field.format,
108839
+ title: field.title,
108840
+ targetModel: field.linkage.parentDataSourceName,
108841
+ foreignKey: field.linkage.parentFieldKey,
108842
+ displayField: field.linkage.parentFieldTitle,
108843
+ }));
108844
+ simplifiedSchema = {
108845
+ userFields,
108846
+ relations,
108847
+ totalFields: Object.keys(properties).length,
108848
+ userFieldsCount: userFields.length,
108849
+ };
108892
108850
  }
108893
- // 尝试生成Mermaid图表
108894
- let mermaidDiagram = null;
108895
- if (result.Data.Schema &&
108896
- jsonSchemaToMermaid &&
108897
- simplifiedSchema &&
108898
- !simplifiedSchema.error) {
108899
- try {
108900
- const mainSchema = JSON.parse(result.Data.Schema);
108901
- const schemasMap = {
108902
- [name]: mainSchema,
108903
- };
108904
- // 获取关联模型的 schema
108905
- if (simplifiedSchema.relations &&
108906
- simplifiedSchema.relations.length > 0) {
108907
- const relatedModelNames = [
108908
- ...new Set(simplifiedSchema.relations.map((rel) => rel.targetModel)),
108909
- ];
108910
- for (const relatedModelName of relatedModelNames) {
108911
- try {
108912
- const relatedResult = await cloudbase
108913
- .commonService("lowcode")
108914
- .call({
108915
- Action: "DescribeBasicDataSource",
108916
- Param: {
108917
- EnvId: currentEnvId,
108918
- Name: relatedModelName,
108919
- },
108920
- });
108921
- if (relatedResult.Data && relatedResult.Data.Schema) {
108922
- schemasMap[relatedModelName] = JSON.parse(relatedResult.Data.Schema);
108923
- }
108924
- }
108925
- catch (e) {
108926
- console.warn(`获取关联模型 ${relatedModelName} schema 失败:`, e);
108851
+ catch (e) {
108852
+ simplifiedSchema = { error: "Schema解析失败" };
108853
+ }
108854
+ }
108855
+ // 尝试生成Mermaid图表
108856
+ let mermaidDiagram = null;
108857
+ if (result.Data.Schema &&
108858
+ jsonSchemaToMermaid &&
108859
+ simplifiedSchema &&
108860
+ !simplifiedSchema.error) {
108861
+ try {
108862
+ const mainSchema = JSON.parse(result.Data.Schema);
108863
+ const schemasMap = {
108864
+ [name]: mainSchema,
108865
+ };
108866
+ // 获取关联模型的 schema
108867
+ if (simplifiedSchema.relations &&
108868
+ simplifiedSchema.relations.length > 0) {
108869
+ const relatedModelNames = [
108870
+ ...new Set(simplifiedSchema.relations.map((rel) => rel.targetModel)),
108871
+ ];
108872
+ for (const relatedModelName of relatedModelNames) {
108873
+ try {
108874
+ const relatedResult = await cloudbase
108875
+ .commonService("lowcode")
108876
+ .call({
108877
+ Action: "DescribeBasicDataSource",
108878
+ Param: {
108879
+ EnvId: currentEnvId,
108880
+ Name: relatedModelName,
108881
+ },
108882
+ });
108883
+ if (relatedResult.Data && relatedResult.Data.Schema) {
108884
+ schemasMap[relatedModelName] = JSON.parse(relatedResult.Data.Schema);
108927
108885
  }
108928
108886
  }
108887
+ catch (e) {
108888
+ console.warn(`获取关联模型 ${relatedModelName} 的 schema 失败:`, e);
108889
+ }
108929
108890
  }
108930
- // 调用 jsonSchemaToMermaid,传入正确的参数格式
108931
- mermaidDiagram = jsonSchemaToMermaid(schemasMap);
108932
- }
108933
- catch (e) {
108934
- console.warn("生成Mermaid图表失败:", e);
108935
108891
  }
108892
+ // 调用 jsonSchemaToMermaid,传入正确的参数格式
108893
+ mermaidDiagram = jsonSchemaToMermaid(schemasMap);
108936
108894
  }
108937
- const simplifiedModel = {
108938
- DbInstanceType: result.Data.DbInstanceType,
108939
- Title: result.Data.Title,
108940
- Description: result.Data.Description,
108941
- Name: result.Data.Name,
108942
- UpdatedAt: result.Data.UpdatedAt,
108943
- Schema: simplifiedSchema,
108944
- mermaid: mermaidDiagram,
108945
- };
108895
+ catch (e) {
108896
+ console.warn("生成Mermaid图表失败:", e);
108897
+ }
108898
+ }
108899
+ const simplifiedModel = {
108900
+ DbInstanceType: result.Data.DbInstanceType,
108901
+ Title: result.Data.Title,
108902
+ Description: result.Data.Description,
108903
+ Name: result.Data.Name,
108904
+ UpdatedAt: result.Data.UpdatedAt,
108905
+ Schema: simplifiedSchema,
108906
+ mermaid: mermaidDiagram,
108907
+ };
108908
+ return {
108909
+ content: [
108910
+ {
108911
+ type: "text",
108912
+ text: JSON.stringify({
108913
+ success: true,
108914
+ action: "get",
108915
+ data: simplifiedModel,
108916
+ message: "获取数据模型成功",
108917
+ }, null, 2),
108918
+ },
108919
+ ],
108920
+ };
108921
+ }
108922
+ catch (error) {
108923
+ if (error.original?.Code === "ResourceNotFound") {
108946
108924
  return {
108947
108925
  content: [
108948
108926
  {
108949
108927
  type: "text",
108950
108928
  text: JSON.stringify({
108951
- success: true,
108929
+ success: false,
108952
108930
  action: "get",
108953
- data: simplifiedModel,
108954
- message: "获取数据模型成功",
108931
+ error: "ResourceNotFound",
108932
+ message: `数据模型 ${name} 不存在`,
108955
108933
  }, null, 2),
108956
108934
  },
108957
108935
  ],
108958
108936
  };
108959
108937
  }
108960
- catch (error) {
108961
- if (error.original?.Code === "ResourceNotFound") {
108962
- return {
108963
- content: [
108964
- {
108965
- type: "text",
108966
- text: JSON.stringify({
108967
- success: false,
108968
- action: "get",
108969
- error: "ResourceNotFound",
108970
- message: `数据模型 ${name} 不存在`,
108971
- }, null, 2),
108972
- },
108973
- ],
108974
- };
108975
- }
108976
- throw error;
108977
- }
108978
- case "list":
108979
- // 构建请求参数
108980
- const listParams = {
108981
- EnvId: currentEnvId,
108982
- PageIndex: 1,
108983
- PageSize: 1000,
108984
- QuerySystemModel: true, // 查询系统模型
108985
- QueryConnector: 0, // 0 表示数据模型
108986
- };
108987
- // 只有当 names 参数存在且不为空时才添加过滤条件
108988
- if (names && names.length > 0) {
108989
- listParams.DataSourceNames = names;
108990
- }
108938
+ throw error;
108939
+ }
108940
+ case "list":
108941
+ // 构建请求参数
108942
+ const listParams = {
108943
+ EnvId: currentEnvId,
108944
+ PageIndex: 1,
108945
+ PageSize: 1000,
108946
+ QuerySystemModel: true, // 查询系统模型
108947
+ QueryConnector: 0, // 0 表示数据模型
108948
+ };
108949
+ // 只有当 names 参数存在且不为空时才添加过滤条件
108950
+ if (names && names.length > 0) {
108951
+ listParams.DataSourceNames = names;
108952
+ }
108953
+ result = await cloudbase.commonService("lowcode").call({
108954
+ Action: "DescribeDataSourceList",
108955
+ Param: listParams,
108956
+ });
108957
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
108958
+ const models = result.Data?.Rows || [];
108959
+ // 只保留基础字段,list操作不返回Schema
108960
+ const simplifiedModels = models.map((model) => ({
108961
+ DbInstanceType: model.DbInstanceType,
108962
+ Title: model.Title,
108963
+ Description: model.Description,
108964
+ Name: model.Name,
108965
+ UpdatedAt: model.UpdatedAt,
108966
+ }));
108967
+ return {
108968
+ content: [
108969
+ {
108970
+ type: "text",
108971
+ text: JSON.stringify({
108972
+ success: true,
108973
+ action: "list",
108974
+ data: simplifiedModels,
108975
+ count: simplifiedModels.length,
108976
+ message: "获取数据模型列表成功",
108977
+ }, null, 2),
108978
+ },
108979
+ ],
108980
+ };
108981
+ case "docs":
108982
+ if (!name) {
108983
+ throw new Error("生成SDK文档需要提供模型名称");
108984
+ }
108985
+ try {
108986
+ // 先获取模型信息
108991
108987
  result = await cloudbase.commonService("lowcode").call({
108992
- Action: "DescribeDataSourceList",
108993
- Param: listParams,
108988
+ Action: "DescribeBasicDataSource",
108989
+ Param: {
108990
+ EnvId: currentEnvId,
108991
+ Name: name,
108992
+ },
108994
108993
  });
108995
108994
  (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
108996
- const models = result.Data?.Rows || [];
108997
- // 只保留基础字段,list操作不返回Schema
108998
- const simplifiedModels = models.map((model) => ({
108999
- DbInstanceType: model.DbInstanceType,
109000
- Title: model.Title,
109001
- Description: model.Description,
109002
- Name: model.Name,
109003
- UpdatedAt: model.UpdatedAt,
109004
- }));
108995
+ if (!result.Data) {
108996
+ throw new Error(`数据模型 ${name} 不存在`);
108997
+ }
108998
+ // 解析Schema获取字段信息
108999
+ let userFields = [];
109000
+ let relations = [];
109001
+ if (result.Data.Schema) {
109002
+ try {
109003
+ const schema = JSON.parse(result.Data.Schema);
109004
+ const properties = schema.properties || {};
109005
+ // 提取用户定义的字段
109006
+ userFields = Object.keys(properties)
109007
+ .filter((key) => !properties[key]["x-system"])
109008
+ .map((key) => {
109009
+ const field = properties[key];
109010
+ return parseFieldStructure(field, key, schema);
109011
+ });
109012
+ // 提取关联关系
109013
+ relations = userFields
109014
+ .filter((field) => field.linkage)
109015
+ .map((field) => ({
109016
+ field: field.name,
109017
+ type: field.format,
109018
+ title: field.title,
109019
+ targetModel: field.linkage.parentDataSourceName,
109020
+ foreignKey: field.linkage.parentFieldKey,
109021
+ displayField: field.linkage.parentFieldTitle,
109022
+ }));
109023
+ }
109024
+ catch (e) {
109025
+ // Schema解析失败,使用空数组
109026
+ console.error("Schema解析失败", e);
109027
+ }
109028
+ }
109029
+ // 生成SDK使用文档
109030
+ const docs = generateSDKDocs(result.Data.Name, result.Data.Title, userFields, relations);
109005
109031
  return {
109006
109032
  content: [
109007
109033
  {
109008
109034
  type: "text",
109009
109035
  text: JSON.stringify({
109010
109036
  success: true,
109011
- action: "list",
109012
- data: simplifiedModels,
109013
- count: simplifiedModels.length,
109014
- message: "获取数据模型列表成功",
109037
+ action: "docs",
109038
+ modelName: name,
109039
+ modelTitle: result.Data.Title,
109040
+ docs,
109041
+ message: "SDK使用文档生成成功",
109015
109042
  }, null, 2),
109016
109043
  },
109017
109044
  ],
109018
109045
  };
109019
- case "docs":
109020
- if (!name) {
109021
- throw new Error("生成SDK文档需要提供模型名称");
109022
- }
109023
- try {
109024
- // 先获取模型信息
109025
- result = await cloudbase.commonService("lowcode").call({
109026
- Action: "DescribeBasicDataSource",
109027
- Param: {
109028
- EnvId: currentEnvId,
109029
- Name: name,
109030
- },
109031
- });
109032
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
109033
- if (!result.Data) {
109034
- throw new Error(`数据模型 ${name} 不存在`);
109035
- }
109036
- // 解析Schema获取字段信息
109037
- let userFields = [];
109038
- let relations = [];
109039
- if (result.Data.Schema) {
109040
- try {
109041
- const schema = JSON.parse(result.Data.Schema);
109042
- const properties = schema.properties || {};
109043
- // 提取用户定义的字段
109044
- userFields = Object.keys(properties)
109045
- .filter((key) => !properties[key]["x-system"])
109046
- .map((key) => {
109047
- const field = properties[key];
109048
- return parseFieldStructure(field, key, schema);
109049
- });
109050
- // 提取关联关系
109051
- relations = userFields
109052
- .filter((field) => field.linkage)
109053
- .map((field) => ({
109054
- field: field.name,
109055
- type: field.format,
109056
- title: field.title,
109057
- targetModel: field.linkage.parentDataSourceName,
109058
- foreignKey: field.linkage.parentFieldKey,
109059
- displayField: field.linkage.parentFieldTitle,
109060
- }));
109061
- }
109062
- catch (e) {
109063
- // Schema解析失败,使用空数组
109064
- console.error("Schema解析失败", e);
109065
- }
109066
- }
109067
- // 生成SDK使用文档
109068
- const docs = generateSDKDocs(result.Data.Name, result.Data.Title, userFields, relations);
109046
+ }
109047
+ catch (error) {
109048
+ if (error.original?.Code === "ResourceNotFound") {
109069
109049
  return {
109070
109050
  content: [
109071
109051
  {
109072
109052
  type: "text",
109073
109053
  text: JSON.stringify({
109074
- success: true,
109054
+ success: false,
109075
109055
  action: "docs",
109076
- modelName: name,
109077
- modelTitle: result.Data.Title,
109078
- docs,
109079
- message: "SDK使用文档生成成功",
109056
+ error: "ResourceNotFound",
109057
+ message: `数据模型 ${name} 不存在`,
109080
109058
  }, null, 2),
109081
109059
  },
109082
109060
  ],
109083
109061
  };
109084
109062
  }
109085
- catch (error) {
109086
- if (error.original?.Code === "ResourceNotFound") {
109087
- return {
109088
- content: [
109089
- {
109090
- type: "text",
109091
- text: JSON.stringify({
109092
- success: false,
109093
- action: "docs",
109094
- error: "ResourceNotFound",
109095
- message: `数据模型 ${name} 不存在`,
109096
- }, null, 2),
109097
- },
109098
- ],
109099
- };
109100
- }
109101
- throw error;
109102
- }
109103
- default:
109104
- throw new Error(`不支持的操作类型: ${action}`);
109105
- }
109106
- }
109107
- catch (error) {
109108
- return {
109109
- content: [
109110
- {
109111
- type: "text",
109112
- text: JSON.stringify({
109113
- success: false,
109114
- action,
109115
- error: error.message || error.original?.Message || "未知错误",
109116
- code: error.original?.Code,
109117
- message: "数据模型操作失败",
109118
- }, null, 2),
109119
- },
109120
- ],
109121
- };
109063
+ throw error;
109064
+ }
109065
+ default:
109066
+ throw new Error(`不支持的操作类型: ${action}`);
109122
109067
  }
109123
109068
  });
109124
109069
  // modifyDataModel - 数据模型修改工具(创建/更新)
@@ -109191,126 +109136,108 @@ classDiagram
109191
109136
  category: "database",
109192
109137
  },
109193
109138
  }, async ({ mermaidDiagram, action = "create", publish = false, dbInstanceType = "MYSQL", }) => {
109194
- try {
109195
- const cloudbase = await getManager();
109196
- let currentEnvId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
109197
- // 使用mermaidToJsonSchema转换Mermaid图表
109198
- const schemas = mermaidToJsonSchema(mermaidDiagram);
109199
- if (!schemas || Object.keys(schemas).length === 0) {
109200
- return {
109201
- content: [
109202
- {
109203
- type: "text",
109204
- text: JSON.stringify({
109205
- success: false,
109206
- error: "No schemas generated from Mermaid diagram",
109207
- message: "无法从Mermaid图表生成数据模型Schema",
109208
- }, null, 2),
109209
- },
109210
- ],
109211
- };
109212
- }
109213
- // 创建数据模型列表
109214
- const createDataModelList = Object.entries(schemas).map(([name, schema]) => {
109215
- return {
109216
- CreateSource: "cloudbase_create",
109217
- Creator: null,
109218
- DbLinkName: null,
109219
- Description: schema.description ||
109220
- `${schema.title || name}数据模型`,
109221
- Schema: JSON.stringify(createBackendSchemaParams(schema)),
109222
- Title: schema.title || name,
109223
- Name: name,
109224
- TableNameRule: "only_name",
109225
- };
109226
- });
109227
- // 调用批量创建数据模型API
109228
- const result = await cloudbase.commonService("lowcode").call({
109229
- Action: "BatchCreateDataModelList",
109230
- Param: {
109231
- CreateDataModelList: createDataModelList,
109232
- Creator: null,
109233
- DbInstanceType: dbInstanceType,
109234
- EnvId: currentEnvId,
109235
- },
109236
- });
109237
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
109238
- const taskId = result.Data?.TaskId;
109239
- if (!taskId) {
109240
- return {
109241
- content: [
109242
- {
109243
- type: "text",
109244
- text: JSON.stringify({
109245
- success: false,
109246
- requestId: result.RequestId,
109247
- error: "No TaskId returned",
109248
- message: "创建任务失败,未返回任务ID",
109249
- }, null, 2),
109250
- },
109251
- ],
109252
- };
109253
- }
109254
- // 轮询任务状态直至完成或超时
109255
- const maxWaitTime = 30000; // 30秒超时
109256
- const startTime = Date.now();
109257
- let status = "init";
109258
- let statusResult = null;
109259
- while (status === "init" && Date.now() - startTime < maxWaitTime) {
109260
- await new Promise((resolve) => setTimeout(resolve, 2000)); // 等待2秒
109261
- statusResult = await cloudbase.commonService("lowcode").call({
109262
- Action: "QueryModelTaskStatus",
109263
- Param: {
109264
- EnvId: currentEnvId,
109265
- TaskId: taskId,
109266
- },
109267
- });
109268
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, statusResult);
109269
- status = statusResult.Data?.Status || "init";
109270
- }
109271
- // 返回最终结果
109272
- const models = Object.keys(schemas);
109273
- const successModels = statusResult?.Data?.SuccessResourceIdList || [];
109274
- const failedModels = models.filter((model) => !successModels.includes(model));
109139
+ const cloudbase = await getManager();
109140
+ let currentEnvId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
109141
+ const schemas = mermaidToJsonSchema(mermaidDiagram);
109142
+ if (!schemas || Object.keys(schemas).length === 0) {
109275
109143
  return {
109276
109144
  content: [
109277
109145
  {
109278
109146
  type: "text",
109279
109147
  text: JSON.stringify({
109280
- success: status === "success",
109281
- requestId: result.RequestId,
109282
- taskId: taskId,
109283
- models: models,
109284
- successModels: successModels,
109285
- failedModels: failedModels,
109286
- status: status,
109287
- action: action,
109288
- message: status === "success"
109289
- ? `数据模型${action === "create" ? "创建" : "更新"}成功,共处理${models.length}个模型`
109290
- : status === "init"
109291
- ? `任务超时,任务ID: ${taskId},请稍后手动查询状态`
109292
- : `数据模型${action === "create" ? "创建" : "更新"}失败`,
109293
- taskResult: statusResult?.Data,
109148
+ success: false,
109149
+ error: "No schemas generated from Mermaid diagram",
109150
+ message: "无法从Mermaid图表生成数据模型Schema",
109294
109151
  }, null, 2),
109295
109152
  },
109296
109153
  ],
109297
109154
  };
109298
109155
  }
109299
- catch (error) {
109156
+ // 创建数据模型列表
109157
+ const createDataModelList = Object.entries(schemas).map(([name, schema]) => {
109158
+ return {
109159
+ CreateSource: "cloudbase_create",
109160
+ Creator: null,
109161
+ DbLinkName: null,
109162
+ Description: schema.description ||
109163
+ `${schema.title || name}数据模型`,
109164
+ Schema: JSON.stringify(createBackendSchemaParams(schema)),
109165
+ Title: schema.title || name,
109166
+ Name: name,
109167
+ TableNameRule: "only_name",
109168
+ };
109169
+ });
109170
+ // 调用批量创建数据模型API
109171
+ const result = await cloudbase.commonService("lowcode").call({
109172
+ Action: "BatchCreateDataModelList",
109173
+ Param: {
109174
+ CreateDataModelList: createDataModelList,
109175
+ Creator: null,
109176
+ DbInstanceType: dbInstanceType,
109177
+ EnvId: currentEnvId,
109178
+ },
109179
+ });
109180
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
109181
+ const taskId = result.Data?.TaskId;
109182
+ if (!taskId) {
109300
109183
  return {
109301
109184
  content: [
109302
109185
  {
109303
109186
  type: "text",
109304
109187
  text: JSON.stringify({
109305
109188
  success: false,
109306
- error: error.message || error.original?.Message || "未知错误",
109307
- code: error.original?.Code,
109308
- message: "数据模型修改操作失败",
109189
+ requestId: result.RequestId,
109190
+ error: "No TaskId returned",
109191
+ message: "创建任务失败,未返回任务ID",
109309
109192
  }, null, 2),
109310
109193
  },
109311
109194
  ],
109312
109195
  };
109313
109196
  }
109197
+ // 轮询任务状态直至完成或超时
109198
+ const maxWaitTime = 30000; // 30秒超时
109199
+ const startTime = Date.now();
109200
+ let status = "init";
109201
+ let statusResult = null;
109202
+ while (status === "init" && Date.now() - startTime < maxWaitTime) {
109203
+ await new Promise((resolve) => setTimeout(resolve, 2000)); // 等待2秒
109204
+ statusResult = await cloudbase.commonService("lowcode").call({
109205
+ Action: "QueryModelTaskStatus",
109206
+ Param: {
109207
+ EnvId: currentEnvId,
109208
+ TaskId: taskId,
109209
+ },
109210
+ });
109211
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, statusResult);
109212
+ status = statusResult.Data?.Status || "init";
109213
+ }
109214
+ // 返回最终结果
109215
+ const models = Object.keys(schemas);
109216
+ const successModels = statusResult?.Data?.SuccessResourceIdList || [];
109217
+ const failedModels = models.filter((model) => !successModels.includes(model));
109218
+ return {
109219
+ content: [
109220
+ {
109221
+ type: "text",
109222
+ text: JSON.stringify({
109223
+ success: status === "success",
109224
+ requestId: result.RequestId,
109225
+ taskId: taskId,
109226
+ models: models,
109227
+ successModels: successModels,
109228
+ failedModels: failedModels,
109229
+ status: status,
109230
+ action: action,
109231
+ message: status === "success"
109232
+ ? `数据模型${action === "create" ? "创建" : "更新"}成功,共处理${models.length}个模型`
109233
+ : status === "init"
109234
+ ? `任务超时,任务ID: ${taskId},请稍后手动查询状态`
109235
+ : `数据模型${action === "create" ? "创建" : "更新"}失败`,
109236
+ taskResult: statusResult?.Data,
109237
+ }, null, 2),
109238
+ },
109239
+ ],
109240
+ };
109314
109241
  });
109315
109242
  }
109316
109243
 
@@ -112347,113 +112274,97 @@ function registerCloudRunTools(server) {
112347
112274
  category: "cloudrun"
112348
112275
  }
112349
112276
  }, async (args) => {
112350
- try {
112351
- const input = args;
112352
- const manager = await getManager();
112353
- if (!manager) {
112354
- throw new Error("Failed to initialize CloudBase manager. Please check your credentials and environment configuration.");
112355
- }
112356
- const cloudrunService = manager.cloudrun;
112357
- switch (input.action) {
112358
- case 'list': {
112359
- const listParams = {
112360
- pageSize: input.pageSize,
112361
- pageNum: input.pageNum,
112362
- };
112363
- if (input.serverName) {
112364
- listParams.serverName = input.serverName;
112365
- }
112366
- if (input.serverType) {
112367
- listParams.serverType = input.serverType;
112368
- }
112369
- const result = await cloudrunService.list(listParams);
112370
- return {
112371
- content: [
112372
- {
112373
- type: "text",
112374
- text: JSON.stringify({
112375
- success: true,
112376
- data: {
112377
- services: result.ServerList || [],
112378
- pagination: {
112379
- total: result.Total || 0,
112380
- pageSize: input.pageSize,
112381
- pageNum: input.pageNum,
112382
- totalPages: Math.ceil((result.Total || 0) / (input.pageSize || 10))
112383
- }
112384
- },
112385
- message: `Found ${result.ServerList?.length || 0} CloudRun services`
112386
- }, null, 2)
112387
- }
112388
- ]
112389
- };
112277
+ const input = args;
112278
+ const manager = await getManager();
112279
+ if (!manager) {
112280
+ throw new Error("Failed to initialize CloudBase manager. Please check your credentials and environment configuration.");
112281
+ }
112282
+ const cloudrunService = manager.cloudrun;
112283
+ switch (input.action) {
112284
+ case 'list': {
112285
+ const listParams = {
112286
+ pageSize: input.pageSize,
112287
+ pageNum: input.pageNum,
112288
+ };
112289
+ if (input.serverName) {
112290
+ listParams.serverName = input.serverName;
112390
112291
  }
112391
- case 'detail': {
112392
- const serverName = input.detailServerName || input.serverName;
112393
- const result = await cloudrunService.detail({ serverName });
112394
- if (!result) {
112395
- return {
112396
- content: [
112397
- {
112398
- type: "text",
112399
- text: JSON.stringify({
112400
- success: false,
112401
- error: `Service '${serverName}' not found`,
112402
- message: "Please check the service name and try again."
112403
- }, null, 2)
112404
- }
112405
- ]
112406
- };
112407
- }
112408
- return {
112409
- content: [
112410
- {
112411
- type: "text",
112412
- text: JSON.stringify({
112413
- success: true,
112414
- data: {
112415
- service: result
112416
- },
112417
- message: `Retrieved details for service '${serverName}'`
112418
- }, null, 2)
112419
- }
112420
- ]
112421
- };
112292
+ if (input.serverType) {
112293
+ listParams.serverType = input.serverType;
112422
112294
  }
112423
- case 'templates': {
112424
- const result = await cloudrunService.getTemplates();
112295
+ const result = await cloudrunService.list(listParams);
112296
+ return {
112297
+ content: [
112298
+ {
112299
+ type: "text",
112300
+ text: JSON.stringify({
112301
+ success: true,
112302
+ data: {
112303
+ services: result.ServerList || [],
112304
+ pagination: {
112305
+ total: result.Total || 0,
112306
+ pageSize: input.pageSize,
112307
+ pageNum: input.pageNum,
112308
+ totalPages: Math.ceil((result.Total || 0) / (input.pageSize || 10))
112309
+ }
112310
+ },
112311
+ message: `Found ${result.ServerList?.length || 0} CloudRun services`
112312
+ }, null, 2)
112313
+ }
112314
+ ]
112315
+ };
112316
+ }
112317
+ case 'detail': {
112318
+ const serverName = input.detailServerName || input.serverName;
112319
+ const result = await cloudrunService.detail({ serverName });
112320
+ if (!result) {
112425
112321
  return {
112426
112322
  content: [
112427
112323
  {
112428
112324
  type: "text",
112429
112325
  text: JSON.stringify({
112430
- success: true,
112431
- data: {
112432
- templates: result || []
112433
- },
112434
- message: `Found ${result?.length || 0} available templates`
112326
+ success: false,
112327
+ error: `Service '${serverName}' not found`,
112328
+ message: "Please check the service name and try again."
112435
112329
  }, null, 2)
112436
112330
  }
112437
112331
  ]
112438
112332
  };
112439
112333
  }
112440
- default:
112441
- throw new Error(`Unsupported action: ${input.action}`);
112334
+ return {
112335
+ content: [
112336
+ {
112337
+ type: "text",
112338
+ text: JSON.stringify({
112339
+ success: true,
112340
+ data: {
112341
+ service: result
112342
+ },
112343
+ message: `Retrieved details for service '${serverName}'`
112344
+ }, null, 2)
112345
+ }
112346
+ ]
112347
+ };
112442
112348
  }
112443
- }
112444
- catch (error) {
112445
- return {
112446
- content: [
112447
- {
112448
- type: "text",
112449
- text: JSON.stringify({
112450
- success: false,
112451
- error: error.message || 'Unknown error occurred',
112452
- message: "Failed to query CloudRun information. Please check your permissions and try again."
112453
- }, null, 2)
112454
- }
112455
- ]
112456
- };
112349
+ case 'templates': {
112350
+ const result = await cloudrunService.getTemplates();
112351
+ return {
112352
+ content: [
112353
+ {
112354
+ type: "text",
112355
+ text: JSON.stringify({
112356
+ success: true,
112357
+ data: {
112358
+ templates: result || []
112359
+ },
112360
+ message: `Found ${result?.length || 0} available templates`
112361
+ }, null, 2)
112362
+ }
112363
+ ]
112364
+ };
112365
+ }
112366
+ default:
112367
+ throw new Error(`Unsupported action: ${input.action}`);
112457
112368
  }
112458
112369
  });
112459
112370
  // Track local running processes for CloudRun function services
@@ -112471,62 +112382,60 @@ function registerCloudRunTools(server) {
112471
112382
  category: "cloudrun"
112472
112383
  }
112473
112384
  }, async (args) => {
112474
- try {
112475
- const input = args;
112476
- const manager = await getManager();
112477
- if (!manager) {
112478
- throw new Error("Failed to initialize CloudBase manager. Please check your credentials and environment configuration.");
112479
- }
112480
- const cloudrunService = manager.cloudrun;
112481
- let targetPath;
112482
- // Validate and normalize path for operations that require it
112483
- if (input.targetPath) {
112484
- targetPath = validateAndNormalizePath(input.targetPath);
112485
- }
112486
- switch (input.action) {
112487
- case 'createAgent': {
112488
- if (!targetPath) {
112489
- throw new Error("targetPath is required for createAgent operation");
112490
- }
112491
- if (!input.agentConfig) {
112492
- throw new Error("agentConfig is required for createAgent operation");
112493
- }
112494
- const { agentName, botTag, description, template = 'blank' } = input.agentConfig;
112495
- // Generate BotId
112496
- const botId = botTag ? `ibot-${agentName}-${botTag}` : `ibot-${agentName}-${Date.now()}`;
112497
- // Create Agent using CloudBase Manager
112498
- const agentResult = await manager.agent.createFunctionAgent(targetPath, {
112499
- Name: agentName,
112500
- BotId: botId,
112501
- Introduction: description || `Agent created by ${agentName}`,
112502
- Avatar: undefined
112503
- });
112504
- // Create project directory
112505
- const projectDir = path_1.default.join(targetPath, input.serverName);
112506
- if (!fs_1.default.existsSync(projectDir)) {
112507
- fs_1.default.mkdirSync(projectDir, { recursive: true });
112385
+ const input = args;
112386
+ const manager = await getManager();
112387
+ if (!manager) {
112388
+ throw new Error("Failed to initialize CloudBase manager. Please check your credentials and environment configuration.");
112389
+ }
112390
+ const cloudrunService = manager.cloudrun;
112391
+ let targetPath;
112392
+ if (input.targetPath) {
112393
+ targetPath = validateAndNormalizePath(input.targetPath);
112394
+ }
112395
+ switch (input.action) {
112396
+ case 'createAgent': {
112397
+ if (!targetPath) {
112398
+ throw new Error("targetPath is required for createAgent operation");
112399
+ }
112400
+ if (!input.agentConfig) {
112401
+ throw new Error("agentConfig is required for createAgent operation");
112402
+ }
112403
+ const { agentName, botTag, description, template = 'blank' } = input.agentConfig;
112404
+ // Generate BotId
112405
+ const botId = botTag ? `ibot-${agentName}-${botTag}` : `ibot-${agentName}-${Date.now()}`;
112406
+ // Create Agent using CloudBase Manager
112407
+ const agentResult = await manager.agent.createFunctionAgent(targetPath, {
112408
+ Name: agentName,
112409
+ BotId: botId,
112410
+ Introduction: description || `Agent created by ${agentName}`,
112411
+ Avatar: undefined
112412
+ });
112413
+ // Create project directory
112414
+ const projectDir = path_1.default.join(targetPath, input.serverName);
112415
+ if (!fs_1.default.existsSync(projectDir)) {
112416
+ fs_1.default.mkdirSync(projectDir, { recursive: true });
112417
+ }
112418
+ // Generate package.json
112419
+ const packageJson = {
112420
+ name: input.serverName,
112421
+ version: "1.0.0",
112422
+ description: description || `Agent created by ${agentName}`,
112423
+ main: "index.js",
112424
+ scripts: {
112425
+ "dev": "tcb cloudrun run --runMode=agent -w",
112426
+ "deploy": "tcb cloudrun deploy",
112427
+ "start": "node index.js"
112428
+ },
112429
+ dependencies: {
112430
+ "@cloudbase/aiagent-framework": "^1.0.0-beta.10"
112431
+ },
112432
+ devDependencies: {
112433
+ "@cloudbase/cli": "^2.6.16"
112508
112434
  }
112509
- // Generate package.json
112510
- const packageJson = {
112511
- name: input.serverName,
112512
- version: "1.0.0",
112513
- description: description || `Agent created by ${agentName}`,
112514
- main: "index.js",
112515
- scripts: {
112516
- "dev": "tcb cloudrun run --runMode=agent -w",
112517
- "deploy": "tcb cloudrun deploy",
112518
- "start": "node index.js"
112519
- },
112520
- dependencies: {
112521
- "@cloudbase/aiagent-framework": "^1.0.0-beta.10"
112522
- },
112523
- devDependencies: {
112524
- "@cloudbase/cli": "^2.6.16"
112525
- }
112526
- };
112527
- fs_1.default.writeFileSync(path_1.default.join(projectDir, 'package.json'), JSON.stringify(packageJson, null, 2));
112528
- // Generate index.js with Agent template
112529
- const indexJsContent = `const { IBot } = require("@cloudbase/aiagent-framework");
112435
+ };
112436
+ fs_1.default.writeFileSync(path_1.default.join(projectDir, 'package.json'), JSON.stringify(packageJson, null, 2));
112437
+ // Generate index.js with Agent template
112438
+ const indexJsContent = `const { IBot } = require("@cloudbase/aiagent-framework");
112530
112439
  const { BotRunner } = require("@cloudbase/aiagent-framework");
112531
112440
 
112532
112441
  const ANSWER = "你好,我是一个智能体,但我只会说这一句话。";
@@ -112571,18 +112480,18 @@ exports.main = function (event, context) {
112571
112480
  return BotRunner.run(event, context, new MyBot(context));
112572
112481
  };
112573
112482
  `;
112574
- fs_1.default.writeFileSync(path_1.default.join(projectDir, 'index.js'), indexJsContent);
112575
- // Generate cloudbaserc.json
112576
- const currentEnvId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
112577
- const cloudbasercContent = {
112578
- envId: currentEnvId,
112579
- cloudrun: {
112580
- name: input.serverName
112581
- }
112582
- };
112583
- fs_1.default.writeFileSync(path_1.default.join(projectDir, 'cloudbaserc.json'), JSON.stringify(cloudbasercContent, null, 2));
112584
- // Generate README.md
112585
- const readmeContent = `# ${agentName} Agent
112483
+ fs_1.default.writeFileSync(path_1.default.join(projectDir, 'index.js'), indexJsContent);
112484
+ // Generate cloudbaserc.json
112485
+ const currentEnvId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
112486
+ const cloudbasercContent = {
112487
+ envId: currentEnvId,
112488
+ cloudrun: {
112489
+ name: input.serverName
112490
+ }
112491
+ };
112492
+ fs_1.default.writeFileSync(path_1.default.join(projectDir, 'cloudbaserc.json'), JSON.stringify(cloudbasercContent, null, 2));
112493
+ // Generate README.md
112494
+ const readmeContent = `# ${agentName} Agent
112586
112495
 
112587
112496
  这是一个基于函数型云托管的 AI 智能体。
112588
112497
 
@@ -112627,230 +112536,230 @@ for await (let x of res.textStream) {
112627
112536
  </script>
112628
112537
  \`\`\`
112629
112538
  `;
112630
- fs_1.default.writeFileSync(path_1.default.join(projectDir, 'README.md'), readmeContent);
112631
- return {
112632
- content: [
112633
- {
112634
- type: "text",
112635
- text: JSON.stringify({
112636
- success: true,
112637
- data: {
112638
- agentName: agentName,
112639
- botId: botId,
112640
- projectDir: projectDir,
112641
- serverName: input.serverName,
112642
- template: template,
112643
- filesCreated: ['package.json', 'index.js', 'cloudbaserc.json', 'README.md']
112644
- },
112645
- message: `Successfully created Agent '${agentName}' with BotId '${botId}' in ${projectDir}`
112646
- }, null, 2)
112647
- }
112648
- ]
112649
- };
112539
+ fs_1.default.writeFileSync(path_1.default.join(projectDir, 'README.md'), readmeContent);
112540
+ return {
112541
+ content: [
112542
+ {
112543
+ type: "text",
112544
+ text: JSON.stringify({
112545
+ success: true,
112546
+ data: {
112547
+ agentName: agentName,
112548
+ botId: botId,
112549
+ projectDir: projectDir,
112550
+ serverName: input.serverName,
112551
+ template: template,
112552
+ filesCreated: ['package.json', 'index.js', 'cloudbaserc.json', 'README.md']
112553
+ },
112554
+ message: `Successfully created Agent '${agentName}' with BotId '${botId}' in ${projectDir}`
112555
+ }, null, 2)
112556
+ }
112557
+ ]
112558
+ };
112559
+ }
112560
+ case 'deploy': {
112561
+ if (!targetPath) {
112562
+ throw new Error("targetPath is required for deploy operation");
112650
112563
  }
112651
- case 'deploy': {
112652
- if (!targetPath) {
112653
- throw new Error("targetPath is required for deploy operation");
112654
- }
112655
- // Determine service type - use input.serverType if provided, otherwise auto-detect
112656
- let serverType;
112657
- if (input.serverType) {
112658
- serverType = input.serverType;
112564
+ // Determine service type - use input.serverType if provided, otherwise auto-detect
112565
+ let serverType;
112566
+ if (input.serverType) {
112567
+ serverType = input.serverType;
112568
+ }
112569
+ else {
112570
+ try {
112571
+ // First try to get existing service details
112572
+ const details = await cloudrunService.detail({ serverName: input.serverName });
112573
+ serverType = details.BaseInfo?.ServerType || 'container';
112659
112574
  }
112660
- else {
112661
- try {
112662
- // First try to get existing service details
112663
- const details = await cloudrunService.detail({ serverName: input.serverName });
112664
- serverType = details.BaseInfo?.ServerType || 'container';
112575
+ catch (e) {
112576
+ // If service doesn't exist, determine by project structure
112577
+ const dockerfilePath = path_1.default.join(targetPath, 'Dockerfile');
112578
+ if (fs_1.default.existsSync(dockerfilePath)) {
112579
+ serverType = 'container';
112665
112580
  }
112666
- catch (e) {
112667
- // If service doesn't exist, determine by project structure
112668
- const dockerfilePath = path_1.default.join(targetPath, 'Dockerfile');
112669
- if (fs_1.default.existsSync(dockerfilePath)) {
112670
- serverType = 'container';
112671
- }
112672
- else {
112673
- // Check if it's a Node.js function project (has package.json with specific structure)
112674
- const packageJsonPath = path_1.default.join(targetPath, 'package.json');
112675
- if (fs_1.default.existsSync(packageJsonPath)) {
112676
- try {
112677
- const packageJson = JSON.parse(fs_1.default.readFileSync(packageJsonPath, 'utf8'));
112678
- // If it has function-specific dependencies or scripts, treat as function
112679
- if (packageJson.dependencies?.['@cloudbase/aiagent-framework'] ||
112680
- packageJson.scripts?.['dev']?.includes('cloudrun run')) {
112681
- serverType = 'function';
112682
- }
112683
- else {
112684
- serverType = 'container';
112685
- }
112581
+ else {
112582
+ // Check if it's a Node.js function project (has package.json with specific structure)
112583
+ const packageJsonPath = path_1.default.join(targetPath, 'package.json');
112584
+ if (fs_1.default.existsSync(packageJsonPath)) {
112585
+ try {
112586
+ const packageJson = JSON.parse(fs_1.default.readFileSync(packageJsonPath, 'utf8'));
112587
+ // If it has function-specific dependencies or scripts, treat as function
112588
+ if (packageJson.dependencies?.['@cloudbase/aiagent-framework'] ||
112589
+ packageJson.scripts?.['dev']?.includes('cloudrun run')) {
112590
+ serverType = 'function';
112686
112591
  }
112687
- catch (parseError) {
112592
+ else {
112688
112593
  serverType = 'container';
112689
112594
  }
112690
112595
  }
112691
- else {
112692
- // No package.json, default to container
112596
+ catch (parseError) {
112693
112597
  serverType = 'container';
112694
112598
  }
112695
112599
  }
112600
+ else {
112601
+ // No package.json, default to container
112602
+ serverType = 'container';
112603
+ }
112696
112604
  }
112697
112605
  }
112698
- const deployParams = {
112699
- serverName: input.serverName,
112700
- targetPath: targetPath,
112701
- force: input.force,
112702
- serverType: serverType,
112703
- };
112704
- // Add server configuration if provided
112705
- if (input.serverConfig) {
112706
- deployParams.serverConfig = input.serverConfig;
112707
- }
112708
- const result = await cloudrunService.deploy(deployParams);
112709
- // Generate cloudbaserc.json configuration file
112710
- const currentEnvId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
112711
- const cloudbasercPath = path_1.default.join(targetPath, 'cloudbaserc.json');
112712
- const cloudbasercContent = {
112713
- envId: currentEnvId,
112714
- cloudrun: {
112715
- name: input.serverName
112716
- }
112717
- };
112718
- try {
112719
- fs_1.default.writeFileSync(cloudbasercPath, JSON.stringify(cloudbasercContent, null, 2));
112720
- }
112721
- catch (error) {
112722
- // Ignore cloudbaserc.json creation errors
112606
+ }
112607
+ const deployParams = {
112608
+ serverName: input.serverName,
112609
+ targetPath: targetPath,
112610
+ force: input.force,
112611
+ serverType: serverType,
112612
+ };
112613
+ // Add server configuration if provided
112614
+ if (input.serverConfig) {
112615
+ deployParams.serverConfig = input.serverConfig;
112616
+ }
112617
+ const result = await cloudrunService.deploy(deployParams);
112618
+ // Generate cloudbaserc.json configuration file
112619
+ const currentEnvId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
112620
+ const cloudbasercPath = path_1.default.join(targetPath, 'cloudbaserc.json');
112621
+ const cloudbasercContent = {
112622
+ envId: currentEnvId,
112623
+ cloudrun: {
112624
+ name: input.serverName
112723
112625
  }
112724
- // Send deployment notification to CodeBuddy IDE
112626
+ };
112627
+ try {
112628
+ fs_1.default.writeFileSync(cloudbasercPath, JSON.stringify(cloudbasercContent, null, 2));
112629
+ }
112630
+ catch (error) {
112631
+ // Ignore cloudbaserc.json creation errors
112632
+ }
112633
+ // Send deployment notification to CodeBuddy IDE
112634
+ try {
112635
+ // Query service details to get access URL
112636
+ let serviceUrl = "";
112725
112637
  try {
112726
- // Query service details to get access URL
112727
- let serviceUrl = "";
112728
- try {
112729
- const serviceDetails = await cloudrunService.detail({ serverName: input.serverName });
112730
- // Extract access URL from service details
112731
- // Priority: DefaultDomainName > CustomDomainName > PublicDomain > InternalDomain
112732
- const details = serviceDetails; // Use any to access dynamic properties
112733
- if (details?.BaseInfo?.DefaultDomainName) {
112734
- // DefaultDomainName is already a complete URL (e.g., https://...)
112735
- serviceUrl = details.BaseInfo.DefaultDomainName;
112736
- }
112737
- else if (details?.BaseInfo?.CustomDomainName) {
112738
- // CustomDomainName might be a domain without protocol
112739
- const customDomain = details.BaseInfo.CustomDomainName;
112740
- serviceUrl = customDomain.startsWith('http') ? customDomain : `https://${customDomain}`;
112741
- }
112742
- else if (details?.BaseInfo?.PublicDomain) {
112743
- serviceUrl = `https://${details.BaseInfo.PublicDomain}`;
112744
- }
112745
- else if (details?.BaseInfo?.InternalDomain) {
112746
- serviceUrl = `https://${details.BaseInfo.InternalDomain}`;
112747
- }
112748
- else if (details?.AccessInfo?.PublicDomain) {
112749
- serviceUrl = `https://${details.AccessInfo.PublicDomain}`;
112750
- }
112751
- else {
112752
- serviceUrl = ""; // URL not available
112753
- }
112638
+ const serviceDetails = await cloudrunService.detail({ serverName: input.serverName });
112639
+ // Extract access URL from service details
112640
+ // Priority: DefaultDomainName > CustomDomainName > PublicDomain > InternalDomain
112641
+ const details = serviceDetails; // Use any to access dynamic properties
112642
+ if (details?.BaseInfo?.DefaultDomainName) {
112643
+ // DefaultDomainName is already a complete URL (e.g., https://...)
112644
+ serviceUrl = details.BaseInfo.DefaultDomainName;
112754
112645
  }
112755
- catch (detailErr) {
112756
- // If query fails, continue with empty URL
112757
- serviceUrl = "";
112646
+ else if (details?.BaseInfo?.CustomDomainName) {
112647
+ // CustomDomainName might be a domain without protocol
112648
+ const customDomain = details.BaseInfo.CustomDomainName;
112649
+ serviceUrl = customDomain.startsWith('http') ? customDomain : `https://${customDomain}`;
112650
+ }
112651
+ else if (details?.BaseInfo?.PublicDomain) {
112652
+ serviceUrl = `https://${details.BaseInfo.PublicDomain}`;
112653
+ }
112654
+ else if (details?.BaseInfo?.InternalDomain) {
112655
+ serviceUrl = `https://${details.BaseInfo.InternalDomain}`;
112656
+ }
112657
+ else if (details?.AccessInfo?.PublicDomain) {
112658
+ serviceUrl = `https://${details.AccessInfo.PublicDomain}`;
112659
+ }
112660
+ else {
112661
+ serviceUrl = ""; // URL not available
112758
112662
  }
112759
- // Extract project name from targetPath
112760
- const projectName = path_1.default.basename(targetPath);
112761
- // Build console URL
112762
- const consoleUrl = `https://tcb.cloud.tencent.com/dev?envId=${currentEnvId}#/platform-run/service/detail?serverName=${input.serverName}&tabId=overview&envId=${currentEnvId}`;
112763
- // Send notification
112764
- await (0, notification_js_1.sendDeployNotification)(server, {
112765
- deployType: 'cloudrun',
112766
- url: serviceUrl,
112767
- projectId: currentEnvId,
112768
- projectName: projectName,
112769
- consoleUrl: consoleUrl
112770
- });
112771
112663
  }
112772
- catch (notifyErr) {
112773
- // Notification failure should not affect deployment flow
112774
- // Error is already logged in sendDeployNotification
112664
+ catch (detailErr) {
112665
+ // If query fails, continue with empty URL
112666
+ serviceUrl = "";
112775
112667
  }
112776
- return {
112777
- content: [
112778
- {
112779
- type: "text",
112780
- text: JSON.stringify({
112781
- success: true,
112782
- data: {
112783
- serviceName: input.serverName,
112784
- status: 'deployed',
112785
- deployPath: targetPath,
112786
- serverType: serverType,
112787
- cloudbasercGenerated: true
112788
- },
112789
- message: `Successfully deployed ${serverType} service '${input.serverName}' from ${targetPath}`
112790
- }, null, 2)
112791
- }
112792
- ]
112793
- };
112668
+ // Extract project name from targetPath
112669
+ const projectName = path_1.default.basename(targetPath);
112670
+ // Build console URL
112671
+ const consoleUrl = `https://tcb.cloud.tencent.com/dev?envId=${currentEnvId}#/platform-run/service/detail?serverName=${input.serverName}&tabId=overview&envId=${currentEnvId}`;
112672
+ // Send notification
112673
+ await (0, notification_js_1.sendDeployNotification)(server, {
112674
+ deployType: 'cloudrun',
112675
+ url: serviceUrl,
112676
+ projectId: currentEnvId,
112677
+ projectName: projectName,
112678
+ consoleUrl: consoleUrl
112679
+ });
112794
112680
  }
112795
- case 'run': {
112796
- if (!targetPath) {
112797
- throw new Error("targetPath is required for run operation");
112798
- }
112799
- // Do not support container services locally: basic heuristic - if Dockerfile exists, treat as container
112800
- const dockerfilePath = path_1.default.join(targetPath, 'Dockerfile');
112801
- if (fs_1.default.existsSync(dockerfilePath)) {
112802
- throw new Error("Local run is only supported for function-type CloudRun services. Container services are not supported.");
112803
- }
112804
- // Check if this is an Agent project
112805
- const isAgent = checkIfAgentProject(targetPath);
112806
- const runMode = input.runOptions?.runMode || (isAgent ? 'agent' : 'normal');
112807
- // Check if service is already running and verify process exists
112808
- if (runningProcesses.has(input.serverName)) {
112809
- const existingPid = runningProcesses.get(input.serverName);
112810
- try {
112811
- // Check if process actually exists
112812
- process.kill(existingPid, 0);
112813
- return {
112814
- content: [
112815
- {
112816
- type: "text",
112817
- text: JSON.stringify({
112818
- success: true,
112819
- data: {
112820
- serviceName: input.serverName,
112821
- status: 'running',
112822
- pid: existingPid,
112823
- cwd: targetPath
112824
- },
112825
- message: `Service '${input.serverName}' is already running locally (pid=${existingPid})`
112826
- }, null, 2)
112827
- }
112828
- ]
112829
- };
112830
- }
112831
- catch (error) {
112832
- // Process doesn't exist, remove from tracking
112833
- runningProcesses.delete(input.serverName);
112681
+ catch (notifyErr) {
112682
+ // Notification failure should not affect deployment flow
112683
+ // Error is already logged in sendDeployNotification
112684
+ }
112685
+ return {
112686
+ content: [
112687
+ {
112688
+ type: "text",
112689
+ text: JSON.stringify({
112690
+ success: true,
112691
+ data: {
112692
+ serviceName: input.serverName,
112693
+ status: 'deployed',
112694
+ deployPath: targetPath,
112695
+ serverType: serverType,
112696
+ cloudbasercGenerated: true
112697
+ },
112698
+ message: `Successfully deployed ${serverType} service '${input.serverName}' from ${targetPath}`
112699
+ }, null, 2)
112834
112700
  }
112701
+ ]
112702
+ };
112703
+ }
112704
+ case 'run': {
112705
+ if (!targetPath) {
112706
+ throw new Error("targetPath is required for run operation");
112707
+ }
112708
+ // Do not support container services locally: basic heuristic - if Dockerfile exists, treat as container
112709
+ const dockerfilePath = path_1.default.join(targetPath, 'Dockerfile');
112710
+ if (fs_1.default.existsSync(dockerfilePath)) {
112711
+ throw new Error("Local run is only supported for function-type CloudRun services. Container services are not supported.");
112712
+ }
112713
+ // Check if this is an Agent project
112714
+ const isAgent = checkIfAgentProject(targetPath);
112715
+ const runMode = input.runOptions?.runMode || (isAgent ? 'agent' : 'normal');
112716
+ // Check if service is already running and verify process exists
112717
+ if (runningProcesses.has(input.serverName)) {
112718
+ const existingPid = runningProcesses.get(input.serverName);
112719
+ try {
112720
+ // Check if process actually exists
112721
+ process.kill(existingPid, 0);
112722
+ return {
112723
+ content: [
112724
+ {
112725
+ type: "text",
112726
+ text: JSON.stringify({
112727
+ success: true,
112728
+ data: {
112729
+ serviceName: input.serverName,
112730
+ status: 'running',
112731
+ pid: existingPid,
112732
+ cwd: targetPath
112733
+ },
112734
+ message: `Service '${input.serverName}' is already running locally (pid=${existingPid})`
112735
+ }, null, 2)
112736
+ }
112737
+ ]
112738
+ };
112835
112739
  }
112836
- const runPort = input.runOptions?.port ?? 3000;
112837
- const extraEnv = input.runOptions?.envParams ?? {};
112838
- // Set environment variables for functions-framework
112839
- const env = {
112840
- ...process.env,
112841
- PORT: String(runPort),
112842
- ...extraEnv,
112843
- // Add functions-framework specific environment variables
112844
- ENABLE_CORS: 'true',
112845
- ALLOWED_ORIGINS: '*'
112846
- };
112847
- // Choose execution method based on run mode
112848
- let child;
112849
- let command;
112850
- if (runMode === 'agent') {
112851
- // For Agent mode, use a different approach since functions-framework doesn't support Agent mode
112852
- // We'll use a custom script that sets up the Agent environment
112853
- command = `node -e "
112740
+ catch (error) {
112741
+ // Process doesn't exist, remove from tracking
112742
+ runningProcesses.delete(input.serverName);
112743
+ }
112744
+ }
112745
+ const runPort = input.runOptions?.port ?? 3000;
112746
+ const extraEnv = input.runOptions?.envParams ?? {};
112747
+ // Set environment variables for functions-framework
112748
+ const env = {
112749
+ ...process.env,
112750
+ PORT: String(runPort),
112751
+ ...extraEnv,
112752
+ // Add functions-framework specific environment variables
112753
+ ENABLE_CORS: 'true',
112754
+ ALLOWED_ORIGINS: '*'
112755
+ };
112756
+ // Choose execution method based on run mode
112757
+ let child;
112758
+ let command;
112759
+ if (runMode === 'agent') {
112760
+ // For Agent mode, use a different approach since functions-framework doesn't support Agent mode
112761
+ // We'll use a custom script that sets up the Agent environment
112762
+ command = `node -e "
112854
112763
  const { runCLI } = require('@cloudbase/functions-framework');
112855
112764
  process.env.PORT = '${runPort}';
112856
112765
  process.env.ENABLE_CORS = 'true';
@@ -112859,16 +112768,16 @@ for await (let x of res.textStream) {
112859
112768
  ${Object.entries(extraEnv).map(([key, value]) => `process.env.${key} = '${value}';`).join('\n')}
112860
112769
  runCLI();
112861
112770
  "`;
112862
- child = (0, child_process_1.spawn)(process.execPath, ['-e', command], {
112863
- cwd: targetPath,
112864
- env,
112865
- stdio: ['ignore', 'pipe', 'pipe'],
112866
- detached: true
112867
- });
112868
- }
112869
- else {
112870
- // Normal function mode
112871
- command = `node -e "
112771
+ child = (0, child_process_1.spawn)(process.execPath, ['-e', command], {
112772
+ cwd: targetPath,
112773
+ env,
112774
+ stdio: ['ignore', 'pipe', 'pipe'],
112775
+ detached: true
112776
+ });
112777
+ }
112778
+ else {
112779
+ // Normal function mode
112780
+ command = `node -e "
112872
112781
  const { runCLI } = require('@cloudbase/functions-framework');
112873
112782
  process.env.PORT = '${runPort}';
112874
112783
  process.env.ENABLE_CORS = 'true';
@@ -112876,182 +112785,167 @@ for await (let x of res.textStream) {
112876
112785
  ${Object.entries(extraEnv).map(([key, value]) => `process.env.${key} = '${value}';`).join('\n')}
112877
112786
  runCLI();
112878
112787
  "`;
112879
- child = (0, child_process_1.spawn)(process.execPath, ['-e', command], {
112880
- cwd: targetPath,
112881
- env,
112882
- stdio: ['ignore', 'pipe', 'pipe'],
112883
- detached: true
112884
- });
112885
- }
112886
- // Handle process exit to clean up tracking
112887
- child.on('exit', (code, signal) => {
112888
- runningProcesses.delete(input.serverName);
112788
+ child = (0, child_process_1.spawn)(process.execPath, ['-e', command], {
112789
+ cwd: targetPath,
112790
+ env,
112791
+ stdio: ['ignore', 'pipe', 'pipe'],
112792
+ detached: true
112889
112793
  });
112890
- child.on('error', (error) => {
112891
- runningProcesses.delete(input.serverName);
112892
- });
112893
- child.unref();
112894
- if (typeof child.pid !== 'number') {
112895
- throw new Error('Failed to start local process: PID is undefined.');
112896
- }
112897
- runningProcesses.set(input.serverName, child.pid);
112898
- return {
112899
- content: [
112900
- {
112901
- type: "text",
112902
- text: JSON.stringify({
112903
- success: true,
112904
- data: {
112905
- serviceName: input.serverName,
112906
- status: 'running',
112907
- pid: child.pid,
112908
- port: runPort,
112909
- runMode: runMode,
112910
- isAgent: isAgent,
112911
- command: command,
112912
- cwd: targetPath
112913
- },
112914
- message: `Started local run for ${runMode} service '${input.serverName}' on port ${runPort} (pid=${child.pid})`
112915
- }, null, 2)
112916
- }
112917
- ]
112918
- };
112919
112794
  }
112920
- case 'download': {
112921
- if (!targetPath) {
112922
- throw new Error("targetPath is required for download operation");
112923
- }
112924
- const result = await cloudrunService.download({
112925
- serverName: input.serverName,
112926
- targetPath: targetPath,
112927
- });
112928
- // Generate cloudbaserc.json configuration file
112929
- const currentEnvId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
112930
- const cloudbasercPath = path_1.default.join(targetPath, 'cloudbaserc.json');
112931
- const cloudbasercContent = {
112932
- envId: currentEnvId,
112933
- cloudrun: {
112934
- name: input.serverName
112795
+ // Handle process exit to clean up tracking
112796
+ child.on('exit', (code, signal) => {
112797
+ runningProcesses.delete(input.serverName);
112798
+ });
112799
+ child.on('error', (error) => {
112800
+ runningProcesses.delete(input.serverName);
112801
+ });
112802
+ child.unref();
112803
+ if (typeof child.pid !== 'number') {
112804
+ throw new Error('Failed to start local process: PID is undefined.');
112805
+ }
112806
+ runningProcesses.set(input.serverName, child.pid);
112807
+ return {
112808
+ content: [
112809
+ {
112810
+ type: "text",
112811
+ text: JSON.stringify({
112812
+ success: true,
112813
+ data: {
112814
+ serviceName: input.serverName,
112815
+ status: 'running',
112816
+ pid: child.pid,
112817
+ port: runPort,
112818
+ runMode: runMode,
112819
+ isAgent: isAgent,
112820
+ command: command,
112821
+ cwd: targetPath
112822
+ },
112823
+ message: `Started local run for ${runMode} service '${input.serverName}' on port ${runPort} (pid=${child.pid})`
112824
+ }, null, 2)
112935
112825
  }
112936
- };
112937
- try {
112938
- fs_1.default.writeFileSync(cloudbasercPath, JSON.stringify(cloudbasercContent, null, 2));
112939
- }
112940
- catch (error) {
112941
- // Ignore cloudbaserc.json creation errors
112942
- }
112943
- return {
112944
- content: [
112945
- {
112946
- type: "text",
112947
- text: JSON.stringify({
112948
- success: true,
112949
- data: {
112950
- serviceName: input.serverName,
112951
- downloadPath: targetPath,
112952
- filesCount: 0,
112953
- cloudbasercGenerated: true
112954
- },
112955
- message: `Successfully downloaded service '${input.serverName}' to ${targetPath}`
112956
- }, null, 2)
112957
- }
112958
- ]
112959
- };
112826
+ ]
112827
+ };
112828
+ }
112829
+ case 'download': {
112830
+ if (!targetPath) {
112831
+ throw new Error("targetPath is required for download operation");
112960
112832
  }
112961
- case 'delete': {
112962
- if (!input.force) {
112963
- return {
112964
- content: [
112965
- {
112966
- type: "text",
112967
- text: JSON.stringify({
112968
- success: false,
112969
- error: "Delete operation requires confirmation",
112970
- message: "Please set force: true to confirm deletion of the service. This action cannot be undone."
112971
- }, null, 2)
112972
- }
112973
- ]
112974
- };
112833
+ const result = await cloudrunService.download({
112834
+ serverName: input.serverName,
112835
+ targetPath: targetPath,
112836
+ });
112837
+ // Generate cloudbaserc.json configuration file
112838
+ const currentEnvId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
112839
+ const cloudbasercPath = path_1.default.join(targetPath, 'cloudbaserc.json');
112840
+ const cloudbasercContent = {
112841
+ envId: currentEnvId,
112842
+ cloudrun: {
112843
+ name: input.serverName
112975
112844
  }
112976
- const result = await cloudrunService.delete({
112977
- serverName: input.serverName,
112978
- });
112979
- return {
112980
- content: [
112981
- {
112982
- type: "text",
112983
- text: JSON.stringify({
112984
- success: true,
112985
- data: {
112986
- serviceName: input.serverName,
112987
- status: 'deleted'
112988
- },
112989
- message: `Successfully deleted service '${input.serverName}'`
112990
- }, null, 2)
112991
- }
112992
- ]
112993
- };
112845
+ };
112846
+ try {
112847
+ fs_1.default.writeFileSync(cloudbasercPath, JSON.stringify(cloudbasercContent, null, 2));
112994
112848
  }
112995
- case 'init': {
112996
- if (!targetPath) {
112997
- throw new Error("targetPath is required for init operation");
112998
- }
112999
- const result = await cloudrunService.init({
113000
- serverName: input.serverName,
113001
- targetPath: targetPath,
113002
- template: input.template,
113003
- });
113004
- // Generate cloudbaserc.json configuration file
113005
- const currentEnvId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
113006
- const cloudbasercPath = path_1.default.join(targetPath, input.serverName, 'cloudbaserc.json');
113007
- const cloudbasercContent = {
113008
- envId: currentEnvId,
113009
- cloudrun: {
113010
- name: input.serverName
112849
+ catch (error) {
112850
+ // Ignore cloudbaserc.json creation errors
112851
+ }
112852
+ return {
112853
+ content: [
112854
+ {
112855
+ type: "text",
112856
+ text: JSON.stringify({
112857
+ success: true,
112858
+ data: {
112859
+ serviceName: input.serverName,
112860
+ downloadPath: targetPath,
112861
+ filesCount: 0,
112862
+ cloudbasercGenerated: true
112863
+ },
112864
+ message: `Successfully downloaded service '${input.serverName}' to ${targetPath}`
112865
+ }, null, 2)
113011
112866
  }
113012
- };
113013
- try {
113014
- fs_1.default.writeFileSync(cloudbasercPath, JSON.stringify(cloudbasercContent, null, 2));
113015
- }
113016
- catch (error) {
113017
- // Ignore cloudbaserc.json creation errors
113018
- }
112867
+ ]
112868
+ };
112869
+ }
112870
+ case 'delete': {
112871
+ if (!input.force) {
113019
112872
  return {
113020
112873
  content: [
113021
112874
  {
113022
112875
  type: "text",
113023
112876
  text: JSON.stringify({
113024
- success: true,
113025
- data: {
113026
- serviceName: input.serverName,
113027
- template: input.template,
113028
- initPath: targetPath,
113029
- projectDir: result.projectDir || path_1.default.join(targetPath, input.serverName),
113030
- cloudbasercGenerated: true
113031
- },
113032
- message: `Successfully initialized service '${input.serverName}' with template '${input.template}' at ${targetPath}`
112877
+ success: false,
112878
+ error: "Delete operation requires confirmation",
112879
+ message: "Please set force: true to confirm deletion of the service. This action cannot be undone."
113033
112880
  }, null, 2)
113034
112881
  }
113035
112882
  ]
113036
112883
  };
113037
112884
  }
113038
- default:
113039
- throw new Error(`Unsupported action: ${input.action}`);
112885
+ const result = await cloudrunService.delete({
112886
+ serverName: input.serverName,
112887
+ });
112888
+ return {
112889
+ content: [
112890
+ {
112891
+ type: "text",
112892
+ text: JSON.stringify({
112893
+ success: true,
112894
+ data: {
112895
+ serviceName: input.serverName,
112896
+ status: 'deleted'
112897
+ },
112898
+ message: `Successfully deleted service '${input.serverName}'`
112899
+ }, null, 2)
112900
+ }
112901
+ ]
112902
+ };
113040
112903
  }
113041
- }
113042
- catch (error) {
113043
- return {
113044
- content: [
113045
- {
113046
- type: "text",
113047
- text: JSON.stringify({
113048
- success: false,
113049
- error: error.message || 'Unknown error occurred',
113050
- message: `Failed to ${args.action} CloudRun service. Please check your permissions and parameters.`
113051
- }, null, 2)
112904
+ case 'init': {
112905
+ if (!targetPath) {
112906
+ throw new Error("targetPath is required for init operation");
112907
+ }
112908
+ const result = await cloudrunService.init({
112909
+ serverName: input.serverName,
112910
+ targetPath: targetPath,
112911
+ template: input.template,
112912
+ });
112913
+ // Generate cloudbaserc.json configuration file
112914
+ const currentEnvId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
112915
+ const cloudbasercPath = path_1.default.join(targetPath, input.serverName, 'cloudbaserc.json');
112916
+ const cloudbasercContent = {
112917
+ envId: currentEnvId,
112918
+ cloudrun: {
112919
+ name: input.serverName
113052
112920
  }
113053
- ]
113054
- };
112921
+ };
112922
+ try {
112923
+ fs_1.default.writeFileSync(cloudbasercPath, JSON.stringify(cloudbasercContent, null, 2));
112924
+ }
112925
+ catch (error) {
112926
+ // Ignore cloudbaserc.json creation errors
112927
+ }
112928
+ return {
112929
+ content: [
112930
+ {
112931
+ type: "text",
112932
+ text: JSON.stringify({
112933
+ success: true,
112934
+ data: {
112935
+ serviceName: input.serverName,
112936
+ template: input.template,
112937
+ initPath: targetPath,
112938
+ projectDir: result.projectDir || path_1.default.join(targetPath, input.serverName),
112939
+ cloudbasercGenerated: true
112940
+ },
112941
+ message: `Successfully initialized service '${input.serverName}' with template '${input.template}' at ${targetPath}`
112942
+ }, null, 2)
112943
+ }
112944
+ ]
112945
+ };
112946
+ }
112947
+ default:
112948
+ throw new Error(`Unsupported action: ${input.action}`);
113055
112949
  }
113056
112950
  });
113057
112951
  }
@@ -125414,7 +125308,6 @@ const cloudbase_manager_js_1 = __webpack_require__(3431);
125414
125308
  const CATEGORY = "cloud-api";
125415
125309
  const ALLOWED_SERVICES = [
125416
125310
  "tcb",
125417
- "flexdb",
125418
125311
  "scf",
125419
125312
  "sts",
125420
125313
  "cam",
@@ -125437,7 +125330,7 @@ function registerCapiTools(server) {
125437
125330
  inputSchema: {
125438
125331
  service: zod_1.z
125439
125332
  .enum(ALLOWED_SERVICES)
125440
- .describe("选择要访问的服务,必须先查看规则/技能确认是否可用。可选:tcb、flexdb、scf、sts、cam、lowcode、cdn、vpc。"),
125333
+ .describe("选择要访问的服务,必须先查看规则/技能确认是否可用。可选:tcb、scf、sts、cam、lowcode、cdn、vpc。"),
125441
125334
  action: zod_1.z
125442
125335
  .string()
125443
125336
  .min(1)
@@ -132403,41 +132296,25 @@ function registerInviteCodeTools(server) {
132403
132296
  ]
132404
132297
  };
132405
132298
  }
132406
- try {
132407
- const manager = await getManager();
132408
- const EnvId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
132409
- const result = await manager.commonService().call({
132410
- Action: 'ActivateInviteCode',
132411
- Param: { InviteCode, EnvId }
132412
- });
132413
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
132414
- return {
132415
- content: [
132416
- {
132417
- type: "text",
132418
- text: JSON.stringify({
132419
- ErrorCode: result?.ErrorCode || '',
132420
- ErrorMsg: result?.ErrorMsg || '',
132421
- RequestId: result?.RequestId || ''
132422
- }, null, 2)
132423
- }
132424
- ]
132425
- };
132426
- }
132427
- catch (e) {
132428
- return {
132429
- content: [
132430
- {
132431
- type: "text",
132432
- text: JSON.stringify({
132433
- ErrorCode: e.code || 'Exception',
132434
- ErrorMsg: '激活失败:' + e.message,
132435
- RequestId: e.RequestId || ''
132436
- }, null, 2)
132437
- }
132438
- ]
132439
- };
132440
- }
132299
+ const manager = await getManager();
132300
+ const EnvId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
132301
+ const result = await manager.commonService().call({
132302
+ Action: 'ActivateInviteCode',
132303
+ Param: { InviteCode, EnvId }
132304
+ });
132305
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
132306
+ return {
132307
+ content: [
132308
+ {
132309
+ type: "text",
132310
+ text: JSON.stringify({
132311
+ ErrorCode: result?.ErrorCode || '',
132312
+ ErrorMsg: result?.ErrorMsg || '',
132313
+ RequestId: result?.RequestId || ''
132314
+ }, null, 2)
132315
+ }
132316
+ ]
132317
+ };
132441
132318
  });
132442
132319
  }
132443
132320
 
@@ -137058,7 +136935,7 @@ class TelemetryReporter {
137058
136935
  const nodeVersion = process.version; // Node.js版本
137059
136936
  const arch = os_1.default.arch(); // 系统架构
137060
136937
  // 从构建时注入的版本号获取MCP版本信息
137061
- const mcpVersion = process.env.npm_package_version || "2.8.0" || 0;
136938
+ const mcpVersion = process.env.npm_package_version || "2.10.0" || 0;
137062
136939
  return {
137063
136940
  userAgent: `${osType} ${osRelease} ${arch} ${nodeVersion} CloudBase-MCP/${mcpVersion}`,
137064
136941
  deviceId: this.deviceId,
@@ -196594,7 +196471,7 @@ function renderHeader(accountInfo, ide) {
196594
196471
  <img class="logo" src="https://7463-tcb-advanced-a656fc-1257967285.tcb.qcloud.la/mcp/cloudbase-logo.svg" alt="CloudBase Logo" />
196595
196472
  <span class="title">CloudBase</span>
196596
196473
  </div>
196597
- ${hasAccount ? `
196474
+ ${(hasAccount && accountInfo.region !== 'ap-singapore') ? /** 国际站不支持切 */ `
196598
196475
  <div class="header-right">
196599
196476
  <div class="account-section">
196600
196477
  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
@@ -196602,6 +196479,7 @@ function renderHeader(accountInfo, ide) {
196602
196479
  <circle cx="12" cy="7" r="4"/>
196603
196480
  </svg>
196604
196481
  <span class="account-uin">${accountInfo.uin}</span>
196482
+ ${accountInfo.region ? `<span class="account-region">${accountInfo.region}</span>` : ''}
196605
196483
  ${!isCodeBuddy ? `
196606
196484
  <button class="btn-switch" onclick="switchAccount()" title="切换账号">
196607
196485
  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
@@ -203629,7 +203507,7 @@ ${envIdSection}
203629
203507
  ## 环境信息
203630
203508
  - 操作系统: ${os_1.default.type()} ${os_1.default.release()}
203631
203509
  - Node.js版本: ${process.version}
203632
- - MCP 版本:${process.env.npm_package_version || "2.8.0" || 0}
203510
+ - MCP 版本:${process.env.npm_package_version || "2.10.0" || 0}
203633
203511
  - 系统架构: ${os_1.default.arch()}
203634
203512
  - 时间: ${new Date().toISOString()}
203635
203513
  - 请求ID: ${requestId}
@@ -211773,9 +211651,10 @@ checkIndex: 检查索引是否存在`),
211773
211651
  title: "修改 NoSQL 数据库结构",
211774
211652
  description: "修改 NoSQL 数据库结构",
211775
211653
  inputSchema: {
211776
- action: zod_1.z.enum(["createCollection", "updateCollection"])
211654
+ action: zod_1.z.enum(["createCollection", "updateCollection", "deleteCollection"])
211777
211655
  .describe(`createCollection: 创建集合
211778
- updateCollection: 更新集合`),
211656
+ updateCollection: 更新集合
211657
+ deleteCollection: 删除集合`),
211779
211658
  collectionName: zod_1.z.string().describe("集合名称"),
211780
211659
  updateOptions: zod_1.z
211781
211660
  .object({
@@ -211802,68 +211681,74 @@ updateCollection: 更新集合`),
211802
211681
  },
211803
211682
  annotations: {
211804
211683
  readOnlyHint: false,
211805
- destructiveHint: false,
211684
+ destructiveHint: true,
211806
211685
  idempotentHint: false,
211807
211686
  openWorldHint: true,
211808
211687
  category: CATEGORY,
211809
211688
  },
211810
211689
  }, async ({ action, collectionName, updateOptions }) => {
211811
- try {
211812
- const cloudbase = await getManager();
211813
- if (action === "createCollection") {
211814
- const result = await cloudbase.database.createCollection(collectionName);
211815
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
211816
- return {
211817
- content: [
211818
- {
211819
- type: "text",
211820
- text: JSON.stringify({
211821
- success: true,
211822
- requestId: result.RequestId,
211823
- action,
211824
- message: "云开发数据库集合创建成功",
211825
- }, null, 2),
211826
- },
211827
- ],
211828
- };
211829
- }
211830
- if (action === "updateCollection") {
211831
- if (!updateOptions) {
211832
- throw new Error("更新集合时必须提供 options");
211833
- }
211834
- const result = await cloudbase.database.updateCollection(collectionName, updateOptions);
211835
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
211836
- return {
211837
- content: [
211838
- {
211839
- type: "text",
211840
- text: JSON.stringify({
211841
- success: true,
211842
- requestId: result.RequestId,
211843
- action,
211844
- message: "云开发数据库集合更新成功",
211845
- }, null, 2),
211846
- },
211847
- ],
211848
- };
211849
- }
211850
- throw new Error(`不支持的操作类型: ${action}`);
211690
+ const cloudbase = await getManager();
211691
+ if (action === "createCollection") {
211692
+ const result = await cloudbase.database.createCollection(collectionName);
211693
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
211694
+ return {
211695
+ content: [
211696
+ {
211697
+ type: "text",
211698
+ text: JSON.stringify({
211699
+ success: true,
211700
+ requestId: result.RequestId,
211701
+ action,
211702
+ message: "云开发数据库集合创建成功",
211703
+ }, null, 2),
211704
+ },
211705
+ ],
211706
+ };
211851
211707
  }
211852
- catch (error) {
211708
+ if (action === "updateCollection") {
211709
+ if (!updateOptions) {
211710
+ throw new Error("更新集合时必须提供 options");
211711
+ }
211712
+ const result = await cloudbase.database.updateCollection(collectionName, updateOptions);
211713
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
211853
211714
  return {
211854
211715
  content: [
211855
211716
  {
211856
211717
  type: "text",
211857
211718
  text: JSON.stringify({
211858
- success: false,
211719
+ success: true,
211720
+ requestId: result.RequestId,
211859
211721
  action,
211860
- error: error.message,
211861
- message: "集合创建/更新操作失败",
211722
+ message: "云开发数据库集合更新成功",
211862
211723
  }, null, 2),
211863
211724
  },
211864
211725
  ],
211865
211726
  };
211866
211727
  }
211728
+ if (action === "deleteCollection") {
211729
+ const result = await cloudbase.database.deleteCollection(collectionName);
211730
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
211731
+ const body = {
211732
+ success: true,
211733
+ requestId: result.RequestId,
211734
+ action,
211735
+ message: result.Exists === false
211736
+ ? "集合不存在"
211737
+ : "云开发数据库集合删除成功",
211738
+ };
211739
+ if (result.Exists === false) {
211740
+ body.exists = false;
211741
+ }
211742
+ return {
211743
+ content: [
211744
+ {
211745
+ type: "text",
211746
+ text: JSON.stringify(body, null, 2),
211747
+ },
211748
+ ],
211749
+ };
211750
+ }
211751
+ throw new Error(`不支持的操作类型: ${action}`);
211867
211752
  });
211868
211753
  // readNoSqlDatabaseContent
211869
211754
  server.registerTool?.("readNoSqlDatabaseContent", {
@@ -211892,53 +211777,36 @@ updateCollection: 更新集合`),
211892
211777
  category: CATEGORY,
211893
211778
  },
211894
211779
  }, async ({ collectionName, query, projection, sort, limit, offset }) => {
211895
- try {
211896
- const cloudbase = await getManager();
211897
- const instanceId = await getDatabaseInstanceId(getManager);
211898
- // 兼容对象和字符串
211899
- const toJSONString = (v) => typeof v === "object" && v !== null ? JSON.stringify(v) : v;
211900
- const result = await cloudbase.commonService("flexdb").call({
211901
- Action: "Query",
211902
- Param: {
211903
- TableName: collectionName,
211904
- MgoQuery: toJSONString(query),
211905
- MgoProjection: toJSONString(projection),
211906
- MgoSort: toJSONString(sort),
211907
- MgoLimit: limit ?? 100, // 默认返回100条,避免底层SDK缺参报错
211908
- MgoOffset: offset,
211909
- Tag: instanceId,
211780
+ const cloudbase = await getManager();
211781
+ const instanceId = await getDatabaseInstanceId(getManager);
211782
+ const toJSONString = (v) => typeof v === "object" && v !== null ? JSON.stringify(v) : v;
211783
+ const result = await cloudbase.commonService("tcb", "2018-06-08").call({
211784
+ Action: "QueryRecords",
211785
+ Param: {
211786
+ TableName: collectionName,
211787
+ MgoQuery: toJSONString(query),
211788
+ MgoProjection: toJSONString(projection),
211789
+ MgoSort: toJSONString(sort),
211790
+ MgoLimit: limit ?? 100,
211791
+ MgoOffset: offset,
211792
+ Tag: instanceId,
211793
+ },
211794
+ });
211795
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
211796
+ return {
211797
+ content: [
211798
+ {
211799
+ type: "text",
211800
+ text: JSON.stringify({
211801
+ success: true,
211802
+ requestId: result.RequestId,
211803
+ data: result.Data,
211804
+ pager: result.Pager,
211805
+ message: "文档查询成功",
211806
+ }, null, 2),
211910
211807
  },
211911
- });
211912
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
211913
- return {
211914
- content: [
211915
- {
211916
- type: "text",
211917
- text: JSON.stringify({
211918
- success: true,
211919
- requestId: result.RequestId,
211920
- data: result.Data,
211921
- pager: result.Pager,
211922
- message: "文档查询成功",
211923
- }, null, 2),
211924
- },
211925
- ],
211926
- };
211927
- }
211928
- catch (error) {
211929
- return {
211930
- content: [
211931
- {
211932
- type: "text",
211933
- text: JSON.stringify({
211934
- success: false,
211935
- error: error.message,
211936
- message: "文档查询失败",
211937
- }, null, 2),
211938
- },
211939
- ],
211940
- };
211941
- }
211808
+ ],
211809
+ };
211942
211810
  });
211943
211811
  // writeNoSqlDatabaseContent
211944
211812
  server.registerTool?.("writeNoSqlDatabaseContent", {
@@ -211946,9 +211814,7 @@ updateCollection: 更新集合`),
211946
211814
  description: "修改 NoSQL 数据库数据记录",
211947
211815
  inputSchema: {
211948
211816
  action: zod_1.z.enum(["insert", "update", "delete"])
211949
- .describe(`createCollection: 创建数据
211950
- updateCollection: 更新数据
211951
- deleteCollection: 删除数据`),
211817
+ .describe(`insert: 插入数据(新增文档)\nupdate: 更新数据\ndelete: 删除数据`),
211952
211818
  collectionName: zod_1.z.string().describe("集合名称"),
211953
211819
  documents: zod_1.z
211954
211820
  .array(zod_1.z.object({}).passthrough())
@@ -212047,98 +211913,70 @@ deleteCollection: 删除数据`),
212047
211913
  });
212048
211914
  }
212049
211915
  async function insertDocuments({ collectionName, documents, getManager, logger, }) {
212050
- try {
212051
- const cloudbase = await getManager();
212052
- const instanceId = await getDatabaseInstanceId(getManager);
212053
- // 将对象数组序列化为字符串数组
212054
- const docsAsStrings = documents.map((doc) => JSON.stringify(doc));
212055
- const result = await cloudbase.commonService("flexdb").call({
212056
- Action: "PutItem",
212057
- Param: {
212058
- TableName: collectionName,
212059
- MgoDocs: docsAsStrings,
212060
- Tag: instanceId,
212061
- },
212062
- });
212063
- (0, cloudbase_manager_js_1.logCloudBaseResult)(logger, result);
212064
- return JSON.stringify({
212065
- success: true,
212066
- requestId: result.RequestId,
212067
- insertedIds: result.InsertedIds,
212068
- message: "文档插入成功",
212069
- }, null, 2);
212070
- }
212071
- catch (error) {
212072
- return JSON.stringify({
212073
- success: false,
212074
- error: error.message,
212075
- message: "文档插入失败",
212076
- }, null, 2);
212077
- }
211916
+ const cloudbase = await getManager();
211917
+ const instanceId = await getDatabaseInstanceId(getManager);
211918
+ const docsAsStrings = documents.map((doc) => JSON.stringify(doc));
211919
+ const result = await cloudbase.commonService("tcb", "2018-06-08").call({
211920
+ Action: "PutItem",
211921
+ Param: {
211922
+ TableName: collectionName,
211923
+ MgoDocs: docsAsStrings,
211924
+ Tag: instanceId,
211925
+ },
211926
+ });
211927
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(logger, result);
211928
+ return JSON.stringify({
211929
+ success: true,
211930
+ requestId: result.RequestId,
211931
+ insertedIds: result.InsertedIds,
211932
+ message: "文档插入成功",
211933
+ }, null, 2);
212078
211934
  }
212079
211935
  async function updateDocuments({ collectionName, query, update, isMulti, upsert, getManager, logger, }) {
212080
- try {
212081
- const cloudbase = await getManager();
212082
- const instanceId = await getDatabaseInstanceId(getManager);
212083
- const toJSONString = (v) => typeof v === "object" && v !== null ? JSON.stringify(v) : v;
212084
- const result = await cloudbase.commonService("flexdb").call({
212085
- Action: "UpdateItem",
212086
- Param: {
212087
- TableName: collectionName,
212088
- MgoQuery: toJSONString(query),
212089
- MgoUpdate: toJSONString(update),
212090
- MgoIsMulti: isMulti,
212091
- MgoUpsert: upsert,
212092
- Tag: instanceId,
212093
- },
212094
- });
212095
- (0, cloudbase_manager_js_1.logCloudBaseResult)(logger, result);
212096
- return JSON.stringify({
212097
- success: true,
212098
- requestId: result.RequestId,
212099
- modifiedCount: result.ModifiedNum,
212100
- matchedCount: result.MatchedNum,
212101
- upsertedId: result.UpsertedId,
212102
- message: "文档更新成功",
212103
- }, null, 2);
212104
- }
212105
- catch (error) {
212106
- return JSON.stringify({
212107
- success: false,
212108
- error: error.message,
212109
- message: "文档更新失败",
212110
- }, null, 2);
212111
- }
211936
+ const cloudbase = await getManager();
211937
+ const instanceId = await getDatabaseInstanceId(getManager);
211938
+ const toJSONString = (v) => typeof v === "object" && v !== null ? JSON.stringify(v) : v;
211939
+ const result = await cloudbase.commonService("tcb", "2018-06-08").call({
211940
+ Action: "UpdateItem",
211941
+ Param: {
211942
+ TableName: collectionName,
211943
+ MgoQuery: toJSONString(query),
211944
+ MgoUpdate: toJSONString(update),
211945
+ MgoIsMulti: isMulti,
211946
+ MgoUpsert: upsert,
211947
+ Tag: instanceId,
211948
+ },
211949
+ });
211950
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(logger, result);
211951
+ return JSON.stringify({
211952
+ success: true,
211953
+ requestId: result.RequestId,
211954
+ modifiedCount: result.ModifiedNum,
211955
+ matchedCount: result.MatchedNum,
211956
+ upsertedId: result.UpsertedId,
211957
+ message: "文档更新成功",
211958
+ }, null, 2);
212112
211959
  }
212113
211960
  async function deleteDocuments({ collectionName, query, isMulti, getManager, logger, }) {
212114
- try {
212115
- const cloudbase = await getManager();
212116
- const instanceId = await getDatabaseInstanceId(getManager);
212117
- const toJSONString = (v) => typeof v === "object" && v !== null ? JSON.stringify(v) : v;
212118
- const result = await cloudbase.commonService("flexdb").call({
212119
- Action: "DeleteItem",
212120
- Param: {
212121
- TableName: collectionName,
212122
- MgoQuery: toJSONString(query),
212123
- MgoIsMulti: isMulti,
212124
- Tag: instanceId,
212125
- },
212126
- });
212127
- (0, cloudbase_manager_js_1.logCloudBaseResult)(logger, result);
212128
- return JSON.stringify({
212129
- success: true,
212130
- requestId: result.RequestId,
212131
- deleted: result.Deleted,
212132
- message: "文档删除成功",
212133
- }, null, 2);
212134
- }
212135
- catch (error) {
212136
- return JSON.stringify({
212137
- success: false,
212138
- error: error.message,
212139
- message: "文档删除失败",
212140
- }, null, 2);
212141
- }
211961
+ const cloudbase = await getManager();
211962
+ const instanceId = await getDatabaseInstanceId(getManager);
211963
+ const toJSONString = (v) => typeof v === "object" && v !== null ? JSON.stringify(v) : v;
211964
+ const result = await cloudbase.commonService("tcb", "2018-06-08").call({
211965
+ Action: "DeleteItem",
211966
+ Param: {
211967
+ TableName: collectionName,
211968
+ MgoQuery: toJSONString(query),
211969
+ MgoIsMulti: isMulti,
211970
+ Tag: instanceId,
211971
+ },
211972
+ });
211973
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(logger, result);
211974
+ return JSON.stringify({
211975
+ success: true,
211976
+ requestId: result.RequestId,
211977
+ deleted: result.Deleted,
211978
+ message: "文档删除成功",
211979
+ }, null, 2);
212142
211980
  }
212143
211981
 
212144
211982
 
@@ -218385,15 +218223,14 @@ function registerSetupTools(server) {
218385
218223
  title: "下载项目模板",
218386
218224
  description: `自动下载并部署CloudBase项目模板。⚠️ **MANDATORY FOR NEW PROJECTS** ⚠️
218387
218225
 
218388
- **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- 其他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.8.0" : 0}),便于后续维护和版本追踪\n- 下载 rules 模板时,如果项目中已存在 README.md 文件,系统会自动保护该文件不被覆盖(除非设置 overwrite=true)`,
218226
+ **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- 其他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.10.0" : 0}),便于后续维护和版本追踪\n- 下载 rules 模板时,如果项目中已存在 README.md 文件,系统会自动保护该文件不被覆盖(除非设置 overwrite=true)`,
218389
218227
  inputSchema: {
218390
218228
  template: zod_1.z
218391
218229
  .enum(["react", "vue", "miniprogram", "uniapp", "rules"])
218392
218230
  .describe("要下载的模板类型"),
218393
218231
  ide: zod_1.z
218394
218232
  .enum(IDE_TYPES)
218395
- .optional()
218396
- .describe("指定要下载的IDE类型。如果未指定,会根据 INTEGRATION_IDE 环境变量自动选择对应的IDE配置;如果环境变量也未设置,则必须传入此参数"),
218233
+ .describe("指定要下载的IDE类型。"),
218397
218234
  overwrite: zod_1.z
218398
218235
  .boolean()
218399
218236
  .optional()
@@ -218408,7 +218245,7 @@ function registerSetupTools(server) {
218408
218245
  },
218409
218246
  }, async ({ template, ide, overwrite = false, }) => {
218410
218247
  try {
218411
- const ideResolution = resolveDownloadTemplateIDE(ide, process.env.INTEGRATION_IDE);
218248
+ const ideResolution = resolveDownloadTemplateIDE(ide, undefined);
218412
218249
  if (!ideResolution.ok) {
218413
218250
  const supportedIDEs = ideResolution.supportedIDEs.join(", ");
218414
218251
  if (ideResolution.reason === "unmapped_integration_ide") {
@@ -219682,6 +219519,7 @@ exports.getLoginState = getLoginState;
219682
219519
  exports.logout = logout;
219683
219520
  const toolbox_1 = __webpack_require__(25901);
219684
219521
  const logger_js_1 = __webpack_require__(13039);
219522
+ const tencet_cloud_js_1 = __webpack_require__(95018);
219685
219523
  const auth = toolbox_1.AuthSupevisor.getInstance({});
219686
219524
  async function getLoginState(options) {
219687
219525
  const { TENCENTCLOUD_SECRETID, TENCENTCLOUD_SECRETKEY, TENCENTCLOUD_SESSIONTOKEN, } = process.env;
@@ -219699,9 +219537,10 @@ async function getLoginState(options) {
219699
219537
  }
219700
219538
  const loginState = await auth.getLoginState();
219701
219539
  if (!loginState) {
219702
- await auth.loginByWebAuth(options?.fromCloudBaseLoginPage
219540
+ await auth.loginByWebAuth((options?.fromCloudBaseLoginPage && !(0, tencet_cloud_js_1.isInternationalRegion)(options?.region))
219703
219541
  ? {
219704
219542
  getAuthUrl: (url) => {
219543
+ // 国际站
219705
219544
  const separator = url.includes('?') ? '&' : '?';
219706
219545
  const urlWithParam = `${url}${separator}allowNoEnv=true`;
219707
219546
  return `https://tcb.cloud.tencent.com/login?_redirect_uri=${encodeURIComponent(urlWithParam)}`;
@@ -219709,6 +219548,9 @@ async function getLoginState(options) {
219709
219548
  }
219710
219549
  : {
219711
219550
  getAuthUrl: (url) => {
219551
+ if ((0, tencet_cloud_js_1.isInternationalRegion)(options?.region)) {
219552
+ url = url.replace('cloud.tencent.com', 'tencentcloud.com');
219553
+ }
219712
219554
  const separator = url.includes('?') ? '&' : '?';
219713
219555
  return `${url}${separator}allowNoEnv=true`;
219714
219556
  },
@@ -256605,7 +256447,7 @@ class InteractiveServer {
256605
256447
  IsVisible: false,
256606
256448
  Channels: ["dcloud", "iotenable", "tem", "scene_module"],
256607
256449
  };
256608
- envResult = await sessionData.manager.commonService("tcb").call({
256450
+ envResult = await sessionData.manager.commonService("tcb", "2018-06-08").call({
256609
256451
  Action: "DescribeEnvs",
256610
256452
  Param: queryParams,
256611
256453
  });
@@ -265452,94 +265294,78 @@ function registerStorageTools(server) {
265452
265294
  category: "storage"
265453
265295
  }
265454
265296
  }, async (args) => {
265455
- try {
265456
- const input = args;
265457
- const manager = await getManager();
265458
- if (!manager) {
265459
- throw new Error("Failed to initialize CloudBase manager. Please check your credentials and environment configuration.");
265460
- }
265461
- const storageService = manager.storage;
265462
- switch (input.action) {
265463
- case 'list': {
265464
- const result = await storageService.listDirectoryFiles(input.cloudPath);
265465
- return {
265466
- content: [
265467
- {
265468
- type: "text",
265469
- text: JSON.stringify({
265470
- success: true,
265471
- data: {
265472
- action: 'list',
265473
- cloudPath: input.cloudPath,
265474
- files: result || [],
265475
- totalCount: result?.length || 0
265476
- },
265477
- message: `Successfully listed ${result?.length || 0} files in directory '${input.cloudPath}'`
265478
- }, null, 2)
265479
- }
265480
- ]
265481
- };
265482
- }
265483
- case 'info': {
265484
- const result = await storageService.getFileInfo(input.cloudPath);
265485
- return {
265486
- content: [
265487
- {
265488
- type: "text",
265489
- text: JSON.stringify({
265490
- success: true,
265491
- data: {
265492
- action: 'info',
265493
- cloudPath: input.cloudPath,
265494
- fileInfo: result
265495
- },
265496
- message: `Successfully retrieved file info for '${input.cloudPath}'`
265497
- }, null, 2)
265498
- }
265499
- ]
265500
- };
265501
- }
265502
- case 'url': {
265503
- const result = await storageService.getTemporaryUrl([{
265504
- cloudPath: input.cloudPath,
265505
- maxAge: input.maxAge || 3600
265506
- }]);
265507
- return {
265508
- content: [
265509
- {
265510
- type: "text",
265511
- text: JSON.stringify({
265512
- success: true,
265513
- data: {
265514
- action: 'url',
265515
- cloudPath: input.cloudPath,
265516
- temporaryUrl: result[0]?.url || "",
265517
- expireTime: `${input.maxAge || 3600}秒`,
265518
- fileId: result[0]?.fileId || ""
265519
- },
265520
- message: `Successfully generated temporary URL for '${input.cloudPath}'`
265521
- }, null, 2)
265522
- }
265523
- ]
265524
- };
265525
- }
265526
- default:
265527
- throw new Error(`Unsupported action: ${input.action}`);
265297
+ const input = args;
265298
+ const manager = await getManager();
265299
+ if (!manager) {
265300
+ throw new Error("Failed to initialize CloudBase manager. Please check your credentials and environment configuration.");
265301
+ }
265302
+ const storageService = manager.storage;
265303
+ switch (input.action) {
265304
+ case 'list': {
265305
+ const result = await storageService.listDirectoryFiles(input.cloudPath);
265306
+ return {
265307
+ content: [
265308
+ {
265309
+ type: "text",
265310
+ text: JSON.stringify({
265311
+ success: true,
265312
+ data: {
265313
+ action: 'list',
265314
+ cloudPath: input.cloudPath,
265315
+ files: result || [],
265316
+ totalCount: result?.length || 0
265317
+ },
265318
+ message: `Successfully listed ${result?.length || 0} files in directory '${input.cloudPath}'`
265319
+ }, null, 2)
265320
+ }
265321
+ ]
265322
+ };
265528
265323
  }
265529
- }
265530
- catch (error) {
265531
- return {
265532
- content: [
265533
- {
265534
- type: "text",
265535
- text: JSON.stringify({
265536
- success: false,
265537
- error: error.message || 'Unknown error occurred',
265538
- message: `Failed to query storage information. Please check your permissions and parameters.`
265539
- }, null, 2)
265540
- }
265541
- ]
265542
- };
265324
+ case 'info': {
265325
+ const result = await storageService.getFileInfo(input.cloudPath);
265326
+ return {
265327
+ content: [
265328
+ {
265329
+ type: "text",
265330
+ text: JSON.stringify({
265331
+ success: true,
265332
+ data: {
265333
+ action: 'info',
265334
+ cloudPath: input.cloudPath,
265335
+ fileInfo: result
265336
+ },
265337
+ message: `Successfully retrieved file info for '${input.cloudPath}'`
265338
+ }, null, 2)
265339
+ }
265340
+ ]
265341
+ };
265342
+ }
265343
+ case 'url': {
265344
+ const result = await storageService.getTemporaryUrl([{
265345
+ cloudPath: input.cloudPath,
265346
+ maxAge: input.maxAge || 3600
265347
+ }]);
265348
+ return {
265349
+ content: [
265350
+ {
265351
+ type: "text",
265352
+ text: JSON.stringify({
265353
+ success: true,
265354
+ data: {
265355
+ action: 'url',
265356
+ cloudPath: input.cloudPath,
265357
+ temporaryUrl: result[0]?.url || "",
265358
+ expireTime: `${input.maxAge || 3600}秒`,
265359
+ fileId: result[0]?.fileId || ""
265360
+ },
265361
+ message: `Successfully generated temporary URL for '${input.cloudPath}'`
265362
+ }, null, 2)
265363
+ }
265364
+ ]
265365
+ };
265366
+ }
265367
+ default:
265368
+ throw new Error(`Unsupported action: ${input.action}`);
265543
265369
  }
265544
265370
  });
265545
265371
  // Tool 2: manageStorage - 管理存储文件(写操作)
@@ -265555,151 +265381,128 @@ function registerStorageTools(server) {
265555
265381
  category: "storage"
265556
265382
  }
265557
265383
  }, async (args) => {
265558
- try {
265559
- const input = args;
265560
- const manager = await getManager();
265561
- if (!manager) {
265562
- throw new Error("Failed to initialize CloudBase manager. Please check your credentials and environment configuration.");
265563
- }
265564
- const storageService = manager.storage;
265565
- switch (input.action) {
265566
- case 'upload': {
265567
- if (input.isDirectory) {
265568
- // 上传目录
265569
- await storageService.uploadDirectory({
265570
- localPath: input.localPath,
265571
- cloudPath: input.cloudPath,
265572
- onProgress: (progressData) => {
265573
- console.log("Upload directory progress:", progressData);
265574
- }
265575
- });
265576
- }
265577
- else {
265578
- // 上传文件
265579
- await storageService.uploadFile({
265580
- localPath: input.localPath,
265581
- cloudPath: input.cloudPath,
265582
- onProgress: (progressData) => {
265583
- console.log("Upload file progress:", progressData);
265584
- }
265585
- });
265586
- }
265587
- // 获取文件临时下载地址
265588
- const fileUrls = await storageService.getTemporaryUrl([{
265589
- cloudPath: input.cloudPath,
265590
- maxAge: 3600 // 临时链接有效期1小时
265591
- }]);
265592
- return {
265593
- content: [
265594
- {
265595
- type: "text",
265596
- text: JSON.stringify({
265597
- success: true,
265598
- data: {
265599
- action: 'upload',
265600
- localPath: input.localPath,
265601
- cloudPath: input.cloudPath,
265602
- isDirectory: input.isDirectory,
265603
- temporaryUrl: fileUrls[0]?.url || "",
265604
- expireTime: "1小时"
265605
- },
265606
- message: `Successfully uploaded ${input.isDirectory ? 'directory' : 'file'} from '${input.localPath}' to '${input.cloudPath}'`
265607
- }, null, 2)
265608
- }
265609
- ]
265610
- };
265384
+ const input = args;
265385
+ const manager = await getManager();
265386
+ if (!manager) {
265387
+ throw new Error("Failed to initialize CloudBase manager. Please check your credentials and environment configuration.");
265388
+ }
265389
+ const storageService = manager.storage;
265390
+ switch (input.action) {
265391
+ case 'upload': {
265392
+ if (input.isDirectory) {
265393
+ await storageService.uploadDirectory({
265394
+ localPath: input.localPath,
265395
+ cloudPath: input.cloudPath,
265396
+ onProgress: (progressData) => {
265397
+ console.log("Upload directory progress:", progressData);
265398
+ }
265399
+ });
265611
265400
  }
265612
- case 'download': {
265613
- if (input.isDirectory) {
265614
- // 下载目录
265615
- await storageService.downloadDirectory({
265616
- cloudPath: input.cloudPath,
265617
- localPath: input.localPath
265618
- });
265619
- }
265620
- else {
265621
- // 下载文件
265622
- await storageService.downloadFile({
265623
- cloudPath: input.cloudPath,
265624
- localPath: input.localPath
265625
- });
265626
- }
265627
- return {
265628
- content: [
265629
- {
265630
- type: "text",
265631
- text: JSON.stringify({
265632
- success: true,
265633
- data: {
265634
- action: 'download',
265635
- cloudPath: input.cloudPath,
265636
- localPath: input.localPath,
265637
- isDirectory: input.isDirectory
265638
- },
265639
- message: `Successfully downloaded ${input.isDirectory ? 'directory' : 'file'} from '${input.cloudPath}' to '${input.localPath}'`
265640
- }, null, 2)
265641
- }
265642
- ]
265643
- };
265401
+ else {
265402
+ await storageService.uploadFile({
265403
+ localPath: input.localPath,
265404
+ cloudPath: input.cloudPath,
265405
+ onProgress: (progressData) => {
265406
+ console.log("Upload file progress:", progressData);
265407
+ }
265408
+ });
265644
265409
  }
265645
- case 'delete': {
265646
- if (!input.force) {
265647
- return {
265648
- content: [
265649
- {
265650
- type: "text",
265651
- text: JSON.stringify({
265652
- success: false,
265653
- error: "Delete operation requires confirmation",
265654
- message: "Please set force: true to confirm deletion. This action cannot be undone."
265655
- }, null, 2)
265656
- }
265657
- ]
265658
- };
265659
- }
265660
- if (input.isDirectory) {
265661
- // 删除目录
265662
- await storageService.deleteDirectory(input.cloudPath);
265663
- }
265664
- else {
265665
- // 删除文件
265666
- await storageService.deleteFile([input.cloudPath]);
265667
- }
265410
+ const fileUrls = await storageService.getTemporaryUrl([{
265411
+ cloudPath: input.cloudPath,
265412
+ maxAge: 3600
265413
+ }]);
265414
+ return {
265415
+ content: [
265416
+ {
265417
+ type: "text",
265418
+ text: JSON.stringify({
265419
+ success: true,
265420
+ data: {
265421
+ action: 'upload',
265422
+ localPath: input.localPath,
265423
+ cloudPath: input.cloudPath,
265424
+ isDirectory: input.isDirectory,
265425
+ temporaryUrl: fileUrls[0]?.url || "",
265426
+ expireTime: "1小时"
265427
+ },
265428
+ message: `Successfully uploaded ${input.isDirectory ? 'directory' : 'file'} from '${input.localPath}' to '${input.cloudPath}'`
265429
+ }, null, 2)
265430
+ }
265431
+ ]
265432
+ };
265433
+ }
265434
+ case 'download': {
265435
+ if (input.isDirectory) {
265436
+ await storageService.downloadDirectory({
265437
+ cloudPath: input.cloudPath,
265438
+ localPath: input.localPath
265439
+ });
265440
+ }
265441
+ else {
265442
+ await storageService.downloadFile({
265443
+ cloudPath: input.cloudPath,
265444
+ localPath: input.localPath
265445
+ });
265446
+ }
265447
+ return {
265448
+ content: [
265449
+ {
265450
+ type: "text",
265451
+ text: JSON.stringify({
265452
+ success: true,
265453
+ data: {
265454
+ action: 'download',
265455
+ cloudPath: input.cloudPath,
265456
+ localPath: input.localPath,
265457
+ isDirectory: input.isDirectory
265458
+ },
265459
+ message: `Successfully downloaded ${input.isDirectory ? 'directory' : 'file'} from '${input.cloudPath}' to '${input.localPath}'`
265460
+ }, null, 2)
265461
+ }
265462
+ ]
265463
+ };
265464
+ }
265465
+ case 'delete': {
265466
+ if (!input.force) {
265668
265467
  return {
265669
265468
  content: [
265670
265469
  {
265671
265470
  type: "text",
265672
265471
  text: JSON.stringify({
265673
- success: true,
265674
- data: {
265675
- action: 'delete',
265676
- cloudPath: input.cloudPath,
265677
- isDirectory: input.isDirectory,
265678
- deleted: true
265679
- },
265680
- message: `Successfully deleted ${input.isDirectory ? 'directory' : 'file'} '${input.cloudPath}'`
265472
+ success: false,
265473
+ error: "Delete operation requires confirmation",
265474
+ message: "Please set force: true to confirm deletion. This action cannot be undone."
265681
265475
  }, null, 2)
265682
265476
  }
265683
265477
  ]
265684
265478
  };
265685
265479
  }
265686
- default:
265687
- throw new Error(`Unsupported action: ${input.action}`);
265480
+ if (input.isDirectory) {
265481
+ await storageService.deleteDirectory(input.cloudPath);
265482
+ }
265483
+ else {
265484
+ await storageService.deleteFile([input.cloudPath]);
265485
+ }
265486
+ return {
265487
+ content: [
265488
+ {
265489
+ type: "text",
265490
+ text: JSON.stringify({
265491
+ success: true,
265492
+ data: {
265493
+ action: 'delete',
265494
+ cloudPath: input.cloudPath,
265495
+ isDirectory: input.isDirectory,
265496
+ deleted: true
265497
+ },
265498
+ message: `Successfully deleted ${input.isDirectory ? 'directory' : 'file'} '${input.cloudPath}'`
265499
+ }, null, 2)
265500
+ }
265501
+ ]
265502
+ };
265688
265503
  }
265689
- }
265690
- catch (error) {
265691
- return {
265692
- content: [
265693
- {
265694
- type: "text",
265695
- text: JSON.stringify({
265696
- success: false,
265697
- error: error.message || 'Unknown error occurred',
265698
- message: `Failed to manage storage. Please check your permissions and parameters.`
265699
- }, null, 2)
265700
- }
265701
- ]
265702
- };
265504
+ default:
265505
+ throw new Error(`Unsupported action: ${input.action}`);
265703
265506
  }
265704
265507
  });
265705
265508
  }
@@ -266628,6 +266431,27 @@ function pauseStreams (streams, options) {
266628
266431
  }
266629
266432
 
266630
266433
 
266434
+ /***/ }),
266435
+
266436
+ /***/ 95018:
266437
+ /***/ ((__unused_webpack_module, exports) => {
266438
+
266439
+ "use strict";
266440
+
266441
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
266442
+ exports.isInternationalRegion = void 0;
266443
+ exports.isValidRegion = isValidRegion;
266444
+ const REGION = {
266445
+ SHANGHAI: 'ap-shanghai',
266446
+ SINGAPORE: 'ap-singapore',
266447
+ };
266448
+ const isInternationalRegion = (region) => region === REGION.SINGAPORE;
266449
+ exports.isInternationalRegion = isInternationalRegion;
266450
+ function isValidRegion(region) {
266451
+ return Object.values(REGION).includes(region);
266452
+ }
266453
+
266454
+
266631
266455
  /***/ }),
266632
266456
 
266633
266457
  /***/ 95026: