@cloudbase/cloudbase-mcp 2.27.0 → 2.28.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/README.zh-CN.md +1 -0
- package/dist/cli.cjs +5 -5
- package/dist/index.cjs +1480 -104
- package/dist/index.js +1511 -135
- package/package.json +4 -2
- package/server.json +60 -0
package/dist/index.cjs
CHANGED
|
@@ -3310,8 +3310,17 @@ warn.forProperties(exports, 'deprecated', ['emitErrs', 'levelLength']);
|
|
|
3310
3310
|
"use strict";
|
|
3311
3311
|
|
|
3312
3312
|
Object.defineProperty(exports, "__esModule", ({ value: true }));
|
|
3313
|
-
exports.DEFAULT_CREATE_ENV_RESOURCES = exports.CREATE_ENV_RESOURCE_VALUES = void 0;
|
|
3313
|
+
exports.GATEWAY_ENV_QPS_DEFAULT_RESOURCE_ID = exports.ENV_METRIC_PERIOD_VALUES = exports.ENV_METRIC_NAME_VALUES = exports.ENV_USAGE_MODULE_VALUES = exports.DEFAULT_CREATE_ENV_RESOURCES = exports.CREATE_ENV_RESOURCE_VALUES = void 0;
|
|
3314
3314
|
exports.resolveCreateEnvResources = resolveCreateEnvResources;
|
|
3315
|
+
exports.resolveEnvUsageModules = resolveEnvUsageModules;
|
|
3316
|
+
exports.extractAccountCircleDate = extractAccountCircleDate;
|
|
3317
|
+
exports.resolveEnvUsageDateRange = resolveEnvUsageDateRange;
|
|
3318
|
+
exports.formatEnvMetricTime = formatEnvMetricTime;
|
|
3319
|
+
exports.resolveEnvMetricName = resolveEnvMetricName;
|
|
3320
|
+
exports.resolveEnvMetricPeriod = resolveEnvMetricPeriod;
|
|
3321
|
+
exports.resolveEnvMetricTimeRange = resolveEnvMetricTimeRange;
|
|
3322
|
+
exports.resolveEnvMetricResourceId = resolveEnvMetricResourceId;
|
|
3323
|
+
exports.summarizeEnvMetricCurve = summarizeEnvMetricCurve;
|
|
3315
3324
|
exports.simplifyEnvList = simplifyEnvList;
|
|
3316
3325
|
exports.isUsableNoSqlDatabaseEntry = isUsableNoSqlDatabaseEntry;
|
|
3317
3326
|
exports.registerEnvTools = registerEnvTools;
|
|
@@ -3343,6 +3352,245 @@ function resolveCreateEnvResources(resources) {
|
|
|
3343
3352
|
}
|
|
3344
3353
|
return [...exports.DEFAULT_CREATE_ENV_RESOURCES];
|
|
3345
3354
|
}
|
|
3355
|
+
/**
|
|
3356
|
+
* Resource-usage modules aligned with tcb CLI `USAGE_MODULES`
|
|
3357
|
+
* (`tcb env usage` / `tcb env info --type`).
|
|
3358
|
+
*/
|
|
3359
|
+
exports.ENV_USAGE_MODULE_VALUES = [
|
|
3360
|
+
"FLEXDB",
|
|
3361
|
+
"TDSQL",
|
|
3362
|
+
"SCF",
|
|
3363
|
+
"EKS",
|
|
3364
|
+
"COS",
|
|
3365
|
+
"AI",
|
|
3366
|
+
"HOSTING",
|
|
3367
|
+
"Auth",
|
|
3368
|
+
"APIInvocation",
|
|
3369
|
+
"HTTPInvocation",
|
|
3370
|
+
"VM",
|
|
3371
|
+
"Workflow",
|
|
3372
|
+
"Other",
|
|
3373
|
+
];
|
|
3374
|
+
const ENV_USAGE_MODULE_SET = new Set(exports.ENV_USAGE_MODULE_VALUES);
|
|
3375
|
+
const ENV_USAGE_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
|
|
3376
|
+
function resolveEnvUsageModules(type) {
|
|
3377
|
+
if (!Array.isArray(type) || type.length === 0) {
|
|
3378
|
+
return [...exports.ENV_USAGE_MODULE_VALUES];
|
|
3379
|
+
}
|
|
3380
|
+
const normalized = type
|
|
3381
|
+
.map((item) => (typeof item === "string" ? item.trim() : ""))
|
|
3382
|
+
.filter(Boolean);
|
|
3383
|
+
const invalid = normalized.filter((item) => !ENV_USAGE_MODULE_SET.has(item));
|
|
3384
|
+
if (invalid.length > 0) {
|
|
3385
|
+
throw new Error(`无效的用量模块 type: ${invalid.join(", ")}。可选值:${exports.ENV_USAGE_MODULE_VALUES.join(", ")}`);
|
|
3386
|
+
}
|
|
3387
|
+
return normalized;
|
|
3388
|
+
}
|
|
3389
|
+
function extractAccountCircleDate(rawTime) {
|
|
3390
|
+
if (typeof rawTime !== "string" || rawTime.trim().length === 0) {
|
|
3391
|
+
return undefined;
|
|
3392
|
+
}
|
|
3393
|
+
const datePart = rawTime.trim().split(/\s+/)[0];
|
|
3394
|
+
return ENV_USAGE_DATE_RE.test(datePart) ? datePart : undefined;
|
|
3395
|
+
}
|
|
3396
|
+
function normalizeUsageDateInput(value) {
|
|
3397
|
+
return typeof value === "string" && value.trim().length > 0
|
|
3398
|
+
? value.trim()
|
|
3399
|
+
: undefined;
|
|
3400
|
+
}
|
|
3401
|
+
function resolveEnvUsageDateRange(options) {
|
|
3402
|
+
const startFromParams = normalizeUsageDateInput(options.startDate);
|
|
3403
|
+
const endFromParams = normalizeUsageDateInput(options.endDate);
|
|
3404
|
+
if (startFromParams || endFromParams) {
|
|
3405
|
+
if (!startFromParams || !endFromParams) {
|
|
3406
|
+
throw new Error("查询资源用量时 startDate 与 endDate 必须同时提供,格式为 YYYY-MM-DD。");
|
|
3407
|
+
}
|
|
3408
|
+
if (!ENV_USAGE_DATE_RE.test(startFromParams) || !ENV_USAGE_DATE_RE.test(endFromParams)) {
|
|
3409
|
+
throw new Error("startDate / endDate 格式必须为 YYYY-MM-DD。");
|
|
3410
|
+
}
|
|
3411
|
+
if (startFromParams > endFromParams) {
|
|
3412
|
+
throw new Error("startDate 不能晚于 endDate。");
|
|
3413
|
+
}
|
|
3414
|
+
return {
|
|
3415
|
+
startDate: startFromParams,
|
|
3416
|
+
endDate: endFromParams,
|
|
3417
|
+
dateSource: "params",
|
|
3418
|
+
};
|
|
3419
|
+
}
|
|
3420
|
+
const startDate = extractAccountCircleDate(options.accountCircle?.StartTime);
|
|
3421
|
+
const endDate = extractAccountCircleDate(options.accountCircle?.EndTime);
|
|
3422
|
+
if (!startDate || !endDate) {
|
|
3423
|
+
throw new Error("无法从计费周期推导用量日期范围。请显式传入 startDate/endDate(YYYY-MM-DD),或确认环境计费周期可用。");
|
|
3424
|
+
}
|
|
3425
|
+
return { startDate, endDate, dateSource: "accountCircle" };
|
|
3426
|
+
}
|
|
3427
|
+
/**
|
|
3428
|
+
* Monitor metric names for queryEnv(action=metrics).
|
|
3429
|
+
* Subset of TCB DescribeCurveData MetricName from the CloudBase monitor catalog
|
|
3430
|
+
* (gateway/env QPS, functions, NoSQL, MySQL, CloudRun).
|
|
3431
|
+
*/
|
|
3432
|
+
exports.ENV_METRIC_NAME_VALUES = [
|
|
3433
|
+
"GatewayTraceEnvQPS",
|
|
3434
|
+
"EnvQPSAll",
|
|
3435
|
+
"FunctionInvocation",
|
|
3436
|
+
"FunctionError",
|
|
3437
|
+
"FunctionTimeout",
|
|
3438
|
+
"FunctionThrottle",
|
|
3439
|
+
"FunctionDuration",
|
|
3440
|
+
"FunctionConcurrentExecutions",
|
|
3441
|
+
"DbRead",
|
|
3442
|
+
"DbWrite",
|
|
3443
|
+
"DbSizepkg",
|
|
3444
|
+
"MysqlCpuUsageRate",
|
|
3445
|
+
"MysqlMemoryUse",
|
|
3446
|
+
"MysqlStorageUsage",
|
|
3447
|
+
"MysqlQps",
|
|
3448
|
+
"MysqlSlowQueries",
|
|
3449
|
+
"MysqlDbConnections",
|
|
3450
|
+
"TkeCpuUsedService",
|
|
3451
|
+
"TkeMemUsedService",
|
|
3452
|
+
"TkeQPSService",
|
|
3453
|
+
"TkeHttpErrorService",
|
|
3454
|
+
"TkeInvokeNumService",
|
|
3455
|
+
];
|
|
3456
|
+
exports.ENV_METRIC_PERIOD_VALUES = [300, 3600, 86400];
|
|
3457
|
+
/** Console default ResourceID for environment-level gateway QPS. */
|
|
3458
|
+
exports.GATEWAY_ENV_QPS_DEFAULT_RESOURCE_ID = "all|:|all|:|all|:|all";
|
|
3459
|
+
const ENV_METRIC_NAME_SET = new Set(exports.ENV_METRIC_NAME_VALUES);
|
|
3460
|
+
const ENV_METRIC_PERIOD_SET = new Set(exports.ENV_METRIC_PERIOD_VALUES);
|
|
3461
|
+
const ENV_METRICS_REQUIRING_RESOURCE_ID = new Set([
|
|
3462
|
+
"TkeCpuUsedService",
|
|
3463
|
+
"TkeMemUsedService",
|
|
3464
|
+
"TkeQPSService",
|
|
3465
|
+
"TkeHttpErrorService",
|
|
3466
|
+
"TkeInvokeNumService",
|
|
3467
|
+
]);
|
|
3468
|
+
const ENV_METRIC_TIME_RE = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/;
|
|
3469
|
+
const ENV_METRIC_MIN_RANGE_MS = 5 * 60 * 1000;
|
|
3470
|
+
function padMetricTimeUnit(value) {
|
|
3471
|
+
return value.toString().padStart(2, "0");
|
|
3472
|
+
}
|
|
3473
|
+
function formatEnvMetricTime(date) {
|
|
3474
|
+
return `${date.getFullYear()}-${padMetricTimeUnit(date.getMonth() + 1)}-${padMetricTimeUnit(date.getDate())} ${padMetricTimeUnit(date.getHours())}:${padMetricTimeUnit(date.getMinutes())}:${padMetricTimeUnit(date.getSeconds())}`;
|
|
3475
|
+
}
|
|
3476
|
+
function resolveEnvMetricName(metricName) {
|
|
3477
|
+
const normalized = typeof metricName === "string" && metricName.trim().length > 0
|
|
3478
|
+
? metricName.trim()
|
|
3479
|
+
: undefined;
|
|
3480
|
+
if (!normalized) {
|
|
3481
|
+
throw new Error(`查询监控指标时 metricName 为必填参数。可选值:${exports.ENV_METRIC_NAME_VALUES.join(", ")}`);
|
|
3482
|
+
}
|
|
3483
|
+
if (!ENV_METRIC_NAME_SET.has(normalized)) {
|
|
3484
|
+
throw new Error(`无效的 metricName: ${normalized}。可选值:${exports.ENV_METRIC_NAME_VALUES.join(", ")}`);
|
|
3485
|
+
}
|
|
3486
|
+
return normalized;
|
|
3487
|
+
}
|
|
3488
|
+
function resolveEnvMetricPeriod(period) {
|
|
3489
|
+
if (period === undefined || period === null || period === "") {
|
|
3490
|
+
return undefined;
|
|
3491
|
+
}
|
|
3492
|
+
const numericPeriod = typeof period === "number"
|
|
3493
|
+
? period
|
|
3494
|
+
: typeof period === "string" && /^\d+$/.test(period.trim())
|
|
3495
|
+
? Number(period.trim())
|
|
3496
|
+
: Number.NaN;
|
|
3497
|
+
if (!ENV_METRIC_PERIOD_SET.has(numericPeriod)) {
|
|
3498
|
+
throw new Error(`period 仅支持 300、3600、86400(秒)。当前值:${String(period)}`);
|
|
3499
|
+
}
|
|
3500
|
+
return numericPeriod;
|
|
3501
|
+
}
|
|
3502
|
+
function resolveEnvMetricTimeRange(options) {
|
|
3503
|
+
const startFromParams = typeof options.startTime === "string" && options.startTime.trim().length > 0
|
|
3504
|
+
? options.startTime.trim()
|
|
3505
|
+
: undefined;
|
|
3506
|
+
const endFromParams = typeof options.endTime === "string" && options.endTime.trim().length > 0
|
|
3507
|
+
? options.endTime.trim()
|
|
3508
|
+
: undefined;
|
|
3509
|
+
if (startFromParams || endFromParams) {
|
|
3510
|
+
if (!startFromParams || !endFromParams) {
|
|
3511
|
+
throw new Error("查询监控指标时 startTime 与 endTime 必须同时提供,格式为 YYYY-MM-DD HH:mm:ss。");
|
|
3512
|
+
}
|
|
3513
|
+
if (!ENV_METRIC_TIME_RE.test(startFromParams) || !ENV_METRIC_TIME_RE.test(endFromParams)) {
|
|
3514
|
+
throw new Error("startTime / endTime 格式必须为 YYYY-MM-DD HH:mm:ss。");
|
|
3515
|
+
}
|
|
3516
|
+
const startMs = Date.parse(startFromParams.replace(" ", "T"));
|
|
3517
|
+
const endMs = Date.parse(endFromParams.replace(" ", "T"));
|
|
3518
|
+
if (Number.isNaN(startMs) || Number.isNaN(endMs)) {
|
|
3519
|
+
throw new Error("startTime / endTime 无法解析为有效时间。");
|
|
3520
|
+
}
|
|
3521
|
+
if (endMs - startMs < ENV_METRIC_MIN_RANGE_MS) {
|
|
3522
|
+
throw new Error("结束时间需要晚于开始时间至少五分钟(监控最小粒度为 5 分钟)。");
|
|
3523
|
+
}
|
|
3524
|
+
return {
|
|
3525
|
+
startTime: startFromParams,
|
|
3526
|
+
endTime: endFromParams,
|
|
3527
|
+
timeSource: "params",
|
|
3528
|
+
};
|
|
3529
|
+
}
|
|
3530
|
+
const now = options.now ?? new Date();
|
|
3531
|
+
const start = new Date(now.getTime() - 24 * 60 * 60 * 1000);
|
|
3532
|
+
return {
|
|
3533
|
+
startTime: formatEnvMetricTime(start),
|
|
3534
|
+
endTime: formatEnvMetricTime(now),
|
|
3535
|
+
timeSource: "defaultLast24h",
|
|
3536
|
+
};
|
|
3537
|
+
}
|
|
3538
|
+
function resolveEnvMetricResourceId(metricName, resourceID) {
|
|
3539
|
+
const normalized = typeof resourceID === "string" && resourceID.trim().length > 0
|
|
3540
|
+
? resourceID.trim()
|
|
3541
|
+
: undefined;
|
|
3542
|
+
if (normalized) {
|
|
3543
|
+
return normalized;
|
|
3544
|
+
}
|
|
3545
|
+
if (metricName === "GatewayTraceEnvQPS") {
|
|
3546
|
+
return exports.GATEWAY_ENV_QPS_DEFAULT_RESOURCE_ID;
|
|
3547
|
+
}
|
|
3548
|
+
if (ENV_METRICS_REQUIRING_RESOURCE_ID.has(metricName)) {
|
|
3549
|
+
throw new Error(`查询 ${metricName} 时 resourceID 为必填(云托管服务名)。请先 queryCloudRun(action="list") 获取服务名后再查询。`);
|
|
3550
|
+
}
|
|
3551
|
+
return undefined;
|
|
3552
|
+
}
|
|
3553
|
+
function summarizeEnvMetricCurve(curve) {
|
|
3554
|
+
const newValues = Array.isArray(curve.NewValues) ? curve.NewValues : [];
|
|
3555
|
+
const values = Array.isArray(curve.Values) ? curve.Values : [];
|
|
3556
|
+
const times = Array.isArray(curve.Time) ? curve.Time : [];
|
|
3557
|
+
const series = (newValues.length > 0 ? newValues : values).filter((item) => typeof item === "number" && Number.isFinite(item));
|
|
3558
|
+
if (series.length === 0) {
|
|
3559
|
+
return {
|
|
3560
|
+
sampleCount: 0,
|
|
3561
|
+
max: null,
|
|
3562
|
+
min: null,
|
|
3563
|
+
avg: null,
|
|
3564
|
+
latest: null,
|
|
3565
|
+
peakTimestamp: null,
|
|
3566
|
+
allZero: true,
|
|
3567
|
+
};
|
|
3568
|
+
}
|
|
3569
|
+
let max = series[0];
|
|
3570
|
+
let min = series[0];
|
|
3571
|
+
let sum = 0;
|
|
3572
|
+
let peakIndex = 0;
|
|
3573
|
+
for (let i = 0; i < series.length; i++) {
|
|
3574
|
+
const value = series[i];
|
|
3575
|
+
sum += value;
|
|
3576
|
+
if (value > max) {
|
|
3577
|
+
max = value;
|
|
3578
|
+
peakIndex = i;
|
|
3579
|
+
}
|
|
3580
|
+
if (value < min) {
|
|
3581
|
+
min = value;
|
|
3582
|
+
}
|
|
3583
|
+
}
|
|
3584
|
+
return {
|
|
3585
|
+
sampleCount: series.length,
|
|
3586
|
+
max,
|
|
3587
|
+
min,
|
|
3588
|
+
avg: sum / series.length,
|
|
3589
|
+
latest: series[series.length - 1],
|
|
3590
|
+
peakTimestamp: typeof times[peakIndex] === "number" ? times[peakIndex] : null,
|
|
3591
|
+
allZero: series.every((value) => value === 0),
|
|
3592
|
+
};
|
|
3593
|
+
}
|
|
3346
3594
|
/**
|
|
3347
3595
|
* Simplify environment list data by keeping only essential fields for AI assistant
|
|
3348
3596
|
* This reduces token consumption when returning environment lists via MCP tools
|
|
@@ -4196,6 +4444,19 @@ function buildEnvQueryErrorMessage(error, action) {
|
|
|
4196
4444
|
if (hasNetworkError) {
|
|
4197
4445
|
suggestions.push("网络错误:请检查网络连接,稍后重试。");
|
|
4198
4446
|
}
|
|
4447
|
+
if (action === "usage" && suggestions.length === 0) {
|
|
4448
|
+
suggestions.push("查询环境资源用量失败,建议:");
|
|
4449
|
+
suggestions.push("1. 先调用 auth(action=\"status\") 确认登录状态;未登录则 auth(action=\"start_auth\")");
|
|
4450
|
+
suggestions.push("2. 使用 queryEnv(action=\"list\") 确认 envId 正确且可访问");
|
|
4451
|
+
suggestions.push(`3. 再调用 queryEnv(action=\"usage\", envId=\"<EnvId>\");可用 type 过滤模块(${exports.ENV_USAGE_MODULE_VALUES.join(", ")})`);
|
|
4452
|
+
}
|
|
4453
|
+
if (action === "metrics" && suggestions.length === 0) {
|
|
4454
|
+
suggestions.push("查询环境监控指标失败,建议:");
|
|
4455
|
+
suggestions.push("1. 先调用 auth(action=\"status\") 确认登录状态;未登录则 auth(action=\"start_auth\")");
|
|
4456
|
+
suggestions.push("2. 使用 queryEnv(action=\"list\") 确认 envId 正确且可访问");
|
|
4457
|
+
suggestions.push(`3. 再调用 queryEnv(action=\"metrics\", envId=\"<EnvId>\", metricName=\"GatewayTraceEnvQPS\");metricName 可选值:${exports.ENV_METRIC_NAME_VALUES.join(", ")}`);
|
|
4458
|
+
suggestions.push("4. startTime/endTime 格式为 YYYY-MM-DD HH:mm:ss,须成对传入;period 仅 300/3600/86400");
|
|
4459
|
+
}
|
|
4199
4460
|
// If no specific pattern matched, provide general guidance
|
|
4200
4461
|
if (suggestions.length === 0) {
|
|
4201
4462
|
suggestions.push("查询环境信息时出错,建议:");
|
|
@@ -5106,8 +5367,8 @@ function registerEnvTools(server) {
|
|
|
5106
5367
|
}
|
|
5107
5368
|
});
|
|
5108
5369
|
} // end: wxide guard for auth tool
|
|
5109
|
-
// queryEnv - 环境查询(合并 listEnvs + getEnvInfo + getEnvAuthDomains)
|
|
5110
|
-
const queryEnvHandler = async ({ action, alias, aliasExact, envId, limit, offset, fields, }) => {
|
|
5370
|
+
// queryEnv - 环境查询(合并 listEnvs + getEnvInfo + getEnvAuthDomains + usage + metrics)
|
|
5371
|
+
const queryEnvHandler = async ({ action, alias, aliasExact, envId, limit, offset, fields, type, startDate, endDate, needUsageDetails, metricName, startTime, endTime, period, resourceID, subresourceID, }) => {
|
|
5111
5372
|
try {
|
|
5112
5373
|
let result;
|
|
5113
5374
|
switch (action) {
|
|
@@ -5269,6 +5530,94 @@ function registerEnvTools(server) {
|
|
|
5269
5530
|
};
|
|
5270
5531
|
}
|
|
5271
5532
|
break;
|
|
5533
|
+
case "usage": {
|
|
5534
|
+
// Explicit EnvId is required (DescribeEnvPostpayPackage / credits APIs reject missing EnvId).
|
|
5535
|
+
const usageEnvId = normalizeOptionalToolString(envId);
|
|
5536
|
+
if (!usageEnvId) {
|
|
5537
|
+
throw new Error('查询资源用量时 envId 为必填参数。请先调用 queryEnv(action="list") 获取 EnvId,再调用 queryEnv(action="usage", envId="<EnvId>")。');
|
|
5538
|
+
}
|
|
5539
|
+
const modules = resolveEnvUsageModules(type);
|
|
5540
|
+
const includeDetails = typeof needUsageDetails === "boolean" ? needUsageDetails : true;
|
|
5541
|
+
const cloudbaseUsage = await getManagerForEnvQuery(usageEnvId);
|
|
5542
|
+
const accountCircle = await cloudbaseUsage.env.describeEnvAccountCircle({
|
|
5543
|
+
EnvId: usageEnvId,
|
|
5544
|
+
});
|
|
5545
|
+
(0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, accountCircle);
|
|
5546
|
+
const dateRange = resolveEnvUsageDateRange({
|
|
5547
|
+
startDate,
|
|
5548
|
+
endDate,
|
|
5549
|
+
accountCircle,
|
|
5550
|
+
});
|
|
5551
|
+
const usageDetail = await cloudbaseUsage.env.describeCreditsUsageDetail({
|
|
5552
|
+
EnvId: usageEnvId,
|
|
5553
|
+
Modules: modules,
|
|
5554
|
+
StartDate: dateRange.startDate,
|
|
5555
|
+
EndDate: dateRange.endDate,
|
|
5556
|
+
NeedUsageDetails: includeDetails,
|
|
5557
|
+
});
|
|
5558
|
+
(0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, usageDetail);
|
|
5559
|
+
result = {
|
|
5560
|
+
EnvId: usageEnvId,
|
|
5561
|
+
Modules: modules,
|
|
5562
|
+
StartDate: dateRange.startDate,
|
|
5563
|
+
EndDate: dateRange.endDate,
|
|
5564
|
+
DateSource: dateRange.dateSource,
|
|
5565
|
+
NeedUsageDetails: includeDetails,
|
|
5566
|
+
AccountCircle: {
|
|
5567
|
+
StartTime: accountCircle?.StartTime,
|
|
5568
|
+
EndTime: accountCircle?.EndTime,
|
|
5569
|
+
HistoryTime: accountCircle?.HistoryTime ?? [],
|
|
5570
|
+
RequestId: accountCircle?.RequestId,
|
|
5571
|
+
},
|
|
5572
|
+
Usages: usageDetail?.Usages ?? [],
|
|
5573
|
+
RequestId: usageDetail?.RequestId,
|
|
5574
|
+
};
|
|
5575
|
+
break;
|
|
5576
|
+
}
|
|
5577
|
+
case "metrics": {
|
|
5578
|
+
const metricsEnvId = normalizeOptionalToolString(envId);
|
|
5579
|
+
if (!metricsEnvId) {
|
|
5580
|
+
throw new Error('查询监控指标时 envId 为必填参数。请先调用 queryEnv(action="list") 获取 EnvId,再调用 queryEnv(action="metrics", envId="<EnvId>", metricName="GatewayTraceEnvQPS")。');
|
|
5581
|
+
}
|
|
5582
|
+
const resolvedMetricName = resolveEnvMetricName(metricName);
|
|
5583
|
+
const timeRange = resolveEnvMetricTimeRange({ startTime, endTime });
|
|
5584
|
+
const resolvedPeriod = resolveEnvMetricPeriod(period);
|
|
5585
|
+
const resolvedResourceId = resolveEnvMetricResourceId(resolvedMetricName, resourceID);
|
|
5586
|
+
const resolvedSubresourceId = normalizeOptionalToolString(subresourceID);
|
|
5587
|
+
const cloudbaseMetrics = await getManagerForEnvQuery(metricsEnvId);
|
|
5588
|
+
if (typeof cloudbaseMetrics?.monitor?.describeCurveData !== "function") {
|
|
5589
|
+
throw new Error("当前 CloudBase Manager 不支持 monitor.describeCurveData。请升级 @cloudbase/manager-node。");
|
|
5590
|
+
}
|
|
5591
|
+
const curveParams = {
|
|
5592
|
+
MetricName: resolvedMetricName,
|
|
5593
|
+
StartTime: timeRange.startTime,
|
|
5594
|
+
EndTime: timeRange.endTime,
|
|
5595
|
+
};
|
|
5596
|
+
if (resolvedPeriod !== undefined) {
|
|
5597
|
+
curveParams.Period = resolvedPeriod;
|
|
5598
|
+
}
|
|
5599
|
+
if (resolvedResourceId) {
|
|
5600
|
+
curveParams.ResourceID = resolvedResourceId;
|
|
5601
|
+
}
|
|
5602
|
+
if (resolvedSubresourceId) {
|
|
5603
|
+
curveParams.SubresourceID = resolvedSubresourceId;
|
|
5604
|
+
}
|
|
5605
|
+
const curve = await cloudbaseMetrics.monitor.describeCurveData(curveParams);
|
|
5606
|
+
(0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, curve);
|
|
5607
|
+
result = {
|
|
5608
|
+
EnvId: metricsEnvId,
|
|
5609
|
+
MetricName: resolvedMetricName,
|
|
5610
|
+
StartTime: timeRange.startTime,
|
|
5611
|
+
EndTime: timeRange.endTime,
|
|
5612
|
+
TimeSource: timeRange.timeSource,
|
|
5613
|
+
Period: resolvedPeriod ?? curve?.Period,
|
|
5614
|
+
ResourceID: resolvedResourceId,
|
|
5615
|
+
SubresourceID: resolvedSubresourceId,
|
|
5616
|
+
Curve: curve,
|
|
5617
|
+
Summary: summarizeEnvMetricCurve(curve ?? {}),
|
|
5618
|
+
};
|
|
5619
|
+
break;
|
|
5620
|
+
}
|
|
5272
5621
|
default:
|
|
5273
5622
|
throw new Error(`不支持的查询类型: ${action}`);
|
|
5274
5623
|
}
|
|
@@ -5301,20 +5650,63 @@ function registerEnvTools(server) {
|
|
|
5301
5650
|
// Register primary tool name (queryEnv)
|
|
5302
5651
|
const queryEnvToolSchema = {
|
|
5303
5652
|
title: "CloudBase 环境查询",
|
|
5304
|
-
description: "查询 CloudBase
|
|
5653
|
+
description: "查询 CloudBase 环境相关信息,支持查询环境列表、指定环境详情、安全域名、资源用量与监控指标。(曾用名:envQuery、listEnvs、getEnvInfo、getEnvAuthDomains)当 action=list 时,会按 DescribeEnvs 语义做列表/筛选,标准返回字段为 EnvId、Alias、Status、EnvType、Region、PackageId、PackageName、IsDefault,并支持通过 fields 白名单裁剪这些字段;aliasExact=true 时会按别名精确筛选,避免把前缀相近的环境误当作候选;即使传入 envId,action=list 也只返回摘要,不会返回完整资源明细或 expiry。如需查询某个已知 EnvId 对应环境的详细信息(包括资源字段和计费信息),必须使用 action=info 并传入目标环境的 envId 参数。action=info 会在可用时补充 BillingInfo(如 ExpireTime、PayMode、IsAutoRenew 等计费字段)。\n\n📊 action=usage 对齐 tcb env usage/info:透传 Manager SDK describeEnvAccountCircle + describeCreditsUsageDetail,返回计费周期与各模块资源点用量(FLEXDB/SCF/COS 等)。envId 必填;type 可选过滤模块;未传 startDate/endDate 时自动使用当前计费周期。\n\n📈 action=metrics 对齐 TCB DescribeCurveData(manager.monitor.describeCurveData,不是云监控 GetMonitorData):查询环境/网关 QPS、云函数调用与错误、数据库 CPU/内存/磁盘、云托管 CPU/QPS 等时序。envId 与 metricName 必填;startTime/endTime 格式 YYYY-MM-DD HH:mm:ss,须成对传入,不传则默认最近 24 小时;period 仅 300/3600/86400。GatewayTraceEnvQPS 未传 resourceID 时自动填环境级 all|:|all|:|all|:|all;云托管 Tke* 指标必须传服务名 resourceID。禁止用 callCloudApi 猜测监控 Action。\n\n🔍 action=info 还会派生三个用于后端选型的字段:\n- `EnvInfo.RuntimeMode`:'postgresql' 或 'nosql',表示新业务建议默认使用的后端(PG 已开通时为 postgresql,否则为 nosql)。\n- `EnvInfo.RuntimeBackends`:`{postgresql, nosql, mysql}` 三个布尔值,描述当前环境实际并存的后端。\n- `EnvInfo.RuntimeModeHints`:每个后端对应的 API/工具/skill 提示。\n\n🌐 action=info 还会在不改写 `StaticStorages[].StaticDomain`(云 API 名义域名)的前提下,投影网关路由 Enable 状态:`StaticStorages[].staticDomainRouteEnabled` 与 `EnvInfo.staticDomainRouteEnabled`(与 queryHosting websiteConfig 同源)。`false` 表示默认静态域名根路由已禁用(访问会返回 GATEWAY_ROUTE_DISABLED),勿把名义域名当成可达 URL。\n\nAI 在写业务/权限/存储代码前必须先看这三项:PG 模式下新业务推荐 `app.rdb()` + RLS(`managePgDatabase action=execute` 跑 `CREATE POLICY`)+ pgstore;已存在的 NoSQL 集合 / 旧 storage / `managePermissions(resourceType=\"noSqlDatabase\")` 在 PG 环境下仍然有效。真正不适用的是 MySQL:当 `RuntimeBackends.mysql === false` 时,`manageMysqlDatabase` / `queryMysqlDatabase` / `relational-database-mcp-cloudbase` skill 都不该使用。",
|
|
5305
5654
|
inputSchema: {
|
|
5306
5655
|
action: zod_1.z
|
|
5307
|
-
.enum(["list", "info", "domains"])
|
|
5308
|
-
.describe("查询类型:list=环境列表/摘要筛选(按 DescribeEnvs 语义筛选,支持通过 envId 筛选,返回 EnvId、Alias、Status、EnvType、Region、PackageId、PackageName、IsDefault,不支持 expiry),info=指定环境的详细信息(必须传入 envId,返回资源字段和计费信息),domains
|
|
5656
|
+
.enum(["list", "info", "domains", "usage", "metrics"])
|
|
5657
|
+
.describe("查询类型:list=环境列表/摘要筛选(按 DescribeEnvs 语义筛选,支持通过 envId 筛选,返回 EnvId、Alias、Status、EnvType、Region、PackageId、PackageName、IsDefault,不支持 expiry),info=指定环境的详细信息(必须传入 envId,返回资源字段和计费信息),domains=安全域名列表,usage=环境资源用量(必须传入 envId,对齐 tcb env usage/info),metrics=环境监控时序(必须传入 envId 与 metricName,对齐 TCB DescribeCurveData)"),
|
|
5309
5658
|
alias: zod_1.z.string().optional().describe("按环境别名筛选。action=list 时可选"),
|
|
5310
5659
|
aliasExact: zod_1.z.boolean().optional().describe("按环境别名精确筛选。action=list 时可选;与 alias 配合使用"),
|
|
5311
|
-
envId: zod_1.z
|
|
5660
|
+
envId: zod_1.z
|
|
5661
|
+
.string()
|
|
5662
|
+
.optional()
|
|
5663
|
+
.describe("环境 ID。action=list 时可选(仅按 DescribeEnvs 语义做筛选,仍返回摘要);action=info / action=usage / action=metrics 时必填。"),
|
|
5312
5664
|
limit: zod_1.z.number().int().positive().optional().describe("返回数量上限。action=list 时可选"),
|
|
5313
5665
|
offset: zod_1.z.number().int().min(0).optional().describe("分页偏移。action=list 时可选"),
|
|
5314
5666
|
fields: zod_1.z
|
|
5315
5667
|
.array(zod_1.z.enum(DEFAULT_ENV_FIELDS))
|
|
5316
5668
|
.optional()
|
|
5317
5669
|
.describe("返回字段白名单。仅支持 EnvId、Alias、Status、EnvType、Region、PackageId、PackageName、IsDefault。action=list 时可选"),
|
|
5670
|
+
type: zod_1.z
|
|
5671
|
+
.array(zod_1.z.enum(exports.ENV_USAGE_MODULE_VALUES))
|
|
5672
|
+
.optional()
|
|
5673
|
+
.describe("用量模块过滤。仅 action=usage 时有效;不传则查询全部模块。可选值对齐 tcb CLI:FLEXDB、TDSQL、SCF、EKS、COS、AI、HOSTING、Auth、APIInvocation、HTTPInvocation、VM、Workflow、Other。"),
|
|
5674
|
+
startDate: zod_1.z
|
|
5675
|
+
.string()
|
|
5676
|
+
.optional()
|
|
5677
|
+
.describe("用量开始日期(YYYY-MM-DD)。仅 action=usage 时有效;与 endDate 成对传入。不传则使用当前计费周期。"),
|
|
5678
|
+
endDate: zod_1.z
|
|
5679
|
+
.string()
|
|
5680
|
+
.optional()
|
|
5681
|
+
.describe("用量结束日期(YYYY-MM-DD)。仅 action=usage 时有效;与 startDate 成对传入。不传则使用当前计费周期。"),
|
|
5682
|
+
needUsageDetails: zod_1.z
|
|
5683
|
+
.boolean()
|
|
5684
|
+
.optional()
|
|
5685
|
+
.describe("是否返回每日用量明细。仅 action=usage 时有效;默认 true。"),
|
|
5686
|
+
metricName: zod_1.z
|
|
5687
|
+
.enum(exports.ENV_METRIC_NAME_VALUES)
|
|
5688
|
+
.optional()
|
|
5689
|
+
.describe("监控指标名。仅 action=metrics 时有效且必填。GatewayTraceEnvQPS/EnvQPSAll=环境与网关 QPS;FunctionInvocation/FunctionError/FunctionTimeout/FunctionThrottle=云函数调用、错误、超时、限流;DbRead/DbWrite/DbSizepkg=文档库读写与容量;MysqlCpuUsageRate/MysqlMemoryUse/MysqlStorageUsage=SQL 库 CPU/内存/磁盘;TkeCpuUsedService/TkeQPSService/TkeHttpErrorService=云托管 CPU/QPS/错误。"),
|
|
5690
|
+
startTime: zod_1.z
|
|
5691
|
+
.string()
|
|
5692
|
+
.optional()
|
|
5693
|
+
.describe("监控开始时间(YYYY-MM-DD HH:mm:ss)。仅 action=metrics 时有效;与 endTime 成对传入。不传则默认最近 24 小时。结束时间须晚于开始时间至少五分钟。"),
|
|
5694
|
+
endTime: zod_1.z
|
|
5695
|
+
.string()
|
|
5696
|
+
.optional()
|
|
5697
|
+
.describe("监控结束时间(YYYY-MM-DD HH:mm:ss)。仅 action=metrics 时有效;与 startTime 成对传入。不传则默认最近 24 小时。"),
|
|
5698
|
+
period: zod_1.z
|
|
5699
|
+
.union([zod_1.z.literal(300), zod_1.z.literal(3600), zod_1.z.literal(86400)])
|
|
5700
|
+
.optional()
|
|
5701
|
+
.describe("统计周期(秒)。仅 action=metrics 时有效;仅支持 300、3600、86400。不传则由后端按时间范围自动选择。时间范围 ≤1 天不可用 86400;>3 天不可用 300。"),
|
|
5702
|
+
resourceID: zod_1.z
|
|
5703
|
+
.string()
|
|
5704
|
+
.optional()
|
|
5705
|
+
.describe("资源 ID。仅 action=metrics 时有效。云函数传函数名,文档库传集合名,云托管必须传服务名;GatewayTraceEnvQPS 不传则使用环境级 all|:|all|:|all|:|all。"),
|
|
5706
|
+
subresourceID: zod_1.z
|
|
5707
|
+
.string()
|
|
5708
|
+
.optional()
|
|
5709
|
+
.describe("子资源 ID。仅 action=metrics 时有效;查询云托管某版本监控时传入版本名。"),
|
|
5318
5710
|
},
|
|
5319
5711
|
annotations: {
|
|
5320
5712
|
readOnlyHint: true,
|
|
@@ -116574,9 +116966,18 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
116574
116966
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
116575
116967
|
};
|
|
116576
116968
|
Object.defineProperty(exports, "__esModule", ({ value: true }));
|
|
116577
|
-
exports.CLOUDRUN_PACKAGE_TYPES = exports.CLOUDRUN_ACCESS_TYPES = exports.CLOUDRUN_SERVICE_TYPES = void 0;
|
|
116969
|
+
exports.CLOUDRUN_ENV_TYPE = exports.CLOUDRUN_DEPLOY_REGISTRATION_INTERVAL_MS = exports.CLOUDRUN_DEPLOY_REGISTRATION_MAX_WAIT_MS = exports.CLOUDRUN_PACKAGE_TYPES = exports.CLOUDRUN_ACCESS_TYPES = exports.CLOUDRUN_SERVICE_TYPES = void 0;
|
|
116970
|
+
exports.buildManageCloudRunErrorMessage = buildManageCloudRunErrorMessage;
|
|
116971
|
+
exports.isValidCloudRunBuildId = isValidCloudRunBuildId;
|
|
116972
|
+
exports.isValidCloudRunRunId = isValidCloudRunRunId;
|
|
116973
|
+
exports.waitForCloudRunDeployRegistration = waitForCloudRunDeployRegistration;
|
|
116974
|
+
exports.buildCloudRunDeployNextStep = buildCloudRunDeployNextStep;
|
|
116975
|
+
exports.buildCloudRunDeployProgressHint = buildCloudRunDeployProgressHint;
|
|
116578
116976
|
exports.queryCloudRunEnvStatus = queryCloudRunEnvStatus;
|
|
116579
116977
|
exports.describeCloudRunEnvStatus = describeCloudRunEnvStatus;
|
|
116978
|
+
exports.extractEnvBaseInfoVpc = extractEnvBaseInfoVpc;
|
|
116979
|
+
exports.resolveCloudRunDeployVpcInfo = resolveCloudRunDeployVpcInfo;
|
|
116980
|
+
exports.buildCreateCloudRunEnvParam = buildCreateCloudRunEnvParam;
|
|
116580
116981
|
exports.ensureCloudRunEnvInitialized = ensureCloudRunEnvInitialized;
|
|
116581
116982
|
exports.detectCloudRunDbNetworkRisk = detectCloudRunDbNetworkRisk;
|
|
116582
116983
|
exports.extractCloudRunImageInfo = extractCloudRunImageInfo;
|
|
@@ -116589,6 +116990,7 @@ const cloudbase_manager_js_1 = __webpack_require__(3431);
|
|
|
116589
116990
|
const logger_js_1 = __webpack_require__(13039);
|
|
116590
116991
|
const gateway_access_urls_js_1 = __webpack_require__(22435);
|
|
116591
116992
|
const notification_js_1 = __webpack_require__(32720);
|
|
116993
|
+
const capi_js_1 = __webpack_require__(40738);
|
|
116592
116994
|
const cloudrun_config_js_1 = __webpack_require__(48266);
|
|
116593
116995
|
// CloudRun service types
|
|
116594
116996
|
exports.CLOUDRUN_SERVICE_TYPES = ['function', 'container'];
|
|
@@ -116598,7 +117000,7 @@ exports.CLOUDRUN_ACCESS_TYPES = ['OA', 'PUBLIC', 'MINIAPP', 'VPC'];
|
|
|
116598
117000
|
exports.CLOUDRUN_PACKAGE_TYPES = ['Trial', 'Standard', 'Professional', 'Enterprise'];
|
|
116599
117001
|
// Input schema for queryCloudRun tool
|
|
116600
117002
|
const queryCloudRunInputSchema = {
|
|
116601
|
-
action: zod_1.z.enum(['list', 'detail', 'templates', 'getDeployLog', 'envStatus']).describe('查询操作类型:list=获取云托管服务列表(支持分页和筛选),detail=查询指定服务的详细信息(包含服务配置和最新部署状态),templates=获取可用的项目模板列表(用于初始化新项目),getDeployLog
|
|
117003
|
+
action: zod_1.z.enum(['list', 'detail', 'templates', 'getDeployLog', 'getProcessLog', 'getDeployRecords', 'envStatus']).describe('查询操作类型:list=获取云托管服务列表(支持分页和筛选),detail=查询指定服务的详细信息(包含服务配置和最新部署状态),templates=获取可用的项目模板列表(用于初始化新项目),getDeployLog=获取构建日志(仅云端源码构建有意义,走 CODING/DescribeCloudRunBuildLog;已有镜像部署无构建过程;未登录 CODING 的账号会报错),getProcessLog=获取运行日志(部署阶段步骤+容器启动/运行日志,走 tcbr/DescribeCloudRunProcessLog;镜像部署与源码构建均可用,不依赖 CODING;RunId 来自 detail/getDeployRecords 的 latestDeploy.RunId),getDeployRecords=获取指定服务的部署记录列表(按部署时间倒序,含 BuildId/RunId/FlowRatio/Status 等字段,用于查看历史发布与回滚上下文),envStatus=查询当前环境云托管是否已开通及开通状态(Status=creating开通中/normal已开通),用于initEnv之后轮询进度或deploy之前确认环境是否就绪'),
|
|
116602
117004
|
// List operation parameters
|
|
116603
117005
|
pageSize: zod_1.z.number().min(1).max(100).optional().default(10).describe('分页大小,控制每页返回的服务数量。取值范围:1-100,默认值:10。建议根据网络性能和显示需求调整'),
|
|
116604
117006
|
pageNum: zod_1.z.number().min(1).optional().default(1).describe('页码,用于分页查询。从1开始,默认值:1。配合pageSize使用可实现分页浏览'),
|
|
@@ -116606,19 +117008,26 @@ const queryCloudRunInputSchema = {
|
|
|
116606
117008
|
serverType: zod_1.z.enum(exports.CLOUDRUN_SERVICE_TYPES).optional().describe('服务类型筛选条件:function=函数型云托管(仅支持Node.js,有特殊的开发要求和限制,适合简单的API服务),container=容器型服务(推荐使用,支持任意语言和框架如Java/Go/Python/PHP/.NET等,适合大多数应用场景)'),
|
|
116607
117009
|
envId: zod_1.z.string().optional().describe('环境 ID(action=envStatus 时使用;不传则使用当前配置的环境)。格式如 env-xxxxxx'),
|
|
116608
117010
|
// Detail and log operation parameters
|
|
116609
|
-
detailServerName: zod_1.z.string().optional().describe('
|
|
116610
|
-
buildId: zod_1.z.number().optional().describe('构建ID,仅在action=getDeployLog
|
|
117011
|
+
detailServerName: zod_1.z.string().optional().describe('要查询详细信息、部署记录、构建日志或运行日志的服务名称。当action为detail、getDeployLog、getProcessLog或getDeployRecords时建议提供,必须是已存在的服务名称。可通过list操作获取可用的服务名称列表'),
|
|
117012
|
+
buildId: zod_1.z.number().optional().describe('构建ID,仅在action=getDeployLog时使用(构建日志,仅云端源码构建)。不传时默认返回最近一次部署的构建日志'),
|
|
117013
|
+
runId: zod_1.z.string().optional().describe('运行ID(RunId),仅在action=getProcessLog时使用。不传时默认取该服务最近一次部署记录的 RunId(与 detail/getDeployRecords 的 latestDeploy.RunId 同源)。镜像部署与源码构建均可查询运行日志'),
|
|
116611
117014
|
};
|
|
116612
117015
|
// Input schema for manageCloudRun tool
|
|
116613
117016
|
const ManageCloudRunInputSchema = {
|
|
116614
|
-
action: zod_1.z.enum(['init', 'download', 'run', 'deploy', 'delete', 'createAgent', 'updateConfig', 'initEnv']).describe('云托管服务管理操作类型:init=从模板初始化新的云托管项目代码(在targetPath目录下创建以serverName命名的子目录,支持多种语言和框架模板),download=从云端下载现有服务的代码到本地进行开发,run=在本地运行函数型云托管服务(用于开发和调试,仅支持函数型服务),deploy
|
|
117017
|
+
action: zod_1.z.enum(['init', 'download', 'run', 'deploy', 'delete', 'createAgent', 'updateConfig', 'initEnv', 'traffic']).describe('云托管服务管理操作类型:init=从模板初始化新的云托管项目代码(在targetPath目录下创建以serverName命名的子目录,支持多种语言和框架模板),download=从云端下载现有服务的代码到本地进行开发,run=在本地运行函数型云托管服务(用于开发和调试,仅支持函数型服务),deploy=触发部署并轻量等待任务注册(不会 hang 等完整构建)。源码构建(targetPath)返回 buildId,用 getDeployLog 轮询后再 getProcessLog;已有镜像部署(imageUrl,DeployType=image,BuildId 常为 0)跳过 getDeployLog,用 detail/getDeployRecords 取 RunId 后 getProcessLog。传 imageUrl 时 targetPath 可省略;已存在服务会 Read-Merge-Write 保留远程 VpcConf/EnvParams/OpenAccessTypes),updateConfig=仅更新服务配置不重新上传代码(对齐控制台服务设置,走 SubmitServerConfigChangeDiff;不需要 targetPath),delete=删除指定的云托管服务(不可恢复,需要确认),createAgent=创建函数型Agent(基于函数型云托管开发AI智能体),initEnv=开通当前环境的云托管(异步创建云托管环境,幂等:已开通直接返回;适合新环境首次部署前使用),traffic=流量管理与灰度发布(set=调整稳定版/灰度版流量比例,promote=将灰度版本升级为全量,rollback=回滚到上一个稳定版本;对应 tcb cloudrun traffic 命令)'),
|
|
116615
117018
|
serverName: zod_1.z.string().describe('云托管服务名称,用于标识和管理服务。命名规则:支持大小写字母、数字、连字符和下划线,必须以字母开头,长度3-45个字符。在init操作中会作为在targetPath下创建的子目录名,在其他操作中作为目标服务名。initEnv 操作不需要此参数'),
|
|
117019
|
+
// Traffic management operation parameters (action=traffic)
|
|
117020
|
+
trafficOp: zod_1.z.enum(['set', 'promote', 'rollback']).optional().describe('流量管理子操作(action=traffic 时使用):set=调整灰度流量比例(需先部署新版本至灰度,通过 stablePercent/canaryPercent 设置稳定版与灰度版流量比例,两者之和必须等于100);promote=将灰度版本全量发布(灰度版本流量置为100%并关闭灰度发布,等价于 tcb cloudrun traffic promote);rollback=回滚到上一个稳定版本(停止当前灰度/发布中的版本,回到稳定版本,等价于 tcb cloudrun traffic rollback)'),
|
|
117021
|
+
stablePercent: zod_1.z.number().min(0).max(100).optional().describe('稳定版本流量比例(trafficOp=set 时使用),取值范围0-100。与 canaryPercent 之和必须等于100。例如希望 90% 流量打到稳定版、10% 打到灰度版,则 stablePercent=90, canaryPercent=10'),
|
|
117022
|
+
canaryPercent: zod_1.z.number().min(0).max(100).optional().describe('灰度版本流量比例(trafficOp=set 时使用),取值范围0-100。与 stablePercent 之和必须等于100。例如希望 90% 流量打到稳定版、10% 打到灰度版,则 stablePercent=90, canaryPercent=10'),
|
|
116616
117023
|
// InitEnv operation parameters
|
|
116617
117024
|
envId: zod_1.z.string().optional().describe('环境 ID(action=initEnv 时使用;不传则使用当前配置的环境)。格式如 env-xxxxxx'),
|
|
116618
117025
|
packageType: zod_1.z.enum(exports.CLOUDRUN_PACKAGE_TYPES).optional().default('Trial').describe('云托管环境套餐类型(action=initEnv 时使用):Trial=试用,Standard=标准,Professional=专业,Enterprise=企业。默认 Trial'),
|
|
117026
|
+
vpcId: zod_1.z.string().optional().describe('VPC 网络 ID(action=initEnv 时可选)。当平台拒绝系统创建网络时必填,格式如 vpc-xxxxxxxx。与 subnetIds 一起透传给 CreateCloudRunEnv 的 VpcId/SubNetIds。多数场景可不传(由系统创建网络)'),
|
|
117027
|
+
subnetIds: zod_1.z.array(zod_1.z.string()).optional().describe('子网 ID 列表(action=initEnv 时可选)。当需指定自有 VPC 时必填,如 ["subnet-xxxxxxxx"]。与 vpcId 一起透传给 CreateCloudRunEnv 的 SubNetIds'),
|
|
116619
117028
|
// Deploy operation parameters
|
|
116620
|
-
targetPath: zod_1.z.string().optional().describe('本地代码路径,必须是绝对路径。在deploy操作中指定要部署的代码目录,在download操作中指定下载目标目录,在init操作中指定云托管服务的上级目录(会在该目录下创建以serverName命名的子目录)。updateConfig 不需要此参数。建议约定:项目根目录下的cloudrun/目录,例如:/Users/username/projects/my-project/cloudrun。使用 imageUrl
|
|
116621
|
-
imageUrl: zod_1.z.string().optional().describe('已有镜像部署(action=deploy 时使用):直接指定容器镜像地址,如 ccr.ccs.tencentyun.com/ns/img:v1 或公网 registry 地址。传入后走 DeployType="image"(容器型)部署,无需本地源码目录(targetPath 可省略)。支持:1) 公网匿名可拉取的镜像直填地址;2) 私有/需登录的镜像(如 ghcr.io)需先在本地 docker pull → docker tag/push 到腾讯云 CCR → 填入 CCR
|
|
117029
|
+
targetPath: zod_1.z.string().optional().describe('本地代码路径,必须是绝对路径。在deploy操作中指定要部署的代码目录,在download操作中指定下载目标目录,在init操作中指定云托管服务的上级目录(会在该目录下创建以serverName命名的子目录)。updateConfig 不需要此参数。建议约定:项目根目录下的cloudrun/目录,例如:/Users/username/projects/my-project/cloudrun。使用 imageUrl 部署已有镜像时此参数可省略。注意:本地有源码目录不等于必须走源码构建;若用户指定镜像请优先传 imageUrl,不要仅因存在 targetPath 就回退到源码构建'),
|
|
117030
|
+
imageUrl: zod_1.z.string().optional().describe('已有镜像部署(action=deploy 时使用):直接指定容器镜像地址,如 ccr.ccs.tencentyun.com/ns/img:v1 或公网 registry 地址。传入后走 DeployType="image"(容器型)部署,无需本地源码目录(targetPath 可省略)。支持:1) 公网匿名可拉取的镜像直填地址;2) 私有/需登录的镜像(如 ghcr.io)需先在本地 docker pull → docker tag/push 到腾讯云 CCR → 填入 CCR 地址。不传则维持源码构建(本地代码打包上传)。约束:若用户明确提到使用某个镜像、或无需重新构建代码,则必须传 imageUrl 走镜像部署,不要回退到源码构建。注意:无论哪种部署方式,环境都需先开通云托管(未开通时先调用 initEnv,Status=normal 后再部署)'),
|
|
116622
117031
|
envParamsReplaceAll: zod_1.z.boolean().optional().default(false).describe('EnvParams 合并策略(deploy / updateConfig):false(默认)= 与远程按 key 合并(输入覆盖同名 key,远程其余 key 保留);true= 用输入 EnvParams 整包替换远程。仅当显式传入 EnvParams 时生效'),
|
|
116623
117032
|
serverConfig: zod_1.z.object({
|
|
116624
117033
|
OpenAccessTypes: zod_1.z.array(zod_1.z.enum(exports.CLOUDRUN_ACCESS_TYPES)).optional().describe('公网访问类型配置,控制服务的访问权限:OA=办公网访问,PUBLIC=公网访问(默认,可通过HTTPS域名访问),MINIAPP=小程序访问,VPC=VPC访问(仅同VPC内可访问)。可配置多个类型'),
|
|
@@ -116639,7 +117048,7 @@ const ManageCloudRunInputSchema = {
|
|
|
116639
117048
|
InternalDomain: zod_1.z.string().optional().describe('内网域名配置,用于配置服务的内网访问域名。仅在启用内网访问时有效'),
|
|
116640
117049
|
EntryPoint: zod_1.z.array(zod_1.z.string()).optional().describe('Dockerfile EntryPoint参数配置,仅容器型服务需要。指定容器启动时的入口程序数组,如["node","app.js"]'),
|
|
116641
117050
|
Cmd: zod_1.z.array(zod_1.z.string()).optional().describe('Dockerfile Cmd参数配置,仅容器型服务需要。指定容器启动时的默认命令数组,如["npm","start"]'),
|
|
116642
|
-
InitialDelaySeconds: zod_1.z.number().min(0).optional().describe('
|
|
117051
|
+
InitialDelaySeconds: zod_1.z.number().min(0).optional().describe('端口健康检查初始延迟(秒)。部署完成后先等待 N 秒才开始端口探测,之后约每 5s 检查一次、连续约 30 次;30 次全失败才判定部署失败(约 150s 探测窗口),不是「N 秒后立即失败」。启动耗时长的应用建议调到 60–120'),
|
|
116643
117052
|
LogType: zod_1.z.string().optional().describe('日志类型配置,指定服务的日志收集类型。影响日志的采集方式和存储格式'),
|
|
116644
117053
|
LogSetId: zod_1.z.string().optional().describe('CLS日志集ID配置,指定日志服务(CLS)的日志集ID。需要先开通CLS日志服务'),
|
|
116645
117054
|
LogTopicId: zod_1.z.string().optional().describe('CLS日志主题ID配置,指定日志服务(CLS)的日志主题ID。需要先开通CLS日志服务'),
|
|
@@ -116753,15 +117162,228 @@ function validateAndNormalizePath(inputPath) {
|
|
|
116753
117162
|
function buildManageCloudRunErrorMessage(action, serverName, error) {
|
|
116754
117163
|
const baseMessage = error instanceof Error ? error.message : String(error);
|
|
116755
117164
|
const suggestions = [];
|
|
117165
|
+
if ((0, capi_js_1.isCamAuthError)(baseMessage)) {
|
|
117166
|
+
suggestions.push((0, capi_js_1.buildCamAuthGuidance)());
|
|
117167
|
+
}
|
|
116756
117168
|
if (/已有部署发布任务运行中|部署发布任务运行中/i.test(baseMessage)) {
|
|
116757
117169
|
suggestions.push(`服务 \`${serverName}\` 当前已有部署任务在执行,请等待现有任务完成后再重试。`);
|
|
116758
117170
|
suggestions.push("如果你确认要覆盖当前流程,可在合适时机使用 `force=true` 再次发起。");
|
|
116759
117171
|
}
|
|
117172
|
+
if (/云托管资源未开通|无法使用系统创建网络|VpcInfo/i.test(baseMessage)) {
|
|
117173
|
+
suggestions.push("CreateCloudRunServer 需要有效 VPC:请传 serverConfig.VpcConf(VpcId+SubnetId)," +
|
|
117174
|
+
"或在 initEnv 时传入 vpcId/subnetIds(环境开通后 deploy 会自动从 EnvBaseInfo 回填)。" +
|
|
117175
|
+
"若平台拒绝系统创建网络,必须指定上海地域 VPC。");
|
|
117176
|
+
}
|
|
116760
117177
|
if (suggestions.length === 0) {
|
|
116761
117178
|
suggestions.push("请检查服务状态、部署参数和目标目录后重试。");
|
|
116762
117179
|
}
|
|
116763
117180
|
return `[manageCloudRun/${action}] ${baseMessage}\n建议:${suggestions.join(" ")}`;
|
|
116764
117181
|
}
|
|
117182
|
+
/**
|
|
117183
|
+
* Lightweight wait after manageCloudRun deploy: poll until the platform has
|
|
117184
|
+
* registered the manage task / assigned identifiers for follow-up log queries.
|
|
117185
|
+
* - source builds: prefer BuildId > 0 (getDeployLog)
|
|
117186
|
+
* - image deploys: prefer RunId (getProcessLog; BuildId is often 0)
|
|
117187
|
+
* Does NOT wait for the full build/deploy (that can take 5–30 minutes).
|
|
117188
|
+
* Aligns with tcb CLI's DescribeServerManageTask polling entrypoint, but with
|
|
117189
|
+
* a short timeout suitable for MCP tool calls.
|
|
117190
|
+
*/
|
|
117191
|
+
exports.CLOUDRUN_DEPLOY_REGISTRATION_MAX_WAIT_MS = 45_000;
|
|
117192
|
+
exports.CLOUDRUN_DEPLOY_REGISTRATION_INTERVAL_MS = 3_000;
|
|
117193
|
+
function sleepMs(ms) {
|
|
117194
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
117195
|
+
}
|
|
117196
|
+
function isValidCloudRunBuildId(value) {
|
|
117197
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0;
|
|
117198
|
+
}
|
|
117199
|
+
function isValidCloudRunRunId(value) {
|
|
117200
|
+
return typeof value === "string" && value.trim().length > 0;
|
|
117201
|
+
}
|
|
117202
|
+
function extractServerManageTaskInfo(resp) {
|
|
117203
|
+
const data = (resp ?? {});
|
|
117204
|
+
const task = (data.Task ?? data.task ?? {});
|
|
117205
|
+
const rawId = task.Id ?? task.id;
|
|
117206
|
+
const rawStatus = task.Status ?? task.status;
|
|
117207
|
+
const taskId = typeof rawId === "number" && rawId > 0
|
|
117208
|
+
? rawId
|
|
117209
|
+
: typeof rawId === "string" && /^\d+$/.test(rawId) && Number(rawId) > 0
|
|
117210
|
+
? Number(rawId)
|
|
117211
|
+
: undefined;
|
|
117212
|
+
const taskStatus = typeof rawStatus === "string" && rawStatus.trim()
|
|
117213
|
+
? rawStatus.trim()
|
|
117214
|
+
: undefined;
|
|
117215
|
+
return {
|
|
117216
|
+
...(taskId !== undefined ? { taskId } : {}),
|
|
117217
|
+
...(taskStatus ? { taskStatus } : {}),
|
|
117218
|
+
};
|
|
117219
|
+
}
|
|
117220
|
+
/**
|
|
117221
|
+
* Poll DescribeServerManageTask + getDeployRecords until the preferred
|
|
117222
|
+
* identifier appears:
|
|
117223
|
+
* - source (default): BuildId > 0 for getDeployLog
|
|
117224
|
+
* - image: RunId for getProcessLog (BuildId is often 0)
|
|
117225
|
+
* If only taskId is seen, keeps polling for the preferred id until maxWaitMs.
|
|
117226
|
+
*/
|
|
117227
|
+
async function waitForCloudRunDeployRegistration(options) {
|
|
117228
|
+
const mode = options.mode ?? "source";
|
|
117229
|
+
const maxWaitMs = options.maxWaitMs ?? exports.CLOUDRUN_DEPLOY_REGISTRATION_MAX_WAIT_MS;
|
|
117230
|
+
const intervalMs = options.intervalMs ?? exports.CLOUDRUN_DEPLOY_REGISTRATION_INTERVAL_MS;
|
|
117231
|
+
const sleepFn = options.sleepFn ?? sleepMs;
|
|
117232
|
+
const startAt = Date.now();
|
|
117233
|
+
let lastTaskId;
|
|
117234
|
+
let lastTaskStatus;
|
|
117235
|
+
let lastBuildId;
|
|
117236
|
+
let lastRunId;
|
|
117237
|
+
// Immediate first probe, then interval retries until timeout.
|
|
117238
|
+
for (;;) {
|
|
117239
|
+
if (options.manager.commonService) {
|
|
117240
|
+
try {
|
|
117241
|
+
const resp = await options.manager
|
|
117242
|
+
.commonService("tcbr", "2022-02-17")
|
|
117243
|
+
.call({
|
|
117244
|
+
Action: "DescribeServerManageTask",
|
|
117245
|
+
Param: {
|
|
117246
|
+
EnvId: options.envId,
|
|
117247
|
+
ServerName: options.serverName,
|
|
117248
|
+
TaskId: lastTaskId ?? 0,
|
|
117249
|
+
},
|
|
117250
|
+
});
|
|
117251
|
+
const info = extractServerManageTaskInfo(resp);
|
|
117252
|
+
if (info.taskId !== undefined) {
|
|
117253
|
+
lastTaskId = info.taskId;
|
|
117254
|
+
}
|
|
117255
|
+
if (info.taskStatus) {
|
|
117256
|
+
lastTaskStatus = info.taskStatus;
|
|
117257
|
+
}
|
|
117258
|
+
}
|
|
117259
|
+
catch {
|
|
117260
|
+
// Task may not be queryable yet; retry until timeout.
|
|
117261
|
+
}
|
|
117262
|
+
}
|
|
117263
|
+
if (typeof options.cloudrunService.getDeployRecords === "function") {
|
|
117264
|
+
try {
|
|
117265
|
+
const recordsResult = (await options.cloudrunService.getDeployRecords({
|
|
117266
|
+
serverName: options.serverName,
|
|
117267
|
+
}));
|
|
117268
|
+
const latest = recordsResult?.DeployRecords?.[0];
|
|
117269
|
+
if (isValidCloudRunBuildId(latest?.BuildId)) {
|
|
117270
|
+
lastBuildId = latest.BuildId;
|
|
117271
|
+
}
|
|
117272
|
+
if (isValidCloudRunRunId(latest?.RunId)) {
|
|
117273
|
+
lastRunId = latest.RunId.trim();
|
|
117274
|
+
}
|
|
117275
|
+
}
|
|
117276
|
+
catch {
|
|
117277
|
+
// Deploy record may lag behind task registration; retry.
|
|
117278
|
+
}
|
|
117279
|
+
}
|
|
117280
|
+
const preferredReady = mode === "image"
|
|
117281
|
+
? isValidCloudRunRunId(lastRunId)
|
|
117282
|
+
: isValidCloudRunBuildId(lastBuildId);
|
|
117283
|
+
if (preferredReady) {
|
|
117284
|
+
return {
|
|
117285
|
+
registered: true,
|
|
117286
|
+
timedOut: false,
|
|
117287
|
+
taskId: lastTaskId,
|
|
117288
|
+
...(isValidCloudRunBuildId(lastBuildId) ? { buildId: lastBuildId } : {}),
|
|
117289
|
+
...(isValidCloudRunRunId(lastRunId) ? { runId: lastRunId } : {}),
|
|
117290
|
+
taskStatus: lastTaskStatus,
|
|
117291
|
+
waitMs: Date.now() - startAt,
|
|
117292
|
+
};
|
|
117293
|
+
}
|
|
117294
|
+
if (Date.now() - startAt >= maxWaitMs) {
|
|
117295
|
+
break;
|
|
117296
|
+
}
|
|
117297
|
+
await sleepFn(intervalMs);
|
|
117298
|
+
}
|
|
117299
|
+
const registered = isValidCloudRunBuildId(lastBuildId) ||
|
|
117300
|
+
isValidCloudRunRunId(lastRunId) ||
|
|
117301
|
+
(typeof lastTaskId === "number" && lastTaskId > 0);
|
|
117302
|
+
return {
|
|
117303
|
+
registered,
|
|
117304
|
+
timedOut: true,
|
|
117305
|
+
taskId: lastTaskId,
|
|
117306
|
+
...(isValidCloudRunBuildId(lastBuildId) ? { buildId: lastBuildId } : {}),
|
|
117307
|
+
...(isValidCloudRunRunId(lastRunId) ? { runId: lastRunId } : {}),
|
|
117308
|
+
taskStatus: lastTaskStatus,
|
|
117309
|
+
waitMs: Date.now() - startAt,
|
|
117310
|
+
};
|
|
117311
|
+
}
|
|
117312
|
+
/**
|
|
117313
|
+
* Build manageCloudRun(deploy) next_step by DeployType:
|
|
117314
|
+
* - source: getDeployLog (+ follow-up getProcessLog)
|
|
117315
|
+
* - image: skip getDeployLog; getProcessLog via RunId (or getDeployRecords first)
|
|
117316
|
+
*/
|
|
117317
|
+
function buildCloudRunDeployNextStep(options) {
|
|
117318
|
+
const { deployType, serverName, registered } = options;
|
|
117319
|
+
if (deployType === "image") {
|
|
117320
|
+
if (isValidCloudRunRunId(options.runId)) {
|
|
117321
|
+
return {
|
|
117322
|
+
tool: "queryCloudRun",
|
|
117323
|
+
action: "getProcessLog",
|
|
117324
|
+
suggested_args: {
|
|
117325
|
+
action: "getProcessLog",
|
|
117326
|
+
detailServerName: serverName,
|
|
117327
|
+
runId: options.runId.trim(),
|
|
117328
|
+
},
|
|
117329
|
+
note: "Image deploy has no CODING build process; skip getDeployLog. Poll getProcessLog for deploy-step and container runtime logs.",
|
|
117330
|
+
};
|
|
117331
|
+
}
|
|
117332
|
+
return {
|
|
117333
|
+
tool: "queryCloudRun",
|
|
117334
|
+
action: "getDeployRecords",
|
|
117335
|
+
suggested_args: {
|
|
117336
|
+
action: "getDeployRecords",
|
|
117337
|
+
detailServerName: serverName,
|
|
117338
|
+
},
|
|
117339
|
+
note: registered
|
|
117340
|
+
? "Image deploy: read latestDeploy.RunId, then queryCloudRun(action=\"getProcessLog\", runId=...). Skip getDeployLog."
|
|
117341
|
+
: "Image deploy registration still queueing; retry getDeployRecords for RunId, then getProcessLog. Skip getDeployLog.",
|
|
117342
|
+
};
|
|
117343
|
+
}
|
|
117344
|
+
if (isValidCloudRunBuildId(options.buildId)) {
|
|
117345
|
+
return {
|
|
117346
|
+
tool: "queryCloudRun",
|
|
117347
|
+
action: "getDeployLog",
|
|
117348
|
+
suggested_args: {
|
|
117349
|
+
action: "getDeployLog",
|
|
117350
|
+
detailServerName: serverName,
|
|
117351
|
+
buildId: options.buildId,
|
|
117352
|
+
},
|
|
117353
|
+
note: "Source build: poll getDeployLog for build progress, then getProcessLog (RunId from detail/getDeployRecords) for runtime/deploy-step logs.",
|
|
117354
|
+
};
|
|
117355
|
+
}
|
|
117356
|
+
return {
|
|
117357
|
+
tool: "queryCloudRun",
|
|
117358
|
+
action: "getDeployLog",
|
|
117359
|
+
suggested_args: {
|
|
117360
|
+
action: "getDeployLog",
|
|
117361
|
+
detailServerName: serverName,
|
|
117362
|
+
},
|
|
117363
|
+
note: registered
|
|
117364
|
+
? "BuildId not yet available; omit buildId to use the latest deploy record. After build, use getProcessLog for runtime logs."
|
|
117365
|
+
: "Registration timed out; wait a moment then retry getDeployLog, or open consoleUrl. After build, use getProcessLog for runtime logs.",
|
|
117366
|
+
};
|
|
117367
|
+
}
|
|
117368
|
+
function buildCloudRunDeployProgressHint(options) {
|
|
117369
|
+
const { deployType, serverName, consoleUrl } = options;
|
|
117370
|
+
if (deployType === "image") {
|
|
117371
|
+
if (isValidCloudRunRunId(options.runId)) {
|
|
117372
|
+
return ` Image deploy: use queryCloudRun(action="getProcessLog", detailServerName="${serverName}", runId="${options.runId.trim()}") for runtime/deploy-step logs (skip getDeployLog).`;
|
|
117373
|
+
}
|
|
117374
|
+
if (options.registered) {
|
|
117375
|
+
return ` Image deploy registered${typeof options.taskId === "number" ? ` (taskId=${options.taskId})` : ""}; RunId not yet available — use queryCloudRun(action="getDeployRecords", detailServerName="${serverName}") then getProcessLog (skip getDeployLog), or check ${consoleUrl}.`;
|
|
117376
|
+
}
|
|
117377
|
+
return ` Image deploy registration timed out after ${Math.round(options.waitMs / 1000)}s — retry getDeployRecords for RunId then getProcessLog (skip getDeployLog), or check ${consoleUrl}.`;
|
|
117378
|
+
}
|
|
117379
|
+
if (isValidCloudRunBuildId(options.buildId)) {
|
|
117380
|
+
return ` Use queryCloudRun(action="getDeployLog", detailServerName="${serverName}", buildId=${options.buildId}) to poll build progress, then getProcessLog for runtime logs.`;
|
|
117381
|
+
}
|
|
117382
|
+
if (options.registered) {
|
|
117383
|
+
return ` Task registered (taskId=${options.taskId ?? "unknown"}); BuildId not yet available — retry queryCloudRun(action="getDeployLog", detailServerName="${serverName}") shortly, then getProcessLog, or check ${consoleUrl}.`;
|
|
117384
|
+
}
|
|
117385
|
+
return ` Build registration timed out after ${Math.round(options.waitMs / 1000)}s — deployment may still be queueing. Check ${consoleUrl} or retry queryCloudRun(action="getDeployLog", detailServerName="${serverName}") later.`;
|
|
117386
|
+
}
|
|
116765
117387
|
const CLOUDRUN_DB_ENV_KEY_PATTERN = /^(DATABASE_URL|DB_HOST|DB_PORT|DB_USER|DB_PASSWORD|DB_NAME|MYSQL_|POSTGRES_|PGHOST|PGPORT|PGUSER|PGPASSWORD|PGDATABASE|PG_|REDIS_|MONGO_|MONGODB_|SQLALCHEMY_DATABASE_URI|SPRING_DATASOURCE_)/i;
|
|
116766
117388
|
const CLOUDRUN_DB_URL_PATTERN = /(mysql|mariadb|postgres|postgresql|mongodb(\+srv)?|redis|rediss):\/\//i;
|
|
116767
117389
|
async function queryCloudRunEnvStatus(options) {
|
|
@@ -116788,11 +117410,80 @@ async function describeCloudRunEnvStatus(manager, envId) {
|
|
|
116788
117410
|
return { isExist: false, status: "unopened", baseInfo };
|
|
116789
117411
|
}
|
|
116790
117412
|
const rawStatus = typeof baseInfo.Status === "string" ? baseInfo.Status : "";
|
|
116791
|
-
|
|
116792
|
-
|
|
117413
|
+
// Platform may return NORMAL/CREATING (uppercase); normalize before matching.
|
|
117414
|
+
const normalizedStatus = rawStatus.toLowerCase();
|
|
117415
|
+
const status = normalizedStatus === "creating" || normalizedStatus === "normal"
|
|
117416
|
+
? normalizedStatus
|
|
116793
117417
|
: "unknown";
|
|
116794
117418
|
return { isExist: true, status, baseInfo };
|
|
116795
117419
|
}
|
|
117420
|
+
/** CloudRun EnvType for CreateCloudRunEnv (tcbr DescribeEnvBaseInfo enum). */
|
|
117421
|
+
exports.CLOUDRUN_ENV_TYPE = "tcbr";
|
|
117422
|
+
/**
|
|
117423
|
+
* Extract VPC binding from DescribeEnvBaseInfo.EnvBaseInfo when the env was
|
|
117424
|
+
* opened with an explicit VPC.
|
|
117425
|
+
*/
|
|
117426
|
+
function extractEnvBaseInfoVpc(baseInfo) {
|
|
117427
|
+
if (!baseInfo) {
|
|
117428
|
+
return undefined;
|
|
117429
|
+
}
|
|
117430
|
+
const vpcId = typeof baseInfo.VpcId === "string" ? baseInfo.VpcId.trim() : "";
|
|
117431
|
+
const rawSubnets = baseInfo.SubNetIds ?? baseInfo.SubnetIds;
|
|
117432
|
+
const subnetIds = Array.isArray(rawSubnets)
|
|
117433
|
+
? rawSubnets
|
|
117434
|
+
.filter((item) => typeof item === "string" && item.trim().length > 0)
|
|
117435
|
+
.map((item) => item.trim())
|
|
117436
|
+
: [];
|
|
117437
|
+
if (!vpcId || subnetIds.length === 0) {
|
|
117438
|
+
return undefined;
|
|
117439
|
+
}
|
|
117440
|
+
return { VpcId: vpcId, SubnetIds: subnetIds };
|
|
117441
|
+
}
|
|
117442
|
+
/**
|
|
117443
|
+
* Resolve CreateCloudRunServer.VpcInfo: prefer explicit serverConfig.VpcConf,
|
|
117444
|
+
* otherwise fall back to env-level VPC from DescribeEnvBaseInfo.
|
|
117445
|
+
*/
|
|
117446
|
+
function resolveCloudRunDeployVpcInfo(options) {
|
|
117447
|
+
const conf = options.vpcConf;
|
|
117448
|
+
if (conf?.VpcId?.trim() && conf?.SubnetId?.trim()) {
|
|
117449
|
+
return {
|
|
117450
|
+
VpcId: conf.VpcId.trim(),
|
|
117451
|
+
CreateType: 2,
|
|
117452
|
+
SubnetIds: [conf.SubnetId.trim()],
|
|
117453
|
+
};
|
|
117454
|
+
}
|
|
117455
|
+
const fromEnv = extractEnvBaseInfoVpc(options.envBaseInfo);
|
|
117456
|
+
if (!fromEnv) {
|
|
117457
|
+
return undefined;
|
|
117458
|
+
}
|
|
117459
|
+
return {
|
|
117460
|
+
VpcId: fromEnv.VpcId,
|
|
117461
|
+
CreateType: 2,
|
|
117462
|
+
SubnetIds: fromEnv.SubnetIds,
|
|
117463
|
+
};
|
|
117464
|
+
}
|
|
117465
|
+
/**
|
|
117466
|
+
* Build CreateCloudRunEnv Param, always including EnvType=tcbr.
|
|
117467
|
+
* Optional vpcId/subnetIds are used when the platform requires an explicit VPC.
|
|
117468
|
+
*/
|
|
117469
|
+
function buildCreateCloudRunEnvParam(options) {
|
|
117470
|
+
const param = {
|
|
117471
|
+
EnvId: options.envId,
|
|
117472
|
+
PackageType: options.packageType,
|
|
117473
|
+
EnvType: exports.CLOUDRUN_ENV_TYPE,
|
|
117474
|
+
};
|
|
117475
|
+
const vpcId = options.vpcId?.trim();
|
|
117476
|
+
const subnetIds = (options.subnetIds ?? [])
|
|
117477
|
+
.filter((id) => typeof id === "string" && id.trim().length > 0)
|
|
117478
|
+
.map((id) => id.trim());
|
|
117479
|
+
if (vpcId) {
|
|
117480
|
+
param.VpcId = vpcId;
|
|
117481
|
+
}
|
|
117482
|
+
if (subnetIds.length > 0) {
|
|
117483
|
+
param.SubNetIds = subnetIds;
|
|
117484
|
+
}
|
|
117485
|
+
return param;
|
|
117486
|
+
}
|
|
116796
117487
|
/**
|
|
116797
117488
|
* 探测当前环境云托管(大租户)是否已初始化。
|
|
116798
117489
|
*
|
|
@@ -117002,7 +117693,7 @@ function registerCloudRunTools(server) {
|
|
|
117002
117693
|
// Tool 1: Get CloudRun service information (read operations)
|
|
117003
117694
|
server.registerTool("queryCloudRun", {
|
|
117004
117695
|
title: "查询 CloudRun 服务信息",
|
|
117005
|
-
description: "
|
|
117696
|
+
description: "查询云托管服务信息,支持获取服务列表、查询服务详情、获取可用模板列表、获取构建日志(getDeployLog,仅云端源码构建/依赖 CODING)、获取运行日志(getProcessLog,镜像与源码部署均可/不依赖 CODING)、获取部署记录以及查询环境云托管开通状态(envStatus)。返回的服务信息包括服务名称、状态、访问类型、配置详情以及最近部署上下文。",
|
|
117006
117697
|
inputSchema: queryCloudRunInputSchema,
|
|
117007
117698
|
annotations: {
|
|
117008
117699
|
readOnlyHint: true,
|
|
@@ -117090,10 +117781,13 @@ function registerCloudRunTools(server) {
|
|
|
117090
117781
|
if (!latestDeploy) {
|
|
117091
117782
|
message = `Retrieved details for service '${serverName}'. No deploy records found yet.`;
|
|
117092
117783
|
}
|
|
117093
|
-
else if (typeof latestDeploy.Status ===
|
|
117094
|
-
|
|
117784
|
+
else if (typeof latestDeploy.Status === "string" &&
|
|
117785
|
+
// Platform may return FAILED/CREATING (uppercase); normalize before matching.
|
|
117786
|
+
latestDeploy.Status.toLowerCase().includes("failed")) {
|
|
117787
|
+
message = `Service '${serverName}' latest deploy failed. Use queryCloudRun(action="getProcessLog") for runtime/deploy-step logs (RunId from latestDeploy); use getDeployLog only for cloud source-build logs (CODING).`;
|
|
117095
117788
|
}
|
|
117096
|
-
else if (typeof latestDeploy.Status ===
|
|
117789
|
+
else if (typeof latestDeploy.Status === "string" &&
|
|
117790
|
+
latestDeploy.Status.toLowerCase().includes("creating")) {
|
|
117097
117791
|
message = `Service '${serverName}' latest deploy is still running. Please check again later or query the deploy log for progress.`;
|
|
117098
117792
|
}
|
|
117099
117793
|
else {
|
|
@@ -117176,6 +117870,9 @@ function registerCloudRunTools(server) {
|
|
|
117176
117870
|
};
|
|
117177
117871
|
}
|
|
117178
117872
|
const buildId = input.buildId ?? latestDeploy.BuildId;
|
|
117873
|
+
// Build log (CODING / DescribeCloudRunBuildLog). Meaningful only for
|
|
117874
|
+
// cloud source builds; image deploys have no build process. Accounts
|
|
117875
|
+
// without a CODING user may fail here — use getProcessLog for runtime logs.
|
|
117179
117876
|
const buildLogResult = await cloudrunService.getBuildLog({
|
|
117180
117877
|
serverName,
|
|
117181
117878
|
buildId,
|
|
@@ -117206,11 +117903,130 @@ function registerCloudRunTools(server) {
|
|
|
117206
117903
|
buildId,
|
|
117207
117904
|
deployRecord: latestDeploy,
|
|
117208
117905
|
buildLog: buildLogResult?.Log || null,
|
|
117906
|
+
// Optional best-effort attach; prefer dedicated getProcessLog for runtime diagnosis
|
|
117209
117907
|
processLogs,
|
|
117210
117908
|
combinedLogText,
|
|
117211
117909
|
...(processLogsWarning ? { processLogsWarning } : {})
|
|
117212
117910
|
},
|
|
117213
|
-
message: `Retrieved
|
|
117911
|
+
message: `Retrieved build log for service '${serverName}' (getDeployLog=构建日志; for 运行日志 use getProcessLog with RunId)`
|
|
117912
|
+
}, null, 2)
|
|
117913
|
+
}
|
|
117914
|
+
]
|
|
117915
|
+
};
|
|
117916
|
+
}
|
|
117917
|
+
case 'getProcessLog': {
|
|
117918
|
+
const serverName = getCloudRunQueryServerName(input);
|
|
117919
|
+
if (!serverName && !input.runId?.trim()) {
|
|
117920
|
+
return {
|
|
117921
|
+
content: [
|
|
117922
|
+
{
|
|
117923
|
+
type: "text",
|
|
117924
|
+
text: JSON.stringify({
|
|
117925
|
+
success: false,
|
|
117926
|
+
error: "runId is required, or provide detailServerName/serverName to resolve latest RunId",
|
|
117927
|
+
message: "Pass runId from detail/getDeployRecords latestDeploy.RunId, or provide a service name to use the latest deploy RunId."
|
|
117928
|
+
}, null, 2)
|
|
117929
|
+
}
|
|
117930
|
+
]
|
|
117931
|
+
};
|
|
117932
|
+
}
|
|
117933
|
+
let runId = input.runId?.trim() || "";
|
|
117934
|
+
let deployRecord = null;
|
|
117935
|
+
if (serverName) {
|
|
117936
|
+
const deployRecordsResult = await cloudrunService.getDeployRecords({ serverName });
|
|
117937
|
+
const deployRecords = Array.isArray(deployRecordsResult?.DeployRecords)
|
|
117938
|
+
? deployRecordsResult.DeployRecords
|
|
117939
|
+
: [];
|
|
117940
|
+
deployRecord = deployRecords[0] ?? null;
|
|
117941
|
+
if (!runId) {
|
|
117942
|
+
runId = typeof deployRecord?.RunId === "string" ? deployRecord.RunId.trim() : "";
|
|
117943
|
+
}
|
|
117944
|
+
else if (deployRecord?.RunId && deployRecord.RunId !== runId) {
|
|
117945
|
+
// Keep latest deploy as context only; explicit runId wins
|
|
117946
|
+
}
|
|
117947
|
+
}
|
|
117948
|
+
if (!runId) {
|
|
117949
|
+
return {
|
|
117950
|
+
content: [
|
|
117951
|
+
{
|
|
117952
|
+
type: "text",
|
|
117953
|
+
text: JSON.stringify({
|
|
117954
|
+
success: false,
|
|
117955
|
+
error: serverName
|
|
117956
|
+
? `Service '${serverName}' has no RunId on the latest deploy record.`
|
|
117957
|
+
: "runId is required for getProcessLog action",
|
|
117958
|
+
message: "Deploy the service first, then read RunId from queryCloudRun(action=\"detail\") or getDeployRecords (latestDeploy.RunId)."
|
|
117959
|
+
}, null, 2)
|
|
117960
|
+
}
|
|
117961
|
+
]
|
|
117962
|
+
};
|
|
117963
|
+
}
|
|
117964
|
+
if (typeof cloudrunService.getProcessLog !== "function") {
|
|
117965
|
+
throw new Error("Current CloudBase Manager SDK does not support getProcessLog; please upgrade @cloudbase/manager-node.");
|
|
117966
|
+
}
|
|
117967
|
+
const processLogResult = await cloudrunService.getProcessLog({
|
|
117968
|
+
RunId: runId,
|
|
117969
|
+
});
|
|
117970
|
+
const processLogs = Array.isArray(processLogResult?.Logs)
|
|
117971
|
+
? processLogResult.Logs
|
|
117972
|
+
: [];
|
|
117973
|
+
const processLogText = processLogs.length > 0
|
|
117974
|
+
? normalizeProcessLogText(processLogs)
|
|
117975
|
+
: "";
|
|
117976
|
+
return {
|
|
117977
|
+
content: [
|
|
117978
|
+
{
|
|
117979
|
+
type: "text",
|
|
117980
|
+
text: JSON.stringify({
|
|
117981
|
+
success: true,
|
|
117982
|
+
data: {
|
|
117983
|
+
serverName: serverName || undefined,
|
|
117984
|
+
runId,
|
|
117985
|
+
deployRecord,
|
|
117986
|
+
processLogs,
|
|
117987
|
+
processLogText,
|
|
117988
|
+
requestId: processLogResult?.RequestId,
|
|
117989
|
+
},
|
|
117990
|
+
message: `Retrieved process/runtime log for RunId='${runId}' (getProcessLog=运行日志; getDeployLog=构建日志且仅云端构建/依赖 CODING)`
|
|
117991
|
+
}, null, 2)
|
|
117992
|
+
}
|
|
117993
|
+
]
|
|
117994
|
+
};
|
|
117995
|
+
}
|
|
117996
|
+
case 'getDeployRecords': {
|
|
117997
|
+
const serverName = getCloudRunQueryServerName(input);
|
|
117998
|
+
if (!serverName) {
|
|
117999
|
+
return {
|
|
118000
|
+
content: [
|
|
118001
|
+
{
|
|
118002
|
+
type: "text",
|
|
118003
|
+
text: JSON.stringify({
|
|
118004
|
+
success: false,
|
|
118005
|
+
error: "detailServerName or serverName is required for getDeployRecords action",
|
|
118006
|
+
message: "Please provide detailServerName or serverName."
|
|
118007
|
+
}, null, 2)
|
|
118008
|
+
}
|
|
118009
|
+
]
|
|
118010
|
+
};
|
|
118011
|
+
}
|
|
118012
|
+
const deployRecordsResult = await cloudrunService.getDeployRecords({ serverName });
|
|
118013
|
+
const deployRecords = Array.isArray(deployRecordsResult?.DeployRecords)
|
|
118014
|
+
? deployRecordsResult.DeployRecords
|
|
118015
|
+
: [];
|
|
118016
|
+
return {
|
|
118017
|
+
content: [
|
|
118018
|
+
{
|
|
118019
|
+
type: "text",
|
|
118020
|
+
text: JSON.stringify({
|
|
118021
|
+
success: true,
|
|
118022
|
+
data: {
|
|
118023
|
+
serverName,
|
|
118024
|
+
deployRecords,
|
|
118025
|
+
// 部署记录按部署时间倒序(最新在前),首条为最近一次部署
|
|
118026
|
+
total: deployRecords.length,
|
|
118027
|
+
latestDeploy: deployRecords[0] ?? null
|
|
118028
|
+
},
|
|
118029
|
+
message: `Retrieved ${deployRecords.length} deploy records for service '${serverName}'`
|
|
117214
118030
|
}, null, 2)
|
|
117215
118031
|
}
|
|
117216
118032
|
]
|
|
@@ -117284,7 +118100,7 @@ function registerCloudRunTools(server) {
|
|
|
117284
118100
|
// Tool 2: Manage CloudRun services (write operations)
|
|
117285
118101
|
server.registerTool("manageCloudRun", {
|
|
117286
118102
|
title: "管理 CloudRun 服务",
|
|
117287
|
-
description: "管理云托管服务,按开发顺序支持:开通云托管环境(initEnv)、初始化项目(可从模板开始,模板列表可通过 queryCloudRun 查询)、下载服务代码、本地运行(仅函数型服务)、部署代码、仅更新配置(updateConfig,无需重新上传代码)、删除服务。deploy 支持两种方式:1) 源码构建(传入 targetPath,本地代码打包上传,默认路径);2) 已有镜像部署(传入 imageUrl,如 ccr.ccs.tencentyun.com/ns/img:v1,走 DeployType=image 容器型部署,targetPath 可省略)。deploy 对已存在服务会先读取远程配置再合并(保留 VpcConf/EnvParams/OpenAccessTypes)。updateConfig 对齐控制台服务设置页。删除操作需要确认,建议设置force=true。新环境首次部署前若提示未开通云托管,先调用 initEnv 开通(异步、幂等)。",
|
|
118103
|
+
description: "管理云托管服务,按开发顺序支持:开通云托管环境(initEnv)、初始化项目(可从模板开始,模板列表可通过 queryCloudRun 查询)、下载服务代码、本地运行(仅函数型服务)、部署代码、仅更新配置(updateConfig,无需重新上传代码)、删除服务。deploy 支持两种方式:1) 源码构建(传入 targetPath,本地代码打包上传,默认路径);2) 已有镜像部署(传入 imageUrl,如 ccr.ccs.tencentyun.com/ns/img:v1,走 DeployType=image 容器型部署,targetPath 可省略)。deploy 语义为「触发部署 + 轻量等待任务注册」(最多约 45s)。源码构建返回 buildId,用 getDeployLog 轮询构建进度后再 getProcessLog;镜像部署(imageUrl)BuildId 常为 0,跳过 getDeployLog,返回 runId/next_step 引导 getProcessLog(或先 getDeployRecords 取 RunId)。若用户明确指定镜像或无需重新构建,必须传 imageUrl,不要仅因本地有源码目录就回退到源码构建。deploy 对已存在服务会先读取远程配置再合并(保留 VpcConf/EnvParams/OpenAccessTypes)。updateConfig 对齐控制台服务设置页。删除操作需要确认,建议设置force=true。新环境首次部署前若提示未开通云托管,先调用 initEnv 开通(异步、幂等)。",
|
|
117288
118104
|
inputSchema: ManageCloudRunInputSchema,
|
|
117289
118105
|
annotations: {
|
|
117290
118106
|
readOnlyHint: false,
|
|
@@ -117364,13 +118180,19 @@ function registerCloudRunTools(server) {
|
|
|
117364
118180
|
};
|
|
117365
118181
|
}
|
|
117366
118182
|
// 未开通 → 发起异步开通(CreateCloudRunEnv 异步,不阻塞等待)。
|
|
118183
|
+
// Always pass EnvType=tcbr; optional vpcId/subnetIds when an explicit VPC is required.
|
|
117367
118184
|
let createResult;
|
|
117368
118185
|
try {
|
|
117369
118186
|
createResult = await manager
|
|
117370
118187
|
.commonService("tcbr", "2022-02-17")
|
|
117371
118188
|
.call({
|
|
117372
118189
|
Action: "CreateCloudRunEnv",
|
|
117373
|
-
Param: {
|
|
118190
|
+
Param: buildCreateCloudRunEnvParam({
|
|
118191
|
+
envId,
|
|
118192
|
+
packageType,
|
|
118193
|
+
vpcId: input.vpcId,
|
|
118194
|
+
subnetIds: input.subnetIds,
|
|
118195
|
+
}),
|
|
117374
118196
|
});
|
|
117375
118197
|
}
|
|
117376
118198
|
catch (error) {
|
|
@@ -117398,6 +118220,98 @@ function registerCloudRunTools(server) {
|
|
|
117398
118220
|
]
|
|
117399
118221
|
};
|
|
117400
118222
|
}
|
|
118223
|
+
case 'traffic': {
|
|
118224
|
+
const trafficOp = input.trafficOp;
|
|
118225
|
+
if (!trafficOp) {
|
|
118226
|
+
throw new Error("trafficOp is required for traffic operation (set | promote | rollback)");
|
|
118227
|
+
}
|
|
118228
|
+
if (trafficOp === 'set') {
|
|
118229
|
+
const stable = input.stablePercent;
|
|
118230
|
+
const canary = input.canaryPercent;
|
|
118231
|
+
if (typeof stable !== 'number' ||
|
|
118232
|
+
typeof canary !== 'number') {
|
|
118233
|
+
throw new Error("stablePercent and canaryPercent are required for trafficOp=set");
|
|
118234
|
+
}
|
|
118235
|
+
if (stable + canary !== 100) {
|
|
118236
|
+
throw new Error(`stablePercent + canaryPercent must equal 100 (got ${stable} + ${canary} = ${stable + canary}). ` +
|
|
118237
|
+
`Example: 90/10 means 90% to stable version, 10% to canary version.`);
|
|
118238
|
+
}
|
|
118239
|
+
let setResult;
|
|
118240
|
+
try {
|
|
118241
|
+
setResult = await cloudrunService.setTraffic(input.serverName, stable, canary);
|
|
118242
|
+
}
|
|
118243
|
+
catch (error) {
|
|
118244
|
+
throw new Error(buildManageCloudRunErrorMessage('traffic/set', input.serverName, error));
|
|
118245
|
+
}
|
|
118246
|
+
return {
|
|
118247
|
+
content: [
|
|
118248
|
+
{
|
|
118249
|
+
type: "text",
|
|
118250
|
+
text: JSON.stringify({
|
|
118251
|
+
success: true,
|
|
118252
|
+
data: {
|
|
118253
|
+
serverName: input.serverName,
|
|
118254
|
+
trafficOp: 'set',
|
|
118255
|
+
stablePercent: stable,
|
|
118256
|
+
canaryPercent: canary,
|
|
118257
|
+
result: setResult ?? null
|
|
118258
|
+
},
|
|
118259
|
+
message: `Set traffic for service '${input.serverName}': stable ${stable}% / canary ${canary}%`
|
|
118260
|
+
}, null, 2)
|
|
118261
|
+
}
|
|
118262
|
+
]
|
|
118263
|
+
};
|
|
118264
|
+
}
|
|
118265
|
+
if (trafficOp === 'promote') {
|
|
118266
|
+
let promoteResult;
|
|
118267
|
+
try {
|
|
118268
|
+
promoteResult = await cloudrunService.promote(input.serverName);
|
|
118269
|
+
}
|
|
118270
|
+
catch (error) {
|
|
118271
|
+
throw new Error(buildManageCloudRunErrorMessage('traffic/promote', input.serverName, error));
|
|
118272
|
+
}
|
|
118273
|
+
return {
|
|
118274
|
+
content: [
|
|
118275
|
+
{
|
|
118276
|
+
type: "text",
|
|
118277
|
+
text: JSON.stringify({
|
|
118278
|
+
success: true,
|
|
118279
|
+
data: {
|
|
118280
|
+
serverName: input.serverName,
|
|
118281
|
+
trafficOp: 'promote',
|
|
118282
|
+
result: promoteResult ?? null
|
|
118283
|
+
},
|
|
118284
|
+
message: `Promoted canary version to full release for service '${input.serverName}' (100% traffic). This is irreversible.`
|
|
118285
|
+
}, null, 2)
|
|
118286
|
+
}
|
|
118287
|
+
]
|
|
118288
|
+
};
|
|
118289
|
+
}
|
|
118290
|
+
// rollback
|
|
118291
|
+
let rollbackResult;
|
|
118292
|
+
try {
|
|
118293
|
+
rollbackResult = await cloudrunService.rollback(input.serverName);
|
|
118294
|
+
}
|
|
118295
|
+
catch (error) {
|
|
118296
|
+
throw new Error(buildManageCloudRunErrorMessage('traffic/rollback', input.serverName, error));
|
|
118297
|
+
}
|
|
118298
|
+
return {
|
|
118299
|
+
content: [
|
|
118300
|
+
{
|
|
118301
|
+
type: "text",
|
|
118302
|
+
text: JSON.stringify({
|
|
118303
|
+
success: true,
|
|
118304
|
+
data: {
|
|
118305
|
+
serverName: input.serverName,
|
|
118306
|
+
trafficOp: 'rollback',
|
|
118307
|
+
result: rollbackResult ?? null
|
|
118308
|
+
},
|
|
118309
|
+
message: `Rolled back service '${input.serverName}' to the previous stable version.`
|
|
118310
|
+
}, null, 2)
|
|
118311
|
+
}
|
|
118312
|
+
]
|
|
118313
|
+
};
|
|
118314
|
+
}
|
|
117401
118315
|
case 'createAgent': {
|
|
117402
118316
|
if (!targetPath) {
|
|
117403
118317
|
throw new Error("targetPath is required for createAgent operation");
|
|
@@ -117663,14 +118577,30 @@ for await (let x of res.textStream) {
|
|
|
117663
118577
|
deployParams.serverConfig = effectiveServerConfig;
|
|
117664
118578
|
}
|
|
117665
118579
|
// Manager SDK create path prefers top-level vpcInfo (CreateCloudRunServer.VpcInfo).
|
|
117666
|
-
//
|
|
118580
|
+
// Prefer serverConfig.VpcConf; if missing, auto-fill from env DescribeEnvBaseInfo
|
|
118581
|
+
// (envs opened with vpcId/subnetIds already carry VpcId/SubNetIds).
|
|
117667
118582
|
const vpcConf = effectiveServerConfig?.VpcConf;
|
|
117668
|
-
|
|
117669
|
-
|
|
117670
|
-
|
|
117671
|
-
|
|
117672
|
-
|
|
117673
|
-
|
|
118583
|
+
let envBaseInfoForVpc = null;
|
|
118584
|
+
const explicitVpcId = vpcConf?.VpcId?.trim() ?? "";
|
|
118585
|
+
const explicitSubnetId = vpcConf?.SubnetId?.trim() ?? "";
|
|
118586
|
+
if (!explicitVpcId || !explicitSubnetId) {
|
|
118587
|
+
try {
|
|
118588
|
+
const envIdForVpc = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
|
|
118589
|
+
const envStatusForVpc = await describeCloudRunEnvStatus(manager, envIdForVpc);
|
|
118590
|
+
if (envStatusForVpc.isExist) {
|
|
118591
|
+
envBaseInfoForVpc = envStatusForVpc.baseInfo;
|
|
118592
|
+
}
|
|
118593
|
+
}
|
|
118594
|
+
catch {
|
|
118595
|
+
// Best-effort: deploy may still succeed without vpcInfo when the platform creates the network.
|
|
118596
|
+
}
|
|
118597
|
+
}
|
|
118598
|
+
const resolvedVpcInfo = resolveCloudRunDeployVpcInfo({
|
|
118599
|
+
vpcConf,
|
|
118600
|
+
envBaseInfo: envBaseInfoForVpc,
|
|
118601
|
+
});
|
|
118602
|
+
if (resolvedVpcInfo) {
|
|
118603
|
+
deployParams.vpcInfo = resolvedVpcInfo;
|
|
117674
118604
|
}
|
|
117675
118605
|
let result;
|
|
117676
118606
|
try {
|
|
@@ -117681,6 +118611,18 @@ for await (let x of res.textStream) {
|
|
|
117681
118611
|
}
|
|
117682
118612
|
// Generate cloudbaserc.json configuration file (source-build only; image deploy has no local project dir)
|
|
117683
118613
|
const currentEnvId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
|
|
118614
|
+
// Lightweight wait for task / BuildId (source) or RunId (image) registration.
|
|
118615
|
+
// Does not wait for full build/deploy completion.
|
|
118616
|
+
const deployType = input.imageUrl
|
|
118617
|
+
? "image"
|
|
118618
|
+
: "source";
|
|
118619
|
+
const registration = await waitForCloudRunDeployRegistration({
|
|
118620
|
+
manager,
|
|
118621
|
+
cloudrunService,
|
|
118622
|
+
envId: currentEnvId,
|
|
118623
|
+
serverName: input.serverName,
|
|
118624
|
+
mode: deployType,
|
|
118625
|
+
});
|
|
117684
118626
|
let cloudbasercGenerated = false;
|
|
117685
118627
|
if (targetPath) {
|
|
117686
118628
|
const cloudbasercPath = path_1.default.join(targetPath, 'cloudbaserc.json');
|
|
@@ -117756,6 +118698,24 @@ for await (let x of res.textStream) {
|
|
|
117756
118698
|
const warningSuffix = dbNetworkRisk
|
|
117757
118699
|
? ` Warning: ${dbNetworkRisk.message} Set serverConfig.VpcConf before relying on DB connectivity.`
|
|
117758
118700
|
: "";
|
|
118701
|
+
const progressHint = buildCloudRunDeployProgressHint({
|
|
118702
|
+
deployType,
|
|
118703
|
+
serverName: input.serverName,
|
|
118704
|
+
buildId: registration.buildId,
|
|
118705
|
+
runId: registration.runId,
|
|
118706
|
+
registered: registration.registered,
|
|
118707
|
+
timedOut: registration.timedOut,
|
|
118708
|
+
waitMs: registration.waitMs,
|
|
118709
|
+
consoleUrl,
|
|
118710
|
+
taskId: registration.taskId,
|
|
118711
|
+
});
|
|
118712
|
+
const nextStep = buildCloudRunDeployNextStep({
|
|
118713
|
+
deployType,
|
|
118714
|
+
serverName: input.serverName,
|
|
118715
|
+
buildId: registration.buildId,
|
|
118716
|
+
runId: registration.runId,
|
|
118717
|
+
registered: registration.registered,
|
|
118718
|
+
});
|
|
117759
118719
|
return {
|
|
117760
118720
|
content: [
|
|
117761
118721
|
{
|
|
@@ -117765,12 +118725,30 @@ for await (let x of res.textStream) {
|
|
|
117765
118725
|
data: {
|
|
117766
118726
|
serviceName: input.serverName,
|
|
117767
118727
|
status: 'deploying',
|
|
117768
|
-
deployType
|
|
118728
|
+
deployType,
|
|
117769
118729
|
...(targetPath ? { deployPath: targetPath } : {}),
|
|
117770
118730
|
...(input.imageUrl ? { imageUrl: input.imageUrl } : {}),
|
|
117771
118731
|
serverType: serverType,
|
|
117772
118732
|
cloudbasercGenerated,
|
|
117773
118733
|
consoleUrl,
|
|
118734
|
+
...(isValidCloudRunBuildId(registration.buildId)
|
|
118735
|
+
? { buildId: registration.buildId }
|
|
118736
|
+
: {}),
|
|
118737
|
+
...(isValidCloudRunRunId(registration.runId)
|
|
118738
|
+
? { runId: registration.runId }
|
|
118739
|
+
: {}),
|
|
118740
|
+
...(typeof registration.taskId === "number"
|
|
118741
|
+
? { taskId: registration.taskId }
|
|
118742
|
+
: {}),
|
|
118743
|
+
registration: {
|
|
118744
|
+
registered: registration.registered,
|
|
118745
|
+
timedOut: registration.timedOut,
|
|
118746
|
+
waitMs: registration.waitMs,
|
|
118747
|
+
...(registration.taskStatus
|
|
118748
|
+
? { taskStatus: registration.taskStatus }
|
|
118749
|
+
: {}),
|
|
118750
|
+
},
|
|
118751
|
+
next_step: nextStep,
|
|
117774
118752
|
...(existingService
|
|
117775
118753
|
? {
|
|
117776
118754
|
configMerge: {
|
|
@@ -117791,8 +118769,10 @@ for await (let x of res.textStream) {
|
|
|
117791
118769
|
? { accessUrlSource: preferredAccessSource }
|
|
117792
118770
|
: {}),
|
|
117793
118771
|
...(warnings.length > 0 ? { warnings } : {}),
|
|
118772
|
+
// Keep raw SDK result for debugging without implying build finished.
|
|
118773
|
+
...(result != null ? { deployAccepted: true } : {}),
|
|
117794
118774
|
},
|
|
117795
|
-
message: `Triggered deployment for ${serverType} service '${input.serverName}' ${input.imageUrl ? `from image ${input.imageUrl}` : `from ${targetPath}`}.
|
|
118775
|
+
message: `Triggered deployment for ${serverType} service '${input.serverName}' ${input.imageUrl ? `from image ${input.imageUrl}` : `from ${targetPath}`}. Deployment is registering/${deployType === "image" ? "starting" : "building"} (status=deploying); this call does not wait for full completion.${progressHint}${warningSuffix}`
|
|
117796
118776
|
}, null, 2)
|
|
117797
118777
|
}
|
|
117798
118778
|
]
|
|
@@ -121928,7 +122908,9 @@ function registerAppTools(server) {
|
|
|
121928
122908
|
buildId,
|
|
121929
122909
|
});
|
|
121930
122910
|
(0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
|
|
121931
|
-
|
|
122911
|
+
// Platform may return Failed/failed; normalize before matching.
|
|
122912
|
+
const isFailed = typeof result.Status === "string" &&
|
|
122913
|
+
result.Status.toLowerCase() === "failed";
|
|
121932
122914
|
const payload = {
|
|
121933
122915
|
action,
|
|
121934
122916
|
serviceName,
|
|
@@ -131459,8 +132441,11 @@ module.exports = setup;
|
|
|
131459
132441
|
"use strict";
|
|
131460
132442
|
|
|
131461
132443
|
Object.defineProperty(exports, "__esModule", ({ value: true }));
|
|
132444
|
+
exports.CAM_AUTH_ERROR_PATTERN = void 0;
|
|
131462
132445
|
exports.assertTcbCloudRunActionAllowed = assertTcbCloudRunActionAllowed;
|
|
131463
132446
|
exports.removeEmptyStringParams = removeEmptyStringParams;
|
|
132447
|
+
exports.buildCamAuthGuidance = buildCamAuthGuidance;
|
|
132448
|
+
exports.isCamAuthError = isCamAuthError;
|
|
131464
132449
|
exports.buildCapiErrorMessage = buildCapiErrorMessage;
|
|
131465
132450
|
exports.registerCapiTools = registerCapiTools;
|
|
131466
132451
|
const zod_1 = __webpack_require__(7552);
|
|
@@ -131480,27 +132465,30 @@ const ALLOWED_SERVICES = [
|
|
|
131480
132465
|
"vpc",
|
|
131481
132466
|
];
|
|
131482
132467
|
/**
|
|
131483
|
-
* tcb
|
|
132468
|
+
* Legacy tcb small-tenant CloudRun (CloudBase Run) API family — blocked.
|
|
131484
132469
|
*
|
|
131485
|
-
*
|
|
131486
|
-
* CreateCloudBaseRunResource
|
|
131487
|
-
*
|
|
131488
|
-
*
|
|
132470
|
+
* CloudRun must use tcbr (CreateCloudRunEnv / CreateCloudRunServer). tcb
|
|
132471
|
+
* CreateCloudBaseRunResource is the 2018 small-tenant open API and is no longer
|
|
132472
|
+
* publicly listed; calling it on an env without a large-tenant record creates
|
|
132473
|
+
* wrong small-tenant services/versions (user incident 2026-08-13; ATO research
|
|
132474
|
+
* efec7cc5). Describe/Delete of the same family are blocked too. Matching is
|
|
132475
|
+
* case-insensitive so Action casing variants cannot bypass the check.
|
|
131489
132476
|
*/
|
|
131490
132477
|
const TCB_CLOUDRUN_FORBIDDEN_ACTIONS = [
|
|
131491
132478
|
"CreateCloudBaseRunResource",
|
|
131492
132479
|
"DescribeCloudBaseRunResource",
|
|
131493
132480
|
"DeleteCloudBaseRunResource",
|
|
131494
132481
|
];
|
|
132482
|
+
const TCB_CLOUDRUN_FORBIDDEN_ACTIONS_LOWER = new Set(TCB_CLOUDRUN_FORBIDDEN_ACTIONS.map((name) => name.toLowerCase()));
|
|
131495
132483
|
const TCB_CLOUDRUN_FORBIDDEN_HINT = `云托管(CloudBase Run)统一走 tcbr 新逻辑(CreateCloudRunEnv / CreateCloudRunServer),` +
|
|
131496
132484
|
`不要使用 tcb 旧小租户接口(${TCB_CLOUDRUN_FORBIDDEN_ACTIONS.join(" / ")})。` +
|
|
131497
132485
|
`新环境请先初始化云托管:callCloudApi(service="tcbr", version="2022-02-17", action="CreateCloudRunEnv", params={EnvId:"..."}),` +
|
|
131498
132486
|
`再通过 manageCloudRun(action="deploy") 创建服务;查询单个环境基础信息/是否已开通云托管用 callCloudApi(service="tcbr", version="2022-02-17", action="DescribeEnvBaseInfo", params={EnvId:"..."}),查询环境列表/资源信息用 DescribeCloudRunEnvs。`;
|
|
131499
132487
|
/**
|
|
131500
|
-
*
|
|
132488
|
+
* Reject legacy tcb small-tenant CloudRun APIs; throw with tcbr guidance when blocked.
|
|
131501
132489
|
*/
|
|
131502
132490
|
function assertTcbCloudRunActionAllowed(service, action) {
|
|
131503
|
-
if (service === "tcb" &&
|
|
132491
|
+
if (service === "tcb" && TCB_CLOUDRUN_FORBIDDEN_ACTIONS_LOWER.has(action.toLowerCase())) {
|
|
131504
132492
|
throw new Error(`[${service}/${action}] 已禁用:${TCB_CLOUDRUN_FORBIDDEN_HINT}`);
|
|
131505
132493
|
}
|
|
131506
132494
|
}
|
|
@@ -131584,6 +132572,21 @@ function buildCapiDocGuidance(service) {
|
|
|
131584
132572
|
}
|
|
131585
132573
|
return `请优先核对对应官方云 API 文档;若你的场景其实是通过 HTTP 协议直接集成 auth/functions/cloudrun/storage/mysqldb 等 CloudBase 业务 API,请优先使用 OpenAPI / Swagger 或 searchKnowledgeBase(mode="openapi"),不要继续猜测管控面 Action。`;
|
|
131586
132574
|
}
|
|
132575
|
+
/** Match CAM / authorization failures from Tencent Cloud control-plane APIs. */
|
|
132576
|
+
exports.CAM_AUTH_ERROR_PATTERN = /UnauthorizedOperation|AuthFailure|not authorized|cam.*denied|Forbidden/i;
|
|
132577
|
+
/**
|
|
132578
|
+
* Guidance when control-plane calls fail due to CAM / API Key scope limits.
|
|
132579
|
+
* Shared by callCloudApi and manageCloudRun error builders.
|
|
132580
|
+
*/
|
|
132581
|
+
function buildCamAuthGuidance() {
|
|
132582
|
+
return ("这通常是 CAM 权限不足(常见于 API Key 登录仅授权数据面:DB/函数/存储)。请任选其一:" +
|
|
132583
|
+
"1) 改用 device code 登录管控面:auth(action=\"start_auth\", authMode=\"device\");" +
|
|
132584
|
+
"2) 或使用腾讯云 SecretId/SecretKey(确认子账号已授 CAM 策略,如 QcloudTCBFullAccess、QcloudVPCReadOnlyAccess);" +
|
|
132585
|
+
"3) 确认目标资源属于当前登录账号。");
|
|
132586
|
+
}
|
|
132587
|
+
function isCamAuthError(message) {
|
|
132588
|
+
return exports.CAM_AUTH_ERROR_PATTERN.test(message);
|
|
132589
|
+
}
|
|
131587
132590
|
function buildCapiErrorMessage(service, action, error) {
|
|
131588
132591
|
const baseMessage = error instanceof Error ? error.message : String(error);
|
|
131589
132592
|
const suggestions = [];
|
|
@@ -131591,6 +132594,10 @@ function buildCapiErrorMessage(service, action, error) {
|
|
|
131591
132594
|
const hasInvalidActionError = /invalid or not found|does not exist|not recognized/i.test(baseMessage);
|
|
131592
132595
|
const hasParameterError = /parameter\s+`?.+?`?\s+is not recognized|MissingParameter|missing parameter|missing required/i.test(baseMessage);
|
|
131593
132596
|
const hasInvalidParameterValueError = /invalid parameter value/i.test(baseMessage);
|
|
132597
|
+
const hasCamAuthError = isCamAuthError(baseMessage);
|
|
132598
|
+
if (hasCamAuthError) {
|
|
132599
|
+
suggestions.push(buildCamAuthGuidance());
|
|
132600
|
+
}
|
|
131594
132601
|
if (hasInvalidActionError) {
|
|
131595
132602
|
suggestions.push(`Action \`${action}\` 可能不存在或不对外开放。请不要继续猜测 Action 名称,先确认 service=\`${service}\` 下该 Action 在当前 API 版本是否真实存在。`);
|
|
131596
132603
|
if (service === "tcb") {
|
|
@@ -131708,9 +132715,13 @@ function registerCapiTools(server) {
|
|
|
131708
132715
|
}
|
|
131709
132716
|
if (service === 'tcb') {
|
|
131710
132717
|
const tcbCapiForbidList = [
|
|
131711
|
-
//
|
|
132718
|
+
// Cloud APIs not clearly public
|
|
131712
132719
|
'DescribeStorageACL', 'ModifyStorageACL', 'DescribeSecurityRule',
|
|
131713
|
-
//
|
|
132720
|
+
// Legacy small-tenant CloudRun open/query/delete (no longer public; also blocked by assertTcbCloudRunActionAllowed)
|
|
132721
|
+
"CreateCloudBaseRunResource",
|
|
132722
|
+
"DescribeCloudBaseRunResource",
|
|
132723
|
+
"DeleteCloudBaseRunResource",
|
|
132724
|
+
// Cloud APIs scheduled for retirement
|
|
131714
132725
|
"ListTables",
|
|
131715
132726
|
"DescribeCloudBaseGWAPI",
|
|
131716
132727
|
"DescribeCloudBaseGWService",
|
|
@@ -142355,7 +143366,7 @@ class TelemetryReporter {
|
|
|
142355
143366
|
const arch = os_1.default.arch(); // 系统架构
|
|
142356
143367
|
// Build-time injected version; guard for vitest / non-webpack runtimes.
|
|
142357
143368
|
const mcpVersion = process.env.npm_package_version ||
|
|
142358
|
-
( true ? "2.
|
|
143369
|
+
( true ? "2.28.0" : 0);
|
|
142359
143370
|
return {
|
|
142360
143371
|
userAgent: `${osType} ${osRelease} ${arch} ${nodeVersion} CloudBase-MCP/${mcpVersion}`,
|
|
142361
143372
|
deviceId: this.deviceId,
|
|
@@ -169298,6 +170309,98 @@ async function resolvePgDbContext(cloudBaseOptions, args) {
|
|
|
169298
170309
|
role: args?.role ?? "cloudbase_admin",
|
|
169299
170310
|
};
|
|
169300
170311
|
}
|
|
170312
|
+
/** Default / recommended roles for CloudBase PG ExecutePGSql.Role */
|
|
170313
|
+
const PG_DEFAULT_ROLE = "cloudbase_admin";
|
|
170314
|
+
const PG_RECOMMENDED_ROLES = [
|
|
170315
|
+
"cloudbase_admin",
|
|
170316
|
+
"anon",
|
|
170317
|
+
"authenticated",
|
|
170318
|
+
"service_role",
|
|
170319
|
+
];
|
|
170320
|
+
/**
|
|
170321
|
+
* Roles that look like login/instance principals and routinely fail SET ROLE
|
|
170322
|
+
* in beacon data (e.g. postgres, postgres_pgdb_<id>). Reject before the API call.
|
|
170323
|
+
*/
|
|
170324
|
+
function isLikelyInvalidPgExecuteRole(role) {
|
|
170325
|
+
const normalized = role.trim();
|
|
170326
|
+
if (!normalized) {
|
|
170327
|
+
return true;
|
|
170328
|
+
}
|
|
170329
|
+
if (normalized === "postgres") {
|
|
170330
|
+
return true;
|
|
170331
|
+
}
|
|
170332
|
+
// Instance-derived login principals, not valid ExecutePGSql Role targets
|
|
170333
|
+
if (/^postgres_pgdb_[a-z0-9]+$/i.test(normalized)) {
|
|
170334
|
+
return true;
|
|
170335
|
+
}
|
|
170336
|
+
// AI-invented concatenations such as cloudbase_admin_pgdb_xxx_pgdb_xxx
|
|
170337
|
+
if (/_pgdb_[a-z0-9]+(_pgdb_[a-z0-9]+)?$/i.test(normalized) &&
|
|
170338
|
+
!PG_RECOMMENDED_ROLES.includes(normalized)) {
|
|
170339
|
+
return true;
|
|
170340
|
+
}
|
|
170341
|
+
return false;
|
|
170342
|
+
}
|
|
170343
|
+
function extractPgRoleNameFromError(message) {
|
|
170344
|
+
const missing = message.match(/role\s+"([^"]+)"\s+does\s+not\s+exist/i);
|
|
170345
|
+
if (missing?.[1]) {
|
|
170346
|
+
return missing[1];
|
|
170347
|
+
}
|
|
170348
|
+
const setRole = message.match(/set\s+role\s+([^\s:]+)/i);
|
|
170349
|
+
if (setRole?.[1]) {
|
|
170350
|
+
return setRole[1].replace(/^"|"$/g, "");
|
|
170351
|
+
}
|
|
170352
|
+
const denied = message.match(/permission\s+denied\s+to\s+set\s+role\s+"([^"]+)"/i);
|
|
170353
|
+
if (denied?.[1]) {
|
|
170354
|
+
return denied[1];
|
|
170355
|
+
}
|
|
170356
|
+
return null;
|
|
170357
|
+
}
|
|
170358
|
+
function isPgRoleExecutionError(message) {
|
|
170359
|
+
const lower = message.toLowerCase();
|
|
170360
|
+
return ((lower.includes("set role") &&
|
|
170361
|
+
(lower.includes("does not exist") ||
|
|
170362
|
+
lower.includes("permission denied"))) ||
|
|
170363
|
+
/role\s+"[^"]+"\s+does\s+not\s+exist/i.test(message) ||
|
|
170364
|
+
/permission\s+denied\s+to\s+set\s+role/i.test(message));
|
|
170365
|
+
}
|
|
170366
|
+
function buildPgRoleGuidanceMessage(attemptedRole) {
|
|
170367
|
+
const recommended = PG_RECOMMENDED_ROLES.join(", ");
|
|
170368
|
+
return (`PostgreSQL role "${attemptedRole}" cannot be used with ExecutePGSql (SET ROLE failed or role does not exist). ` +
|
|
170369
|
+
`Do not invent roles like postgres / postgres_pgdb_* from env or instance names. ` +
|
|
170370
|
+
`Omit role (defaults to ${PG_DEFAULT_ROLE}) or pass one of: ${recommended}. ` +
|
|
170371
|
+
`To list roles that exist in this database, retry with role=${PG_DEFAULT_ROLE} and SQL: SELECT rolname FROM pg_roles ORDER BY rolname;`);
|
|
170372
|
+
}
|
|
170373
|
+
function buildPgRoleErrorPayload(attemptedRole, rawMessage) {
|
|
170374
|
+
return {
|
|
170375
|
+
success: false,
|
|
170376
|
+
errorCode: "PG_ROLE_NOT_AVAILABLE",
|
|
170377
|
+
message: buildPgRoleGuidanceMessage(attemptedRole),
|
|
170378
|
+
data: {
|
|
170379
|
+
attemptedRole,
|
|
170380
|
+
defaultRole: PG_DEFAULT_ROLE,
|
|
170381
|
+
recommendedRoles: [...PG_RECOMMENDED_ROLES],
|
|
170382
|
+
listRolesSql: "SELECT rolname FROM pg_roles ORDER BY rolname;",
|
|
170383
|
+
...(rawMessage ? { rawError: rawMessage.slice(0, 500) } : {}),
|
|
170384
|
+
},
|
|
170385
|
+
nextActions: [
|
|
170386
|
+
buildNextAction(MANAGE_PG_DATABASE, "execute", `Retry without a custom role (defaults to ${PG_DEFAULT_ROLE}), or pass role=${PG_DEFAULT_ROLE} explicitly.`, {
|
|
170387
|
+
action: "execute",
|
|
170388
|
+
role: PG_DEFAULT_ROLE,
|
|
170389
|
+
sql: "SELECT rolname FROM pg_roles ORDER BY rolname;",
|
|
170390
|
+
confirm: true,
|
|
170391
|
+
}),
|
|
170392
|
+
buildNextAction(QUERY_PG_DATABASE, "context", "Inspect the auto-derived PG context (includes default role) before retrying.", { action: "context" }),
|
|
170393
|
+
],
|
|
170394
|
+
};
|
|
170395
|
+
}
|
|
170396
|
+
function tryBuildPgRoleErrorPayload(error, fallbackRole) {
|
|
170397
|
+
const rawMessage = error instanceof Error ? error.message : String(error);
|
|
170398
|
+
if (!isPgRoleExecutionError(rawMessage)) {
|
|
170399
|
+
return null;
|
|
170400
|
+
}
|
|
170401
|
+
const attemptedRole = extractPgRoleNameFromError(rawMessage) ?? fallbackRole;
|
|
170402
|
+
return buildPgRoleErrorPayload(attemptedRole, rawMessage);
|
|
170403
|
+
}
|
|
169301
170404
|
function normalizeLimit(limit, fallback = 20, max = 200) {
|
|
169302
170405
|
if (!Number.isFinite(limit)) {
|
|
169303
170406
|
return fallback;
|
|
@@ -170522,7 +171625,26 @@ async function handleReadOnlySql(args, context, deps) {
|
|
|
170522
171625
|
}
|
|
170523
171626
|
const limit = normalizeLimit(args.limit);
|
|
170524
171627
|
const limitedSql = buildLimitedReadOnlySql(args.sql, limit);
|
|
170525
|
-
|
|
171628
|
+
let result;
|
|
171629
|
+
try {
|
|
171630
|
+
result = await withPgClient(context, deps, (client) => client.query(limitedSql));
|
|
171631
|
+
}
|
|
171632
|
+
catch (error) {
|
|
171633
|
+
const rolePayload = tryBuildPgRoleErrorPayload(error, context.role);
|
|
171634
|
+
if (rolePayload) {
|
|
171635
|
+
return buildPgToolResult(rolePayload);
|
|
171636
|
+
}
|
|
171637
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
171638
|
+
return buildPgToolResult({
|
|
171639
|
+
success: false,
|
|
171640
|
+
errorCode: "PG_SQL_EXEC_FAILED",
|
|
171641
|
+
message: `PostgreSQL read-only SQL execution failed: ${reason}`,
|
|
171642
|
+
data: {
|
|
171643
|
+
role: context.role,
|
|
171644
|
+
sqlPreview: limitedSql.trim().slice(0, 500),
|
|
171645
|
+
},
|
|
171646
|
+
});
|
|
171647
|
+
}
|
|
170526
171648
|
const summary = summarizeQueryResult(result, limit);
|
|
170527
171649
|
return buildPgToolResult({
|
|
170528
171650
|
success: true,
|
|
@@ -170577,6 +171699,9 @@ async function handleExecuteSql(args, context, deps) {
|
|
|
170577
171699
|
],
|
|
170578
171700
|
});
|
|
170579
171701
|
}
|
|
171702
|
+
if (args.role !== undefined && isLikelyInvalidPgExecuteRole(args.role)) {
|
|
171703
|
+
return buildPgToolResult(buildPgRoleErrorPayload(args.role.trim() || "(empty)"));
|
|
171704
|
+
}
|
|
170580
171705
|
if (!classification.readOnly && !args.confirm) {
|
|
170581
171706
|
return buildPgToolResult({
|
|
170582
171707
|
success: false,
|
|
@@ -170596,7 +171721,26 @@ async function handleExecuteSql(args, context, deps) {
|
|
|
170596
171721
|
],
|
|
170597
171722
|
});
|
|
170598
171723
|
}
|
|
170599
|
-
|
|
171724
|
+
let result;
|
|
171725
|
+
try {
|
|
171726
|
+
result = await withPgClient(context, deps, (client) => client.query(args.sql));
|
|
171727
|
+
}
|
|
171728
|
+
catch (error) {
|
|
171729
|
+
const rolePayload = tryBuildPgRoleErrorPayload(error, context.role);
|
|
171730
|
+
if (rolePayload) {
|
|
171731
|
+
return buildPgToolResult(rolePayload);
|
|
171732
|
+
}
|
|
171733
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
171734
|
+
return buildPgToolResult({
|
|
171735
|
+
success: false,
|
|
171736
|
+
errorCode: "PG_SQL_EXEC_FAILED",
|
|
171737
|
+
message: `PostgreSQL SQL execution failed: ${reason}`,
|
|
171738
|
+
data: {
|
|
171739
|
+
role: context.role,
|
|
171740
|
+
sqlPreview: args.sql.trim().slice(0, 500),
|
|
171741
|
+
},
|
|
171742
|
+
});
|
|
171743
|
+
}
|
|
170600
171744
|
const targetTable = parseTargetTableFromSql(args.sql, context.defaultSchema);
|
|
170601
171745
|
return buildPgToolResult({
|
|
170602
171746
|
success: true,
|
|
@@ -171489,7 +172633,9 @@ function registerPGDatabaseTools(server, providedDeps) {
|
|
|
171489
172633
|
role: zod_1.z
|
|
171490
172634
|
.string()
|
|
171491
172635
|
.optional()
|
|
171492
|
-
.describe(
|
|
172636
|
+
.describe(`可选的 PostgreSQL role,传给 Manager SDK executePGSql 的 Role(平台会 SET ROLE)。默认 ${PG_DEFAULT_ROLE}。` +
|
|
172637
|
+
`推荐取值:${PG_RECOMMENDED_ROLES.join(" / ")}。` +
|
|
172638
|
+
`不要传 postgres、postgres_pgdb_* 或从环境名臆造的角色;不确定时省略本字段,或先用 ${PG_DEFAULT_ROLE} 执行 SELECT rolname FROM pg_roles。`),
|
|
171493
172639
|
objectName: zod_1.z
|
|
171494
172640
|
.string()
|
|
171495
172641
|
.optional()
|
|
@@ -171593,6 +172739,10 @@ function registerPGDatabaseTools(server, providedDeps) {
|
|
|
171593
172739
|
return handleExecuteSql(args, context, deps);
|
|
171594
172740
|
}
|
|
171595
172741
|
}
|
|
172742
|
+
// Reject known-bad Role values before readiness probe / ExecutePGSql SET ROLE.
|
|
172743
|
+
if (args.role !== undefined && isLikelyInvalidPgExecuteRole(args.role)) {
|
|
172744
|
+
return buildPgToolResult(buildPgRoleErrorPayload(args.role.trim() || "(empty)"));
|
|
172745
|
+
}
|
|
171596
172746
|
try {
|
|
171597
172747
|
await ensurePgReadyOnce(cbOpts, deps);
|
|
171598
172748
|
}
|
|
@@ -223930,7 +225080,7 @@ ${envIdSection}
|
|
|
223930
225080
|
## 环境信息
|
|
223931
225081
|
- 操作系统: ${os_1.default.type()} ${os_1.default.release()}
|
|
223932
225082
|
- Node.js版本: ${process.version}
|
|
223933
|
-
- MCP 版本:${process.env.npm_package_version || ( true ? "2.
|
|
225083
|
+
- MCP 版本:${process.env.npm_package_version || ( true ? "2.28.0" : 0)}
|
|
223934
225084
|
- 系统架构: ${os_1.default.arch()}
|
|
223935
225085
|
- 时间: ${new Date().toISOString()}
|
|
223936
225086
|
- 请求ID: ${requestId}
|
|
@@ -224011,7 +225161,7 @@ function createWrappedHandler(name, handler, server) {
|
|
|
224011
225161
|
requestId: (typeof error === 'object' && error && 'requestId' in error) ? error.requestId : '',
|
|
224012
225162
|
ide: server.ide || process.env.INTEGRATION_IDE || ''
|
|
224013
225163
|
});
|
|
224014
|
-
const mcpVersion = true ? "2.
|
|
225164
|
+
const mcpVersion = true ? "2.28.0" : 0;
|
|
224015
225165
|
const requestIdSuffix = requestId ? `\n🆔 RequestId: ${requestId}` : '';
|
|
224016
225166
|
const enhancedErrorMessage = `${errorMessage}${requestIdSuffix}\n\n📦 CloudBase MCP v${mcpVersion}\n🔗 遇到问题?请复制以下链接到浏览器打开\n即可自动携带错误详情快速创建 GitHub Issue:\n${issueLink}`;
|
|
224017
225167
|
// 创建新的错误对象,保持原有的错误类型但更新消息
|
|
@@ -233968,6 +235118,15 @@ const logger_js_1 = __webpack_require__(13039);
|
|
|
233968
235118
|
const CATEGORY = "NoSQL database";
|
|
233969
235119
|
const COLLECTION_READY_TIMEOUT_MS = 10000;
|
|
233970
235120
|
const COLLECTION_READY_POLL_INTERVAL_MS = 500;
|
|
235121
|
+
/** Default page size for QueryRecords (unchanged; overrun tuning is a separate track). */
|
|
235122
|
+
const QUERY_RECORDS_DEFAULT_LIMIT = 100;
|
|
235123
|
+
/** Cloud API MgoLimit `lte` upper bound (aligned with ListTables / SDK limit docs). */
|
|
235124
|
+
const QUERY_RECORDS_MAX_LIMIT = 1000;
|
|
235125
|
+
const PROJECTION_EXAMPLE = '{"_id":1,"name":1,"createdAt":1}';
|
|
235126
|
+
const PROJECTION_EXCLUDE_EXAMPLE = '{"password":0}';
|
|
235127
|
+
const PROJECTION_GUIDANCE = `projection 必须是字段投影对象(或对应 JSON 字符串),值只能是 1/0/true/false。` +
|
|
235128
|
+
`合法示例:${PROJECTION_EXAMPLE}(只返回这些字段),或 ${PROJECTION_EXCLUDE_EXAMPLE}(排除字段)。` +
|
|
235129
|
+
`不要传字段名数组、逗号分隔字符串、查询条件,也不要在同一投影里混用包含(1/true)与排除(0/false)(_id 除外)。`;
|
|
233971
235130
|
/** Convert object values to JSON strings for API calls */
|
|
233972
235131
|
const toJSONString = (v) => typeof v === "object" && v !== null ? JSON.stringify(v) : v;
|
|
233973
235132
|
function delay(ms) {
|
|
@@ -234038,6 +235197,95 @@ function normalizeSortInput(sort) {
|
|
|
234038
235197
|
}
|
|
234039
235198
|
return JSON.stringify(parsed.map((item) => normalizeSortItem(item)));
|
|
234040
235199
|
}
|
|
235200
|
+
function isProjectionFlag(value) {
|
|
235201
|
+
return value === 0 || value === 1 || value === true || value === false;
|
|
235202
|
+
}
|
|
235203
|
+
function normalizeProjectionInput(projection) {
|
|
235204
|
+
if (projection === undefined || projection === null) {
|
|
235205
|
+
return undefined;
|
|
235206
|
+
}
|
|
235207
|
+
let parsed = projection;
|
|
235208
|
+
if (typeof parsed === "string") {
|
|
235209
|
+
const trimmed = parsed.trim();
|
|
235210
|
+
if (!trimmed) {
|
|
235211
|
+
return undefined;
|
|
235212
|
+
}
|
|
235213
|
+
try {
|
|
235214
|
+
parsed = JSON.parse(trimmed);
|
|
235215
|
+
}
|
|
235216
|
+
catch {
|
|
235217
|
+
throw new Error(`projection 必须是合法 JSON 对象字符串。${PROJECTION_GUIDANCE}`);
|
|
235218
|
+
}
|
|
235219
|
+
}
|
|
235220
|
+
if (Array.isArray(parsed)) {
|
|
235221
|
+
throw new Error(`projection 不支持字段名数组。请改为对象,例如 ${PROJECTION_EXAMPLE}。${PROJECTION_GUIDANCE}`);
|
|
235222
|
+
}
|
|
235223
|
+
if (!parsed || typeof parsed !== "object") {
|
|
235224
|
+
throw new Error(`projection 必须是对象。请改为例如 ${PROJECTION_EXAMPLE}。${PROJECTION_GUIDANCE}`);
|
|
235225
|
+
}
|
|
235226
|
+
const entries = Object.entries(parsed);
|
|
235227
|
+
if (entries.length === 0) {
|
|
235228
|
+
return undefined;
|
|
235229
|
+
}
|
|
235230
|
+
let hasInclude = false;
|
|
235231
|
+
let hasExclude = false;
|
|
235232
|
+
const normalized = {};
|
|
235233
|
+
for (const [key, value] of entries) {
|
|
235234
|
+
if (typeof key !== "string" || key.trim() === "") {
|
|
235235
|
+
throw new Error(`projection 字段名必须是非空字符串。${PROJECTION_GUIDANCE}`);
|
|
235236
|
+
}
|
|
235237
|
+
if (!isProjectionFlag(value)) {
|
|
235238
|
+
throw new Error(`projection["${key}"] 的值非法(当前为 ${JSON.stringify(value)}),仅支持 1/0/true/false。` +
|
|
235239
|
+
`合法示例:${PROJECTION_EXAMPLE}。${PROJECTION_GUIDANCE}`);
|
|
235240
|
+
}
|
|
235241
|
+
const flag = value === true || value === 1 ? 1 : 0;
|
|
235242
|
+
normalized[key] = flag;
|
|
235243
|
+
if (key === "_id") {
|
|
235244
|
+
continue;
|
|
235245
|
+
}
|
|
235246
|
+
if (flag === 1) {
|
|
235247
|
+
hasInclude = true;
|
|
235248
|
+
}
|
|
235249
|
+
else {
|
|
235250
|
+
hasExclude = true;
|
|
235251
|
+
}
|
|
235252
|
+
}
|
|
235253
|
+
if (hasInclude && hasExclude) {
|
|
235254
|
+
throw new Error(`projection 不能同时混用包含(1/true)与排除(0/false)(_id 除外)。` +
|
|
235255
|
+
`请只保留一种模式,例如 ${PROJECTION_EXAMPLE} 或 ${PROJECTION_EXCLUDE_EXAMPLE}。`);
|
|
235256
|
+
}
|
|
235257
|
+
return JSON.stringify(normalized);
|
|
235258
|
+
}
|
|
235259
|
+
function normalizeQueryLimit(limit) {
|
|
235260
|
+
if (limit === undefined || limit === null) {
|
|
235261
|
+
return QUERY_RECORDS_DEFAULT_LIMIT;
|
|
235262
|
+
}
|
|
235263
|
+
if (typeof limit !== "number" || !Number.isFinite(limit)) {
|
|
235264
|
+
throw new Error(`limit 必须是数字,取值范围 1-${QUERY_RECORDS_MAX_LIMIT}(默认 ${QUERY_RECORDS_DEFAULT_LIMIT})。` +
|
|
235265
|
+
`超出上限时请用 offset 分页,例如 limit=${QUERY_RECORDS_MAX_LIMIT}, offset=0,再 offset+=limit。`);
|
|
235266
|
+
}
|
|
235267
|
+
if (!Number.isInteger(limit)) {
|
|
235268
|
+
throw new Error(`limit 必须是整数,取值范围 1-${QUERY_RECORDS_MAX_LIMIT}。当前值:${limit}`);
|
|
235269
|
+
}
|
|
235270
|
+
if (limit < 1 || limit > QUERY_RECORDS_MAX_LIMIT) {
|
|
235271
|
+
throw new Error(`limit 超出上限:当前 ${limit},允许范围 1-${QUERY_RECORDS_MAX_LIMIT}(Cloud API MgoLimit lte)。` +
|
|
235272
|
+
`请将 limit 调整为 ≤${QUERY_RECORDS_MAX_LIMIT},并用 offset 分页拉取更多数据` +
|
|
235273
|
+
`(例如 limit=${QUERY_RECORDS_MAX_LIMIT}, offset=0,下一页 offset=${QUERY_RECORDS_MAX_LIMIT})。`);
|
|
235274
|
+
}
|
|
235275
|
+
return limit;
|
|
235276
|
+
}
|
|
235277
|
+
function enhanceQueryRecordsError(error) {
|
|
235278
|
+
const message = error instanceof Error ? error.message : String(error ?? "");
|
|
235279
|
+
if (/Query projection.*illegal|projection entered in the request is illegal/i.test(message)) {
|
|
235280
|
+
throw new Error(`QueryRecords 投影非法:${message}。修正建议:${PROJECTION_GUIDANCE}`);
|
|
235281
|
+
}
|
|
235282
|
+
if (/MgoLimit.*lte|Field validation for 'MgoLimit' failed on the 'lte'/i.test(message)) {
|
|
235283
|
+
throw new Error(`QueryRecords MgoLimit 超限:${message}。` +
|
|
235284
|
+
`limit 最大为 ${QUERY_RECORDS_MAX_LIMIT},请缩小 limit 并用 offset 分页` +
|
|
235285
|
+
`(例如 limit=${QUERY_RECORDS_MAX_LIMIT}, offset=0)。`);
|
|
235286
|
+
}
|
|
235287
|
+
throw error instanceof Error ? error : new Error(message);
|
|
235288
|
+
}
|
|
234041
235289
|
function withCollectionName(collectionName, payload) {
|
|
234042
235290
|
return {
|
|
234043
235291
|
...payload,
|
|
@@ -234572,7 +235820,9 @@ deleteCollection: 删除集合`),
|
|
|
234572
235820
|
// readNoSqlDatabaseContent
|
|
234573
235821
|
server.registerTool?.("readNoSqlDatabaseContent", {
|
|
234574
235822
|
title: "查询并获取 CloudBase NoSQL 数据库数据记录",
|
|
234575
|
-
description: "查询 CloudBase NoSQL 数据库中的数据记录。支持按条件筛选、分页、排序,适用于管理端数据查询与运维。"
|
|
235823
|
+
description: "查询 CloudBase NoSQL 数据库中的数据记录。支持按条件筛选、分页、排序,适用于管理端数据查询与运维。" +
|
|
235824
|
+
`limit 默认 ${QUERY_RECORDS_DEFAULT_LIMIT}、最大 ${QUERY_RECORDS_MAX_LIMIT};超出请用 offset 分页。` +
|
|
235825
|
+
`projection 仅支持 { field: 1|0 } 对象(示例 ${PROJECTION_EXAMPLE}),不要传字段数组。`,
|
|
234576
235826
|
inputSchema: {
|
|
234577
235827
|
collectionName: zod_1.z.string().describe("集合名称"),
|
|
234578
235828
|
instanceId: zod_1.z
|
|
@@ -234586,7 +235836,9 @@ deleteCollection: 删除集合`),
|
|
|
234586
235836
|
projection: zod_1.z
|
|
234587
235837
|
.union([zod_1.z.object({}).passthrough(), zod_1.z.string()])
|
|
234588
235838
|
.optional()
|
|
234589
|
-
.describe(
|
|
235839
|
+
.describe(`返回字段投影,仅支持对象或对应 JSON 字符串,值只能是 1/0/true/false。` +
|
|
235840
|
+
`合法示例:${PROJECTION_EXAMPLE}(包含)或 ${PROJECTION_EXCLUDE_EXAMPLE}(排除)。` +
|
|
235841
|
+
`不要传 ["name","age"] 这类字段数组,也不要混用包含与排除(_id 除外)。`),
|
|
234590
235842
|
sort: zod_1.z
|
|
234591
235843
|
.union([
|
|
234592
235844
|
zod_1.z.array(zod_1.z
|
|
@@ -234599,7 +235851,11 @@ deleteCollection: 删除集合`),
|
|
|
234599
235851
|
])
|
|
234600
235852
|
.optional()
|
|
234601
235853
|
.describe('排序条件,仅支持数组 [{"key":"createdAt","direction":-1}] 或对应 JSON 字符串。'),
|
|
234602
|
-
limit: zod_1.z
|
|
235854
|
+
limit: zod_1.z
|
|
235855
|
+
.number()
|
|
235856
|
+
.optional()
|
|
235857
|
+
.describe(`返回数量限制,整数,范围 1-${QUERY_RECORDS_MAX_LIMIT},默认 ${QUERY_RECORDS_DEFAULT_LIMIT}。` +
|
|
235858
|
+
`超过 ${QUERY_RECORDS_MAX_LIMIT} 会被 Cloud API MgoLimit lte 校验拒绝;请用 offset 分页。`),
|
|
234603
235859
|
offset: zod_1.z.number().optional().describe("跳过的记录数"),
|
|
234604
235860
|
},
|
|
234605
235861
|
annotations: {
|
|
@@ -234615,46 +235871,53 @@ deleteCollection: 删除集合`),
|
|
|
234615
235871
|
durationMs: Date.now() - managerStartedAt,
|
|
234616
235872
|
});
|
|
234617
235873
|
const normalizedSort = normalizeSortInput(sort);
|
|
234618
|
-
const
|
|
234619
|
-
|
|
234620
|
-
|
|
234621
|
-
|
|
234622
|
-
|
|
234623
|
-
|
|
234624
|
-
|
|
234625
|
-
|
|
234626
|
-
|
|
234627
|
-
|
|
234628
|
-
|
|
234629
|
-
|
|
234630
|
-
|
|
234631
|
-
|
|
234632
|
-
|
|
234633
|
-
|
|
234634
|
-
const parseStartedAt = Date.now();
|
|
234635
|
-
const documents = normalizeNoSqlDocuments(result.Data);
|
|
234636
|
-
logNoSqlLatency("readNoSqlDatabaseContent", "parseResult", {
|
|
234637
|
-
collectionName,
|
|
234638
|
-
durationMs: Date.now() - parseStartedAt,
|
|
234639
|
-
documentCount: documents.length,
|
|
234640
|
-
});
|
|
234641
|
-
return {
|
|
234642
|
-
content: [
|
|
234643
|
-
{
|
|
234644
|
-
type: "text",
|
|
234645
|
-
text: JSON.stringify(withCollectionName(collectionName, {
|
|
234646
|
-
success: true,
|
|
234647
|
-
requestId: result.RequestId,
|
|
234648
|
-
data: documents,
|
|
234649
|
-
total: typeof result.Pager?.Total === "number"
|
|
234650
|
-
? result.Pager.Total
|
|
234651
|
-
: documents.length,
|
|
234652
|
-
pager: result.Pager,
|
|
234653
|
-
message: "文档查询成功",
|
|
234654
|
-
}), null, 2),
|
|
235874
|
+
const normalizedProjection = normalizeProjectionInput(projection);
|
|
235875
|
+
const normalizedLimit = normalizeQueryLimit(limit);
|
|
235876
|
+
try {
|
|
235877
|
+
const result = await callNoSqlContentApi({
|
|
235878
|
+
toolName: "readNoSqlDatabaseContent",
|
|
235879
|
+
action: "QueryRecords",
|
|
235880
|
+
collectionName,
|
|
235881
|
+
cloudbase,
|
|
235882
|
+
cloudBaseOptions,
|
|
235883
|
+
instanceIdOverride: instanceId,
|
|
235884
|
+
param: {
|
|
235885
|
+
MgoQuery: toJSONString(query),
|
|
235886
|
+
MgoProjection: normalizedProjection,
|
|
235887
|
+
MgoSort: normalizedSort,
|
|
235888
|
+
MgoLimit: normalizedLimit,
|
|
235889
|
+
MgoOffset: offset,
|
|
234655
235890
|
},
|
|
234656
|
-
|
|
234657
|
-
|
|
235891
|
+
});
|
|
235892
|
+
(0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
|
|
235893
|
+
const parseStartedAt = Date.now();
|
|
235894
|
+
const documents = normalizeNoSqlDocuments(result.Data);
|
|
235895
|
+
logNoSqlLatency("readNoSqlDatabaseContent", "parseResult", {
|
|
235896
|
+
collectionName,
|
|
235897
|
+
durationMs: Date.now() - parseStartedAt,
|
|
235898
|
+
documentCount: documents.length,
|
|
235899
|
+
});
|
|
235900
|
+
return {
|
|
235901
|
+
content: [
|
|
235902
|
+
{
|
|
235903
|
+
type: "text",
|
|
235904
|
+
text: JSON.stringify(withCollectionName(collectionName, {
|
|
235905
|
+
success: true,
|
|
235906
|
+
requestId: result.RequestId,
|
|
235907
|
+
data: documents,
|
|
235908
|
+
total: typeof result.Pager?.Total === "number"
|
|
235909
|
+
? result.Pager.Total
|
|
235910
|
+
: documents.length,
|
|
235911
|
+
pager: result.Pager,
|
|
235912
|
+
message: "文档查询成功",
|
|
235913
|
+
}), null, 2),
|
|
235914
|
+
},
|
|
235915
|
+
],
|
|
235916
|
+
};
|
|
235917
|
+
}
|
|
235918
|
+
catch (error) {
|
|
235919
|
+
enhanceQueryRecordsError(error);
|
|
235920
|
+
}
|
|
234658
235921
|
});
|
|
234659
235922
|
// writeNoSqlDatabaseContent
|
|
234660
235923
|
server.registerTool?.("writeNoSqlDatabaseContent", {
|
|
@@ -239838,6 +241101,7 @@ exports.CloudBaseError = CloudBaseError;
|
|
|
239838
241101
|
"use strict";
|
|
239839
241102
|
|
|
239840
241103
|
Object.defineProperty(exports, "__esModule", ({ value: true }));
|
|
241104
|
+
exports.validateUserRegoContent = validateUserRegoContent;
|
|
239841
241105
|
exports.registerPermissionTools = registerPermissionTools;
|
|
239842
241106
|
const zod_1 = __webpack_require__(7552);
|
|
239843
241107
|
const cloudbase_manager_js_1 = __webpack_require__(3431);
|
|
@@ -239849,6 +241113,9 @@ const QUERY_PERMISSION_ACTIONS = [
|
|
|
239849
241113
|
"getRole",
|
|
239850
241114
|
"listUsers",
|
|
239851
241115
|
"getUser",
|
|
241116
|
+
// Align with CLI `tcb policy list/get` (OPA gateway authz)
|
|
241117
|
+
"listPolicy",
|
|
241118
|
+
"getPolicy",
|
|
239852
241119
|
];
|
|
239853
241120
|
const MANAGE_PERMISSION_ACTIONS = [
|
|
239854
241121
|
"updateResourcePermission",
|
|
@@ -239862,7 +241129,14 @@ const MANAGE_PERMISSION_ACTIONS = [
|
|
|
239862
241129
|
"createUser",
|
|
239863
241130
|
"updateUser",
|
|
239864
241131
|
"deleteUsers",
|
|
241132
|
+
// Align with CLI `tcb policy set` (OPA Rego; disables legacy gateway auth)
|
|
241133
|
+
"setPolicy",
|
|
239865
241134
|
];
|
|
241135
|
+
/** Keys accepted by Manager SDK describeEnvAuthzConfig / modifyEnvAuthzConfig. */
|
|
241136
|
+
const AUTHZ_USER_REGO_KEY = "authz.user.rego";
|
|
241137
|
+
const AUTHZ_PLATFORM_EXTENSION_REGO_KEY = "authz.platform.extension.rego";
|
|
241138
|
+
/** CLI `tcb policy list --resource-type` only documents `policy`. */
|
|
241139
|
+
const POLICY_LIST_RESOURCE_TYPES = ["policy"];
|
|
239866
241140
|
function buildWriteVerificationHint(resourceId) {
|
|
239867
241141
|
return `对于 ${resourceId} 这类有后端权限控制的集合,前端调用 .doc(id).update() / .doc(id).remove() 后,不能只看是否没有抛异常。请显式检查返回结果中的 updated / deleted 是否大于 0;如果 result.code、result.message 存在,或 updated / deleted 为 0,要把它当作真实失败并向上抛错。`;
|
|
239868
241142
|
}
|
|
@@ -239901,10 +241175,32 @@ function isPostgresqlPermissionApiUnsupported(error) {
|
|
|
239901
241175
|
const message = error instanceof Error ? error.message : String(error);
|
|
239902
241176
|
return /does not support PostgreSQL type environments/i.test(message);
|
|
239903
241177
|
}
|
|
239904
|
-
const AUTHZ_USER_REGO_KEY = "authz.user.rego";
|
|
239905
241178
|
function looksLikeUserRego(value) {
|
|
239906
241179
|
return /^\s*package\s+authz\.user\b/m.test(value);
|
|
239907
241180
|
}
|
|
241181
|
+
/**
|
|
241182
|
+
* Validate user Rego before setPolicy / modifyEnvAuthzConfig.
|
|
241183
|
+
* Aligns with CLI docs (must start with `package authz.user`) and CLI non-empty check.
|
|
241184
|
+
* Does not run a full OPA compiler; backend still owns deep syntax validation.
|
|
241185
|
+
*/
|
|
241186
|
+
function validateUserRegoContent(value) {
|
|
241187
|
+
if (typeof value !== "string" || value.trim().length === 0) {
|
|
241188
|
+
throw new Error("action=setPolicy 需要非空 regoContent(对齐 CLI `tcb policy set <regoContent>`)。");
|
|
241189
|
+
}
|
|
241190
|
+
const trimmed = value.trim();
|
|
241191
|
+
if (!looksLikeUserRego(trimmed)) {
|
|
241192
|
+
throw new Error("Rego 策略必须以 `package authz.user` 开头(对齐 https://docs.cloudbase.net/cli-v1/policy/management )。");
|
|
241193
|
+
}
|
|
241194
|
+
const open = (trimmed.match(/\{/g) || []).length;
|
|
241195
|
+
const close = (trimmed.match(/\}/g) || []).length;
|
|
241196
|
+
if (open !== close) {
|
|
241197
|
+
throw new Error(`Rego 策略花括号不匹配({=${open}, }=${close})。请检查语法后再调用 setPolicy。`);
|
|
241198
|
+
}
|
|
241199
|
+
return trimmed;
|
|
241200
|
+
}
|
|
241201
|
+
function resolveAuthzConfigKey(extension) {
|
|
241202
|
+
return extension ? AUTHZ_PLATFORM_EXTENSION_REGO_KEY : AUTHZ_USER_REGO_KEY;
|
|
241203
|
+
}
|
|
239908
241204
|
/** Detect legacy function securityRule shapes that mean "public invoke". */
|
|
239909
241205
|
function isPublicFunctionInvokeRule(securityRule) {
|
|
239910
241206
|
if (!securityRule || securityRule.trim() === "") {
|
|
@@ -239976,29 +241272,38 @@ function resolveFunctionAuthzRegoInput(securityRule, resourceId) {
|
|
|
239976
241272
|
`2) permission="CUSTOM" with securityRule='{"invoke":true}' to generate a public-functions allow policy.\n` +
|
|
239977
241273
|
`See https://docs.cloudbase.net/cli-v1/policy/management`);
|
|
239978
241274
|
}
|
|
239979
|
-
async function
|
|
241275
|
+
async function describeEnvAuthzConfigByKey(cloudbase, key = AUTHZ_USER_REGO_KEY) {
|
|
239980
241276
|
if (!cloudbase?.permission?.describeEnvAuthzConfig) {
|
|
239981
241277
|
throw new Error("Current @cloudbase/manager-node does not expose permission.describeEnvAuthzConfig. Upgrade manager-node (>= 5.5.5) to align with CLI tcb policy get.");
|
|
239982
241278
|
}
|
|
239983
|
-
const result = await cloudbase.permission.describeEnvAuthzConfig({
|
|
239984
|
-
key: AUTHZ_USER_REGO_KEY,
|
|
239985
|
-
});
|
|
241279
|
+
const result = await cloudbase.permission.describeEnvAuthzConfig({ key });
|
|
239986
241280
|
const value = typeof result?.Item?.Value === "string"
|
|
239987
241281
|
? result.Item.Value
|
|
239988
241282
|
: typeof result?.Value === "string"
|
|
239989
241283
|
? result.Value
|
|
239990
241284
|
: "";
|
|
239991
|
-
return { value, raw: result };
|
|
241285
|
+
return { key, value, raw: result };
|
|
241286
|
+
}
|
|
241287
|
+
async function describeEnvAuthzUserRego(cloudbase) {
|
|
241288
|
+
const result = await describeEnvAuthzConfigByKey(cloudbase, AUTHZ_USER_REGO_KEY);
|
|
241289
|
+
return { value: result.value, raw: result.raw };
|
|
239992
241290
|
}
|
|
239993
241291
|
async function modifyEnvAuthzUserRego(cloudbase, value) {
|
|
239994
241292
|
if (!cloudbase?.permission?.modifyEnvAuthzConfig) {
|
|
239995
241293
|
throw new Error("Current @cloudbase/manager-node does not expose permission.modifyEnvAuthzConfig. Upgrade manager-node (>= 5.5.5) to align with CLI tcb policy set.");
|
|
239996
241294
|
}
|
|
241295
|
+
const validated = validateUserRegoContent(value);
|
|
239997
241296
|
return cloudbase.permission.modifyEnvAuthzConfig({
|
|
239998
241297
|
key: AUTHZ_USER_REGO_KEY,
|
|
239999
|
-
value,
|
|
241298
|
+
value: validated,
|
|
240000
241299
|
});
|
|
240001
241300
|
}
|
|
241301
|
+
async function describeResourcePolicyListAligned(cloudbase, policyResourceType) {
|
|
241302
|
+
if (!cloudbase?.permission?.describeResourcePolicyList) {
|
|
241303
|
+
throw new Error("Current @cloudbase/manager-node does not expose permission.describeResourcePolicyList. Upgrade manager-node (>= 5.5.5) to align with CLI tcb policy list.");
|
|
241304
|
+
}
|
|
241305
|
+
return cloudbase.permission.describeResourcePolicyList(policyResourceType ? { resourceType: policyResourceType } : undefined);
|
|
241306
|
+
}
|
|
240002
241307
|
async function describeResourcePermissionWithFunctionPgFallback(options) {
|
|
240003
241308
|
const { cloudbase, envId, resourceType, resources } = options;
|
|
240004
241309
|
try {
|
|
@@ -240232,7 +241537,7 @@ function registerPermissionTools(server) {
|
|
|
240232
241537
|
};
|
|
240233
241538
|
server.registerTool?.("queryPermissions", {
|
|
240234
241539
|
title: "查询 CloudBase 权限与用户配置",
|
|
240235
|
-
description: "查询 CloudBase
|
|
241540
|
+
description: "查询 CloudBase 权限与用户配置,支持查询资源权限(数据库/云函数/存储桶等)、角色列表/详情、应用用户列表/详情,以及网关 OPA 授权策略(对齐 CLI `tcb policy list/get`)。\n\n示例:\n- 查询存储桶权限:`action=\"getResourcePermission\", resourceType=\"storage\", resourceId=\"bucket-name\"`\n- 列出旧网关策略:`action=\"listPolicy\"`(PG / OPA 引擎环境返回空列表,与 CLI 一致)\n- 读取用户 Rego:`action=\"getPolicy\"`;平台扩展策略:`action=\"getPolicy\", extension=true`\n\n📌 跨后端边界提示:调用前先用 `envQuery(action=\"info\", envId=...)` 看 `EnvInfo.RuntimeBackends`。`resourceType=\"noSqlDatabase\"` 查询的是 CloudBase NoSQL 集合规则,与 CloudBase PostgreSQL(PG)表的行级安全(RLS)是两套独立机制——同一个 PG 环境里 NoSQL 集合若仍在使用,对那些集合查询本工具结果**仍然有效**。要查 PG 表 RLS,请改用 `queryPgDatabase(action=\"sql\", sql=\"SELECT * FROM pg_policies WHERE tablename=...\")`。本工具不涉及 MySQL 权限。\n\n⚠️ PostgreSQL 环境:平台 `DescribeResourcePermission` 对 PG 环境会直接拒绝。当 `resourceType=\"function\"` 时,本工具会自动回退到 Manager SDK `describeEnvAuthzConfig`(与 CLI `tcb policy get` 一致,读取 `authz.user.rego`)。显式 OPA 策略请用 `listPolicy` / `getPolicy`。",
|
|
240236
241541
|
inputSchema: {
|
|
240237
241542
|
action: zod_1.z.enum(QUERY_PERMISSION_ACTIONS),
|
|
240238
241543
|
resourceType: zod_1.z
|
|
@@ -240247,13 +241552,21 @@ function registerPermissionTools(server) {
|
|
|
240247
241552
|
username: zod_1.z.string().optional(),
|
|
240248
241553
|
pageNo: zod_1.z.number().optional(),
|
|
240249
241554
|
pageSize: zod_1.z.number().optional(),
|
|
241555
|
+
extension: zod_1.z
|
|
241556
|
+
.boolean()
|
|
241557
|
+
.optional()
|
|
241558
|
+
.describe("仅 action=getPolicy。true=读取平台为该环境单独配置的策略(authz.platform.extension.rego),默认 false=用户策略(authz.user.rego),对齐 CLI `tcb policy get --extension`。"),
|
|
241559
|
+
policyResourceType: zod_1.z
|
|
241560
|
+
.enum(POLICY_LIST_RESOURCE_TYPES)
|
|
241561
|
+
.optional()
|
|
241562
|
+
.describe("仅 action=listPolicy。按资源类型过滤,当前仅支持 `policy`,对齐 CLI `tcb policy list --resource-type policy`。"),
|
|
240250
241563
|
},
|
|
240251
241564
|
annotations: {
|
|
240252
241565
|
readOnlyHint: true,
|
|
240253
241566
|
openWorldHint: true,
|
|
240254
241567
|
category: "permissions",
|
|
240255
241568
|
},
|
|
240256
|
-
}, async ({ action, resourceType, resourceId, resourceIds, roleId, roleIdentity, roleName, uid, username, pageNo, pageSize, }) => withEnvelope(async () => {
|
|
241569
|
+
}, async ({ action, resourceType, resourceId, resourceIds, roleId, roleIdentity, roleName, uid, username, pageNo, pageSize, extension, policyResourceType, }) => withEnvelope(async () => {
|
|
240257
241570
|
const envId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
|
|
240258
241571
|
const cloudbase = await getManager();
|
|
240259
241572
|
switch (action) {
|
|
@@ -240399,11 +241712,43 @@ function registerPermissionTools(server) {
|
|
|
240399
241712
|
raw: result,
|
|
240400
241713
|
}, "应用用户详情查询成功");
|
|
240401
241714
|
}
|
|
241715
|
+
case "listPolicy": {
|
|
241716
|
+
const result = await describeResourcePolicyListAligned(cloudbase, policyResourceType);
|
|
241717
|
+
(0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
|
|
241718
|
+
const data = result
|
|
241719
|
+
?.Data;
|
|
241720
|
+
const policyList = data?.PolicyList ?? [];
|
|
241721
|
+
const total = data?.Total ?? policyList.length;
|
|
241722
|
+
return buildEnvelope({
|
|
241723
|
+
action,
|
|
241724
|
+
envId,
|
|
241725
|
+
policyResourceType: policyResourceType ?? null,
|
|
241726
|
+
policies: policyList,
|
|
241727
|
+
total,
|
|
241728
|
+
note: "PG 环境与 authz_engine=opa 的环境会返回空列表(与 CLI `tcb policy list` / SDK describeResourcePolicyList 一致)。读取用户 Rego 请用 action=getPolicy。",
|
|
241729
|
+
raw: result,
|
|
241730
|
+
}, "网关授权策略列表查询成功");
|
|
241731
|
+
}
|
|
241732
|
+
case "getPolicy": {
|
|
241733
|
+
const key = resolveAuthzConfigKey(extension);
|
|
241734
|
+
const result = await describeEnvAuthzConfigByKey(cloudbase, key);
|
|
241735
|
+
(0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result.raw);
|
|
241736
|
+
return buildEnvelope({
|
|
241737
|
+
action,
|
|
241738
|
+
envId,
|
|
241739
|
+
key: result.key,
|
|
241740
|
+
extension: Boolean(extension),
|
|
241741
|
+
rego: result.value,
|
|
241742
|
+
raw: result.raw,
|
|
241743
|
+
}, extension
|
|
241744
|
+
? "平台扩展 OPA 策略查询成功(authz.platform.extension.rego)"
|
|
241745
|
+
: "用户 OPA 策略查询成功(authz.user.rego)");
|
|
241746
|
+
}
|
|
240402
241747
|
}
|
|
240403
241748
|
}));
|
|
240404
241749
|
server.registerTool?.("managePermissions", {
|
|
240405
241750
|
title: "管理 CloudBase 权限与用户配置",
|
|
240406
|
-
description: "管理 CloudBase 权限与用户配置,支持修改资源权限(数据库/云函数/存储桶等)、角色管理、成员与策略增删、应用用户 CRUD
|
|
241751
|
+
description: "管理 CloudBase 权限与用户配置,支持修改资源权限(数据库/云函数/存储桶等)、角色管理、成员与策略增删、应用用户 CRUD,以及设置网关 OPA Rego 策略(对齐 CLI `tcb policy set`)。\n\n示例:\n- 设置存储桶为私有:`action=\"updateResourcePermission\", resourceType=\"storage\", resourceId=\"bucket-name\", permission=\"PRIVATE\"`\n- 创建角色:`action=\"createRole\", roleName=\"admin\", roleIdentity=\"admin\"`\n- 放开云函数匿名/未登录访问(PG 会走 OPA,对齐 CLI `tcb policy set`):`action=\"updateResourcePermission\", resourceType=\"function\", resourceId=\"myFn\", permission=\"CUSTOM\", securityRule='{\"invoke\":true}'`\n- 直接设置用户 Rego:`action=\"setPolicy\", regoContent=\"package authz.user\\n\\ndefault allow := false\\n\", confirm=true`(⚠️ 立即禁用旧网关鉴权)\n\n注意:`createUser` / `updateUser` 是环境侧应用用户管理能力,适合测试账号、管理员或预置用户,不应替代浏览器里的 Web SDK 注册表单;前端用户名密码注册应使用 `auth.signUp({ username, password })`,登录应使用 `auth.signInWithPassword({ username, password })`。直接在浏览器里用 `auth.signUp` 创建用户名密码用户取决于 SDK/provider 支持,使用前必须验证;不支持时应走后端或管理端边界,不能在浏览器暴露密钥。`securityRule` 的详细语义取决于 `resourceType`:`doc._openid`、`auth.openid`、查询条件子集校验,以及 `create` / `update` / `delete` JSON 模板仅适用于 `resourceType=\"noSqlDatabase\"` 的文档数据库安全规则;配置 `function` 或 `storage` 时,请参考各自官方安全规则文档,而不是复用 NoSQL 模板。\n\n📌 跨后端边界提示:调用前先用 `envQuery(action=\"info\", envId=...)` 看 `EnvInfo.RuntimeBackends`:\n- `resourceType=\"noSqlDatabase\"` 仅作用于 CloudBase NoSQL 文档数据库的集合;CloudBase PostgreSQL(PG)表的行级权限**不**受它控制——PG 表请改用 RLS:`managePgDatabase(action=\"execute\", confirm=true)` 跑 `ALTER TABLE ... ENABLE ROW LEVEL SECURITY` 与 `CREATE POLICY ...`。同一个 PG 环境里如果还有 NoSQL 集合在用,对那些**集合**继续使用 `noSqlDatabase` 规则是正确的——不是\"PG 环境就禁用本工具\"。\n- `resourceType=\"storage\"` 控制的是 NoSQL/COS 存储桶 ACL;PG 的 `pgstore` bucket 不在此 `resourceType` 覆盖范围内。\n- 本工具不涉及 MySQL;MySQL 数据库权限请走 MySQL 自身的 GRANT/REVOKE 语句(通过 `manageMysqlDatabase`)。\n\n⚠️ PostgreSQL 环境:平台 `ModifyResourcePermission` 对 PG 环境会直接拒绝。当 `resourceType=\"function\"` 时,本工具会自动回退到 Manager SDK `modifyEnvAuthzConfig`(与 CLI `tcb policy set` 一致,写入 `authz.user.rego`)。`securityRule` 可传完整 Rego(`package authz.user`)或 `'{\"invoke\":true}'`(自动生成放通 anonymous/unauthenticated 调 functions 的策略)。设置 Rego 后旧网关鉴权会失效,行为与 CLI 相同。显式 OPA 策略请优先用 `action=\"setPolicy\"`。",
|
|
240407
241752
|
inputSchema: {
|
|
240408
241753
|
action: zod_1.z.enum(MANAGE_PERMISSION_ACTIONS),
|
|
240409
241754
|
resourceType: zod_1.z
|
|
@@ -240434,6 +241779,14 @@ function registerPermissionTools(server) {
|
|
|
240434
241779
|
username: zod_1.z.string().optional(),
|
|
240435
241780
|
password: zod_1.z.string().optional(),
|
|
240436
241781
|
userStatus: zod_1.z.enum(["ACTIVE", "BLOCKED"]).optional(),
|
|
241782
|
+
regoContent: zod_1.z
|
|
241783
|
+
.string()
|
|
241784
|
+
.optional()
|
|
241785
|
+
.describe("仅 action=setPolicy。用户 OPA Rego 全文,必须以 `package authz.user` 开头,对齐 CLI `tcb policy set <regoContent>`。"),
|
|
241786
|
+
confirm: zod_1.z
|
|
241787
|
+
.boolean()
|
|
241788
|
+
.optional()
|
|
241789
|
+
.describe("仅 action=setPolicy。设置 Rego 后会立即禁用旧网关鉴权,必须显式传 confirm=true(对齐 CLI 确认提示)。"),
|
|
240437
241790
|
},
|
|
240438
241791
|
annotations: {
|
|
240439
241792
|
readOnlyHint: false,
|
|
@@ -240442,7 +241795,7 @@ function registerPermissionTools(server) {
|
|
|
240442
241795
|
openWorldHint: true,
|
|
240443
241796
|
category: "permissions",
|
|
240444
241797
|
},
|
|
240445
|
-
}, async ({ action, resourceType, resourceId, permission, securityRule, roleId, roleIds, roleName, roleIdentity, description, memberUids, policies, policyIds, uid, uids, username, password, userStatus, }) => withEnvelope(async () => {
|
|
241798
|
+
}, async ({ action, resourceType, resourceId, permission, securityRule, roleId, roleIds, roleName, roleIdentity, description, memberUids, policies, policyIds, uid, uids, username, password, userStatus, regoContent, confirm, }) => withEnvelope(async () => {
|
|
240446
241799
|
const envId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
|
|
240447
241800
|
const cloudbase = await getManager();
|
|
240448
241801
|
const normalizedPolicies = normalizeRecordArray(policies, "policies");
|
|
@@ -240623,6 +241976,26 @@ function registerPermissionTools(server) {
|
|
|
240623
241976
|
raw: result,
|
|
240624
241977
|
}, "应用用户删除成功");
|
|
240625
241978
|
}
|
|
241979
|
+
case "setPolicy": {
|
|
241980
|
+
if (confirm !== true) {
|
|
241981
|
+
throw new Error("action=setPolicy 会立即禁用旧网关鉴权(对齐 CLI `tcb policy set`),必须显式传 confirm=true。");
|
|
241982
|
+
}
|
|
241983
|
+
const validated = validateUserRegoContent(regoContent ?? "");
|
|
241984
|
+
const result = await modifyEnvAuthzUserRego(cloudbase, validated);
|
|
241985
|
+
(0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
|
|
241986
|
+
return buildEnvelope({
|
|
241987
|
+
action,
|
|
241988
|
+
envId,
|
|
241989
|
+
key: AUTHZ_USER_REGO_KEY,
|
|
241990
|
+
rego: validated,
|
|
241991
|
+
sideEffect: "Setting authz.user.rego immediately disables legacy gateway authorization.",
|
|
241992
|
+
nextSteps: [
|
|
241993
|
+
'queryPermissions(action="getPolicy")',
|
|
241994
|
+
'queryPermissions(action="listPolicy")',
|
|
241995
|
+
],
|
|
241996
|
+
raw: result,
|
|
241997
|
+
}, "用户 OPA Rego 策略设置成功(旧网关鉴权已失效)");
|
|
241998
|
+
}
|
|
240626
241999
|
}
|
|
240627
242000
|
}));
|
|
240628
242001
|
}
|
|
@@ -241231,7 +242604,7 @@ function registerSetupTools(server) {
|
|
|
241231
242604
|
server.registerTool("downloadTemplate", {
|
|
241232
242605
|
title: "下载项目模板",
|
|
241233
242606
|
description: `自动下载并部署CloudBase项目模板。
|
|
241234
|
-
**Note**: Call this tool when the user requests to create a new project using a CloudBase template.\n\n支持的模板:\n- react: React + CloudBase 全栈应用模板\n- vue: Vue + CloudBase 全栈应用模板\n- miniprogram: 微信小程序 + 云开发模板 \n- uniapp: UniApp + CloudBase 跨端应用模板\n- rules: 只包含AI编辑器配置文件(包含Cursor、WindSurf、CodeBuddy等所有主流编辑器配置),适合在已有项目中补充AI编辑器配置\n\n支持的IDE类型:\n- all: 下载所有IDE配置\n- cursor: Cursor AI编辑器\n- 其他IDE类型见下方列表\n\n注意:如果未传入 ide 参数且无法从环境变量检测到 IDE,将提示错误并要求传入 ide 参数\n- windsurf: WindSurf AI编辑器\n- codebuddy: CodeBuddy AI编辑器\n- claude-code: Claude Code AI编辑器\n- cline: Cline AI编辑器\n- gemini-cli: Gemini CLI\n- opencode: OpenCode AI编辑器\n- qwen-code: 通义灵码\n- baidu-comate: 百度Comate\n- openai-codex-cli: OpenAI Codex CLI\n- augment-code: Augment Code\n- github-copilot: GitHub Copilot\n- roocode: RooCode AI编辑器\n- tongyi-lingma: 通义灵码\n- trae: Trae AI编辑器\n- qoder: Qoder AI编辑器\n- antigravity: Google Antigravity AI编辑器\n- vscode: Visual Studio Code\n- kiro: Kiro AI编辑器\n- aider: Aider AI编辑器\n\n特别说明:\n- rules 模板会自动包含当前 mcp 版本号信息(版本号:${ true ? "2.
|
|
242607
|
+
**Note**: Call this tool when the user requests to create a new project using a CloudBase template.\n\n支持的模板:\n- react: React + CloudBase 全栈应用模板\n- vue: Vue + CloudBase 全栈应用模板\n- miniprogram: 微信小程序 + 云开发模板 \n- uniapp: UniApp + CloudBase 跨端应用模板\n- rules: 只包含AI编辑器配置文件(包含Cursor、WindSurf、CodeBuddy等所有主流编辑器配置),适合在已有项目中补充AI编辑器配置\n\n支持的IDE类型:\n- all: 下载所有IDE配置\n- cursor: Cursor AI编辑器\n- 其他IDE类型见下方列表\n\n注意:如果未传入 ide 参数且无法从环境变量检测到 IDE,将提示错误并要求传入 ide 参数\n- windsurf: WindSurf AI编辑器\n- codebuddy: CodeBuddy AI编辑器\n- claude-code: Claude Code AI编辑器\n- cline: Cline AI编辑器\n- gemini-cli: Gemini CLI\n- opencode: OpenCode AI编辑器\n- qwen-code: 通义灵码\n- baidu-comate: 百度Comate\n- openai-codex-cli: OpenAI Codex CLI\n- augment-code: Augment Code\n- github-copilot: GitHub Copilot\n- roocode: RooCode AI编辑器\n- tongyi-lingma: 通义灵码\n- trae: Trae AI编辑器\n- qoder: Qoder AI编辑器\n- antigravity: Google Antigravity AI编辑器\n- vscode: Visual Studio Code\n- kiro: Kiro AI编辑器\n- aider: Aider AI编辑器\n\n特别说明:\n- rules 模板会自动包含当前 mcp 版本号信息(版本号:${ true ? "2.28.0" : 0}),便于后续维护和版本追踪\n- 下载 rules 模板时,如果项目中已存在 README.md 文件,系统会自动保护该文件不被覆盖(除非设置 overwrite=true)`,
|
|
241235
242608
|
inputSchema: {
|
|
241236
242609
|
template: zod_1.z
|
|
241237
242610
|
.enum(["react", "vue", "miniprogram", "uniapp", "rules"])
|
|
@@ -264455,7 +265828,10 @@ function registerGatewayTools(server) {
|
|
|
264455
265828
|
};
|
|
264456
265829
|
const pickUsableDefaultDomain = (domains) => {
|
|
264457
265830
|
const candidates = domains.filter((item) => item.IsDefault === true && item.Domain);
|
|
264458
|
-
return (candidates.find((item) => item.Enable !== false &&
|
|
265831
|
+
return (candidates.find((item) => item.Enable !== false &&
|
|
265832
|
+
// Platform may return Success/success; normalize before matching.
|
|
265833
|
+
typeof item.Status === "string" &&
|
|
265834
|
+
item.Status.toLowerCase() === "success") ??
|
|
264459
265835
|
candidates.find((item) => item.Enable !== false) ??
|
|
264460
265836
|
candidates[0]);
|
|
264461
265837
|
};
|