@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,30 +1,14 @@
1
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;
2
+ import { createMcpHandler } from "@modelcontextprotocol/server";
3
+ import { hostHeaderValidation, originValidation, toNodeHandler } from "@modelcontextprotocol/node";
4
+ import { createGatewayMcpServer } from "./mcp/server.js";
5
5
  /**
6
- * Exposes the MCP gateway over the Streamable HTTP single-endpoint transport.
6
+ * Exposes the gateway through SDK v2 Streamable HTTP.
7
7
  */
8
8
  export class StreamableHttpGatewayServer {
9
- /**
10
- * Stores inbound HTTP behavior.
11
- */
12
9
  config;
13
- /**
14
- * Stores the transport-neutral gateway engine.
15
- */
16
- engine;
17
- /**
18
- * Stores the shared logger instance.
19
- */
20
10
  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
- */
11
+ handler;
28
12
  server = null;
29
13
  /**
30
14
  * Returns the current endpoint URL after the server starts.
@@ -35,27 +19,42 @@ export class StreamableHttpGatewayServer {
35
19
  return `http://${this.config.host}:${port}${this.config.path}`;
36
20
  }
37
21
  /**
38
- * Creates a Streamable HTTP gateway server.
22
+ * Creates an SDK HTTP handler that automatically serves both standard protocol revisions.
39
23
  */
40
24
  constructor(config, engine, logger) {
41
25
  this.config = config;
42
- this.engine = engine;
43
26
  this.logger = logger;
27
+ this.handler = createMcpHandler(() => createGatewayMcpServer(engine), {
28
+ legacy: "stateless",
29
+ responseMode: config.enableJsonResponse ? "json" : "auto",
30
+ onerror: (error) => {
31
+ this.logger.error("gateway.http_protocol_error", { message: error.message });
32
+ }
33
+ });
44
34
  }
45
35
  /**
46
- * Starts listening for inbound HTTP requests.
36
+ * Starts the guarded single-endpoint HTTP server.
47
37
  */
48
38
  async start() {
49
39
  if (this.server) {
50
40
  return;
51
41
  }
42
+ const allowedHosts = allowedHostnames(this.config.host);
43
+ const validateHost = hostHeaderValidation(allowedHosts);
44
+ const validateOrigin = originValidation(allowedHosts);
45
+ const handleMcp = toNodeHandler(this.handler, {
46
+ onerror: (error) => this.logger.error("gateway.http_adapter_error", { message: error.message })
47
+ });
52
48
  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
- });
49
+ const pathname = new URL(request.url ?? "/", "http://localhost").pathname;
50
+ if (pathname !== this.config.path) {
51
+ response.writeHead(404).end();
52
+ return;
53
+ }
54
+ if (!validateHost(request, response) || !validateOrigin(request, response)) {
55
+ return;
56
+ }
57
+ void handleMcp(request, response);
59
58
  });
60
59
  await new Promise((resolveListen, rejectListen) => {
61
60
  this.server?.once("error", rejectListen);
@@ -68,143 +67,28 @@ export class StreamableHttpGatewayServer {
68
67
  host: this.config.host,
69
68
  port: this.config.port,
70
69
  path: this.config.path,
71
- enableJsonResponse: this.config.enableJsonResponse
70
+ responseMode: this.config.enableJsonResponse ? "json" : "auto"
72
71
  });
73
72
  }
74
73
  /**
75
- * Stops listening and closes all active SSE sessions.
74
+ * Stops accepting requests and closes all in-flight SDK exchanges.
76
75
  */
77
76
  async stop() {
78
- for (const response of this.sessions.values()) {
79
- response.end();
80
- }
81
- this.sessions.clear();
77
+ await this.handler.close();
82
78
  const server = this.server;
83
79
  this.server = null;
84
80
  if (!server) {
85
81
  return;
86
82
  }
87
83
  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
84
+ server.close((error) => error ? rejectClose(error) : resolveClose());
85
+ server.closeAllConnections();
129
86
  });
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
87
  }
159
88
  }
160
89
  /**
161
- * Reads one JSON-RPC message from a bounded HTTP request body.
90
+ * Builds the Host and Origin allow-list for the configured bind address.
162
91
  */
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");
92
+ function allowedHostnames(host) {
93
+ return [...new Set([host, "localhost", "127.0.0.1", "[::1]"])];
210
94
  }
package/dist/index.js CHANGED
@@ -89,6 +89,7 @@ class Application {
89
89
  this.logger.info("gateway.stopping", { signal });
90
90
  this.watcher.stop();
91
91
  await this.httpServer?.stop();
92
+ await this.server.stop();
92
93
  await this.registry.dispose();
93
94
  process.exit(0);
94
95
  };
@@ -114,6 +115,9 @@ if (import.meta.main) {
114
115
  });
115
116
  }
116
117
  export function parseCliArgs(args) {
118
+ if (args.includes("--protocol-mode")) {
119
+ throw new Error("--protocol-mode is no longer supported; protocol negotiation is automatic.");
120
+ }
117
121
  const configPath = readOption(args, "--config") ?? process.env.MCP_GATEWAY_CONFIG ?? "config.json";
118
122
  const port = readIntegerOption(args, "--port");
119
123
  const host = readOption(args, "--host");