@xiaozhi-client/config 1.9.4-beta.5

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/src/manager.ts ADDED
@@ -0,0 +1,2259 @@
1
+ import { copyFileSync, existsSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { dirname, resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import * as commentJson from "comment-json";
5
+ import dayjs from "dayjs";
6
+ import { createJson5Writer, parseJson5 } from "./json5-adapter.js";
7
+
8
+ // 在 ESM 中,需要从 import.meta.url 获取当前文件目录
9
+ const __dirname = dirname(fileURLToPath(import.meta.url));
10
+
11
+ // 默认连接配置
12
+ const DEFAULT_CONNECTION_CONFIG: Required<ConnectionConfig> = {
13
+ heartbeatInterval: 30000, // 30秒心跳间隔
14
+ heartbeatTimeout: 10000, // 10秒心跳超时
15
+ reconnectInterval: 5000, // 5秒重连间隔
16
+ };
17
+
18
+ // 配置文件接口定义
19
+ // 本地 MCP 服务配置
20
+ export interface LocalMCPServerConfig {
21
+ command: string;
22
+ args: string[];
23
+ env?: Record<string, string>;
24
+ }
25
+
26
+ // SSE MCP 服务配置
27
+ export interface SSEMCPServerConfig {
28
+ type: "sse";
29
+ url: string;
30
+ headers?: Record<string, string>;
31
+ }
32
+
33
+ // Streamable HTTP MCP 服务配置
34
+ export interface StreamableHTTPMCPServerConfig {
35
+ type?: "streamable-http"; // 可选,因为默认就是 streamable-http
36
+ url: string;
37
+ headers?: Record<string, string>;
38
+ }
39
+
40
+ // 统一的 MCP 服务配置
41
+ export type MCPServerConfig =
42
+ | LocalMCPServerConfig
43
+ | SSEMCPServerConfig
44
+ | StreamableHTTPMCPServerConfig;
45
+
46
+ export interface MCPToolConfig {
47
+ description?: string;
48
+ enable: boolean;
49
+ usageCount?: number; // 工具使用次数
50
+ lastUsedTime?: string; // 最后使用时间(ISO 8601 格式)
51
+ }
52
+
53
+ export interface MCPServerToolsConfig {
54
+ tools: Record<string, MCPToolConfig>;
55
+ }
56
+
57
+ export interface ConnectionConfig {
58
+ heartbeatInterval?: number; // 心跳检测间隔(毫秒),默认30000
59
+ heartbeatTimeout?: number; // 心跳超时时间(毫秒),默认10000
60
+ reconnectInterval?: number; // 重连间隔(毫秒),默认5000
61
+ }
62
+
63
+ export interface ModelScopeConfig {
64
+ apiKey?: string; // ModelScope API 密钥
65
+ }
66
+
67
+ export interface WebUIConfig {
68
+ port?: number; // Web UI 端口号,默认 9999
69
+ autoRestart?: boolean; // 是否在配置更新后自动重启服务,默认 true
70
+ }
71
+
72
+ // 工具调用日志配置接口
73
+ export interface ToolCallLogConfig {
74
+ maxRecords?: number; // 最大记录条数,默认 100
75
+ logFilePath?: string; // 自定义日志文件路径(可选)
76
+ }
77
+
78
+ // CustomMCP 相关接口定义
79
+
80
+ // 代理处理器配置
81
+ export interface ProxyHandlerConfig {
82
+ type: "proxy";
83
+ platform: "coze" | "openai" | "anthropic" | "custom";
84
+ config: {
85
+ // Coze 平台配置
86
+ workflow_id?: string;
87
+ bot_id?: string;
88
+ api_key?: string;
89
+ base_url?: string;
90
+ // 通用配置
91
+ timeout?: number;
92
+ retry_count?: number;
93
+ retry_delay?: number;
94
+ headers?: Record<string, string>;
95
+ params?: Record<string, unknown>;
96
+ };
97
+ }
98
+
99
+ // HTTP 处理器配置
100
+ export interface HttpHandlerConfig {
101
+ type: "http";
102
+ url: string;
103
+ method?: "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
104
+ headers?: Record<string, string>;
105
+ timeout?: number;
106
+ retry_count?: number;
107
+ retry_delay?: number;
108
+ auth?: {
109
+ type: "bearer" | "basic" | "api_key";
110
+ token?: string;
111
+ username?: string;
112
+ password?: string;
113
+ api_key?: string;
114
+ api_key_header?: string;
115
+ };
116
+ body_template?: string; // 支持模板变量替换
117
+ response_mapping?: {
118
+ success_path?: string; // JSONPath 表达式
119
+ error_path?: string;
120
+ data_path?: string;
121
+ };
122
+ }
123
+
124
+ // 函数处理器配置
125
+ export interface FunctionHandlerConfig {
126
+ type: "function";
127
+ module: string; // 模块路径
128
+ function: string; // 函数名
129
+ timeout?: number;
130
+ context?: Record<string, unknown>; // 函数执行上下文
131
+ }
132
+
133
+ // 脚本处理器配置
134
+ export interface ScriptHandlerConfig {
135
+ type: "script";
136
+ script: string; // 脚本内容或文件路径
137
+ interpreter?: "node" | "python" | "bash";
138
+ timeout?: number;
139
+ env?: Record<string, string>; // 环境变量
140
+ }
141
+
142
+ // 链式处理器配置
143
+ export interface ChainHandlerConfig {
144
+ type: "chain";
145
+ tools: string[]; // 要链式调用的工具名称
146
+ mode: "sequential" | "parallel"; // 执行模式
147
+ error_handling: "stop" | "continue" | "retry"; // 错误处理策略
148
+ }
149
+
150
+ // MCP 处理器配置(用于同步的工具)
151
+ export interface MCPHandlerConfig {
152
+ type: "mcp";
153
+ config: {
154
+ serviceName: string;
155
+ toolName: string;
156
+ };
157
+ }
158
+
159
+ export type HandlerConfig =
160
+ | ProxyHandlerConfig
161
+ | HttpHandlerConfig
162
+ | FunctionHandlerConfig
163
+ | ScriptHandlerConfig
164
+ | ChainHandlerConfig
165
+ | MCPHandlerConfig;
166
+
167
+ // CustomMCP 工具接口(与核心库兼容)
168
+ export interface CustomMCPTool {
169
+ // 确保必填字段
170
+ name: string;
171
+ description: string;
172
+ inputSchema: Record<string, unknown>;
173
+ handler: HandlerConfig;
174
+
175
+ // 使用统计信息(可选)
176
+ stats?: {
177
+ usageCount?: number; // 工具使用次数
178
+ lastUsedTime?: string; // 最后使用时间(ISO 8601格式)
179
+ };
180
+ }
181
+
182
+ export interface CustomMCPConfig {
183
+ tools: CustomMCPTool[];
184
+ }
185
+
186
+ // Web 服务器实例接口(用于配置更新通知)
187
+ export interface WebServerInstance {
188
+ broadcastConfigUpdate(config: AppConfig): void;
189
+ }
190
+
191
+ export interface PlatformsConfig {
192
+ [platformName: string]: PlatformConfig;
193
+ }
194
+
195
+ export interface PlatformConfig {
196
+ token?: string;
197
+ }
198
+
199
+ /**
200
+ * 扣子平台配置接口
201
+ */
202
+ export interface CozePlatformConfig extends PlatformConfig {
203
+ /** 扣子 API Token */
204
+ token: string;
205
+ }
206
+
207
+ export interface AppConfig {
208
+ mcpEndpoint: string | string[];
209
+ mcpServers: Record<string, MCPServerConfig>;
210
+ mcpServerConfig?: Record<string, MCPServerToolsConfig>;
211
+ customMCP?: CustomMCPConfig; // 新增 customMCP 配置支持
212
+ connection?: ConnectionConfig; // 连接配置(可选,用于向后兼容)
213
+ modelscope?: ModelScopeConfig; // ModelScope 配置(可选)
214
+ webUI?: WebUIConfig; // Web UI 配置(可选)
215
+ platforms?: PlatformsConfig; // 平台配置(可选)
216
+ toolCallLog?: ToolCallLogConfig; // 工具调用日志配置(可选)
217
+ }
218
+
219
+ /**
220
+ * 配置管理类
221
+ * 负责管理应用配置,提供只读访问和安全的配置更新功能
222
+ */
223
+ export class ConfigManager {
224
+ private static instance: ConfigManager;
225
+ private defaultConfigPath: string;
226
+ private config: AppConfig | null = null;
227
+ private currentConfigPath: string | null = null; // 跟踪当前使用的配置文件路径
228
+ private json5Writer: {
229
+ write(data: unknown): void;
230
+ toSource(): string;
231
+ } | null = null; // json5-writer 实例,用于保留 JSON5 注释
232
+
233
+ // 统计更新并发控制
234
+ private statsUpdateLocks: Map<string, Promise<void>> = new Map();
235
+ private statsUpdateLockTimeouts: Map<string, NodeJS.Timeout> = new Map();
236
+ private readonly STATS_UPDATE_TIMEOUT = 5000; // 5秒超时
237
+
238
+ // 事件回调(用于解耦 EventBus 依赖)
239
+ private eventCallbacks: Map<string, Array<(data: unknown) => void>> = new Map();
240
+
241
+ private constructor() {
242
+ // 使用模板目录中的默认配置文件
243
+ // 在不同环境中尝试不同的路径
244
+ const possiblePaths = [
245
+ // 构建后的环境:dist/configManager.js -> dist/templates/default/xiaozhi.config.json
246
+ resolve(__dirname, "templates", "default", "xiaozhi.config.json"),
247
+ // 开发环境:src/configManager.ts -> templates/default/xiaozhi.config.json
248
+ resolve(__dirname, "..", "templates", "default", "xiaozhi.config.json"),
249
+ // 测试环境或其他情况
250
+ resolve(process.cwd(), "templates", "default", "xiaozhi.config.json"),
251
+ ];
252
+
253
+ // 找到第一个存在的路径
254
+ this.defaultConfigPath =
255
+ possiblePaths.find((path) => existsSync(path)) || possiblePaths[0];
256
+ }
257
+
258
+ /**
259
+ * 注册事件监听器
260
+ */
261
+ public on(eventName: string, callback: (data: unknown) => void): void {
262
+ if (!this.eventCallbacks.has(eventName)) {
263
+ this.eventCallbacks.set(eventName, []);
264
+ }
265
+ this.eventCallbacks.get(eventName)?.push(callback);
266
+ }
267
+
268
+ /**
269
+ * 发射事件
270
+ */
271
+ private emitEvent(eventName: string, data: unknown): void {
272
+ const callbacks = this.eventCallbacks.get(eventName);
273
+ if (callbacks) {
274
+ for (const callback of callbacks) {
275
+ try {
276
+ callback(data);
277
+ } catch (error) {
278
+ console.error(`事件回调执行失败 [${eventName}]:`, error);
279
+ }
280
+ }
281
+ }
282
+ }
283
+
284
+ /**
285
+ * 获取配置文件路径(动态计算)
286
+ * 支持多种配置文件格式:json5 > jsonc > json
287
+ */
288
+ private getConfigFilePath(): string {
289
+ // 配置文件路径 - 优先使用环境变量指定的目录,否则使用当前工作目录
290
+ const configDir = process.env.XIAOZHI_CONFIG_DIR || process.cwd();
291
+
292
+ // 按优先级检查配置文件是否存在
293
+ const configFileNames = [
294
+ "xiaozhi.config.json5",
295
+ "xiaozhi.config.jsonc",
296
+ "xiaozhi.config.json",
297
+ ];
298
+
299
+ for (const fileName of configFileNames) {
300
+ const filePath = resolve(configDir, fileName);
301
+ if (existsSync(filePath)) {
302
+ return filePath;
303
+ }
304
+ }
305
+
306
+ // 如果都不存在,返回默认的 JSON 文件路径
307
+ return resolve(configDir, "xiaozhi.config.json");
308
+ }
309
+
310
+ /**
311
+ * 获取配置文件格式
312
+ */
313
+ private getConfigFileFormat(filePath: string): "json5" | "jsonc" | "json" {
314
+ if (filePath.endsWith(".json5")) {
315
+ return "json5";
316
+ }
317
+
318
+ if (filePath.endsWith(".jsonc")) {
319
+ return "jsonc";
320
+ }
321
+
322
+ return "json";
323
+ }
324
+
325
+ /**
326
+ * 获取配置管理器单例实例
327
+ */
328
+ public static getInstance(): ConfigManager {
329
+ if (!ConfigManager.instance) {
330
+ ConfigManager.instance = new ConfigManager();
331
+ }
332
+ return ConfigManager.instance;
333
+ }
334
+
335
+ /**
336
+ * 检查配置文件是否存在
337
+ */
338
+ public configExists(): boolean {
339
+ // 配置文件路径 - 优先使用环境变量指定的目录,否则使用当前工作目录
340
+ const configDir = process.env.XIAOZHI_CONFIG_DIR || process.cwd();
341
+
342
+ // 按优先级检查配置文件是否存在
343
+ const configFileNames = [
344
+ "xiaozhi.config.json5",
345
+ "xiaozhi.config.jsonc",
346
+ "xiaozhi.config.json",
347
+ ];
348
+
349
+ for (const fileName of configFileNames) {
350
+ const filePath = resolve(configDir, fileName);
351
+ if (existsSync(filePath)) {
352
+ return true;
353
+ }
354
+ }
355
+
356
+ return false;
357
+ }
358
+
359
+ /**
360
+ * 初始化配置文件
361
+ * 从 config.default.json 复制到 config.json
362
+ * @param format 配置文件格式,默认为 json
363
+ */
364
+ public initConfig(format: "json" | "json5" | "jsonc" = "json"): void {
365
+ if (!existsSync(this.defaultConfigPath)) {
366
+ throw new Error(`默认配置模板文件不存在: ${this.defaultConfigPath}`);
367
+ }
368
+
369
+ // 检查是否已有任何格式的配置文件
370
+ if (this.configExists()) {
371
+ throw new Error("配置文件已存在,无需重复初始化");
372
+ }
373
+
374
+ // 确定目标配置文件路径
375
+ const configDir = process.env.XIAOZHI_CONFIG_DIR || process.cwd();
376
+ const targetFileName = `xiaozhi.config.${format}`;
377
+ const configPath = resolve(configDir, targetFileName);
378
+
379
+ // 复制默认配置文件
380
+ copyFileSync(this.defaultConfigPath, configPath);
381
+ this.config = null; // 重置缓存
382
+ this.json5Writer = null; // 重置 json5Writer 实例
383
+ }
384
+
385
+ /**
386
+ * 加载配置文件
387
+ */
388
+ private loadConfig(): AppConfig {
389
+ if (!this.configExists()) {
390
+ const error = new Error(
391
+ "配置文件不存在,请先运行 xiaozhi init 初始化配置"
392
+ );
393
+ this.emitEvent("config:error", {
394
+ error,
395
+ operation: "loadConfig",
396
+ });
397
+ throw error;
398
+ }
399
+
400
+ try {
401
+ const configPath = this.getConfigFilePath();
402
+ this.currentConfigPath = configPath; // 记录当前使用的配置文件路径
403
+ const configFileFormat = this.getConfigFileFormat(configPath);
404
+ const rawConfigData = readFileSync(configPath, "utf8");
405
+
406
+ // 移除可能存在的UTF-8 BOM字符(\uFEFF)
407
+ // BOM字符在某些编辑器中不可见,但会导致JSON解析失败
408
+ // 这个过滤确保即使文件包含BOM字符也能正常解析
409
+ const configData = rawConfigData.replace(/^\uFEFF/, "");
410
+
411
+ let config: AppConfig;
412
+
413
+ // 根据文件格式使用相应的解析器
414
+ switch (configFileFormat) {
415
+ case "json5":
416
+ // 使用 JSON5 解析配置对象,同时使用适配器保留注释信息
417
+ config = parseJson5(configData) as AppConfig;
418
+ // 创建适配器实例用于后续保存时保留注释
419
+ this.json5Writer = createJson5Writer(configData);
420
+ break;
421
+ case "jsonc":
422
+ // 使用 comment-json 解析 JSONC 格式,保留注释信息
423
+ config = commentJson.parse(configData) as unknown as AppConfig;
424
+ break;
425
+ default:
426
+ config = JSON.parse(configData) as AppConfig;
427
+ break;
428
+ }
429
+
430
+ // 验证配置结构
431
+ this.validateConfig(config);
432
+
433
+ return config;
434
+ } catch (error) {
435
+ // 发射配置错误事件
436
+ this.emitEvent("config:error", {
437
+ error: error instanceof Error ? error : new Error(String(error)),
438
+ operation: "loadConfig",
439
+ });
440
+ if (error instanceof SyntaxError) {
441
+ throw new Error(`配置文件格式错误: ${error.message}`);
442
+ }
443
+ throw error;
444
+ }
445
+ }
446
+
447
+ /**
448
+ * 验证配置文件结构
449
+ */
450
+ public validateConfig(config: unknown): void {
451
+ if (!config || typeof config !== "object") {
452
+ throw new Error("配置文件格式错误:根对象无效");
453
+ }
454
+
455
+ const configObj = config as Record<string, unknown>;
456
+
457
+ if (configObj.mcpEndpoint === undefined || configObj.mcpEndpoint === null) {
458
+ throw new Error("配置文件格式错误:mcpEndpoint 字段无效");
459
+ }
460
+
461
+ // 验证 mcpEndpoint 类型(字符串或字符串数组)
462
+ if (typeof configObj.mcpEndpoint === "string") {
463
+ // 空字符串是允许的,getMcpEndpoints 会返回空数组
464
+ } else if (Array.isArray(configObj.mcpEndpoint)) {
465
+ for (const endpoint of configObj.mcpEndpoint) {
466
+ if (typeof endpoint !== "string" || endpoint.trim() === "") {
467
+ throw new Error(
468
+ "配置文件格式错误:mcpEndpoint 数组中的每个元素必须是非空字符串"
469
+ );
470
+ }
471
+ }
472
+ } else {
473
+ throw new Error("配置文件格式错误:mcpEndpoint 必须是字符串或字符串数组");
474
+ }
475
+
476
+ if (!configObj.mcpServers || typeof configObj.mcpServers !== "object") {
477
+ throw new Error("配置文件格式错误:mcpServers 字段无效");
478
+ }
479
+
480
+ // 验证每个 MCP 服务配置
481
+ for (const [serverName, serverConfig] of Object.entries(
482
+ configObj.mcpServers as Record<string, unknown>
483
+ )) {
484
+ if (!serverConfig || typeof serverConfig !== "object") {
485
+ throw new Error(`配置文件格式错误:mcpServers.${serverName} 无效`);
486
+ }
487
+
488
+ // 基本验证:确保配置有效
489
+ // 更详细的验证应该由调用方完成
490
+ }
491
+ }
492
+
493
+ /**
494
+ * 获取配置(只读)
495
+ */
496
+ public getConfig(): Readonly<AppConfig> {
497
+ this.config = this.loadConfig();
498
+
499
+ // 返回深度只读副本
500
+ return JSON.parse(JSON.stringify(this.config));
501
+ }
502
+
503
+ /**
504
+ * 获取可修改的配置对象(内部使用,保留注释信息)
505
+ */
506
+ private getMutableConfig(): AppConfig {
507
+ if (!this.config) {
508
+ this.config = this.loadConfig();
509
+ }
510
+ return this.config;
511
+ }
512
+
513
+ /**
514
+ * 获取 MCP 端点(向后兼容)
515
+ * @deprecated 使用 getMcpEndpoints() 获取所有端点
516
+ */
517
+ public getMcpEndpoint(): string {
518
+ const config = this.getConfig();
519
+ if (Array.isArray(config.mcpEndpoint)) {
520
+ return config.mcpEndpoint[0] || "";
521
+ }
522
+ return config.mcpEndpoint;
523
+ }
524
+
525
+ /**
526
+ * 获取所有 MCP 端点
527
+ */
528
+ public getMcpEndpoints(): string[] {
529
+ const config = this.getConfig();
530
+ if (Array.isArray(config.mcpEndpoint)) {
531
+ return [...config.mcpEndpoint];
532
+ }
533
+ return config.mcpEndpoint ? [config.mcpEndpoint] : [];
534
+ }
535
+
536
+ /**
537
+ * 获取 MCP 服务配置
538
+ */
539
+ public getMcpServers(): Readonly<Record<string, MCPServerConfig>> {
540
+ const config = this.getConfig();
541
+ return config.mcpServers;
542
+ }
543
+
544
+ /**
545
+ * 获取 MCP 服务工具配置
546
+ */
547
+ public getMcpServerConfig(): Readonly<Record<string, MCPServerToolsConfig>> {
548
+ const config = this.getConfig();
549
+ return config.mcpServerConfig || {};
550
+ }
551
+
552
+ /**
553
+ * 获取指定服务的工具配置
554
+ */
555
+ public getServerToolsConfig(
556
+ serverName: string
557
+ ): Readonly<Record<string, MCPToolConfig>> {
558
+ const serverConfig = this.getMcpServerConfig();
559
+ return serverConfig[serverName]?.tools || {};
560
+ }
561
+
562
+ /**
563
+ * 检查工具是否启用
564
+ */
565
+ public isToolEnabled(serverName: string, toolName: string): boolean {
566
+ const toolsConfig = this.getServerToolsConfig(serverName);
567
+ const toolConfig = toolsConfig[toolName];
568
+ return toolConfig?.enable !== false; // 默认启用
569
+ }
570
+
571
+ /**
572
+ * 更新 MCP 端点(支持字符串或数组)
573
+ */
574
+ public updateMcpEndpoint(endpoint: string | string[]): void {
575
+ if (Array.isArray(endpoint)) {
576
+ for (const ep of endpoint) {
577
+ if (!ep || typeof ep !== "string") {
578
+ throw new Error("MCP 端点数组中的每个元素必须是非空字符串");
579
+ }
580
+ }
581
+ }
582
+
583
+ const config = this.getMutableConfig();
584
+ config.mcpEndpoint = endpoint;
585
+ this.saveConfig(config);
586
+
587
+ // 发射配置更新事件
588
+ this.emitEvent("config:updated", {
589
+ type: "endpoint",
590
+ timestamp: new Date(),
591
+ });
592
+ }
593
+
594
+ /**
595
+ * 添加 MCP 端点
596
+ */
597
+ public addMcpEndpoint(endpoint: string): void {
598
+ if (!endpoint || typeof endpoint !== "string") {
599
+ throw new Error("MCP 端点必须是非空字符串");
600
+ }
601
+
602
+ const config = this.getMutableConfig();
603
+ const currentEndpoints = this.getMcpEndpoints();
604
+
605
+ // 检查是否已存在
606
+ if (currentEndpoints.includes(endpoint)) {
607
+ throw new Error(`MCP 端点 ${endpoint} 已存在`);
608
+ }
609
+
610
+ const newEndpoints = [...currentEndpoints, endpoint];
611
+ config.mcpEndpoint = newEndpoints;
612
+ this.saveConfig(config);
613
+ }
614
+
615
+ /**
616
+ * 移除 MCP 端点
617
+ */
618
+ public removeMcpEndpoint(endpoint: string): void {
619
+ if (!endpoint || typeof endpoint !== "string") {
620
+ throw new Error("MCP 端点必须是非空字符串");
621
+ }
622
+
623
+ const config = this.getMutableConfig();
624
+ const currentEndpoints = this.getMcpEndpoints();
625
+
626
+ // 检查是否存在
627
+ const index = currentEndpoints.indexOf(endpoint);
628
+ if (index === -1) {
629
+ throw new Error(`MCP 端点 ${endpoint} 不存在`);
630
+ }
631
+
632
+ const newEndpoints = currentEndpoints.filter((ep) => ep !== endpoint);
633
+ config.mcpEndpoint = newEndpoints;
634
+ this.saveConfig(config);
635
+ }
636
+
637
+ /**
638
+ * 更新 MCP 服务配置
639
+ */
640
+ public updateMcpServer(
641
+ serverName: string,
642
+ serverConfig: MCPServerConfig
643
+ ): void {
644
+ if (!serverName || typeof serverName !== "string") {
645
+ throw new Error("服务名称必须是非空字符串");
646
+ }
647
+
648
+ const config = this.getMutableConfig();
649
+ // 直接修改配置对象以保留注释信息
650
+ config.mcpServers[serverName] = serverConfig;
651
+ this.saveConfig(config);
652
+ }
653
+
654
+ /**
655
+ * 删除 MCP 服务配置
656
+ */
657
+ public removeMcpServer(serverName: string): void {
658
+ if (!serverName || typeof serverName !== "string") {
659
+ throw new Error("服务名称必须是非空字符串");
660
+ }
661
+
662
+ const config = this.getMutableConfig();
663
+
664
+ // 检查服务是否存在
665
+ if (!config.mcpServers[serverName]) {
666
+ throw new Error(`服务 ${serverName} 不存在`);
667
+ }
668
+
669
+ // 1. 清理 mcpServers 字段(现有逻辑)
670
+ delete config.mcpServers[serverName];
671
+
672
+ // 2. 清理 mcpServerConfig 字段(复用现有方法)
673
+ if (config.mcpServerConfig?.[serverName]) {
674
+ delete config.mcpServerConfig[serverName];
675
+ }
676
+
677
+ // 3. 清理 customMCP 字段中相关的工具定义
678
+ if (config.customMCP?.tools) {
679
+ // 查找与该服务相关的 CustomMCP 工具
680
+ const relatedTools = config.customMCP.tools.filter(
681
+ (tool) =>
682
+ tool.handler?.type === "mcp" &&
683
+ tool.handler.config?.serviceName === serverName
684
+ );
685
+
686
+ // 移除相关工具
687
+ for (const tool of relatedTools) {
688
+ const toolIndex = config.customMCP.tools.findIndex(
689
+ (t) => t.name === tool.name
690
+ );
691
+ if (toolIndex !== -1) {
692
+ config.customMCP.tools.splice(toolIndex, 1);
693
+ }
694
+ }
695
+
696
+ // 如果没有工具了,可以清理整个 customMCP 对象
697
+ if (config.customMCP.tools.length === 0) {
698
+ config.customMCP = undefined;
699
+ }
700
+ }
701
+
702
+ // 4. 保存配置(单次原子性操作)
703
+ this.saveConfig(config);
704
+
705
+ // 5. 发射配置更新事件,通知 CustomMCPHandler 重新初始化
706
+ this.emitEvent("config:updated", {
707
+ type: "customMCP",
708
+ timestamp: new Date(),
709
+ });
710
+
711
+ // 记录清理结果
712
+ console.log("成功移除 MCP 服务", { serverName });
713
+ }
714
+
715
+ /**
716
+ * 批量更新配置(由 Handler 调用)
717
+ */
718
+ public updateConfig(newConfig: Partial<AppConfig>): void {
719
+ const config = this.getMutableConfig();
720
+
721
+ // 更新 MCP 端点
722
+ if (newConfig.mcpEndpoint !== undefined) {
723
+ config.mcpEndpoint = newConfig.mcpEndpoint;
724
+ }
725
+
726
+ // 更新 MCP 服务
727
+ if (newConfig.mcpServers) {
728
+ const currentServers = { ...config.mcpServers };
729
+ for (const [name, serverConfig] of Object.entries(newConfig.mcpServers)) {
730
+ config.mcpServers[name] = serverConfig;
731
+ }
732
+ // 删除不存在的服务
733
+ for (const name of Object.keys(currentServers)) {
734
+ if (!(name in newConfig.mcpServers)) {
735
+ delete config.mcpServers[name];
736
+ // 同时清理工具配置
737
+ if (config.mcpServerConfig?.[name]) {
738
+ delete config.mcpServerConfig[name];
739
+ }
740
+ }
741
+ }
742
+ }
743
+
744
+ // 更新连接配置
745
+ if (newConfig.connection) {
746
+ if (!config.connection) {
747
+ config.connection = {};
748
+ }
749
+ Object.assign(config.connection, newConfig.connection);
750
+ }
751
+
752
+ // 更新 ModelScope 配置
753
+ if (newConfig.modelscope) {
754
+ if (!config.modelscope) {
755
+ config.modelscope = {};
756
+ }
757
+ Object.assign(config.modelscope, newConfig.modelscope);
758
+ }
759
+
760
+ // 更新 Web UI 配置
761
+ if (newConfig.webUI) {
762
+ if (!config.webUI) {
763
+ config.webUI = {};
764
+ }
765
+ Object.assign(config.webUI, newConfig.webUI);
766
+ }
767
+
768
+ // 更新服务工具配置
769
+ if (newConfig.mcpServerConfig) {
770
+ for (const [serverName, toolsConfig] of Object.entries(
771
+ newConfig.mcpServerConfig
772
+ )) {
773
+ if (config.mcpServerConfig?.[serverName]) {
774
+ config.mcpServerConfig[serverName] = toolsConfig;
775
+ }
776
+ }
777
+ }
778
+
779
+ // 更新平台配置
780
+ if (newConfig.platforms) {
781
+ for (const [platformName, platformConfig] of Object.entries(
782
+ newConfig.platforms
783
+ )) {
784
+ if (!config.platforms) {
785
+ config.platforms = {};
786
+ }
787
+ config.platforms[platformName] = platformConfig;
788
+ }
789
+ }
790
+
791
+ this.saveConfig(config);
792
+
793
+ // 发射配置更新事件
794
+ this.emitEvent("config:updated", {
795
+ type: "config",
796
+ timestamp: new Date(),
797
+ });
798
+ }
799
+
800
+ /**
801
+ * 更新服务工具配置
802
+ */
803
+ public updateServerToolsConfig(
804
+ serverName: string,
805
+ toolsConfig: Record<string, MCPToolConfig>
806
+ ): void {
807
+ const config = this.getMutableConfig();
808
+
809
+ // 确保 mcpServerConfig 存在
810
+ if (!config.mcpServerConfig) {
811
+ config.mcpServerConfig = {};
812
+ }
813
+
814
+ // 如果 toolsConfig 为空对象,则删除该服务的配置
815
+ if (Object.keys(toolsConfig).length === 0) {
816
+ delete config.mcpServerConfig[serverName];
817
+ } else {
818
+ // 更新指定服务的工具配置
819
+ config.mcpServerConfig[serverName] = {
820
+ tools: toolsConfig,
821
+ };
822
+ }
823
+
824
+ this.saveConfig(config);
825
+
826
+ // 发射配置更新事件
827
+ this.emitEvent("config:updated", {
828
+ type: "serverTools",
829
+ serviceName: serverName,
830
+ timestamp: new Date(),
831
+ });
832
+ }
833
+
834
+ /**
835
+ * 删除指定服务器的工具配置
836
+ */
837
+ public removeServerToolsConfig(serverName: string): void {
838
+ const config = this.getConfig();
839
+ const newConfig = { ...config };
840
+
841
+ // 确保 mcpServerConfig 存在
842
+ if (newConfig.mcpServerConfig) {
843
+ // 删除指定服务的工具配置
844
+ delete newConfig.mcpServerConfig[serverName];
845
+ this.saveConfig(newConfig);
846
+ }
847
+ }
848
+
849
+ /**
850
+ * 清理无效的服务器工具配置
851
+ * 删除在 mcpServerConfig 中存在但在 mcpServers 中不存在的服务配置
852
+ */
853
+ public cleanupInvalidServerToolsConfig(): void {
854
+ const config = this.getMutableConfig();
855
+
856
+ // 如果没有 mcpServerConfig,无需清理
857
+ if (!config.mcpServerConfig) {
858
+ return;
859
+ }
860
+
861
+ const validServerNames = Object.keys(config.mcpServers);
862
+ const configuredServerNames = Object.keys(config.mcpServerConfig);
863
+
864
+ // 找出需要清理的服务名称
865
+ const invalidServerNames = configuredServerNames.filter(
866
+ (serverName) => !validServerNames.includes(serverName)
867
+ );
868
+
869
+ if (invalidServerNames.length > 0) {
870
+ // 删除无效的服务配置
871
+ for (const serverName of invalidServerNames) {
872
+ delete config.mcpServerConfig[serverName];
873
+ }
874
+
875
+ this.saveConfig(config);
876
+
877
+ console.log("已清理无效的服务工具配置", {
878
+ count: invalidServerNames.length,
879
+ serverNames: invalidServerNames,
880
+ });
881
+ }
882
+ }
883
+
884
+ /**
885
+ * 设置工具启用状态
886
+ */
887
+ public setToolEnabled(
888
+ serverName: string,
889
+ toolName: string,
890
+ enabled: boolean,
891
+ description?: string
892
+ ): void {
893
+ const config = this.getMutableConfig();
894
+
895
+ // 确保 mcpServerConfig 存在
896
+ if (!config.mcpServerConfig) {
897
+ config.mcpServerConfig = {};
898
+ }
899
+
900
+ // 确保服务配置存在
901
+ if (!config.mcpServerConfig[serverName]) {
902
+ config.mcpServerConfig[serverName] = { tools: {} };
903
+ }
904
+
905
+ // 更新工具配置
906
+ config.mcpServerConfig[serverName].tools[toolName] = {
907
+ ...config.mcpServerConfig[serverName].tools[toolName],
908
+ enable: enabled,
909
+ ...(description && { description }),
910
+ };
911
+
912
+ this.saveConfig(config);
913
+ }
914
+
915
+ /**
916
+ * 保存配置到文件
917
+ * 保存到原始配置文件路径,保持文件格式一致性
918
+ */
919
+ private saveConfig(config: AppConfig): void {
920
+ try {
921
+ // 验证配置
922
+ this.validateConfig(config);
923
+
924
+ // 确定保存路径 - 优先使用当前配置文件路径,否则使用默认路径
925
+ let configPath: string;
926
+ if (this.currentConfigPath) {
927
+ configPath = this.currentConfigPath;
928
+ } else {
929
+ // 如果没有当前路径,使用 getConfigFilePath 获取
930
+ configPath = this.getConfigFilePath();
931
+ this.currentConfigPath = configPath;
932
+ }
933
+
934
+ // 根据文件格式选择序列化方法
935
+ const configFileFormat = this.getConfigFileFormat(configPath);
936
+ let configContent: string;
937
+
938
+ switch (configFileFormat) {
939
+ case "json5":
940
+ // 对于 JSON5 格式,使用适配器保留注释
941
+ try {
942
+ if (this.json5Writer) {
943
+ // 使用适配器更新配置并保留注释
944
+ this.json5Writer.write(config);
945
+ configContent = this.json5Writer.toSource();
946
+ } else {
947
+ // 如果没有适配器实例,回退到 comment-json 序列化
948
+ console.warn("没有 JSON5 适配器实例,使用 comment-json 序列化");
949
+ configContent = commentJson.stringify(config, null, 2);
950
+ }
951
+ } catch (json5Error) {
952
+ // 如果适配器序列化失败,回退到 comment-json 序列化
953
+ console.warn(
954
+ "使用 JSON5 适配器保存失败,回退到 comment-json 序列化:",
955
+ json5Error
956
+ );
957
+ configContent = commentJson.stringify(config, null, 2);
958
+ }
959
+ break;
960
+ case "jsonc":
961
+ // 对于 JSONC 格式,使用 comment-json 库保留注释
962
+ try {
963
+ // 直接使用 comment-json 的 stringify 方法
964
+ // 如果 config 是通过 comment-json.parse 解析的,注释信息会被保留
965
+ configContent = commentJson.stringify(config, null, 2);
966
+ } catch (commentJsonError) {
967
+ // 如果 comment-json 序列化失败,回退到标准 JSON
968
+ console.warn(
969
+ "使用 comment-json 保存失败,回退到标准 JSON 格式:",
970
+ commentJsonError
971
+ );
972
+ configContent = JSON.stringify(config, null, 2);
973
+ }
974
+ break;
975
+ default:
976
+ configContent = JSON.stringify(config, null, 2);
977
+ break;
978
+ }
979
+
980
+ // 保存到文件
981
+ writeFileSync(configPath, configContent, "utf8");
982
+
983
+ // 更新缓存
984
+ this.config = config;
985
+
986
+ console.log("配置保存成功");
987
+
988
+ // 通知 Web 界面配置已更新(如果 Web 服务器正在运行)
989
+ this.notifyConfigUpdate(config);
990
+ } catch (error) {
991
+ // 发射配置错误事件
992
+ this.emitEvent("config:error", {
993
+ error: error instanceof Error ? error : new Error(String(error)),
994
+ operation: "saveConfig",
995
+ });
996
+ throw new Error(
997
+ `保存配置失败: ${
998
+ error instanceof Error ? error.message : String(error)
999
+ }`
1000
+ );
1001
+ }
1002
+ }
1003
+
1004
+ /**
1005
+ * 重新加载配置(清除缓存)
1006
+ */
1007
+ public reloadConfig(): void {
1008
+ this.config = null;
1009
+ this.currentConfigPath = null; // 清除配置文件路径缓存
1010
+ this.json5Writer = null; // 清除 json5Writer 实例
1011
+ }
1012
+
1013
+ /**
1014
+ * 获取配置文件路径
1015
+ */
1016
+ public getConfigPath(): string {
1017
+ return this.getConfigFilePath();
1018
+ }
1019
+
1020
+ /**
1021
+ * 获取默认配置文件路径
1022
+ */
1023
+ public getDefaultConfigPath(): string {
1024
+ return this.defaultConfigPath;
1025
+ }
1026
+
1027
+ /**
1028
+ * 获取连接配置(包含默认值)
1029
+ */
1030
+ public getConnectionConfig(): Required<ConnectionConfig> {
1031
+ const config = this.getConfig();
1032
+ const connectionConfig = config.connection || {};
1033
+
1034
+ return {
1035
+ heartbeatInterval:
1036
+ connectionConfig.heartbeatInterval ??
1037
+ DEFAULT_CONNECTION_CONFIG.heartbeatInterval,
1038
+ heartbeatTimeout:
1039
+ connectionConfig.heartbeatTimeout ??
1040
+ DEFAULT_CONNECTION_CONFIG.heartbeatTimeout,
1041
+ reconnectInterval:
1042
+ connectionConfig.reconnectInterval ??
1043
+ DEFAULT_CONNECTION_CONFIG.reconnectInterval,
1044
+ };
1045
+ }
1046
+
1047
+ /**
1048
+ * 获取心跳检测间隔(毫秒)
1049
+ */
1050
+ public getHeartbeatInterval(): number {
1051
+ return this.getConnectionConfig().heartbeatInterval;
1052
+ }
1053
+
1054
+ /**
1055
+ * 获取心跳超时时间(毫秒)
1056
+ */
1057
+ public getHeartbeatTimeout(): number {
1058
+ return this.getConnectionConfig().heartbeatTimeout;
1059
+ }
1060
+
1061
+ /**
1062
+ * 获取重连间隔(毫秒)
1063
+ */
1064
+ public getReconnectInterval(): number {
1065
+ return this.getConnectionConfig().reconnectInterval;
1066
+ }
1067
+
1068
+ /**
1069
+ * 更新连接配置
1070
+ */
1071
+ public updateConnectionConfig(
1072
+ connectionConfig: Partial<ConnectionConfig>
1073
+ ): void {
1074
+ const config = this.getMutableConfig();
1075
+
1076
+ // 确保 connection 对象存在
1077
+ if (!config.connection) {
1078
+ config.connection = {};
1079
+ }
1080
+
1081
+ // 直接修改现有的 connection 对象以保留注释
1082
+ Object.assign(config.connection, connectionConfig);
1083
+ this.saveConfig(config);
1084
+
1085
+ // 发射配置更新事件
1086
+ this.emitEvent("config:updated", {
1087
+ type: "connection",
1088
+ timestamp: new Date(),
1089
+ });
1090
+ }
1091
+
1092
+ /**
1093
+ * 更新工具使用统计信息(MCP 服务工具)
1094
+ * @param serverName 服务名称
1095
+ * @param toolName 工具名称
1096
+ * @param callTime 调用时间(ISO 8601 格式)
1097
+ */
1098
+ public async updateToolUsageStats(
1099
+ serverName: string,
1100
+ toolName: string,
1101
+ callTime: string
1102
+ ): Promise<void>;
1103
+
1104
+ /**
1105
+ * 更新工具使用统计信息(CustomMCP 工具)
1106
+ * @param toolName 工具名称(customMCP 工具名称)
1107
+ * @param incrementUsageCount 是否增加使用计数,默认为 true
1108
+ */
1109
+ public async updateToolUsageStats(
1110
+ toolName: string,
1111
+ incrementUsageCount?: boolean
1112
+ ): Promise<void>;
1113
+
1114
+ /**
1115
+ * 更新工具使用统计信息的实现
1116
+ */
1117
+ public async updateToolUsageStats(
1118
+ arg1: string,
1119
+ arg2: string | boolean | undefined,
1120
+ arg3?: string
1121
+ ): Promise<void> {
1122
+ try {
1123
+ // 判断参数类型来区分不同的重载
1124
+ if (typeof arg2 === "string" && arg3) {
1125
+ // 三个参数的情况:updateToolUsageStats(serverName, toolName, callTime)
1126
+ const serverName = arg1;
1127
+ const toolName = arg2;
1128
+ const callTime = arg3;
1129
+
1130
+ // 双写机制:同时更新 mcpServerConfig 和 customMCP 中的统计信息
1131
+ await Promise.all([
1132
+ this._updateMCPServerToolStats(serverName, toolName, callTime),
1133
+ this.updateCustomMCPToolStats(serverName, toolName, callTime),
1134
+ ]);
1135
+
1136
+ console.log("工具使用统计已更新", { serverName, toolName });
1137
+ } else {
1138
+ // 两个参数的情况:updateToolUsageStats(toolName, incrementUsageCount)
1139
+ const toolName = arg1;
1140
+ const incrementUsageCount = arg2 as boolean;
1141
+ const callTime = new Date().toISOString();
1142
+
1143
+ // 只更新 customMCP 中的统计信息
1144
+ await this.updateCustomMCPToolStats(
1145
+ toolName,
1146
+ callTime,
1147
+ incrementUsageCount
1148
+ );
1149
+
1150
+ console.log("CustomMCP 工具使用统计已更新", { toolName });
1151
+ }
1152
+ } catch (error) {
1153
+ // 错误不应该影响主要的工具调用流程
1154
+ if (typeof arg2 === "string" && arg3) {
1155
+ const serverName = arg1;
1156
+ const toolName = arg2;
1157
+ console.error("更新工具使用统计失败", { serverName, toolName, error });
1158
+ } else {
1159
+ const toolName = arg1;
1160
+ console.error("更新 CustomMCP 工具使用统计失败", { toolName, error });
1161
+ }
1162
+ }
1163
+ }
1164
+
1165
+ /**
1166
+ * 更新 MCP 服务工具统计信息(重载方法)
1167
+ * @param serviceName 服务名称
1168
+ * @param toolName 工具名称
1169
+ * @param callTime 调用时间(ISO 8601 格式)
1170
+ * @param incrementUsageCount 是否增加使用计数,默认为 true
1171
+ */
1172
+ public async updateMCPServerToolStats(
1173
+ serviceName: string,
1174
+ toolName: string,
1175
+ callTime: string,
1176
+ incrementUsageCount = true
1177
+ ): Promise<void> {
1178
+ await this._updateMCPServerToolStats(
1179
+ serviceName,
1180
+ toolName,
1181
+ callTime,
1182
+ incrementUsageCount
1183
+ );
1184
+ }
1185
+
1186
+ /**
1187
+ * 设置心跳检测间隔
1188
+ */
1189
+ public setHeartbeatInterval(interval: number): void {
1190
+ if (interval <= 0) {
1191
+ throw new Error("心跳检测间隔必须大于0");
1192
+ }
1193
+ this.updateConnectionConfig({ heartbeatInterval: interval });
1194
+ }
1195
+
1196
+ /**
1197
+ * 设置心跳超时时间
1198
+ */
1199
+ public setHeartbeatTimeout(timeout: number): void {
1200
+ if (timeout <= 0) {
1201
+ throw new Error("心跳超时时间必须大于0");
1202
+ }
1203
+ this.updateConnectionConfig({ heartbeatTimeout: timeout });
1204
+ }
1205
+
1206
+ /**
1207
+ * 设置重连间隔
1208
+ */
1209
+ public setReconnectInterval(interval: number): void {
1210
+ if (interval <= 0) {
1211
+ throw new Error("重连间隔必须大于0");
1212
+ }
1213
+ this.updateConnectionConfig({ reconnectInterval: interval });
1214
+ }
1215
+
1216
+ /**
1217
+ * 获取 ModelScope 配置
1218
+ */
1219
+ public getModelScopeConfig(): Readonly<ModelScopeConfig> {
1220
+ const config = this.getConfig();
1221
+ return config.modelscope || {};
1222
+ }
1223
+
1224
+ /**
1225
+ * 获取 ModelScope API Key
1226
+ * 优先从配置文件读取,其次从环境变量读取
1227
+ */
1228
+ public getModelScopeApiKey(): string | undefined {
1229
+ const modelScopeConfig = this.getModelScopeConfig();
1230
+ return modelScopeConfig.apiKey || process.env.MODELSCOPE_API_TOKEN;
1231
+ }
1232
+
1233
+ /**
1234
+ * 更新 ModelScope 配置
1235
+ */
1236
+ public updateModelScopeConfig(
1237
+ modelScopeConfig: Partial<ModelScopeConfig>
1238
+ ): void {
1239
+ const config = this.getMutableConfig();
1240
+
1241
+ // 确保 modelscope 对象存在
1242
+ if (!config.modelscope) {
1243
+ config.modelscope = {};
1244
+ }
1245
+
1246
+ // 直接修改现有的 modelscope 对象以保留注释
1247
+ Object.assign(config.modelscope, modelScopeConfig);
1248
+ this.saveConfig(config);
1249
+
1250
+ // 发射配置更新事件
1251
+ this.emitEvent("config:updated", {
1252
+ type: "modelscope",
1253
+ timestamp: new Date(),
1254
+ });
1255
+ }
1256
+
1257
+ /**
1258
+ * 设置 ModelScope API Key
1259
+ */
1260
+ public setModelScopeApiKey(apiKey: string): void {
1261
+ if (!apiKey || typeof apiKey !== "string") {
1262
+ throw new Error("API Key 必须是非空字符串");
1263
+ }
1264
+ this.updateModelScopeConfig({ apiKey });
1265
+ }
1266
+
1267
+ /**
1268
+ * 获取 customMCP 配置
1269
+ */
1270
+ public getCustomMCPConfig(): CustomMCPConfig | null {
1271
+ const config = this.getConfig();
1272
+ return config.customMCP || null;
1273
+ }
1274
+
1275
+ /**
1276
+ * 获取 customMCP 工具列表
1277
+ */
1278
+ public getCustomMCPTools(): CustomMCPTool[] {
1279
+ const customMCPConfig = this.getCustomMCPConfig();
1280
+ if (!customMCPConfig || !customMCPConfig.tools) {
1281
+ return [];
1282
+ }
1283
+
1284
+ return customMCPConfig.tools;
1285
+ }
1286
+
1287
+ /**
1288
+ * 验证 customMCP 工具配置
1289
+ */
1290
+ public validateCustomMCPTools(tools: CustomMCPTool[]): boolean {
1291
+ if (!Array.isArray(tools)) {
1292
+ return false;
1293
+ }
1294
+
1295
+ for (const tool of tools) {
1296
+ // 检查必需字段
1297
+ if (!tool.name || typeof tool.name !== "string") {
1298
+ console.warn("CustomMCP 工具缺少有效的 name 字段", { tool });
1299
+ return false;
1300
+ }
1301
+
1302
+ if (!tool.description || typeof tool.description !== "string") {
1303
+ console.warn("CustomMCP 工具缺少有效的 description 字段", {
1304
+ toolName: tool.name,
1305
+ });
1306
+ return false;
1307
+ }
1308
+
1309
+ if (!tool.inputSchema || typeof tool.inputSchema !== "object") {
1310
+ console.warn("CustomMCP 工具缺少有效的 inputSchema 字段", {
1311
+ toolName: tool.name,
1312
+ });
1313
+ return false;
1314
+ }
1315
+
1316
+ if (!tool.handler || typeof tool.handler !== "object") {
1317
+ console.warn("CustomMCP 工具缺少有效的 handler 字段", {
1318
+ toolName: tool.name,
1319
+ });
1320
+ return false;
1321
+ }
1322
+
1323
+ // 检查 handler 类型
1324
+ if (
1325
+ !["proxy", "function", "http", "script", "chain", "mcp"].includes(
1326
+ tool.handler.type
1327
+ )
1328
+ ) {
1329
+ console.warn("CustomMCP 工具的 handler.type 类型无效", {
1330
+ toolName: tool.name,
1331
+ type: tool.handler.type,
1332
+ });
1333
+ return false;
1334
+ }
1335
+
1336
+ // 根据处理器类型进行特定验证
1337
+ if (!this.validateHandlerConfig(tool.name, tool.handler)) {
1338
+ return false;
1339
+ }
1340
+ }
1341
+
1342
+ return true;
1343
+ }
1344
+
1345
+ /**
1346
+ * 验证处理器配置
1347
+ */
1348
+ private validateHandlerConfig(
1349
+ toolName: string,
1350
+ handler: HandlerConfig
1351
+ ): boolean {
1352
+ switch (handler.type) {
1353
+ case "proxy":
1354
+ return this.validateProxyHandler(toolName, handler);
1355
+ case "http":
1356
+ return this.validateHttpHandler(toolName, handler);
1357
+ case "function":
1358
+ return this.validateFunctionHandler(toolName, handler);
1359
+ case "script":
1360
+ return this.validateScriptHandler(toolName, handler);
1361
+ case "chain":
1362
+ return this.validateChainHandler(toolName, handler);
1363
+ case "mcp":
1364
+ return this.validateMCPHandler(toolName, handler);
1365
+ default:
1366
+ console.warn("CustomMCP 工具使用了未知的处理器类型", {
1367
+ toolName,
1368
+ handlerType: (handler as HandlerConfig).type,
1369
+ });
1370
+ return false;
1371
+ }
1372
+ }
1373
+
1374
+ /**
1375
+ * 验证代理处理器配置
1376
+ */
1377
+ private validateProxyHandler(
1378
+ toolName: string,
1379
+ handler: ProxyHandlerConfig
1380
+ ): boolean {
1381
+ if (!handler.platform) {
1382
+ console.warn("CustomMCP 工具的 proxy 处理器缺少 platform 字段", {
1383
+ toolName,
1384
+ });
1385
+ return false;
1386
+ }
1387
+
1388
+ if (!["coze", "openai", "anthropic", "custom"].includes(handler.platform)) {
1389
+ console.warn("CustomMCP 工具的 proxy 处理器使用了不支持的平台", {
1390
+ toolName,
1391
+ platform: handler.platform,
1392
+ });
1393
+ return false;
1394
+ }
1395
+
1396
+ if (!handler.config || typeof handler.config !== "object") {
1397
+ console.warn("CustomMCP 工具的 proxy 处理器缺少 config 字段", {
1398
+ toolName,
1399
+ });
1400
+ return false;
1401
+ }
1402
+
1403
+ // Coze 平台特定验证
1404
+ if (handler.platform === "coze") {
1405
+ if (!handler.config.workflow_id && !handler.config.bot_id) {
1406
+ console.warn(
1407
+ "CustomMCP 工具的 Coze 处理器必须提供 workflow_id 或 bot_id",
1408
+ { toolName }
1409
+ );
1410
+ return false;
1411
+ }
1412
+ }
1413
+
1414
+ return true;
1415
+ }
1416
+
1417
+ /**
1418
+ * 验证 HTTP 处理器配置
1419
+ */
1420
+ private validateHttpHandler(
1421
+ toolName: string,
1422
+ handler: HttpHandlerConfig
1423
+ ): boolean {
1424
+ if (!handler.url || typeof handler.url !== "string") {
1425
+ console.warn("CustomMCP 工具的 http 处理器缺少有效的 url 字段", {
1426
+ toolName,
1427
+ });
1428
+ return false;
1429
+ }
1430
+
1431
+ try {
1432
+ new URL(handler.url);
1433
+ } catch {
1434
+ console.warn("CustomMCP 工具的 http 处理器 url 格式无效", {
1435
+ toolName,
1436
+ url: handler.url,
1437
+ });
1438
+ return false;
1439
+ }
1440
+
1441
+ if (
1442
+ handler.method &&
1443
+ !["GET", "POST", "PUT", "DELETE", "PATCH"].includes(handler.method)
1444
+ ) {
1445
+ console.warn("CustomMCP 工具的 http 处理器使用了不支持的 HTTP 方法", {
1446
+ toolName,
1447
+ method: handler.method,
1448
+ });
1449
+ return false;
1450
+ }
1451
+
1452
+ return true;
1453
+ }
1454
+
1455
+ /**
1456
+ * 验证函数处理器配置
1457
+ */
1458
+ private validateFunctionHandler(
1459
+ toolName: string,
1460
+ handler: FunctionHandlerConfig
1461
+ ): boolean {
1462
+ if (!handler.module || typeof handler.module !== "string") {
1463
+ console.warn("CustomMCP 工具的 function 处理器缺少有效的 module 字段", {
1464
+ toolName,
1465
+ });
1466
+ return false;
1467
+ }
1468
+
1469
+ if (!handler.function || typeof handler.function !== "string") {
1470
+ console.warn("CustomMCP 工具的 function 处理器缺少有效的 function 字段", {
1471
+ toolName,
1472
+ });
1473
+ return false;
1474
+ }
1475
+
1476
+ return true;
1477
+ }
1478
+
1479
+ /**
1480
+ * 验证脚本处理器配置
1481
+ */
1482
+ private validateScriptHandler(
1483
+ toolName: string,
1484
+ handler: ScriptHandlerConfig
1485
+ ): boolean {
1486
+ if (!handler.script || typeof handler.script !== "string") {
1487
+ console.warn("CustomMCP 工具的 script 处理器缺少有效的 script 字段", {
1488
+ toolName,
1489
+ });
1490
+ return false;
1491
+ }
1492
+
1493
+ if (
1494
+ handler.interpreter &&
1495
+ !["node", "python", "bash"].includes(handler.interpreter)
1496
+ ) {
1497
+ console.warn("CustomMCP 工具的 script 处理器使用了不支持的解释器", {
1498
+ toolName,
1499
+ interpreter: handler.interpreter,
1500
+ });
1501
+ return false;
1502
+ }
1503
+
1504
+ return true;
1505
+ }
1506
+
1507
+ /**
1508
+ * 验证链式处理器配置
1509
+ */
1510
+ private validateChainHandler(
1511
+ toolName: string,
1512
+ handler: ChainHandlerConfig
1513
+ ): boolean {
1514
+ if (
1515
+ !handler.tools ||
1516
+ !Array.isArray(handler.tools) ||
1517
+ handler.tools.length === 0
1518
+ ) {
1519
+ console.warn("CustomMCP 工具的 chain 处理器缺少有效的 tools 数组", {
1520
+ toolName,
1521
+ });
1522
+ return false;
1523
+ }
1524
+
1525
+ if (!["sequential", "parallel"].includes(handler.mode)) {
1526
+ console.warn("CustomMCP 工具的 chain 处理器使用了不支持的执行模式", {
1527
+ toolName,
1528
+ mode: handler.mode,
1529
+ });
1530
+ return false;
1531
+ }
1532
+
1533
+ if (!["stop", "continue", "retry"].includes(handler.error_handling)) {
1534
+ console.warn("CustomMCP 工具的 chain 处理器使用了不支持的错误处理策略", {
1535
+ toolName,
1536
+ errorHandling: handler.error_handling,
1537
+ });
1538
+ return false;
1539
+ }
1540
+
1541
+ return true;
1542
+ }
1543
+
1544
+ /**
1545
+ * 验证 MCP 处理器配置
1546
+ */
1547
+ private validateMCPHandler(
1548
+ toolName: string,
1549
+ handler: MCPHandlerConfig
1550
+ ): boolean {
1551
+ if (!handler.config || typeof handler.config !== "object") {
1552
+ console.warn("CustomMCP 工具的 mcp 处理器缺少 config 字段", { toolName });
1553
+ return false;
1554
+ }
1555
+
1556
+ if (
1557
+ !handler.config.serviceName ||
1558
+ typeof handler.config.serviceName !== "string"
1559
+ ) {
1560
+ console.warn("CustomMCP 工具的 mcp 处理器缺少有效的 serviceName", {
1561
+ toolName,
1562
+ });
1563
+ return false;
1564
+ }
1565
+
1566
+ if (
1567
+ !handler.config.toolName ||
1568
+ typeof handler.config.toolName !== "string"
1569
+ ) {
1570
+ console.warn("CustomMCP 工具的 mcp 处理器缺少有效的 toolName", {
1571
+ toolName,
1572
+ });
1573
+ return false;
1574
+ }
1575
+
1576
+ return true;
1577
+ }
1578
+
1579
+ /**
1580
+ * 检查是否配置了有效的 customMCP 工具
1581
+ */
1582
+ public hasValidCustomMCPTools(): boolean {
1583
+ try {
1584
+ const tools = this.getCustomMCPTools();
1585
+ if (tools.length === 0) {
1586
+ return false;
1587
+ }
1588
+
1589
+ return this.validateCustomMCPTools(tools);
1590
+ } catch (error) {
1591
+ console.error("检查 customMCP 工具配置时出错", { error });
1592
+ return false;
1593
+ }
1594
+ }
1595
+
1596
+ /**
1597
+ * 添加自定义 MCP 工具
1598
+ */
1599
+ public addCustomMCPTool(tool: CustomMCPTool): void {
1600
+ if (!tool || typeof tool !== "object") {
1601
+ throw new Error("工具配置不能为空");
1602
+ }
1603
+
1604
+ const config = this.getMutableConfig();
1605
+
1606
+ // 确保 customMCP 配置存在
1607
+ if (!config.customMCP) {
1608
+ config.customMCP = { tools: [] };
1609
+ }
1610
+
1611
+ // 检查工具名称是否已存在
1612
+ const existingTool = config.customMCP.tools.find(
1613
+ (t) => t.name === tool.name
1614
+ );
1615
+ if (existingTool) {
1616
+ throw new Error(`工具 "${tool.name}" 已存在`);
1617
+ }
1618
+
1619
+ // 验证工具配置
1620
+ if (!this.validateCustomMCPTools([tool])) {
1621
+ throw new Error("工具配置验证失败");
1622
+ }
1623
+
1624
+ // 添加工具
1625
+ config.customMCP.tools.unshift(tool);
1626
+ this.saveConfig(config);
1627
+
1628
+ console.log("成功添加自定义 MCP 工具", { toolName: tool.name });
1629
+ }
1630
+
1631
+ /**
1632
+ * 批量添加自定义 MCP 工具
1633
+ * @param tools 要添加的工具数组
1634
+ */
1635
+ public async addCustomMCPTools(tools: CustomMCPTool[]): Promise<void> {
1636
+ if (!Array.isArray(tools)) {
1637
+ throw new Error("工具配置必须是数组");
1638
+ }
1639
+
1640
+ if (tools.length === 0) {
1641
+ return; // 空数组,无需处理
1642
+ }
1643
+
1644
+ const config = this.getMutableConfig();
1645
+
1646
+ // 确保 customMCP 配置存在
1647
+ if (!config.customMCP) {
1648
+ config.customMCP = { tools: [] };
1649
+ }
1650
+
1651
+ // 添加新工具,避免重复
1652
+ const existingNames = new Set(
1653
+ config.customMCP.tools.map((tool) => tool.name)
1654
+ );
1655
+ const newTools = tools.filter((tool) => !existingNames.has(tool.name));
1656
+
1657
+ if (newTools.length > 0) {
1658
+ // 验证新工具配置
1659
+ if (!this.validateCustomMCPTools(newTools)) {
1660
+ throw new Error("工具配置验证失败");
1661
+ }
1662
+
1663
+ // 添加工具
1664
+ config.customMCP.tools.push(...newTools);
1665
+ this.saveConfig(config);
1666
+
1667
+ // 发射配置更新事件
1668
+ this.emitEvent("config:updated", {
1669
+ type: "customMCP",
1670
+ timestamp: new Date(),
1671
+ });
1672
+
1673
+ console.log("成功批量添加自定义 MCP 工具", {
1674
+ count: newTools.length,
1675
+ toolNames: newTools.map((t) => t.name),
1676
+ });
1677
+ }
1678
+ }
1679
+
1680
+ /**
1681
+ * 删除自定义 MCP 工具
1682
+ */
1683
+ public removeCustomMCPTool(toolName: string): void {
1684
+ if (!toolName || typeof toolName !== "string") {
1685
+ throw new Error("工具名称不能为空");
1686
+ }
1687
+
1688
+ const config = this.getMutableConfig();
1689
+
1690
+ if (!config.customMCP || !config.customMCP.tools) {
1691
+ throw new Error("未配置自定义 MCP 工具");
1692
+ }
1693
+
1694
+ const toolIndex = config.customMCP.tools.findIndex(
1695
+ (t) => t.name === toolName
1696
+ );
1697
+ if (toolIndex === -1) {
1698
+ throw new Error(`工具 "${toolName}" 不存在`);
1699
+ }
1700
+
1701
+ // 删除工具
1702
+ config.customMCP.tools.splice(toolIndex, 1);
1703
+ this.saveConfig(config);
1704
+
1705
+ console.log("成功删除自定义 MCP 工具", { toolName });
1706
+ }
1707
+
1708
+ /**
1709
+ * 更新单个自定义 MCP 工具配置
1710
+ * @param toolName 工具名称
1711
+ * @param updatedTool 更新后的工具配置
1712
+ */
1713
+ public updateCustomMCPTool(
1714
+ toolName: string,
1715
+ updatedTool: CustomMCPTool
1716
+ ): void {
1717
+ if (!toolName || typeof toolName !== "string") {
1718
+ throw new Error("工具名称不能为空");
1719
+ }
1720
+ if (!updatedTool || typeof updatedTool !== "object") {
1721
+ throw new Error("更新后的工具配置不能为空");
1722
+ }
1723
+
1724
+ const config = this.getMutableConfig();
1725
+
1726
+ if (!config.customMCP || !config.customMCP.tools) {
1727
+ throw new Error("未配置自定义 MCP 工具");
1728
+ }
1729
+
1730
+ const toolIndex = config.customMCP.tools.findIndex(
1731
+ (t) => t.name === toolName
1732
+ );
1733
+ if (toolIndex === -1) {
1734
+ throw new Error(`工具 "${toolName}" 不存在`);
1735
+ }
1736
+
1737
+ // 验证更新后的工具配置
1738
+ if (!this.validateCustomMCPTools([updatedTool])) {
1739
+ throw new Error("更新后的工具配置验证失败");
1740
+ }
1741
+
1742
+ // 更新工具配置
1743
+ config.customMCP.tools[toolIndex] = updatedTool;
1744
+ this.saveConfig(config);
1745
+
1746
+ console.log("成功更新自定义 MCP 工具", { toolName });
1747
+ }
1748
+
1749
+ /**
1750
+ * 更新自定义 MCP 工具配置
1751
+ */
1752
+ public updateCustomMCPTools(tools: CustomMCPTool[]): void {
1753
+ if (!Array.isArray(tools)) {
1754
+ throw new Error("工具配置必须是数组");
1755
+ }
1756
+
1757
+ // 验证工具配置
1758
+ if (!this.validateCustomMCPTools(tools)) {
1759
+ throw new Error("工具配置验证失败");
1760
+ }
1761
+
1762
+ const config = this.getMutableConfig();
1763
+
1764
+ // 确保 customMCP 配置存在
1765
+ if (!config.customMCP) {
1766
+ config.customMCP = { tools: [] };
1767
+ }
1768
+
1769
+ config.customMCP.tools = tools;
1770
+ this.saveConfig(config);
1771
+
1772
+ // 发射配置更新事件
1773
+ this.emitEvent("config:updated", {
1774
+ type: "customMCP",
1775
+ timestamp: new Date(),
1776
+ });
1777
+
1778
+ console.log("成功更新自定义 MCP 工具配置", { count: tools.length });
1779
+ }
1780
+
1781
+ /**
1782
+ * 获取 Web UI 配置
1783
+ */
1784
+ public getWebUIConfig(): Readonly<WebUIConfig> {
1785
+ const config = this.getConfig();
1786
+ return config.webUI || {};
1787
+ }
1788
+
1789
+ /**
1790
+ * 获取 Web UI 端口号
1791
+ */
1792
+ public getWebUIPort(): number {
1793
+ const webUIConfig = this.getWebUIConfig();
1794
+ return webUIConfig.port ?? 9999; // 默认端口 9999
1795
+ }
1796
+
1797
+ /**
1798
+ * 通知 Web 界面配置已更新
1799
+ * 如果 Web 服务器正在运行,通过 WebSocket 广播配置更新
1800
+ */
1801
+ private notifyConfigUpdate(config: AppConfig): void {
1802
+ try {
1803
+ // 检查是否有全局的 webServer 实例(当使用 --ui 参数启动时会设置)
1804
+ const webServer = (
1805
+ global as typeof global & { __webServer?: WebServerInstance }
1806
+ ).__webServer;
1807
+ if (webServer && typeof webServer.broadcastConfigUpdate === "function") {
1808
+ // 调用 webServer 的 broadcastConfigUpdate 方法来通知所有连接的客户端
1809
+ webServer.broadcastConfigUpdate(config);
1810
+ console.log("已通过 WebSocket 广播配置更新");
1811
+ }
1812
+ } catch (error) {
1813
+ // 静默处理错误,不影响配置保存的主要功能
1814
+ console.warn(
1815
+ "通知 Web 界面配置更新失败:",
1816
+ error instanceof Error ? error.message : String(error)
1817
+ );
1818
+ }
1819
+ }
1820
+
1821
+ /**
1822
+ * 更新 Web UI 配置
1823
+ */
1824
+ public updateWebUIConfig(webUIConfig: Partial<WebUIConfig>): void {
1825
+ const config = this.getMutableConfig();
1826
+
1827
+ // 确保 webUI 对象存在
1828
+ if (!config.webUI) {
1829
+ config.webUI = {};
1830
+ }
1831
+
1832
+ // 直接修改现有的 webUI 对象以保留注释
1833
+ Object.assign(config.webUI, webUIConfig);
1834
+ this.saveConfig(config);
1835
+
1836
+ // 发射配置更新事件
1837
+ this.emitEvent("config:updated", {
1838
+ type: "webui",
1839
+ timestamp: new Date(),
1840
+ });
1841
+ }
1842
+
1843
+ /**
1844
+ * 设置 Web UI 端口号
1845
+ */
1846
+ public setWebUIPort(port: number): void {
1847
+ if (!Number.isInteger(port) || port <= 0 || port > 65535) {
1848
+ throw new Error("端口号必须是 1-65535 之间的整数");
1849
+ }
1850
+ this.updateWebUIConfig({ port });
1851
+ }
1852
+
1853
+ public updatePlatformConfig(
1854
+ platformName: string,
1855
+ platformConfig: PlatformConfig
1856
+ ): void {
1857
+ const config = this.getMutableConfig();
1858
+ if (!config.platforms) {
1859
+ config.platforms = {};
1860
+ }
1861
+ config.platforms[platformName] = platformConfig;
1862
+ // 注意:Web UI 可能需要刷新才能看到更新后的数据
1863
+ this.saveConfig(config);
1864
+
1865
+ // 发射配置更新事件
1866
+ this.emitEvent("config:updated", {
1867
+ type: "platform",
1868
+ platformName,
1869
+ timestamp: new Date(),
1870
+ });
1871
+ }
1872
+
1873
+ /**
1874
+ * 获取扣子平台配置
1875
+ */
1876
+ public getCozePlatformConfig(): CozePlatformConfig | null {
1877
+ const config = this.getConfig();
1878
+ const cozeConfig = config.platforms?.coze;
1879
+
1880
+ if (!cozeConfig || !cozeConfig.token) {
1881
+ return null;
1882
+ }
1883
+
1884
+ return {
1885
+ token: cozeConfig.token,
1886
+ };
1887
+ }
1888
+
1889
+ /**
1890
+ * 获取扣子 API Token
1891
+ */
1892
+ public getCozeToken(): string | null {
1893
+ const cozeConfig = this.getCozePlatformConfig();
1894
+ return cozeConfig?.token || null;
1895
+ }
1896
+
1897
+ /**
1898
+ * 设置扣子平台配置
1899
+ */
1900
+ public setCozePlatformConfig(config: CozePlatformConfig): void {
1901
+ if (
1902
+ !config.token ||
1903
+ typeof config.token !== "string" ||
1904
+ config.token.trim() === ""
1905
+ ) {
1906
+ throw new Error("扣子 API Token 不能为空");
1907
+ }
1908
+
1909
+ this.updatePlatformConfig("coze", {
1910
+ token: config.token.trim(),
1911
+ });
1912
+ }
1913
+
1914
+ /**
1915
+ * 检查扣子平台配置是否有效
1916
+ */
1917
+ public isCozeConfigValid(): boolean {
1918
+ const cozeConfig = this.getCozePlatformConfig();
1919
+ return (
1920
+ cozeConfig !== null &&
1921
+ typeof cozeConfig.token === "string" &&
1922
+ cozeConfig.token.trim() !== ""
1923
+ );
1924
+ }
1925
+
1926
+ /**
1927
+ * 更新 mcpServerConfig 中的工具使用统计信息(内部实现)
1928
+ * @param serverName 服务名称
1929
+ * @param toolName 工具名称
1930
+ * @param callTime 调用时间(ISO 8601 格式)
1931
+ * @param incrementUsageCount 是否增加使用计数
1932
+ * @private
1933
+ */
1934
+ private async _updateMCPServerToolStats(
1935
+ serverName: string,
1936
+ toolName: string,
1937
+ callTime: string,
1938
+ incrementUsageCount = true
1939
+ ): Promise<void> {
1940
+ const config = this.getMutableConfig();
1941
+
1942
+ // 确保 mcpServerConfig 存在
1943
+ if (!config.mcpServerConfig) {
1944
+ config.mcpServerConfig = {};
1945
+ }
1946
+
1947
+ // 确保服务配置存在
1948
+ if (!config.mcpServerConfig[serverName]) {
1949
+ config.mcpServerConfig[serverName] = { tools: {} };
1950
+ }
1951
+
1952
+ // 确保工具配置存在
1953
+ if (!config.mcpServerConfig[serverName].tools[toolName]) {
1954
+ config.mcpServerConfig[serverName].tools[toolName] = {
1955
+ enable: true, // 默认启用
1956
+ };
1957
+ }
1958
+
1959
+ const toolConfig = config.mcpServerConfig[serverName].tools[toolName];
1960
+ const currentUsageCount = toolConfig.usageCount || 0;
1961
+ const currentLastUsedTime = toolConfig.lastUsedTime;
1962
+
1963
+ // 根据参数决定是否更新使用次数
1964
+ if (incrementUsageCount) {
1965
+ toolConfig.usageCount = currentUsageCount + 1;
1966
+ }
1967
+
1968
+ // 时间校验:只有新时间晚于现有时间才更新 lastUsedTime
1969
+ if (
1970
+ !currentLastUsedTime ||
1971
+ new Date(callTime) > new Date(currentLastUsedTime)
1972
+ ) {
1973
+ // 使用 dayjs 格式化时间为更易读的格式
1974
+ toolConfig.lastUsedTime = dayjs(callTime).format("YYYY-MM-DD HH:mm:ss");
1975
+ }
1976
+
1977
+ // 保存配置
1978
+ this.saveConfig(config);
1979
+ }
1980
+
1981
+ /**
1982
+ * 更新 customMCP 中的工具使用统计信息(服务名+工具名版本)
1983
+ * @param serverName 服务名称
1984
+ * @param toolName 工具名称
1985
+ * @param callTime 调用时间(ISO 8601 格式)
1986
+ * @private
1987
+ */
1988
+ private async updateCustomMCPToolStats(
1989
+ serverName: string,
1990
+ toolName: string,
1991
+ callTime: string
1992
+ ): Promise<void>;
1993
+
1994
+ /**
1995
+ * 更新 customMCP 中的工具使用统计信息(工具名版本)
1996
+ * @param toolName 工具名称(customMCP 工具名称)
1997
+ * @param callTime 调用时间(ISO 8601 格式)
1998
+ * @param incrementUsageCount 是否增加使用计数,默认为 true
1999
+ * @private
2000
+ */
2001
+ private async updateCustomMCPToolStats(
2002
+ toolName: string,
2003
+ callTime: string,
2004
+ incrementUsageCount?: boolean
2005
+ ): Promise<void>;
2006
+
2007
+ /**
2008
+ * 更新 customMCP 工具使用统计信息的实现
2009
+ * @private
2010
+ */
2011
+ private async updateCustomMCPToolStats(
2012
+ arg1: string,
2013
+ arg2: string,
2014
+ arg3?: string | boolean
2015
+ ): Promise<void> {
2016
+ try {
2017
+ let toolName: string;
2018
+ let callTime: string;
2019
+ let incrementUsageCount = true;
2020
+ let logPrefix: string;
2021
+
2022
+ // 判断参数类型来区分不同的重载
2023
+ if (typeof arg3 === "string") {
2024
+ // 三个字符串参数的情况:updateCustomMCPToolStats(serverName, toolName, callTime)
2025
+ const serverName = arg1;
2026
+ toolName = `${serverName}__${arg2}`;
2027
+ callTime = arg3;
2028
+ logPrefix = `${serverName}/${arg2}`;
2029
+ } else {
2030
+ // 两个或三个参数的情况:updateCustomMCPToolStats(toolName, callTime, incrementUsageCount?)
2031
+ toolName = arg1;
2032
+ callTime = arg2;
2033
+ incrementUsageCount = (arg3 as boolean) || true;
2034
+ logPrefix = toolName;
2035
+ }
2036
+
2037
+ const customTools = this.getCustomMCPTools();
2038
+ const toolIndex = customTools.findIndex((tool) => tool.name === toolName);
2039
+
2040
+ if (toolIndex === -1) {
2041
+ // 如果 customMCP 中没有对应的工具,跳过更新
2042
+ return;
2043
+ }
2044
+
2045
+ const updatedTools = [...customTools];
2046
+ const tool = updatedTools[toolIndex];
2047
+
2048
+ // 确保 stats 对象存在
2049
+ if (!tool.stats) {
2050
+ tool.stats = {};
2051
+ }
2052
+
2053
+ const currentUsageCount = tool.stats.usageCount || 0;
2054
+ const currentLastUsedTime = tool.stats.lastUsedTime;
2055
+
2056
+ // 根据参数决定是否更新使用次数
2057
+ if (incrementUsageCount) {
2058
+ tool.stats.usageCount = currentUsageCount + 1;
2059
+ }
2060
+
2061
+ // 时间校验:只有新时间晚于现有时间才更新 lastUsedTime
2062
+ if (
2063
+ !currentLastUsedTime ||
2064
+ new Date(callTime) > new Date(currentLastUsedTime)
2065
+ ) {
2066
+ tool.stats.lastUsedTime = dayjs(callTime).format("YYYY-MM-DD HH:mm:ss");
2067
+ }
2068
+
2069
+ // 保存更新后的工具配置
2070
+ await this.updateCustomMCPTools(updatedTools);
2071
+ } catch (error) {
2072
+ // 根据参数类型决定错误日志的前缀
2073
+ if (typeof arg3 === "string") {
2074
+ const serverName = arg1;
2075
+ const toolName = arg2;
2076
+ console.error("更新 customMCP 工具统计信息失败", {
2077
+ serverName,
2078
+ toolName,
2079
+ error,
2080
+ });
2081
+ } else {
2082
+ const toolName = arg1;
2083
+ console.error("更新 customMCP 工具统计信息失败", { toolName, error });
2084
+ }
2085
+ // customMCP 统计更新失败不应该影响主要流程
2086
+ }
2087
+ }
2088
+
2089
+ /**
2090
+ * 获取统计更新锁(确保同一工具的统计更新串行执行)
2091
+ * @param toolKey 工具键
2092
+ * @private
2093
+ */
2094
+ private async acquireStatsUpdateLock(toolKey: string): Promise<boolean> {
2095
+ if (this.statsUpdateLocks.has(toolKey)) {
2096
+ console.log("工具统计更新正在进行中,跳过本次更新", { toolKey });
2097
+ return false;
2098
+ }
2099
+
2100
+ const updatePromise = new Promise<void>((resolve) => {
2101
+ // 锁定逻辑在调用者中实现
2102
+ });
2103
+
2104
+ this.statsUpdateLocks.set(toolKey, updatePromise);
2105
+
2106
+ // 设置超时自动释放锁
2107
+ const timeout = setTimeout(() => {
2108
+ this.releaseStatsUpdateLock(toolKey);
2109
+ }, this.STATS_UPDATE_TIMEOUT);
2110
+
2111
+ this.statsUpdateLockTimeouts.set(toolKey, timeout);
2112
+
2113
+ return true;
2114
+ }
2115
+
2116
+ /**
2117
+ * 释放统计更新锁
2118
+ * @param toolKey 工具键
2119
+ * @private
2120
+ */
2121
+ private releaseStatsUpdateLock(toolKey: string): void {
2122
+ this.statsUpdateLocks.delete(toolKey);
2123
+
2124
+ const timeout = this.statsUpdateLockTimeouts.get(toolKey);
2125
+ if (timeout) {
2126
+ clearTimeout(timeout);
2127
+ this.statsUpdateLockTimeouts.delete(toolKey);
2128
+ }
2129
+
2130
+ console.log("已释放工具的统计更新锁", { toolKey });
2131
+ }
2132
+
2133
+ /**
2134
+ * 带并发控制的工具统计更新(CustomMCP 工具)
2135
+ * @param toolName 工具名称
2136
+ * @param incrementUsageCount 是否增加使用计数
2137
+ */
2138
+ public async updateToolUsageStatsWithLock(
2139
+ toolName: string,
2140
+ incrementUsageCount = true
2141
+ ): Promise<void> {
2142
+ const toolKey = `custommcp_${toolName}`;
2143
+
2144
+ if (!(await this.acquireStatsUpdateLock(toolKey))) {
2145
+ return; // 已有其他更新在进行
2146
+ }
2147
+
2148
+ try {
2149
+ await this.updateToolUsageStats(toolName, incrementUsageCount);
2150
+ console.log("工具统计更新完成", { toolName });
2151
+ } catch (error) {
2152
+ console.error("工具统计更新失败", { toolName, error });
2153
+ throw error;
2154
+ } finally {
2155
+ this.releaseStatsUpdateLock(toolKey);
2156
+ }
2157
+ }
2158
+
2159
+ /**
2160
+ * 带并发控制的工具统计更新(MCP 服务工具)
2161
+ * @param serviceName 服务名称
2162
+ * @param toolName 工具名称
2163
+ * @param callTime 调用时间
2164
+ * @param incrementUsageCount 是否增加使用计数
2165
+ */
2166
+ public async updateMCPServerToolStatsWithLock(
2167
+ serviceName: string,
2168
+ toolName: string,
2169
+ callTime: string,
2170
+ incrementUsageCount = true
2171
+ ): Promise<void> {
2172
+ const toolKey = `mcpserver_${serviceName}_${toolName}`;
2173
+
2174
+ if (!(await this.acquireStatsUpdateLock(toolKey))) {
2175
+ return; // 已有其他更新在进行
2176
+ }
2177
+
2178
+ try {
2179
+ await this.updateMCPServerToolStats(
2180
+ serviceName,
2181
+ toolName,
2182
+ callTime,
2183
+ incrementUsageCount
2184
+ );
2185
+ console.log("MCP 服务工具统计更新完成", { serviceName, toolName });
2186
+ } catch (error) {
2187
+ console.error("MCP 服务工具统计更新失败", {
2188
+ serviceName,
2189
+ toolName,
2190
+ error,
2191
+ });
2192
+ throw error;
2193
+ } finally {
2194
+ this.releaseStatsUpdateLock(toolKey);
2195
+ }
2196
+ }
2197
+
2198
+ /**
2199
+ * 清理所有统计更新锁(用于异常恢复)
2200
+ */
2201
+ public clearAllStatsUpdateLocks(): void {
2202
+ const lockCount = this.statsUpdateLocks.size;
2203
+ this.statsUpdateLocks.clear();
2204
+
2205
+ // 清理所有超时定时器
2206
+ for (const timeout of this.statsUpdateLockTimeouts.values()) {
2207
+ clearTimeout(timeout);
2208
+ }
2209
+ this.statsUpdateLockTimeouts.clear();
2210
+
2211
+ if (lockCount > 0) {
2212
+ console.log("已清理统计更新锁", { count: lockCount });
2213
+ }
2214
+ }
2215
+
2216
+ /**
2217
+ * 获取统计更新锁状态(用于调试和监控)
2218
+ */
2219
+ public getStatsUpdateLocks(): string[] {
2220
+ return Array.from(this.statsUpdateLocks.keys());
2221
+ }
2222
+
2223
+ /**
2224
+ * 获取工具调用日志配置
2225
+ */
2226
+ public getToolCallLogConfig(): Readonly<ToolCallLogConfig> {
2227
+ const config = this.getConfig();
2228
+ return config.toolCallLog || {};
2229
+ }
2230
+
2231
+ /**
2232
+ * 更新工具调用日志配置
2233
+ */
2234
+ public updateToolCallLogConfig(
2235
+ toolCallLogConfig: Partial<ToolCallLogConfig>
2236
+ ): void {
2237
+ const config = this.getMutableConfig();
2238
+
2239
+ // 确保 toolCallLog 对象存在
2240
+ if (!config.toolCallLog) {
2241
+ config.toolCallLog = {};
2242
+ }
2243
+
2244
+ // 直接修改现有的 toolCallLog 对象以保留注释
2245
+ Object.assign(config.toolCallLog, toolCallLogConfig);
2246
+ this.saveConfig(config);
2247
+ }
2248
+
2249
+ /**
2250
+ * 获取配置目录路径(与配置文件同级目录)
2251
+ */
2252
+ public getConfigDir(): string {
2253
+ // 配置文件路径 - 优先使用环境变量指定的目录,否则使用当前工作目录
2254
+ return process.env.XIAOZHI_CONFIG_DIR || process.cwd();
2255
+ }
2256
+ }
2257
+
2258
+ // 导出单例实例
2259
+ export const configManager = ConfigManager.getInstance();