@jadchene/mcp-gateway-service 0.3.4 → 0.4.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.
@@ -0,0 +1,492 @@
1
+ import { VERSION } from "../version.js";
2
+ const DEFAULT_REQUEST_TIMEOUT_MS = 10_000;
3
+ /**
4
+ * Provides one reusable Streamable HTTP-backed MCP client for a downstream service.
5
+ */
6
+ export class StreamableHttpClient {
7
+ /**
8
+ * Stores the bound service config.
9
+ */
10
+ service;
11
+ /**
12
+ * Stores the shared logger instance.
13
+ */
14
+ logger;
15
+ /**
16
+ * Stores pending request resolvers keyed by request id.
17
+ */
18
+ pending = new Map();
19
+ /**
20
+ * Stores the active stream abort controller.
21
+ */
22
+ streamAbort = null;
23
+ /**
24
+ * Stores a promise for the current connection attempt.
25
+ */
26
+ connectPromise = null;
27
+ /**
28
+ * Tracks whether downstream initialization succeeded.
29
+ */
30
+ initialized = false;
31
+ /**
32
+ * Stores the endpoint used for POST messages after the SSE handshake.
33
+ */
34
+ messageEndpoint = null;
35
+ /**
36
+ * Stores the session id returned by the downstream stream endpoint.
37
+ */
38
+ sessionId = null;
39
+ /**
40
+ * Stores the next request id used for downstream calls.
41
+ */
42
+ nextId = 1;
43
+ /**
44
+ * Stores the downstream server info captured during initialization.
45
+ */
46
+ serverInfo = null;
47
+ /**
48
+ * Stores the downstream protocol version captured during initialization.
49
+ */
50
+ protocolVersion = null;
51
+ /**
52
+ * Counts reconnect attempts after transport-level failures.
53
+ */
54
+ restartAttempts = 0;
55
+ /**
56
+ * Stores the terminal unavailability reason.
57
+ */
58
+ unavailableReason = null;
59
+ /**
60
+ * Creates a client for one Streamable HTTP downstream service.
61
+ */
62
+ constructor(service, logger) {
63
+ this.service = service;
64
+ this.logger = logger;
65
+ }
66
+ /**
67
+ * Returns a stable key for logs.
68
+ */
69
+ get key() {
70
+ return this.service.serviceId;
71
+ }
72
+ /**
73
+ * Indicates whether the service has become unavailable after recovery exhaustion.
74
+ */
75
+ get isUnavailable() {
76
+ return this.unavailableReason !== null;
77
+ }
78
+ /**
79
+ * Returns the terminal unavailability reason when one exists.
80
+ */
81
+ get unavailableMessage() {
82
+ return this.unavailableReason;
83
+ }
84
+ /**
85
+ * Returns the restart attempts consumed by the current lifecycle.
86
+ */
87
+ get restartCount() {
88
+ return this.restartAttempts;
89
+ }
90
+ /**
91
+ * Checks whether the current client still matches a desired service config.
92
+ */
93
+ matchesConfig(service) {
94
+ return JSON.stringify(this.service) === JSON.stringify(service);
95
+ }
96
+ /**
97
+ * Ensures that the downstream HTTP stream is connected and initialized.
98
+ */
99
+ async ensureConnected() {
100
+ if (this.unavailableReason) {
101
+ throw new Error(this.unavailableReason);
102
+ }
103
+ if (this.initialized) {
104
+ return;
105
+ }
106
+ const transport = requireHttpTransport(this.service);
107
+ if (transport.enableJsonResponse) {
108
+ this.messageEndpoint = transport.url;
109
+ await this.initialize();
110
+ return;
111
+ }
112
+ if (!this.connectPromise) {
113
+ this.connectPromise = this.connectStream().finally(() => {
114
+ this.connectPromise = null;
115
+ });
116
+ }
117
+ await this.connectPromise;
118
+ await this.initialize();
119
+ }
120
+ /**
121
+ * Stops the downstream HTTP stream and clears runtime error state.
122
+ */
123
+ async dispose() {
124
+ this.restartAttempts = 0;
125
+ this.unavailableReason = null;
126
+ this.initialized = false;
127
+ this.messageEndpoint = null;
128
+ this.sessionId = null;
129
+ this.streamAbort?.abort();
130
+ this.streamAbort = null;
131
+ this.failAllPending(new Error("The downstream HTTP client was disposed."));
132
+ }
133
+ /**
134
+ * Refreshes downstream metadata.
135
+ */
136
+ async getMetadata() {
137
+ return this.executeWithRecovery(async () => {
138
+ await this.ensureConnected();
139
+ const tools = await this.requestToolsList();
140
+ return {
141
+ protocolVersion: this.protocolVersion,
142
+ serverInfo: this.serverInfo,
143
+ tools,
144
+ refreshedAt: new Date().toISOString()
145
+ };
146
+ });
147
+ }
148
+ /**
149
+ * Lists tools exposed by the downstream service.
150
+ */
151
+ async listTools() {
152
+ return this.executeWithRecovery(async () => {
153
+ await this.ensureConnected();
154
+ return this.requestToolsList();
155
+ });
156
+ }
157
+ /**
158
+ * Calls one downstream tool with the provided arguments.
159
+ */
160
+ async callTool(name, args) {
161
+ return this.executeWithRecovery(async () => {
162
+ await this.ensureConnected();
163
+ return this.request("tools/call", {
164
+ name,
165
+ arguments: args
166
+ });
167
+ });
168
+ }
169
+ /**
170
+ * Opens the SSE read channel and waits for the endpoint event.
171
+ */
172
+ async connectStream() {
173
+ const transport = requireHttpTransport(this.service);
174
+ this.streamAbort?.abort();
175
+ this.streamAbort = new AbortController();
176
+ this.messageEndpoint = null;
177
+ this.sessionId = null;
178
+ const response = await fetch(transport.url, {
179
+ method: "GET",
180
+ headers: {
181
+ Accept: "text/event-stream",
182
+ ...transport.headers
183
+ },
184
+ signal: this.streamAbort.signal
185
+ });
186
+ if (!response.ok || !response.body) {
187
+ throw new Error(`Streamable HTTP GET failed for '${this.key}' with status ${response.status}.`);
188
+ }
189
+ this.sessionId = response.headers.get("mcp-session-id") ?? response.headers.get("Mcp-Session-Id");
190
+ void this.readEventStream(response.body).catch((error) => {
191
+ if (this.streamAbort?.signal.aborted) {
192
+ return;
193
+ }
194
+ const message = error instanceof Error ? error.message : String(error);
195
+ this.logger.warn("downstream.http_stream_failed", {
196
+ serviceId: this.key,
197
+ message
198
+ });
199
+ this.initialized = false;
200
+ this.messageEndpoint = null;
201
+ this.failAllPending(new Error(message));
202
+ });
203
+ await waitUntil(() => this.messageEndpoint !== null, DEFAULT_REQUEST_TIMEOUT_MS, `Timed out waiting for Streamable HTTP endpoint event from '${this.key}'.`);
204
+ }
205
+ /**
206
+ * Performs the MCP initialization handshake once per stream lifecycle.
207
+ */
208
+ async initialize() {
209
+ const result = await this.request("initialize", {
210
+ protocolVersion: "2025-06-18",
211
+ capabilities: {
212
+ tools: {}
213
+ },
214
+ clientInfo: {
215
+ name: "mcp-gateway",
216
+ version: VERSION
217
+ }
218
+ });
219
+ if (isRecord(result)) {
220
+ this.protocolVersion = typeof result.protocolVersion === "string" ? result.protocolVersion : null;
221
+ this.serverInfo = isRecord(result.serverInfo) ? result.serverInfo : null;
222
+ }
223
+ else {
224
+ this.protocolVersion = null;
225
+ this.serverInfo = null;
226
+ }
227
+ this.initialized = true;
228
+ void this.postMessage({
229
+ jsonrpc: "2.0",
230
+ method: "notifications/initialized",
231
+ params: {}
232
+ });
233
+ }
234
+ /**
235
+ * Lists tools without applying an extra recovery loop.
236
+ */
237
+ async requestToolsList() {
238
+ const result = await this.request("tools/list", {});
239
+ if (!isRecord(result) || !Array.isArray(result.tools)) {
240
+ throw new Error(`Downstream service '${this.key}' returned an invalid tools/list payload.`);
241
+ }
242
+ return result.tools.map((tool) => normalizeToolDefinition(this.key, tool));
243
+ }
244
+ /**
245
+ * Runs one downstream operation with one reconnect attempt for transport failures.
246
+ */
247
+ async executeWithRecovery(operation) {
248
+ try {
249
+ return await operation();
250
+ }
251
+ catch (error) {
252
+ const normalizedError = normalizeError(error);
253
+ if (normalizedError instanceof DownstreamRpcError) {
254
+ throw normalizedError;
255
+ }
256
+ const nextRestartAttempts = this.restartAttempts + 1;
257
+ await this.dispose();
258
+ this.restartAttempts = nextRestartAttempts;
259
+ this.unavailableReason = null;
260
+ this.logger.warn("downstream.http_reconnect_attempt", {
261
+ serviceId: this.key,
262
+ attempt: this.restartAttempts,
263
+ message: normalizedError.message
264
+ });
265
+ return operation();
266
+ }
267
+ }
268
+ /**
269
+ * Sends one JSON-RPC request and waits for the correlated response.
270
+ */
271
+ async request(method, params) {
272
+ const id = this.nextId++;
273
+ const request = {
274
+ jsonrpc: "2.0",
275
+ id,
276
+ method,
277
+ params
278
+ };
279
+ const responsePromise = new Promise((resolveResponse, rejectResponse) => {
280
+ const timer = setTimeout(() => {
281
+ this.pending.delete(id);
282
+ rejectResponse(new Error(`Downstream request '${method}' timed out after ${DEFAULT_REQUEST_TIMEOUT_MS}ms for '${this.key}'.`));
283
+ }, DEFAULT_REQUEST_TIMEOUT_MS);
284
+ this.pending.set(id, {
285
+ resolve: (result) => {
286
+ clearTimeout(timer);
287
+ resolveResponse(result);
288
+ },
289
+ reject: (error) => {
290
+ clearTimeout(timer);
291
+ rejectResponse(error);
292
+ }
293
+ });
294
+ });
295
+ try {
296
+ const directResponse = await this.postMessage(request);
297
+ if (directResponse) {
298
+ this.handleMessage(directResponse);
299
+ }
300
+ }
301
+ catch (error) {
302
+ this.pending.delete(id);
303
+ throw error;
304
+ }
305
+ return responsePromise;
306
+ }
307
+ /**
308
+ * Sends one JSON-RPC message to the current POST endpoint.
309
+ */
310
+ async postMessage(message) {
311
+ const transport = requireHttpTransport(this.service);
312
+ const endpoint = this.messageEndpoint ?? transport.url;
313
+ const response = await fetch(endpoint, {
314
+ method: "POST",
315
+ headers: {
316
+ "Content-Type": "application/json",
317
+ Accept: "application/json, text/event-stream",
318
+ ...(this.sessionId ? { "Mcp-Session-Id": this.sessionId } : {}),
319
+ ...transport.headers
320
+ },
321
+ body: JSON.stringify(message)
322
+ });
323
+ if (!response.ok) {
324
+ throw new Error(`Streamable HTTP POST failed for '${this.key}' with status ${response.status}.`);
325
+ }
326
+ const contentType = response.headers.get("content-type") ?? "";
327
+ if (transport.enableJsonResponse || contentType.includes("application/json")) {
328
+ const text = await response.text();
329
+ if (text.trim() === "") {
330
+ return null;
331
+ }
332
+ return JSON.parse(text);
333
+ }
334
+ return null;
335
+ }
336
+ /**
337
+ * Reads and dispatches Server-Sent Events from the downstream response body.
338
+ */
339
+ async readEventStream(body) {
340
+ const reader = body.getReader();
341
+ const decoder = new TextDecoder();
342
+ let buffer = "";
343
+ while (true) {
344
+ const read = await reader.read();
345
+ if (read.done) {
346
+ break;
347
+ }
348
+ buffer += decoder.decode(read.value, { stream: true });
349
+ let boundary = findSseBoundary(buffer);
350
+ while (boundary >= 0) {
351
+ const rawEvent = buffer.slice(0, boundary);
352
+ buffer = buffer.slice(skipSseBoundary(buffer, boundary));
353
+ this.handleSseEvent(rawEvent);
354
+ boundary = findSseBoundary(buffer);
355
+ }
356
+ }
357
+ const tail = `${buffer}${decoder.decode()}`.trim();
358
+ if (tail.length > 0) {
359
+ this.handleSseEvent(tail);
360
+ }
361
+ }
362
+ /**
363
+ * Parses one SSE event block and applies endpoint/message events.
364
+ */
365
+ handleSseEvent(rawEvent) {
366
+ let eventName = "message";
367
+ const dataLines = [];
368
+ for (const line of rawEvent.split(/\r?\n/)) {
369
+ if (line.startsWith("event:")) {
370
+ eventName = line.slice("event:".length).trim();
371
+ }
372
+ else if (line.startsWith("data:")) {
373
+ dataLines.push(line.slice("data:".length).trimStart());
374
+ }
375
+ }
376
+ const data = dataLines.join("\n");
377
+ if (eventName === "endpoint") {
378
+ this.messageEndpoint = new URL(data, requireHttpTransport(this.service).url).toString();
379
+ return;
380
+ }
381
+ if (eventName === "message" && data.trim() !== "") {
382
+ this.handleMessage(JSON.parse(data));
383
+ }
384
+ }
385
+ /**
386
+ * Routes one inbound response to the matching pending request.
387
+ */
388
+ handleMessage(message) {
389
+ if (!("id" in message) || message.id === null) {
390
+ return;
391
+ }
392
+ const pending = this.pending.get(message.id);
393
+ if (!pending) {
394
+ return;
395
+ }
396
+ this.pending.delete(message.id);
397
+ if ("error" in message) {
398
+ const failure = message;
399
+ pending.reject(new DownstreamRpcError(failure.error.message));
400
+ return;
401
+ }
402
+ const success = message;
403
+ pending.resolve(success.result);
404
+ }
405
+ /**
406
+ * Rejects all pending requests after a transport-level failure.
407
+ */
408
+ failAllPending(error) {
409
+ for (const pending of this.pending.values()) {
410
+ pending.reject(error);
411
+ }
412
+ this.pending.clear();
413
+ }
414
+ }
415
+ /**
416
+ * Marks a downstream JSON-RPC error response so it is not treated as a transport failure.
417
+ */
418
+ class DownstreamRpcError extends Error {
419
+ }
420
+ /**
421
+ * Narrows a service config to its HTTP transport.
422
+ */
423
+ function requireHttpTransport(service) {
424
+ if (service.transport.type !== "http") {
425
+ throw new Error(`Unsupported transport '${String(service.transport.type)}'.`);
426
+ }
427
+ return service.transport;
428
+ }
429
+ /**
430
+ * Normalizes one raw downstream tool definition.
431
+ */
432
+ function normalizeToolDefinition(clientKey, input) {
433
+ if (!isRecord(input)) {
434
+ throw new Error(`Downstream tool definition from '${clientKey}' must be an object.`);
435
+ }
436
+ if (typeof input.name !== "string" || input.name.trim() === "") {
437
+ throw new Error(`Downstream tool definition from '${clientKey}' is missing a valid name.`);
438
+ }
439
+ return {
440
+ name: input.name,
441
+ description: typeof input.description === "string" ? input.description : undefined,
442
+ inputSchema: isRecord(input.inputSchema) ? input.inputSchema : undefined,
443
+ outputSchema: isRecord(input.outputSchema) ? input.outputSchema : null
444
+ };
445
+ }
446
+ /**
447
+ * Normalizes unknown thrown values into Error instances.
448
+ */
449
+ function normalizeError(error) {
450
+ if (error instanceof Error) {
451
+ return error;
452
+ }
453
+ return new Error(String(error));
454
+ }
455
+ /**
456
+ * Polls until a condition is met or a timeout is reached.
457
+ */
458
+ async function waitUntil(condition, timeoutMs, timeoutMessage) {
459
+ const startedAt = Date.now();
460
+ while (!condition()) {
461
+ if (Date.now() - startedAt > timeoutMs) {
462
+ throw new Error(timeoutMessage);
463
+ }
464
+ await new Promise((resolve) => setTimeout(resolve, 10));
465
+ }
466
+ }
467
+ /**
468
+ * Checks whether a value is a plain object record.
469
+ */
470
+ function isRecord(input) {
471
+ return typeof input === "object" && input !== null && !Array.isArray(input);
472
+ }
473
+ /**
474
+ * Finds the next SSE event separator for LF or CRLF streams.
475
+ */
476
+ function findSseBoundary(input) {
477
+ const lf = input.indexOf("\n\n");
478
+ const crlf = input.indexOf("\r\n\r\n");
479
+ if (lf < 0) {
480
+ return crlf;
481
+ }
482
+ if (crlf < 0) {
483
+ return lf;
484
+ }
485
+ return Math.min(lf, crlf);
486
+ }
487
+ /**
488
+ * Returns the index after the detected SSE separator.
489
+ */
490
+ function skipSseBoundary(input, boundary) {
491
+ return input.startsWith("\r\n\r\n", boundary) ? boundary + 4 : boundary + 2;
492
+ }
@@ -1,6 +1,7 @@
1
1
  import { readFile, writeFile } from "node:fs/promises";
2
2
  import { resolve } from "node:path";
3
3
  import { StdioMcpClient } from "./mcp/client.js";
4
+ import { StreamableHttpClient } from "./mcp/http-client.js";
4
5
  /**
5
6
  * Maintains the active service pool, client instances, and cached metadata.
6
7
  */
@@ -179,7 +180,7 @@ export class ServiceRegistry {
179
180
  if (!currentClient) {
180
181
  throw new Error(`Service '${serviceId}' is unavailable.`);
181
182
  }
182
- const nextClient = new StdioMcpClient(snapshot.config, this.logger);
183
+ const nextClient = createClient(snapshot.config, this.logger);
183
184
  try {
184
185
  await currentClient.dispose().catch(() => undefined);
185
186
  const metadata = await nextClient.getMetadata();
@@ -245,7 +246,7 @@ export class ServiceRegistry {
245
246
  const reusedClient = this.clients.get(service.serviceId);
246
247
  const client = reusedClient && reusedClient.matchesConfig(service)
247
248
  ? reusedClient
248
- : new StdioMcpClient(service, this.logger);
249
+ : createClient(service, this.logger);
249
250
  nextClients.set(service.serviceId, client);
250
251
  let metadata = {
251
252
  protocolVersion: null,
@@ -339,6 +340,19 @@ async function disposeRemovedClients(previous, next) {
339
340
  }
340
341
  await Promise.all(removed.map((client) => client.dispose().catch(() => undefined)));
341
342
  }
343
+ /**
344
+ * Creates a downstream client implementation for one service config.
345
+ */
346
+ function createClient(service, logger) {
347
+ switch (service.transport.type) {
348
+ case "stdio":
349
+ return new StdioMcpClient(service, logger);
350
+ case "http":
351
+ return new StreamableHttpClient(service, logger);
352
+ default:
353
+ throw new Error(`Unsupported transport '${String(service.transport.type)}'.`);
354
+ }
355
+ }
342
356
  /**
343
357
  * Loads the raw config document for management edits that must preserve disabled services.
344
358
  */
package/package.json CHANGED
@@ -1,15 +1,23 @@
1
1
  {
2
2
  "name": "@jadchene/mcp-gateway-service",
3
- "version": "0.3.4",
3
+ "version": "0.4.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",
7
7
  "bin": {
8
8
  "mcp-gateway-service": "dist/index.js"
9
9
  },
10
- "license": "MIT",
11
- "author": "jadchene",
12
- "scripts": {
10
+ "license": "MIT",
11
+ "author": "jadchene",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/jadchene/mcp-gateway.git"
15
+ },
16
+ "homepage": "https://github.com/jadchene/mcp-gateway#readme",
17
+ "bugs": {
18
+ "url": "https://github.com/jadchene/mcp-gateway/issues"
19
+ },
20
+ "scripts": {
13
21
  "build": "tsc -p tsconfig.build.json",
14
22
  "dev": "node --experimental-strip-types src/index.ts",
15
23
  "start": "node dist/index.js",