@jadchene/mcp-gateway-service 0.2.2 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -131,22 +131,31 @@ mcp-gateway-service -v
131
131
 
132
132
  ## Configuration
133
133
 
134
- The gateway currently supports `stdio` downstream transports only.
135
-
136
- A service is loaded only when `enable` is missing or set to `true`. If `enable` is set to `false`, the gateway skips that service entirely. During hot reload, disabling or removing a service also stops its existing downstream process if one is running.
137
-
138
- - `enable` is optional. When omitted, the gateway treats the service as enabled.
139
- - `cwd` is optional. When omitted, the gateway uses its current working directory.
140
- - `env` is optional.
141
- - `framing` is optional. When omitted, the gateway tries `line` first and then `content-length`.
134
+ The gateway currently supports `stdio` downstream transports only.
135
+
136
+ A service is loaded only when `enable` is missing or set to `true`. If `enable` is set to `false`, the gateway skips that service entirely. During hot reload, disabling or removing a service also stops its existing downstream process if one is running.
137
+
138
+ - `logging.enable` is optional and defaults to `false`.
139
+ - `logging.path` is required only when `logging.enable` is `true`.
140
+ - When enabled, the gateway writes newline-delimited JSON logs to the configured file and never writes operational logs to MCP `stdout` or `stderr`.
141
+ - Relative `logging.path` values are resolved from the config file directory.
142
+ - Logging config supports hot reload, so changing `logging.enable` or `logging.path` in the config file takes effect without restarting the gateway.
143
+ - `enable` is optional. When omitted, the gateway treats the service as enabled.
144
+ - `cwd` is optional. When omitted, the gateway uses its current working directory.
145
+ - `env` is optional.
146
+ - `framing` is optional. When omitted, the gateway tries `line` first and then `content-length`.
142
147
 
143
148
  ### Config shape
144
149
 
145
- ```json
146
- {
147
- "services": [
148
- {
149
- "serviceId": "demo-echo",
150
+ ```json
151
+ {
152
+ "logging": {
153
+ "enable": false,
154
+ "path": "./logs/mcp-gateway.log"
155
+ },
156
+ "services": [
157
+ {
158
+ "serviceId": "demo-echo",
150
159
  "enable": true,
151
160
  "name": "Demo Echo Service",
152
161
  "description": "Sample echo MCP service.",
@@ -165,30 +174,60 @@ A service is loaded only when `enable` is missing or set to `true`. If `enable`
165
174
 
166
175
  ## Public Gateway Tools
167
176
 
168
- The gateway exposes a fixed set of discovery and routing tools:
169
-
170
- - `gateway.listServices`
171
- - `gateway.getService`
172
- - `gateway.listTools`
173
- - `gateway.getToolSchema`
174
- - `gateway.callTool`
175
-
176
- ### Response design
177
-
178
- - `gateway.listServices` returns only `serviceId`, `description`, and `available`.
179
- - `gateway.listTools` returns only `name` and `description`.
180
- - `gateway.getToolSchema` returns only `inputSchema` and `outputSchema`.
181
- - `gateway.callTool` forwards the downstream MCP tool result directly without extra gateway metadata wrapping.
177
+ The gateway exposes a fixed set of discovery and routing tools:
178
+
179
+ - `gateway.listServices`
180
+ - `gateway.getService`
181
+ - `gateway.listTools`
182
+ - `gateway.getToolSchema`
183
+ - `gateway.manageService`
184
+ - `gateway.callTool`
185
+
186
+ ### Response design
187
+
188
+ - `gateway.listServices` returns only `serviceId`, `description`, and `available`.
189
+ - `gateway.listTools` returns only `name` and `description`.
190
+ - `gateway.getToolSchema` returns only `inputSchema` and `outputSchema`.
191
+ - `gateway.manageService` returns only `serviceId`, `action`, `enabled`, and `available`.
192
+ - `gateway.callTool` forwards the downstream MCP tool result directly without extra gateway metadata wrapping.
193
+
194
+ ### Default workflow vs diagnostics
195
+
196
+ - The default token-efficient workflow still uses four tools: `gateway.listServices`, `gateway.listTools`, `gateway.getToolSchema`, and `gateway.callTool`.
197
+ - `gateway.getService` is primarily for diagnostics, such as checking recent service errors, connection state, protocol version, or downstream server info.
198
+ - `gateway.manageService` is an operational tool for explicit service control, not part of the normal discovery flow.
199
+
200
+ ### `gateway.manageService`
201
+
202
+ Use `gateway.manageService` when you explicitly need to reconnect a service or persistently change its enabled state.
203
+
204
+ Input:
205
+
206
+ - `serviceId`: logical service identifier
207
+ - `action`: one of `reconnect`, `enable`, or `disable`
208
+
209
+ Action behavior:
210
+
211
+ - `reconnect`: immediately tries to start and reinitialize the specified downstream MCP again. Use this when a service previously failed because its dependency was not ready, such as an IDE that was not open yet.
212
+ - `enable`: writes `enable: true` to the config file for that service and triggers a reload.
213
+ - `disable`: writes `enable: false` to the config file for that service and triggers a reload.
214
+
215
+ Important notes:
216
+
217
+ - `enable` and `disable` are persisted to the JSON config file. They are not session-only toggles.
218
+ - `reconnect` does not modify the config file. It only retries the current service lifecycle.
182
219
 
183
220
  ## Recommended Client Workflow
184
221
 
185
222
  For the best token efficiency, the MCP client should cache discovery results instead of repeatedly querying the gateway:
186
223
 
187
- 1. Call `gateway.listServices` once at session start.
188
- 2. Call `gateway.listTools(serviceId)` only when a service is actually needed.
189
- 3. Call `gateway.getToolSchema(serviceId, toolName)` only before the first use of that tool.
190
- 4. Call `gateway.callTool(...)` for execution.
191
- 5. Refresh discovery data only when a call fails, the config changes, or the client explicitly wants a refresh.
224
+ 1. Call `gateway.listServices` once at session start.
225
+ 2. Call `gateway.listTools(serviceId)` only when a service is actually needed.
226
+ 3. Call `gateway.getToolSchema(serviceId, toolName)` only before the first use of that tool.
227
+ 4. Call `gateway.callTool(...)` for execution.
228
+ 5. Use `gateway.getService` only when diagnostics are explicitly needed.
229
+ 6. Use `gateway.manageService` only when a service must be reconnected or explicitly enabled/disabled.
230
+ 7. Refresh discovery data only when a call fails, the config changes, or the client explicitly wants a refresh.
192
231
 
193
232
  ## Skill Integration (Recommended)
194
233
 
@@ -259,6 +298,7 @@ args = ["--config", "./config.json"]
259
298
  - Repository-managed `config.json` and `config.example.json` are examples only.
260
299
  - Copy `config.example.json` to your own local `config.json` before running the gateway.
261
300
  - Keep real local configs and logs outside the repository.
301
+ - File logging is disabled by default so MCP startup stays quiet unless you explicitly enable it.
262
302
  - Downstream output schema is returned only when the downstream service exposes it.
263
303
  - Windows command resolution supports PowerShell shims such as `.ps1`-backed command aliases.
264
304
  - On Windows, the gateway prefers `pwsh` for `.ps1` shim resolution and execution, and automatically falls back to `powershell.exe` when `pwsh` is unavailable.
package/README_zh.md CHANGED
@@ -137,20 +137,29 @@ mcp-gateway-service -v
137
137
 
138
138
  ## 配置格式
139
139
 
140
- 当前只支持 `stdio` 类型的下游传输。
141
-
142
- 只有当 `enable` 未填写或显式为 `true` 时,服务才会被加载;如果 `enable` 为 `false`,网关会跳过该服务。热刷新时,如果某个服务被禁用或从配置中删除,网关也会停掉它当前已启动的下游进程。
143
-
144
- - `enable` 可选,不填时默认按启用处理
145
- - `cwd` 可选,不填时使用当前工作目录
146
- - `env` 可选
147
- - `framing` 可选,不填时先尝试 `line`,再尝试 `content-length`
148
-
149
- ```json
150
- {
151
- "services": [
152
- {
153
- "serviceId": "demo-echo",
140
+ 当前只支持 `stdio` 类型的下游传输。
141
+
142
+ 只有当 `enable` 未填写或显式为 `true` 时,服务才会被加载;如果 `enable` 为 `false`,网关会跳过该服务。热刷新时,如果某个服务被禁用或从配置中删除,网关也会停掉它当前已启动的下游进程。
143
+
144
+ - `logging.enable` 可选,默认是 `false`
145
+ - 只有当 `logging.enable` 为 `true` 时,`logging.path` 才是必填
146
+ - 启用后,网关会把换行分隔的 JSON 日志写入指定文件,不再把运行日志写到 MCP 的 `stdout` 或 `stderr`
147
+ - 相对 `logging.path` 会按配置文件所在目录解析
148
+ - 日志配置支持热更新,直接修改 `logging.enable` 或 `logging.path` 并保存即可生效,无需重启网关
149
+ - `enable` 可选,不填时默认按启用处理
150
+ - `cwd` 可选,不填时使用当前工作目录
151
+ - `env` 可选
152
+ - `framing` 可选,不填时先尝试 `line`,再尝试 `content-length`
153
+
154
+ ```json
155
+ {
156
+ "logging": {
157
+ "enable": false,
158
+ "path": "./logs/mcp-gateway.log"
159
+ },
160
+ "services": [
161
+ {
162
+ "serviceId": "demo-echo",
154
163
  "enable": true,
155
164
  "name": "Demo Echo Service",
156
165
  "description": "Sample echo MCP service.",
@@ -169,28 +178,58 @@ mcp-gateway-service -v
169
178
 
170
179
  ## 对外网关工具
171
180
 
172
- - `gateway.listServices`
173
- - `gateway.getService`
174
- - `gateway.listTools`
175
- - `gateway.getToolSchema`
176
- - `gateway.callTool`
177
-
178
- ### 返回结构约定
179
-
180
- - `gateway.listServices` 只返回 `serviceId`、`description`、`available`
181
- - `gateway.listTools` 只返回 `name`、`description`
182
- - `gateway.getToolSchema` 只返回 `inputSchema`、`outputSchema`
183
- - `gateway.callTool` 直接返回下游 MCP 的结果,不再额外包一层网关元数据
181
+ - `gateway.listServices`
182
+ - `gateway.getService`
183
+ - `gateway.listTools`
184
+ - `gateway.getToolSchema`
185
+ - `gateway.manageService`
186
+ - `gateway.callTool`
187
+
188
+ ### 返回结构约定
189
+
190
+ - `gateway.listServices` 只返回 `serviceId`、`description`、`available`
191
+ - `gateway.listTools` 只返回 `name`、`description`
192
+ - `gateway.getToolSchema` 只返回 `inputSchema`、`outputSchema`
193
+ - `gateway.manageService` 只返回 `serviceId`、`action`、`enabled`、`available`
194
+ - `gateway.callTool` 直接返回下游 MCP 的结果,不再额外包一层网关元数据
195
+
196
+ ### 默认流程与诊断的区别
197
+
198
+ - 默认的节省 token 工作流仍然只依赖 4 个工具:`gateway.listServices`、`gateway.listTools`、`gateway.getToolSchema`、`gateway.callTool`
199
+ - `gateway.getService` 主要用于诊断,例如查看最近错误、连接状态、协议版本、下游服务信息
200
+ - `gateway.manageService` 是显式运维控制工具,不属于日常 discovery 流程
201
+
202
+ ### `gateway.manageService`
203
+
204
+ 当你明确需要重新拉起某个服务,或者持久化修改某个服务的启用状态时,使用 `gateway.manageService`。
205
+
206
+ 输入参数:
207
+
208
+ - `serviceId`:逻辑服务标识
209
+ - `action`:只能是 `reconnect`、`enable`、`disable`
210
+
211
+ 动作语义:
212
+
213
+ - `reconnect`:立即重新尝试启动并重新初始化指定下游 MCP。适合处理“之前因为依赖没准备好而启动失败”的场景,比如当时 IDE 没开,后来打开后再次尝试拉起 IDE MCP。
214
+ - `enable`:把该服务在配置文件中的 `enable` 写成 `true`,然后触发 reload。
215
+ - `disable`:把该服务在配置文件中的 `enable` 写成 `false`,然后触发 reload。
216
+
217
+ 注意:
218
+
219
+ - `enable` 和 `disable` 会持久化写入 JSON 配置文件,不是只在当前会话里生效。
220
+ - `reconnect` 不会修改配置文件,只会重新尝试当前服务生命周期。
184
221
 
185
222
  ## 推荐调用流程
186
223
 
187
224
  为了尽量节省 token,推荐由客户端缓存发现结果,而不是每次都重新调用网关:
188
225
 
189
- 1. 会话开始时调用一次 `gateway.listServices`
190
- 2. 真正需要某个服务时,再调用 `gateway.listTools(serviceId)`
191
- 3. 第一次调用某个工具前,再调用 `gateway.getToolSchema(serviceId, toolName)`
192
- 4. 执行时调用 `gateway.callTool(...)`
193
- 5. 只有在调用失败、配置变更、或明确需要刷新时才重新发现
226
+ 1. 会话开始时调用一次 `gateway.listServices`
227
+ 2. 真正需要某个服务时,再调用 `gateway.listTools(serviceId)`
228
+ 3. 第一次调用某个工具前,再调用 `gateway.getToolSchema(serviceId, toolName)`
229
+ 4. 执行时调用 `gateway.callTool(...)`
230
+ 5. 只有在明确需要诊断时才调用 `gateway.getService`
231
+ 6. 只有在需要重新拉起服务或显式启用/停用服务时才调用 `gateway.manageService`
232
+ 7. 只有在调用失败、配置变更、或明确需要刷新时才重新发现
194
233
 
195
234
  ## Skill 集成(推荐)
196
235
 
@@ -261,6 +300,7 @@ args = ["--config", "./config.json"]
261
300
  - 仓库只保留 `config.example.json` 作为示例
262
301
  - 运行前请自行复制一份本地 `config.json`
263
302
  - 真实本地配置和日志建议放在仓库外
303
+ - 默认关闭文件日志,避免 MCP 启动阶段产生额外标准流输出
264
304
  - 只有下游服务自己暴露了 `outputSchema` 时,网关才会返回它
265
305
  - Windows 下支持解析 PowerShell shim 命令,例如实际落到 `.ps1` 的全局命令
266
306
  - 在 Windows 上,网关会优先使用 `pwsh` 解析和执行 `.ps1` shim;如果机器上没有 `pwsh`,会自动回退到 `powershell.exe`
@@ -1,7 +1,11 @@
1
- {
2
- "services": [
3
- {
4
- "serviceId": "demo-echo",
1
+ {
2
+ "logging": {
3
+ "enable": false,
4
+ "path": "./logs/mcp-gateway.log"
5
+ },
6
+ "services": [
7
+ {
8
+ "serviceId": "demo-echo",
5
9
  "enable": true,
6
10
  "name": "Demo Echo Service",
7
11
  "description": "Sample echo MCP service.",
@@ -15,4 +19,4 @@
15
19
  }
16
20
  }
17
21
  ]
18
- }
22
+ }
package/dist/config.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { readFile } from "node:fs/promises";
2
- import { resolve } from "node:path";
2
+ import { dirname, resolve } from "node:path";
3
3
  /**
4
4
  * Provides config loading and validation for the gateway service pool definition.
5
5
  */
@@ -11,13 +11,13 @@ export class ConfigLoader {
11
11
  const absolutePath = resolve(configPath);
12
12
  const rawText = await readFile(absolutePath, "utf8");
13
13
  const parsed = JSON.parse(rawText);
14
- return validateGatewayConfig(parsed);
14
+ return validateGatewayConfig(parsed, dirname(absolutePath));
15
15
  }
16
16
  }
17
17
  /**
18
18
  * Validates the top-level config object and normalizes optional fields.
19
19
  */
20
- export function validateGatewayConfig(input) {
20
+ export function validateGatewayConfig(input, baseDir = process.cwd()) {
21
21
  if (!isRecord(input)) {
22
22
  throw new Error("The gateway config must be a JSON object.");
23
23
  }
@@ -33,9 +33,39 @@ export function validateGatewayConfig(input) {
33
33
  seenServiceIds.add(service.serviceId);
34
34
  }
35
35
  return {
36
+ logging: validateLoggingConfig(input.logging, baseDir),
36
37
  services: services.filter((service) => service.enable)
37
38
  };
38
39
  }
40
+ /**
41
+ * Validates the optional logging config and resolves the log path.
42
+ */
43
+ function validateLoggingConfig(input, baseDir) {
44
+ if (input === undefined) {
45
+ return {
46
+ enable: false,
47
+ path: null
48
+ };
49
+ }
50
+ if (!isRecord(input)) {
51
+ throw new Error("The 'logging' field must be a JSON object when present.");
52
+ }
53
+ const enable = optionalBoolean(input.enable, "logging.enable") ?? false;
54
+ const path = optionalString(input.path, "logging.path");
55
+ if (!enable) {
56
+ return {
57
+ enable: false,
58
+ path: path ? resolve(baseDir, path) : null
59
+ };
60
+ }
61
+ if (!path || path.trim() === "") {
62
+ throw new Error("The 'logging.path' field must be a non-empty string when logging is enabled.");
63
+ }
64
+ return {
65
+ enable: true,
66
+ path: resolve(baseDir, path)
67
+ };
68
+ }
39
69
  /**
40
70
  * Validates one logical service definition.
41
71
  */
@@ -111,6 +111,8 @@ export class GatewayServer {
111
111
  return this.listTools(args);
112
112
  case "gateway.getToolSchema":
113
113
  return this.getToolSchema(args);
114
+ case "gateway.manageService":
115
+ return this.manageService(args);
114
116
  case "gateway.callTool":
115
117
  return this.callDownstreamTool(args);
116
118
  default:
@@ -174,6 +176,20 @@ export class GatewayServer {
174
176
  const call = await this.registry.callTool(serviceId, toolName, toolArgs);
175
177
  return call.result;
176
178
  }
179
+ /**
180
+ * Applies one compact service management action.
181
+ */
182
+ async manageService(args) {
183
+ const serviceId = requireString(args.serviceId, "The 'serviceId' argument must be a string.");
184
+ const action = requireServiceAction(args.action);
185
+ const result = await this.registry.manageService(serviceId, action);
186
+ return successContent({
187
+ serviceId: result.serviceId,
188
+ action: result.action,
189
+ enabled: result.enabled,
190
+ available: result.available
191
+ });
192
+ }
177
193
  /**
178
194
  * Builds the MCP initialize result advertised by the gateway.
179
195
  */
@@ -187,7 +203,7 @@ export class GatewayServer {
187
203
  },
188
204
  serverInfo: {
189
205
  name: "mcp-gateway",
190
- version: "0.2.2"
206
+ version: "0.3.3"
191
207
  }
192
208
  };
193
209
  }
@@ -228,6 +244,18 @@ function buildGatewayTools() {
228
244
  toolName: stringSchema("Downstream tool name.")
229
245
  })
230
246
  },
247
+ {
248
+ name: "gateway.manageService",
249
+ description: "Reconnects one service or updates its enabled state with a compact action.",
250
+ inputSchema: objectSchema(["serviceId", "action"], {
251
+ serviceId: stringSchema("Logical service identifier."),
252
+ action: {
253
+ type: "string",
254
+ description: "Management action applied to the service.",
255
+ enum: ["reconnect", "enable", "disable"]
256
+ }
257
+ })
258
+ },
231
259
  {
232
260
  name: "gateway.callTool",
233
261
  description: "Calls one downstream tool through the gateway service pool.",
@@ -304,6 +332,15 @@ function requireString(input, message) {
304
332
  }
305
333
  return input;
306
334
  }
335
+ /**
336
+ * Ensures the service management action is supported.
337
+ */
338
+ function requireServiceAction(input) {
339
+ if (input === "reconnect" || input === "enable" || input === "disable") {
340
+ return input;
341
+ }
342
+ throw new Error("The 'action' argument must be one of 'reconnect', 'enable', or 'disable'.");
343
+ }
307
344
  function isJsonRpcRequest(message) {
308
345
  return "id" in message && "method" in message && typeof message.method === "string";
309
346
  }
package/dist/logger.js CHANGED
@@ -1,35 +1,74 @@
1
+ import { mkdirSync, appendFileSync } from "node:fs";
2
+ import { dirname, resolve } from "node:path";
1
3
  /**
2
- * Provides a minimal structured logger that writes newline-delimited JSON to stderr.
4
+ * Provides a minimal structured logger that appends newline-delimited JSON to a file.
3
5
  */
4
6
  export class Logger {
5
7
  /**
6
- * Logs one structured event.
8
+ * Stores the current effective logging config.
9
+ */
10
+ config = {
11
+ enable: false,
12
+ path: null
13
+ };
14
+ /**
15
+ * Updates the effective logging config at runtime.
16
+ */
17
+ configure(config) {
18
+ this.config = {
19
+ enable: config.enable,
20
+ path: config.path ? resolve(config.path) : null
21
+ };
22
+ if (!this.config.enable || !this.config.path) {
23
+ return;
24
+ }
25
+ try {
26
+ mkdirSync(dirname(this.config.path), { recursive: true });
27
+ }
28
+ catch {
29
+ /**
30
+ * Ignores directory creation failures so logging never blocks MCP traffic.
31
+ */
32
+ }
33
+ }
34
+ /**
35
+ * Logs one structured info event.
7
36
  */
8
37
  info(event, details = {}) {
9
38
  this.write("info", event, details);
10
39
  }
11
40
  /**
12
- * Logs one warning event.
41
+ * Logs one structured warning event.
13
42
  */
14
43
  warn(event, details = {}) {
15
44
  this.write("warn", event, details);
16
45
  }
17
46
  /**
18
- * Logs one error event.
47
+ * Logs one structured error event.
19
48
  */
20
49
  error(event, details = {}) {
21
50
  this.write("error", event, details);
22
51
  }
23
52
  /**
24
- * Serializes a log entry to stderr without polluting stdout-based MCP traffic.
53
+ * Serializes one log entry to the configured file without touching MCP stdio streams.
25
54
  */
26
55
  write(level, event, details) {
56
+ if (!this.config.enable || !this.config.path) {
57
+ return;
58
+ }
27
59
  const payload = {
28
60
  timestamp: new Date().toISOString(),
29
61
  level,
30
62
  event,
31
63
  ...details
32
64
  };
33
- process.stderr.write(`${JSON.stringify(payload)}\n`);
65
+ try {
66
+ appendFileSync(this.config.path, `${JSON.stringify(payload)}\n`, "utf8");
67
+ }
68
+ catch {
69
+ /**
70
+ * Ignores append failures so the gateway stays usable even if logging breaks.
71
+ */
72
+ }
34
73
  }
35
74
  }
@@ -310,7 +310,7 @@ export class StdioMcpClient {
310
310
  },
311
311
  clientInfo: {
312
312
  name: "mcp-gateway",
313
- version: "0.2.2"
313
+ version: "0.3.3"
314
314
  }
315
315
  });
316
316
  if (isRecord(result)) {
@@ -1,3 +1,4 @@
1
+ import { readFile, writeFile } from "node:fs/promises";
1
2
  import { resolve } from "node:path";
2
3
  import { StdioMcpClient } from "./mcp/client.js";
3
4
  /**
@@ -19,7 +20,13 @@ export class ServiceRegistry {
19
20
  /**
20
21
  * Stores the last valid config snapshot.
21
22
  */
22
- currentConfig = { services: [] };
23
+ currentConfig = {
24
+ logging: {
25
+ enable: false,
26
+ path: null
27
+ },
28
+ services: []
29
+ };
23
30
  /**
24
31
  * Stores the current immutable runtime view used by request handlers.
25
32
  */
@@ -54,6 +61,7 @@ export class ServiceRegistry {
54
61
  const absolutePath = resolve(this.configPath);
55
62
  this.logger.info("config.reload.started", { configPath: absolutePath });
56
63
  const nextConfig = await this.configLoader.load(absolutePath);
64
+ this.logger.configure(nextConfig.logging);
57
65
  const nextSnapshots = new Map();
58
66
  const nextClients = new Map();
59
67
  try {
@@ -140,6 +148,21 @@ export class ServiceRegistry {
140
148
  throw error;
141
149
  }
142
150
  }
151
+ /**
152
+ * Manages one service runtime or persisted enable flag through a compact action interface.
153
+ */
154
+ async manageService(serviceId, action) {
155
+ switch (action) {
156
+ case "reconnect":
157
+ return this.reconnectService(serviceId);
158
+ case "enable":
159
+ return this.setServiceEnabled(serviceId, true);
160
+ case "disable":
161
+ return this.setServiceEnabled(serviceId, false);
162
+ default:
163
+ throw new Error(`Unsupported service action '${action}'.`);
164
+ }
165
+ }
143
166
  /**
144
167
  * Disposes all downstream clients during shutdown.
145
168
  */
@@ -147,6 +170,74 @@ export class ServiceRegistry {
147
170
  await disposeClientMap(this.clients);
148
171
  this.clients.clear();
149
172
  }
173
+ /**
174
+ * Reconnects one currently configured service and refreshes its metadata snapshot.
175
+ */
176
+ async reconnectService(serviceId) {
177
+ const snapshot = this.requireService(serviceId);
178
+ const currentClient = this.clients.get(serviceId);
179
+ if (!currentClient) {
180
+ throw new Error(`Service '${serviceId}' is unavailable.`);
181
+ }
182
+ const nextClient = new StdioMcpClient(snapshot.config, this.logger);
183
+ try {
184
+ await currentClient.dispose().catch(() => undefined);
185
+ const metadata = await nextClient.getMetadata();
186
+ snapshot.metadata = metadata;
187
+ snapshot.runtime = {
188
+ available: true,
189
+ lastError: null,
190
+ lastConnectedAt: new Date().toISOString(),
191
+ restartAttempts: nextClient.restartCount
192
+ };
193
+ this.clients.set(serviceId, nextClient);
194
+ return {
195
+ serviceId,
196
+ action: "reconnect",
197
+ enabled: true,
198
+ available: true
199
+ };
200
+ }
201
+ catch (error) {
202
+ await nextClient.dispose().catch(() => undefined);
203
+ const message = error instanceof Error ? error.message : String(error);
204
+ snapshot.runtime = {
205
+ available: false,
206
+ lastError: message,
207
+ lastConnectedAt: snapshot.runtime.lastConnectedAt,
208
+ restartAttempts: currentClient.restartCount
209
+ };
210
+ this.clients.set(serviceId, currentClient);
211
+ return {
212
+ serviceId,
213
+ action: "reconnect",
214
+ enabled: true,
215
+ available: false
216
+ };
217
+ }
218
+ }
219
+ /**
220
+ * Persists the service enable flag to the config file and reloads the registry.
221
+ */
222
+ async setServiceEnabled(serviceId, enabled) {
223
+ const rawConfig = await readRawConfig(this.configPath);
224
+ if (!Array.isArray(rawConfig.services)) {
225
+ throw new Error("The 'services' field must be an array.");
226
+ }
227
+ const service = rawConfig.services.find((candidate) => isRecord(candidate) && candidate.serviceId === serviceId);
228
+ if (!service || !isRecord(service)) {
229
+ throw new Error(`Unknown service '${serviceId}'.`);
230
+ }
231
+ service.enable = enabled;
232
+ await writeFile(resolve(this.configPath), `${JSON.stringify(rawConfig, null, 2)}\n`, "utf8");
233
+ await this.reload();
234
+ return {
235
+ serviceId,
236
+ action: enabled ? "enable" : "disable",
237
+ enabled,
238
+ available: enabled ? (this.getService(serviceId)?.runtime.available ?? false) : false
239
+ };
240
+ }
150
241
  /**
151
242
  * Builds one runtime snapshot and initializes required metadata.
152
243
  */
@@ -248,3 +339,20 @@ async function disposeRemovedClients(previous, next) {
248
339
  }
249
340
  await Promise.all(removed.map((client) => client.dispose().catch(() => undefined)));
250
341
  }
342
+ /**
343
+ * Loads the raw config document for management edits that must preserve disabled services.
344
+ */
345
+ async function readRawConfig(configPath) {
346
+ const rawText = await readFile(resolve(configPath), "utf8");
347
+ const parsed = JSON.parse(rawText);
348
+ if (!isRecord(parsed)) {
349
+ throw new Error("The gateway config must be a JSON object.");
350
+ }
351
+ return parsed;
352
+ }
353
+ /**
354
+ * Checks whether a value is a plain record.
355
+ */
356
+ function isRecord(input) {
357
+ return typeof input === "object" && input !== null && !Array.isArray(input);
358
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jadchene/mcp-gateway-service",
3
- "version": "0.2.2",
3
+ "version": "0.3.3",
4
4
  "description": "A token-efficient MCP gateway that provides one unified entry point for multiple downstream MCP services.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -11,7 +11,7 @@ Operate downstream MCP services through the gateway's fixed, token-efficient dis
11
11
 
12
12
  - **Discovery First**: Never guess a `serviceId` or downstream `toolName`. Discover them through the gateway.
13
13
  - **Token Efficiency**: Do not enumerate every service and every tool unless the task genuinely needs it.
14
- - **Schema Before First Call**: Before the first call to an unfamiliar downstream tool, fetch its schema.
14
+ - **Schema Before Unclear Arguments**: If the tool arguments are not fully certain, fetch the schema before calling the tool. Do not guess argument names, shapes, or confirmation fields.
15
15
  - **Cache Mentally Per Session**: Reuse known service lists, tool lists, and schemas within the current session instead of asking again without reason.
16
16
  - **Compression Recovery Gate**: After any context compression event, re-read `AGENTS.md` and this `SKILL.md` before continuing.
17
17
 
@@ -19,7 +19,7 @@ Operate downstream MCP services through the gateway's fixed, token-efficient dis
19
19
 
20
20
  1. Call `gateway.listServices` once to find the right downstream service.
21
21
  2. Call `gateway.listTools(serviceId)` only for the selected service.
22
- 3. Call `gateway.getToolSchema(serviceId, toolName)` only before the first use of that tool, or when arguments are unclear.
22
+ 3. Call `gateway.getToolSchema(serviceId, toolName)` before the first use of that tool, or any time the arguments are not fully certain.
23
23
  4. Call `gateway.callTool(serviceId, toolName, arguments)` for execution.
24
24
  5. Re-discover only when a call fails, service availability changes, or the task clearly requires fresh metadata.
25
25
 
@@ -28,6 +28,15 @@ Operate downstream MCP services through the gateway's fixed, token-efficient dis
28
28
  - Treat `gateway.getService` as a diagnostic tool, not part of the default workflow.
29
29
  - Use it only when the user explicitly asks to inspect service health, connection state, protocol details, or recent service errors.
30
30
  - Do not call it during normal task execution when the four-tool flow is sufficient.
31
+ - Treat `gateway.manageService` as an explicit service-control tool, not part of the default workflow.
32
+ - Use `gateway.manageService({ serviceId, action: "reconnect" })` only when the user explicitly wants to retry starting a failed service after its dependency becomes ready.
33
+ - Use `gateway.manageService({ serviceId, action: "enable" | "disable" })` only when the user explicitly wants to persistently change that service's enabled state in the config file.
34
+
35
+ ## Strict Argument Rule
36
+
37
+ - If a tool has any non-trivial arguments, optional flags, confirmation fields, enum values, or write-safety fields, call `gateway.getToolSchema` before execution unless the exact argument contract is already confirmed in the current session.
38
+ - Do not rely on tool descriptions alone when the argument shape could affect correctness or safety.
39
+ - This is especially important for write tools, confirmation-based tools, and tools with nested argument objects.
31
40
 
32
41
  ## Response Shape Expectations
33
42
 
@@ -52,7 +61,7 @@ Operate downstream MCP services through the gateway's fixed, token-efficient dis
52
61
  - `gateway.getToolSchema({ serviceId: "selected-service", toolName: "selected-tool" })`
53
62
  - `gateway.callTool({ serviceId: "selected-service", toolName: "selected-tool", arguments: {...} })`
54
63
 
55
- - Need to inspect an unfamiliar tool before first use:
64
+ - Need to inspect an unfamiliar tool before first use, or any tool whose arguments are not fully certain:
56
65
  - `gateway.getToolSchema({ serviceId: "selected-service", toolName: "selected-tool" })`
57
66
  - build arguments strictly from `inputSchema`
58
67
  - call the tool only after the schema is understood
@@ -61,6 +70,7 @@ Operate downstream MCP services through the gateway's fixed, token-efficient dis
61
70
 
62
71
  - **Never** flatten all downstream tools into your own notes unless the task explicitly needs a full inventory.
63
72
  - **Never** invent arguments for a tool when the schema can be queried cheaply.
73
+ - **Never** skip `gateway.getToolSchema` when argument names or fields are unclear.
64
74
  - **Never** assume a service is available without checking recent gateway discovery results when availability matters.
65
75
 
66
76
  ## Practical Guidance
@@ -68,3 +78,4 @@ Operate downstream MCP services through the gateway's fixed, token-efficient dis
68
78
  - Choose `serviceId` by task domain and service description instead of assuming a fixed service naming scheme.
69
79
  - Prefer the smallest discovery step that can answer the question.
70
80
  - If a downstream tool fails with a validation error, fetch or re-check its schema before retrying.
81
+ - If there is any doubt about required parameters, confirmation tokens, or argument structure, fetch the schema first instead of guessing.