@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.
package/README.md CHANGED
@@ -92,11 +92,23 @@ Start the gateway:
92
92
  mcp-gateway-service
93
93
  ```
94
94
 
95
- With an explicit config path:
96
-
97
- ```bash
98
- mcp-gateway-service --config ./config.json
99
- ```
95
+ With an explicit config path:
96
+
97
+ ```bash
98
+ mcp-gateway-service --config ./config.json
99
+ ```
100
+
101
+ Expose the same gateway over Streamable HTTP with CLI arguments:
102
+
103
+ ```bash
104
+ mcp-gateway-service --config ./config.json --http --port 3100 --path /mcp
105
+ ```
106
+
107
+ Use `--json-response` when the HTTP client expects stateless JSON-RPC responses directly from `POST` requests:
108
+
109
+ ```bash
110
+ mcp-gateway-service --config ./config.json --http --port 3100 --json-response
111
+ ```
100
112
 
101
113
  ### Run from source
102
114
 
@@ -129,9 +141,9 @@ Short form:
129
141
  mcp-gateway-service -v
130
142
  ```
131
143
 
132
- ## Configuration
133
-
134
- The gateway currently supports `stdio` downstream transports only.
144
+ ## Configuration
145
+
146
+ The gateway supports `stdio` and Streamable HTTP downstream transports. Inbound Streamable HTTP is enabled only with CLI arguments, not with `config.json`, so stdio-based agents can safely share the same service-pool config without accidentally starting an HTTP listener.
135
147
 
136
148
  A service is loaded only when `enable` is missing or set to `true`. If `enable` is set to `false`, the gateway skips that service entirely. During hot reload, disabling or removing a service also stops its existing downstream process if one is running.
137
149
 
@@ -144,9 +156,12 @@ A service is loaded only when `enable` is missing or set to `true`. If `enable`
144
156
  - `cwd` is optional. When omitted, the gateway uses its current working directory.
145
157
  - `env` is optional.
146
158
  - `framing` is optional. When omitted, the gateway tries `line` first and then `content-length`.
147
-
148
- ### Config shape
149
-
159
+ - HTTP downstream transports use `transport.type: "http"` and a single `transport.url`.
160
+ - `transport.headers` can provide static headers for an HTTP downstream service.
161
+ - `transport.enableJsonResponse` enables stateless JSON response mode for an HTTP downstream service.
162
+
163
+ ### Config shape
164
+
150
165
  ```json
151
166
  {
152
167
  "logging": {
@@ -165,12 +180,36 @@ A service is loaded only when `enable` is missing or set to `true`. If `enable`
165
180
  "args": [
166
181
  "--experimental-strip-types",
167
182
  "examples/echo-service.ts"
168
- ]
169
- }
170
- }
171
- ]
172
- }
173
- ```
183
+ ]
184
+ }
185
+ },
186
+ {
187
+ "serviceId": "remote-http",
188
+ "enable": false,
189
+ "name": "Remote Streamable HTTP Service",
190
+ "description": "Example downstream MCP service over Streamable HTTP.",
191
+ "transport": {
192
+ "type": "http",
193
+ "url": "http://127.0.0.1:3200/mcp",
194
+ "headers": {
195
+ "Authorization": "Bearer replace-me"
196
+ },
197
+ "enableJsonResponse": false
198
+ }
199
+ }
200
+ ]
201
+ }
202
+ ```
203
+
204
+ ### Streamable HTTP notes
205
+
206
+ - The gateway uses one endpoint for both `GET` and `POST`.
207
+ - Inbound HTTP is enabled only by the explicit `--http` CLI option, optionally with settings such as `--port 3100 --path /mcp`.
208
+ - Passing `--port`, `--host`, `--path`, or `--json-response` without `--http` does not start an HTTP listener.
209
+ - `GET /mcp` opens the SSE read channel and returns the session in the `Mcp-Session-Id` header.
210
+ - `POST /mcp` sends JSON-RPC messages. The preferred session binding is the `Mcp-Session-Id` header.
211
+ - Query-string `sessionId` is accepted for compatibility, but new clients should use the header.
212
+ - The `endpoint` SSE event advertises the single path, such as `/mcp`, without embedding the session id in the URL.
174
213
 
175
214
  ## Public Gateway Tools
176
215
 
package/README_zh.md CHANGED
@@ -98,11 +98,23 @@ npm install -g @jadchene/mcp-gateway-service
98
98
  mcp-gateway-service
99
99
  ```
100
100
 
101
- 显式指定配置文件:
102
-
103
- ```bash
104
- mcp-gateway-service --config ./config.json
105
- ```
101
+ 显式指定配置文件:
102
+
103
+ ```bash
104
+ mcp-gateway-service --config ./config.json
105
+ ```
106
+
107
+ 通过 CLI 参数同时暴露 Streamable HTTP 接口:
108
+
109
+ ```bash
110
+ mcp-gateway-service --config ./config.json --http --port 3100 --path /mcp
111
+ ```
112
+
113
+ 如果 HTTP 客户端希望 `POST` 直接返回 JSON-RPC 响应,可以启用无状态 JSON 直返:
114
+
115
+ ```bash
116
+ mcp-gateway-service --config ./config.json --http --port 3100 --json-response
117
+ ```
106
118
 
107
119
  ### 从源码运行
108
120
 
@@ -135,9 +147,9 @@ mcp-gateway-service --version
135
147
  mcp-gateway-service -v
136
148
  ```
137
149
 
138
- ## 配置格式
139
-
140
- 当前只支持 `stdio` 类型的下游传输。
150
+ ## 配置格式
151
+
152
+ 当前支持 `stdio` 和 Streamable HTTP 类型的下游传输。网关自身的入站 Streamable HTTP 只通过 CLI 参数启用,不通过 `config.json` 启用,这样 stdio agent 可以安全共用同一份服务池配置,不会意外启动 HTTP 监听。
141
153
 
142
154
  只有当 `enable` 未填写或显式为 `true` 时,服务才会被加载;如果 `enable` 为 `false`,网关会跳过该服务。热刷新时,如果某个服务被禁用或从配置中删除,网关也会停掉它当前已启动的下游进程。
143
155
 
@@ -150,7 +162,10 @@ mcp-gateway-service -v
150
162
  - `cwd` 可选,不填时使用当前工作目录
151
163
  - `env` 可选
152
164
  - `framing` 可选,不填时先尝试 `line`,再尝试 `content-length`
153
-
165
+ - HTTP 下游使用 `transport.type: "http"` 和一个 `transport.url`
166
+ - `transport.headers` 可为 HTTP 下游提供静态请求头
167
+ - `transport.enableJsonResponse` 可为 HTTP 下游启用无状态 JSON 直返模式
168
+
154
169
  ```json
155
170
  {
156
171
  "logging": {
@@ -169,12 +184,36 @@ mcp-gateway-service -v
169
184
  "args": [
170
185
  "--experimental-strip-types",
171
186
  "examples/echo-service.ts"
172
- ]
173
- }
174
- }
175
- ]
176
- }
177
- ```
187
+ ]
188
+ }
189
+ },
190
+ {
191
+ "serviceId": "remote-http",
192
+ "enable": false,
193
+ "name": "Remote Streamable HTTP Service",
194
+ "description": "Example downstream MCP service over Streamable HTTP.",
195
+ "transport": {
196
+ "type": "http",
197
+ "url": "http://127.0.0.1:3200/mcp",
198
+ "headers": {
199
+ "Authorization": "Bearer replace-me"
200
+ },
201
+ "enableJsonResponse": false
202
+ }
203
+ }
204
+ ]
205
+ }
206
+ ```
207
+
208
+ ### Streamable HTTP 说明
209
+
210
+ - 网关使用同一个 endpoint 处理 `GET` 和 `POST`
211
+ - 入站 HTTP 只通过显式 `--http` CLI 参数启用,可搭配 `--port 3100 --path /mcp`
212
+ - 只传 `--port`、`--host`、`--path` 或 `--json-response`,但不传 `--http` 时,不会启动 HTTP 监听
213
+ - `GET /mcp` 打开 SSE 下行通道,并通过 `Mcp-Session-Id` 响应头返回 session
214
+ - `POST /mcp` 发送 JSON-RPC 消息,推荐通过 `Mcp-Session-Id` 请求头绑定 session
215
+ - 为兼容旧客户端,仍接受 query string 里的 `sessionId`,但新客户端应优先使用 header
216
+ - `endpoint` SSE 事件只返回统一路径,例如 `/mcp`,不会把 session id 塞进 URL
178
217
 
179
218
  ## 对外网关工具
180
219
 
@@ -15,8 +15,22 @@
15
15
  "args": [
16
16
  "--experimental-strip-types",
17
17
  "examples/echo-service.ts"
18
- ]
19
- }
20
- }
21
- ]
18
+ ]
19
+ }
20
+ },
21
+ {
22
+ "serviceId": "remote-http",
23
+ "enable": false,
24
+ "name": "Remote Streamable HTTP Service",
25
+ "description": "Example downstream MCP service over Streamable HTTP.",
26
+ "transport": {
27
+ "type": "http",
28
+ "url": "http://127.0.0.1:3200/mcp",
29
+ "headers": {
30
+ "Authorization": "Bearer replace-me"
31
+ },
32
+ "enableJsonResponse": false
33
+ }
34
+ }
35
+ ]
22
36
  }
package/dist/config.js CHANGED
@@ -93,6 +93,9 @@ function validateTransportConfig(serviceId, input) {
93
93
  throw new Error(`Service '${serviceId}' transport must be a JSON object.`);
94
94
  }
95
95
  const type = requireNonEmptyString(input.type, `service '${serviceId}' transport.type`);
96
+ if (type === "http") {
97
+ return validateHttpTransportConfig(serviceId, input);
98
+ }
96
99
  if (type !== "stdio") {
97
100
  throw new Error(`Service '${serviceId}' uses unsupported transport type '${type}'.`);
98
101
  }
@@ -110,6 +113,27 @@ function validateTransportConfig(serviceId, input) {
110
113
  framing
111
114
  };
112
115
  }
116
+ /**
117
+ * Validates a downstream Streamable HTTP transport definition.
118
+ */
119
+ function validateHttpTransportConfig(serviceId, input) {
120
+ const url = requireNonEmptyString(input.url, `service '${serviceId}' transport.url`);
121
+ try {
122
+ const parsed = new URL(url);
123
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
124
+ throw new Error("invalid protocol");
125
+ }
126
+ }
127
+ catch {
128
+ throw new Error(`The 'service ${serviceId} transport.url' field must be a valid http or https URL.`);
129
+ }
130
+ return {
131
+ type: "http",
132
+ url,
133
+ headers: optionalStringRecord(input.headers, `service '${serviceId}' transport.headers`),
134
+ enableJsonResponse: optionalBoolean(input.enableJsonResponse, `service '${serviceId}' transport.enableJsonResponse`)
135
+ };
136
+ }
113
137
  /**
114
138
  * Checks whether a value is a record-like object.
115
139
  */
@@ -0,0 +1,324 @@
1
+ import { jsonRpcError, jsonRpcResult } from "./mcp/protocol.js";
2
+ import { VERSION } from "./version.js";
3
+ /**
4
+ * Handles MCP JSON-RPC requests independently of the outer transport.
5
+ */
6
+ export class McpGatewayEngine {
7
+ /**
8
+ * Stores the registry used for metadata lookup and routing.
9
+ */
10
+ registry;
11
+ /**
12
+ * Stores the shared logger instance.
13
+ */
14
+ logger;
15
+ /**
16
+ * Stores the startup barrier that must resolve before gateway tools can use the registry.
17
+ */
18
+ startupBarrier = Promise.resolve();
19
+ /**
20
+ * Creates the transport-neutral gateway engine.
21
+ */
22
+ constructor(registry, logger) {
23
+ this.registry = registry;
24
+ this.logger = logger;
25
+ }
26
+ /**
27
+ * Sets the startup barrier used to delay tool handling until the registry is ready.
28
+ */
29
+ setStartupBarrier(barrier) {
30
+ this.startupBarrier = barrier;
31
+ }
32
+ /**
33
+ * Handles one inbound JSON-RPC message and returns a response when the message has an id.
34
+ */
35
+ async handleMessage(message) {
36
+ if (!isJsonRpcRequest(message)) {
37
+ return null;
38
+ }
39
+ return this.handleRequest(message);
40
+ }
41
+ /**
42
+ * Handles one inbound JSON-RPC request.
43
+ */
44
+ async handleRequest(request) {
45
+ try {
46
+ if (request.method === "initialize") {
47
+ return jsonRpcResult(request.id, this.buildInitializeResult());
48
+ }
49
+ if (request.method === "ping") {
50
+ return jsonRpcResult(request.id, {});
51
+ }
52
+ if (request.method === "tools/list") {
53
+ return jsonRpcResult(request.id, { tools: buildGatewayTools() });
54
+ }
55
+ if (request.method === "tools/call") {
56
+ await this.startupBarrier;
57
+ const result = await this.handleToolCall(request);
58
+ return jsonRpcResult(request.id, result);
59
+ }
60
+ if (request.method === "notifications/initialized") {
61
+ return null;
62
+ }
63
+ return jsonRpcError(request.id, -32601, `Unsupported method '${request.method}'.`);
64
+ }
65
+ catch (error) {
66
+ const message = error instanceof Error ? error.message : String(error);
67
+ this.logger.error("gateway.request_failed", {
68
+ method: request.method,
69
+ message
70
+ });
71
+ return jsonRpcError(request.id, -32000, message);
72
+ }
73
+ }
74
+ /**
75
+ * Handles one gateway tool invocation.
76
+ */
77
+ async handleToolCall(request) {
78
+ const params = toObject(request.params, "The tools/call params must be an object.");
79
+ const toolName = requireString(params.name, "The tool name must be a string.");
80
+ const args = toObject(params.arguments ?? {}, "The tool arguments must be an object.");
81
+ switch (toolName) {
82
+ case "gateway.listServices":
83
+ return successContent({
84
+ services: this.registry.listServices().map(formatServiceSummary)
85
+ });
86
+ case "gateway.getService":
87
+ return this.getService(args);
88
+ case "gateway.listTools":
89
+ return this.listTools(args);
90
+ case "gateway.getToolSchema":
91
+ return this.getToolSchema(args);
92
+ case "gateway.manageService":
93
+ return this.manageService(args);
94
+ case "gateway.callTool":
95
+ return this.callDownstreamTool(args);
96
+ default:
97
+ throw new Error(`Unknown gateway tool '${toolName}'.`);
98
+ }
99
+ }
100
+ /**
101
+ * Returns detailed metadata for one logical service.
102
+ */
103
+ getService(args) {
104
+ const serviceId = requireString(args.serviceId, "The 'serviceId' argument must be a string.");
105
+ const snapshot = this.registry.getService(serviceId);
106
+ if (!snapshot) {
107
+ throw new Error(`Unknown service '${serviceId}'.`);
108
+ }
109
+ return successContent({
110
+ serviceId: snapshot.config.serviceId,
111
+ name: snapshot.config.name,
112
+ description: snapshot.config.description ?? null,
113
+ available: snapshot.runtime.available,
114
+ lastError: snapshot.runtime.lastError,
115
+ lastConnectedAt: snapshot.runtime.lastConnectedAt,
116
+ protocolVersion: snapshot.metadata.protocolVersion,
117
+ serverInfo: snapshot.metadata.serverInfo
118
+ });
119
+ }
120
+ /**
121
+ * Returns tool summaries for one logical service.
122
+ */
123
+ listTools(args) {
124
+ const serviceId = requireString(args.serviceId, "The 'serviceId' argument must be a string.");
125
+ return successContent({
126
+ tools: this.registry.listTools(serviceId).map((tool) => ({
127
+ name: tool.name,
128
+ description: tool.description ?? null
129
+ }))
130
+ });
131
+ }
132
+ /**
133
+ * Returns input and output schemas for one downstream tool.
134
+ */
135
+ getToolSchema(args) {
136
+ const serviceId = requireString(args.serviceId, "The 'serviceId' argument must be a string.");
137
+ const toolName = requireString(args.toolName, "The 'toolName' argument must be a string.");
138
+ const tool = this.registry.getTool(serviceId, toolName);
139
+ if (!tool) {
140
+ throw new Error(`Unknown tool '${toolName}' in service '${serviceId}'.`);
141
+ }
142
+ return successContent({
143
+ inputSchema: tool.inputSchema ?? null,
144
+ outputSchema: tool.outputSchema ?? null
145
+ });
146
+ }
147
+ /**
148
+ * Routes one downstream tool call through the service registry.
149
+ */
150
+ async callDownstreamTool(args) {
151
+ const serviceId = requireString(args.serviceId, "The 'serviceId' argument must be a string.");
152
+ const toolName = requireString(args.toolName, "The 'toolName' argument must be a string.");
153
+ const toolArgs = toObject(args.arguments ?? {}, "The 'arguments' field must be an object.");
154
+ const call = await this.registry.callTool(serviceId, toolName, toolArgs);
155
+ return call.result;
156
+ }
157
+ /**
158
+ * Applies one compact service management action.
159
+ */
160
+ async manageService(args) {
161
+ const serviceId = requireString(args.serviceId, "The 'serviceId' argument must be a string.");
162
+ const action = requireServiceAction(args.action);
163
+ const result = await this.registry.manageService(serviceId, action);
164
+ return successContent({
165
+ serviceId: result.serviceId,
166
+ action: result.action,
167
+ enabled: result.enabled,
168
+ available: result.available
169
+ });
170
+ }
171
+ /**
172
+ * Builds the MCP initialize result advertised by the gateway.
173
+ */
174
+ buildInitializeResult() {
175
+ return {
176
+ protocolVersion: "2025-06-18",
177
+ capabilities: {
178
+ tools: {
179
+ listChanged: false
180
+ }
181
+ },
182
+ serverInfo: {
183
+ name: "mcp-gateway",
184
+ version: VERSION
185
+ }
186
+ };
187
+ }
188
+ }
189
+ /**
190
+ * Builds the fixed gateway tool definitions exposed to all MCP clients.
191
+ */
192
+ export function buildGatewayTools() {
193
+ return [
194
+ {
195
+ name: "gateway.listServices",
196
+ description: "Lists all MCP services currently managed by the gateway.",
197
+ inputSchema: {
198
+ type: "object",
199
+ properties: {},
200
+ additionalProperties: false
201
+ }
202
+ },
203
+ {
204
+ name: "gateway.getService",
205
+ description: "Returns one service summary, runtime state, and metadata cache details.",
206
+ inputSchema: objectSchema(["serviceId"], {
207
+ serviceId: stringSchema("Logical service identifier.")
208
+ })
209
+ },
210
+ {
211
+ name: "gateway.listTools",
212
+ description: "Lists all tools exposed by one downstream service.",
213
+ inputSchema: objectSchema(["serviceId"], {
214
+ serviceId: stringSchema("Logical service identifier.")
215
+ })
216
+ },
217
+ {
218
+ name: "gateway.getToolSchema",
219
+ description: "Returns the input and output schema for one downstream tool.",
220
+ inputSchema: objectSchema(["serviceId", "toolName"], {
221
+ serviceId: stringSchema("Logical service identifier."),
222
+ toolName: stringSchema("Downstream tool name.")
223
+ })
224
+ },
225
+ {
226
+ name: "gateway.manageService",
227
+ description: "Reconnects one service or updates its enabled state with a compact action.",
228
+ inputSchema: objectSchema(["serviceId", "action"], {
229
+ serviceId: stringSchema("Logical service identifier."),
230
+ action: {
231
+ type: "string",
232
+ description: "Management action applied to the service.",
233
+ enum: ["reconnect", "enable", "disable"]
234
+ }
235
+ })
236
+ },
237
+ {
238
+ name: "gateway.callTool",
239
+ description: "Calls one downstream tool through the gateway service pool.",
240
+ inputSchema: objectSchema(["serviceId", "toolName", "arguments"], {
241
+ serviceId: stringSchema("Logical service identifier."),
242
+ toolName: stringSchema("Downstream tool name."),
243
+ arguments: {
244
+ type: "object",
245
+ description: "Arguments passed to the downstream tool."
246
+ }
247
+ })
248
+ }
249
+ ];
250
+ }
251
+ /**
252
+ * Formats one service into the compact listServices result shape.
253
+ */
254
+ function formatServiceSummary(snapshot) {
255
+ return {
256
+ serviceId: snapshot.config.serviceId,
257
+ description: snapshot.config.description ?? null,
258
+ available: snapshot.runtime.available
259
+ };
260
+ }
261
+ /**
262
+ * Builds a standard MCP tool success payload with text and structured content.
263
+ */
264
+ function successContent(data) {
265
+ return {
266
+ content: [
267
+ {
268
+ type: "text",
269
+ text: JSON.stringify(data, null, 2)
270
+ }
271
+ ],
272
+ structuredContent: data
273
+ };
274
+ }
275
+ /**
276
+ * Builds a simple JSON schema object descriptor.
277
+ */
278
+ function objectSchema(required, properties) {
279
+ return {
280
+ type: "object",
281
+ properties,
282
+ required,
283
+ additionalProperties: false
284
+ };
285
+ }
286
+ /**
287
+ * Builds a simple JSON schema string descriptor.
288
+ */
289
+ function stringSchema(description) {
290
+ return {
291
+ type: "string",
292
+ description
293
+ };
294
+ }
295
+ /**
296
+ * Ensures the input is a plain object.
297
+ */
298
+ function toObject(input, message) {
299
+ if (typeof input !== "object" || input === null || Array.isArray(input)) {
300
+ throw new Error(message);
301
+ }
302
+ return input;
303
+ }
304
+ /**
305
+ * Ensures the input is a string.
306
+ */
307
+ function requireString(input, message) {
308
+ if (typeof input !== "string" || input.trim() === "") {
309
+ throw new Error(message);
310
+ }
311
+ return input;
312
+ }
313
+ /**
314
+ * Ensures the service management action is supported.
315
+ */
316
+ function requireServiceAction(input) {
317
+ if (input === "reconnect" || input === "enable" || input === "disable") {
318
+ return input;
319
+ }
320
+ throw new Error("The 'action' argument must be one of 'reconnect', 'enable', or 'disable'.");
321
+ }
322
+ function isJsonRpcRequest(message) {
323
+ return "id" in message && "method" in message && typeof message.method === "string";
324
+ }