@agiflowai/one-mcp 0.2.7 → 0.3.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/cli.mjs CHANGED
@@ -1,10 +1,11 @@
1
1
  #!/usr/bin/env node
2
- import { a as SkillService, c as ConfigFetcherService, i as createServer, n as SseTransportHandler, o as findConfigFile, r as StdioTransportHandler, s as McpClientManagerService, t as HttpTransportHandler } from "./http-DSkkpGJU.mjs";
2
+ import { a as SkillService, c as ConfigFetcherService, i as createServer, n as SseTransportHandler, o as findConfigFile, r as StdioTransportHandler, s as McpClientManagerService, t as HttpTransportHandler } from "./http-xi_ha63Y.mjs";
3
3
  import { writeFile } from "node:fs/promises";
4
4
  import { resolve } from "node:path";
5
5
  import { Liquid } from "liquidjs";
6
6
  import { Command } from "commander";
7
- import { log } from "@agiflowai/aicode-utils";
7
+ import { log, print } from "@agiflowai/aicode-utils";
8
+ import { spawn } from "node:child_process";
8
9
 
9
10
  //#region src/types/index.ts
10
11
  /**
@@ -68,7 +69,7 @@ async function startServer(handler) {
68
69
  /**
69
70
  * MCP Serve command
70
71
  */
71
- const mcpServeCommand = new Command("mcp-serve").description("Start MCP server with specified transport").option("-t, --type <type>", "Transport type: stdio, http, or sse", "stdio").option("-p, --port <port>", "Port to listen on (http/sse only)", (val) => parseInt(val, 10), 3e3).option("--host <host>", "Host to bind to (http/sse only)", "localhost").option("-c, --config <path>", "Path to MCP server configuration file").option("--no-cache", "Disable configuration caching, always reload from config file").action(async (options) => {
72
+ const mcpServeCommand = new Command("mcp-serve").description("Start MCP server with specified transport").option("-t, --type <type>", "Transport type: stdio, http, or sse", "stdio").option("-p, --port <port>", "Port to listen on (http/sse only)", (val) => parseInt(val, 10), 3e3).option("--host <host>", "Host to bind to (http/sse only)", "localhost").option("-c, --config <path>", "Path to MCP server configuration file").option("--no-cache", "Disable configuration caching, always reload from config file").option("--id <id>", "Unique server identifier (overrides config file id, auto-generated if not provided)").action(async (options) => {
72
73
  const transportType = options.type.toLowerCase();
73
74
  if (!isValidTransportType(transportType)) {
74
75
  console.error(`Unknown transport type: '${transportType}'. Valid options: stdio, http, sse`);
@@ -77,7 +78,8 @@ const mcpServeCommand = new Command("mcp-serve").description("Start MCP server w
77
78
  try {
78
79
  const serverOptions = {
79
80
  configFilePath: options.config || findConfigFile() || void 0,
80
- noCache: options.cache === false
81
+ noCache: options.cache === false,
82
+ serverId: options.id
81
83
  };
82
84
  if (transportType === "stdio") await startServer(new StdioTransportHandler(await createServer(serverOptions)));
83
85
  else if (transportType === "http") await startServer(new HttpTransportHandler(await createServer(serverOptions), {
@@ -546,9 +548,462 @@ const initCommand = new Command("init").description("Initialize MCP configuratio
546
548
  }
547
549
  });
548
550
 
551
+ //#endregion
552
+ //#region src/services/PrefetchService/constants.ts
553
+ /**
554
+ * PrefetchService Constants
555
+ *
556
+ * Constants for package manager commands and process configuration.
557
+ */
558
+ /** Transport type for stdio-based MCP servers */
559
+ const TRANSPORT_STDIO = "stdio";
560
+ /** npx command name */
561
+ const COMMAND_NPX = "npx";
562
+ /** npm command name */
563
+ const COMMAND_NPM = "npm";
564
+ /** pnpx command name (pnpm's npx equivalent) */
565
+ const COMMAND_PNPX = "pnpx";
566
+ /** pnpm command name */
567
+ const COMMAND_PNPM = "pnpm";
568
+ /** uvx command name */
569
+ const COMMAND_UVX = "uvx";
570
+ /** uv command name */
571
+ const COMMAND_UV = "uv";
572
+ /** Path suffix for npx command */
573
+ const COMMAND_NPX_SUFFIX = "/npx";
574
+ /** Path suffix for pnpx command */
575
+ const COMMAND_PNPX_SUFFIX = "/pnpx";
576
+ /** Path suffix for uvx command */
577
+ const COMMAND_UVX_SUFFIX = "/uvx";
578
+ /** Path suffix for uv command */
579
+ const COMMAND_UV_SUFFIX = "/uv";
580
+ /** Run subcommand for uv */
581
+ const ARG_RUN = "run";
582
+ /** Tool subcommand for uv */
583
+ const ARG_TOOL = "tool";
584
+ /** Install subcommand for uv tool and npm/pnpm */
585
+ const ARG_INSTALL = "install";
586
+ /** Add subcommand for pnpm */
587
+ const ARG_ADD = "add";
588
+ /** Global flag for npm/pnpm install */
589
+ const ARG_GLOBAL = "-g";
590
+ /** Flag prefix for command arguments */
591
+ const FLAG_PREFIX = "-";
592
+ /** npx --package flag (long form) */
593
+ const FLAG_PACKAGE_LONG = "--package";
594
+ /** npx -p flag (short form) */
595
+ const FLAG_PACKAGE_SHORT = "-p";
596
+ /** Equals delimiter used in flag=value patterns */
597
+ const EQUALS_DELIMITER = "=";
598
+ /**
599
+ * Regex pattern for valid package names (npm, pnpm, uvx, uv)
600
+ * Allows: @scope/package-name@version, package-name, package_name
601
+ * Prevents shell metacharacters that could enable command injection
602
+ * @example
603
+ * // Valid: '@scope/package@1.0.0', 'my-package', 'my_package', '@org/pkg'
604
+ * // Invalid: 'pkg; rm -rf /', 'pkg$(cmd)', 'pkg`whoami`', 'pkg|cat /etc/passwd'
605
+ */
606
+ const VALID_PACKAGE_NAME_PATTERN = /^(@[a-zA-Z0-9_-]+\/)?[a-zA-Z0-9._-]+(@[a-zA-Z0-9._-]+)?$/;
607
+ /** Windows platform identifier */
608
+ const PLATFORM_WIN32 = "win32";
609
+ /** Success exit code */
610
+ const EXIT_CODE_SUCCESS = 0;
611
+ /** Stdio option to ignore stream */
612
+ const STDIO_IGNORE = "ignore";
613
+ /** Stdio option to pipe stream */
614
+ const STDIO_PIPE = "pipe";
615
+
616
+ //#endregion
617
+ //#region src/services/PrefetchService/PrefetchService.ts
618
+ /**
619
+ * PrefetchService
620
+ *
621
+ * DESIGN PATTERNS:
622
+ * - Service pattern for business logic encapsulation
623
+ * - Single responsibility principle
624
+ *
625
+ * CODING STANDARDS:
626
+ * - Use async/await for asynchronous operations
627
+ * - Throw descriptive errors for error cases
628
+ * - Keep methods focused and well-named
629
+ * - Document complex logic with comments
630
+ *
631
+ * AVOID:
632
+ * - Mixing concerns (keep focused on single domain)
633
+ * - Direct tool implementation (services should be tool-agnostic)
634
+ */
635
+ /**
636
+ * Type guard to check if a config object is an McpStdioConfig
637
+ * @param config - Config object to check
638
+ * @returns True if config has required McpStdioConfig properties
639
+ */
640
+ function isMcpStdioConfig(config) {
641
+ return typeof config === "object" && config !== null && "command" in config;
642
+ }
643
+ /**
644
+ * PrefetchService handles pre-downloading packages used by MCP servers.
645
+ * Supports npx (Node.js), uvx (Python/uv), and uv run commands.
646
+ *
647
+ * @example
648
+ * ```typescript
649
+ * const service = new PrefetchService({
650
+ * mcpConfig: await configFetcher.fetchConfiguration(),
651
+ * parallel: true,
652
+ * });
653
+ * const packages = service.extractPackages();
654
+ * const summary = await service.prefetch();
655
+ * ```
656
+ */
657
+ var PrefetchService = class {
658
+ config;
659
+ /**
660
+ * Creates a new PrefetchService instance
661
+ * @param config - Service configuration options
662
+ */
663
+ constructor(config) {
664
+ this.config = config;
665
+ }
666
+ /**
667
+ * Extract all prefetchable packages from the MCP configuration
668
+ * @returns Array of package info objects
669
+ */
670
+ extractPackages() {
671
+ const packages = [];
672
+ const { mcpConfig, filter } = this.config;
673
+ for (const [serverName, serverConfig] of Object.entries(mcpConfig.mcpServers)) {
674
+ if (serverConfig.disabled) continue;
675
+ if (serverConfig.transport !== TRANSPORT_STDIO) continue;
676
+ if (!isMcpStdioConfig(serverConfig.config)) continue;
677
+ const packageInfo = this.extractPackageInfo(serverName, serverConfig.config);
678
+ if (packageInfo) {
679
+ if (filter && packageInfo.packageManager !== filter) continue;
680
+ packages.push(packageInfo);
681
+ }
682
+ }
683
+ return packages;
684
+ }
685
+ /**
686
+ * Prefetch all packages from the configuration
687
+ * @returns Summary of prefetch results
688
+ * @throws Error if prefetch operation fails unexpectedly
689
+ */
690
+ async prefetch() {
691
+ try {
692
+ const packages = this.extractPackages();
693
+ const results = [];
694
+ if (packages.length === 0) return {
695
+ totalPackages: 0,
696
+ successful: 0,
697
+ failed: 0,
698
+ results: []
699
+ };
700
+ if (this.config.parallel) {
701
+ const promises = packages.map(async (pkg) => this.prefetchPackage(pkg));
702
+ results.push(...await Promise.all(promises));
703
+ } else for (const pkg of packages) {
704
+ const result = await this.prefetchPackage(pkg);
705
+ results.push(result);
706
+ }
707
+ const successful = results.filter((r) => r.success).length;
708
+ const failed = results.filter((r) => !r.success).length;
709
+ return {
710
+ totalPackages: packages.length,
711
+ successful,
712
+ failed,
713
+ results
714
+ };
715
+ } catch (error) {
716
+ throw new Error(`Failed to prefetch packages: ${error instanceof Error ? error.message : String(error)}`);
717
+ }
718
+ }
719
+ /**
720
+ * Prefetch a single package
721
+ * @param pkg - Package info to prefetch
722
+ * @returns Result of the prefetch operation
723
+ */
724
+ async prefetchPackage(pkg) {
725
+ try {
726
+ const [command, ...args] = pkg.fullCommand;
727
+ const result = await this.runCommand(command, args);
728
+ return {
729
+ package: pkg,
730
+ success: result.success,
731
+ output: result.output
732
+ };
733
+ } catch (error) {
734
+ return {
735
+ package: pkg,
736
+ success: false,
737
+ output: error instanceof Error ? error.message : String(error)
738
+ };
739
+ }
740
+ }
741
+ /**
742
+ * Validate package name to prevent command injection
743
+ * @param packageName - Package name to validate
744
+ * @returns True if package name is safe, false otherwise
745
+ * @remarks Rejects package names containing shell metacharacters
746
+ * @example
747
+ * isValidPackageName('@scope/package') // true
748
+ * isValidPackageName('my-package@1.0.0') // true
749
+ * isValidPackageName('pkg; rm -rf /') // false (shell injection)
750
+ * isValidPackageName('pkg$(whoami)') // false (command substitution)
751
+ */
752
+ isValidPackageName(packageName) {
753
+ return VALID_PACKAGE_NAME_PATTERN.test(packageName);
754
+ }
755
+ /**
756
+ * Extract package info from a server's stdio config
757
+ * @param serverName - Name of the MCP server
758
+ * @param config - Stdio configuration for the server
759
+ * @returns Package info if extractable, null otherwise
760
+ */
761
+ extractPackageInfo(serverName, config) {
762
+ const command = config.command.toLowerCase();
763
+ const args = config.args || [];
764
+ if (command === COMMAND_NPX || command.endsWith(COMMAND_NPX_SUFFIX)) {
765
+ const packageName = this.extractNpxPackage(args);
766
+ if (packageName && this.isValidPackageName(packageName)) return {
767
+ serverName,
768
+ packageManager: COMMAND_NPX,
769
+ packageName,
770
+ fullCommand: [
771
+ COMMAND_NPM,
772
+ ARG_INSTALL,
773
+ ARG_GLOBAL,
774
+ packageName
775
+ ]
776
+ };
777
+ }
778
+ if (command === COMMAND_PNPX || command.endsWith(COMMAND_PNPX_SUFFIX)) {
779
+ const packageName = this.extractNpxPackage(args);
780
+ if (packageName && this.isValidPackageName(packageName)) return {
781
+ serverName,
782
+ packageManager: COMMAND_PNPX,
783
+ packageName,
784
+ fullCommand: [
785
+ COMMAND_PNPM,
786
+ ARG_ADD,
787
+ ARG_GLOBAL,
788
+ packageName
789
+ ]
790
+ };
791
+ }
792
+ if (command === COMMAND_UVX || command.endsWith(COMMAND_UVX_SUFFIX)) {
793
+ const packageName = this.extractUvxPackage(args);
794
+ if (packageName && this.isValidPackageName(packageName)) return {
795
+ serverName,
796
+ packageManager: COMMAND_UVX,
797
+ packageName,
798
+ fullCommand: [COMMAND_UVX, packageName]
799
+ };
800
+ }
801
+ if ((command === COMMAND_UV || command.endsWith(COMMAND_UV_SUFFIX)) && args.includes(ARG_RUN)) {
802
+ const packageName = this.extractUvRunPackage(args);
803
+ if (packageName && this.isValidPackageName(packageName)) return {
804
+ serverName,
805
+ packageManager: COMMAND_UV,
806
+ packageName,
807
+ fullCommand: [
808
+ COMMAND_UV,
809
+ ARG_TOOL,
810
+ ARG_INSTALL,
811
+ packageName
812
+ ]
813
+ };
814
+ }
815
+ return null;
816
+ }
817
+ /**
818
+ * Extract package name from npx command args
819
+ * @param args - Command arguments
820
+ * @returns Package name or null
821
+ * @remarks Handles --package=value, --package value, -p value patterns.
822
+ * Falls back to first non-flag argument if no --package/-p flag found.
823
+ * Returns null if flag has no value or is followed by another flag.
824
+ * When multiple --package flags exist, returns the first valid one.
825
+ * @example
826
+ * extractNpxPackage(['--package=@scope/pkg']) // returns '@scope/pkg'
827
+ * extractNpxPackage(['--package', 'pkg-name']) // returns 'pkg-name'
828
+ * extractNpxPackage(['-p', 'pkg']) // returns 'pkg'
829
+ * extractNpxPackage(['-y', 'pkg-name', '--flag']) // returns 'pkg-name' (fallback)
830
+ * extractNpxPackage(['--package=']) // returns null (empty value)
831
+ */
832
+ extractNpxPackage(args) {
833
+ for (let i = 0; i < args.length; i++) {
834
+ const arg = args[i];
835
+ if (arg.startsWith(FLAG_PACKAGE_LONG + EQUALS_DELIMITER)) return arg.slice(FLAG_PACKAGE_LONG.length + EQUALS_DELIMITER.length) || null;
836
+ if (arg === FLAG_PACKAGE_LONG && i + 1 < args.length) {
837
+ const nextArg = args[i + 1];
838
+ if (!nextArg.startsWith(FLAG_PREFIX)) return nextArg;
839
+ }
840
+ if (arg === FLAG_PACKAGE_SHORT && i + 1 < args.length) {
841
+ const nextArg = args[i + 1];
842
+ if (!nextArg.startsWith(FLAG_PREFIX)) return nextArg;
843
+ }
844
+ }
845
+ for (const arg of args) {
846
+ if (arg.startsWith(FLAG_PREFIX)) continue;
847
+ return arg;
848
+ }
849
+ return null;
850
+ }
851
+ /**
852
+ * Extract package name from uvx command args
853
+ * @param args - Command arguments
854
+ * @returns Package name or null
855
+ * @remarks Assumes the first non-flag argument is the package name.
856
+ * Handles both single (-) and double (--) dash flags.
857
+ * @example
858
+ * extractUvxPackage(['mcp-server-fetch']) // returns 'mcp-server-fetch'
859
+ * extractUvxPackage(['--quiet', 'pkg-name']) // returns 'pkg-name'
860
+ */
861
+ extractUvxPackage(args) {
862
+ for (const arg of args) {
863
+ if (arg.startsWith(FLAG_PREFIX)) continue;
864
+ return arg;
865
+ }
866
+ return null;
867
+ }
868
+ /**
869
+ * Extract package name from uv run command args
870
+ * @param args - Command arguments
871
+ * @returns Package name or null
872
+ * @remarks Looks for the first non-flag argument after the 'run' subcommand.
873
+ * Returns null if 'run' is not found in args.
874
+ * @example
875
+ * extractUvRunPackage(['run', 'mcp-server']) // returns 'mcp-server'
876
+ * extractUvRunPackage(['run', '--verbose', 'pkg']) // returns 'pkg'
877
+ * extractUvRunPackage(['install', 'pkg']) // returns null (no 'run')
878
+ */
879
+ extractUvRunPackage(args) {
880
+ const runIndex = args.indexOf(ARG_RUN);
881
+ if (runIndex === -1) return null;
882
+ for (let i = runIndex + 1; i < args.length; i++) {
883
+ const arg = args[i];
884
+ if (arg.startsWith(FLAG_PREFIX)) continue;
885
+ return arg;
886
+ }
887
+ return null;
888
+ }
889
+ /**
890
+ * Run a shell command and capture output
891
+ * @param command - Command to run
892
+ * @param args - Command arguments
893
+ * @returns Promise with success status and output
894
+ */
895
+ runCommand(command, args) {
896
+ return new Promise((resolve$1) => {
897
+ const proc = spawn(command, args, {
898
+ stdio: [
899
+ STDIO_IGNORE,
900
+ STDIO_PIPE,
901
+ STDIO_PIPE
902
+ ],
903
+ shell: process.platform === PLATFORM_WIN32
904
+ });
905
+ let stdout = "";
906
+ let stderr = "";
907
+ proc.stdout?.on("data", (data) => {
908
+ stdout += data.toString();
909
+ });
910
+ proc.stderr?.on("data", (data) => {
911
+ stderr += data.toString();
912
+ });
913
+ proc.on("close", (code) => {
914
+ resolve$1({
915
+ success: code === EXIT_CODE_SUCCESS,
916
+ output: stdout || stderr
917
+ });
918
+ });
919
+ proc.on("error", (error) => {
920
+ resolve$1({
921
+ success: false,
922
+ output: error.message
923
+ });
924
+ });
925
+ });
926
+ }
927
+ };
928
+
929
+ //#endregion
930
+ //#region src/commands/prefetch.ts
931
+ /**
932
+ * Prefetch Command
933
+ *
934
+ * DESIGN PATTERNS:
935
+ * - Command pattern with Commander for CLI argument parsing
936
+ * - Async/await pattern for asynchronous operations
937
+ * - Error handling pattern with try-catch and proper exit codes
938
+ *
939
+ * CODING STANDARDS:
940
+ * - Use async action handlers for asynchronous operations
941
+ * - Provide clear option descriptions and default values
942
+ * - Handle errors gracefully with process.exit()
943
+ * - Log progress and errors to console
944
+ * - Use Commander's .option() and .argument() for inputs
945
+ *
946
+ * AVOID:
947
+ * - Synchronous blocking operations in action handlers
948
+ * - Missing error handling (always use try-catch)
949
+ * - Hardcoded values (use options or environment variables)
950
+ * - Not exiting with appropriate exit codes on errors
951
+ */
952
+ /**
953
+ * Pre-download packages used by MCP servers (npx, pnpx, uvx, uv)
954
+ */
955
+ const prefetchCommand = new Command("prefetch").description("Pre-download packages used by MCP servers (npx, pnpx, uvx, uv)").option("-c, --config <path>", "Path to MCP server configuration file").option("-p, --parallel", "Run prefetch commands in parallel", false).option("-d, --dry-run", "Show what would be prefetched without executing", false).option("-f, --filter <type>", "Filter by package manager type: npx, pnpx, uvx, or uv").action(async (options) => {
956
+ try {
957
+ const configFilePath = options.config || findConfigFile();
958
+ if (!configFilePath) {
959
+ print.error("No MCP configuration file found.");
960
+ print.info("Use --config <path> to specify a config file, or run \"one-mcp init\" to create one.");
961
+ process.exit(1);
962
+ }
963
+ print.info(`Loading configuration from: ${configFilePath}`);
964
+ const prefetchService = new PrefetchService({
965
+ mcpConfig: await new ConfigFetcherService({
966
+ configFilePath,
967
+ useCache: false
968
+ }).fetchConfiguration(true),
969
+ filter: options.filter,
970
+ parallel: options.parallel
971
+ });
972
+ const packages = prefetchService.extractPackages();
973
+ if (packages.length === 0) {
974
+ print.warning("No packages found to prefetch.");
975
+ print.info("Prefetch supports: npx, pnpx, uvx, and uv run commands");
976
+ return;
977
+ }
978
+ print.info(`Found ${packages.length} package(s) to prefetch:`);
979
+ for (const pkg of packages) print.item(`${pkg.serverName}: ${pkg.packageManager} ${pkg.packageName}`);
980
+ if (options.dryRun) {
981
+ print.newline();
982
+ print.header("Dry run mode - commands that would be executed:");
983
+ for (const pkg of packages) print.indent(pkg.fullCommand.join(" "));
984
+ return;
985
+ }
986
+ print.newline();
987
+ print.info("Prefetching packages...");
988
+ const summary = await prefetchService.prefetch();
989
+ print.newline();
990
+ if (summary.failed === 0) print.success(`Prefetch complete: ${summary.successful} succeeded, ${summary.failed} failed`);
991
+ else print.warning(`Prefetch complete: ${summary.successful} succeeded, ${summary.failed} failed`);
992
+ if (summary.failed > 0) {
993
+ print.newline();
994
+ print.error("Failed packages:");
995
+ for (const result of summary.results.filter((r) => !r.success)) print.item(`${result.package.serverName} (${result.package.packageName}): ${result.output.trim()}`);
996
+ process.exit(1);
997
+ }
998
+ } catch (error) {
999
+ print.error("Error executing prefetch:", error instanceof Error ? error.message : String(error));
1000
+ process.exit(1);
1001
+ }
1002
+ });
1003
+
549
1004
  //#endregion
550
1005
  //#region package.json
551
- var version = "0.2.6";
1006
+ var version = "0.3.0";
552
1007
 
553
1008
  //#endregion
554
1009
  //#region src/cli.ts
@@ -574,16 +1029,25 @@ var version = "0.2.6";
574
1029
  * Main entry point
575
1030
  */
576
1031
  async function main() {
577
- const program = new Command();
578
- program.name("one-mcp").description("One MCP server package").version(version);
579
- program.addCommand(initCommand);
580
- program.addCommand(mcpServeCommand);
581
- program.addCommand(listToolsCommand);
582
- program.addCommand(describeToolsCommand);
583
- program.addCommand(useToolCommand);
584
- await program.parseAsync(process.argv);
1032
+ try {
1033
+ const program = new Command();
1034
+ program.name("one-mcp").description("One MCP server package").version(version);
1035
+ program.addCommand(initCommand);
1036
+ program.addCommand(mcpServeCommand);
1037
+ program.addCommand(listToolsCommand);
1038
+ program.addCommand(describeToolsCommand);
1039
+ program.addCommand(useToolCommand);
1040
+ program.addCommand(prefetchCommand);
1041
+ await program.parseAsync(process.argv);
1042
+ } catch (error) {
1043
+ console.error(`CLI execution failed: ${error instanceof Error ? error.message : error}`);
1044
+ process.exit(1);
1045
+ }
585
1046
  }
586
- main();
1047
+ main().catch((error) => {
1048
+ console.error(`Fatal error: ${error instanceof Error ? error.message : error}`);
1049
+ process.exit(1);
1050
+ });
587
1051
 
588
1052
  //#endregion
589
1053
  export { };