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