@cloudbase/cloudbase-mcp 2.26.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 +8 -1
- package/README.zh-CN.md +2 -1
- package/dist/341.index.js +6 -1
- package/dist/602.index.cjs +6 -1
- package/dist/cli.cjs +5 -5
- package/dist/index.cjs +2247 -610
- package/dist/index.d.ts +8 -1
- package/dist/index.js +2318 -665
- 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,
|
|
@@ -28452,6 +28844,7 @@ const manager_node_1 = __importDefault(__webpack_require__(95492));
|
|
|
28452
28844
|
const auth_js_1 = __webpack_require__(77291);
|
|
28453
28845
|
const logger_js_1 = __webpack_require__(13039);
|
|
28454
28846
|
const tool_result_js_1 = __webpack_require__(9835);
|
|
28847
|
+
const site_map_js_1 = __webpack_require__(68107);
|
|
28455
28848
|
// Timeout for envId auto-resolution flow.
|
|
28456
28849
|
// 10 minutes (600 seconds) - matches InteractiveServer timeout
|
|
28457
28850
|
const ENV_ID_TIMEOUT = 600000;
|
|
@@ -28476,7 +28869,7 @@ function createManagerFromLoginState(loginState, region) {
|
|
|
28476
28869
|
envId: loginState.envId,
|
|
28477
28870
|
token: loginState.token,
|
|
28478
28871
|
proxy: process.env.http_proxy,
|
|
28479
|
-
region: region ??
|
|
28872
|
+
region: region ?? (0, site_map_js_1.resolveSiteAndRegion)().region,
|
|
28480
28873
|
});
|
|
28481
28874
|
}
|
|
28482
28875
|
async function listAvailableEnvCandidates(options) {
|
|
@@ -28504,7 +28897,7 @@ async function listAvailableEnvCandidates(options) {
|
|
|
28504
28897
|
if (!loginState?.secretId || !loginState?.secretKey) {
|
|
28505
28898
|
return [];
|
|
28506
28899
|
}
|
|
28507
|
-
const region = cloudBaseOptions
|
|
28900
|
+
const region = (0, site_map_js_1.resolveSiteAndRegion)(cloudBaseOptions ?? {}).region;
|
|
28508
28901
|
cloudbase = createManagerFromLoginState(loginState, region);
|
|
28509
28902
|
}
|
|
28510
28903
|
try {
|
|
@@ -28705,7 +29098,10 @@ function getCachedEnvId() {
|
|
|
28705
29098
|
const databaseInstanceIdCache = new Map();
|
|
28706
29099
|
function buildDatabaseInstanceIdCacheKey(options) {
|
|
28707
29100
|
const envId = options?.envId ?? options?.cloudBaseOptions?.envId ?? process.env.CLOUDBASE_ENV_ID ?? 'unknown';
|
|
28708
|
-
const region =
|
|
29101
|
+
const region = (0, site_map_js_1.resolveSiteAndRegion)({
|
|
29102
|
+
site: options?.cloudBaseOptions?.site,
|
|
29103
|
+
region: options?.region ?? options?.cloudBaseOptions?.region,
|
|
29104
|
+
}).region;
|
|
28709
29105
|
return `${region}:${envId}`;
|
|
28710
29106
|
}
|
|
28711
29107
|
function resetDatabaseInstanceIdCache() {
|
|
@@ -28811,11 +29207,11 @@ async function getCloudBaseManager(options = {}) {
|
|
|
28811
29207
|
});
|
|
28812
29208
|
}
|
|
28813
29209
|
try {
|
|
28814
|
-
// Region priority: explicit option > env
|
|
28815
|
-
const fallbackRegion =
|
|
29210
|
+
// Region priority: explicit option > TCB_REGION/TCB_SITE env > .cloudbase/project.json > ap-shanghai default
|
|
29211
|
+
const { region: fallbackRegion, site } = (0, site_map_js_1.resolveSiteAndRegion)(cloudBaseOptions ?? {});
|
|
28816
29212
|
const loginState = authStrategy === 'ensure'
|
|
28817
|
-
? await (0, auth_js_1.getLoginState)({ region: fallbackRegion })
|
|
28818
|
-
: await (0, auth_js_1.peekLoginState)();
|
|
29213
|
+
? await (0, auth_js_1.getLoginState)({ region: fallbackRegion, site })
|
|
29214
|
+
: await (0, auth_js_1.peekLoginState)({ region: fallbackRegion, site });
|
|
28819
29215
|
if (!loginState) {
|
|
28820
29216
|
const authState = await (0, auth_js_1.getAuthProgressState)();
|
|
28821
29217
|
if (authState.status === 'PENDING') {
|
|
@@ -28863,7 +29259,7 @@ async function getCloudBaseManager(options = {}) {
|
|
|
28863
29259
|
}
|
|
28864
29260
|
// envId priority: explicit option > envManager cache > loginState.envId
|
|
28865
29261
|
const resolvedEnvId = finalEnvId || loginEnvId;
|
|
28866
|
-
// region 直接使用 fallbackRegion
|
|
29262
|
+
// region 直接使用 fallbackRegion(resolveSiteAndRegion 统一解析)
|
|
28867
29263
|
// 不再通过 DescribeEnvs 查询 region,以兼容 STS 临时密钥场景
|
|
28868
29264
|
const region = fallbackRegion;
|
|
28869
29265
|
const manager = new manager_node_1.default({
|
|
@@ -28895,8 +29291,8 @@ function createCloudBaseManagerWithOptions(cloudBaseOptions) {
|
|
|
28895
29291
|
hasSecretKey: !!cloudBaseOptions.secretKey,
|
|
28896
29292
|
hasToken: !!cloudBaseOptions.token,
|
|
28897
29293
|
});
|
|
28898
|
-
// Region priority: explicit option > env
|
|
28899
|
-
const region = cloudBaseOptions.region
|
|
29294
|
+
// Region priority: explicit option > TCB_REGION/TCB_SITE env > .cloudbase/project.json > ap-shanghai default
|
|
29295
|
+
const region = (0, site_map_js_1.resolveSiteAndRegion)(cloudBaseOptions).region;
|
|
28900
29296
|
const manager = new manager_node_1.default({
|
|
28901
29297
|
...cloudBaseOptions,
|
|
28902
29298
|
proxy: cloudBaseOptions.proxy || process.env.http_proxy,
|
|
@@ -41808,424 +42204,6 @@ function done(stream, er, data) {
|
|
|
41808
42204
|
})));
|
|
41809
42205
|
|
|
41810
42206
|
|
|
41811
|
-
/***/ }),
|
|
41812
|
-
|
|
41813
|
-
/***/ 9097:
|
|
41814
|
-
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
|
|
41815
|
-
|
|
41816
|
-
"use strict";
|
|
41817
|
-
|
|
41818
|
-
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
41819
|
-
if (k2 === undefined) k2 = k;
|
|
41820
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
41821
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
41822
|
-
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
41823
|
-
}
|
|
41824
|
-
Object.defineProperty(o, k2, desc);
|
|
41825
|
-
}) : (function(o, m, k, k2) {
|
|
41826
|
-
if (k2 === undefined) k2 = k;
|
|
41827
|
-
o[k2] = m[k];
|
|
41828
|
-
}));
|
|
41829
|
-
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
41830
|
-
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
41831
|
-
}) : function(o, v) {
|
|
41832
|
-
o["default"] = v;
|
|
41833
|
-
});
|
|
41834
|
-
var __importStar = (this && this.__importStar) || (function () {
|
|
41835
|
-
var ownKeys = function(o) {
|
|
41836
|
-
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
41837
|
-
var ar = [];
|
|
41838
|
-
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
41839
|
-
return ar;
|
|
41840
|
-
};
|
|
41841
|
-
return ownKeys(o);
|
|
41842
|
-
};
|
|
41843
|
-
return function (mod) {
|
|
41844
|
-
if (mod && mod.__esModule) return mod;
|
|
41845
|
-
var result = {};
|
|
41846
|
-
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
41847
|
-
__setModuleDefault(result, mod);
|
|
41848
|
-
return result;
|
|
41849
|
-
};
|
|
41850
|
-
})();
|
|
41851
|
-
Object.defineProperty(exports, "__esModule", ({ value: true }));
|
|
41852
|
-
exports.registerDownloadTools = registerDownloadTools;
|
|
41853
|
-
const crypto = __importStar(__webpack_require__(55511));
|
|
41854
|
-
const fs = __importStar(__webpack_require__(29021));
|
|
41855
|
-
const fsPromises = __importStar(__webpack_require__(79748));
|
|
41856
|
-
const http = __importStar(__webpack_require__(81630));
|
|
41857
|
-
const https = __importStar(__webpack_require__(55591));
|
|
41858
|
-
const os = __importStar(__webpack_require__(21820));
|
|
41859
|
-
const path = __importStar(__webpack_require__(33873));
|
|
41860
|
-
const url_1 = __webpack_require__(79551);
|
|
41861
|
-
const zod_1 = __webpack_require__(7552);
|
|
41862
|
-
const remote_url_safety_js_1 = __webpack_require__(89192);
|
|
41863
|
-
// 常量定义
|
|
41864
|
-
const MAX_FILE_SIZE = 100 * 1024 * 1024; // 100MB
|
|
41865
|
-
const MAX_REDIRECT_HOPS = 5;
|
|
41866
|
-
const ALLOWED_CONTENT_TYPES = [
|
|
41867
|
-
"text/",
|
|
41868
|
-
"image/",
|
|
41869
|
-
"application/json",
|
|
41870
|
-
"application/xml",
|
|
41871
|
-
"application/pdf",
|
|
41872
|
-
"application/zip",
|
|
41873
|
-
"application/x-zip-compressed"
|
|
41874
|
-
];
|
|
41875
|
-
// 获取项目根目录
|
|
41876
|
-
function getProjectRoot() {
|
|
41877
|
-
// 优先级:环境变量 > 当前工作目录
|
|
41878
|
-
return process.env.WORKSPACE_FOLDER_PATHS ||
|
|
41879
|
-
process.env.PROJECT_ROOT ||
|
|
41880
|
-
process.env.GITHUB_WORKSPACE ||
|
|
41881
|
-
process.env.CI_PROJECT_DIR ||
|
|
41882
|
-
process.env.BUILD_SOURCESDIRECTORY ||
|
|
41883
|
-
process.cwd();
|
|
41884
|
-
}
|
|
41885
|
-
// 验证相对路径是否安全(不允许路径遍历)
|
|
41886
|
-
function isPathSafe(relativePath) {
|
|
41887
|
-
// 检查是否包含路径遍历操作
|
|
41888
|
-
if (relativePath.includes('..') ||
|
|
41889
|
-
relativePath.includes('~') ||
|
|
41890
|
-
path.isAbsolute(relativePath)) {
|
|
41891
|
-
return false;
|
|
41892
|
-
}
|
|
41893
|
-
// 检查路径是否规范化后仍然安全
|
|
41894
|
-
const normalizedPath = path.normalize(relativePath);
|
|
41895
|
-
if (normalizedPath.startsWith('..') ||
|
|
41896
|
-
normalizedPath.startsWith('/') ||
|
|
41897
|
-
normalizedPath.startsWith('\\')) {
|
|
41898
|
-
return false;
|
|
41899
|
-
}
|
|
41900
|
-
return true;
|
|
41901
|
-
}
|
|
41902
|
-
// 计算最终下载路径
|
|
41903
|
-
function calculateDownloadPath(relativePath) {
|
|
41904
|
-
const projectRoot = getProjectRoot();
|
|
41905
|
-
const finalPath = path.join(projectRoot, relativePath);
|
|
41906
|
-
// 确保最终路径在项目根目录内
|
|
41907
|
-
const normalizedProjectRoot = path.resolve(projectRoot);
|
|
41908
|
-
const normalizedFinalPath = path.resolve(finalPath);
|
|
41909
|
-
if (!normalizedFinalPath.startsWith(normalizedProjectRoot)) {
|
|
41910
|
-
throw new Error('相对路径超出项目根目录范围');
|
|
41911
|
-
}
|
|
41912
|
-
return finalPath;
|
|
41913
|
-
}
|
|
41914
|
-
// 生成随机文件名
|
|
41915
|
-
function generateRandomFileName(extension = '') {
|
|
41916
|
-
const randomBytes = crypto.randomBytes(16);
|
|
41917
|
-
const fileName = randomBytes.toString('hex');
|
|
41918
|
-
return `${fileName}${extension}`;
|
|
41919
|
-
}
|
|
41920
|
-
// 获取安全的临时文件路径
|
|
41921
|
-
function getSafeTempFilePath(fileName) {
|
|
41922
|
-
return path.join(os.tmpdir(), fileName);
|
|
41923
|
-
}
|
|
41924
|
-
// 从 URL 或 Content-Disposition 获取文件扩展名
|
|
41925
|
-
function getFileExtension(url, contentType, contentDisposition) {
|
|
41926
|
-
let extension = "";
|
|
41927
|
-
// 从 URL 获取扩展名
|
|
41928
|
-
const urlPath = new url_1.URL(url).pathname;
|
|
41929
|
-
const urlExt = path.extname(urlPath);
|
|
41930
|
-
if (urlExt) {
|
|
41931
|
-
extension = urlExt;
|
|
41932
|
-
}
|
|
41933
|
-
// 从 Content-Disposition 获取扩展名
|
|
41934
|
-
if (contentDisposition) {
|
|
41935
|
-
const filenameMatch = contentDisposition.match(/filename=["']?([^"']+)["']?/);
|
|
41936
|
-
if (filenameMatch) {
|
|
41937
|
-
const dispositionExt = path.extname(filenameMatch[1]);
|
|
41938
|
-
if (dispositionExt) {
|
|
41939
|
-
extension = dispositionExt;
|
|
41940
|
-
}
|
|
41941
|
-
}
|
|
41942
|
-
}
|
|
41943
|
-
// 从 Content-Type 获取扩展名
|
|
41944
|
-
if (!extension && contentType) {
|
|
41945
|
-
const mimeToExt = {
|
|
41946
|
-
"text/plain": ".txt",
|
|
41947
|
-
"text/html": ".html",
|
|
41948
|
-
"text/css": ".css",
|
|
41949
|
-
"text/javascript": ".js",
|
|
41950
|
-
"image/jpeg": ".jpg",
|
|
41951
|
-
"image/png": ".png",
|
|
41952
|
-
"image/gif": ".gif",
|
|
41953
|
-
"image/webp": ".webp",
|
|
41954
|
-
"application/json": ".json",
|
|
41955
|
-
"application/xml": ".xml",
|
|
41956
|
-
"application/pdf": ".pdf",
|
|
41957
|
-
"application/zip": ".zip",
|
|
41958
|
-
"application/x-zip-compressed": ".zip"
|
|
41959
|
-
};
|
|
41960
|
-
extension = mimeToExt[contentType] || "";
|
|
41961
|
-
}
|
|
41962
|
-
return extension;
|
|
41963
|
-
}
|
|
41964
|
-
function isAllowedContentType(contentType) {
|
|
41965
|
-
return ALLOWED_CONTENT_TYPES.some((allowedType) => contentType.startsWith(allowedType));
|
|
41966
|
-
}
|
|
41967
|
-
// 检查是否为可重试的网络错误
|
|
41968
|
-
function isRetryableError(error) {
|
|
41969
|
-
const retryableCodes = [
|
|
41970
|
-
'ECONNRESET',
|
|
41971
|
-
'ECONNREFUSED',
|
|
41972
|
-
'ETIMEDOUT',
|
|
41973
|
-
'ESOCKETTIMEDOUT',
|
|
41974
|
-
'ENOTFOUND',
|
|
41975
|
-
'EHOSTUNREACH',
|
|
41976
|
-
'ENETUNREACH',
|
|
41977
|
-
'ECONNABORTED'
|
|
41978
|
-
];
|
|
41979
|
-
return retryableCodes.includes(error.code || '');
|
|
41980
|
-
}
|
|
41981
|
-
// 下载文件到指定路径(带重试逻辑)
|
|
41982
|
-
async function downloadFileToPath(url, targetPath, retryCount = 0, redirectCount = 0) {
|
|
41983
|
-
const MAX_RETRIES = 3;
|
|
41984
|
-
const BASE_DELAY_MS = 1000; // 1秒基础延迟
|
|
41985
|
-
if (redirectCount > MAX_REDIRECT_HOPS) {
|
|
41986
|
-
throw new Error(`重定向次数超过 ${MAX_REDIRECT_HOPS} 次限制`);
|
|
41987
|
-
}
|
|
41988
|
-
const { requestUrl, requestOptions } = await (0, remote_url_safety_js_1.prepareSafeRemoteRequest)(url);
|
|
41989
|
-
const client = requestUrl.protocol === "https:" ? https : http;
|
|
41990
|
-
return new Promise((resolve, reject) => {
|
|
41991
|
-
const request = client.get(requestUrl, requestOptions ?? {}, async (res) => {
|
|
41992
|
-
// 处理重定向
|
|
41993
|
-
if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
|
|
41994
|
-
try {
|
|
41995
|
-
const redirectUrl = new url_1.URL(res.headers.location, requestUrl).toString();
|
|
41996
|
-
return resolve(await downloadFileToPath(redirectUrl, targetPath, retryCount, redirectCount + 1));
|
|
41997
|
-
}
|
|
41998
|
-
catch (error) {
|
|
41999
|
-
return reject(error);
|
|
42000
|
-
}
|
|
42001
|
-
}
|
|
42002
|
-
if (res.statusCode !== 200) {
|
|
42003
|
-
reject(new Error(`HTTP Error: ${res.statusCode}`));
|
|
42004
|
-
return;
|
|
42005
|
-
}
|
|
42006
|
-
const contentType = res.headers["content-type"] || "";
|
|
42007
|
-
const contentLength = parseInt(res.headers["content-length"] || "0", 10);
|
|
42008
|
-
if (!isAllowedContentType(contentType)) {
|
|
42009
|
-
reject(new Error(`不允许的内容类型: ${contentType || "unknown"}`));
|
|
42010
|
-
return;
|
|
42011
|
-
}
|
|
42012
|
-
// 文件大小检查
|
|
42013
|
-
if (contentLength > MAX_FILE_SIZE) {
|
|
42014
|
-
reject(new Error(`文件大小 ${contentLength} 字节超过 ${MAX_FILE_SIZE} 字节限制`));
|
|
42015
|
-
return;
|
|
42016
|
-
}
|
|
42017
|
-
// 确保目标目录存在
|
|
42018
|
-
const targetDir = path.dirname(targetPath);
|
|
42019
|
-
try {
|
|
42020
|
-
await fsPromises.mkdir(targetDir, { recursive: true });
|
|
42021
|
-
}
|
|
42022
|
-
catch (error) {
|
|
42023
|
-
reject(new Error(`无法创建目标目录: ${error instanceof Error ? error.message : "未知错误"}`));
|
|
42024
|
-
return;
|
|
42025
|
-
}
|
|
42026
|
-
// 创建写入流
|
|
42027
|
-
const fileStream = fs.createWriteStream(targetPath);
|
|
42028
|
-
let downloadedSize = 0;
|
|
42029
|
-
res.on("data", (chunk) => {
|
|
42030
|
-
downloadedSize += chunk.length;
|
|
42031
|
-
if (downloadedSize > MAX_FILE_SIZE) {
|
|
42032
|
-
fileStream.destroy();
|
|
42033
|
-
fsPromises.unlink(targetPath).catch(() => { });
|
|
42034
|
-
reject(new Error(`文件大小超过 ${MAX_FILE_SIZE} 字节限制`));
|
|
42035
|
-
}
|
|
42036
|
-
});
|
|
42037
|
-
res.pipe(fileStream);
|
|
42038
|
-
fileStream.on("finish", () => {
|
|
42039
|
-
resolve({
|
|
42040
|
-
filePath: targetPath,
|
|
42041
|
-
contentType,
|
|
42042
|
-
fileSize: downloadedSize,
|
|
42043
|
-
});
|
|
42044
|
-
});
|
|
42045
|
-
fileStream.on("error", (error) => {
|
|
42046
|
-
fsPromises.unlink(targetPath).catch(() => { });
|
|
42047
|
-
reject(error);
|
|
42048
|
-
});
|
|
42049
|
-
});
|
|
42050
|
-
request.on("error", async (error) => {
|
|
42051
|
-
// 检查是否可重试
|
|
42052
|
-
if (isRetryableError(error) && retryCount < MAX_RETRIES) {
|
|
42053
|
-
const delay = BASE_DELAY_MS * Math.pow(2, retryCount); // 指数退避
|
|
42054
|
-
console.warn(`下载失败 (${error.code}),${delay}ms 后重试 (${retryCount + 1}/${MAX_RETRIES})...`);
|
|
42055
|
-
await new Promise((resolveDelay) => setTimeout(resolveDelay, delay));
|
|
42056
|
-
try {
|
|
42057
|
-
return resolve(await downloadFileToPath(url, targetPath, retryCount + 1, redirectCount));
|
|
42058
|
-
}
|
|
42059
|
-
catch (retryError) {
|
|
42060
|
-
return reject(retryError);
|
|
42061
|
-
}
|
|
42062
|
-
}
|
|
42063
|
-
reject(error);
|
|
42064
|
-
});
|
|
42065
|
-
});
|
|
42066
|
-
}
|
|
42067
|
-
// 下载文件到临时目录(保持向后兼容,带重试逻辑)
|
|
42068
|
-
async function downloadFile(url, retryCount = 0, redirectCount = 0) {
|
|
42069
|
-
const MAX_RETRIES = 3;
|
|
42070
|
-
const BASE_DELAY_MS = 1000; // 1秒基础延迟
|
|
42071
|
-
if (redirectCount > MAX_REDIRECT_HOPS) {
|
|
42072
|
-
throw new Error(`重定向次数超过 ${MAX_REDIRECT_HOPS} 次限制`);
|
|
42073
|
-
}
|
|
42074
|
-
const { requestUrl, requestOptions } = await (0, remote_url_safety_js_1.prepareSafeRemoteRequest)(url);
|
|
42075
|
-
const client = requestUrl.protocol === "https:" ? https : http;
|
|
42076
|
-
return new Promise((resolve, reject) => {
|
|
42077
|
-
const request = client.get(requestUrl, requestOptions ?? {}, async (res) => {
|
|
42078
|
-
// 处理重定向
|
|
42079
|
-
if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
|
|
42080
|
-
try {
|
|
42081
|
-
const redirectUrl = new url_1.URL(res.headers.location, requestUrl).toString();
|
|
42082
|
-
return resolve(await downloadFile(redirectUrl, retryCount, redirectCount + 1));
|
|
42083
|
-
}
|
|
42084
|
-
catch (error) {
|
|
42085
|
-
return reject(error);
|
|
42086
|
-
}
|
|
42087
|
-
}
|
|
42088
|
-
if (res.statusCode !== 200) {
|
|
42089
|
-
reject(new Error(`HTTP Error: ${res.statusCode}`));
|
|
42090
|
-
return;
|
|
42091
|
-
}
|
|
42092
|
-
const contentType = res.headers["content-type"] || "";
|
|
42093
|
-
const contentLength = parseInt(res.headers["content-length"] || "0", 10);
|
|
42094
|
-
const contentDisposition = res.headers["content-disposition"];
|
|
42095
|
-
if (!isAllowedContentType(contentType)) {
|
|
42096
|
-
reject(new Error(`不允许的内容类型: ${contentType || "unknown"}`));
|
|
42097
|
-
return;
|
|
42098
|
-
}
|
|
42099
|
-
// 文件大小检查
|
|
42100
|
-
if (contentLength > MAX_FILE_SIZE) {
|
|
42101
|
-
reject(new Error(`文件大小 ${contentLength} 字节超过 ${MAX_FILE_SIZE} 字节限制`));
|
|
42102
|
-
return;
|
|
42103
|
-
}
|
|
42104
|
-
// 生成临时文件路径
|
|
42105
|
-
const extension = getFileExtension(requestUrl.toString(), contentType, contentDisposition);
|
|
42106
|
-
const fileName = generateRandomFileName(extension);
|
|
42107
|
-
const filePath = getSafeTempFilePath(fileName);
|
|
42108
|
-
// 创建写入流
|
|
42109
|
-
const fileStream = fs.createWriteStream(filePath);
|
|
42110
|
-
let downloadedSize = 0;
|
|
42111
|
-
res.on("data", (chunk) => {
|
|
42112
|
-
downloadedSize += chunk.length;
|
|
42113
|
-
if (downloadedSize > MAX_FILE_SIZE) {
|
|
42114
|
-
fileStream.destroy();
|
|
42115
|
-
fsPromises.unlink(filePath).catch(() => { });
|
|
42116
|
-
reject(new Error(`文件大小超过 ${MAX_FILE_SIZE} 字节限制`));
|
|
42117
|
-
}
|
|
42118
|
-
});
|
|
42119
|
-
res.pipe(fileStream);
|
|
42120
|
-
fileStream.on("finish", () => {
|
|
42121
|
-
resolve({
|
|
42122
|
-
filePath,
|
|
42123
|
-
contentType,
|
|
42124
|
-
fileSize: downloadedSize,
|
|
42125
|
-
});
|
|
42126
|
-
});
|
|
42127
|
-
fileStream.on("error", (error) => {
|
|
42128
|
-
fsPromises.unlink(filePath).catch(() => { });
|
|
42129
|
-
reject(error);
|
|
42130
|
-
});
|
|
42131
|
-
});
|
|
42132
|
-
request.on("error", async (error) => {
|
|
42133
|
-
// 检查是否可重试
|
|
42134
|
-
if (isRetryableError(error) && retryCount < MAX_RETRIES) {
|
|
42135
|
-
const delay = BASE_DELAY_MS * Math.pow(2, retryCount); // 指数退避
|
|
42136
|
-
console.warn(`下载失败 (${error.code}),${delay}ms 后重试 (${retryCount + 1}/${MAX_RETRIES})...`);
|
|
42137
|
-
await new Promise((resolveDelay) => setTimeout(resolveDelay, delay));
|
|
42138
|
-
try {
|
|
42139
|
-
return resolve(await downloadFile(url, retryCount + 1, redirectCount));
|
|
42140
|
-
}
|
|
42141
|
-
catch (retryError) {
|
|
42142
|
-
return reject(retryError);
|
|
42143
|
-
}
|
|
42144
|
-
}
|
|
42145
|
-
reject(error);
|
|
42146
|
-
});
|
|
42147
|
-
});
|
|
42148
|
-
}
|
|
42149
|
-
function buildDownloadRemoteFileErrorMessage(url, error) {
|
|
42150
|
-
const baseMessage = error instanceof Error ? error.message : String(error);
|
|
42151
|
-
const suggestions = [];
|
|
42152
|
-
if (/HTTP Error:\s*404/i.test(baseMessage)) {
|
|
42153
|
-
suggestions.push("目标 URL 当前返回 404,说明资源链接已失效或路径不正确。");
|
|
42154
|
-
suggestions.push("请先在浏览器中确认该链接可访问,再重新执行下载。");
|
|
42155
|
-
}
|
|
42156
|
-
if (/ENOTFOUND|ECONNRESET|ETIMEDOUT|socket hang up/i.test(baseMessage)) {
|
|
42157
|
-
suggestions.push("下载过程中出现网络异常,系统已自动重试 3 次但均失败。");
|
|
42158
|
-
suggestions.push("建议:1) 检查本地网络或代理设置;2) 该网站可能限频,请尝试更换其他图片源(如 Unsplash、Pexels);3) 稍后重试。");
|
|
42159
|
-
}
|
|
42160
|
-
if (suggestions.length === 0) {
|
|
42161
|
-
suggestions.push("请检查 URL 是否可访问,以及目标资源是否允许直接下载。");
|
|
42162
|
-
}
|
|
42163
|
-
return `[downloadRemoteFile] ${baseMessage}\nURL: ${url}\n建议:${suggestions.join(" ")}`;
|
|
42164
|
-
}
|
|
42165
|
-
function registerDownloadTools(server) {
|
|
42166
|
-
server.registerTool("downloadRemoteFile", {
|
|
42167
|
-
title: "下载远程文件到指定路径",
|
|
42168
|
-
description: "下载远程文件到项目根目录下的指定相对路径。例如:小程序的 Tabbar 等素材图片,必须使用 **png** 格式,可以从 Unsplash、wikimedia【一般选用 500 大小即可、Pexels、Apple 官方 UI 等资源中选择来下载。",
|
|
42169
|
-
inputSchema: {
|
|
42170
|
-
url: zod_1.z.string().describe("远程文件的 URL 地址"),
|
|
42171
|
-
relativePath: zod_1.z.string().describe("相对于项目根目录的路径,例如:'assets/images/logo.png' 或 'docs/api.md'。不允许使用 ../ 等路径遍历操作。")
|
|
42172
|
-
},
|
|
42173
|
-
annotations: {
|
|
42174
|
-
readOnlyHint: false,
|
|
42175
|
-
destructiveHint: false,
|
|
42176
|
-
idempotentHint: false,
|
|
42177
|
-
openWorldHint: true,
|
|
42178
|
-
category: "download"
|
|
42179
|
-
}
|
|
42180
|
-
}, async ({ url, relativePath }) => {
|
|
42181
|
-
if (!isPathSafe(relativePath)) {
|
|
42182
|
-
return {
|
|
42183
|
-
content: [
|
|
42184
|
-
{
|
|
42185
|
-
type: "text",
|
|
42186
|
-
text: JSON.stringify({
|
|
42187
|
-
success: false,
|
|
42188
|
-
error: "不安全的相对路径",
|
|
42189
|
-
message: "相对路径包含路径遍历操作(../)或绝对路径,出于安全考虑已拒绝",
|
|
42190
|
-
suggestion: "请使用项目根目录下的相对路径,例如:'assets/images/logo.png'"
|
|
42191
|
-
}, null, 2)
|
|
42192
|
-
}
|
|
42193
|
-
]
|
|
42194
|
-
};
|
|
42195
|
-
}
|
|
42196
|
-
const targetPath = calculateDownloadPath(relativePath);
|
|
42197
|
-
const projectRoot = getProjectRoot();
|
|
42198
|
-
console.log(`📁 项目根目录: ${projectRoot}`);
|
|
42199
|
-
console.log(`📁 相对路径: ${relativePath}`);
|
|
42200
|
-
console.log(`📁 最终路径: ${targetPath}`);
|
|
42201
|
-
let result;
|
|
42202
|
-
try {
|
|
42203
|
-
result = await downloadFileToPath(url, targetPath);
|
|
42204
|
-
}
|
|
42205
|
-
catch (error) {
|
|
42206
|
-
throw new Error(buildDownloadRemoteFileErrorMessage(url, error));
|
|
42207
|
-
}
|
|
42208
|
-
return {
|
|
42209
|
-
content: [
|
|
42210
|
-
{
|
|
42211
|
-
type: "text",
|
|
42212
|
-
text: JSON.stringify({
|
|
42213
|
-
success: true,
|
|
42214
|
-
filePath: result.filePath,
|
|
42215
|
-
relativePath: relativePath,
|
|
42216
|
-
contentType: result.contentType,
|
|
42217
|
-
fileSize: result.fileSize,
|
|
42218
|
-
projectRoot: projectRoot,
|
|
42219
|
-
message: "文件下载成功到指定路径",
|
|
42220
|
-
note: `文件已保存到项目目录: ${relativePath}`
|
|
42221
|
-
}, null, 2)
|
|
42222
|
-
}
|
|
42223
|
-
]
|
|
42224
|
-
};
|
|
42225
|
-
});
|
|
42226
|
-
}
|
|
42227
|
-
|
|
42228
|
-
|
|
42229
42207
|
/***/ }),
|
|
42230
42208
|
|
|
42231
42209
|
/***/ 9141:
|
|
@@ -83681,27 +83659,6 @@ function done(stream, er, data) {
|
|
|
83681
83659
|
return stream.push(null);
|
|
83682
83660
|
}
|
|
83683
83661
|
|
|
83684
|
-
/***/ }),
|
|
83685
|
-
|
|
83686
|
-
/***/ 21454:
|
|
83687
|
-
/***/ ((__unused_webpack_module, exports) => {
|
|
83688
|
-
|
|
83689
|
-
"use strict";
|
|
83690
|
-
|
|
83691
|
-
Object.defineProperty(exports, "__esModule", ({ value: true }));
|
|
83692
|
-
exports.isInternationalRegion = void 0;
|
|
83693
|
-
exports.isValidRegion = isValidRegion;
|
|
83694
|
-
const REGION = {
|
|
83695
|
-
SHANGHAI: 'ap-shanghai',
|
|
83696
|
-
SINGAPORE: 'ap-singapore',
|
|
83697
|
-
};
|
|
83698
|
-
const isInternationalRegion = (region) => region === REGION.SINGAPORE;
|
|
83699
|
-
exports.isInternationalRegion = isInternationalRegion;
|
|
83700
|
-
function isValidRegion(region) {
|
|
83701
|
-
return Object.values(REGION).includes(region);
|
|
83702
|
-
}
|
|
83703
|
-
|
|
83704
|
-
|
|
83705
83662
|
/***/ }),
|
|
83706
83663
|
|
|
83707
83664
|
/***/ 21605:
|
|
@@ -91460,8 +91417,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
91460
91417
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
91461
91418
|
};
|
|
91462
91419
|
Object.defineProperty(exports, "__esModule", ({ value: true }));
|
|
91463
|
-
exports.CUSTOM_IMAGE_RUNTIME = exports.MANAGE_FUNCTION_ACTIONS = exports.QUERY_FUNCTION_ACTIONS = exports.TRIGGER_CONFIG_EXAMPLES = exports.SUPPORTED_TRIGGER_TYPES = exports.DEFAULT_NODEJS_RUNTIME = exports.SUPPORTED_NODEJS_RUNTIMES = exports.RECOMMENDED_RUNTIMES = exports.DEFAULT_RUNTIME = exports.ALL_SUPPORTED_RUNTIMES = exports.SUPPORTED_RUNTIMES = void 0;
|
|
91420
|
+
exports.CUSTOM_IMAGE_RUNTIME = exports.LAYER_SOFT_WARN = exports.MANAGE_FUNCTION_ACTIONS = exports.QUERY_FUNCTION_ACTIONS = exports.TRIGGER_CONFIG_EXAMPLES = exports.SUPPORTED_TRIGGER_TYPES = exports.DEFAULT_NODEJS_RUNTIME = exports.SUPPORTED_NODEJS_RUNTIMES = exports.RECOMMENDED_RUNTIMES = exports.DEFAULT_RUNTIME = exports.ALL_SUPPORTED_RUNTIMES = exports.SUPPORTED_RUNTIMES = void 0;
|
|
91464
91421
|
exports.formatRuntimeList = formatRuntimeList;
|
|
91422
|
+
exports.layerNameIncludesEnvId = layerNameIncludesEnvId;
|
|
91423
|
+
exports.buildCreateLayerNameWarning = buildCreateLayerNameWarning;
|
|
91465
91424
|
exports.validateTimerCron = validateTimerCron;
|
|
91466
91425
|
exports.pickManageFunctionName = pickManageFunctionName;
|
|
91467
91426
|
exports.shouldInstallDependencyForFunction = shouldInstallDependencyForFunction;
|
|
@@ -91566,6 +91525,24 @@ exports.MANAGE_FUNCTION_ACTIONS = [
|
|
|
91566
91525
|
"updateFunctionLayers",
|
|
91567
91526
|
"incrementalDeployFunction", // 增量部署,需通过 pluginOptions.functions 注入实现
|
|
91568
91527
|
];
|
|
91528
|
+
/** Layer soft-warn copy — account-scoped SCF LayerName guidance (no hard fail). */
|
|
91529
|
+
exports.LAYER_SOFT_WARN = {
|
|
91530
|
+
createNameFormat: (envId) => `建议使用 {layerName}_${envId} 格式,当前名称可能与其他环境共享版本序列`,
|
|
91531
|
+
deleteVersion: "该层为账号级共享资源,删除版本会影响所有绑定该版本的环境的函数,请确认",
|
|
91532
|
+
bindShared: "层为账号级共享,绑定/解绑影响所有引用该层名的环境",
|
|
91533
|
+
accountLevelView: "返回账号级视图,含其他环境创建的层",
|
|
91534
|
+
};
|
|
91535
|
+
function layerNameIncludesEnvId(layerName, envId) {
|
|
91536
|
+
if (!envId)
|
|
91537
|
+
return true;
|
|
91538
|
+
return layerName.includes(envId);
|
|
91539
|
+
}
|
|
91540
|
+
function buildCreateLayerNameWarning(layerName, envId) {
|
|
91541
|
+
if (!envId || layerNameIncludesEnvId(layerName, envId)) {
|
|
91542
|
+
return undefined;
|
|
91543
|
+
}
|
|
91544
|
+
return exports.LAYER_SOFT_WARN.createNameFormat(envId);
|
|
91545
|
+
}
|
|
91569
91546
|
const VPC_SCHEMA = zod_1.z.object({
|
|
91570
91547
|
vpcId: zod_1.z
|
|
91571
91548
|
.string()
|
|
@@ -91807,11 +91784,12 @@ function registerFunctionTools(server) {
|
|
|
91807
91784
|
const cloudBaseOptions = server.cloudBaseOptions;
|
|
91808
91785
|
const deployOverrides = server.pluginOptions?.functions;
|
|
91809
91786
|
const getManager = () => (0, cloudbase_manager_js_1.getCloudBaseManager)({ cloudBaseOptions });
|
|
91810
|
-
const buildEnvelope = (data, message, nextActions) => ({
|
|
91787
|
+
const buildEnvelope = (data, message, nextActions, warnings) => ({
|
|
91811
91788
|
success: true,
|
|
91812
91789
|
data,
|
|
91813
91790
|
message,
|
|
91814
91791
|
...(nextActions?.length ? { nextActions } : {}),
|
|
91792
|
+
...(warnings?.length ? { warnings } : {}),
|
|
91815
91793
|
});
|
|
91816
91794
|
const buildErrorEnvelope = (error, errorCode) => ({
|
|
91817
91795
|
success: false,
|
|
@@ -92062,7 +92040,7 @@ function registerFunctionTools(server) {
|
|
|
92062
92040
|
action: "createLayerVersion",
|
|
92063
92041
|
reason: "发布新的层版本",
|
|
92064
92042
|
},
|
|
92065
|
-
]);
|
|
92043
|
+
], [exports.LAYER_SOFT_WARN.accountLevelView]);
|
|
92066
92044
|
}
|
|
92067
92045
|
case "listLayerVersions": {
|
|
92068
92046
|
if (!input.layerName) {
|
|
@@ -92090,7 +92068,7 @@ function registerFunctionTools(server) {
|
|
|
92090
92068
|
action: "attachLayer",
|
|
92091
92069
|
reason: "将某个层版本绑定到函数",
|
|
92092
92070
|
},
|
|
92093
|
-
]);
|
|
92071
|
+
], [exports.LAYER_SOFT_WARN.accountLevelView]);
|
|
92094
92072
|
}
|
|
92095
92073
|
case "getLayerVersionDetail": {
|
|
92096
92074
|
if (!input.layerName) {
|
|
@@ -92123,7 +92101,7 @@ function registerFunctionTools(server) {
|
|
|
92123
92101
|
action: "deleteLayerVersion",
|
|
92124
92102
|
reason: "删除该层版本",
|
|
92125
92103
|
},
|
|
92126
|
-
]);
|
|
92104
|
+
], [exports.LAYER_SOFT_WARN.accountLevelView]);
|
|
92127
92105
|
}
|
|
92128
92106
|
case "listFunctionTriggers": {
|
|
92129
92107
|
if (!input.functionName) {
|
|
@@ -92639,6 +92617,8 @@ function registerFunctionTools(server) {
|
|
|
92639
92617
|
if (!input.contentPath && !input.base64Content) {
|
|
92640
92618
|
throw new Error("createLayerVersion 操作时,contentPath 和 base64Content 至少需要提供一个");
|
|
92641
92619
|
}
|
|
92620
|
+
const envId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
|
|
92621
|
+
const nameWarning = buildCreateLayerNameWarning(input.layerName, envId);
|
|
92642
92622
|
const cloudbase = await getManager();
|
|
92643
92623
|
const result = await cloudbase.functions.createLayer({
|
|
92644
92624
|
name: input.layerName,
|
|
@@ -92661,7 +92641,7 @@ function registerFunctionTools(server) {
|
|
|
92661
92641
|
action: "listLayerVersions",
|
|
92662
92642
|
reason: "查看该层的全部版本",
|
|
92663
92643
|
},
|
|
92664
|
-
]);
|
|
92644
|
+
], nameWarning ? [nameWarning] : undefined);
|
|
92665
92645
|
}
|
|
92666
92646
|
case "deleteLayerVersion": {
|
|
92667
92647
|
if (!input.layerName) {
|
|
@@ -92688,7 +92668,7 @@ function registerFunctionTools(server) {
|
|
|
92688
92668
|
action: "listLayerVersions",
|
|
92689
92669
|
reason: "确认剩余层版本",
|
|
92690
92670
|
},
|
|
92691
|
-
]);
|
|
92671
|
+
], [exports.LAYER_SOFT_WARN.deleteVersion]);
|
|
92692
92672
|
}
|
|
92693
92673
|
case "attachLayer":
|
|
92694
92674
|
case "detachLayer":
|
|
@@ -92698,6 +92678,7 @@ function registerFunctionTools(server) {
|
|
|
92698
92678
|
}
|
|
92699
92679
|
const cloudbase = await getManager();
|
|
92700
92680
|
const envId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
|
|
92681
|
+
const bindWarnings = [exports.LAYER_SOFT_WARN.bindShared];
|
|
92701
92682
|
if (input.action === "attachLayer") {
|
|
92702
92683
|
if (!input.layerName) {
|
|
92703
92684
|
throw new Error("attachLayer 操作时,layerName 参数是必需的");
|
|
@@ -92726,7 +92707,7 @@ function registerFunctionTools(server) {
|
|
|
92726
92707
|
action: "listFunctionLayers",
|
|
92727
92708
|
reason: "确认函数当前绑定层列表",
|
|
92728
92709
|
},
|
|
92729
|
-
]);
|
|
92710
|
+
], bindWarnings);
|
|
92730
92711
|
}
|
|
92731
92712
|
if (input.action === "detachLayer") {
|
|
92732
92713
|
if (!input.layerName) {
|
|
@@ -92757,7 +92738,7 @@ function registerFunctionTools(server) {
|
|
|
92757
92738
|
action: "listFunctionLayers",
|
|
92758
92739
|
reason: "确认解绑后的层列表",
|
|
92759
92740
|
},
|
|
92760
|
-
]);
|
|
92741
|
+
], bindWarnings);
|
|
92761
92742
|
}
|
|
92762
92743
|
const normalizedLayers = normalizeManageLayers(input.layers);
|
|
92763
92744
|
if (!normalizedLayers.length) {
|
|
@@ -92782,7 +92763,7 @@ function registerFunctionTools(server) {
|
|
|
92782
92763
|
action: "listFunctionLayers",
|
|
92783
92764
|
reason: "确认最新层顺序和绑定结果",
|
|
92784
92765
|
},
|
|
92785
|
-
]);
|
|
92766
|
+
], bindWarnings);
|
|
92786
92767
|
}
|
|
92787
92768
|
default:
|
|
92788
92769
|
// incrementalDeployFunction:无默认实现,必须通过 pluginOptions 注入
|
|
@@ -92812,6 +92793,10 @@ function registerFunctionTools(server) {
|
|
|
92812
92793
|
"\n- 示例:`queryFunctions(action=\"listFunctionLogs\", functionName=\"my-function\")`" +
|
|
92813
92794
|
"\n- 如需查看日志详情:`queryFunctions(action=\"getFunctionLogDetail\", requestId=\"xxx\")`" +
|
|
92814
92795
|
"\n\n**定时任务 / cron / 定时跑**:使用 `listFunctionTriggers` 查询函数的 timer 触发器配置。" +
|
|
92796
|
+
"\n\n**层(Layer)说明**:" +
|
|
92797
|
+
"\n- 层为 SCF 账号级共享命名空间:不同环境创建同名层会共享同一层的版本序列;删除某版本会影响所有绑定该版本的环境的函数" +
|
|
92798
|
+
"\n- 创建层必须用带环境标识的唯一层名,固定格式:`{layerName}_{当前envId}`(如 `common_cloud1-d9ghadgak3edf6b36`)。不要在不同环境使用相同裸层名,创建前先 `listLayers` 查重" +
|
|
92799
|
+
"\n- `listLayers` / `listLayerVersions` / `getLayerVersionDetail` 返回账号级视图,可能含其他环境创建的层" +
|
|
92815
92800
|
"\n\n**区分 `queryLogs` 工具**:" +
|
|
92816
92801
|
"\n- 本工具用于查询特定 CloudBase 云函数的执行日志" +
|
|
92817
92802
|
"\n- `queryLogs` 工具用于搜索 CLS 日志服务(跨服务日志聚合)",
|
|
@@ -92824,9 +92809,9 @@ function registerFunctionTools(server) {
|
|
|
92824
92809
|
"\n- `listFunctionLogs`: 查询 CloudBase 云函数执行日志(需要 functionName)" +
|
|
92825
92810
|
"\n- `getFunctionLogDetail`: 获取日志详情(需要 requestId)" +
|
|
92826
92811
|
"\n- `listFunctionLayers`: 列出函数绑定的层" +
|
|
92827
|
-
"\n- `listLayers`:
|
|
92828
|
-
"\n- `listLayerVersions`: 列出层的版本(注意:是 Versions 不是 Version
|
|
92829
|
-
"\n- `getLayerVersionDetail`:
|
|
92812
|
+
"\n- `listLayers`: 列出所有层(账号级视图,含其他环境创建的层)" +
|
|
92813
|
+
"\n- `listLayerVersions`: 列出层的版本(注意:是 Versions 不是 Version;账号级视图)" +
|
|
92814
|
+
"\n- `getLayerVersionDetail`: 获取层版本详情(账号级视图)" +
|
|
92830
92815
|
"\n- `listFunctionTriggers`: 列出函数触发器(用于查看定时任务 / cron / timer 配置)" +
|
|
92831
92816
|
"\n- `getFunctionDownloadUrl`: 获取函数代码下载地址"),
|
|
92832
92817
|
functionName: zod_1.z
|
|
@@ -92853,7 +92838,11 @@ function registerFunctionTools(server) {
|
|
|
92853
92838
|
qualifier: zod_1.z.string().optional().describe("函数版本别名,如 $LATEST、$DEFAULT。日志查询时可选"),
|
|
92854
92839
|
runtime: zod_1.z.string().optional().describe("层查询的运行时筛选,如 Nodejs18.15"),
|
|
92855
92840
|
searchKey: zod_1.z.string().optional().describe("层名称搜索关键字"),
|
|
92856
|
-
layerName: zod_1.z
|
|
92841
|
+
layerName: zod_1.z
|
|
92842
|
+
.string()
|
|
92843
|
+
.optional()
|
|
92844
|
+
.describe("层名称。`listLayerVersions`、`getLayerVersionDetail` 操作必填。" +
|
|
92845
|
+
"层为账号级共享命名空间;推荐固定格式 `{layerName}_{当前envId}`(如 common_cloud1-d9ghadgak3edf6b36)"),
|
|
92857
92846
|
layerVersion: zod_1.z.number().optional().describe("层版本号。`getLayerVersionDetail` 操作必填"),
|
|
92858
92847
|
},
|
|
92859
92848
|
annotations: {
|
|
@@ -92868,12 +92857,18 @@ function registerFunctionTools(server) {
|
|
|
92868
92857
|
"如果要创建 cron 定时任务,先用 createFunction 创建函数,再用 createFunctionTrigger 创建 timer 触发器(支持7段cron表达式),deleteFunctionTrigger 删除触发器。" +
|
|
92869
92858
|
"镜像部署(Runtime=CustomImage):先把代码经 zip→COS→CloudApp custom 构建→TCR 推镜像(这一阶段为裸腾讯云 API,本工具不覆盖)," +
|
|
92870
92859
|
"再用 createFunction(func.runtime=\"CustomImage\", imageConfig) 基于 TCR 镜像创建 HTTP 函数;后续迭代用 updateFunctionCode + imageConfig 换镜像 tag。" +
|
|
92871
|
-
"危险操作需要显式 confirm=true。"
|
|
92860
|
+
"危险操作需要显式 confirm=true。" +
|
|
92861
|
+
"\n\n**层(Layer)说明**:" +
|
|
92862
|
+
"\n- 层为 SCF 账号级共享命名空间:不同环境创建同名层会共享同一层的版本序列;删除某版本会影响所有绑定该版本的环境的函数" +
|
|
92863
|
+
"\n- 创建层必须用带环境标识的唯一层名,固定格式:`{layerName}_{当前envId}`(如 `common_cloud1-d9ghadgak3edf6b36`)。不要在不同环境使用相同裸层名,创建前先 `listLayers` 查重" +
|
|
92864
|
+
"\n- 相关 action:`createLayerVersion` / `deleteLayerVersion` / `attachLayer` / `detachLayer` / `updateFunctionLayers`(只读查询见 queryFunctions 的 listLayers / listLayerVersions / getLayerVersionDetail)",
|
|
92872
92865
|
inputSchema: {
|
|
92873
92866
|
action: zod_1.z
|
|
92874
92867
|
.enum(exports.MANAGE_FUNCTION_ACTIONS)
|
|
92875
92868
|
.describe("写操作类型,例如 createFunction、updateFunctionCode、incrementalDeployFunction、invokeFunction、deleteFunction、" +
|
|
92876
|
-
"createFunctionTrigger(定时任务 / cron / timer)、deleteFunctionTrigger、
|
|
92869
|
+
"createFunctionTrigger(定时任务 / cron / timer)、deleteFunctionTrigger、" +
|
|
92870
|
+
"createLayerVersion、deleteLayerVersion、attachLayer、detachLayer、updateFunctionLayers。" +
|
|
92871
|
+
"层名推荐固定格式 `{layerName}_{当前envId}`(如 common_cloud1-d9ghadgak3edf6b36)"),
|
|
92877
92872
|
func: CREATE_FUNCTION_SCHEMA.optional().describe("createFunction 操作的函数配置"),
|
|
92878
92873
|
functionRootPath: zod_1.z.string().optional().describe("创建或更新函数代码时默认推荐的本地目录方式。" +
|
|
92879
92874
|
"必须是直接包含函数文件夹的目录绝对路径(如 /abs/path/cloudfunctions 或 /abs/path/functions)," +
|
|
@@ -92903,7 +92898,11 @@ function registerFunctionTools(server) {
|
|
|
92903
92898
|
.describe("createFunctionTrigger 的触发器列表,用于定时跑 / 定时任务 / scheduled job。timer 触发器使用7段 cron 表达式(秒 分 时 日 月 星期 年)," +
|
|
92904
92899
|
'如 "0 */5 * * * * *" 表示每5分钟执行一次'),
|
|
92905
92900
|
triggerName: zod_1.z.string().optional().describe("deleteFunctionTrigger 的目标触发器名称"),
|
|
92906
|
-
layerName: zod_1.z
|
|
92901
|
+
layerName: zod_1.z
|
|
92902
|
+
.string()
|
|
92903
|
+
.optional()
|
|
92904
|
+
.describe("层名称。创建层推荐固定格式 `{layerName}_{当前envId}`(如 common_cloud1-d9ghadgak3edf6b36);" +
|
|
92905
|
+
"不要跨环境复用裸层名。层为账号级共享命名空间"),
|
|
92907
92906
|
layerVersion: zod_1.z.number().optional().describe("层版本号"),
|
|
92908
92907
|
contentPath: zod_1.z.string().optional().describe("层内容路径,可为目录或 ZIP 文件"),
|
|
92909
92908
|
base64Content: zod_1.z.string().optional().describe("层内容的 base64 编码"),
|
|
@@ -105446,7 +105445,6 @@ const mcp_js_1 = __webpack_require__(7011);
|
|
|
105446
105445
|
const databaseNoSQL_js_1 = __webpack_require__(73903);
|
|
105447
105446
|
const databasePG_js_1 = __webpack_require__(56473);
|
|
105448
105447
|
const databaseSQL_js_1 = __webpack_require__(9782);
|
|
105449
|
-
const download_js_1 = __webpack_require__(9097);
|
|
105450
105448
|
const env_js_1 = __webpack_require__(622);
|
|
105451
105449
|
const functions_js_1 = __webpack_require__(25936);
|
|
105452
105450
|
const hosting_js_1 = __webpack_require__(37279);
|
|
@@ -105467,7 +105465,7 @@ const logs_js_1 = __webpack_require__(92322);
|
|
|
105467
105465
|
const permissions_js_1 = __webpack_require__(76485);
|
|
105468
105466
|
const cloud_mode_js_1 = __webpack_require__(89684);
|
|
105469
105467
|
const logger_js_1 = __webpack_require__(13039);
|
|
105470
|
-
const
|
|
105468
|
+
const site_map_js_1 = __webpack_require__(68107);
|
|
105471
105469
|
const tool_result_js_1 = __webpack_require__(9835);
|
|
105472
105470
|
const tool_wrapper_js_1 = __webpack_require__(71363);
|
|
105473
105471
|
// 默认插件列表
|
|
@@ -105489,13 +105487,15 @@ const DEFAULT_PLUGINS = [
|
|
|
105489
105487
|
"permissions",
|
|
105490
105488
|
"logs",
|
|
105491
105489
|
"agents",
|
|
105492
|
-
"download",
|
|
105493
105490
|
"capi",
|
|
105494
105491
|
];
|
|
105495
105492
|
function registerDatabase(server) {
|
|
105496
|
-
//
|
|
105497
|
-
const
|
|
105498
|
-
|
|
105493
|
+
// NoSQL 数据库按站点能力集合注册(国际站默认不支持 NoSQL)
|
|
105494
|
+
const { site } = (0, site_map_js_1.resolveSiteAndRegion)({
|
|
105495
|
+
site: server.cloudBaseOptions?.site,
|
|
105496
|
+
region: server.cloudBaseOptions?.region,
|
|
105497
|
+
});
|
|
105498
|
+
if (site_map_js_1.SITE_REGION_MAP[site].capabilities.noSql) {
|
|
105499
105499
|
(0, databaseNoSQL_js_1.registerDatabaseTools)(server);
|
|
105500
105500
|
}
|
|
105501
105501
|
(0, dataModel_js_1.registerDataModelTools)(server);
|
|
@@ -105504,8 +105504,11 @@ function registerMysqlDatabase(server) {
|
|
|
105504
105504
|
(0, databaseSQL_js_1.registerSQLDatabaseTools)(server);
|
|
105505
105505
|
}
|
|
105506
105506
|
function registerNoSQLDatabase(server) {
|
|
105507
|
-
const
|
|
105508
|
-
|
|
105507
|
+
const { site } = (0, site_map_js_1.resolveSiteAndRegion)({
|
|
105508
|
+
site: server.cloudBaseOptions?.site,
|
|
105509
|
+
region: server.cloudBaseOptions?.region,
|
|
105510
|
+
});
|
|
105511
|
+
if (site_map_js_1.SITE_REGION_MAP[site].capabilities.noSql) {
|
|
105509
105512
|
(0, databaseNoSQL_js_1.registerDatabaseTools)(server);
|
|
105510
105513
|
}
|
|
105511
105514
|
}
|
|
@@ -105524,7 +105527,6 @@ const AVAILABLE_PLUGINS = {
|
|
|
105524
105527
|
storage: { name: "storage", register: storage_js_1.registerStorageTools },
|
|
105525
105528
|
setup: { name: "setup", register: setup_js_1.registerSetupTools },
|
|
105526
105529
|
rag: { name: "rag", register: rag_js_1.registerRagTools },
|
|
105527
|
-
download: { name: "download", register: download_js_1.registerDownloadTools },
|
|
105528
105530
|
gateway: { name: "gateway", register: gateway_js_1.registerGatewayTools },
|
|
105529
105531
|
"app-auth": { name: "app-auth", register: app_auth_js_1.registerAppAuthTools },
|
|
105530
105532
|
permissions: { name: "permissions", register: permissions_js_1.registerPermissionTools },
|
|
@@ -116964,8 +116966,21 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
116964
116966
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
116965
116967
|
};
|
|
116966
116968
|
Object.defineProperty(exports, "__esModule", ({ value: true }));
|
|
116967
|
-
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;
|
|
116976
|
+
exports.queryCloudRunEnvStatus = queryCloudRunEnvStatus;
|
|
116977
|
+
exports.describeCloudRunEnvStatus = describeCloudRunEnvStatus;
|
|
116978
|
+
exports.extractEnvBaseInfoVpc = extractEnvBaseInfoVpc;
|
|
116979
|
+
exports.resolveCloudRunDeployVpcInfo = resolveCloudRunDeployVpcInfo;
|
|
116980
|
+
exports.buildCreateCloudRunEnvParam = buildCreateCloudRunEnvParam;
|
|
116981
|
+
exports.ensureCloudRunEnvInitialized = ensureCloudRunEnvInitialized;
|
|
116968
116982
|
exports.detectCloudRunDbNetworkRisk = detectCloudRunDbNetworkRisk;
|
|
116983
|
+
exports.extractCloudRunImageInfo = extractCloudRunImageInfo;
|
|
116969
116984
|
exports.registerCloudRunTools = registerCloudRunTools;
|
|
116970
116985
|
const child_process_1 = __webpack_require__(79646);
|
|
116971
116986
|
const fs_1 = __importDefault(__webpack_require__(29021));
|
|
@@ -116975,29 +116990,44 @@ const cloudbase_manager_js_1 = __webpack_require__(3431);
|
|
|
116975
116990
|
const logger_js_1 = __webpack_require__(13039);
|
|
116976
116991
|
const gateway_access_urls_js_1 = __webpack_require__(22435);
|
|
116977
116992
|
const notification_js_1 = __webpack_require__(32720);
|
|
116993
|
+
const capi_js_1 = __webpack_require__(40738);
|
|
116978
116994
|
const cloudrun_config_js_1 = __webpack_require__(48266);
|
|
116979
116995
|
// CloudRun service types
|
|
116980
116996
|
exports.CLOUDRUN_SERVICE_TYPES = ['function', 'container'];
|
|
116981
116997
|
// CloudRun access types
|
|
116982
116998
|
exports.CLOUDRUN_ACCESS_TYPES = ['OA', 'PUBLIC', 'MINIAPP', 'VPC'];
|
|
116999
|
+
// CloudRun env package types (CreateCloudRunEnv.PackageType)
|
|
117000
|
+
exports.CLOUDRUN_PACKAGE_TYPES = ['Trial', 'Standard', 'Professional', 'Enterprise'];
|
|
116983
117001
|
// Input schema for queryCloudRun tool
|
|
116984
117002
|
const queryCloudRunInputSchema = {
|
|
116985
|
-
action: zod_1.z.enum(['list', 'detail', 'templates', 'getDeployLog']).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之前确认环境是否就绪'),
|
|
116986
117004
|
// List operation parameters
|
|
116987
117005
|
pageSize: zod_1.z.number().min(1).max(100).optional().default(10).describe('分页大小,控制每页返回的服务数量。取值范围:1-100,默认值:10。建议根据网络性能和显示需求调整'),
|
|
116988
117006
|
pageNum: zod_1.z.number().min(1).optional().default(1).describe('页码,用于分页查询。从1开始,默认值:1。配合pageSize使用可实现分页浏览'),
|
|
116989
117007
|
serverName: zod_1.z.string().optional().describe('服务名称筛选条件,支持模糊匹配。例如:输入"test"可匹配"test-service"、"my-test-app"等服务名称。留空则查询所有服务'),
|
|
116990
117008
|
serverType: zod_1.z.enum(exports.CLOUDRUN_SERVICE_TYPES).optional().describe('服务类型筛选条件:function=函数型云托管(仅支持Node.js,有特殊的开发要求和限制,适合简单的API服务),container=容器型服务(推荐使用,支持任意语言和框架如Java/Go/Python/PHP/.NET等,适合大多数应用场景)'),
|
|
117009
|
+
envId: zod_1.z.string().optional().describe('环境 ID(action=envStatus 时使用;不传则使用当前配置的环境)。格式如 env-xxxxxx'),
|
|
116991
117010
|
// Detail and log operation parameters
|
|
116992
|
-
detailServerName: zod_1.z.string().optional().describe('
|
|
116993
|
-
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 同源)。镜像部署与源码构建均可查询运行日志'),
|
|
116994
117014
|
};
|
|
116995
117015
|
// Input schema for manageCloudRun tool
|
|
116996
117016
|
const ManageCloudRunInputSchema = {
|
|
116997
|
-
action: zod_1.z.enum(['init', 'download', 'run', 'deploy', 'delete', 'createAgent', 'updateConfig']).describe('云托管服务管理操作类型:init=从模板初始化新的云托管项目代码(在targetPath目录下创建以serverName命名的子目录,支持多种语言和框架模板),download=从云端下载现有服务的代码到本地进行开发,run=在本地运行函数型云托管服务(用于开发和调试,仅支持函数型服务),deploy
|
|
116998
|
-
serverName: zod_1.z.string().describe('云托管服务名称,用于标识和管理服务。命名规则:支持大小写字母、数字、连字符和下划线,必须以字母开头,长度3-45个字符。在init操作中会作为在targetPath
|
|
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 命令)'),
|
|
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'),
|
|
117023
|
+
// InitEnv operation parameters
|
|
117024
|
+
envId: zod_1.z.string().optional().describe('环境 ID(action=initEnv 时使用;不传则使用当前配置的环境)。格式如 env-xxxxxx'),
|
|
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'),
|
|
116999
117028
|
// Deploy operation parameters
|
|
117000
|
-
targetPath: zod_1.z.string().optional().describe('本地代码路径,必须是绝对路径。在deploy操作中指定要部署的代码目录,在download操作中指定下载目标目录,在init操作中指定云托管服务的上级目录(会在该目录下创建以serverName命名的子目录)。updateConfig 不需要此参数。建议约定:项目根目录下的cloudrun/目录,例如:/Users/username/projects/my-project/cloudrun'),
|
|
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 后再部署)'),
|
|
117001
117031
|
envParamsReplaceAll: zod_1.z.boolean().optional().default(false).describe('EnvParams 合并策略(deploy / updateConfig):false(默认)= 与远程按 key 合并(输入覆盖同名 key,远程其余 key 保留);true= 用输入 EnvParams 整包替换远程。仅当显式传入 EnvParams 时生效'),
|
|
117002
117032
|
serverConfig: zod_1.z.object({
|
|
117003
117033
|
OpenAccessTypes: zod_1.z.array(zod_1.z.enum(exports.CLOUDRUN_ACCESS_TYPES)).optional().describe('公网访问类型配置,控制服务的访问权限:OA=办公网访问,PUBLIC=公网访问(默认,可通过HTTPS域名访问),MINIAPP=小程序访问,VPC=VPC访问(仅同VPC内可访问)。可配置多个类型'),
|
|
@@ -117018,7 +117048,7 @@ const ManageCloudRunInputSchema = {
|
|
|
117018
117048
|
InternalDomain: zod_1.z.string().optional().describe('内网域名配置,用于配置服务的内网访问域名。仅在启用内网访问时有效'),
|
|
117019
117049
|
EntryPoint: zod_1.z.array(zod_1.z.string()).optional().describe('Dockerfile EntryPoint参数配置,仅容器型服务需要。指定容器启动时的入口程序数组,如["node","app.js"]'),
|
|
117020
117050
|
Cmd: zod_1.z.array(zod_1.z.string()).optional().describe('Dockerfile Cmd参数配置,仅容器型服务需要。指定容器启动时的默认命令数组,如["npm","start"]'),
|
|
117021
|
-
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'),
|
|
117022
117052
|
LogType: zod_1.z.string().optional().describe('日志类型配置,指定服务的日志收集类型。影响日志的采集方式和存储格式'),
|
|
117023
117053
|
LogSetId: zod_1.z.string().optional().describe('CLS日志集ID配置,指定日志服务(CLS)的日志集ID。需要先开通CLS日志服务'),
|
|
117024
117054
|
LogTopicId: zod_1.z.string().optional().describe('CLS日志主题ID配置,指定日志服务(CLS)的日志主题ID。需要先开通CLS日志服务'),
|
|
@@ -117132,17 +117162,381 @@ function validateAndNormalizePath(inputPath) {
|
|
|
117132
117162
|
function buildManageCloudRunErrorMessage(action, serverName, error) {
|
|
117133
117163
|
const baseMessage = error instanceof Error ? error.message : String(error);
|
|
117134
117164
|
const suggestions = [];
|
|
117165
|
+
if ((0, capi_js_1.isCamAuthError)(baseMessage)) {
|
|
117166
|
+
suggestions.push((0, capi_js_1.buildCamAuthGuidance)());
|
|
117167
|
+
}
|
|
117135
117168
|
if (/已有部署发布任务运行中|部署发布任务运行中/i.test(baseMessage)) {
|
|
117136
117169
|
suggestions.push(`服务 \`${serverName}\` 当前已有部署任务在执行,请等待现有任务完成后再重试。`);
|
|
117137
117170
|
suggestions.push("如果你确认要覆盖当前流程,可在合适时机使用 `force=true` 再次发起。");
|
|
117138
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
|
+
}
|
|
117139
117177
|
if (suggestions.length === 0) {
|
|
117140
117178
|
suggestions.push("请检查服务状态、部署参数和目标目录后重试。");
|
|
117141
117179
|
}
|
|
117142
117180
|
return `[manageCloudRun/${action}] ${baseMessage}\n建议:${suggestions.join(" ")}`;
|
|
117143
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
|
+
}
|
|
117144
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;
|
|
117145
117388
|
const CLOUDRUN_DB_URL_PATTERN = /(mysql|mariadb|postgres|postgresql|mongodb(\+srv)?|redis|rediss):\/\//i;
|
|
117389
|
+
async function queryCloudRunEnvStatus(options) {
|
|
117390
|
+
const manager = await (0, cloudbase_manager_js_1.getCloudBaseManager)({ cloudBaseOptions: options.cloudBaseOptions });
|
|
117391
|
+
if (!manager?.commonService) {
|
|
117392
|
+
throw new Error("Current CloudBase Manager does not support commonService; cannot query CloudRun env status.");
|
|
117393
|
+
}
|
|
117394
|
+
return describeCloudRunEnvStatus(manager, options.envId);
|
|
117395
|
+
}
|
|
117396
|
+
/**
|
|
117397
|
+
* 核心实现:用已获取的 manager 查询云托管开通状态(供 initEnv/envStatus 及
|
|
117398
|
+
* ensureCloudRunEnvInitialized 复用,避免重复 getCloudBaseManager)。
|
|
117399
|
+
*/
|
|
117400
|
+
async function describeCloudRunEnvStatus(manager, envId) {
|
|
117401
|
+
const result = await manager
|
|
117402
|
+
.commonService("tcbr", "2022-02-17")
|
|
117403
|
+
.call({
|
|
117404
|
+
Action: "DescribeEnvBaseInfo",
|
|
117405
|
+
Param: { EnvId: envId },
|
|
117406
|
+
});
|
|
117407
|
+
const data = (result ?? {});
|
|
117408
|
+
const baseInfo = (data.EnvBaseInfo ?? {}) ?? {};
|
|
117409
|
+
if (data.IsExist !== true) {
|
|
117410
|
+
return { isExist: false, status: "unopened", baseInfo };
|
|
117411
|
+
}
|
|
117412
|
+
const rawStatus = typeof baseInfo.Status === "string" ? baseInfo.Status : "";
|
|
117413
|
+
// Platform may return NORMAL/CREATING (uppercase); normalize before matching.
|
|
117414
|
+
const normalizedStatus = rawStatus.toLowerCase();
|
|
117415
|
+
const status = normalizedStatus === "creating" || normalizedStatus === "normal"
|
|
117416
|
+
? normalizedStatus
|
|
117417
|
+
: "unknown";
|
|
117418
|
+
return { isExist: true, status, baseInfo };
|
|
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
|
+
}
|
|
117487
|
+
/**
|
|
117488
|
+
* 探测当前环境云托管(大租户)是否已初始化。
|
|
117489
|
+
*
|
|
117490
|
+
* 背景(2026-08-13 用户实测):新环境未调 CreateCloudRunEnv 初始化云托管时,
|
|
117491
|
+
* 直接 CreateCloudRunServer 会因"无大租户记录"被默认转入小租户,创建出小租户的
|
|
117492
|
+
* 服务和版本——这是错误路径。本函数在 deploy 创建新服务前用 tcbr DescribeEnvBaseInfo
|
|
117493
|
+
* 探测环境是否已开通云托管;未开通则抛错引导先初始化,而不是默默走到小租户路径。
|
|
117494
|
+
*
|
|
117495
|
+
* 实测(2026-08-13 真实凭据):tcbr 不存在 DescribeCloudRunEnv(单数)Action,调用
|
|
117496
|
+
* 恒返回 InvalidAction;正确的探测接口是 DescribeEnvBaseInfo。未开通云托管的环境返回
|
|
117497
|
+
* IsExist=false 且 EnvBaseInfo 为空结构(不抛错);已开通的环境(实测 ai-share-
|
|
117498
|
+
* d2guukyxybb63b206)返回 IsExist=true 且 EnvBaseInfo 含完整字段(Status="normal"、
|
|
117499
|
+
* PackageType/Region/EnvType/CreateTime 等已填充),两分支可明确区分。
|
|
117500
|
+
*
|
|
117501
|
+
* 双验证:DescribeCloudRunServers 未初始化与已初始化但无服务均返回 ServerList=[],
|
|
117502
|
+
* 无法区分,故不作为初始化判定依据。
|
|
117503
|
+
*
|
|
117504
|
+
* @returns 已初始化返回 true;探测到未初始化抛出带引导信息的 Error。
|
|
117505
|
+
*/
|
|
117506
|
+
async function ensureCloudRunEnvInitialized(options) {
|
|
117507
|
+
const manager = await (0, cloudbase_manager_js_1.getCloudBaseManager)({ cloudBaseOptions: options.cloudBaseOptions });
|
|
117508
|
+
if (!manager?.commonService) {
|
|
117509
|
+
// 老 SDK 无 commonService 时退化为不拦截(保持既有行为,避免误伤)。
|
|
117510
|
+
return true;
|
|
117511
|
+
}
|
|
117512
|
+
try {
|
|
117513
|
+
const status = await describeCloudRunEnvStatus(manager, options.envId);
|
|
117514
|
+
if (!status.isExist) {
|
|
117515
|
+
throwCloudRunEnvNotInitialized(options.envId);
|
|
117516
|
+
}
|
|
117517
|
+
return true;
|
|
117518
|
+
}
|
|
117519
|
+
catch (error) {
|
|
117520
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
117521
|
+
// 错误兜底:未初始化/未开通类错误码。
|
|
117522
|
+
// 注意:裸 InvalidParameter 可能是普通参数错误,不拦截;仅当其带 Env/CloudRun
|
|
117523
|
+
// 上下文(疑似 "EnvironmentId not found / CloudRun Env 未开通")时才按未初始化处理。
|
|
117524
|
+
if (/ResourceNotFound|not.?initialized|未开通|未初始化/i.test(msg) ||
|
|
117525
|
+
/InvalidParameter.*(?:Env|CloudRun)/i.test(msg)) {
|
|
117526
|
+
throwCloudRunEnvNotInitialized(options.envId);
|
|
117527
|
+
}
|
|
117528
|
+
// 其他错误(网络/权限等)不拦截,让上层按原逻辑处理。
|
|
117529
|
+
return true;
|
|
117530
|
+
}
|
|
117531
|
+
}
|
|
117532
|
+
function throwCloudRunEnvNotInitialized(envId) {
|
|
117533
|
+
throw new Error(`当前环境(${envId})尚未初始化云托管(CloudRun Env)。` +
|
|
117534
|
+
`不能直接创建服务(CreateCloudRunServer 在无大租户记录时会默认创建到小租户,产生错误的小租户服务与版本)。\n` +
|
|
117535
|
+
`请先开通云托管环境,再重试部署:\n` +
|
|
117536
|
+
`- MCP:manageCloudRun(action="initEnv", envId="${envId}")(异步开通,幂等;开通完成后可用 queryCloudRun(action="envStatus", envId="${envId}") 查询 Status=normal)\n` +
|
|
117537
|
+
`- 或控制台:环境 → 云托管 → 开通(https://tcb.cloud.tencent.com/dev?envId=${envId}#/platform-run)\n` +
|
|
117538
|
+
`初始化完成后重新调用 manageCloudRun(action="deploy")。`);
|
|
117539
|
+
}
|
|
117146
117540
|
/**
|
|
117147
117541
|
* Detect likely TCP database/cache env usage without VpcConf.
|
|
117148
117542
|
* Soft signal for AI agents — does not block deploy.
|
|
@@ -117239,6 +117633,36 @@ function normalizeCloudRunDomainUrl(input) {
|
|
|
117239
117633
|
? raw
|
|
117240
117634
|
: `https://${raw}`;
|
|
117241
117635
|
}
|
|
117636
|
+
/**
|
|
117637
|
+
* 从服务详情 / 最新部署记录中提取镜像信息(镜像部署时才有)。
|
|
117638
|
+
* 镜像部署(DeployType=image)的服务详情与部署记录通常会携带 ImageUrl 等字段;
|
|
117639
|
+
* 源码构建的服务无此字段,返回 undefined 表示无镜像信息。
|
|
117640
|
+
*/
|
|
117641
|
+
function extractCloudRunImageInfo(serviceDetail, latestDeploy) {
|
|
117642
|
+
const candidates = [
|
|
117643
|
+
latestDeploy,
|
|
117644
|
+
serviceDetail?.ServerConfig,
|
|
117645
|
+
serviceDetail?.BaseInfo,
|
|
117646
|
+
serviceDetail,
|
|
117647
|
+
];
|
|
117648
|
+
for (const source of candidates) {
|
|
117649
|
+
if (!source || typeof source !== "object")
|
|
117650
|
+
continue;
|
|
117651
|
+
const imageUrl = source.ImageUrl ??
|
|
117652
|
+
source.imageUrl ??
|
|
117653
|
+
(typeof source.ImageInfo === "string" ? source.ImageInfo : undefined) ??
|
|
117654
|
+
(typeof source.ImageInfo?.ImageUrl === "string" ? source.ImageInfo.ImageUrl : undefined);
|
|
117655
|
+
if (typeof imageUrl === "string" && imageUrl.trim()) {
|
|
117656
|
+
const deployType = typeof source.DeployType === "string"
|
|
117657
|
+
? source.DeployType
|
|
117658
|
+
: typeof source.deployType === "string"
|
|
117659
|
+
? source.deployType
|
|
117660
|
+
: undefined;
|
|
117661
|
+
return { imageUrl: imageUrl.trim(), ...(deployType ? { deployType } : {}) };
|
|
117662
|
+
}
|
|
117663
|
+
}
|
|
117664
|
+
return undefined;
|
|
117665
|
+
}
|
|
117242
117666
|
function resolveCloudRunFallbackAccess(details) {
|
|
117243
117667
|
const custom = normalizeCloudRunDomainUrl(details?.BaseInfo?.CustomDomainName);
|
|
117244
117668
|
if (custom)
|
|
@@ -117269,7 +117693,7 @@ function registerCloudRunTools(server) {
|
|
|
117269
117693
|
// Tool 1: Get CloudRun service information (read operations)
|
|
117270
117694
|
server.registerTool("queryCloudRun", {
|
|
117271
117695
|
title: "查询 CloudRun 服务信息",
|
|
117272
|
-
description: "
|
|
117696
|
+
description: "查询云托管服务信息,支持获取服务列表、查询服务详情、获取可用模板列表、获取构建日志(getDeployLog,仅云端源码构建/依赖 CODING)、获取运行日志(getProcessLog,镜像与源码部署均可/不依赖 CODING)、获取部署记录以及查询环境云托管开通状态(envStatus)。返回的服务信息包括服务名称、状态、访问类型、配置详情以及最近部署上下文。",
|
|
117273
117697
|
inputSchema: queryCloudRunInputSchema,
|
|
117274
117698
|
annotations: {
|
|
117275
117699
|
readOnlyHint: true,
|
|
@@ -117357,10 +117781,13 @@ function registerCloudRunTools(server) {
|
|
|
117357
117781
|
if (!latestDeploy) {
|
|
117358
117782
|
message = `Retrieved details for service '${serverName}'. No deploy records found yet.`;
|
|
117359
117783
|
}
|
|
117360
|
-
else if (typeof latestDeploy.Status ===
|
|
117361
|
-
|
|
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).`;
|
|
117362
117788
|
}
|
|
117363
|
-
else if (typeof latestDeploy.Status ===
|
|
117789
|
+
else if (typeof latestDeploy.Status === "string" &&
|
|
117790
|
+
latestDeploy.Status.toLowerCase().includes("creating")) {
|
|
117364
117791
|
message = `Service '${serverName}' latest deploy is still running. Please check again later or query the deploy log for progress.`;
|
|
117365
117792
|
}
|
|
117366
117793
|
else {
|
|
@@ -117381,6 +117808,10 @@ function registerCloudRunTools(server) {
|
|
|
117381
117808
|
data: {
|
|
117382
117809
|
service: result,
|
|
117383
117810
|
latestDeploy,
|
|
117811
|
+
// 若最新部署记录带镜像信息(镜像部署),透出便于展示
|
|
117812
|
+
...(extractCloudRunImageInfo(result, latestDeploy)
|
|
117813
|
+
? { imageInfo: extractCloudRunImageInfo(result, latestDeploy) }
|
|
117814
|
+
: {}),
|
|
117384
117815
|
...(deployRecordsWarning ? { deployRecordsWarning } : {})
|
|
117385
117816
|
},
|
|
117386
117817
|
message
|
|
@@ -117439,6 +117870,9 @@ function registerCloudRunTools(server) {
|
|
|
117439
117870
|
};
|
|
117440
117871
|
}
|
|
117441
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.
|
|
117442
117876
|
const buildLogResult = await cloudrunService.getBuildLog({
|
|
117443
117877
|
serverName,
|
|
117444
117878
|
buildId,
|
|
@@ -117469,11 +117903,189 @@ function registerCloudRunTools(server) {
|
|
|
117469
117903
|
buildId,
|
|
117470
117904
|
deployRecord: latestDeploy,
|
|
117471
117905
|
buildLog: buildLogResult?.Log || null,
|
|
117906
|
+
// Optional best-effort attach; prefer dedicated getProcessLog for runtime diagnosis
|
|
117472
117907
|
processLogs,
|
|
117473
117908
|
combinedLogText,
|
|
117474
117909
|
...(processLogsWarning ? { processLogsWarning } : {})
|
|
117475
117910
|
},
|
|
117476
|
-
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}'`
|
|
118030
|
+
}, null, 2)
|
|
118031
|
+
}
|
|
118032
|
+
]
|
|
118033
|
+
};
|
|
118034
|
+
}
|
|
118035
|
+
case 'envStatus': {
|
|
118036
|
+
const envId = input.envId?.trim() || (await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions));
|
|
118037
|
+
if (!manager.commonService) {
|
|
118038
|
+
throw new Error("Current CloudBase Manager does not support commonService; cannot query CloudRun env status.");
|
|
118039
|
+
}
|
|
118040
|
+
let status;
|
|
118041
|
+
try {
|
|
118042
|
+
status = await describeCloudRunEnvStatus(manager, envId);
|
|
118043
|
+
}
|
|
118044
|
+
catch (error) {
|
|
118045
|
+
const baseMessage = error instanceof Error ? error.message : String(error);
|
|
118046
|
+
if (/ResourceNotFound|not.?initialized|未开通|未初始化/i.test(baseMessage) ||
|
|
118047
|
+
/InvalidParameter.*(?:Env|CloudRun)/i.test(baseMessage)) {
|
|
118048
|
+
status = { isExist: false, status: "unopened", baseInfo: {} };
|
|
118049
|
+
}
|
|
118050
|
+
else {
|
|
118051
|
+
throw new Error(`[queryCloudRun/envStatus] ${baseMessage}`);
|
|
118052
|
+
}
|
|
118053
|
+
}
|
|
118054
|
+
let message;
|
|
118055
|
+
if (!status.isExist) {
|
|
118056
|
+
message = `环境 ${envId} 尚未开通云托管。请先调用 manageCloudRun(action="initEnv", envId="${envId}") 开通(异步、幂等),或前往控制台 环境 → 云托管 → 开通;Status=normal 后即可 deploy。`;
|
|
118057
|
+
}
|
|
118058
|
+
else if (status.status === "creating") {
|
|
118059
|
+
message = `环境 ${envId} 云托管正在开通中(Status=creating)。请稍后重试 manageCloudRun(action="deploy"),或用本 action 再次查询直到 Status=normal。`;
|
|
118060
|
+
}
|
|
118061
|
+
else if (status.status === "normal") {
|
|
118062
|
+
message = `环境 ${envId} 云托管已开通(Status=normal),可直接 manageCloudRun(action="deploy")。`;
|
|
118063
|
+
}
|
|
118064
|
+
else {
|
|
118065
|
+
message = `环境 ${envId} 云托管状态未知(Status=${status.status ?? "unknown"}),请稍后重试。`;
|
|
118066
|
+
}
|
|
118067
|
+
return {
|
|
118068
|
+
content: [
|
|
118069
|
+
{
|
|
118070
|
+
type: "text",
|
|
118071
|
+
text: JSON.stringify({
|
|
118072
|
+
success: true,
|
|
118073
|
+
data: {
|
|
118074
|
+
envId,
|
|
118075
|
+
status: status.status,
|
|
118076
|
+
isExist: status.isExist,
|
|
118077
|
+
...(status.isExist
|
|
118078
|
+
? {
|
|
118079
|
+
envBaseInfo: {
|
|
118080
|
+
Status: status.baseInfo.Status ?? null,
|
|
118081
|
+
PackageType: status.baseInfo.PackageType ?? null,
|
|
118082
|
+
Region: status.baseInfo.Region ?? null,
|
|
118083
|
+
EnvType: status.baseInfo.EnvType ?? null,
|
|
118084
|
+
},
|
|
118085
|
+
}
|
|
118086
|
+
: {}),
|
|
118087
|
+
},
|
|
118088
|
+
message
|
|
117477
118089
|
}, null, 2)
|
|
117478
118090
|
}
|
|
117479
118091
|
]
|
|
@@ -117488,7 +118100,7 @@ function registerCloudRunTools(server) {
|
|
|
117488
118100
|
// Tool 2: Manage CloudRun services (write operations)
|
|
117489
118101
|
server.registerTool("manageCloudRun", {
|
|
117490
118102
|
title: "管理 CloudRun 服务",
|
|
117491
|
-
description: "
|
|
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 开通(异步、幂等)。",
|
|
117492
118104
|
inputSchema: ManageCloudRunInputSchema,
|
|
117493
118105
|
annotations: {
|
|
117494
118106
|
readOnlyHint: false,
|
|
@@ -117509,6 +118121,197 @@ function registerCloudRunTools(server) {
|
|
|
117509
118121
|
targetPath = validateAndNormalizePath(input.targetPath);
|
|
117510
118122
|
}
|
|
117511
118123
|
switch (input.action) {
|
|
118124
|
+
case 'initEnv': {
|
|
118125
|
+
const envId = input.envId?.trim() || (await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions));
|
|
118126
|
+
const packageType = input.packageType || 'Trial';
|
|
118127
|
+
if (!manager.commonService) {
|
|
118128
|
+
throw new Error("Current CloudBase Manager does not support commonService; cannot initialize CloudRun env.");
|
|
118129
|
+
}
|
|
118130
|
+
// 幂等:先查当前开通状态,已开通 / 开通中不重复创建。
|
|
118131
|
+
let current;
|
|
118132
|
+
try {
|
|
118133
|
+
current = await describeCloudRunEnvStatus(manager, envId);
|
|
118134
|
+
}
|
|
118135
|
+
catch (error) {
|
|
118136
|
+
const baseMessage = error instanceof Error ? error.message : String(error);
|
|
118137
|
+
if (/ResourceNotFound|not.?initialized|未开通|未初始化/i.test(baseMessage) ||
|
|
118138
|
+
/InvalidParameter.*(?:Env|CloudRun)/i.test(baseMessage)) {
|
|
118139
|
+
current = { isExist: false, status: "unopened", baseInfo: {} };
|
|
118140
|
+
}
|
|
118141
|
+
else {
|
|
118142
|
+
throw new Error(`[manageCloudRun/initEnv] ${baseMessage}`);
|
|
118143
|
+
}
|
|
118144
|
+
}
|
|
118145
|
+
if (current.isExist && current.status === "normal") {
|
|
118146
|
+
return {
|
|
118147
|
+
content: [
|
|
118148
|
+
{
|
|
118149
|
+
type: "text",
|
|
118150
|
+
text: JSON.stringify({
|
|
118151
|
+
success: true,
|
|
118152
|
+
data: {
|
|
118153
|
+
envId,
|
|
118154
|
+
status: "normal",
|
|
118155
|
+
packageType: current.baseInfo.PackageType ?? packageType,
|
|
118156
|
+
created: false
|
|
118157
|
+
},
|
|
118158
|
+
message: `环境 ${envId} 已开通云托管(Status=normal),无需重复开通。可直接 manageCloudRun(action="deploy")。`
|
|
118159
|
+
}, null, 2)
|
|
118160
|
+
}
|
|
118161
|
+
]
|
|
118162
|
+
};
|
|
118163
|
+
}
|
|
118164
|
+
if (current.isExist && current.status === "creating") {
|
|
118165
|
+
return {
|
|
118166
|
+
content: [
|
|
118167
|
+
{
|
|
118168
|
+
type: "text",
|
|
118169
|
+
text: JSON.stringify({
|
|
118170
|
+
success: true,
|
|
118171
|
+
data: {
|
|
118172
|
+
envId,
|
|
118173
|
+
status: "creating",
|
|
118174
|
+
created: false
|
|
118175
|
+
},
|
|
118176
|
+
message: `环境 ${envId} 云托管正在开通中(Status=creating),无需重复开通。请稍后用 queryCloudRun(action="envStatus", envId="${envId}") 查询,Status=normal 后即可 deploy。`
|
|
118177
|
+
}, null, 2)
|
|
118178
|
+
}
|
|
118179
|
+
]
|
|
118180
|
+
};
|
|
118181
|
+
}
|
|
118182
|
+
// 未开通 → 发起异步开通(CreateCloudRunEnv 异步,不阻塞等待)。
|
|
118183
|
+
// Always pass EnvType=tcbr; optional vpcId/subnetIds when an explicit VPC is required.
|
|
118184
|
+
let createResult;
|
|
118185
|
+
try {
|
|
118186
|
+
createResult = await manager
|
|
118187
|
+
.commonService("tcbr", "2022-02-17")
|
|
118188
|
+
.call({
|
|
118189
|
+
Action: "CreateCloudRunEnv",
|
|
118190
|
+
Param: buildCreateCloudRunEnvParam({
|
|
118191
|
+
envId,
|
|
118192
|
+
packageType,
|
|
118193
|
+
vpcId: input.vpcId,
|
|
118194
|
+
subnetIds: input.subnetIds,
|
|
118195
|
+
}),
|
|
118196
|
+
});
|
|
118197
|
+
}
|
|
118198
|
+
catch (error) {
|
|
118199
|
+
throw new Error(buildManageCloudRunErrorMessage('initEnv', envId, error));
|
|
118200
|
+
}
|
|
118201
|
+
const tranId = createResult?.TranId ??
|
|
118202
|
+
createResult?.Response?.TranId ??
|
|
118203
|
+
createResult?.tranId;
|
|
118204
|
+
return {
|
|
118205
|
+
content: [
|
|
118206
|
+
{
|
|
118207
|
+
type: "text",
|
|
118208
|
+
text: JSON.stringify({
|
|
118209
|
+
success: true,
|
|
118210
|
+
data: {
|
|
118211
|
+
envId,
|
|
118212
|
+
status: "creating",
|
|
118213
|
+
packageType,
|
|
118214
|
+
created: true,
|
|
118215
|
+
...(tranId ? { tranId } : {})
|
|
118216
|
+
},
|
|
118217
|
+
message: `已发起云托管开通(异步,Status=creating)。请稍后用 queryCloudRun(action="envStatus", envId="${envId}") 查询状态,Status=normal 后即可 manageCloudRun(action="deploy")。`
|
|
118218
|
+
}, null, 2)
|
|
118219
|
+
}
|
|
118220
|
+
]
|
|
118221
|
+
};
|
|
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
|
+
}
|
|
117512
118315
|
case 'createAgent': {
|
|
117513
118316
|
if (!targetPath) {
|
|
117514
118317
|
throw new Error("targetPath is required for createAgent operation");
|
|
@@ -117674,14 +118477,18 @@ for await (let x of res.textStream) {
|
|
|
117674
118477
|
};
|
|
117675
118478
|
}
|
|
117676
118479
|
case 'deploy': {
|
|
117677
|
-
if (!targetPath) {
|
|
117678
|
-
throw new Error("targetPath is required for deploy operation");
|
|
118480
|
+
if (!targetPath && !input.imageUrl) {
|
|
118481
|
+
throw new Error("targetPath (source build) or imageUrl (existing image) is required for deploy operation");
|
|
117679
118482
|
}
|
|
117680
118483
|
// Determine service type - use input.serverType if provided, otherwise auto-detect
|
|
117681
118484
|
let serverType;
|
|
117682
118485
|
let remoteServerConfig = null;
|
|
117683
118486
|
let existingService = false;
|
|
117684
|
-
if (input.
|
|
118487
|
+
if (input.imageUrl) {
|
|
118488
|
+
// Image deploy is always container type (SDK: DeployInfo={DeployType:"image", ImageUrl}).
|
|
118489
|
+
serverType = 'container';
|
|
118490
|
+
}
|
|
118491
|
+
else if (input.serverType) {
|
|
117685
118492
|
serverType = input.serverType;
|
|
117686
118493
|
}
|
|
117687
118494
|
else {
|
|
@@ -117735,6 +118542,17 @@ for await (let x of res.textStream) {
|
|
|
117735
118542
|
// New service create path
|
|
117736
118543
|
}
|
|
117737
118544
|
}
|
|
118545
|
+
// 新环境必须先初始化云托管(大租户),否则 CreateCloudRunServer 会默认
|
|
118546
|
+
// 创建小租户服务。仅创建新服务(非 existing)前探测一次。
|
|
118547
|
+
// (2026-08-13 用户实测:luapi-v2 因未初始化云托管被创建到小租户)
|
|
118548
|
+
if (!existingService) {
|
|
118549
|
+
const currentEnvId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
|
|
118550
|
+
await ensureCloudRunEnvInitialized({
|
|
118551
|
+
cloudBaseOptions,
|
|
118552
|
+
envId: currentEnvId,
|
|
118553
|
+
serverName: input.serverName,
|
|
118554
|
+
});
|
|
118555
|
+
}
|
|
117738
118556
|
let mergedFromRemote = [];
|
|
117739
118557
|
let effectiveServerConfig = input.serverConfig;
|
|
117740
118558
|
if (existingService) {
|
|
@@ -117752,18 +118570,37 @@ for await (let x of res.textStream) {
|
|
|
117752
118570
|
force: input.force,
|
|
117753
118571
|
serverType: serverType,
|
|
117754
118572
|
};
|
|
118573
|
+
if (input.imageUrl) {
|
|
118574
|
+
deployParams.imageUrl = input.imageUrl;
|
|
118575
|
+
}
|
|
117755
118576
|
if (effectiveServerConfig && Object.keys(effectiveServerConfig).length > 0) {
|
|
117756
118577
|
deployParams.serverConfig = effectiveServerConfig;
|
|
117757
118578
|
}
|
|
117758
118579
|
// Manager SDK create path prefers top-level vpcInfo (CreateCloudRunServer.VpcInfo).
|
|
117759
|
-
//
|
|
118580
|
+
// Prefer serverConfig.VpcConf; if missing, auto-fill from env DescribeEnvBaseInfo
|
|
118581
|
+
// (envs opened with vpcId/subnetIds already carry VpcId/SubNetIds).
|
|
117760
118582
|
const vpcConf = effectiveServerConfig?.VpcConf;
|
|
117761
|
-
|
|
117762
|
-
|
|
117763
|
-
|
|
117764
|
-
|
|
117765
|
-
|
|
117766
|
-
|
|
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;
|
|
117767
118604
|
}
|
|
117768
118605
|
let result;
|
|
117769
118606
|
try {
|
|
@@ -117772,22 +118609,38 @@ for await (let x of res.textStream) {
|
|
|
117772
118609
|
catch (error) {
|
|
117773
118610
|
throw new Error(buildManageCloudRunErrorMessage('deploy', input.serverName, error));
|
|
117774
118611
|
}
|
|
117775
|
-
// Generate cloudbaserc.json configuration file
|
|
118612
|
+
// Generate cloudbaserc.json configuration file (source-build only; image deploy has no local project dir)
|
|
117776
118613
|
const currentEnvId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
|
|
117777
|
-
|
|
117778
|
-
|
|
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,
|
|
117779
118622
|
envId: currentEnvId,
|
|
117780
|
-
|
|
117781
|
-
|
|
118623
|
+
serverName: input.serverName,
|
|
118624
|
+
mode: deployType,
|
|
118625
|
+
});
|
|
118626
|
+
let cloudbasercGenerated = false;
|
|
118627
|
+
if (targetPath) {
|
|
118628
|
+
const cloudbasercPath = path_1.default.join(targetPath, 'cloudbaserc.json');
|
|
118629
|
+
const cloudbasercContent = {
|
|
118630
|
+
envId: currentEnvId,
|
|
118631
|
+
cloudrun: {
|
|
118632
|
+
name: input.serverName
|
|
118633
|
+
}
|
|
118634
|
+
};
|
|
118635
|
+
try {
|
|
118636
|
+
fs_1.default.writeFileSync(cloudbasercPath, JSON.stringify(cloudbasercContent, null, 2));
|
|
118637
|
+
cloudbasercGenerated = true;
|
|
118638
|
+
}
|
|
118639
|
+
catch (error) {
|
|
118640
|
+
(0, logger_js_1.debug)('cloudbaserc.json creation skipped:', error instanceof Error ? error : new Error(String(error)));
|
|
117782
118641
|
}
|
|
117783
|
-
};
|
|
117784
|
-
const consoleUrl = `https://tcb.cloud.tencent.com/dev?envId=${currentEnvId}#/platform-run/service/detail?serverName=${input.serverName}&tabId=overview&envId=${currentEnvId}`;
|
|
117785
|
-
try {
|
|
117786
|
-
fs_1.default.writeFileSync(cloudbasercPath, JSON.stringify(cloudbasercContent, null, 2));
|
|
117787
|
-
}
|
|
117788
|
-
catch (error) {
|
|
117789
|
-
(0, logger_js_1.debug)('cloudbaserc.json creation skipped:', error instanceof Error ? error : new Error(String(error)));
|
|
117790
118642
|
}
|
|
118643
|
+
const consoleUrl = `https://tcb.cloud.tencent.com/dev?envId=${currentEnvId}#/platform-run/service/detail?serverName=${input.serverName}&tabId=overview&envId=${currentEnvId}`;
|
|
117791
118644
|
let preferredAccessUrl;
|
|
117792
118645
|
let preferredAccessUrls = [];
|
|
117793
118646
|
let preferredAccessSource;
|
|
@@ -117824,7 +118677,7 @@ for await (let x of res.textStream) {
|
|
|
117824
118677
|
}
|
|
117825
118678
|
// Send deployment notification to CodeBuddy IDE
|
|
117826
118679
|
try {
|
|
117827
|
-
const projectName = path_1.default.basename(targetPath);
|
|
118680
|
+
const projectName = targetPath ? path_1.default.basename(targetPath) : input.serverName;
|
|
117828
118681
|
await (0, notification_js_1.sendDeployNotification)(server, {
|
|
117829
118682
|
deployType: 'cloudrun',
|
|
117830
118683
|
url: preferredAccessUrl ?? "",
|
|
@@ -117845,6 +118698,24 @@ for await (let x of res.textStream) {
|
|
|
117845
118698
|
const warningSuffix = dbNetworkRisk
|
|
117846
118699
|
? ` Warning: ${dbNetworkRisk.message} Set serverConfig.VpcConf before relying on DB connectivity.`
|
|
117847
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
|
+
});
|
|
117848
118719
|
return {
|
|
117849
118720
|
content: [
|
|
117850
118721
|
{
|
|
@@ -117854,10 +118725,30 @@ for await (let x of res.textStream) {
|
|
|
117854
118725
|
data: {
|
|
117855
118726
|
serviceName: input.serverName,
|
|
117856
118727
|
status: 'deploying',
|
|
117857
|
-
|
|
118728
|
+
deployType,
|
|
118729
|
+
...(targetPath ? { deployPath: targetPath } : {}),
|
|
118730
|
+
...(input.imageUrl ? { imageUrl: input.imageUrl } : {}),
|
|
117858
118731
|
serverType: serverType,
|
|
117859
|
-
cloudbasercGenerated
|
|
118732
|
+
cloudbasercGenerated,
|
|
117860
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,
|
|
117861
118752
|
...(existingService
|
|
117862
118753
|
? {
|
|
117863
118754
|
configMerge: {
|
|
@@ -117878,8 +118769,10 @@ for await (let x of res.textStream) {
|
|
|
117878
118769
|
? { accessUrlSource: preferredAccessSource }
|
|
117879
118770
|
: {}),
|
|
117880
118771
|
...(warnings.length > 0 ? { warnings } : {}),
|
|
118772
|
+
// Keep raw SDK result for debugging without implying build finished.
|
|
118773
|
+
...(result != null ? { deployAccepted: true } : {}),
|
|
117881
118774
|
},
|
|
117882
|
-
message: `Triggered deployment for ${serverType} service '${input.serverName}' 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}`
|
|
117883
118776
|
}, null, 2)
|
|
117884
118777
|
}
|
|
117885
118778
|
]
|
|
@@ -122015,7 +122908,9 @@ function registerAppTools(server) {
|
|
|
122015
122908
|
buildId,
|
|
122016
122909
|
});
|
|
122017
122910
|
(0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
|
|
122018
|
-
|
|
122911
|
+
// Platform may return Failed/failed; normalize before matching.
|
|
122912
|
+
const isFailed = typeof result.Status === "string" &&
|
|
122913
|
+
result.Status.toLowerCase() === "failed";
|
|
122019
122914
|
const payload = {
|
|
122020
122915
|
action,
|
|
122021
122916
|
serviceName,
|
|
@@ -122114,7 +123009,8 @@ function registerAppTools(server) {
|
|
|
122114
123009
|
.optional()
|
|
122115
123010
|
.describe("自定义部署命令。通常无需填写,默认自动生成 tcb hosting deploy 命令。" +
|
|
122116
123011
|
"有 buildPath 时远端已 cd 到该目录,默认用 . 作为源码路径;无 buildPath 时默认用 dist。"),
|
|
122117
|
-
ignore: zod_1.z.array(zod_1.z.string()).optional().describe("上传时忽略的文件/目录 glob 模式,例如 **/node_modules
|
|
123012
|
+
ignore: zod_1.z.array(zod_1.z.string()).optional().describe("上传时忽略的文件/目录 glob 模式,例如 **/node_modules/**。\n" +
|
|
123013
|
+
"⚠️ 打包的是项目根目录(filePath)而非 buildPath 产物目录:若项目根含 target/(Rust)、.next/、dist-old/、build/ 等大构建产物,必须加进 ignore(如 **/target/**),否则整个目录被打进上传 zip(实证 54GB target → 34GB zip)。默认已排除 node_modules/.git/.DS_Store/**/target/**/.next/**/.next.bak/**。"),
|
|
122118
123014
|
versionName: zod_1.z
|
|
122119
123015
|
.string()
|
|
122120
123016
|
.optional()
|
|
@@ -122134,6 +123030,17 @@ function registerAppTools(server) {
|
|
|
122134
123030
|
if (!appService) {
|
|
122135
123031
|
throw new Error("当前 manager 未提供 cloudAppService");
|
|
122136
123032
|
}
|
|
123033
|
+
// 默认排除的大目录(2026-08-14 实证:ato 项目 target/ 54GB 被整个打进 zip)
|
|
123034
|
+
// tcb app deploy 打包的是项目根目录(localPath)而非 outputDir,必须排除构建产物
|
|
123035
|
+
const defaultPackIgnore = [
|
|
123036
|
+
"node_modules/**",
|
|
123037
|
+
".git/**",
|
|
123038
|
+
".DS_Store",
|
|
123039
|
+
"**/.DS_Store",
|
|
123040
|
+
"**/target/**",
|
|
123041
|
+
"**/.next/**",
|
|
123042
|
+
"**/.next.bak/**",
|
|
123043
|
+
];
|
|
122137
123044
|
// getUploadUrl — 获取预签名上传 URL(cloud mode 专用)
|
|
122138
123045
|
if (action === "getUploadUrl") {
|
|
122139
123046
|
if (!serviceName) {
|
|
@@ -122144,9 +123051,9 @@ function registerAppTools(server) {
|
|
|
122144
123051
|
serviceName,
|
|
122145
123052
|
});
|
|
122146
123053
|
(0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, cosInfoResult);
|
|
122147
|
-
const defaultIgnore =
|
|
123054
|
+
const defaultIgnore = defaultPackIgnore;
|
|
122148
123055
|
// eslint-disable-next-line max-len
|
|
122149
|
-
const zipCmd = "zip -r upload.zip . -x 'node_modules/**' -x '.git/**' -x '.DS_Store' -x '**/.DS_Store'";
|
|
123056
|
+
const zipCmd = "zip -r upload.zip . -x 'node_modules/**' -x '.git/**' -x '.DS_Store' -x '**/.DS_Store' -x '**/target/**' -x '**/.next/**' -x '**/.next.bak/**'";
|
|
122150
123057
|
const followupArgs = {
|
|
122151
123058
|
action: "deployApp",
|
|
122152
123059
|
serviceName,
|
|
@@ -122190,11 +123097,17 @@ function registerAppTools(server) {
|
|
|
122190
123097
|
// 上传代码到 COS(仅本地模式需要,cloud mode 用 cosTimestamp 跳过)
|
|
122191
123098
|
let cosTs = cosTimestamp;
|
|
122192
123099
|
if (filePath && !cosTs) {
|
|
123100
|
+
// 默认排除大目录(2026-08-14 实证:ato 项目 target/ 54GB 被整个打进 zip)
|
|
123101
|
+
// 用户显式传 ignore 时合并,避免覆盖默认值
|
|
123102
|
+
const mergedIgnore = Array.from(new Set([
|
|
123103
|
+
...defaultPackIgnore,
|
|
123104
|
+
...(ignore ?? []),
|
|
123105
|
+
]));
|
|
122193
123106
|
const uploadResult = await appService.uploadCode({
|
|
122194
123107
|
deployType: "static-hosting",
|
|
122195
123108
|
serviceName,
|
|
122196
123109
|
localPath: filePath,
|
|
122197
|
-
ignore,
|
|
123110
|
+
ignore: mergedIgnore,
|
|
122198
123111
|
});
|
|
122199
123112
|
(0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, uploadResult);
|
|
122200
123113
|
cosTs = uploadResult.cosTimestamp;
|
|
@@ -131528,7 +132441,11 @@ module.exports = setup;
|
|
|
131528
132441
|
"use strict";
|
|
131529
132442
|
|
|
131530
132443
|
Object.defineProperty(exports, "__esModule", ({ value: true }));
|
|
132444
|
+
exports.CAM_AUTH_ERROR_PATTERN = void 0;
|
|
132445
|
+
exports.assertTcbCloudRunActionAllowed = assertTcbCloudRunActionAllowed;
|
|
131531
132446
|
exports.removeEmptyStringParams = removeEmptyStringParams;
|
|
132447
|
+
exports.buildCamAuthGuidance = buildCamAuthGuidance;
|
|
132448
|
+
exports.isCamAuthError = isCamAuthError;
|
|
131532
132449
|
exports.buildCapiErrorMessage = buildCapiErrorMessage;
|
|
131533
132450
|
exports.registerCapiTools = registerCapiTools;
|
|
131534
132451
|
const zod_1 = __webpack_require__(7552);
|
|
@@ -131539,6 +132456,7 @@ const CLOUDBASE_CONTROL_PLANE_DOC_URL = "https://cloud.tencent.com/document/prod
|
|
|
131539
132456
|
const CLOUDBASE_DEPENDENCY_API_DOC_URL = "https://cloud.tencent.com/document/product/876/34808";
|
|
131540
132457
|
const ALLOWED_SERVICES = [
|
|
131541
132458
|
"tcb",
|
|
132459
|
+
"tcbr",
|
|
131542
132460
|
"scf",
|
|
131543
132461
|
"sts",
|
|
131544
132462
|
"cam",
|
|
@@ -131546,6 +132464,34 @@ const ALLOWED_SERVICES = [
|
|
|
131546
132464
|
"cdn",
|
|
131547
132465
|
"vpc",
|
|
131548
132466
|
];
|
|
132467
|
+
/**
|
|
132468
|
+
* Legacy tcb small-tenant CloudRun (CloudBase Run) API family — blocked.
|
|
132469
|
+
*
|
|
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.
|
|
132476
|
+
*/
|
|
132477
|
+
const TCB_CLOUDRUN_FORBIDDEN_ACTIONS = [
|
|
132478
|
+
"CreateCloudBaseRunResource",
|
|
132479
|
+
"DescribeCloudBaseRunResource",
|
|
132480
|
+
"DeleteCloudBaseRunResource",
|
|
132481
|
+
];
|
|
132482
|
+
const TCB_CLOUDRUN_FORBIDDEN_ACTIONS_LOWER = new Set(TCB_CLOUDRUN_FORBIDDEN_ACTIONS.map((name) => name.toLowerCase()));
|
|
132483
|
+
const TCB_CLOUDRUN_FORBIDDEN_HINT = `云托管(CloudBase Run)统一走 tcbr 新逻辑(CreateCloudRunEnv / CreateCloudRunServer),` +
|
|
132484
|
+
`不要使用 tcb 旧小租户接口(${TCB_CLOUDRUN_FORBIDDEN_ACTIONS.join(" / ")})。` +
|
|
132485
|
+
`新环境请先初始化云托管:callCloudApi(service="tcbr", version="2022-02-17", action="CreateCloudRunEnv", params={EnvId:"..."}),` +
|
|
132486
|
+
`再通过 manageCloudRun(action="deploy") 创建服务;查询单个环境基础信息/是否已开通云托管用 callCloudApi(service="tcbr", version="2022-02-17", action="DescribeEnvBaseInfo", params={EnvId:"..."}),查询环境列表/资源信息用 DescribeCloudRunEnvs。`;
|
|
132487
|
+
/**
|
|
132488
|
+
* Reject legacy tcb small-tenant CloudRun APIs; throw with tcbr guidance when blocked.
|
|
132489
|
+
*/
|
|
132490
|
+
function assertTcbCloudRunActionAllowed(service, action) {
|
|
132491
|
+
if (service === "tcb" && TCB_CLOUDRUN_FORBIDDEN_ACTIONS_LOWER.has(action.toLowerCase())) {
|
|
132492
|
+
throw new Error(`[${service}/${action}] 已禁用:${TCB_CLOUDRUN_FORBIDDEN_HINT}`);
|
|
132493
|
+
}
|
|
132494
|
+
}
|
|
131549
132495
|
function levenshteinDistance(left, right) {
|
|
131550
132496
|
const rows = left.length + 1;
|
|
131551
132497
|
const cols = right.length + 1;
|
|
@@ -131621,11 +132567,26 @@ function formatTcbParamsTypeHint(action) {
|
|
|
131621
132567
|
return `参数类型参考:\n\`\`\`ts\n${entry.paramsType}\n\`\`\``;
|
|
131622
132568
|
}
|
|
131623
132569
|
function buildCapiDocGuidance(service) {
|
|
131624
|
-
if (service === "tcb" || service === "lowcode" || service === "scf") {
|
|
132570
|
+
if (service === "tcb" || service === "tcbr" || service === "lowcode" || service === "scf") {
|
|
131625
132571
|
return `优先查阅 CloudBase API 概览 ${CLOUDBASE_CONTROL_PLANE_DOC_URL} 与云开发依赖资源接口指引 ${CLOUDBASE_DEPENDENCY_API_DOC_URL}。`;
|
|
131626
132572
|
}
|
|
131627
132573
|
return `请优先核对对应官方云 API 文档;若你的场景其实是通过 HTTP 协议直接集成 auth/functions/cloudrun/storage/mysqldb 等 CloudBase 业务 API,请优先使用 OpenAPI / Swagger 或 searchKnowledgeBase(mode="openapi"),不要继续猜测管控面 Action。`;
|
|
131628
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
|
+
}
|
|
131629
132590
|
function buildCapiErrorMessage(service, action, error) {
|
|
131630
132591
|
const baseMessage = error instanceof Error ? error.message : String(error);
|
|
131631
132592
|
const suggestions = [];
|
|
@@ -131633,6 +132594,10 @@ function buildCapiErrorMessage(service, action, error) {
|
|
|
131633
132594
|
const hasInvalidActionError = /invalid or not found|does not exist|not recognized/i.test(baseMessage);
|
|
131634
132595
|
const hasParameterError = /parameter\s+`?.+?`?\s+is not recognized|MissingParameter|missing parameter|missing required/i.test(baseMessage);
|
|
131635
132596
|
const hasInvalidParameterValueError = /invalid parameter value/i.test(baseMessage);
|
|
132597
|
+
const hasCamAuthError = isCamAuthError(baseMessage);
|
|
132598
|
+
if (hasCamAuthError) {
|
|
132599
|
+
suggestions.push(buildCamAuthGuidance());
|
|
132600
|
+
}
|
|
131636
132601
|
if (hasInvalidActionError) {
|
|
131637
132602
|
suggestions.push(`Action \`${action}\` 可能不存在或不对外开放。请不要继续猜测 Action 名称,先确认 service=\`${service}\` 下该 Action 在当前 API 版本是否真实存在。`);
|
|
131638
132603
|
if (service === "tcb") {
|
|
@@ -131711,15 +132676,21 @@ function registerCapiTools(server) {
|
|
|
131711
132676
|
**云函数**: \`DescribeFunctions\`、\`CreateFunction\`、\`UpdateFunctionCode\`、\`DeleteFunction\`
|
|
131712
132677
|
**数据库**: \`CreateMySQLInstance\`、\`DescribeMySQLInstances\`、\`DestroyMySQLInstance\`
|
|
131713
132678
|
|
|
132679
|
+
⚠️ 云托管(CloudBase Run)统一走 tcbr service(CreateCloudRunEnv / CreateCloudRunServer / DescribeEnvBaseInfo / DescribeCloudRunEnvs,version="2022-02-17"),tcb 旧小租户接口 CreateCloudBaseRunResource 等已被禁用;部署请用 manageCloudRun。查询单个环境基础信息/是否已开通云托管用 DescribeEnvBaseInfo(EnvId 必填),查询环境列表及资源信息用 DescribeCloudRunEnvs(EnvId 可选过滤)。
|
|
132680
|
+
|
|
131714
132681
|
销毁环境时,常见做法是至少带上 \`EnvId\` 和 \`BypassCheck: true\`,如果环境已经处于隔离期再按文档补 \`IsForce: true\`。`,
|
|
131715
132682
|
inputSchema: {
|
|
131716
132683
|
service: zod_1.z
|
|
131717
132684
|
.enum(ALLOWED_SERVICES)
|
|
131718
|
-
.describe("选择要访问的服务。可选:tcb、scf、sts、cam、lowcode、cdn、vpc。对于 tcb / scf / lowcode 等 CloudBase 管控面 Action,请优先查官方文档,不要直接猜测 Action
|
|
132685
|
+
.describe("选择要访问的服务。可选:tcb、tcbr、scf、sts、cam、lowcode、cdn、vpc。对于 tcb / scf / lowcode 等 CloudBase 管控面 Action,请优先查官方文档,不要直接猜测 Action。云托管统一走 tcbr(version 需传 2022-02-17)。"),
|
|
131719
132686
|
action: zod_1.z
|
|
131720
132687
|
.string()
|
|
131721
132688
|
.min(1)
|
|
131722
|
-
.describe("具体 Action 名称,需符合对应服务的官方 API 定义。若不确定正确 Action,请先查官方文档;不要用近义词或历史命名进行猜测。tcb 常用 Action:环境管理 CreateEnv/ModifyEnv/DescribeEnvs/DestroyEnv、用户管理 CreateUser/ModifyUser/DescribeUserList/DeleteUsers、认证配置 EditAuthConfig、云函数 DescribeFunctions/CreateFunction、数据库 CreateMySQLInstance 等。"),
|
|
132689
|
+
.describe("具体 Action 名称,需符合对应服务的官方 API 定义。若不确定正确 Action,请先查官方文档;不要用近义词或历史命名进行猜测。tcb 常用 Action:环境管理 CreateEnv/ModifyEnv/DescribeEnvs/DestroyEnv、用户管理 CreateUser/ModifyUser/DescribeUserList/DeleteUsers、认证配置 EditAuthConfig、云函数 DescribeFunctions/CreateFunction、数据库 CreateMySQLInstance 等。tcbr 常用 Action:CreateCloudRunEnv(初始化云托管)、DescribeEnvBaseInfo(查询单个环境基础信息,EnvId 必填)、DescribeCloudRunEnvs(查询环境列表/资源信息,EnvId 可选过滤)、CreateCloudRunServer/DescribeCloudRunServers。"),
|
|
132690
|
+
version: zod_1.z
|
|
132691
|
+
.string()
|
|
132692
|
+
.optional()
|
|
132693
|
+
.describe("API 版本(可选)。缺省时按 service 使用 SDK 内置默认版本;tcbr 必须传 \"2022-02-17\"(否则请求缺少 X-TC-Version 会失败)。示例:service=\"tcbr\", version=\"2022-02-17\", action=\"CreateCloudRunEnv\", params={EnvId:\"env-xxx\",PackageType:\"Standard\"}。"),
|
|
131723
132694
|
params: zod_1.z
|
|
131724
132695
|
.record(zod_1.z.any())
|
|
131725
132696
|
.optional()
|
|
@@ -131732,10 +132703,11 @@ function registerCapiTools(server) {
|
|
|
131732
132703
|
openWorldHint: true,
|
|
131733
132704
|
category: CATEGORY,
|
|
131734
132705
|
},
|
|
131735
|
-
}, async ({ service, action, params, }) => {
|
|
132706
|
+
}, async ({ service, action, params, version, }) => {
|
|
131736
132707
|
if (!ALLOWED_SERVICES.includes(service)) {
|
|
131737
132708
|
throw new Error(`Service ${service} is not allowed. Allowed services: ${ALLOWED_SERVICES.join(", ")}`);
|
|
131738
132709
|
}
|
|
132710
|
+
assertTcbCloudRunActionAllowed(service, action);
|
|
131739
132711
|
const cloudbase = await getManager();
|
|
131740
132712
|
if (['1', 'true'].includes(process.env.CLOUDBASE_EVALUATE_MODE ?? '')) {
|
|
131741
132713
|
if (service === 'lowcode') {
|
|
@@ -131743,9 +132715,13 @@ function registerCapiTools(server) {
|
|
|
131743
132715
|
}
|
|
131744
132716
|
if (service === 'tcb') {
|
|
131745
132717
|
const tcbCapiForbidList = [
|
|
131746
|
-
//
|
|
132718
|
+
// Cloud APIs not clearly public
|
|
131747
132719
|
'DescribeStorageACL', 'ModifyStorageACL', 'DescribeSecurityRule',
|
|
131748
|
-
//
|
|
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
|
|
131749
132725
|
"ListTables",
|
|
131750
132726
|
"DescribeCloudBaseGWAPI",
|
|
131751
132727
|
"DescribeCloudBaseGWService",
|
|
@@ -131764,7 +132740,7 @@ function registerCapiTools(server) {
|
|
|
131764
132740
|
let result;
|
|
131765
132741
|
try {
|
|
131766
132742
|
const cleanedParams = params ? removeEmptyStringParams(params) : {};
|
|
131767
|
-
result = await cloudbase.commonService(service).call({
|
|
132743
|
+
result = await cloudbase.commonService(service, version).call({
|
|
131768
132744
|
Action: action,
|
|
131769
132745
|
Param: cleanedParams,
|
|
131770
132746
|
});
|
|
@@ -142390,7 +143366,7 @@ class TelemetryReporter {
|
|
|
142390
143366
|
const arch = os_1.default.arch(); // 系统架构
|
|
142391
143367
|
// Build-time injected version; guard for vitest / non-webpack runtimes.
|
|
142392
143368
|
const mcpVersion = process.env.npm_package_version ||
|
|
142393
|
-
( true ? "2.
|
|
143369
|
+
( true ? "2.28.0" : 0);
|
|
142394
143370
|
return {
|
|
142395
143371
|
userAgent: `${osType} ${osRelease} ${arch} ${nodeVersion} CloudBase-MCP/${mcpVersion}`,
|
|
142396
143372
|
deviceId: this.deviceId,
|
|
@@ -169333,6 +170309,98 @@ async function resolvePgDbContext(cloudBaseOptions, args) {
|
|
|
169333
170309
|
role: args?.role ?? "cloudbase_admin",
|
|
169334
170310
|
};
|
|
169335
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
|
+
}
|
|
169336
170404
|
function normalizeLimit(limit, fallback = 20, max = 200) {
|
|
169337
170405
|
if (!Number.isFinite(limit)) {
|
|
169338
170406
|
return fallback;
|
|
@@ -170557,7 +171625,26 @@ async function handleReadOnlySql(args, context, deps) {
|
|
|
170557
171625
|
}
|
|
170558
171626
|
const limit = normalizeLimit(args.limit);
|
|
170559
171627
|
const limitedSql = buildLimitedReadOnlySql(args.sql, limit);
|
|
170560
|
-
|
|
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
|
+
}
|
|
170561
171648
|
const summary = summarizeQueryResult(result, limit);
|
|
170562
171649
|
return buildPgToolResult({
|
|
170563
171650
|
success: true,
|
|
@@ -170612,6 +171699,9 @@ async function handleExecuteSql(args, context, deps) {
|
|
|
170612
171699
|
],
|
|
170613
171700
|
});
|
|
170614
171701
|
}
|
|
171702
|
+
if (args.role !== undefined && isLikelyInvalidPgExecuteRole(args.role)) {
|
|
171703
|
+
return buildPgToolResult(buildPgRoleErrorPayload(args.role.trim() || "(empty)"));
|
|
171704
|
+
}
|
|
170615
171705
|
if (!classification.readOnly && !args.confirm) {
|
|
170616
171706
|
return buildPgToolResult({
|
|
170617
171707
|
success: false,
|
|
@@ -170631,7 +171721,26 @@ async function handleExecuteSql(args, context, deps) {
|
|
|
170631
171721
|
],
|
|
170632
171722
|
});
|
|
170633
171723
|
}
|
|
170634
|
-
|
|
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
|
+
}
|
|
170635
171744
|
const targetTable = parseTargetTableFromSql(args.sql, context.defaultSchema);
|
|
170636
171745
|
return buildPgToolResult({
|
|
170637
171746
|
success: true,
|
|
@@ -171524,7 +172633,9 @@ function registerPGDatabaseTools(server, providedDeps) {
|
|
|
171524
172633
|
role: zod_1.z
|
|
171525
172634
|
.string()
|
|
171526
172635
|
.optional()
|
|
171527
|
-
.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。`),
|
|
171528
172639
|
objectName: zod_1.z
|
|
171529
172640
|
.string()
|
|
171530
172641
|
.optional()
|
|
@@ -171628,6 +172739,10 @@ function registerPGDatabaseTools(server, providedDeps) {
|
|
|
171628
172739
|
return handleExecuteSql(args, context, deps);
|
|
171629
172740
|
}
|
|
171630
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
|
+
}
|
|
171631
172746
|
try {
|
|
171632
172747
|
await ensurePgReadyOnce(cbOpts, deps);
|
|
171633
172748
|
}
|
|
@@ -218487,6 +219602,127 @@ TransportStream.prototype._nop = function _nop() {
|
|
|
218487
219602
|
};
|
|
218488
219603
|
|
|
218489
219604
|
|
|
219605
|
+
/***/ }),
|
|
219606
|
+
|
|
219607
|
+
/***/ 68107:
|
|
219608
|
+
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
|
|
219609
|
+
|
|
219610
|
+
"use strict";
|
|
219611
|
+
|
|
219612
|
+
Object.defineProperty(exports, "__esModule", ({ value: true }));
|
|
219613
|
+
exports.SITE_IDS = exports.SITE_REGION_MAP = void 0;
|
|
219614
|
+
exports.isSiteId = isSiteId;
|
|
219615
|
+
exports.normalizeSite = normalizeSite;
|
|
219616
|
+
exports.getSite = getSite;
|
|
219617
|
+
exports.resolveSite = resolveSite;
|
|
219618
|
+
exports.resolveSiteAndRegion = resolveSiteAndRegion;
|
|
219619
|
+
const project_config_js_1 = __webpack_require__(68445);
|
|
219620
|
+
exports.SITE_REGION_MAP = {
|
|
219621
|
+
domestic: {
|
|
219622
|
+
id: "domestic",
|
|
219623
|
+
label: "国内站",
|
|
219624
|
+
authHost: "tcb.cloud.tencent.com",
|
|
219625
|
+
consoleHost: "tcb.cloud.tencent.com",
|
|
219626
|
+
defaultRegion: "ap-shanghai",
|
|
219627
|
+
regions: ["ap-shanghai", "ap-guangzhou", "ap-singapore"],
|
|
219628
|
+
capabilities: { noSql: true },
|
|
219629
|
+
},
|
|
219630
|
+
intl: {
|
|
219631
|
+
id: "intl",
|
|
219632
|
+
label: "国际站",
|
|
219633
|
+
authHost: "tcb.tencentcloud.com",
|
|
219634
|
+
consoleHost: "tcb.tencentcloud.com",
|
|
219635
|
+
defaultRegion: "ap-singapore",
|
|
219636
|
+
regions: ["ap-singapore"],
|
|
219637
|
+
capabilities: { noSql: false },
|
|
219638
|
+
},
|
|
219639
|
+
};
|
|
219640
|
+
exports.SITE_IDS = Object.keys(exports.SITE_REGION_MAP);
|
|
219641
|
+
function isSiteId(value) {
|
|
219642
|
+
return value === "domestic" || value === "intl";
|
|
219643
|
+
}
|
|
219644
|
+
function normalizeSite(value) {
|
|
219645
|
+
if (typeof value !== "string") {
|
|
219646
|
+
return undefined;
|
|
219647
|
+
}
|
|
219648
|
+
const normalized = value.trim().toLowerCase();
|
|
219649
|
+
if (normalized === "intl" || normalized === "international") {
|
|
219650
|
+
return "intl";
|
|
219651
|
+
}
|
|
219652
|
+
if (normalized === "domestic" || normalized === "cn") {
|
|
219653
|
+
return "domestic";
|
|
219654
|
+
}
|
|
219655
|
+
return undefined;
|
|
219656
|
+
}
|
|
219657
|
+
/**
|
|
219658
|
+
* 根据 region 与显式 site 解析站点。
|
|
219659
|
+
*
|
|
219660
|
+
* - 显式 site 优先(`domestic`/`intl`,兼容 `cn`/`international` 别名)
|
|
219661
|
+
* - 否则查 SITE_REGION_MAP:region 只属于一个站点时返回该站点
|
|
219662
|
+
* - 当 region 同时存在于多个站点(如 ap-singapore)时返回 `ambiguous`,由上层决定
|
|
219663
|
+
* - 未知 region 或未提供 region 时回退 domestic(全局默认)
|
|
219664
|
+
*/
|
|
219665
|
+
function getSite(region, explicitSite) {
|
|
219666
|
+
const explicit = normalizeSite(explicitSite);
|
|
219667
|
+
if (explicit) {
|
|
219668
|
+
return explicit;
|
|
219669
|
+
}
|
|
219670
|
+
if (!region) {
|
|
219671
|
+
return "domestic";
|
|
219672
|
+
}
|
|
219673
|
+
const matches = exports.SITE_IDS.filter((site) => exports.SITE_REGION_MAP[site].regions.includes(region));
|
|
219674
|
+
if (matches.length === 1) {
|
|
219675
|
+
return matches[0];
|
|
219676
|
+
}
|
|
219677
|
+
if (matches.length > 1) {
|
|
219678
|
+
return "ambiguous";
|
|
219679
|
+
}
|
|
219680
|
+
return "domestic";
|
|
219681
|
+
}
|
|
219682
|
+
/**
|
|
219683
|
+
* 认证/路由场景下解析站点:歧义(如 ap-singapore 未配 site)时默认 intl,保持既有国际站行为。
|
|
219684
|
+
*/
|
|
219685
|
+
function resolveSite(region, explicitSite) {
|
|
219686
|
+
const site = getSite(region, explicitSite);
|
|
219687
|
+
return site === "ambiguous" ? "intl" : site;
|
|
219688
|
+
}
|
|
219689
|
+
/**
|
|
219690
|
+
* 统一 site/region 解析入口(收敛各调用点分散的 region fallback)。
|
|
219691
|
+
*
|
|
219692
|
+
* 优先级:显式参数 > 环境变量(TCB_SITE/TCB_REGION)> 项目配置(.cloudbase/project.json)> 全局默认
|
|
219693
|
+
* (site=domestic, region=ap-shanghai)。
|
|
219694
|
+
*
|
|
219695
|
+
* 当仅指定 region 且该 region 在多个 site 的地域列表中都存在(如 ap-singapore)时,
|
|
219696
|
+
* 返回 site=intl 并标记 ambiguous=true(兼容既有国际站行为),调用方可用 ambiguous 提示用户显式指定 site。
|
|
219697
|
+
*/
|
|
219698
|
+
function resolveSiteAndRegion(opts = {}) {
|
|
219699
|
+
const projectConfig = (0, project_config_js_1.readProjectConfig)();
|
|
219700
|
+
const explicitSite = normalizeSite(opts.site) ??
|
|
219701
|
+
normalizeSite(process.env.TCB_SITE) ??
|
|
219702
|
+
normalizeSite(projectConfig?.site);
|
|
219703
|
+
const explicitRegion = opts.region ?? process.env.TCB_REGION ?? projectConfig?.region;
|
|
219704
|
+
let site = explicitSite;
|
|
219705
|
+
let ambiguous = false;
|
|
219706
|
+
if (!site && explicitRegion) {
|
|
219707
|
+
const inferred = getSite(explicitRegion);
|
|
219708
|
+
if (inferred === "ambiguous") {
|
|
219709
|
+
site = "intl";
|
|
219710
|
+
ambiguous = true;
|
|
219711
|
+
}
|
|
219712
|
+
else if (inferred !== "domestic") {
|
|
219713
|
+
site = inferred;
|
|
219714
|
+
}
|
|
219715
|
+
}
|
|
219716
|
+
const resolvedSite = site ?? "domestic";
|
|
219717
|
+
const region = explicitRegion ?? exports.SITE_REGION_MAP[resolvedSite].defaultRegion;
|
|
219718
|
+
return {
|
|
219719
|
+
site: resolvedSite,
|
|
219720
|
+
region,
|
|
219721
|
+
...(ambiguous ? { ambiguous: true } : {}),
|
|
219722
|
+
};
|
|
219723
|
+
}
|
|
219724
|
+
|
|
219725
|
+
|
|
218490
219726
|
/***/ }),
|
|
218491
219727
|
|
|
218492
219728
|
/***/ 68182:
|
|
@@ -218578,6 +219814,44 @@ function parseEffectsDef(_def, refs) {
|
|
|
218578
219814
|
exports.parseEffectsDef = parseEffectsDef;
|
|
218579
219815
|
|
|
218580
219816
|
|
|
219817
|
+
/***/ }),
|
|
219818
|
+
|
|
219819
|
+
/***/ 68445:
|
|
219820
|
+
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
|
|
219821
|
+
|
|
219822
|
+
"use strict";
|
|
219823
|
+
|
|
219824
|
+
Object.defineProperty(exports, "__esModule", ({ value: true }));
|
|
219825
|
+
exports.readProjectConfig = readProjectConfig;
|
|
219826
|
+
const node_fs_1 = __webpack_require__(89971);
|
|
219827
|
+
const node_path_1 = __webpack_require__(26743);
|
|
219828
|
+
/**
|
|
219829
|
+
* 读取项目级配置 `.cloudbase/project.json`。
|
|
219830
|
+
*
|
|
219831
|
+
* 该文件是 site/region/envId 的可选持久化来源,让"打开项目即连对服务"
|
|
219832
|
+
* (对齐 Vercel `.vercel/project.json` 的三级回退)。读取失败/文件不存在
|
|
219833
|
+
* 返回 undefined,不阻塞调用方。
|
|
219834
|
+
*/
|
|
219835
|
+
function readProjectConfig(cwd) {
|
|
219836
|
+
try {
|
|
219837
|
+
const projectRoot = cwd ?? process.env.WORKSPACE_FOLDER_PATHS ?? process.cwd();
|
|
219838
|
+
const configPath = (0, node_path_1.join)(projectRoot, ".cloudbase", "project.json");
|
|
219839
|
+
if (!(0, node_fs_1.existsSync)(configPath)) {
|
|
219840
|
+
return undefined;
|
|
219841
|
+
}
|
|
219842
|
+
const raw = (0, node_fs_1.readFileSync)(configPath, "utf-8");
|
|
219843
|
+
const parsed = JSON.parse(raw);
|
|
219844
|
+
if (!parsed || typeof parsed !== "object") {
|
|
219845
|
+
return undefined;
|
|
219846
|
+
}
|
|
219847
|
+
return parsed;
|
|
219848
|
+
}
|
|
219849
|
+
catch {
|
|
219850
|
+
return undefined;
|
|
219851
|
+
}
|
|
219852
|
+
}
|
|
219853
|
+
|
|
219854
|
+
|
|
218581
219855
|
/***/ }),
|
|
218582
219856
|
|
|
218583
219857
|
/***/ 68599:
|
|
@@ -223806,7 +225080,7 @@ ${envIdSection}
|
|
|
223806
225080
|
## 环境信息
|
|
223807
225081
|
- 操作系统: ${os_1.default.type()} ${os_1.default.release()}
|
|
223808
225082
|
- Node.js版本: ${process.version}
|
|
223809
|
-
- MCP 版本:${process.env.npm_package_version || ( true ? "2.
|
|
225083
|
+
- MCP 版本:${process.env.npm_package_version || ( true ? "2.28.0" : 0)}
|
|
223810
225084
|
- 系统架构: ${os_1.default.arch()}
|
|
223811
225085
|
- 时间: ${new Date().toISOString()}
|
|
223812
225086
|
- 请求ID: ${requestId}
|
|
@@ -223887,7 +225161,7 @@ function createWrappedHandler(name, handler, server) {
|
|
|
223887
225161
|
requestId: (typeof error === 'object' && error && 'requestId' in error) ? error.requestId : '',
|
|
223888
225162
|
ide: server.ide || process.env.INTEGRATION_IDE || ''
|
|
223889
225163
|
});
|
|
223890
|
-
const mcpVersion = true ? "2.
|
|
225164
|
+
const mcpVersion = true ? "2.28.0" : 0;
|
|
223891
225165
|
const requestIdSuffix = requestId ? `\n🆔 RequestId: ${requestId}` : '';
|
|
223892
225166
|
const enhancedErrorMessage = `${errorMessage}${requestIdSuffix}\n\n📦 CloudBase MCP v${mcpVersion}\n🔗 遇到问题?请复制以下链接到浏览器打开\n即可自动携带错误详情快速创建 GitHub Issue:\n${issueLink}`;
|
|
223893
225167
|
// 创建新的错误对象,保持原有的错误类型但更新消息
|
|
@@ -233844,6 +235118,15 @@ const logger_js_1 = __webpack_require__(13039);
|
|
|
233844
235118
|
const CATEGORY = "NoSQL database";
|
|
233845
235119
|
const COLLECTION_READY_TIMEOUT_MS = 10000;
|
|
233846
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 除外)。`;
|
|
233847
235130
|
/** Convert object values to JSON strings for API calls */
|
|
233848
235131
|
const toJSONString = (v) => typeof v === "object" && v !== null ? JSON.stringify(v) : v;
|
|
233849
235132
|
function delay(ms) {
|
|
@@ -233914,6 +235197,95 @@ function normalizeSortInput(sort) {
|
|
|
233914
235197
|
}
|
|
233915
235198
|
return JSON.stringify(parsed.map((item) => normalizeSortItem(item)));
|
|
233916
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
|
+
}
|
|
233917
235289
|
function withCollectionName(collectionName, payload) {
|
|
233918
235290
|
return {
|
|
233919
235291
|
...payload,
|
|
@@ -234448,7 +235820,9 @@ deleteCollection: 删除集合`),
|
|
|
234448
235820
|
// readNoSqlDatabaseContent
|
|
234449
235821
|
server.registerTool?.("readNoSqlDatabaseContent", {
|
|
234450
235822
|
title: "查询并获取 CloudBase NoSQL 数据库数据记录",
|
|
234451
|
-
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}),不要传字段数组。`,
|
|
234452
235826
|
inputSchema: {
|
|
234453
235827
|
collectionName: zod_1.z.string().describe("集合名称"),
|
|
234454
235828
|
instanceId: zod_1.z
|
|
@@ -234462,7 +235836,9 @@ deleteCollection: 删除集合`),
|
|
|
234462
235836
|
projection: zod_1.z
|
|
234463
235837
|
.union([zod_1.z.object({}).passthrough(), zod_1.z.string()])
|
|
234464
235838
|
.optional()
|
|
234465
|
-
.describe(
|
|
235839
|
+
.describe(`返回字段投影,仅支持对象或对应 JSON 字符串,值只能是 1/0/true/false。` +
|
|
235840
|
+
`合法示例:${PROJECTION_EXAMPLE}(包含)或 ${PROJECTION_EXCLUDE_EXAMPLE}(排除)。` +
|
|
235841
|
+
`不要传 ["name","age"] 这类字段数组,也不要混用包含与排除(_id 除外)。`),
|
|
234466
235842
|
sort: zod_1.z
|
|
234467
235843
|
.union([
|
|
234468
235844
|
zod_1.z.array(zod_1.z
|
|
@@ -234475,7 +235851,11 @@ deleteCollection: 删除集合`),
|
|
|
234475
235851
|
])
|
|
234476
235852
|
.optional()
|
|
234477
235853
|
.describe('排序条件,仅支持数组 [{"key":"createdAt","direction":-1}] 或对应 JSON 字符串。'),
|
|
234478
|
-
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 分页。`),
|
|
234479
235859
|
offset: zod_1.z.number().optional().describe("跳过的记录数"),
|
|
234480
235860
|
},
|
|
234481
235861
|
annotations: {
|
|
@@ -234491,46 +235871,53 @@ deleteCollection: 删除集合`),
|
|
|
234491
235871
|
durationMs: Date.now() - managerStartedAt,
|
|
234492
235872
|
});
|
|
234493
235873
|
const normalizedSort = normalizeSortInput(sort);
|
|
234494
|
-
const
|
|
234495
|
-
|
|
234496
|
-
|
|
234497
|
-
|
|
234498
|
-
|
|
234499
|
-
|
|
234500
|
-
|
|
234501
|
-
|
|
234502
|
-
|
|
234503
|
-
|
|
234504
|
-
|
|
234505
|
-
|
|
234506
|
-
|
|
234507
|
-
|
|
234508
|
-
|
|
234509
|
-
|
|
234510
|
-
const parseStartedAt = Date.now();
|
|
234511
|
-
const documents = normalizeNoSqlDocuments(result.Data);
|
|
234512
|
-
logNoSqlLatency("readNoSqlDatabaseContent", "parseResult", {
|
|
234513
|
-
collectionName,
|
|
234514
|
-
durationMs: Date.now() - parseStartedAt,
|
|
234515
|
-
documentCount: documents.length,
|
|
234516
|
-
});
|
|
234517
|
-
return {
|
|
234518
|
-
content: [
|
|
234519
|
-
{
|
|
234520
|
-
type: "text",
|
|
234521
|
-
text: JSON.stringify(withCollectionName(collectionName, {
|
|
234522
|
-
success: true,
|
|
234523
|
-
requestId: result.RequestId,
|
|
234524
|
-
data: documents,
|
|
234525
|
-
total: typeof result.Pager?.Total === "number"
|
|
234526
|
-
? result.Pager.Total
|
|
234527
|
-
: documents.length,
|
|
234528
|
-
pager: result.Pager,
|
|
234529
|
-
message: "文档查询成功",
|
|
234530
|
-
}), 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,
|
|
234531
235890
|
},
|
|
234532
|
-
|
|
234533
|
-
|
|
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
|
+
}
|
|
234534
235921
|
});
|
|
234535
235922
|
// writeNoSqlDatabaseContent
|
|
234536
235923
|
server.registerTool?.("writeNoSqlDatabaseContent", {
|
|
@@ -239714,6 +241101,7 @@ exports.CloudBaseError = CloudBaseError;
|
|
|
239714
241101
|
"use strict";
|
|
239715
241102
|
|
|
239716
241103
|
Object.defineProperty(exports, "__esModule", ({ value: true }));
|
|
241104
|
+
exports.validateUserRegoContent = validateUserRegoContent;
|
|
239717
241105
|
exports.registerPermissionTools = registerPermissionTools;
|
|
239718
241106
|
const zod_1 = __webpack_require__(7552);
|
|
239719
241107
|
const cloudbase_manager_js_1 = __webpack_require__(3431);
|
|
@@ -239725,6 +241113,9 @@ const QUERY_PERMISSION_ACTIONS = [
|
|
|
239725
241113
|
"getRole",
|
|
239726
241114
|
"listUsers",
|
|
239727
241115
|
"getUser",
|
|
241116
|
+
// Align with CLI `tcb policy list/get` (OPA gateway authz)
|
|
241117
|
+
"listPolicy",
|
|
241118
|
+
"getPolicy",
|
|
239728
241119
|
];
|
|
239729
241120
|
const MANAGE_PERMISSION_ACTIONS = [
|
|
239730
241121
|
"updateResourcePermission",
|
|
@@ -239738,7 +241129,14 @@ const MANAGE_PERMISSION_ACTIONS = [
|
|
|
239738
241129
|
"createUser",
|
|
239739
241130
|
"updateUser",
|
|
239740
241131
|
"deleteUsers",
|
|
241132
|
+
// Align with CLI `tcb policy set` (OPA Rego; disables legacy gateway auth)
|
|
241133
|
+
"setPolicy",
|
|
239741
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"];
|
|
239742
241140
|
function buildWriteVerificationHint(resourceId) {
|
|
239743
241141
|
return `对于 ${resourceId} 这类有后端权限控制的集合,前端调用 .doc(id).update() / .doc(id).remove() 后,不能只看是否没有抛异常。请显式检查返回结果中的 updated / deleted 是否大于 0;如果 result.code、result.message 存在,或 updated / deleted 为 0,要把它当作真实失败并向上抛错。`;
|
|
239744
241142
|
}
|
|
@@ -239777,10 +241175,32 @@ function isPostgresqlPermissionApiUnsupported(error) {
|
|
|
239777
241175
|
const message = error instanceof Error ? error.message : String(error);
|
|
239778
241176
|
return /does not support PostgreSQL type environments/i.test(message);
|
|
239779
241177
|
}
|
|
239780
|
-
const AUTHZ_USER_REGO_KEY = "authz.user.rego";
|
|
239781
241178
|
function looksLikeUserRego(value) {
|
|
239782
241179
|
return /^\s*package\s+authz\.user\b/m.test(value);
|
|
239783
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
|
+
}
|
|
239784
241204
|
/** Detect legacy function securityRule shapes that mean "public invoke". */
|
|
239785
241205
|
function isPublicFunctionInvokeRule(securityRule) {
|
|
239786
241206
|
if (!securityRule || securityRule.trim() === "") {
|
|
@@ -239852,29 +241272,38 @@ function resolveFunctionAuthzRegoInput(securityRule, resourceId) {
|
|
|
239852
241272
|
`2) permission="CUSTOM" with securityRule='{"invoke":true}' to generate a public-functions allow policy.\n` +
|
|
239853
241273
|
`See https://docs.cloudbase.net/cli-v1/policy/management`);
|
|
239854
241274
|
}
|
|
239855
|
-
async function
|
|
241275
|
+
async function describeEnvAuthzConfigByKey(cloudbase, key = AUTHZ_USER_REGO_KEY) {
|
|
239856
241276
|
if (!cloudbase?.permission?.describeEnvAuthzConfig) {
|
|
239857
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.");
|
|
239858
241278
|
}
|
|
239859
|
-
const result = await cloudbase.permission.describeEnvAuthzConfig({
|
|
239860
|
-
key: AUTHZ_USER_REGO_KEY,
|
|
239861
|
-
});
|
|
241279
|
+
const result = await cloudbase.permission.describeEnvAuthzConfig({ key });
|
|
239862
241280
|
const value = typeof result?.Item?.Value === "string"
|
|
239863
241281
|
? result.Item.Value
|
|
239864
241282
|
: typeof result?.Value === "string"
|
|
239865
241283
|
? result.Value
|
|
239866
241284
|
: "";
|
|
239867
|
-
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 };
|
|
239868
241290
|
}
|
|
239869
241291
|
async function modifyEnvAuthzUserRego(cloudbase, value) {
|
|
239870
241292
|
if (!cloudbase?.permission?.modifyEnvAuthzConfig) {
|
|
239871
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.");
|
|
239872
241294
|
}
|
|
241295
|
+
const validated = validateUserRegoContent(value);
|
|
239873
241296
|
return cloudbase.permission.modifyEnvAuthzConfig({
|
|
239874
241297
|
key: AUTHZ_USER_REGO_KEY,
|
|
239875
|
-
value,
|
|
241298
|
+
value: validated,
|
|
239876
241299
|
});
|
|
239877
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
|
+
}
|
|
239878
241307
|
async function describeResourcePermissionWithFunctionPgFallback(options) {
|
|
239879
241308
|
const { cloudbase, envId, resourceType, resources } = options;
|
|
239880
241309
|
try {
|
|
@@ -240108,7 +241537,7 @@ function registerPermissionTools(server) {
|
|
|
240108
241537
|
};
|
|
240109
241538
|
server.registerTool?.("queryPermissions", {
|
|
240110
241539
|
title: "查询 CloudBase 权限与用户配置",
|
|
240111
|
-
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`。",
|
|
240112
241541
|
inputSchema: {
|
|
240113
241542
|
action: zod_1.z.enum(QUERY_PERMISSION_ACTIONS),
|
|
240114
241543
|
resourceType: zod_1.z
|
|
@@ -240123,13 +241552,21 @@ function registerPermissionTools(server) {
|
|
|
240123
241552
|
username: zod_1.z.string().optional(),
|
|
240124
241553
|
pageNo: zod_1.z.number().optional(),
|
|
240125
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`。"),
|
|
240126
241563
|
},
|
|
240127
241564
|
annotations: {
|
|
240128
241565
|
readOnlyHint: true,
|
|
240129
241566
|
openWorldHint: true,
|
|
240130
241567
|
category: "permissions",
|
|
240131
241568
|
},
|
|
240132
|
-
}, 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 () => {
|
|
240133
241570
|
const envId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
|
|
240134
241571
|
const cloudbase = await getManager();
|
|
240135
241572
|
switch (action) {
|
|
@@ -240275,11 +241712,43 @@ function registerPermissionTools(server) {
|
|
|
240275
241712
|
raw: result,
|
|
240276
241713
|
}, "应用用户详情查询成功");
|
|
240277
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
|
+
}
|
|
240278
241747
|
}
|
|
240279
241748
|
}));
|
|
240280
241749
|
server.registerTool?.("managePermissions", {
|
|
240281
241750
|
title: "管理 CloudBase 权限与用户配置",
|
|
240282
|
-
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\"`。",
|
|
240283
241752
|
inputSchema: {
|
|
240284
241753
|
action: zod_1.z.enum(MANAGE_PERMISSION_ACTIONS),
|
|
240285
241754
|
resourceType: zod_1.z
|
|
@@ -240310,6 +241779,14 @@ function registerPermissionTools(server) {
|
|
|
240310
241779
|
username: zod_1.z.string().optional(),
|
|
240311
241780
|
password: zod_1.z.string().optional(),
|
|
240312
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 确认提示)。"),
|
|
240313
241790
|
},
|
|
240314
241791
|
annotations: {
|
|
240315
241792
|
readOnlyHint: false,
|
|
@@ -240318,7 +241795,7 @@ function registerPermissionTools(server) {
|
|
|
240318
241795
|
openWorldHint: true,
|
|
240319
241796
|
category: "permissions",
|
|
240320
241797
|
},
|
|
240321
|
-
}, 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 () => {
|
|
240322
241799
|
const envId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
|
|
240323
241800
|
const cloudbase = await getManager();
|
|
240324
241801
|
const normalizedPolicies = normalizeRecordArray(policies, "policies");
|
|
@@ -240499,6 +241976,26 @@ function registerPermissionTools(server) {
|
|
|
240499
241976
|
raw: result,
|
|
240500
241977
|
}, "应用用户删除成功");
|
|
240501
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
|
+
}
|
|
240502
241999
|
}
|
|
240503
242000
|
}));
|
|
240504
242001
|
}
|
|
@@ -241107,7 +242604,7 @@ function registerSetupTools(server) {
|
|
|
241107
242604
|
server.registerTool("downloadTemplate", {
|
|
241108
242605
|
title: "下载项目模板",
|
|
241109
242606
|
description: `自动下载并部署CloudBase项目模板。
|
|
241110
|
-
**Note**: Call this tool when the user requests to create a new project using a CloudBase template.\n\n支持的模板:\n- react: React + CloudBase 全栈应用模板\n- vue: Vue + CloudBase 全栈应用模板\n- miniprogram: 微信小程序 + 云开发模板 \n- uniapp: UniApp + CloudBase 跨端应用模板\n- rules: 只包含AI编辑器配置文件(包含Cursor、WindSurf、CodeBuddy等所有主流编辑器配置),适合在已有项目中补充AI编辑器配置\n\n支持的IDE类型:\n- all: 下载所有IDE配置\n- cursor: Cursor AI编辑器\n- 其他IDE类型见下方列表\n\n注意:如果未传入 ide 参数且无法从环境变量检测到 IDE,将提示错误并要求传入 ide 参数\n- windsurf: WindSurf AI编辑器\n- codebuddy: CodeBuddy AI编辑器\n- claude-code: Claude Code AI编辑器\n- cline: Cline AI编辑器\n- gemini-cli: Gemini CLI\n- opencode: OpenCode AI编辑器\n- qwen-code: 通义灵码\n- baidu-comate: 百度Comate\n- openai-codex-cli: OpenAI Codex CLI\n- augment-code: Augment Code\n- github-copilot: GitHub Copilot\n- roocode: RooCode AI编辑器\n- tongyi-lingma: 通义灵码\n- trae: Trae AI编辑器\n- qoder: Qoder AI编辑器\n- antigravity: Google Antigravity AI编辑器\n- vscode: Visual Studio Code\n- kiro: Kiro AI编辑器\n- aider: Aider AI编辑器\n\n特别说明:\n- rules 模板会自动包含当前 mcp 版本号信息(版本号:${ true ? "2.
|
|
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)`,
|
|
241111
242608
|
inputSchema: {
|
|
241112
242609
|
template: zod_1.z
|
|
241113
242610
|
.enum(["react", "vue", "miniprogram", "uniapp", "rules"])
|
|
@@ -242537,7 +244034,7 @@ exports.getLoginState = getLoginState;
|
|
|
242537
244034
|
exports.logout = logout;
|
|
242538
244035
|
const toolbox_1 = __webpack_require__(25901);
|
|
242539
244036
|
const logger_js_1 = __webpack_require__(13039);
|
|
242540
|
-
const
|
|
244037
|
+
const site_map_js_1 = __webpack_require__(68107);
|
|
242541
244038
|
const auth = toolbox_1.AuthSupervisor.getInstance({});
|
|
242542
244039
|
const authProgressState = {
|
|
242543
244040
|
status: "IDLE",
|
|
@@ -242786,6 +244283,98 @@ function resetAuthProgressState() {
|
|
|
242786
244283
|
lastError: undefined,
|
|
242787
244284
|
});
|
|
242788
244285
|
}
|
|
244286
|
+
const LEGACY_SITE = "domestic";
|
|
244287
|
+
function isSlottedCredential(value) {
|
|
244288
|
+
if (!value || typeof value !== "object") {
|
|
244289
|
+
return false;
|
|
244290
|
+
}
|
|
244291
|
+
return "domestic" in value || "intl" in value;
|
|
244292
|
+
}
|
|
244293
|
+
async function readStoredCredentialRaw() {
|
|
244294
|
+
return toolbox_1.authStore.get("credential");
|
|
244295
|
+
}
|
|
244296
|
+
/**
|
|
244297
|
+
* 读取指定 site 槽位的原始凭证;旧格式(单槽 flat)视为 domestic 槽位。
|
|
244298
|
+
*/
|
|
244299
|
+
async function readSiteCredentialRaw(site) {
|
|
244300
|
+
const raw = await readStoredCredentialRaw();
|
|
244301
|
+
if (!raw) {
|
|
244302
|
+
return undefined;
|
|
244303
|
+
}
|
|
244304
|
+
if (isSlottedCredential(raw)) {
|
|
244305
|
+
return raw[site];
|
|
244306
|
+
}
|
|
244307
|
+
return site === LEGACY_SITE ? raw : undefined;
|
|
244308
|
+
}
|
|
244309
|
+
/**
|
|
244310
|
+
* 将凭证写入指定 site 槽位,保留其他槽位数据。
|
|
244311
|
+
* base 缺省时读取当前存储;旧单槽数据会被迁移为 domestic 槽位(写回时升级分槽)。
|
|
244312
|
+
*/
|
|
244313
|
+
async function writeSiteCredential(site, credential, base) {
|
|
244314
|
+
const current = base ?? (await readStoredCredentialRaw());
|
|
244315
|
+
const slotted = current && isSlottedCredential(current)
|
|
244316
|
+
? { ...current }
|
|
244317
|
+
: { domestic: current ?? {} };
|
|
244318
|
+
slotted[site] = credential ?? {};
|
|
244319
|
+
await toolbox_1.authStore.set("credential", slotted);
|
|
244320
|
+
}
|
|
244321
|
+
/**
|
|
244322
|
+
* 确保存储已为分槽格式并返回槽位快照。
|
|
244323
|
+
* 用于登录前迁移旧单槽数据,避免 @cloudbase/toolbox 内部误命中旧凭证而跳过新站点登录。
|
|
244324
|
+
*/
|
|
244325
|
+
async function ensureSlottedCredential() {
|
|
244326
|
+
const raw = await readStoredCredentialRaw();
|
|
244327
|
+
if (raw && isSlottedCredential(raw)) {
|
|
244328
|
+
return { ...raw };
|
|
244329
|
+
}
|
|
244330
|
+
const slotted = { domestic: raw ?? {} };
|
|
244331
|
+
await toolbox_1.authStore.set("credential", slotted);
|
|
244332
|
+
return slotted;
|
|
244333
|
+
}
|
|
244334
|
+
function isSlotTokenExpired(credential, gap = 120) {
|
|
244335
|
+
return (!!credential.accessTokenExpired &&
|
|
244336
|
+
Number(credential.accessTokenExpired) < Date.now() + gap * 1000);
|
|
244337
|
+
}
|
|
244338
|
+
/**
|
|
244339
|
+
* 读取并解析指定 site 的登录态,必要时走 refreshToken 续期(镜像 @cloudbase/toolbox 行为)。
|
|
244340
|
+
*/
|
|
244341
|
+
async function resolveSiteLoginState(site) {
|
|
244342
|
+
const raw = await readSiteCredentialRaw(site);
|
|
244343
|
+
if (!raw) {
|
|
244344
|
+
return null;
|
|
244345
|
+
}
|
|
244346
|
+
const credential = (0, toolbox_1.resolveCredential)(raw);
|
|
244347
|
+
if (!credential?.secretId || !credential?.secretKey) {
|
|
244348
|
+
return null;
|
|
244349
|
+
}
|
|
244350
|
+
if (credential.refreshToken) {
|
|
244351
|
+
if (!isSlotTokenExpired(credential)) {
|
|
244352
|
+
return credential;
|
|
244353
|
+
}
|
|
244354
|
+
if (Date.now() < Number(credential.expired)) {
|
|
244355
|
+
try {
|
|
244356
|
+
const refreshed = await (0, toolbox_1.refreshTmpToken)(credential);
|
|
244357
|
+
await writeSiteCredential(site, refreshed ?? {});
|
|
244358
|
+
const resolved = (0, toolbox_1.resolveCredential)(refreshed ?? {});
|
|
244359
|
+
return resolved?.secretId ? resolved : null;
|
|
244360
|
+
}
|
|
244361
|
+
catch (e) {
|
|
244362
|
+
const code = e?.code;
|
|
244363
|
+
if (code === "AUTH_FAIL" || code === "InternalError.GetRoleError") {
|
|
244364
|
+
return null;
|
|
244365
|
+
}
|
|
244366
|
+
throw e;
|
|
244367
|
+
}
|
|
244368
|
+
}
|
|
244369
|
+
return null;
|
|
244370
|
+
}
|
|
244371
|
+
return credential;
|
|
244372
|
+
}
|
|
244373
|
+
function isUsableCredential(value) {
|
|
244374
|
+
return (!!value &&
|
|
244375
|
+
typeof value === "object" &&
|
|
244376
|
+
Object.keys(value).length > 0);
|
|
244377
|
+
}
|
|
242789
244378
|
async function peekLoginState(options) {
|
|
242790
244379
|
const envVarLoginState = normalizeLoginStateFromEnvVars(options);
|
|
242791
244380
|
if (envVarLoginState) {
|
|
@@ -242807,14 +244396,25 @@ async function peekLoginState(options) {
|
|
|
242807
244396
|
(0, logger_js_1.debug)("loginByApiSecret");
|
|
242808
244397
|
return envVarLoginState;
|
|
242809
244398
|
}
|
|
242810
|
-
//
|
|
242811
|
-
|
|
244399
|
+
// 按 site 读取分槽凭证(缺省按 TCB_SITE/region 解析站点,默认 domestic)
|
|
244400
|
+
const site = (0, site_map_js_1.normalizeSite)(options?.site) ?? (0, site_map_js_1.resolveSite)(options?.region, process.env.TCB_SITE);
|
|
244401
|
+
const slotLoginState = await resolveSiteLoginState(site);
|
|
244402
|
+
if (slotLoginState) {
|
|
244403
|
+
return slotLoginState;
|
|
244404
|
+
}
|
|
244405
|
+
// 兼容旧单槽数据(视为 domestic),走 toolbox 读取/续期
|
|
244406
|
+
if (site === LEGACY_SITE) {
|
|
244407
|
+
return auth.getLoginState();
|
|
244408
|
+
}
|
|
244409
|
+
return null;
|
|
242812
244410
|
}
|
|
242813
244411
|
async function ensureLogin(options) {
|
|
242814
244412
|
(0, logger_js_1.debug)("TENCENTCLOUD_SECRETID", { hasSecretId: !!process.env.TENCENTCLOUD_SECRETID });
|
|
242815
244413
|
(0, logger_js_1.debug)("CLOUDBASE_API_KEY", { hasApiKey: !!getCloudBaseApiKeyFromEnv() });
|
|
242816
244414
|
const loginState = await peekLoginState({
|
|
242817
244415
|
ignoreEnvVars: options?.ignoreEnvVars,
|
|
244416
|
+
site: options?.site,
|
|
244417
|
+
region: options?.region,
|
|
242818
244418
|
});
|
|
242819
244419
|
if (!loginState) {
|
|
242820
244420
|
const resolvedAuthOptions = resolveAuthOptions({
|
|
@@ -242830,21 +244430,31 @@ async function ensureLogin(options) {
|
|
|
242830
244430
|
throw new Error(validationError);
|
|
242831
244431
|
}
|
|
242832
244432
|
const mode = resolvedAuthOptions.authMode;
|
|
244433
|
+
// 按显式 site > TCB_SITE > region 映射表解析站点(ap-singapore 歧义默认 intl,兼容既有国际站行为)
|
|
244434
|
+
const resolvedSite = (0, site_map_js_1.resolveSite)(options?.region, options?.site ?? process.env.TCB_SITE);
|
|
242833
244435
|
const loginOptions = { flow: mode };
|
|
242834
244436
|
if (mode === "web") {
|
|
242835
244437
|
loginOptions.getAuthUrl =
|
|
242836
|
-
options?.fromCloudBaseLoginPage &&
|
|
244438
|
+
options?.fromCloudBaseLoginPage && resolvedSite === "domestic"
|
|
242837
244439
|
? (url) => {
|
|
242838
244440
|
const separator = url.includes("?") ? "&" : "?";
|
|
242839
244441
|
const urlWithParam = `${url}${separator}allowNoEnv=true`;
|
|
242840
|
-
return `https
|
|
244442
|
+
return `https://${site_map_js_1.SITE_REGION_MAP.domestic.authHost}/login?_redirect_uri=${encodeURIComponent(urlWithParam)}`;
|
|
242841
244443
|
}
|
|
242842
244444
|
: (url) => {
|
|
242843
|
-
|
|
242844
|
-
|
|
244445
|
+
let finalUrl = url;
|
|
244446
|
+
if (resolvedSite === "intl") {
|
|
244447
|
+
try {
|
|
244448
|
+
const parsed = new URL(url);
|
|
244449
|
+
parsed.host = site_map_js_1.SITE_REGION_MAP.intl.authHost;
|
|
244450
|
+
finalUrl = parsed.toString();
|
|
244451
|
+
}
|
|
244452
|
+
catch {
|
|
244453
|
+
finalUrl = url.replace("cloud.tencent.com", "tencentcloud.com");
|
|
244454
|
+
}
|
|
242845
244455
|
}
|
|
242846
|
-
const separator =
|
|
242847
|
-
return `${
|
|
244456
|
+
const separator = finalUrl.includes("?") ? "&" : "?";
|
|
244457
|
+
return `${finalUrl}${separator}allowNoEnv=true`;
|
|
242848
244458
|
};
|
|
242849
244459
|
}
|
|
242850
244460
|
else {
|
|
@@ -242865,8 +244475,23 @@ async function ensureLogin(options) {
|
|
|
242865
244475
|
}
|
|
242866
244476
|
}
|
|
242867
244477
|
(0, logger_js_1.debug)("beforeloginByWebAuth", { loginOptions });
|
|
244478
|
+
// 登录前迁移旧单槽数据为分槽格式,避免 toolbox 内部命中旧凭证而跳过新站点登录
|
|
244479
|
+
const slotsBefore = await ensureSlottedCredential();
|
|
242868
244480
|
try {
|
|
242869
|
-
await auth.loginByWebAuth(loginOptions);
|
|
244481
|
+
const loginResult = await auth.loginByWebAuth(loginOptions);
|
|
244482
|
+
// toolbox 将新凭证写入 flat 'credential',将其并入对应 site 槽位,保留其他槽位
|
|
244483
|
+
const newRaw = await readStoredCredentialRaw();
|
|
244484
|
+
let credentialToSlot = loginResult;
|
|
244485
|
+
if (isSlottedCredential(newRaw)) {
|
|
244486
|
+
credentialToSlot = newRaw[resolvedSite] ?? newRaw.domestic;
|
|
244487
|
+
}
|
|
244488
|
+
else if (newRaw) {
|
|
244489
|
+
credentialToSlot = newRaw;
|
|
244490
|
+
}
|
|
244491
|
+
if (isUsableCredential(credentialToSlot)) {
|
|
244492
|
+
const merged = { ...slotsBefore, [resolvedSite]: credentialToSlot };
|
|
244493
|
+
await toolbox_1.authStore.set("credential", merged);
|
|
244494
|
+
}
|
|
242870
244495
|
resolveAuthProgressState();
|
|
242871
244496
|
}
|
|
242872
244497
|
catch (error) {
|
|
@@ -242875,6 +244500,8 @@ async function ensureLogin(options) {
|
|
|
242875
244500
|
}
|
|
242876
244501
|
const loginState = await peekLoginState({
|
|
242877
244502
|
ignoreEnvVars: options?.ignoreEnvVars,
|
|
244503
|
+
site: options?.site,
|
|
244504
|
+
region: options?.region,
|
|
242878
244505
|
});
|
|
242879
244506
|
(0, logger_js_1.debug)("loginByWebAuth", { mode, hasLoginState: !!loginState });
|
|
242880
244507
|
return loginState;
|
|
@@ -242887,11 +244514,19 @@ async function ensureLogin(options) {
|
|
|
242887
244514
|
async function getLoginState(options) {
|
|
242888
244515
|
return ensureLogin(options);
|
|
242889
244516
|
}
|
|
242890
|
-
async function logout() {
|
|
242891
|
-
const
|
|
242892
|
-
const
|
|
244517
|
+
async function logout(options) {
|
|
244518
|
+
const site = (0, site_map_js_1.normalizeSite)(options?.site) ?? "domestic";
|
|
244519
|
+
const raw = await readStoredCredentialRaw();
|
|
244520
|
+
if (raw && isSlottedCredential(raw)) {
|
|
244521
|
+
const slotted = { ...raw };
|
|
244522
|
+
delete slotted[site];
|
|
244523
|
+
await toolbox_1.authStore.set("credential", slotted);
|
|
244524
|
+
}
|
|
244525
|
+
else if (site === LEGACY_SITE) {
|
|
244526
|
+
const cwd = process.env.WORKSPACE_FOLDER_PATHS || process.cwd();
|
|
244527
|
+
await auth.logout({ cwd });
|
|
244528
|
+
}
|
|
242893
244529
|
resetAuthProgressState();
|
|
242894
|
-
return result;
|
|
242895
244530
|
}
|
|
242896
244531
|
|
|
242897
244532
|
|
|
@@ -264193,7 +265828,10 @@ function registerGatewayTools(server) {
|
|
|
264193
265828
|
};
|
|
264194
265829
|
const pickUsableDefaultDomain = (domains) => {
|
|
264195
265830
|
const candidates = domains.filter((item) => item.IsDefault === true && item.Domain);
|
|
264196
|
-
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") ??
|
|
264197
265835
|
candidates.find((item) => item.Enable !== false) ??
|
|
264198
265836
|
candidates[0]);
|
|
264199
265837
|
};
|
|
@@ -275020,7 +276658,6 @@ function shouldRegisterTool(toolName) {
|
|
|
275020
276658
|
'createFunction', // also involves local files
|
|
275021
276659
|
// Download tools - local file downloads
|
|
275022
276660
|
'downloadTemplate',
|
|
275023
|
-
'downloadRemoteFile',
|
|
275024
276661
|
// Setup tools - local config file operations
|
|
275025
276662
|
'setupEnvironmentId',
|
|
275026
276663
|
// CloudRun tools - local file operations
|