@alcyone-labs/arg-parser 2.6.0 → 2.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -35,6 +35,7 @@ var __flags, _throwForDuplicateFlags, _appName, _appCommandName, _subCommandName
35
35
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
36
36
  const fs = require("node:fs");
37
37
  const path = require("node:path");
38
+ const node_url = require("node:url");
38
39
  const magicRegexp = require("magic-regexp");
39
40
  const getTsconfig = require("get-tsconfig");
40
41
  const zod = require("zod");
@@ -3952,22 +3953,41 @@ const _ArgParserBase = class _ArgParserBase {
3952
3953
  console.log("--- End Configuration Dump ---\\n");
3953
3954
  }
3954
3955
  }
3956
+ /**
3957
+ * Detects if the current script is being executed directly (not imported)
3958
+ * Uses a robust method that works across different environments and sandboxes
3959
+ * @param importMetaUrl The import.meta.url from the calling script (optional)
3960
+ * @returns true if the script is being executed directly, false if imported
3961
+ */
3962
+ static isExecutedDirectly(importMetaUrl) {
3963
+ try {
3964
+ if (importMetaUrl) {
3965
+ const currentFile = node_url.fileURLToPath(importMetaUrl);
3966
+ const executedFile = path__namespace.resolve(process.argv[1]);
3967
+ return currentFile === executedFile;
3968
+ }
3969
+ if (typeof process !== "undefined" && process.argv && process.argv[1]) {
3970
+ return false;
3971
+ }
3972
+ return false;
3973
+ } catch {
3974
+ return false;
3975
+ }
3976
+ }
3955
3977
  async parse(processArgs, options) {
3956
- var _a, _b;
3978
+ var _a;
3957
3979
  debug.log("ArgParserBase.parse() called with args:", processArgs);
3980
+ const shouldCheckAutoExecution = (options == null ? void 0 : options.importMetaUrl) && (options == null ? void 0 : options.autoExecute) !== false;
3981
+ if (shouldCheckAutoExecution) {
3982
+ const isDirectExecution = _ArgParserBase.isExecutedDirectly(options.importMetaUrl);
3983
+ if (!isDirectExecution) {
3984
+ debug.log("Auto-execution enabled but script is imported, skipping execution");
3985
+ return {};
3986
+ }
3987
+ }
3958
3988
  if (processArgs === void 0) {
3959
3989
  if (typeof process !== "undefined" && process.argv && Array.isArray(process.argv)) {
3960
3990
  processArgs = process.argv.slice(2);
3961
- const isCliMode = !__privateGet(this, _parentParser) && !!__privateGet(this, _appCommandName);
3962
- const isMcpMode = (options == null ? void 0 : options.isMcp) || ((_a = globalThis.console) == null ? void 0 : _a.mcpError);
3963
- if (isCliMode && !isMcpMode) {
3964
- console.warn(
3965
- `Warning: parse() called without arguments. Auto-detected Node.js environment and using process.argv.slice(2).`
3966
- );
3967
- console.warn(
3968
- `For explicit control, call parse(process.argv.slice(2)) instead.`
3969
- );
3970
- }
3971
3991
  } else {
3972
3992
  throw new Error(
3973
3993
  "parse() called without arguments in non-Node.js environment. Please provide arguments explicitly: parse(['--flag', 'value'])"
@@ -3992,7 +4012,7 @@ const _ArgParserBase = class _ArgParserBase {
3992
4012
  commandChain: identifiedCommandChain,
3993
4013
  parserChain: identifiedParserChain
3994
4014
  } = __privateMethod(this, _ArgParserBase_instances, _identifyCommandChainAndParsers_fn).call(this, processArgs, this, [], [this]);
3995
- const saveToEnvResult = __privateMethod(_b = identifiedFinalParser, _ArgParserBase_instances, _handleSaveToEnvFlag_fn).call(_b, processArgs, identifiedParserChain);
4015
+ const saveToEnvResult = __privateMethod(_a = identifiedFinalParser, _ArgParserBase_instances, _handleSaveToEnvFlag_fn).call(_a, processArgs, identifiedParserChain);
3996
4016
  if (saveToEnvResult !== false) {
3997
4017
  return saveToEnvResult === true ? {} : saveToEnvResult;
3998
4018
  }
@@ -5156,10 +5176,12 @@ _handleMcpServeFlag_fn = async function(processArgs, _mcpServeIndex) {
5156
5176
  if (typeof loggerConfig === "string") {
5157
5177
  mcpLogger = mcpLoggerModule.createMcpLogger("MCP Serve", loggerConfig);
5158
5178
  } else {
5159
- mcpLogger = mcpLoggerModule.createMcpLogger(
5160
- loggerConfig.prefix || "MCP Serve",
5161
- loggerConfig.logToFile
5162
- );
5179
+ mcpLogger = mcpLoggerModule.createMcpLogger({
5180
+ prefix: loggerConfig.prefix || "MCP Serve",
5181
+ logToFile: loggerConfig.logToFile,
5182
+ level: loggerConfig.level,
5183
+ mcpMode: loggerConfig.mcpMode ?? true
5184
+ });
5163
5185
  }
5164
5186
  debug.log("Created MCP logger, about to hijack console");
5165
5187
  globalThis.console = mcpLogger;
@@ -5311,7 +5333,10 @@ _startUnifiedMcpServer_fn = async function(mcpServerConfig, transportOptions) {
5311
5333
  const finalTransportOptions = {
5312
5334
  port: transportOptions.port,
5313
5335
  host: transportOptions.host || "localhost",
5314
- path: transportOptions.path || "/mcp"
5336
+ path: transportOptions.path || "/mcp",
5337
+ // Pass-through for streamable-http only; harmlessly ignored for others
5338
+ cors: transportOptions.cors,
5339
+ auth: transportOptions.auth
5315
5340
  };
5316
5341
  await mcpParser.startMcpServerWithTransport(
5317
5342
  serverInfo,
@@ -5419,6 +5444,27 @@ _parseMcpTransportOptions_fn = function(processArgs) {
5419
5444
  i++;
5420
5445
  }
5421
5446
  break;
5447
+ // Streamable HTTP extras (accept JSON string)
5448
+ case "--s-mcp-cors":
5449
+ if (nextArg && !nextArg.startsWith("-")) {
5450
+ try {
5451
+ options.cors = JSON.parse(nextArg);
5452
+ } catch {
5453
+ options.cors = nextArg;
5454
+ }
5455
+ i++;
5456
+ }
5457
+ break;
5458
+ case "--s-mcp-auth":
5459
+ if (nextArg && !nextArg.startsWith("-")) {
5460
+ try {
5461
+ options.auth = JSON.parse(nextArg);
5462
+ } catch {
5463
+ options.auth = nextArg;
5464
+ }
5465
+ i++;
5466
+ }
5467
+ break;
5422
5468
  // Backward compatibility: support old flags but with deprecation warning
5423
5469
  case "--transport":
5424
5470
  case "--port":
@@ -6992,7 +7038,7 @@ Migration guide: https://github.com/alcyone-labs/arg-parser/blob/main/docs/MCP-M
6992
7038
  `After deduplication: ${uniqueTools.length} unique tools`
6993
7039
  );
6994
7040
  uniqueTools.forEach((tool) => {
6995
- var _a2, _b2, _c2, _d, _e, _f;
7041
+ var _a2, _b2, _c2, _d, _e, _f, _g;
6996
7042
  logger.mcpError(`Registering tool: ${tool.name}`);
6997
7043
  let zodSchema;
6998
7044
  const toolFromUnified = Array.from(this._tools.values()).find(
@@ -7108,6 +7154,29 @@ Migration guide: https://github.com/alcyone-labs/arg-parser/blob/main/docs/MCP-M
7108
7154
  inputSchema: mcpCompatibleSchema
7109
7155
  });
7110
7156
  }
7157
+ if (tool.outputSchema && this.supportsOutputSchemas()) {
7158
+ const convertedOutputSchema = createOutputSchema(tool.outputSchema);
7159
+ toolConfig.outputSchema = convertedOutputSchema;
7160
+ if (process.env["MCP_DEBUG"]) {
7161
+ console.error(
7162
+ `[MCP Debug] Including outputSchema for tool '${tool.name}':`,
7163
+ typeof tool.outputSchema
7164
+ );
7165
+ console.error(
7166
+ `[MCP Debug] Converted outputSchema constructor:`,
7167
+ (_g = convertedOutputSchema == null ? void 0 : convertedOutputSchema.constructor) == null ? void 0 : _g.name
7168
+ );
7169
+ console.error(
7170
+ `[MCP Debug] supportsOutputSchemas():`,
7171
+ this.supportsOutputSchemas()
7172
+ );
7173
+ }
7174
+ } else if (process.env["MCP_DEBUG"]) {
7175
+ console.error(
7176
+ `[MCP Debug] NOT including outputSchema for tool '${tool.name}':`,
7177
+ `hasOutputSchema=${!!tool.outputSchema}, supportsOutputSchemas=${this.supportsOutputSchemas()}`
7178
+ );
7179
+ }
7111
7180
  const simpleExecute = async (args) => {
7112
7181
  if (process.env["MCP_DEBUG"]) {
7113
7182
  console.error(
@@ -7456,6 +7525,34 @@ Migration guide: https://github.com/alcyone-labs/arg-parser/blob/main/docs/MCP-M
7456
7525
  parseAsync(processArgs, options) {
7457
7526
  return this.parse(processArgs, options);
7458
7527
  }
7528
+ /**
7529
+ * Convenience method for auto-execution: only runs if the script is executed directly (not imported).
7530
+ * This eliminates the need for boilerplate code to check if the script is being run directly.
7531
+ *
7532
+ * @param importMetaUrl Pass import.meta.url from your script for reliable detection
7533
+ * @param processArgs Optional arguments to parse (defaults to process.argv.slice(2))
7534
+ * @param options Additional parse options
7535
+ * @returns Promise that resolves to the parse result, or empty object if script is imported
7536
+ *
7537
+ * @example
7538
+ * ```typescript
7539
+ * // At the bottom of your CLI script:
7540
+ * await cli.parseIfExecutedDirectly(import.meta.url);
7541
+ *
7542
+ * // With error handling:
7543
+ * await cli.parseIfExecutedDirectly(import.meta.url).catch((error) => {
7544
+ * console.error("Fatal error:", error instanceof Error ? error.message : String(error));
7545
+ * process.exit(1);
7546
+ * });
7547
+ * ```
7548
+ */
7549
+ async parseIfExecutedDirectly(importMetaUrl, processArgs, options) {
7550
+ return this.parse(processArgs, {
7551
+ ...options,
7552
+ autoExecute: true,
7553
+ importMetaUrl
7554
+ });
7555
+ }
7459
7556
  addMcpSubCommand(subCommandName = "mcp-server", serverInfo, optionsOrToolOptions) {
7460
7557
  console.warn(`[DEPRECATED] addMcpSubCommand() is deprecated and will be removed in v2.0.
7461
7558
  Please use withMcp() to configure server metadata and the --s-mcp-serve system flag instead.
@@ -7734,6 +7831,7 @@ registerToolAsSubCommand_fn = function(toolConfig) {
7734
7831
  });
7735
7832
  };
7736
7833
  _startSingleTransport_fn = async function(server, serverInfo, transportConfig, logPath) {
7834
+ var _a, _b, _c, _d, _e, _f;
7737
7835
  const resolvedLogPath = resolveLogPath(logPath || "./logs/mcp.log");
7738
7836
  const logger = simpleMcpLogger.createMcpLogger("MCP Transport", resolvedLogPath);
7739
7837
  try {
@@ -7776,11 +7874,153 @@ _startSingleTransport_fn = async function(server, serverInfo, transportConfig, l
7776
7874
  const { StreamableHTTPServerTransport: StreamableHTTPServerTransport2 } = await Promise.resolve().then(() => streamableHttp);
7777
7875
  const express = (await import("express")).default;
7778
7876
  const app = express();
7877
+ app.disable("x-powered-by");
7779
7878
  app.use(express.json());
7879
+ app.get("/favicon.ico", (_req, res) => {
7880
+ const favicon = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
7881
+ <rect width="16" height="16" fill="white"/>
7882
+ <circle cx="8" cy="8" r="4" fill="red"/>
7883
+ </svg>`;
7884
+ res.setHeader("Content-Type", "image/svg+xml");
7885
+ res.setHeader("Cache-Control", "public, max-age=86400");
7886
+ res.send(favicon);
7887
+ });
7888
+ try {
7889
+ (_c = (_b = (_a = this._mcpServerConfig) == null ? void 0 : _a.httpServer) == null ? void 0 : _b.configureExpress) == null ? void 0 : _c.call(_b, app);
7890
+ } catch (e) {
7891
+ }
7780
7892
  const port = transportConfig.port || 3e3;
7781
7893
  const path2 = transportConfig.path || "/mcp";
7894
+ if (transportConfig.cors) {
7895
+ const cors = transportConfig.cors;
7896
+ const allowMethods = ((_d = cors.methods) == null ? void 0 : _d.join(", ")) || "GET,POST,PUT,PATCH,DELETE,OPTIONS";
7897
+ const allowHeaders = (req) => {
7898
+ var _a2;
7899
+ return ((_a2 = cors.headers) == null ? void 0 : _a2.join(", ")) || req.headers["access-control-request-headers"] || "Content-Type, Authorization, MCP-Session-Id";
7900
+ };
7901
+ const exposed = ((_e = cors.exposedHeaders) == null ? void 0 : _e.join(", ")) || void 0;
7902
+ const resolveOrigin = (req) => {
7903
+ const reqOrigin = req.headers.origin;
7904
+ const origins = cors.origins ?? "*";
7905
+ if (origins === "*") return cors.credentials ? reqOrigin : "*";
7906
+ if (!reqOrigin) return void 0;
7907
+ const list = Array.isArray(origins) ? origins : [origins];
7908
+ for (const o of list) {
7909
+ if (typeof o === "string" && o === reqOrigin) return reqOrigin;
7910
+ if (o instanceof RegExp && o.test(reqOrigin)) return reqOrigin;
7911
+ }
7912
+ return void 0;
7913
+ };
7914
+ const applyCorsHeaders = (req, res) => {
7915
+ const origin = resolveOrigin(req);
7916
+ if (origin) res.setHeader("Access-Control-Allow-Origin", origin);
7917
+ if (cors.credentials) res.setHeader("Access-Control-Allow-Credentials", "true");
7918
+ res.setHeader("Vary", "Origin");
7919
+ res.setHeader("Access-Control-Allow-Methods", allowMethods);
7920
+ const hdrs = allowHeaders(req);
7921
+ if (hdrs) res.setHeader("Access-Control-Allow-Headers", hdrs);
7922
+ if (exposed) res.setHeader("Access-Control-Expose-Headers", exposed);
7923
+ if (typeof cors.maxAge === "number") res.setHeader("Access-Control-Max-Age", String(cors.maxAge));
7924
+ };
7925
+ app.options(path2, (req, res) => {
7926
+ applyCorsHeaders(req, res);
7927
+ res.status(204).end();
7928
+ });
7929
+ app.use((req, res, next) => {
7930
+ if (req.path === path2) applyCorsHeaders(req, res);
7931
+ next();
7932
+ });
7933
+ }
7934
+ if ((_f = transportConfig.auth) == null ? void 0 : _f.customMiddleware) {
7935
+ app.use(transportConfig.auth.customMiddleware);
7936
+ }
7937
+ const authOpts = transportConfig.auth;
7938
+ const shouldRequireAuthFor = (req) => {
7939
+ if (!authOpts) return false;
7940
+ const reqPath = req.path;
7941
+ const pub = authOpts.publicPaths || [];
7942
+ const prot = authOpts.protectedPaths;
7943
+ if (pub.includes(reqPath)) return false;
7944
+ if (prot && !prot.includes(reqPath)) return false;
7945
+ return authOpts.required !== false;
7946
+ };
7947
+ const base64urlDecode = (s) => Buffer.from(s.replace(/-/g, "+").replace(/_/g, "/"), "base64");
7948
+ const verifyJwt = async (token) => {
7949
+ if (!(authOpts == null ? void 0 : authOpts.jwt)) return false;
7950
+ const [h, p, sig] = token.split(".");
7951
+ if (!h || !p || !sig) return false;
7952
+ const header = JSON.parse(base64urlDecode(h).toString("utf8"));
7953
+ const payload = JSON.parse(base64urlDecode(p).toString("utf8"));
7954
+ const alg = header.alg;
7955
+ if (authOpts.jwt.algorithms && !authOpts.jwt.algorithms.includes(alg)) return false;
7956
+ const data2 = Buffer.from(`${h}.${p}`);
7957
+ const signature = base64urlDecode(sig);
7958
+ if (alg === "HS256") {
7959
+ const secret = authOpts.jwt.secret;
7960
+ if (!secret) return false;
7961
+ const hmac = (await import("node:crypto")).createHmac("sha256", secret).update(data2).digest();
7962
+ if (!hmac.equals(signature)) return false;
7963
+ } else if (alg === "RS256") {
7964
+ const crypto = await import("node:crypto");
7965
+ let key = authOpts.jwt.publicKey;
7966
+ if (!key && authOpts.jwt.getPublicKey) {
7967
+ key = await authOpts.jwt.getPublicKey(header, payload);
7968
+ }
7969
+ if (!key) return false;
7970
+ const verify = crypto.createVerify("RSA-SHA256");
7971
+ verify.update(data2);
7972
+ verify.end();
7973
+ const ok = verify.verify(key, signature);
7974
+ if (!ok) return false;
7975
+ } else {
7976
+ return false;
7977
+ }
7978
+ if (authOpts.jwt.audience) {
7979
+ const allowed = Array.isArray(authOpts.jwt.audience) ? authOpts.jwt.audience : [authOpts.jwt.audience];
7980
+ if (!allowed.includes(payload.aud)) return false;
7981
+ }
7982
+ if (authOpts.jwt.issuer) {
7983
+ const allowed = Array.isArray(authOpts.jwt.issuer) ? authOpts.jwt.issuer : [authOpts.jwt.issuer];
7984
+ if (!allowed.includes(payload.iss)) return false;
7985
+ }
7986
+ const nowSec = Math.floor(Date.now() / 1e3);
7987
+ const tol = authOpts.jwt.clockToleranceSec || 0;
7988
+ if (payload.nbf && nowSec + tol < payload.nbf) return false;
7989
+ if (payload.exp && nowSec - tol >= payload.exp) return false;
7990
+ return true;
7991
+ };
7992
+ const authenticate = async (req) => {
7993
+ if (!authOpts) return true;
7994
+ const authz = req.headers.authorization;
7995
+ const token = (authz == null ? void 0 : authz.startsWith("Bearer ")) ? authz.slice(7) : void 0;
7996
+ if (!token) {
7997
+ if (authOpts.validator) return !!await authOpts.validator(req, token);
7998
+ return false;
7999
+ }
8000
+ if (authOpts.scheme === "jwt" || authOpts.jwt) {
8001
+ const ok = await verifyJwt(token);
8002
+ if (!ok) return false;
8003
+ } else if (authOpts.scheme === "bearer" || !authOpts.scheme) {
8004
+ if (authOpts.allowedTokens && !authOpts.allowedTokens.includes(token)) {
8005
+ if (authOpts.validator) return !!await authOpts.validator(req, token);
8006
+ return false;
8007
+ }
8008
+ }
8009
+ if (authOpts.validator) {
8010
+ const ok = await authOpts.validator(req, token);
8011
+ if (!ok) return false;
8012
+ }
8013
+ return true;
8014
+ };
7782
8015
  const transports = {};
7783
8016
  app.all(path2, async (req, res) => {
8017
+ if (shouldRequireAuthFor(req)) {
8018
+ const ok = await authenticate(req);
8019
+ if (!ok) {
8020
+ res.status(401).json({ error: "Unauthorized" });
8021
+ return;
8022
+ }
8023
+ }
7784
8024
  const sessionId = req.headers["mcp-session-id"];
7785
8025
  let transport;
7786
8026
  if (sessionId && transports[sessionId]) {
@@ -7793,9 +8033,7 @@ _startSingleTransport_fn = async function(server, serverInfo, transportConfig, l
7793
8033
  }
7794
8034
  });
7795
8035
  transport.onclose = () => {
7796
- if (transport.sessionId) {
7797
- delete transports[transport.sessionId];
7798
- }
8036
+ if (transport.sessionId) delete transports[transport.sessionId];
7799
8037
  };
7800
8038
  await server.connect(transport);
7801
8039
  }