@jadchene/mcp-gateway-service 0.4.4 → 0.6.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.
@@ -1,523 +1,92 @@
1
- import { execFileSync, spawn } from "node:child_process";
1
+ import { execFileSync } from "node:child_process";
2
2
  import { resolve } from "node:path";
3
- import { VERSION } from "../version.js";
4
- import { createMessageReader, createMessageWriter } from "./protocol.js";
3
+ import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
4
+ import { SdkMcpClient } from "./sdk-client.js";
5
5
  /**
6
- * Defines the default timeout applied to downstream JSON-RPC requests.
6
+ * Connects to a downstream stdio service through the official MCP SDK v2.
7
7
  */
8
- const DEFAULT_REQUEST_TIMEOUT_MS = 10_000;
9
- /**
10
- * Defines the maximum number of restart attempts allowed for one service.
11
- */
12
- const MAX_RESTART_ATTEMPTS = 3;
13
- /**
14
- * Defines how long the gateway waits for a child process to exit gracefully.
15
- */
16
- const PROCESS_EXIT_TIMEOUT_MS = 2_000;
17
- /**
18
- * Provides one reusable stdio-backed MCP client for a downstream service.
19
- */
20
- export class StdioMcpClient {
21
- /**
22
- * Stores the bound service config.
23
- */
24
- service;
25
- /**
26
- * Stores the shared logger instance.
27
- */
28
- logger;
29
- /**
30
- * Stores pending request resolvers keyed by request id.
31
- */
32
- pending = new Map();
33
- /**
34
- * Stores the current child process when connected.
35
- */
36
- child = null;
37
- /**
38
- * Stores the writer bound to the child stdin.
39
- */
40
- writer = null;
41
- /**
42
- * Tracks whether downstream initialization succeeded.
43
- */
44
- initialized = false;
45
- /**
46
- * Stores the next request id used for downstream calls.
47
- */
48
- nextId = 1;
49
- /**
50
- * Stores the downstream server info captured during initialization.
51
- */
52
- serverInfo = null;
53
- /**
54
- * Stores the downstream protocol version captured during initialization.
55
- */
56
- protocolVersion = null;
57
- /**
58
- * Counts automatic restart attempts after transport-level failures.
59
- */
60
- restartAttempts = 0;
8
+ export class StdioMcpClient extends SdkMcpClient {
61
9
  /**
62
- * Stores the terminal unavailability reason once restart recovery is exhausted.
63
- */
64
- unavailableReason = null;
65
- /**
66
- * Creates a client for one logical service.
10
+ * Creates the standards-compliant newline-delimited stdio transport.
67
11
  */
68
12
  constructor(service, logger) {
69
- this.service = service;
70
- this.logger = logger;
71
- }
72
- /**
73
- * Returns a stable key for logs.
74
- */
75
- get key() {
76
- return this.service.serviceId;
77
- }
78
- /**
79
- * Indicates whether the service has become unavailable after recovery exhaustion.
80
- */
81
- get isUnavailable() {
82
- return this.unavailableReason !== null;
83
- }
84
- /**
85
- * Returns the terminal unavailability reason when one exists.
86
- */
87
- get unavailableMessage() {
88
- return this.unavailableReason;
89
- }
90
- /**
91
- * Returns the restart attempts consumed by the current lifecycle.
92
- */
93
- get restartCount() {
94
- return this.restartAttempts;
95
- }
96
- /**
97
- * Checks whether the current client still matches a desired service config.
98
- */
99
- matchesConfig(service) {
100
- return JSON.stringify(this.service) === JSON.stringify(service);
101
- }
102
- /**
103
- * Ensures that the downstream process is started and initialized.
104
- */
105
- async ensureConnected() {
106
- if (this.unavailableReason) {
107
- throw new Error(this.unavailableReason);
108
- }
109
- if (this.initialized) {
110
- return;
111
- }
112
- const transport = requireStdioTransport(this.service);
113
- const framingCandidates = transport.framing
114
- ? [transport.framing]
115
- : ["line", "content-length"];
116
- let lastError = null;
117
- for (const framing of framingCandidates) {
118
- try {
119
- await this.startProcess(framing);
120
- await this.initialize();
121
- return;
122
- }
123
- catch (error) {
124
- lastError = normalizeError(error);
125
- await this.disposeProcess();
126
- if (transport.framing) {
127
- break;
128
- }
129
- this.logger.warn("downstream.framing_probe_failed", {
130
- serviceId: this.key,
131
- framing,
132
- message: lastError.message
133
- });
134
- }
135
- }
136
- throw lastError ?? new Error(`Failed to initialize downstream service '${this.key}'.`);
137
- }
138
- /**
139
- * Stops the downstream process and clears runtime error state.
140
- */
141
- async dispose() {
142
- this.restartAttempts = 0;
143
- this.unavailableReason = null;
144
- await this.disposeProcess();
145
- }
146
- /**
147
- * Refreshes downstream metadata by calling tools/list after a valid initialization handshake.
148
- */
149
- async getMetadata() {
150
- return this.executeWithRecovery(async () => {
151
- await this.ensureConnected();
152
- const tools = await this.requestToolsList();
153
- return {
154
- protocolVersion: this.protocolVersion,
155
- serverInfo: this.serverInfo,
156
- tools,
157
- refreshedAt: new Date().toISOString()
158
- };
159
- });
160
- }
161
- /**
162
- * Lists tools exposed by the downstream service.
163
- */
164
- async listTools() {
165
- return this.executeWithRecovery(async () => {
166
- await this.ensureConnected();
167
- return this.requestToolsList();
168
- });
169
- }
170
- /**
171
- * Calls one downstream tool with the provided arguments.
172
- */
173
- async callTool(name, args) {
174
- return this.executeWithRecovery(async () => {
175
- await this.ensureConnected();
176
- return this.request("tools/call", {
177
- name,
178
- arguments: args
179
- });
180
- });
181
- }
182
- /**
183
- * Lists tools without applying an extra recovery loop.
184
- */
185
- async requestToolsList() {
186
- const result = await this.request("tools/list", {});
187
- if (!isRecord(result) || !Array.isArray(result.tools)) {
188
- throw new Error(`Downstream service '${this.key}' returned an invalid tools/list payload.`);
189
- }
190
- return result.tools.map((tool) => normalizeToolDefinition(this.key, tool));
191
- }
192
- /**
193
- * Runs one downstream operation with bounded restart recovery for transport failures.
194
- */
195
- async executeWithRecovery(operation) {
196
- while (true) {
197
- if (this.unavailableReason) {
198
- throw new Error(this.unavailableReason);
199
- }
200
- try {
201
- const result = await operation();
202
- return result;
203
- }
204
- catch (error) {
205
- const normalizedError = normalizeError(error);
206
- if (normalizedError instanceof DownstreamRpcError) {
207
- throw normalizedError;
208
- }
209
- const canRetry = await this.tryRestart(normalizedError);
210
- if (!canRetry) {
211
- throw new Error(this.unavailableReason ?? normalizedError.message);
212
- }
213
- }
214
- }
215
- }
216
- /**
217
- * Attempts to restart the downstream service after a transport-level failure.
218
- */
219
- async tryRestart(error) {
220
- await this.disposeProcess();
221
- if (this.restartAttempts >= MAX_RESTART_ATTEMPTS) {
222
- this.unavailableReason = `Service '${this.key}' is unavailable after ${MAX_RESTART_ATTEMPTS} restart attempts. Last error: ${error.message}`;
223
- this.logger.error("downstream.unavailable", {
224
- serviceId: this.key,
225
- attempts: this.restartAttempts,
226
- message: error.message
227
- });
228
- return false;
229
- }
230
- this.restartAttempts += 1;
231
- this.logger.warn("downstream.restart_attempt", {
232
- serviceId: this.key,
233
- attempt: this.restartAttempts,
234
- message: error.message
235
- });
236
- return true;
237
- }
238
- /**
239
- * Starts the configured child process and wires protocol handlers.
240
- */
241
- async startProcess(framingMode) {
242
- if (this.child) {
243
- return;
244
- }
245
- const transport = requireStdioTransport(this.service);
246
- const cwd = transport.cwd ? resolve(transport.cwd) : process.cwd();
13
+ const transport = requireStdioTransport(service);
247
14
  const commandSpec = resolveCommandSpec(transport.command, transport.args ?? []);
248
- const child = spawn(commandSpec.command, commandSpec.args, {
249
- cwd,
250
- env: {
251
- ...process.env,
252
- ...transport.env
253
- },
254
- stdio: "pipe",
255
- windowsHide: true
256
- });
257
- this.child = child;
258
- this.writer = createMessageWriter(child.stdin, framingMode);
259
- const reader = createMessageReader(child.stdout, transport.framing ?? "auto");
260
- reader.on("message", (message) => this.handleMessage(message));
261
- reader.on("error", (error) => this.failAllPending(new Error(`Protocol error from ${this.key}: ${String(error)}`)));
262
- child.on("error", (error) => {
263
- this.initialized = false;
264
- this.child = null;
265
- this.writer = null;
266
- this.failAllPending(error);
267
- });
268
- child.stderr.on("data", (chunk) => {
269
- const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
270
- this.logger.warn("downstream.stderr", {
271
- serviceId: this.key,
272
- message: text.trim()
273
- });
274
- });
275
- child.on("close", (code, signal) => {
276
- this.initialized = false;
277
- this.child = null;
278
- this.writer = null;
279
- this.failAllPending(new Error(`Downstream service '${this.key}' exited with code=${String(code)} signal=${String(signal)}.`));
280
- });
281
- }
282
- /**
283
- * Stops the current downstream process without resetting terminal unavailability state.
284
- */
285
- async disposeProcess() {
286
- for (const pending of this.pending.values()) {
287
- pending.reject(new Error("The downstream client was disposed."));
288
- }
289
- this.pending.clear();
290
- this.initialized = false;
291
- if (!this.child) {
292
- return;
293
- }
294
- const child = this.child;
295
- this.child = null;
296
- this.writer = null;
297
- terminateChildProcess(child);
298
- await waitForChildExit(child);
299
- cleanupChildProcess(child);
300
- }
301
- /**
302
- * Performs the MCP initialization handshake once per process lifecycle.
303
- */
304
- async initialize() {
305
- const result = await this.request("initialize", {
306
- protocolVersion: "2025-06-18",
307
- capabilities: {
308
- tools: {}
309
- },
310
- clientInfo: {
311
- name: "mcp-gateway",
312
- version: VERSION
313
- }
314
- });
315
- if (isRecord(result)) {
316
- this.protocolVersion = typeof result.protocolVersion === "string" ? result.protocolVersion : null;
317
- this.serverInfo = isRecord(result.serverInfo) ? result.serverInfo : null;
318
- }
319
- else {
320
- this.protocolVersion = null;
321
- this.serverInfo = null;
322
- }
323
- this.initialized = true;
324
- this.notify("notifications/initialized", {});
325
- }
326
- /**
327
- * Sends one JSON-RPC request and waits for the correlated response.
328
- */
329
- async request(method, params) {
330
- if (!this.writer) {
331
- throw new Error(`Downstream service '${this.key}' is not connected.`);
332
- }
333
- const id = this.nextId++;
334
- const request = {
335
- jsonrpc: "2.0",
336
- id,
337
- method,
338
- params
339
- };
340
- const responsePromise = new Promise((resolveResponse, rejectResponse) => {
341
- const timer = setTimeout(() => {
342
- this.pending.delete(id);
343
- rejectResponse(new Error(`Downstream request '${method}' timed out after ${DEFAULT_REQUEST_TIMEOUT_MS}ms for '${this.key}'.`));
344
- }, DEFAULT_REQUEST_TIMEOUT_MS);
345
- this.pending.set(id, {
346
- resolve: (result) => {
347
- clearTimeout(timer);
348
- resolveResponse(result);
349
- },
350
- reject: (error) => {
351
- clearTimeout(timer);
352
- rejectResponse(error);
353
- }
354
- });
355
- });
356
- this.writer.write(request);
357
- return responsePromise;
358
- }
359
- /**
360
- * Sends one fire-and-forget JSON-RPC notification.
361
- */
362
- notify(method, params) {
363
- this.writer?.write({
364
- jsonrpc: "2.0",
365
- method,
366
- params
367
- });
368
- }
369
- /**
370
- * Routes one inbound response to the matching pending request.
371
- */
372
- handleMessage(message) {
373
- if (!("id" in message) || message.id === null) {
374
- return;
375
- }
376
- const pending = this.pending.get(message.id);
377
- if (!pending) {
378
- return;
379
- }
380
- this.pending.delete(message.id);
381
- if ("error" in message) {
382
- const failure = message;
383
- pending.reject(new DownstreamRpcError(failure.error.message));
384
- return;
385
- }
386
- const success = message;
387
- pending.resolve(success.result);
388
- }
389
- /**
390
- * Rejects all pending requests after a transport-level failure.
391
- */
392
- failAllPending(error) {
393
- for (const pending of this.pending.values()) {
394
- pending.reject(error);
395
- }
396
- this.pending.clear();
397
- }
398
- }
399
- /**
400
- * Marks a downstream JSON-RPC error response so it is not treated as a transport failure.
401
- */
402
- class DownstreamRpcError extends Error {
403
- }
404
- /**
405
- * Normalizes one raw downstream tool definition.
406
- */
407
- function normalizeToolDefinition(clientKey, input) {
408
- if (!isRecord(input)) {
409
- throw new Error(`Downstream tool definition from '${clientKey}' must be an object.`);
410
- }
411
- if (typeof input.name !== "string" || input.name.trim() === "") {
412
- throw new Error(`Downstream tool definition from '${clientKey}' is missing a valid name.`);
15
+ const cwd = transport.cwd ? resolve(transport.cwd) : process.cwd();
16
+ const environment = mergeEnvironment(transport.env);
17
+ super(service, logger, () => createStandardTransport(commandSpec.command, commandSpec.args, cwd, environment, logger, service.serviceId));
413
18
  }
414
- return {
415
- name: input.name,
416
- description: typeof input.description === "string" ? input.description : undefined,
417
- inputSchema: isRecord(input.inputSchema) ? input.inputSchema : undefined,
418
- outputSchema: isRecord(input.outputSchema) ? input.outputSchema : null
419
- };
420
19
  }
421
20
  /**
422
- * Normalizes unknown thrown values into Error instances.
21
+ * Creates the SDK's standards-compliant newline-delimited stdio transport.
423
22
  */
424
- function normalizeError(error) {
425
- if (error instanceof Error) {
426
- return error;
427
- }
428
- return new Error(String(error));
23
+ function createStandardTransport(command, args, cwd, env, logger, serviceId) {
24
+ const transport = new StdioClientTransport({
25
+ command,
26
+ args,
27
+ cwd,
28
+ env,
29
+ stderr: "pipe"
30
+ });
31
+ transport.stderr?.on("data", (chunk) => {
32
+ const message = (typeof chunk === "string" ? chunk : chunk.toString("utf8")).trim();
33
+ if (message) {
34
+ logger.warn("downstream.stderr", { serviceId, message });
35
+ }
36
+ });
37
+ return transport;
429
38
  }
430
39
  /**
431
40
  * Resolves a configured command into a directly spawnable executable on Windows.
432
41
  */
433
42
  function resolveCommandSpec(command, args) {
434
- if (process.platform !== "win32") {
43
+ if (process.platform !== "win32" || /[\\/]/.test(command) || /\.[A-Za-z0-9]+$/.test(command)) {
435
44
  return { command, args };
436
45
  }
437
- if (/[\\/]/.test(command) || /\.[A-Za-z0-9]+$/.test(command)) {
46
+ const resolved = resolveViaPowerShell(command) ?? resolveViaWhere(command);
47
+ if (!resolved) {
438
48
  return { command, args };
439
49
  }
440
- const powershellResolved = resolveViaPowerShell(command);
441
- if (powershellResolved) {
442
- if (powershellResolved.toLowerCase().endsWith(".ps1")) {
443
- const powerShellHost = resolvePowerShellHost();
444
- if (!powerShellHost) {
445
- return { command, args };
446
- }
447
- return {
448
- command: powerShellHost,
449
- args: ["-File", powershellResolved, ...args]
450
- };
451
- }
452
- return {
453
- command: powershellResolved,
454
- args
455
- };
456
- }
457
- try {
458
- const output = execFileSync("where.exe", [command], {
459
- encoding: "utf8",
460
- stdio: ["ignore", "pipe", "ignore"]
461
- });
462
- const candidates = output
463
- .split(/\r?\n/)
464
- .map((line) => line.trim())
465
- .filter((line) => line.length > 0);
466
- const preferred = candidates.find((candidate) => !candidate.toLowerCase().endsWith(".ps1")) ?? candidates[0];
467
- if (!preferred) {
468
- return { command, args };
469
- }
470
- if (preferred.toLowerCase().endsWith(".ps1")) {
471
- const powerShellHost = resolvePowerShellHost();
472
- if (!powerShellHost) {
473
- return { command, args };
474
- }
475
- return {
476
- command: powerShellHost,
477
- args: ["-File", preferred, ...args]
478
- };
479
- }
480
- return {
481
- command: preferred,
482
- args
483
- };
484
- }
485
- catch {
486
- return { command, args };
50
+ if (resolved.toLowerCase().endsWith(".ps1")) {
51
+ const host = resolvePowerShellHost();
52
+ return host ? { command: host, args: ["-File", resolved, ...args] } : { command, args };
487
53
  }
54
+ return { command: resolved, args };
488
55
  }
489
56
  /**
490
57
  * Resolves a command name through PowerShell so script shims map to their real targets.
491
58
  */
492
59
  function resolveViaPowerShell(command) {
493
- const powerShellHost = resolvePowerShellHost();
494
- if (!powerShellHost) {
60
+ const host = resolvePowerShellHost();
61
+ if (!host) {
495
62
  return null;
496
63
  }
497
64
  try {
498
- const output = execFileSync(powerShellHost, [
65
+ const output = execFileSync(host, [
499
66
  "-NoProfile",
500
67
  "-Command",
501
- `(Get-Command '${escapePowerShellSingleQuotedString(command)}' -ErrorAction Stop).Source`
502
- ], {
503
- encoding: "utf8",
504
- stdio: ["ignore", "pipe", "ignore"]
505
- });
506
- const resolved = output.trim();
507
- return resolved.length > 0 ? resolved : null;
68
+ `(Get-Command '${command.replace(/'/g, "''")}' -ErrorAction Stop).Source`
69
+ ], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
70
+ return output.trim() || null;
508
71
  }
509
72
  catch {
510
73
  return null;
511
74
  }
512
75
  }
513
76
  /**
514
- * Narrows a service config to its stdio transport.
77
+ * Resolves an executable through the Windows where command.
515
78
  */
516
- function requireStdioTransport(service) {
517
- if (service.transport.type !== "stdio") {
518
- throw new Error(`Unsupported transport '${String(service.transport.type)}'.`);
79
+ function resolveViaWhere(command) {
80
+ try {
81
+ const output = execFileSync("where.exe", [command], {
82
+ encoding: "utf8",
83
+ stdio: ["ignore", "pipe", "ignore"]
84
+ });
85
+ return output.split(/\r?\n/).map((line) => line.trim()).find((line) => line && !line.toLowerCase().endsWith(".ps1")) ?? null;
86
+ }
87
+ catch {
88
+ return null;
519
89
  }
520
- return service.transport;
521
90
  }
522
91
  /**
523
92
  * Resolves the preferred PowerShell host on Windows.
@@ -532,19 +101,11 @@ export function resolvePowerShellHost(probe = commandExists) {
532
101
  return null;
533
102
  }
534
103
  /**
535
- * Escapes a string for use inside a single-quoted PowerShell literal.
536
- */
537
- function escapePowerShellSingleQuotedString(value) {
538
- return value.replace(/'/g, "''");
539
- }
540
- /**
541
- * Checks whether a command exists in the current PATH.
104
+ * Checks whether one command exists on the current PATH.
542
105
  */
543
106
  function commandExists(command) {
544
107
  try {
545
- execFileSync("where.exe", [command], {
546
- stdio: ["ignore", "ignore", "ignore"]
547
- });
108
+ execFileSync("where.exe", [command], { stdio: ["ignore", "ignore", "ignore"] });
548
109
  return true;
549
110
  }
550
111
  catch {
@@ -552,85 +113,18 @@ function commandExists(command) {
552
113
  }
553
114
  }
554
115
  /**
555
- * Terminates one child process, using process-tree shutdown on Windows when possible.
556
- */
557
- function terminateChildProcess(child) {
558
- if (process.platform === "win32" && child.pid) {
559
- try {
560
- execFileSync("taskkill.exe", ["/PID", String(child.pid), "/T", "/F"], {
561
- stdio: ["ignore", "ignore", "ignore"]
562
- });
563
- return;
564
- }
565
- catch {
566
- /**
567
- * Falls back to normal child termination when taskkill fails.
568
- */
569
- }
570
- }
571
- try {
572
- child.kill();
573
- }
574
- catch {
575
- /**
576
- * Ignores kill failures because the process may have already exited.
577
- */
578
- }
579
- }
580
- /**
581
- * Waits for one child process to exit and force-kills it if graceful shutdown stalls.
116
+ * Narrows a service config to stdio.
582
117
  */
583
- async function waitForChildExit(child) {
584
- if (child.exitCode !== null || child.signalCode !== null) {
585
- return;
586
- }
587
- await new Promise((resolveClose) => {
588
- let settled = false;
589
- const finish = () => {
590
- if (settled) {
591
- return;
592
- }
593
- settled = true;
594
- clearTimeout(timer);
595
- child.removeListener("close", onClose);
596
- resolveClose();
597
- };
598
- const onClose = () => finish();
599
- const timer = setTimeout(() => {
600
- try {
601
- child.kill("SIGKILL");
602
- }
603
- catch {
604
- /**
605
- * Ignores force-kill failures because the process may already be exiting.
606
- */
607
- }
608
- finish();
609
- }, PROCESS_EXIT_TIMEOUT_MS);
610
- child.once("close", onClose);
611
- });
612
- }
613
- /**
614
- * Releases child process stdio resources after the process exits.
615
- */
616
- function cleanupChildProcess(child) {
617
- child.removeAllListeners();
618
- child.stdin.removeAllListeners();
619
- child.stdout.removeAllListeners();
620
- child.stderr.removeAllListeners();
621
- if (!child.stdin.destroyed) {
622
- child.stdin.destroy();
623
- }
624
- if (!child.stdout.destroyed) {
625
- child.stdout.destroy();
626
- }
627
- if (!child.stderr.destroyed) {
628
- child.stderr.destroy();
118
+ function requireStdioTransport(service) {
119
+ if (service.transport.type !== "stdio") {
120
+ throw new Error(`Unsupported transport '${String(service.transport.type)}'.`);
629
121
  }
122
+ return service.transport;
630
123
  }
631
124
  /**
632
- * Checks whether a value is a plain object record.
125
+ * Merges configured values into the current process environment without undefined entries.
633
126
  */
634
- function isRecord(input) {
635
- return typeof input === "object" && input !== null && !Array.isArray(input);
127
+ function mergeEnvironment(overrides) {
128
+ const inherited = Object.fromEntries(Object.entries(process.env).filter((entry) => entry[1] !== undefined));
129
+ return { ...inherited, ...overrides };
636
130
  }