@jadchene/mcp-gateway-service 0.6.4 → 0.7.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 +196 -153
- package/README_zh.md +196 -153
- package/config.example.json +34 -30
- package/dist/config.js +47 -5
- package/dist/file-watcher.js +16 -2
- package/dist/gateway-engine.js +5 -2
- package/dist/http-server.js +57 -1
- package/dist/index.js +41 -6
- package/dist/logger.js +83 -49
- package/dist/mcp/client.js +11 -4
- package/dist/mcp/form-elicitation-bridge.js +51 -2
- package/dist/mcp/sdk-client.js +30 -4
- package/dist/mcp/server.js +5 -5
- package/dist/service-registry.js +97 -31
- package/package.json +16 -12
- package/scripts/install-global.ps1 +46 -15
- package/skills/mcp-gateway/SKILL.md +26 -90
package/dist/http-server.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import http from "node:http";
|
|
2
|
+
import { timingSafeEqual } from "node:crypto";
|
|
2
3
|
import { createMcpHandler } from "@modelcontextprotocol/server";
|
|
3
4
|
import { hostHeaderValidation, originValidation, toNodeHandler } from "@modelcontextprotocol/node";
|
|
4
5
|
import { createGatewayMcpServer } from "./mcp/server.js";
|
|
@@ -24,7 +25,9 @@ export class StreamableHttpGatewayServer {
|
|
|
24
25
|
constructor(config, engine, logger) {
|
|
25
26
|
this.config = config;
|
|
26
27
|
this.logger = logger;
|
|
27
|
-
this.handler = createMcpHandler(() => createGatewayMcpServer(engine
|
|
28
|
+
this.handler = createMcpHandler(() => createGatewayMcpServer(engine, {
|
|
29
|
+
includeAdminTools: config.enableAdminTools ?? false
|
|
30
|
+
}), {
|
|
28
31
|
legacy: "stateless",
|
|
29
32
|
onerror: (error) => {
|
|
30
33
|
this.logger.error("gateway.http_protocol_error", { message: error.message });
|
|
@@ -38,12 +41,20 @@ export class StreamableHttpGatewayServer {
|
|
|
38
41
|
if (this.server) {
|
|
39
42
|
return;
|
|
40
43
|
}
|
|
44
|
+
if (!isLoopbackHost(this.config.host) && !this.config.authToken) {
|
|
45
|
+
throw new Error("HTTP bearer authentication is required when binding to a non-loopback host.");
|
|
46
|
+
}
|
|
47
|
+
if (this.config.enableAdminTools && !this.config.authToken) {
|
|
48
|
+
throw new Error("HTTP admin tools require bearer authentication.");
|
|
49
|
+
}
|
|
41
50
|
const allowedHosts = allowedHostnames(this.config.host);
|
|
42
51
|
const validateHost = hostHeaderValidation(allowedHosts);
|
|
43
52
|
const validateOrigin = originValidation(allowedHosts);
|
|
44
53
|
const handleMcp = toNodeHandler(this.handler, {
|
|
45
54
|
onerror: (error) => this.logger.error("gateway.http_adapter_error", { message: error.message })
|
|
46
55
|
});
|
|
56
|
+
const maxConcurrentRequests = this.config.maxConcurrentRequests ?? 64;
|
|
57
|
+
let activeRequests = 0;
|
|
47
58
|
this.server = http.createServer((request, response) => {
|
|
48
59
|
const pathname = new URL(request.url ?? "/", "http://localhost").pathname;
|
|
49
60
|
if (pathname !== this.config.path) {
|
|
@@ -53,6 +64,24 @@ export class StreamableHttpGatewayServer {
|
|
|
53
64
|
if (!validateHost(request, response) || !validateOrigin(request, response)) {
|
|
54
65
|
return;
|
|
55
66
|
}
|
|
67
|
+
if (!hasValidBearerToken(request, this.config.authToken)) {
|
|
68
|
+
response.writeHead(401, { "WWW-Authenticate": "Bearer" }).end();
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
if (activeRequests >= maxConcurrentRequests) {
|
|
72
|
+
response.writeHead(503, { "Retry-After": "1" }).end();
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
activeRequests += 1;
|
|
76
|
+
let released = false;
|
|
77
|
+
const release = () => {
|
|
78
|
+
if (!released) {
|
|
79
|
+
released = true;
|
|
80
|
+
activeRequests -= 1;
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
response.once("finish", release);
|
|
84
|
+
response.once("close", release);
|
|
56
85
|
void handleMcp(request, response);
|
|
57
86
|
});
|
|
58
87
|
await new Promise((resolveListen, rejectListen) => {
|
|
@@ -84,6 +113,33 @@ export class StreamableHttpGatewayServer {
|
|
|
84
113
|
});
|
|
85
114
|
}
|
|
86
115
|
}
|
|
116
|
+
/**
|
|
117
|
+
* Compares a supplied bearer credential without leaking a useful timing signal.
|
|
118
|
+
*/
|
|
119
|
+
function hasValidBearerToken(request, expectedToken) {
|
|
120
|
+
if (!expectedToken) {
|
|
121
|
+
return true;
|
|
122
|
+
}
|
|
123
|
+
const supplied = request.headers.authorization;
|
|
124
|
+
const expected = `Bearer ${expectedToken}`;
|
|
125
|
+
if (!supplied) {
|
|
126
|
+
return false;
|
|
127
|
+
}
|
|
128
|
+
const suppliedBytes = Buffer.from(supplied);
|
|
129
|
+
const expectedBytes = Buffer.from(expected);
|
|
130
|
+
return suppliedBytes.length === expectedBytes.length
|
|
131
|
+
&& timingSafeEqual(suppliedBytes, expectedBytes);
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Identifies bind addresses that do not expose the gateway off-machine.
|
|
135
|
+
*/
|
|
136
|
+
function isLoopbackHost(host) {
|
|
137
|
+
const normalized = host.toLowerCase();
|
|
138
|
+
return normalized === "localhost"
|
|
139
|
+
|| normalized === "::1"
|
|
140
|
+
|| normalized === "[::1]"
|
|
141
|
+
|| /^127(?:\.\d{1,3}){3}$/.test(normalized);
|
|
142
|
+
}
|
|
87
143
|
/**
|
|
88
144
|
* Builds the Host and Origin allow-list for the configured bind address.
|
|
89
145
|
*/
|
package/dist/index.js
CHANGED
|
@@ -20,7 +20,7 @@ class Application {
|
|
|
20
20
|
/**
|
|
21
21
|
* Stores a shared logger instance.
|
|
22
22
|
*/
|
|
23
|
-
logger = new Logger();
|
|
23
|
+
logger = new Logger(true);
|
|
24
24
|
/**
|
|
25
25
|
* Stores the config file path in use for the current process.
|
|
26
26
|
*/
|
|
@@ -103,11 +103,11 @@ class Application {
|
|
|
103
103
|
}
|
|
104
104
|
}
|
|
105
105
|
if (import.meta.main) {
|
|
106
|
-
const application = new Application();
|
|
107
106
|
if (process.argv.includes("-v") || process.argv.includes("--version")) {
|
|
108
107
|
process.stdout.write(`${VERSION}\n`);
|
|
109
108
|
process.exit(0);
|
|
110
109
|
}
|
|
110
|
+
const application = new Application();
|
|
111
111
|
void application.start().catch((error) => {
|
|
112
112
|
const message = error instanceof Error ? error.message : String(error);
|
|
113
113
|
process.stderr.write(`${message}\n`);
|
|
@@ -123,6 +123,13 @@ export function parseCliArgs(args) {
|
|
|
123
123
|
const host = readOption(args, "--host");
|
|
124
124
|
const path = readHttpPathOption(args);
|
|
125
125
|
const enableHttp = args.includes("--http");
|
|
126
|
+
const enableAdminTools = args.includes("--http-admin-tools");
|
|
127
|
+
const authTokenEnv = readOption(args, "--auth-token-env") ?? "MCP_GATEWAY_AUTH_TOKEN";
|
|
128
|
+
const maxConcurrentRequests = readIntegerOption(args, "--max-concurrent-requests", 10_000);
|
|
129
|
+
validateCliArgs(args);
|
|
130
|
+
if (!enableHttp && (host || port || path || enableAdminTools || maxConcurrentRequests || args.includes("--auth-token-env"))) {
|
|
131
|
+
throw new Error("HTTP options require --http.");
|
|
132
|
+
}
|
|
126
133
|
return {
|
|
127
134
|
configPath,
|
|
128
135
|
server: enableHttp
|
|
@@ -130,7 +137,10 @@ export function parseCliArgs(args) {
|
|
|
130
137
|
enable: true,
|
|
131
138
|
host: host ?? "127.0.0.1",
|
|
132
139
|
port: port ?? 3000,
|
|
133
|
-
path: path ?? "/mcp"
|
|
140
|
+
path: path ?? "/mcp",
|
|
141
|
+
authToken: process.env[authTokenEnv],
|
|
142
|
+
enableAdminTools,
|
|
143
|
+
maxConcurrentRequests: maxConcurrentRequests ?? 64
|
|
134
144
|
}
|
|
135
145
|
: undefined
|
|
136
146
|
};
|
|
@@ -148,17 +158,42 @@ function readOption(args, name) {
|
|
|
148
158
|
/**
|
|
149
159
|
* Reads an integer option from argv.
|
|
150
160
|
*/
|
|
151
|
-
function readIntegerOption(args, name) {
|
|
161
|
+
function readIntegerOption(args, name, maximum = 65_535) {
|
|
152
162
|
const value = readOption(args, name);
|
|
153
163
|
if (value === undefined) {
|
|
154
164
|
return undefined;
|
|
155
165
|
}
|
|
156
166
|
const parsed = Number(value);
|
|
157
|
-
if (!Number.isInteger(parsed) || parsed < 1 || parsed >
|
|
158
|
-
throw new Error(`${name} must be an integer from 1 to
|
|
167
|
+
if (!Number.isInteger(parsed) || parsed < 1 || parsed > maximum) {
|
|
168
|
+
throw new Error(`${name} must be an integer from 1 to ${maximum}.`);
|
|
159
169
|
}
|
|
160
170
|
return parsed;
|
|
161
171
|
}
|
|
172
|
+
/**
|
|
173
|
+
* Rejects unknown flags, duplicate options, and missing option values.
|
|
174
|
+
*/
|
|
175
|
+
function validateCliArgs(args) {
|
|
176
|
+
const switches = new Set(["--http", "--http-admin-tools", "-v", "--version"]);
|
|
177
|
+
const valued = new Set(["--config", "--port", "--host", "--path", "--auth-token-env", "--max-concurrent-requests"]);
|
|
178
|
+
const seen = new Set();
|
|
179
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
180
|
+
const arg = args[index];
|
|
181
|
+
if (!switches.has(arg) && !valued.has(arg)) {
|
|
182
|
+
throw new Error(`Unknown option '${arg}'.`);
|
|
183
|
+
}
|
|
184
|
+
if (seen.has(arg)) {
|
|
185
|
+
throw new Error(`Option '${arg}' was provided more than once.`);
|
|
186
|
+
}
|
|
187
|
+
seen.add(arg);
|
|
188
|
+
if (valued.has(arg)) {
|
|
189
|
+
const value = args[index + 1];
|
|
190
|
+
if (!value || value.startsWith("-")) {
|
|
191
|
+
throw new Error(`Option '${arg}' requires a value.`);
|
|
192
|
+
}
|
|
193
|
+
index += 1;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
}
|
|
162
197
|
/**
|
|
163
198
|
* Reads and validates the inbound HTTP endpoint path option.
|
|
164
199
|
*/
|
package/dist/logger.js
CHANGED
|
@@ -1,74 +1,108 @@
|
|
|
1
|
-
import { mkdirSync
|
|
1
|
+
import { mkdirSync } from "node:fs";
|
|
2
|
+
import { appendFile, rename, stat, unlink } from "node:fs/promises";
|
|
2
3
|
import { dirname, resolve } from "node:path";
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
4
|
+
const DEFAULT_MAX_BYTES = 10 * 1024 * 1024;
|
|
5
|
+
const MAX_STRING_LENGTH = 8_192;
|
|
6
|
+
const SENSITIVE_KEY = /(?:authorization|cookie|token|secret|password|api[-_]?key|credential)/i;
|
|
7
|
+
/** Provides queued, bounded, redacting structured file logging. */
|
|
6
8
|
export class Logger {
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
};
|
|
14
|
-
/**
|
|
15
|
-
* Updates the effective logging config at runtime.
|
|
16
|
-
*/
|
|
9
|
+
config = { enable: false, path: null, maxBytes: DEFAULT_MAX_BYTES };
|
|
10
|
+
queue = Promise.resolve();
|
|
11
|
+
stderr;
|
|
12
|
+
constructor(stderr = false) {
|
|
13
|
+
this.stderr = stderr;
|
|
14
|
+
}
|
|
17
15
|
configure(config) {
|
|
18
16
|
this.config = {
|
|
19
17
|
enable: config.enable,
|
|
20
|
-
path: config.path ? resolve(config.path) : null
|
|
18
|
+
path: config.path ? resolve(config.path) : null,
|
|
19
|
+
maxBytes: config.maxBytes ?? DEFAULT_MAX_BYTES
|
|
21
20
|
};
|
|
22
|
-
if (
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
/**
|
|
30
|
-
* Ignores directory creation failures so logging never blocks MCP traffic.
|
|
31
|
-
*/
|
|
21
|
+
if (this.config.enable && this.config.path) {
|
|
22
|
+
try {
|
|
23
|
+
mkdirSync(dirname(this.config.path), { recursive: true });
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
// Logging failures must not block protocol traffic.
|
|
27
|
+
}
|
|
32
28
|
}
|
|
33
29
|
}
|
|
34
|
-
/**
|
|
35
|
-
* Logs one structured info event.
|
|
36
|
-
*/
|
|
37
30
|
info(event, details = {}) {
|
|
38
31
|
this.write("info", event, details);
|
|
39
32
|
}
|
|
40
|
-
/**
|
|
41
|
-
* Logs one structured warning event.
|
|
42
|
-
*/
|
|
43
33
|
warn(event, details = {}) {
|
|
44
34
|
this.write("warn", event, details);
|
|
45
35
|
}
|
|
46
|
-
/**
|
|
47
|
-
* Logs one structured error event.
|
|
48
|
-
*/
|
|
49
36
|
error(event, details = {}) {
|
|
50
37
|
this.write("error", event, details);
|
|
51
38
|
}
|
|
52
|
-
/**
|
|
53
|
-
|
|
54
|
-
|
|
39
|
+
/** Waits until all queued log entries have been attempted. */
|
|
40
|
+
async flush() {
|
|
41
|
+
await this.queue;
|
|
42
|
+
}
|
|
55
43
|
write(level, event, details) {
|
|
56
|
-
|
|
57
|
-
return;
|
|
58
|
-
}
|
|
59
|
-
const payload = {
|
|
44
|
+
const payload = JSON.stringify({
|
|
60
45
|
timestamp: new Date().toISOString(),
|
|
61
46
|
level,
|
|
62
47
|
event,
|
|
63
|
-
...details
|
|
64
|
-
};
|
|
65
|
-
|
|
66
|
-
|
|
48
|
+
...sanitize(details)
|
|
49
|
+
});
|
|
50
|
+
const config = { ...this.config };
|
|
51
|
+
if (level === "error" && this.stderr) {
|
|
52
|
+
process.stderr.write(`${payload}\n`);
|
|
67
53
|
}
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
* Ignores append failures so the gateway stays usable even if logging breaks.
|
|
71
|
-
*/
|
|
54
|
+
if (!config.enable || !config.path) {
|
|
55
|
+
return;
|
|
72
56
|
}
|
|
57
|
+
this.queue = this.queue.catch(() => undefined).then(async () => {
|
|
58
|
+
try {
|
|
59
|
+
const size = await stat(config.path).then((value) => value.size).catch(() => 0);
|
|
60
|
+
if (size + Buffer.byteLength(payload, "utf8") + 1 > (config.maxBytes ?? DEFAULT_MAX_BYTES)) {
|
|
61
|
+
await unlink(`${config.path}.1`).catch(() => undefined);
|
|
62
|
+
await rename(config.path, `${config.path}.1`).catch(() => undefined);
|
|
63
|
+
}
|
|
64
|
+
await appendFile(config.path, `${payload}\n`, "utf8");
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
// Logging failures must not block protocol traffic.
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/** Redacts sensitive fields and limits attacker-controlled log volume. */
|
|
73
|
+
function sanitize(value, key = "", seen = new WeakSet(), budget = { remaining: 200 }, depth = 0) {
|
|
74
|
+
if (budget.remaining <= 0 || depth > 8) {
|
|
75
|
+
return "[Truncated]";
|
|
76
|
+
}
|
|
77
|
+
budget.remaining -= 1;
|
|
78
|
+
if (SENSITIVE_KEY.test(key)) {
|
|
79
|
+
return "[REDACTED]";
|
|
80
|
+
}
|
|
81
|
+
if (typeof value === "string") {
|
|
82
|
+
const redacted = value
|
|
83
|
+
.replace(/\bBearer\s+[^\s,;]+/gi, "Bearer [REDACTED]")
|
|
84
|
+
.replace(/\b(api[-_]?key|token|password|secret)=([^\s&]+)/gi, "$1=[REDACTED]");
|
|
85
|
+
return redacted.length > MAX_STRING_LENGTH
|
|
86
|
+
? `${redacted.slice(0, MAX_STRING_LENGTH)}...[truncated]`
|
|
87
|
+
: redacted;
|
|
88
|
+
}
|
|
89
|
+
if (typeof value === "bigint") {
|
|
90
|
+
return value.toString();
|
|
91
|
+
}
|
|
92
|
+
if (typeof value === "function" || typeof value === "symbol") {
|
|
93
|
+
return String(value);
|
|
94
|
+
}
|
|
95
|
+
if (!value || typeof value !== "object") {
|
|
96
|
+
return value;
|
|
97
|
+
}
|
|
98
|
+
if (seen.has(value)) {
|
|
99
|
+
return "[Circular]";
|
|
100
|
+
}
|
|
101
|
+
seen.add(value);
|
|
102
|
+
if (Array.isArray(value)) {
|
|
103
|
+
return value.slice(0, 100).map((item) => sanitize(item, key, seen, budget, depth + 1));
|
|
73
104
|
}
|
|
105
|
+
return Object.fromEntries(Object.entries(value)
|
|
106
|
+
.slice(0, 100)
|
|
107
|
+
.map(([childKey, childValue]) => [childKey, sanitize(childValue, childKey, seen, budget, depth + 1)]));
|
|
74
108
|
}
|
package/dist/mcp/client.js
CHANGED
|
@@ -14,7 +14,7 @@ export class StdioMcpClient extends SdkMcpClient {
|
|
|
14
14
|
const transport = requireStdioTransport(service);
|
|
15
15
|
const commandSpec = resolveCommandSpec(transport.command, transport.args ?? []);
|
|
16
16
|
const cwd = transport.cwd ? resolve(transport.cwd) : process.cwd();
|
|
17
|
-
const environment = mergeEnvironment(transport.env);
|
|
17
|
+
const environment = mergeEnvironment(transport.env, transport.inheritEnv ?? false, transport.envAllowlist ?? []);
|
|
18
18
|
super(service, logger, () => createStandardTransport(commandSpec.command, commandSpec.args, cwd, environment, logger, service.serviceId));
|
|
19
19
|
}
|
|
20
20
|
}
|
|
@@ -159,9 +159,16 @@ function requireStdioTransport(service) {
|
|
|
159
159
|
return service.transport;
|
|
160
160
|
}
|
|
161
161
|
/**
|
|
162
|
-
*
|
|
162
|
+
* Builds a least-privilege child environment with explicit opt-in for full inheritance.
|
|
163
163
|
*/
|
|
164
|
-
function mergeEnvironment(overrides) {
|
|
165
|
-
const
|
|
164
|
+
export function mergeEnvironment(overrides, inheritEnv = false, allowlist = []) {
|
|
165
|
+
const safeNames = process.platform === "win32"
|
|
166
|
+
? ["PATH", "SystemRoot", "WINDIR", "PATHEXT", "COMSPEC", "TEMP", "TMP", "USERPROFILE"]
|
|
167
|
+
: ["PATH", "HOME", "TMPDIR", "TMP", "LANG", "LC_ALL"];
|
|
168
|
+
const names = inheritEnv ? Object.keys(process.env) : [...new Set([...safeNames, ...allowlist])];
|
|
169
|
+
const inherited = Object.fromEntries(names.flatMap((name) => {
|
|
170
|
+
const value = process.env[name];
|
|
171
|
+
return value === undefined ? [] : [[name, value]];
|
|
172
|
+
}));
|
|
166
173
|
return { ...inherited, ...overrides };
|
|
167
174
|
}
|
|
@@ -7,8 +7,13 @@ const INPUT_RESPONSE_KEY = "form";
|
|
|
7
7
|
* Serializes 2025-era downstream calls and bridges their push-style form elicitation.
|
|
8
8
|
*/
|
|
9
9
|
export class FormElicitationBridge {
|
|
10
|
-
mutex
|
|
10
|
+
mutex;
|
|
11
|
+
continuationTtlMs;
|
|
11
12
|
activeCall = null;
|
|
13
|
+
constructor(options = {}) {
|
|
14
|
+
this.continuationTtlMs = options.continuationTtlMs ?? 10 * 60_000;
|
|
15
|
+
this.mutex = new AsyncMutex(options.maxQueueSize ?? 32, options.queueTimeoutMs ?? 30_000);
|
|
16
|
+
}
|
|
12
17
|
/**
|
|
13
18
|
* Executes or resumes one 2025-era downstream tool call.
|
|
14
19
|
*/
|
|
@@ -70,6 +75,10 @@ export class FormElicitationBridge {
|
|
|
70
75
|
if (state.name !== name || !isDeepStrictEqual(state.args, args)) {
|
|
71
76
|
throw new ProtocolError(ProtocolErrorCode.InvalidParams, "Form elicitation retry does not match the original downstream tool call.");
|
|
72
77
|
}
|
|
78
|
+
if (state.expiryTimer) {
|
|
79
|
+
clearTimeout(state.expiryTimer);
|
|
80
|
+
state.expiryTimer = null;
|
|
81
|
+
}
|
|
73
82
|
const pending = state.pendingElicitation;
|
|
74
83
|
if (pending && Object.hasOwn(context.inputResponses ?? {}, INPUT_RESPONSE_KEY)) {
|
|
75
84
|
state.pendingElicitation = null;
|
|
@@ -100,6 +109,15 @@ export class FormElicitationBridge {
|
|
|
100
109
|
return outcome.value;
|
|
101
110
|
}
|
|
102
111
|
state.parked = true;
|
|
112
|
+
state.expiryTimer = setTimeout(() => {
|
|
113
|
+
const reason = new Error("Form elicitation state expired before it was resumed.");
|
|
114
|
+
state.outcome = { status: "rejected", error: reason };
|
|
115
|
+
state.abortController.abort(reason);
|
|
116
|
+
state.pendingElicitation?.response.reject(reason);
|
|
117
|
+
notifyStateChanged(state);
|
|
118
|
+
this.release(state);
|
|
119
|
+
}, this.continuationTtlMs);
|
|
120
|
+
state.expiryTimer.unref();
|
|
103
121
|
return buildInputRequiredResult(state);
|
|
104
122
|
}
|
|
105
123
|
finally {
|
|
@@ -134,6 +152,10 @@ export class FormElicitationBridge {
|
|
|
134
152
|
return;
|
|
135
153
|
}
|
|
136
154
|
state.released = true;
|
|
155
|
+
if (state.expiryTimer) {
|
|
156
|
+
clearTimeout(state.expiryTimer);
|
|
157
|
+
state.expiryTimer = null;
|
|
158
|
+
}
|
|
137
159
|
state.pendingElicitation = null;
|
|
138
160
|
if (this.activeCall === state) {
|
|
139
161
|
this.activeCall = null;
|
|
@@ -147,6 +169,12 @@ export class FormElicitationBridge {
|
|
|
147
169
|
class AsyncMutex {
|
|
148
170
|
locked = false;
|
|
149
171
|
queue = [];
|
|
172
|
+
maxQueueSize;
|
|
173
|
+
queueTimeoutMs;
|
|
174
|
+
constructor(maxQueueSize, queueTimeoutMs) {
|
|
175
|
+
this.maxQueueSize = maxQueueSize;
|
|
176
|
+
this.queueTimeoutMs = queueTimeoutMs;
|
|
177
|
+
}
|
|
150
178
|
/**
|
|
151
179
|
* Acquires the lock and returns an idempotent release callback.
|
|
152
180
|
*/
|
|
@@ -158,14 +186,31 @@ class AsyncMutex {
|
|
|
158
186
|
this.locked = true;
|
|
159
187
|
return createRelease(() => this.releaseNext());
|
|
160
188
|
}
|
|
189
|
+
if (this.queue.length >= this.maxQueueSize) {
|
|
190
|
+
throw new Error(`Legacy form-elicitation queue is full (${this.maxQueueSize} waiting calls).`);
|
|
191
|
+
}
|
|
161
192
|
return new Promise((resolve, reject) => {
|
|
162
193
|
const waiter = { resolve, reject, signal };
|
|
194
|
+
waiter.timer = setTimeout(() => {
|
|
195
|
+
const index = this.queue.indexOf(waiter);
|
|
196
|
+
if (index >= 0) {
|
|
197
|
+
this.queue.splice(index, 1);
|
|
198
|
+
}
|
|
199
|
+
if (waiter.abort && waiter.signal) {
|
|
200
|
+
waiter.signal.removeEventListener("abort", waiter.abort);
|
|
201
|
+
}
|
|
202
|
+
reject(new Error("Timed out waiting for the legacy form-elicitation queue."));
|
|
203
|
+
}, this.queueTimeoutMs);
|
|
204
|
+
waiter.timer.unref();
|
|
163
205
|
if (signal) {
|
|
164
206
|
waiter.abort = () => {
|
|
165
207
|
const index = this.queue.indexOf(waiter);
|
|
166
208
|
if (index >= 0) {
|
|
167
209
|
this.queue.splice(index, 1);
|
|
168
210
|
}
|
|
211
|
+
if (waiter.timer) {
|
|
212
|
+
clearTimeout(waiter.timer);
|
|
213
|
+
}
|
|
169
214
|
reject(abortReason(signal));
|
|
170
215
|
};
|
|
171
216
|
signal.addEventListener("abort", waiter.abort, { once: true });
|
|
@@ -185,6 +230,9 @@ class AsyncMutex {
|
|
|
185
230
|
if (waiter.abort && waiter.signal) {
|
|
186
231
|
waiter.signal.removeEventListener("abort", waiter.abort);
|
|
187
232
|
}
|
|
233
|
+
if (waiter.timer) {
|
|
234
|
+
clearTimeout(waiter.timer);
|
|
235
|
+
}
|
|
188
236
|
waiter.resolve(createRelease(() => this.releaseNext()));
|
|
189
237
|
}
|
|
190
238
|
}
|
|
@@ -203,7 +251,8 @@ function createActiveCall(name, args, elicitForm, release) {
|
|
|
203
251
|
abortController: new AbortController(),
|
|
204
252
|
pendingElicitation: null,
|
|
205
253
|
outcome: null,
|
|
206
|
-
changed: createDeferred()
|
|
254
|
+
changed: createDeferred(),
|
|
255
|
+
expiryTimer: null
|
|
207
256
|
};
|
|
208
257
|
}
|
|
209
258
|
/**
|
package/dist/mcp/sdk-client.js
CHANGED
|
@@ -4,6 +4,9 @@ import { FormElicitationBridge } from "./form-elicitation-bridge.js";
|
|
|
4
4
|
import { SUPPORTED_MCP_PROTOCOL_VERSIONS } from "./versions.js";
|
|
5
5
|
const MAX_RESTART_ATTEMPTS = 3;
|
|
6
6
|
const CONNECT_TIMEOUT_MS = 30_000;
|
|
7
|
+
const DEFAULT_CALL_TIMEOUT_MS = 120_000;
|
|
8
|
+
const MAX_DOWNSTREAM_TOOLS = 5_000;
|
|
9
|
+
const MAX_TOOL_CATALOG_BYTES = 5 * 1024 * 1024;
|
|
7
10
|
/**
|
|
8
11
|
* Implements shared MCP SDK v2 client behavior for stdio and HTTP transports.
|
|
9
12
|
*/
|
|
@@ -109,7 +112,7 @@ export class SdkMcpClient {
|
|
|
109
112
|
* Calls a downstream tool while preserving cancellation, custom headers, and MRTR state.
|
|
110
113
|
*/
|
|
111
114
|
async callTool(name, args, context = {}) {
|
|
112
|
-
|
|
115
|
+
try {
|
|
113
116
|
const client = await this.requireClient();
|
|
114
117
|
const params = {
|
|
115
118
|
name,
|
|
@@ -118,8 +121,9 @@ export class SdkMcpClient {
|
|
|
118
121
|
...(context.requestState ? { requestState: context.requestState } : {})
|
|
119
122
|
};
|
|
120
123
|
const invoke = async (signal) => {
|
|
124
|
+
const callSignal = combineWithTimeout(signal, this.service.callTimeoutMs ?? DEFAULT_CALL_TIMEOUT_MS);
|
|
121
125
|
const result = await client.callTool(params, {
|
|
122
|
-
signal,
|
|
126
|
+
signal: callSignal,
|
|
123
127
|
allowInputRequired: true,
|
|
124
128
|
toolDefinition: this.tools.get(name)
|
|
125
129
|
});
|
|
@@ -130,7 +134,15 @@ export class SdkMcpClient {
|
|
|
130
134
|
}
|
|
131
135
|
const result = await invoke(context.signal ?? new AbortController().signal);
|
|
132
136
|
return result;
|
|
133
|
-
}
|
|
137
|
+
}
|
|
138
|
+
catch (error) {
|
|
139
|
+
const normalized = normalizeError(error);
|
|
140
|
+
if (isNonRetryable(normalized) || context.signal?.aborted) {
|
|
141
|
+
throw normalized;
|
|
142
|
+
}
|
|
143
|
+
await this.disposeConnection();
|
|
144
|
+
throw new Error(`Downstream tool '${name}' failed; execution status is unknown and the gateway did not replay it. ${normalized.message}`, { cause: normalized });
|
|
145
|
+
}
|
|
134
146
|
}
|
|
135
147
|
/**
|
|
136
148
|
* Connects one fresh SDK client and transport.
|
|
@@ -201,6 +213,12 @@ export class SdkMcpClient {
|
|
|
201
213
|
*/
|
|
202
214
|
async requestToolsList(client) {
|
|
203
215
|
const result = await client.listTools();
|
|
216
|
+
if (result.tools.length > MAX_DOWNSTREAM_TOOLS) {
|
|
217
|
+
throw new ResourceLimitError(`Service '${this.key}' returned more than ${MAX_DOWNSTREAM_TOOLS} tools.`);
|
|
218
|
+
}
|
|
219
|
+
if (Buffer.byteLength(JSON.stringify(result.tools), "utf8") > MAX_TOOL_CATALOG_BYTES) {
|
|
220
|
+
throw new ResourceLimitError(`Service '${this.key}' returned a tool catalog larger than ${MAX_TOOL_CATALOG_BYTES} bytes.`);
|
|
221
|
+
}
|
|
204
222
|
this.tools = new Map(result.tools.map((tool) => [tool.name, tool]));
|
|
205
223
|
return result.tools.map(normalizeToolDefinition);
|
|
206
224
|
}
|
|
@@ -271,14 +289,22 @@ function toJsonObject(input) {
|
|
|
271
289
|
* Prevents protocol and explicit HTTP failures from being disguised as reconnects.
|
|
272
290
|
*/
|
|
273
291
|
function isNonRetryable(error) {
|
|
274
|
-
if (error instanceof ProtocolError) {
|
|
292
|
+
if (error instanceof ProtocolError || error instanceof ResourceLimitError) {
|
|
275
293
|
return true;
|
|
276
294
|
}
|
|
277
295
|
return error instanceof SdkHttpError && error.status >= 400 && error.status < 500;
|
|
278
296
|
}
|
|
297
|
+
class ResourceLimitError extends Error {
|
|
298
|
+
}
|
|
279
299
|
/**
|
|
280
300
|
* Normalizes unknown thrown values into Error instances.
|
|
281
301
|
*/
|
|
282
302
|
function normalizeError(error) {
|
|
283
303
|
return error instanceof Error ? error : new Error(String(error));
|
|
284
304
|
}
|
|
305
|
+
/**
|
|
306
|
+
* Applies the configured deadline while preserving caller cancellation.
|
|
307
|
+
*/
|
|
308
|
+
function combineWithTimeout(signal, timeoutMs) {
|
|
309
|
+
return AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]);
|
|
310
|
+
}
|
package/dist/mcp/server.js
CHANGED
|
@@ -3,10 +3,10 @@ import { buildGatewayTools } from "../gateway-engine.js";
|
|
|
3
3
|
import { VERSION } from "../version.js";
|
|
4
4
|
import { SUPPORTED_MCP_PROTOCOL_VERSIONS } from "./versions.js";
|
|
5
5
|
/**
|
|
6
|
-
* Creates one SDK server instance with
|
|
6
|
+
* Creates one SDK server instance with the selected gateway tool surface.
|
|
7
7
|
*/
|
|
8
|
-
export function createGatewayMcpServer(engine) {
|
|
9
|
-
const
|
|
8
|
+
export function createGatewayMcpServer(engine, options = {}) {
|
|
9
|
+
const serverOptions = {
|
|
10
10
|
supportedProtocolVersions: [...SUPPORTED_MCP_PROTOCOL_VERSIONS],
|
|
11
11
|
capabilities: {
|
|
12
12
|
tools: {
|
|
@@ -27,8 +27,8 @@ export function createGatewayMcpServer(engine) {
|
|
|
27
27
|
maxRounds: 8
|
|
28
28
|
}
|
|
29
29
|
};
|
|
30
|
-
const server = new McpServer({ name: "mcp-gateway", version: VERSION },
|
|
31
|
-
for (const tool of buildGatewayTools()) {
|
|
30
|
+
const server = new McpServer({ name: "mcp-gateway", version: VERSION }, serverOptions);
|
|
31
|
+
for (const tool of buildGatewayTools(options)) {
|
|
32
32
|
const inputSchema = fromJsonSchema(tool.inputSchema);
|
|
33
33
|
const outputSchema = tool.outputSchema
|
|
34
34
|
? fromJsonSchema(tool.outputSchema)
|