@jadchene/mcp-gateway-service 0.6.5 → 0.7.1

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.
@@ -4,6 +4,9 @@ import { FormElicitationBridge } from "./form-elicitation-bridge.js";
4
4
  import { SUPPORTED_MCP_PROTOCOL_VERSIONS } from "./versions.js";
5
5
  const MAX_RESTART_ATTEMPTS = 3;
6
6
  const CONNECT_TIMEOUT_MS = 30_000;
7
+ const DEFAULT_CALL_TIMEOUT_MS = 120_000;
8
+ const MAX_DOWNSTREAM_TOOLS = 5_000;
9
+ const MAX_TOOL_CATALOG_BYTES = 5 * 1024 * 1024;
7
10
  /**
8
11
  * Implements shared MCP SDK v2 client behavior for stdio and HTTP transports.
9
12
  */
@@ -109,7 +112,7 @@ export class SdkMcpClient {
109
112
  * Calls a downstream tool while preserving cancellation, custom headers, and MRTR state.
110
113
  */
111
114
  async callTool(name, args, context = {}) {
112
- return this.executeWithRecovery(async () => {
115
+ try {
113
116
  const client = await this.requireClient();
114
117
  const params = {
115
118
  name,
@@ -118,8 +121,9 @@ export class SdkMcpClient {
118
121
  ...(context.requestState ? { requestState: context.requestState } : {})
119
122
  };
120
123
  const invoke = async (signal) => {
124
+ const callSignal = combineWithTimeout(signal, this.service.callTimeoutMs ?? DEFAULT_CALL_TIMEOUT_MS);
121
125
  const result = await client.callTool(params, {
122
- signal,
126
+ signal: callSignal,
123
127
  allowInputRequired: true,
124
128
  toolDefinition: this.tools.get(name)
125
129
  });
@@ -130,7 +134,15 @@ export class SdkMcpClient {
130
134
  }
131
135
  const result = await invoke(context.signal ?? new AbortController().signal);
132
136
  return result;
133
- });
137
+ }
138
+ catch (error) {
139
+ const normalized = normalizeError(error);
140
+ if (isNonRetryable(normalized) || context.signal?.aborted) {
141
+ throw normalized;
142
+ }
143
+ await this.disposeConnection();
144
+ throw new Error(`Downstream tool '${name}' failed; execution status is unknown and the gateway did not replay it. ${normalized.message}`, { cause: normalized });
145
+ }
134
146
  }
135
147
  /**
136
148
  * Connects one fresh SDK client and transport.
@@ -201,6 +213,12 @@ export class SdkMcpClient {
201
213
  */
202
214
  async requestToolsList(client) {
203
215
  const result = await client.listTools();
216
+ if (result.tools.length > MAX_DOWNSTREAM_TOOLS) {
217
+ throw new ResourceLimitError(`Service '${this.key}' returned more than ${MAX_DOWNSTREAM_TOOLS} tools.`);
218
+ }
219
+ if (Buffer.byteLength(JSON.stringify(result.tools), "utf8") > MAX_TOOL_CATALOG_BYTES) {
220
+ throw new ResourceLimitError(`Service '${this.key}' returned a tool catalog larger than ${MAX_TOOL_CATALOG_BYTES} bytes.`);
221
+ }
204
222
  this.tools = new Map(result.tools.map((tool) => [tool.name, tool]));
205
223
  return result.tools.map(normalizeToolDefinition);
206
224
  }
@@ -271,14 +289,22 @@ function toJsonObject(input) {
271
289
  * Prevents protocol and explicit HTTP failures from being disguised as reconnects.
272
290
  */
273
291
  function isNonRetryable(error) {
274
- if (error instanceof ProtocolError) {
292
+ if (error instanceof ProtocolError || error instanceof ResourceLimitError) {
275
293
  return true;
276
294
  }
277
295
  return error instanceof SdkHttpError && error.status >= 400 && error.status < 500;
278
296
  }
297
+ class ResourceLimitError extends Error {
298
+ }
279
299
  /**
280
300
  * Normalizes unknown thrown values into Error instances.
281
301
  */
282
302
  function normalizeError(error) {
283
303
  return error instanceof Error ? error : new Error(String(error));
284
304
  }
305
+ /**
306
+ * Applies the configured deadline while preserving caller cancellation.
307
+ */
308
+ function combineWithTimeout(signal, timeoutMs) {
309
+ return AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]);
310
+ }
@@ -3,10 +3,10 @@ import { buildGatewayTools } from "../gateway-engine.js";
3
3
  import { VERSION } from "../version.js";
4
4
  import { SUPPORTED_MCP_PROTOCOL_VERSIONS } from "./versions.js";
5
5
  /**
6
- * Creates one SDK server instance with all six stable gateway tools.
6
+ * Creates one SDK server instance with the selected gateway tool surface.
7
7
  */
8
- export function createGatewayMcpServer(engine) {
9
- const options = {
8
+ export function createGatewayMcpServer(engine, options = {}) {
9
+ const serverOptions = {
10
10
  supportedProtocolVersions: [...SUPPORTED_MCP_PROTOCOL_VERSIONS],
11
11
  capabilities: {
12
12
  tools: {
@@ -27,8 +27,8 @@ export function createGatewayMcpServer(engine) {
27
27
  maxRounds: 8
28
28
  }
29
29
  };
30
- const server = new McpServer({ name: "mcp-gateway", version: VERSION }, options);
31
- for (const tool of buildGatewayTools()) {
30
+ const server = new McpServer({ name: "mcp-gateway", version: VERSION }, serverOptions);
31
+ for (const tool of buildGatewayTools(options)) {
32
32
  const inputSchema = fromJsonSchema(tool.inputSchema);
33
33
  const outputSchema = tool.outputSchema
34
34
  ? fromJsonSchema(tool.outputSchema)
@@ -53,6 +53,9 @@ function toDownstreamContext(context, mcp2025ClientCapabilities) {
53
53
  const clientCapabilities = isRecord(envelopeCapabilities)
54
54
  ? envelopeCapabilities
55
55
  : mcp2025ClientCapabilities;
56
+ if (!context.mcpReq.envelope) {
57
+ normalizeLegacyFormElicitationCapability(clientCapabilities);
58
+ }
56
59
  return {
57
60
  signal: context.mcpReq.signal,
58
61
  ...(clientCapabilities ? { clientCapabilities } : {}),
@@ -60,11 +63,25 @@ function toDownstreamContext(context, mcp2025ClientCapabilities) {
60
63
  ...(context.mcpReq.requestState() ? { requestState: context.mcpReq.requestState() } : {}),
61
64
  ...(!context.mcpReq.envelope
62
65
  ? {
63
- elicitForm: (params, signal) => context.mcpReq.elicitInput(params, { signal })
66
+ elicitForm: (params, signal) => context.mcpReq.elicitInput(params, {
67
+ signal,
68
+ relatedRequestId: context.mcpReq.id
69
+ })
64
70
  }
65
71
  : {})
66
72
  };
67
73
  }
74
+ /**
75
+ * MCP 2025 clients may advertise form elicitation as the legacy shorthand
76
+ * `elicitation: {}`. The SDK's request helper expects the later explicit
77
+ * `elicitation.form` shape, so normalize the negotiated capability in place.
78
+ */
79
+ export function normalizeLegacyFormElicitationCapability(clientCapabilities) {
80
+ const elicitation = clientCapabilities?.elicitation;
81
+ if (isRecord(elicitation) && !("form" in elicitation)) {
82
+ elicitation.form = {};
83
+ }
84
+ }
68
85
  /**
69
86
  * Checks whether a value is a plain record.
70
87
  */
@@ -1,5 +1,6 @@
1
- import { readFile, writeFile } from "node:fs/promises";
2
- import { resolve } from "node:path";
1
+ import { open, readFile, rename, unlink, writeFile } from "node:fs/promises";
2
+ import { dirname, resolve } from "node:path";
3
+ import { randomUUID } from "node:crypto";
3
4
  import { StdioMcpClient } from "./mcp/client.js";
4
5
  import { StreamableHttpClient } from "./mcp/http-client.js";
5
6
  /**
@@ -40,6 +41,7 @@ export class ServiceRegistry {
40
41
  * Prevents overlapping config reload operations.
41
42
  */
42
43
  reloadPromise = Promise.resolve();
44
+ managementPromise = Promise.resolve();
43
45
  /**
44
46
  * Creates a registry bound to one config file path.
45
47
  */
@@ -52,12 +54,27 @@ export class ServiceRegistry {
52
54
  * Loads the initial config snapshot.
53
55
  */
54
56
  async initialize() {
55
- await this.reload();
57
+ await this.reloadStrict();
56
58
  }
57
59
  /**
58
60
  * Reloads the config file and atomically swaps the runtime snapshot on success.
59
61
  */
60
62
  async reload() {
63
+ try {
64
+ await this.reloadStrict();
65
+ }
66
+ catch (error) {
67
+ this.logger.error("config.reload.failed", {
68
+ configPath: resolve(this.configPath),
69
+ message: error instanceof Error ? error.message : String(error)
70
+ });
71
+ await this.logger.flush();
72
+ }
73
+ }
74
+ /**
75
+ * Serializes reloads and lets startup and management callers observe failures.
76
+ */
77
+ async reloadStrict() {
61
78
  this.reloadPromise = this.reloadPromise.catch(() => undefined).then(async () => {
62
79
  const absolutePath = resolve(this.configPath);
63
80
  this.logger.info("config.reload.started", { configPath: absolutePath });
@@ -76,26 +93,21 @@ export class ServiceRegistry {
76
93
  configPath: absolutePath,
77
94
  message: error instanceof Error ? error.message : String(error)
78
95
  });
79
- await disposeClientMap(nextClients);
96
+ await disposeNewClients(this.clients, nextClients);
80
97
  throw error;
81
98
  }
82
- await disposeRemovedClients(this.clients, nextClients);
99
+ const previousClients = this.clients;
83
100
  this.currentConfig = nextConfig;
84
101
  this.snapshots = nextSnapshots;
85
102
  this.clients = nextClients;
103
+ await disposeRemovedClients(previousClients, nextClients);
86
104
  this.logger.info("config.reload.succeeded", {
87
105
  configPath: absolutePath,
88
106
  serviceCount: nextConfig.services.length
89
107
  });
108
+ await this.logger.flush();
90
109
  });
91
- try {
92
- await this.reloadPromise;
93
- }
94
- catch {
95
- /**
96
- * Keeps the last valid snapshot active while surfacing the error through logs.
97
- */
98
- }
110
+ await this.reloadPromise;
99
111
  }
100
112
  /**
101
113
  * Returns a sorted list of runtime service snapshots.
@@ -232,23 +244,36 @@ export class ServiceRegistry {
232
244
  * Persists the service enable flag to the config file and reloads the registry.
233
245
  */
234
246
  async setServiceEnabled(serviceId, enabled) {
235
- const rawConfig = await readRawConfig(this.configPath);
236
- if (!Array.isArray(rawConfig.services)) {
237
- throw new Error("The 'services' field must be an array.");
238
- }
239
- const service = rawConfig.services.find((candidate) => isRecord(candidate) && candidate.serviceId === serviceId);
240
- if (!service || !isRecord(service)) {
241
- throw new Error(`Unknown service '${serviceId}'.`);
242
- }
243
- service.enable = enabled;
244
- await writeFile(resolve(this.configPath), `${JSON.stringify(rawConfig, null, 2)}\n`, "utf8");
245
- await this.reload();
246
- return {
247
- serviceId,
248
- action: enabled ? "enable" : "disable",
249
- enabled,
250
- available: enabled ? (this.getService(serviceId)?.runtime.available ?? false) : false
251
- };
247
+ let result;
248
+ const operation = this.managementPromise.catch(() => undefined).then(async () => {
249
+ const { config: rawConfig, rawText: original } = await readRawConfig(this.configPath);
250
+ if (!Array.isArray(rawConfig.services)) {
251
+ throw new Error("The 'services' field must be an array.");
252
+ }
253
+ const service = rawConfig.services.find((candidate) => isRecord(candidate) && candidate.serviceId === serviceId);
254
+ if (!service || !isRecord(service)) {
255
+ throw new Error(`Unknown service '${serviceId}'.`);
256
+ }
257
+ service.enable = enabled;
258
+ const absolutePath = resolve(this.configPath);
259
+ await writeFileAtomically(absolutePath, `${JSON.stringify(rawConfig, null, 2)}\n`);
260
+ try {
261
+ await this.reloadStrict();
262
+ }
263
+ catch (error) {
264
+ await writeFileAtomically(absolutePath, original);
265
+ throw error;
266
+ }
267
+ result = {
268
+ serviceId,
269
+ action: enabled ? "enable" : "disable",
270
+ enabled,
271
+ available: enabled ? (this.getService(serviceId)?.runtime.available ?? false) : false
272
+ };
273
+ });
274
+ this.managementPromise = operation;
275
+ await operation;
276
+ return result;
252
277
  }
253
278
  /**
254
279
  * Builds one runtime snapshot and initializes required metadata.
@@ -352,6 +377,13 @@ async function disposeRemovedClients(previous, next) {
352
377
  }
353
378
  await Promise.all(removed.map((client) => client.dispose().catch(() => undefined)));
354
379
  }
380
+ /** Disposes only clients created by a failed reload, preserving reused active clients. */
381
+ async function disposeNewClients(previous, next) {
382
+ const created = [...next.entries()]
383
+ .filter(([key, client]) => previous.get(key) !== client)
384
+ .map(([, client]) => client);
385
+ await Promise.all(created.map((client) => client.dispose().catch(() => undefined)));
386
+ }
355
387
  /**
356
388
  * Creates a downstream client implementation for one service config.
357
389
  */
@@ -385,7 +417,41 @@ async function readRawConfig(configPath) {
385
417
  if (!isRecord(parsed)) {
386
418
  throw new Error("The gateway config must be a JSON object.");
387
419
  }
388
- return parsed;
420
+ return { config: parsed, rawText };
421
+ }
422
+ /**
423
+ * Replaces a config file through a flushed same-directory temporary file.
424
+ */
425
+ async function writeFileAtomically(path, content) {
426
+ const tempPath = resolve(dirname(path), `.${randomUUID()}.tmp`);
427
+ try {
428
+ await writeFile(tempPath, content, { encoding: "utf8", mode: 0o600 });
429
+ const handle = await open(tempPath, "r");
430
+ try {
431
+ if (process.platform !== "win32") {
432
+ await handle.sync();
433
+ }
434
+ }
435
+ finally {
436
+ await handle.close();
437
+ }
438
+ await rename(tempPath, path);
439
+ if (process.platform !== "win32") {
440
+ const directory = await open(dirname(path), "r").catch(() => null);
441
+ if (directory) {
442
+ try {
443
+ await directory.sync();
444
+ }
445
+ finally {
446
+ await directory.close();
447
+ }
448
+ }
449
+ }
450
+ }
451
+ catch (error) {
452
+ await unlink(tempPath).catch(() => undefined);
453
+ throw error;
454
+ }
389
455
  }
390
456
  /**
391
457
  * Checks whether a value is a plain record.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jadchene/mcp-gateway-service",
3
- "version": "0.6.5",
3
+ "version": "0.7.1",
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",
@@ -17,18 +17,18 @@
17
17
  "bugs": {
18
18
  "url": "https://github.com/jadchene/mcp-gateway/issues"
19
19
  },
20
- "scripts": {
21
- "clean": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"",
22
- "prebuild": "npm run clean",
23
- "build": "tsc -p tsconfig.build.json",
24
- "dev": "node --experimental-strip-types src/index.ts",
25
- "start": "node dist/index.js",
26
- "pretest": "npm run build",
27
- "test": "node --test --experimental-strip-types test/**/*.test.ts",
28
- "typecheck": "tsc -p tsconfig.json --noEmit",
29
- "verify": "npm run typecheck && npm test",
20
+ "scripts": {
21
+ "clean": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"",
22
+ "prebuild": "npm run clean",
23
+ "build": "tsc -p tsconfig.build.json",
24
+ "dev": "node --experimental-strip-types src/index.ts",
25
+ "start": "node dist/index.js",
26
+ "pretest": "npm run build",
27
+ "test": "node --test --experimental-strip-types test/**/*.test.ts",
28
+ "typecheck": "tsc -p tsconfig.json --noEmit",
29
+ "verify": "npm run typecheck && npm test",
30
30
  "version": "node dist/index.js --version",
31
- "prepack": "npm run build",
31
+ "prepack": "npm run build",
32
32
  "prepublishOnly": "npm run build"
33
33
  },
34
34
  "files": [
@@ -59,5 +59,9 @@
59
59
  "@modelcontextprotocol/node": "2.0.0",
60
60
  "@modelcontextprotocol/server": "2.0.0",
61
61
  "zod": "4.4.3"
62
+ },
63
+ "overrides": {
64
+ "@hono/node-server": "2.1.0",
65
+ "hono": "4.12.34"
62
66
  }
63
67
  }
@@ -47,41 +47,72 @@ function Invoke-CaptureStep {
47
47
  return @()
48
48
  }
49
49
 
50
+ function Resolve-PackedTarballPath {
51
+ param(
52
+ [string[]]$PackOutput,
53
+ [string]$ProjectRoot
54
+ )
55
+
56
+ if ($PackOutput.Count -eq 0) {
57
+ throw "npm pack did not return package metadata."
58
+ }
59
+
60
+ $parsedOutput = $PackOutput -join "`n" | ConvertFrom-Json
61
+ $packInfo = if ($parsedOutput -is [System.Array]) {
62
+ $parsedOutput[0]
63
+ }
64
+ else {
65
+ @($parsedOutput.PSObject.Properties.Value)[0]
66
+ }
67
+ $filename = [string]$packInfo.filename
68
+
69
+ if ([string]::IsNullOrWhiteSpace($filename)) {
70
+ throw "npm pack metadata did not contain a tarball filename."
71
+ }
72
+ if ([IO.Path]::GetFileName($filename) -ne $filename -or [IO.Path]::GetExtension($filename) -ne ".tgz") {
73
+ throw "npm pack returned an unsafe tarball filename: $filename"
74
+ }
75
+
76
+ $tarballPath = [IO.Path]::GetFullPath((Join-Path $ProjectRoot $filename))
77
+ $tarballParent = [IO.Path]::GetDirectoryName($tarballPath)
78
+ if (-not [StringComparer]::OrdinalIgnoreCase.Equals($tarballParent, $ProjectRoot)) {
79
+ throw "npm pack returned a tarball outside the project root: $tarballPath"
80
+ }
81
+ if (-not (Test-Path -LiteralPath $tarballPath -PathType Leaf)) {
82
+ throw "Packed tarball was not created: $tarballPath"
83
+ }
84
+
85
+ return $tarballPath
86
+ }
87
+
50
88
  $resolvedProjectRoot = (Resolve-Path $ProjectRoot).Path
51
89
  $packageJsonPath = Join-Path $resolvedProjectRoot "package.json"
52
90
  $defaultConfigPath = Join-Path $resolvedProjectRoot "config.example.json"
53
91
  $resolvedConfigPath = if ($ExampleConfigPath) { $ExampleConfigPath } else { $defaultConfigPath }
54
- $packageName = "mcp-gateway-service"
55
92
 
56
93
  if (-not (Test-Path $packageJsonPath)) {
57
94
  throw "package.json not found under project root: $resolvedProjectRoot"
58
95
  }
59
96
 
60
97
  $packageInfo = Get-Content -Raw $packageJsonPath | ConvertFrom-Json
98
+ $packageName = [string]$packageInfo.name
99
+ if ([string]::IsNullOrWhiteSpace($packageName)) {
100
+ throw "package.json does not contain a package name."
101
+ }
61
102
 
62
103
  Push-Location $resolvedProjectRoot
63
104
  try {
64
105
  Invoke-Step -FilePath "npm" -Arguments @("install") -Description "Install project dependencies"
65
106
  Invoke-Step -FilePath "npm" -Arguments @("run", "build") -Description "Build the MCP gateway"
66
107
  $packOutput = Invoke-CaptureStep -FilePath "npm" -Arguments @("pack", "--json") -Description "Create a package tarball for global installation"
67
- if ($packOutput.Count -gt 0) {
68
- $packInfo = ($packOutput -join "`n" | ConvertFrom-Json)[0]
69
- $tarballPath = Join-Path $resolvedProjectRoot $packInfo.filename
70
- } else {
71
- $tarballPath = Join-Path $resolvedProjectRoot "$($packageInfo.name)-$($packageInfo.version).tgz"
72
- }
108
+ $tarballPath = Resolve-PackedTarballPath -PackOutput $packOutput -ProjectRoot $resolvedProjectRoot
73
109
 
74
- try {
75
- Invoke-Step -FilePath "npm" -Arguments @("uninstall", "-g", $packageName) -Description "Remove any previous global installation of mcp-gateway-service"
76
- }
77
- catch {
78
- Write-Host "Previous global installation was not removed cleanly. Continuing with fresh install."
79
- }
110
+ Invoke-Step -FilePath "npm" -Arguments @("uninstall", "-g", $packageName) -Description "Remove any previous global installation of $packageName"
80
111
 
81
112
  Invoke-Step -FilePath "npm" -Arguments @("install", "-g", $tarballPath) -Description "Install the packaged mcp-gateway-service tarball globally"
82
113
 
83
- if (-not $KeepTarball -and (Test-Path $tarballPath)) {
84
- Remove-Item $tarballPath -Force
114
+ if (-not $KeepTarball -and (Test-Path -LiteralPath $tarballPath -PathType Leaf)) {
115
+ Remove-Item -LiteralPath $tarballPath -Force
85
116
  }
86
117
  }
87
118
  finally {