@jadchene/mcp-gateway-service 0.7.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -17,6 +17,7 @@ The project uses the official TypeScript SDK v2 and requires Node.js 24 or later
17
17
  - Connect the agent once, then add or remove downstream services in the gateway config.
18
18
  - Find tools by name or description and load schemas only when required.
19
19
  - Use stdio and Streamable HTTP services through the same interface.
20
+ - Require user confirmation for selected tool-name patterns, or hide and block matching tools entirely.
20
21
  - Reload config changes without restarting the gateway.
21
22
 
22
23
  ## Quick Start
@@ -100,6 +101,8 @@ claude mcp add --transport http gateway http://127.0.0.1:3000/mcp
100
101
  | `--auth-token-env <name>` | Environment variable containing the HTTP bearer token. | `MCP_GATEWAY_AUTH_TOKEN` |
101
102
  | `--http-admin-tools` | Exposes `gateway_manage_service` over authenticated HTTP. | Disabled |
102
103
  | `--max-concurrent-requests <n>` | Bounds in-flight HTTP requests. | `64` |
104
+ | `--max-request-body-bytes <n>` | Rejects HTTP request bodies above this byte limit; maximum configurable value is 64 MiB. | `16777216` (16 MiB) |
105
+ | `--max-legacy-sessions <n>` | Bounds retained stateful legacy HTTP sessions. | `256` |
103
106
  | `--version`, `-v` | Prints the installed version. | — |
104
107
 
105
108
  Stdio remains available when `--http` is enabled.
@@ -116,6 +119,8 @@ Stdio remains available when `--http` is enabled.
116
119
  {
117
120
  "serviceId": "local-tools",
118
121
  "name": "Local Tools",
122
+ "confirmationRequiredTools": ["delete_*", "deploy_?"],
123
+ "disabledTools": ["internal_*", "legacy_tool"],
119
124
  "transport": {
120
125
  "type": "stdio",
121
126
  "command": "your-mcp-service",
@@ -142,6 +147,8 @@ Stdio remains available when `--http` is enabled.
142
147
  | `description` | Optional service description. |
143
148
  | `enable` | Optional; defaults to `true`. |
144
149
  | `callTimeoutMs` | Optional downstream tool-call timeout; defaults to 120 seconds. |
150
+ | `confirmationRequiredTools` | Optional unique array of case-sensitive full-name glob patterns. `*` matches zero or more characters and `?` matches one character. The gateway asks the upstream user for form elicitation confirmation before calling a matching tool. |
151
+ | `disabledTools` | Optional unique array using the same glob syntax. Matching tools are hidden from tool listing and schema lookup, and calls are rejected before reaching the downstream service. |
145
152
  | `transport.type` | `stdio` or `http`. |
146
153
  | `transport.command` | Required command for a stdio service. |
147
154
  | `transport.args` | Optional command arguments for a stdio service. |
@@ -170,7 +177,9 @@ The config file is watched for changes. Invalid updates are rejected and the las
170
177
 
171
178
  The usual flow is `gateway_list_services` → `gateway_list_tools` → `gateway_get_tool_schema` when needed → `gateway_call_tool`. Pass `{}` to `gateway_call_tool` when the downstream tool has no arguments.
172
179
 
173
- Calls keep the downstream tool's original side effects and confirmation rules. An uncertain `gateway_call_tool` failure is never replayed automatically. Enabling or disabling a service with `gateway_manage_service` atomically updates the config file.
180
+ Calls keep the downstream tool's original side effects and confirmation rules. Tools matching `confirmationRequiredTools` are never invoked until the current MCP session reviews the exact service, tool, and arguments and answers `yes` to the form elicitation; sessions without form elicitation support receive an error. A `no`, decline, or cancel returns an explicit rejection without invoking the downstream tool. An uncertain `gateway_call_tool` failure is never replayed automatically. Enabling or disabling a service with `gateway_manage_service` atomically updates the config file.
181
+
182
+ `disabledTools` takes precedence over `confirmationRequiredTools` when both match. A disabled tool is hidden and rejected immediately without asking for confirmation.
174
183
 
175
184
  Agents with Skills support can use the included [MCP Gateway Skill](./skills/mcp-gateway/SKILL.md) for the discovery and calling workflow.
176
185
 
package/README_zh.md CHANGED
@@ -17,6 +17,7 @@ MCP Gateway 把多个 MCP 服务收拢到一个入口。Agent 连接网关后只
17
17
  - Agent 只需接入一次,后续增减下游服务只改网关配置。
18
18
  - 可以按名称或描述查找工具,需要时再读取 schema。
19
19
  - Stdio 和 Streamable HTTP 服务使用同一套调用方式。
20
+ - 可按工具名模式要求用户确认,或隐藏并禁止调用指定工具。
20
21
  - 修改配置文件后自动重载,不必重启网关。
21
22
 
22
23
  ## 快速开始
@@ -100,6 +101,8 @@ claude mcp add --transport http gateway http://127.0.0.1:3000/mcp
100
101
  | `--auth-token-env <名称>` | 保存 HTTP Bearer Token 的环境变量名。 | `MCP_GATEWAY_AUTH_TOKEN` |
101
102
  | `--http-admin-tools` | 在已认证 HTTP 入口暴露 `gateway_manage_service`。 | 不启用 |
102
103
  | `--max-concurrent-requests <数量>` | HTTP 并发请求上限。 | `64` |
104
+ | `--max-request-body-bytes <字节数>` | HTTP 请求体字节上限,最大可配置为 64 MiB,超限返回 `413`。 | `16777216`(16 MiB) |
105
+ | `--max-legacy-sessions <数量>` | 有状态旧版 HTTP 会话的保留上限。 | `256` |
103
106
  | `--version`、`-v` | 输出已安装版本。 | — |
104
107
 
105
108
  启用 `--http` 后,stdio 入口仍然可用。
@@ -116,6 +119,8 @@ claude mcp add --transport http gateway http://127.0.0.1:3000/mcp
116
119
  {
117
120
  "serviceId": "local-tools",
118
121
  "name": "Local Tools",
122
+ "confirmationRequiredTools": ["delete_*", "deploy_?"],
123
+ "disabledTools": ["internal_*", "legacy_tool"],
119
124
  "transport": {
120
125
  "type": "stdio",
121
126
  "command": "your-mcp-service",
@@ -142,6 +147,8 @@ claude mcp add --transport http gateway http://127.0.0.1:3000/mcp
142
147
  | `description` | 可选,服务说明。 |
143
148
  | `enable` | 可选,默认为 `true`。 |
144
149
  | `callTimeoutMs` | 可选,下游工具调用超时;默认 120 秒。 |
150
+ | `confirmationRequiredTools` | 可选,填写区分大小写的完整工具名 glob 模式;`*` 匹配零个或多个字符,`?` 匹配一个字符。数组项必须唯一且非空,网关在调用匹配的工具前会向上游用户发起表单 elicitation。 |
151
+ | `disabledTools` | 可选,使用相同 glob 语法。匹配的工具不会出现在工具列表和 schema 查询中,调用也会在到达下游服务前被拒绝。 |
145
152
  | `transport.type` | `stdio` 或 `http`。 |
146
153
  | `transport.command` | stdio 服务必填,启动命令。 |
147
154
  | `transport.args` | stdio 服务的可选命令参数。 |
@@ -170,7 +177,9 @@ claude mcp add --transport http gateway http://127.0.0.1:3000/mcp
170
177
 
171
178
  通常按 `gateway_list_services` → `gateway_list_tools` → 按需调用 `gateway_get_tool_schema` → `gateway_call_tool` 的顺序使用。下游工具没有参数时,`gateway_call_tool` 的 `arguments` 传 `{}`。
172
179
 
173
- 工具调用会保留下游工具原有的副作用和确认规则。状态不确定的 `gateway_call_tool` 失败不会自动重放。通过 `gateway_manage_service` 启用或禁用服务会原子更新配置文件。
180
+ 工具调用会保留下游工具原有的副作用和确认规则。匹配 `confirmationRequiredTools` 模式的工具会展示实际服务、工具和完整参数,只有当前 MCP 会话在表单 elicitation 中选择 `yes` 后才会调用;会话不支持表单 elicitation,或用户选择 `no`、拒绝、取消时,网关会返回明确的拒绝结果且不会调用下游工具。状态不确定的 `gateway_call_tool` 失败不会自动重放。通过 `gateway_manage_service` 启用或禁用服务会原子更新配置文件。
181
+
182
+ 当一个工具同时匹配 `disabledTools` 和 `confirmationRequiredTools` 时,`disabledTools` 优先:工具会被隐藏并直接拒绝,不会发起确认。
174
183
 
175
184
  支持 Skills 的 Agent 可以使用仓库内置的 [MCP Gateway Skill](./skills/mcp-gateway/SKILL.md) 完成工具发现和调用。
176
185
 
@@ -11,6 +11,12 @@
11
11
  "name": "Demo Echo Service",
12
12
  "description": "Sample echo MCP service.",
13
13
  "callTimeoutMs": 120000,
14
+ "confirmationRequiredTools": [
15
+ "echo*"
16
+ ],
17
+ "disabledTools": [
18
+ "echo_debug*"
19
+ ],
14
20
  "transport": {
15
21
  "type": "stdio",
16
22
  "command": "node",
package/dist/config.js CHANGED
@@ -88,13 +88,17 @@ function validateServiceConfig(input) {
88
88
  const name = requireNonEmptyString(input.name, `service '${serviceId}' name`);
89
89
  const description = optionalString(input.description, `service '${serviceId}' description`);
90
90
  const callTimeoutMs = optionalInteger(input.callTimeoutMs, `service '${serviceId}' callTimeoutMs`, 1, 24 * 60 * 60 * 1000);
91
+ const confirmationRequiredTools = optionalUniqueStringArray(input.confirmationRequiredTools, `service '${serviceId}' confirmationRequiredTools`);
92
+ const disabledTools = optionalUniqueStringArray(input.disabledTools, `service '${serviceId}' disabledTools`);
91
93
  return {
92
94
  serviceId,
93
95
  enable,
94
96
  name,
95
97
  description,
96
98
  transport: validateTransportConfig(serviceId, input.transport),
97
- ...(callTimeoutMs === undefined ? {} : { callTimeoutMs })
99
+ ...(callTimeoutMs === undefined ? {} : { callTimeoutMs }),
100
+ ...(confirmationRequiredTools === undefined ? {} : { confirmationRequiredTools }),
101
+ ...(disabledTools === undefined ? {} : { disabledTools })
98
102
  };
99
103
  }
100
104
  /**
@@ -1,3 +1,5 @@
1
+ import { ToolConfirmationInterceptor } from "./mcp/tool-confirmation.js";
2
+ import { matchesAnyToolNamePattern } from "./tool-name-pattern.js";
1
3
  /**
2
4
  * Handles MCP JSON-RPC requests independently of the outer transport.
3
5
  */
@@ -10,6 +12,10 @@ export class McpGatewayEngine {
10
12
  * Stores the startup barrier that must resolve before gateway tools can use the registry.
11
13
  */
12
14
  startupBarrier = Promise.resolve();
15
+ /**
16
+ * Stores pending and approved confirmation continuation state.
17
+ */
18
+ toolConfirmation = new ToolConfirmationInterceptor();
13
19
  /**
14
20
  * Creates the transport-neutral gateway engine.
15
21
  */
@@ -113,8 +119,19 @@ export class McpGatewayEngine {
113
119
  const serviceId = requireString(args.serviceId, "The 'serviceId' argument must be a string.");
114
120
  const toolName = requireString(args.toolName, "The 'toolName' argument must be a string.");
115
121
  const toolArgs = toObject(args.arguments, "The 'arguments' field must be an object.");
116
- const call = await this.registry.callTool(serviceId, toolName, toolArgs, context);
117
- return call.result;
122
+ const snapshot = this.registry.getService(serviceId);
123
+ const invoke = async (callContext) => {
124
+ const call = await this.registry.callTool(serviceId, toolName, toolArgs, callContext);
125
+ return call.result;
126
+ };
127
+ if (matchesAnyToolNamePattern(toolName, snapshot?.config.disabledTools)) {
128
+ throw new Error(`Tool '${toolName}' in service '${serviceId}' is disabled by gateway configuration.`);
129
+ }
130
+ if (this.toolConfirmation.handlesState(context.requestState)
131
+ || matchesAnyToolNamePattern(toolName, snapshot?.config.confirmationRequiredTools)) {
132
+ return this.toolConfirmation.execute(serviceId, toolName, toolArgs, context, invoke);
133
+ }
134
+ return invoke(context);
118
135
  }
119
136
  /**
120
137
  * Applies one compact service management action.
@@ -5,6 +5,7 @@ import { hostHeaderValidation, originValidation, toNodeHandler } from "@modelcon
5
5
  import { createGatewayMcpServer } from "./mcp/server.js";
6
6
  const LEGACY_SESSION_IDLE_TIMEOUT_MS = 30 * 60 * 1_000;
7
7
  const LEGACY_SESSION_SWEEP_INTERVAL_MS = 60 * 1_000;
8
+ const DEFAULT_MAX_REQUEST_BODY_BYTES = 16 * 1024 * 1024;
8
9
  /**
9
10
  * Exposes the gateway through SDK v2 Streamable HTTP.
10
11
  */
@@ -14,6 +15,7 @@ export class StreamableHttpGatewayServer {
14
15
  logger;
15
16
  handler;
16
17
  legacySessions = new Map();
18
+ legacySessionsInitializing = 0;
17
19
  legacySessionSweepTimer = null;
18
20
  server = null;
19
21
  /**
@@ -22,7 +24,10 @@ export class StreamableHttpGatewayServer {
22
24
  get url() {
23
25
  const address = this.server?.address();
24
26
  const port = typeof address === "object" && address ? address.port : this.config.port;
25
- return `http://${this.config.host}:${port}${this.config.path}`;
27
+ const host = this.config.host.includes(":") && !this.config.host.startsWith("[")
28
+ ? `[${this.config.host}]`
29
+ : this.config.host;
30
+ return `http://${host}:${port}${this.config.path}`;
26
31
  }
27
32
  /**
28
33
  * Creates an SDK HTTP handler that automatically serves both standard protocol revisions.
@@ -62,6 +67,7 @@ export class StreamableHttpGatewayServer {
62
67
  onerror: (error) => this.logger.error("gateway.http_adapter_error", { message: error.message })
63
68
  });
64
69
  const maxConcurrentRequests = this.config.maxConcurrentRequests ?? 64;
70
+ const maxRequestBodyBytes = this.config.maxRequestBodyBytes ?? DEFAULT_MAX_REQUEST_BODY_BYTES;
65
71
  let activeRequests = 0;
66
72
  this.server = http.createServer((request, response) => {
67
73
  const pathname = new URL(request.url ?? "/", "http://localhost").pathname;
@@ -90,7 +96,7 @@ export class StreamableHttpGatewayServer {
90
96
  };
91
97
  response.once("finish", release);
92
98
  response.once("close", release);
93
- void handleMcp(request, response);
99
+ void handleBoundedRequest(request, response, maxRequestBodyBytes, handleMcp, this.logger);
94
100
  });
95
101
  await new Promise((resolveListen, rejectListen) => {
96
102
  this.server?.once("error", rejectListen);
@@ -150,6 +156,18 @@ export class StreamableHttpGatewayServer {
150
156
  * Creates a stateful 2025 transport for an initialize request.
151
157
  */
152
158
  async handleLegacyInitialization(request) {
159
+ const maxLegacySessions = this.config.maxLegacySessions ?? 256;
160
+ if (this.legacySessions.size + this.legacySessionsInitializing >= maxLegacySessions) {
161
+ return Response.json({
162
+ jsonrpc: "2.0",
163
+ error: {
164
+ code: -32000,
165
+ message: "Legacy session capacity reached"
166
+ },
167
+ id: null
168
+ }, { status: 503, headers: { "Retry-After": "1" } });
169
+ }
170
+ this.legacySessionsInitializing += 1;
153
171
  let session;
154
172
  const transport = new WebStandardStreamableHTTPServerTransport({
155
173
  sessionIdGenerator: randomUUID,
@@ -164,8 +182,8 @@ export class StreamableHttpGatewayServer {
164
182
  includeAdminTools: this.config.enableAdminTools ?? false
165
183
  });
166
184
  session = { server, transport, lastAccessedAt: Date.now() };
167
- await server.connect(transport);
168
185
  try {
186
+ await server.connect(transport);
169
187
  const response = await transport.handleRequest(request);
170
188
  if (!transport.sessionId) {
171
189
  await server.close().catch(() => undefined);
@@ -179,6 +197,9 @@ export class StreamableHttpGatewayServer {
179
197
  await server.close().catch(() => undefined);
180
198
  throw error;
181
199
  }
200
+ finally {
201
+ this.legacySessionsInitializing -= 1;
202
+ }
182
203
  }
183
204
  /**
184
205
  * Releases abandoned legacy sessions without touching active modern requests.
@@ -193,6 +214,85 @@ export class StreamableHttpGatewayServer {
193
214
  }
194
215
  }
195
216
  }
217
+ /**
218
+ * Reads a JSON request body with a byte limit before handing it to the SDK.
219
+ * Supplying the parsed body prevents the SDK Node adapter from buffering the
220
+ * same unbounded stream a second time.
221
+ */
222
+ async function handleBoundedRequest(request, response, maxBytes, handleMcp, logger) {
223
+ try {
224
+ const body = await readBoundedJsonBody(request, maxBytes);
225
+ if (body === NO_BODY) {
226
+ await handleMcp(request, response);
227
+ }
228
+ else {
229
+ await handleMcp(request, response, body);
230
+ }
231
+ }
232
+ catch (error) {
233
+ if (response.headersSent || response.destroyed) {
234
+ return;
235
+ }
236
+ const bodyError = error instanceof HttpBodyError
237
+ ? error
238
+ : new HttpBodyError(400, "Invalid JSON request body.");
239
+ logger.warn("gateway.http_body_rejected", {
240
+ status: bodyError.status,
241
+ message: bodyError.message
242
+ });
243
+ response.writeHead(bodyError.status, {
244
+ "Content-Type": "application/json",
245
+ "Connection": "close"
246
+ }).end(JSON.stringify({
247
+ jsonrpc: "2.0",
248
+ error: { code: -32700, message: bodyError.message },
249
+ id: null
250
+ }));
251
+ }
252
+ }
253
+ const NO_BODY = Symbol("no-http-body");
254
+ async function readBoundedJsonBody(request, maxBytes) {
255
+ const contentEncoding = request.headers["content-encoding"];
256
+ if (contentEncoding && contentEncoding !== "identity") {
257
+ throw new HttpBodyError(415, "Compressed HTTP request bodies are not supported.");
258
+ }
259
+ const declaredLength = request.headers["content-length"];
260
+ if (declaredLength !== undefined) {
261
+ const normalized = Array.isArray(declaredLength) ? declaredLength[0] : declaredLength;
262
+ if (!/^\d+$/.test(normalized)) {
263
+ throw new HttpBodyError(400, "Invalid Content-Length header.");
264
+ }
265
+ if (Number(normalized) > maxBytes) {
266
+ throw new HttpBodyError(413, `HTTP request body exceeds the ${maxBytes}-byte limit.`);
267
+ }
268
+ }
269
+ const chunks = [];
270
+ let totalBytes = 0;
271
+ for await (const chunk of request) {
272
+ const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
273
+ totalBytes += bytes.length;
274
+ if (totalBytes > maxBytes) {
275
+ throw new HttpBodyError(413, `HTTP request body exceeds the ${maxBytes}-byte limit.`);
276
+ }
277
+ chunks.push(bytes);
278
+ }
279
+ if (totalBytes === 0) {
280
+ return NO_BODY;
281
+ }
282
+ try {
283
+ return JSON.parse(Buffer.concat(chunks, totalBytes).toString("utf8"));
284
+ }
285
+ catch {
286
+ throw new HttpBodyError(400, "Invalid JSON request body.");
287
+ }
288
+ }
289
+ class HttpBodyError extends Error {
290
+ status;
291
+ constructor(status, message) {
292
+ super(message);
293
+ this.status = status;
294
+ }
295
+ }
196
296
  /**
197
297
  * Returns the standard status for a missing or expired MCP session.
198
298
  */
package/dist/index.js CHANGED
@@ -126,8 +126,11 @@ export function parseCliArgs(args) {
126
126
  const enableAdminTools = args.includes("--http-admin-tools");
127
127
  const authTokenEnv = readOption(args, "--auth-token-env") ?? "MCP_GATEWAY_AUTH_TOKEN";
128
128
  const maxConcurrentRequests = readIntegerOption(args, "--max-concurrent-requests", 10_000);
129
+ const maxRequestBodyBytes = readIntegerOption(args, "--max-request-body-bytes", 64 * 1024 * 1024);
130
+ const maxLegacySessions = readIntegerOption(args, "--max-legacy-sessions", 10_000);
129
131
  validateCliArgs(args);
130
- if (!enableHttp && (host || port || path || enableAdminTools || maxConcurrentRequests || args.includes("--auth-token-env"))) {
132
+ if (!enableHttp && (host || port || path || enableAdminTools || maxConcurrentRequests || maxRequestBodyBytes || maxLegacySessions
133
+ || args.includes("--auth-token-env"))) {
131
134
  throw new Error("HTTP options require --http.");
132
135
  }
133
136
  return {
@@ -140,7 +143,9 @@ export function parseCliArgs(args) {
140
143
  path: path ?? "/mcp",
141
144
  authToken: process.env[authTokenEnv],
142
145
  enableAdminTools,
143
- maxConcurrentRequests: maxConcurrentRequests ?? 64
146
+ maxConcurrentRequests: maxConcurrentRequests ?? 64,
147
+ maxRequestBodyBytes: maxRequestBodyBytes ?? 16 * 1024 * 1024,
148
+ maxLegacySessions: maxLegacySessions ?? 256
144
149
  }
145
150
  : undefined
146
151
  };
@@ -174,7 +179,16 @@ function readIntegerOption(args, name, maximum = 65_535) {
174
179
  */
175
180
  function validateCliArgs(args) {
176
181
  const switches = new Set(["--http", "--http-admin-tools", "-v", "--version"]);
177
- const valued = new Set(["--config", "--port", "--host", "--path", "--auth-token-env", "--max-concurrent-requests"]);
182
+ const valued = new Set([
183
+ "--config",
184
+ "--port",
185
+ "--host",
186
+ "--path",
187
+ "--auth-token-env",
188
+ "--max-concurrent-requests",
189
+ "--max-request-body-bytes",
190
+ "--max-legacy-sessions"
191
+ ]);
178
192
  const seen = new Set();
179
193
  for (let index = 0; index < args.length; index += 1) {
180
194
  const arg = args[index];
@@ -0,0 +1,215 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { isDeepStrictEqual } from "node:util";
3
+ const CONFIRMATION_STATE_PREFIX = "mcp-gateway-tool-confirmation-v1.";
4
+ const APPROVED_STATE_PREFIX = "mcp-gateway-approved-tool-continuation-v1.";
5
+ const CONFIRMATION_RESPONSE_KEY = "confirm";
6
+ const DEFAULT_STATE_TTL_MS = 10 * 60_000;
7
+ const DEFAULT_MAX_STATES = 1024;
8
+ /**
9
+ * Gates configured downstream tools behind one upstream form elicitation round.
10
+ */
11
+ export class ToolConfirmationInterceptor {
12
+ stateTtlMs;
13
+ maxStates;
14
+ pending = new Map();
15
+ approvedContinuations = new Map();
16
+ activeInvocations = 0;
17
+ constructor(options = {}) {
18
+ this.stateTtlMs = options.stateTtlMs ?? DEFAULT_STATE_TTL_MS;
19
+ this.maxStates = options.maxStates ?? DEFAULT_MAX_STATES;
20
+ if (!Number.isInteger(this.maxStates) || this.maxStates < 1) {
21
+ throw new Error("Tool confirmation maxStates must be a positive integer.");
22
+ }
23
+ }
24
+ /**
25
+ * Checks whether a request state belongs to this interceptor.
26
+ */
27
+ handlesState(requestState) {
28
+ return requestState?.startsWith(CONFIRMATION_STATE_PREFIX) === true
29
+ || requestState?.startsWith(APPROVED_STATE_PREFIX) === true;
30
+ }
31
+ /**
32
+ * Confirms a fresh invocation or resumes a previously approved downstream round.
33
+ */
34
+ async execute(serviceId, toolName, args, context, invoke) {
35
+ const requestState = context.requestState;
36
+ if (requestState?.startsWith(APPROVED_STATE_PREFIX)) {
37
+ const approved = this.consumeState(this.approvedContinuations, requestState, serviceId, toolName, args);
38
+ if (!approved?.downstreamRequestState) {
39
+ throw new Error("Tool confirmation state is invalid or has expired.");
40
+ }
41
+ return this.invokeReserved(serviceId, toolName, args, { ...context, requestState: approved.downstreamRequestState }, invoke);
42
+ }
43
+ if (requestState?.startsWith(CONFIRMATION_STATE_PREFIX)) {
44
+ return this.resumeConfirmation(requestState, serviceId, toolName, args, context, invoke);
45
+ }
46
+ if (requestState) {
47
+ throw new Error("Tool confirmation state is invalid or has expired.");
48
+ }
49
+ if (!supportsFormElicitation(context.clientCapabilities)) {
50
+ throw new Error(`Tool '${toolName}' in service '${serviceId}' requires confirmation, but the current MCP session does not support form elicitation.`);
51
+ }
52
+ if (this.stateCount() >= this.maxStates) {
53
+ throw new Error(`Tool confirmation state capacity of ${this.maxStates} has been reached.`);
54
+ }
55
+ const state = this.createState(serviceId, toolName, args);
56
+ this.pending.set(state.requestState, state);
57
+ return buildConfirmationRequest(state);
58
+ }
59
+ /**
60
+ * Consumes the upstream answer before invoking the downstream tool.
61
+ */
62
+ async resumeConfirmation(requestState, serviceId, toolName, args, context, invoke) {
63
+ const pending = this.consumeState(this.pending, requestState, serviceId, toolName, args);
64
+ if (!pending) {
65
+ throw new Error("Tool confirmation state is invalid or has expired.");
66
+ }
67
+ const response = context.inputResponses?.[CONFIRMATION_RESPONSE_KEY];
68
+ if (!isConfirmed(response)) {
69
+ throw new Error(`Tool '${toolName}' in service '${serviceId}' was not called because the user rejected the confirmation request.`);
70
+ }
71
+ return this.invokeReserved(serviceId, toolName, args, withoutConfirmationContinuation(context), invoke);
72
+ }
73
+ /**
74
+ * Keeps a consumed state slot reserved while a downstream round is active.
75
+ */
76
+ async invokeReserved(serviceId, toolName, args, context, invoke) {
77
+ this.activeInvocations += 1;
78
+ try {
79
+ return await this.invokeAndTrack(serviceId, toolName, args, context, invoke);
80
+ }
81
+ finally {
82
+ this.activeInvocations -= 1;
83
+ }
84
+ }
85
+ /**
86
+ * Records downstream MRTR state so later rounds do not ask for confirmation again.
87
+ */
88
+ async invokeAndTrack(serviceId, toolName, args, context, invoke) {
89
+ const result = await invoke(context);
90
+ if (isInputRequiredResult(result) && typeof result.requestState === "string") {
91
+ const state = this.createState(serviceId, toolName, args, `${APPROVED_STATE_PREFIX}${randomUUID()}`, result.requestState);
92
+ this.approvedContinuations.set(state.requestState, state);
93
+ return { ...result, requestState: state.requestState };
94
+ }
95
+ return result;
96
+ }
97
+ /**
98
+ * Creates an expiring state record with an unguessable token when needed.
99
+ */
100
+ createState(serviceId, toolName, args, requestState = `${CONFIRMATION_STATE_PREFIX}${randomUUID()}`, downstreamRequestState) {
101
+ const state = {
102
+ serviceId,
103
+ toolName,
104
+ args: structuredClone(args),
105
+ requestState,
106
+ ...(downstreamRequestState ? { downstreamRequestState } : {}),
107
+ expiryTimer: setTimeout(() => {
108
+ this.pending.delete(requestState);
109
+ this.approvedContinuations.delete(requestState);
110
+ }, this.stateTtlMs)
111
+ };
112
+ state.expiryTimer.unref();
113
+ return state;
114
+ }
115
+ /**
116
+ * Atomically consumes a matching state record.
117
+ */
118
+ consumeState(states, requestState, serviceId, toolName, args) {
119
+ const state = states.get(requestState);
120
+ if (!state
121
+ || state.serviceId !== serviceId
122
+ || state.toolName !== toolName
123
+ || !isDeepStrictEqual(state.args, args)) {
124
+ return null;
125
+ }
126
+ states.delete(requestState);
127
+ clearTimeout(state.expiryTimer);
128
+ return state;
129
+ }
130
+ /**
131
+ * Counts parked and currently executing confirmation-protected invocations.
132
+ */
133
+ stateCount() {
134
+ return this.pending.size + this.approvedContinuations.size + this.activeInvocations;
135
+ }
136
+ }
137
+ /**
138
+ * Creates the modern continuation result; the SDK bridges it for legacy clients.
139
+ */
140
+ function buildConfirmationRequest(state) {
141
+ return {
142
+ resultType: "input_required",
143
+ inputRequests: {
144
+ [CONFIRMATION_RESPONSE_KEY]: {
145
+ method: "elicitation/create",
146
+ params: {
147
+ mode: "form",
148
+ message: buildConfirmationMessage(state),
149
+ requestedSchema: {
150
+ type: "object",
151
+ properties: {
152
+ decision: {
153
+ type: "string",
154
+ title: "Run this tool call?",
155
+ description: "Choose yes to execute the displayed call or no to reject it.",
156
+ enum: ["yes", "no"]
157
+ }
158
+ },
159
+ required: ["decision"],
160
+ additionalProperties: false
161
+ }
162
+ }
163
+ }
164
+ },
165
+ requestState: state.requestState
166
+ };
167
+ }
168
+ /**
169
+ * Shows the exact protected invocation so the user can make an informed decision.
170
+ */
171
+ function buildConfirmationMessage(state) {
172
+ return [
173
+ "Review this gateway-protected tool call before execution.",
174
+ `Service: ${JSON.stringify(state.serviceId)}`,
175
+ `Tool: ${JSON.stringify(state.toolName)}`,
176
+ "Risk: Gateway policy requires explicit confirmation.",
177
+ "Arguments:",
178
+ JSON.stringify(state.args, null, 2),
179
+ "Choose yes to execute it or no to reject it."
180
+ ].join("\n");
181
+ }
182
+ /**
183
+ * Checks the explicit capability instead of relying on a later SDK failure.
184
+ */
185
+ function supportsFormElicitation(capabilities) {
186
+ const elicitation = capabilities?.elicitation;
187
+ return isRecord(elicitation) && isRecord(elicitation.form);
188
+ }
189
+ /**
190
+ * Treats cancel, decline, malformed content, and a no decision as refusal.
191
+ */
192
+ function isConfirmed(response) {
193
+ return response?.action === "accept"
194
+ && isRecord(response.content)
195
+ && response.content.decision === "yes";
196
+ }
197
+ /**
198
+ * Removes the gateway's private confirmation continuation before the first call.
199
+ */
200
+ function withoutConfirmationContinuation(context) {
201
+ const { inputResponses: _inputResponses, requestState: _requestState, ...rest } = context;
202
+ return rest;
203
+ }
204
+ /**
205
+ * Detects a modern input-required tool result without depending on SDK internals.
206
+ */
207
+ function isInputRequiredResult(result) {
208
+ return "resultType" in result && result.resultType === "input_required";
209
+ }
210
+ /**
211
+ * Checks whether a value is a plain record.
212
+ */
213
+ function isRecord(value) {
214
+ return typeof value === "object" && value !== null && !Array.isArray(value);
215
+ }
@@ -3,6 +3,7 @@ import { dirname, resolve } from "node:path";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { StdioMcpClient } from "./mcp/client.js";
5
5
  import { StreamableHttpClient } from "./mcp/http-client.js";
6
+ import { matchesAnyToolNamePattern } from "./tool-name-pattern.js";
6
7
  /**
7
8
  * Maintains the active service pool, client instances, and cached metadata.
8
9
  */
@@ -22,13 +23,6 @@ export class ServiceRegistry {
22
23
  /**
23
24
  * Stores the last valid config snapshot.
24
25
  */
25
- currentConfig = {
26
- logging: {
27
- enable: false,
28
- path: null
29
- },
30
- services: []
31
- };
32
26
  /**
33
27
  * Stores the current immutable runtime view used by request handlers.
34
28
  */
@@ -97,7 +91,6 @@ export class ServiceRegistry {
97
91
  throw error;
98
92
  }
99
93
  const previousClients = this.clients;
100
- this.currentConfig = nextConfig;
101
94
  this.snapshots = nextSnapshots;
102
95
  this.clients = nextClients;
103
96
  await disposeRemovedClients(previousClients, nextClients);
@@ -125,7 +118,8 @@ export class ServiceRegistry {
125
118
  * Lists tools for one logical service, optionally matching name or description keywords.
126
119
  */
127
120
  listTools(serviceId, toolName, desc) {
128
- const tools = this.requireService(serviceId).metadata.tools;
121
+ const snapshot = this.requireService(serviceId);
122
+ const tools = snapshot.metadata.tools.filter((tool) => !matchesAnyToolNamePattern(tool.name, snapshot.config.disabledTools));
129
123
  const nameKeywords = normalizeKeywords(toolName);
130
124
  const descriptionKeywords = normalizeKeywords(desc);
131
125
  if (nameKeywords.length === 0 && descriptionKeywords.length === 0) {
@@ -142,13 +136,20 @@ export class ServiceRegistry {
142
136
  * Returns one tool definition for a service.
143
137
  */
144
138
  getTool(serviceId, toolName) {
145
- return this.requireService(serviceId).metadata.tools.find((tool) => tool.name === toolName) ?? null;
139
+ const snapshot = this.requireService(serviceId);
140
+ if (matchesAnyToolNamePattern(toolName, snapshot.config.disabledTools)) {
141
+ return null;
142
+ }
143
+ return snapshot.metadata.tools.find((tool) => tool.name === toolName) ?? null;
146
144
  }
147
145
  /**
148
146
  * Calls one downstream tool using the only configured service process.
149
147
  */
150
148
  async callTool(serviceId, toolName, args, context = {}) {
151
149
  const snapshot = this.requireService(serviceId);
150
+ if (matchesAnyToolNamePattern(toolName, snapshot.config.disabledTools)) {
151
+ throw new Error(`Tool '${toolName}' in service '${serviceId}' is disabled by gateway configuration.`);
152
+ }
152
153
  const client = this.clients.get(serviceId);
153
154
  if (!client) {
154
155
  throw new Error(`Service '${serviceId}' is unavailable.`);
@@ -199,13 +200,13 @@ export class ServiceRegistry {
199
200
  */
200
201
  async reconnectService(serviceId) {
201
202
  const snapshot = this.requireService(serviceId);
203
+ const previousRuntime = snapshot.runtime;
202
204
  const currentClient = this.clients.get(serviceId);
203
205
  if (!currentClient) {
204
206
  throw new Error(`Service '${serviceId}' is unavailable.`);
205
207
  }
206
208
  const nextClient = createClient(snapshot.config, this.logger);
207
209
  try {
208
- await currentClient.dispose().catch(() => undefined);
209
210
  const metadata = await nextClient.getMetadata();
210
211
  snapshot.metadata = metadata;
211
212
  snapshot.runtime = {
@@ -215,6 +216,7 @@ export class ServiceRegistry {
215
216
  restartAttempts: nextClient.restartCount
216
217
  };
217
218
  this.clients.set(serviceId, nextClient);
219
+ await currentClient.dispose().catch(() => undefined);
218
220
  return {
219
221
  serviceId,
220
222
  action: "reconnect",
@@ -226,17 +228,16 @@ export class ServiceRegistry {
226
228
  await nextClient.dispose().catch(() => undefined);
227
229
  const message = error instanceof Error ? error.message : String(error);
228
230
  snapshot.runtime = {
229
- available: false,
230
- lastError: message,
231
- lastConnectedAt: snapshot.runtime.lastConnectedAt,
231
+ available: previousRuntime.available,
232
+ lastError: `Reconnect failed; existing connection retained: ${message}`,
233
+ lastConnectedAt: previousRuntime.lastConnectedAt,
232
234
  restartAttempts: currentClient.restartCount
233
235
  };
234
- this.clients.set(serviceId, currentClient);
235
236
  return {
236
237
  serviceId,
237
238
  action: "reconnect",
238
239
  enabled: true,
239
- available: false
240
+ available: previousRuntime.available
240
241
  };
241
242
  }
242
243
  }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Matches one complete, case-sensitive tool name against a compact glob pattern.
3
+ * `*` matches zero or more characters and `?` matches exactly one character.
4
+ */
5
+ export function matchesToolNamePattern(toolName, pattern) {
6
+ const nameCharacters = [...toolName];
7
+ const patternCharacters = [...pattern];
8
+ let nameIndex = 0;
9
+ let patternIndex = 0;
10
+ let starIndex = -1;
11
+ let starNameIndex = -1;
12
+ while (nameIndex < nameCharacters.length) {
13
+ const patternCharacter = patternCharacters[patternIndex];
14
+ if (patternCharacter === "?" || patternCharacter === nameCharacters[nameIndex]) {
15
+ nameIndex += 1;
16
+ patternIndex += 1;
17
+ continue;
18
+ }
19
+ if (patternCharacter === "*") {
20
+ starIndex = patternIndex;
21
+ starNameIndex = nameIndex;
22
+ patternIndex += 1;
23
+ continue;
24
+ }
25
+ if (starIndex >= 0) {
26
+ patternIndex = starIndex + 1;
27
+ starNameIndex += 1;
28
+ nameIndex = starNameIndex;
29
+ continue;
30
+ }
31
+ return false;
32
+ }
33
+ while (patternCharacters[patternIndex] === "*") {
34
+ patternIndex += 1;
35
+ }
36
+ return patternIndex === patternCharacters.length;
37
+ }
38
+ /**
39
+ * Checks whether a tool name matches any configured pattern.
40
+ */
41
+ export function matchesAnyToolNamePattern(toolName, patterns) {
42
+ return patterns?.some((pattern) => matchesToolNamePattern(toolName, pattern)) ?? false;
43
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jadchene/mcp-gateway-service",
3
- "version": "0.7.1",
3
+ "version": "0.9.0",
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",
@@ -1,40 +1,27 @@
1
- ---
2
- name: mcp-gateway
3
- description: Route work through an MCP gateway with token-efficient downstream service discovery, filtered tool search, exact schema lookup, service diagnostics, and forwarded tool calls. Use when an agent needs to find or call tools behind the gateway without loading every downstream schema.
4
- ---
5
-
6
- # MCP Gateway
7
-
8
- Use the gateway as the single entry point for downstream MCP services.
9
-
10
- ## Routing Workflow
11
-
12
- 1. Reuse an exact `serviceId` already confirmed in the current session; otherwise call `gateway_list_services`.
13
- 2. Reuse an exact downstream tool name already confirmed in the current session; otherwise call `gateway_list_tools` for only the selected service.
14
- 3. Filter discovery with unique non-empty `toolName` and/or `desc` string arrays. Treat both filters as case-insensitive literal substring matches joined by OR.
15
- 4. Obtain the input schema when arguments are unfamiliar, incomplete, or safety-sensitive. Use `includeSchema: true` during filtered discovery or call `gateway_get_tool_schema` with exact case-sensitive tool names.
16
- 5. Call `gateway_call_tool` with the confirmed `serviceId`, exact `toolName`, and an explicit `arguments` object. Pass `{}` for a no-argument tool.
17
- 6. Refresh only stale service, tool, or schema information after an unknown-identifier or validation failure.
18
-
19
- ## Discovery Rules
20
-
21
- - Never guess a service identifier, tool name, or argument shape.
22
- - Treat `serviceId` as a downstream identifier returned by `gateway_list_services`; never use a gateway-owned tool name as a service identifier.
23
- - Search only the relevant service instead of collecting every downstream tool.
24
- - Inspect description matches because negative guidance may also contain the search term.
25
- - Reuse schemas returned by `gateway_list_tools(includeSchema: true)` instead of fetching them again.
26
- - Batch exact names in one `gateway_get_tool_schema` call when several selected tools need schemas.
27
- - Treat downstream `structuredContent` as arbitrary JSON.
28
-
29
- ## Diagnostics and Control
30
-
31
- - Use `gateway_get_service` only when connection state, protocol details, server identity, or recent errors matter.
32
- - Use `gateway_manage_service` only when the user explicitly requests reconnecting, enabling, or disabling a service.
33
- - Treat `reconnect` as a connection refresh that does not change config.
34
- - Treat `enable` and `disable` as persistent config changes.
35
-
36
- ## Safety
37
-
38
- - Apply the downstream tool's schema, side-effect rules, and confirmation flow before calling it.
39
- - Treat gateway failures and structured downstream error results as failures.
40
- - Never auto-approve an `input_required` result. Obtain the requested user input and retry with the returned opaque state and matching responses.
1
+ ---
2
+ name: mcp-gateway
3
+ description: Route work through an MCP gateway with token-efficient downstream service discovery, filtered tool search, exact schema lookup, service diagnostics, and forwarded tool calls. Use when an agent needs to find or call tools behind the gateway without loading every downstream schema.
4
+ ---
5
+
6
+ # MCP Gateway
7
+
8
+ Use the gateway as the single entry point for downstream MCP services.
9
+
10
+ ## Workflow
11
+
12
+ 1. Reuse an exact `serviceId` already confirmed in the current session; otherwise call `gateway_list_services`.
13
+ 2. Reuse an exact downstream tool name already confirmed in the session; otherwise search only that service with `gateway_list_tools`. The unique non-empty `toolName` and `desc` filters are case-insensitive literal substrings joined by OR, so inspect description matches for negative guidance.
14
+ 3. Obtain unfamiliar or safety-sensitive schemas with `includeSchema: true` or `gateway_get_tool_schema`; tool names are exact and case-sensitive.
15
+ 4. Call `gateway_call_tool` with the confirmed identifiers and an explicit `arguments` object; pass `{}` when the tool has no arguments.
16
+ 5. Refresh only the identifier or schema rejected as stale.
17
+
18
+ ## Diagnostics and Control
19
+
20
+ - Treat `serviceId` as a downstream identifier, never as a gateway-owned tool.
21
+ - Use `gateway_get_service` for connection diagnostics. Use `gateway_manage_service` only when explicitly requested: `reconnect` does not change config, while `enable` and `disable` persist.
22
+
23
+ ## Safety
24
+
25
+ - Apply the downstream tool's schema, side-effect rules, and confirmation flow before calling it.
26
+ - Treat gateway failures and structured downstream error results as failures.
27
+ - Never auto-approve an `input_required` result. Obtain the requested user input and retry with the returned opaque state and matching responses.