@jadchene/mcp-gateway-service 0.8.0 → 0.9.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 +3 -0
- package/README_zh.md +3 -0
- package/dist/http-server.js +103 -3
- package/dist/index.js +17 -3
- package/dist/service-registry.js +6 -14
- package/package.json +1 -1
- package/skills/mcp-gateway/SKILL.md +27 -40
package/README.md
CHANGED
|
@@ -17,6 +17,7 @@ The project uses the official TypeScript SDK v2 and requires Node.js 24 or later
|
|
|
17
17
|
- Connect the agent once, then add or remove downstream services in the gateway config.
|
|
18
18
|
- Find tools by name or description and load schemas only when required.
|
|
19
19
|
- Use stdio and Streamable HTTP services through the same interface.
|
|
20
|
+
- Require user confirmation for selected tool-name patterns, or hide and block matching tools entirely.
|
|
20
21
|
- Reload config changes without restarting the gateway.
|
|
21
22
|
|
|
22
23
|
## Quick Start
|
|
@@ -100,6 +101,8 @@ claude mcp add --transport http gateway http://127.0.0.1:3000/mcp
|
|
|
100
101
|
| `--auth-token-env <name>` | Environment variable containing the HTTP bearer token. | `MCP_GATEWAY_AUTH_TOKEN` |
|
|
101
102
|
| `--http-admin-tools` | Exposes `gateway_manage_service` over authenticated HTTP. | Disabled |
|
|
102
103
|
| `--max-concurrent-requests <n>` | Bounds in-flight HTTP requests. | `64` |
|
|
104
|
+
| `--max-request-body-bytes <n>` | Rejects HTTP request bodies above this byte limit; maximum configurable value is 64 MiB. | `16777216` (16 MiB) |
|
|
105
|
+
| `--max-legacy-sessions <n>` | Bounds retained stateful legacy HTTP sessions. | `256` |
|
|
103
106
|
| `--version`, `-v` | Prints the installed version. | — |
|
|
104
107
|
|
|
105
108
|
Stdio remains available when `--http` is enabled.
|
package/README_zh.md
CHANGED
|
@@ -17,6 +17,7 @@ MCP Gateway 把多个 MCP 服务收拢到一个入口。Agent 连接网关后只
|
|
|
17
17
|
- Agent 只需接入一次,后续增减下游服务只改网关配置。
|
|
18
18
|
- 可以按名称或描述查找工具,需要时再读取 schema。
|
|
19
19
|
- Stdio 和 Streamable HTTP 服务使用同一套调用方式。
|
|
20
|
+
- 可按工具名模式要求用户确认,或隐藏并禁止调用指定工具。
|
|
20
21
|
- 修改配置文件后自动重载,不必重启网关。
|
|
21
22
|
|
|
22
23
|
## 快速开始
|
|
@@ -100,6 +101,8 @@ claude mcp add --transport http gateway http://127.0.0.1:3000/mcp
|
|
|
100
101
|
| `--auth-token-env <名称>` | 保存 HTTP Bearer Token 的环境变量名。 | `MCP_GATEWAY_AUTH_TOKEN` |
|
|
101
102
|
| `--http-admin-tools` | 在已认证 HTTP 入口暴露 `gateway_manage_service`。 | 不启用 |
|
|
102
103
|
| `--max-concurrent-requests <数量>` | HTTP 并发请求上限。 | `64` |
|
|
104
|
+
| `--max-request-body-bytes <字节数>` | HTTP 请求体字节上限,最大可配置为 64 MiB,超限返回 `413`。 | `16777216`(16 MiB) |
|
|
105
|
+
| `--max-legacy-sessions <数量>` | 有状态旧版 HTTP 会话的保留上限。 | `256` |
|
|
103
106
|
| `--version`、`-v` | 输出已安装版本。 | — |
|
|
104
107
|
|
|
105
108
|
启用 `--http` 后,stdio 入口仍然可用。
|
package/dist/http-server.js
CHANGED
|
@@ -5,6 +5,7 @@ import { hostHeaderValidation, originValidation, toNodeHandler } from "@modelcon
|
|
|
5
5
|
import { createGatewayMcpServer } from "./mcp/server.js";
|
|
6
6
|
const LEGACY_SESSION_IDLE_TIMEOUT_MS = 30 * 60 * 1_000;
|
|
7
7
|
const LEGACY_SESSION_SWEEP_INTERVAL_MS = 60 * 1_000;
|
|
8
|
+
const DEFAULT_MAX_REQUEST_BODY_BYTES = 16 * 1024 * 1024;
|
|
8
9
|
/**
|
|
9
10
|
* Exposes the gateway through SDK v2 Streamable HTTP.
|
|
10
11
|
*/
|
|
@@ -14,6 +15,7 @@ export class StreamableHttpGatewayServer {
|
|
|
14
15
|
logger;
|
|
15
16
|
handler;
|
|
16
17
|
legacySessions = new Map();
|
|
18
|
+
legacySessionsInitializing = 0;
|
|
17
19
|
legacySessionSweepTimer = null;
|
|
18
20
|
server = null;
|
|
19
21
|
/**
|
|
@@ -22,7 +24,10 @@ export class StreamableHttpGatewayServer {
|
|
|
22
24
|
get url() {
|
|
23
25
|
const address = this.server?.address();
|
|
24
26
|
const port = typeof address === "object" && address ? address.port : this.config.port;
|
|
25
|
-
|
|
27
|
+
const host = this.config.host.includes(":") && !this.config.host.startsWith("[")
|
|
28
|
+
? `[${this.config.host}]`
|
|
29
|
+
: this.config.host;
|
|
30
|
+
return `http://${host}:${port}${this.config.path}`;
|
|
26
31
|
}
|
|
27
32
|
/**
|
|
28
33
|
* Creates an SDK HTTP handler that automatically serves both standard protocol revisions.
|
|
@@ -62,6 +67,7 @@ export class StreamableHttpGatewayServer {
|
|
|
62
67
|
onerror: (error) => this.logger.error("gateway.http_adapter_error", { message: error.message })
|
|
63
68
|
});
|
|
64
69
|
const maxConcurrentRequests = this.config.maxConcurrentRequests ?? 64;
|
|
70
|
+
const maxRequestBodyBytes = this.config.maxRequestBodyBytes ?? DEFAULT_MAX_REQUEST_BODY_BYTES;
|
|
65
71
|
let activeRequests = 0;
|
|
66
72
|
this.server = http.createServer((request, response) => {
|
|
67
73
|
const pathname = new URL(request.url ?? "/", "http://localhost").pathname;
|
|
@@ -90,7 +96,7 @@ export class StreamableHttpGatewayServer {
|
|
|
90
96
|
};
|
|
91
97
|
response.once("finish", release);
|
|
92
98
|
response.once("close", release);
|
|
93
|
-
void
|
|
99
|
+
void handleBoundedRequest(request, response, maxRequestBodyBytes, handleMcp, this.logger);
|
|
94
100
|
});
|
|
95
101
|
await new Promise((resolveListen, rejectListen) => {
|
|
96
102
|
this.server?.once("error", rejectListen);
|
|
@@ -150,6 +156,18 @@ export class StreamableHttpGatewayServer {
|
|
|
150
156
|
* Creates a stateful 2025 transport for an initialize request.
|
|
151
157
|
*/
|
|
152
158
|
async handleLegacyInitialization(request) {
|
|
159
|
+
const maxLegacySessions = this.config.maxLegacySessions ?? 256;
|
|
160
|
+
if (this.legacySessions.size + this.legacySessionsInitializing >= maxLegacySessions) {
|
|
161
|
+
return Response.json({
|
|
162
|
+
jsonrpc: "2.0",
|
|
163
|
+
error: {
|
|
164
|
+
code: -32000,
|
|
165
|
+
message: "Legacy session capacity reached"
|
|
166
|
+
},
|
|
167
|
+
id: null
|
|
168
|
+
}, { status: 503, headers: { "Retry-After": "1" } });
|
|
169
|
+
}
|
|
170
|
+
this.legacySessionsInitializing += 1;
|
|
153
171
|
let session;
|
|
154
172
|
const transport = new WebStandardStreamableHTTPServerTransport({
|
|
155
173
|
sessionIdGenerator: randomUUID,
|
|
@@ -164,8 +182,8 @@ export class StreamableHttpGatewayServer {
|
|
|
164
182
|
includeAdminTools: this.config.enableAdminTools ?? false
|
|
165
183
|
});
|
|
166
184
|
session = { server, transport, lastAccessedAt: Date.now() };
|
|
167
|
-
await server.connect(transport);
|
|
168
185
|
try {
|
|
186
|
+
await server.connect(transport);
|
|
169
187
|
const response = await transport.handleRequest(request);
|
|
170
188
|
if (!transport.sessionId) {
|
|
171
189
|
await server.close().catch(() => undefined);
|
|
@@ -179,6 +197,9 @@ export class StreamableHttpGatewayServer {
|
|
|
179
197
|
await server.close().catch(() => undefined);
|
|
180
198
|
throw error;
|
|
181
199
|
}
|
|
200
|
+
finally {
|
|
201
|
+
this.legacySessionsInitializing -= 1;
|
|
202
|
+
}
|
|
182
203
|
}
|
|
183
204
|
/**
|
|
184
205
|
* Releases abandoned legacy sessions without touching active modern requests.
|
|
@@ -193,6 +214,85 @@ export class StreamableHttpGatewayServer {
|
|
|
193
214
|
}
|
|
194
215
|
}
|
|
195
216
|
}
|
|
217
|
+
/**
|
|
218
|
+
* Reads a JSON request body with a byte limit before handing it to the SDK.
|
|
219
|
+
* Supplying the parsed body prevents the SDK Node adapter from buffering the
|
|
220
|
+
* same unbounded stream a second time.
|
|
221
|
+
*/
|
|
222
|
+
async function handleBoundedRequest(request, response, maxBytes, handleMcp, logger) {
|
|
223
|
+
try {
|
|
224
|
+
const body = await readBoundedJsonBody(request, maxBytes);
|
|
225
|
+
if (body === NO_BODY) {
|
|
226
|
+
await handleMcp(request, response);
|
|
227
|
+
}
|
|
228
|
+
else {
|
|
229
|
+
await handleMcp(request, response, body);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
catch (error) {
|
|
233
|
+
if (response.headersSent || response.destroyed) {
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
const bodyError = error instanceof HttpBodyError
|
|
237
|
+
? error
|
|
238
|
+
: new HttpBodyError(400, "Invalid JSON request body.");
|
|
239
|
+
logger.warn("gateway.http_body_rejected", {
|
|
240
|
+
status: bodyError.status,
|
|
241
|
+
message: bodyError.message
|
|
242
|
+
});
|
|
243
|
+
response.writeHead(bodyError.status, {
|
|
244
|
+
"Content-Type": "application/json",
|
|
245
|
+
"Connection": "close"
|
|
246
|
+
}).end(JSON.stringify({
|
|
247
|
+
jsonrpc: "2.0",
|
|
248
|
+
error: { code: -32700, message: bodyError.message },
|
|
249
|
+
id: null
|
|
250
|
+
}));
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
const NO_BODY = Symbol("no-http-body");
|
|
254
|
+
async function readBoundedJsonBody(request, maxBytes) {
|
|
255
|
+
const contentEncoding = request.headers["content-encoding"];
|
|
256
|
+
if (contentEncoding && contentEncoding !== "identity") {
|
|
257
|
+
throw new HttpBodyError(415, "Compressed HTTP request bodies are not supported.");
|
|
258
|
+
}
|
|
259
|
+
const declaredLength = request.headers["content-length"];
|
|
260
|
+
if (declaredLength !== undefined) {
|
|
261
|
+
const normalized = Array.isArray(declaredLength) ? declaredLength[0] : declaredLength;
|
|
262
|
+
if (!/^\d+$/.test(normalized)) {
|
|
263
|
+
throw new HttpBodyError(400, "Invalid Content-Length header.");
|
|
264
|
+
}
|
|
265
|
+
if (Number(normalized) > maxBytes) {
|
|
266
|
+
throw new HttpBodyError(413, `HTTP request body exceeds the ${maxBytes}-byte limit.`);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
const chunks = [];
|
|
270
|
+
let totalBytes = 0;
|
|
271
|
+
for await (const chunk of request) {
|
|
272
|
+
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
273
|
+
totalBytes += bytes.length;
|
|
274
|
+
if (totalBytes > maxBytes) {
|
|
275
|
+
throw new HttpBodyError(413, `HTTP request body exceeds the ${maxBytes}-byte limit.`);
|
|
276
|
+
}
|
|
277
|
+
chunks.push(bytes);
|
|
278
|
+
}
|
|
279
|
+
if (totalBytes === 0) {
|
|
280
|
+
return NO_BODY;
|
|
281
|
+
}
|
|
282
|
+
try {
|
|
283
|
+
return JSON.parse(Buffer.concat(chunks, totalBytes).toString("utf8"));
|
|
284
|
+
}
|
|
285
|
+
catch {
|
|
286
|
+
throw new HttpBodyError(400, "Invalid JSON request body.");
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
class HttpBodyError extends Error {
|
|
290
|
+
status;
|
|
291
|
+
constructor(status, message) {
|
|
292
|
+
super(message);
|
|
293
|
+
this.status = status;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
196
296
|
/**
|
|
197
297
|
* Returns the standard status for a missing or expired MCP session.
|
|
198
298
|
*/
|
package/dist/index.js
CHANGED
|
@@ -126,8 +126,11 @@ export function parseCliArgs(args) {
|
|
|
126
126
|
const enableAdminTools = args.includes("--http-admin-tools");
|
|
127
127
|
const authTokenEnv = readOption(args, "--auth-token-env") ?? "MCP_GATEWAY_AUTH_TOKEN";
|
|
128
128
|
const maxConcurrentRequests = readIntegerOption(args, "--max-concurrent-requests", 10_000);
|
|
129
|
+
const maxRequestBodyBytes = readIntegerOption(args, "--max-request-body-bytes", 64 * 1024 * 1024);
|
|
130
|
+
const maxLegacySessions = readIntegerOption(args, "--max-legacy-sessions", 10_000);
|
|
129
131
|
validateCliArgs(args);
|
|
130
|
-
if (!enableHttp && (host || port || path || enableAdminTools || maxConcurrentRequests ||
|
|
132
|
+
if (!enableHttp && (host || port || path || enableAdminTools || maxConcurrentRequests || maxRequestBodyBytes || maxLegacySessions
|
|
133
|
+
|| args.includes("--auth-token-env"))) {
|
|
131
134
|
throw new Error("HTTP options require --http.");
|
|
132
135
|
}
|
|
133
136
|
return {
|
|
@@ -140,7 +143,9 @@ export function parseCliArgs(args) {
|
|
|
140
143
|
path: path ?? "/mcp",
|
|
141
144
|
authToken: process.env[authTokenEnv],
|
|
142
145
|
enableAdminTools,
|
|
143
|
-
maxConcurrentRequests: maxConcurrentRequests ?? 64
|
|
146
|
+
maxConcurrentRequests: maxConcurrentRequests ?? 64,
|
|
147
|
+
maxRequestBodyBytes: maxRequestBodyBytes ?? 16 * 1024 * 1024,
|
|
148
|
+
maxLegacySessions: maxLegacySessions ?? 256
|
|
144
149
|
}
|
|
145
150
|
: undefined
|
|
146
151
|
};
|
|
@@ -174,7 +179,16 @@ function readIntegerOption(args, name, maximum = 65_535) {
|
|
|
174
179
|
*/
|
|
175
180
|
function validateCliArgs(args) {
|
|
176
181
|
const switches = new Set(["--http", "--http-admin-tools", "-v", "--version"]);
|
|
177
|
-
const valued = new Set([
|
|
182
|
+
const valued = new Set([
|
|
183
|
+
"--config",
|
|
184
|
+
"--port",
|
|
185
|
+
"--host",
|
|
186
|
+
"--path",
|
|
187
|
+
"--auth-token-env",
|
|
188
|
+
"--max-concurrent-requests",
|
|
189
|
+
"--max-request-body-bytes",
|
|
190
|
+
"--max-legacy-sessions"
|
|
191
|
+
]);
|
|
178
192
|
const seen = new Set();
|
|
179
193
|
for (let index = 0; index < args.length; index += 1) {
|
|
180
194
|
const arg = args[index];
|
package/dist/service-registry.js
CHANGED
|
@@ -23,13 +23,6 @@ export class ServiceRegistry {
|
|
|
23
23
|
/**
|
|
24
24
|
* Stores the last valid config snapshot.
|
|
25
25
|
*/
|
|
26
|
-
currentConfig = {
|
|
27
|
-
logging: {
|
|
28
|
-
enable: false,
|
|
29
|
-
path: null
|
|
30
|
-
},
|
|
31
|
-
services: []
|
|
32
|
-
};
|
|
33
26
|
/**
|
|
34
27
|
* Stores the current immutable runtime view used by request handlers.
|
|
35
28
|
*/
|
|
@@ -98,7 +91,6 @@ export class ServiceRegistry {
|
|
|
98
91
|
throw error;
|
|
99
92
|
}
|
|
100
93
|
const previousClients = this.clients;
|
|
101
|
-
this.currentConfig = nextConfig;
|
|
102
94
|
this.snapshots = nextSnapshots;
|
|
103
95
|
this.clients = nextClients;
|
|
104
96
|
await disposeRemovedClients(previousClients, nextClients);
|
|
@@ -208,13 +200,13 @@ export class ServiceRegistry {
|
|
|
208
200
|
*/
|
|
209
201
|
async reconnectService(serviceId) {
|
|
210
202
|
const snapshot = this.requireService(serviceId);
|
|
203
|
+
const previousRuntime = snapshot.runtime;
|
|
211
204
|
const currentClient = this.clients.get(serviceId);
|
|
212
205
|
if (!currentClient) {
|
|
213
206
|
throw new Error(`Service '${serviceId}' is unavailable.`);
|
|
214
207
|
}
|
|
215
208
|
const nextClient = createClient(snapshot.config, this.logger);
|
|
216
209
|
try {
|
|
217
|
-
await currentClient.dispose().catch(() => undefined);
|
|
218
210
|
const metadata = await nextClient.getMetadata();
|
|
219
211
|
snapshot.metadata = metadata;
|
|
220
212
|
snapshot.runtime = {
|
|
@@ -224,6 +216,7 @@ export class ServiceRegistry {
|
|
|
224
216
|
restartAttempts: nextClient.restartCount
|
|
225
217
|
};
|
|
226
218
|
this.clients.set(serviceId, nextClient);
|
|
219
|
+
await currentClient.dispose().catch(() => undefined);
|
|
227
220
|
return {
|
|
228
221
|
serviceId,
|
|
229
222
|
action: "reconnect",
|
|
@@ -235,17 +228,16 @@ export class ServiceRegistry {
|
|
|
235
228
|
await nextClient.dispose().catch(() => undefined);
|
|
236
229
|
const message = error instanceof Error ? error.message : String(error);
|
|
237
230
|
snapshot.runtime = {
|
|
238
|
-
available:
|
|
239
|
-
lastError: message
|
|
240
|
-
lastConnectedAt:
|
|
231
|
+
available: previousRuntime.available,
|
|
232
|
+
lastError: `Reconnect failed; existing connection retained: ${message}`,
|
|
233
|
+
lastConnectedAt: previousRuntime.lastConnectedAt,
|
|
241
234
|
restartAttempts: currentClient.restartCount
|
|
242
235
|
};
|
|
243
|
-
this.clients.set(serviceId, currentClient);
|
|
244
236
|
return {
|
|
245
237
|
serviceId,
|
|
246
238
|
action: "reconnect",
|
|
247
239
|
enabled: true,
|
|
248
|
-
available:
|
|
240
|
+
available: previousRuntime.available
|
|
249
241
|
};
|
|
250
242
|
}
|
|
251
243
|
}
|
package/package.json
CHANGED
|
@@ -1,40 +1,27 @@
|
|
|
1
|
-
---
|
|
2
|
-
name: mcp-gateway
|
|
3
|
-
description: Route work through an MCP gateway with token-efficient downstream service discovery, filtered tool search, exact schema lookup, service diagnostics, and forwarded tool calls. Use when an agent needs to find or call tools behind the gateway without loading every downstream schema.
|
|
4
|
-
---
|
|
5
|
-
|
|
6
|
-
# MCP Gateway
|
|
7
|
-
|
|
8
|
-
Use the gateway as the single entry point for downstream MCP services.
|
|
9
|
-
|
|
10
|
-
##
|
|
11
|
-
|
|
12
|
-
1. Reuse an exact `serviceId` already confirmed in the current session; otherwise call `gateway_list_services`.
|
|
13
|
-
2. Reuse an exact downstream tool name already confirmed in the
|
|
14
|
-
3.
|
|
15
|
-
4.
|
|
16
|
-
5.
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
-
|
|
26
|
-
-
|
|
27
|
-
-
|
|
28
|
-
|
|
29
|
-
## Diagnostics and Control
|
|
30
|
-
|
|
31
|
-
- Use `gateway_get_service` only when connection state, protocol details, server identity, or recent errors matter.
|
|
32
|
-
- Use `gateway_manage_service` only when the user explicitly requests reconnecting, enabling, or disabling a service.
|
|
33
|
-
- Treat `reconnect` as a connection refresh that does not change config.
|
|
34
|
-
- Treat `enable` and `disable` as persistent config changes.
|
|
35
|
-
|
|
36
|
-
## Safety
|
|
37
|
-
|
|
38
|
-
- Apply the downstream tool's schema, side-effect rules, and confirmation flow before calling it.
|
|
39
|
-
- Treat gateway failures and structured downstream error results as failures.
|
|
40
|
-
- Never auto-approve an `input_required` result. Obtain the requested user input and retry with the returned opaque state and matching responses.
|
|
1
|
+
---
|
|
2
|
+
name: mcp-gateway
|
|
3
|
+
description: Route work through an MCP gateway with token-efficient downstream service discovery, filtered tool search, exact schema lookup, service diagnostics, and forwarded tool calls. Use when an agent needs to find or call tools behind the gateway without loading every downstream schema.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# MCP Gateway
|
|
7
|
+
|
|
8
|
+
Use the gateway as the single entry point for downstream MCP services.
|
|
9
|
+
|
|
10
|
+
## Workflow
|
|
11
|
+
|
|
12
|
+
1. Reuse an exact `serviceId` already confirmed in the current session; otherwise call `gateway_list_services`.
|
|
13
|
+
2. Reuse an exact downstream tool name already confirmed in the session; otherwise search only that service with `gateway_list_tools`. The unique non-empty `toolName` and `desc` filters are case-insensitive literal substrings joined by OR, so inspect description matches for negative guidance.
|
|
14
|
+
3. Obtain unfamiliar or safety-sensitive schemas with `includeSchema: true` or `gateway_get_tool_schema`; tool names are exact and case-sensitive.
|
|
15
|
+
4. Call `gateway_call_tool` with the confirmed identifiers and an explicit `arguments` object; pass `{}` when the tool has no arguments.
|
|
16
|
+
5. Refresh only the identifier or schema rejected as stale.
|
|
17
|
+
|
|
18
|
+
## Diagnostics and Control
|
|
19
|
+
|
|
20
|
+
- Treat `serviceId` as a downstream identifier, never as a gateway-owned tool.
|
|
21
|
+
- Use `gateway_get_service` for connection diagnostics. Use `gateway_manage_service` only when explicitly requested: `reconnect` does not change config, while `enable` and `disable` persist.
|
|
22
|
+
|
|
23
|
+
## Safety
|
|
24
|
+
|
|
25
|
+
- Apply the downstream tool's schema, side-effect rules, and confirmation flow before calling it.
|
|
26
|
+
- Treat gateway failures and structured downstream error results as failures.
|
|
27
|
+
- Never auto-approve an `input_required` result. Obtain the requested user input and retry with the returned opaque state and matching responses.
|