@jadchene/mcp-gateway-service 0.6.5 → 0.7.1
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 -188
- package/README_zh.md +196 -188
- 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 +153 -4
- 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 +23 -6
- package/dist/service-registry.js +97 -31
- package/package.json +16 -12
- package/scripts/install-global.ps1 +46 -15
package/dist/http-server.js
CHANGED
|
@@ -1,14 +1,20 @@
|
|
|
1
1
|
import http from "node:http";
|
|
2
|
-
import {
|
|
2
|
+
import { randomUUID, timingSafeEqual } from "node:crypto";
|
|
3
|
+
import { createMcpHandler, isLegacyRequest, WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/server";
|
|
3
4
|
import { hostHeaderValidation, originValidation, toNodeHandler } from "@modelcontextprotocol/node";
|
|
4
5
|
import { createGatewayMcpServer } from "./mcp/server.js";
|
|
6
|
+
const LEGACY_SESSION_IDLE_TIMEOUT_MS = 30 * 60 * 1_000;
|
|
7
|
+
const LEGACY_SESSION_SWEEP_INTERVAL_MS = 60 * 1_000;
|
|
5
8
|
/**
|
|
6
9
|
* Exposes the gateway through SDK v2 Streamable HTTP.
|
|
7
10
|
*/
|
|
8
11
|
export class StreamableHttpGatewayServer {
|
|
9
12
|
config;
|
|
13
|
+
engine;
|
|
10
14
|
logger;
|
|
11
15
|
handler;
|
|
16
|
+
legacySessions = new Map();
|
|
17
|
+
legacySessionSweepTimer = null;
|
|
12
18
|
server = null;
|
|
13
19
|
/**
|
|
14
20
|
* Returns the current endpoint URL after the server starts.
|
|
@@ -23,9 +29,12 @@ export class StreamableHttpGatewayServer {
|
|
|
23
29
|
*/
|
|
24
30
|
constructor(config, engine, logger) {
|
|
25
31
|
this.config = config;
|
|
32
|
+
this.engine = engine;
|
|
26
33
|
this.logger = logger;
|
|
27
|
-
this.handler = createMcpHandler(() => createGatewayMcpServer(engine
|
|
28
|
-
|
|
34
|
+
this.handler = createMcpHandler(() => createGatewayMcpServer(engine, {
|
|
35
|
+
includeAdminTools: config.enableAdminTools ?? false
|
|
36
|
+
}), {
|
|
37
|
+
legacy: "reject",
|
|
29
38
|
onerror: (error) => {
|
|
30
39
|
this.logger.error("gateway.http_protocol_error", { message: error.message });
|
|
31
40
|
}
|
|
@@ -38,12 +47,22 @@ export class StreamableHttpGatewayServer {
|
|
|
38
47
|
if (this.server) {
|
|
39
48
|
return;
|
|
40
49
|
}
|
|
50
|
+
if (!isLoopbackHost(this.config.host) && !this.config.authToken) {
|
|
51
|
+
throw new Error("HTTP bearer authentication is required when binding to a non-loopback host.");
|
|
52
|
+
}
|
|
53
|
+
if (this.config.enableAdminTools && !this.config.authToken) {
|
|
54
|
+
throw new Error("HTTP admin tools require bearer authentication.");
|
|
55
|
+
}
|
|
41
56
|
const allowedHosts = allowedHostnames(this.config.host);
|
|
42
57
|
const validateHost = hostHeaderValidation(allowedHosts);
|
|
43
58
|
const validateOrigin = originValidation(allowedHosts);
|
|
44
|
-
const handleMcp = toNodeHandler(
|
|
59
|
+
const handleMcp = toNodeHandler({
|
|
60
|
+
fetch: (request) => this.handleMcpRequest(request)
|
|
61
|
+
}, {
|
|
45
62
|
onerror: (error) => this.logger.error("gateway.http_adapter_error", { message: error.message })
|
|
46
63
|
});
|
|
64
|
+
const maxConcurrentRequests = this.config.maxConcurrentRequests ?? 64;
|
|
65
|
+
let activeRequests = 0;
|
|
47
66
|
this.server = http.createServer((request, response) => {
|
|
48
67
|
const pathname = new URL(request.url ?? "/", "http://localhost").pathname;
|
|
49
68
|
if (pathname !== this.config.path) {
|
|
@@ -53,6 +72,24 @@ export class StreamableHttpGatewayServer {
|
|
|
53
72
|
if (!validateHost(request, response) || !validateOrigin(request, response)) {
|
|
54
73
|
return;
|
|
55
74
|
}
|
|
75
|
+
if (!hasValidBearerToken(request, this.config.authToken)) {
|
|
76
|
+
response.writeHead(401, { "WWW-Authenticate": "Bearer" }).end();
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
if (activeRequests >= maxConcurrentRequests) {
|
|
80
|
+
response.writeHead(503, { "Retry-After": "1" }).end();
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
activeRequests += 1;
|
|
84
|
+
let released = false;
|
|
85
|
+
const release = () => {
|
|
86
|
+
if (!released) {
|
|
87
|
+
released = true;
|
|
88
|
+
activeRequests -= 1;
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
response.once("finish", release);
|
|
92
|
+
response.once("close", release);
|
|
56
93
|
void handleMcp(request, response);
|
|
57
94
|
});
|
|
58
95
|
await new Promise((resolveListen, rejectListen) => {
|
|
@@ -62,6 +99,8 @@ export class StreamableHttpGatewayServer {
|
|
|
62
99
|
resolveListen();
|
|
63
100
|
});
|
|
64
101
|
});
|
|
102
|
+
this.legacySessionSweepTimer = setInterval(() => void this.closeExpiredLegacySessions(), LEGACY_SESSION_SWEEP_INTERVAL_MS);
|
|
103
|
+
this.legacySessionSweepTimer.unref();
|
|
65
104
|
this.logger.info("gateway.http_started", {
|
|
66
105
|
host: this.config.host,
|
|
67
106
|
port: this.config.port,
|
|
@@ -72,6 +111,12 @@ export class StreamableHttpGatewayServer {
|
|
|
72
111
|
* Stops accepting requests and closes all in-flight SDK exchanges.
|
|
73
112
|
*/
|
|
74
113
|
async stop() {
|
|
114
|
+
if (this.legacySessionSweepTimer) {
|
|
115
|
+
clearInterval(this.legacySessionSweepTimer);
|
|
116
|
+
this.legacySessionSweepTimer = null;
|
|
117
|
+
}
|
|
118
|
+
await Promise.all([...this.legacySessions.values()].map((session) => session.server.close().catch(() => undefined)));
|
|
119
|
+
this.legacySessions.clear();
|
|
75
120
|
await this.handler.close();
|
|
76
121
|
const server = this.server;
|
|
77
122
|
this.server = null;
|
|
@@ -83,6 +128,110 @@ export class StreamableHttpGatewayServer {
|
|
|
83
128
|
server.closeAllConnections();
|
|
84
129
|
});
|
|
85
130
|
}
|
|
131
|
+
/**
|
|
132
|
+
* Routes modern requests to the per-request handler and preserves 2025 sessions.
|
|
133
|
+
*/
|
|
134
|
+
async handleMcpRequest(request) {
|
|
135
|
+
if (!(await isLegacyRequest(request))) {
|
|
136
|
+
return this.handler.fetch(request);
|
|
137
|
+
}
|
|
138
|
+
const sessionId = request.headers.get("mcp-session-id");
|
|
139
|
+
if (sessionId) {
|
|
140
|
+
const session = this.legacySessions.get(sessionId);
|
|
141
|
+
if (!session) {
|
|
142
|
+
return sessionNotFoundResponse();
|
|
143
|
+
}
|
|
144
|
+
session.lastAccessedAt = Date.now();
|
|
145
|
+
return session.transport.handleRequest(request);
|
|
146
|
+
}
|
|
147
|
+
return this.handleLegacyInitialization(request);
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Creates a stateful 2025 transport for an initialize request.
|
|
151
|
+
*/
|
|
152
|
+
async handleLegacyInitialization(request) {
|
|
153
|
+
let session;
|
|
154
|
+
const transport = new WebStandardStreamableHTTPServerTransport({
|
|
155
|
+
sessionIdGenerator: randomUUID,
|
|
156
|
+
onsessioninitialized: (sessionId) => {
|
|
157
|
+
this.legacySessions.set(sessionId, session);
|
|
158
|
+
},
|
|
159
|
+
onsessionclosed: (sessionId) => {
|
|
160
|
+
this.legacySessions.delete(sessionId);
|
|
161
|
+
}
|
|
162
|
+
});
|
|
163
|
+
const server = createGatewayMcpServer(this.engine, {
|
|
164
|
+
includeAdminTools: this.config.enableAdminTools ?? false
|
|
165
|
+
});
|
|
166
|
+
session = { server, transport, lastAccessedAt: Date.now() };
|
|
167
|
+
await server.connect(transport);
|
|
168
|
+
try {
|
|
169
|
+
const response = await transport.handleRequest(request);
|
|
170
|
+
if (!transport.sessionId) {
|
|
171
|
+
await server.close().catch(() => undefined);
|
|
172
|
+
}
|
|
173
|
+
return response;
|
|
174
|
+
}
|
|
175
|
+
catch (error) {
|
|
176
|
+
if (transport.sessionId) {
|
|
177
|
+
this.legacySessions.delete(transport.sessionId);
|
|
178
|
+
}
|
|
179
|
+
await server.close().catch(() => undefined);
|
|
180
|
+
throw error;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Releases abandoned legacy sessions without touching active modern requests.
|
|
185
|
+
*/
|
|
186
|
+
async closeExpiredLegacySessions() {
|
|
187
|
+
const expiresBefore = Date.now() - LEGACY_SESSION_IDLE_TIMEOUT_MS;
|
|
188
|
+
const expired = [...this.legacySessions.entries()]
|
|
189
|
+
.filter(([, session]) => session.lastAccessedAt < expiresBefore);
|
|
190
|
+
for (const [sessionId, session] of expired) {
|
|
191
|
+
this.legacySessions.delete(sessionId);
|
|
192
|
+
await session.server.close().catch(() => undefined);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Returns the standard status for a missing or expired MCP session.
|
|
198
|
+
*/
|
|
199
|
+
function sessionNotFoundResponse() {
|
|
200
|
+
return Response.json({
|
|
201
|
+
jsonrpc: "2.0",
|
|
202
|
+
error: {
|
|
203
|
+
code: -32001,
|
|
204
|
+
message: "Session not found"
|
|
205
|
+
},
|
|
206
|
+
id: null
|
|
207
|
+
}, { status: 404 });
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Compares a supplied bearer credential without leaking a useful timing signal.
|
|
211
|
+
*/
|
|
212
|
+
function hasValidBearerToken(request, expectedToken) {
|
|
213
|
+
if (!expectedToken) {
|
|
214
|
+
return true;
|
|
215
|
+
}
|
|
216
|
+
const supplied = request.headers.authorization;
|
|
217
|
+
const expected = `Bearer ${expectedToken}`;
|
|
218
|
+
if (!supplied) {
|
|
219
|
+
return false;
|
|
220
|
+
}
|
|
221
|
+
const suppliedBytes = Buffer.from(supplied);
|
|
222
|
+
const expectedBytes = Buffer.from(expected);
|
|
223
|
+
return suppliedBytes.length === expectedBytes.length
|
|
224
|
+
&& timingSafeEqual(suppliedBytes, expectedBytes);
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Identifies bind addresses that do not expose the gateway off-machine.
|
|
228
|
+
*/
|
|
229
|
+
function isLoopbackHost(host) {
|
|
230
|
+
const normalized = host.toLowerCase();
|
|
231
|
+
return normalized === "localhost"
|
|
232
|
+
|| normalized === "::1"
|
|
233
|
+
|| normalized === "[::1]"
|
|
234
|
+
|| /^127(?:\.\d{1,3}){3}$/.test(normalized);
|
|
86
235
|
}
|
|
87
236
|
/**
|
|
88
237
|
* Builds the Host and Origin allow-list for the configured bind address.
|
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
|
/**
|