@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,279 @@
1
+ /**
2
+ * Downstream server manager: one MCP client per configured server.
3
+ *
4
+ * Reliability per blueprint §5:
5
+ * - bounded concurrency semaphore (stdio defaults to 1: most stdio servers
6
+ * are single-threaded and collapse under parallel calls)
7
+ * - per-call timeout (timeout rejects the call; the server is left alone)
8
+ * - circuit breaker: failureThreshold consecutive failures -> open for
9
+ * breakerCooldownMs (fail fast), then a half-open ping probe
10
+ * - periodic ping health checks; catalog refresh on list_changed
11
+ * notifications (debounced; routing table swapped atomically upstream)
12
+ *
13
+ * Child processes are spawned with shell:false and an argv array taken from
14
+ * the trusted config file. Server-initiated requests (sampling/elicitation)
15
+ * are NOT proxied (blueprint D2): the SDK answers them with a standard
16
+ * "method not found" error, which can never crash the gateway.
17
+ */
18
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
19
+ import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
20
+ import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
21
+ import { CallToolResultSchema, PromptListChangedNotificationSchema, ResourceListChangedNotificationSchema, ToolListChangedNotificationSchema, } from '@modelcontextprotocol/sdk/types.js';
22
+ import { VERSION } from './version.js';
23
+ import { sleep, withTimeout } from './util.js';
24
+ class Semaphore {
25
+ max;
26
+ active = 0;
27
+ queue = [];
28
+ constructor(max) {
29
+ this.max = max;
30
+ }
31
+ get inFlight() {
32
+ return this.active;
33
+ }
34
+ async acquire() {
35
+ if (this.active < this.max) {
36
+ this.active += 1;
37
+ return () => this.release();
38
+ }
39
+ return new Promise((resolve) => {
40
+ this.queue.push(() => {
41
+ this.active += 1;
42
+ resolve(() => this.release());
43
+ });
44
+ });
45
+ }
46
+ release() {
47
+ this.active -= 1;
48
+ const next = this.queue.shift();
49
+ if (next)
50
+ next();
51
+ }
52
+ }
53
+ export class DownstreamServer {
54
+ cfg;
55
+ hooks;
56
+ transportOverride;
57
+ name;
58
+ client;
59
+ transport = null;
60
+ catalogs = { tools: [], resources: [], prompts: [] };
61
+ semaphore;
62
+ breakerState = 'closed';
63
+ consecutiveFailures = 0;
64
+ breakerOpenedAt = 0;
65
+ healthTimer = null;
66
+ refreshTimer = null;
67
+ closed = false;
68
+ lastPingOk = null;
69
+ lastError = null;
70
+ constructor(cfg, hooks,
71
+ /** Injected transport for tests (skips spawning/connecting real servers). */
72
+ transportOverride) {
73
+ this.cfg = cfg;
74
+ this.hooks = hooks;
75
+ this.transportOverride = transportOverride;
76
+ this.name = cfg.name;
77
+ this.client = new Client({ name: 'mcpgateway', version: VERSION }, { capabilities: {} });
78
+ this.semaphore = new Semaphore(cfg.concurrency);
79
+ }
80
+ get inFlight() {
81
+ return this.semaphore.inFlight;
82
+ }
83
+ get healthy() {
84
+ return this.breakerState !== 'open' && this.lastPingOk !== false;
85
+ }
86
+ get circuitState() {
87
+ return this.breakerState;
88
+ }
89
+ getCatalogs() {
90
+ return this.catalogs;
91
+ }
92
+ async connect() {
93
+ const transport = this.transportOverride ?? this.createTransport();
94
+ this.transport = transport;
95
+ // If the server binary is missing or hangs, fail fast instead of hanging serve.
96
+ await withTimeout(this.client.connect(transport), 30_000, `connect to server "${this.name}"`);
97
+ this.registerCatalogWatchers();
98
+ await this.refreshCatalogs();
99
+ this.startHealthChecks();
100
+ }
101
+ createTransport() {
102
+ if (this.cfg.transport === 'stdio') {
103
+ return new StdioClientTransport({
104
+ command: this.cfg.command,
105
+ args: this.cfg.args ?? [],
106
+ env: this.cfg.env ?? {},
107
+ cwd: this.cfg.cwd,
108
+ // inherit (not pipe): the SDK creates an undrained PassThrough for
109
+ // 'pipe', so a chatty server would block forever on a full stderr
110
+ // buffer. In stdio upstream mode stderr is our log channel anyway.
111
+ stderr: 'inherit',
112
+ });
113
+ }
114
+ return new StreamableHTTPClientTransport(new URL(this.cfg.url), {
115
+ requestInit: { headers: this.cfg.headers ?? {} },
116
+ });
117
+ }
118
+ registerCatalogWatchers() {
119
+ const schedule = () => {
120
+ if (this.closed)
121
+ return;
122
+ if (this.refreshTimer)
123
+ clearTimeout(this.refreshTimer);
124
+ this.refreshTimer = setTimeout(() => void this.refreshCatalogs(true), 500);
125
+ };
126
+ // setNotificationHandler exists on Client (Protocol). Schemas imported above.
127
+ this.client.setNotificationHandler(ToolListChangedNotificationSchema, schedule);
128
+ this.client.setNotificationHandler(ResourceListChangedNotificationSchema, schedule);
129
+ this.client.setNotificationHandler(PromptListChangedNotificationSchema, schedule);
130
+ }
131
+ async refreshCatalogs(notify = false) {
132
+ try {
133
+ const [tools, resources, prompts] = await Promise.all([
134
+ this.client.listTools().catch(() => ({ tools: [] })),
135
+ this.client.listResources().catch(() => ({ resources: [] })),
136
+ this.client.listPrompts().catch(() => ({ prompts: [] })),
137
+ ]);
138
+ this.catalogs = { tools: tools.tools, resources: resources.resources, prompts: prompts.prompts };
139
+ if (notify)
140
+ this.hooks.onCatalogChanged(this);
141
+ }
142
+ catch (e) {
143
+ this.lastError = e.message;
144
+ }
145
+ }
146
+ startHealthChecks() {
147
+ this.healthTimer = setInterval(() => void this.ping(), this.cfg.healthCheckMs);
148
+ this.healthTimer.unref?.();
149
+ }
150
+ async ping() {
151
+ if (this.closed)
152
+ return;
153
+ if (this.breakerState === 'open') {
154
+ if (Date.now() - this.breakerOpenedAt < this.cfg.breakerCooldownMs)
155
+ return;
156
+ // Half-open probe: a successful ping lets the next real call through,
157
+ // so recovery doesn't wait for user traffic.
158
+ try {
159
+ await withTimeout(this.client.ping(), 10_000, `ping server "${this.name}"`);
160
+ this.breakerState = 'half-open';
161
+ this.consecutiveFailures = 0;
162
+ this.lastPingOk = true;
163
+ }
164
+ catch {
165
+ this.breakerOpenedAt = Date.now(); // extend the cooldown
166
+ this.lastPingOk = false;
167
+ }
168
+ return;
169
+ }
170
+ try {
171
+ await withTimeout(this.client.ping(), 10_000, `ping server "${this.name}"`);
172
+ this.lastPingOk = true;
173
+ }
174
+ catch {
175
+ this.lastPingOk = false;
176
+ }
177
+ }
178
+ /**
179
+ * Call a tool on this server. Enforces the circuit breaker, concurrency
180
+ * bound, and per-call timeout. Throws on failure (caller maps to JSON-RPC).
181
+ */
182
+ async callTool(originalName, args) {
183
+ if (this.closed)
184
+ throw new Error(`server "${this.name}" is closed`);
185
+ // Circuit breaker.
186
+ if (this.breakerState === 'open') {
187
+ if (Date.now() - this.breakerOpenedAt >= this.cfg.breakerCooldownMs) {
188
+ this.breakerState = 'half-open';
189
+ }
190
+ else {
191
+ throw new Error(`server "${this.name}" circuit breaker is open (too many failures)`);
192
+ }
193
+ }
194
+ const release = await this.semaphore.acquire();
195
+ try {
196
+ const result = (await withTimeout(this.client.callTool({ name: originalName, arguments: (args ?? {}) }, CallToolResultSchema, {
197
+ timeout: this.cfg.timeoutMs,
198
+ }), this.cfg.timeoutMs + 5_000, `tool "${originalName}" on server "${this.name}"`));
199
+ this.onSuccess();
200
+ return result;
201
+ }
202
+ catch (e) {
203
+ this.onFailure();
204
+ throw e;
205
+ }
206
+ finally {
207
+ release();
208
+ }
209
+ }
210
+ onSuccess() {
211
+ this.consecutiveFailures = 0;
212
+ if (this.breakerState === 'half-open')
213
+ this.breakerState = 'closed';
214
+ this.lastError = null;
215
+ }
216
+ /** Read a resource by its ORIGINAL uri. Same breaker/timeout discipline as tools. */
217
+ async readResource(originalUri) {
218
+ if (this.closed)
219
+ throw new Error(`server "${this.name}" is closed`);
220
+ if (this.breakerState === 'open')
221
+ throw new Error(`server "${this.name}" circuit breaker is open (too many failures)`);
222
+ const release = await this.semaphore.acquire();
223
+ try {
224
+ const result = await withTimeout(this.client.readResource({ uri: originalUri }, { timeout: this.cfg.timeoutMs }), this.cfg.timeoutMs + 5_000, `resource "${originalUri}" on server "${this.name}"`);
225
+ this.onSuccess();
226
+ return result;
227
+ }
228
+ catch (e) {
229
+ this.onFailure();
230
+ throw e;
231
+ }
232
+ finally {
233
+ release();
234
+ }
235
+ }
236
+ /** Get a prompt by its ORIGINAL name. Same breaker/timeout discipline as tools. */
237
+ async getPrompt(originalName, args) {
238
+ if (this.closed)
239
+ throw new Error(`server "${this.name}" is closed`);
240
+ if (this.breakerState === 'open')
241
+ throw new Error(`server "${this.name}" circuit breaker is open (too many failures)`);
242
+ const release = await this.semaphore.acquire();
243
+ try {
244
+ const result = await withTimeout(this.client.getPrompt({ name: originalName, arguments: args }, { timeout: this.cfg.timeoutMs }), this.cfg.timeoutMs + 5_000, `prompt "${originalName}" on server "${this.name}"`);
245
+ this.onSuccess();
246
+ return result;
247
+ }
248
+ catch (e) {
249
+ this.onFailure();
250
+ throw e;
251
+ }
252
+ finally {
253
+ release();
254
+ }
255
+ }
256
+ onFailure() {
257
+ this.consecutiveFailures += 1;
258
+ if (this.breakerState === 'half-open' || this.consecutiveFailures >= this.cfg.failureThreshold) {
259
+ this.breakerState = 'open';
260
+ this.breakerOpenedAt = Date.now();
261
+ }
262
+ }
263
+ async close() {
264
+ this.closed = true;
265
+ if (this.healthTimer)
266
+ clearInterval(this.healthTimer);
267
+ if (this.refreshTimer)
268
+ clearTimeout(this.refreshTimer);
269
+ try {
270
+ await this.client.close();
271
+ }
272
+ catch {
273
+ /* already gone */
274
+ }
275
+ // Give the child a moment, then make sure a stuck stdio server dies with us.
276
+ await sleep(50);
277
+ }
278
+ }
279
+ //# sourceMappingURL=downstream.js.map
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Gateway orchestrator: wires config -> downstream servers -> unified
3
+ * namespace -> routing table -> upstream + admin.
4
+ *
5
+ * The routing table is rebuilt (atomically swapped) whenever a downstream
6
+ * server's catalog changes. A rebuild that throws (e.g. a newly appeared
7
+ * collision under `explicit` strategy) keeps the previous table and logs a
8
+ * warning — a misbehaving server must never take the gateway's namespace down.
9
+ */
10
+ import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';
11
+ import { AuditLogger } from './audit.js';
12
+ import { Metrics } from './metrics.js';
13
+ import { DownstreamServer } from './downstream.js';
14
+ import { GatewayUpstream } from './upstream.js';
15
+ import { type NamespaceResult } from './namespace.js';
16
+ import { type GatewayConfig } from './config.js';
17
+ export interface Gateway {
18
+ config: GatewayConfig;
19
+ servers: DownstreamServer[];
20
+ upstream: GatewayUpstream;
21
+ audit: AuditLogger;
22
+ metrics: Metrics;
23
+ getNamespace(): NamespaceResult | null;
24
+ reloadCatalogs(): Promise<void>;
25
+ close(): Promise<void>;
26
+ /** set when upstream.http.enabled */
27
+ httpServer?: import('node:http').Server;
28
+ /** set when admin.enabled and not opts.noAdmin */
29
+ adminServer?: import('node:http').Server;
30
+ }
31
+ export interface StartOptions {
32
+ /** Test hook: pre-built transports keyed by server name (skips spawning). */
33
+ transportOverrides?: Map<string, Transport>;
34
+ /** Skip starting the admin HTTP API (tests). */
35
+ noAdmin?: boolean;
36
+ /** Where operational logs go (stderr in stdio mode). Defaults to console. */
37
+ log?: (msg: string) => void;
38
+ /** Started HTTP upstream server, if enabled. */
39
+ httpServer?: import('node:http').Server;
40
+ /** Started admin server, if enabled. */
41
+ adminServer?: import('node:http').Server;
42
+ }
43
+ export declare function startGateway(cfg: GatewayConfig, opts?: StartOptions): Promise<Gateway>;
44
+ //# sourceMappingURL=gateway.d.ts.map
@@ -0,0 +1,194 @@
1
+ import { AuditLogger } from './audit.js';
2
+ import { Metrics } from './metrics.js';
3
+ import { RateLimiter } from './ratelimit.js';
4
+ import { DownstreamServer } from './downstream.js';
5
+ import { GatewayUpstream, publicResourceUri } from './upstream.js';
6
+ import { buildNamespace, resolveNames } from './namespace.js';
7
+ import { configWarnings } from './config.js';
8
+ import { PinGuard } from './pinning.js';
9
+ import { HiddenCharGuard } from './hiddenchars.js';
10
+ import { VERSION } from './version.js';
11
+ export async function startGateway(cfg, opts = {}) {
12
+ const log = opts.log ?? ((m) => console.error(m));
13
+ const metrics = new Metrics();
14
+ // Blueprint §5: audit write failures are counted in Prometheus, never
15
+ // fatal to the request path.
16
+ const audit = new AuditLogger(cfg.audit, () => metrics.auditErrors.inc({}));
17
+ metrics.buildInfo.set({ version: VERSION }, 1);
18
+ const rateLimiter = new RateLimiter();
19
+ const pins = new PinGuard(cfg.pinning.mode, cfg.pinning.file, audit, metrics);
20
+ const hiddenChars = new HiddenCharGuard(cfg.policy.hideSuspicious, audit, metrics);
21
+ const state = { namespace: null, table: null };
22
+ const rebuildNamespace = (why) => {
23
+ try {
24
+ // Quarantined tools are dropped before the namespace exists: invisible
25
+ // in listings, and calls get the ordinary unknown-tool error.
26
+ const raw = servers.map((s) => ({ server: s.name, tools: s.getCatalogs().tools }));
27
+ const held = new Set([...pins.check(raw), ...hiddenChars.check(raw)]);
28
+ const catalogs = servers.map((s) => ({ server: s.name, tools: s.getCatalogs().tools.filter((t) => !held.has(`${s.name}\0${t.name}`)) }));
29
+ const ns = buildNamespace(catalogs, cfg.namespace);
30
+ state.namespace = ns;
31
+ state.table = buildRoutingTable(servers, ns, cfg);
32
+ for (const w of ns.warnings)
33
+ log(`[mcpgateway] namespace warning: ${w}`);
34
+ if (why !== 'startup')
35
+ log(`[mcpgateway] namespace rebuilt (${why}): ${ns.tools.length} tools`);
36
+ }
37
+ catch (e) {
38
+ // Keep serving the previous table; shout about it.
39
+ log(`[mcpgateway] WARNING: namespace rebuild failed (${why}): ${e.message} — keeping previous table`);
40
+ }
41
+ };
42
+ const servers = cfg.servers.map((sc) => new DownstreamServer(sc, { onCatalogChanged: () => rebuildNamespace(`catalog change`) }, opts.transportOverrides?.get(sc.name)));
43
+ // Connect sequentially: deterministic startup order, clearer errors.
44
+ for (const s of servers) {
45
+ try {
46
+ await s.connect();
47
+ metrics.serverUp.set({ server: s.name }, 1);
48
+ log(`[mcpgateway] connected to server "${s.name}" (${s.getCatalogs().tools.length} tools)`);
49
+ }
50
+ catch (e) {
51
+ metrics.serverUp.set({ server: s.name }, 0);
52
+ // Fail-closed at startup: a server we cannot reach is a config error.
53
+ // (At runtime the circuit breaker handles flapping.)
54
+ await closeServers(servers);
55
+ throw new Error(`cannot connect to server "${s.name}": ${e.message}`);
56
+ }
57
+ }
58
+ rebuildNamespace('startup');
59
+ if (state.table === null || state.namespace === null) {
60
+ await closeServers(servers);
61
+ throw new Error('namespace build failed at startup');
62
+ }
63
+ const ns = state.namespace;
64
+ if (ns.collisions.length > 0) {
65
+ log(`[mcpgateway] ${ns.collisions.length} tool name collision(s) resolved with strategy "${cfg.namespace.strategy}":`);
66
+ for (const c of ns.collisions) {
67
+ log(`[mcpgateway] "${c.originalName}" (${c.servers.join(', ')}) -> ${c.resolvedAs.join(', ')}`);
68
+ }
69
+ }
70
+ for (const w of configWarnings(cfg))
71
+ log(`[mcpgateway] ${w}`);
72
+ const deps = {
73
+ getTable: () => {
74
+ const t = state.table;
75
+ if (t === null)
76
+ throw new Error('namespace not ready');
77
+ return t;
78
+ },
79
+ policy: cfg.policy,
80
+ rateLimiter,
81
+ defaultRateLimit: cfg.defaultRateLimit,
82
+ perToolRateLimits: cfg.perToolRateLimits,
83
+ audit,
84
+ auditCfg: cfg.audit,
85
+ metrics,
86
+ globalMaxInflight: cfg.globalMaxInflight,
87
+ maxResultChars: cfg.maxResultChars,
88
+ httpMaxSessions: cfg.upstream.http.maxSessions,
89
+ httpAllowedOrigins: cfg.upstream.http.allowedOrigins,
90
+ httpAllowedHosts: cfg.upstream.http.allowedHosts,
91
+ auth: cfg.auth,
92
+ log,
93
+ };
94
+ const upstream = new GatewayUpstream(deps);
95
+ // Prune idle rate-limit buckets on a slow timer; unref'd so it never
96
+ // keeps the process alive on its own.
97
+ const pruneTimer = setInterval(() => rateLimiter.pruneIdle(), 60_000);
98
+ pruneTimer.unref?.();
99
+ let adminServer;
100
+ if (cfg.admin.enabled && !opts.noAdmin) {
101
+ const { startAdmin } = await import('./admin.js');
102
+ adminServer = await startAdmin({
103
+ auth: cfg.auth,
104
+ audit,
105
+ metrics,
106
+ getServers: () => servers,
107
+ getNamespace: () => state.namespace,
108
+ pinMismatches: () => pins.mismatchCount,
109
+ reloadCatalogs: async () => rebuildNamespace('admin reload'),
110
+ }, cfg.admin.host, cfg.admin.port);
111
+ log(`[mcpgateway] admin API on http://${cfg.admin.host}:${cfg.admin.port}`);
112
+ }
113
+ let httpServer;
114
+ if (cfg.upstream.http.enabled) {
115
+ httpServer = await upstream.listenHttp(cfg.upstream.http.host, cfg.upstream.http.port);
116
+ log(`[mcpgateway] MCP Streamable HTTP on http://${cfg.upstream.http.host}:${cfg.upstream.http.port}/mcp`);
117
+ }
118
+ let closed = false;
119
+ const gateway = {
120
+ config: cfg,
121
+ servers,
122
+ upstream,
123
+ audit,
124
+ metrics,
125
+ getNamespace: () => state.namespace,
126
+ reloadCatalogs: async () => rebuildNamespace('manual reload'),
127
+ close: async () => {
128
+ if (closed)
129
+ return;
130
+ closed = true;
131
+ clearInterval(pruneTimer);
132
+ if (httpServer)
133
+ await new Promise((r) => httpServer?.close(() => r()));
134
+ if (adminServer)
135
+ await new Promise((r) => adminServer?.close(() => r()));
136
+ await closeServers(servers);
137
+ audit.close();
138
+ },
139
+ };
140
+ if (httpServer)
141
+ gateway.httpServer = httpServer;
142
+ if (adminServer)
143
+ gateway.adminServer = adminServer;
144
+ return gateway;
145
+ }
146
+ async function closeServers(servers) {
147
+ await Promise.all(servers.map((s) => s.close().catch(() => undefined)));
148
+ }
149
+ function buildRoutingTable(servers, ns, cfg) {
150
+ const byServer = new Map(servers.map((s) => [s.name, s]));
151
+ const table = {
152
+ tools: new Map(),
153
+ toolMeta: new Map(),
154
+ prompts: new Map(),
155
+ promptMeta: new Map(),
156
+ resources: new Map(),
157
+ resourceMeta: new Map(),
158
+ };
159
+ for (const entry of ns.tools) {
160
+ const server = byServer.get(entry.server);
161
+ if (!server)
162
+ continue;
163
+ table.tools.set(entry.publicName, { server, original: entry.originalName });
164
+ table.toolMeta.set(entry.publicName, entry);
165
+ }
166
+ // Prompts: same collision strategies, strategy-only (aliases are tool-scoped).
167
+ const promptCatalogs = servers.map((s) => ({ server: s.name, names: s.getCatalogs().prompts.map((p) => p.name) }));
168
+ const resolved = resolveNames(promptCatalogs, { ...cfg.namespace, aliases: {} });
169
+ const promptLookup = new Map();
170
+ for (const s of servers) {
171
+ for (const p of s.getCatalogs().prompts) {
172
+ promptLookup.set(`${s.name}\0${p.name}`, { description: p.description ?? undefined, args: p.arguments });
173
+ }
174
+ }
175
+ for (const [key, publicName] of resolved.assigned) {
176
+ const [srv, orig] = key.split('\0');
177
+ const server = byServer.get(srv);
178
+ const meta = promptLookup.get(key);
179
+ if (!server || !meta)
180
+ continue;
181
+ table.prompts.set(publicName, { server, original: orig });
182
+ table.promptMeta.set(publicName, { publicName, server: srv, originalName: orig, description: meta.description, args: meta.args });
183
+ }
184
+ // Resources: namespaced by URI rewriting (clients treat URIs opaquely).
185
+ for (const s of servers) {
186
+ for (const r of s.getCatalogs().resources) {
187
+ const publicUri = publicResourceUri(s.name, r.uri);
188
+ table.resources.set(publicUri, { server: s, original: r.uri });
189
+ table.resourceMeta.set(publicUri, { ...r, uri: publicUri });
190
+ }
191
+ }
192
+ return table;
193
+ }
194
+ //# sourceMappingURL=gateway.js.map
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Invisible-character check on tool metadata: Unicode tag block, zero-width,
3
+ * bidi overrides/isolates, word joiners, BOM. Text hidden this way reaches the
4
+ * model but not a human reviewer.
5
+ *
6
+ * Flags invisible characters; does not judge visible text.
7
+ */
8
+ import type { Tool } from '@modelcontextprotocol/sdk/types.js';
9
+ import type { AuditLogger } from './audit.js';
10
+ import type { Metrics } from './metrics.js';
11
+ export interface HiddenHit {
12
+ path: string;
13
+ codePoints: string[];
14
+ }
15
+ export declare function findHiddenChars(s: string): string[];
16
+ /** Scan name, title, description and every string inside inputSchema. */
17
+ export declare function scanTool(tool: Tool): HiddenHit[];
18
+ export declare class HiddenCharGuard {
19
+ private hide;
20
+ private audit;
21
+ private metrics;
22
+ /** last findings reported per tool, so rebuilds don't repeat the same event */
23
+ private reported;
24
+ constructor(hide: boolean, audit: AuditLogger, metrics: Metrics);
25
+ /** Audit flagged tools; returns "<server>\0<name>" keys to hide (hideSuspicious only). */
26
+ check(catalogs: Array<{
27
+ server: string;
28
+ tools: Tool[];
29
+ }>): Set<string>;
30
+ }
31
+ //# sourceMappingURL=hiddenchars.d.ts.map
@@ -0,0 +1,77 @@
1
+ import { newRequestId } from './util.js';
2
+ const HIDDEN = /[\u{E0000}-\u{E007F}\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u2069\uFEFF]/gu;
3
+ export function findHiddenChars(s) {
4
+ return [...s.matchAll(HIDDEN)].map((m) => 'U+' + m[0].codePointAt(0).toString(16).toUpperCase().padStart(4, '0'));
5
+ }
6
+ /** Scan name, title, description and every string inside inputSchema. */
7
+ export function scanTool(tool) {
8
+ const hits = [];
9
+ const walk = (v, path, depth) => {
10
+ if (depth > 50)
11
+ return;
12
+ if (typeof v === 'string') {
13
+ const codePoints = findHiddenChars(v);
14
+ if (codePoints.length > 0)
15
+ hits.push({ path, codePoints });
16
+ }
17
+ else if (Array.isArray(v)) {
18
+ v.forEach((x, i) => walk(x, `${path}[${i}]`, depth + 1));
19
+ }
20
+ else if (v !== null && typeof v === 'object') {
21
+ for (const [k, x] of Object.entries(v))
22
+ walk(x, `${path}.${k}`, depth + 1);
23
+ }
24
+ };
25
+ for (const f of ['name', 'title', 'description'])
26
+ walk(tool[f], f, 0);
27
+ walk(tool.inputSchema, 'inputSchema', 0);
28
+ return hits;
29
+ }
30
+ export class HiddenCharGuard {
31
+ hide;
32
+ audit;
33
+ metrics;
34
+ /** last findings reported per tool, so rebuilds don't repeat the same event */
35
+ reported = new Map();
36
+ constructor(hide, audit, metrics) {
37
+ this.hide = hide;
38
+ this.audit = audit;
39
+ this.metrics = metrics;
40
+ }
41
+ /** Audit flagged tools; returns "<server>\0<name>" keys to hide (hideSuspicious only). */
42
+ check(catalogs) {
43
+ const held = new Set();
44
+ let flagged = 0;
45
+ for (const { server, tools } of catalogs) {
46
+ for (const tool of tools) {
47
+ const hits = scanTool(tool);
48
+ const key = `${server}:${tool.name}`;
49
+ if (hits.length === 0) {
50
+ this.reported.delete(key);
51
+ continue;
52
+ }
53
+ flagged += 1;
54
+ if (this.hide)
55
+ held.add(`${server}\0${tool.name}`);
56
+ const sig = JSON.stringify(hits);
57
+ if (this.reported.get(key) === sig)
58
+ continue;
59
+ this.reported.set(key, sig);
60
+ this.audit.log({
61
+ ts: new Date().toISOString(),
62
+ reqId: newRequestId(),
63
+ tool: tool.name,
64
+ server,
65
+ originalTool: tool.name,
66
+ durationMs: 0,
67
+ status: 'hidden_chars',
68
+ policyReason: this.hide ? 'hide_suspicious' : undefined,
69
+ hiddenChars: hits,
70
+ });
71
+ }
72
+ }
73
+ this.metrics.hiddenCharsTools.set({}, flagged);
74
+ return held;
75
+ }
76
+ }
77
+ //# sourceMappingURL=hiddenchars.js.map
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ import { main } from './cli.js';
3
+ main(process.argv.slice(2)).catch((e) => {
4
+ console.error(`mcpgateway: fatal: ${e.message}`);
5
+ process.exit(1);
6
+ });
7
+ //# sourceMappingURL=index.js.map