dynmcp 0.4.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,13 +1,13 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/cli.ts
4
- import process7 from "process";
4
+ import process14 from "process";
5
5
  import { Command } from "commander";
6
6
 
7
7
  // package.json
8
8
  var package_default = {
9
9
  name: "dynmcp",
10
- version: "0.4.1",
10
+ version: "0.6.0",
11
11
  description: "Dynamic MCP context management tool for AI MCP-enabled agents and clients.",
12
12
  author: "Brandon Burrus <brandon@burrus.io>",
13
13
  license: "MIT",
@@ -69,6 +69,7 @@ var package_default = {
69
69
  },
70
70
  dependencies: {
71
71
  "@modelcontextprotocol/sdk": "^1.29.0",
72
+ "@napi-rs/keyring": "^1.3.0",
72
73
  boxen: "^8.0.1",
73
74
  chalk: "^5.6.2",
74
75
  commander: "^14.0.3",
@@ -98,9 +99,330 @@ var package_default = {
98
99
  import figlet from "figlet";
99
100
  import chalk from "chalk";
100
101
 
101
- // src/proxy/index.ts
102
- import process6 from "process";
103
- import { StdioClientTransport as StdioClientTransport2 } from "@modelcontextprotocol/sdk/client/stdio.js";
102
+ // src/auth/errors.ts
103
+ var AuthRequiredError = class extends Error {
104
+ mcpName;
105
+ constructor(mcpName2) {
106
+ super(
107
+ `Upstream MCP "${mcpName2}" requires authorization. Run \`dynmcp login ${mcpName2}\` from your terminal, then retry.`
108
+ );
109
+ this.name = "AuthRequiredError";
110
+ this.mcpName = mcpName2;
111
+ }
112
+ };
113
+ function isAuthRequiredError(error) {
114
+ let current = error;
115
+ for (let depth = 0; depth < 8 && current !== null && current !== void 0; depth += 1) {
116
+ if (current instanceof AuthRequiredError) return true;
117
+ if (current instanceof Error && current.name === "AuthRequiredError") return true;
118
+ if (current instanceof Error) {
119
+ current = current.cause;
120
+ continue;
121
+ }
122
+ return false;
123
+ }
124
+ return false;
125
+ }
126
+
127
+ // src/auth/keychain-store.ts
128
+ import { Entry } from "@napi-rs/keyring";
129
+
130
+ // src/auth/types.ts
131
+ var KEYCHAIN_BLOB_VERSION = 1;
132
+
133
+ // src/auth/keychain-store.ts
134
+ var KEYCHAIN_SERVICE = "dynmcp";
135
+ function buildKeychainAccount(mcpName2, serverUrl) {
136
+ const origin = new URL(serverUrl).origin;
137
+ return `${mcpName2}:${origin}`;
138
+ }
139
+ var KeychainStore = class {
140
+ constructor(mcpName2, serverUrl, service = KEYCHAIN_SERVICE) {
141
+ this.mcpName = mcpName2;
142
+ this.serverUrl = serverUrl;
143
+ this.entry = new Entry(service, buildKeychainAccount(mcpName2, serverUrl));
144
+ }
145
+ mcpName;
146
+ serverUrl;
147
+ entry;
148
+ /**
149
+ * Returns the parsed blob or `undefined` if no entry exists. Entries written under
150
+ * a different {@link KeychainBlob.version} are treated as absent — the caller must
151
+ * re-authenticate. Malformed JSON also returns `undefined` (corrupt entries are not
152
+ * surfaced as errors; recovery is the same: re-auth).
153
+ */
154
+ get() {
155
+ const raw = this.entry.getPassword();
156
+ if (raw === null) return void 0;
157
+ let parsed;
158
+ try {
159
+ parsed = JSON.parse(raw);
160
+ } catch {
161
+ return void 0;
162
+ }
163
+ if (!isCurrentVersionBlob(parsed)) {
164
+ return void 0;
165
+ }
166
+ return parsed;
167
+ }
168
+ /**
169
+ * Persists the blob atomically. Caller must construct a complete {@link
170
+ * KeychainBlob} — partial updates are not supported. To mutate, call {@link get},
171
+ * spread, and pass the result back to {@link set}.
172
+ */
173
+ set(blob) {
174
+ const stamped = { ...blob, version: KEYCHAIN_BLOB_VERSION };
175
+ this.entry.setPassword(JSON.stringify(stamped));
176
+ }
177
+ /**
178
+ * Deletes the entry. Returns `true` if an entry was present and removed, `false`
179
+ * if there was nothing to delete. Idempotent: callers should treat both outcomes
180
+ * as success (a no-op delete is not an error).
181
+ */
182
+ delete() {
183
+ return this.entry.deletePassword();
184
+ }
185
+ };
186
+ function isCurrentVersionBlob(value) {
187
+ return typeof value === "object" && value !== null && "version" in value && value.version === KEYCHAIN_BLOB_VERSION;
188
+ }
189
+
190
+ // src/auth/oauth-provider.ts
191
+ import { randomBytes } from "crypto";
192
+ var CLIENT_NAME = "dynmcp";
193
+ var SOFTWARE_ID = "dynmcp";
194
+ var REFRESH_SLACK_SECONDS = 30;
195
+ var BaseOAuthProvider = class {
196
+ constructor(mcpName2, keychain, configAuth) {
197
+ this.mcpName = mcpName2;
198
+ this.keychain = keychain;
199
+ this.configAuth = configAuth;
200
+ }
201
+ mcpName;
202
+ keychain;
203
+ configAuth;
204
+ clientInformation() {
205
+ if (this.configAuth !== void 0) {
206
+ const info2 = { client_id: this.configAuth.client_id };
207
+ if (this.configAuth.client_secret !== void 0) {
208
+ info2.client_secret = this.configAuth.client_secret;
209
+ }
210
+ return info2;
211
+ }
212
+ const blob = this.keychain.get();
213
+ if (blob?.dcr === void 0) return void 0;
214
+ const info = { client_id: blob.dcr.client_id };
215
+ if (blob.dcr.client_secret !== void 0) {
216
+ info.client_secret = blob.dcr.client_secret;
217
+ }
218
+ return info;
219
+ }
220
+ tokens() {
221
+ const blob = this.keychain.get();
222
+ if (blob === void 0) return void 0;
223
+ const remaining = Math.max(
224
+ 0,
225
+ blob.expires_at - Math.floor(Date.now() / 1e3) - REFRESH_SLACK_SECONDS
226
+ );
227
+ const tokens = {
228
+ access_token: blob.access_token,
229
+ token_type: blob.token_type,
230
+ expires_in: remaining
231
+ };
232
+ if (blob.refresh_token !== void 0) tokens.refresh_token = blob.refresh_token;
233
+ if (blob.scope_granted !== void 0) tokens.scope = blob.scope_granted;
234
+ return tokens;
235
+ }
236
+ /**
237
+ * Builds the {@link OAuthDiscoveryState} the SDK can use to skip rediscovery,
238
+ * reconstructed from the cached keychain blob. Returns `undefined` when there is
239
+ * no cached blob (e.g. fresh login flow before saveTokens fires).
240
+ */
241
+ buildDiscoveryStateFromBlob(blob) {
242
+ if (blob === void 0) return void 0;
243
+ return {
244
+ authorizationServerUrl: blob.authorization_server.issuer,
245
+ authorizationServerMetadata: {
246
+ issuer: blob.authorization_server.issuer,
247
+ authorization_endpoint: blob.authorization_server.authorization_endpoint,
248
+ token_endpoint: blob.authorization_server.token_endpoint,
249
+ ...blob.authorization_server.registration_endpoint !== void 0 ? { registration_endpoint: blob.authorization_server.registration_endpoint } : {},
250
+ response_types_supported: ["code"]
251
+ },
252
+ resourceMetadata: {
253
+ resource: blob.resource_metadata.resource,
254
+ authorization_servers: blob.resource_metadata.authorization_servers
255
+ }
256
+ };
257
+ }
258
+ };
259
+ var ProxyOAuthProvider = class extends BaseOAuthProvider {
260
+ get redirectUrl() {
261
+ return void 0;
262
+ }
263
+ get clientMetadata() {
264
+ return {
265
+ client_name: CLIENT_NAME,
266
+ software_id: SOFTWARE_ID,
267
+ redirect_uris: [],
268
+ grant_types: ["authorization_code", "refresh_token"],
269
+ response_types: ["code"],
270
+ token_endpoint_auth_method: this.configAuth?.client_secret !== void 0 ? "client_secret_basic" : "none",
271
+ ...this.configAuth?.scope !== void 0 ? { scope: this.configAuth.scope } : {}
272
+ };
273
+ }
274
+ saveTokens(tokens) {
275
+ const existing = this.keychain.get();
276
+ if (existing === void 0) {
277
+ throw new AuthRequiredError(this.mcpName);
278
+ }
279
+ const expiresAt = tokens.expires_in !== void 0 ? Math.floor(Date.now() / 1e3) + tokens.expires_in : existing.expires_at;
280
+ const updated = {
281
+ ...existing,
282
+ access_token: tokens.access_token,
283
+ token_type: tokens.token_type ?? "Bearer",
284
+ expires_at: expiresAt,
285
+ refresh_token: tokens.refresh_token ?? existing.refresh_token,
286
+ ...tokens.scope !== void 0 ? { scope_granted: tokens.scope } : {}
287
+ };
288
+ this.keychain.set(updated);
289
+ }
290
+ redirectToAuthorization(_url) {
291
+ throw new AuthRequiredError(this.mcpName);
292
+ }
293
+ saveCodeVerifier(_verifier) {
294
+ throw new AuthRequiredError(this.mcpName);
295
+ }
296
+ codeVerifier() {
297
+ throw new AuthRequiredError(this.mcpName);
298
+ }
299
+ discoveryState() {
300
+ return this.buildDiscoveryStateFromBlob(this.keychain.get());
301
+ }
302
+ invalidateCredentials(_scope) {
303
+ this.keychain.delete();
304
+ }
305
+ };
306
+ var LoginOAuthProvider = class extends BaseOAuthProvider {
307
+ redirectUriString;
308
+ pending = {};
309
+ callbacks;
310
+ constructor(opts) {
311
+ super(opts.mcpName, opts.keychain, opts.configAuth);
312
+ this.redirectUriString = opts.redirectUri;
313
+ this.callbacks = opts.callbacks;
314
+ }
315
+ get redirectUrl() {
316
+ return this.redirectUriString;
317
+ }
318
+ get clientMetadata() {
319
+ return {
320
+ client_name: CLIENT_NAME,
321
+ software_id: SOFTWARE_ID,
322
+ redirect_uris: [this.redirectUriString],
323
+ grant_types: ["authorization_code", "refresh_token"],
324
+ response_types: ["code"],
325
+ token_endpoint_auth_method: this.configAuth?.client_secret !== void 0 ? "client_secret_basic" : "none",
326
+ ...this.configAuth?.scope !== void 0 ? { scope: this.configAuth.scope } : {}
327
+ };
328
+ }
329
+ state() {
330
+ if (this.pending.state !== void 0) return this.pending.state;
331
+ const generated = randomBytes(32).toString("base64url");
332
+ this.pending.state = generated;
333
+ return generated;
334
+ }
335
+ /** The state value generated for this flow, for the callback handler to verify. */
336
+ get currentState() {
337
+ return this.pending.state;
338
+ }
339
+ clientInformation() {
340
+ if (this.pending.dcr !== void 0) {
341
+ const info = { client_id: this.pending.dcr.client_id };
342
+ if (this.pending.dcr.client_secret !== void 0) {
343
+ info.client_secret = this.pending.dcr.client_secret;
344
+ }
345
+ return info;
346
+ }
347
+ return super.clientInformation();
348
+ }
349
+ saveClientInformation(info) {
350
+ this.pending.dcr = info;
351
+ }
352
+ saveTokens(tokens) {
353
+ const discovery = this.pending.discovery ?? this.buildDiscoveryStateFromBlob(this.keychain.get());
354
+ if (discovery === void 0) {
355
+ throw new Error(
356
+ `Cannot persist tokens for "${this.mcpName}": no discovery state captured during the flow.`
357
+ );
358
+ }
359
+ if (discovery.authorizationServerMetadata === void 0) {
360
+ throw new Error(
361
+ `Cannot persist tokens for "${this.mcpName}": authorization server metadata not available.`
362
+ );
363
+ }
364
+ if (discovery.resourceMetadata === void 0) {
365
+ throw new Error(
366
+ `Cannot persist tokens for "${this.mcpName}": protected resource metadata not available.`
367
+ );
368
+ }
369
+ const expiresAt = tokens.expires_in !== void 0 ? Math.floor(Date.now() / 1e3) + tokens.expires_in : Math.floor(Date.now() / 1e3) + 3600;
370
+ const authorizationServer = {
371
+ issuer: discovery.authorizationServerMetadata.issuer ?? discovery.authorizationServerUrl,
372
+ authorization_endpoint: discovery.authorizationServerMetadata.authorization_endpoint,
373
+ token_endpoint: discovery.authorizationServerMetadata.token_endpoint,
374
+ ...discovery.authorizationServerMetadata.registration_endpoint !== void 0 ? { registration_endpoint: discovery.authorizationServerMetadata.registration_endpoint } : {}
375
+ };
376
+ const resourceMetadata = {
377
+ resource: discovery.resourceMetadata.resource,
378
+ authorization_servers: discovery.resourceMetadata.authorization_servers ?? []
379
+ };
380
+ const blob = {
381
+ version: KEYCHAIN_BLOB_VERSION,
382
+ access_token: tokens.access_token,
383
+ token_type: tokens.token_type ?? "Bearer",
384
+ expires_at: expiresAt,
385
+ ...tokens.refresh_token !== void 0 ? { refresh_token: tokens.refresh_token } : {},
386
+ ...tokens.scope !== void 0 ? { scope_granted: tokens.scope } : {},
387
+ authorization_server: authorizationServer,
388
+ resource_metadata: resourceMetadata,
389
+ ...this.pending.dcr !== void 0 ? {
390
+ dcr: {
391
+ client_id: this.pending.dcr.client_id,
392
+ ...this.pending.dcr.client_secret !== void 0 ? { client_secret: this.pending.dcr.client_secret } : {}
393
+ }
394
+ } : {}
395
+ };
396
+ this.keychain.set(blob);
397
+ }
398
+ async redirectToAuthorization(url) {
399
+ await this.callbacks.onAuthorizationUrl(url);
400
+ }
401
+ saveCodeVerifier(verifier) {
402
+ this.pending.codeVerifier = verifier;
403
+ }
404
+ codeVerifier() {
405
+ if (this.pending.codeVerifier === void 0) {
406
+ throw new Error("Code verifier requested before it was saved.");
407
+ }
408
+ return this.pending.codeVerifier;
409
+ }
410
+ saveDiscoveryState(state) {
411
+ this.pending.discovery = state;
412
+ }
413
+ /**
414
+ * Force a fresh RFC 9728 + RFC 8414 discovery for every login flow. We intentionally
415
+ * do NOT pre-seed from the keychain on login — if endpoints changed since the last
416
+ * login, we want to pick them up now and persist the new snapshot.
417
+ */
418
+ discoveryState() {
419
+ return void 0;
420
+ }
421
+ };
422
+
423
+ // src/auth/login.ts
424
+ import process4 from "process";
425
+ import { auth, extractWWWAuthenticateParams } from "@modelcontextprotocol/sdk/client/auth.js";
104
426
 
105
427
  // src/config/schema.ts
106
428
  import { z } from "zod";
@@ -122,26 +444,35 @@ var stdioTransport = z.object({
122
444
  var httpUrl = z.string().url().refine((u) => u.startsWith("http://") || u.startsWith("https://"), {
123
445
  message: "URL must use http:// or https:// scheme"
124
446
  });
447
+ var authConfig = z.object({
448
+ client_id: z.string().min(1, { message: "auth.client_id must be a non-empty string" }).refine((value) => value.trim().length > 0, {
449
+ message: "auth.client_id must not be whitespace-only"
450
+ }),
451
+ client_secret: z.string().min(1).optional(),
452
+ scope: z.string().min(1).optional()
453
+ }).strict().optional();
125
454
  var streamableHttpTransport = z.object({
126
455
  transport: z.literal("streamable-http"),
127
456
  description,
128
457
  url: httpUrl,
129
- headers: z.record(z.string(), z.string()).optional()
458
+ headers: z.record(z.string(), z.string()).optional(),
459
+ auth: authConfig
130
460
  }).strict();
131
461
  var sseTransport = z.object({
132
462
  transport: z.literal("sse"),
133
463
  description,
134
464
  url: httpUrl,
135
- headers: z.record(z.string(), z.string()).optional()
465
+ headers: z.record(z.string(), z.string()).optional(),
466
+ auth: authConfig
136
467
  }).strict();
137
- var transportConfig = z.discriminatedUnion("transport", [
468
+ var transportConfigSchema = z.discriminatedUnion("transport", [
138
469
  stdioTransport,
139
470
  streamableHttpTransport,
140
471
  sseTransport
141
472
  ]);
142
473
  var mcpConfigSchema = z.object({
143
474
  env: envModeSchema.optional(),
144
- mcp: z.record(mcpName, transportConfig).refine((obj) => Object.keys(obj).length > 0, { message: "At least one MCP must be configured" })
475
+ mcp: z.record(mcpName, transportConfigSchema).refine((obj) => Object.keys(obj).length > 0, { message: "At least one MCP must be configured" })
145
476
  });
146
477
 
147
478
  // src/config/loader.ts
@@ -208,9 +539,9 @@ function filterDefined(env) {
208
539
  var TOP_LEVEL_PASSTHROUGH_KEYS = /* @__PURE__ */ new Set(["$schema", "env"]);
209
540
  var MissingEnvVarsError = class extends Error {
210
541
  constructor(missingVars) {
211
- const list = missingVars.join(", ");
542
+ const list2 = missingVars.join(", ");
212
543
  const plural = missingVars.length === 1 ? "" : "s";
213
- super(`Missing required environment variable${plural}: ${list}`);
544
+ super(`Missing required environment variable${plural}: ${list2}`);
214
545
  this.missingVars = missingVars;
215
546
  this.name = "MissingEnvVarsError";
216
547
  }
@@ -348,28 +679,1124 @@ function loadConfig(options = {}) {
348
679
  throw new Error(`Invalid config file (${resolvedPath}):
349
680
  ${formatted}`);
350
681
  }
351
- return result.data;
682
+ return result.data;
683
+ }
684
+ function readEnvMode(content) {
685
+ if (content === null || typeof content !== "object" || Array.isArray(content)) {
686
+ return DEFAULT_ENV_MODE;
687
+ }
688
+ const value = content.env;
689
+ if (value === void 0) return DEFAULT_ENV_MODE;
690
+ if (typeof value === "string" && VALID_ENV_MODES.includes(value)) {
691
+ return value;
692
+ }
693
+ return DEFAULT_ENV_MODE;
694
+ }
695
+ function isYamlFile(filePath) {
696
+ return filePath.endsWith(".yml") || filePath.endsWith(".yaml");
697
+ }
698
+
699
+ // src/config/json-schema.ts
700
+ import { z as z2 } from "zod";
701
+
702
+ // src/auth/browser.ts
703
+ import { spawn } from "child_process";
704
+ import process3 from "process";
705
+ async function openUrl(url) {
706
+ const { command, args } = openerForPlatform(url);
707
+ return new Promise((resolve4, reject) => {
708
+ const child = spawn(command, args, {
709
+ stdio: "ignore",
710
+ detached: true
711
+ });
712
+ child.once("error", reject);
713
+ child.once("spawn", () => {
714
+ child.unref();
715
+ resolve4();
716
+ });
717
+ });
718
+ }
719
+ function openerForPlatform(url) {
720
+ switch (process3.platform) {
721
+ case "darwin":
722
+ return { command: "open", args: [url] };
723
+ case "win32":
724
+ return { command: "cmd", args: ["/c", "start", '""', url] };
725
+ default:
726
+ return { command: "xdg-open", args: [url] };
727
+ }
728
+ }
729
+
730
+ // src/auth/callback-server.ts
731
+ import { createServer } from "http";
732
+ var CallbackTimeoutError = class extends Error {
733
+ constructor(timeoutMs) {
734
+ super(`Timed out after ${timeoutMs}ms waiting for the OAuth callback.`);
735
+ this.name = "CallbackTimeoutError";
736
+ }
737
+ };
738
+ var CallbackOAuthError = class extends Error {
739
+ constructor(oauthError, oauthErrorDescription) {
740
+ super(
741
+ oauthErrorDescription ? `OAuth error from authorization server: ${oauthError} \u2014 ${oauthErrorDescription}` : `OAuth error from authorization server: ${oauthError}`
742
+ );
743
+ this.oauthError = oauthError;
744
+ this.oauthErrorDescription = oauthErrorDescription;
745
+ this.name = "CallbackOAuthError";
746
+ }
747
+ oauthError;
748
+ oauthErrorDescription;
749
+ };
750
+ var SUCCESS_HTML = `<!DOCTYPE html>
751
+ <html lang="en">
752
+ <head>
753
+ <meta charset="utf-8" />
754
+ <title>dynmcp \u2014 authorization complete</title>
755
+ <style>
756
+ body { font-family: -apple-system, BlinkMacSystemFont, sans-serif; padding: 4rem; max-width: 36rem; margin: 0 auto; color: #222; }
757
+ code { background: #f4f4f4; padding: 0.1rem 0.3rem; border-radius: 3px; }
758
+ </style>
759
+ </head>
760
+ <body>
761
+ <h1>Authorization complete</h1>
762
+ <p>You may close this tab and return to your terminal.</p>
763
+ <p><small>Issued by <code>dynmcp</code>.</small></p>
764
+ </body>
765
+ </html>
766
+ `;
767
+ var ERROR_HTML_PREFIX = `<!DOCTYPE html>
768
+ <html lang="en">
769
+ <head><meta charset="utf-8" /><title>dynmcp \u2014 authorization failed</title></head>
770
+ <body style="font-family: -apple-system, BlinkMacSystemFont, sans-serif; padding: 4rem; max-width: 36rem; margin: 0 auto;">
771
+ <h1>Authorization failed</h1>
772
+ <p>`;
773
+ var ERROR_HTML_SUFFIX = `</p>
774
+ <p>Return to your terminal for details.</p>
775
+ </body>
776
+ </html>
777
+ `;
778
+ var CallbackServer = class _CallbackServer {
779
+ server = null;
780
+ boundPort = null;
781
+ pending = null;
782
+ /** The redirect path served. Must match the redirect URI registered with the OAuth client. */
783
+ static CALLBACK_PATH = "/callback";
784
+ /** Begins listening on `127.0.0.1` at an OS-assigned port. */
785
+ async start() {
786
+ if (this.server !== null) {
787
+ throw new Error("CallbackServer is already started.");
788
+ }
789
+ const server = createServer((req, res) => this.handleRequest(req, res));
790
+ await new Promise((resolve4, reject) => {
791
+ const onError = (err) => {
792
+ server.removeListener("listening", onListening);
793
+ reject(err);
794
+ };
795
+ const onListening = () => {
796
+ server.removeListener("error", onError);
797
+ resolve4();
798
+ };
799
+ server.once("error", onError);
800
+ server.once("listening", onListening);
801
+ server.listen({ port: 0, host: "127.0.0.1" });
802
+ });
803
+ const address = server.address();
804
+ if (address === null || typeof address === "string") {
805
+ server.close();
806
+ throw new Error("Failed to determine bound port for callback server.");
807
+ }
808
+ this.boundPort = address.port;
809
+ this.server = server;
810
+ }
811
+ /** The port the OS assigned. Available after {@link start} resolves. */
812
+ get port() {
813
+ if (this.boundPort === null) {
814
+ throw new Error("CallbackServer is not started.");
815
+ }
816
+ return this.boundPort;
817
+ }
818
+ /** The full redirect URI to register with the authorization server. */
819
+ get redirectUri() {
820
+ return `http://127.0.0.1:${this.port}${_CallbackServer.CALLBACK_PATH}`;
821
+ }
822
+ /**
823
+ * Resolves with the captured `code` and `state` once a valid callback is received,
824
+ * or rejects with {@link CallbackTimeoutError} / {@link CallbackOAuthError} on the
825
+ * documented failure paths. Only one callback is accepted; subsequent requests to
826
+ * `/callback` after the first valid hit return `400`.
827
+ */
828
+ awaitCallback(timeoutMs) {
829
+ if (this.server === null) {
830
+ return Promise.reject(new Error("CallbackServer is not started."));
831
+ }
832
+ if (this.pending !== null) {
833
+ return Promise.reject(new Error("awaitCallback already in progress."));
834
+ }
835
+ return new Promise((resolve4, reject) => {
836
+ const timer = setTimeout(() => {
837
+ this.pending = null;
838
+ reject(new CallbackTimeoutError(timeoutMs));
839
+ }, timeoutMs);
840
+ this.pending = { resolve: resolve4, reject, timer };
841
+ });
842
+ }
843
+ /** Closes the listening socket. Safe to call multiple times. */
844
+ async stop() {
845
+ if (this.pending !== null) {
846
+ clearTimeout(this.pending.timer);
847
+ this.pending = null;
848
+ }
849
+ if (this.server === null) return;
850
+ await new Promise((resolve4) => {
851
+ this.server.close(() => resolve4());
852
+ });
853
+ this.server = null;
854
+ this.boundPort = null;
855
+ }
856
+ handleRequest(req, res) {
857
+ if (req.method !== "GET") {
858
+ res.writeHead(405, { "content-type": "text/plain", allow: "GET" });
859
+ res.end("Method Not Allowed");
860
+ return;
861
+ }
862
+ const url = new URL(req.url ?? "/", `http://127.0.0.1:${this.boundPort ?? 0}`);
863
+ if (url.pathname !== _CallbackServer.CALLBACK_PATH) {
864
+ res.writeHead(404, { "content-type": "text/plain" });
865
+ res.end("Not Found");
866
+ return;
867
+ }
868
+ if (this.pending === null) {
869
+ res.writeHead(400, { "content-type": "text/plain" });
870
+ res.end("No callback expected.");
871
+ return;
872
+ }
873
+ const oauthError = url.searchParams.get("error");
874
+ if (oauthError !== null) {
875
+ const errorDescription = url.searchParams.get("error_description") ?? void 0;
876
+ this.respondError(res, oauthError, errorDescription);
877
+ const { reject, timer: timer2 } = this.pending;
878
+ clearTimeout(timer2);
879
+ this.pending = null;
880
+ reject(new CallbackOAuthError(oauthError, errorDescription));
881
+ return;
882
+ }
883
+ const code = url.searchParams.get("code");
884
+ const state = url.searchParams.get("state");
885
+ if (code === null || state === null) {
886
+ this.respondError(res, "invalid_callback", "Missing code or state parameter.");
887
+ const { reject, timer: timer2 } = this.pending;
888
+ clearTimeout(timer2);
889
+ this.pending = null;
890
+ reject(new Error("Callback missing code or state parameter."));
891
+ return;
892
+ }
893
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
894
+ res.end(SUCCESS_HTML);
895
+ const { resolve: resolve4, timer } = this.pending;
896
+ clearTimeout(timer);
897
+ this.pending = null;
898
+ resolve4({ code, state });
899
+ }
900
+ respondError(res, errorCode, description2) {
901
+ res.writeHead(400, { "content-type": "text/html; charset=utf-8" });
902
+ res.end(
903
+ ERROR_HTML_PREFIX + escapeHtml(description2 ?? `OAuth error: ${errorCode}`) + ERROR_HTML_SUFFIX
904
+ );
905
+ }
906
+ };
907
+ function escapeHtml(value) {
908
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
909
+ }
910
+
911
+ // src/auth/login.ts
912
+ var CALLBACK_TIMEOUT_MS = 6e4;
913
+ async function login(options) {
914
+ const config = loadConfig({
915
+ configPath: options.configPath,
916
+ envFilePath: options.envFilePath
917
+ });
918
+ const entry = resolveOAuthCapableEntry(config, options.mcpName);
919
+ const writeStatus = options.writeStatus ?? defaultStatusWriter;
920
+ const openInBrowser = options.openInBrowser ?? openUrl;
921
+ writeStatus(`Probing ${entry.url} for OAuth challenge...
922
+ `);
923
+ const resourceMetadataUrl = await probeFor401ResourceMetadata(entry.url);
924
+ if (resourceMetadataUrl === void 0) {
925
+ throw new Error(
926
+ `Upstream "${options.mcpName}" did not return a 401 challenge with a WWW-Authenticate \`resource_metadata\` URL. The server does not appear to require OAuth; no credentials stored.`
927
+ );
928
+ }
929
+ const keychain = new KeychainStore(options.mcpName, entry.url);
930
+ const callbackServer = new CallbackServer();
931
+ await callbackServer.start();
932
+ writeStatus(`Callback server listening on ${callbackServer.redirectUri}
933
+ `);
934
+ try {
935
+ const provider = new LoginOAuthProvider({
936
+ mcpName: options.mcpName,
937
+ keychain,
938
+ configAuth: configAuthFromEntry(entry),
939
+ redirectUri: callbackServer.redirectUri,
940
+ callbacks: {
941
+ onAuthorizationUrl: async (url) => {
942
+ writeStatus(`Opening browser for authorization: ${url.toString()}
943
+ `);
944
+ try {
945
+ await openInBrowser(url.toString());
946
+ } catch (error) {
947
+ const reason = error instanceof Error ? error.message : String(error);
948
+ writeStatus(
949
+ `Failed to launch browser (${reason}). Open this URL manually:
950
+ ${url.toString()}
951
+ `
952
+ );
953
+ }
954
+ }
955
+ }
956
+ });
957
+ const firstResult = await auth(provider, {
958
+ serverUrl: entry.url,
959
+ resourceMetadataUrl,
960
+ ...entry.auth?.scope !== void 0 ? { scope: entry.auth.scope } : {}
961
+ });
962
+ if (firstResult === "AUTHORIZED") {
963
+ writeStatus(`Already authorized for "${options.mcpName}"; no changes made.
964
+ `);
965
+ return;
966
+ }
967
+ writeStatus(`Waiting for browser callback (timeout ${CALLBACK_TIMEOUT_MS / 1e3}s)...
968
+ `);
969
+ const { code, state: receivedState } = await callbackServer.awaitCallback(CALLBACK_TIMEOUT_MS);
970
+ const expectedState = provider.currentState;
971
+ if (expectedState === void 0 || receivedState !== expectedState) {
972
+ throw new Error(
973
+ "OAuth state mismatch on callback. Possible CSRF attempt or stale browser tab; not exchanging the authorization code."
974
+ );
975
+ }
976
+ const secondResult = await auth(provider, {
977
+ serverUrl: entry.url,
978
+ authorizationCode: code,
979
+ resourceMetadataUrl,
980
+ ...entry.auth?.scope !== void 0 ? { scope: entry.auth.scope } : {}
981
+ });
982
+ if (secondResult !== "AUTHORIZED") {
983
+ throw new Error(`Token exchange did not return AUTHORIZED (got ${secondResult}).`);
984
+ }
985
+ writeStatus(`Successfully authenticated "${options.mcpName}".
986
+ `);
987
+ } finally {
988
+ await callbackServer.stop();
989
+ }
990
+ }
991
+ function resolveOAuthCapableEntry(config, mcpName2) {
992
+ const entry = config.mcp[mcpName2];
993
+ if (entry === void 0) {
994
+ const available = Object.keys(config.mcp).sort().join(", ");
995
+ throw new Error(`Unknown MCP "${mcpName2}". Configured MCPs: ${available || "(none)"}.`);
996
+ }
997
+ if (entry.transport !== "streamable-http" && entry.transport !== "sse") {
998
+ throw new Error(
999
+ `MCP "${mcpName2}" uses the "${entry.transport}" transport; OAuth is only supported for streamable-http and sse upstreams.`
1000
+ );
1001
+ }
1002
+ return entry;
1003
+ }
1004
+ function configAuthFromEntry(entry) {
1005
+ if (entry.auth === void 0) return void 0;
1006
+ const overrides = { client_id: entry.auth.client_id };
1007
+ if (entry.auth.client_secret !== void 0) overrides.client_secret = entry.auth.client_secret;
1008
+ if (entry.auth.scope !== void 0) overrides.scope = entry.auth.scope;
1009
+ return overrides;
1010
+ }
1011
+ async function probeFor401ResourceMetadata(serverUrl) {
1012
+ let response;
1013
+ try {
1014
+ response = await fetch(serverUrl, { method: "GET", redirect: "manual" });
1015
+ } catch (error) {
1016
+ const reason = error instanceof Error ? error.message : String(error);
1017
+ throw new Error(`Failed to reach ${serverUrl}: ${reason}`);
1018
+ }
1019
+ if (response.status !== 401) {
1020
+ return void 0;
1021
+ }
1022
+ const { resourceMetadataUrl } = extractWWWAuthenticateParams(response);
1023
+ return resourceMetadataUrl;
1024
+ }
1025
+ function defaultStatusWriter(message) {
1026
+ process4.stderr.write(message);
1027
+ }
1028
+
1029
+ // src/auth/logout.ts
1030
+ import process5 from "process";
1031
+ async function logout(options) {
1032
+ const config = loadConfig({
1033
+ configPath: options.configPath,
1034
+ envFilePath: options.envFilePath
1035
+ });
1036
+ const entry = resolveOAuthCapableEntry2(config, options.mcpName);
1037
+ const writeStatus = options.writeStatus ?? defaultStatusWriter2;
1038
+ const keychain = new KeychainStore(options.mcpName, entry.url);
1039
+ const removed = keychain.delete();
1040
+ if (removed) {
1041
+ writeStatus(`Removed keychain credentials for "${options.mcpName}".
1042
+ `);
1043
+ } else {
1044
+ writeStatus(
1045
+ `No keychain credentials were stored for "${options.mcpName}"; nothing to remove.
1046
+ `
1047
+ );
1048
+ }
1049
+ }
1050
+ function resolveOAuthCapableEntry2(config, mcpName2) {
1051
+ const entry = config.mcp[mcpName2];
1052
+ if (entry === void 0) {
1053
+ const available = Object.keys(config.mcp).sort().join(", ");
1054
+ throw new Error(`Unknown MCP "${mcpName2}". Configured MCPs: ${available || "(none)"}.`);
1055
+ }
1056
+ if (entry.transport !== "streamable-http" && entry.transport !== "sse") {
1057
+ throw new Error(
1058
+ `MCP "${mcpName2}" uses the "${entry.transport}" transport; OAuth is only supported for streamable-http and sse upstreams.`
1059
+ );
1060
+ }
1061
+ return entry;
1062
+ }
1063
+ function defaultStatusWriter2(message) {
1064
+ process5.stderr.write(message);
1065
+ }
1066
+
1067
+ // src/diagnostics/list.ts
1068
+ import process6 from "process";
1069
+
1070
+ // src/diagnostics/format.ts
1071
+ function renderTable(headers, rows) {
1072
+ const allRows = [headers, ...rows];
1073
+ const widths = headers.map(
1074
+ (_, colIdx) => Math.max(...allRows.map((row) => (row[colIdx] ?? "").length))
1075
+ );
1076
+ return allRows.map(
1077
+ (row) => row.map((cell, i) => {
1078
+ if (i === headers.length - 1) return cell;
1079
+ return cell.padEnd(widths[i] ?? 0);
1080
+ }).join(" ").trimEnd()
1081
+ ).join("\n");
1082
+ }
1083
+ function truncate(value, max) {
1084
+ if (value.length <= max) return value;
1085
+ if (max <= 3) return value.slice(0, max);
1086
+ return `${value.slice(0, max - 3)}...`;
1087
+ }
1088
+ function humanizeDuration(seconds) {
1089
+ if (seconds < 0) return "expired";
1090
+ if (seconds < 60) return `${Math.floor(seconds)}s`;
1091
+ const totalMinutes = Math.floor(seconds / 60);
1092
+ if (totalMinutes < 60) return `${totalMinutes}m`;
1093
+ const totalHours = Math.floor(totalMinutes / 60);
1094
+ const remainingMinutes = totalMinutes % 60;
1095
+ if (totalHours < 24) {
1096
+ return remainingMinutes > 0 ? `${totalHours}h ${remainingMinutes}m` : `${totalHours}h`;
1097
+ }
1098
+ const totalDays = Math.floor(totalHours / 24);
1099
+ const remainingHours = totalHours % 24;
1100
+ return remainingHours > 0 ? `${totalDays}d ${remainingHours}h` : `${totalDays}d`;
1101
+ }
1102
+
1103
+ // src/diagnostics/list.ts
1104
+ var ENDPOINT_MAX_WIDTH = 48;
1105
+ async function list(options = {}) {
1106
+ const config = loadConfig({
1107
+ configPath: options.configPath,
1108
+ envFilePath: options.envFilePath
1109
+ });
1110
+ const write = options.write ?? ((chunk) => void process6.stdout.write(chunk));
1111
+ const now = options.now ?? (() => Math.floor(Date.now() / 1e3));
1112
+ const entries = buildEntries(config, now);
1113
+ if (options.json === true) {
1114
+ write(`${JSON.stringify(entries, null, 2)}
1115
+ `);
1116
+ return;
1117
+ }
1118
+ if (entries.length === 0) {
1119
+ write("No upstream MCPs configured.\n");
1120
+ return;
1121
+ }
1122
+ const headers = ["NAME", "TRANSPORT", "MODE", "ENDPOINT", "AUTH"];
1123
+ const rows = entries.map((entry) => [
1124
+ entry.name,
1125
+ entry.transport,
1126
+ entry.mode,
1127
+ truncate(entry.endpoint, ENDPOINT_MAX_WIDTH),
1128
+ formatAuthStatus(entry.auth)
1129
+ ]);
1130
+ write(`${renderTable(headers, rows)}
1131
+ `);
1132
+ }
1133
+ function buildEntries(config, now) {
1134
+ return Object.entries(config.mcp).map(([name, entry]) => {
1135
+ const mode = entry.description !== void 0 ? "lazy" : "eager";
1136
+ if (entry.transport === "stdio") {
1137
+ const command = entry.command;
1138
+ const args = (entry.args ?? []).join(" ");
1139
+ const endpoint = args.length > 0 ? `${command} ${args}` : command;
1140
+ const built2 = {
1141
+ name,
1142
+ transport: "stdio",
1143
+ mode,
1144
+ endpoint,
1145
+ auth: { kind: "n/a" }
1146
+ };
1147
+ if (entry.description !== void 0) built2.description = entry.description;
1148
+ return built2;
1149
+ }
1150
+ const hasAuthHeader = hasBearerAuthHeader(entry.headers);
1151
+ const keychain = new KeychainStore(name, entry.url);
1152
+ const blob = keychain.get();
1153
+ let auth2;
1154
+ if (blob !== void 0) {
1155
+ const expiresInSeconds = blob.expires_at - now();
1156
+ auth2 = {
1157
+ kind: "oauth",
1158
+ status: "logged_in",
1159
+ expiresInSeconds,
1160
+ expiresAt: blob.expires_at
1161
+ };
1162
+ if (hasAuthHeader) auth2.alsoHeader = true;
1163
+ } else if (hasAuthHeader) {
1164
+ auth2 = { kind: "header" };
1165
+ } else {
1166
+ auth2 = { kind: "oauth", status: "not_logged_in" };
1167
+ }
1168
+ const built = {
1169
+ name,
1170
+ transport: entry.transport,
1171
+ mode,
1172
+ endpoint: entry.url,
1173
+ auth: auth2
1174
+ };
1175
+ if (entry.description !== void 0) built.description = entry.description;
1176
+ return built;
1177
+ });
1178
+ }
1179
+ function hasBearerAuthHeader(headers) {
1180
+ if (headers === void 0) return false;
1181
+ for (const key of Object.keys(headers)) {
1182
+ if (key.toLowerCase() === "authorization") return true;
1183
+ }
1184
+ return false;
1185
+ }
1186
+ function formatAuthStatus(auth2) {
1187
+ switch (auth2.kind) {
1188
+ case "n/a":
1189
+ return "n/a";
1190
+ case "header":
1191
+ return "header";
1192
+ case "oauth": {
1193
+ if (auth2.status === "not_logged_in") return "oauth: not logged in";
1194
+ const duration = humanizeDuration(auth2.expiresInSeconds ?? 0);
1195
+ const base = `oauth: logged in (expires in ${duration})`;
1196
+ return auth2.alsoHeader === true ? `${base} (header also set)` : base;
1197
+ }
1198
+ }
1199
+ }
1200
+
1201
+ // src/diagnostics/test.ts
1202
+ import process8 from "process";
1203
+
1204
+ // src/proxy/transport-factory.ts
1205
+ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
1206
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
1207
+ import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
1208
+ function createTransport(mcpName2, config) {
1209
+ switch (config.transport) {
1210
+ case "stdio":
1211
+ return new StdioClientTransport({
1212
+ command: config.command,
1213
+ args: config.args,
1214
+ env: config.env
1215
+ });
1216
+ case "streamable-http":
1217
+ return new StreamableHTTPClientTransport(new URL(config.url), {
1218
+ ...config.headers !== void 0 ? { requestInit: { headers: config.headers } } : {},
1219
+ authProvider: buildOAuthProvider(mcpName2, config)
1220
+ });
1221
+ case "sse":
1222
+ return new SSEClientTransport(new URL(config.url), {
1223
+ ...config.headers !== void 0 ? { requestInit: { headers: config.headers } } : {},
1224
+ authProvider: buildOAuthProvider(mcpName2, config)
1225
+ });
1226
+ default: {
1227
+ const _exhaustive = config;
1228
+ return _exhaustive;
1229
+ }
1230
+ }
1231
+ }
1232
+ function buildOAuthProvider(mcpName2, config) {
1233
+ const keychain = new KeychainStore(mcpName2, config.url);
1234
+ return new ProxyOAuthProvider(mcpName2, keychain, config.auth);
1235
+ }
1236
+
1237
+ // src/proxy/upstream-client.ts
1238
+ import process7 from "process";
1239
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
1240
+ import {
1241
+ CreateMessageRequestSchema,
1242
+ ElicitRequestSchema,
1243
+ ListRootsRequestSchema,
1244
+ LoggingMessageNotificationSchema,
1245
+ PromptListChangedNotificationSchema,
1246
+ ResourceListChangedNotificationSchema,
1247
+ ResourceUpdatedNotificationSchema,
1248
+ ToolListChangedNotificationSchema
1249
+ } from "@modelcontextprotocol/sdk/types.js";
1250
+ var UpstreamClient = class {
1251
+ transport;
1252
+ onTransportError;
1253
+ notificationHandlers;
1254
+ serverRequestHandlers;
1255
+ client = null;
1256
+ constructor({
1257
+ name,
1258
+ transport,
1259
+ onTransportError,
1260
+ notifications,
1261
+ serverRequests
1262
+ }) {
1263
+ this.transport = transport;
1264
+ this.notificationHandlers = notifications ?? {};
1265
+ this.serverRequestHandlers = serverRequests ?? {};
1266
+ this.onTransportError = onTransportError ?? ((error) => {
1267
+ process7.stderr.write(`[${name}] Upstream MCP transport error: ${error.message}
1268
+ `);
1269
+ });
1270
+ }
1271
+ async connect() {
1272
+ this.transport.onerror = this.onTransportError;
1273
+ this.client = new Client(
1274
+ { name: "dynamic-discovery-mcp", version: "1.0.0" },
1275
+ {
1276
+ capabilities: {
1277
+ // Declare every client-side capability the proxy may relay on behalf of the host.
1278
+ // Actual reachability of each feature depends on what the host supports — if the
1279
+ // host does not support sampling, for instance, the host call returns an error
1280
+ // which we forward back to the upstream verbatim.
1281
+ sampling: {},
1282
+ elicitation: {},
1283
+ roots: { listChanged: true }
1284
+ }
1285
+ }
1286
+ );
1287
+ this.registerServerRequestHandlers(this.client);
1288
+ if (this.notificationHandlers.onToolsListChanged !== void 0) {
1289
+ this.client.setNotificationHandler(ToolListChangedNotificationSchema, async () => {
1290
+ await this.notificationHandlers.onToolsListChanged?.();
1291
+ });
1292
+ }
1293
+ if (this.notificationHandlers.onResourcesListChanged !== void 0) {
1294
+ this.client.setNotificationHandler(ResourceListChangedNotificationSchema, async () => {
1295
+ await this.notificationHandlers.onResourcesListChanged?.();
1296
+ });
1297
+ }
1298
+ if (this.notificationHandlers.onResourceUpdated !== void 0) {
1299
+ this.client.setNotificationHandler(ResourceUpdatedNotificationSchema, async (notification) => {
1300
+ await this.notificationHandlers.onResourceUpdated?.({ uri: notification.params.uri });
1301
+ });
1302
+ }
1303
+ if (this.notificationHandlers.onPromptsListChanged !== void 0) {
1304
+ this.client.setNotificationHandler(PromptListChangedNotificationSchema, async () => {
1305
+ await this.notificationHandlers.onPromptsListChanged?.();
1306
+ });
1307
+ }
1308
+ if (this.notificationHandlers.onLogMessage !== void 0) {
1309
+ this.client.setNotificationHandler(LoggingMessageNotificationSchema, async (notification) => {
1310
+ await this.notificationHandlers.onLogMessage?.(notification.params);
1311
+ });
1312
+ }
1313
+ await this.client.connect(this.transport);
1314
+ }
1315
+ async setLoggingLevel(level, options) {
1316
+ const client = this.requireClient();
1317
+ await client.setLoggingLevel(level, options);
1318
+ }
1319
+ async listPrompts(options) {
1320
+ const client = this.requireClient();
1321
+ const result = await client.listPrompts(void 0, options);
1322
+ return result.prompts;
1323
+ }
1324
+ async getPrompt(name, args, options) {
1325
+ const client = this.requireClient();
1326
+ const params = { name };
1327
+ if (args !== void 0) {
1328
+ params.arguments = args;
1329
+ }
1330
+ return client.getPrompt(params, options);
1331
+ }
1332
+ async complete(params, options) {
1333
+ const client = this.requireClient();
1334
+ return client.complete(params, options);
1335
+ }
1336
+ /**
1337
+ * Returns the capabilities advertised by the upstream server during initialize.
1338
+ * Returns `undefined` if the client is not connected, or if the SDK has not yet
1339
+ * recorded the server's capabilities (e.g. during a partially-completed handshake).
1340
+ */
1341
+ getCapabilities() {
1342
+ return this.client?.getServerCapabilities();
1343
+ }
1344
+ async listTools(options) {
1345
+ const client = this.requireClient();
1346
+ const result = await client.listTools(void 0, options);
1347
+ return result.tools.map((tool) => {
1348
+ const upstreamTool = {
1349
+ name: tool.name,
1350
+ description: tool.description ?? "",
1351
+ inputSchema: tool.inputSchema
1352
+ };
1353
+ if (tool.outputSchema !== void 0) {
1354
+ upstreamTool.outputSchema = tool.outputSchema;
1355
+ }
1356
+ if (tool.annotations !== void 0) {
1357
+ upstreamTool.annotations = {
1358
+ title: tool.annotations.title,
1359
+ readOnlyHint: tool.annotations.readOnlyHint,
1360
+ destructiveHint: tool.annotations.destructiveHint,
1361
+ idempotentHint: tool.annotations.idempotentHint,
1362
+ openWorldHint: tool.annotations.openWorldHint
1363
+ };
1364
+ }
1365
+ return upstreamTool;
1366
+ });
1367
+ }
1368
+ async callTool(name, input, options) {
1369
+ const client = this.requireClient();
1370
+ const result = await client.callTool({ name, arguments: input }, void 0, options);
1371
+ return result;
1372
+ }
1373
+ async listResources(options) {
1374
+ const client = this.requireClient();
1375
+ const result = await client.listResources(void 0, options);
1376
+ return result.resources;
1377
+ }
1378
+ async listResourceTemplates(options) {
1379
+ const client = this.requireClient();
1380
+ const result = await client.listResourceTemplates(void 0, options);
1381
+ return result.resourceTemplates;
1382
+ }
1383
+ async readResource(uri, options) {
1384
+ const client = this.requireClient();
1385
+ return client.readResource({ uri }, options);
1386
+ }
1387
+ async subscribeResource(uri, options) {
1388
+ const client = this.requireClient();
1389
+ await client.subscribeResource({ uri }, options);
1390
+ }
1391
+ async unsubscribeResource(uri, options) {
1392
+ const client = this.requireClient();
1393
+ await client.unsubscribeResource({ uri }, options);
1394
+ }
1395
+ async disconnect() {
1396
+ if (this.client === null) {
1397
+ return;
1398
+ }
1399
+ await this.client.close();
1400
+ this.client = null;
1401
+ }
1402
+ /**
1403
+ * Sends `notifications/roots/list_changed` to the upstream, letting it know that
1404
+ * the host's set of filesystem roots has changed.
1405
+ */
1406
+ async sendRootsListChanged() {
1407
+ const client = this.requireClient();
1408
+ await client.sendRootsListChanged();
1409
+ }
1410
+ registerServerRequestHandlers(client) {
1411
+ if (this.serverRequestHandlers.onCreateMessage !== void 0) {
1412
+ client.setRequestHandler(
1413
+ CreateMessageRequestSchema,
1414
+ async (request, extra) => {
1415
+ return this.serverRequestHandlers.onCreateMessage(request.params, {
1416
+ signal: extra.signal
1417
+ });
1418
+ }
1419
+ );
1420
+ }
1421
+ if (this.serverRequestHandlers.onElicitInput !== void 0) {
1422
+ client.setRequestHandler(
1423
+ ElicitRequestSchema,
1424
+ async (request, extra) => {
1425
+ return this.serverRequestHandlers.onElicitInput(request.params, {
1426
+ signal: extra.signal
1427
+ });
1428
+ }
1429
+ );
1430
+ }
1431
+ if (this.serverRequestHandlers.onListRoots !== void 0) {
1432
+ client.setRequestHandler(
1433
+ ListRootsRequestSchema,
1434
+ async (request, extra) => {
1435
+ return this.serverRequestHandlers.onListRoots(request.params, {
1436
+ signal: extra.signal
1437
+ });
1438
+ }
1439
+ );
1440
+ }
1441
+ }
1442
+ requireClient() {
1443
+ if (this.client === null) {
1444
+ throw new Error("Client is not connected. Call connect() first.");
1445
+ }
1446
+ return this.client;
1447
+ }
1448
+ };
1449
+
1450
+ // src/diagnostics/test.ts
1451
+ var DESCRIPTION_MAX_LENGTH = 100;
1452
+ var DEFAULT_TIMEOUT_MS = 15e3;
1453
+ async function test(options = {}) {
1454
+ const config = loadConfig({
1455
+ configPath: options.configPath,
1456
+ envFilePath: options.envFilePath
1457
+ });
1458
+ const write = options.write ?? ((chunk) => void process8.stdout.write(chunk));
1459
+ const now = options.now ?? (() => Math.floor(Date.now() / 1e3));
1460
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
1461
+ if (options.mcpName !== void 0) {
1462
+ return runSingle(config, options.mcpName, {
1463
+ write,
1464
+ now,
1465
+ timeoutMs,
1466
+ json: options.json === true
1467
+ });
1468
+ }
1469
+ return runAll(config, { write, now, timeoutMs, json: options.json === true });
1470
+ }
1471
+ async function runSingle(config, mcpName2, options) {
1472
+ const entry = config.mcp[mcpName2];
1473
+ if (entry === void 0) {
1474
+ const available = Object.keys(config.mcp).sort().join(", ");
1475
+ throw new Error(`Unknown MCP "${mcpName2}". Configured MCPs: ${available || "(none)"}.`);
1476
+ }
1477
+ if (!options.json) {
1478
+ options.write(`Testing "${mcpName2}" (${entry.transport}, ${endpointForEntry(entry)})
1479
+ `);
1480
+ }
1481
+ const result = await probeOne(mcpName2, entry, options.timeoutMs, options.now);
1482
+ if (options.json) {
1483
+ options.write(`${JSON.stringify(result, null, 2)}
1484
+ `);
1485
+ } else {
1486
+ for (const step of result.steps) {
1487
+ options.write(` [${step.status}] ${step.label}
1488
+ `);
1489
+ if (step.error !== void 0) {
1490
+ options.write(` -> ${step.error}
1491
+ `);
1492
+ }
1493
+ }
1494
+ renderDiscoveredSurface(options.write, result);
1495
+ options.write(`Result: ${result.result}
1496
+ `);
1497
+ }
1498
+ return result.result === "PASS" ? 0 : 1;
1499
+ }
1500
+ async function runAll(config, options) {
1501
+ const names = Object.keys(config.mcp);
1502
+ const total = names.length;
1503
+ if (!options.json) {
1504
+ options.write(`Testing all configured upstreams (${total})...
1505
+
1506
+ `);
1507
+ }
1508
+ const results = [];
1509
+ for (let index = 0; index < names.length; index += 1) {
1510
+ const name = names[index];
1511
+ const entry = config.mcp[name];
1512
+ if (!options.json) {
1513
+ options.write(`[${index + 1}/${total}] ${name} (${entry.transport}) ... `);
1514
+ }
1515
+ const result = await probeOne(name, entry, options.timeoutMs, options.now);
1516
+ results.push(result);
1517
+ if (!options.json) {
1518
+ if (result.result === "PASS") {
1519
+ const counts = `${result.tools?.length ?? 0} tools, ${(result.resources?.length ?? 0) + (result.resource_templates?.length ?? 0)} resources, ${result.prompts?.length ?? 0} prompts`;
1520
+ options.write(`PASS (${counts})
1521
+ `);
1522
+ } else {
1523
+ options.write(`FAIL (${result.fail_reason ?? "unknown"})
1524
+ `);
1525
+ }
1526
+ }
1527
+ }
1528
+ const passed = results.filter((r) => r.result === "PASS").length;
1529
+ const failed = results.length - passed;
1530
+ if (options.json) {
1531
+ const payload = { summary: { passed, failed }, results };
1532
+ options.write(`${JSON.stringify(payload, null, 2)}
1533
+ `);
1534
+ } else {
1535
+ options.write(`
1536
+ Summary: ${passed} passed, ${failed} failed
1537
+ `);
1538
+ }
1539
+ return failed === 0 ? 0 : 1;
1540
+ }
1541
+ async function probeOne(mcpName2, entry, timeoutMs, now) {
1542
+ const result = {
1543
+ name: mcpName2,
1544
+ result: "PASS",
1545
+ transport: entry.transport,
1546
+ endpoint: endpointForEntry(entry),
1547
+ auth: deriveAuthSummary(mcpName2, entry, now),
1548
+ steps: []
1549
+ };
1550
+ if (entry.transport !== "stdio") {
1551
+ result.steps.push({ label: authStepLabel(result.auth), status: "ok" });
1552
+ }
1553
+ const clientHolder = { value: null };
1554
+ let timeoutHandle;
1555
+ const run = (async () => {
1556
+ const transport = createTransport(mcpName2, entry);
1557
+ const client = new UpstreamClient({
1558
+ name: mcpName2,
1559
+ transport,
1560
+ onTransportError: () => {
1561
+ }
1562
+ });
1563
+ clientHolder.value = client;
1564
+ await client.connect();
1565
+ result.steps.push({ label: "Connected and initialized", status: "ok" });
1566
+ const caps = client.getCapabilities();
1567
+ result.capabilities = caps;
1568
+ result.steps.push({
1569
+ label: `Capabilities: ${describeCapabilities(caps)}`,
1570
+ status: "ok"
1571
+ });
1572
+ const tools = await client.listTools();
1573
+ result.tools = tools.map((tool) => ({
1574
+ name: tool.name,
1575
+ description: tool.description
1576
+ }));
1577
+ result.steps.push({
1578
+ label: `tools/list returned ${tools.length} tool${tools.length === 1 ? "" : "s"}`,
1579
+ status: "ok"
1580
+ });
1581
+ let resources = [];
1582
+ let templates = [];
1583
+ if (caps?.resources !== void 0) {
1584
+ try {
1585
+ resources = await client.listResources();
1586
+ templates = await client.listResourceTemplates();
1587
+ result.resources = resources.map((r) => {
1588
+ const out = {
1589
+ uri: r.uri,
1590
+ name: r.name
1591
+ };
1592
+ if (r.description !== void 0) out.description = r.description;
1593
+ return out;
1594
+ });
1595
+ result.resource_templates = templates.map((t) => {
1596
+ const out = {
1597
+ uriTemplate: t.uriTemplate,
1598
+ name: t.name
1599
+ };
1600
+ if (t.description !== void 0) out.description = t.description;
1601
+ return out;
1602
+ });
1603
+ result.steps.push({
1604
+ label: `resources/list returned ${resources.length} resource${resources.length === 1 ? "" : "s"}, ${templates.length} template${templates.length === 1 ? "" : "s"}`,
1605
+ status: "ok"
1606
+ });
1607
+ } catch (error) {
1608
+ result.steps.push({
1609
+ label: "resources/list",
1610
+ status: "fail",
1611
+ error: errorMessage(error)
1612
+ });
1613
+ }
1614
+ }
1615
+ let prompts = [];
1616
+ if (caps?.prompts !== void 0) {
1617
+ try {
1618
+ prompts = await client.listPrompts();
1619
+ result.prompts = prompts.map((p) => {
1620
+ const out = { name: p.name };
1621
+ if (p.description !== void 0) out.description = p.description;
1622
+ return out;
1623
+ });
1624
+ result.steps.push({
1625
+ label: `prompts/list returned ${prompts.length} prompt${prompts.length === 1 ? "" : "s"}`,
1626
+ status: "ok"
1627
+ });
1628
+ } catch (error) {
1629
+ result.steps.push({
1630
+ label: "prompts/list",
1631
+ status: "fail",
1632
+ error: errorMessage(error)
1633
+ });
1634
+ }
1635
+ }
1636
+ })();
1637
+ const timeout = new Promise((_, reject) => {
1638
+ timeoutHandle = setTimeout(() => {
1639
+ reject(new TestTimeoutError(timeoutMs));
1640
+ }, timeoutMs);
1641
+ });
1642
+ try {
1643
+ await Promise.race([run, timeout]);
1644
+ } catch (error) {
1645
+ result.result = "FAIL";
1646
+ result.fail_reason = failReason(error, mcpName2);
1647
+ result.steps.push({
1648
+ label: `aborted: ${result.fail_reason}`,
1649
+ status: "fail",
1650
+ error: errorMessage(error)
1651
+ });
1652
+ } finally {
1653
+ if (timeoutHandle !== void 0) clearTimeout(timeoutHandle);
1654
+ const connected = clientHolder.value;
1655
+ if (connected !== null) {
1656
+ try {
1657
+ await connected.disconnect();
1658
+ } catch {
1659
+ }
1660
+ }
1661
+ }
1662
+ if (result.result === "PASS" && result.steps.some((s) => s.status === "fail")) {
1663
+ result.result = "FAIL";
1664
+ const failed = result.steps.find((s) => s.status === "fail");
1665
+ result.fail_reason = failed?.error ?? failed?.label ?? "unknown";
1666
+ }
1667
+ return result;
1668
+ }
1669
+ var TestTimeoutError = class extends Error {
1670
+ constructor(timeoutMs) {
1671
+ super(`Test timed out after ${timeoutMs}ms`);
1672
+ this.name = "TestTimeoutError";
1673
+ }
1674
+ };
1675
+ function endpointForEntry(entry) {
1676
+ if (entry.transport === "stdio") {
1677
+ const args = (entry.args ?? []).join(" ");
1678
+ return args.length > 0 ? `${entry.command} ${args}` : entry.command;
1679
+ }
1680
+ return entry.url;
352
1681
  }
353
- function readEnvMode(content) {
354
- if (content === null || typeof content !== "object" || Array.isArray(content)) {
355
- return DEFAULT_ENV_MODE;
1682
+ function deriveAuthSummary(mcpName2, entry, now) {
1683
+ if (entry.transport === "stdio") return { kind: "n/a" };
1684
+ const keychain = new KeychainStore(mcpName2, entry.url);
1685
+ const blob = keychain.get();
1686
+ if (blob !== void 0) {
1687
+ return {
1688
+ kind: "oauth",
1689
+ status: "valid",
1690
+ expiresInSeconds: blob.expires_at - now()
1691
+ };
356
1692
  }
357
- const value = content.env;
358
- if (value === void 0) return DEFAULT_ENV_MODE;
359
- if (typeof value === "string" && VALID_ENV_MODES.includes(value)) {
360
- return value;
1693
+ const hasHeader = entry.headers !== void 0 && Object.keys(entry.headers).some((k) => k.toLowerCase() === "authorization");
1694
+ if (hasHeader) return { kind: "header" };
1695
+ return { kind: "oauth", status: "missing" };
1696
+ }
1697
+ function authStepLabel(auth2) {
1698
+ switch (auth2.kind) {
1699
+ case "n/a":
1700
+ return "(no auth applicable)";
1701
+ case "header":
1702
+ return "Static Authorization header present";
1703
+ case "oauth":
1704
+ if (auth2.status === "missing") return "No cached OAuth token";
1705
+ return `OAuth token present (expires in ${humanizeDuration(auth2.expiresInSeconds ?? 0)})`;
361
1706
  }
362
- return DEFAULT_ENV_MODE;
363
1707
  }
364
- function isYamlFile(filePath) {
365
- return filePath.endsWith(".yml") || filePath.endsWith(".yaml");
1708
+ function describeCapabilities(caps) {
1709
+ if (caps === void 0) return "(none advertised)";
1710
+ const parts = [];
1711
+ for (const [name, value] of Object.entries(caps)) {
1712
+ if (value === void 0 || value === null) continue;
1713
+ if (typeof value === "object" && Object.keys(value).length > 0) {
1714
+ const flags = Object.entries(value).filter(([, v]) => v === true).map(([k]) => k).join(",");
1715
+ parts.push(flags.length > 0 ? `${name}(${flags})` : name);
1716
+ } else {
1717
+ parts.push(name);
1718
+ }
1719
+ }
1720
+ return parts.length > 0 ? parts.join(", ") : "(none advertised)";
1721
+ }
1722
+ function failReason(error, mcpName2) {
1723
+ if (isAuthRequiredError(error)) {
1724
+ return `auth required: run \`dynmcp login ${mcpName2}\``;
1725
+ }
1726
+ if (error instanceof TestTimeoutError) return error.message;
1727
+ if (error instanceof Error) return error.message.split("\n")[0] ?? "unknown error";
1728
+ return String(error);
1729
+ }
1730
+ function errorMessage(error) {
1731
+ if (error instanceof Error) return error.message;
1732
+ return String(error);
1733
+ }
1734
+ function renderDiscoveredSurface(write, result) {
1735
+ if (result.result !== "PASS") return;
1736
+ const sections = [
1737
+ [
1738
+ `Tools (${result.tools?.length ?? 0})`,
1739
+ result.tools && result.tools.length > 0 ? () => {
1740
+ const sorted = [...result.tools ?? []].sort((a, b) => a.name.localeCompare(b.name));
1741
+ for (const tool of sorted) {
1742
+ write(` - ${tool.name}: ${truncate(tool.description, DESCRIPTION_MAX_LENGTH)}
1743
+ `);
1744
+ }
1745
+ } : void 0
1746
+ ],
1747
+ [
1748
+ `Resources (${result.resources?.length ?? 0})`,
1749
+ result.resources && result.resources.length > 0 ? () => {
1750
+ const sorted = [...result.resources ?? []].sort((a, b) => a.uri.localeCompare(b.uri));
1751
+ for (const r of sorted) {
1752
+ const tail = r.description ?? r.name;
1753
+ write(` - ${r.uri}: ${truncate(tail, DESCRIPTION_MAX_LENGTH)}
1754
+ `);
1755
+ }
1756
+ } : void 0
1757
+ ],
1758
+ [
1759
+ `Resource templates (${result.resource_templates?.length ?? 0})`,
1760
+ result.resource_templates && result.resource_templates.length > 0 ? () => {
1761
+ const sorted = [...result.resource_templates ?? []].sort(
1762
+ (a, b) => a.uriTemplate.localeCompare(b.uriTemplate)
1763
+ );
1764
+ for (const t of sorted) {
1765
+ const tail = t.description ?? t.name;
1766
+ write(` - ${t.uriTemplate}: ${truncate(tail, DESCRIPTION_MAX_LENGTH)}
1767
+ `);
1768
+ }
1769
+ } : void 0
1770
+ ],
1771
+ [
1772
+ `Prompts (${result.prompts?.length ?? 0})`,
1773
+ result.prompts && result.prompts.length > 0 ? () => {
1774
+ const sorted = [...result.prompts ?? []].sort((a, b) => a.name.localeCompare(b.name));
1775
+ for (const p of sorted) {
1776
+ const tail = p.description ?? "";
1777
+ write(
1778
+ ` - ${p.name}${tail.length > 0 ? `: ${truncate(tail, DESCRIPTION_MAX_LENGTH)}` : ""}
1779
+ `
1780
+ );
1781
+ }
1782
+ } : void 0
1783
+ ]
1784
+ ];
1785
+ for (const [header, render] of sections) {
1786
+ if (render === void 0) continue;
1787
+ write(`
1788
+ ${header}:
1789
+ `);
1790
+ render();
1791
+ }
366
1792
  }
367
1793
 
368
- // src/config/json-schema.ts
369
- import { z as z2 } from "zod";
1794
+ // src/proxy/index.ts
1795
+ import process11 from "process";
1796
+ import { StdioClientTransport as StdioClientTransport2 } from "@modelcontextprotocol/sdk/client/stdio.js";
370
1797
 
371
1798
  // src/proxy/orchestrator.ts
372
- import process4 from "process";
1799
+ import process9 from "process";
373
1800
 
374
1801
  // src/proxy/capability-aggregator.ts
375
1802
  function aggregateCapabilities(upstreams) {
@@ -782,305 +2209,92 @@ var ToolCatalog = class _ToolCatalog {
782
2209
  const sortedNames = [...this.tools.keys()].sort().join(", ");
783
2210
  return `Unknown tool: "${toolName}". Available tools: ${sortedNames}`;
784
2211
  }
785
- return buildToolDetailsString(toolName, tool);
786
- }
787
- };
788
- function buildFlatDescription(tools) {
789
- const sortedTools = [...tools].sort((a, b) => a.name.localeCompare(b.name));
790
- const toolLines = sortedTools.map((tool) => `- ${tool.name}: ${tool.description}`).join("\n");
791
- return `${DISCOVER_TOOL_PREAMBLE}
792
-
793
- <tools>
794
- ${toolLines}
795
- </tools>`;
796
- }
797
- function buildGroupedDescription(groups, lazyDescriptions) {
798
- const parts = [DISCOVER_TOOL_PREAMBLE];
799
- if (lazyDescriptions.size > 0) {
800
- parts.push(DYNAMIC_DISCOVERY_PREAMBLE);
801
- parts.push(buildMcpServersBlock(lazyDescriptions));
802
- }
803
- if (groups.size > 0) {
804
- parts.push(buildToolsBlock(groups));
805
- } else if (lazyDescriptions.size > 0) {
806
- parts.push(NO_TOOLS_LOADED_FOOTER);
807
- } else {
808
- parts.push("<tools>\n</tools>");
809
- }
810
- return parts.join("\n\n");
811
- }
812
- function buildToolsBlock(groups) {
813
- const sortedMcpNames = [...groups.keys()].sort();
814
- const sections = sortedMcpNames.map((mcpName2) => {
815
- const tools = groups.get(mcpName2);
816
- const sortedTools = [...tools].sort((a, b) => a.name.localeCompare(b.name));
817
- const toolLines = sortedTools.map((tool) => `- ${tool.name}: ${tool.description}`).join("\n");
818
- return `${mcpName2}:
819
- ${toolLines}`;
820
- });
821
- return `<tools>
822
- ${sections.join("\n\n")}
823
- </tools>`;
824
- }
825
- function buildMcpServersBlock(lazyDescriptions) {
826
- const lines = [...lazyDescriptions].map(([name, desc]) => `- ${name}: ${desc}`).join("\n");
827
- return `<mcp_servers>
828
- ${lines}
829
- </mcp_servers>`;
830
- }
831
- function buildToolDetailsString(displayName, tool) {
832
- const lines = [
833
- `Tool: ${displayName}`,
834
- `Description: ${tool.description}`,
835
- "",
836
- "Input Schema:",
837
- JSON.stringify(tool.inputSchema, null, 2)
838
- ];
839
- if (tool.outputSchema !== void 0) {
840
- lines.push("", "Output Schema:", JSON.stringify(tool.outputSchema, null, 2));
841
- }
842
- const annotationLines = buildAnnotationLines(tool);
843
- if (annotationLines.length > 0) {
844
- lines.push("", "Annotations:", ...annotationLines);
845
- }
846
- return lines.join("\n");
847
- }
848
- function buildAnnotationLines(tool) {
849
- if (tool.annotations === void 0) {
850
- return [];
851
- }
852
- const { annotations } = tool;
853
- const lines = [];
854
- if (annotations.title !== void 0) {
855
- lines.push(`- title: ${annotations.title}`);
856
- }
857
- if (annotations.readOnlyHint !== void 0) {
858
- lines.push(`- readOnlyHint: ${annotations.readOnlyHint}`);
859
- }
860
- if (annotations.destructiveHint !== void 0) {
861
- lines.push(`- destructiveHint: ${annotations.destructiveHint}`);
862
- }
863
- if (annotations.idempotentHint !== void 0) {
864
- lines.push(`- idempotentHint: ${annotations.idempotentHint}`);
865
- }
866
- if (annotations.openWorldHint !== void 0) {
867
- lines.push(`- openWorldHint: ${annotations.openWorldHint}`);
868
- }
869
- return lines;
870
- }
871
-
872
- // src/proxy/upstream-client.ts
873
- import process3 from "process";
874
- import { Client } from "@modelcontextprotocol/sdk/client/index.js";
875
- import {
876
- CreateMessageRequestSchema,
877
- ElicitRequestSchema,
878
- ListRootsRequestSchema,
879
- LoggingMessageNotificationSchema,
880
- PromptListChangedNotificationSchema,
881
- ResourceListChangedNotificationSchema,
882
- ResourceUpdatedNotificationSchema,
883
- ToolListChangedNotificationSchema
884
- } from "@modelcontextprotocol/sdk/types.js";
885
- var UpstreamClient = class {
886
- transport;
887
- onTransportError;
888
- notificationHandlers;
889
- serverRequestHandlers;
890
- client = null;
891
- constructor({
892
- name,
893
- transport,
894
- onTransportError,
895
- notifications,
896
- serverRequests
897
- }) {
898
- this.transport = transport;
899
- this.notificationHandlers = notifications ?? {};
900
- this.serverRequestHandlers = serverRequests ?? {};
901
- this.onTransportError = onTransportError ?? ((error) => {
902
- process3.stderr.write(`[${name}] Upstream MCP transport error: ${error.message}
903
- `);
904
- });
905
- }
906
- async connect() {
907
- this.transport.onerror = this.onTransportError;
908
- this.client = new Client(
909
- { name: "dynamic-discovery-mcp", version: "1.0.0" },
910
- {
911
- capabilities: {
912
- // Declare every client-side capability the proxy may relay on behalf of the host.
913
- // Actual reachability of each feature depends on what the host supports — if the
914
- // host does not support sampling, for instance, the host call returns an error
915
- // which we forward back to the upstream verbatim.
916
- sampling: {},
917
- elicitation: {},
918
- roots: { listChanged: true }
919
- }
920
- }
921
- );
922
- this.registerServerRequestHandlers(this.client);
923
- if (this.notificationHandlers.onToolsListChanged !== void 0) {
924
- this.client.setNotificationHandler(ToolListChangedNotificationSchema, async () => {
925
- await this.notificationHandlers.onToolsListChanged?.();
926
- });
927
- }
928
- if (this.notificationHandlers.onResourcesListChanged !== void 0) {
929
- this.client.setNotificationHandler(ResourceListChangedNotificationSchema, async () => {
930
- await this.notificationHandlers.onResourcesListChanged?.();
931
- });
932
- }
933
- if (this.notificationHandlers.onResourceUpdated !== void 0) {
934
- this.client.setNotificationHandler(ResourceUpdatedNotificationSchema, async (notification) => {
935
- await this.notificationHandlers.onResourceUpdated?.({ uri: notification.params.uri });
936
- });
937
- }
938
- if (this.notificationHandlers.onPromptsListChanged !== void 0) {
939
- this.client.setNotificationHandler(PromptListChangedNotificationSchema, async () => {
940
- await this.notificationHandlers.onPromptsListChanged?.();
941
- });
942
- }
943
- if (this.notificationHandlers.onLogMessage !== void 0) {
944
- this.client.setNotificationHandler(LoggingMessageNotificationSchema, async (notification) => {
945
- await this.notificationHandlers.onLogMessage?.(notification.params);
946
- });
947
- }
948
- await this.client.connect(this.transport);
949
- }
950
- async setLoggingLevel(level, options) {
951
- const client = this.requireClient();
952
- await client.setLoggingLevel(level, options);
953
- }
954
- async listPrompts(options) {
955
- const client = this.requireClient();
956
- const result = await client.listPrompts(void 0, options);
957
- return result.prompts;
958
- }
959
- async getPrompt(name, args, options) {
960
- const client = this.requireClient();
961
- const params = { name };
962
- if (args !== void 0) {
963
- params.arguments = args;
964
- }
965
- return client.getPrompt(params, options);
966
- }
967
- async complete(params, options) {
968
- const client = this.requireClient();
969
- return client.complete(params, options);
970
- }
971
- /**
972
- * Returns the capabilities advertised by the upstream server during initialize.
973
- * Returns `undefined` if the client is not connected, or if the SDK has not yet
974
- * recorded the server's capabilities (e.g. during a partially-completed handshake).
975
- */
976
- getCapabilities() {
977
- return this.client?.getServerCapabilities();
978
- }
979
- async listTools(options) {
980
- const client = this.requireClient();
981
- const result = await client.listTools(void 0, options);
982
- return result.tools.map((tool) => {
983
- const upstreamTool = {
984
- name: tool.name,
985
- description: tool.description ?? "",
986
- inputSchema: tool.inputSchema
987
- };
988
- if (tool.outputSchema !== void 0) {
989
- upstreamTool.outputSchema = tool.outputSchema;
990
- }
991
- if (tool.annotations !== void 0) {
992
- upstreamTool.annotations = {
993
- title: tool.annotations.title,
994
- readOnlyHint: tool.annotations.readOnlyHint,
995
- destructiveHint: tool.annotations.destructiveHint,
996
- idempotentHint: tool.annotations.idempotentHint,
997
- openWorldHint: tool.annotations.openWorldHint
998
- };
999
- }
1000
- return upstreamTool;
1001
- });
2212
+ return buildToolDetailsString(toolName, tool);
1002
2213
  }
1003
- async callTool(name, input, options) {
1004
- const client = this.requireClient();
1005
- const result = await client.callTool({ name, arguments: input }, void 0, options);
1006
- return result;
2214
+ };
2215
+ function buildFlatDescription(tools) {
2216
+ const sortedTools = [...tools].sort((a, b) => a.name.localeCompare(b.name));
2217
+ const toolLines = sortedTools.map((tool) => `- ${tool.name}: ${tool.description}`).join("\n");
2218
+ return `${DISCOVER_TOOL_PREAMBLE}
2219
+
2220
+ <tools>
2221
+ ${toolLines}
2222
+ </tools>`;
2223
+ }
2224
+ function buildGroupedDescription(groups, lazyDescriptions) {
2225
+ const parts = [DISCOVER_TOOL_PREAMBLE];
2226
+ if (lazyDescriptions.size > 0) {
2227
+ parts.push(DYNAMIC_DISCOVERY_PREAMBLE);
2228
+ parts.push(buildMcpServersBlock(lazyDescriptions));
1007
2229
  }
1008
- async listResources(options) {
1009
- const client = this.requireClient();
1010
- const result = await client.listResources(void 0, options);
1011
- return result.resources;
2230
+ if (groups.size > 0) {
2231
+ parts.push(buildToolsBlock(groups));
2232
+ } else if (lazyDescriptions.size > 0) {
2233
+ parts.push(NO_TOOLS_LOADED_FOOTER);
2234
+ } else {
2235
+ parts.push("<tools>\n</tools>");
1012
2236
  }
1013
- async listResourceTemplates(options) {
1014
- const client = this.requireClient();
1015
- const result = await client.listResourceTemplates(void 0, options);
1016
- return result.resourceTemplates;
2237
+ return parts.join("\n\n");
2238
+ }
2239
+ function buildToolsBlock(groups) {
2240
+ const sortedMcpNames = [...groups.keys()].sort();
2241
+ const sections = sortedMcpNames.map((mcpName2) => {
2242
+ const tools = groups.get(mcpName2);
2243
+ const sortedTools = [...tools].sort((a, b) => a.name.localeCompare(b.name));
2244
+ const toolLines = sortedTools.map((tool) => `- ${tool.name}: ${tool.description}`).join("\n");
2245
+ return `${mcpName2}:
2246
+ ${toolLines}`;
2247
+ });
2248
+ return `<tools>
2249
+ ${sections.join("\n\n")}
2250
+ </tools>`;
2251
+ }
2252
+ function buildMcpServersBlock(lazyDescriptions) {
2253
+ const lines = [...lazyDescriptions].map(([name, desc]) => `- ${name}: ${desc}`).join("\n");
2254
+ return `<mcp_servers>
2255
+ ${lines}
2256
+ </mcp_servers>`;
2257
+ }
2258
+ function buildToolDetailsString(displayName, tool) {
2259
+ const lines = [
2260
+ `Tool: ${displayName}`,
2261
+ `Description: ${tool.description}`,
2262
+ "",
2263
+ "Input Schema:",
2264
+ JSON.stringify(tool.inputSchema, null, 2)
2265
+ ];
2266
+ if (tool.outputSchema !== void 0) {
2267
+ lines.push("", "Output Schema:", JSON.stringify(tool.outputSchema, null, 2));
1017
2268
  }
1018
- async readResource(uri, options) {
1019
- const client = this.requireClient();
1020
- return client.readResource({ uri }, options);
2269
+ const annotationLines = buildAnnotationLines(tool);
2270
+ if (annotationLines.length > 0) {
2271
+ lines.push("", "Annotations:", ...annotationLines);
1021
2272
  }
1022
- async subscribeResource(uri, options) {
1023
- const client = this.requireClient();
1024
- await client.subscribeResource({ uri }, options);
2273
+ return lines.join("\n");
2274
+ }
2275
+ function buildAnnotationLines(tool) {
2276
+ if (tool.annotations === void 0) {
2277
+ return [];
1025
2278
  }
1026
- async unsubscribeResource(uri, options) {
1027
- const client = this.requireClient();
1028
- await client.unsubscribeResource({ uri }, options);
2279
+ const { annotations } = tool;
2280
+ const lines = [];
2281
+ if (annotations.title !== void 0) {
2282
+ lines.push(`- title: ${annotations.title}`);
1029
2283
  }
1030
- async disconnect() {
1031
- if (this.client === null) {
1032
- return;
1033
- }
1034
- await this.client.close();
1035
- this.client = null;
2284
+ if (annotations.readOnlyHint !== void 0) {
2285
+ lines.push(`- readOnlyHint: ${annotations.readOnlyHint}`);
1036
2286
  }
1037
- /**
1038
- * Sends `notifications/roots/list_changed` to the upstream, letting it know that
1039
- * the host's set of filesystem roots has changed.
1040
- */
1041
- async sendRootsListChanged() {
1042
- const client = this.requireClient();
1043
- await client.sendRootsListChanged();
2287
+ if (annotations.destructiveHint !== void 0) {
2288
+ lines.push(`- destructiveHint: ${annotations.destructiveHint}`);
1044
2289
  }
1045
- registerServerRequestHandlers(client) {
1046
- if (this.serverRequestHandlers.onCreateMessage !== void 0) {
1047
- client.setRequestHandler(
1048
- CreateMessageRequestSchema,
1049
- async (request, extra) => {
1050
- return this.serverRequestHandlers.onCreateMessage(request.params, {
1051
- signal: extra.signal
1052
- });
1053
- }
1054
- );
1055
- }
1056
- if (this.serverRequestHandlers.onElicitInput !== void 0) {
1057
- client.setRequestHandler(
1058
- ElicitRequestSchema,
1059
- async (request, extra) => {
1060
- return this.serverRequestHandlers.onElicitInput(request.params, {
1061
- signal: extra.signal
1062
- });
1063
- }
1064
- );
1065
- }
1066
- if (this.serverRequestHandlers.onListRoots !== void 0) {
1067
- client.setRequestHandler(
1068
- ListRootsRequestSchema,
1069
- async (request, extra) => {
1070
- return this.serverRequestHandlers.onListRoots(request.params, {
1071
- signal: extra.signal
1072
- });
1073
- }
1074
- );
1075
- }
2290
+ if (annotations.idempotentHint !== void 0) {
2291
+ lines.push(`- idempotentHint: ${annotations.idempotentHint}`);
1076
2292
  }
1077
- requireClient() {
1078
- if (this.client === null) {
1079
- throw new Error("Client is not connected. Call connect() first.");
1080
- }
1081
- return this.client;
2293
+ if (annotations.openWorldHint !== void 0) {
2294
+ lines.push(`- openWorldHint: ${annotations.openWorldHint}`);
1082
2295
  }
1083
- };
2296
+ return lines;
2297
+ }
1084
2298
 
1085
2299
  // src/proxy/upstream-registry.ts
1086
2300
  var UpstreamRegistry = class {
@@ -1333,6 +2547,9 @@ var Orchestrator = class {
1333
2547
  }
1334
2548
  } catch (error) {
1335
2549
  await this.registry.deleteOne(mcpName2);
2550
+ if (isAuthRequiredError(error)) {
2551
+ throw error;
2552
+ }
1336
2553
  const failures = this.lazyRegistry.recordFailure(mcpName2);
1337
2554
  if (failures >= MAX_LOAD_ATTEMPTS) {
1338
2555
  this.lazyRegistry.take(mcpName2);
@@ -1579,7 +2796,7 @@ var Orchestrator = class {
1579
2796
  targets.push(
1580
2797
  action(client).catch((error) => {
1581
2798
  const message = error instanceof Error ? error.message : String(error);
1582
- process4.stderr.write(`dynmcp: ${label} failed for "${mcpName2}": ${message}
2799
+ process9.stderr.write(`dynmcp: ${label} failed for "${mcpName2}": ${message}
1583
2800
  `);
1584
2801
  })
1585
2802
  );
@@ -1604,13 +2821,13 @@ function splitNamespacedName(namespacedName, knownMcpNames) {
1604
2821
  }
1605
2822
  function logCollisions(resourceRouter, promptRouter) {
1606
2823
  for (const collision of resourceRouter.collisions()) {
1607
- process4.stderr.write(
2824
+ process9.stderr.write(
1608
2825
  `dynmcp: resource URI collision: "${collision.uri}" is provided by "${collision.chosen}" and "${collision.shadowed}"; routing to "${collision.chosen}".
1609
2826
  `
1610
2827
  );
1611
2828
  }
1612
2829
  for (const collision of promptRouter.collisions()) {
1613
- process4.stderr.write(
2830
+ process9.stderr.write(
1614
2831
  `dynmcp: prompt name collision: "${collision.name}" is provided by "${collision.chosen}" and "${collision.shadowed}"; routing to "${collision.chosen}".
1615
2832
  `
1616
2833
  );
@@ -1618,7 +2835,7 @@ function logCollisions(resourceRouter, promptRouter) {
1618
2835
  }
1619
2836
 
1620
2837
  // src/proxy/server.ts
1621
- import process5 from "process";
2838
+ import process10 from "process";
1622
2839
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
1623
2840
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
1624
2841
  import {
@@ -1765,7 +2982,7 @@ var ProxyServer = class {
1765
2982
  async start() {
1766
2983
  const server = this.buildServer();
1767
2984
  const transport = new StdioServerTransport();
1768
- process5.stderr.write("Starting dynamic-discovery-mcp server over stdio\n");
2985
+ process10.stderr.write("Starting dynamic-discovery-mcp server over stdio\n");
1769
2986
  await server.connect(transport);
1770
2987
  }
1771
2988
  /**
@@ -1978,35 +3195,6 @@ var ProxyServer = class {
1978
3195
  }
1979
3196
  };
1980
3197
 
1981
- // src/proxy/transport-factory.ts
1982
- import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
1983
- import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
1984
- import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
1985
- function createTransport(config) {
1986
- switch (config.transport) {
1987
- case "stdio":
1988
- return new StdioClientTransport({
1989
- command: config.command,
1990
- args: config.args,
1991
- env: config.env
1992
- });
1993
- case "streamable-http":
1994
- return new StreamableHTTPClientTransport(
1995
- new URL(config.url),
1996
- config.headers ? { requestInit: { headers: config.headers } } : void 0
1997
- );
1998
- case "sse":
1999
- return new SSEClientTransport(
2000
- new URL(config.url),
2001
- config.headers ? { requestInit: { headers: config.headers } } : void 0
2002
- );
2003
- default: {
2004
- const _exhaustive = config;
2005
- return _exhaustive;
2006
- }
2007
- }
2008
- }
2009
-
2010
3198
  // src/proxy/index.ts
2011
3199
  var SINGLE_MCP_NAME = "__default__";
2012
3200
  async function startProxy(command, args) {
@@ -2024,7 +3212,7 @@ async function startProxyFromConfig(options = {}) {
2024
3212
  const eagerMcps = /* @__PURE__ */ new Map();
2025
3213
  const lazyMcps = /* @__PURE__ */ new Map();
2026
3214
  for (const [name, entry] of Object.entries(config.mcp)) {
2027
- const transport = createTransport(entry);
3215
+ const transport = createTransport(name, entry);
2028
3216
  if (entry.description !== void 0) {
2029
3217
  lazyMcps.set(name, { transport, description: entry.description });
2030
3218
  } else {
@@ -2046,7 +3234,7 @@ function buildOrchestrator(params) {
2046
3234
  lazyMcps: params.lazyMcps,
2047
3235
  namespaced: params.namespaced,
2048
3236
  onTransportError: (mcpName2, error) => {
2049
- process6.stderr.write(
3237
+ process11.stderr.write(
2050
3238
  `${params.transportErrorPrefix(mcpName2)} transport error: ${error.message}
2051
3239
  `
2052
3240
  );
@@ -2060,19 +3248,19 @@ async function runProxy(orchestrator) {
2060
3248
  if (isShuttingDown) return;
2061
3249
  isShuttingDown = true;
2062
3250
  orchestrator.disconnectAll().catch((error) => {
2063
- process6.stderr.write(
3251
+ process11.stderr.write(
2064
3252
  `dynmcp: error during disconnect: ${error instanceof Error ? error.message : String(error)}
2065
3253
  `
2066
3254
  );
2067
- }).finally(() => process6.exit(exitCode));
3255
+ }).finally(() => process11.exit(exitCode));
2068
3256
  };
2069
3257
  activeShutdown.shutdown = shutdown;
2070
3258
  try {
2071
3259
  await orchestrator.connect();
2072
3260
  } catch (error) {
2073
- process6.stderr.write(`dynmcp: ${error instanceof Error ? error.message : String(error)}
3261
+ process11.stderr.write(`dynmcp: ${error instanceof Error ? error.message : String(error)}
2074
3262
  `);
2075
- process6.exit(1);
3263
+ process11.exit(1);
2076
3264
  return;
2077
3265
  }
2078
3266
  const proxyServer = new ProxyServer({
@@ -2109,10 +3297,10 @@ async function runProxy(orchestrator) {
2109
3297
  onElicitInput: (params, options) => proxyServer.forwardElicitInput(params, options),
2110
3298
  onListRoots: (params, options) => proxyServer.forwardListRoots(params, options)
2111
3299
  });
2112
- process6.on("SIGINT", () => shutdown(0));
2113
- process6.on("SIGTERM", () => shutdown(0));
2114
- process6.stdin.on("end", () => shutdown(0));
2115
- process6.stdin.on("close", () => shutdown(0));
3300
+ process11.on("SIGINT", () => shutdown(0));
3301
+ process11.on("SIGTERM", () => shutdown(0));
3302
+ process11.stdin.on("end", () => shutdown(0));
3303
+ process11.stdin.on("close", () => shutdown(0));
2116
3304
  try {
2117
3305
  await proxyServer.start();
2118
3306
  } catch (error) {
@@ -2121,6 +3309,215 @@ async function runProxy(orchestrator) {
2121
3309
  }
2122
3310
  }
2123
3311
 
3312
+ // src/scaffold/init.ts
3313
+ import { existsSync as existsSync3, writeFileSync } from "fs";
3314
+ import { resolve as resolve3 } from "path";
3315
+ import process12 from "process";
3316
+
3317
+ // src/scaffold/format.ts
3318
+ import { extname } from "path";
3319
+ function detectFormat(filePath) {
3320
+ const ext = extname(filePath).toLowerCase();
3321
+ return ext === ".yml" || ext === ".yaml" ? "yaml" : "json";
3322
+ }
3323
+ var SCHEMA_URL = "https://dynamicmcp.tools/config.json";
3324
+
3325
+ // src/scaffold/init.ts
3326
+ function init(options = {}) {
3327
+ const cwd = options.cwd ?? process12.cwd();
3328
+ const stdout = options.write ?? ((chunk) => void process12.stdout.write(chunk));
3329
+ const fileWriter = options.fileWriter ?? ((p, c) => writeFileSync(p, c, "utf-8"));
3330
+ const fileExists = options.fileExists ?? ((p) => existsSync3(p));
3331
+ const targetPath = resolveInitPath({ cwd, path: options.path, yaml: options.yaml === true });
3332
+ const format = detectFormat(targetPath);
3333
+ if (fileExists(targetPath) && options.force !== true) {
3334
+ throw new Error(`File already exists: ${targetPath}
3335
+ Use --force to overwrite.`);
3336
+ }
3337
+ const contents = format === "yaml" ? renderYamlSkeleton() : renderJsonSkeleton();
3338
+ fileWriter(targetPath, contents);
3339
+ stdout(`Wrote ${targetPath}
3340
+ `);
3341
+ stdout("\nThis config has no MCPs yet. Add one with:\n");
3342
+ stdout(" dynmcp add <name> --command <cmd> (stdio upstream)\n");
3343
+ stdout(" dynmcp add <name> --transport streamable-http --url <url> (remote HTTP upstream)\n");
3344
+ stdout("\nSee https://dynamicmcp.tools for full documentation.\n");
3345
+ }
3346
+ function resolveInitPath(opts) {
3347
+ if (opts.path !== void 0) {
3348
+ return resolve3(opts.cwd, opts.path);
3349
+ }
3350
+ return resolve3(opts.cwd, opts.yaml ? "mcp.yaml" : "mcp.json");
3351
+ }
3352
+ function renderJsonSkeleton() {
3353
+ const body = JSON.stringify({ $schema: SCHEMA_URL, mcp: {} }, null, 2);
3354
+ return `${body}
3355
+ `;
3356
+ }
3357
+ function renderYamlSkeleton() {
3358
+ return `# yaml-language-server: $schema=${SCHEMA_URL}
3359
+
3360
+ mcp: {}
3361
+ `;
3362
+ }
3363
+
3364
+ // src/scaffold/add.ts
3365
+ import { readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
3366
+ import process13 from "process";
3367
+ import { parseDocument } from "yaml";
3368
+ function add(options) {
3369
+ validateName(options.name);
3370
+ const stdout = options.write ?? ((chunk) => void process13.stdout.write(chunk));
3371
+ const fileReader = options.fileReader ?? ((p) => readFileSync3(p, "utf-8"));
3372
+ const fileWriter = options.fileWriter ?? ((p, c) => writeFileSync2(p, c, "utf-8"));
3373
+ const resolvePath = options.resolvePath ?? resolveConfigPath;
3374
+ let targetPath;
3375
+ try {
3376
+ targetPath = resolvePath(options.configPath);
3377
+ } catch (error) {
3378
+ const message = error instanceof Error ? error.message : String(error);
3379
+ throw new Error(`${message}
3380
+ Hint: run 'dynmcp init' to create a starter config file.`);
3381
+ }
3382
+ const raw = fileReader(targetPath);
3383
+ const format = detectFormat(targetPath);
3384
+ const entry = buildEntry(options);
3385
+ const parsed = transportConfigSchema.safeParse(entry);
3386
+ if (!parsed.success) {
3387
+ const issues = parsed.error.issues.map((i) => ` - ${i.path.join(".") || "<root>"}: ${i.message}`).join("\n");
3388
+ throw new Error(`Invalid MCP entry:
3389
+ ${issues}`);
3390
+ }
3391
+ const next = format === "yaml" ? writeYaml(raw, options.name, parsed.data, options.force === true) : writeJson(raw, options.name, parsed.data, options.force === true);
3392
+ fileWriter(targetPath, next);
3393
+ stdout(`Added '${options.name}' (${options.transport}) to ${targetPath}
3394
+ `);
3395
+ }
3396
+ function validateName(name) {
3397
+ if (!MCP_NAME_PATTERN.test(name)) {
3398
+ throw new Error(
3399
+ `Invalid MCP name '${name}'. Names must match ${MCP_NAME_PATTERN.source} (lowercase letters, digits, and dashes; starting with a letter or digit).`
3400
+ );
3401
+ }
3402
+ }
3403
+ function buildEntry(options) {
3404
+ if (options.transport === "stdio") {
3405
+ if (options.command === void 0 || options.command.length === 0) {
3406
+ throw new Error("--command is required for stdio transport");
3407
+ }
3408
+ const entry2 = {
3409
+ transport: "stdio",
3410
+ command: options.command
3411
+ };
3412
+ if (options.description !== void 0) entry2.description = options.description;
3413
+ if (options.args !== void 0 && options.args.length > 0) {
3414
+ entry2.args = options.args;
3415
+ }
3416
+ if (options.envVars !== void 0 && options.envVars.length > 0) {
3417
+ entry2.env = parseKeyValuePairs(options.envVars, "--env");
3418
+ }
3419
+ return entry2;
3420
+ }
3421
+ if (options.url === void 0 || options.url.length === 0) {
3422
+ throw new Error(`--url is required for ${options.transport} transport`);
3423
+ }
3424
+ const entry = {
3425
+ transport: options.transport,
3426
+ url: options.url
3427
+ };
3428
+ if (options.description !== void 0) entry.description = options.description;
3429
+ if (options.headers !== void 0 && options.headers.length > 0) {
3430
+ entry.headers = parseHeaderPairs(options.headers);
3431
+ }
3432
+ const auth2 = buildAuthBlock(options);
3433
+ if (auth2 !== void 0) entry.auth = auth2;
3434
+ return entry;
3435
+ }
3436
+ function buildAuthBlock(options) {
3437
+ const hasAny = options.clientId !== void 0 || options.clientSecret !== void 0 || options.scope !== void 0;
3438
+ if (!hasAny) return void 0;
3439
+ if (options.clientId === void 0) {
3440
+ throw new Error("--client-id is required when --client-secret or --scope is provided");
3441
+ }
3442
+ const auth2 = { client_id: options.clientId };
3443
+ if (options.clientSecret !== void 0) auth2.client_secret = options.clientSecret;
3444
+ if (options.scope !== void 0) auth2.scope = options.scope;
3445
+ return auth2;
3446
+ }
3447
+ function parseKeyValuePairs(pairs, flag) {
3448
+ const out = {};
3449
+ for (const pair of pairs) {
3450
+ const eq = pair.indexOf("=");
3451
+ if (eq <= 0) {
3452
+ throw new Error(`${flag} expects KEY=VALUE (got: ${JSON.stringify(pair)})`);
3453
+ }
3454
+ const key = pair.slice(0, eq);
3455
+ out[key] = pair.slice(eq + 1);
3456
+ }
3457
+ return out;
3458
+ }
3459
+ function parseHeaderPairs(pairs) {
3460
+ const out = {};
3461
+ for (const pair of pairs) {
3462
+ const colon = pair.indexOf(":");
3463
+ if (colon <= 0) {
3464
+ throw new Error(`--header expects "Name: Value" (got: ${JSON.stringify(pair)})`);
3465
+ }
3466
+ const key = pair.slice(0, colon).trim();
3467
+ const value = pair.slice(colon + 1).trim();
3468
+ if (key.length === 0) {
3469
+ throw new Error(`--header name cannot be empty (got: ${JSON.stringify(pair)})`);
3470
+ }
3471
+ out[key] = value;
3472
+ }
3473
+ return out;
3474
+ }
3475
+ function writeJson(raw, name, entry, force) {
3476
+ let parsed;
3477
+ try {
3478
+ parsed = JSON.parse(raw);
3479
+ } catch (error) {
3480
+ const message = error instanceof Error ? error.message : String(error);
3481
+ throw new Error(`Failed to parse config as JSON: ${message}`);
3482
+ }
3483
+ if (!isPlainObject(parsed)) {
3484
+ throw new Error("Top-level config must be a JSON object.");
3485
+ }
3486
+ let mcp = parsed.mcp;
3487
+ if (mcp === void 0) {
3488
+ mcp = {};
3489
+ parsed.mcp = mcp;
3490
+ } else if (!isPlainObject(mcp)) {
3491
+ throw new Error("Config field 'mcp' must be an object.");
3492
+ }
3493
+ const mcpRecord = mcp;
3494
+ if (mcpRecord[name] !== void 0 && !force) {
3495
+ throw new Error(`Entry '${name}' already exists. Use --force to overwrite.`);
3496
+ }
3497
+ mcpRecord[name] = entry;
3498
+ return `${JSON.stringify(parsed, null, 2)}
3499
+ `;
3500
+ }
3501
+ function writeYaml(raw, name, entry, force) {
3502
+ const doc = parseDocument(raw);
3503
+ if (doc.errors.length > 0) {
3504
+ const first = doc.errors[0]?.message ?? "unknown error";
3505
+ throw new Error(`Failed to parse config as YAML: ${first}`);
3506
+ }
3507
+ if (!doc.has("mcp")) {
3508
+ doc.set("mcp", {});
3509
+ }
3510
+ const path = ["mcp", name];
3511
+ if (doc.hasIn(path) && !force) {
3512
+ throw new Error(`Entry '${name}' already exists. Use --force to overwrite.`);
3513
+ }
3514
+ doc.setIn(path, entry);
3515
+ return doc.toString();
3516
+ }
3517
+ function isPlainObject(value) {
3518
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3519
+ }
3520
+
2124
3521
  // src/cli.ts
2125
3522
  var cliBanner = chalk.bold.magentaBright(
2126
3523
  figlet.textSync("DYNAMIC MCP", {
@@ -2131,41 +3528,162 @@ var cliBanner = chalk.bold.magentaBright(
2131
3528
  );
2132
3529
  var cli = new Command(package_default.name).description(package_default.description).version(package_default.version).addHelpText("beforeAll", cliBanner).addHelpText(
2133
3530
  "after",
2134
- "\nExamples:\n dynmcp -- npx -y chrome-devtools-mcp@latest\n dynmcp --config ./mcp.json\n"
3531
+ "\nExamples:\n dynmcp -- npx -y chrome-devtools-mcp@latest\n dynmcp --config ./mcp.json\n dynmcp init\n dynmcp add filesystem --command npx --arg -y --arg @modelcontextprotocol/server-filesystem --arg /tmp\n dynmcp add github --transport streamable-http --url https://api.githubcopilot.com/mcp\n dynmcp ls\n dynmcp test github\n dynmcp login github\n dynmcp logout github\n"
2135
3532
  ).option("-c, --config <path>", "Path to config file (JSON or YAML)").option("-e, --env <path>", "Path to a .env file for environment variable interpolation").allowExcessArguments(true).passThroughOptions(true).action(async (_options, cmd) => {
2136
- const separatorIndex = process7.argv.indexOf("--");
3533
+ const separatorIndex = process14.argv.indexOf("--");
2137
3534
  const configPath = cmd.opts().config;
2138
3535
  const envFilePath = cmd.opts().env;
2139
3536
  if (separatorIndex !== -1) {
2140
- const [command, ...args] = process7.argv.slice(separatorIndex + 1);
3537
+ const [command, ...args] = process14.argv.slice(separatorIndex + 1);
2141
3538
  if (command === void 0) {
2142
- process7.stderr.write(
3539
+ process14.stderr.write(
2143
3540
  "dynmcp: no upstream command provided after --.\nUsage: dynmcp -- <command> [args...]\n"
2144
3541
  );
2145
- process7.exit(1);
3542
+ process14.exit(1);
2146
3543
  }
2147
3544
  try {
2148
3545
  await startProxy(command, args);
2149
3546
  } catch (error) {
2150
- process7.stderr.write(`dynmcp: ${error instanceof Error ? error.message : String(error)}
3547
+ process14.stderr.write(`dynmcp: ${error instanceof Error ? error.message : String(error)}
2151
3548
  `);
2152
- process7.exit(1);
3549
+ process14.exit(1);
2153
3550
  }
2154
3551
  return;
2155
3552
  }
2156
3553
  try {
2157
3554
  await startProxyFromConfig({ configPath, envFilePath });
2158
3555
  } catch (error) {
2159
- process7.stderr.write(`dynmcp: ${error instanceof Error ? error.message : String(error)}
3556
+ process14.stderr.write(`dynmcp: ${error instanceof Error ? error.message : String(error)}
3557
+ `);
3558
+ process14.exit(1);
3559
+ }
3560
+ });
3561
+ cli.command("init").description("Write a starter config file (mcp.json by default) in the current directory.").option("--path <path>", "Explicit target path (extension determines format).").option("--yaml", "Write mcp.yaml instead of mcp.json (ignored if --path is set).").option("--force", "Overwrite an existing file.").action((options) => {
3562
+ try {
3563
+ init({
3564
+ ...options.path !== void 0 ? { path: options.path } : {},
3565
+ ...options.yaml === true ? { yaml: true } : {},
3566
+ ...options.force === true ? { force: true } : {}
3567
+ });
3568
+ } catch (error) {
3569
+ process14.stderr.write(`dynmcp: ${error instanceof Error ? error.message : String(error)}
3570
+ `);
3571
+ process14.exit(1);
3572
+ }
3573
+ });
3574
+ var collectRepeatable = (value, previous) => [...previous, value];
3575
+ cli.command("add <name>").description("Insert a new MCP entry into the resolved config file.").option(
3576
+ "-t, --transport <transport>",
3577
+ "Transport: stdio | streamable-http | sse (default: stdio).",
3578
+ "stdio"
3579
+ ).option("-c, --config <path>", "Path to config file (otherwise auto-discovered).").option("--description <text>", "Per-entry description; presence makes the entry lazy.").option("--command <cmd>", "(stdio) Command to spawn for the upstream MCP.").option(
3580
+ "--arg <arg>",
3581
+ "(stdio) Repeatable positional argument passed after --command.",
3582
+ collectRepeatable,
3583
+ []
3584
+ ).option(
3585
+ "--env <KEY=VAL>",
3586
+ "(stdio) Repeatable env var for the spawned process.",
3587
+ collectRepeatable,
3588
+ []
3589
+ ).option("--url <url>", "(http/sse) Endpoint URL.").option(
3590
+ "--header <header>",
3591
+ '(http/sse) Repeatable "Name: Value" header.',
3592
+ collectRepeatable,
3593
+ []
3594
+ ).option("--client-id <id>", "(http/sse) Pre-registered OAuth client_id (skips DCR).").option("--client-secret <secret>", "(http/sse) Pre-registered OAuth client_secret.").option("--scope <scope>", "(http/sse) OAuth scope to request.").option("--force", "Overwrite an existing entry with the same name.").action(
3595
+ (name, options) => {
3596
+ try {
3597
+ const transport = options.transport;
3598
+ if (transport !== "stdio" && transport !== "streamable-http" && transport !== "sse") {
3599
+ throw new Error(
3600
+ `Invalid --transport '${options.transport}'. Must be one of: stdio, streamable-http, sse.`
3601
+ );
3602
+ }
3603
+ add({
3604
+ name,
3605
+ transport,
3606
+ ...options.config !== void 0 ? { configPath: options.config } : {},
3607
+ ...options.force === true ? { force: true } : {},
3608
+ ...options.description !== void 0 ? { description: options.description } : {},
3609
+ ...options.command !== void 0 ? { command: options.command } : {},
3610
+ ...options.arg.length > 0 ? { args: options.arg } : {},
3611
+ ...options.env.length > 0 ? { envVars: options.env } : {},
3612
+ ...options.url !== void 0 ? { url: options.url } : {},
3613
+ ...options.header.length > 0 ? { headers: options.header } : {},
3614
+ ...options.clientId !== void 0 ? { clientId: options.clientId } : {},
3615
+ ...options.clientSecret !== void 0 ? { clientSecret: options.clientSecret } : {},
3616
+ ...options.scope !== void 0 ? { scope: options.scope } : {}
3617
+ });
3618
+ } catch (error) {
3619
+ process14.stderr.write(`dynmcp: ${error instanceof Error ? error.message : String(error)}
3620
+ `);
3621
+ process14.exit(1);
3622
+ }
3623
+ }
3624
+ );
3625
+ cli.command("login <name>").description("Run the OAuth authorization-code flow for an upstream MCP and store tokens.").option("-c, --config <path>", "Path to config file (JSON or YAML)").option("-e, --env <path>", "Path to a .env file for environment variable interpolation").action(async (name, options) => {
3626
+ try {
3627
+ await login({
3628
+ mcpName: name,
3629
+ ...options.config !== void 0 ? { configPath: options.config } : {},
3630
+ ...options.env !== void 0 ? { envFilePath: options.env } : {}
3631
+ });
3632
+ } catch (error) {
3633
+ process14.stderr.write(`dynmcp: ${error instanceof Error ? error.message : String(error)}
3634
+ `);
3635
+ process14.exit(1);
3636
+ }
3637
+ });
3638
+ cli.command("logout <name>").description("Delete the OAuth keychain entry for an upstream MCP.").option("-c, --config <path>", "Path to config file (JSON or YAML)").option("-e, --env <path>", "Path to a .env file for environment variable interpolation").action(async (name, options) => {
3639
+ try {
3640
+ await logout({
3641
+ mcpName: name,
3642
+ ...options.config !== void 0 ? { configPath: options.config } : {},
3643
+ ...options.env !== void 0 ? { envFilePath: options.env } : {}
3644
+ });
3645
+ } catch (error) {
3646
+ process14.stderr.write(`dynmcp: ${error instanceof Error ? error.message : String(error)}
3647
+ `);
3648
+ process14.exit(1);
3649
+ }
3650
+ });
3651
+ cli.command("ls").description("List configured upstream MCPs with transport, mode, endpoint, and auth status.").option("-c, --config <path>", "Path to config file (JSON or YAML)").option("-e, --env <path>", "Path to a .env file for environment variable interpolation").option("--json", "Emit JSON instead of the aligned text table").action(async (options) => {
3652
+ try {
3653
+ await list({
3654
+ ...options.config !== void 0 ? { configPath: options.config } : {},
3655
+ ...options.env !== void 0 ? { envFilePath: options.env } : {},
3656
+ ...options.json === true ? { json: true } : {}
3657
+ });
3658
+ } catch (error) {
3659
+ process14.stderr.write(`dynmcp: ${error instanceof Error ? error.message : String(error)}
2160
3660
  `);
2161
- process7.exit(1);
3661
+ process14.exit(1);
2162
3662
  }
2163
3663
  });
3664
+ cli.command("test [name]").description("Probe one or all configured upstream MCPs and print their discovered catalogs.").option("-c, --config <path>", "Path to config file (JSON or YAML)").option("-e, --env <path>", "Path to a .env file for environment variable interpolation").option("--json", "Emit JSON instead of the formatted text output").option("--timeout <ms>", "Per-MCP timeout in milliseconds (default: 15000)", (v) => Number(v)).action(
3665
+ async (name, options) => {
3666
+ try {
3667
+ const exitCode = await test({
3668
+ ...name !== void 0 ? { mcpName: name } : {},
3669
+ ...options.config !== void 0 ? { configPath: options.config } : {},
3670
+ ...options.env !== void 0 ? { envFilePath: options.env } : {},
3671
+ ...options.json === true ? { json: true } : {},
3672
+ ...options.timeout !== void 0 && !Number.isNaN(options.timeout) ? { timeoutMs: options.timeout } : {}
3673
+ });
3674
+ if (exitCode !== 0) process14.exit(exitCode);
3675
+ } catch (error) {
3676
+ process14.stderr.write(`dynmcp: ${error instanceof Error ? error.message : String(error)}
3677
+ `);
3678
+ process14.exit(1);
3679
+ }
3680
+ }
3681
+ );
2164
3682
 
2165
3683
  // src/index.ts
2166
- import process8 from "process";
3684
+ import process15 from "process";
2167
3685
  async function main() {
2168
- cli.parse(process8.argv);
3686
+ cli.parse(process15.argv);
2169
3687
  }
2170
3688
  main();
2171
3689
  //# sourceMappingURL=index.js.map