@cloudbase/cloudbase-mcp 2.27.0 → 2.28.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/README.zh-CN.md +1 -0
- package/dist/cli.cjs +5 -5
- package/dist/index.cjs +1480 -104
- package/dist/index.js +1511 -135
- package/package.json +4 -2
- package/server.json +60 -0
package/dist/index.js
CHANGED
|
@@ -32,8 +32,17 @@ import * as __WEBPACK_EXTERNAL_MODULE_node_fs_75ed2103__ from "node:fs";
|
|
|
32
32
|
|
|
33
33
|
|
|
34
34
|
Object.defineProperty(exports, "__esModule", ({ value: true }));
|
|
35
|
-
exports.DEFAULT_CREATE_ENV_RESOURCES = exports.CREATE_ENV_RESOURCE_VALUES = void 0;
|
|
35
|
+
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;
|
|
36
36
|
exports.resolveCreateEnvResources = resolveCreateEnvResources;
|
|
37
|
+
exports.resolveEnvUsageModules = resolveEnvUsageModules;
|
|
38
|
+
exports.extractAccountCircleDate = extractAccountCircleDate;
|
|
39
|
+
exports.resolveEnvUsageDateRange = resolveEnvUsageDateRange;
|
|
40
|
+
exports.formatEnvMetricTime = formatEnvMetricTime;
|
|
41
|
+
exports.resolveEnvMetricName = resolveEnvMetricName;
|
|
42
|
+
exports.resolveEnvMetricPeriod = resolveEnvMetricPeriod;
|
|
43
|
+
exports.resolveEnvMetricTimeRange = resolveEnvMetricTimeRange;
|
|
44
|
+
exports.resolveEnvMetricResourceId = resolveEnvMetricResourceId;
|
|
45
|
+
exports.summarizeEnvMetricCurve = summarizeEnvMetricCurve;
|
|
37
46
|
exports.simplifyEnvList = simplifyEnvList;
|
|
38
47
|
exports.isUsableNoSqlDatabaseEntry = isUsableNoSqlDatabaseEntry;
|
|
39
48
|
exports.registerEnvTools = registerEnvTools;
|
|
@@ -65,6 +74,245 @@ function resolveCreateEnvResources(resources) {
|
|
|
65
74
|
}
|
|
66
75
|
return [...exports.DEFAULT_CREATE_ENV_RESOURCES];
|
|
67
76
|
}
|
|
77
|
+
/**
|
|
78
|
+
* Resource-usage modules aligned with tcb CLI `USAGE_MODULES`
|
|
79
|
+
* (`tcb env usage` / `tcb env info --type`).
|
|
80
|
+
*/
|
|
81
|
+
exports.ENV_USAGE_MODULE_VALUES = [
|
|
82
|
+
"FLEXDB",
|
|
83
|
+
"TDSQL",
|
|
84
|
+
"SCF",
|
|
85
|
+
"EKS",
|
|
86
|
+
"COS",
|
|
87
|
+
"AI",
|
|
88
|
+
"HOSTING",
|
|
89
|
+
"Auth",
|
|
90
|
+
"APIInvocation",
|
|
91
|
+
"HTTPInvocation",
|
|
92
|
+
"VM",
|
|
93
|
+
"Workflow",
|
|
94
|
+
"Other",
|
|
95
|
+
];
|
|
96
|
+
const ENV_USAGE_MODULE_SET = new Set(exports.ENV_USAGE_MODULE_VALUES);
|
|
97
|
+
const ENV_USAGE_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
|
|
98
|
+
function resolveEnvUsageModules(type) {
|
|
99
|
+
if (!Array.isArray(type) || type.length === 0) {
|
|
100
|
+
return [...exports.ENV_USAGE_MODULE_VALUES];
|
|
101
|
+
}
|
|
102
|
+
const normalized = type
|
|
103
|
+
.map((item) => (typeof item === "string" ? item.trim() : ""))
|
|
104
|
+
.filter(Boolean);
|
|
105
|
+
const invalid = normalized.filter((item) => !ENV_USAGE_MODULE_SET.has(item));
|
|
106
|
+
if (invalid.length > 0) {
|
|
107
|
+
throw new Error(`无效的用量模块 type: ${invalid.join(", ")}。可选值:${exports.ENV_USAGE_MODULE_VALUES.join(", ")}`);
|
|
108
|
+
}
|
|
109
|
+
return normalized;
|
|
110
|
+
}
|
|
111
|
+
function extractAccountCircleDate(rawTime) {
|
|
112
|
+
if (typeof rawTime !== "string" || rawTime.trim().length === 0) {
|
|
113
|
+
return undefined;
|
|
114
|
+
}
|
|
115
|
+
const datePart = rawTime.trim().split(/\s+/)[0];
|
|
116
|
+
return ENV_USAGE_DATE_RE.test(datePart) ? datePart : undefined;
|
|
117
|
+
}
|
|
118
|
+
function normalizeUsageDateInput(value) {
|
|
119
|
+
return typeof value === "string" && value.trim().length > 0
|
|
120
|
+
? value.trim()
|
|
121
|
+
: undefined;
|
|
122
|
+
}
|
|
123
|
+
function resolveEnvUsageDateRange(options) {
|
|
124
|
+
const startFromParams = normalizeUsageDateInput(options.startDate);
|
|
125
|
+
const endFromParams = normalizeUsageDateInput(options.endDate);
|
|
126
|
+
if (startFromParams || endFromParams) {
|
|
127
|
+
if (!startFromParams || !endFromParams) {
|
|
128
|
+
throw new Error("查询资源用量时 startDate 与 endDate 必须同时提供,格式为 YYYY-MM-DD。");
|
|
129
|
+
}
|
|
130
|
+
if (!ENV_USAGE_DATE_RE.test(startFromParams) || !ENV_USAGE_DATE_RE.test(endFromParams)) {
|
|
131
|
+
throw new Error("startDate / endDate 格式必须为 YYYY-MM-DD。");
|
|
132
|
+
}
|
|
133
|
+
if (startFromParams > endFromParams) {
|
|
134
|
+
throw new Error("startDate 不能晚于 endDate。");
|
|
135
|
+
}
|
|
136
|
+
return {
|
|
137
|
+
startDate: startFromParams,
|
|
138
|
+
endDate: endFromParams,
|
|
139
|
+
dateSource: "params",
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
const startDate = extractAccountCircleDate(options.accountCircle?.StartTime);
|
|
143
|
+
const endDate = extractAccountCircleDate(options.accountCircle?.EndTime);
|
|
144
|
+
if (!startDate || !endDate) {
|
|
145
|
+
throw new Error("无法从计费周期推导用量日期范围。请显式传入 startDate/endDate(YYYY-MM-DD),或确认环境计费周期可用。");
|
|
146
|
+
}
|
|
147
|
+
return { startDate, endDate, dateSource: "accountCircle" };
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Monitor metric names for queryEnv(action=metrics).
|
|
151
|
+
* Subset of TCB DescribeCurveData MetricName from the CloudBase monitor catalog
|
|
152
|
+
* (gateway/env QPS, functions, NoSQL, MySQL, CloudRun).
|
|
153
|
+
*/
|
|
154
|
+
exports.ENV_METRIC_NAME_VALUES = [
|
|
155
|
+
"GatewayTraceEnvQPS",
|
|
156
|
+
"EnvQPSAll",
|
|
157
|
+
"FunctionInvocation",
|
|
158
|
+
"FunctionError",
|
|
159
|
+
"FunctionTimeout",
|
|
160
|
+
"FunctionThrottle",
|
|
161
|
+
"FunctionDuration",
|
|
162
|
+
"FunctionConcurrentExecutions",
|
|
163
|
+
"DbRead",
|
|
164
|
+
"DbWrite",
|
|
165
|
+
"DbSizepkg",
|
|
166
|
+
"MysqlCpuUsageRate",
|
|
167
|
+
"MysqlMemoryUse",
|
|
168
|
+
"MysqlStorageUsage",
|
|
169
|
+
"MysqlQps",
|
|
170
|
+
"MysqlSlowQueries",
|
|
171
|
+
"MysqlDbConnections",
|
|
172
|
+
"TkeCpuUsedService",
|
|
173
|
+
"TkeMemUsedService",
|
|
174
|
+
"TkeQPSService",
|
|
175
|
+
"TkeHttpErrorService",
|
|
176
|
+
"TkeInvokeNumService",
|
|
177
|
+
];
|
|
178
|
+
exports.ENV_METRIC_PERIOD_VALUES = [300, 3600, 86400];
|
|
179
|
+
/** Console default ResourceID for environment-level gateway QPS. */
|
|
180
|
+
exports.GATEWAY_ENV_QPS_DEFAULT_RESOURCE_ID = "all|:|all|:|all|:|all";
|
|
181
|
+
const ENV_METRIC_NAME_SET = new Set(exports.ENV_METRIC_NAME_VALUES);
|
|
182
|
+
const ENV_METRIC_PERIOD_SET = new Set(exports.ENV_METRIC_PERIOD_VALUES);
|
|
183
|
+
const ENV_METRICS_REQUIRING_RESOURCE_ID = new Set([
|
|
184
|
+
"TkeCpuUsedService",
|
|
185
|
+
"TkeMemUsedService",
|
|
186
|
+
"TkeQPSService",
|
|
187
|
+
"TkeHttpErrorService",
|
|
188
|
+
"TkeInvokeNumService",
|
|
189
|
+
]);
|
|
190
|
+
const ENV_METRIC_TIME_RE = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/;
|
|
191
|
+
const ENV_METRIC_MIN_RANGE_MS = 5 * 60 * 1000;
|
|
192
|
+
function padMetricTimeUnit(value) {
|
|
193
|
+
return value.toString().padStart(2, "0");
|
|
194
|
+
}
|
|
195
|
+
function formatEnvMetricTime(date) {
|
|
196
|
+
return `${date.getFullYear()}-${padMetricTimeUnit(date.getMonth() + 1)}-${padMetricTimeUnit(date.getDate())} ${padMetricTimeUnit(date.getHours())}:${padMetricTimeUnit(date.getMinutes())}:${padMetricTimeUnit(date.getSeconds())}`;
|
|
197
|
+
}
|
|
198
|
+
function resolveEnvMetricName(metricName) {
|
|
199
|
+
const normalized = typeof metricName === "string" && metricName.trim().length > 0
|
|
200
|
+
? metricName.trim()
|
|
201
|
+
: undefined;
|
|
202
|
+
if (!normalized) {
|
|
203
|
+
throw new Error(`查询监控指标时 metricName 为必填参数。可选值:${exports.ENV_METRIC_NAME_VALUES.join(", ")}`);
|
|
204
|
+
}
|
|
205
|
+
if (!ENV_METRIC_NAME_SET.has(normalized)) {
|
|
206
|
+
throw new Error(`无效的 metricName: ${normalized}。可选值:${exports.ENV_METRIC_NAME_VALUES.join(", ")}`);
|
|
207
|
+
}
|
|
208
|
+
return normalized;
|
|
209
|
+
}
|
|
210
|
+
function resolveEnvMetricPeriod(period) {
|
|
211
|
+
if (period === undefined || period === null || period === "") {
|
|
212
|
+
return undefined;
|
|
213
|
+
}
|
|
214
|
+
const numericPeriod = typeof period === "number"
|
|
215
|
+
? period
|
|
216
|
+
: typeof period === "string" && /^\d+$/.test(period.trim())
|
|
217
|
+
? Number(period.trim())
|
|
218
|
+
: Number.NaN;
|
|
219
|
+
if (!ENV_METRIC_PERIOD_SET.has(numericPeriod)) {
|
|
220
|
+
throw new Error(`period 仅支持 300、3600、86400(秒)。当前值:${String(period)}`);
|
|
221
|
+
}
|
|
222
|
+
return numericPeriod;
|
|
223
|
+
}
|
|
224
|
+
function resolveEnvMetricTimeRange(options) {
|
|
225
|
+
const startFromParams = typeof options.startTime === "string" && options.startTime.trim().length > 0
|
|
226
|
+
? options.startTime.trim()
|
|
227
|
+
: undefined;
|
|
228
|
+
const endFromParams = typeof options.endTime === "string" && options.endTime.trim().length > 0
|
|
229
|
+
? options.endTime.trim()
|
|
230
|
+
: undefined;
|
|
231
|
+
if (startFromParams || endFromParams) {
|
|
232
|
+
if (!startFromParams || !endFromParams) {
|
|
233
|
+
throw new Error("查询监控指标时 startTime 与 endTime 必须同时提供,格式为 YYYY-MM-DD HH:mm:ss。");
|
|
234
|
+
}
|
|
235
|
+
if (!ENV_METRIC_TIME_RE.test(startFromParams) || !ENV_METRIC_TIME_RE.test(endFromParams)) {
|
|
236
|
+
throw new Error("startTime / endTime 格式必须为 YYYY-MM-DD HH:mm:ss。");
|
|
237
|
+
}
|
|
238
|
+
const startMs = Date.parse(startFromParams.replace(" ", "T"));
|
|
239
|
+
const endMs = Date.parse(endFromParams.replace(" ", "T"));
|
|
240
|
+
if (Number.isNaN(startMs) || Number.isNaN(endMs)) {
|
|
241
|
+
throw new Error("startTime / endTime 无法解析为有效时间。");
|
|
242
|
+
}
|
|
243
|
+
if (endMs - startMs < ENV_METRIC_MIN_RANGE_MS) {
|
|
244
|
+
throw new Error("结束时间需要晚于开始时间至少五分钟(监控最小粒度为 5 分钟)。");
|
|
245
|
+
}
|
|
246
|
+
return {
|
|
247
|
+
startTime: startFromParams,
|
|
248
|
+
endTime: endFromParams,
|
|
249
|
+
timeSource: "params",
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
const now = options.now ?? new Date();
|
|
253
|
+
const start = new Date(now.getTime() - 24 * 60 * 60 * 1000);
|
|
254
|
+
return {
|
|
255
|
+
startTime: formatEnvMetricTime(start),
|
|
256
|
+
endTime: formatEnvMetricTime(now),
|
|
257
|
+
timeSource: "defaultLast24h",
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
function resolveEnvMetricResourceId(metricName, resourceID) {
|
|
261
|
+
const normalized = typeof resourceID === "string" && resourceID.trim().length > 0
|
|
262
|
+
? resourceID.trim()
|
|
263
|
+
: undefined;
|
|
264
|
+
if (normalized) {
|
|
265
|
+
return normalized;
|
|
266
|
+
}
|
|
267
|
+
if (metricName === "GatewayTraceEnvQPS") {
|
|
268
|
+
return exports.GATEWAY_ENV_QPS_DEFAULT_RESOURCE_ID;
|
|
269
|
+
}
|
|
270
|
+
if (ENV_METRICS_REQUIRING_RESOURCE_ID.has(metricName)) {
|
|
271
|
+
throw new Error(`查询 ${metricName} 时 resourceID 为必填(云托管服务名)。请先 queryCloudRun(action="list") 获取服务名后再查询。`);
|
|
272
|
+
}
|
|
273
|
+
return undefined;
|
|
274
|
+
}
|
|
275
|
+
function summarizeEnvMetricCurve(curve) {
|
|
276
|
+
const newValues = Array.isArray(curve.NewValues) ? curve.NewValues : [];
|
|
277
|
+
const values = Array.isArray(curve.Values) ? curve.Values : [];
|
|
278
|
+
const times = Array.isArray(curve.Time) ? curve.Time : [];
|
|
279
|
+
const series = (newValues.length > 0 ? newValues : values).filter((item) => typeof item === "number" && Number.isFinite(item));
|
|
280
|
+
if (series.length === 0) {
|
|
281
|
+
return {
|
|
282
|
+
sampleCount: 0,
|
|
283
|
+
max: null,
|
|
284
|
+
min: null,
|
|
285
|
+
avg: null,
|
|
286
|
+
latest: null,
|
|
287
|
+
peakTimestamp: null,
|
|
288
|
+
allZero: true,
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
let max = series[0];
|
|
292
|
+
let min = series[0];
|
|
293
|
+
let sum = 0;
|
|
294
|
+
let peakIndex = 0;
|
|
295
|
+
for (let i = 0; i < series.length; i++) {
|
|
296
|
+
const value = series[i];
|
|
297
|
+
sum += value;
|
|
298
|
+
if (value > max) {
|
|
299
|
+
max = value;
|
|
300
|
+
peakIndex = i;
|
|
301
|
+
}
|
|
302
|
+
if (value < min) {
|
|
303
|
+
min = value;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
return {
|
|
307
|
+
sampleCount: series.length,
|
|
308
|
+
max,
|
|
309
|
+
min,
|
|
310
|
+
avg: sum / series.length,
|
|
311
|
+
latest: series[series.length - 1],
|
|
312
|
+
peakTimestamp: typeof times[peakIndex] === "number" ? times[peakIndex] : null,
|
|
313
|
+
allZero: series.every((value) => value === 0),
|
|
314
|
+
};
|
|
315
|
+
}
|
|
68
316
|
/**
|
|
69
317
|
* Simplify environment list data by keeping only essential fields for AI assistant
|
|
70
318
|
* This reduces token consumption when returning environment lists via MCP tools
|
|
@@ -918,6 +1166,19 @@ function buildEnvQueryErrorMessage(error, action) {
|
|
|
918
1166
|
if (hasNetworkError) {
|
|
919
1167
|
suggestions.push("网络错误:请检查网络连接,稍后重试。");
|
|
920
1168
|
}
|
|
1169
|
+
if (action === "usage" && suggestions.length === 0) {
|
|
1170
|
+
suggestions.push("查询环境资源用量失败,建议:");
|
|
1171
|
+
suggestions.push("1. 先调用 auth(action=\"status\") 确认登录状态;未登录则 auth(action=\"start_auth\")");
|
|
1172
|
+
suggestions.push("2. 使用 queryEnv(action=\"list\") 确认 envId 正确且可访问");
|
|
1173
|
+
suggestions.push(`3. 再调用 queryEnv(action=\"usage\", envId=\"<EnvId>\");可用 type 过滤模块(${exports.ENV_USAGE_MODULE_VALUES.join(", ")})`);
|
|
1174
|
+
}
|
|
1175
|
+
if (action === "metrics" && suggestions.length === 0) {
|
|
1176
|
+
suggestions.push("查询环境监控指标失败,建议:");
|
|
1177
|
+
suggestions.push("1. 先调用 auth(action=\"status\") 确认登录状态;未登录则 auth(action=\"start_auth\")");
|
|
1178
|
+
suggestions.push("2. 使用 queryEnv(action=\"list\") 确认 envId 正确且可访问");
|
|
1179
|
+
suggestions.push(`3. 再调用 queryEnv(action=\"metrics\", envId=\"<EnvId>\", metricName=\"GatewayTraceEnvQPS\");metricName 可选值:${exports.ENV_METRIC_NAME_VALUES.join(", ")}`);
|
|
1180
|
+
suggestions.push("4. startTime/endTime 格式为 YYYY-MM-DD HH:mm:ss,须成对传入;period 仅 300/3600/86400");
|
|
1181
|
+
}
|
|
921
1182
|
// If no specific pattern matched, provide general guidance
|
|
922
1183
|
if (suggestions.length === 0) {
|
|
923
1184
|
suggestions.push("查询环境信息时出错,建议:");
|
|
@@ -1828,8 +2089,8 @@ function registerEnvTools(server) {
|
|
|
1828
2089
|
}
|
|
1829
2090
|
});
|
|
1830
2091
|
} // end: wxide guard for auth tool
|
|
1831
|
-
// queryEnv - 环境查询(合并 listEnvs + getEnvInfo + getEnvAuthDomains)
|
|
1832
|
-
const queryEnvHandler = async ({ action, alias, aliasExact, envId, limit, offset, fields, }) => {
|
|
2092
|
+
// queryEnv - 环境查询(合并 listEnvs + getEnvInfo + getEnvAuthDomains + usage + metrics)
|
|
2093
|
+
const queryEnvHandler = async ({ action, alias, aliasExact, envId, limit, offset, fields, type, startDate, endDate, needUsageDetails, metricName, startTime, endTime, period, resourceID, subresourceID, }) => {
|
|
1833
2094
|
try {
|
|
1834
2095
|
let result;
|
|
1835
2096
|
switch (action) {
|
|
@@ -1991,6 +2252,94 @@ function registerEnvTools(server) {
|
|
|
1991
2252
|
};
|
|
1992
2253
|
}
|
|
1993
2254
|
break;
|
|
2255
|
+
case "usage": {
|
|
2256
|
+
// Explicit EnvId is required (DescribeEnvPostpayPackage / credits APIs reject missing EnvId).
|
|
2257
|
+
const usageEnvId = normalizeOptionalToolString(envId);
|
|
2258
|
+
if (!usageEnvId) {
|
|
2259
|
+
throw new Error('查询资源用量时 envId 为必填参数。请先调用 queryEnv(action="list") 获取 EnvId,再调用 queryEnv(action="usage", envId="<EnvId>")。');
|
|
2260
|
+
}
|
|
2261
|
+
const modules = resolveEnvUsageModules(type);
|
|
2262
|
+
const includeDetails = typeof needUsageDetails === "boolean" ? needUsageDetails : true;
|
|
2263
|
+
const cloudbaseUsage = await getManagerForEnvQuery(usageEnvId);
|
|
2264
|
+
const accountCircle = await cloudbaseUsage.env.describeEnvAccountCircle({
|
|
2265
|
+
EnvId: usageEnvId,
|
|
2266
|
+
});
|
|
2267
|
+
(0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, accountCircle);
|
|
2268
|
+
const dateRange = resolveEnvUsageDateRange({
|
|
2269
|
+
startDate,
|
|
2270
|
+
endDate,
|
|
2271
|
+
accountCircle,
|
|
2272
|
+
});
|
|
2273
|
+
const usageDetail = await cloudbaseUsage.env.describeCreditsUsageDetail({
|
|
2274
|
+
EnvId: usageEnvId,
|
|
2275
|
+
Modules: modules,
|
|
2276
|
+
StartDate: dateRange.startDate,
|
|
2277
|
+
EndDate: dateRange.endDate,
|
|
2278
|
+
NeedUsageDetails: includeDetails,
|
|
2279
|
+
});
|
|
2280
|
+
(0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, usageDetail);
|
|
2281
|
+
result = {
|
|
2282
|
+
EnvId: usageEnvId,
|
|
2283
|
+
Modules: modules,
|
|
2284
|
+
StartDate: dateRange.startDate,
|
|
2285
|
+
EndDate: dateRange.endDate,
|
|
2286
|
+
DateSource: dateRange.dateSource,
|
|
2287
|
+
NeedUsageDetails: includeDetails,
|
|
2288
|
+
AccountCircle: {
|
|
2289
|
+
StartTime: accountCircle?.StartTime,
|
|
2290
|
+
EndTime: accountCircle?.EndTime,
|
|
2291
|
+
HistoryTime: accountCircle?.HistoryTime ?? [],
|
|
2292
|
+
RequestId: accountCircle?.RequestId,
|
|
2293
|
+
},
|
|
2294
|
+
Usages: usageDetail?.Usages ?? [],
|
|
2295
|
+
RequestId: usageDetail?.RequestId,
|
|
2296
|
+
};
|
|
2297
|
+
break;
|
|
2298
|
+
}
|
|
2299
|
+
case "metrics": {
|
|
2300
|
+
const metricsEnvId = normalizeOptionalToolString(envId);
|
|
2301
|
+
if (!metricsEnvId) {
|
|
2302
|
+
throw new Error('查询监控指标时 envId 为必填参数。请先调用 queryEnv(action="list") 获取 EnvId,再调用 queryEnv(action="metrics", envId="<EnvId>", metricName="GatewayTraceEnvQPS")。');
|
|
2303
|
+
}
|
|
2304
|
+
const resolvedMetricName = resolveEnvMetricName(metricName);
|
|
2305
|
+
const timeRange = resolveEnvMetricTimeRange({ startTime, endTime });
|
|
2306
|
+
const resolvedPeriod = resolveEnvMetricPeriod(period);
|
|
2307
|
+
const resolvedResourceId = resolveEnvMetricResourceId(resolvedMetricName, resourceID);
|
|
2308
|
+
const resolvedSubresourceId = normalizeOptionalToolString(subresourceID);
|
|
2309
|
+
const cloudbaseMetrics = await getManagerForEnvQuery(metricsEnvId);
|
|
2310
|
+
if (typeof cloudbaseMetrics?.monitor?.describeCurveData !== "function") {
|
|
2311
|
+
throw new Error("当前 CloudBase Manager 不支持 monitor.describeCurveData。请升级 @cloudbase/manager-node。");
|
|
2312
|
+
}
|
|
2313
|
+
const curveParams = {
|
|
2314
|
+
MetricName: resolvedMetricName,
|
|
2315
|
+
StartTime: timeRange.startTime,
|
|
2316
|
+
EndTime: timeRange.endTime,
|
|
2317
|
+
};
|
|
2318
|
+
if (resolvedPeriod !== undefined) {
|
|
2319
|
+
curveParams.Period = resolvedPeriod;
|
|
2320
|
+
}
|
|
2321
|
+
if (resolvedResourceId) {
|
|
2322
|
+
curveParams.ResourceID = resolvedResourceId;
|
|
2323
|
+
}
|
|
2324
|
+
if (resolvedSubresourceId) {
|
|
2325
|
+
curveParams.SubresourceID = resolvedSubresourceId;
|
|
2326
|
+
}
|
|
2327
|
+
const curve = await cloudbaseMetrics.monitor.describeCurveData(curveParams);
|
|
2328
|
+
(0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, curve);
|
|
2329
|
+
result = {
|
|
2330
|
+
EnvId: metricsEnvId,
|
|
2331
|
+
MetricName: resolvedMetricName,
|
|
2332
|
+
StartTime: timeRange.startTime,
|
|
2333
|
+
EndTime: timeRange.endTime,
|
|
2334
|
+
TimeSource: timeRange.timeSource,
|
|
2335
|
+
Period: resolvedPeriod ?? curve?.Period,
|
|
2336
|
+
ResourceID: resolvedResourceId,
|
|
2337
|
+
SubresourceID: resolvedSubresourceId,
|
|
2338
|
+
Curve: curve,
|
|
2339
|
+
Summary: summarizeEnvMetricCurve(curve ?? {}),
|
|
2340
|
+
};
|
|
2341
|
+
break;
|
|
2342
|
+
}
|
|
1994
2343
|
default:
|
|
1995
2344
|
throw new Error(`不支持的查询类型: ${action}`);
|
|
1996
2345
|
}
|
|
@@ -2023,20 +2372,63 @@ function registerEnvTools(server) {
|
|
|
2023
2372
|
// Register primary tool name (queryEnv)
|
|
2024
2373
|
const queryEnvToolSchema = {
|
|
2025
2374
|
title: "CloudBase 环境查询",
|
|
2026
|
-
description: "查询 CloudBase
|
|
2375
|
+
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 都不该使用。",
|
|
2027
2376
|
inputSchema: {
|
|
2028
2377
|
action: zod_1.z
|
|
2029
|
-
.enum(["list", "info", "domains"])
|
|
2030
|
-
.describe("查询类型:list=环境列表/摘要筛选(按 DescribeEnvs 语义筛选,支持通过 envId 筛选,返回 EnvId、Alias、Status、EnvType、Region、PackageId、PackageName、IsDefault,不支持 expiry),info=指定环境的详细信息(必须传入 envId,返回资源字段和计费信息),domains
|
|
2378
|
+
.enum(["list", "info", "domains", "usage", "metrics"])
|
|
2379
|
+
.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)"),
|
|
2031
2380
|
alias: zod_1.z.string().optional().describe("按环境别名筛选。action=list 时可选"),
|
|
2032
2381
|
aliasExact: zod_1.z.boolean().optional().describe("按环境别名精确筛选。action=list 时可选;与 alias 配合使用"),
|
|
2033
|
-
envId: zod_1.z
|
|
2382
|
+
envId: zod_1.z
|
|
2383
|
+
.string()
|
|
2384
|
+
.optional()
|
|
2385
|
+
.describe("环境 ID。action=list 时可选(仅按 DescribeEnvs 语义做筛选,仍返回摘要);action=info / action=usage / action=metrics 时必填。"),
|
|
2034
2386
|
limit: zod_1.z.number().int().positive().optional().describe("返回数量上限。action=list 时可选"),
|
|
2035
2387
|
offset: zod_1.z.number().int().min(0).optional().describe("分页偏移。action=list 时可选"),
|
|
2036
2388
|
fields: zod_1.z
|
|
2037
2389
|
.array(zod_1.z.enum(DEFAULT_ENV_FIELDS))
|
|
2038
2390
|
.optional()
|
|
2039
2391
|
.describe("返回字段白名单。仅支持 EnvId、Alias、Status、EnvType、Region、PackageId、PackageName、IsDefault。action=list 时可选"),
|
|
2392
|
+
type: zod_1.z
|
|
2393
|
+
.array(zod_1.z.enum(exports.ENV_USAGE_MODULE_VALUES))
|
|
2394
|
+
.optional()
|
|
2395
|
+
.describe("用量模块过滤。仅 action=usage 时有效;不传则查询全部模块。可选值对齐 tcb CLI:FLEXDB、TDSQL、SCF、EKS、COS、AI、HOSTING、Auth、APIInvocation、HTTPInvocation、VM、Workflow、Other。"),
|
|
2396
|
+
startDate: zod_1.z
|
|
2397
|
+
.string()
|
|
2398
|
+
.optional()
|
|
2399
|
+
.describe("用量开始日期(YYYY-MM-DD)。仅 action=usage 时有效;与 endDate 成对传入。不传则使用当前计费周期。"),
|
|
2400
|
+
endDate: zod_1.z
|
|
2401
|
+
.string()
|
|
2402
|
+
.optional()
|
|
2403
|
+
.describe("用量结束日期(YYYY-MM-DD)。仅 action=usage 时有效;与 startDate 成对传入。不传则使用当前计费周期。"),
|
|
2404
|
+
needUsageDetails: zod_1.z
|
|
2405
|
+
.boolean()
|
|
2406
|
+
.optional()
|
|
2407
|
+
.describe("是否返回每日用量明细。仅 action=usage 时有效;默认 true。"),
|
|
2408
|
+
metricName: zod_1.z
|
|
2409
|
+
.enum(exports.ENV_METRIC_NAME_VALUES)
|
|
2410
|
+
.optional()
|
|
2411
|
+
.describe("监控指标名。仅 action=metrics 时有效且必填。GatewayTraceEnvQPS/EnvQPSAll=环境与网关 QPS;FunctionInvocation/FunctionError/FunctionTimeout/FunctionThrottle=云函数调用、错误、超时、限流;DbRead/DbWrite/DbSizepkg=文档库读写与容量;MysqlCpuUsageRate/MysqlMemoryUse/MysqlStorageUsage=SQL 库 CPU/内存/磁盘;TkeCpuUsedService/TkeQPSService/TkeHttpErrorService=云托管 CPU/QPS/错误。"),
|
|
2412
|
+
startTime: zod_1.z
|
|
2413
|
+
.string()
|
|
2414
|
+
.optional()
|
|
2415
|
+
.describe("监控开始时间(YYYY-MM-DD HH:mm:ss)。仅 action=metrics 时有效;与 endTime 成对传入。不传则默认最近 24 小时。结束时间须晚于开始时间至少五分钟。"),
|
|
2416
|
+
endTime: zod_1.z
|
|
2417
|
+
.string()
|
|
2418
|
+
.optional()
|
|
2419
|
+
.describe("监控结束时间(YYYY-MM-DD HH:mm:ss)。仅 action=metrics 时有效;与 startTime 成对传入。不传则默认最近 24 小时。"),
|
|
2420
|
+
period: zod_1.z
|
|
2421
|
+
.union([zod_1.z.literal(300), zod_1.z.literal(3600), zod_1.z.literal(86400)])
|
|
2422
|
+
.optional()
|
|
2423
|
+
.describe("统计周期(秒)。仅 action=metrics 时有效;仅支持 300、3600、86400。不传则由后端按时间范围自动选择。时间范围 ≤1 天不可用 86400;>3 天不可用 300。"),
|
|
2424
|
+
resourceID: zod_1.z
|
|
2425
|
+
.string()
|
|
2426
|
+
.optional()
|
|
2427
|
+
.describe("资源 ID。仅 action=metrics 时有效。云函数传函数名,文档库传集合名,云托管必须传服务名;GatewayTraceEnvQPS 不传则使用环境级 all|:|all|:|all|:|all。"),
|
|
2428
|
+
subresourceID: zod_1.z
|
|
2429
|
+
.string()
|
|
2430
|
+
.optional()
|
|
2431
|
+
.describe("子资源 ID。仅 action=metrics 时有效;查询云托管某版本监控时传入版本名。"),
|
|
2040
2432
|
},
|
|
2041
2433
|
annotations: {
|
|
2042
2434
|
readOnlyHint: true,
|
|
@@ -2552,8 +2944,11 @@ function registerEnvTools(server) {
|
|
|
2552
2944
|
|
|
2553
2945
|
|
|
2554
2946
|
Object.defineProperty(exports, "__esModule", ({ value: true }));
|
|
2947
|
+
exports.CAM_AUTH_ERROR_PATTERN = void 0;
|
|
2555
2948
|
exports.assertTcbCloudRunActionAllowed = assertTcbCloudRunActionAllowed;
|
|
2556
2949
|
exports.removeEmptyStringParams = removeEmptyStringParams;
|
|
2950
|
+
exports.buildCamAuthGuidance = buildCamAuthGuidance;
|
|
2951
|
+
exports.isCamAuthError = isCamAuthError;
|
|
2557
2952
|
exports.buildCapiErrorMessage = buildCapiErrorMessage;
|
|
2558
2953
|
exports.registerCapiTools = registerCapiTools;
|
|
2559
2954
|
const zod_1 = __webpack_require__(2971);
|
|
@@ -2573,27 +2968,30 @@ const ALLOWED_SERVICES = [
|
|
|
2573
2968
|
"vpc",
|
|
2574
2969
|
];
|
|
2575
2970
|
/**
|
|
2576
|
-
* tcb
|
|
2971
|
+
* Legacy tcb small-tenant CloudRun (CloudBase Run) API family — blocked.
|
|
2577
2972
|
*
|
|
2578
|
-
*
|
|
2579
|
-
* CreateCloudBaseRunResource
|
|
2580
|
-
*
|
|
2581
|
-
*
|
|
2973
|
+
* CloudRun must use tcbr (CreateCloudRunEnv / CreateCloudRunServer). tcb
|
|
2974
|
+
* CreateCloudBaseRunResource is the 2018 small-tenant open API and is no longer
|
|
2975
|
+
* publicly listed; calling it on an env without a large-tenant record creates
|
|
2976
|
+
* wrong small-tenant services/versions (user incident 2026-08-13; ATO research
|
|
2977
|
+
* efec7cc5). Describe/Delete of the same family are blocked too. Matching is
|
|
2978
|
+
* case-insensitive so Action casing variants cannot bypass the check.
|
|
2582
2979
|
*/
|
|
2583
2980
|
const TCB_CLOUDRUN_FORBIDDEN_ACTIONS = [
|
|
2584
2981
|
"CreateCloudBaseRunResource",
|
|
2585
2982
|
"DescribeCloudBaseRunResource",
|
|
2586
2983
|
"DeleteCloudBaseRunResource",
|
|
2587
2984
|
];
|
|
2985
|
+
const TCB_CLOUDRUN_FORBIDDEN_ACTIONS_LOWER = new Set(TCB_CLOUDRUN_FORBIDDEN_ACTIONS.map((name) => name.toLowerCase()));
|
|
2588
2986
|
const TCB_CLOUDRUN_FORBIDDEN_HINT = `云托管(CloudBase Run)统一走 tcbr 新逻辑(CreateCloudRunEnv / CreateCloudRunServer),` +
|
|
2589
2987
|
`不要使用 tcb 旧小租户接口(${TCB_CLOUDRUN_FORBIDDEN_ACTIONS.join(" / ")})。` +
|
|
2590
2988
|
`新环境请先初始化云托管:callCloudApi(service="tcbr", version="2022-02-17", action="CreateCloudRunEnv", params={EnvId:"..."}),` +
|
|
2591
2989
|
`再通过 manageCloudRun(action="deploy") 创建服务;查询单个环境基础信息/是否已开通云托管用 callCloudApi(service="tcbr", version="2022-02-17", action="DescribeEnvBaseInfo", params={EnvId:"..."}),查询环境列表/资源信息用 DescribeCloudRunEnvs。`;
|
|
2592
2990
|
/**
|
|
2593
|
-
*
|
|
2991
|
+
* Reject legacy tcb small-tenant CloudRun APIs; throw with tcbr guidance when blocked.
|
|
2594
2992
|
*/
|
|
2595
2993
|
function assertTcbCloudRunActionAllowed(service, action) {
|
|
2596
|
-
if (service === "tcb" &&
|
|
2994
|
+
if (service === "tcb" && TCB_CLOUDRUN_FORBIDDEN_ACTIONS_LOWER.has(action.toLowerCase())) {
|
|
2597
2995
|
throw new Error(`[${service}/${action}] 已禁用:${TCB_CLOUDRUN_FORBIDDEN_HINT}`);
|
|
2598
2996
|
}
|
|
2599
2997
|
}
|
|
@@ -2677,6 +3075,21 @@ function buildCapiDocGuidance(service) {
|
|
|
2677
3075
|
}
|
|
2678
3076
|
return `请优先核对对应官方云 API 文档;若你的场景其实是通过 HTTP 协议直接集成 auth/functions/cloudrun/storage/mysqldb 等 CloudBase 业务 API,请优先使用 OpenAPI / Swagger 或 searchKnowledgeBase(mode="openapi"),不要继续猜测管控面 Action。`;
|
|
2679
3077
|
}
|
|
3078
|
+
/** Match CAM / authorization failures from Tencent Cloud control-plane APIs. */
|
|
3079
|
+
exports.CAM_AUTH_ERROR_PATTERN = /UnauthorizedOperation|AuthFailure|not authorized|cam.*denied|Forbidden/i;
|
|
3080
|
+
/**
|
|
3081
|
+
* Guidance when control-plane calls fail due to CAM / API Key scope limits.
|
|
3082
|
+
* Shared by callCloudApi and manageCloudRun error builders.
|
|
3083
|
+
*/
|
|
3084
|
+
function buildCamAuthGuidance() {
|
|
3085
|
+
return ("这通常是 CAM 权限不足(常见于 API Key 登录仅授权数据面:DB/函数/存储)。请任选其一:" +
|
|
3086
|
+
"1) 改用 device code 登录管控面:auth(action=\"start_auth\", authMode=\"device\");" +
|
|
3087
|
+
"2) 或使用腾讯云 SecretId/SecretKey(确认子账号已授 CAM 策略,如 QcloudTCBFullAccess、QcloudVPCReadOnlyAccess);" +
|
|
3088
|
+
"3) 确认目标资源属于当前登录账号。");
|
|
3089
|
+
}
|
|
3090
|
+
function isCamAuthError(message) {
|
|
3091
|
+
return exports.CAM_AUTH_ERROR_PATTERN.test(message);
|
|
3092
|
+
}
|
|
2680
3093
|
function buildCapiErrorMessage(service, action, error) {
|
|
2681
3094
|
const baseMessage = error instanceof Error ? error.message : String(error);
|
|
2682
3095
|
const suggestions = [];
|
|
@@ -2684,6 +3097,10 @@ function buildCapiErrorMessage(service, action, error) {
|
|
|
2684
3097
|
const hasInvalidActionError = /invalid or not found|does not exist|not recognized/i.test(baseMessage);
|
|
2685
3098
|
const hasParameterError = /parameter\s+`?.+?`?\s+is not recognized|MissingParameter|missing parameter|missing required/i.test(baseMessage);
|
|
2686
3099
|
const hasInvalidParameterValueError = /invalid parameter value/i.test(baseMessage);
|
|
3100
|
+
const hasCamAuthError = isCamAuthError(baseMessage);
|
|
3101
|
+
if (hasCamAuthError) {
|
|
3102
|
+
suggestions.push(buildCamAuthGuidance());
|
|
3103
|
+
}
|
|
2687
3104
|
if (hasInvalidActionError) {
|
|
2688
3105
|
suggestions.push(`Action \`${action}\` 可能不存在或不对外开放。请不要继续猜测 Action 名称,先确认 service=\`${service}\` 下该 Action 在当前 API 版本是否真实存在。`);
|
|
2689
3106
|
if (service === "tcb") {
|
|
@@ -2801,9 +3218,13 @@ function registerCapiTools(server) {
|
|
|
2801
3218
|
}
|
|
2802
3219
|
if (service === 'tcb') {
|
|
2803
3220
|
const tcbCapiForbidList = [
|
|
2804
|
-
//
|
|
3221
|
+
// Cloud APIs not clearly public
|
|
2805
3222
|
'DescribeStorageACL', 'ModifyStorageACL', 'DescribeSecurityRule',
|
|
2806
|
-
//
|
|
3223
|
+
// Legacy small-tenant CloudRun open/query/delete (no longer public; also blocked by assertTcbCloudRunActionAllowed)
|
|
3224
|
+
"CreateCloudBaseRunResource",
|
|
3225
|
+
"DescribeCloudBaseRunResource",
|
|
3226
|
+
"DeleteCloudBaseRunResource",
|
|
3227
|
+
// Cloud APIs scheduled for retirement
|
|
2807
3228
|
"ListTables",
|
|
2808
3229
|
"DescribeCloudBaseGWAPI",
|
|
2809
3230
|
"DescribeCloudBaseGWService",
|
|
@@ -2939,7 +3360,7 @@ ${envIdSection}
|
|
|
2939
3360
|
## 环境信息
|
|
2940
3361
|
- 操作系统: ${os_1.default.type()} ${os_1.default.release()}
|
|
2941
3362
|
- Node.js版本: ${process.version}
|
|
2942
|
-
- MCP 版本:${process.env.npm_package_version || ( true ? "2.
|
|
3363
|
+
- MCP 版本:${process.env.npm_package_version || ( true ? "2.28.0" : 0)}
|
|
2943
3364
|
- 系统架构: ${os_1.default.arch()}
|
|
2944
3365
|
- 时间: ${new Date().toISOString()}
|
|
2945
3366
|
- 请求ID: ${requestId}
|
|
@@ -3020,7 +3441,7 @@ function createWrappedHandler(name, handler, server) {
|
|
|
3020
3441
|
requestId: (typeof error === 'object' && error && 'requestId' in error) ? error.requestId : '',
|
|
3021
3442
|
ide: server.ide || process.env.INTEGRATION_IDE || ''
|
|
3022
3443
|
});
|
|
3023
|
-
const mcpVersion = true ? "2.
|
|
3444
|
+
const mcpVersion = true ? "2.28.0" : 0;
|
|
3024
3445
|
const requestIdSuffix = requestId ? `\n🆔 RequestId: ${requestId}` : '';
|
|
3025
3446
|
const enhancedErrorMessage = `${errorMessage}${requestIdSuffix}\n\n📦 CloudBase MCP v${mcpVersion}\n🔗 遇到问题?请复制以下链接到浏览器打开\n即可自动携带错误详情快速创建 GitHub Issue:\n${issueLink}`;
|
|
3026
3447
|
// 创建新的错误对象,保持原有的错误类型但更新消息
|
|
@@ -5412,6 +5833,15 @@ const logger_js_1 = __webpack_require__(3039);
|
|
|
5412
5833
|
const CATEGORY = "NoSQL database";
|
|
5413
5834
|
const COLLECTION_READY_TIMEOUT_MS = 10000;
|
|
5414
5835
|
const COLLECTION_READY_POLL_INTERVAL_MS = 500;
|
|
5836
|
+
/** Default page size for QueryRecords (unchanged; overrun tuning is a separate track). */
|
|
5837
|
+
const QUERY_RECORDS_DEFAULT_LIMIT = 100;
|
|
5838
|
+
/** Cloud API MgoLimit `lte` upper bound (aligned with ListTables / SDK limit docs). */
|
|
5839
|
+
const QUERY_RECORDS_MAX_LIMIT = 1000;
|
|
5840
|
+
const PROJECTION_EXAMPLE = '{"_id":1,"name":1,"createdAt":1}';
|
|
5841
|
+
const PROJECTION_EXCLUDE_EXAMPLE = '{"password":0}';
|
|
5842
|
+
const PROJECTION_GUIDANCE = `projection 必须是字段投影对象(或对应 JSON 字符串),值只能是 1/0/true/false。` +
|
|
5843
|
+
`合法示例:${PROJECTION_EXAMPLE}(只返回这些字段),或 ${PROJECTION_EXCLUDE_EXAMPLE}(排除字段)。` +
|
|
5844
|
+
`不要传字段名数组、逗号分隔字符串、查询条件,也不要在同一投影里混用包含(1/true)与排除(0/false)(_id 除外)。`;
|
|
5415
5845
|
/** Convert object values to JSON strings for API calls */
|
|
5416
5846
|
const toJSONString = (v) => typeof v === "object" && v !== null ? JSON.stringify(v) : v;
|
|
5417
5847
|
function delay(ms) {
|
|
@@ -5482,6 +5912,95 @@ function normalizeSortInput(sort) {
|
|
|
5482
5912
|
}
|
|
5483
5913
|
return JSON.stringify(parsed.map((item) => normalizeSortItem(item)));
|
|
5484
5914
|
}
|
|
5915
|
+
function isProjectionFlag(value) {
|
|
5916
|
+
return value === 0 || value === 1 || value === true || value === false;
|
|
5917
|
+
}
|
|
5918
|
+
function normalizeProjectionInput(projection) {
|
|
5919
|
+
if (projection === undefined || projection === null) {
|
|
5920
|
+
return undefined;
|
|
5921
|
+
}
|
|
5922
|
+
let parsed = projection;
|
|
5923
|
+
if (typeof parsed === "string") {
|
|
5924
|
+
const trimmed = parsed.trim();
|
|
5925
|
+
if (!trimmed) {
|
|
5926
|
+
return undefined;
|
|
5927
|
+
}
|
|
5928
|
+
try {
|
|
5929
|
+
parsed = JSON.parse(trimmed);
|
|
5930
|
+
}
|
|
5931
|
+
catch {
|
|
5932
|
+
throw new Error(`projection 必须是合法 JSON 对象字符串。${PROJECTION_GUIDANCE}`);
|
|
5933
|
+
}
|
|
5934
|
+
}
|
|
5935
|
+
if (Array.isArray(parsed)) {
|
|
5936
|
+
throw new Error(`projection 不支持字段名数组。请改为对象,例如 ${PROJECTION_EXAMPLE}。${PROJECTION_GUIDANCE}`);
|
|
5937
|
+
}
|
|
5938
|
+
if (!parsed || typeof parsed !== "object") {
|
|
5939
|
+
throw new Error(`projection 必须是对象。请改为例如 ${PROJECTION_EXAMPLE}。${PROJECTION_GUIDANCE}`);
|
|
5940
|
+
}
|
|
5941
|
+
const entries = Object.entries(parsed);
|
|
5942
|
+
if (entries.length === 0) {
|
|
5943
|
+
return undefined;
|
|
5944
|
+
}
|
|
5945
|
+
let hasInclude = false;
|
|
5946
|
+
let hasExclude = false;
|
|
5947
|
+
const normalized = {};
|
|
5948
|
+
for (const [key, value] of entries) {
|
|
5949
|
+
if (typeof key !== "string" || key.trim() === "") {
|
|
5950
|
+
throw new Error(`projection 字段名必须是非空字符串。${PROJECTION_GUIDANCE}`);
|
|
5951
|
+
}
|
|
5952
|
+
if (!isProjectionFlag(value)) {
|
|
5953
|
+
throw new Error(`projection["${key}"] 的值非法(当前为 ${JSON.stringify(value)}),仅支持 1/0/true/false。` +
|
|
5954
|
+
`合法示例:${PROJECTION_EXAMPLE}。${PROJECTION_GUIDANCE}`);
|
|
5955
|
+
}
|
|
5956
|
+
const flag = value === true || value === 1 ? 1 : 0;
|
|
5957
|
+
normalized[key] = flag;
|
|
5958
|
+
if (key === "_id") {
|
|
5959
|
+
continue;
|
|
5960
|
+
}
|
|
5961
|
+
if (flag === 1) {
|
|
5962
|
+
hasInclude = true;
|
|
5963
|
+
}
|
|
5964
|
+
else {
|
|
5965
|
+
hasExclude = true;
|
|
5966
|
+
}
|
|
5967
|
+
}
|
|
5968
|
+
if (hasInclude && hasExclude) {
|
|
5969
|
+
throw new Error(`projection 不能同时混用包含(1/true)与排除(0/false)(_id 除外)。` +
|
|
5970
|
+
`请只保留一种模式,例如 ${PROJECTION_EXAMPLE} 或 ${PROJECTION_EXCLUDE_EXAMPLE}。`);
|
|
5971
|
+
}
|
|
5972
|
+
return JSON.stringify(normalized);
|
|
5973
|
+
}
|
|
5974
|
+
function normalizeQueryLimit(limit) {
|
|
5975
|
+
if (limit === undefined || limit === null) {
|
|
5976
|
+
return QUERY_RECORDS_DEFAULT_LIMIT;
|
|
5977
|
+
}
|
|
5978
|
+
if (typeof limit !== "number" || !Number.isFinite(limit)) {
|
|
5979
|
+
throw new Error(`limit 必须是数字,取值范围 1-${QUERY_RECORDS_MAX_LIMIT}(默认 ${QUERY_RECORDS_DEFAULT_LIMIT})。` +
|
|
5980
|
+
`超出上限时请用 offset 分页,例如 limit=${QUERY_RECORDS_MAX_LIMIT}, offset=0,再 offset+=limit。`);
|
|
5981
|
+
}
|
|
5982
|
+
if (!Number.isInteger(limit)) {
|
|
5983
|
+
throw new Error(`limit 必须是整数,取值范围 1-${QUERY_RECORDS_MAX_LIMIT}。当前值:${limit}`);
|
|
5984
|
+
}
|
|
5985
|
+
if (limit < 1 || limit > QUERY_RECORDS_MAX_LIMIT) {
|
|
5986
|
+
throw new Error(`limit 超出上限:当前 ${limit},允许范围 1-${QUERY_RECORDS_MAX_LIMIT}(Cloud API MgoLimit lte)。` +
|
|
5987
|
+
`请将 limit 调整为 ≤${QUERY_RECORDS_MAX_LIMIT},并用 offset 分页拉取更多数据` +
|
|
5988
|
+
`(例如 limit=${QUERY_RECORDS_MAX_LIMIT}, offset=0,下一页 offset=${QUERY_RECORDS_MAX_LIMIT})。`);
|
|
5989
|
+
}
|
|
5990
|
+
return limit;
|
|
5991
|
+
}
|
|
5992
|
+
function enhanceQueryRecordsError(error) {
|
|
5993
|
+
const message = error instanceof Error ? error.message : String(error ?? "");
|
|
5994
|
+
if (/Query projection.*illegal|projection entered in the request is illegal/i.test(message)) {
|
|
5995
|
+
throw new Error(`QueryRecords 投影非法:${message}。修正建议:${PROJECTION_GUIDANCE}`);
|
|
5996
|
+
}
|
|
5997
|
+
if (/MgoLimit.*lte|Field validation for 'MgoLimit' failed on the 'lte'/i.test(message)) {
|
|
5998
|
+
throw new Error(`QueryRecords MgoLimit 超限:${message}。` +
|
|
5999
|
+
`limit 最大为 ${QUERY_RECORDS_MAX_LIMIT},请缩小 limit 并用 offset 分页` +
|
|
6000
|
+
`(例如 limit=${QUERY_RECORDS_MAX_LIMIT}, offset=0)。`);
|
|
6001
|
+
}
|
|
6002
|
+
throw error instanceof Error ? error : new Error(message);
|
|
6003
|
+
}
|
|
5485
6004
|
function withCollectionName(collectionName, payload) {
|
|
5486
6005
|
return {
|
|
5487
6006
|
...payload,
|
|
@@ -6016,7 +6535,9 @@ deleteCollection: 删除集合`),
|
|
|
6016
6535
|
// readNoSqlDatabaseContent
|
|
6017
6536
|
server.registerTool?.("readNoSqlDatabaseContent", {
|
|
6018
6537
|
title: "查询并获取 CloudBase NoSQL 数据库数据记录",
|
|
6019
|
-
description: "查询 CloudBase NoSQL 数据库中的数据记录。支持按条件筛选、分页、排序,适用于管理端数据查询与运维。"
|
|
6538
|
+
description: "查询 CloudBase NoSQL 数据库中的数据记录。支持按条件筛选、分页、排序,适用于管理端数据查询与运维。" +
|
|
6539
|
+
`limit 默认 ${QUERY_RECORDS_DEFAULT_LIMIT}、最大 ${QUERY_RECORDS_MAX_LIMIT};超出请用 offset 分页。` +
|
|
6540
|
+
`projection 仅支持 { field: 1|0 } 对象(示例 ${PROJECTION_EXAMPLE}),不要传字段数组。`,
|
|
6020
6541
|
inputSchema: {
|
|
6021
6542
|
collectionName: zod_1.z.string().describe("集合名称"),
|
|
6022
6543
|
instanceId: zod_1.z
|
|
@@ -6030,7 +6551,9 @@ deleteCollection: 删除集合`),
|
|
|
6030
6551
|
projection: zod_1.z
|
|
6031
6552
|
.union([zod_1.z.object({}).passthrough(), zod_1.z.string()])
|
|
6032
6553
|
.optional()
|
|
6033
|
-
.describe(
|
|
6554
|
+
.describe(`返回字段投影,仅支持对象或对应 JSON 字符串,值只能是 1/0/true/false。` +
|
|
6555
|
+
`合法示例:${PROJECTION_EXAMPLE}(包含)或 ${PROJECTION_EXCLUDE_EXAMPLE}(排除)。` +
|
|
6556
|
+
`不要传 ["name","age"] 这类字段数组,也不要混用包含与排除(_id 除外)。`),
|
|
6034
6557
|
sort: zod_1.z
|
|
6035
6558
|
.union([
|
|
6036
6559
|
zod_1.z.array(zod_1.z
|
|
@@ -6043,7 +6566,11 @@ deleteCollection: 删除集合`),
|
|
|
6043
6566
|
])
|
|
6044
6567
|
.optional()
|
|
6045
6568
|
.describe('排序条件,仅支持数组 [{"key":"createdAt","direction":-1}] 或对应 JSON 字符串。'),
|
|
6046
|
-
limit: zod_1.z
|
|
6569
|
+
limit: zod_1.z
|
|
6570
|
+
.number()
|
|
6571
|
+
.optional()
|
|
6572
|
+
.describe(`返回数量限制,整数,范围 1-${QUERY_RECORDS_MAX_LIMIT},默认 ${QUERY_RECORDS_DEFAULT_LIMIT}。` +
|
|
6573
|
+
`超过 ${QUERY_RECORDS_MAX_LIMIT} 会被 Cloud API MgoLimit lte 校验拒绝;请用 offset 分页。`),
|
|
6047
6574
|
offset: zod_1.z.number().optional().describe("跳过的记录数"),
|
|
6048
6575
|
},
|
|
6049
6576
|
annotations: {
|
|
@@ -6059,46 +6586,53 @@ deleteCollection: 删除集合`),
|
|
|
6059
6586
|
durationMs: Date.now() - managerStartedAt,
|
|
6060
6587
|
});
|
|
6061
6588
|
const normalizedSort = normalizeSortInput(sort);
|
|
6062
|
-
const
|
|
6063
|
-
|
|
6064
|
-
|
|
6065
|
-
|
|
6066
|
-
|
|
6067
|
-
|
|
6068
|
-
|
|
6069
|
-
|
|
6070
|
-
|
|
6071
|
-
|
|
6072
|
-
|
|
6073
|
-
|
|
6074
|
-
|
|
6075
|
-
|
|
6076
|
-
|
|
6077
|
-
|
|
6078
|
-
const parseStartedAt = Date.now();
|
|
6079
|
-
const documents = normalizeNoSqlDocuments(result.Data);
|
|
6080
|
-
logNoSqlLatency("readNoSqlDatabaseContent", "parseResult", {
|
|
6081
|
-
collectionName,
|
|
6082
|
-
durationMs: Date.now() - parseStartedAt,
|
|
6083
|
-
documentCount: documents.length,
|
|
6084
|
-
});
|
|
6085
|
-
return {
|
|
6086
|
-
content: [
|
|
6087
|
-
{
|
|
6088
|
-
type: "text",
|
|
6089
|
-
text: JSON.stringify(withCollectionName(collectionName, {
|
|
6090
|
-
success: true,
|
|
6091
|
-
requestId: result.RequestId,
|
|
6092
|
-
data: documents,
|
|
6093
|
-
total: typeof result.Pager?.Total === "number"
|
|
6094
|
-
? result.Pager.Total
|
|
6095
|
-
: documents.length,
|
|
6096
|
-
pager: result.Pager,
|
|
6097
|
-
message: "文档查询成功",
|
|
6098
|
-
}), null, 2),
|
|
6589
|
+
const normalizedProjection = normalizeProjectionInput(projection);
|
|
6590
|
+
const normalizedLimit = normalizeQueryLimit(limit);
|
|
6591
|
+
try {
|
|
6592
|
+
const result = await callNoSqlContentApi({
|
|
6593
|
+
toolName: "readNoSqlDatabaseContent",
|
|
6594
|
+
action: "QueryRecords",
|
|
6595
|
+
collectionName,
|
|
6596
|
+
cloudbase,
|
|
6597
|
+
cloudBaseOptions,
|
|
6598
|
+
instanceIdOverride: instanceId,
|
|
6599
|
+
param: {
|
|
6600
|
+
MgoQuery: toJSONString(query),
|
|
6601
|
+
MgoProjection: normalizedProjection,
|
|
6602
|
+
MgoSort: normalizedSort,
|
|
6603
|
+
MgoLimit: normalizedLimit,
|
|
6604
|
+
MgoOffset: offset,
|
|
6099
6605
|
},
|
|
6100
|
-
|
|
6101
|
-
|
|
6606
|
+
});
|
|
6607
|
+
(0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
|
|
6608
|
+
const parseStartedAt = Date.now();
|
|
6609
|
+
const documents = normalizeNoSqlDocuments(result.Data);
|
|
6610
|
+
logNoSqlLatency("readNoSqlDatabaseContent", "parseResult", {
|
|
6611
|
+
collectionName,
|
|
6612
|
+
durationMs: Date.now() - parseStartedAt,
|
|
6613
|
+
documentCount: documents.length,
|
|
6614
|
+
});
|
|
6615
|
+
return {
|
|
6616
|
+
content: [
|
|
6617
|
+
{
|
|
6618
|
+
type: "text",
|
|
6619
|
+
text: JSON.stringify(withCollectionName(collectionName, {
|
|
6620
|
+
success: true,
|
|
6621
|
+
requestId: result.RequestId,
|
|
6622
|
+
data: documents,
|
|
6623
|
+
total: typeof result.Pager?.Total === "number"
|
|
6624
|
+
? result.Pager.Total
|
|
6625
|
+
: documents.length,
|
|
6626
|
+
pager: result.Pager,
|
|
6627
|
+
message: "文档查询成功",
|
|
6628
|
+
}), null, 2),
|
|
6629
|
+
},
|
|
6630
|
+
],
|
|
6631
|
+
};
|
|
6632
|
+
}
|
|
6633
|
+
catch (error) {
|
|
6634
|
+
enhanceQueryRecordsError(error);
|
|
6635
|
+
}
|
|
6102
6636
|
});
|
|
6103
6637
|
// writeNoSqlDatabaseContent
|
|
6104
6638
|
server.registerTool?.("writeNoSqlDatabaseContent", {
|
|
@@ -8222,7 +8756,10 @@ function registerGatewayTools(server) {
|
|
|
8222
8756
|
};
|
|
8223
8757
|
const pickUsableDefaultDomain = (domains) => {
|
|
8224
8758
|
const candidates = domains.filter((item) => item.IsDefault === true && item.Domain);
|
|
8225
|
-
return (candidates.find((item) => item.Enable !== false &&
|
|
8759
|
+
return (candidates.find((item) => item.Enable !== false &&
|
|
8760
|
+
// Platform may return Success/success; normalize before matching.
|
|
8761
|
+
typeof item.Status === "string" &&
|
|
8762
|
+
item.Status.toLowerCase() === "success") ??
|
|
8226
8763
|
candidates.find((item) => item.Enable !== false) ??
|
|
8227
8764
|
candidates[0]);
|
|
8228
8765
|
};
|
|
@@ -9630,9 +10167,18 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
9630
10167
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
9631
10168
|
};
|
|
9632
10169
|
Object.defineProperty(exports, "__esModule", ({ value: true }));
|
|
9633
|
-
exports.CLOUDRUN_PACKAGE_TYPES = exports.CLOUDRUN_ACCESS_TYPES = exports.CLOUDRUN_SERVICE_TYPES = void 0;
|
|
10170
|
+
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;
|
|
10171
|
+
exports.buildManageCloudRunErrorMessage = buildManageCloudRunErrorMessage;
|
|
10172
|
+
exports.isValidCloudRunBuildId = isValidCloudRunBuildId;
|
|
10173
|
+
exports.isValidCloudRunRunId = isValidCloudRunRunId;
|
|
10174
|
+
exports.waitForCloudRunDeployRegistration = waitForCloudRunDeployRegistration;
|
|
10175
|
+
exports.buildCloudRunDeployNextStep = buildCloudRunDeployNextStep;
|
|
10176
|
+
exports.buildCloudRunDeployProgressHint = buildCloudRunDeployProgressHint;
|
|
9634
10177
|
exports.queryCloudRunEnvStatus = queryCloudRunEnvStatus;
|
|
9635
10178
|
exports.describeCloudRunEnvStatus = describeCloudRunEnvStatus;
|
|
10179
|
+
exports.extractEnvBaseInfoVpc = extractEnvBaseInfoVpc;
|
|
10180
|
+
exports.resolveCloudRunDeployVpcInfo = resolveCloudRunDeployVpcInfo;
|
|
10181
|
+
exports.buildCreateCloudRunEnvParam = buildCreateCloudRunEnvParam;
|
|
9636
10182
|
exports.ensureCloudRunEnvInitialized = ensureCloudRunEnvInitialized;
|
|
9637
10183
|
exports.detectCloudRunDbNetworkRisk = detectCloudRunDbNetworkRisk;
|
|
9638
10184
|
exports.extractCloudRunImageInfo = extractCloudRunImageInfo;
|
|
@@ -9645,6 +10191,7 @@ const cloudbase_manager_js_1 = __webpack_require__(3431);
|
|
|
9645
10191
|
const logger_js_1 = __webpack_require__(3039);
|
|
9646
10192
|
const gateway_access_urls_js_1 = __webpack_require__(2435);
|
|
9647
10193
|
const notification_js_1 = __webpack_require__(2720);
|
|
10194
|
+
const capi_js_1 = __webpack_require__(738);
|
|
9648
10195
|
const cloudrun_config_js_1 = __webpack_require__(8266);
|
|
9649
10196
|
// CloudRun service types
|
|
9650
10197
|
exports.CLOUDRUN_SERVICE_TYPES = ['function', 'container'];
|
|
@@ -9654,7 +10201,7 @@ exports.CLOUDRUN_ACCESS_TYPES = ['OA', 'PUBLIC', 'MINIAPP', 'VPC'];
|
|
|
9654
10201
|
exports.CLOUDRUN_PACKAGE_TYPES = ['Trial', 'Standard', 'Professional', 'Enterprise'];
|
|
9655
10202
|
// Input schema for queryCloudRun tool
|
|
9656
10203
|
const queryCloudRunInputSchema = {
|
|
9657
|
-
action: zod_1.z.enum(['list', 'detail', 'templates', 'getDeployLog', 'envStatus']).describe('查询操作类型:list=获取云托管服务列表(支持分页和筛选),detail=查询指定服务的详细信息(包含服务配置和最新部署状态),templates=获取可用的项目模板列表(用于初始化新项目),getDeployLog
|
|
10204
|
+
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之前确认环境是否就绪'),
|
|
9658
10205
|
// List operation parameters
|
|
9659
10206
|
pageSize: zod_1.z.number().min(1).max(100).optional().default(10).describe('分页大小,控制每页返回的服务数量。取值范围:1-100,默认值:10。建议根据网络性能和显示需求调整'),
|
|
9660
10207
|
pageNum: zod_1.z.number().min(1).optional().default(1).describe('页码,用于分页查询。从1开始,默认值:1。配合pageSize使用可实现分页浏览'),
|
|
@@ -9662,19 +10209,26 @@ const queryCloudRunInputSchema = {
|
|
|
9662
10209
|
serverType: zod_1.z.enum(exports.CLOUDRUN_SERVICE_TYPES).optional().describe('服务类型筛选条件:function=函数型云托管(仅支持Node.js,有特殊的开发要求和限制,适合简单的API服务),container=容器型服务(推荐使用,支持任意语言和框架如Java/Go/Python/PHP/.NET等,适合大多数应用场景)'),
|
|
9663
10210
|
envId: zod_1.z.string().optional().describe('环境 ID(action=envStatus 时使用;不传则使用当前配置的环境)。格式如 env-xxxxxx'),
|
|
9664
10211
|
// Detail and log operation parameters
|
|
9665
|
-
detailServerName: zod_1.z.string().optional().describe('
|
|
9666
|
-
buildId: zod_1.z.number().optional().describe('构建ID,仅在action=getDeployLog
|
|
10212
|
+
detailServerName: zod_1.z.string().optional().describe('要查询详细信息、部署记录、构建日志或运行日志的服务名称。当action为detail、getDeployLog、getProcessLog或getDeployRecords时建议提供,必须是已存在的服务名称。可通过list操作获取可用的服务名称列表'),
|
|
10213
|
+
buildId: zod_1.z.number().optional().describe('构建ID,仅在action=getDeployLog时使用(构建日志,仅云端源码构建)。不传时默认返回最近一次部署的构建日志'),
|
|
10214
|
+
runId: zod_1.z.string().optional().describe('运行ID(RunId),仅在action=getProcessLog时使用。不传时默认取该服务最近一次部署记录的 RunId(与 detail/getDeployRecords 的 latestDeploy.RunId 同源)。镜像部署与源码构建均可查询运行日志'),
|
|
9667
10215
|
};
|
|
9668
10216
|
// Input schema for manageCloudRun tool
|
|
9669
10217
|
const ManageCloudRunInputSchema = {
|
|
9670
|
-
action: zod_1.z.enum(['init', 'download', 'run', 'deploy', 'delete', 'createAgent', 'updateConfig', 'initEnv']).describe('云托管服务管理操作类型:init=从模板初始化新的云托管项目代码(在targetPath目录下创建以serverName命名的子目录,支持多种语言和框架模板),download=从云端下载现有服务的代码到本地进行开发,run=在本地运行函数型云托管服务(用于开发和调试,仅支持函数型服务),deploy
|
|
10218
|
+
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 命令)'),
|
|
9671
10219
|
serverName: zod_1.z.string().describe('云托管服务名称,用于标识和管理服务。命名规则:支持大小写字母、数字、连字符和下划线,必须以字母开头,长度3-45个字符。在init操作中会作为在targetPath下创建的子目录名,在其他操作中作为目标服务名。initEnv 操作不需要此参数'),
|
|
10220
|
+
// Traffic management operation parameters (action=traffic)
|
|
10221
|
+
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)'),
|
|
10222
|
+
stablePercent: zod_1.z.number().min(0).max(100).optional().describe('稳定版本流量比例(trafficOp=set 时使用),取值范围0-100。与 canaryPercent 之和必须等于100。例如希望 90% 流量打到稳定版、10% 打到灰度版,则 stablePercent=90, canaryPercent=10'),
|
|
10223
|
+
canaryPercent: zod_1.z.number().min(0).max(100).optional().describe('灰度版本流量比例(trafficOp=set 时使用),取值范围0-100。与 stablePercent 之和必须等于100。例如希望 90% 流量打到稳定版、10% 打到灰度版,则 stablePercent=90, canaryPercent=10'),
|
|
9672
10224
|
// InitEnv operation parameters
|
|
9673
10225
|
envId: zod_1.z.string().optional().describe('环境 ID(action=initEnv 时使用;不传则使用当前配置的环境)。格式如 env-xxxxxx'),
|
|
9674
10226
|
packageType: zod_1.z.enum(exports.CLOUDRUN_PACKAGE_TYPES).optional().default('Trial').describe('云托管环境套餐类型(action=initEnv 时使用):Trial=试用,Standard=标准,Professional=专业,Enterprise=企业。默认 Trial'),
|
|
10227
|
+
vpcId: zod_1.z.string().optional().describe('VPC 网络 ID(action=initEnv 时可选)。当平台拒绝系统创建网络时必填,格式如 vpc-xxxxxxxx。与 subnetIds 一起透传给 CreateCloudRunEnv 的 VpcId/SubNetIds。多数场景可不传(由系统创建网络)'),
|
|
10228
|
+
subnetIds: zod_1.z.array(zod_1.z.string()).optional().describe('子网 ID 列表(action=initEnv 时可选)。当需指定自有 VPC 时必填,如 ["subnet-xxxxxxxx"]。与 vpcId 一起透传给 CreateCloudRunEnv 的 SubNetIds'),
|
|
9675
10229
|
// Deploy operation parameters
|
|
9676
|
-
targetPath: zod_1.z.string().optional().describe('本地代码路径,必须是绝对路径。在deploy操作中指定要部署的代码目录,在download操作中指定下载目标目录,在init操作中指定云托管服务的上级目录(会在该目录下创建以serverName命名的子目录)。updateConfig 不需要此参数。建议约定:项目根目录下的cloudrun/目录,例如:/Users/username/projects/my-project/cloudrun。使用 imageUrl
|
|
9677
|
-
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
|
|
10230
|
+
targetPath: zod_1.z.string().optional().describe('本地代码路径,必须是绝对路径。在deploy操作中指定要部署的代码目录,在download操作中指定下载目标目录,在init操作中指定云托管服务的上级目录(会在该目录下创建以serverName命名的子目录)。updateConfig 不需要此参数。建议约定:项目根目录下的cloudrun/目录,例如:/Users/username/projects/my-project/cloudrun。使用 imageUrl 部署已有镜像时此参数可省略。注意:本地有源码目录不等于必须走源码构建;若用户指定镜像请优先传 imageUrl,不要仅因存在 targetPath 就回退到源码构建'),
|
|
10231
|
+
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 后再部署)'),
|
|
9678
10232
|
envParamsReplaceAll: zod_1.z.boolean().optional().default(false).describe('EnvParams 合并策略(deploy / updateConfig):false(默认)= 与远程按 key 合并(输入覆盖同名 key,远程其余 key 保留);true= 用输入 EnvParams 整包替换远程。仅当显式传入 EnvParams 时生效'),
|
|
9679
10233
|
serverConfig: zod_1.z.object({
|
|
9680
10234
|
OpenAccessTypes: zod_1.z.array(zod_1.z.enum(exports.CLOUDRUN_ACCESS_TYPES)).optional().describe('公网访问类型配置,控制服务的访问权限:OA=办公网访问,PUBLIC=公网访问(默认,可通过HTTPS域名访问),MINIAPP=小程序访问,VPC=VPC访问(仅同VPC内可访问)。可配置多个类型'),
|
|
@@ -9695,7 +10249,7 @@ const ManageCloudRunInputSchema = {
|
|
|
9695
10249
|
InternalDomain: zod_1.z.string().optional().describe('内网域名配置,用于配置服务的内网访问域名。仅在启用内网访问时有效'),
|
|
9696
10250
|
EntryPoint: zod_1.z.array(zod_1.z.string()).optional().describe('Dockerfile EntryPoint参数配置,仅容器型服务需要。指定容器启动时的入口程序数组,如["node","app.js"]'),
|
|
9697
10251
|
Cmd: zod_1.z.array(zod_1.z.string()).optional().describe('Dockerfile Cmd参数配置,仅容器型服务需要。指定容器启动时的默认命令数组,如["npm","start"]'),
|
|
9698
|
-
InitialDelaySeconds: zod_1.z.number().min(0).optional().describe('
|
|
10252
|
+
InitialDelaySeconds: zod_1.z.number().min(0).optional().describe('端口健康检查初始延迟(秒)。部署完成后先等待 N 秒才开始端口探测,之后约每 5s 检查一次、连续约 30 次;30 次全失败才判定部署失败(约 150s 探测窗口),不是「N 秒后立即失败」。启动耗时长的应用建议调到 60–120'),
|
|
9699
10253
|
LogType: zod_1.z.string().optional().describe('日志类型配置,指定服务的日志收集类型。影响日志的采集方式和存储格式'),
|
|
9700
10254
|
LogSetId: zod_1.z.string().optional().describe('CLS日志集ID配置,指定日志服务(CLS)的日志集ID。需要先开通CLS日志服务'),
|
|
9701
10255
|
LogTopicId: zod_1.z.string().optional().describe('CLS日志主题ID配置,指定日志服务(CLS)的日志主题ID。需要先开通CLS日志服务'),
|
|
@@ -9809,54 +10363,336 @@ function validateAndNormalizePath(inputPath) {
|
|
|
9809
10363
|
function buildManageCloudRunErrorMessage(action, serverName, error) {
|
|
9810
10364
|
const baseMessage = error instanceof Error ? error.message : String(error);
|
|
9811
10365
|
const suggestions = [];
|
|
10366
|
+
if ((0, capi_js_1.isCamAuthError)(baseMessage)) {
|
|
10367
|
+
suggestions.push((0, capi_js_1.buildCamAuthGuidance)());
|
|
10368
|
+
}
|
|
9812
10369
|
if (/已有部署发布任务运行中|部署发布任务运行中/i.test(baseMessage)) {
|
|
9813
10370
|
suggestions.push(`服务 \`${serverName}\` 当前已有部署任务在执行,请等待现有任务完成后再重试。`);
|
|
9814
10371
|
suggestions.push("如果你确认要覆盖当前流程,可在合适时机使用 `force=true` 再次发起。");
|
|
9815
10372
|
}
|
|
10373
|
+
if (/云托管资源未开通|无法使用系统创建网络|VpcInfo/i.test(baseMessage)) {
|
|
10374
|
+
suggestions.push("CreateCloudRunServer 需要有效 VPC:请传 serverConfig.VpcConf(VpcId+SubnetId)," +
|
|
10375
|
+
"或在 initEnv 时传入 vpcId/subnetIds(环境开通后 deploy 会自动从 EnvBaseInfo 回填)。" +
|
|
10376
|
+
"若平台拒绝系统创建网络,必须指定上海地域 VPC。");
|
|
10377
|
+
}
|
|
9816
10378
|
if (suggestions.length === 0) {
|
|
9817
10379
|
suggestions.push("请检查服务状态、部署参数和目标目录后重试。");
|
|
9818
10380
|
}
|
|
9819
10381
|
return `[manageCloudRun/${action}] ${baseMessage}\n建议:${suggestions.join(" ")}`;
|
|
9820
10382
|
}
|
|
9821
|
-
|
|
9822
|
-
|
|
9823
|
-
|
|
9824
|
-
|
|
9825
|
-
|
|
9826
|
-
|
|
9827
|
-
|
|
9828
|
-
|
|
10383
|
+
/**
|
|
10384
|
+
* Lightweight wait after manageCloudRun deploy: poll until the platform has
|
|
10385
|
+
* registered the manage task / assigned identifiers for follow-up log queries.
|
|
10386
|
+
* - source builds: prefer BuildId > 0 (getDeployLog)
|
|
10387
|
+
* - image deploys: prefer RunId (getProcessLog; BuildId is often 0)
|
|
10388
|
+
* Does NOT wait for the full build/deploy (that can take 5–30 minutes).
|
|
10389
|
+
* Aligns with tcb CLI's DescribeServerManageTask polling entrypoint, but with
|
|
10390
|
+
* a short timeout suitable for MCP tool calls.
|
|
10391
|
+
*/
|
|
10392
|
+
exports.CLOUDRUN_DEPLOY_REGISTRATION_MAX_WAIT_MS = 45_000;
|
|
10393
|
+
exports.CLOUDRUN_DEPLOY_REGISTRATION_INTERVAL_MS = 3_000;
|
|
10394
|
+
function sleepMs(ms) {
|
|
10395
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
10396
|
+
}
|
|
10397
|
+
function isValidCloudRunBuildId(value) {
|
|
10398
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0;
|
|
10399
|
+
}
|
|
10400
|
+
function isValidCloudRunRunId(value) {
|
|
10401
|
+
return typeof value === "string" && value.trim().length > 0;
|
|
10402
|
+
}
|
|
10403
|
+
function extractServerManageTaskInfo(resp) {
|
|
10404
|
+
const data = (resp ?? {});
|
|
10405
|
+
const task = (data.Task ?? data.task ?? {});
|
|
10406
|
+
const rawId = task.Id ?? task.id;
|
|
10407
|
+
const rawStatus = task.Status ?? task.status;
|
|
10408
|
+
const taskId = typeof rawId === "number" && rawId > 0
|
|
10409
|
+
? rawId
|
|
10410
|
+
: typeof rawId === "string" && /^\d+$/.test(rawId) && Number(rawId) > 0
|
|
10411
|
+
? Number(rawId)
|
|
10412
|
+
: undefined;
|
|
10413
|
+
const taskStatus = typeof rawStatus === "string" && rawStatus.trim()
|
|
10414
|
+
? rawStatus.trim()
|
|
10415
|
+
: undefined;
|
|
10416
|
+
return {
|
|
10417
|
+
...(taskId !== undefined ? { taskId } : {}),
|
|
10418
|
+
...(taskStatus ? { taskStatus } : {}),
|
|
10419
|
+
};
|
|
9829
10420
|
}
|
|
9830
10421
|
/**
|
|
9831
|
-
*
|
|
9832
|
-
*
|
|
10422
|
+
* Poll DescribeServerManageTask + getDeployRecords until the preferred
|
|
10423
|
+
* identifier appears:
|
|
10424
|
+
* - source (default): BuildId > 0 for getDeployLog
|
|
10425
|
+
* - image: RunId for getProcessLog (BuildId is often 0)
|
|
10426
|
+
* If only taskId is seen, keeps polling for the preferred id until maxWaitMs.
|
|
9833
10427
|
*/
|
|
9834
|
-
async function
|
|
9835
|
-
const
|
|
9836
|
-
|
|
9837
|
-
|
|
9838
|
-
|
|
9839
|
-
|
|
9840
|
-
|
|
9841
|
-
|
|
9842
|
-
|
|
9843
|
-
|
|
9844
|
-
|
|
10428
|
+
async function waitForCloudRunDeployRegistration(options) {
|
|
10429
|
+
const mode = options.mode ?? "source";
|
|
10430
|
+
const maxWaitMs = options.maxWaitMs ?? exports.CLOUDRUN_DEPLOY_REGISTRATION_MAX_WAIT_MS;
|
|
10431
|
+
const intervalMs = options.intervalMs ?? exports.CLOUDRUN_DEPLOY_REGISTRATION_INTERVAL_MS;
|
|
10432
|
+
const sleepFn = options.sleepFn ?? sleepMs;
|
|
10433
|
+
const startAt = Date.now();
|
|
10434
|
+
let lastTaskId;
|
|
10435
|
+
let lastTaskStatus;
|
|
10436
|
+
let lastBuildId;
|
|
10437
|
+
let lastRunId;
|
|
10438
|
+
// Immediate first probe, then interval retries until timeout.
|
|
10439
|
+
for (;;) {
|
|
10440
|
+
if (options.manager.commonService) {
|
|
10441
|
+
try {
|
|
10442
|
+
const resp = await options.manager
|
|
10443
|
+
.commonService("tcbr", "2022-02-17")
|
|
10444
|
+
.call({
|
|
10445
|
+
Action: "DescribeServerManageTask",
|
|
10446
|
+
Param: {
|
|
10447
|
+
EnvId: options.envId,
|
|
10448
|
+
ServerName: options.serverName,
|
|
10449
|
+
TaskId: lastTaskId ?? 0,
|
|
10450
|
+
},
|
|
10451
|
+
});
|
|
10452
|
+
const info = extractServerManageTaskInfo(resp);
|
|
10453
|
+
if (info.taskId !== undefined) {
|
|
10454
|
+
lastTaskId = info.taskId;
|
|
10455
|
+
}
|
|
10456
|
+
if (info.taskStatus) {
|
|
10457
|
+
lastTaskStatus = info.taskStatus;
|
|
10458
|
+
}
|
|
10459
|
+
}
|
|
10460
|
+
catch {
|
|
10461
|
+
// Task may not be queryable yet; retry until timeout.
|
|
10462
|
+
}
|
|
10463
|
+
}
|
|
10464
|
+
if (typeof options.cloudrunService.getDeployRecords === "function") {
|
|
10465
|
+
try {
|
|
10466
|
+
const recordsResult = (await options.cloudrunService.getDeployRecords({
|
|
10467
|
+
serverName: options.serverName,
|
|
10468
|
+
}));
|
|
10469
|
+
const latest = recordsResult?.DeployRecords?.[0];
|
|
10470
|
+
if (isValidCloudRunBuildId(latest?.BuildId)) {
|
|
10471
|
+
lastBuildId = latest.BuildId;
|
|
10472
|
+
}
|
|
10473
|
+
if (isValidCloudRunRunId(latest?.RunId)) {
|
|
10474
|
+
lastRunId = latest.RunId.trim();
|
|
10475
|
+
}
|
|
10476
|
+
}
|
|
10477
|
+
catch {
|
|
10478
|
+
// Deploy record may lag behind task registration; retry.
|
|
10479
|
+
}
|
|
10480
|
+
}
|
|
10481
|
+
const preferredReady = mode === "image"
|
|
10482
|
+
? isValidCloudRunRunId(lastRunId)
|
|
10483
|
+
: isValidCloudRunBuildId(lastBuildId);
|
|
10484
|
+
if (preferredReady) {
|
|
10485
|
+
return {
|
|
10486
|
+
registered: true,
|
|
10487
|
+
timedOut: false,
|
|
10488
|
+
taskId: lastTaskId,
|
|
10489
|
+
...(isValidCloudRunBuildId(lastBuildId) ? { buildId: lastBuildId } : {}),
|
|
10490
|
+
...(isValidCloudRunRunId(lastRunId) ? { runId: lastRunId } : {}),
|
|
10491
|
+
taskStatus: lastTaskStatus,
|
|
10492
|
+
waitMs: Date.now() - startAt,
|
|
10493
|
+
};
|
|
10494
|
+
}
|
|
10495
|
+
if (Date.now() - startAt >= maxWaitMs) {
|
|
10496
|
+
break;
|
|
10497
|
+
}
|
|
10498
|
+
await sleepFn(intervalMs);
|
|
9845
10499
|
}
|
|
9846
|
-
const
|
|
9847
|
-
|
|
9848
|
-
|
|
9849
|
-
|
|
9850
|
-
|
|
10500
|
+
const registered = isValidCloudRunBuildId(lastBuildId) ||
|
|
10501
|
+
isValidCloudRunRunId(lastRunId) ||
|
|
10502
|
+
(typeof lastTaskId === "number" && lastTaskId > 0);
|
|
10503
|
+
return {
|
|
10504
|
+
registered,
|
|
10505
|
+
timedOut: true,
|
|
10506
|
+
taskId: lastTaskId,
|
|
10507
|
+
...(isValidCloudRunBuildId(lastBuildId) ? { buildId: lastBuildId } : {}),
|
|
10508
|
+
...(isValidCloudRunRunId(lastRunId) ? { runId: lastRunId } : {}),
|
|
10509
|
+
taskStatus: lastTaskStatus,
|
|
10510
|
+
waitMs: Date.now() - startAt,
|
|
10511
|
+
};
|
|
9851
10512
|
}
|
|
9852
10513
|
/**
|
|
9853
|
-
*
|
|
9854
|
-
*
|
|
9855
|
-
*
|
|
9856
|
-
|
|
9857
|
-
|
|
9858
|
-
|
|
9859
|
-
|
|
10514
|
+
* Build manageCloudRun(deploy) next_step by DeployType:
|
|
10515
|
+
* - source: getDeployLog (+ follow-up getProcessLog)
|
|
10516
|
+
* - image: skip getDeployLog; getProcessLog via RunId (or getDeployRecords first)
|
|
10517
|
+
*/
|
|
10518
|
+
function buildCloudRunDeployNextStep(options) {
|
|
10519
|
+
const { deployType, serverName, registered } = options;
|
|
10520
|
+
if (deployType === "image") {
|
|
10521
|
+
if (isValidCloudRunRunId(options.runId)) {
|
|
10522
|
+
return {
|
|
10523
|
+
tool: "queryCloudRun",
|
|
10524
|
+
action: "getProcessLog",
|
|
10525
|
+
suggested_args: {
|
|
10526
|
+
action: "getProcessLog",
|
|
10527
|
+
detailServerName: serverName,
|
|
10528
|
+
runId: options.runId.trim(),
|
|
10529
|
+
},
|
|
10530
|
+
note: "Image deploy has no CODING build process; skip getDeployLog. Poll getProcessLog for deploy-step and container runtime logs.",
|
|
10531
|
+
};
|
|
10532
|
+
}
|
|
10533
|
+
return {
|
|
10534
|
+
tool: "queryCloudRun",
|
|
10535
|
+
action: "getDeployRecords",
|
|
10536
|
+
suggested_args: {
|
|
10537
|
+
action: "getDeployRecords",
|
|
10538
|
+
detailServerName: serverName,
|
|
10539
|
+
},
|
|
10540
|
+
note: registered
|
|
10541
|
+
? "Image deploy: read latestDeploy.RunId, then queryCloudRun(action=\"getProcessLog\", runId=...). Skip getDeployLog."
|
|
10542
|
+
: "Image deploy registration still queueing; retry getDeployRecords for RunId, then getProcessLog. Skip getDeployLog.",
|
|
10543
|
+
};
|
|
10544
|
+
}
|
|
10545
|
+
if (isValidCloudRunBuildId(options.buildId)) {
|
|
10546
|
+
return {
|
|
10547
|
+
tool: "queryCloudRun",
|
|
10548
|
+
action: "getDeployLog",
|
|
10549
|
+
suggested_args: {
|
|
10550
|
+
action: "getDeployLog",
|
|
10551
|
+
detailServerName: serverName,
|
|
10552
|
+
buildId: options.buildId,
|
|
10553
|
+
},
|
|
10554
|
+
note: "Source build: poll getDeployLog for build progress, then getProcessLog (RunId from detail/getDeployRecords) for runtime/deploy-step logs.",
|
|
10555
|
+
};
|
|
10556
|
+
}
|
|
10557
|
+
return {
|
|
10558
|
+
tool: "queryCloudRun",
|
|
10559
|
+
action: "getDeployLog",
|
|
10560
|
+
suggested_args: {
|
|
10561
|
+
action: "getDeployLog",
|
|
10562
|
+
detailServerName: serverName,
|
|
10563
|
+
},
|
|
10564
|
+
note: registered
|
|
10565
|
+
? "BuildId not yet available; omit buildId to use the latest deploy record. After build, use getProcessLog for runtime logs."
|
|
10566
|
+
: "Registration timed out; wait a moment then retry getDeployLog, or open consoleUrl. After build, use getProcessLog for runtime logs.",
|
|
10567
|
+
};
|
|
10568
|
+
}
|
|
10569
|
+
function buildCloudRunDeployProgressHint(options) {
|
|
10570
|
+
const { deployType, serverName, consoleUrl } = options;
|
|
10571
|
+
if (deployType === "image") {
|
|
10572
|
+
if (isValidCloudRunRunId(options.runId)) {
|
|
10573
|
+
return ` Image deploy: use queryCloudRun(action="getProcessLog", detailServerName="${serverName}", runId="${options.runId.trim()}") for runtime/deploy-step logs (skip getDeployLog).`;
|
|
10574
|
+
}
|
|
10575
|
+
if (options.registered) {
|
|
10576
|
+
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}.`;
|
|
10577
|
+
}
|
|
10578
|
+
return ` Image deploy registration timed out after ${Math.round(options.waitMs / 1000)}s — retry getDeployRecords for RunId then getProcessLog (skip getDeployLog), or check ${consoleUrl}.`;
|
|
10579
|
+
}
|
|
10580
|
+
if (isValidCloudRunBuildId(options.buildId)) {
|
|
10581
|
+
return ` Use queryCloudRun(action="getDeployLog", detailServerName="${serverName}", buildId=${options.buildId}) to poll build progress, then getProcessLog for runtime logs.`;
|
|
10582
|
+
}
|
|
10583
|
+
if (options.registered) {
|
|
10584
|
+
return ` Task registered (taskId=${options.taskId ?? "unknown"}); BuildId not yet available — retry queryCloudRun(action="getDeployLog", detailServerName="${serverName}") shortly, then getProcessLog, or check ${consoleUrl}.`;
|
|
10585
|
+
}
|
|
10586
|
+
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.`;
|
|
10587
|
+
}
|
|
10588
|
+
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;
|
|
10589
|
+
const CLOUDRUN_DB_URL_PATTERN = /(mysql|mariadb|postgres|postgresql|mongodb(\+srv)?|redis|rediss):\/\//i;
|
|
10590
|
+
async function queryCloudRunEnvStatus(options) {
|
|
10591
|
+
const manager = await (0, cloudbase_manager_js_1.getCloudBaseManager)({ cloudBaseOptions: options.cloudBaseOptions });
|
|
10592
|
+
if (!manager?.commonService) {
|
|
10593
|
+
throw new Error("Current CloudBase Manager does not support commonService; cannot query CloudRun env status.");
|
|
10594
|
+
}
|
|
10595
|
+
return describeCloudRunEnvStatus(manager, options.envId);
|
|
10596
|
+
}
|
|
10597
|
+
/**
|
|
10598
|
+
* 核心实现:用已获取的 manager 查询云托管开通状态(供 initEnv/envStatus 及
|
|
10599
|
+
* ensureCloudRunEnvInitialized 复用,避免重复 getCloudBaseManager)。
|
|
10600
|
+
*/
|
|
10601
|
+
async function describeCloudRunEnvStatus(manager, envId) {
|
|
10602
|
+
const result = await manager
|
|
10603
|
+
.commonService("tcbr", "2022-02-17")
|
|
10604
|
+
.call({
|
|
10605
|
+
Action: "DescribeEnvBaseInfo",
|
|
10606
|
+
Param: { EnvId: envId },
|
|
10607
|
+
});
|
|
10608
|
+
const data = (result ?? {});
|
|
10609
|
+
const baseInfo = (data.EnvBaseInfo ?? {}) ?? {};
|
|
10610
|
+
if (data.IsExist !== true) {
|
|
10611
|
+
return { isExist: false, status: "unopened", baseInfo };
|
|
10612
|
+
}
|
|
10613
|
+
const rawStatus = typeof baseInfo.Status === "string" ? baseInfo.Status : "";
|
|
10614
|
+
// Platform may return NORMAL/CREATING (uppercase); normalize before matching.
|
|
10615
|
+
const normalizedStatus = rawStatus.toLowerCase();
|
|
10616
|
+
const status = normalizedStatus === "creating" || normalizedStatus === "normal"
|
|
10617
|
+
? normalizedStatus
|
|
10618
|
+
: "unknown";
|
|
10619
|
+
return { isExist: true, status, baseInfo };
|
|
10620
|
+
}
|
|
10621
|
+
/** CloudRun EnvType for CreateCloudRunEnv (tcbr DescribeEnvBaseInfo enum). */
|
|
10622
|
+
exports.CLOUDRUN_ENV_TYPE = "tcbr";
|
|
10623
|
+
/**
|
|
10624
|
+
* Extract VPC binding from DescribeEnvBaseInfo.EnvBaseInfo when the env was
|
|
10625
|
+
* opened with an explicit VPC.
|
|
10626
|
+
*/
|
|
10627
|
+
function extractEnvBaseInfoVpc(baseInfo) {
|
|
10628
|
+
if (!baseInfo) {
|
|
10629
|
+
return undefined;
|
|
10630
|
+
}
|
|
10631
|
+
const vpcId = typeof baseInfo.VpcId === "string" ? baseInfo.VpcId.trim() : "";
|
|
10632
|
+
const rawSubnets = baseInfo.SubNetIds ?? baseInfo.SubnetIds;
|
|
10633
|
+
const subnetIds = Array.isArray(rawSubnets)
|
|
10634
|
+
? rawSubnets
|
|
10635
|
+
.filter((item) => typeof item === "string" && item.trim().length > 0)
|
|
10636
|
+
.map((item) => item.trim())
|
|
10637
|
+
: [];
|
|
10638
|
+
if (!vpcId || subnetIds.length === 0) {
|
|
10639
|
+
return undefined;
|
|
10640
|
+
}
|
|
10641
|
+
return { VpcId: vpcId, SubnetIds: subnetIds };
|
|
10642
|
+
}
|
|
10643
|
+
/**
|
|
10644
|
+
* Resolve CreateCloudRunServer.VpcInfo: prefer explicit serverConfig.VpcConf,
|
|
10645
|
+
* otherwise fall back to env-level VPC from DescribeEnvBaseInfo.
|
|
10646
|
+
*/
|
|
10647
|
+
function resolveCloudRunDeployVpcInfo(options) {
|
|
10648
|
+
const conf = options.vpcConf;
|
|
10649
|
+
if (conf?.VpcId?.trim() && conf?.SubnetId?.trim()) {
|
|
10650
|
+
return {
|
|
10651
|
+
VpcId: conf.VpcId.trim(),
|
|
10652
|
+
CreateType: 2,
|
|
10653
|
+
SubnetIds: [conf.SubnetId.trim()],
|
|
10654
|
+
};
|
|
10655
|
+
}
|
|
10656
|
+
const fromEnv = extractEnvBaseInfoVpc(options.envBaseInfo);
|
|
10657
|
+
if (!fromEnv) {
|
|
10658
|
+
return undefined;
|
|
10659
|
+
}
|
|
10660
|
+
return {
|
|
10661
|
+
VpcId: fromEnv.VpcId,
|
|
10662
|
+
CreateType: 2,
|
|
10663
|
+
SubnetIds: fromEnv.SubnetIds,
|
|
10664
|
+
};
|
|
10665
|
+
}
|
|
10666
|
+
/**
|
|
10667
|
+
* Build CreateCloudRunEnv Param, always including EnvType=tcbr.
|
|
10668
|
+
* Optional vpcId/subnetIds are used when the platform requires an explicit VPC.
|
|
10669
|
+
*/
|
|
10670
|
+
function buildCreateCloudRunEnvParam(options) {
|
|
10671
|
+
const param = {
|
|
10672
|
+
EnvId: options.envId,
|
|
10673
|
+
PackageType: options.packageType,
|
|
10674
|
+
EnvType: exports.CLOUDRUN_ENV_TYPE,
|
|
10675
|
+
};
|
|
10676
|
+
const vpcId = options.vpcId?.trim();
|
|
10677
|
+
const subnetIds = (options.subnetIds ?? [])
|
|
10678
|
+
.filter((id) => typeof id === "string" && id.trim().length > 0)
|
|
10679
|
+
.map((id) => id.trim());
|
|
10680
|
+
if (vpcId) {
|
|
10681
|
+
param.VpcId = vpcId;
|
|
10682
|
+
}
|
|
10683
|
+
if (subnetIds.length > 0) {
|
|
10684
|
+
param.SubNetIds = subnetIds;
|
|
10685
|
+
}
|
|
10686
|
+
return param;
|
|
10687
|
+
}
|
|
10688
|
+
/**
|
|
10689
|
+
* 探测当前环境云托管(大租户)是否已初始化。
|
|
10690
|
+
*
|
|
10691
|
+
* 背景(2026-08-13 用户实测):新环境未调 CreateCloudRunEnv 初始化云托管时,
|
|
10692
|
+
* 直接 CreateCloudRunServer 会因"无大租户记录"被默认转入小租户,创建出小租户的
|
|
10693
|
+
* 服务和版本——这是错误路径。本函数在 deploy 创建新服务前用 tcbr DescribeEnvBaseInfo
|
|
10694
|
+
* 探测环境是否已开通云托管;未开通则抛错引导先初始化,而不是默默走到小租户路径。
|
|
10695
|
+
*
|
|
9860
10696
|
* 实测(2026-08-13 真实凭据):tcbr 不存在 DescribeCloudRunEnv(单数)Action,调用
|
|
9861
10697
|
* 恒返回 InvalidAction;正确的探测接口是 DescribeEnvBaseInfo。未开通云托管的环境返回
|
|
9862
10698
|
* IsExist=false 且 EnvBaseInfo 为空结构(不抛错);已开通的环境(实测 ai-share-
|
|
@@ -10058,7 +10894,7 @@ function registerCloudRunTools(server) {
|
|
|
10058
10894
|
// Tool 1: Get CloudRun service information (read operations)
|
|
10059
10895
|
server.registerTool("queryCloudRun", {
|
|
10060
10896
|
title: "查询 CloudRun 服务信息",
|
|
10061
|
-
description: "
|
|
10897
|
+
description: "查询云托管服务信息,支持获取服务列表、查询服务详情、获取可用模板列表、获取构建日志(getDeployLog,仅云端源码构建/依赖 CODING)、获取运行日志(getProcessLog,镜像与源码部署均可/不依赖 CODING)、获取部署记录以及查询环境云托管开通状态(envStatus)。返回的服务信息包括服务名称、状态、访问类型、配置详情以及最近部署上下文。",
|
|
10062
10898
|
inputSchema: queryCloudRunInputSchema,
|
|
10063
10899
|
annotations: {
|
|
10064
10900
|
readOnlyHint: true,
|
|
@@ -10146,10 +10982,13 @@ function registerCloudRunTools(server) {
|
|
|
10146
10982
|
if (!latestDeploy) {
|
|
10147
10983
|
message = `Retrieved details for service '${serverName}'. No deploy records found yet.`;
|
|
10148
10984
|
}
|
|
10149
|
-
else if (typeof latestDeploy.Status ===
|
|
10150
|
-
|
|
10985
|
+
else if (typeof latestDeploy.Status === "string" &&
|
|
10986
|
+
// Platform may return FAILED/CREATING (uppercase); normalize before matching.
|
|
10987
|
+
latestDeploy.Status.toLowerCase().includes("failed")) {
|
|
10988
|
+
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).`;
|
|
10151
10989
|
}
|
|
10152
|
-
else if (typeof latestDeploy.Status ===
|
|
10990
|
+
else if (typeof latestDeploy.Status === "string" &&
|
|
10991
|
+
latestDeploy.Status.toLowerCase().includes("creating")) {
|
|
10153
10992
|
message = `Service '${serverName}' latest deploy is still running. Please check again later or query the deploy log for progress.`;
|
|
10154
10993
|
}
|
|
10155
10994
|
else {
|
|
@@ -10232,6 +11071,9 @@ function registerCloudRunTools(server) {
|
|
|
10232
11071
|
};
|
|
10233
11072
|
}
|
|
10234
11073
|
const buildId = input.buildId ?? latestDeploy.BuildId;
|
|
11074
|
+
// Build log (CODING / DescribeCloudRunBuildLog). Meaningful only for
|
|
11075
|
+
// cloud source builds; image deploys have no build process. Accounts
|
|
11076
|
+
// without a CODING user may fail here — use getProcessLog for runtime logs.
|
|
10235
11077
|
const buildLogResult = await cloudrunService.getBuildLog({
|
|
10236
11078
|
serverName,
|
|
10237
11079
|
buildId,
|
|
@@ -10262,11 +11104,130 @@ function registerCloudRunTools(server) {
|
|
|
10262
11104
|
buildId,
|
|
10263
11105
|
deployRecord: latestDeploy,
|
|
10264
11106
|
buildLog: buildLogResult?.Log || null,
|
|
11107
|
+
// Optional best-effort attach; prefer dedicated getProcessLog for runtime diagnosis
|
|
10265
11108
|
processLogs,
|
|
10266
11109
|
combinedLogText,
|
|
10267
11110
|
...(processLogsWarning ? { processLogsWarning } : {})
|
|
10268
11111
|
},
|
|
10269
|
-
message: `Retrieved
|
|
11112
|
+
message: `Retrieved build log for service '${serverName}' (getDeployLog=构建日志; for 运行日志 use getProcessLog with RunId)`
|
|
11113
|
+
}, null, 2)
|
|
11114
|
+
}
|
|
11115
|
+
]
|
|
11116
|
+
};
|
|
11117
|
+
}
|
|
11118
|
+
case 'getProcessLog': {
|
|
11119
|
+
const serverName = getCloudRunQueryServerName(input);
|
|
11120
|
+
if (!serverName && !input.runId?.trim()) {
|
|
11121
|
+
return {
|
|
11122
|
+
content: [
|
|
11123
|
+
{
|
|
11124
|
+
type: "text",
|
|
11125
|
+
text: JSON.stringify({
|
|
11126
|
+
success: false,
|
|
11127
|
+
error: "runId is required, or provide detailServerName/serverName to resolve latest RunId",
|
|
11128
|
+
message: "Pass runId from detail/getDeployRecords latestDeploy.RunId, or provide a service name to use the latest deploy RunId."
|
|
11129
|
+
}, null, 2)
|
|
11130
|
+
}
|
|
11131
|
+
]
|
|
11132
|
+
};
|
|
11133
|
+
}
|
|
11134
|
+
let runId = input.runId?.trim() || "";
|
|
11135
|
+
let deployRecord = null;
|
|
11136
|
+
if (serverName) {
|
|
11137
|
+
const deployRecordsResult = await cloudrunService.getDeployRecords({ serverName });
|
|
11138
|
+
const deployRecords = Array.isArray(deployRecordsResult?.DeployRecords)
|
|
11139
|
+
? deployRecordsResult.DeployRecords
|
|
11140
|
+
: [];
|
|
11141
|
+
deployRecord = deployRecords[0] ?? null;
|
|
11142
|
+
if (!runId) {
|
|
11143
|
+
runId = typeof deployRecord?.RunId === "string" ? deployRecord.RunId.trim() : "";
|
|
11144
|
+
}
|
|
11145
|
+
else if (deployRecord?.RunId && deployRecord.RunId !== runId) {
|
|
11146
|
+
// Keep latest deploy as context only; explicit runId wins
|
|
11147
|
+
}
|
|
11148
|
+
}
|
|
11149
|
+
if (!runId) {
|
|
11150
|
+
return {
|
|
11151
|
+
content: [
|
|
11152
|
+
{
|
|
11153
|
+
type: "text",
|
|
11154
|
+
text: JSON.stringify({
|
|
11155
|
+
success: false,
|
|
11156
|
+
error: serverName
|
|
11157
|
+
? `Service '${serverName}' has no RunId on the latest deploy record.`
|
|
11158
|
+
: "runId is required for getProcessLog action",
|
|
11159
|
+
message: "Deploy the service first, then read RunId from queryCloudRun(action=\"detail\") or getDeployRecords (latestDeploy.RunId)."
|
|
11160
|
+
}, null, 2)
|
|
11161
|
+
}
|
|
11162
|
+
]
|
|
11163
|
+
};
|
|
11164
|
+
}
|
|
11165
|
+
if (typeof cloudrunService.getProcessLog !== "function") {
|
|
11166
|
+
throw new Error("Current CloudBase Manager SDK does not support getProcessLog; please upgrade @cloudbase/manager-node.");
|
|
11167
|
+
}
|
|
11168
|
+
const processLogResult = await cloudrunService.getProcessLog({
|
|
11169
|
+
RunId: runId,
|
|
11170
|
+
});
|
|
11171
|
+
const processLogs = Array.isArray(processLogResult?.Logs)
|
|
11172
|
+
? processLogResult.Logs
|
|
11173
|
+
: [];
|
|
11174
|
+
const processLogText = processLogs.length > 0
|
|
11175
|
+
? normalizeProcessLogText(processLogs)
|
|
11176
|
+
: "";
|
|
11177
|
+
return {
|
|
11178
|
+
content: [
|
|
11179
|
+
{
|
|
11180
|
+
type: "text",
|
|
11181
|
+
text: JSON.stringify({
|
|
11182
|
+
success: true,
|
|
11183
|
+
data: {
|
|
11184
|
+
serverName: serverName || undefined,
|
|
11185
|
+
runId,
|
|
11186
|
+
deployRecord,
|
|
11187
|
+
processLogs,
|
|
11188
|
+
processLogText,
|
|
11189
|
+
requestId: processLogResult?.RequestId,
|
|
11190
|
+
},
|
|
11191
|
+
message: `Retrieved process/runtime log for RunId='${runId}' (getProcessLog=运行日志; getDeployLog=构建日志且仅云端构建/依赖 CODING)`
|
|
11192
|
+
}, null, 2)
|
|
11193
|
+
}
|
|
11194
|
+
]
|
|
11195
|
+
};
|
|
11196
|
+
}
|
|
11197
|
+
case 'getDeployRecords': {
|
|
11198
|
+
const serverName = getCloudRunQueryServerName(input);
|
|
11199
|
+
if (!serverName) {
|
|
11200
|
+
return {
|
|
11201
|
+
content: [
|
|
11202
|
+
{
|
|
11203
|
+
type: "text",
|
|
11204
|
+
text: JSON.stringify({
|
|
11205
|
+
success: false,
|
|
11206
|
+
error: "detailServerName or serverName is required for getDeployRecords action",
|
|
11207
|
+
message: "Please provide detailServerName or serverName."
|
|
11208
|
+
}, null, 2)
|
|
11209
|
+
}
|
|
11210
|
+
]
|
|
11211
|
+
};
|
|
11212
|
+
}
|
|
11213
|
+
const deployRecordsResult = await cloudrunService.getDeployRecords({ serverName });
|
|
11214
|
+
const deployRecords = Array.isArray(deployRecordsResult?.DeployRecords)
|
|
11215
|
+
? deployRecordsResult.DeployRecords
|
|
11216
|
+
: [];
|
|
11217
|
+
return {
|
|
11218
|
+
content: [
|
|
11219
|
+
{
|
|
11220
|
+
type: "text",
|
|
11221
|
+
text: JSON.stringify({
|
|
11222
|
+
success: true,
|
|
11223
|
+
data: {
|
|
11224
|
+
serverName,
|
|
11225
|
+
deployRecords,
|
|
11226
|
+
// 部署记录按部署时间倒序(最新在前),首条为最近一次部署
|
|
11227
|
+
total: deployRecords.length,
|
|
11228
|
+
latestDeploy: deployRecords[0] ?? null
|
|
11229
|
+
},
|
|
11230
|
+
message: `Retrieved ${deployRecords.length} deploy records for service '${serverName}'`
|
|
10270
11231
|
}, null, 2)
|
|
10271
11232
|
}
|
|
10272
11233
|
]
|
|
@@ -10340,7 +11301,7 @@ function registerCloudRunTools(server) {
|
|
|
10340
11301
|
// Tool 2: Manage CloudRun services (write operations)
|
|
10341
11302
|
server.registerTool("manageCloudRun", {
|
|
10342
11303
|
title: "管理 CloudRun 服务",
|
|
10343
|
-
description: "管理云托管服务,按开发顺序支持:开通云托管环境(initEnv)、初始化项目(可从模板开始,模板列表可通过 queryCloudRun 查询)、下载服务代码、本地运行(仅函数型服务)、部署代码、仅更新配置(updateConfig,无需重新上传代码)、删除服务。deploy 支持两种方式:1) 源码构建(传入 targetPath,本地代码打包上传,默认路径);2) 已有镜像部署(传入 imageUrl,如 ccr.ccs.tencentyun.com/ns/img:v1,走 DeployType=image 容器型部署,targetPath 可省略)。deploy 对已存在服务会先读取远程配置再合并(保留 VpcConf/EnvParams/OpenAccessTypes)。updateConfig 对齐控制台服务设置页。删除操作需要确认,建议设置force=true。新环境首次部署前若提示未开通云托管,先调用 initEnv 开通(异步、幂等)。",
|
|
11304
|
+
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 开通(异步、幂等)。",
|
|
10344
11305
|
inputSchema: ManageCloudRunInputSchema,
|
|
10345
11306
|
annotations: {
|
|
10346
11307
|
readOnlyHint: false,
|
|
@@ -10420,13 +11381,19 @@ function registerCloudRunTools(server) {
|
|
|
10420
11381
|
};
|
|
10421
11382
|
}
|
|
10422
11383
|
// 未开通 → 发起异步开通(CreateCloudRunEnv 异步,不阻塞等待)。
|
|
11384
|
+
// Always pass EnvType=tcbr; optional vpcId/subnetIds when an explicit VPC is required.
|
|
10423
11385
|
let createResult;
|
|
10424
11386
|
try {
|
|
10425
11387
|
createResult = await manager
|
|
10426
11388
|
.commonService("tcbr", "2022-02-17")
|
|
10427
11389
|
.call({
|
|
10428
11390
|
Action: "CreateCloudRunEnv",
|
|
10429
|
-
Param: {
|
|
11391
|
+
Param: buildCreateCloudRunEnvParam({
|
|
11392
|
+
envId,
|
|
11393
|
+
packageType,
|
|
11394
|
+
vpcId: input.vpcId,
|
|
11395
|
+
subnetIds: input.subnetIds,
|
|
11396
|
+
}),
|
|
10430
11397
|
});
|
|
10431
11398
|
}
|
|
10432
11399
|
catch (error) {
|
|
@@ -10454,6 +11421,98 @@ function registerCloudRunTools(server) {
|
|
|
10454
11421
|
]
|
|
10455
11422
|
};
|
|
10456
11423
|
}
|
|
11424
|
+
case 'traffic': {
|
|
11425
|
+
const trafficOp = input.trafficOp;
|
|
11426
|
+
if (!trafficOp) {
|
|
11427
|
+
throw new Error("trafficOp is required for traffic operation (set | promote | rollback)");
|
|
11428
|
+
}
|
|
11429
|
+
if (trafficOp === 'set') {
|
|
11430
|
+
const stable = input.stablePercent;
|
|
11431
|
+
const canary = input.canaryPercent;
|
|
11432
|
+
if (typeof stable !== 'number' ||
|
|
11433
|
+
typeof canary !== 'number') {
|
|
11434
|
+
throw new Error("stablePercent and canaryPercent are required for trafficOp=set");
|
|
11435
|
+
}
|
|
11436
|
+
if (stable + canary !== 100) {
|
|
11437
|
+
throw new Error(`stablePercent + canaryPercent must equal 100 (got ${stable} + ${canary} = ${stable + canary}). ` +
|
|
11438
|
+
`Example: 90/10 means 90% to stable version, 10% to canary version.`);
|
|
11439
|
+
}
|
|
11440
|
+
let setResult;
|
|
11441
|
+
try {
|
|
11442
|
+
setResult = await cloudrunService.setTraffic(input.serverName, stable, canary);
|
|
11443
|
+
}
|
|
11444
|
+
catch (error) {
|
|
11445
|
+
throw new Error(buildManageCloudRunErrorMessage('traffic/set', input.serverName, error));
|
|
11446
|
+
}
|
|
11447
|
+
return {
|
|
11448
|
+
content: [
|
|
11449
|
+
{
|
|
11450
|
+
type: "text",
|
|
11451
|
+
text: JSON.stringify({
|
|
11452
|
+
success: true,
|
|
11453
|
+
data: {
|
|
11454
|
+
serverName: input.serverName,
|
|
11455
|
+
trafficOp: 'set',
|
|
11456
|
+
stablePercent: stable,
|
|
11457
|
+
canaryPercent: canary,
|
|
11458
|
+
result: setResult ?? null
|
|
11459
|
+
},
|
|
11460
|
+
message: `Set traffic for service '${input.serverName}': stable ${stable}% / canary ${canary}%`
|
|
11461
|
+
}, null, 2)
|
|
11462
|
+
}
|
|
11463
|
+
]
|
|
11464
|
+
};
|
|
11465
|
+
}
|
|
11466
|
+
if (trafficOp === 'promote') {
|
|
11467
|
+
let promoteResult;
|
|
11468
|
+
try {
|
|
11469
|
+
promoteResult = await cloudrunService.promote(input.serverName);
|
|
11470
|
+
}
|
|
11471
|
+
catch (error) {
|
|
11472
|
+
throw new Error(buildManageCloudRunErrorMessage('traffic/promote', input.serverName, error));
|
|
11473
|
+
}
|
|
11474
|
+
return {
|
|
11475
|
+
content: [
|
|
11476
|
+
{
|
|
11477
|
+
type: "text",
|
|
11478
|
+
text: JSON.stringify({
|
|
11479
|
+
success: true,
|
|
11480
|
+
data: {
|
|
11481
|
+
serverName: input.serverName,
|
|
11482
|
+
trafficOp: 'promote',
|
|
11483
|
+
result: promoteResult ?? null
|
|
11484
|
+
},
|
|
11485
|
+
message: `Promoted canary version to full release for service '${input.serverName}' (100% traffic). This is irreversible.`
|
|
11486
|
+
}, null, 2)
|
|
11487
|
+
}
|
|
11488
|
+
]
|
|
11489
|
+
};
|
|
11490
|
+
}
|
|
11491
|
+
// rollback
|
|
11492
|
+
let rollbackResult;
|
|
11493
|
+
try {
|
|
11494
|
+
rollbackResult = await cloudrunService.rollback(input.serverName);
|
|
11495
|
+
}
|
|
11496
|
+
catch (error) {
|
|
11497
|
+
throw new Error(buildManageCloudRunErrorMessage('traffic/rollback', input.serverName, error));
|
|
11498
|
+
}
|
|
11499
|
+
return {
|
|
11500
|
+
content: [
|
|
11501
|
+
{
|
|
11502
|
+
type: "text",
|
|
11503
|
+
text: JSON.stringify({
|
|
11504
|
+
success: true,
|
|
11505
|
+
data: {
|
|
11506
|
+
serverName: input.serverName,
|
|
11507
|
+
trafficOp: 'rollback',
|
|
11508
|
+
result: rollbackResult ?? null
|
|
11509
|
+
},
|
|
11510
|
+
message: `Rolled back service '${input.serverName}' to the previous stable version.`
|
|
11511
|
+
}, null, 2)
|
|
11512
|
+
}
|
|
11513
|
+
]
|
|
11514
|
+
};
|
|
11515
|
+
}
|
|
10457
11516
|
case 'createAgent': {
|
|
10458
11517
|
if (!targetPath) {
|
|
10459
11518
|
throw new Error("targetPath is required for createAgent operation");
|
|
@@ -10719,14 +11778,30 @@ for await (let x of res.textStream) {
|
|
|
10719
11778
|
deployParams.serverConfig = effectiveServerConfig;
|
|
10720
11779
|
}
|
|
10721
11780
|
// Manager SDK create path prefers top-level vpcInfo (CreateCloudRunServer.VpcInfo).
|
|
10722
|
-
//
|
|
11781
|
+
// Prefer serverConfig.VpcConf; if missing, auto-fill from env DescribeEnvBaseInfo
|
|
11782
|
+
// (envs opened with vpcId/subnetIds already carry VpcId/SubNetIds).
|
|
10723
11783
|
const vpcConf = effectiveServerConfig?.VpcConf;
|
|
10724
|
-
|
|
10725
|
-
|
|
10726
|
-
|
|
10727
|
-
|
|
10728
|
-
|
|
10729
|
-
|
|
11784
|
+
let envBaseInfoForVpc = null;
|
|
11785
|
+
const explicitVpcId = vpcConf?.VpcId?.trim() ?? "";
|
|
11786
|
+
const explicitSubnetId = vpcConf?.SubnetId?.trim() ?? "";
|
|
11787
|
+
if (!explicitVpcId || !explicitSubnetId) {
|
|
11788
|
+
try {
|
|
11789
|
+
const envIdForVpc = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
|
|
11790
|
+
const envStatusForVpc = await describeCloudRunEnvStatus(manager, envIdForVpc);
|
|
11791
|
+
if (envStatusForVpc.isExist) {
|
|
11792
|
+
envBaseInfoForVpc = envStatusForVpc.baseInfo;
|
|
11793
|
+
}
|
|
11794
|
+
}
|
|
11795
|
+
catch {
|
|
11796
|
+
// Best-effort: deploy may still succeed without vpcInfo when the platform creates the network.
|
|
11797
|
+
}
|
|
11798
|
+
}
|
|
11799
|
+
const resolvedVpcInfo = resolveCloudRunDeployVpcInfo({
|
|
11800
|
+
vpcConf,
|
|
11801
|
+
envBaseInfo: envBaseInfoForVpc,
|
|
11802
|
+
});
|
|
11803
|
+
if (resolvedVpcInfo) {
|
|
11804
|
+
deployParams.vpcInfo = resolvedVpcInfo;
|
|
10730
11805
|
}
|
|
10731
11806
|
let result;
|
|
10732
11807
|
try {
|
|
@@ -10737,6 +11812,18 @@ for await (let x of res.textStream) {
|
|
|
10737
11812
|
}
|
|
10738
11813
|
// Generate cloudbaserc.json configuration file (source-build only; image deploy has no local project dir)
|
|
10739
11814
|
const currentEnvId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
|
|
11815
|
+
// Lightweight wait for task / BuildId (source) or RunId (image) registration.
|
|
11816
|
+
// Does not wait for full build/deploy completion.
|
|
11817
|
+
const deployType = input.imageUrl
|
|
11818
|
+
? "image"
|
|
11819
|
+
: "source";
|
|
11820
|
+
const registration = await waitForCloudRunDeployRegistration({
|
|
11821
|
+
manager,
|
|
11822
|
+
cloudrunService,
|
|
11823
|
+
envId: currentEnvId,
|
|
11824
|
+
serverName: input.serverName,
|
|
11825
|
+
mode: deployType,
|
|
11826
|
+
});
|
|
10740
11827
|
let cloudbasercGenerated = false;
|
|
10741
11828
|
if (targetPath) {
|
|
10742
11829
|
const cloudbasercPath = path_1.default.join(targetPath, 'cloudbaserc.json');
|
|
@@ -10812,6 +11899,24 @@ for await (let x of res.textStream) {
|
|
|
10812
11899
|
const warningSuffix = dbNetworkRisk
|
|
10813
11900
|
? ` Warning: ${dbNetworkRisk.message} Set serverConfig.VpcConf before relying on DB connectivity.`
|
|
10814
11901
|
: "";
|
|
11902
|
+
const progressHint = buildCloudRunDeployProgressHint({
|
|
11903
|
+
deployType,
|
|
11904
|
+
serverName: input.serverName,
|
|
11905
|
+
buildId: registration.buildId,
|
|
11906
|
+
runId: registration.runId,
|
|
11907
|
+
registered: registration.registered,
|
|
11908
|
+
timedOut: registration.timedOut,
|
|
11909
|
+
waitMs: registration.waitMs,
|
|
11910
|
+
consoleUrl,
|
|
11911
|
+
taskId: registration.taskId,
|
|
11912
|
+
});
|
|
11913
|
+
const nextStep = buildCloudRunDeployNextStep({
|
|
11914
|
+
deployType,
|
|
11915
|
+
serverName: input.serverName,
|
|
11916
|
+
buildId: registration.buildId,
|
|
11917
|
+
runId: registration.runId,
|
|
11918
|
+
registered: registration.registered,
|
|
11919
|
+
});
|
|
10815
11920
|
return {
|
|
10816
11921
|
content: [
|
|
10817
11922
|
{
|
|
@@ -10821,12 +11926,30 @@ for await (let x of res.textStream) {
|
|
|
10821
11926
|
data: {
|
|
10822
11927
|
serviceName: input.serverName,
|
|
10823
11928
|
status: 'deploying',
|
|
10824
|
-
deployType
|
|
11929
|
+
deployType,
|
|
10825
11930
|
...(targetPath ? { deployPath: targetPath } : {}),
|
|
10826
11931
|
...(input.imageUrl ? { imageUrl: input.imageUrl } : {}),
|
|
10827
11932
|
serverType: serverType,
|
|
10828
11933
|
cloudbasercGenerated,
|
|
10829
11934
|
consoleUrl,
|
|
11935
|
+
...(isValidCloudRunBuildId(registration.buildId)
|
|
11936
|
+
? { buildId: registration.buildId }
|
|
11937
|
+
: {}),
|
|
11938
|
+
...(isValidCloudRunRunId(registration.runId)
|
|
11939
|
+
? { runId: registration.runId }
|
|
11940
|
+
: {}),
|
|
11941
|
+
...(typeof registration.taskId === "number"
|
|
11942
|
+
? { taskId: registration.taskId }
|
|
11943
|
+
: {}),
|
|
11944
|
+
registration: {
|
|
11945
|
+
registered: registration.registered,
|
|
11946
|
+
timedOut: registration.timedOut,
|
|
11947
|
+
waitMs: registration.waitMs,
|
|
11948
|
+
...(registration.taskStatus
|
|
11949
|
+
? { taskStatus: registration.taskStatus }
|
|
11950
|
+
: {}),
|
|
11951
|
+
},
|
|
11952
|
+
next_step: nextStep,
|
|
10830
11953
|
...(existingService
|
|
10831
11954
|
? {
|
|
10832
11955
|
configMerge: {
|
|
@@ -10847,8 +11970,10 @@ for await (let x of res.textStream) {
|
|
|
10847
11970
|
? { accessUrlSource: preferredAccessSource }
|
|
10848
11971
|
: {}),
|
|
10849
11972
|
...(warnings.length > 0 ? { warnings } : {}),
|
|
11973
|
+
// Keep raw SDK result for debugging without implying build finished.
|
|
11974
|
+
...(result != null ? { deployAccepted: true } : {}),
|
|
10850
11975
|
},
|
|
10851
|
-
message: `Triggered deployment for ${serverType} service '${input.serverName}' ${input.imageUrl ? `from image ${input.imageUrl}` : `from ${targetPath}`}.
|
|
11976
|
+
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}`
|
|
10852
11977
|
}, null, 2)
|
|
10853
11978
|
}
|
|
10854
11979
|
]
|
|
@@ -11983,7 +13108,7 @@ class TelemetryReporter {
|
|
|
11983
13108
|
const arch = os_1.default.arch(); // 系统架构
|
|
11984
13109
|
// Build-time injected version; guard for vitest / non-webpack runtimes.
|
|
11985
13110
|
const mcpVersion = process.env.npm_package_version ||
|
|
11986
|
-
( true ? "2.
|
|
13111
|
+
( true ? "2.28.0" : 0);
|
|
11987
13112
|
return {
|
|
11988
13113
|
userAgent: `${osType} ${osRelease} ${arch} ${nodeVersion} CloudBase-MCP/${mcpVersion}`,
|
|
11989
13114
|
deviceId: this.deviceId,
|
|
@@ -13934,6 +15059,98 @@ async function resolvePgDbContext(cloudBaseOptions, args) {
|
|
|
13934
15059
|
role: args?.role ?? "cloudbase_admin",
|
|
13935
15060
|
};
|
|
13936
15061
|
}
|
|
15062
|
+
/** Default / recommended roles for CloudBase PG ExecutePGSql.Role */
|
|
15063
|
+
const PG_DEFAULT_ROLE = "cloudbase_admin";
|
|
15064
|
+
const PG_RECOMMENDED_ROLES = [
|
|
15065
|
+
"cloudbase_admin",
|
|
15066
|
+
"anon",
|
|
15067
|
+
"authenticated",
|
|
15068
|
+
"service_role",
|
|
15069
|
+
];
|
|
15070
|
+
/**
|
|
15071
|
+
* Roles that look like login/instance principals and routinely fail SET ROLE
|
|
15072
|
+
* in beacon data (e.g. postgres, postgres_pgdb_<id>). Reject before the API call.
|
|
15073
|
+
*/
|
|
15074
|
+
function isLikelyInvalidPgExecuteRole(role) {
|
|
15075
|
+
const normalized = role.trim();
|
|
15076
|
+
if (!normalized) {
|
|
15077
|
+
return true;
|
|
15078
|
+
}
|
|
15079
|
+
if (normalized === "postgres") {
|
|
15080
|
+
return true;
|
|
15081
|
+
}
|
|
15082
|
+
// Instance-derived login principals, not valid ExecutePGSql Role targets
|
|
15083
|
+
if (/^postgres_pgdb_[a-z0-9]+$/i.test(normalized)) {
|
|
15084
|
+
return true;
|
|
15085
|
+
}
|
|
15086
|
+
// AI-invented concatenations such as cloudbase_admin_pgdb_xxx_pgdb_xxx
|
|
15087
|
+
if (/_pgdb_[a-z0-9]+(_pgdb_[a-z0-9]+)?$/i.test(normalized) &&
|
|
15088
|
+
!PG_RECOMMENDED_ROLES.includes(normalized)) {
|
|
15089
|
+
return true;
|
|
15090
|
+
}
|
|
15091
|
+
return false;
|
|
15092
|
+
}
|
|
15093
|
+
function extractPgRoleNameFromError(message) {
|
|
15094
|
+
const missing = message.match(/role\s+"([^"]+)"\s+does\s+not\s+exist/i);
|
|
15095
|
+
if (missing?.[1]) {
|
|
15096
|
+
return missing[1];
|
|
15097
|
+
}
|
|
15098
|
+
const setRole = message.match(/set\s+role\s+([^\s:]+)/i);
|
|
15099
|
+
if (setRole?.[1]) {
|
|
15100
|
+
return setRole[1].replace(/^"|"$/g, "");
|
|
15101
|
+
}
|
|
15102
|
+
const denied = message.match(/permission\s+denied\s+to\s+set\s+role\s+"([^"]+)"/i);
|
|
15103
|
+
if (denied?.[1]) {
|
|
15104
|
+
return denied[1];
|
|
15105
|
+
}
|
|
15106
|
+
return null;
|
|
15107
|
+
}
|
|
15108
|
+
function isPgRoleExecutionError(message) {
|
|
15109
|
+
const lower = message.toLowerCase();
|
|
15110
|
+
return ((lower.includes("set role") &&
|
|
15111
|
+
(lower.includes("does not exist") ||
|
|
15112
|
+
lower.includes("permission denied"))) ||
|
|
15113
|
+
/role\s+"[^"]+"\s+does\s+not\s+exist/i.test(message) ||
|
|
15114
|
+
/permission\s+denied\s+to\s+set\s+role/i.test(message));
|
|
15115
|
+
}
|
|
15116
|
+
function buildPgRoleGuidanceMessage(attemptedRole) {
|
|
15117
|
+
const recommended = PG_RECOMMENDED_ROLES.join(", ");
|
|
15118
|
+
return (`PostgreSQL role "${attemptedRole}" cannot be used with ExecutePGSql (SET ROLE failed or role does not exist). ` +
|
|
15119
|
+
`Do not invent roles like postgres / postgres_pgdb_* from env or instance names. ` +
|
|
15120
|
+
`Omit role (defaults to ${PG_DEFAULT_ROLE}) or pass one of: ${recommended}. ` +
|
|
15121
|
+
`To list roles that exist in this database, retry with role=${PG_DEFAULT_ROLE} and SQL: SELECT rolname FROM pg_roles ORDER BY rolname;`);
|
|
15122
|
+
}
|
|
15123
|
+
function buildPgRoleErrorPayload(attemptedRole, rawMessage) {
|
|
15124
|
+
return {
|
|
15125
|
+
success: false,
|
|
15126
|
+
errorCode: "PG_ROLE_NOT_AVAILABLE",
|
|
15127
|
+
message: buildPgRoleGuidanceMessage(attemptedRole),
|
|
15128
|
+
data: {
|
|
15129
|
+
attemptedRole,
|
|
15130
|
+
defaultRole: PG_DEFAULT_ROLE,
|
|
15131
|
+
recommendedRoles: [...PG_RECOMMENDED_ROLES],
|
|
15132
|
+
listRolesSql: "SELECT rolname FROM pg_roles ORDER BY rolname;",
|
|
15133
|
+
...(rawMessage ? { rawError: rawMessage.slice(0, 500) } : {}),
|
|
15134
|
+
},
|
|
15135
|
+
nextActions: [
|
|
15136
|
+
buildNextAction(MANAGE_PG_DATABASE, "execute", `Retry without a custom role (defaults to ${PG_DEFAULT_ROLE}), or pass role=${PG_DEFAULT_ROLE} explicitly.`, {
|
|
15137
|
+
action: "execute",
|
|
15138
|
+
role: PG_DEFAULT_ROLE,
|
|
15139
|
+
sql: "SELECT rolname FROM pg_roles ORDER BY rolname;",
|
|
15140
|
+
confirm: true,
|
|
15141
|
+
}),
|
|
15142
|
+
buildNextAction(QUERY_PG_DATABASE, "context", "Inspect the auto-derived PG context (includes default role) before retrying.", { action: "context" }),
|
|
15143
|
+
],
|
|
15144
|
+
};
|
|
15145
|
+
}
|
|
15146
|
+
function tryBuildPgRoleErrorPayload(error, fallbackRole) {
|
|
15147
|
+
const rawMessage = error instanceof Error ? error.message : String(error);
|
|
15148
|
+
if (!isPgRoleExecutionError(rawMessage)) {
|
|
15149
|
+
return null;
|
|
15150
|
+
}
|
|
15151
|
+
const attemptedRole = extractPgRoleNameFromError(rawMessage) ?? fallbackRole;
|
|
15152
|
+
return buildPgRoleErrorPayload(attemptedRole, rawMessage);
|
|
15153
|
+
}
|
|
13937
15154
|
function normalizeLimit(limit, fallback = 20, max = 200) {
|
|
13938
15155
|
if (!Number.isFinite(limit)) {
|
|
13939
15156
|
return fallback;
|
|
@@ -15158,7 +16375,26 @@ async function handleReadOnlySql(args, context, deps) {
|
|
|
15158
16375
|
}
|
|
15159
16376
|
const limit = normalizeLimit(args.limit);
|
|
15160
16377
|
const limitedSql = buildLimitedReadOnlySql(args.sql, limit);
|
|
15161
|
-
|
|
16378
|
+
let result;
|
|
16379
|
+
try {
|
|
16380
|
+
result = await withPgClient(context, deps, (client) => client.query(limitedSql));
|
|
16381
|
+
}
|
|
16382
|
+
catch (error) {
|
|
16383
|
+
const rolePayload = tryBuildPgRoleErrorPayload(error, context.role);
|
|
16384
|
+
if (rolePayload) {
|
|
16385
|
+
return buildPgToolResult(rolePayload);
|
|
16386
|
+
}
|
|
16387
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
16388
|
+
return buildPgToolResult({
|
|
16389
|
+
success: false,
|
|
16390
|
+
errorCode: "PG_SQL_EXEC_FAILED",
|
|
16391
|
+
message: `PostgreSQL read-only SQL execution failed: ${reason}`,
|
|
16392
|
+
data: {
|
|
16393
|
+
role: context.role,
|
|
16394
|
+
sqlPreview: limitedSql.trim().slice(0, 500),
|
|
16395
|
+
},
|
|
16396
|
+
});
|
|
16397
|
+
}
|
|
15162
16398
|
const summary = summarizeQueryResult(result, limit);
|
|
15163
16399
|
return buildPgToolResult({
|
|
15164
16400
|
success: true,
|
|
@@ -15213,6 +16449,9 @@ async function handleExecuteSql(args, context, deps) {
|
|
|
15213
16449
|
],
|
|
15214
16450
|
});
|
|
15215
16451
|
}
|
|
16452
|
+
if (args.role !== undefined && isLikelyInvalidPgExecuteRole(args.role)) {
|
|
16453
|
+
return buildPgToolResult(buildPgRoleErrorPayload(args.role.trim() || "(empty)"));
|
|
16454
|
+
}
|
|
15216
16455
|
if (!classification.readOnly && !args.confirm) {
|
|
15217
16456
|
return buildPgToolResult({
|
|
15218
16457
|
success: false,
|
|
@@ -15232,7 +16471,26 @@ async function handleExecuteSql(args, context, deps) {
|
|
|
15232
16471
|
],
|
|
15233
16472
|
});
|
|
15234
16473
|
}
|
|
15235
|
-
|
|
16474
|
+
let result;
|
|
16475
|
+
try {
|
|
16476
|
+
result = await withPgClient(context, deps, (client) => client.query(args.sql));
|
|
16477
|
+
}
|
|
16478
|
+
catch (error) {
|
|
16479
|
+
const rolePayload = tryBuildPgRoleErrorPayload(error, context.role);
|
|
16480
|
+
if (rolePayload) {
|
|
16481
|
+
return buildPgToolResult(rolePayload);
|
|
16482
|
+
}
|
|
16483
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
16484
|
+
return buildPgToolResult({
|
|
16485
|
+
success: false,
|
|
16486
|
+
errorCode: "PG_SQL_EXEC_FAILED",
|
|
16487
|
+
message: `PostgreSQL SQL execution failed: ${reason}`,
|
|
16488
|
+
data: {
|
|
16489
|
+
role: context.role,
|
|
16490
|
+
sqlPreview: args.sql.trim().slice(0, 500),
|
|
16491
|
+
},
|
|
16492
|
+
});
|
|
16493
|
+
}
|
|
15236
16494
|
const targetTable = parseTargetTableFromSql(args.sql, context.defaultSchema);
|
|
15237
16495
|
return buildPgToolResult({
|
|
15238
16496
|
success: true,
|
|
@@ -16125,7 +17383,9 @@ function registerPGDatabaseTools(server, providedDeps) {
|
|
|
16125
17383
|
role: zod_1.z
|
|
16126
17384
|
.string()
|
|
16127
17385
|
.optional()
|
|
16128
|
-
.describe(
|
|
17386
|
+
.describe(`可选的 PostgreSQL role,传给 Manager SDK executePGSql 的 Role(平台会 SET ROLE)。默认 ${PG_DEFAULT_ROLE}。` +
|
|
17387
|
+
`推荐取值:${PG_RECOMMENDED_ROLES.join(" / ")}。` +
|
|
17388
|
+
`不要传 postgres、postgres_pgdb_* 或从环境名臆造的角色;不确定时省略本字段,或先用 ${PG_DEFAULT_ROLE} 执行 SELECT rolname FROM pg_roles。`),
|
|
16129
17389
|
objectName: zod_1.z
|
|
16130
17390
|
.string()
|
|
16131
17391
|
.optional()
|
|
@@ -16229,6 +17489,10 @@ function registerPGDatabaseTools(server, providedDeps) {
|
|
|
16229
17489
|
return handleExecuteSql(args, context, deps);
|
|
16230
17490
|
}
|
|
16231
17491
|
}
|
|
17492
|
+
// Reject known-bad Role values before readiness probe / ExecutePGSql SET ROLE.
|
|
17493
|
+
if (args.role !== undefined && isLikelyInvalidPgExecuteRole(args.role)) {
|
|
17494
|
+
return buildPgToolResult(buildPgRoleErrorPayload(args.role.trim() || "(empty)"));
|
|
17495
|
+
}
|
|
16232
17496
|
try {
|
|
16233
17497
|
await ensurePgReadyOnce(cbOpts, deps);
|
|
16234
17498
|
}
|
|
@@ -16285,6 +17549,7 @@ function registerPGDatabaseTools(server, providedDeps) {
|
|
|
16285
17549
|
|
|
16286
17550
|
|
|
16287
17551
|
Object.defineProperty(exports, "__esModule", ({ value: true }));
|
|
17552
|
+
exports.validateUserRegoContent = validateUserRegoContent;
|
|
16288
17553
|
exports.registerPermissionTools = registerPermissionTools;
|
|
16289
17554
|
const zod_1 = __webpack_require__(2971);
|
|
16290
17555
|
const cloudbase_manager_js_1 = __webpack_require__(3431);
|
|
@@ -16296,6 +17561,9 @@ const QUERY_PERMISSION_ACTIONS = [
|
|
|
16296
17561
|
"getRole",
|
|
16297
17562
|
"listUsers",
|
|
16298
17563
|
"getUser",
|
|
17564
|
+
// Align with CLI `tcb policy list/get` (OPA gateway authz)
|
|
17565
|
+
"listPolicy",
|
|
17566
|
+
"getPolicy",
|
|
16299
17567
|
];
|
|
16300
17568
|
const MANAGE_PERMISSION_ACTIONS = [
|
|
16301
17569
|
"updateResourcePermission",
|
|
@@ -16309,7 +17577,14 @@ const MANAGE_PERMISSION_ACTIONS = [
|
|
|
16309
17577
|
"createUser",
|
|
16310
17578
|
"updateUser",
|
|
16311
17579
|
"deleteUsers",
|
|
17580
|
+
// Align with CLI `tcb policy set` (OPA Rego; disables legacy gateway auth)
|
|
17581
|
+
"setPolicy",
|
|
16312
17582
|
];
|
|
17583
|
+
/** Keys accepted by Manager SDK describeEnvAuthzConfig / modifyEnvAuthzConfig. */
|
|
17584
|
+
const AUTHZ_USER_REGO_KEY = "authz.user.rego";
|
|
17585
|
+
const AUTHZ_PLATFORM_EXTENSION_REGO_KEY = "authz.platform.extension.rego";
|
|
17586
|
+
/** CLI `tcb policy list --resource-type` only documents `policy`. */
|
|
17587
|
+
const POLICY_LIST_RESOURCE_TYPES = ["policy"];
|
|
16313
17588
|
function buildWriteVerificationHint(resourceId) {
|
|
16314
17589
|
return `对于 ${resourceId} 这类有后端权限控制的集合,前端调用 .doc(id).update() / .doc(id).remove() 后,不能只看是否没有抛异常。请显式检查返回结果中的 updated / deleted 是否大于 0;如果 result.code、result.message 存在,或 updated / deleted 为 0,要把它当作真实失败并向上抛错。`;
|
|
16315
17590
|
}
|
|
@@ -16348,10 +17623,32 @@ function isPostgresqlPermissionApiUnsupported(error) {
|
|
|
16348
17623
|
const message = error instanceof Error ? error.message : String(error);
|
|
16349
17624
|
return /does not support PostgreSQL type environments/i.test(message);
|
|
16350
17625
|
}
|
|
16351
|
-
const AUTHZ_USER_REGO_KEY = "authz.user.rego";
|
|
16352
17626
|
function looksLikeUserRego(value) {
|
|
16353
17627
|
return /^\s*package\s+authz\.user\b/m.test(value);
|
|
16354
17628
|
}
|
|
17629
|
+
/**
|
|
17630
|
+
* Validate user Rego before setPolicy / modifyEnvAuthzConfig.
|
|
17631
|
+
* Aligns with CLI docs (must start with `package authz.user`) and CLI non-empty check.
|
|
17632
|
+
* Does not run a full OPA compiler; backend still owns deep syntax validation.
|
|
17633
|
+
*/
|
|
17634
|
+
function validateUserRegoContent(value) {
|
|
17635
|
+
if (typeof value !== "string" || value.trim().length === 0) {
|
|
17636
|
+
throw new Error("action=setPolicy 需要非空 regoContent(对齐 CLI `tcb policy set <regoContent>`)。");
|
|
17637
|
+
}
|
|
17638
|
+
const trimmed = value.trim();
|
|
17639
|
+
if (!looksLikeUserRego(trimmed)) {
|
|
17640
|
+
throw new Error("Rego 策略必须以 `package authz.user` 开头(对齐 https://docs.cloudbase.net/cli-v1/policy/management )。");
|
|
17641
|
+
}
|
|
17642
|
+
const open = (trimmed.match(/\{/g) || []).length;
|
|
17643
|
+
const close = (trimmed.match(/\}/g) || []).length;
|
|
17644
|
+
if (open !== close) {
|
|
17645
|
+
throw new Error(`Rego 策略花括号不匹配({=${open}, }=${close})。请检查语法后再调用 setPolicy。`);
|
|
17646
|
+
}
|
|
17647
|
+
return trimmed;
|
|
17648
|
+
}
|
|
17649
|
+
function resolveAuthzConfigKey(extension) {
|
|
17650
|
+
return extension ? AUTHZ_PLATFORM_EXTENSION_REGO_KEY : AUTHZ_USER_REGO_KEY;
|
|
17651
|
+
}
|
|
16355
17652
|
/** Detect legacy function securityRule shapes that mean "public invoke". */
|
|
16356
17653
|
function isPublicFunctionInvokeRule(securityRule) {
|
|
16357
17654
|
if (!securityRule || securityRule.trim() === "") {
|
|
@@ -16423,29 +17720,38 @@ function resolveFunctionAuthzRegoInput(securityRule, resourceId) {
|
|
|
16423
17720
|
`2) permission="CUSTOM" with securityRule='{"invoke":true}' to generate a public-functions allow policy.\n` +
|
|
16424
17721
|
`See https://docs.cloudbase.net/cli-v1/policy/management`);
|
|
16425
17722
|
}
|
|
16426
|
-
async function
|
|
17723
|
+
async function describeEnvAuthzConfigByKey(cloudbase, key = AUTHZ_USER_REGO_KEY) {
|
|
16427
17724
|
if (!cloudbase?.permission?.describeEnvAuthzConfig) {
|
|
16428
17725
|
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.");
|
|
16429
17726
|
}
|
|
16430
|
-
const result = await cloudbase.permission.describeEnvAuthzConfig({
|
|
16431
|
-
key: AUTHZ_USER_REGO_KEY,
|
|
16432
|
-
});
|
|
17727
|
+
const result = await cloudbase.permission.describeEnvAuthzConfig({ key });
|
|
16433
17728
|
const value = typeof result?.Item?.Value === "string"
|
|
16434
17729
|
? result.Item.Value
|
|
16435
17730
|
: typeof result?.Value === "string"
|
|
16436
17731
|
? result.Value
|
|
16437
17732
|
: "";
|
|
16438
|
-
return { value, raw: result };
|
|
17733
|
+
return { key, value, raw: result };
|
|
17734
|
+
}
|
|
17735
|
+
async function describeEnvAuthzUserRego(cloudbase) {
|
|
17736
|
+
const result = await describeEnvAuthzConfigByKey(cloudbase, AUTHZ_USER_REGO_KEY);
|
|
17737
|
+
return { value: result.value, raw: result.raw };
|
|
16439
17738
|
}
|
|
16440
17739
|
async function modifyEnvAuthzUserRego(cloudbase, value) {
|
|
16441
17740
|
if (!cloudbase?.permission?.modifyEnvAuthzConfig) {
|
|
16442
17741
|
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.");
|
|
16443
17742
|
}
|
|
17743
|
+
const validated = validateUserRegoContent(value);
|
|
16444
17744
|
return cloudbase.permission.modifyEnvAuthzConfig({
|
|
16445
17745
|
key: AUTHZ_USER_REGO_KEY,
|
|
16446
|
-
value,
|
|
17746
|
+
value: validated,
|
|
16447
17747
|
});
|
|
16448
17748
|
}
|
|
17749
|
+
async function describeResourcePolicyListAligned(cloudbase, policyResourceType) {
|
|
17750
|
+
if (!cloudbase?.permission?.describeResourcePolicyList) {
|
|
17751
|
+
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.");
|
|
17752
|
+
}
|
|
17753
|
+
return cloudbase.permission.describeResourcePolicyList(policyResourceType ? { resourceType: policyResourceType } : undefined);
|
|
17754
|
+
}
|
|
16449
17755
|
async function describeResourcePermissionWithFunctionPgFallback(options) {
|
|
16450
17756
|
const { cloudbase, envId, resourceType, resources } = options;
|
|
16451
17757
|
try {
|
|
@@ -16679,7 +17985,7 @@ function registerPermissionTools(server) {
|
|
|
16679
17985
|
};
|
|
16680
17986
|
server.registerTool?.("queryPermissions", {
|
|
16681
17987
|
title: "查询 CloudBase 权限与用户配置",
|
|
16682
|
-
description: "查询 CloudBase
|
|
17988
|
+
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`。",
|
|
16683
17989
|
inputSchema: {
|
|
16684
17990
|
action: zod_1.z.enum(QUERY_PERMISSION_ACTIONS),
|
|
16685
17991
|
resourceType: zod_1.z
|
|
@@ -16694,13 +18000,21 @@ function registerPermissionTools(server) {
|
|
|
16694
18000
|
username: zod_1.z.string().optional(),
|
|
16695
18001
|
pageNo: zod_1.z.number().optional(),
|
|
16696
18002
|
pageSize: zod_1.z.number().optional(),
|
|
18003
|
+
extension: zod_1.z
|
|
18004
|
+
.boolean()
|
|
18005
|
+
.optional()
|
|
18006
|
+
.describe("仅 action=getPolicy。true=读取平台为该环境单独配置的策略(authz.platform.extension.rego),默认 false=用户策略(authz.user.rego),对齐 CLI `tcb policy get --extension`。"),
|
|
18007
|
+
policyResourceType: zod_1.z
|
|
18008
|
+
.enum(POLICY_LIST_RESOURCE_TYPES)
|
|
18009
|
+
.optional()
|
|
18010
|
+
.describe("仅 action=listPolicy。按资源类型过滤,当前仅支持 `policy`,对齐 CLI `tcb policy list --resource-type policy`。"),
|
|
16697
18011
|
},
|
|
16698
18012
|
annotations: {
|
|
16699
18013
|
readOnlyHint: true,
|
|
16700
18014
|
openWorldHint: true,
|
|
16701
18015
|
category: "permissions",
|
|
16702
18016
|
},
|
|
16703
|
-
}, async ({ action, resourceType, resourceId, resourceIds, roleId, roleIdentity, roleName, uid, username, pageNo, pageSize, }) => withEnvelope(async () => {
|
|
18017
|
+
}, async ({ action, resourceType, resourceId, resourceIds, roleId, roleIdentity, roleName, uid, username, pageNo, pageSize, extension, policyResourceType, }) => withEnvelope(async () => {
|
|
16704
18018
|
const envId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
|
|
16705
18019
|
const cloudbase = await getManager();
|
|
16706
18020
|
switch (action) {
|
|
@@ -16846,11 +18160,43 @@ function registerPermissionTools(server) {
|
|
|
16846
18160
|
raw: result,
|
|
16847
18161
|
}, "应用用户详情查询成功");
|
|
16848
18162
|
}
|
|
18163
|
+
case "listPolicy": {
|
|
18164
|
+
const result = await describeResourcePolicyListAligned(cloudbase, policyResourceType);
|
|
18165
|
+
(0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
|
|
18166
|
+
const data = result
|
|
18167
|
+
?.Data;
|
|
18168
|
+
const policyList = data?.PolicyList ?? [];
|
|
18169
|
+
const total = data?.Total ?? policyList.length;
|
|
18170
|
+
return buildEnvelope({
|
|
18171
|
+
action,
|
|
18172
|
+
envId,
|
|
18173
|
+
policyResourceType: policyResourceType ?? null,
|
|
18174
|
+
policies: policyList,
|
|
18175
|
+
total,
|
|
18176
|
+
note: "PG 环境与 authz_engine=opa 的环境会返回空列表(与 CLI `tcb policy list` / SDK describeResourcePolicyList 一致)。读取用户 Rego 请用 action=getPolicy。",
|
|
18177
|
+
raw: result,
|
|
18178
|
+
}, "网关授权策略列表查询成功");
|
|
18179
|
+
}
|
|
18180
|
+
case "getPolicy": {
|
|
18181
|
+
const key = resolveAuthzConfigKey(extension);
|
|
18182
|
+
const result = await describeEnvAuthzConfigByKey(cloudbase, key);
|
|
18183
|
+
(0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result.raw);
|
|
18184
|
+
return buildEnvelope({
|
|
18185
|
+
action,
|
|
18186
|
+
envId,
|
|
18187
|
+
key: result.key,
|
|
18188
|
+
extension: Boolean(extension),
|
|
18189
|
+
rego: result.value,
|
|
18190
|
+
raw: result.raw,
|
|
18191
|
+
}, extension
|
|
18192
|
+
? "平台扩展 OPA 策略查询成功(authz.platform.extension.rego)"
|
|
18193
|
+
: "用户 OPA 策略查询成功(authz.user.rego)");
|
|
18194
|
+
}
|
|
16849
18195
|
}
|
|
16850
18196
|
}));
|
|
16851
18197
|
server.registerTool?.("managePermissions", {
|
|
16852
18198
|
title: "管理 CloudBase 权限与用户配置",
|
|
16853
|
-
description: "管理 CloudBase 权限与用户配置,支持修改资源权限(数据库/云函数/存储桶等)、角色管理、成员与策略增删、应用用户 CRUD
|
|
18199
|
+
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\"`。",
|
|
16854
18200
|
inputSchema: {
|
|
16855
18201
|
action: zod_1.z.enum(MANAGE_PERMISSION_ACTIONS),
|
|
16856
18202
|
resourceType: zod_1.z
|
|
@@ -16881,6 +18227,14 @@ function registerPermissionTools(server) {
|
|
|
16881
18227
|
username: zod_1.z.string().optional(),
|
|
16882
18228
|
password: zod_1.z.string().optional(),
|
|
16883
18229
|
userStatus: zod_1.z.enum(["ACTIVE", "BLOCKED"]).optional(),
|
|
18230
|
+
regoContent: zod_1.z
|
|
18231
|
+
.string()
|
|
18232
|
+
.optional()
|
|
18233
|
+
.describe("仅 action=setPolicy。用户 OPA Rego 全文,必须以 `package authz.user` 开头,对齐 CLI `tcb policy set <regoContent>`。"),
|
|
18234
|
+
confirm: zod_1.z
|
|
18235
|
+
.boolean()
|
|
18236
|
+
.optional()
|
|
18237
|
+
.describe("仅 action=setPolicy。设置 Rego 后会立即禁用旧网关鉴权,必须显式传 confirm=true(对齐 CLI 确认提示)。"),
|
|
16884
18238
|
},
|
|
16885
18239
|
annotations: {
|
|
16886
18240
|
readOnlyHint: false,
|
|
@@ -16889,7 +18243,7 @@ function registerPermissionTools(server) {
|
|
|
16889
18243
|
openWorldHint: true,
|
|
16890
18244
|
category: "permissions",
|
|
16891
18245
|
},
|
|
16892
|
-
}, async ({ action, resourceType, resourceId, permission, securityRule, roleId, roleIds, roleName, roleIdentity, description, memberUids, policies, policyIds, uid, uids, username, password, userStatus, }) => withEnvelope(async () => {
|
|
18246
|
+
}, async ({ action, resourceType, resourceId, permission, securityRule, roleId, roleIds, roleName, roleIdentity, description, memberUids, policies, policyIds, uid, uids, username, password, userStatus, regoContent, confirm, }) => withEnvelope(async () => {
|
|
16893
18247
|
const envId = await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions);
|
|
16894
18248
|
const cloudbase = await getManager();
|
|
16895
18249
|
const normalizedPolicies = normalizeRecordArray(policies, "policies");
|
|
@@ -17070,6 +18424,26 @@ function registerPermissionTools(server) {
|
|
|
17070
18424
|
raw: result,
|
|
17071
18425
|
}, "应用用户删除成功");
|
|
17072
18426
|
}
|
|
18427
|
+
case "setPolicy": {
|
|
18428
|
+
if (confirm !== true) {
|
|
18429
|
+
throw new Error("action=setPolicy 会立即禁用旧网关鉴权(对齐 CLI `tcb policy set`),必须显式传 confirm=true。");
|
|
18430
|
+
}
|
|
18431
|
+
const validated = validateUserRegoContent(regoContent ?? "");
|
|
18432
|
+
const result = await modifyEnvAuthzUserRego(cloudbase, validated);
|
|
18433
|
+
(0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
|
|
18434
|
+
return buildEnvelope({
|
|
18435
|
+
action,
|
|
18436
|
+
envId,
|
|
18437
|
+
key: AUTHZ_USER_REGO_KEY,
|
|
18438
|
+
rego: validated,
|
|
18439
|
+
sideEffect: "Setting authz.user.rego immediately disables legacy gateway authorization.",
|
|
18440
|
+
nextSteps: [
|
|
18441
|
+
'queryPermissions(action="getPolicy")',
|
|
18442
|
+
'queryPermissions(action="listPolicy")',
|
|
18443
|
+
],
|
|
18444
|
+
raw: result,
|
|
18445
|
+
}, "用户 OPA Rego 策略设置成功(旧网关鉴权已失效)");
|
|
18446
|
+
}
|
|
17073
18447
|
}
|
|
17074
18448
|
}));
|
|
17075
18449
|
}
|
|
@@ -17560,7 +18934,7 @@ function registerSetupTools(server) {
|
|
|
17560
18934
|
server.registerTool("downloadTemplate", {
|
|
17561
18935
|
title: "下载项目模板",
|
|
17562
18936
|
description: `自动下载并部署CloudBase项目模板。
|
|
17563
|
-
**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.
|
|
18937
|
+
**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)`,
|
|
17564
18938
|
inputSchema: {
|
|
17565
18939
|
template: zod_1.z
|
|
17566
18940
|
.enum(["react", "vue", "miniprogram", "uniapp", "rules"])
|
|
@@ -17916,7 +19290,9 @@ function registerAppTools(server) {
|
|
|
17916
19290
|
buildId,
|
|
17917
19291
|
});
|
|
17918
19292
|
(0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
|
|
17919
|
-
|
|
19293
|
+
// Platform may return Failed/failed; normalize before matching.
|
|
19294
|
+
const isFailed = typeof result.Status === "string" &&
|
|
19295
|
+
result.Status.toLowerCase() === "failed";
|
|
17920
19296
|
const payload = {
|
|
17921
19297
|
action,
|
|
17922
19298
|
serviceName,
|