-
Notifications
You must be signed in to change notification settings - Fork 125
Expand file tree
/
Copy pathfunctions.ts
More file actions
1501 lines (1416 loc) · 49.5 KB
/
functions.ts
File metadata and controls
1501 lines (1416 loc) · 49.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { z } from "zod";
import {
getCloudBaseManager,
getEnvId,
logCloudBaseResult,
} from "../cloudbase-manager.js";
import { ExtendedMcpServer } from "../server.js";
import { isCloudMode } from "../utils/cloud-mode.js";
import { jsonContent } from "../utils/json-content.js";
import { debug } from "../utils/logger.js";
import { IEnvVariable } from "@cloudbase/manager-node/types/function/types.js";
import { existsSync } from "fs";
import path from "path";
export const SUPPORTED_RUNTIMES = {
nodejs: [
"Nodejs20.19",
"Nodejs18.15",
"Nodejs16.13",
"Nodejs14.18",
"Nodejs12.16",
"Nodejs10.15",
"Nodejs8.9",
],
python: [
"Python3.10",
"Python3.9",
"Python3.7",
"Python3.6",
"Python2.7",
],
php: [
"Php8.0",
"Php7.4",
"Php7.2",
],
java: [
"Java8",
"Java11",
],
golang: [
"Golang1",
],
} as const;
export const ALL_SUPPORTED_RUNTIMES = Object.values(SUPPORTED_RUNTIMES).flat();
export const DEFAULT_RUNTIME = "Nodejs18.15";
export const RECOMMENDED_RUNTIMES = {
nodejs: "Nodejs18.15",
python: "Python3.9",
php: "Php7.4",
java: "Java11",
golang: "Golang1",
} as const;
export const SUPPORTED_NODEJS_RUNTIMES = SUPPORTED_RUNTIMES.nodejs;
export const DEFAULT_NODEJS_RUNTIME = DEFAULT_RUNTIME;
export function formatRuntimeList(): string {
return Object.entries(SUPPORTED_RUNTIMES)
.map(([lang, runtimes]) => {
const capitalizedLang = lang.charAt(0).toUpperCase() + lang.slice(1);
return ` ${capitalizedLang}: ${runtimes.join(", ")}`;
})
.join("\n");
}
export const SUPPORTED_TRIGGER_TYPES = [
"timer",
] as const;
export type TriggerType = (typeof SUPPORTED_TRIGGER_TYPES)[number];
export const TRIGGER_CONFIG_EXAMPLES = {
timer: {
description:
"Timer trigger configuration using cron expression format: second minute hour day month week year",
examples: [
"0 0 2 1 * * *",
"0 30 9 * * * *",
"0 0 12 * * * *",
"0 0 0 1 1 * *",
],
},
};
export const QUERY_FUNCTION_ACTIONS = [
"listFunctions",
"getFunctionDetail",
"listFunctionLogs",
"getFunctionLogDetail",
"listFunctionLayers",
"listLayers",
"listLayerVersions",
"getLayerVersionDetail",
"listFunctionTriggers",
"getFunctionDownloadUrl",
] as const;
export const MANAGE_FUNCTION_ACTIONS = [
"createFunction",
"updateFunctionCode",
"updateFunctionConfig",
"invokeFunction",
"createFunctionTrigger",
"deleteFunctionTrigger",
"createLayerVersion",
"deleteLayerVersion",
"attachLayer",
"detachLayer",
"updateFunctionLayers",
] as const;
type QueryFunctionsAction = (typeof QUERY_FUNCTION_ACTIONS)[number];
type ManageFunctionsAction = (typeof MANAGE_FUNCTION_ACTIONS)[number];
type FunctionLayerInput = {
LayerName: string;
LayerVersion: number;
};
type FunctionToolEnvelope = {
success: boolean;
data: Record<string, unknown>;
message: string;
nextActions?: Array<{
tool: string;
action: string;
reason: string;
}>;
};
type QueryFunctionsInput = {
action: QueryFunctionsAction;
functionName?: string;
limit?: number;
offset?: number;
codeSecret?: string;
startTime?: string;
endTime?: string;
requestId?: string;
qualifier?: string;
runtime?: string;
searchKey?: string;
layerName?: string;
layerVersion?: number;
};
type ManageFunctionsInput = {
action: ManageFunctionsAction;
func?: Record<string, unknown>;
functionRootPath?: string;
force?: boolean;
functionName?: string;
zipFile?: string;
handler?: string;
timeout?: number;
envVariables?: Record<string, string>;
vpc?: {
vpcId: string;
subnetId: string;
};
params?: Record<string, unknown>;
triggers?: Array<{
name: string;
type: TriggerType;
config: string;
}>;
triggerName?: string;
layerName?: string;
layerVersion?: number;
contentPath?: string;
base64Content?: string;
runtimes?: string[];
description?: string;
licenseInfo?: string;
layers?: Array<{
layerName?: string;
layerVersion?: number;
LayerName?: string;
LayerVersion?: number;
}>;
codeSecret?: string;
confirm?: boolean;
};
const VPC_SCHEMA = z.object({
vpcId: z.string(),
subnetId: z.string(),
});
const SEVEN_FIELD_CRON_REGEX = /^\s*\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s*$/;
export function validateTimerCron(config: string): string {
const trimmed = config.trim();
const fields = trimmed.split(/\s+/);
if (fields.length === 5) {
throw new Error(
`timer 触发器的 cron 表达式必须使用 7 段格式(秒 分 时 日 月 星期 年),不支持标准 5 段格式。` +
`\n收到 5 段: "${trimmed}"` +
`\n正确示例: "0 */5 * * * * *"(每 5 分钟执行),"0 0 2 1 * * *"(每月 1 号 2 点)`,
);
}
if (fields.length < 7) {
throw new Error(
`timer 触发器的 cron 表达式必须使用 7 段格式(秒 分 时 日 月 星期 年),当前只有 ${fields.length} 段。` +
`\n正确示例: "0 */5 * * * * *"(每 5 分钟执行),"0 0 2 1 * * *"(每月 1 号 2 点)`,
);
}
return trimmed;
}
const TRIGGER_SCHEMA = z.object({
name: z.string().describe("触发器名称"),
type: z.enum(SUPPORTED_TRIGGER_TYPES).describe("触发器类型"),
config: z
.string()
.describe(
"触发器配置。timer 必须使用 CloudBase 7 段 cron 格式:秒 分 时 日 月 星期 年。" +
"⚠️ 不支持标准 5 段 cron(如 */5 * * * * 是错误的)。" +
"正确示例:0 */5 * * * * *(每5分钟)、0 0 2 1 * * *(每月1号2点)、0 30 9 * * * *(每天9:30)",
)
.refine(
(val) => SEVEN_FIELD_CRON_REGEX.test(val),
{
message:
"timer 触发器的 cron 表达式必须使用 7 段格式(秒 分 时 日 月 星期 年),不支持 5 段格式。正确示例:0 */5 * * * * *",
},
),
});
const CREATE_FUNCTION_SCHEMA = z.object({
name: z.string().describe("函数名称"),
type: z.enum(["Event", "HTTP"]).optional().describe("函数类型"),
protocolType: z.enum(["HTTP", "WS"]).optional().describe("HTTP 云函数协议类型"),
protocolParams: z
.object({
wsParams: z
.object({
idleTimeOut: z.number().optional().describe("WebSocket 空闲超时时间(秒)"),
})
.optional(),
})
.optional(),
instanceConcurrencyConfig: z
.object({
dynamicEnabled: z.boolean().optional(),
maxConcurrency: z.number().optional(),
})
.optional(),
timeout: z.number().optional().describe("函数超时时间"),
envVariables: z.record(z.string()).optional().describe("环境变量"),
vpc: VPC_SCHEMA.optional().describe("私有网络配置"),
runtime: z
.string()
.optional()
.describe(
"运行时环境。Event 函数支持多种运行时:\n" +
formatRuntimeList() +
"\n\n推荐运行时:\n" +
` Node.js: ${RECOMMENDED_RUNTIMES.nodejs}\n` +
` Python: ${RECOMMENDED_RUNTIMES.python}\n` +
` PHP: ${RECOMMENDED_RUNTIMES.php}\n` +
` Java: ${RECOMMENDED_RUNTIMES.java}\n` +
` Go: ${RECOMMENDED_RUNTIMES.golang}`,
),
triggers: z.array(TRIGGER_SCHEMA).optional().describe("触发器配置数组"),
handler: z.string().optional().describe("函数入口"),
ignore: z.union([z.string(), z.array(z.string())]).optional().describe("忽略文件"),
isWaitInstall: z.boolean().optional().describe("是否等待依赖安装"),
layers: z
.array(
z.object({
name: z.string(),
version: z.number(),
}),
)
.optional()
.describe("Layer 配置"),
});
const MANAGE_LAYER_SCHEMA = z.object({
layerName: z.string().describe("层名称"),
layerVersion: z.number().describe("层版本号"),
});
function normalizeFunctionLayers(layers: unknown): FunctionLayerInput[] {
if (!Array.isArray(layers)) {
return [];
}
return layers
.filter((layer): layer is Record<string, unknown> => Boolean(layer))
.map((layer) => ({
LayerName: String(layer.LayerName ?? ""),
LayerVersion: Number(layer.LayerVersion ?? 0),
}))
.filter((layer) => Boolean(layer.LayerName) && Number.isFinite(layer.LayerVersion));
}
function processFunctionRootPath(
functionRootPath: string | undefined,
functionName: string,
): string | undefined {
if (!functionRootPath) return functionRootPath;
const normalizedPath = path.normalize(functionRootPath);
const lastDir = path.basename(normalizedPath);
if (lastDir === functionName) {
const parentPath = path.dirname(normalizedPath);
console.warn(
`检测到 functionRootPath 包含函数名 "${functionName}",已自动调整为父目录: ${parentPath}`,
);
return parentPath;
}
return functionRootPath;
}
function getExpectedFunctionPath(
functionRootPath: string | undefined,
functionName: string,
): string | undefined {
if (!functionRootPath) return undefined;
return path.join(path.normalize(functionRootPath), functionName);
}
export function shouldInstallDependencyForFunction(
functionType: string | undefined,
hasPackageJson: boolean,
): boolean {
if (functionType === "HTTP") {
return hasPackageJson;
}
return true;
}
export function resolveEventFunctionRuntime(runtime: unknown): string {
if (typeof runtime !== "string" || !runtime.trim()) {
return DEFAULT_RUNTIME;
}
const normalizedRuntime = runtime.replace(/\s+/g, "");
if ((ALL_SUPPORTED_RUNTIMES as readonly string[]).includes(normalizedRuntime)) {
return normalizedRuntime;
}
throw new Error(
`不支持的运行时环境: "${String(runtime)}"\n\n支持的运行时:\n${formatRuntimeList()}`,
);
}
export function buildFunctionOperationErrorMessage(
operation: "createFunction" | "updateFunctionCode",
functionName: string,
functionRootPath: string | undefined,
error: unknown,
): string {
const baseMessage = error instanceof Error ? error.message : String(error);
const suggestions: string[] = [];
const expectedFunctionPath = getExpectedFunctionPath(functionRootPath, functionName);
if (/GetFunction.*未找到指定的Function|未找到指定的Function/i.test(baseMessage)) {
suggestions.push(
`请先确认环境中已存在函数 \`${functionName}\`;如果还未创建,请先执行 \`manageFunctions(action="createFunction")\`。`,
);
}
if (/路径不存在/i.test(baseMessage) && expectedFunctionPath) {
suggestions.push(
`当前工具会从 \`functionRootPath + 函数名\` 查找代码目录,期望目录是 \`${expectedFunctionPath}\`。`,
);
suggestions.push("如果你传入的已经是函数目录本身,请改为传它的父目录。");
if (functionRootPath) {
const lastDir = path.basename(path.normalize(functionRootPath));
if (lastDir !== "cloudfunctions" && lastDir !== "functions") {
suggestions.push(
`functionRootPath 应该是直接包含函数文件夹的目录(如 cloudfunctions 或 functions),而不是项目根目录。` +
`请将 functionRootPath 改为 \`${path.join(path.normalize(functionRootPath), "cloudfunctions")}\` ` +
`或 \`${path.join(path.normalize(functionRootPath), "functions")}\`。`,
);
}
}
}
if (/paths\[0\].*undefined/i.test(baseMessage)) {
suggestions.push(
"HTTP 函数创建时需要提供 functionRootPath(指向 cloudfunctions 或 functions 目录的绝对路径,不是项目根目录)或 zipFile,否则 SDK 无法定位函数目录。",
);
}
if (/依赖安装失败|package\.json/i.test(baseMessage)) {
suggestions.push(
"如果 HTTP 函数只使用原生 Node.js API 且没有第三方依赖,可以保留函数目录中的 index.js 和 scf_bootstrap,工具会跳过依赖安装。",
);
suggestions.push(
"如果你确实依赖 npm 包,请在函数目录下补充 package.json 后重试。",
);
}
if (suggestions.length === 0) {
suggestions.push("请检查函数名、目录结构和环境中的函数状态后重试。");
}
return `[${operation}] ${baseMessage}\n建议:${suggestions.join(" ")}`;
}
function wrapFunctionOperationError(
operation: "createFunction" | "updateFunctionCode",
functionName: string,
functionRootPath: string | undefined,
error: unknown,
): Error {
const wrappedError = new Error(
buildFunctionOperationErrorMessage(
operation,
functionName,
functionRootPath,
error,
),
);
if (error && typeof error === "object") {
Object.assign(wrappedError, error);
}
if (error instanceof Error) {
wrappedError.name = error.name;
wrappedError.stack = error.stack;
(wrappedError as Error & { cause?: unknown }).cause = error;
}
return wrappedError;
}
export function registerFunctionTools(server: ExtendedMcpServer) {
const cloudBaseOptions = server.cloudBaseOptions;
const getManager = () => getCloudBaseManager({ cloudBaseOptions });
const buildEnvelope = (
data: Record<string, unknown>,
message: string,
nextActions?: FunctionToolEnvelope["nextActions"],
): FunctionToolEnvelope => ({
success: true,
data,
message,
...(nextActions?.length ? { nextActions } : {}),
});
const buildErrorEnvelope = (
error: unknown,
errorCode?: string,
): Record<string, unknown> => ({
success: false,
data: {},
message: error instanceof Error ? error.message : String(error),
...(errorCode ? { errorCode } : {}),
});
const withEnvelope = async (handler: () => Promise<FunctionToolEnvelope>) => {
try {
return jsonContent(await handler());
} catch (error) {
return jsonContent(buildErrorEnvelope(error));
}
};
const requireConfirm = (action: string, confirm?: boolean) => {
if (!confirm) {
throw new Error(`${action} 是危险操作,请显式传入 confirm=true 后再执行`);
}
};
const ensureActionAllowedInCloudMode = (input: ManageFunctionsInput) => {
if (!isCloudMode()) {
return;
}
if (input.action === "createFunction" || input.action === "updateFunctionCode") {
throw new Error(
`${input.action} 在 cloud mode 下不可用,因为该操作依赖本地函数代码目录。请改用本地模式执行。`,
);
}
if (input.action === "createLayerVersion" && input.contentPath) {
throw new Error(
"createLayerVersion 在 cloud mode 下不支持 contentPath,本地文件内容请改为 base64Content 或改用本地模式执行。",
);
}
};
const validateLogRange = (
startTime?: string,
endTime?: string,
offset?: number,
limit?: number,
) => {
if ((offset || 0) + (limit || 0) > 10000) {
throw new Error("offset+limit 不能大于 10000");
}
if (startTime && endTime) {
const start = new Date(startTime).getTime();
const end = new Date(endTime).getTime();
if (!Number.isFinite(start) || !Number.isFinite(end)) {
throw new Error("startTime 和 endTime 必须是有效的日期时间字符串");
}
if (end - start > 24 * 60 * 60 * 1000) {
throw new Error("startTime 和 endTime 间隔不能超过一天");
}
}
};
const normalizeManageLayers = (
layers: ManageFunctionsInput["layers"],
): FunctionLayerInput[] =>
normalizeFunctionLayers(
(layers ?? []).map((layer) => ({
LayerName: layer.layerName ?? layer.LayerName,
LayerVersion: layer.layerVersion ?? layer.LayerVersion,
})),
);
const handleQueryFunctions = async (
input: QueryFunctionsInput,
): Promise<FunctionToolEnvelope> => {
switch (input.action) {
case "listFunctions": {
const cloudbase = await getManager();
const result = await cloudbase.functions.getFunctionList(
input.limit,
input.offset,
);
logCloudBaseResult(server.logger, result);
return buildEnvelope(
{
action: input.action,
functions: result.Functions || [],
totalCount: result.TotalCount || 0,
requestId: result.RequestId,
raw: result,
},
`已获取 ${result.Functions?.length || 0} 个云函数`,
[
{
tool: "queryFunctions",
action: "getFunctionDetail",
reason: "查看单个函数详情",
},
{
tool: "manageFunctions",
action: "createFunction",
reason: "创建新的云函数",
},
],
);
}
case "getFunctionDetail": {
if (!input.functionName) {
throw new Error("getFunctionDetail 操作时,functionName 参数是必需的");
}
const cloudbase = await getManager();
const result = await cloudbase.functions.getFunctionDetail(
input.functionName,
input.codeSecret,
);
logCloudBaseResult(server.logger, result);
return buildEnvelope(
{
action: input.action,
functionName: input.functionName,
functionDetail: result,
layers: normalizeFunctionLayers(result.Layers),
triggers: result.Triggers || [],
requestId: result.RequestId,
raw: result,
},
`已获取函数 ${input.functionName} 的详情`,
[
{
tool: "queryFunctions",
action: "listFunctionLogs",
reason: "查看该函数的执行日志",
},
{
tool: "manageFunctions",
action: "updateFunctionConfig",
reason: "更新该函数配置",
},
{
tool: "queryGateway",
action: "getAccess",
reason: "查看该函数是否已暴露网关访问入口",
},
],
);
}
case "listFunctionLogs": {
if (!input.functionName) {
throw new Error("listFunctionLogs 操作时,functionName 参数是必需的");
}
validateLogRange(
input.startTime,
input.endTime,
input.offset,
input.limit,
);
const cloudbase = await getManager();
const result = await cloudbase.functions.getFunctionLogsV2({
name: input.functionName,
offset: input.offset,
limit: input.limit,
startTime: input.startTime,
endTime: input.endTime,
requestId: input.requestId,
qualifier: input.qualifier,
});
logCloudBaseResult(server.logger, result);
return buildEnvelope(
{
action: input.action,
functionName: input.functionName,
logs: result.LogList || [],
requestId: result.RequestId,
raw: result,
},
`已获取函数 ${input.functionName} 的日志列表`,
[
{
tool: "queryFunctions",
action: "getFunctionLogDetail",
reason: "按 requestId 查看单条日志详情",
},
],
);
}
case "getFunctionLogDetail": {
if (!input.requestId) {
throw new Error("getFunctionLogDetail 操作时,requestId 参数是必需的");
}
validateLogRange(input.startTime, input.endTime);
const cloudbase = await getManager();
const result = await cloudbase.functions.getFunctionLogDetail({
startTime: input.startTime,
endTime: input.endTime,
logRequestId: input.requestId,
});
logCloudBaseResult(server.logger, result);
return buildEnvelope(
{
action: input.action,
requestId: input.requestId,
logDetail: result,
raw: result,
},
`已获取 requestId=${input.requestId} 的日志详情`,
);
}
case "listFunctionLayers": {
if (!input.functionName) {
throw new Error("listFunctionLayers 操作时,functionName 参数是必需的");
}
const cloudbase = await getManager();
const result = await cloudbase.functions.getFunctionDetail(
input.functionName,
input.codeSecret,
);
logCloudBaseResult(server.logger, result);
const layers = normalizeFunctionLayers(result.Layers);
return buildEnvelope(
{
action: input.action,
functionName: input.functionName,
layers,
count: layers.length,
requestId: result.RequestId,
raw: result,
},
`已获取函数 ${input.functionName} 当前绑定的层`,
[
{
tool: "manageFunctions",
action: "attachLayer",
reason: "为该函数追加绑定层",
},
{
tool: "manageFunctions",
action: "updateFunctionLayers",
reason: "整体调整层顺序或绑定列表",
},
],
);
}
case "listLayers": {
const cloudbase = await getManager();
const result = await cloudbase.functions.listLayers({
offset: input.offset,
limit: input.limit,
runtime: input.runtime,
searchKey: input.searchKey,
});
logCloudBaseResult(server.logger, result);
return buildEnvelope(
{
action: input.action,
layers: result.Layers || [],
totalCount: result.TotalCount || 0,
requestId: result.RequestId,
raw: result,
},
`已获取 ${result.Layers?.length || 0} 条层记录`,
[
{
tool: "queryFunctions",
action: "listLayerVersions",
reason: "查看某个层的版本列表",
},
{
tool: "manageFunctions",
action: "createLayerVersion",
reason: "发布新的层版本",
},
],
);
}
case "listLayerVersions": {
if (!input.layerName) {
throw new Error("listLayerVersions 操作时,layerName 参数是必需的");
}
const cloudbase = await getManager();
const result = await cloudbase.functions.listLayerVersions({
name: input.layerName,
});
logCloudBaseResult(server.logger, result);
return buildEnvelope(
{
action: input.action,
layerName: input.layerName,
layerVersions: result.LayerVersions || [],
requestId: result.RequestId,
raw: result,
},
`已获取层 ${input.layerName} 的版本列表`,
[
{
tool: "queryFunctions",
action: "getLayerVersionDetail",
reason: "查看某个层版本详情",
},
{
tool: "manageFunctions",
action: "attachLayer",
reason: "将某个层版本绑定到函数",
},
],
);
}
case "getLayerVersionDetail": {
if (!input.layerName) {
throw new Error("getLayerVersionDetail 操作时,layerName 参数是必需的");
}
if (typeof input.layerVersion !== "number") {
throw new Error("getLayerVersionDetail 操作时,layerVersion 参数是必需的");
}
const cloudbase = await getManager();
const result = await cloudbase.functions.getLayerVersion({
name: input.layerName,
version: input.layerVersion,
});
logCloudBaseResult(server.logger, result);
return buildEnvelope(
{
action: input.action,
layerName: input.layerName,
layerVersion: input.layerVersion,
layerVersionDetail: result,
requestId: result.RequestId,
raw: result,
},
`已获取层 ${input.layerName} 版本 ${input.layerVersion} 的详情`,
[
{
tool: "manageFunctions",
action: "attachLayer",
reason: "绑定该层版本到函数",
},
{
tool: "manageFunctions",
action: "deleteLayerVersion",
reason: "删除该层版本",
},
],
);
}
case "listFunctionTriggers": {
if (!input.functionName) {
throw new Error("listFunctionTriggers 操作时,functionName 参数是必需的");
}
const cloudbase = await getManager();
const result = await cloudbase.functions.getFunctionDetail(
input.functionName,
input.codeSecret,
);
logCloudBaseResult(server.logger, result);
return buildEnvelope(
{
action: input.action,
functionName: input.functionName,
triggers: result.Triggers || [],
requestId: result.RequestId,
raw: result,
},
`已获取函数 ${input.functionName} 的触发器列表`,
[
{
tool: "manageFunctions",
action: "createFunctionTrigger",
reason: "创建新的触发器",
},
{
tool: "manageFunctions",
action: "deleteFunctionTrigger",
reason: "删除指定触发器",
},
],
);
}
case "getFunctionDownloadUrl": {
if (!input.functionName) {
throw new Error("getFunctionDownloadUrl 操作时,functionName 参数是必需的");
}
const cloudbase = await getManager();
const result = await cloudbase.functions.getFunctionDownloadUrl(
input.functionName,
input.codeSecret,
);
logCloudBaseResult(server.logger, result);
return buildEnvelope(
{
action: input.action,
functionName: input.functionName,
downloadUrl: result.Url,
codeSha256: result.CodeSha256,
requestId: result.RequestId,
raw: result,
},
`已获取函数 ${input.functionName} 的代码下载链接`,
);
}
default:
throw new Error(`不支持的操作类型: ${input.action}`);
}
};
const handleManageFunctions = async (
input: ManageFunctionsInput,
): Promise<FunctionToolEnvelope> => {
ensureActionAllowedInCloudMode(input);
switch (input.action) {
case "createFunction": {
if (!input.func?.name || typeof input.func.name !== "string") {
throw new Error("createFunction 操作时,func.name 参数是必需的");
}
const cloudbase = await getManager();
const func = { ...input.func };
const functionName = String(func.name);
debug(
`[createFunction] name=${functionName}, type=${String(func.type || "Event")}`,
);
if (func.type !== "HTTP") {
const originalRuntime = typeof func.runtime === "string" ? func.runtime : undefined;
func.runtime = resolveEventFunctionRuntime(func.runtime);
if (
typeof originalRuntime === "string" &&
originalRuntime.includes(" ") &&
originalRuntime.replace(/\s+/g, "") === func.runtime
) {
console.warn(
`检测到 runtime 参数包含空格: "${originalRuntime}",已自动移除空格`,
);
}
}
const processedRootPath = processFunctionRootPath(
input.functionRootPath,
functionName,
);
const functionType =
typeof func.type === "string" ? func.type : undefined;
const expectedFunctionPath = getExpectedFunctionPath(
processedRootPath,
functionName,
);
if (functionType === "HTTP" && !processedRootPath && !input.zipFile) {
throw new Error(
"createFunction 创建 HTTP 函数时,需要提供 functionRootPath(指向 cloudfunctions 或 functions 目录的绝对路径,不是项目根目录)或 zipFile。",
);
}
const hasPackageJson =
expectedFunctionPath !== undefined
? existsSync(path.join(expectedFunctionPath, "package.json"))
: false;
func.installDependency = input.zipFile
? true
: shouldInstallDependencyForFunction(functionType, hasPackageJson);
if (functionType === "HTTP" && processedRootPath && !hasPackageJson) {
console.warn(
`检测到 HTTP 函数 ${functionName} 目录下没有 package.json,已跳过依赖安装;如果你需要第三方依赖,请补充 package.json 后重试。`,
);
}
let result: unknown;
try {
result = await cloudbase.functions.createFunction({
func,
functionRootPath: processedRootPath,
force: Boolean(input.force),
} as any);
} catch (error) {
throw wrapFunctionOperationError(
"createFunction",
functionName,
processedRootPath,
error,
);
}
logCloudBaseResult(server.logger, result);
const nextActions = [
{
tool: "queryFunctions",
action: "getFunctionDetail",
reason: "确认函数配置",
},
{
tool: "queryFunctions",
action: "listFunctionTriggers",
reason: "检查函数触发器",
},
];
if (func.type === "HTTP") {
nextActions.push({
tool: "manageGateway",
action: "createAccess",
reason:
"如果需要通过 URL 访问 HTTP 函数,请调用 manageGateway(action=\"createAccess\") 并显式传 type=\"HTTP\",再按实际路径和鉴权需求创建访问入口,不要默认假设 /函数名 已存在",
});
nextActions.push({
tool: "queryGateway",
action: "getAccess",
reason: "交付前确认 HTTP 访问路径是否已存在并已生效",
});
nextActions.push({
tool: "queryPermissions",
action: "getResourcePermission",
reason:
"评测、浏览器或其他外部调用方可能以匿名身份访问;若直接报 EXCEED_AUTHORITY,应先读取当前函数安全规则",
});
nextActions.push({
tool: "managePermissions",
action: "updateResourcePermission",
reason:
"只有在确认需要匿名访问时,才按实际安全要求调整函数安全规则,例如处理 EXCEED_AUTHORITY",
});
}
const message =
func.type === "HTTP"
? `已创建 HTTP 函数 ${functionName}。如果后续需要通过 URL 访问,请显式调用 manageGateway(action="createAccess"),并把 type="HTTP" 一起传入,再按实际路径和鉴权需求创建访问入口。评测或其他外部调用方可能会以匿名身份访问,而且失败后不一定会把 EXCEED_AUTHORITY 再反馈给 AI;交付前请主动确认访问路径和函数安全规则,若已出现 EXCEED_AUTHORITY,请先调用 queryPermissions(action="getResourcePermission", resourceType="function", resourceId="${functionName}") 查看当前规则,再按需要使用 managePermissions(action="updateResourcePermission") 调整权限。`
: `已创建函数 ${functionName}`;
return buildEnvelope(
{
action: input.action,
functionName,
raw: result as Record<string, unknown>,
},
message,
nextActions,
);
}
case "updateFunctionCode": {
if (!input.functionName) {
throw new Error("updateFunctionCode 操作时,functionName 参数是必需的");
}
const cloudbase = await getManager();