@jadchene/mcp-gateway-service 0.3.4 → 0.4.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,12 +1,13 @@
1
- import { createMessageReader, createMessageWriter, jsonRpcError, jsonRpcResult } from "./mcp/protocol.js";
1
+ import { McpGatewayEngine } from "./gateway-engine.js";
2
+ import { createMessageReader, createMessageWriter } from "./mcp/protocol.js";
2
3
  /**
3
4
  * Exposes the MCP gateway tools over stdio.
4
5
  */
5
6
  export class GatewayServer {
6
7
  /**
7
- * Stores the registry used for metadata lookup and routing.
8
+ * Stores the transport-neutral gateway engine.
8
9
  */
9
- registry;
10
+ engine;
10
11
  /**
11
12
  * Stores the shared logger instance.
12
13
  */
@@ -20,21 +21,17 @@ export class GatewayServer {
20
21
  */
21
22
  writer = createMessageWriter(process.stdout);
22
23
  /**
23
- * Stores the startup barrier that must resolve before gateway tools can use the registry.
24
+ * Creates the stdio gateway server.
24
25
  */
25
- startupBarrier = Promise.resolve();
26
- /**
27
- * Creates the gateway server.
28
- */
29
- constructor(registry, logger) {
30
- this.registry = registry;
26
+ constructor(registry, logger, engine = new McpGatewayEngine(registry, logger)) {
27
+ this.engine = engine;
31
28
  this.logger = logger;
32
29
  }
33
30
  /**
34
31
  * Sets the startup barrier used to delay tool handling until the registry is ready.
35
32
  */
36
33
  setStartupBarrier(barrier) {
37
- this.startupBarrier = barrier;
34
+ this.engine.setStartupBarrier(barrier);
38
35
  }
39
36
  /**
40
37
  * Starts consuming inbound MCP messages from stdin.
@@ -45,10 +42,7 @@ export class GatewayServer {
45
42
  if (framingMode) {
46
43
  this.writer.setFramingMode(framingMode);
47
44
  }
48
- if (!isJsonRpcRequest(message)) {
49
- return;
50
- }
51
- void this.handleRequest(message);
45
+ void this.handleMessage(message);
52
46
  });
53
47
  this.reader.on("error", (error) => {
54
48
  this.logger.error("gateway.protocol_error", {
@@ -57,290 +51,12 @@ export class GatewayServer {
57
51
  });
58
52
  }
59
53
  /**
60
- * Handles one inbound JSON-RPC request.
61
- */
62
- async handleRequest(request) {
63
- try {
64
- if (request.method === "initialize") {
65
- this.writer.write(jsonRpcResult(request.id, this.buildInitializeResult()));
66
- return;
67
- }
68
- if (request.method === "ping") {
69
- this.writer.write(jsonRpcResult(request.id, {}));
70
- return;
71
- }
72
- if (request.method === "tools/list") {
73
- this.writer.write(jsonRpcResult(request.id, { tools: buildGatewayTools() }));
74
- return;
75
- }
76
- if (request.method === "tools/call") {
77
- await this.startupBarrier;
78
- const result = await this.handleToolCall(request);
79
- this.writer.write(jsonRpcResult(request.id, result));
80
- return;
81
- }
82
- if (request.method === "notifications/initialized") {
83
- return;
84
- }
85
- this.writer.write(jsonRpcError(request.id, -32601, `Unsupported method '${request.method}'.`));
86
- }
87
- catch (error) {
88
- const message = error instanceof Error ? error.message : String(error);
89
- this.logger.error("gateway.request_failed", {
90
- method: request.method,
91
- message
92
- });
93
- this.writer.write(jsonRpcError(request.id, -32000, message));
94
- }
95
- }
96
- /**
97
- * Handles one gateway tool invocation.
98
- */
99
- async handleToolCall(request) {
100
- const params = toObject(request.params, "The tools/call params must be an object.");
101
- const toolName = requireString(params.name, "The tool name must be a string.");
102
- const args = toObject(params.arguments ?? {}, "The tool arguments must be an object.");
103
- switch (toolName) {
104
- case "gateway.listServices":
105
- return successContent({
106
- services: this.registry.listServices().map(formatServiceSummary)
107
- });
108
- case "gateway.getService":
109
- return this.getService(args);
110
- case "gateway.listTools":
111
- return this.listTools(args);
112
- case "gateway.getToolSchema":
113
- return this.getToolSchema(args);
114
- case "gateway.manageService":
115
- return this.manageService(args);
116
- case "gateway.callTool":
117
- return this.callDownstreamTool(args);
118
- default:
119
- throw new Error(`Unknown gateway tool '${toolName}'.`);
120
- }
121
- }
122
- /**
123
- * Returns detailed metadata for one logical service.
124
- */
125
- getService(args) {
126
- const serviceId = requireString(args.serviceId, "The 'serviceId' argument must be a string.");
127
- const snapshot = this.registry.getService(serviceId);
128
- if (!snapshot) {
129
- throw new Error(`Unknown service '${serviceId}'.`);
130
- }
131
- return successContent({
132
- serviceId: snapshot.config.serviceId,
133
- name: snapshot.config.name,
134
- description: snapshot.config.description ?? null,
135
- available: snapshot.runtime.available,
136
- lastError: snapshot.runtime.lastError,
137
- lastConnectedAt: snapshot.runtime.lastConnectedAt,
138
- protocolVersion: snapshot.metadata.protocolVersion,
139
- serverInfo: snapshot.metadata.serverInfo
140
- });
141
- }
142
- /**
143
- * Returns tool summaries for one logical service.
144
- */
145
- listTools(args) {
146
- const serviceId = requireString(args.serviceId, "The 'serviceId' argument must be a string.");
147
- return successContent({
148
- tools: this.registry.listTools(serviceId).map((tool) => ({
149
- name: tool.name,
150
- description: tool.description ?? null
151
- }))
152
- });
153
- }
154
- /**
155
- * Returns input and output schemas for one downstream tool.
156
- */
157
- getToolSchema(args) {
158
- const serviceId = requireString(args.serviceId, "The 'serviceId' argument must be a string.");
159
- const toolName = requireString(args.toolName, "The 'toolName' argument must be a string.");
160
- const tool = this.registry.getTool(serviceId, toolName);
161
- if (!tool) {
162
- throw new Error(`Unknown tool '${toolName}' in service '${serviceId}'.`);
163
- }
164
- return successContent({
165
- inputSchema: tool.inputSchema ?? null,
166
- outputSchema: tool.outputSchema ?? null
167
- });
168
- }
169
- /**
170
- * Routes one downstream tool call through the service registry.
171
- */
172
- async callDownstreamTool(args) {
173
- const serviceId = requireString(args.serviceId, "The 'serviceId' argument must be a string.");
174
- const toolName = requireString(args.toolName, "The 'toolName' argument must be a string.");
175
- const toolArgs = toObject(args.arguments ?? {}, "The 'arguments' field must be an object.");
176
- const call = await this.registry.callTool(serviceId, toolName, toolArgs);
177
- return call.result;
178
- }
179
- /**
180
- * Applies one compact service management action.
181
- */
182
- async manageService(args) {
183
- const serviceId = requireString(args.serviceId, "The 'serviceId' argument must be a string.");
184
- const action = requireServiceAction(args.action);
185
- const result = await this.registry.manageService(serviceId, action);
186
- return successContent({
187
- serviceId: result.serviceId,
188
- action: result.action,
189
- enabled: result.enabled,
190
- available: result.available
191
- });
192
- }
193
- /**
194
- * Builds the MCP initialize result advertised by the gateway.
54
+ * Handles one inbound MCP message.
195
55
  */
196
- buildInitializeResult() {
197
- return {
198
- protocolVersion: "2025-06-18",
199
- capabilities: {
200
- tools: {
201
- listChanged: false
202
- }
203
- },
204
- serverInfo: {
205
- name: "mcp-gateway",
206
- version: "0.3.3"
207
- }
208
- };
209
- }
210
- }
211
- /**
212
- * Builds the fixed gateway tool definitions exposed to all MCP clients.
213
- */
214
- function buildGatewayTools() {
215
- return [
216
- {
217
- name: "gateway.listServices",
218
- description: "Lists all MCP services currently managed by the gateway.",
219
- inputSchema: {
220
- type: "object",
221
- properties: {},
222
- additionalProperties: false
223
- }
224
- },
225
- {
226
- name: "gateway.getService",
227
- description: "Returns one service summary, runtime state, and metadata cache details.",
228
- inputSchema: objectSchema(["serviceId"], {
229
- serviceId: stringSchema("Logical service identifier.")
230
- })
231
- },
232
- {
233
- name: "gateway.listTools",
234
- description: "Lists all tools exposed by one downstream service.",
235
- inputSchema: objectSchema(["serviceId"], {
236
- serviceId: stringSchema("Logical service identifier.")
237
- })
238
- },
239
- {
240
- name: "gateway.getToolSchema",
241
- description: "Returns the input and output schema for one downstream tool.",
242
- inputSchema: objectSchema(["serviceId", "toolName"], {
243
- serviceId: stringSchema("Logical service identifier."),
244
- toolName: stringSchema("Downstream tool name.")
245
- })
246
- },
247
- {
248
- name: "gateway.manageService",
249
- description: "Reconnects one service or updates its enabled state with a compact action.",
250
- inputSchema: objectSchema(["serviceId", "action"], {
251
- serviceId: stringSchema("Logical service identifier."),
252
- action: {
253
- type: "string",
254
- description: "Management action applied to the service.",
255
- enum: ["reconnect", "enable", "disable"]
256
- }
257
- })
258
- },
259
- {
260
- name: "gateway.callTool",
261
- description: "Calls one downstream tool through the gateway service pool.",
262
- inputSchema: objectSchema(["serviceId", "toolName", "arguments"], {
263
- serviceId: stringSchema("Logical service identifier."),
264
- toolName: stringSchema("Downstream tool name."),
265
- arguments: {
266
- type: "object",
267
- description: "Arguments passed to the downstream tool."
268
- }
269
- })
56
+ async handleMessage(message) {
57
+ const response = await this.engine.handleMessage(message);
58
+ if (response) {
59
+ this.writer.write(response);
270
60
  }
271
- ];
272
- }
273
- /**
274
- * Formats one service into the compact listServices result shape.
275
- */
276
- function formatServiceSummary(snapshot) {
277
- return {
278
- serviceId: snapshot.config.serviceId,
279
- description: snapshot.config.description ?? null,
280
- available: snapshot.runtime.available
281
- };
282
- }
283
- /**
284
- * Builds a standard MCP tool success payload with text and structured content.
285
- */
286
- function successContent(data) {
287
- return {
288
- content: [
289
- {
290
- type: "text",
291
- text: JSON.stringify(data, null, 2)
292
- }
293
- ],
294
- structuredContent: data
295
- };
296
- }
297
- /**
298
- * Builds a simple JSON schema object descriptor.
299
- */
300
- function objectSchema(required, properties) {
301
- return {
302
- type: "object",
303
- properties,
304
- required,
305
- additionalProperties: false
306
- };
307
- }
308
- /**
309
- * Builds a simple JSON schema string descriptor.
310
- */
311
- function stringSchema(description) {
312
- return {
313
- type: "string",
314
- description
315
- };
316
- }
317
- /**
318
- * Ensures the input is a plain object.
319
- */
320
- function toObject(input, message) {
321
- if (typeof input !== "object" || input === null || Array.isArray(input)) {
322
- throw new Error(message);
323
61
  }
324
- return input;
325
- }
326
- /**
327
- * Ensures the input is a string.
328
- */
329
- function requireString(input, message) {
330
- if (typeof input !== "string" || input.trim() === "") {
331
- throw new Error(message);
332
- }
333
- return input;
334
- }
335
- /**
336
- * Ensures the service management action is supported.
337
- */
338
- function requireServiceAction(input) {
339
- if (input === "reconnect" || input === "enable" || input === "disable") {
340
- return input;
341
- }
342
- throw new Error("The 'action' argument must be one of 'reconnect', 'enable', or 'disable'.");
343
- }
344
- function isJsonRpcRequest(message) {
345
- return "id" in message && "method" in message && typeof message.method === "string";
346
62
  }
@@ -0,0 +1,210 @@
1
+ import http from "node:http";
2
+ import { randomUUID } from "node:crypto";
3
+ import { jsonRpcError } from "./mcp/protocol.js";
4
+ const MAX_POST_BODY_BYTES = 4 * 1024 * 1024;
5
+ /**
6
+ * Exposes the MCP gateway over the Streamable HTTP single-endpoint transport.
7
+ */
8
+ export class StreamableHttpGatewayServer {
9
+ /**
10
+ * Stores inbound HTTP behavior.
11
+ */
12
+ config;
13
+ /**
14
+ * Stores the transport-neutral gateway engine.
15
+ */
16
+ engine;
17
+ /**
18
+ * Stores the shared logger instance.
19
+ */
20
+ logger;
21
+ /**
22
+ * Stores active SSE sessions keyed by MCP session id.
23
+ */
24
+ sessions = new Map();
25
+ /**
26
+ * Stores the underlying HTTP server instance.
27
+ */
28
+ server = null;
29
+ /**
30
+ * Returns the current endpoint URL after the server starts.
31
+ */
32
+ get url() {
33
+ const address = this.server?.address();
34
+ const port = typeof address === "object" && address ? address.port : this.config.port;
35
+ return `http://${this.config.host}:${port}${this.config.path}`;
36
+ }
37
+ /**
38
+ * Creates a Streamable HTTP gateway server.
39
+ */
40
+ constructor(config, engine, logger) {
41
+ this.config = config;
42
+ this.engine = engine;
43
+ this.logger = logger;
44
+ }
45
+ /**
46
+ * Starts listening for inbound HTTP requests.
47
+ */
48
+ async start() {
49
+ if (this.server) {
50
+ return;
51
+ }
52
+ this.server = http.createServer((request, response) => {
53
+ void this.handleRequest(request, response).catch((error) => {
54
+ this.logger.error("gateway.http_request_failed", {
55
+ message: error instanceof Error ? error.message : String(error)
56
+ });
57
+ writeJson(response, 500, jsonRpcError(null, -32000, error instanceof Error ? error.message : String(error)));
58
+ });
59
+ });
60
+ await new Promise((resolveListen, rejectListen) => {
61
+ this.server?.once("error", rejectListen);
62
+ this.server?.listen(this.config.port, this.config.host, () => {
63
+ this.server?.off("error", rejectListen);
64
+ resolveListen();
65
+ });
66
+ });
67
+ this.logger.info("gateway.http_started", {
68
+ host: this.config.host,
69
+ port: this.config.port,
70
+ path: this.config.path,
71
+ enableJsonResponse: this.config.enableJsonResponse
72
+ });
73
+ }
74
+ /**
75
+ * Stops listening and closes all active SSE sessions.
76
+ */
77
+ async stop() {
78
+ for (const response of this.sessions.values()) {
79
+ response.end();
80
+ }
81
+ this.sessions.clear();
82
+ const server = this.server;
83
+ this.server = null;
84
+ if (!server) {
85
+ return;
86
+ }
87
+ await new Promise((resolveClose, rejectClose) => {
88
+ server.close((error) => {
89
+ if (error) {
90
+ rejectClose(error);
91
+ return;
92
+ }
93
+ resolveClose();
94
+ });
95
+ });
96
+ }
97
+ /**
98
+ * Dispatches one HTTP request by method on the configured single endpoint.
99
+ */
100
+ async handleRequest(request, response) {
101
+ const requestUrl = new URL(request.url ?? "/", `http://${request.headers.host ?? "localhost"}`);
102
+ if (requestUrl.pathname !== this.config.path) {
103
+ response.writeHead(404).end();
104
+ return;
105
+ }
106
+ if (request.method === "GET") {
107
+ this.handleGet(request, response, requestUrl);
108
+ return;
109
+ }
110
+ if (request.method === "POST") {
111
+ await this.handlePost(request, response, requestUrl);
112
+ return;
113
+ }
114
+ response.writeHead(405, {
115
+ "Allow": "GET, POST"
116
+ }).end();
117
+ }
118
+ /**
119
+ * Opens one SSE session for downstream messages.
120
+ */
121
+ handleGet(request, response, requestUrl) {
122
+ const sessionId = getSessionId(request, requestUrl) ?? randomUUID();
123
+ this.sessions.set(sessionId, response);
124
+ response.writeHead(200, {
125
+ "Content-Type": "text/event-stream; charset=utf-8",
126
+ "Cache-Control": "no-cache",
127
+ "Connection": "keep-alive",
128
+ "Mcp-Session-Id": sessionId
129
+ });
130
+ response.write(":\n\n");
131
+ writeSseEvent(response, "endpoint", this.config.path);
132
+ request.on("close", () => {
133
+ if (this.sessions.get(sessionId) === response) {
134
+ this.sessions.delete(sessionId);
135
+ }
136
+ });
137
+ }
138
+ /**
139
+ * Handles one JSON-RPC POST request.
140
+ */
141
+ async handlePost(request, response, requestUrl) {
142
+ const message = await readJsonRpcMessage(request);
143
+ const result = await this.engine.handleMessage(message);
144
+ if (!result) {
145
+ response.writeHead(202).end();
146
+ return;
147
+ }
148
+ const sessionId = getSessionId(request, requestUrl);
149
+ const session = sessionId ? this.sessions.get(sessionId) : null;
150
+ if (!this.config.enableJsonResponse && session) {
151
+ writeSseEvent(session, "message", JSON.stringify(result));
152
+ response.writeHead(202, {
153
+ "Content-Type": "application/json"
154
+ }).end(JSON.stringify({ accepted: true }));
155
+ return;
156
+ }
157
+ writeJson(response, 200, result);
158
+ }
159
+ }
160
+ /**
161
+ * Reads one JSON-RPC message from a bounded HTTP request body.
162
+ */
163
+ async function readJsonRpcMessage(request) {
164
+ const chunks = [];
165
+ let totalBytes = 0;
166
+ for await (const chunk of request) {
167
+ const buffer = typeof chunk === "string" ? Buffer.from(chunk, "utf8") : chunk;
168
+ totalBytes += buffer.byteLength;
169
+ if (totalBytes > MAX_POST_BODY_BYTES) {
170
+ throw new Error(`HTTP request body exceeded ${MAX_POST_BODY_BYTES} bytes.`);
171
+ }
172
+ chunks.push(buffer);
173
+ }
174
+ const text = Buffer.concat(chunks).toString("utf8");
175
+ return JSON.parse(text);
176
+ }
177
+ /**
178
+ * Extracts the MCP session id from header or query string.
179
+ */
180
+ function getSessionId(request, requestUrl) {
181
+ const header = request.headers["mcp-session-id"];
182
+ if (typeof header === "string" && header.trim() !== "") {
183
+ return header;
184
+ }
185
+ const query = requestUrl.searchParams.get("sessionId");
186
+ return query && query.trim() !== "" ? query : null;
187
+ }
188
+ /**
189
+ * Writes one JSON response.
190
+ */
191
+ function writeJson(response, statusCode, payload) {
192
+ if (response.headersSent) {
193
+ response.end();
194
+ return;
195
+ }
196
+ response.writeHead(statusCode, {
197
+ "Content-Type": "application/json; charset=utf-8"
198
+ });
199
+ response.end(JSON.stringify(payload));
200
+ }
201
+ /**
202
+ * Writes one Server-Sent Event.
203
+ */
204
+ function writeSseEvent(response, eventName, data) {
205
+ response.write(`event: ${eventName}\n`);
206
+ for (const line of data.split(/\r?\n/)) {
207
+ response.write(`data: ${line}\n`);
208
+ }
209
+ response.write("\n");
210
+ }