@decnutz/mcpgateway 0.0.0-stage → 0.2.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.
@@ -0,0 +1,599 @@
1
+ /**
2
+ * Config loading, `${VAR}` interpolation, and strict validation.
3
+ *
4
+ * The config file is TRUSTED operator input (like sshd_config): it names the
5
+ * commands to spawn and the URLs to call. Docs say this loudly; `validate`
6
+ * still sanity-checks commands exist and warns on cleartext remote URLs.
7
+ */
8
+ import { accessSync, constants, existsSync, readFileSync } from 'node:fs';
9
+ import { delimiter as pathDelimiter, isAbsolute } from 'node:path';
10
+ import { parse as parseYaml } from 'yaml';
11
+ import { globMatch } from './util.js';
12
+ export class ConfigError extends Error {
13
+ problems;
14
+ constructor(problems) {
15
+ super(`invalid config:\n - ${problems.join('\n - ')}`);
16
+ this.name = 'ConfigError';
17
+ this.problems = problems;
18
+ }
19
+ }
20
+ export const DEFAULT_REDACT_KEYS = ['token', 'secret', 'password', 'passwd', 'api_key', 'apikey', 'authorization', 'cookie', 'session', 'credential'];
21
+ export const VALID_SCOPES = ['tools:call', 'tools:list', 'resources:*', 'prompts:*', 'admin'];
22
+ const SERVER_NAME_RE = /^[a-z0-9][a-z0-9_-]{0,31}$/;
23
+ const TOOL_NAME_RE = /^[a-zA-Z0-9_-]{1,64}$/;
24
+ // ---------------------------------------------------------------------------
25
+ // Env interpolation
26
+ // ---------------------------------------------------------------------------
27
+ const ENV_REF = /\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-(.*?))?\}/g;
28
+ /** Expand ${VAR} and ${VAR:-default}; throws naming the variable when unset. */
29
+ export function interpolateEnv(value, context) {
30
+ return value.replace(ENV_REF, (_m, name, def) => {
31
+ const v = process.env[name];
32
+ if (v !== undefined)
33
+ return v;
34
+ if (def !== undefined)
35
+ return def;
36
+ throw new ConfigError([`${context}: environment variable ${name} is not set and has no default (use \${${name}:-default})`]);
37
+ });
38
+ }
39
+ function interpolateDeep(value, context) {
40
+ if (typeof value === 'string')
41
+ return interpolateEnv(value, context);
42
+ if (Array.isArray(value))
43
+ return value.map((v, i) => interpolateDeep(v, `${context}[${i}]`));
44
+ if (value !== null && typeof value === 'object') {
45
+ const out = {};
46
+ for (const [k, v] of Object.entries(value))
47
+ out[k] = interpolateDeep(v, `${context}.${k}`);
48
+ return out;
49
+ }
50
+ return value;
51
+ }
52
+ function isRaw(v) {
53
+ return v !== null && typeof v === 'object' && !Array.isArray(v);
54
+ }
55
+ function str(v) {
56
+ return typeof v === 'string';
57
+ }
58
+ function num(v) {
59
+ return typeof v === 'number' && Number.isFinite(v);
60
+ }
61
+ function problems() {
62
+ return [];
63
+ }
64
+ function reqStr(raw, key, ctx, problems) {
65
+ const v = raw[key];
66
+ if (!str(v) || v.length === 0) {
67
+ problems.push(`${ctx}: "${key}" must be a non-empty string`);
68
+ return undefined;
69
+ }
70
+ return v;
71
+ }
72
+ function optNum(raw, key, ctx, def, min, problems) {
73
+ const v = raw[key];
74
+ if (v === undefined)
75
+ return def;
76
+ if (!num(v) || v < min) {
77
+ problems.push(`${ctx}: "${key}" must be a number >= ${min}`);
78
+ return def;
79
+ }
80
+ return v;
81
+ }
82
+ function strArray(raw, key, ctx, problems) {
83
+ const v = raw[key];
84
+ if (v === undefined)
85
+ return [];
86
+ if (!Array.isArray(v) || !v.every(str)) {
87
+ problems.push(`${ctx}: "${key}" must be an array of strings`);
88
+ return [];
89
+ }
90
+ return v;
91
+ }
92
+ function strMap(raw, key, ctx, problems) {
93
+ const v = raw[key];
94
+ if (v === undefined)
95
+ return {};
96
+ if (!isRaw(v) || !Object.values(v).every(str)) {
97
+ problems.push(`${ctx}: "${key}" must be a map of string -> string`);
98
+ return {};
99
+ }
100
+ return v;
101
+ }
102
+ function rateLimit(raw, ctx, problems) {
103
+ if (!isRaw(raw)) {
104
+ problems.push(`${ctx}: rate limit must be {rps, burst}`);
105
+ return undefined;
106
+ }
107
+ const rps = raw['rps'];
108
+ const burst = raw['burst'];
109
+ if (!num(rps) || rps <= 0 || !num(burst) || burst < 1) {
110
+ problems.push(`${ctx}: rate limit needs positive "rps" and "burst" >= 1`);
111
+ return undefined;
112
+ }
113
+ return { rps, burst };
114
+ }
115
+ export function loadConfigFile(path, opts = {}) {
116
+ let text;
117
+ try {
118
+ text = readFileSync(path, 'utf8');
119
+ }
120
+ catch (e) {
121
+ throw new ConfigError([`cannot read config file ${path}: ${e.message}`]);
122
+ }
123
+ let parsed;
124
+ try {
125
+ parsed = parseYaml(text);
126
+ }
127
+ catch (e) {
128
+ throw new ConfigError([`YAML parse error in ${path}: ${e.message}`]);
129
+ }
130
+ if (!isRaw(parsed))
131
+ throw new ConfigError([`${path}: top level must be a mapping`]);
132
+ const interpolated = interpolateDeep(parsed, 'config');
133
+ return validateConfig(interpolated, path, opts);
134
+ }
135
+ export function validateConfig(raw, source, opts = {}) {
136
+ const p = problems();
137
+ const ctx = (s) => `${source}: ${s}`;
138
+ // ---- gateway name ----
139
+ const gwRaw = raw['gateway'];
140
+ const name = (isRaw(gwRaw) && str(gwRaw['name']) ? gwRaw['name'] : 'mcpgateway');
141
+ // ---- servers ----
142
+ const serversRaw = raw['servers'];
143
+ const servers = [];
144
+ const seenNames = new Set();
145
+ if (!Array.isArray(serversRaw) || serversRaw.length === 0) {
146
+ p.push(ctx('"servers" must be a non-empty array'));
147
+ }
148
+ else {
149
+ serversRaw.forEach((s, i) => {
150
+ const sc = `${ctx(`servers[${i}]`)}`;
151
+ if (!isRaw(s)) {
152
+ p.push(`${sc}: must be a mapping`);
153
+ return;
154
+ }
155
+ const nm = reqStr(s, 'name', sc, p);
156
+ if (nm !== undefined) {
157
+ if (!SERVER_NAME_RE.test(nm))
158
+ p.push(`${sc}: "name" must match ${SERVER_NAME_RE} (lowercase, used in tool prefixes)`);
159
+ if (seenNames.has(nm))
160
+ p.push(`${sc}: duplicate server name "${nm}"`);
161
+ seenNames.add(nm);
162
+ }
163
+ const transport = s['transport'];
164
+ if (transport !== 'stdio' && transport !== 'http') {
165
+ p.push(`${sc}: "transport" must be "stdio" or "http"`);
166
+ return;
167
+ }
168
+ const cfg = {
169
+ name: nm ?? `server-${i}`,
170
+ transport,
171
+ timeoutMs: optNum(s, 'timeoutMs', sc, 60_000, 1_000, p),
172
+ concurrency: optNum(s, 'concurrency', sc, transport === 'stdio' ? 1 : 8, 1, p),
173
+ failureThreshold: optNum(s, 'failureThreshold', sc, 5, 1, p),
174
+ breakerCooldownMs: optNum(s, 'breakerCooldownMs', sc, 30_000, 1_000, p),
175
+ healthCheckMs: optNum(s, 'healthCheckMs', sc, 30_000, 5_000, p),
176
+ };
177
+ if (transport === 'stdio') {
178
+ const command = reqStr(s, 'command', sc, p);
179
+ if (command) {
180
+ cfg.command = command;
181
+ if (!opts.noNetwork) {
182
+ // command may be a bare binary resolved via PATH; check resolvability
183
+ const isPath = command.includes('/') || command.includes('\\') || isAbsolute(command);
184
+ const resolved = isPath ? existsSync(command) : commandResolvable(command);
185
+ if (!resolved)
186
+ p.push(`${sc}: command "${command}" not found (not on PATH and not an existing path)`);
187
+ }
188
+ }
189
+ const args = s['args'];
190
+ if (args !== undefined) {
191
+ if (!Array.isArray(args) || !args.every(str))
192
+ p.push(`${sc}: "args" must be an array of strings (no shell: argv only)`);
193
+ else
194
+ cfg.args = args;
195
+ }
196
+ cfg.env = strMap(s, 'env', sc, p);
197
+ const cwd = s['cwd'];
198
+ if (cwd !== undefined) {
199
+ if (!str(cwd))
200
+ p.push(`${sc}: "cwd" must be a string`);
201
+ else
202
+ cfg.cwd = cwd;
203
+ }
204
+ }
205
+ else {
206
+ const url = reqStr(s, 'url', sc, p);
207
+ if (url) {
208
+ let u;
209
+ try {
210
+ u = new URL(url);
211
+ }
212
+ catch {
213
+ p.push(`${sc}: "url" is not a valid URL`);
214
+ u = undefined;
215
+ }
216
+ if (u && u.protocol !== 'http:' && u.protocol !== 'https:') {
217
+ p.push(`${sc}: "url" must be http(s)`);
218
+ }
219
+ else if (u && u.protocol === 'http:' && !isLocalhost(u.hostname)) {
220
+ p.push(`${sc}: WARNING — cleartext http to non-localhost host "${u.hostname}" (credentials in headers would travel unencrypted)`);
221
+ }
222
+ cfg.url = url;
223
+ }
224
+ cfg.headers = strMap(s, 'headers', sc, p);
225
+ }
226
+ servers.push(cfg);
227
+ });
228
+ }
229
+ // ---- namespace ----
230
+ const nsRaw = isRaw(raw['namespace']) ? raw['namespace'] : {};
231
+ const strategy = nsRaw['strategy'];
232
+ const namespace = {
233
+ strategy: strategy === undefined ? 'prefix' : strategy,
234
+ separator: '__',
235
+ priority: [],
236
+ mappings: {},
237
+ aliases: {},
238
+ };
239
+ if (!['prefix', 'priority', 'explicit'].includes(namespace.strategy)) {
240
+ p.push(ctx(`namespace.strategy must be prefix|priority|explicit, got "${String(strategy)}"`));
241
+ namespace.strategy = 'prefix';
242
+ }
243
+ const sep = nsRaw['separator'];
244
+ if (sep !== undefined) {
245
+ if (!str(sep) || !/^[A-Za-z0-9_]{1,4}$/.test(sep))
246
+ p.push(ctx('namespace.separator must be 1-4 chars of [A-Za-z0-9_]'));
247
+ else
248
+ namespace.separator = sep;
249
+ }
250
+ namespace.priority = strArray(nsRaw, 'priority', ctx('namespace'), p);
251
+ const mappingsRaw = nsRaw['mappings'];
252
+ if (mappingsRaw !== undefined) {
253
+ if (!isRaw(mappingsRaw) || !Object.values(mappingsRaw).every(str)) {
254
+ p.push(ctx('namespace.mappings must be {toolName: serverName}'));
255
+ }
256
+ else {
257
+ namespace.mappings = mappingsRaw;
258
+ for (const [tool, srv] of Object.entries(namespace.mappings)) {
259
+ if (!seenNames.has(srv))
260
+ p.push(ctx(`namespace.mappings["${tool}"] references unknown server "${srv}"`));
261
+ }
262
+ }
263
+ }
264
+ const aliasesRaw = nsRaw['aliases'];
265
+ if (aliasesRaw !== undefined) {
266
+ if (!isRaw(aliasesRaw) || !Object.values(aliasesRaw).every(str)) {
267
+ p.push(ctx('namespace.aliases must be {"<server>:<tool>": "<publicName>"}'));
268
+ }
269
+ else {
270
+ for (const [from, to] of Object.entries(aliasesRaw)) {
271
+ if (!/^[^:]+:[^:]+$/.test(from))
272
+ p.push(ctx(`namespace.aliases key "${from}" must look like "<server>:<tool>"`));
273
+ if (!TOOL_NAME_RE.test(to))
274
+ p.push(ctx(`namespace.aliases["${from}"] = "${to}" is not a legal MCP tool name`));
275
+ const [srv] = from.split(':');
276
+ if (srv && !seenNames.has(srv))
277
+ p.push(ctx(`namespace.aliases["${from}"] references unknown server "${srv}"`));
278
+ }
279
+ namespace.aliases = aliasesRaw;
280
+ }
281
+ }
282
+ if (namespace.strategy === 'priority') {
283
+ for (const s of namespace.priority) {
284
+ if (!seenNames.has(s))
285
+ p.push(ctx(`namespace.priority references unknown server "${s}"`));
286
+ }
287
+ }
288
+ // ---- rate limits ----
289
+ const rlRaw = isRaw(raw['rateLimits']) ? raw['rateLimits'] : {};
290
+ const defRaw = rlRaw['default'];
291
+ const defaultRateLimit = defRaw === undefined ? { rps: 10, burst: 20 } : rateLimit(defRaw, ctx('rateLimits.default'), p);
292
+ const perToolRateLimits = {};
293
+ const toolsRaw = rlRaw['tools'];
294
+ if (toolsRaw !== undefined) {
295
+ if (!isRaw(toolsRaw))
296
+ p.push(ctx('rateLimits.tools must be a mapping'));
297
+ else {
298
+ for (const [tool, rule] of Object.entries(toolsRaw)) {
299
+ const r = rateLimit(rule, ctx(`rateLimits.tools["${tool}"]`), p);
300
+ if (r)
301
+ perToolRateLimits[tool] = r;
302
+ }
303
+ }
304
+ }
305
+ // ---- policy ----
306
+ const polRaw = isRaw(raw['policy']) ? raw['policy'] : {};
307
+ const mode = polRaw['mode'];
308
+ const policy = {
309
+ mode: mode === undefined ? 'enforce' : mode,
310
+ allowTools: strArray(polRaw, 'allowTools', ctx('policy'), p),
311
+ denyTools: strArray(polRaw, 'denyTools', ctx('policy'), p),
312
+ hideTools: strArray(polRaw, 'hideTools', ctx('policy'), p),
313
+ argRules: {},
314
+ responseRedact: strArray(polRaw, 'responseRedact', ctx('policy'), p),
315
+ responseBlock: strArray(polRaw, 'responseBlock', ctx('policy'), p),
316
+ responseWarn: strArray(polRaw, 'responseWarn', ctx('policy'), p),
317
+ scanWindowChars: optNum(polRaw, 'scanWindowChars', ctx('policy'), 65536, 1024, p),
318
+ hideSuspicious: polRaw['hideSuspicious'] === true,
319
+ };
320
+ if (polRaw['hideSuspicious'] !== undefined && typeof polRaw['hideSuspicious'] !== 'boolean')
321
+ p.push(ctx('policy.hideSuspicious must be boolean'));
322
+ if (policy.mode !== 'enforce' && policy.mode !== 'observe') {
323
+ p.push(ctx('policy.mode must be enforce|observe'));
324
+ policy.mode = 'enforce';
325
+ }
326
+ if (policy.allowTools.length === 0)
327
+ policy.allowTools = ['*'];
328
+ const argRulesRaw = polRaw['argRules'];
329
+ if (argRulesRaw !== undefined) {
330
+ if (!isRaw(argRulesRaw))
331
+ p.push(ctx('policy.argRules must be a mapping'));
332
+ else {
333
+ for (const [tool, rule] of Object.entries(argRulesRaw)) {
334
+ if (!isRaw(rule)) {
335
+ p.push(ctx(`policy.argRules["${tool}"] must be {allow?, deny?}`));
336
+ continue;
337
+ }
338
+ const ar = {};
339
+ for (const k of ['allow', 'deny']) {
340
+ const v = rule[k];
341
+ if (v !== undefined) {
342
+ if (!Array.isArray(v) || !v.every(str))
343
+ p.push(ctx(`policy.argRules["${tool}"].${k} must be an array of strings (substring matchers)`));
344
+ else
345
+ ar[k] = v;
346
+ }
347
+ }
348
+ policy.argRules[tool] = ar;
349
+ }
350
+ }
351
+ }
352
+ // validate glob patterns compile (they always do — globMatch is ReDoS-safe —
353
+ // but catch typos like unbalanced intent early is unnecessary; skip)
354
+ // ---- auth ----
355
+ const authRaw = isRaw(raw['auth']) ? raw['auth'] : {};
356
+ const authDisabled = authRaw['disabled'] === true;
357
+ const keys = [];
358
+ const keysRaw = authRaw['keys'];
359
+ if (keysRaw !== undefined) {
360
+ if (!Array.isArray(keysRaw))
361
+ p.push(ctx('auth.keys must be an array'));
362
+ else {
363
+ const seenIds = new Set();
364
+ keysRaw.forEach((k, i) => {
365
+ const kc = `${ctx(`auth.keys[${i}]`)}`;
366
+ if (!isRaw(k)) {
367
+ p.push(`${kc}: must be a mapping`);
368
+ return;
369
+ }
370
+ const id = reqStr(k, 'id', kc, p);
371
+ const key = reqStr(k, 'key', kc, p);
372
+ if (id && seenIds.has(id))
373
+ p.push(`${kc}: duplicate key id "${id}"`);
374
+ if (id)
375
+ seenIds.add(id);
376
+ const scopesRaw = k['scopes'];
377
+ const scopes = [];
378
+ if (scopesRaw === undefined)
379
+ scopes.push('tools:call', 'tools:list');
380
+ else if (!Array.isArray(scopesRaw) || !scopesRaw.every(str))
381
+ p.push(`${kc}: "scopes" must be an array of strings`);
382
+ else {
383
+ for (const s of scopesRaw) {
384
+ if (!VALID_SCOPES.includes(s))
385
+ p.push(`${kc}: unknown scope "${s}" (valid: ${VALID_SCOPES.join(', ')})`);
386
+ else
387
+ scopes.push(s);
388
+ }
389
+ }
390
+ const toolsRaw = k['tools'];
391
+ if (toolsRaw !== undefined && (!Array.isArray(toolsRaw) || !toolsRaw.every(str))) {
392
+ p.push(`${kc}: "tools" must be an array of glob strings`);
393
+ }
394
+ if (id && key) {
395
+ if (key.length < 16)
396
+ p.push(`${kc}: key is shorter than 16 chars — use a long random secret`);
397
+ // The shipped example's default contains "changeme": a gateway started
398
+ // without GATEWAY_KEY must not run on a key published in the repo.
399
+ if (!authDisabled && /changeme/i.test(key)) {
400
+ p.push(`${kc}: key "${id}" is the shipped placeholder. Set GATEWAY_KEY to a long random secret (e.g. \`node -e "console.log(crypto.randomBytes(32).toString('hex'))"\`)`);
401
+ }
402
+ keys.push(Array.isArray(toolsRaw) ? { id, key, scopes, tools: toolsRaw } : { id, key, scopes });
403
+ }
404
+ });
405
+ }
406
+ }
407
+ if (!authDisabled && keys.length === 0) {
408
+ p.push(ctx('auth.keys is empty and auth.disabled is not true — HTTP upstream/admin would accept nobody (or set auth.disabled: true explicitly)'));
409
+ }
410
+ // ---- audit ----
411
+ const audRaw = isRaw(raw['audit']) ? raw['audit'] : {};
412
+ const audit = {
413
+ path: './mcpgateway-audit.jsonl',
414
+ logArgs: true,
415
+ redactKeys: [...DEFAULT_REDACT_KEYS],
416
+ maxArgsChars: 8192,
417
+ maxSizeMB: 100,
418
+ keepFiles: 5,
419
+ };
420
+ if (audRaw['path'] !== undefined) {
421
+ if (!str(audRaw['path']))
422
+ p.push(ctx('audit.path must be a string'));
423
+ else
424
+ audit.path = audRaw['path'];
425
+ }
426
+ if (audRaw['logArgs'] !== undefined) {
427
+ if (typeof audRaw['logArgs'] !== 'boolean')
428
+ p.push(ctx('audit.logArgs must be boolean'));
429
+ else
430
+ audit.logArgs = audRaw['logArgs'];
431
+ }
432
+ const rk = audRaw['redactKeys'];
433
+ if (rk !== undefined) {
434
+ if (!Array.isArray(rk) || !rk.every(str))
435
+ p.push(ctx('audit.redactKeys must be an array of strings'));
436
+ else
437
+ audit.redactKeys = rk;
438
+ }
439
+ audit.maxArgsChars = optNum(audRaw, 'maxArgsChars', ctx('audit'), 8192, 256, p);
440
+ audit.maxSizeMB = optNum(audRaw, 'maxSizeMB', ctx('audit'), 100, 1, p);
441
+ audit.keepFiles = optNum(audRaw, 'keepFiles', ctx('audit'), 5, 1, p);
442
+ // ---- admin ----
443
+ const admRaw = isRaw(raw['admin']) ? raw['admin'] : {};
444
+ const admin = {
445
+ enabled: true,
446
+ host: '127.0.0.1',
447
+ port: 3001,
448
+ allowPublicAdmin: false,
449
+ };
450
+ if (admRaw['enabled'] !== undefined) {
451
+ if (typeof admRaw['enabled'] !== 'boolean')
452
+ p.push(ctx('admin.enabled must be boolean'));
453
+ else
454
+ admin.enabled = admRaw['enabled'];
455
+ }
456
+ if (admRaw['host'] !== undefined) {
457
+ if (!str(admRaw['host']))
458
+ p.push(ctx('admin.host must be a string'));
459
+ else
460
+ admin.host = admRaw['host'];
461
+ }
462
+ admin.port = optNum(admRaw, 'port', ctx('admin'), 3001, 0, p);
463
+ if (admRaw['allowPublicAdmin'] !== undefined) {
464
+ if (typeof admRaw['allowPublicAdmin'] !== 'boolean')
465
+ p.push(ctx('admin.allowPublicAdmin must be boolean'));
466
+ else
467
+ admin.allowPublicAdmin = admRaw['allowPublicAdmin'];
468
+ }
469
+ if (admin.enabled && isPublicBind(admin.host) && !admin.allowPublicAdmin) {
470
+ p.push(ctx(`admin.host "${admin.host}" is public but admin.allowPublicAdmin is not true — refusing (bind 127.0.0.1 or set the flag explicitly)`));
471
+ }
472
+ // ---- upstream ----
473
+ const upRaw = isRaw(raw['upstream']) ? raw['upstream'] : {};
474
+ const stdioRaw = isRaw(upRaw['stdio']) ? upRaw['stdio'] : {};
475
+ const httpRaw = isRaw(upRaw['http']) ? upRaw['http'] : {};
476
+ const upstream = {
477
+ stdio: { enabled: stdioRaw['enabled'] !== undefined ? stdioRaw['enabled'] === true : true },
478
+ http: { enabled: false, host: '127.0.0.1', port: 3000, maxSessions: 128, allowedOrigins: [], allowedHosts: [] },
479
+ };
480
+ if (typeof stdioRaw['enabled'] !== 'undefined' && typeof stdioRaw['enabled'] !== 'boolean') {
481
+ p.push(ctx('upstream.stdio.enabled must be boolean'));
482
+ }
483
+ if (httpRaw['enabled'] !== undefined) {
484
+ if (typeof httpRaw['enabled'] !== 'boolean')
485
+ p.push(ctx('upstream.http.enabled must be boolean'));
486
+ else
487
+ upstream.http.enabled = httpRaw['enabled'];
488
+ }
489
+ if (httpRaw['host'] !== undefined) {
490
+ if (!str(httpRaw['host']))
491
+ p.push(ctx('upstream.http.host must be a string'));
492
+ else
493
+ upstream.http.host = httpRaw['host'];
494
+ }
495
+ upstream.http.port = optNum(httpRaw, 'port', ctx('upstream.http'), 3000, 0, p);
496
+ upstream.http.maxSessions = optNum(httpRaw, 'maxSessions', ctx('upstream.http'), 128, 1, p);
497
+ upstream.http.allowedOrigins = strArray(httpRaw, 'allowedOrigins', ctx('upstream.http'), p);
498
+ // DNS-rebinding guard: a loopback bind only answers to loopback Host names
499
+ // unless the operator lists others. A public bind can't guess its names.
500
+ if (httpRaw['allowedHosts'] !== undefined) {
501
+ upstream.http.allowedHosts = strArray(httpRaw, 'allowedHosts', ctx('upstream.http'), p);
502
+ }
503
+ else if (isLocalhost(upstream.http.host)) {
504
+ upstream.http.allowedHosts = ['localhost', '127.0.0.1', '[::1]'];
505
+ }
506
+ else if (upstream.http.enabled) {
507
+ p.push(ctx(`WARNING: upstream.http.host "${upstream.http.host}" is not loopback and upstream.http.allowedHosts is empty — no Host-header (DNS-rebinding) check; list the names clients use`));
508
+ }
509
+ if (!upstream.stdio.enabled && !upstream.http.enabled) {
510
+ p.push(ctx('at least one upstream transport (stdio or http) must be enabled'));
511
+ }
512
+ // ---- pinning ----
513
+ const pinRaw = isRaw(raw['pinning']) ? raw['pinning'] : {};
514
+ const pinning = { mode: 'warn' };
515
+ if (pinRaw['mode'] !== undefined) {
516
+ if (pinRaw['mode'] !== 'off' && pinRaw['mode'] !== 'warn' && pinRaw['mode'] !== 'quarantine')
517
+ p.push(ctx('pinning.mode must be off|warn|quarantine'));
518
+ else
519
+ pinning.mode = pinRaw['mode'];
520
+ }
521
+ if (pinRaw['file'] !== undefined) {
522
+ if (!str(pinRaw['file']))
523
+ p.push(ctx('pinning.file must be a string'));
524
+ else
525
+ pinning.file = pinRaw['file'];
526
+ }
527
+ // ---- global limits ----
528
+ const globalMaxInflight = optNum(raw, 'globalMaxInflight', source, 256, 1, p);
529
+ const maxResultChars = optNum(raw, 'maxResultChars', source, 10_000_000, 1024, p);
530
+ // unknown top-level keys: warn via problems? Panel said warn, not fail.
531
+ // We surface them as warnings through the returned config instead.
532
+ const knownTop = new Set(['gateway', 'servers', 'namespace', 'rateLimits', 'policy', 'auth', 'audit', 'admin', 'upstream', 'globalMaxInflight', 'maxResultChars', 'pinning']);
533
+ const unknownTop = Object.keys(raw).filter((k) => !knownTop.has(k));
534
+ if (unknownTop.length > 0) {
535
+ // non-fatal: attach to stderr at serve time via a thrown-adjacent channel.
536
+ // Simplest: push as a special problem the CLI prints as warning.
537
+ p.push(ctx(`WARNING: unknown top-level keys ignored: ${unknownTop.join(', ')}`));
538
+ }
539
+ // fail on real problems; warnings are prefixed and filtered by the caller.
540
+ const real = p.filter((x) => !x.includes('WARNING'));
541
+ const warnings = p.filter((x) => x.includes('WARNING'));
542
+ if (real.length > 0)
543
+ throw new ConfigError(real);
544
+ const cfg = {
545
+ name,
546
+ servers,
547
+ namespace,
548
+ defaultRateLimit: defaultRateLimit ?? { rps: 10, burst: 20 },
549
+ perToolRateLimits,
550
+ policy,
551
+ auth: { disabled: authDisabled, keys },
552
+ audit,
553
+ admin,
554
+ upstream,
555
+ globalMaxInflight,
556
+ maxResultChars,
557
+ pinning,
558
+ };
559
+ cfg.__warnings = warnings;
560
+ return cfg;
561
+ }
562
+ /** Warnings collected during validation (unknown keys etc.). Non-fatal. */
563
+ export function configWarnings(cfg) {
564
+ return cfg.__warnings ?? [];
565
+ }
566
+ function isLocalhost(host) {
567
+ const h = host.toLowerCase();
568
+ return h === 'localhost' || h === '127.0.0.1' || h === '::1' || h === '[::1]' || h.endsWith('.localhost');
569
+ }
570
+ function isPublicBind(host) {
571
+ return host === '0.0.0.0' || host === '::';
572
+ }
573
+ function commandResolvable(command) {
574
+ // bare binary: search PATH manually (no shell — never spawn one for this)
575
+ const pathEnv = process.env['PATH'] ?? '';
576
+ // Windows: spawn() finds `node` as node.exe via PATHEXT, so check those too.
577
+ const exts = process.platform === 'win32' ? ['', ...(process.env['PATHEXT'] ?? '.COM;.EXE;.BAT;.CMD').split(';')] : [''];
578
+ for (const dir of pathEnv.split(pathDelimiter)) {
579
+ if (!dir)
580
+ continue;
581
+ for (const ext of exts) {
582
+ try {
583
+ accessSync(`${dir}/${command}${ext}`, constants.X_OK);
584
+ return true;
585
+ }
586
+ catch {
587
+ /* next */
588
+ }
589
+ }
590
+ }
591
+ return false;
592
+ }
593
+ /** Does this public tool name match any allow/deny-style glob list? Exported for policy use. */
594
+ export function matchesAny(patterns, value) {
595
+ return patterns.some((pat) => globMatch(pat, value));
596
+ }
597
+ // re-export for namespace/policy convenience
598
+ export { globMatch };
599
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1,59 @@
1
+ import { type CallToolResult, type GetPromptResult, type Prompt, type ReadResourceResult, type Resource, type Tool } from '@modelcontextprotocol/sdk/types.js';
2
+ import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';
3
+ import type { ServerConfig } from './config.js';
4
+ export interface ServerCatalogs {
5
+ tools: Tool[];
6
+ resources: Resource[];
7
+ prompts: Prompt[];
8
+ }
9
+ type BreakerState = 'closed' | 'open' | 'half-open';
10
+ export interface DownstreamHooks {
11
+ /** Catalogs changed (list_changed notification): rebuild the namespace. */
12
+ onCatalogChanged: (server: DownstreamServer) => void;
13
+ }
14
+ export declare class DownstreamServer {
15
+ private cfg;
16
+ private hooks;
17
+ /** Injected transport for tests (skips spawning/connecting real servers). */
18
+ private transportOverride?;
19
+ readonly name: string;
20
+ private client;
21
+ private transport;
22
+ private catalogs;
23
+ private semaphore;
24
+ private breakerState;
25
+ private consecutiveFailures;
26
+ private breakerOpenedAt;
27
+ private healthTimer;
28
+ private refreshTimer;
29
+ private closed;
30
+ lastPingOk: boolean | null;
31
+ lastError: string | null;
32
+ constructor(cfg: ServerConfig, hooks: DownstreamHooks,
33
+ /** Injected transport for tests (skips spawning/connecting real servers). */
34
+ transportOverride?: Transport | undefined);
35
+ get inFlight(): number;
36
+ get healthy(): boolean;
37
+ get circuitState(): BreakerState;
38
+ getCatalogs(): ServerCatalogs;
39
+ connect(): Promise<void>;
40
+ private createTransport;
41
+ private registerCatalogWatchers;
42
+ private refreshCatalogs;
43
+ private startHealthChecks;
44
+ private ping;
45
+ /**
46
+ * Call a tool on this server. Enforces the circuit breaker, concurrency
47
+ * bound, and per-call timeout. Throws on failure (caller maps to JSON-RPC).
48
+ */
49
+ callTool(originalName: string, args: unknown): Promise<CallToolResult>;
50
+ private onSuccess;
51
+ /** Read a resource by its ORIGINAL uri. Same breaker/timeout discipline as tools. */
52
+ readResource(originalUri: string): Promise<ReadResourceResult>;
53
+ /** Get a prompt by its ORIGINAL name. Same breaker/timeout discipline as tools. */
54
+ getPrompt(originalName: string, args: Record<string, string>): Promise<GetPromptResult>;
55
+ private onFailure;
56
+ close(): Promise<void>;
57
+ }
58
+ export {};
59
+ //# sourceMappingURL=downstream.d.ts.map