@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,185 @@
1
+ /**
2
+ * Centralized audit log: append-only JSONL, one record per tool call.
3
+ *
4
+ * Safety properties (scrutiny-relevant):
5
+ * - Every record is a single JSON-encoded line: args containing newlines can
6
+ * never break the JSONL framing (log injection impossible by construction).
7
+ * - Secret-looking argument values are redacted by key-name substring match
8
+ * (recursive); serialized args are capped with a visible truncation marker.
9
+ * - The writer NEVER throws into the request path: failures are counted and
10
+ * exposed via /healthz.
11
+ * - Size-based rotation with a bounded number of kept files: the audit log
12
+ * can never fill the disk unboundedly.
13
+ */
14
+ import { createHash } from 'node:crypto';
15
+ import { appendFileSync, existsSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
16
+ import { nowIso, safeJsonStringify, truncate } from './util.js';
17
+ const REDACTED = '[REDACTED]';
18
+ export class AuditLogger {
19
+ cfg;
20
+ onError;
21
+ bytesWritten = 0;
22
+ maxBytes;
23
+ errors = 0;
24
+ constructor(cfg, onError) {
25
+ this.cfg = cfg;
26
+ this.onError = onError;
27
+ this.maxBytes = cfg.maxSizeMB * 1024 * 1024;
28
+ }
29
+ /** Count a write failure and notify the metrics registry (never throws). */
30
+ fail() {
31
+ this.errors += 1;
32
+ try {
33
+ this.onError?.();
34
+ }
35
+ catch {
36
+ /* metrics must never break the audit path */
37
+ }
38
+ }
39
+ /** Append one record. Never throws. */
40
+ log(record) {
41
+ try {
42
+ this.ensureOpen();
43
+ const line = safeJsonStringify(this.prepare(record)) + '\n';
44
+ appendFileSync(this.cfg.path, line, { encoding: 'utf8' });
45
+ this.bytesWritten += Buffer.byteLength(line);
46
+ if (this.bytesWritten >= this.maxBytes)
47
+ this.rotate();
48
+ }
49
+ catch {
50
+ this.fail();
51
+ }
52
+ }
53
+ close() {
54
+ // appendFileSync opens/closes per write; nothing to flush.
55
+ }
56
+ ensureOpen() {
57
+ try {
58
+ this.bytesWritten = statSync(this.cfg.path).size;
59
+ }
60
+ catch {
61
+ this.bytesWritten = 0;
62
+ // Prove the path is writable now rather than failing silently forever.
63
+ try {
64
+ writeFileSync(this.cfg.path, '', { flag: 'a' });
65
+ }
66
+ catch {
67
+ throw new Error(`cannot write audit log at ${this.cfg.path}`);
68
+ }
69
+ }
70
+ }
71
+ prepare(record) {
72
+ const out = { ...record, ts: record.ts || nowIso() };
73
+ if (this.cfg.logArgs && record.args !== undefined) {
74
+ const redacted = redactDeep(record.args, this.cfg.redactKeys);
75
+ const serialized = safeJsonStringify(redacted);
76
+ const { text, truncated } = truncate(serialized, this.cfg.maxArgsChars);
77
+ // Store the (possibly truncated) JSON string form: re-parsing truncated
78
+ // JSON would be lossy and could throw, so keep it as a string.
79
+ out.args = text;
80
+ out.argsTruncated = truncated || undefined;
81
+ }
82
+ else if (!this.cfg.logArgs && record.args !== undefined) {
83
+ out.argsHash = 'sha256:' + createHash('sha256').update(safeJsonStringify(record.args)).digest('hex');
84
+ delete out.args;
85
+ }
86
+ return out;
87
+ }
88
+ rotate() {
89
+ try {
90
+ // mcpgateway-audit.jsonl -> .1 (newest), shift older ones, drop beyond keep.
91
+ for (let i = this.cfg.keepFiles - 1; i >= 1; i--) {
92
+ const older = `${this.cfg.path}.${i}`;
93
+ const newer = `${this.cfg.path}.${i + 1}`;
94
+ if (existsSync(older)) {
95
+ if (i + 1 > this.cfg.keepFiles)
96
+ unlinkSync(older);
97
+ else
98
+ renameSync(older, newer);
99
+ }
100
+ }
101
+ if (existsSync(this.cfg.path))
102
+ renameSync(this.cfg.path, `${this.cfg.path}.1`);
103
+ // Drop the file that would exceed keepFiles (the loop above leaves
104
+ // .keepFiles+1 only when keepFiles files already existed; clean it).
105
+ const overflow = `${this.cfg.path}.${this.cfg.keepFiles + 1}`;
106
+ if (existsSync(overflow))
107
+ unlinkSync(overflow);
108
+ this.bytesWritten = 0;
109
+ }
110
+ catch {
111
+ this.fail();
112
+ }
113
+ }
114
+ }
115
+ /** Recursively redact values whose key contains a redact substring (case-insensitive). */
116
+ export function redactDeep(value, redactKeys) {
117
+ const lowered = redactKeys.map((k) => k.toLowerCase());
118
+ const shouldRedact = (key) => {
119
+ const lk = key.toLowerCase();
120
+ return lowered.some((rk) => rk.length > 0 && lk.includes(rk));
121
+ };
122
+ const walk = (v, depth) => {
123
+ if (depth > 50)
124
+ return REDACTED; // pathological nesting guard
125
+ if (Array.isArray(v))
126
+ return v.map((item) => walk(item, depth + 1));
127
+ if (v !== null && typeof v === 'object') {
128
+ const out = {};
129
+ for (const [k, val] of Object.entries(v)) {
130
+ out[k] = shouldRedact(k) ? REDACTED : walk(val, depth + 1);
131
+ }
132
+ return out;
133
+ }
134
+ return v;
135
+ };
136
+ return walk(value, 0);
137
+ }
138
+ /**
139
+ * Collect the actual secret VALUES from a call's args (values of keys that
140
+ * matched the redact list). Used to scrub those values out of downstream
141
+ * error messages, which otherwise echo secrets into the audit log and the
142
+ * agent-facing error. Only values >= 8 chars are collected, so redacting
143
+ * them elsewhere can never nuke ordinary words.
144
+ */
145
+ export function collectSecretValues(args, redactKeys) {
146
+ const lowered = redactKeys.map((k) => k.toLowerCase()).filter((k) => k.length > 0);
147
+ const values = new Set();
148
+ const walk = (v, depth) => {
149
+ if (depth > 50 || values.size >= 100)
150
+ return;
151
+ if (Array.isArray(v)) {
152
+ for (const item of v)
153
+ walk(item, depth + 1);
154
+ return;
155
+ }
156
+ if (v !== null && typeof v === 'object') {
157
+ for (const [k, val] of Object.entries(v)) {
158
+ const lk = k.toLowerCase();
159
+ if (typeof val === 'string' && val.length >= 8 && lowered.some((rk) => lk.includes(rk))) {
160
+ values.add(val);
161
+ }
162
+ else {
163
+ walk(val, depth + 1);
164
+ }
165
+ }
166
+ }
167
+ };
168
+ walk(args, 0);
169
+ return [...values];
170
+ }
171
+ /** Replace every occurrence of each secret value with [REDACTED]. */
172
+ export function redactSecretValues(text, secrets) {
173
+ let out = text;
174
+ for (const s of secrets) {
175
+ if (s.length === 0)
176
+ continue;
177
+ let idx = out.indexOf(s);
178
+ while (idx !== -1) {
179
+ out = out.slice(0, idx) + REDACTED + out.slice(idx + s.length);
180
+ idx = out.indexOf(s, idx + REDACTED.length);
181
+ }
182
+ }
183
+ return out;
184
+ }
185
+ //# sourceMappingURL=audit.js.map
@@ -0,0 +1,34 @@
1
+ interface Args {
2
+ command: string;
3
+ config: string;
4
+ network: boolean;
5
+ http: boolean;
6
+ output: string;
7
+ force: boolean;
8
+ /** init: .mcp.json to take the servers from */
9
+ from: string;
10
+ /** first positional after the command (import: path) */
11
+ target: string;
12
+ }
13
+ declare function parseArgs(argv: string[]): Args;
14
+ export { parseArgs };
15
+ export type { Args };
16
+ /** Apply serve-time CLI overrides to a loaded config. */
17
+ export declare function applyServeFlags(cfg: {
18
+ upstream: {
19
+ http: {
20
+ enabled: boolean;
21
+ };
22
+ };
23
+ }, args: Args): void;
24
+ export declare function main(argv: string[]): Promise<void>;
25
+ /**
26
+ * Convert a Claude-style .mcp.json object to gateway `servers:` entries.
27
+ * Literal values under secret-looking env/header names become ${NAME}
28
+ * references, so secrets never land in the generated YAML.
29
+ */
30
+ export declare function mcpJsonToServers(data: unknown): {
31
+ servers: Array<Record<string, unknown>>;
32
+ notes: string[];
33
+ };
34
+ //# sourceMappingURL=cli.d.ts.map
@@ -0,0 +1,374 @@
1
+ /**
2
+ * CLI: serve | validate | namespace | init | pin | import
3
+ *
4
+ * In stdio upstream mode, stdout is the MCP channel — ALL operational logging
5
+ * goes to stderr.
6
+ */
7
+ import { randomBytes } from 'node:crypto';
8
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
9
+ import { dirname, join } from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+ import { parseDocument, stringify as stringifyYaml } from 'yaml';
12
+ import { ConfigError, DEFAULT_REDACT_KEYS, configWarnings, loadConfigFile } from './config.js';
13
+ import { startGateway } from './gateway.js';
14
+ import { buildNamespace } from './namespace.js';
15
+ import { DownstreamServer } from './downstream.js';
16
+ import { pinsFileContent } from './pinning.js';
17
+ import { VERSION } from './version.js';
18
+ const HELP = `mcpgateway ${VERSION} — one process fronting all your MCP servers.
19
+
20
+ Usage:
21
+ mcpgateway serve [-c config.yaml] Serve the unified gateway (stdio upstream by default)
22
+ mcpgateway serve --http [-c config] Also serve Streamable HTTP upstream (uses upstream.http.* settings)
23
+ mcpgateway validate [-c config.yaml] Validate config (add --network for reachability checks)
24
+ mcpgateway namespace [-c config.yaml] Connect and print the unified tool table
25
+ mcpgateway init [-o out.yaml] [--from .mcp.json] Write a commented starter config
26
+ mcpgateway pin [-c config] [-o pins.json] Connect and write tool-definition pins (stdout without -o)
27
+ mcpgateway import <.mcp.json> Print a servers: block converted from a Claude-style .mcp.json
28
+ mcpgateway --version | --help
29
+
30
+ Options:
31
+ -c, --config <path> Config file (default: ./mcpgateway.yaml)
32
+ --http serve: enable the Streamable HTTP upstream too
33
+ --network validate/namespace: check server reachability (validate skips by default)
34
+ -o, --output <path> init: output path (default: ./mcpgateway.yaml); pin: pins file (default: stdout)
35
+ -f, --force init: overwrite existing file
36
+ --from <.mcp.json> init: start from your existing .mcp.json servers (secrets become env-var placeholders)
37
+
38
+ Docs: https://github.com/calasdan-sketch/mcpgateway (when published)
39
+ `;
40
+ function parseArgs(argv) {
41
+ const args = { command: '', config: './mcpgateway.yaml', network: false, http: false, output: '', force: false, from: '', target: '' };
42
+ const rest = [];
43
+ for (let i = 0; i < argv.length; i++) {
44
+ const a = argv[i];
45
+ const value = () => {
46
+ const v = argv[++i];
47
+ if (v === undefined || v.startsWith('-'))
48
+ throw new Error(`${a} needs a value (see --help)`);
49
+ return v;
50
+ };
51
+ if (a === '-c' || a === '--config')
52
+ args.config = value();
53
+ else if (a === '--network')
54
+ args.network = true;
55
+ else if (a === '--http')
56
+ args.http = true;
57
+ else if (a === '-o' || a === '--output')
58
+ args.output = value();
59
+ else if (a === '-f' || a === '--force')
60
+ args.force = true;
61
+ else if (a === '--from')
62
+ args.from = value();
63
+ else if (a === '--version' || a === '-V')
64
+ return { ...args, command: 'version' };
65
+ else if (a === '--help' || a === '-h')
66
+ return { ...args, command: 'help' };
67
+ else if (!a.startsWith('-'))
68
+ rest.push(a);
69
+ else
70
+ throw new Error(`unknown flag "${a}" (see --help)`);
71
+ }
72
+ if (rest.length > 0)
73
+ args.command = rest[0];
74
+ if (rest.length > 1)
75
+ args.target = rest[1];
76
+ return args;
77
+ }
78
+ // Exported for tests.
79
+ export { parseArgs };
80
+ /** Apply serve-time CLI overrides to a loaded config. */
81
+ export function applyServeFlags(cfg, args) {
82
+ if (args.http)
83
+ cfg.upstream.http.enabled = true;
84
+ }
85
+ export async function main(argv) {
86
+ let args;
87
+ try {
88
+ args = parseArgs(argv);
89
+ }
90
+ catch (e) {
91
+ console.error(`error: ${e.message}`);
92
+ process.exitCode = 2;
93
+ return;
94
+ }
95
+ switch (args.command) {
96
+ case 'version':
97
+ console.log(VERSION);
98
+ return;
99
+ case 'help':
100
+ case '':
101
+ console.log(HELP);
102
+ if (args.command === '')
103
+ process.exitCode = 2;
104
+ return;
105
+ case 'serve':
106
+ await cmdServe(args);
107
+ return;
108
+ case 'validate':
109
+ await cmdValidate(args);
110
+ return;
111
+ case 'namespace':
112
+ await cmdNamespace(args);
113
+ return;
114
+ case 'import':
115
+ cmdImport(args);
116
+ return;
117
+ case 'pin':
118
+ await cmdPin(args);
119
+ return;
120
+ case 'init':
121
+ cmdInit(args);
122
+ return;
123
+ default:
124
+ console.error(`unknown command "${args.command}" (see --help)`);
125
+ process.exitCode = 2;
126
+ }
127
+ }
128
+ async function cmdServe(args) {
129
+ const cfg = loadConfigOrExit(args.config, false);
130
+ applyServeFlags(cfg, args);
131
+ if (cfg.auth.disabled) {
132
+ console.error('[mcpgateway] WARNING: auth.disabled=true — HTTP upstream and admin accept unauthenticated requests');
133
+ }
134
+ if (cfg.admin.enabled && cfg.admin.allowPublicAdmin) {
135
+ console.error('[mcpgateway] WARNING: admin.allowPublicAdmin=true — admin API is reachable beyond localhost');
136
+ }
137
+ if (cfg.upstream.http.enabled && cfg.upstream.stdio.enabled) {
138
+ console.error(`[mcpgateway] upstream: stdio + Streamable HTTP on ${cfg.upstream.http.host}:${cfg.upstream.http.port}/mcp`);
139
+ }
140
+ const gateway = await startGateway(cfg, { log: (m) => console.error(m) });
141
+ if (cfg.upstream.stdio.enabled) {
142
+ await gateway.upstream.connectStdio();
143
+ console.error(`[mcpgateway] serving ${gateway.getNamespace()?.tools.length ?? 0} unified tools on stdio`);
144
+ }
145
+ const shutdown = () => {
146
+ console.error('[mcpgateway] shutting down…');
147
+ void gateway.close().then(() => process.exit(0));
148
+ // Hard stop if graceful close hangs (a wedged child must not pin us).
149
+ setTimeout(() => process.exit(1), 5000).unref();
150
+ };
151
+ process.on('SIGINT', shutdown);
152
+ process.on('SIGTERM', shutdown);
153
+ // Keep the event loop alive for stdio mode (the transport holds it anyway;
154
+ // this is belt-and-braces for http-only mode without admin).
155
+ await new Promise(() => undefined);
156
+ }
157
+ async function cmdValidate(args) {
158
+ let cfg;
159
+ try {
160
+ cfg = loadConfigFile(args.config, { noNetwork: !args.network });
161
+ }
162
+ catch (e) {
163
+ reportConfigError(e);
164
+ return;
165
+ }
166
+ for (const w of configWarnings(cfg))
167
+ console.log(`warning: ${w}`);
168
+ console.log(`ok: ${cfg.servers.length} server(s), namespace strategy "${cfg.namespace.strategy}", ` +
169
+ `upstream=${[cfg.upstream.stdio.enabled && 'stdio', cfg.upstream.http.enabled && 'http'].filter(Boolean).join('+')}, ` +
170
+ `admin=${cfg.admin.enabled ? `${cfg.admin.host}:${cfg.admin.port}` : 'off'}`);
171
+ console.log('hint: run `mcpgateway namespace` to preview the unified tool table (connects to servers)');
172
+ }
173
+ async function cmdNamespace(args) {
174
+ // namespace always connects: the table IS the live catalogs.
175
+ const cfg = loadConfigOrExit(args.config, false);
176
+ const servers = [];
177
+ try {
178
+ for (const sc of cfg.servers) {
179
+ const s = new DownstreamServer(sc, { onCatalogChanged: () => undefined });
180
+ await s.connect();
181
+ servers.push(s);
182
+ }
183
+ const catalogs = servers.map((s) => ({ server: s.name, tools: s.getCatalogs().tools }));
184
+ const ns = buildNamespace(catalogs, cfg.namespace);
185
+ const rows = [];
186
+ const nameW = Math.max(4, ...ns.tools.map((t) => t.publicName.length));
187
+ rows.push(`${'TOOL'.padEnd(nameW)} SERVER -> ORIGINAL`);
188
+ for (const t of ns.tools)
189
+ rows.push(`${t.publicName.padEnd(nameW)} ${t.server} -> ${t.originalName}`);
190
+ console.log(rows.join('\n'));
191
+ if (ns.collisions.length > 0) {
192
+ console.log(`\n${ns.collisions.length} collision(s) resolved with strategy "${cfg.namespace.strategy}":`);
193
+ for (const c of ns.collisions) {
194
+ console.log(` "${c.originalName}" (${c.servers.join(', ')})`);
195
+ c.resolvedAs.forEach((r, i) => console.log(` -> ${r}${c.shadowed.includes(c.servers[i]) ? ' [shadowed]' : ''}`));
196
+ }
197
+ }
198
+ for (const w of ns.warnings)
199
+ console.log(`warning: ${w}`);
200
+ }
201
+ finally {
202
+ await Promise.all(servers.map((s) => s.close().catch(() => undefined)));
203
+ }
204
+ }
205
+ function cmdInit(args) {
206
+ const output = args.output || './mcpgateway.yaml';
207
+ if (existsSync(output) && !args.force) {
208
+ console.error(`error: ${output} already exists (use --force to overwrite)`);
209
+ process.exitCode = 2;
210
+ return;
211
+ }
212
+ // Single source of truth: the example file shipped at the package root.
213
+ const examplePath = join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'mcpgateway.example.yaml');
214
+ let example;
215
+ try {
216
+ example = readFileSync(examplePath, 'utf8');
217
+ }
218
+ catch {
219
+ console.error(`error: cannot read shipped example at ${examplePath}`);
220
+ process.exitCode = 1;
221
+ return;
222
+ }
223
+ let text = example;
224
+ let note = '';
225
+ if (args.from) {
226
+ let data;
227
+ try {
228
+ data = JSON.parse(readFileSync(args.from, 'utf8'));
229
+ }
230
+ catch (e) {
231
+ console.error(`error: ${args.from} is unreadable or not valid JSON: ${e.message}`);
232
+ process.exitCode = 2;
233
+ return;
234
+ }
235
+ const { servers, notes } = mcpJsonToServers(data);
236
+ for (const n of notes)
237
+ console.error(`note: ${n}`);
238
+ if (servers.length === 0) {
239
+ console.error(`error: no servers found in ${args.from}`);
240
+ process.exitCode = 2;
241
+ return;
242
+ }
243
+ const doc = parseDocument(example);
244
+ doc.set('servers', doc.createNode(servers));
245
+ text = String(doc);
246
+ note = ` with ${servers.length} server${servers.length === 1 ? '' : 's'} from ${args.from}`;
247
+ }
248
+ writeFileSync(output, text, 'utf8');
249
+ console.log(`wrote ${output}${note} — edit it, then run: mcpgateway validate -c ${output}`);
250
+ // Printed, never written: the config file may get committed.
251
+ console.log(`generated a gateway key (not saved to the file) — set it in your environment:\n export GATEWAY_KEY=${randomBytes(32).toString('hex')}`);
252
+ }
253
+ async function cmdPin(args) {
254
+ const cfg = loadConfigOrExit(args.config, false);
255
+ const servers = [];
256
+ try {
257
+ for (const sc of cfg.servers) {
258
+ const s = new DownstreamServer(sc, { onCatalogChanged: () => undefined });
259
+ await s.connect();
260
+ servers.push(s);
261
+ }
262
+ const text = pinsFileContent(servers.map((s) => ({ server: s.name, tools: s.getCatalogs().tools })));
263
+ if (args.output) {
264
+ writeFileSync(args.output, text, 'utf8');
265
+ console.error(`wrote ${args.output} — review the diff, then set pinning.file to it`);
266
+ }
267
+ else {
268
+ process.stdout.write(text);
269
+ }
270
+ }
271
+ finally {
272
+ await Promise.all(servers.map((s) => s.close().catch(() => undefined)));
273
+ }
274
+ }
275
+ /**
276
+ * Convert a Claude-style .mcp.json object to gateway `servers:` entries.
277
+ * Literal values under secret-looking env/header names become ${NAME}
278
+ * references, so secrets never land in the generated YAML.
279
+ */
280
+ export function mcpJsonToServers(data) {
281
+ const obj = (data ?? {});
282
+ const src = (obj['mcpServers'] ?? obj['servers'] ?? obj);
283
+ const servers = [];
284
+ const notes = [];
285
+ const used = new Set();
286
+ const secretKey = (k) => DEFAULT_REDACT_KEYS.some((r) => k.toLowerCase().includes(r));
287
+ const scrub = (map, server) => {
288
+ if (map === null || typeof map !== 'object')
289
+ return undefined;
290
+ const out = {};
291
+ for (const [k, v] of Object.entries(map)) {
292
+ const value = String(v);
293
+ if (secretKey(k) && !/^[$][{][A-Za-z_][A-Za-z0-9_]*(:-.*)?[}]$/.test(value)) {
294
+ const envName = k.toUpperCase().replace(/[^A-Z0-9_]/g, '_');
295
+ out[k] = '${' + envName + '}';
296
+ notes.push(`server "${server}": ${k} replaced with \${${envName}} — export ${envName} before serve`);
297
+ }
298
+ else {
299
+ out[k] = value;
300
+ }
301
+ }
302
+ return out;
303
+ };
304
+ for (const [rawName, entry] of Object.entries(src)) {
305
+ if (entry === null || typeof entry !== 'object')
306
+ continue;
307
+ const e = entry;
308
+ const base = rawName.toLowerCase().replace(/[^a-z0-9_-]/g, '-').replace(/^[^a-z0-9]+/, '').slice(0, 29) || 'server';
309
+ let name = base;
310
+ for (let n = 2; used.has(name); n++)
311
+ name = `${base}-${n}`;
312
+ used.add(name);
313
+ if (typeof e['command'] === 'string') {
314
+ const s = { name, transport: 'stdio', command: e['command'] };
315
+ if (Array.isArray(e['args']))
316
+ s['args'] = e['args'].map(String);
317
+ const env = scrub(e['env'], name);
318
+ if (env !== undefined)
319
+ s['env'] = env;
320
+ servers.push(s);
321
+ }
322
+ else if (typeof e['url'] === 'string') {
323
+ if (e['type'] === 'sse')
324
+ notes.push(`server "${name}": legacy SSE transport — the gateway speaks Streamable HTTP only; check the server supports it`);
325
+ const s = { name, transport: 'http', url: e['url'] };
326
+ const headers = scrub(e['headers'], name);
327
+ if (headers !== undefined)
328
+ s['headers'] = headers;
329
+ servers.push(s);
330
+ }
331
+ else {
332
+ notes.push(`server "${rawName}": no command or url — skipped`);
333
+ }
334
+ }
335
+ return { servers, notes };
336
+ }
337
+ function cmdImport(args) {
338
+ let data;
339
+ try {
340
+ data = JSON.parse(readFileSync(args.target, 'utf8'));
341
+ }
342
+ catch (e) {
343
+ console.error(args.target === '' ? 'error: usage: mcpgateway import <path-to-.mcp.json>'
344
+ : `error: ${args.target} is unreadable or not valid JSON: ${e.message}`);
345
+ process.exitCode = 2;
346
+ return;
347
+ }
348
+ const { servers, notes } = mcpJsonToServers(data);
349
+ for (const n of notes)
350
+ console.error(`note: ${n}`);
351
+ process.stdout.write(stringifyYaml({ servers }));
352
+ }
353
+ function loadConfigOrExit(path, noNetwork) {
354
+ try {
355
+ return loadConfigFile(path, { noNetwork });
356
+ }
357
+ catch (e) {
358
+ reportConfigError(e);
359
+ process.exit(2);
360
+ throw new Error('unreachable');
361
+ }
362
+ }
363
+ function reportConfigError(e) {
364
+ if (e instanceof ConfigError) {
365
+ console.error(e.message);
366
+ for (const w of e.__warnings ?? [])
367
+ console.error(w);
368
+ }
369
+ else {
370
+ console.error(`error: ${e.message}`);
371
+ }
372
+ process.exitCode = 2;
373
+ }
374
+ //# sourceMappingURL=cli.js.map