@cloudbase/cloudbase-mcp 2.9.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.
Files changed (4) hide show
  1. package/dist/cli.cjs +3 -3
  2. package/dist/index.cjs +1404 -1658
  3. package/dist/index.js +1416 -1670
  4. package/package.json +1 -1
package/dist/index.cjs CHANGED
@@ -35573,90 +35573,70 @@ function registerSecurityRuleTools(server) {
35573
35573
  },
35574
35574
  }, async ({ resourceType, resourceId }) => {
35575
35575
  const envId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
35576
- try {
35577
- const cloudbase = await getManager();
35578
- let result;
35579
- if (resourceType === "noSqlDatabase") {
35580
- // 查询数据库安全规则
35581
- result = await cloudbase.commonService().call({
35582
- Action: "DescribeSafeRule",
35583
- Param: {
35584
- CollectionName: resourceId,
35585
- EnvId: envId,
35586
- },
35587
- });
35588
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
35589
- }
35590
- else if (resourceType === "function") {
35591
- // 查询云函数安全规则
35592
- result = await cloudbase.commonService().call({
35593
- Action: "DescribeSecurityRule",
35594
- Param: {
35595
- ResourceType: "FUNCTION",
35596
- EnvId: envId,
35597
- },
35598
- });
35599
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
35600
- }
35601
- else if (resourceType === "storage") {
35602
- // 查询存储安全规则
35603
- result = await cloudbase.commonService().call({
35604
- Action: "DescribeStorageSafeRule",
35605
- Param: {
35606
- Bucket: resourceId,
35607
- EnvId: envId,
35608
- },
35609
- });
35610
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
35611
- }
35612
- else if (resourceType === "sqlDatabase") {
35613
- // TODO: 考虑是否有支持指定其他 instance、schema 的需求
35614
- const instanceId = "default";
35615
- const schema = envId;
35616
- const tableName = resourceId;
35617
- result = await cloudbase.commonService("lowcode").call({
35618
- Action: "DescribeDataSourceBasicPolicy",
35619
- Param: {
35620
- EnvId: envId,
35621
- ResourceType: "table",
35622
- ResourceId: `${instanceId}#${schema}#${tableName}`,
35623
- RoleIdentityList: ["allUser"],
35624
- },
35625
- });
35626
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
35627
- }
35628
- else {
35629
- throw new Error(`不支持的资源类型: ${resourceType}`);
35630
- }
35631
- return {
35632
- content: [
35633
- {
35634
- type: "text",
35635
- text: JSON.stringify({
35636
- success: true,
35637
- aclTag: result.AclTag,
35638
- rule: result.Rule ?? null,
35639
- raw: result,
35640
- message: "安全规则读取成功",
35641
- }, null, 2),
35642
- },
35643
- ],
35644
- };
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);
35645
35587
  }
35646
- catch (error) {
35647
- return {
35648
- content: [
35649
- {
35650
- type: "text",
35651
- text: JSON.stringify({
35652
- success: false,
35653
- error: error.message,
35654
- message: "安全规则读取失败",
35655
- }, null, 2),
35656
- },
35657
- ],
35658
- };
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);
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}`);
35659
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
+ };
35660
35640
  });
35661
35641
  // 写入安全规则 Tool
35662
35642
  server.registerTool?.(exports.WRITE_SECURITY_RULE, {
@@ -35683,154 +35663,138 @@ function registerSecurityRuleTools(server) {
35683
35663
  category: "security-rule",
35684
35664
  },
35685
35665
  }, async ({ resourceType, resourceId, aclTag, rule }) => {
35686
- try {
35687
- const cloudbase = await getManager();
35688
- const envId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
35689
- let result;
35690
- if (resourceType === "noSqlDatabase") {
35691
- if (aclTag === "CUSTOM") {
35692
- if (!rule)
35693
- throw new Error("noSQL 数据库自定义安全规则(CUSTOM)必须提供 rule 字段");
35694
- result = await cloudbase.commonService().call({
35695
- Action: "ModifySafeRule",
35696
- Param: {
35697
- CollectionName: resourceId,
35698
- EnvId: envId,
35699
- AclTag: aclTag,
35700
- Rule: rule,
35701
- },
35702
- });
35703
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
35704
- }
35705
- else {
35706
- result = await cloudbase.commonService().call({
35707
- Action: "ModifyDatabaseACL",
35708
- Param: {
35709
- CollectionName: resourceId,
35710
- EnvId: envId,
35711
- AclTag: aclTag,
35712
- },
35713
- });
35714
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
35715
- }
35716
- }
35717
- else if (resourceType === "function") {
35718
- if (aclTag !== "CUSTOM")
35719
- 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") {
35720
35671
  if (!rule)
35721
- throw new Error("云函数自定义安全规则(CUSTOM)必须提供 rule 字段");
35672
+ throw new Error("noSQL 数据库自定义安全规则(CUSTOM)必须提供 rule 字段");
35722
35673
  result = await cloudbase.commonService().call({
35723
- Action: "ModifySecurityRule",
35674
+ Action: "ModifySafeRule",
35724
35675
  Param: {
35725
- AclTag: aclTag,
35676
+ CollectionName: resourceId,
35726
35677
  EnvId: envId,
35727
- ResourceType: "FUNCTION",
35678
+ AclTag: aclTag,
35728
35679
  Rule: rule,
35729
35680
  },
35730
35681
  });
35731
35682
  (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
35732
35683
  }
35733
- else if (resourceType === "storage") {
35734
- if (aclTag === "CUSTOM") {
35735
- if (!rule)
35736
- throw new Error("存储自定义安全规则(CUSTOM)必须提供 rule 字段");
35737
- result = await cloudbase.commonService().call({
35738
- Action: "ModifyStorageSafeRule",
35739
- Param: {
35740
- Bucket: resourceId,
35741
- EnvId: envId,
35742
- AclTag: aclTag,
35743
- Rule: rule,
35744
- },
35745
- });
35746
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
35747
- }
35748
- else {
35749
- result = await cloudbase.commonService().call({
35750
- Action: "ModifyStorageSafeRule",
35751
- Param: {
35752
- Bucket: resourceId,
35753
- EnvId: envId,
35754
- AclTag: aclTag,
35755
- },
35756
- });
35757
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
35758
- }
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);
35759
35694
  }
35760
- else if (resourceType === "sqlDatabase") {
35761
- if (aclTag === "CUSTOM") {
35762
- throw new Error("SQL 数据库不支持自定义安全规则(CUSTOM");
35763
- }
35764
- const schema = envId;
35765
- const tableName = resourceId;
35766
- const instanceId = "default";
35767
- const resource = `${instanceId}#${schema}#${tableName}`;
35768
- const resourceType = "table";
35769
- const effect = "allow";
35770
- const policyList = [
35771
- "allUser",
35772
- "anonymousUser",
35773
- "externalUser",
35774
- "internalUser",
35775
- ].map((roleIdentity) => ({
35776
- RoleIdentity: roleIdentity,
35777
- ResourceType: resourceType,
35778
- ResourceId: resource,
35779
- RowPermission: [],
35780
- Effect: effect,
35781
- }));
35782
- policyList[0].RowPermission = getRowPermission(aclTag);
35783
- result = await cloudbase.commonService("lowcode").call({
35784
- 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",
35785
35718
  Param: {
35719
+ Bucket: resourceId,
35786
35720
  EnvId: envId,
35787
- PolicyList: policyList,
35721
+ AclTag: aclTag,
35722
+ Rule: rule,
35788
35723
  },
35789
35724
  });
35790
35725
  (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
35791
- function getRowPermission(policy) {
35792
- return {
35793
- READONLY: [
35794
- { Key: "all", Value: "r" },
35795
- { Key: "me", Value: "rw" },
35796
- ],
35797
- PRIVATE: [{ Key: "me", Value: "rw" }],
35798
- ADMINWRITE: [{ Key: "all", Value: "r" }],
35799
- ADMINONLY: [],
35800
- }[policy];
35801
- }
35802
35726
  }
35803
35727
  else {
35804
- throw new Error(`不支持的资源类型: ${resourceType}`);
35805
- }
35806
- return {
35807
- content: [
35808
- {
35809
- type: "text",
35810
- text: JSON.stringify({
35811
- success: true,
35812
- requestId: result.RequestId,
35813
- raw: result,
35814
- message: "安全规则写入成功",
35815
- }, null, 2),
35728
+ result = await cloudbase.commonService().call({
35729
+ Action: "ModifyStorageSafeRule",
35730
+ Param: {
35731
+ Bucket: resourceId,
35732
+ EnvId: envId,
35733
+ AclTag: aclTag,
35816
35734
  },
35817
- ],
35818
- };
35735
+ });
35736
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
35737
+ }
35819
35738
  }
35820
- catch (error) {
35821
- return {
35822
- content: [
35823
- {
35824
- type: "text",
35825
- text: JSON.stringify({
35826
- success: false,
35827
- error: error.message,
35828
- message: "安全规则写入失败",
35829
- }, null, 2),
35830
- },
35831
- ],
35832
- };
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
+ }
35781
+ }
35782
+ else {
35783
+ throw new Error(`不支持的资源类型: ${resourceType}`);
35833
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
+ };
35834
35798
  });
35835
35799
  }
35836
35800
 
@@ -38103,64 +38067,44 @@ function registerDownloadTools(server) {
38103
38067
  category: "download"
38104
38068
  }
38105
38069
  }, async ({ url, relativePath }) => {
38106
- try {
38107
- // 验证相对路径安全性
38108
- if (!isPathSafe(relativePath)) {
38109
- return {
38110
- content: [
38111
- {
38112
- type: "text",
38113
- text: JSON.stringify({
38114
- success: false,
38115
- error: "不安全的相对路径",
38116
- message: "相对路径包含路径遍历操作(../)或绝对路径,出于安全考虑已拒绝",
38117
- suggestion: "请使用项目根目录下的相对路径,例如:'assets/images/logo.png'"
38118
- }, null, 2)
38119
- }
38120
- ]
38121
- };
38122
- }
38123
- // 计算最终下载路径
38124
- const targetPath = calculateDownloadPath(relativePath);
38125
- const projectRoot = getProjectRoot();
38126
- console.log(`📁 项目根目录: ${projectRoot}`);
38127
- console.log(`📁 相对路径: ${relativePath}`);
38128
- console.log(`📁 最终路径: ${targetPath}`);
38129
- // 下载文件到指定路径
38130
- const result = await downloadFileToPath(url, targetPath);
38131
- return {
38132
- content: [
38133
- {
38134
- type: "text",
38135
- text: JSON.stringify({
38136
- success: true,
38137
- filePath: result.filePath,
38138
- relativePath: relativePath,
38139
- contentType: result.contentType,
38140
- fileSize: result.fileSize,
38141
- projectRoot: projectRoot,
38142
- message: "文件下载成功到指定路径",
38143
- note: `文件已保存到项目目录: ${relativePath}`
38144
- }, null, 2)
38145
- }
38146
- ]
38147
- };
38148
- }
38149
- catch (error) {
38070
+ if (!isPathSafe(relativePath)) {
38150
38071
  return {
38151
38072
  content: [
38152
38073
  {
38153
38074
  type: "text",
38154
38075
  text: JSON.stringify({
38155
38076
  success: false,
38156
- error: error.message,
38157
- message: "文件下载失败",
38158
- suggestion: "请检查相对路径是否正确,确保不包含 ../ 等路径遍历操作"
38077
+ error: "不安全的相对路径",
38078
+ message: "相对路径包含路径遍历操作(../)或绝对路径,出于安全考虑已拒绝",
38079
+ suggestion: "请使用项目根目录下的相对路径,例如:'assets/images/logo.png'"
38159
38080
  }, null, 2)
38160
38081
  }
38161
38082
  ]
38162
38083
  };
38163
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
+ };
38164
38108
  });
38165
38109
  }
38166
38110
 
@@ -40416,52 +40360,35 @@ function registerSQLDatabaseTools(server) {
40416
40360
  category: CATEGORY,
40417
40361
  },
40418
40362
  }, async ({ sql }) => {
40419
- try {
40420
- const cloudbase = await getManager();
40421
- const envId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
40422
- // TODO: 考虑是否有支持指定其他 instance、schema 的需求
40423
- const schemaId = envId;
40424
- const instanceId = "default";
40425
- const result = await cloudbase.commonService("tcb", "2018-06-08").call({
40426
- Action: "RunSql",
40427
- 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: {
40428
40373
  EnvId: envId,
40429
- Sql: sql,
40430
- DbInstance: {
40431
- EnvId: envId,
40432
- InstanceId: instanceId,
40433
- Schema: schemaId,
40434
- },
40374
+ InstanceId: instanceId,
40375
+ Schema: schemaId,
40435
40376
  },
40436
- });
40437
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
40438
- return {
40439
- content: [
40440
- {
40441
- type: "text",
40442
- text: JSON.stringify({
40443
- success: true,
40444
- message: "SQL query executed successfully",
40445
- result,
40446
- }, null, 2),
40447
- },
40448
- ],
40449
- };
40450
- }
40451
- catch (error) {
40452
- return {
40453
- content: [
40454
- {
40455
- type: "text",
40456
- text: JSON.stringify({
40457
- success: false,
40458
- error: error.message,
40459
- message: "SQL query execution failed",
40460
- }, null, 2),
40461
- },
40462
- ],
40463
- };
40464
- }
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
+ };
40465
40392
  });
40466
40393
  // executeWriteSQL
40467
40394
  server.registerTool?.("executeWriteSQL", {
@@ -40480,52 +40407,35 @@ function registerSQLDatabaseTools(server) {
40480
40407
  category: CATEGORY,
40481
40408
  },
40482
40409
  }, async ({ sql }) => {
40483
- try {
40484
- const cloudbase = await getManager();
40485
- const envId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
40486
- // TODO: 考虑是否有支持指定其他 instance、schema 的需求
40487
- const schemaId = envId;
40488
- const instanceId = "default";
40489
- const result = await cloudbase.commonService("tcb", "2018-06-08").call({
40490
- Action: "RunSql",
40491
- 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: {
40492
40420
  EnvId: envId,
40493
- Sql: sql,
40494
- DbInstance: {
40495
- EnvId: envId,
40496
- InstanceId: instanceId,
40497
- Schema: schemaId,
40498
- },
40421
+ InstanceId: instanceId,
40422
+ Schema: schemaId,
40499
40423
  },
40500
- });
40501
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
40502
- return {
40503
- content: [
40504
- {
40505
- type: "text",
40506
- text: JSON.stringify({
40507
- success: true,
40508
- 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.`,
40509
- result,
40510
- }, null, 2),
40511
- },
40512
- ],
40513
- };
40514
- }
40515
- catch (error) {
40516
- return {
40517
- content: [
40518
- {
40519
- type: "text",
40520
- text: JSON.stringify({
40521
- success: false,
40522
- error: error.message,
40523
- message: "SQL statement execution failed",
40524
- }, null, 2),
40525
- },
40526
- ],
40527
- };
40528
- }
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
+ };
40529
40439
  });
40530
40440
  }
40531
40441
 
@@ -108889,289 +108799,271 @@ function registerDataModelTools(server) {
108889
108799
  category: "database",
108890
108800
  },
108891
108801
  }, async ({ action, name, names, }) => {
108892
- try {
108893
- const cloudbase = await getManager();
108894
- let currentEnvId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
108895
- let result;
108896
- switch (action) {
108897
- case "get":
108898
- if (!name) {
108899
- throw new Error("获取数据模型需要提供模型名称");
108900
- }
108901
- try {
108902
- result = await cloudbase.commonService("lowcode").call({
108903
- Action: "DescribeBasicDataSource",
108904
- Param: {
108905
- EnvId: currentEnvId,
108906
- Name: name,
108907
- },
108908
- });
108909
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
108910
- // 只保留基础字段,过滤掉冗余信息,并简化Schema
108911
- let simplifiedSchema = null;
108912
- // 解析并简化Schema
108913
- if (result.Data.Schema) {
108914
- try {
108915
- const schema = JSON.parse(result.Data.Schema);
108916
- const properties = schema.properties || {};
108917
- // 提取用户定义的字段(排除系统字段)
108918
- const userFields = Object.keys(properties)
108919
- .filter((key) => !properties[key]["x-system"]) // 排除系统字段
108920
- .map((key) => {
108921
- const field = properties[key];
108922
- return parseFieldStructure(field, key, schema);
108923
- });
108924
- // 提取关联关系
108925
- const relations = userFields
108926
- .filter((field) => field.linkage)
108927
- .map((field) => ({
108928
- field: field.name,
108929
- type: field.format,
108930
- title: field.title,
108931
- targetModel: field.linkage.parentDataSourceName,
108932
- foreignKey: field.linkage.parentFieldKey,
108933
- displayField: field.linkage.parentFieldTitle,
108934
- }));
108935
- simplifiedSchema = {
108936
- userFields,
108937
- relations,
108938
- totalFields: Object.keys(properties).length,
108939
- userFieldsCount: userFields.length,
108940
- };
108941
- }
108942
- catch (e) {
108943
- simplifiedSchema = { error: "Schema解析失败" };
108944
- }
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
+ };
108945
108850
  }
108946
- // 尝试生成Mermaid图表
108947
- let mermaidDiagram = null;
108948
- if (result.Data.Schema &&
108949
- jsonSchemaToMermaid &&
108950
- simplifiedSchema &&
108951
- !simplifiedSchema.error) {
108952
- try {
108953
- const mainSchema = JSON.parse(result.Data.Schema);
108954
- const schemasMap = {
108955
- [name]: mainSchema,
108956
- };
108957
- // 获取关联模型的 schema
108958
- if (simplifiedSchema.relations &&
108959
- simplifiedSchema.relations.length > 0) {
108960
- const relatedModelNames = [
108961
- ...new Set(simplifiedSchema.relations.map((rel) => rel.targetModel)),
108962
- ];
108963
- for (const relatedModelName of relatedModelNames) {
108964
- try {
108965
- const relatedResult = await cloudbase
108966
- .commonService("lowcode")
108967
- .call({
108968
- Action: "DescribeBasicDataSource",
108969
- Param: {
108970
- EnvId: currentEnvId,
108971
- Name: relatedModelName,
108972
- },
108973
- });
108974
- if (relatedResult.Data && relatedResult.Data.Schema) {
108975
- schemasMap[relatedModelName] = JSON.parse(relatedResult.Data.Schema);
108976
- }
108977
- }
108978
- catch (e) {
108979
- 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);
108980
108885
  }
108981
108886
  }
108887
+ catch (e) {
108888
+ console.warn(`获取关联模型 ${relatedModelName} 的 schema 失败:`, e);
108889
+ }
108982
108890
  }
108983
- // 调用 jsonSchemaToMermaid,传入正确的参数格式
108984
- mermaidDiagram = jsonSchemaToMermaid(schemasMap);
108985
- }
108986
- catch (e) {
108987
- console.warn("生成Mermaid图表失败:", e);
108988
108891
  }
108892
+ // 调用 jsonSchemaToMermaid,传入正确的参数格式
108893
+ mermaidDiagram = jsonSchemaToMermaid(schemasMap);
108989
108894
  }
108990
- const simplifiedModel = {
108991
- DbInstanceType: result.Data.DbInstanceType,
108992
- Title: result.Data.Title,
108993
- Description: result.Data.Description,
108994
- Name: result.Data.Name,
108995
- UpdatedAt: result.Data.UpdatedAt,
108996
- Schema: simplifiedSchema,
108997
- mermaid: mermaidDiagram,
108998
- };
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") {
108999
108924
  return {
109000
108925
  content: [
109001
108926
  {
109002
108927
  type: "text",
109003
108928
  text: JSON.stringify({
109004
- success: true,
108929
+ success: false,
109005
108930
  action: "get",
109006
- data: simplifiedModel,
109007
- message: "获取数据模型成功",
108931
+ error: "ResourceNotFound",
108932
+ message: `数据模型 ${name} 不存在`,
109008
108933
  }, null, 2),
109009
108934
  },
109010
108935
  ],
109011
108936
  };
109012
108937
  }
109013
- catch (error) {
109014
- if (error.original?.Code === "ResourceNotFound") {
109015
- return {
109016
- content: [
109017
- {
109018
- type: "text",
109019
- text: JSON.stringify({
109020
- success: false,
109021
- action: "get",
109022
- error: "ResourceNotFound",
109023
- message: `数据模型 ${name} 不存在`,
109024
- }, null, 2),
109025
- },
109026
- ],
109027
- };
109028
- }
109029
- throw error;
109030
- }
109031
- case "list":
109032
- // 构建请求参数
109033
- const listParams = {
109034
- EnvId: currentEnvId,
109035
- PageIndex: 1,
109036
- PageSize: 1000,
109037
- QuerySystemModel: true, // 查询系统模型
109038
- QueryConnector: 0, // 0 表示数据模型
109039
- };
109040
- // 只有当 names 参数存在且不为空时才添加过滤条件
109041
- if (names && names.length > 0) {
109042
- listParams.DataSourceNames = names;
109043
- }
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
+ // 先获取模型信息
109044
108987
  result = await cloudbase.commonService("lowcode").call({
109045
- Action: "DescribeDataSourceList",
109046
- Param: listParams,
108988
+ Action: "DescribeBasicDataSource",
108989
+ Param: {
108990
+ EnvId: currentEnvId,
108991
+ Name: name,
108992
+ },
109047
108993
  });
109048
108994
  (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
109049
- const models = result.Data?.Rows || [];
109050
- // 只保留基础字段,list操作不返回Schema
109051
- const simplifiedModels = models.map((model) => ({
109052
- DbInstanceType: model.DbInstanceType,
109053
- Title: model.Title,
109054
- Description: model.Description,
109055
- Name: model.Name,
109056
- UpdatedAt: model.UpdatedAt,
109057
- }));
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);
109058
109031
  return {
109059
109032
  content: [
109060
109033
  {
109061
109034
  type: "text",
109062
109035
  text: JSON.stringify({
109063
109036
  success: true,
109064
- action: "list",
109065
- data: simplifiedModels,
109066
- count: simplifiedModels.length,
109067
- message: "获取数据模型列表成功",
109037
+ action: "docs",
109038
+ modelName: name,
109039
+ modelTitle: result.Data.Title,
109040
+ docs,
109041
+ message: "SDK使用文档生成成功",
109068
109042
  }, null, 2),
109069
109043
  },
109070
109044
  ],
109071
109045
  };
109072
- case "docs":
109073
- if (!name) {
109074
- throw new Error("生成SDK文档需要提供模型名称");
109075
- }
109076
- try {
109077
- // 先获取模型信息
109078
- result = await cloudbase.commonService("lowcode").call({
109079
- Action: "DescribeBasicDataSource",
109080
- Param: {
109081
- EnvId: currentEnvId,
109082
- Name: name,
109083
- },
109084
- });
109085
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
109086
- if (!result.Data) {
109087
- throw new Error(`数据模型 ${name} 不存在`);
109088
- }
109089
- // 解析Schema获取字段信息
109090
- let userFields = [];
109091
- let relations = [];
109092
- if (result.Data.Schema) {
109093
- try {
109094
- const schema = JSON.parse(result.Data.Schema);
109095
- const properties = schema.properties || {};
109096
- // 提取用户定义的字段
109097
- userFields = Object.keys(properties)
109098
- .filter((key) => !properties[key]["x-system"])
109099
- .map((key) => {
109100
- const field = properties[key];
109101
- return parseFieldStructure(field, key, schema);
109102
- });
109103
- // 提取关联关系
109104
- relations = userFields
109105
- .filter((field) => field.linkage)
109106
- .map((field) => ({
109107
- field: field.name,
109108
- type: field.format,
109109
- title: field.title,
109110
- targetModel: field.linkage.parentDataSourceName,
109111
- foreignKey: field.linkage.parentFieldKey,
109112
- displayField: field.linkage.parentFieldTitle,
109113
- }));
109114
- }
109115
- catch (e) {
109116
- // Schema解析失败,使用空数组
109117
- console.error("Schema解析失败", e);
109118
- }
109119
- }
109120
- // 生成SDK使用文档
109121
- const docs = generateSDKDocs(result.Data.Name, result.Data.Title, userFields, relations);
109046
+ }
109047
+ catch (error) {
109048
+ if (error.original?.Code === "ResourceNotFound") {
109122
109049
  return {
109123
109050
  content: [
109124
109051
  {
109125
109052
  type: "text",
109126
109053
  text: JSON.stringify({
109127
- success: true,
109054
+ success: false,
109128
109055
  action: "docs",
109129
- modelName: name,
109130
- modelTitle: result.Data.Title,
109131
- docs,
109132
- message: "SDK使用文档生成成功",
109056
+ error: "ResourceNotFound",
109057
+ message: `数据模型 ${name} 不存在`,
109133
109058
  }, null, 2),
109134
109059
  },
109135
109060
  ],
109136
109061
  };
109137
109062
  }
109138
- catch (error) {
109139
- if (error.original?.Code === "ResourceNotFound") {
109140
- return {
109141
- content: [
109142
- {
109143
- type: "text",
109144
- text: JSON.stringify({
109145
- success: false,
109146
- action: "docs",
109147
- error: "ResourceNotFound",
109148
- message: `数据模型 ${name} 不存在`,
109149
- }, null, 2),
109150
- },
109151
- ],
109152
- };
109153
- }
109154
- throw error;
109155
- }
109156
- default:
109157
- throw new Error(`不支持的操作类型: ${action}`);
109158
- }
109159
- }
109160
- catch (error) {
109161
- return {
109162
- content: [
109163
- {
109164
- type: "text",
109165
- text: JSON.stringify({
109166
- success: false,
109167
- action,
109168
- error: error.message || error.original?.Message || "未知错误",
109169
- code: error.original?.Code,
109170
- message: "数据模型操作失败",
109171
- }, null, 2),
109172
- },
109173
- ],
109174
- };
109063
+ throw error;
109064
+ }
109065
+ default:
109066
+ throw new Error(`不支持的操作类型: ${action}`);
109175
109067
  }
109176
109068
  });
109177
109069
  // modifyDataModel - 数据模型修改工具(创建/更新)
@@ -109244,126 +109136,108 @@ classDiagram
109244
109136
  category: "database",
109245
109137
  },
109246
109138
  }, async ({ mermaidDiagram, action = "create", publish = false, dbInstanceType = "MYSQL", }) => {
109247
- try {
109248
- const cloudbase = await getManager();
109249
- let currentEnvId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
109250
- // 使用mermaidToJsonSchema转换Mermaid图表
109251
- const schemas = mermaidToJsonSchema(mermaidDiagram);
109252
- if (!schemas || Object.keys(schemas).length === 0) {
109253
- return {
109254
- content: [
109255
- {
109256
- type: "text",
109257
- text: JSON.stringify({
109258
- success: false,
109259
- error: "No schemas generated from Mermaid diagram",
109260
- message: "无法从Mermaid图表生成数据模型Schema",
109261
- }, null, 2),
109262
- },
109263
- ],
109264
- };
109265
- }
109266
- // 创建数据模型列表
109267
- const createDataModelList = Object.entries(schemas).map(([name, schema]) => {
109268
- return {
109269
- CreateSource: "cloudbase_create",
109270
- Creator: null,
109271
- DbLinkName: null,
109272
- Description: schema.description ||
109273
- `${schema.title || name}数据模型`,
109274
- Schema: JSON.stringify(createBackendSchemaParams(schema)),
109275
- Title: schema.title || name,
109276
- Name: name,
109277
- TableNameRule: "only_name",
109278
- };
109279
- });
109280
- // 调用批量创建数据模型API
109281
- const result = await cloudbase.commonService("lowcode").call({
109282
- Action: "BatchCreateDataModelList",
109283
- Param: {
109284
- CreateDataModelList: createDataModelList,
109285
- Creator: null,
109286
- DbInstanceType: dbInstanceType,
109287
- EnvId: currentEnvId,
109288
- },
109289
- });
109290
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
109291
- const taskId = result.Data?.TaskId;
109292
- if (!taskId) {
109293
- return {
109294
- content: [
109295
- {
109296
- type: "text",
109297
- text: JSON.stringify({
109298
- success: false,
109299
- requestId: result.RequestId,
109300
- error: "No TaskId returned",
109301
- message: "创建任务失败,未返回任务ID",
109302
- }, null, 2),
109303
- },
109304
- ],
109305
- };
109306
- }
109307
- // 轮询任务状态直至完成或超时
109308
- const maxWaitTime = 30000; // 30秒超时
109309
- const startTime = Date.now();
109310
- let status = "init";
109311
- let statusResult = null;
109312
- while (status === "init" && Date.now() - startTime < maxWaitTime) {
109313
- await new Promise((resolve) => setTimeout(resolve, 2000)); // 等待2秒
109314
- statusResult = await cloudbase.commonService("lowcode").call({
109315
- Action: "QueryModelTaskStatus",
109316
- Param: {
109317
- EnvId: currentEnvId,
109318
- TaskId: taskId,
109319
- },
109320
- });
109321
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, statusResult);
109322
- status = statusResult.Data?.Status || "init";
109323
- }
109324
- // 返回最终结果
109325
- const models = Object.keys(schemas);
109326
- const successModels = statusResult?.Data?.SuccessResourceIdList || [];
109327
- 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) {
109328
109143
  return {
109329
109144
  content: [
109330
109145
  {
109331
109146
  type: "text",
109332
109147
  text: JSON.stringify({
109333
- success: status === "success",
109334
- requestId: result.RequestId,
109335
- taskId: taskId,
109336
- models: models,
109337
- successModels: successModels,
109338
- failedModels: failedModels,
109339
- status: status,
109340
- action: action,
109341
- message: status === "success"
109342
- ? `数据模型${action === "create" ? "创建" : "更新"}成功,共处理${models.length}个模型`
109343
- : status === "init"
109344
- ? `任务超时,任务ID: ${taskId},请稍后手动查询状态`
109345
- : `数据模型${action === "create" ? "创建" : "更新"}失败`,
109346
- taskResult: statusResult?.Data,
109148
+ success: false,
109149
+ error: "No schemas generated from Mermaid diagram",
109150
+ message: "无法从Mermaid图表生成数据模型Schema",
109347
109151
  }, null, 2),
109348
109152
  },
109349
109153
  ],
109350
109154
  };
109351
109155
  }
109352
- 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) {
109353
109183
  return {
109354
109184
  content: [
109355
109185
  {
109356
109186
  type: "text",
109357
109187
  text: JSON.stringify({
109358
109188
  success: false,
109359
- error: error.message || error.original?.Message || "未知错误",
109360
- code: error.original?.Code,
109361
- message: "数据模型修改操作失败",
109189
+ requestId: result.RequestId,
109190
+ error: "No TaskId returned",
109191
+ message: "创建任务失败,未返回任务ID",
109362
109192
  }, null, 2),
109363
109193
  },
109364
109194
  ],
109365
109195
  };
109366
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
+ };
109367
109241
  });
109368
109242
  }
109369
109243
 
@@ -112400,113 +112274,97 @@ function registerCloudRunTools(server) {
112400
112274
  category: "cloudrun"
112401
112275
  }
112402
112276
  }, async (args) => {
112403
- try {
112404
- const input = args;
112405
- const manager = await getManager();
112406
- if (!manager) {
112407
- throw new Error("Failed to initialize CloudBase manager. Please check your credentials and environment configuration.");
112408
- }
112409
- const cloudrunService = manager.cloudrun;
112410
- switch (input.action) {
112411
- case 'list': {
112412
- const listParams = {
112413
- pageSize: input.pageSize,
112414
- pageNum: input.pageNum,
112415
- };
112416
- if (input.serverName) {
112417
- listParams.serverName = input.serverName;
112418
- }
112419
- if (input.serverType) {
112420
- listParams.serverType = input.serverType;
112421
- }
112422
- const result = await cloudrunService.list(listParams);
112423
- return {
112424
- content: [
112425
- {
112426
- type: "text",
112427
- text: JSON.stringify({
112428
- success: true,
112429
- data: {
112430
- services: result.ServerList || [],
112431
- pagination: {
112432
- total: result.Total || 0,
112433
- pageSize: input.pageSize,
112434
- pageNum: input.pageNum,
112435
- totalPages: Math.ceil((result.Total || 0) / (input.pageSize || 10))
112436
- }
112437
- },
112438
- message: `Found ${result.ServerList?.length || 0} CloudRun services`
112439
- }, null, 2)
112440
- }
112441
- ]
112442
- };
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;
112443
112291
  }
112444
- case 'detail': {
112445
- const serverName = input.detailServerName || input.serverName;
112446
- const result = await cloudrunService.detail({ serverName });
112447
- if (!result) {
112448
- return {
112449
- content: [
112450
- {
112451
- type: "text",
112452
- text: JSON.stringify({
112453
- success: false,
112454
- error: `Service '${serverName}' not found`,
112455
- message: "Please check the service name and try again."
112456
- }, null, 2)
112457
- }
112458
- ]
112459
- };
112460
- }
112461
- return {
112462
- content: [
112463
- {
112464
- type: "text",
112465
- text: JSON.stringify({
112466
- success: true,
112467
- data: {
112468
- service: result
112469
- },
112470
- message: `Retrieved details for service '${serverName}'`
112471
- }, null, 2)
112472
- }
112473
- ]
112474
- };
112292
+ if (input.serverType) {
112293
+ listParams.serverType = input.serverType;
112475
112294
  }
112476
- case 'templates': {
112477
- 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) {
112478
112321
  return {
112479
112322
  content: [
112480
112323
  {
112481
112324
  type: "text",
112482
112325
  text: JSON.stringify({
112483
- success: true,
112484
- data: {
112485
- templates: result || []
112486
- },
112487
- 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."
112488
112329
  }, null, 2)
112489
112330
  }
112490
112331
  ]
112491
112332
  };
112492
112333
  }
112493
- default:
112494
- 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
+ };
112495
112348
  }
112496
- }
112497
- catch (error) {
112498
- return {
112499
- content: [
112500
- {
112501
- type: "text",
112502
- text: JSON.stringify({
112503
- success: false,
112504
- error: error.message || 'Unknown error occurred',
112505
- message: "Failed to query CloudRun information. Please check your permissions and try again."
112506
- }, null, 2)
112507
- }
112508
- ]
112509
- };
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}`);
112510
112368
  }
112511
112369
  });
112512
112370
  // Track local running processes for CloudRun function services
@@ -112524,62 +112382,60 @@ function registerCloudRunTools(server) {
112524
112382
  category: "cloudrun"
112525
112383
  }
112526
112384
  }, async (args) => {
112527
- try {
112528
- const input = args;
112529
- const manager = await getManager();
112530
- if (!manager) {
112531
- throw new Error("Failed to initialize CloudBase manager. Please check your credentials and environment configuration.");
112532
- }
112533
- const cloudrunService = manager.cloudrun;
112534
- let targetPath;
112535
- // Validate and normalize path for operations that require it
112536
- if (input.targetPath) {
112537
- targetPath = validateAndNormalizePath(input.targetPath);
112538
- }
112539
- switch (input.action) {
112540
- case 'createAgent': {
112541
- if (!targetPath) {
112542
- throw new Error("targetPath is required for createAgent operation");
112543
- }
112544
- if (!input.agentConfig) {
112545
- throw new Error("agentConfig is required for createAgent operation");
112546
- }
112547
- const { agentName, botTag, description, template = 'blank' } = input.agentConfig;
112548
- // Generate BotId
112549
- const botId = botTag ? `ibot-${agentName}-${botTag}` : `ibot-${agentName}-${Date.now()}`;
112550
- // Create Agent using CloudBase Manager
112551
- const agentResult = await manager.agent.createFunctionAgent(targetPath, {
112552
- Name: agentName,
112553
- BotId: botId,
112554
- Introduction: description || `Agent created by ${agentName}`,
112555
- Avatar: undefined
112556
- });
112557
- // Create project directory
112558
- const projectDir = path_1.default.join(targetPath, input.serverName);
112559
- if (!fs_1.default.existsSync(projectDir)) {
112560
- 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"
112561
112434
  }
112562
- // Generate package.json
112563
- const packageJson = {
112564
- name: input.serverName,
112565
- version: "1.0.0",
112566
- description: description || `Agent created by ${agentName}`,
112567
- main: "index.js",
112568
- scripts: {
112569
- "dev": "tcb cloudrun run --runMode=agent -w",
112570
- "deploy": "tcb cloudrun deploy",
112571
- "start": "node index.js"
112572
- },
112573
- dependencies: {
112574
- "@cloudbase/aiagent-framework": "^1.0.0-beta.10"
112575
- },
112576
- devDependencies: {
112577
- "@cloudbase/cli": "^2.6.16"
112578
- }
112579
- };
112580
- fs_1.default.writeFileSync(path_1.default.join(projectDir, 'package.json'), JSON.stringify(packageJson, null, 2));
112581
- // Generate index.js with Agent template
112582
- 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");
112583
112439
  const { BotRunner } = require("@cloudbase/aiagent-framework");
112584
112440
 
112585
112441
  const ANSWER = "你好,我是一个智能体,但我只会说这一句话。";
@@ -112624,18 +112480,18 @@ exports.main = function (event, context) {
112624
112480
  return BotRunner.run(event, context, new MyBot(context));
112625
112481
  };
112626
112482
  `;
112627
- fs_1.default.writeFileSync(path_1.default.join(projectDir, 'index.js'), indexJsContent);
112628
- // Generate cloudbaserc.json
112629
- const currentEnvId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
112630
- const cloudbasercContent = {
112631
- envId: currentEnvId,
112632
- cloudrun: {
112633
- name: input.serverName
112634
- }
112635
- };
112636
- fs_1.default.writeFileSync(path_1.default.join(projectDir, 'cloudbaserc.json'), JSON.stringify(cloudbasercContent, null, 2));
112637
- // Generate README.md
112638
- 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
112639
112495
 
112640
112496
  这是一个基于函数型云托管的 AI 智能体。
112641
112497
 
@@ -112680,230 +112536,230 @@ for await (let x of res.textStream) {
112680
112536
  </script>
112681
112537
  \`\`\`
112682
112538
  `;
112683
- fs_1.default.writeFileSync(path_1.default.join(projectDir, 'README.md'), readmeContent);
112684
- return {
112685
- content: [
112686
- {
112687
- type: "text",
112688
- text: JSON.stringify({
112689
- success: true,
112690
- data: {
112691
- agentName: agentName,
112692
- botId: botId,
112693
- projectDir: projectDir,
112694
- serverName: input.serverName,
112695
- template: template,
112696
- filesCreated: ['package.json', 'index.js', 'cloudbaserc.json', 'README.md']
112697
- },
112698
- message: `Successfully created Agent '${agentName}' with BotId '${botId}' in ${projectDir}`
112699
- }, null, 2)
112700
- }
112701
- ]
112702
- };
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");
112703
112563
  }
112704
- case 'deploy': {
112705
- if (!targetPath) {
112706
- throw new Error("targetPath is required for deploy operation");
112707
- }
112708
- // Determine service type - use input.serverType if provided, otherwise auto-detect
112709
- let serverType;
112710
- if (input.serverType) {
112711
- 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';
112712
112574
  }
112713
- else {
112714
- try {
112715
- // First try to get existing service details
112716
- const details = await cloudrunService.detail({ serverName: input.serverName });
112717
- 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';
112718
112580
  }
112719
- catch (e) {
112720
- // If service doesn't exist, determine by project structure
112721
- const dockerfilePath = path_1.default.join(targetPath, 'Dockerfile');
112722
- if (fs_1.default.existsSync(dockerfilePath)) {
112723
- serverType = 'container';
112724
- }
112725
- else {
112726
- // Check if it's a Node.js function project (has package.json with specific structure)
112727
- const packageJsonPath = path_1.default.join(targetPath, 'package.json');
112728
- if (fs_1.default.existsSync(packageJsonPath)) {
112729
- try {
112730
- const packageJson = JSON.parse(fs_1.default.readFileSync(packageJsonPath, 'utf8'));
112731
- // If it has function-specific dependencies or scripts, treat as function
112732
- if (packageJson.dependencies?.['@cloudbase/aiagent-framework'] ||
112733
- packageJson.scripts?.['dev']?.includes('cloudrun run')) {
112734
- serverType = 'function';
112735
- }
112736
- else {
112737
- serverType = 'container';
112738
- }
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';
112739
112591
  }
112740
- catch (parseError) {
112592
+ else {
112741
112593
  serverType = 'container';
112742
112594
  }
112743
112595
  }
112744
- else {
112745
- // No package.json, default to container
112596
+ catch (parseError) {
112746
112597
  serverType = 'container';
112747
112598
  }
112748
112599
  }
112600
+ else {
112601
+ // No package.json, default to container
112602
+ serverType = 'container';
112603
+ }
112749
112604
  }
112750
112605
  }
112751
- const deployParams = {
112752
- serverName: input.serverName,
112753
- targetPath: targetPath,
112754
- force: input.force,
112755
- serverType: serverType,
112756
- };
112757
- // Add server configuration if provided
112758
- if (input.serverConfig) {
112759
- deployParams.serverConfig = input.serverConfig;
112760
- }
112761
- const result = await cloudrunService.deploy(deployParams);
112762
- // Generate cloudbaserc.json configuration file
112763
- const currentEnvId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
112764
- const cloudbasercPath = path_1.default.join(targetPath, 'cloudbaserc.json');
112765
- const cloudbasercContent = {
112766
- envId: currentEnvId,
112767
- cloudrun: {
112768
- name: input.serverName
112769
- }
112770
- };
112771
- try {
112772
- fs_1.default.writeFileSync(cloudbasercPath, JSON.stringify(cloudbasercContent, null, 2));
112773
- }
112774
- catch (error) {
112775
- // 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
112776
112625
  }
112777
- // 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 = "";
112778
112637
  try {
112779
- // Query service details to get access URL
112780
- let serviceUrl = "";
112781
- try {
112782
- const serviceDetails = await cloudrunService.detail({ serverName: input.serverName });
112783
- // Extract access URL from service details
112784
- // Priority: DefaultDomainName > CustomDomainName > PublicDomain > InternalDomain
112785
- const details = serviceDetails; // Use any to access dynamic properties
112786
- if (details?.BaseInfo?.DefaultDomainName) {
112787
- // DefaultDomainName is already a complete URL (e.g., https://...)
112788
- serviceUrl = details.BaseInfo.DefaultDomainName;
112789
- }
112790
- else if (details?.BaseInfo?.CustomDomainName) {
112791
- // CustomDomainName might be a domain without protocol
112792
- const customDomain = details.BaseInfo.CustomDomainName;
112793
- serviceUrl = customDomain.startsWith('http') ? customDomain : `https://${customDomain}`;
112794
- }
112795
- else if (details?.BaseInfo?.PublicDomain) {
112796
- serviceUrl = `https://${details.BaseInfo.PublicDomain}`;
112797
- }
112798
- else if (details?.BaseInfo?.InternalDomain) {
112799
- serviceUrl = `https://${details.BaseInfo.InternalDomain}`;
112800
- }
112801
- else if (details?.AccessInfo?.PublicDomain) {
112802
- serviceUrl = `https://${details.AccessInfo.PublicDomain}`;
112803
- }
112804
- else {
112805
- serviceUrl = ""; // URL not available
112806
- }
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;
112807
112645
  }
112808
- catch (detailErr) {
112809
- // If query fails, continue with empty URL
112810
- 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
112811
112662
  }
112812
- // Extract project name from targetPath
112813
- const projectName = path_1.default.basename(targetPath);
112814
- // Build console URL
112815
- const consoleUrl = `https://tcb.cloud.tencent.com/dev?envId=${currentEnvId}#/platform-run/service/detail?serverName=${input.serverName}&tabId=overview&envId=${currentEnvId}`;
112816
- // Send notification
112817
- await (0, notification_js_1.sendDeployNotification)(server, {
112818
- deployType: 'cloudrun',
112819
- url: serviceUrl,
112820
- projectId: currentEnvId,
112821
- projectName: projectName,
112822
- consoleUrl: consoleUrl
112823
- });
112824
112663
  }
112825
- catch (notifyErr) {
112826
- // Notification failure should not affect deployment flow
112827
- // Error is already logged in sendDeployNotification
112664
+ catch (detailErr) {
112665
+ // If query fails, continue with empty URL
112666
+ serviceUrl = "";
112828
112667
  }
112829
- return {
112830
- content: [
112831
- {
112832
- type: "text",
112833
- text: JSON.stringify({
112834
- success: true,
112835
- data: {
112836
- serviceName: input.serverName,
112837
- status: 'deployed',
112838
- deployPath: targetPath,
112839
- serverType: serverType,
112840
- cloudbasercGenerated: true
112841
- },
112842
- message: `Successfully deployed ${serverType} service '${input.serverName}' from ${targetPath}`
112843
- }, null, 2)
112844
- }
112845
- ]
112846
- };
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
+ });
112847
112680
  }
112848
- case 'run': {
112849
- if (!targetPath) {
112850
- throw new Error("targetPath is required for run operation");
112851
- }
112852
- // Do not support container services locally: basic heuristic - if Dockerfile exists, treat as container
112853
- const dockerfilePath = path_1.default.join(targetPath, 'Dockerfile');
112854
- if (fs_1.default.existsSync(dockerfilePath)) {
112855
- throw new Error("Local run is only supported for function-type CloudRun services. Container services are not supported.");
112856
- }
112857
- // Check if this is an Agent project
112858
- const isAgent = checkIfAgentProject(targetPath);
112859
- const runMode = input.runOptions?.runMode || (isAgent ? 'agent' : 'normal');
112860
- // Check if service is already running and verify process exists
112861
- if (runningProcesses.has(input.serverName)) {
112862
- const existingPid = runningProcesses.get(input.serverName);
112863
- try {
112864
- // Check if process actually exists
112865
- process.kill(existingPid, 0);
112866
- return {
112867
- content: [
112868
- {
112869
- type: "text",
112870
- text: JSON.stringify({
112871
- success: true,
112872
- data: {
112873
- serviceName: input.serverName,
112874
- status: 'running',
112875
- pid: existingPid,
112876
- cwd: targetPath
112877
- },
112878
- message: `Service '${input.serverName}' is already running locally (pid=${existingPid})`
112879
- }, null, 2)
112880
- }
112881
- ]
112882
- };
112883
- }
112884
- catch (error) {
112885
- // Process doesn't exist, remove from tracking
112886
- 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)
112887
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
+ };
112888
112739
  }
112889
- const runPort = input.runOptions?.port ?? 3000;
112890
- const extraEnv = input.runOptions?.envParams ?? {};
112891
- // Set environment variables for functions-framework
112892
- const env = {
112893
- ...process.env,
112894
- PORT: String(runPort),
112895
- ...extraEnv,
112896
- // Add functions-framework specific environment variables
112897
- ENABLE_CORS: 'true',
112898
- ALLOWED_ORIGINS: '*'
112899
- };
112900
- // Choose execution method based on run mode
112901
- let child;
112902
- let command;
112903
- if (runMode === 'agent') {
112904
- // For Agent mode, use a different approach since functions-framework doesn't support Agent mode
112905
- // We'll use a custom script that sets up the Agent environment
112906
- 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 "
112907
112763
  const { runCLI } = require('@cloudbase/functions-framework');
112908
112764
  process.env.PORT = '${runPort}';
112909
112765
  process.env.ENABLE_CORS = 'true';
@@ -112912,16 +112768,16 @@ for await (let x of res.textStream) {
112912
112768
  ${Object.entries(extraEnv).map(([key, value]) => `process.env.${key} = '${value}';`).join('\n')}
112913
112769
  runCLI();
112914
112770
  "`;
112915
- child = (0, child_process_1.spawn)(process.execPath, ['-e', command], {
112916
- cwd: targetPath,
112917
- env,
112918
- stdio: ['ignore', 'pipe', 'pipe'],
112919
- detached: true
112920
- });
112921
- }
112922
- else {
112923
- // Normal function mode
112924
- 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 "
112925
112781
  const { runCLI } = require('@cloudbase/functions-framework');
112926
112782
  process.env.PORT = '${runPort}';
112927
112783
  process.env.ENABLE_CORS = 'true';
@@ -112929,182 +112785,167 @@ for await (let x of res.textStream) {
112929
112785
  ${Object.entries(extraEnv).map(([key, value]) => `process.env.${key} = '${value}';`).join('\n')}
112930
112786
  runCLI();
112931
112787
  "`;
112932
- child = (0, child_process_1.spawn)(process.execPath, ['-e', command], {
112933
- cwd: targetPath,
112934
- env,
112935
- stdio: ['ignore', 'pipe', 'pipe'],
112936
- detached: true
112937
- });
112938
- }
112939
- // Handle process exit to clean up tracking
112940
- child.on('exit', (code, signal) => {
112941
- 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
112942
112793
  });
112943
- child.on('error', (error) => {
112944
- runningProcesses.delete(input.serverName);
112945
- });
112946
- child.unref();
112947
- if (typeof child.pid !== 'number') {
112948
- throw new Error('Failed to start local process: PID is undefined.');
112949
- }
112950
- runningProcesses.set(input.serverName, child.pid);
112951
- return {
112952
- content: [
112953
- {
112954
- type: "text",
112955
- text: JSON.stringify({
112956
- success: true,
112957
- data: {
112958
- serviceName: input.serverName,
112959
- status: 'running',
112960
- pid: child.pid,
112961
- port: runPort,
112962
- runMode: runMode,
112963
- isAgent: isAgent,
112964
- command: command,
112965
- cwd: targetPath
112966
- },
112967
- message: `Started local run for ${runMode} service '${input.serverName}' on port ${runPort} (pid=${child.pid})`
112968
- }, null, 2)
112969
- }
112970
- ]
112971
- };
112972
112794
  }
112973
- case 'download': {
112974
- if (!targetPath) {
112975
- throw new Error("targetPath is required for download operation");
112976
- }
112977
- const result = await cloudrunService.download({
112978
- serverName: input.serverName,
112979
- targetPath: targetPath,
112980
- });
112981
- // Generate cloudbaserc.json configuration file
112982
- const currentEnvId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
112983
- const cloudbasercPath = path_1.default.join(targetPath, 'cloudbaserc.json');
112984
- const cloudbasercContent = {
112985
- envId: currentEnvId,
112986
- cloudrun: {
112987
- 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)
112988
112825
  }
112989
- };
112990
- try {
112991
- fs_1.default.writeFileSync(cloudbasercPath, JSON.stringify(cloudbasercContent, null, 2));
112992
- }
112993
- catch (error) {
112994
- // Ignore cloudbaserc.json creation errors
112995
- }
112996
- return {
112997
- content: [
112998
- {
112999
- type: "text",
113000
- text: JSON.stringify({
113001
- success: true,
113002
- data: {
113003
- serviceName: input.serverName,
113004
- downloadPath: targetPath,
113005
- filesCount: 0,
113006
- cloudbasercGenerated: true
113007
- },
113008
- message: `Successfully downloaded service '${input.serverName}' to ${targetPath}`
113009
- }, null, 2)
113010
- }
113011
- ]
113012
- };
112826
+ ]
112827
+ };
112828
+ }
112829
+ case 'download': {
112830
+ if (!targetPath) {
112831
+ throw new Error("targetPath is required for download operation");
113013
112832
  }
113014
- case 'delete': {
113015
- if (!input.force) {
113016
- return {
113017
- content: [
113018
- {
113019
- type: "text",
113020
- text: JSON.stringify({
113021
- success: false,
113022
- error: "Delete operation requires confirmation",
113023
- message: "Please set force: true to confirm deletion of the service. This action cannot be undone."
113024
- }, null, 2)
113025
- }
113026
- ]
113027
- };
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
113028
112844
  }
113029
- const result = await cloudrunService.delete({
113030
- serverName: input.serverName,
113031
- });
113032
- return {
113033
- content: [
113034
- {
113035
- type: "text",
113036
- text: JSON.stringify({
113037
- success: true,
113038
- data: {
113039
- serviceName: input.serverName,
113040
- status: 'deleted'
113041
- },
113042
- message: `Successfully deleted service '${input.serverName}'`
113043
- }, null, 2)
113044
- }
113045
- ]
113046
- };
112845
+ };
112846
+ try {
112847
+ fs_1.default.writeFileSync(cloudbasercPath, JSON.stringify(cloudbasercContent, null, 2));
113047
112848
  }
113048
- case 'init': {
113049
- if (!targetPath) {
113050
- throw new Error("targetPath is required for init operation");
113051
- }
113052
- const result = await cloudrunService.init({
113053
- serverName: input.serverName,
113054
- targetPath: targetPath,
113055
- template: input.template,
113056
- });
113057
- // Generate cloudbaserc.json configuration file
113058
- const currentEnvId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
113059
- const cloudbasercPath = path_1.default.join(targetPath, input.serverName, 'cloudbaserc.json');
113060
- const cloudbasercContent = {
113061
- envId: currentEnvId,
113062
- cloudrun: {
113063
- 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)
113064
112866
  }
113065
- };
113066
- try {
113067
- fs_1.default.writeFileSync(cloudbasercPath, JSON.stringify(cloudbasercContent, null, 2));
113068
- }
113069
- catch (error) {
113070
- // Ignore cloudbaserc.json creation errors
113071
- }
112867
+ ]
112868
+ };
112869
+ }
112870
+ case 'delete': {
112871
+ if (!input.force) {
113072
112872
  return {
113073
112873
  content: [
113074
112874
  {
113075
112875
  type: "text",
113076
112876
  text: JSON.stringify({
113077
- success: true,
113078
- data: {
113079
- serviceName: input.serverName,
113080
- template: input.template,
113081
- initPath: targetPath,
113082
- projectDir: result.projectDir || path_1.default.join(targetPath, input.serverName),
113083
- cloudbasercGenerated: true
113084
- },
113085
- 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."
113086
112880
  }, null, 2)
113087
112881
  }
113088
112882
  ]
113089
112883
  };
113090
112884
  }
113091
- default:
113092
- 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
+ };
113093
112903
  }
113094
- }
113095
- catch (error) {
113096
- return {
113097
- content: [
113098
- {
113099
- type: "text",
113100
- text: JSON.stringify({
113101
- success: false,
113102
- error: error.message || 'Unknown error occurred',
113103
- message: `Failed to ${args.action} CloudRun service. Please check your permissions and parameters.`
113104
- }, 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
113105
112920
  }
113106
- ]
113107
- };
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}`);
113108
112949
  }
113109
112950
  });
113110
112951
  }
@@ -132455,41 +132296,25 @@ function registerInviteCodeTools(server) {
132455
132296
  ]
132456
132297
  };
132457
132298
  }
132458
- try {
132459
- const manager = await getManager();
132460
- const EnvId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
132461
- const result = await manager.commonService().call({
132462
- Action: 'ActivateInviteCode',
132463
- Param: { InviteCode, EnvId }
132464
- });
132465
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
132466
- return {
132467
- content: [
132468
- {
132469
- type: "text",
132470
- text: JSON.stringify({
132471
- ErrorCode: result?.ErrorCode || '',
132472
- ErrorMsg: result?.ErrorMsg || '',
132473
- RequestId: result?.RequestId || ''
132474
- }, null, 2)
132475
- }
132476
- ]
132477
- };
132478
- }
132479
- catch (e) {
132480
- return {
132481
- content: [
132482
- {
132483
- type: "text",
132484
- text: JSON.stringify({
132485
- ErrorCode: e.code || 'Exception',
132486
- ErrorMsg: '激活失败:' + e.message,
132487
- RequestId: e.RequestId || ''
132488
- }, null, 2)
132489
- }
132490
- ]
132491
- };
132492
- }
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
+ };
132493
132318
  });
132494
132319
  }
132495
132320
 
@@ -137110,7 +136935,7 @@ class TelemetryReporter {
137110
136935
  const nodeVersion = process.version; // Node.js版本
137111
136936
  const arch = os_1.default.arch(); // 系统架构
137112
136937
  // 从构建时注入的版本号获取MCP版本信息
137113
- const mcpVersion = process.env.npm_package_version || "2.9.0" || 0;
136938
+ const mcpVersion = process.env.npm_package_version || "2.10.0" || 0;
137114
136939
  return {
137115
136940
  userAgent: `${osType} ${osRelease} ${arch} ${nodeVersion} CloudBase-MCP/${mcpVersion}`,
137116
136941
  deviceId: this.deviceId,
@@ -203682,7 +203507,7 @@ ${envIdSection}
203682
203507
  ## 环境信息
203683
203508
  - 操作系统: ${os_1.default.type()} ${os_1.default.release()}
203684
203509
  - Node.js版本: ${process.version}
203685
- - MCP 版本:${process.env.npm_package_version || "2.9.0" || 0}
203510
+ - MCP 版本:${process.env.npm_package_version || "2.10.0" || 0}
203686
203511
  - 系统架构: ${os_1.default.arch()}
203687
203512
  - 时间: ${new Date().toISOString()}
203688
203513
  - 请求ID: ${requestId}
@@ -211826,9 +211651,10 @@ checkIndex: 检查索引是否存在`),
211826
211651
  title: "修改 NoSQL 数据库结构",
211827
211652
  description: "修改 NoSQL 数据库结构",
211828
211653
  inputSchema: {
211829
- action: zod_1.z.enum(["createCollection", "updateCollection"])
211654
+ action: zod_1.z.enum(["createCollection", "updateCollection", "deleteCollection"])
211830
211655
  .describe(`createCollection: 创建集合
211831
- updateCollection: 更新集合`),
211656
+ updateCollection: 更新集合
211657
+ deleteCollection: 删除集合`),
211832
211658
  collectionName: zod_1.z.string().describe("集合名称"),
211833
211659
  updateOptions: zod_1.z
211834
211660
  .object({
@@ -211855,68 +211681,74 @@ updateCollection: 更新集合`),
211855
211681
  },
211856
211682
  annotations: {
211857
211683
  readOnlyHint: false,
211858
- destructiveHint: false,
211684
+ destructiveHint: true,
211859
211685
  idempotentHint: false,
211860
211686
  openWorldHint: true,
211861
211687
  category: CATEGORY,
211862
211688
  },
211863
211689
  }, async ({ action, collectionName, updateOptions }) => {
211864
- try {
211865
- const cloudbase = await getManager();
211866
- if (action === "createCollection") {
211867
- const result = await cloudbase.database.createCollection(collectionName);
211868
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
211869
- return {
211870
- content: [
211871
- {
211872
- type: "text",
211873
- text: JSON.stringify({
211874
- success: true,
211875
- requestId: result.RequestId,
211876
- action,
211877
- message: "云开发数据库集合创建成功",
211878
- }, null, 2),
211879
- },
211880
- ],
211881
- };
211882
- }
211883
- if (action === "updateCollection") {
211884
- if (!updateOptions) {
211885
- throw new Error("更新集合时必须提供 options");
211886
- }
211887
- const result = await cloudbase.database.updateCollection(collectionName, updateOptions);
211888
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
211889
- return {
211890
- content: [
211891
- {
211892
- type: "text",
211893
- text: JSON.stringify({
211894
- success: true,
211895
- requestId: result.RequestId,
211896
- action,
211897
- message: "云开发数据库集合更新成功",
211898
- }, null, 2),
211899
- },
211900
- ],
211901
- };
211902
- }
211903
- 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
+ };
211904
211707
  }
211905
- 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);
211906
211714
  return {
211907
211715
  content: [
211908
211716
  {
211909
211717
  type: "text",
211910
211718
  text: JSON.stringify({
211911
- success: false,
211719
+ success: true,
211720
+ requestId: result.RequestId,
211912
211721
  action,
211913
- error: error.message,
211914
- message: "集合创建/更新操作失败",
211722
+ message: "云开发数据库集合更新成功",
211915
211723
  }, null, 2),
211916
211724
  },
211917
211725
  ],
211918
211726
  };
211919
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}`);
211920
211752
  });
211921
211753
  // readNoSqlDatabaseContent
211922
211754
  server.registerTool?.("readNoSqlDatabaseContent", {
@@ -211945,53 +211777,36 @@ updateCollection: 更新集合`),
211945
211777
  category: CATEGORY,
211946
211778
  },
211947
211779
  }, async ({ collectionName, query, projection, sort, limit, offset }) => {
211948
- try {
211949
- const cloudbase = await getManager();
211950
- const instanceId = await getDatabaseInstanceId(getManager);
211951
- // 兼容对象和字符串
211952
- const toJSONString = (v) => typeof v === "object" && v !== null ? JSON.stringify(v) : v;
211953
- const result = await cloudbase.commonService("tcb", "2018-06-08").call({
211954
- Action: "QueryRecords",
211955
- Param: {
211956
- TableName: collectionName,
211957
- MgoQuery: toJSONString(query),
211958
- MgoProjection: toJSONString(projection),
211959
- MgoSort: toJSONString(sort),
211960
- MgoLimit: limit ?? 100, // 默认返回100条,避免底层SDK缺参报错
211961
- MgoOffset: offset,
211962
- 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),
211963
211807
  },
211964
- });
211965
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
211966
- return {
211967
- content: [
211968
- {
211969
- type: "text",
211970
- text: JSON.stringify({
211971
- success: true,
211972
- requestId: result.RequestId,
211973
- data: result.Data,
211974
- pager: result.Pager,
211975
- message: "文档查询成功",
211976
- }, null, 2),
211977
- },
211978
- ],
211979
- };
211980
- }
211981
- catch (error) {
211982
- return {
211983
- content: [
211984
- {
211985
- type: "text",
211986
- text: JSON.stringify({
211987
- success: false,
211988
- error: error.message,
211989
- message: "文档查询失败",
211990
- }, null, 2),
211991
- },
211992
- ],
211993
- };
211994
- }
211808
+ ],
211809
+ };
211995
211810
  });
211996
211811
  // writeNoSqlDatabaseContent
211997
211812
  server.registerTool?.("writeNoSqlDatabaseContent", {
@@ -211999,9 +211814,7 @@ updateCollection: 更新集合`),
211999
211814
  description: "修改 NoSQL 数据库数据记录",
212000
211815
  inputSchema: {
212001
211816
  action: zod_1.z.enum(["insert", "update", "delete"])
212002
- .describe(`createCollection: 创建数据
212003
- updateCollection: 更新数据
212004
- deleteCollection: 删除数据`),
211817
+ .describe(`insert: 插入数据(新增文档)\nupdate: 更新数据\ndelete: 删除数据`),
212005
211818
  collectionName: zod_1.z.string().describe("集合名称"),
212006
211819
  documents: zod_1.z
212007
211820
  .array(zod_1.z.object({}).passthrough())
@@ -212100,98 +211913,70 @@ deleteCollection: 删除数据`),
212100
211913
  });
212101
211914
  }
212102
211915
  async function insertDocuments({ collectionName, documents, getManager, logger, }) {
212103
- try {
212104
- const cloudbase = await getManager();
212105
- const instanceId = await getDatabaseInstanceId(getManager);
212106
- // 将对象数组序列化为字符串数组
212107
- const docsAsStrings = documents.map((doc) => JSON.stringify(doc));
212108
- const result = await cloudbase.commonService("tcb", "2018-06-08").call({
212109
- Action: "PutItem",
212110
- Param: {
212111
- TableName: collectionName,
212112
- MgoDocs: docsAsStrings,
212113
- Tag: instanceId,
212114
- },
212115
- });
212116
- (0, cloudbase_manager_js_1.logCloudBaseResult)(logger, result);
212117
- return JSON.stringify({
212118
- success: true,
212119
- requestId: result.RequestId,
212120
- insertedIds: result.InsertedIds,
212121
- message: "文档插入成功",
212122
- }, null, 2);
212123
- }
212124
- catch (error) {
212125
- return JSON.stringify({
212126
- success: false,
212127
- error: error.message,
212128
- message: "文档插入失败",
212129
- }, null, 2);
212130
- }
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);
212131
211934
  }
212132
211935
  async function updateDocuments({ collectionName, query, update, isMulti, upsert, getManager, logger, }) {
212133
- try {
212134
- const cloudbase = await getManager();
212135
- const instanceId = await getDatabaseInstanceId(getManager);
212136
- const toJSONString = (v) => typeof v === "object" && v !== null ? JSON.stringify(v) : v;
212137
- const result = await cloudbase.commonService("tcb", "2018-06-08").call({
212138
- Action: "UpdateItem",
212139
- Param: {
212140
- TableName: collectionName,
212141
- MgoQuery: toJSONString(query),
212142
- MgoUpdate: toJSONString(update),
212143
- MgoIsMulti: isMulti,
212144
- MgoUpsert: upsert,
212145
- Tag: instanceId,
212146
- },
212147
- });
212148
- (0, cloudbase_manager_js_1.logCloudBaseResult)(logger, result);
212149
- return JSON.stringify({
212150
- success: true,
212151
- requestId: result.RequestId,
212152
- modifiedCount: result.ModifiedNum,
212153
- matchedCount: result.MatchedNum,
212154
- upsertedId: result.UpsertedId,
212155
- message: "文档更新成功",
212156
- }, null, 2);
212157
- }
212158
- catch (error) {
212159
- return JSON.stringify({
212160
- success: false,
212161
- error: error.message,
212162
- message: "文档更新失败",
212163
- }, null, 2);
212164
- }
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);
212165
211959
  }
212166
211960
  async function deleteDocuments({ collectionName, query, isMulti, getManager, logger, }) {
212167
- try {
212168
- const cloudbase = await getManager();
212169
- const instanceId = await getDatabaseInstanceId(getManager);
212170
- const toJSONString = (v) => typeof v === "object" && v !== null ? JSON.stringify(v) : v;
212171
- const result = await cloudbase.commonService("tcb", "2018-06-08").call({
212172
- Action: "DeleteItem",
212173
- Param: {
212174
- TableName: collectionName,
212175
- MgoQuery: toJSONString(query),
212176
- MgoIsMulti: isMulti,
212177
- Tag: instanceId,
212178
- },
212179
- });
212180
- (0, cloudbase_manager_js_1.logCloudBaseResult)(logger, result);
212181
- return JSON.stringify({
212182
- success: true,
212183
- requestId: result.RequestId,
212184
- deleted: result.Deleted,
212185
- message: "文档删除成功",
212186
- }, null, 2);
212187
- }
212188
- catch (error) {
212189
- return JSON.stringify({
212190
- success: false,
212191
- error: error.message,
212192
- message: "文档删除失败",
212193
- }, null, 2);
212194
- }
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);
212195
211980
  }
212196
211981
 
212197
211982
 
@@ -218438,7 +218223,7 @@ function registerSetupTools(server) {
218438
218223
  title: "下载项目模板",
218439
218224
  description: `自动下载并部署CloudBase项目模板。⚠️ **MANDATORY FOR NEW PROJECTS** ⚠️
218440
218225
 
218441
- **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.9.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)`,
218442
218227
  inputSchema: {
218443
218228
  template: zod_1.z
218444
218229
  .enum(["react", "vue", "miniprogram", "uniapp", "rules"])
@@ -265509,94 +265294,78 @@ function registerStorageTools(server) {
265509
265294
  category: "storage"
265510
265295
  }
265511
265296
  }, async (args) => {
265512
- try {
265513
- const input = args;
265514
- const manager = await getManager();
265515
- if (!manager) {
265516
- throw new Error("Failed to initialize CloudBase manager. Please check your credentials and environment configuration.");
265517
- }
265518
- const storageService = manager.storage;
265519
- switch (input.action) {
265520
- case 'list': {
265521
- const result = await storageService.listDirectoryFiles(input.cloudPath);
265522
- return {
265523
- content: [
265524
- {
265525
- type: "text",
265526
- text: JSON.stringify({
265527
- success: true,
265528
- data: {
265529
- action: 'list',
265530
- cloudPath: input.cloudPath,
265531
- files: result || [],
265532
- totalCount: result?.length || 0
265533
- },
265534
- message: `Successfully listed ${result?.length || 0} files in directory '${input.cloudPath}'`
265535
- }, null, 2)
265536
- }
265537
- ]
265538
- };
265539
- }
265540
- case 'info': {
265541
- const result = await storageService.getFileInfo(input.cloudPath);
265542
- return {
265543
- content: [
265544
- {
265545
- type: "text",
265546
- text: JSON.stringify({
265547
- success: true,
265548
- data: {
265549
- action: 'info',
265550
- cloudPath: input.cloudPath,
265551
- fileInfo: result
265552
- },
265553
- message: `Successfully retrieved file info for '${input.cloudPath}'`
265554
- }, null, 2)
265555
- }
265556
- ]
265557
- };
265558
- }
265559
- case 'url': {
265560
- const result = await storageService.getTemporaryUrl([{
265561
- cloudPath: input.cloudPath,
265562
- maxAge: input.maxAge || 3600
265563
- }]);
265564
- return {
265565
- content: [
265566
- {
265567
- type: "text",
265568
- text: JSON.stringify({
265569
- success: true,
265570
- data: {
265571
- action: 'url',
265572
- cloudPath: input.cloudPath,
265573
- temporaryUrl: result[0]?.url || "",
265574
- expireTime: `${input.maxAge || 3600}秒`,
265575
- fileId: result[0]?.fileId || ""
265576
- },
265577
- message: `Successfully generated temporary URL for '${input.cloudPath}'`
265578
- }, null, 2)
265579
- }
265580
- ]
265581
- };
265582
- }
265583
- default:
265584
- 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
+ };
265585
265323
  }
265586
- }
265587
- catch (error) {
265588
- return {
265589
- content: [
265590
- {
265591
- type: "text",
265592
- text: JSON.stringify({
265593
- success: false,
265594
- error: error.message || 'Unknown error occurred',
265595
- message: `Failed to query storage information. Please check your permissions and parameters.`
265596
- }, null, 2)
265597
- }
265598
- ]
265599
- };
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}`);
265600
265369
  }
265601
265370
  });
265602
265371
  // Tool 2: manageStorage - 管理存储文件(写操作)
@@ -265612,151 +265381,128 @@ function registerStorageTools(server) {
265612
265381
  category: "storage"
265613
265382
  }
265614
265383
  }, async (args) => {
265615
- try {
265616
- const input = args;
265617
- const manager = await getManager();
265618
- if (!manager) {
265619
- throw new Error("Failed to initialize CloudBase manager. Please check your credentials and environment configuration.");
265620
- }
265621
- const storageService = manager.storage;
265622
- switch (input.action) {
265623
- case 'upload': {
265624
- if (input.isDirectory) {
265625
- // 上传目录
265626
- await storageService.uploadDirectory({
265627
- localPath: input.localPath,
265628
- cloudPath: input.cloudPath,
265629
- onProgress: (progressData) => {
265630
- console.log("Upload directory progress:", progressData);
265631
- }
265632
- });
265633
- }
265634
- else {
265635
- // 上传文件
265636
- await storageService.uploadFile({
265637
- localPath: input.localPath,
265638
- cloudPath: input.cloudPath,
265639
- onProgress: (progressData) => {
265640
- console.log("Upload file progress:", progressData);
265641
- }
265642
- });
265643
- }
265644
- // 获取文件临时下载地址
265645
- const fileUrls = await storageService.getTemporaryUrl([{
265646
- cloudPath: input.cloudPath,
265647
- maxAge: 3600 // 临时链接有效期1小时
265648
- }]);
265649
- return {
265650
- content: [
265651
- {
265652
- type: "text",
265653
- text: JSON.stringify({
265654
- success: true,
265655
- data: {
265656
- action: 'upload',
265657
- localPath: input.localPath,
265658
- cloudPath: input.cloudPath,
265659
- isDirectory: input.isDirectory,
265660
- temporaryUrl: fileUrls[0]?.url || "",
265661
- expireTime: "1小时"
265662
- },
265663
- message: `Successfully uploaded ${input.isDirectory ? 'directory' : 'file'} from '${input.localPath}' to '${input.cloudPath}'`
265664
- }, null, 2)
265665
- }
265666
- ]
265667
- };
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
+ });
265668
265400
  }
265669
- case 'download': {
265670
- if (input.isDirectory) {
265671
- // 下载目录
265672
- await storageService.downloadDirectory({
265673
- cloudPath: input.cloudPath,
265674
- localPath: input.localPath
265675
- });
265676
- }
265677
- else {
265678
- // 下载文件
265679
- await storageService.downloadFile({
265680
- cloudPath: input.cloudPath,
265681
- localPath: input.localPath
265682
- });
265683
- }
265684
- return {
265685
- content: [
265686
- {
265687
- type: "text",
265688
- text: JSON.stringify({
265689
- success: true,
265690
- data: {
265691
- action: 'download',
265692
- cloudPath: input.cloudPath,
265693
- localPath: input.localPath,
265694
- isDirectory: input.isDirectory
265695
- },
265696
- message: `Successfully downloaded ${input.isDirectory ? 'directory' : 'file'} from '${input.cloudPath}' to '${input.localPath}'`
265697
- }, null, 2)
265698
- }
265699
- ]
265700
- };
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
+ });
265701
265409
  }
265702
- case 'delete': {
265703
- if (!input.force) {
265704
- return {
265705
- content: [
265706
- {
265707
- type: "text",
265708
- text: JSON.stringify({
265709
- success: false,
265710
- error: "Delete operation requires confirmation",
265711
- message: "Please set force: true to confirm deletion. This action cannot be undone."
265712
- }, null, 2)
265713
- }
265714
- ]
265715
- };
265716
- }
265717
- if (input.isDirectory) {
265718
- // 删除目录
265719
- await storageService.deleteDirectory(input.cloudPath);
265720
- }
265721
- else {
265722
- // 删除文件
265723
- await storageService.deleteFile([input.cloudPath]);
265724
- }
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) {
265725
265467
  return {
265726
265468
  content: [
265727
265469
  {
265728
265470
  type: "text",
265729
265471
  text: JSON.stringify({
265730
- success: true,
265731
- data: {
265732
- action: 'delete',
265733
- cloudPath: input.cloudPath,
265734
- isDirectory: input.isDirectory,
265735
- deleted: true
265736
- },
265737
- 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."
265738
265475
  }, null, 2)
265739
265476
  }
265740
265477
  ]
265741
265478
  };
265742
265479
  }
265743
- default:
265744
- 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
+ };
265745
265503
  }
265746
- }
265747
- catch (error) {
265748
- return {
265749
- content: [
265750
- {
265751
- type: "text",
265752
- text: JSON.stringify({
265753
- success: false,
265754
- error: error.message || 'Unknown error occurred',
265755
- message: `Failed to manage storage. Please check your permissions and parameters.`
265756
- }, null, 2)
265757
- }
265758
- ]
265759
- };
265504
+ default:
265505
+ throw new Error(`Unsupported action: ${input.action}`);
265760
265506
  }
265761
265507
  });
265762
265508
  }