@jadchene/mcp-gateway-service 0.11.3 → 0.12.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/dist/index.js CHANGED
@@ -1,4 +1,8 @@
1
1
  #!/usr/bin/env node
2
+ import { ConfigWebServer } from "./web-config/server.js";
3
+ import { parseWebArgs } from "./web-config/options.js";
4
+ import { validateGatewayConfig } from "./config.js";
5
+ import { dirname } from "node:path";
2
6
  import { existsSync } from "node:fs";
3
7
  import { resolve } from "node:path";
4
8
  import { ConfigLoader } from "./config.js";
@@ -45,6 +49,8 @@ class Application {
45
49
  * Stores the optional Streamable HTTP gateway server.
46
50
  */
47
51
  httpServer = null;
52
+ /** 独立的配置页面服务。 */
53
+ webServer;
48
54
  /**
49
55
  * Stores the file watcher used for config hot reload.
50
56
  */
@@ -62,20 +68,40 @@ class Application {
62
68
  if (!existsSync(this.configPath)) {
63
69
  throw new Error(`Config file was not found: ${this.configPath}`);
64
70
  }
65
- const startup = this.registry.initialize();
66
- this.engine.setStartupBarrier(startup);
67
- this.server.start();
68
- await startup;
69
- const serverConfig = this.cliOptions.server;
70
- this.registerSignals(Boolean(serverConfig));
71
- if (serverConfig) {
72
- this.httpServer = new StreamableHttpGatewayServer(serverConfig, this.engine, this.logger);
73
- await this.httpServer.start();
71
+ try {
72
+ const startup = this.registry.initialize();
73
+ this.engine.setStartupBarrier(startup);
74
+ this.server.start();
75
+ await startup;
76
+ const serverConfig = this.cliOptions.server;
77
+ this.registerSignals(Boolean(serverConfig));
78
+ if (serverConfig) {
79
+ this.httpServer = new StreamableHttpGatewayServer(serverConfig, this.engine, this.logger);
80
+ await this.httpServer.start();
81
+ }
82
+ this.webServer = new ConfigWebServer({
83
+ project: "gateway", configPath: this.configPath, args: process.argv.slice(2), defaultPort: 3100,
84
+ services: {
85
+ list: () => this.registry.listServiceStates(),
86
+ control: (id, action) => this.registry.controlService(id, action)
87
+ },
88
+ validate: raw => validateGatewayConfig(raw, dirname(this.configPath)), reload: () => this.registry.reloadStrict(),
89
+ startup: { mcpHttp: this.cliOptions.server ? { ...this.cliOptions.server, authToken: this.cliOptions.server.authToken ? "已配置(环境变量)" : "未配置" } : { enable: false }, source: "命令行 / 默认值" }
90
+ });
91
+ await this.webServer.startOptional();
92
+ this.watcher.start();
93
+ this.logger.info("gateway.started", {
94
+ configPath: this.configPath
95
+ });
96
+ }
97
+ catch (error) {
98
+ this.watcher.stop();
99
+ await this.webServer?.close();
100
+ await this.httpServer?.stop();
101
+ await this.server.stop();
102
+ await this.registry.dispose();
103
+ throw error;
74
104
  }
75
- this.watcher.start();
76
- this.logger.info("gateway.started", {
77
- configPath: this.configPath
78
- });
79
105
  }
80
106
  /**
81
107
  * Registers signal handlers for graceful shutdown.
@@ -88,6 +114,7 @@ class Application {
88
114
  this.shuttingDown = true;
89
115
  this.logger.info("gateway.stopping", { signal });
90
116
  this.watcher.stop();
117
+ await this.webServer?.close();
91
118
  await this.httpServer?.stop();
92
119
  await this.server.stop();
93
120
  await this.registry.dispose();
@@ -115,6 +142,7 @@ if (import.meta.main) {
115
142
  });
116
143
  }
117
144
  export function parseCliArgs(args) {
145
+ args = parseWebArgs(args).remaining;
118
146
  if (args.includes("--protocol-mode")) {
119
147
  throw new Error("--protocol-mode is no longer supported; protocol negotiation is automatic.");
120
148
  }
@@ -40,7 +40,7 @@ function createStandardTransport(command, args, cwd, env, logger, serviceId) {
40
40
  /**
41
41
  * Resolves a configured command into a directly spawnable executable on Windows.
42
42
  */
43
- export function resolveCommandSpec(command, args) {
43
+ function resolveCommandSpec(command, args) {
44
44
  if (process.platform !== "win32" || /[\\/]/.test(command) || /\.[A-Za-z0-9]+$/.test(command)) {
45
45
  return { command, args };
46
46
  }
@@ -19,6 +19,7 @@ export class SdkMcpClient {
19
19
  logger;
20
20
  transportFactory;
21
21
  client = null;
22
+ disposed = false;
22
23
  connecting = null;
23
24
  restartAttempts = 0;
24
25
  unavailableReason = null;
@@ -39,6 +40,10 @@ export class SdkMcpClient {
39
40
  get isUnavailable() {
40
41
  return this.unavailableReason !== null;
41
42
  }
43
+ /** 显示实际连接状态,连接关闭后立即变为 false。 */
44
+ get isConnected() { return this.client !== null; }
45
+ /** 仅由显式启动或恢复操作重新启用连接。 */
46
+ activate() { this.disposed = false; }
42
47
  /**
43
48
  * Returns the terminal unavailability reason.
44
49
  */
@@ -55,12 +60,16 @@ export class SdkMcpClient {
55
60
  * Checks whether this client can be reused after config reload.
56
61
  */
57
62
  matchesConfig(service) {
58
- return JSON.stringify(this.service) === JSON.stringify(service);
63
+ // 页面地址、名称及工具过滤由注册表处理,不应触发下游进程重启。
64
+ return JSON.stringify(this.service.transport) === JSON.stringify(service.transport)
65
+ && this.service.callTimeoutMs === service.callTimeoutMs;
59
66
  }
60
67
  /**
61
68
  * Establishes an SDK connection with the configured era negotiation policy.
62
69
  */
63
70
  async ensureConnected() {
71
+ if (this.disposed)
72
+ throw new Error(`Service '${this.key}' is stopped.`);
64
73
  if (this.client) {
65
74
  return;
66
75
  }
@@ -82,6 +91,8 @@ export class SdkMcpClient {
82
91
  * Closes the SDK client and clears lifecycle errors.
83
92
  */
84
93
  async dispose() {
94
+ this.disposed = true;
95
+ await this.connecting?.catch(() => undefined);
85
96
  this.restartAttempts = 0;
86
97
  this.unavailableReason = null;
87
98
  await this.disposeConnection();
@@ -198,6 +209,10 @@ export class SdkMcpClient {
198
209
  const transport = transportFactory();
199
210
  try {
200
211
  await client.connect(transport, { timeout: CONNECT_TIMEOUT_MS });
212
+ if (this.disposed) {
213
+ await client.close();
214
+ throw new Error(`Service '${this.key}' is stopped.`);
215
+ }
201
216
  this.client = client;
202
217
  this.logger.info("downstream.connected", {
203
218
  serviceId: this.key,
@@ -36,6 +36,58 @@ export class ServiceRegistry {
36
36
  */
37
37
  reloadPromise = Promise.resolve();
38
38
  managementPromise = Promise.resolve();
39
+ /** 用户停止状态跨配置热重载保留,Gateway 重启后重新按配置加载。 */
40
+ stopped = new Set();
41
+ /** 当前执行中的生命周期动作,用于页面状态和调用拦截。 */
42
+ transitions = new Map();
43
+ /** 返回页面所需的运行信息,不包含启动参数和凭据。 */
44
+ listServiceStates() {
45
+ return this.listServices().map(snapshot => {
46
+ const id = snapshot.config.serviceId;
47
+ const client = this.clients.get(id);
48
+ return {
49
+ serviceId: id,
50
+ status: this.transitions.get(id) ?? (this.stopped.has(id) ? "stopped"
51
+ : client?.isConnected ? "running" : "failed"),
52
+ lastError: snapshot.runtime.lastError ?? (!client?.isConnected && !this.stopped.has(id) && !this.transitions.has(id) ? "下游连接已关闭" : null),
53
+ lastConnectedAt: snapshot.runtime.lastConnectedAt,
54
+ toolCount: this.listTools(id).length
55
+ };
56
+ });
57
+ }
58
+ /** 串行控制已启用服务,停止操作不修改配置文件。 */
59
+ controlService(serviceId, action) {
60
+ const operation = this.reloadPromise.catch(() => undefined).then(async () => {
61
+ const snapshot = this.requireService(serviceId);
62
+ const current = this.clients.get(serviceId);
63
+ if (action === "start" && current?.isConnected && !this.stopped.has(serviceId))
64
+ return;
65
+ this.transitions.set(serviceId, action === "stop" ? "stopping" : "starting");
66
+ try {
67
+ this.stopped.add(serviceId);
68
+ await current?.dispose();
69
+ snapshot.runtime.available = false;
70
+ snapshot.runtime.lastError = null;
71
+ if (action === "stop")
72
+ return;
73
+ this.stopped.delete(serviceId);
74
+ const next = createClient(snapshot.config, this.logger);
75
+ this.clients.set(serviceId, next);
76
+ snapshot.metadata = await next.getMetadata();
77
+ this.markServiceAvailable(serviceId, next.restartCount);
78
+ }
79
+ catch (error) {
80
+ const message = error instanceof Error ? error.message : String(error);
81
+ this.markServiceUnavailable(serviceId, message, this.clients.get(serviceId)?.restartCount ?? 0);
82
+ throw error;
83
+ }
84
+ finally {
85
+ this.transitions.delete(serviceId);
86
+ }
87
+ });
88
+ this.reloadPromise = operation.catch(() => undefined);
89
+ return operation;
90
+ }
39
91
  /**
40
92
  * Creates a registry bound to one config file path.
41
93
  */
@@ -147,6 +199,9 @@ export class ServiceRegistry {
147
199
  */
148
200
  async callTool(serviceId, toolName, args, context = {}) {
149
201
  const snapshot = this.requireService(serviceId);
202
+ if (this.stopped.has(serviceId) || this.transitions.has(serviceId)) {
203
+ throw new Error(`Service '${serviceId}' is stopped or changing state.`);
204
+ }
150
205
  if (matchesAnyToolNamePattern(toolName, snapshot.config.disabledTools)) {
151
206
  throw new Error(`Tool '${toolName}' in service '${serviceId}' is disabled by gateway configuration.`);
152
207
  }
@@ -199,6 +254,14 @@ export class ServiceRegistry {
199
254
  * Reconnects one currently configured service and refreshes its metadata snapshot.
200
255
  */
201
256
  async reconnectService(serviceId) {
257
+ // 与配置重载共用队列,防止两个替换操作同时启动同一服务。
258
+ const operation = this.reloadPromise.catch(() => undefined)
259
+ .then(() => this.reconnectServiceOnce(serviceId));
260
+ this.reloadPromise = operation.then(() => undefined, () => undefined);
261
+ return operation;
262
+ }
263
+ /** 在注册表生命周期队列中执行一次重连。 */
264
+ async reconnectServiceOnce(serviceId) {
202
265
  const snapshot = this.requireService(serviceId);
203
266
  const previousRuntime = snapshot.runtime;
204
267
  const currentClient = this.clients.get(serviceId);
@@ -206,6 +269,10 @@ export class ServiceRegistry {
206
269
  throw new Error(`Service '${serviceId}' is unavailable.`);
207
270
  }
208
271
  const nextClient = createClient(snapshot.config, this.logger);
272
+ const restartProcess = snapshot.config.transport.type === "stdio";
273
+ // stdio 子进程可能持有 Web 端口等独占资源,必须先关闭旧实例。
274
+ if (restartProcess)
275
+ await currentClient.dispose();
209
276
  try {
210
277
  const metadata = await nextClient.getMetadata();
211
278
  snapshot.metadata = metadata;
@@ -216,6 +283,7 @@ export class ServiceRegistry {
216
283
  restartAttempts: nextClient.restartCount
217
284
  };
218
285
  this.clients.set(serviceId, nextClient);
286
+ this.stopped.delete(serviceId);
219
287
  await currentClient.dispose().catch(() => undefined);
220
288
  return {
221
289
  serviceId,
@@ -227,17 +295,28 @@ export class ServiceRegistry {
227
295
  catch (error) {
228
296
  await nextClient.dispose().catch(() => undefined);
229
297
  const message = error instanceof Error ? error.message : String(error);
298
+ let restored = false;
299
+ if (restartProcess) {
300
+ try {
301
+ currentClient.activate();
302
+ snapshot.metadata = await currentClient.getMetadata();
303
+ restored = true;
304
+ }
305
+ catch {
306
+ // 原配置也无法恢复时,保留明确的不可用状态。
307
+ }
308
+ }
230
309
  snapshot.runtime = {
231
- available: previousRuntime.available,
232
- lastError: `Reconnect failed; existing connection retained: ${message}`,
233
- lastConnectedAt: previousRuntime.lastConnectedAt,
310
+ available: restartProcess ? restored : previousRuntime.available,
311
+ lastError: `Reconnect failed; ${restartProcess ? (restored ? "previous configuration restored" : "previous configuration could not be restored") : "existing connection retained"}: ${message}`,
312
+ lastConnectedAt: restored ? new Date().toISOString() : previousRuntime.lastConnectedAt,
234
313
  restartAttempts: currentClient.restartCount
235
314
  };
236
315
  return {
237
316
  serviceId,
238
317
  action: "reconnect",
239
318
  enabled: true,
240
- available: previousRuntime.available
319
+ available: snapshot.runtime.available
241
320
  };
242
321
  }
243
322
  }
@@ -285,6 +364,11 @@ export class ServiceRegistry {
285
364
  ? reusedClient
286
365
  : createClient(service, this.logger);
287
366
  nextClients.set(service.serviceId, client);
367
+ if (reusedClient && reusedClient !== client
368
+ && this.snapshots.get(service.serviceId)?.config.transport.type === "stdio") {
369
+ // 配置切换前释放旧进程的监听端口,避免新旧实例争用同一端口。
370
+ await reusedClient.dispose();
371
+ }
288
372
  let metadata = {
289
373
  protocolVersion: null,
290
374
  protocolEra: null,
@@ -296,6 +380,9 @@ export class ServiceRegistry {
296
380
  let lastError = null;
297
381
  let lastConnectedAt = null;
298
382
  try {
383
+ if (this.stopped.has(service.serviceId)) {
384
+ return { config: service, metadata, runtime: { available: false, lastError: null, lastConnectedAt: null, restartAttempts: 0 } };
385
+ }
299
386
  metadata = await client.getMetadata();
300
387
  available = true;
301
388
  lastConnectedAt = new Date().toISOString();
package/dist/version.js CHANGED
@@ -4,5 +4,4 @@ import { fileURLToPath } from "node:url";
4
4
  const __dirname = dirname(fileURLToPath(import.meta.url));
5
5
  const packageJsonPath = resolve(__dirname, "../package.json");
6
6
  const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf8"));
7
- export const NAME = packageJson.name ?? "mcp-gateway-service";
8
7
  export const VERSION = packageJson.version ?? "0.0.0";
@@ -0,0 +1,71 @@
1
+ /** 检查 Web 文件配置,未设置时保持禁用。 */
2
+ export const validateWebConfig = (input) => {
3
+ if (input === undefined)
4
+ return {};
5
+ if (!input || typeof input !== "object" || Array.isArray(input))
6
+ throw new Error("web must be an object");
7
+ const value = input;
8
+ for (const key of Object.keys(value)) {
9
+ if (!["enabled", "host", "port"].includes(key))
10
+ throw new Error(`Unknown web.${key}`);
11
+ }
12
+ if (value.enabled !== undefined && typeof value.enabled !== "boolean")
13
+ throw new Error("web.enabled must be boolean");
14
+ if (value.port !== undefined &&
15
+ (!Number.isInteger(value.port) ||
16
+ Number(value.port) < 1 ||
17
+ Number(value.port) > 65535))
18
+ throw new Error("web.port must be 1–65535");
19
+ if (value.host !== undefined && value.host !== "127.0.0.1")
20
+ throw new Error("Web only supports 127.0.0.1; remote listening is disabled");
21
+ return value;
22
+ };
23
+ /** 分离 Web 参数,不改变原有 MCP 参数的含义。 */
24
+ export const parseWebArgs = (args) => {
25
+ const remaining = [];
26
+ const overrides = {};
27
+ const seen = new Set();
28
+ for (let index = 0; index < args.length; index++) {
29
+ const arg = args[index];
30
+ if (!["--web", "--no-web", "--web-host", "--web-port"].includes(arg)) {
31
+ remaining.push(arg);
32
+ continue;
33
+ }
34
+ if (seen.has(arg))
35
+ throw new Error(`Duplicate option ${arg}`);
36
+ seen.add(arg);
37
+ if (arg === "--web" || arg === "--no-web")
38
+ overrides.enabled = arg === "--web";
39
+ else {
40
+ const value = args[++index];
41
+ if (!value || value.startsWith("--"))
42
+ throw new Error(`${arg} requires a value`);
43
+ if (arg === "--web-host")
44
+ overrides.host = value;
45
+ else
46
+ overrides.port = Number(value);
47
+ }
48
+ }
49
+ if (seen.has("--web") && seen.has("--no-web"))
50
+ throw new Error("--web and --no-web cannot be combined");
51
+ validateWebConfig(overrides);
52
+ return { remaining, overrides };
53
+ };
54
+ /** 合并默认值、文件值和本次进程覆盖,并提供可展示的来源。 */
55
+ export const resolveWebOptions = (raw, args, port) => {
56
+ const file = validateWebConfig(raw);
57
+ const { overrides } = parseWebArgs(args);
58
+ const defaults = { enabled: false, host: "127.0.0.1", port };
59
+ const effective = { ...defaults, ...file, ...overrides, host: "127.0.0.1" };
60
+ const sources = Object.fromEntries(Object.keys(effective).map((key) => [
61
+ key,
62
+ key === "host"
63
+ ? "固定本机"
64
+ : Object.hasOwn(overrides, key)
65
+ ? "命令行"
66
+ : Object.hasOwn(file, key)
67
+ ? "配置文件"
68
+ : "默认值",
69
+ ]));
70
+ return { effective, sources };
71
+ };
@@ -0,0 +1,231 @@
1
+ const string = (label, required = false) => ({
2
+ type: "string",
3
+ label,
4
+ required,
5
+ });
6
+ const bool = (label, value = false) => ({
7
+ type: "boolean",
8
+ label,
9
+ default: value,
10
+ });
11
+ const number = (label, min, max, value) => ({ type: "number", label, min, max, default: value });
12
+ const object = (label, properties, required = false) => ({ type: "object", label, properties, required });
13
+ const array = (label, item, required = false) => ({
14
+ type: "array",
15
+ label,
16
+ item,
17
+ required,
18
+ });
19
+ const map = (label, item) => ({
20
+ type: "map",
21
+ label,
22
+ item,
23
+ });
24
+ const enumeration = (label, options) => ({
25
+ type: "string",
26
+ label,
27
+ options,
28
+ required: true,
29
+ });
30
+ const password = (label, required = false) => ({
31
+ ...string(label, required),
32
+ secret: true,
33
+ });
34
+ const strings = (label) => array(label, string("值"));
35
+ const port = (value) => number("端口", 1, 65535, value);
36
+ const timeout = (label = "连接超时(毫秒)") => number(label, 1, 2147483647);
37
+ const sessionFields = {
38
+ sessionIdleTimeoutMs: number("会话空闲超时(毫秒)", 100, 86400000, 1800000),
39
+ maxSessions: number("会话上限", 1, 1024, 32),
40
+ };
41
+ const access = {
42
+ enable: bool("启用", true),
43
+ codexAutoReview: bool("Codex 自动审批"),
44
+ dangerMode: bool("Full Access"),
45
+ };
46
+ const identity = {
47
+ host: string("主机", true),
48
+ port: port(22),
49
+ username: string("用户名", true),
50
+ password: password("密码"),
51
+ privateKeyPath: string("私钥文件路径"),
52
+ privateKey: { ...password("私钥内容"), multiline: true },
53
+ passphrase: password("私钥口令"),
54
+ strictHostKeyChecking: bool("校验主机密钥", true),
55
+ hostKeySha256: {
56
+ type: "string|array",
57
+ label: "主机 SHA-256 指纹",
58
+ item: string("指纹"),
59
+ },
60
+ };
61
+ const sqlConnection = {
62
+ host: string("主机", true),
63
+ port: port(),
64
+ databaseName: string("数据库名", true),
65
+ user: string("用户名", true),
66
+ password: password("密码", true),
67
+ connectTimeoutMs: timeout(),
68
+ ssl: {
69
+ type: "boolean|map",
70
+ label: "SSL",
71
+ item: { type: "any", label: "SSL 选项" },
72
+ },
73
+ };
74
+ /** 根据原有配置结构提供完整字段表;web 由只读启动区域展示。 */
75
+ export const configSchema = (project) => {
76
+ if (project === "gateway")
77
+ return object("Gateway 配置", {
78
+ logging: object("日志", {
79
+ enable: bool("启用文件日志"),
80
+ path: string("日志路径"),
81
+ maxBytes: number("单文件字节上限", 1024, Number.MAX_SAFE_INTEGER, 10485760),
82
+ }),
83
+ services: array("下游 MCP 服务", object("服务", {
84
+ serviceId: string("服务标识", true),
85
+ name: string("名称", true),
86
+ description: string("描述"),
87
+ enable: bool("启用", true),
88
+ webUrl: string("Web 配置地址"),
89
+ codexAutoReview: bool("Codex 自动审批"),
90
+ callTimeoutMs: number("调用超时(毫秒)", 1, 86400000),
91
+ confirmationRequiredTools: strings("需要确认的工具"),
92
+ disabledTools: strings("禁用工具"),
93
+ transport: { ...object("传输配置", {}, true), variants: {} },
94
+ }), true),
95
+ });
96
+ if (project === "ssh")
97
+ return object("SSH 配置", {
98
+ ...sessionFields,
99
+ logDir: string("日志目录"),
100
+ defaultTimeout: number("命令超时(毫秒)", 100, 3600000, 60000),
101
+ commandBlacklist: strings("命令黑名单正则"),
102
+ commandWhitelist: strings("命令白名单正则"),
103
+ allowedLocalRoots: strings("允许的本地目录"),
104
+ servers: {
105
+ ...map("SSH 主机", object("主机", {
106
+ ...identity,
107
+ ...access,
108
+ readOnly: bool("只读模式"),
109
+ desc: string("描述"),
110
+ allowedRemoteRoots: strings("允许删除的远程根目录"),
111
+ workingDirectories: map("工作目录", object("目录", {
112
+ path: string("路径", true),
113
+ desc: string("描述", true),
114
+ })),
115
+ proxyJump: object("跳板机", identity),
116
+ })),
117
+ required: true,
118
+ },
119
+ });
120
+ return object("Database 配置", {
121
+ ...sessionFields,
122
+ logging: object("日志", {
123
+ enabled: bool("启用文件日志"),
124
+ directory: string("日志目录"),
125
+ }),
126
+ query: object("查询设置", { timeoutMs: timeout("查询超时(毫秒)") }),
127
+ databases: array("数据源", object("数据库", {
128
+ key: string("标识", true),
129
+ type: enumeration("数据库类型", [
130
+ "mysql",
131
+ "oracle",
132
+ "postgresql",
133
+ "redis",
134
+ ]),
135
+ readonly: { ...bool("只读模式", true), required: true },
136
+ ...access,
137
+ connection: {
138
+ ...object("连接配置", {}, true),
139
+ variants: {
140
+ mysql: object("MySQL 连接", { ...sqlConnection, port: port(3306) }),
141
+ postgresql: object("PostgreSQL 连接", {
142
+ ...sqlConnection,
143
+ port: port(5432),
144
+ }),
145
+ oracle: object("Oracle 连接", {
146
+ host: string("主机", true),
147
+ port: port(1521),
148
+ serviceName: string("服务名"),
149
+ sid: string("SID"),
150
+ user: string("用户名", true),
151
+ password: password("密码", true),
152
+ connectTimeoutMs: timeout(),
153
+ clientMode: {
154
+ ...enumeration("客户端模式", ["thin", "thick"]),
155
+ required: false,
156
+ },
157
+ clientLibDir: string("客户端库目录"),
158
+ }),
159
+ redis: object("Redis 连接", {
160
+ url: password("连接 URL"),
161
+ host: string("主机"),
162
+ port: port(6379),
163
+ databaseName: number("数据库编号", 0, Number.MAX_SAFE_INTEGER),
164
+ username: string("用户名"),
165
+ password: password("密码"),
166
+ connectTimeoutMs: timeout(),
167
+ }),
168
+ },
169
+ },
170
+ }), true),
171
+ });
172
+ };
173
+ /** 传输类型从自身读取,连接类型从父级读取;无关字段仍留在草稿中。 */
174
+ export const resolveField = (field, value, parent) => {
175
+ if (field.label === "传输配置") {
176
+ const type = value?.type;
177
+ return object("传输配置", {
178
+ type: enumeration("传输类型", ["stdio", "http"]),
179
+ ...(type === "http"
180
+ ? {
181
+ url: string("MCP HTTP 地址", true),
182
+ headers: map("请求头", password("值")),
183
+ }
184
+ : {
185
+ command: string("启动命令", true),
186
+ args: strings("命令参数"),
187
+ cwd: string("工作目录"),
188
+ env: map("环境变量", password("值")),
189
+ inheritEnv: bool("继承全部环境变量"),
190
+ envAllowlist: strings("允许继承的环境变量"),
191
+ }),
192
+ }, true);
193
+ }
194
+ return field.variants?.[String(parent?.type)] ?? field;
195
+ };
196
+ /** 验证已知字段的类型,未知字段交给项目原有规则处理。 */
197
+ export const validateFormTypes = (value, raw, path = "", parent) => {
198
+ const field = resolveField(raw, value, parent);
199
+ if (value === undefined)
200
+ return;
201
+ if (field.type === "any")
202
+ return;
203
+ const type = Array.isArray(value)
204
+ ? "array"
205
+ : value !== null && typeof value === "object"
206
+ ? "object"
207
+ : typeof value;
208
+ if (!field.type
209
+ .split("|")
210
+ .map((item) => (item === "map" ? "object" : item))
211
+ .includes(type))
212
+ throw new Error(`${path || "配置"}: 应为 ${field.type}`);
213
+ if (field.options && !field.options.includes(String(value)))
214
+ throw new Error(`${path}: 可选值为 ${field.options.join(", ")}`);
215
+ if (type === "number" &&
216
+ (!Number.isInteger(value) ||
217
+ Number(value) < (field.min ?? -Infinity) ||
218
+ Number(value) > (field.max ?? Infinity)))
219
+ throw new Error(`${path}: 数值超出允许范围`);
220
+ if (type === "array")
221
+ value.forEach((item, index) => validateFormTypes(item, field.item ?? { type: "any" }, `${path}[${index}]`));
222
+ if (type === "object") {
223
+ for (const [key, child] of Object.entries(value)) {
224
+ const descriptor = field.properties && Object.hasOwn(field.properties, key)
225
+ ? field.properties[key]
226
+ : field.item;
227
+ if (descriptor)
228
+ validateFormTypes(child, descriptor, path ? `${path}.${key}` : key, value);
229
+ }
230
+ }
231
+ };