@sherpa-labs/aimcp-lint 0.0.0 → 0.0.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/LICENSE CHANGED
@@ -19,3 +19,18 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
19
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
20
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
21
  SOFTWARE.
22
+
23
+ ---
24
+
25
+ Note: license boundaries inside this repository
26
+
27
+ This repo is a monorepo with mixed licensing. The MIT license above applies to
28
+ the repository root (build configuration, docs, tooling) and to anything not
29
+ otherwise marked.
30
+
31
+ - packages/* — MIT (each package directory contains its own LICENSE file)
32
+ - apps/api, apps/web — proprietary, all rights reserved
33
+ (each app directory contains its own LICENSE file describing the terms)
34
+
35
+ When a file or directory has its own LICENSE, that license takes precedence
36
+ over this one.
package/dist/cli.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAY5C,wBAAgB,SAAS,IAAI,OAAO,CAiBnC;AAED,wBAAsB,MAAM,CAAC,IAAI,GAAE,SAAS,MAAM,EAAiB,GAAG,OAAO,CAAC,IAAI,CAAC,CAIlF"}
1
+ {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAsB5C,wBAAgB,SAAS,IAAI,OAAO,CA0CnC;AAED,wBAAsB,MAAM,CAAC,IAAI,GAAE,SAAS,MAAM,EAAiB,GAAG,OAAO,CAAC,IAAI,CAAC,CASlF"}
@@ -0,0 +1,3 @@
1
+ import type { WritableStreamLike } from './output.js';
2
+ export declare function shouldEnableColor(stream: WritableStreamLike): boolean;
3
+ //# sourceMappingURL=color.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"color.d.ts","sourceRoot":"","sources":["../src/color.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAKtD,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,kBAAkB,GAAG,OAAO,CAUrE"}
@@ -0,0 +1,11 @@
1
+ import { Command } from 'commander/esm.mjs';
2
+ import { type ExitCode } from '../exit-codes.js';
3
+ import type { WritableStreamLike } from '../output.js';
4
+ export interface InitCommandInput {
5
+ readonly force?: boolean;
6
+ readonly cwd?: string;
7
+ readonly stdout?: WritableStreamLike;
8
+ }
9
+ export declare function createInitCommand(): Command;
10
+ export declare function runInitCommand(input?: InitCommandInput): Promise<ExitCode>;
11
+ //# sourceMappingURL=init.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../../src/commands/init.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAI5C,OAAO,EAAgB,KAAK,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC/D,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAEvD,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC;IACzB,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,MAAM,CAAC,EAAE,kBAAkB,CAAC;CACtC;AAED,wBAAgB,iBAAiB,IAAI,OAAO,CAO3C;AAED,wBAAsB,cAAc,CAAC,KAAK,GAAE,gBAAqB,GAAG,OAAO,CAAC,QAAQ,CAAC,CAoBpF"}
@@ -0,0 +1,16 @@
1
+ import type { Command } from 'commander/esm.mjs';
2
+ import { type CommonFlagInput } from '../config.js';
3
+ import { type ExitCode } from '../exit-codes.js';
4
+ import { type WritableStreamLike } from '../output.js';
5
+ export interface LintCommandInput {
6
+ readonly serverCommandTokens: readonly string[] | undefined;
7
+ readonly options: CommonFlagInput;
8
+ readonly commandTokens?: readonly string[];
9
+ readonly cwd?: string;
10
+ readonly stdout?: WritableStreamLike;
11
+ readonly stderr?: WritableStreamLike;
12
+ }
13
+ export declare function addFormatOption(command: Command): Command;
14
+ export declare function addCommonLintOptions(command: Command): Command;
15
+ export declare function runLintCommand(input: LintCommandInput): Promise<ExitCode>;
16
+ //# sourceMappingURL=lint.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lint.d.ts","sourceRoot":"","sources":["../../src/commands/lint.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAKjD,OAAO,EAAE,KAAK,eAAe,EAAiB,MAAM,cAAc,CAAC;AAEnE,OAAO,EAAkC,KAAK,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAEjF,OAAO,EAAoB,KAAK,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAMzE,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,CAAC,mBAAmB,EAAE,SAAS,MAAM,EAAE,GAAG,SAAS,CAAC;IAC5D,QAAQ,CAAC,OAAO,EAAE,eAAe,CAAC;IAClC,QAAQ,CAAC,aAAa,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC3C,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,MAAM,CAAC,EAAE,kBAAkB,CAAC;IACrC,QAAQ,CAAC,MAAM,CAAC,EAAE,kBAAkB,CAAC;CACtC;AAED,wBAAgB,eAAe,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAMzD;AAED,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAW9D;AAED,wBAAsB,cAAc,CAAC,KAAK,EAAE,gBAAgB,GAAG,OAAO,CAAC,QAAQ,CAAC,CA8F/E"}
@@ -0,0 +1,12 @@
1
+ import { Command } from 'commander/esm.mjs';
2
+ import { type OutputFormat } from '../config.js';
3
+ import { type ExitCode } from '../exit-codes.js';
4
+ import { type WritableStreamLike } from '../output.js';
5
+ export interface RulesCommandInput {
6
+ readonly format?: OutputFormat;
7
+ readonly quiet?: boolean;
8
+ readonly stdout?: WritableStreamLike;
9
+ }
10
+ export declare function createRulesCommand(): Command;
11
+ export declare function runRulesCommand(input?: RulesCommandInput): ExitCode;
12
+ //# sourceMappingURL=rules.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rules.d.ts","sourceRoot":"","sources":["../../src/commands/rules.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAG5C,OAAO,EAAE,KAAK,YAAY,EAAE,MAAM,cAAc,CAAC;AACjD,OAAO,EAAgB,KAAK,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC/D,OAAO,EAAqB,KAAK,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAG1E,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,MAAM,CAAC,EAAE,YAAY,CAAC;IAC/B,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC;IACzB,QAAQ,CAAC,MAAM,CAAC,EAAE,kBAAkB,CAAC;CACtC;AAED,wBAAgB,kBAAkB,IAAI,OAAO,CAY5C;AAED,wBAAgB,eAAe,CAAC,KAAK,GAAE,iBAAsB,GAAG,QAAQ,CAYvE"}
@@ -0,0 +1,36 @@
1
+ import { Command } from 'commander/esm.mjs';
2
+ import { type CommonFlagInput } from '../config.js';
3
+ import { type ExitCode } from '../exit-codes.js';
4
+ import type { WritableStreamLike } from '../output.js';
5
+ export interface WatchCommandInput {
6
+ readonly serverCommandTokens: readonly string[] | undefined;
7
+ readonly options: CommonFlagInput;
8
+ readonly cwd?: string;
9
+ readonly stdout?: WritableStreamLike;
10
+ readonly stderr?: WritableStreamLike;
11
+ readonly signal?: AbortSignal;
12
+ readonly createWatcher?: WatcherFactory;
13
+ }
14
+ export interface Watcher {
15
+ close(): void;
16
+ }
17
+ export type WatcherFactory = (path: string, onChange: () => void) => Watcher;
18
+ export interface WatchLoopInput {
19
+ readonly watchPaths: readonly string[];
20
+ readonly runOnce: () => Promise<ExitCode>;
21
+ readonly signal?: AbortSignal;
22
+ readonly debounceMs?: number;
23
+ readonly createWatcher?: WatcherFactory;
24
+ readonly onWatching?: (paths: readonly string[]) => void;
25
+ readonly onChange?: (path: string) => void;
26
+ }
27
+ export declare function createWatchCommand(): Command;
28
+ export declare function runWatchCommand(input: WatchCommandInput): Promise<ExitCode>;
29
+ export declare function runWatchLoop(input: WatchLoopInput): Promise<void>;
30
+ export declare function resolveWatchPaths(input: {
31
+ readonly cwd: string;
32
+ readonly configPath: string;
33
+ readonly configExists: boolean;
34
+ readonly configuredPaths: readonly string[];
35
+ }): readonly string[];
36
+ //# sourceMappingURL=watch.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"watch.d.ts","sourceRoot":"","sources":["../../src/commands/watch.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAE5C,OAAO,EAAE,KAAK,eAAe,EAAoB,MAAM,cAAc,CAAC;AAEtE,OAAO,EAAgB,KAAK,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC/D,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAIvD,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,mBAAmB,EAAE,SAAS,MAAM,EAAE,GAAG,SAAS,CAAC;IAC5D,QAAQ,CAAC,OAAO,EAAE,eAAe,CAAC;IAClC,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,MAAM,CAAC,EAAE,kBAAkB,CAAC;IACrC,QAAQ,CAAC,MAAM,CAAC,EAAE,kBAAkB,CAAC;IACrC,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAC;IAC9B,QAAQ,CAAC,aAAa,CAAC,EAAE,cAAc,CAAC;CACzC;AAED,MAAM,WAAW,OAAO;IACtB,KAAK,IAAI,IAAI,CAAC;CACf;AAED,MAAM,MAAM,cAAc,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,IAAI,KAAK,OAAO,CAAC;AAE7E,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,UAAU,EAAE,SAAS,MAAM,EAAE,CAAC;IACvC,QAAQ,CAAC,OAAO,EAAE,MAAM,OAAO,CAAC,QAAQ,CAAC,CAAC;IAC1C,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAC;IAC9B,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,aAAa,CAAC,EAAE,cAAc,CAAC;IACxC,QAAQ,CAAC,UAAU,CAAC,EAAE,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,KAAK,IAAI,CAAC;IACzD,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;CAC5C;AAED,wBAAgB,kBAAkB,IAAI,OAAO,CAa5C;AAED,wBAAsB,eAAe,CAAC,KAAK,EAAE,iBAAiB,GAAG,OAAO,CAAC,QAAQ,CAAC,CAuCjF;AAED,wBAAsB,YAAY,CAAC,KAAK,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,CAsDvE;AAED,wBAAgB,iBAAiB,CAAC,KAAK,EAAE;IACvC,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,YAAY,EAAE,OAAO,CAAC;IAC/B,QAAQ,CAAC,eAAe,EAAE,SAAS,MAAM,EAAE,CAAC;CAC7C,GAAG,SAAS,MAAM,EAAE,CAQpB"}
@@ -0,0 +1,82 @@
1
+ import type { LintConfig, LintRuleOverride, LintRuleSeverity } from '@sherpa-labs/core-mcp';
2
+ export declare const CONFIG_FILE_NAME = ".aimcp-lint.json";
3
+ export declare const outputFormats: readonly ["terminal", "json", "markdown"];
4
+ export type OutputFormat = (typeof outputFormats)[number];
5
+ export interface CommonFlagInput {
6
+ readonly format?: OutputFormat;
7
+ readonly failUnder?: number;
8
+ readonly ignore?: readonly string[];
9
+ readonly only?: readonly string[];
10
+ readonly config?: string;
11
+ readonly verbose?: boolean;
12
+ readonly quiet?: boolean;
13
+ readonly detailed?: boolean;
14
+ }
15
+ export interface AimcpLintConfigFile {
16
+ readonly command?: string | readonly string[];
17
+ readonly format?: OutputFormat;
18
+ readonly failUnder?: number;
19
+ readonly ignore?: readonly string[];
20
+ readonly only?: readonly string[];
21
+ readonly ignoredRules?: readonly string[];
22
+ readonly includedRules?: readonly string[];
23
+ readonly severityOverrides?: Readonly<Record<string, LintRuleSeverity>>;
24
+ readonly ruleOverrides?: Readonly<Record<string, LintRuleOverride>>;
25
+ readonly thresholds?: Readonly<Record<string, number>>;
26
+ readonly severityWeights?: Readonly<Partial<Record<LintRuleSeverity, number>>>;
27
+ readonly watch?: readonly string[] | AimcpLintWatchConfig;
28
+ readonly detailed?: boolean;
29
+ readonly quiet?: boolean;
30
+ readonly verbose?: boolean;
31
+ }
32
+ export interface AimcpLintWatchConfig {
33
+ readonly paths?: readonly string[];
34
+ }
35
+ export interface LoadedCliConfig {
36
+ readonly config: AimcpLintConfigFile;
37
+ readonly sourcePath: string;
38
+ readonly exists: boolean;
39
+ }
40
+ export interface ResolvedCliConfig {
41
+ readonly format: OutputFormat;
42
+ readonly failUnder?: number;
43
+ readonly ignoredRules: readonly string[];
44
+ readonly includedRules: readonly string[];
45
+ readonly watchPaths: readonly string[];
46
+ readonly configPath: string;
47
+ readonly configExists: boolean;
48
+ readonly verbose: boolean;
49
+ readonly quiet: boolean;
50
+ readonly detailed: boolean;
51
+ readonly lintConfig: LintConfig;
52
+ readonly commandTokens?: readonly string[];
53
+ }
54
+ export declare const DEFAULT_INIT_CONFIG: {
55
+ readonly command: "node ./server.mjs";
56
+ readonly format: "terminal";
57
+ readonly failUnder: 80;
58
+ readonly ignore: readonly [];
59
+ readonly only: readonly [];
60
+ readonly severityOverrides: {};
61
+ readonly ruleOverrides: {};
62
+ readonly thresholds: {};
63
+ readonly severityWeights: {};
64
+ readonly watch: {
65
+ readonly paths: readonly ["."];
66
+ };
67
+ readonly detailed: false;
68
+ readonly quiet: false;
69
+ readonly verbose: false;
70
+ };
71
+ export declare function isOutputFormat(value: string): value is OutputFormat;
72
+ export declare function createInitialConfigContent(): string;
73
+ export declare function resolveCliConfig(input: {
74
+ readonly cwd: string;
75
+ readonly options: CommonFlagInput;
76
+ }): Promise<ResolvedCliConfig>;
77
+ export declare function loadCliConfig(input: {
78
+ readonly cwd: string;
79
+ readonly configPath?: string;
80
+ }): Promise<LoadedCliConfig>;
81
+ export declare function resolveConfigPath(cwd: string, configPath: string | undefined): string;
82
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAI5F,eAAO,MAAM,gBAAgB,qBAAqB,CAAC;AACnD,eAAO,MAAM,aAAa,2CAA4C,CAAC;AAEvE,MAAM,MAAM,YAAY,GAAG,CAAC,OAAO,aAAa,CAAC,CAAC,MAAM,CAAC,CAAC;AAE1D,MAAM,WAAW,eAAe;IAC9B,QAAQ,CAAC,MAAM,CAAC,EAAE,YAAY,CAAC;IAC/B,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,MAAM,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACpC,QAAQ,CAAC,IAAI,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAClC,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC;IAC3B,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC;IACzB,QAAQ,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC;CAC7B;AAED,MAAM,WAAW,mBAAmB;IAClC,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,MAAM,EAAE,CAAC;IAC9C,QAAQ,CAAC,MAAM,CAAC,EAAE,YAAY,CAAC;IAC/B,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,MAAM,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACpC,QAAQ,CAAC,IAAI,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAClC,QAAQ,CAAC,YAAY,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1C,QAAQ,CAAC,aAAa,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC3C,QAAQ,CAAC,iBAAiB,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC,CAAC;IACxE,QAAQ,CAAC,aAAa,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC,CAAC;IACpE,QAAQ,CAAC,UAAU,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IACvD,QAAQ,CAAC,eAAe,CAAC,EAAE,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,gBAAgB,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC;IAC/E,QAAQ,CAAC,KAAK,CAAC,EAAE,SAAS,MAAM,EAAE,GAAG,oBAAoB,CAAC;IAC1D,QAAQ,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC;IAC5B,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC;IACzB,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC;CAC5B;AAED,MAAM,WAAW,oBAAoB;IACnC,QAAQ,CAAC,KAAK,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CACpC;AAED,MAAM,WAAW,eAAe;IAC9B,QAAQ,CAAC,MAAM,EAAE,mBAAmB,CAAC;IACrC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;CAC1B;AAED,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,MAAM,EAAE,YAAY,CAAC;IAC9B,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,YAAY,EAAE,SAAS,MAAM,EAAE,CAAC;IACzC,QAAQ,CAAC,aAAa,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1C,QAAQ,CAAC,UAAU,EAAE,SAAS,MAAM,EAAE,CAAC;IACvC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,YAAY,EAAE,OAAO,CAAC;IAC/B,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC;IACxB,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;IAC3B,QAAQ,CAAC,UAAU,EAAE,UAAU,CAAC;IAChC,QAAQ,CAAC,aAAa,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CAC5C;AAED,eAAO,MAAM,mBAAmB;;;;;;;;;;;;;;;;CAgBQ,CAAC;AAEzC,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,KAAK,IAAI,YAAY,CAEnE;AAED,wBAAgB,0BAA0B,IAAI,MAAM,CAEnD;AAED,wBAAsB,gBAAgB,CAAC,KAAK,EAAE;IAC5C,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,OAAO,EAAE,eAAe,CAAC;CACnC,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAuD7B;AAED,wBAAsB,aAAa,CAAC,KAAK,EAAE;IACzC,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;CAC9B,GAAG,OAAO,CAAC,eAAe,CAAC,CAwD3B;AAED,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAMrF"}
@@ -0,0 +1,12 @@
1
+ import { type ExitCode } from './exit-codes.js';
2
+ export declare class CliError extends Error {
3
+ readonly exitCode: ExitCode;
4
+ constructor(message: string, exitCode?: ExitCode);
5
+ }
6
+ export declare function usageError(message: string): CliError;
7
+ export declare function configError(message: string): CliError;
8
+ export declare function runtimeError(message: string): CliError;
9
+ export declare function serverError(message: string): CliError;
10
+ export declare function describeError(error: unknown): string;
11
+ export declare function errorExitCode(error: unknown): ExitCode;
12
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAEA,OAAO,EAAwC,KAAK,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAEtF,qBAAa,QAAS,SAAQ,KAAK;IACjC,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC;gBAEhB,OAAO,EAAE,MAAM,EAAE,QAAQ,GAAE,QAA4B;CAKpE;AAED,wBAAgB,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,QAAQ,CAEpD;AAED,wBAAgB,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,QAAQ,CAErD;AAED,wBAAgB,YAAY,CAAC,OAAO,EAAE,MAAM,GAAG,QAAQ,CAEtD;AAED,wBAAgB,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,QAAQ,CAErD;AAED,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAMpD;AAED,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,QAAQ,CAUtD"}
@@ -0,0 +1,6 @@
1
+ export declare const EXIT_SUCCESS = 0;
2
+ export declare const EXIT_LINT_FAILED = 1;
3
+ export declare const EXIT_CONFIG_ERROR = 2;
4
+ export declare const EXIT_SERVER_ERROR = 3;
5
+ export type ExitCode = typeof EXIT_SUCCESS | typeof EXIT_LINT_FAILED | typeof EXIT_CONFIG_ERROR | typeof EXIT_SERVER_ERROR;
6
+ //# sourceMappingURL=exit-codes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"exit-codes.d.ts","sourceRoot":"","sources":["../src/exit-codes.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,YAAY,IAAI,CAAC;AAC9B,eAAO,MAAM,gBAAgB,IAAI,CAAC;AAClC,eAAO,MAAM,iBAAiB,IAAI,CAAC;AACnC,eAAO,MAAM,iBAAiB,IAAI,CAAC;AAEnC,MAAM,MAAM,QAAQ,GAChB,OAAO,YAAY,GACnB,OAAO,gBAAgB,GACvB,OAAO,iBAAiB,GACxB,OAAO,iBAAiB,CAAC"}
@@ -0,0 +1,72 @@
1
+ import { type LintResult } from '@sherpa-labs/core-mcp';
2
+ export interface JsonFormatterOptions {
3
+ readonly pretty?: boolean;
4
+ readonly quiet?: boolean;
5
+ }
6
+ export declare function formatJsonReport(result: LintResult, options?: JsonFormatterOptions): string;
7
+ export interface JsonReport {
8
+ readonly schema_version: string;
9
+ readonly score: number;
10
+ readonly max_score: number;
11
+ readonly passed: boolean;
12
+ readonly violations: readonly JsonViolation[];
13
+ readonly summary: JsonSummary;
14
+ readonly category_subscores: Record<string, JsonCategorySubscore>;
15
+ readonly failing_rules: readonly JsonFailingRule[];
16
+ readonly server_info: JsonServerInfo;
17
+ readonly metadata: JsonMetadata;
18
+ }
19
+ export interface JsonViolation {
20
+ readonly rule_id: string;
21
+ readonly category: string;
22
+ readonly severity: string;
23
+ readonly message: string;
24
+ readonly fix_hint: string;
25
+ readonly location?: string;
26
+ readonly evidence?: string;
27
+ }
28
+ export interface JsonSummary {
29
+ readonly error_count: number;
30
+ readonly warning_count: number;
31
+ readonly info_count: number;
32
+ readonly violation_count: number;
33
+ }
34
+ export interface JsonCategorySubscore {
35
+ readonly category: string;
36
+ readonly label: string;
37
+ readonly score: number;
38
+ readonly max_score: number;
39
+ readonly baseline: number;
40
+ readonly deduction: number;
41
+ readonly violation_count: number;
42
+ readonly error_count: number;
43
+ readonly warning_count: number;
44
+ readonly info_count: number;
45
+ readonly failing_rule_ids: readonly string[];
46
+ }
47
+ export interface JsonFailingRule {
48
+ readonly rule_id: string;
49
+ readonly category: string;
50
+ readonly category_label: string;
51
+ readonly worst_severity: string;
52
+ readonly count: number;
53
+ readonly message: string;
54
+ readonly fix_hint: string;
55
+ readonly violation_ids: readonly string[];
56
+ }
57
+ export interface JsonServerInfo {
58
+ readonly transport: string;
59
+ readonly protocol_version?: string;
60
+ readonly name?: string;
61
+ readonly version?: string;
62
+ readonly capabilities: readonly string[];
63
+ readonly tool_count: number;
64
+ readonly resource_count: number;
65
+ readonly prompt_count: number;
66
+ }
67
+ export interface JsonMetadata {
68
+ readonly schema_version: string;
69
+ readonly linted_at: string;
70
+ readonly rules_run: readonly string[];
71
+ }
72
+ //# sourceMappingURL=json.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"json.d.ts","sourceRoot":"","sources":["../../src/formatters/json.ts"],"names":[],"mappings":"AAAA,OAAO,EAA4B,KAAK,UAAU,EAAE,MAAM,uBAAuB,CAAC;AAElF,MAAM,WAAW,oBAAoB;IACnC,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC;IAC1B,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC;CAC1B;AAED,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,UAAU,EAAE,OAAO,GAAE,oBAAyB,GAAG,MAAM,CAgB/F;AAED,MAAM,WAAW,UAAU;IACzB,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;IACzB,QAAQ,CAAC,UAAU,EAAE,SAAS,aAAa,EAAE,CAAC;IAC9C,QAAQ,CAAC,OAAO,EAAE,WAAW,CAAC;IAC9B,QAAQ,CAAC,kBAAkB,EAAE,MAAM,CAAC,MAAM,EAAE,oBAAoB,CAAC,CAAC;IAClE,QAAQ,CAAC,aAAa,EAAE,SAAS,eAAe,EAAE,CAAC;IACnD,QAAQ,CAAC,WAAW,EAAE,cAAc,CAAC;IACrC,QAAQ,CAAC,QAAQ,EAAE,YAAY,CAAC;CACjC;AAED,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAC;CAClC;AAED,MAAM,WAAW,oBAAoB;IACnC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAC;IACjC,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,gBAAgB,EAAE,SAAS,MAAM,EAAE,CAAC;CAC9C;AAED,MAAM,WAAW,eAAe;IAC9B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,aAAa,EAAE,SAAS,MAAM,EAAE,CAAC;CAC3C;AAED,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IACnC,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,YAAY,EAAE,SAAS,MAAM,EAAE,CAAC;IACzC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;CAC/B;AAED,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,SAAS,EAAE,SAAS,MAAM,EAAE,CAAC;CACvC"}
@@ -0,0 +1,6 @@
1
+ import { type LintResult } from '@sherpa-labs/core-mcp';
2
+ export interface MarkdownFormatterOptions {
3
+ readonly quiet?: boolean;
4
+ }
5
+ export declare function formatMarkdownReport(result: LintResult, options?: MarkdownFormatterOptions): string;
6
+ //# sourceMappingURL=markdown.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"markdown.d.ts","sourceRoot":"","sources":["../../src/formatters/markdown.ts"],"names":[],"mappings":"AAAA,OAAO,EAKL,KAAK,UAAU,EAEhB,MAAM,uBAAuB,CAAC;AAE/B,MAAM,WAAW,wBAAwB;IACvC,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC;CAC1B;AAED,wBAAgB,oBAAoB,CAClC,MAAM,EAAE,UAAU,EAClB,OAAO,GAAE,wBAA6B,GACrC,MAAM,CAmBR"}
@@ -0,0 +1,2 @@
1
+ export declare const VIOLATION_COLLAPSE_THRESHOLD = 10;
2
+ //# sourceMappingURL=shared.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shared.d.ts","sourceRoot":"","sources":["../../src/formatters/shared.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,4BAA4B,KAAK,CAAC"}
@@ -0,0 +1,7 @@
1
+ import { type LintResult } from '@sherpa-labs/core-mcp';
2
+ export interface TerminalFormatterOptions {
3
+ readonly colors: boolean;
4
+ readonly detailed: boolean;
5
+ }
6
+ export declare function formatTerminalReport(result: LintResult, options: TerminalFormatterOptions): string;
7
+ //# sourceMappingURL=terminal.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"terminal.d.ts","sourceRoot":"","sources":["../../src/formatters/terminal.ts"],"names":[],"mappings":"AAAA,OAAO,EAKL,KAAK,UAAU,EAGhB,MAAM,uBAAuB,CAAC;AAI/B,MAAM,WAAW,wBAAwB;IACvC,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;IACzB,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;CAC5B;AAED,wBAAgB,oBAAoB,CAClC,MAAM,EAAE,UAAU,EAClB,OAAO,EAAE,wBAAwB,GAChC,MAAM,CAaR"}
package/dist/index.js ADDED
@@ -0,0 +1,52 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __aimcpCreateRequire } from 'node:module';
3
+ const require = __aimcpCreateRequire(import.meta.url);
4
+ var wi=Object.create;var gr=Object.defineProperty;var xi=Object.getOwnPropertyDescriptor;var Oi=Object.getOwnPropertyNames;var Ei=Object.getPrototypeOf,vi=Object.prototype.hasOwnProperty;var ie=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var M=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var $i=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Oi(e))!vi.call(t,i)&&i!==r&&gr(t,i,{get:()=>e[i],enumerable:!(n=xi(e,i))||n.enumerable});return t};var yr=(t,e,r)=>(r=t!=null?wi(Ei(t)):{},$i(e||!t||!t.__esModule?gr(r,"default",{value:t,enumerable:!0}):r,t));var oe=M(Ge=>{"use strict";var ge=class extends Error{constructor(e,r,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=r,this.exitCode=e,this.nestedError=void 0}},Be=class extends ge{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Ge.CommanderError=ge;Ge.InvalidArgumentError=Be});var ye=M(Xe=>{"use strict";var{InvalidArgumentError:Ti}=oe(),Ye=class{constructor(e,r){switch(this.description=r||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,r){return r===this.defaultValue||!Array.isArray(r)?[e]:r.concat(e)}default(e,r){return this.defaultValue=e,this.defaultValueDescription=r,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(r,n)=>{if(!this.argChoices.includes(r))throw new Ti(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(r,n):r},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Li(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}Xe.Argument=Ye;Xe.humanReadableArgName=Li});var Qe=M(Ze=>{"use strict";var{humanReadableArgName:Ii}=ye(),Ke=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let r=e.commands.filter(i=>!i._hidden),n=e._getHelpCommand();return n&&!n._hidden&&r.push(n),this.sortSubcommands&&r.sort((i,o)=>i.name().localeCompare(o.name())),r}compareOptions(e,r){let n=i=>i.short?i.short.replace(/^-/,""):i.long.replace(/^--/,"");return n(e).localeCompare(n(r))}visibleOptions(e){let r=e.options.filter(i=>!i.hidden),n=e._getHelpOption();if(n&&!n.hidden){let i=n.short&&e._findOption(n.short),o=n.long&&e._findOption(n.long);!i&&!o?r.push(n):n.long&&!o?r.push(e.createOption(n.long,n.description)):n.short&&!i&&r.push(e.createOption(n.short,n.description))}return this.sortOptions&&r.sort(this.compareOptions),r}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let r=[];for(let n=e.parent;n;n=n.parent){let i=n.options.filter(o=>!o.hidden);r.push(...i)}return this.sortOptions&&r.sort(this.compareOptions),r}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(r=>{r.description=r.description||e._argsDescription[r.name()]||""}),e.registeredArguments.find(r=>r.description)?e.registeredArguments:[]}subcommandTerm(e){let r=e.registeredArguments.map(n=>Ii(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(r?" "+r:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,r){return r.visibleCommands(e).reduce((n,i)=>Math.max(n,this.displayWidth(r.styleSubcommandTerm(r.subcommandTerm(i)))),0)}longestOptionTermLength(e,r){return r.visibleOptions(e).reduce((n,i)=>Math.max(n,this.displayWidth(r.styleOptionTerm(r.optionTerm(i)))),0)}longestGlobalOptionTermLength(e,r){return r.visibleGlobalOptions(e).reduce((n,i)=>Math.max(n,this.displayWidth(r.styleOptionTerm(r.optionTerm(i)))),0)}longestArgumentTermLength(e,r){return r.visibleArguments(e).reduce((n,i)=>Math.max(n,this.displayWidth(r.styleArgumentTerm(r.argumentTerm(i)))),0)}commandUsage(e){let r=e._name;e._aliases[0]&&(r=r+"|"+e._aliases[0]);let n="";for(let i=e.parent;i;i=i.parent)n=i.name()+" "+n;return n+r+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let r=[];return e.argChoices&&r.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&r.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&r.push(`env: ${e.envVar}`),r.length>0?`${e.description} (${r.join(", ")})`:e.description}argumentDescription(e){let r=[];if(e.argChoices&&r.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),r.length>0){let n=`(${r.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,r){let n=r.padWidth(e,r),i=r.helpWidth??80;function o(l,p){return r.formatItem(l,n,p,r)}let s=[`${r.styleTitle("Usage:")} ${r.styleUsage(r.commandUsage(e))}`,""],a=r.commandDescription(e);a.length>0&&(s=s.concat([r.boxWrap(r.styleCommandDescription(a),i),""]));let u=r.visibleArguments(e).map(l=>o(r.styleArgumentTerm(r.argumentTerm(l)),r.styleArgumentDescription(r.argumentDescription(l))));u.length>0&&(s=s.concat([r.styleTitle("Arguments:"),...u,""]));let c=r.visibleOptions(e).map(l=>o(r.styleOptionTerm(r.optionTerm(l)),r.styleOptionDescription(r.optionDescription(l))));if(c.length>0&&(s=s.concat([r.styleTitle("Options:"),...c,""])),r.showGlobalOptions){let l=r.visibleGlobalOptions(e).map(p=>o(r.styleOptionTerm(r.optionTerm(p)),r.styleOptionDescription(r.optionDescription(p))));l.length>0&&(s=s.concat([r.styleTitle("Global Options:"),...l,""]))}let d=r.visibleCommands(e).map(l=>o(r.styleSubcommandTerm(r.subcommandTerm(l)),r.styleSubcommandDescription(r.subcommandDescription(l))));return d.length>0&&(s=s.concat([r.styleTitle("Commands:"),...d,""])),s.join(`
5
+ `)}displayWidth(e){return br(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map(r=>r==="[options]"?this.styleOptionText(r):r==="[command]"?this.styleSubcommandText(r):r[0]==="["||r[0]==="<"?this.styleArgumentText(r):this.styleCommandText(r)).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map(r=>r==="[options]"?this.styleOptionText(r):r[0]==="["||r[0]==="<"?this.styleArgumentText(r):this.styleSubcommandText(r)).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,r){return Math.max(r.longestOptionTermLength(e,r),r.longestGlobalOptionTermLength(e,r),r.longestSubcommandTermLength(e,r),r.longestArgumentTermLength(e,r))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,r,n,i){let s=" ".repeat(2);if(!n)return s+e;let a=e.padEnd(r+e.length-i.displayWidth(e)),u=2,d=(this.helpWidth??80)-r-u-2,l;return d<this.minWidthToWrap||i.preformatted(n)?l=n:l=i.boxWrap(n,d).replace(/\n/g,`
6
+ `+" ".repeat(r+u)),s+a+" ".repeat(u)+l.replace(/\n/g,`
7
+ ${s}`)}boxWrap(e,r){if(r<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),i=/[\s]*[^\s]+/g,o=[];return n.forEach(s=>{let a=s.match(i);if(a===null){o.push("");return}let u=[a.shift()],c=this.displayWidth(u[0]);a.forEach(d=>{let l=this.displayWidth(d);if(c+l<=r){u.push(d),c+=l;return}o.push(u.join(""));let p=d.trimStart();u=[p],c=this.displayWidth(p)}),o.push(u.join(""))}),o.join(`
8
+ `)}};function br(t){let e=/\x1b\[\d*(;\d*)*m/g;return t.replace(e,"")}Ze.Help=Ke;Ze.stripColor=br});var nt=M(rt=>{"use strict";var{InvalidArgumentError:Ai}=oe(),et=class{constructor(e,r){this.flags=e,this.description=r||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=Pi(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,r){return this.defaultValue=e,this.defaultValueDescription=r,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let r=e;return typeof e=="string"&&(r={[e]:!0}),this.implied=Object.assign(this.implied||{},r),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,r){return r===this.defaultValue||!Array.isArray(r)?[e]:r.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(r,n)=>{if(!this.argChoices.includes(r))throw new Ai(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(r,n):r},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?Cr(this.name().replace(/^no-/,"")):Cr(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},tt=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(r=>{r.negate?this.negativeOptions.set(r.attributeName(),r):this.positiveOptions.set(r.attributeName(),r)}),this.negativeOptions.forEach((r,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,r){let n=r.attributeName();if(!this.dualOptions.has(n))return!0;let i=this.negativeOptions.get(n).presetArg,o=i!==void 0?i:!1;return r.negate===(o===e)}};function Cr(t){return t.split("-").reduce((e,r)=>e+r[0].toUpperCase()+r.slice(1))}function Pi(t){let e,r,n=/^-[^-]$/,i=/^--[^-]/,o=t.split(/[ |,]+/).concat("guard");if(n.test(o[0])&&(e=o.shift()),i.test(o[0])&&(r=o.shift()),!e&&n.test(o[0])&&(e=o.shift()),!e&&i.test(o[0])&&(e=r,r=o.shift()),o[0].startsWith("-")){let s=o[0],a=`option creation failed due to '${s}' in option flags '${t}'`;throw/^-[^-][^-]/.test(s)?new Error(`${a}
9
+ - a short flag is a single dash and a single character
10
+ - either use a single dash and a single character (for a short flag)
11
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):n.test(s)?new Error(`${a}
12
+ - too many short flags`):i.test(s)?new Error(`${a}
13
+ - too many long flags`):new Error(`${a}
14
+ - unrecognised flag format`)}if(e===void 0&&r===void 0)throw new Error(`option creation failed due to no flags found in '${t}'.`);return{shortFlag:e,longFlag:r}}rt.Option=et;rt.DualOptions=tt});var Sr=M(_r=>{"use strict";function Mi(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);let r=[];for(let n=0;n<=t.length;n++)r[n]=[n];for(let n=0;n<=e.length;n++)r[0][n]=n;for(let n=1;n<=e.length;n++)for(let i=1;i<=t.length;i++){let o=1;t[i-1]===e[n-1]?o=0:o=1,r[i][n]=Math.min(r[i-1][n]+1,r[i][n-1]+1,r[i-1][n-1]+o),i>1&&n>1&&t[i-1]===e[n-2]&&t[i-2]===e[n-1]&&(r[i][n]=Math.min(r[i][n],r[i-2][n-2]+1))}return r[t.length][e.length]}function Ni(t,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let r=t.startsWith("--");r&&(t=t.slice(2),e=e.map(s=>s.slice(2)));let n=[],i=3,o=.4;return e.forEach(s=>{if(s.length<=1)return;let a=Mi(t,s),u=Math.max(t.length,s.length);(u-a)/u>o&&(a<i?(i=a,n=[s]):a===i&&n.push(s))}),n.sort((s,a)=>s.localeCompare(a)),r&&(n=n.map(s=>`--${s}`)),n.length>1?`
15
+ (Did you mean one of ${n.join(", ")}?)`:n.length===1?`
16
+ (Did you mean ${n[0]}?)`:""}_r.suggestSimilar=Ni});var Or=M(ut=>{"use strict";var Vi=ie("events").EventEmitter,it=ie("child_process"),L=ie("path"),be=ie("fs"),f=ie("process"),{Argument:ki,humanReadableArgName:Fi}=ye(),{CommanderError:ot}=oe(),{Help:ji,stripColor:Hi}=Qe(),{Option:Rr,DualOptions:Di}=nt(),{suggestSimilar:wr}=Sr(),st=class t extends Vi{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:r=>f.stdout.write(r),writeErr:r=>f.stderr.write(r),outputError:(r,n)=>n(r),getOutHelpWidth:()=>f.stdout.isTTY?f.stdout.columns:void 0,getErrHelpWidth:()=>f.stderr.isTTY?f.stderr.columns:void 0,getOutHasColors:()=>at()??(f.stdout.isTTY&&f.stdout.hasColors?.()),getErrHasColors:()=>at()??(f.stderr.isTTY&&f.stderr.hasColors?.()),stripColor:r=>Hi(r)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let r=this;r;r=r.parent)e.push(r);return e}command(e,r,n){let i=r,o=n;typeof i=="object"&&i!==null&&(o=i,i=null),o=o||{};let[,s,a]=e.match(/([^ ]+) *(.*)/),u=this.createCommand(s);return i&&(u.description(i),u._executableHandler=!0),o.isDefault&&(this._defaultCommandName=u._name),u._hidden=!!(o.noHelp||o.hidden),u._executableFile=o.executableFile||null,a&&u.arguments(a),this._registerCommand(u),u.parent=this,u.copyInheritedSettings(this),i?this:u}createCommand(e){return new t(e)}createHelp(){return Object.assign(new ji,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,r){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
17
+ - specify the name in Command constructor or using .name()`);return r=r||{},r.isDefault&&(this._defaultCommandName=e._name),(r.noHelp||r.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,r){return new ki(e,r)}argument(e,r,n,i){let o=this.createArgument(e,r);return typeof n=="function"?o.default(i).argParser(n):o.default(n),this.addArgument(o),this}arguments(e){return e.trim().split(/ +/).forEach(r=>{this.argument(r)}),this}addArgument(e){let r=this.registeredArguments.slice(-1)[0];if(r&&r.variadic)throw new Error(`only the last argument can be variadic '${r.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,r){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,n,i]=e.match(/([^ ]+) *(.*)/),o=r??"display help for command",s=this.createCommand(n);return s.helpOption(!1),i&&s.arguments(i),o&&s.description(o),this._addImplicitHelpCommand=!0,this._helpCommand=s,this}addHelpCommand(e,r){return typeof e!="object"?(this.helpCommand(e,r),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,r){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
18
+ Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(r):this._lifeCycleHooks[e]=[r],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=r=>{if(r.code!=="commander.executeSubCommandAsync")throw r},this}_exit(e,r,n){this._exitCallback&&this._exitCallback(new ot(e,r,n)),f.exit(e)}action(e){let r=n=>{let i=this.registeredArguments.length,o=n.slice(0,i);return this._storeOptionsAsProperties?o[i]=this:o[i]=this.opts(),o.push(this),e.apply(this,o)};return this._actionHandler=r,this}createOption(e,r){return new Rr(e,r)}_callParseArg(e,r,n,i){try{return e.parseArg(r,n)}catch(o){if(o.code==="commander.invalidArgument"){let s=`${i} ${o.message}`;this.error(s,{exitCode:o.exitCode,code:o.code})}throw o}}_registerOption(e){let r=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(r){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
19
+ - already used by option '${r.flags}'`)}this.options.push(e)}_registerCommand(e){let r=i=>[i.name()].concat(i.aliases()),n=r(e).find(i=>this._findCommand(i));if(n){let i=r(this._findCommand(n)).join("|"),o=r(e).join("|");throw new Error(`cannot add command '${o}' as already have command '${i}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let r=e.name(),n=e.attributeName();if(e.negate){let o=e.long.replace(/^--no-/,"--");this._findOption(o)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let i=(o,s,a)=>{o==null&&e.presetArg!==void 0&&(o=e.presetArg);let u=this.getOptionValue(n);o!==null&&e.parseArg?o=this._callParseArg(e,o,u,s):o!==null&&e.variadic&&(o=e._concatValue(o,u)),o==null&&(e.negate?o=!1:e.isBoolean()||e.optional?o=!0:o=""),this.setOptionValueWithSource(n,o,a)};return this.on("option:"+r,o=>{let s=`error: option '${e.flags}' argument '${o}' is invalid.`;i(o,s,"cli")}),e.envVar&&this.on("optionEnv:"+r,o=>{let s=`error: option '${e.flags}' value '${o}' from env '${e.envVar}' is invalid.`;i(o,s,"env")}),this}_optionEx(e,r,n,i,o){if(typeof r=="object"&&r instanceof Rr)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let s=this.createOption(r,n);if(s.makeOptionMandatory(!!e.mandatory),typeof i=="function")s.default(o).argParser(i);else if(i instanceof RegExp){let a=i;i=(u,c)=>{let d=a.exec(u);return d?d[0]:c},s.default(o).argParser(i)}else s.default(i);return this.addOption(s)}option(e,r,n,i){return this._optionEx({},e,r,n,i)}requiredOption(e,r,n,i){return this._optionEx({mandatory:!0},e,r,n,i)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,r){return this.setOptionValueWithSource(e,r,void 0)}setOptionValueWithSource(e,r,n){return this._storeOptionsAsProperties?this[e]=r:this._optionValues[e]=r,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let r;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(r=n.getOptionValueSource(e))}),r}_prepareUserArgs(e,r){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(r=r||{},e===void 0&&r.from===void 0){f.versions?.electron&&(r.from="electron");let i=f.execArgv??[];(i.includes("-e")||i.includes("--eval")||i.includes("-p")||i.includes("--print"))&&(r.from="eval")}e===void 0&&(e=f.argv),this.rawArgs=e.slice();let n;switch(r.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":f.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${r.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,r){this._prepareForParse();let n=this._prepareUserArgs(e,r);return this._parseCommand([],n),this}async parseAsync(e,r){this._prepareForParse();let n=this._prepareUserArgs(e,r);return await this._parseCommand([],n),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
20
+ - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,r,n){if(be.existsSync(e))return;let i=r?`searched for local subcommand relative to directory '${r}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",o=`'${e}' does not exist
21
+ - if '${n}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
22
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
23
+ - ${i}`;throw new Error(o)}_executeSubCommand(e,r){r=r.slice();let n=!1,i=[".js",".ts",".tsx",".mjs",".cjs"];function o(d,l){let p=L.resolve(d,l);if(be.existsSync(p))return p;if(i.includes(L.extname(l)))return;let b=i.find(Ri=>be.existsSync(`${p}${Ri}`));if(b)return`${p}${b}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let d;try{d=be.realpathSync(this._scriptPath)}catch{d=this._scriptPath}a=L.resolve(L.dirname(d),a)}if(a){let d=o(a,s);if(!d&&!e._executableFile&&this._scriptPath){let l=L.basename(this._scriptPath,L.extname(this._scriptPath));l!==this._name&&(d=o(a,`${l}-${e._name}`))}s=d||s}n=i.includes(L.extname(s));let u;f.platform!=="win32"?n?(r.unshift(s),r=xr(f.execArgv).concat(r),u=it.spawn(f.argv[0],r,{stdio:"inherit"})):u=it.spawn(s,r,{stdio:"inherit"}):(this._checkForMissingExecutable(s,a,e._name),r.unshift(s),r=xr(f.execArgv).concat(r),u=it.spawn(f.execPath,r,{stdio:"inherit"})),u.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(l=>{f.on(l,()=>{u.killed===!1&&u.exitCode===null&&u.kill(l)})});let c=this._exitCallback;u.on("close",d=>{d=d??1,c?c(new ot(d,"commander.executeSubCommandAsync","(close)")):f.exit(d)}),u.on("error",d=>{if(d.code==="ENOENT")this._checkForMissingExecutable(s,a,e._name);else if(d.code==="EACCES")throw new Error(`'${s}' not executable`);if(!c)f.exit(1);else{let l=new ot(1,"commander.executeSubCommandAsync","(error)");l.nestedError=d,c(l)}}),this.runningCommand=u}_dispatchSubcommand(e,r,n){let i=this._findCommand(e);i||this.help({error:!0}),i._prepareForParse();let o;return o=this._chainOrCallSubCommandHook(o,i,"preSubcommand"),o=this._chainOrCall(o,()=>{if(i._executableHandler)this._executeSubCommand(i,r.concat(n));else return i._parseCommand(r,n)}),o}_dispatchHelpCommand(e){e||this.help();let r=this._findCommand(e);return r&&!r._executableHandler&&r.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,r)=>{e.required&&this.args[r]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(n,i,o)=>{let s=i;if(i!==null&&n.parseArg){let a=`error: command-argument value '${i}' is invalid for argument '${n.name()}'.`;s=this._callParseArg(n,i,o,a)}return s};this._checkNumberOfArguments();let r=[];this.registeredArguments.forEach((n,i)=>{let o=n.defaultValue;n.variadic?i<this.args.length?(o=this.args.slice(i),n.parseArg&&(o=o.reduce((s,a)=>e(n,a,s),n.defaultValue))):o===void 0&&(o=[]):i<this.args.length&&(o=this.args[i],n.parseArg&&(o=e(n,o,n.defaultValue))),r[i]=o}),this.processedArgs=r}_chainOrCall(e,r){return e&&e.then&&typeof e.then=="function"?e.then(()=>r()):r()}_chainOrCallHooks(e,r){let n=e,i=[];return this._getCommandAndAncestors().reverse().filter(o=>o._lifeCycleHooks[r]!==void 0).forEach(o=>{o._lifeCycleHooks[r].forEach(s=>{i.push({hookedCommand:o,callback:s})})}),r==="postAction"&&i.reverse(),i.forEach(o=>{n=this._chainOrCall(n,()=>o.callback(o.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,r,n){let i=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(o=>{i=this._chainOrCall(i,()=>o(this,r))}),i}_parseCommand(e,r){let n=this.parseOptions(r);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),r=n.unknown,this.args=e.concat(r),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),r);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(r),this._dispatchSubcommand(this._defaultCommandName,e,r);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},o=`command:${this.name()}`;if(this._actionHandler){i(),this._processArguments();let s;return s=this._chainOrCallHooks(s,"preAction"),s=this._chainOrCall(s,()=>this._actionHandler(this.processedArgs)),this.parent&&(s=this._chainOrCall(s,()=>{this.parent.emit(o,e,r)})),s=this._chainOrCallHooks(s,"postAction"),s}if(this.parent&&this.parent.listenerCount(o))i(),this._processArguments(),this.parent.emit(o,e,r);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,r);this.listenerCount("command:*")?this.emit("command:*",e,r):this.commands.length?this.unknownCommand():(i(),this._processArguments())}else this.commands.length?(i(),this.help({error:!0})):(i(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(r=>r._name===e||r._aliases.includes(e))}_findOption(e){return this.options.find(r=>r.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(r=>{r.mandatory&&e.getOptionValue(r.attributeName())===void 0&&e.missingMandatoryOptionValue(r)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(n=>{let i=n.attributeName();return this.getOptionValue(i)===void 0?!1:this.getOptionValueSource(i)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let i=e.find(o=>n.conflictsWith.includes(o.attributeName()));i&&this._conflictingOption(n,i)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let r=[],n=[],i=r,o=e.slice();function s(u){return u.length>1&&u[0]==="-"}let a=null;for(;o.length;){let u=o.shift();if(u==="--"){i===n&&i.push(u),i.push(...o);break}if(a&&!s(u)){this.emit(`option:${a.name()}`,u);continue}if(a=null,s(u)){let c=this._findOption(u);if(c){if(c.required){let d=o.shift();d===void 0&&this.optionMissingArgument(c),this.emit(`option:${c.name()}`,d)}else if(c.optional){let d=null;o.length>0&&!s(o[0])&&(d=o.shift()),this.emit(`option:${c.name()}`,d)}else this.emit(`option:${c.name()}`);a=c.variadic?c:null;continue}}if(u.length>2&&u[0]==="-"&&u[1]!=="-"){let c=this._findOption(`-${u[1]}`);if(c){c.required||c.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${c.name()}`,u.slice(2)):(this.emit(`option:${c.name()}`),o.unshift(`-${u.slice(2)}`));continue}}if(/^--[^=]+=/.test(u)){let c=u.indexOf("="),d=this._findOption(u.slice(0,c));if(d&&(d.required||d.optional)){this.emit(`option:${d.name()}`,u.slice(c+1));continue}}if(s(u)&&(i=n),(this._enablePositionalOptions||this._passThroughOptions)&&r.length===0&&n.length===0){if(this._findCommand(u)){r.push(u),o.length>0&&n.push(...o);break}else if(this._getHelpCommand()&&u===this._getHelpCommand().name()){r.push(u),o.length>0&&r.push(...o);break}else if(this._defaultCommandName){n.push(u),o.length>0&&n.push(...o);break}}if(this._passThroughOptions){i.push(u),o.length>0&&i.push(...o);break}i.push(u)}return{operands:r,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},r=this.options.length;for(let n=0;n<r;n++){let i=this.options[n].attributeName();e[i]=i===this._versionOptionName?this._version:this[i]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,r)=>Object.assign(e,r.opts()),{})}error(e,r){this._outputConfiguration.outputError(`${e}
24
+ `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
25
+ `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
26
+ `),this.outputHelp({error:!0}));let n=r||{},i=n.exitCode||1,o=n.code||"commander.error";this._exit(i,o,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in f.env){let r=e.attributeName();(this.getOptionValue(r)===void 0||["default","config","env"].includes(this.getOptionValueSource(r)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,f.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Di(this.options),r=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&r(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(i=>!r(i)).forEach(i=>{this.setOptionValueWithSource(i,n.implied[i],"implied")})})}missingArgument(e){let r=`error: missing required argument '${e}'`;this.error(r,{code:"commander.missingArgument"})}optionMissingArgument(e){let r=`error: option '${e.flags}' argument missing`;this.error(r,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let r=`error: required option '${e.flags}' not specified`;this.error(r,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,r){let n=s=>{let a=s.attributeName(),u=this.getOptionValue(a),c=this.options.find(l=>l.negate&&a===l.attributeName()),d=this.options.find(l=>!l.negate&&a===l.attributeName());return c&&(c.presetArg===void 0&&u===!1||c.presetArg!==void 0&&u===c.presetArg)?c:d||s},i=s=>{let a=n(s),u=a.attributeName();return this.getOptionValueSource(u)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},o=`error: ${i(e)} cannot be used with ${i(r)}`;this.error(o,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let r="";if(e.startsWith("--")&&this._showSuggestionAfterError){let i=[],o=this;do{let s=o.createHelp().visibleOptions(o).filter(a=>a.long).map(a=>a.long);i=i.concat(s),o=o.parent}while(o&&!o._enablePositionalOptions);r=wr(e,i)}let n=`error: unknown option '${e}'${r}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let r=this.registeredArguments.length,n=r===1?"":"s",o=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${r} argument${n} but got ${e.length}.`;this.error(o,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],r="";if(this._showSuggestionAfterError){let i=[];this.createHelp().visibleCommands(this).forEach(o=>{i.push(o.name()),o.alias()&&i.push(o.alias())}),r=wr(e,i)}let n=`error: unknown command '${e}'${r}`;this.error(n,{code:"commander.unknownCommand"})}version(e,r,n){if(e===void 0)return this._version;this._version=e,r=r||"-V, --version",n=n||"output the version number";let i=this.createOption(r,n);return this._versionOptionName=i.attributeName(),this._registerOption(i),this.on("option:"+i.name(),()=>{this._outputConfiguration.writeOut(`${e}
27
+ `),this._exit(0,"commander.version",e)}),this}description(e,r){return e===void 0&&r===void 0?this._description:(this._description=e,r&&(this._argsDescription=r),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let r=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(r=this.commands[this.commands.length-1]),e===r._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let i=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${i}'`)}return r._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(r=>this.alias(r)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let r=this.registeredArguments.map(n=>Fi(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?r:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=L.basename(e,L.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let r=this.createHelp(),n=this._getOutputContext(e);r.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let i=r.formatHelp(this,r);return n.hasColors?i:this._outputConfiguration.stripColor(i)}_getOutputContext(e){e=e||{};let r=!!e.error,n,i,o;return r?(n=a=>this._outputConfiguration.writeErr(a),i=this._outputConfiguration.getErrHasColors(),o=this._outputConfiguration.getErrHelpWidth()):(n=a=>this._outputConfiguration.writeOut(a),i=this._outputConfiguration.getOutHasColors(),o=this._outputConfiguration.getOutHelpWidth()),{error:r,write:a=>(i||(a=this._outputConfiguration.stripColor(a)),n(a)),hasColors:i,helpWidth:o}}outputHelp(e){let r;typeof e=="function"&&(r=e,e=void 0);let n=this._getOutputContext(e),i={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(s=>s.emit("beforeAllHelp",i)),this.emit("beforeHelp",i);let o=this.helpInformation({error:n.error});if(r&&(o=r(o),typeof o!="string"&&!Buffer.isBuffer(o)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(o),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",i),this._getCommandAndAncestors().forEach(s=>s.emit("afterAllHelp",i))}helpOption(e,r){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",r=r??"display help for command",this._helpOption=this.createOption(e,r),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let r=Number(f.exitCode??0);r===0&&e&&typeof e!="function"&&e.error&&(r=1),this._exit(r,"commander.help","(outputHelp)")}addHelpText(e,r){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
28
+ Expecting one of '${n.join("', '")}'`);let i=`${e}Help`;return this.on(i,o=>{let s;typeof r=="function"?s=r({error:o.error,command:o.command}):s=r,s&&o.write(`${s}
29
+ `)}),this}_outputHelpIfRequested(e){let r=this._getHelpOption();r&&e.find(i=>r.is(i))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function xr(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let r,n="127.0.0.1",i="9229",o;return(o=e.match(/^(--inspect(-brk)?)$/))!==null?r=o[1]:(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(r=o[1],/^\d+$/.test(o[3])?i=o[3]:n=o[3]):(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(r=o[1],n=o[3],i=o[4]),r&&i!=="0"?`${r}=${n}:${parseInt(i)+1}`:e})}function at(){if(f.env.NO_COLOR||f.env.FORCE_COLOR==="0"||f.env.FORCE_COLOR==="false")return!1;if(f.env.FORCE_COLOR||f.env.CLICOLOR_FORCE!==void 0)return!0}ut.Command=st;ut.useColor=at});var Tr=M(_=>{"use strict";var{Argument:Er}=ye(),{Command:ct}=Or(),{CommanderError:Ui,InvalidArgumentError:vr}=oe(),{Help:qi}=Qe(),{Option:$r}=nt();_.program=new ct;_.createCommand=t=>new ct(t);_.createOption=(t,e)=>new $r(t,e);_.createArgument=(t,e)=>new Er(t,e);_.Command=ct;_.Option=$r;_.Argument=Er;_.Help=qi;_.CommanderError=Ui;_.InvalidArgumentError=vr;_.InvalidOptionArgumentError=vr});var oi=M((lf,mr)=>{"use strict";var He=process||{},ni=He.argv||[],je=He.env||{},_a=!(je.NO_COLOR||ni.includes("--no-color"))&&(!!je.FORCE_COLOR||ni.includes("--color")||He.platform==="win32"||(He.stdout||{}).isTTY&&je.TERM!=="dumb"||!!je.CI),Sa=(t,e,r=t)=>n=>{let i=""+n,o=i.indexOf(e,t.length);return~o?t+Ra(i,e,r,o)+e:t+i+e},Ra=(t,e,r,n)=>{let i="",o=0;do i+=t.substring(o,n)+r,o=n+e.length,n=t.indexOf(e,o);while(~n);return i+t.substring(o)},ii=(t=_a)=>{let e=t?Sa:()=>String;return{isColorSupported:t,reset:e("\x1B[0m","\x1B[0m"),bold:e("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:e("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:e("\x1B[3m","\x1B[23m"),underline:e("\x1B[4m","\x1B[24m"),inverse:e("\x1B[7m","\x1B[27m"),hidden:e("\x1B[8m","\x1B[28m"),strikethrough:e("\x1B[9m","\x1B[29m"),black:e("\x1B[30m","\x1B[39m"),red:e("\x1B[31m","\x1B[39m"),green:e("\x1B[32m","\x1B[39m"),yellow:e("\x1B[33m","\x1B[39m"),blue:e("\x1B[34m","\x1B[39m"),magenta:e("\x1B[35m","\x1B[39m"),cyan:e("\x1B[36m","\x1B[39m"),white:e("\x1B[37m","\x1B[39m"),gray:e("\x1B[90m","\x1B[39m"),bgBlack:e("\x1B[40m","\x1B[49m"),bgRed:e("\x1B[41m","\x1B[49m"),bgGreen:e("\x1B[42m","\x1B[49m"),bgYellow:e("\x1B[43m","\x1B[49m"),bgBlue:e("\x1B[44m","\x1B[49m"),bgMagenta:e("\x1B[45m","\x1B[49m"),bgCyan:e("\x1B[46m","\x1B[49m"),bgWhite:e("\x1B[47m","\x1B[49m"),blackBright:e("\x1B[90m","\x1B[39m"),redBright:e("\x1B[91m","\x1B[39m"),greenBright:e("\x1B[92m","\x1B[39m"),yellowBright:e("\x1B[93m","\x1B[39m"),blueBright:e("\x1B[94m","\x1B[39m"),magentaBright:e("\x1B[95m","\x1B[39m"),cyanBright:e("\x1B[96m","\x1B[39m"),whiteBright:e("\x1B[97m","\x1B[39m"),bgBlackBright:e("\x1B[100m","\x1B[49m"),bgRedBright:e("\x1B[101m","\x1B[49m"),bgGreenBright:e("\x1B[102m","\x1B[49m"),bgYellowBright:e("\x1B[103m","\x1B[49m"),bgBlueBright:e("\x1B[104m","\x1B[49m"),bgMagentaBright:e("\x1B[105m","\x1B[49m"),bgCyanBright:e("\x1B[106m","\x1B[49m"),bgWhiteBright:e("\x1B[107m","\x1B[49m")}};mr.exports=ii();mr.exports.createColors=ii});import{realpathSync as Si}from"fs";import{fileURLToPath as tu}from"url";import he from"process";var Lr=yr(Tr(),1),{program:du,createCommand:mu,createArgument:fu,createOption:pu,CommanderError:hu,InvalidArgumentError:Ir,InvalidOptionArgumentError:gu,Command:N,Argument:yu,Option:Ar,Help:bu}=Lr.default;import{writeFile as Qs}from"fs/promises";import{resolve as ea}from"path";import ar from"process";import{readFile as Jn}from"fs/promises";import{dirname as Ns,isAbsolute as Vs,resolve as le}from"path";var C=class extends Error{code;context;cause;constructor(e){super(e.message),this.name=new.target.name,this.code=e.code,this.context=e.context,this.cause=e.cause}},Ce=class extends C{constructor(e){super({code:"MCP_STDIO_PROCESS_SPAWN_FAILED",message:`Failed to spawn MCP server process: ${e.command}`,context:Pr(e),cause:e.cause})}},se=class extends C{constructor(e){super({code:"MCP_STDIO_PROCESS_EXITED",message:Ji(e),context:{...Pr(e),exitCode:e.exitCode,signal:e.signal,stderrTail:e.stderrTail??""}})}},_e=class extends C{constructor(e){super({code:"MCP_STDIO_REQUEST_TIMEOUT",message:`MCP request timed out after ${e.timeoutMs}ms: ${e.method}`,context:{id:e.id,method:e.method,timeoutMs:e.timeoutMs}})}},g=class extends C{constructor(e,r={}){super({code:"MCP_STDIO_MALFORMED_JSON_RPC",message:`Malformed JSON-RPC message from MCP server: ${e}`,context:{reason:e,lineExcerpt:Gi(r.line)},cause:r.cause})}},H=class extends C{responseError;constructor(e){super({code:"MCP_STDIO_RESPONSE_ERROR",message:`MCP server returned JSON-RPC error ${e.error.code} for ${e.method}: ${e.error.message}`,context:{id:e.id,method:e.method,rpcErrorCode:e.error.code,rpcErrorMessage:e.error.message}}),this.responseError=e.error}},D=class extends C{constructor(e){super({code:"MCP_STDIO_STDIN_WRITE_FAILED",message:`Failed to write MCP message to stdin: ${e.method}`,context:{method:e.method,id:e.id??null},cause:e.cause})}},U=class extends C{constructor(e="MCP stdio client is not connected"){super({code:"MCP_STDIO_DISCONNECTED",message:e})}};function Ji(t){let e=t.signal==null?`exit code ${t.exitCode??"unknown"}`:`signal ${t.signal}`;return`MCP server process exited before completing pending requests: ${t.command} (${e})`}function Pr(t){return{command:t.command,args:zi(t.args),cwd:t.cwd??null}}function zi(t){let e=[],r=!1;for(let n of t){if(r){e.push("[REDACTED]"),r=!1;continue}let[i,o]=Wi(n);if(Bi(i)){o==null?(e.push(i),r=!0):e.push(`${i}=[REDACTED]`);continue}e.push(n)}return e}function Wi(t){let e=t.indexOf("=");return e===-1?[t,void 0]:[t.slice(0,e),t.slice(e+1)]}function Bi(t){let e=t.toLowerCase().replace(/[^a-z0-9]/g,"");return e.includes("token")||e.includes("authorization")||e.includes("apikey")||e.includes("cookie")||e.includes("password")||e.includes("secret")}function Gi(t){return t==null?"":t.length<=200?t:`${t.slice(0,200)}...`}var S="2.0";function lt(t,e,r){return r==null?{jsonrpc:S,id:t,method:e}:{jsonrpc:S,id:t,method:e,params:r}}function dt(t,e){return e==null?{jsonrpc:S,method:t}:{jsonrpc:S,method:t,params:e}}function mt(t){let e;try{e=JSON.parse(t)}catch(r){throw new g("stdout line is not valid JSON",{line:t,cause:r})}if(!Re(e))throw new g("stdout line is not a JSON-RPC object",{line:t});if(e.jsonrpc!==S)throw new g('JSON-RPC message is missing jsonrpc: "2.0"',{line:t});return"method"in e?Xi(e,t):Ki(e,t)}function ft(t){return"id"in t&&("result"in t||"error"in t)&&!("method"in t)}function Xi(t,e){if(typeof t.method!="string"||t.method.length===0)throw new g("JSON-RPC request/notification has invalid method",{line:e});let r=Qi(t,e);if("id"in t){if(!Mr(t.id))throw new g("JSON-RPC request has invalid id",{line:e});return r==null?{jsonrpc:S,id:t.id,method:t.method}:{jsonrpc:S,id:t.id,method:t.method,params:r}}return r==null?{jsonrpc:S,method:t.method}:{jsonrpc:S,method:t.method,params:r}}function Ki(t,e){if(!Mr(t.id))throw new g("JSON-RPC response has invalid id",{line:e});let r="result"in t,n="error"in t;if(r===n)throw new g("JSON-RPC response must include exactly one of result or error",{line:e});return n?{jsonrpc:S,id:t.id,error:Zi(t.error,e)}:{jsonrpc:S,id:t.id,result:Se(t.result)}}function Zi(t,e){if(!Re(t))throw new g("JSON-RPC error response has invalid error object",{line:e});let r=t.code,n=t.message;if(typeof r!="number"||!Number.isInteger(r)||typeof n!="string")throw new g("JSON-RPC error object has invalid code or message",{line:e});return"data"in t?{code:r,message:n,data:Se(t.data)}:{code:r,message:n}}function Qi(t,e){if("params"in t){if(!eo(t.params))throw new g("JSON-RPC params must be an object or array",{line:e});return t.params}}function eo(t){return Array.isArray(t)||Re(t)}function Mr(t){return typeof t=="string"||typeof t=="number"&&Number.isFinite(t)}function Se(t){if(t===null||typeof t=="string"||typeof t=="boolean")return t;if(typeof t=="number"){if(Number.isFinite(t))return t;throw new g("JSON-RPC message contains a non-finite number")}if(Array.isArray(t))return t.map(e=>Se(e));if(Re(t)){let e={};for(let[r,n]of Object.entries(t))e[r]=Se(n);return e}throw new g("JSON-RPC message contains a non-JSON value")}function Re(t){return typeof t=="object"&&t!=null&&!Array.isArray(t)}import Nr from"process";var Vr={debug:10,info:20,warn:30,error:40},to={stdout:t=>{Nr.stdout.write(t)},stderr:t=>{Nr.stderr.write(t)}};function kr(t={}){let e=t.level??"info",r=t.format??(t.ci===!0?"json":"human"),n=t.writer??to,i=t.now??(()=>new Date);function o(s,a,u){if(Vr[s]<Vr[e])return;let c=r==="json"?no(s,a,u,i):ro(s,a,u);if(s==="warn"||s==="error"){n.stderr(c);return}n.stdout(c)}return{debug:(s,a)=>{o("debug",s,a)},info:(s,a)=>{o("info",s,a)},warn:(s,a)=>{o("warn",s,a)},error:(s,a)=>{o("error",s,a)},getLevel:()=>e,setLevel:s=>{e=s}}}function ro(t,e,r){let n=t.toUpperCase(),i=Fr(r)?` ${JSON.stringify(r)}`:"";return`${n} ${e}${i}
30
+ `}function no(t,e,r,n){let i={timestamp:n().toISOString(),level:t,message:e};return Fr(r)&&(i.fields=r),`${JSON.stringify(i)}
31
+ `}function Fr(t){return t!=null&&Object.keys(t).length>0}function pt(t){let e=t.verbose===!0,r=t.logger??(e&&t.onProtocolMessage==null?kr({level:"debug"}):void 0);return{log:(n,i,o)=>{if(!e)return;let s=io(n,i,o);t.onProtocolMessage?.(s),r?.debug("mcp protocol message",{direction:s.direction,id:s.id??null,method:s.method??null,message:s.message,transport:s.transport??null})}}}function we(t){if(t==null||typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;if(Array.isArray(t))return t.map(n=>we(n));let e={};for(let[r,n]of Object.entries(t))e[r]=oo(r)?"[REDACTED]":we(n);return e}function io(t,e,r){let n=we(e),i="id"in e?e.id:void 0,o="method"in e?e.method:void 0,s={direction:t,message:n};return r!=null&&(s.transport=we(r)),i!=null&&(s.id=i),o!=null&&(s.method=o),s}function oo(t){let e=t.toLowerCase().replace(/[^a-z0-9]/g,"");return e.includes("token")||e.includes("authorization")||e.includes("apikey")||e.includes("cookie")||e.includes("password")||e.includes("secret")}import{spawn as lo}from"child_process";import gt from"process";import{setTimeout as mo}from"timers/promises";import{createHash as so}from"crypto";function ao(t){let e=typeof t=="string"?t:G(t);return so("sha256").update(e).digest("hex")}function ae(t,e={}){let r=e.length??16;if(!Number.isInteger(r)||r<1||r>64)throw new RangeError("length must be an integer between 1 and 64.");let n=ao(t).slice(0,r);return e.prefix==null?n:`${e.prefix}_${n}`}function G(t){return ht(t,new WeakSet)}function ht(t,e){if(t==null)return"null";if(typeof t=="string")return JSON.stringify(t);if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError("JSON-compatible numbers must be finite.");return JSON.stringify(t)}return typeof t=="boolean"?t?"true":"false":Array.isArray(t)?uo(t,e):co(t,e)}function uo(t,e){jr(t,e);let r=`[${t.map(n=>ht(n,e)).join(",")}]`;return e.delete(t),r}function co(t,e){jr(t,e);let r=`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${ht(t[n]??null,e)}`).join(",")}}`;return e.delete(t),r}function jr(t,e){if(e.has(t))throw new TypeError("Cannot stableStringify circular values.");e.add(t)}var Y="2025-11-25";var Hr=8192,yt=500,xe=class{command;args;cwd;initializeTimeoutMs;requestTimeoutMs;#e;#r="";#t="";#n=new Map;#a=new Set;#s=0;#o=!1;#i;#u;#l;#d;#m;constructor(e){if(e.command.trim()==="")throw new TypeError("command must be a non-empty string.");this.command=e.command,this.args=e.args??[],this.cwd=e.cwd,this.initializeTimeoutMs=bt(e.initializeTimeoutMs??5e3,"initializeTimeoutMs"),this.requestTimeoutMs=bt(e.requestTimeoutMs??1e4,"requestTimeoutMs"),this.#d=e,this.#l=pt(e),this.#m=ae({command:e.command,args:[...this.args],cwd:e.cwd??"",parentPid:gt.pid,createdAt:Date.now()},{prefix:"mcp",length:12})}get isConnected(){return this.#e!=null&&this.#i==null&&!this.#o}get initializeResult(){return this.#u}get protocolVersion(){return this.#u?.protocolVersion}get serverInfo(){return this.#u?.serverInfo}get serverCapabilities(){return this.#u?.capabilities}async connect(){if(this.isConnected)return;if(this.#e!=null)throw this.#i??new U;let e=lo(this.command,[...this.args],{cwd:this.cwd,env:this.#d.env==null?gt.env:{...gt.env,...this.#d.env},stdio:["pipe","pipe","pipe"],shell:!1});this.#e=e,this.#i=void 0,this.#o=!1,e.stdout.setEncoding("utf8"),e.stderr.setEncoding("utf8"),e.stdout.on("data",r=>{this.#b(r)}),e.stderr.on("data",r=>{this.#R(r)}),e.on("exit",(r,n)=>{this.#_(r,n)}),await new Promise((r,n)=>{let i=a=>{this.#S(a)},o=()=>{e.off("error",s),e.on("error",i),r()},s=a=>{e.off("spawn",o);let u=new Ce({command:this.command,args:this.args,cwd:this.cwd,cause:a});this.#i=u,this.#e=void 0,n(u)};e.once("spawn",o),e.once("error",s)})}async initialize(e,r){let n={protocolVersion:Y,capabilities:{},clientInfo:{name:"@sherpa-labs/core-mcp",version:"0.0.0"},...e},i=await this.request("initialize",n,{timeoutMs:r?.timeoutMs??this.initializeTimeoutMs});if(!fo(i))throw new g("initialize result must be a JSON object");return this.#u=i,await this.notify("notifications/initialized"),i}async request(e,r,n){this.#g(),Dr(e);let i=this.#y(),o=bt(n?.timeoutMs??this.requestTimeoutMs,"timeoutMs"),s=lt(i,e,r);return await new Promise((a,u)=>{let c=setTimeout(()=>{this.#n.delete(i),this.#a.add(i),u(new _e({id:i,method:e,timeoutMs:o}))},o),d={id:i,method:e,timeoutMs:o,resolve:l=>{a(l)},reject:u,timeout:c};this.#n.set(i,d);try{this.#f(s,l=>{l!=null&&this.#h(i,new D({method:e,id:i,cause:l}))})}catch(l){this.#h(i,new D({method:e,id:i,cause:l}))}})}async notify(e,r){this.#g(),Dr(e);let n=dt(e,r);await new Promise((i,o)=>{try{this.#f(n,s=>{if(s==null){i();return}o(new D({method:e,cause:s}))})}catch(s){o(new D({method:e,cause:s}))}})}async listTools(e){return await this.request("tools/list",void 0,e)}async disconnect(){let e=this.#e;if(e!=null){if(this.#o=!0,this.#c(new U("MCP stdio client disconnected before response")),e.stdin.destroyed||e.stdin.end(),e.exitCode!=null||e.signalCode!=null){this.#e=void 0,this.#o=!1;return}await Ct(e,yt)||e.kill("SIGTERM"),await Ct(e,yt)||(e.kill("SIGKILL"),await Ct(e,yt)),this.#e=void 0,this.#o=!1}}#y(){return this.#s+=1,`${this.#m}-${this.#s}`}#f(e,r){let n=this.#e;if(n==null||n.stdin.destroyed||!n.stdin.writable)throw new U;this.#l.log("outbound",e),n.stdin.write(`${JSON.stringify(e)}
32
+ `,"utf8",r)}#b(e){for(this.#r+=e;;){let r=this.#r.indexOf(`
33
+ `);if(r===-1)return;let n=this.#r.slice(0,r).replace(/\r$/,"");this.#r=this.#r.slice(r+1),this.#C(n)}}#C(e){if(e.trim()==="")return;let r;try{r=mt(e)}catch(i){this.#p(i instanceof Error?i:new g("unknown parser failure"));return}if(this.#l.log("inbound",r),!ft(r))return;let n=this.#n.get(r.id);if(n==null){if(this.#a.has(r.id)){this.#a.delete(r.id);return}this.#p(new g(`received response for unknown request id ${String(r.id)}`));return}if(this.#n.delete(r.id),clearTimeout(n.timeout),"error"in r){n.reject(new H({id:r.id,method:n.method,error:r.error}));return}n.resolve(r.result)}#_(e,r){let n=this.#e;if(this.#e=void 0,this.#o)return;let i=new se({command:this.command,args:this.args,cwd:this.cwd,exitCode:e,signal:r,stderrTail:this.#t});this.#i=this.#i??i,this.#c(this.#i),n!=null&&(n.stdout.removeAllListeners(),n.stderr.removeAllListeners())}#S(e){if(this.#o)return;let r=new se({command:this.command,args:this.args,cwd:this.cwd,exitCode:null,signal:null,stderrTail:this.#t===""?e.message:`${this.#t}
34
+ ${e.message}`});this.#i=this.#i??r,this.#c(this.#i)}#R(e){this.#t=`${this.#t}${e}`,this.#t.length>Hr&&(this.#t=this.#t.slice(this.#t.length-Hr))}#p(e){this.#i=e,this.#c(e);let r=this.#e;r!=null&&(this.#e=void 0,r.kill("SIGTERM"))}#h(e,r){let n=this.#n.get(e);n!=null&&(this.#n.delete(e),clearTimeout(n.timeout),n.reject(r))}#c(e){let r=[...this.#n.values()];this.#n.clear();for(let n of r)clearTimeout(n.timeout),n.reject(e)}#g(){if(this.#i!=null)throw this.#i;if(!this.isConnected)throw new U}};function Dr(t){if(t.trim()==="")throw new TypeError("method must be a non-empty string.")}function bt(t,e){if(!Number.isFinite(t)||t<=0)throw new RangeError(`${e} must be a positive finite number.`);return t}function fo(t){return typeof t=="object"&&t!=null&&!Array.isArray(t)}async function Ct(t,e){return t.exitCode!=null||t.signalCode!=null?!0:await Promise.race([new Promise(r=>{t.once("exit",()=>{r(!0)})}),mo(e).then(()=>!1)])}import ic from"process";import{setTimeout as sc}from"timers/promises";import{TextDecoder as uc}from"util";var Oe={error:-10,warning:-3,info:-1};function Ee(t,e={}){let r=e.baseline??100,n=e.minScore??0,i=e.maxScore??100,o={...Oe,...e.severityWeights},s=t.reduce((u,c)=>u+o[c.severity],r),a=ho(s,n,i);return{score:a,maxScore:i,baseline:r,deduction:r-a}}function ve(t){let e=0,r=0,n=0;for(let i of t)i.severity==="error"?e+=1:i.severity==="warning"?r+=1:n+=1;return{errorCount:e,warningCount:r,infoCount:n,violationCount:t.length}}function ho(t,e,r){return Math.min(Math.max(t,e),r)}var go={ignoredRules:[],includedRules:[],ruleOverrides:{},severityWeights:Oe,thresholds:{}};function Wr(t){let e=q(t.config??go),r=t.initializeResult??t.initialize?.result,n=t.protocolVersion??bo(r,"protocolVersion"),i=t.capabilities??Jr(r,"capabilities")??{},o=t.serverInfo??Jr(r,"serverInfo"),s=yo(t.initialize,r),a={transport:t.transport,capabilities:i,tools:t.tools??[],resources:t.resources??[],prompts:t.prompts??[],messages:t.messages??[],timings:t.timings??{},errors:t.errors??[],metadata:t.metadata??{},config:e,thresholds:e.thresholds};return n!==void 0&&(a.protocolVersion=n),o!==void 0&&(a.serverInfo=o),s!==void 0&&(a.initialize=s),a}function Br(t,e){let r=q(e);return{...t,config:r,thresholds:r.thresholds}}function q(t={}){let e=zr(t.ignoredRules??[]),r=zr(t.includedRules??[]),n="severityOverrides"in t?t.severityOverrides??{}:{},i=Co(t.ruleOverrides??{},n),o={...Oe,...t.severityWeights},s={ignoredRules:e,includedRules:r,ruleOverrides:i,severityWeights:o,thresholds:_o(t.thresholds??{})};return t.failUnder!==void 0&&(s.failUnder=t.failUnder),s}function yo(t,e){if(t===void 0&&e===void 0)return;let r={};return t?.request!==void 0&&(r.request=t.request),t?.response!==void 0&&(r.response=t.response),e!==void 0&&(r.result=e),t?.error!==void 0&&(r.error=t.error),t?.completed!==void 0?r.completed=t.completed:e!==void 0&&(r.completed=!0),t?.initializedNotificationSent!==void 0&&(r.initializedNotificationSent=t.initializedNotificationSent),r}function bo(t,e){if(!_t(t))return;let r=t[e];return typeof r=="string"?r:void 0}function Jr(t,e){if(!_t(t))return;let r=t[e];return _t(r)?r:void 0}function _t(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Co(t,e){let r={...t};for(let[n,i]of Object.entries(e)){let o=r[n]??{};r[n]={...o,severity:i}}return r}function _o(t){return Object.fromEntries(Object.entries(t).filter(e=>{let[,r]=e;return typeof r=="number"&&Number.isFinite(r)}))}function zr(t){return Array.from(new Set(t)).sort()}import{posix as So}from"path";import Ic from"process";function St(t){let e=t.replace(/\\/g,"/"),r=e.startsWith("//")&&!e.startsWith("///"),n=So.normalize(e),i=r?`//${n.replace(/^\/+/,"")}`:n;return Ro(i)}function Gr(t){let e=t.replace(/\\/g,"/");return e.startsWith("/")||/^[a-zA-Z]:\//.test(e)}function Ro(t){return t.replace(/^([a-zA-Z]):/,e=>e.toLowerCase())}import{Buffer as Mc}from"buffer";function m(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function x(t){return Array.isArray(t)}function X(t){return Object.entries(t)}function I(t,e){if(!m(t))return;let r=t[e];return typeof r=="string"?r:void 0}function O(t,e){if(!m(t))return;let r=t[e];return m(r)?r:void 0}function K(t){return I(t,"method")}function Rt(t){if(!m(t)||!("id"in t))return;let e=t.id;return typeof e=="string"||typeof e=="number"||e===null?e:void 0}function wt(t){return typeof t=="string"||typeof t=="number"&&Number.isFinite(t)}function Yr(t,e){let r=t.capabilities[e];return r!=null&&r!==!1}function Xr(t,e){return t.errors.some(r=>r.method===e)||xt(t,e)?.ok===!1}function xt(t,e){return(t.metadata.methodObservations??[]).find(n=>n.method===e)}function J(t,e,r,n){let i=t.config.ruleOverrides[e]?.thresholds?.[r],o=t.thresholds[r],s=i??o??n;return Number.isFinite(s)?s:n}function Kr(t){return t.structuredContent!==void 0?t.structuredContent:m(t.result)?t.result.structuredContent:void 0}function V(t,e=160){return t.length<=e?t:`${t.slice(0,e)}...`}function Ot(t){return t.split(";",1)[0]?.trim().toLowerCase()??""}var Et="F001",Zr=5e3,vt={id:Et,category:"performance",severity:"warning",title:"Initialization latency stays within budget",description:"Flags initialize timings above the configured latency budget.",check(t){let e=t.timings.initializeMs,r=J(t,Et,"initializeLatencyMs",Zr);return e===void 0||e<=r?[]:[{message:`initialize took ${e}ms, above the ${r}ms budget.`,location:"timings.initializeMs",fixHint:"Defer expensive startup work until after initialization or cache discovery data."}]}};var $t="F002",Qr=2e3,Tt={id:$t,category:"performance",severity:"warning",title:"List methods stay within latency budget",description:"Flags tools/list, resources/list, and prompts/list timings above the configured budget.",check(t){let e=J(t,$t,"listLatencyMs",Qr),r=[{method:"tools/list",path:"timings.toolsListMs",value:t.timings.toolsListMs},{method:"resources/list",path:"timings.resourcesListMs",value:t.timings.resourcesListMs},{method:"prompts/list",path:"timings.promptsListMs",value:t.timings.promptsListMs}],n=[];for(let i of r)i.value!==void 0&&i.value>e&&n.push({message:`${i.method} took ${i.value}ms, above the ${e}ms budget.`,location:i.path,fixHint:"Keep discovery methods fast by caching static metadata and paginating large lists."});return n}};import{Buffer as wo}from"buffer";var $e="F003",en=100,tn=512*1024,At={id:$e,category:"performance",severity:"warning",title:"List payloads stay bounded",description:"Flags discovery lists with too many items or too many response bytes.",check(t){let e=J(t,$e,"maxListItems",en),r=J(t,$e,"maxListPayloadBytes",tn);return[...Lt(t,"tools",t.tools.length,It(t.tools),e,r),...Lt(t,"resources",t.resources.length,It(t.resources),e,r),...Lt(t,"prompts",t.prompts.length,It(t.prompts),e,r)]}};function Lt(t,e,r,n,i,o){let s=[],a=t.metadata.listPayloadBytes?.[e]??n;return r>i&&s.push({message:`${e}/list returned ${r} items, above the ${i} item budget.`,location:e,fixHint:"Paginate large discovery lists and return nextCursor instead of one oversized page."}),a>o&&s.push({message:`${e}/list payload was ${a} bytes, above the ${o} byte budget.`,location:`metadata.listPayloadBytes.${e}`,fixHint:"Shorten descriptions, paginate list responses, or defer large details until item access."}),s}function It(t){return wo.byteLength(JSON.stringify(t),"utf8")}var rn=[vt,Tt,At];var nn="P001",Pt={id:nn,category:"protocol",severity:"error",title:"Initialization response is complete",description:"Requires initialize to complete with protocolVersion, capabilities, and serverInfo.",check(t){let e=[],r=t.initialize;if(r===void 0)return[{message:"No initialize observation was captured.",location:"initialize",fixHint:"Capture and return a JSON-RPC initialize response before running MCP lint rules."}];(r.completed===!1||r.error!==void 0)&&e.push({message:`initialize did not complete successfully${r.error?.message!==void 0?`: ${r.error.message}`:""}.`,location:r.error?.location??"initialize",fixHint:"Ensure the server responds to initialize within the client timeout."});let n=r.result??O(r.response,"result");return m(n)?(I(n,"protocolVersion")===void 0&&e.push({message:"initialize result is missing protocolVersion.",location:"initialize.result.protocolVersion",fixHint:"Include the negotiated MCP protocol version in initialize.result.protocolVersion."}),m(n.capabilities)||e.push({message:"initialize result is missing capabilities.",location:"initialize.result.capabilities",fixHint:"Return a capabilities object, even when no optional capabilities are supported."}),O(n,"serverInfo")===void 0&&e.push({message:"initialize result is missing serverInfo.",location:"initialize.result.serverInfo",fixHint:"Return serverInfo with at least a stable name and version."}),e):(e.push({message:"initialize response result must be a JSON object.",location:"initialize.result",fixHint:"Return InitializeResult as an object with protocolVersion, capabilities, and serverInfo."}),e)}};var on="P002",Mt={id:on,category:"protocol",severity:"error",title:"JSON-RPC envelopes are valid",description:"Flags malformed JSON-RPC version, id, request, response, and error envelopes.",check(t){let e=[];return t.messages.forEach((r,n)=>{e.push(...xo(r,n))}),e}};function xo(t,e){let r=[],n=`messages[${e}]`;return t.malformed===!0&&r.push({message:t.error??"Observed protocol message was marked malformed.",location:n,fixHint:"Emit one valid JSON-RPC 2.0 object for each MCP protocol message.",...t.raw!==void 0?{evidence:t.raw}:{}}),t.message===void 0?r:Array.isArray(t.message)?(r.push({message:"JSON-RPC batch arrays are not valid for modern MCP sessions.",location:n,fixHint:"Send each JSON-RPC request, response, or notification as a separate message."}),r):m(t.message)?(t.message.jsonrpc!=="2.0"&&r.push({message:'JSON-RPC message is missing jsonrpc: "2.0".',location:`${n}.jsonrpc`,fixHint:'Set jsonrpc to exactly "2.0" on every MCP protocol message.'}),K(t.message)!==void 0?Oo(t.message,n,r):Eo(t.message,n,r),r):(r.push({message:"JSON-RPC message must be an object.",location:n,fixHint:'Serialize protocol messages as JSON objects with jsonrpc: "2.0".'}),r)}function Oo(t,e,r){let n=t.method;(typeof n!="string"||n.trim()==="")&&r.push({message:"JSON-RPC request or notification has an invalid method.",location:`${e}.method`,fixHint:"Use a non-empty string method name for every request and notification."}),"id"in t&&!wt(t.id)&&r.push({message:"JSON-RPC request id must be a non-null string or number.",location:`${e}.id`,fixHint:"Use string or number IDs for requests and omit id entirely for notifications."}),"params"in t&&!$o(t.params)&&r.push({message:"JSON-RPC params must be an object or array when present.",location:`${e}.params`,fixHint:"Encode params as a JSON object or array, or omit params when there are none."})}function Eo(t,e,r){wt(t.id)||r.push({message:"JSON-RPC response id must be a non-null string or number.",location:`${e}.id`,fixHint:"Echo the original request id in every result or error response."});let n="result"in t,i="error"in t;n===i&&r.push({message:"JSON-RPC response must include exactly one of result or error.",location:e,fixHint:"Return either result for success or error for failure, never both or neither."}),i&&vo(t.error,`${e}.error`,r)}function vo(t,e,r){if(!m(t)){r.push({message:"JSON-RPC error must be an object.",location:e,fixHint:"Return error with integer code and string message fields."});return}(typeof t.code!="number"||!Number.isInteger(t.code))&&r.push({message:"JSON-RPC error code must be an integer.",location:`${e}.code`,fixHint:"Use standard JSON-RPC integer error codes such as -32601 for unknown methods."}),typeof t.message!="string"&&r.push({message:"JSON-RPC error message must be a string.",location:`${e}.message`,fixHint:"Include a human-readable error.message string in every JSON-RPC error."})}function $o(t){return Array.isArray(t)||m(t)}var sn="P003",Nt={id:sn,category:"protocol",severity:"error",title:"Initialization lifecycle order is valid",description:"Flags normal protocol traffic before initialize and notifications/initialized complete.",check(t){let e=[],r=To(t.messages,"initialize"),n=Lo(t.messages,r?.id),i=an(t.messages,"notifications/initialized");return t.initialize?.completed===!0&&t.initialize.initializedNotificationSent!==!0&&i===-1&&e.push({message:"initialize completed but notifications/initialized was not observed.",location:"messages",fixHint:"Send notifications/initialized immediately after a successful initialize result."}),t.messages.forEach((o,s)=>{let a=K(o.message);a!==void 0&&(o.direction==="client-to-server"&&s<n&&a!=="initialize"&&a!=="ping"&&e.push({message:`${a} was sent before initialize completed.`,location:`messages[${s}].method`,fixHint:"Only send initialize or ping before the server returns InitializeResult."}),o.direction==="server-to-client"&&s<Io(i)&&a!=="ping"&&a!=="notifications/message"&&e.push({message:`Server sent ${a} before notifications/initialized was observed.`,location:`messages[${s}].method`,fixHint:"Do not send server-initiated requests until the client sends notifications/initialized."}))}),e}};function To(t,e){let r=an(t,e);if(r===-1)return;let n=Rt(t[r]?.message);return n===void 0?{index:r}:{index:r,id:n}}function an(t,e){return t.findIndex(r=>r.direction==="client-to-server"&&K(r.message)===e)}function Lo(t,e){let r=t.findIndex(n=>n.direction!=="server-to-client"||K(n.message)!==void 0?!1:e==null?!0:Rt(n.message)===e);return r===-1?Number.MAX_SAFE_INTEGER:r}function Io(t){return t===-1?Number.MAX_SAFE_INTEGER:t}var un="P004",Ao=["2025-11-25","2025-06-18","2024-11-05"],Vt={id:un,category:"protocol",severity:"error",title:"Protocol version negotiation is valid",description:"Flags malformed or unsupported negotiated MCP protocol versions.",check(t){let e=[],r=t.protocolVersion;if(r===void 0)return e;Po(r)||e.push({message:`Negotiated protocol version ${r} is not a YYYY-MM-DD date string.`,location:"protocolVersion",fixHint:"Return an MCP protocol version date such as 2025-11-25."});let n=t.metadata.supportedProtocolVersions??Ao;return n.includes(r)||e.push({message:`Negotiated protocol version ${r} was not in the supported version set.`,location:"protocolVersion",evidence:n.join(", "),fixHint:"Negotiate a protocol version supported by the client or disconnect cleanly."}),e}};function Po(t){if(!/^\d{4}-\d{2}-\d{2}$/.test(t))return!1;let e=new Date(`${t}T00:00:00.000Z`);return Number.isFinite(e.valueOf())&&e.toISOString().slice(0,10)===t}var cn="P005",Ft={id:cn,category:"protocol",severity:"warning",title:"Capabilities match observed behavior",description:"Flags advertised capabilities that fail and discovered features that were not advertised.",check(t){return[...kt(t,"tools","tools/list",t.tools.length),...kt(t,"resources","resources/list",t.resources.length),...kt(t,"prompts","prompts/list",t.prompts.length)]}};function kt(t,e,r,n){let i=[],o=Yr(t,e);return o&&Xr(t,r)&&i.push({message:`Server advertised ${e} but ${r} failed.`,location:`capabilities.${e}`,fixHint:`Only advertise ${e} when ${r} is implemented and returns a valid result.`}),!o&&n>0&&i.push({message:`Server exposed ${n} ${e} item(s) without advertising ${e}.`,location:e,fixHint:`Advertise capabilities.${e} during initialize before exposing ${r}.`}),i}var ln="P006",jt={id:ln,category:"protocol",severity:"warning",title:"Unknown methods return method-not-found",description:"Requires the unknown-method probe to return JSON-RPC -32601.",check(t){let e=t.metadata.unknownMethod??xt(t,"sherpa/unknownMethod")??Mo(t.metadata.methodObservations??[]);return e===void 0?[{message:"Unknown method probe was not captured.",location:"metadata.unknownMethod",fixHint:"Capture a deterministic unknown-method probe and verify it returns -32601."}]:e.ok?[{message:`Unknown method ${e.method} returned success.`,location:"metadata.unknownMethod",fixHint:"Return a JSON-RPC error with code -32601 for unsupported methods."}]:e.errorCode!==-32601?[{message:`Unknown method ${e.method} returned ${String(e.errorCode)} instead of -32601.`,location:"metadata.unknownMethod.errorCode",fixHint:"Use JSON-RPC code -32601 for method-not-found responses."}]:[]}};function Mo(t){return t.find(e=>e.method.toLowerCase().includes("unknown"))}var dn="P007",Ht={id:dn,category:"protocol",severity:"error",title:"stdio framing is clean",description:"Flags non-MCP stdout lines, partial lines, and non-JSON-RPC stdout frames.",check(t){if(t.transport!=="stdio")return[];let e=[];return(t.metadata.stdio?.stdoutLines??Vo(t)).forEach((n,i)=>{if(n.trim()!==""){if(n.includes(`
35
+ `)||n.includes("\r")){e.push({message:"stdio stdout frame contains an embedded newline.",location:`metadata.stdio.stdoutLines[${i}]`,evidence:V(n),fixHint:"Write each JSON-RPC message as one compact JSON line terminated by a single newline."});return}No(n,i,e)}}),t.metadata.stdio?.stdoutHadPartialLine===!0&&e.push({message:"stdio stdout ended with a partial non-newline-delimited frame.",location:"metadata.stdio.stdoutHadPartialLine",fixHint:"Terminate every stdout JSON-RPC frame with a newline."}),e}};function No(t,e,r){let n;try{n=JSON.parse(t)}catch{r.push({message:"stdio stdout line is not valid JSON.",location:`metadata.stdio.stdoutLines[${e}]`,evidence:V(t),fixHint:"Send logs to stderr only and reserve stdout for newline-delimited JSON-RPC messages."});return}(!m(n)||n.jsonrpc!=="2.0")&&r.push({message:"stdio stdout line is not a JSON-RPC 2.0 object.",location:`metadata.stdio.stdoutLines[${e}]`,evidence:V(t),fixHint:"Write only JSON-RPC 2.0 protocol objects to stdout."})}function Vo(t){return t.messages.filter(e=>e.channel==="stdout"&&e.raw!==void 0).map(e=>e.raw??"")}var mn="P008",Dt={id:mn,category:"protocol",severity:"error",title:"HTTP transport contract is valid",description:"Flags invalid streamable HTTP method, content-type, and protocol-version behavior.",check(t){if(t.transport!=="sse"&&t.transport!=="streamable-http")return[];let e=t.metadata.http;if(e===void 0)return[{message:"HTTP transport metadata was not captured.",location:"metadata.http",fixHint:"Capture HTTP request and response contract observations for HTTP MCP transports."}];let r=[],n=e.postAcceptHeader?.toLowerCase()??"";(!n.includes("application/json")||!n.includes("text/event-stream"))&&r.push({message:"HTTP POST Accept header does not include application/json and text/event-stream.",location:"metadata.http.postAcceptHeader",fixHint:"Send Accept: application/json, text/event-stream on MCP HTTP POST requests.",...e.postAcceptHeader!==void 0?{evidence:e.postAcceptHeader}:{}}),e.postContentType!==void 0&&Ot(e.postContentType)!=="application/json"&&r.push({message:"HTTP POST Content-Type is not application/json.",location:"metadata.http.postContentType",evidence:e.postContentType,fixHint:"Use application/json for client-to-server JSON-RPC POST bodies."});let i=e.postResponseContentTypes??[];return i.length===0&&r.push({message:"HTTP POST response content type was not captured.",location:"metadata.http.postResponseContentTypes",fixHint:"Capture whether request POST responses are application/json or text/event-stream."}),i.forEach((o,s)=>{let a=Ot(o);a!=="application/json"&&a!=="text/event-stream"&&r.push({message:`HTTP POST response content type ${o} is not valid for MCP.`,location:`metadata.http.postResponseContentTypes[${s}]`,fixHint:"Return application/json or text/event-stream for MCP request POST responses."})}),e.notificationStatus!==void 0&&e.notificationStatus!==202&&r.push({message:`HTTP notification POST returned ${e.notificationStatus} instead of 202.`,location:"metadata.http.notificationStatus",fixHint:"Return 202 Accepted with an empty body for accepted client notifications."}),(e.notificationBodyBytes??0)>0&&r.push({message:"HTTP notification POST returned a response body.",location:"metadata.http.notificationBodyBytes",fixHint:"Return an empty body for accepted notification POSTs."}),t.transport==="streamable-http"&&ko(t.protocolVersion,e.protocolVersionHeader,r),e.invalidProtocolVersionStatus!==void 0&&e.invalidProtocolVersionStatus!==400&&r.push({message:`Invalid MCP-Protocol-Version returned ${e.invalidProtocolVersionStatus} instead of 400.`,location:"metadata.http.invalidProtocolVersionStatus",fixHint:"Reject invalid MCP-Protocol-Version headers with HTTP 400."}),e.sessionId!==void 0&&e.missingSessionStatus!==void 0&&e.missingSessionStatus!==400&&r.push({message:`Missing MCP-Session-Id returned ${e.missingSessionStatus} instead of 400.`,location:"metadata.http.missingSessionStatus",fixHint:"Reject requests missing a required MCP-Session-Id with HTTP 400."}),r}};function ko(t,e,r){if(t!==void 0){if(e===void 0){r.push({message:"Streamable HTTP request did not include MCP-Protocol-Version after initialization.",location:"metadata.http.protocolVersionHeader",fixHint:"Include MCP-Protocol-Version on every post-initialization HTTP request."});return}e!==t&&r.push({message:`HTTP MCP-Protocol-Version ${e} does not match negotiated ${t}.`,location:"metadata.http.protocolVersionHeader",fixHint:"Send the negotiated protocol version on all post-initialization HTTP requests."})}}var fn=[Pt,Mt,Nt,Vt,Ft,jt,Ht,Dt];var pn="S001",Ut={id:pn,category:"schema",severity:"error",title:"Tool input schema is present",description:"Requires every tool to expose an object inputSchema.",check(t){let e=[];return t.tools.forEach((r,n)=>{m(r.inputSchema)||e.push({message:`Tool ${r.name??n} is missing a valid object inputSchema.`,location:`tools[${n}].inputSchema`,fixHint:"Define inputSchema as a JSON Schema object, even for no-argument tools."})}),e}};var Fo=new Set(["https://json-schema.org/draft/2020-12/schema","https://json-schema.org/draft/2020-12/schema#","http://json-schema.org/draft-07/schema#","https://json-schema.org/draft-07/schema#"]),hn=new Set(["object","array","string","number","integer","boolean","null"]);function gn(t,e){let r=[];return Z(t,e,r),r}function yn(t,e){let r=[];return bn(t,e,r),r}function Te(t,e,r){let n=[];return Le(t,e,r,n),n}function Z(t,e,r){if(typeof t=="boolean")return;if(!m(t)){r.push({path:e,message:"schema must be a JSON object or boolean schema"});return}let n=t.$schema;n!==void 0&&(typeof n!="string"?r.push({path:`${e}.$schema`,message:"$schema must be a string URI"}):Fo.has(n)||r.push({path:`${e}.$schema`,message:`unsupported JSON Schema dialect ${n}`})),jo(t,e,r),Ho(t,e,r),Do(t,e,r),Uo(t,e,r),qo(t,e,r),Jo(t,e,r),zo(t,e,r),qt(t,"allOf",e,r),qt(t,"anyOf",e,r),qt(t,"oneOf",e,r)}function jo(t,e,r){let n=t.type;if(n!==void 0){if(typeof n=="string"){hn.has(n)||r.push({path:`${e}.type`,message:`unsupported schema type ${n}`});return}if(Array.isArray(n)&&n.every(i=>typeof i=="string")){for(let i of n)hn.has(i)||r.push({path:`${e}.type`,message:`unsupported schema type ${i}`});return}r.push({path:`${e}.type`,message:"type must be a string or array of strings"})}}function Ho(t,e,r){let n=t.properties;if(n!==void 0){if(!m(n)){r.push({path:`${e}.properties`,message:"properties must be an object"});return}for(let[i,o]of X(n))Z(o,`${e}.properties.${i}`,r)}}function Do(t,e,r){let n=t.required;n!==void 0&&(!Array.isArray(n)||!n.every(i=>typeof i=="string"))&&r.push({path:`${e}.required`,message:"required must be an array of strings"})}function Uo(t,e,r){let n=t.items;if(n!==void 0){if(x(n)){n.forEach((i,o)=>{Z(i,`${e}.items[${o}]`,r)});return}Z(n,`${e}.items`,r)}}function qo(t,e,r){let n=t.additionalProperties;n===void 0||typeof n=="boolean"||Z(n,`${e}.additionalProperties`,r)}function Jo(t,e,r){t.enum!==void 0&&!Array.isArray(t.enum)&&r.push({path:`${e}.enum`,message:"enum must be an array"})}function zo(t,e,r){let n=t.pattern;if(n!==void 0){if(typeof n!="string"){r.push({path:`${e}.pattern`,message:"pattern must be a string"});return}try{new RegExp(n)}catch{r.push({path:`${e}.pattern`,message:"pattern must be a valid regular expression"})}}}function qt(t,e,r,n){let i=t[e];if(i!==void 0){if(!x(i)||i.length===0){n.push({path:`${r}.${e}`,message:`${e} must be a non-empty array`});return}i.forEach((o,s)=>{Z(o,`${r}.${e}[${s}]`,n)})}}function bn(t,e,r){if(!m(t))return;let n=t.required,i=O(t,"properties")??{};if(n!==void 0)if(!Array.isArray(n)||!n.every(o=>typeof o=="string"))r.push({path:`${e}.required`,message:"required must be an array of strings"});else for(let o of n)o in i||r.push({path:`${e}.required`,message:`required property ${o} is missing from properties`});for(let[o,s]of X(i))bn(s,`${e}.properties.${o}`,r)}function Le(t,e,r,n){if(!(e===!0||e===void 0)){if(e===!1){n.push({path:r,message:"value is rejected by false schema"});return}m(e)&&(Wo(t,e,r,n),Bo(t,e,r,n),Go(t,e,r,n),Qo(t,e,r,n))}}function Wo(t,e,r,n){if(!x(e.enum))return;let i=t===void 0?void 0:G(t);e.enum.some(s=>G(s)===i)||n.push({path:r,message:"value is not one of the allowed enum values"})}function Bo(t,e,r,n){if(!("const"in e))return;let i=e.const;(t===void 0||G(t)!==G(i))&&n.push({path:r,message:"value does not match const"})}function Go(t,e,r,n){let i=es(e);if(i.length>0&&!i.some(o=>ts(t,o))){n.push({path:r,message:`value does not match schema type ${i.join("|")}`});return}m(t)&&Yo(t,e,r,n),Array.isArray(t)&&Xo(t,e,r,n),typeof t=="string"&&Ko(t,e,r,n),typeof t=="number"&&Zo(t,e,r,n)}function Yo(t,e,r,n){let i=O(e,"properties")??{},o=e.required;if(Array.isArray(o))for(let s of o)typeof s=="string"&&!(s in t)&&n.push({path:r,message:`missing required property ${s}`});for(let[s,a]of X(i))s in t&&Le(t[s],a,`${r}.${s}`,n);if(e.additionalProperties===!1)for(let s of Object.keys(t))s in i||n.push({path:`${r}.${s}`,message:"additional property is not allowed"})}function Xo(t,e,r,n){let i=e.items;i===void 0||x(i)||t.forEach((o,s)=>{Le(o,i,`${r}[${s}]`,n)})}function Ko(t,e,r,n){let i=I(e,"pattern"),o=typeof e.minLength=="number"?e.minLength:void 0,s=typeof e.maxLength=="number"?e.maxLength:void 0;i!==void 0&&!new RegExp(i).test(t)&&n.push({path:r,message:"string does not match pattern"}),o!==void 0&&t.length<o&&n.push({path:r,message:`string is shorter than minLength ${o}`}),s!==void 0&&t.length>s&&n.push({path:r,message:`string is longer than maxLength ${s}`})}function Zo(t,e,r,n){let i=typeof e.minimum=="number"?e.minimum:void 0,o=typeof e.maximum=="number"?e.maximum:void 0;i!==void 0&&t<i&&n.push({path:r,message:`number is less than minimum ${i}`}),o!==void 0&&t>o&&n.push({path:r,message:`number is greater than maximum ${o}`})}function Qo(t,e,r,n){let i=e.allOf;x(i)&&i.forEach((a,u)=>{Le(t,a,`${r}.allOf[${u}]`,n)});let o=e.anyOf;x(o)&&!o.some(a=>Te(t,a,r).length===0)&&n.push({path:r,message:"value does not match any anyOf schema"});let s=e.oneOf;x(s)&&s.filter(u=>Te(t,u,r).length===0).length!==1&&n.push({path:r,message:"value must match exactly one oneOf schema"})}function es(t){return typeof t.type=="string"?[t.type]:Array.isArray(t.type)?t.type.filter(e=>typeof e=="string"):[]}function ts(t,e){return t===void 0?!1:e==="null"?t===null:e==="array"?Array.isArray(t):e==="object"?m(t):e==="integer"?typeof t=="number"&&Number.isInteger(t):typeof t===e}var _n="S002",Jt={id:_n,category:"schema",severity:"error",title:"Tool schemas use a supported dialect",description:"Validates input and output schema structure for supported JSON Schema dialects.",check(t){let e=[];return t.tools.forEach((r,n)=>{m(r.inputSchema)&&e.push(...Cn(r.inputSchema,`tools[${n}].inputSchema`)),r.outputSchema!==void 0&&e.push(...Cn(r.outputSchema,`tools[${n}].outputSchema`))}),e}};function Cn(t,e){return gn(t,e).map(r=>({message:r.message,location:r.path,fixHint:"Use valid JSON Schema 2020-12 by default or an explicitly supported draft URI."}))}var Sn="S003",zt={id:Sn,category:"schema",severity:"error",title:"Required properties are declared",description:"Requires every required schema property to be present in properties.",check(t){let e=[];return t.tools.forEach((r,n)=>{m(r.inputSchema)&&e.push(...yn(r.inputSchema,`tools[${n}].inputSchema`).map(i=>({message:i.message,location:i.path,fixHint:"Declare every required argument under the same schema object properties map."})))}),e}};var Rn="S004",rs=/^[A-Za-z0-9_.-]{1,128}$/,Wt={id:Rn,category:"schema",severity:"warning",title:"Tool names are stable",description:"Flags tool names outside the recommended ASCII letters, digits, underscore, hyphen, and dot format.",check(t){let e=[];return t.tools.forEach((r,n)=>{(typeof r.name!="string"||!rs.test(r.name))&&e.push({message:`Tool name ${r.name??"<missing>"} is not stable across MCP clients.`,location:`tools[${n}].name`,fixHint:"Use 1-128 ASCII letters, digits, underscores, hyphens, or dots for tool names."})}),e}};var wn="S005",Bt={id:wn,category:"schema",severity:"warning",title:"Tool output schema is honored",description:"Checks sampled safe structuredContent against declared outputSchema.",check(t){let e=[];return t.tools.forEach((r,n)=>{if(!m(r.outputSchema))return;let i=r.outputSchema;(r.calls??[]).forEach((o,s)=>{o.safe===!1||o.isError===!0||e.push(...ns(i,o,`tools[${n}].calls[${s}]`))})}),e}};function ns(t,e,r){let n=Kr(e);return n===void 0?[{message:"Tool declares outputSchema but sampled call did not return structuredContent.",location:`${r}.structuredContent`,fixHint:"Return structuredContent that conforms to the declared outputSchema for successful calls."}]:Te(n,t,`${r}.structuredContent`).map(i=>({message:i.message,location:i.path,fixHint:"Align successful structuredContent with the tool outputSchema or update the schema."}))}var xn=[Ut,Jt,zt,Wt,Bt];var On="X001",Gt={id:On,category:"security",severity:"error",title:"Filesystem access stays within declared roots",description:"Flags traversal, null-byte paths, and file resources outside allowed roots.",check(t){let e=[],r=t.metadata.allowedRoots??[];return(t.metadata.filesystemAccess??[]).forEach((n,i)=>{e.push(...is(n,r,`metadata.filesystemAccess[${i}]`))}),t.resources.forEach((n,i)=>{e.push(...os(n,r,`resources[${i}]`))}),e}};function is(t,e,r){let n=[];(ss(t.path)||En(t.path))&&t.outcome!=="rejected"&&n.push({message:`Filesystem access accepted unsafe path ${t.path}.`,location:`${r}.path`,evidence:V(t.reason??t.path),fixHint:"Reject traversal and null-byte paths before resolving filesystem access."});let o=t.allowedRoot!==void 0?[t.allowedRoot]:e;return t.outcome==="allowed"&&t.resolvedPath!==void 0&&o.length>0&&(vn(t.resolvedPath,o)||n.push({message:`Filesystem access resolved outside allowed roots: ${t.resolvedPath}.`,location:`${r}.resolvedPath`,evidence:o.join(", "),fixHint:"Resolve real paths and reject symlinks or traversals that escape allowed roots."})),n}function os(t,e,r){if(!t.uri?.startsWith("file://"))return[];let n=as(t.uri),i=[];return n===void 0?[{message:`Resource URI ${t.uri} is not a valid file URI.`,location:`${r}.uri`,fixHint:"Expose valid RFC 3986 file URIs for filesystem resources."}]:(En(n)&&i.push({message:`Resource URI contains path traversal: ${t.uri}.`,location:`${r}.uri`,fixHint:"Normalize resource URIs and never expose ../ traversal segments."}),e.length>0&&Gr(n)&&!vn(n,e)&&i.push({message:`File resource ${t.uri} is outside allowed roots.`,location:`${r}.uri`,evidence:e.join(", "),fixHint:"Only list file resources under configured MCP roots or allowed directories."}),i)}function ss(t){return t.includes("\0")||t.toLowerCase().includes("%00")}function En(t){return $n(t).replace(/\\/g,"/").split("/").includes("..")}function vn(t,e){let r=St(t);return e.some(n=>{let i=St(n).replace(/\/$/,"");return r===i||r.startsWith(`${i}/`)})}function as(t){try{let e=new URL(t);return $n(e.pathname)}catch{return}}function $n(t){try{return decodeURIComponent(t)}catch{return t}}var Tn="X002",us=/(^|[_-])(path|file|filename|directory|dir|root|repo_path|workspace)([_-]|$)/i,Yt={id:Tn,category:"security",severity:"warning",title:"Path parameters are constrained",description:"Flags path-like string parameters without patterns, enums, or documented root boundaries.",check(t){let e=[];return t.tools.forEach((r,n)=>{m(r.inputSchema)&&Ln(r,r.inputSchema,`tools[${n}].inputSchema`,e)}),e}};function Ln(t,e,r,n){let i=O(e,"properties");if(i!==void 0)for(let[o,s]of Object.entries(i)){let a=`${r}.properties.${o}`;m(s)&&(cs(t,o,s)&&n.push({message:`Path-like parameter ${o} is unconstrained.`,location:a,fixHint:"Constrain path parameters with a safe pattern, enum, or documented allowed root behavior."}),Ln(t,s,a,n))}}function cs(t,e,r){if(!us.test(e)||!ls(r)||ds(r))return!1;let n=`${t.description??""} ${I(r,"description")??""}`.toLowerCase();return!(n.includes("allowed root")||n.includes("allowed director")||n.includes("workspace root")||n.includes("within root")||n.includes("read-only"))}function ls(t){let e=t.type;return e===void 0||e==="string"||Array.isArray(e)&&e.some(r=>r==="string")}function ds(t){return ms(t.pattern)||fs(t.enum)||t.const!==void 0||typeof t.format=="string"&&t.format.toLowerCase().includes("path")}function ms(t){return typeof t=="string"&&t.trim().length>0}function fs(t){return Array.isArray(t)&&t.length>0}var In="X003",ps=/(^|[_-])(url|uri|endpoint|callback|webhook|redirect)([_-]|$)/i,Xt={id:In,category:"security",severity:"warning",title:"URL parameters are constrained",description:"Flags URL-like string parameters without scheme, host, enum, or allowlist constraints.",check(t){let e=[];return t.tools.forEach((r,n)=>{m(r.inputSchema)&&An(r,r.inputSchema,`tools[${n}].inputSchema`,e)}),e}};function An(t,e,r,n){let i=O(e,"properties");if(i!==void 0)for(let[o,s]of Object.entries(i)){let a=`${r}.properties.${o}`;m(s)&&(hs(t,o,s)&&n.push({message:`URL-like parameter ${o} is unconstrained.`,location:a,fixHint:"Constrain URL parameters with an enum, host allowlist pattern, or approved endpoint list."}),An(t,s,a,n))}}function hs(t,e,r){if(!ps.test(e)||!gs(r)||ys(r))return!1;let n=`${t.description??""} ${I(r,"description")??""}`.toLowerCase();return!(n.includes("allowlist")||n.includes("approved host")||n.includes("approved endpoint"))}function gs(t){let e=t.type;return e===void 0||e==="string"||Array.isArray(e)&&e.some(r=>r==="string")}function ys(t){return bs(t.pattern)||Cs(t.enum)||t.const!==void 0}function bs(t){return typeof t=="string"&&t.trim().length>0}function Cs(t){return Array.isArray(t)&&t.length>0}var Pn="X004",_s=[{name:"private key block",pattern:/-----BEGIN [A-Z ]*PRIVATE KEY-----/},{name:"authorization bearer token",pattern:/Authorization\s*:\s*Bearer\s+[A-Za-z0-9._~+/=-]{8,}/i},{name:"OpenAI-style secret key",pattern:/\bsk_(?:live|test|proj)_[A-Za-z0-9_-]{8,}\b/},{name:"GitHub token",pattern:/\bgh[opsu]_[A-Za-z0-9_]{12,}\b/},{name:"AWS access key",pattern:/\bAKIA[0-9A-Z]{16}\b/},{name:"secret assignment",pattern:/\b(?:api[_-]?key|secret|token|password)\s*[:=]\s*["']?[A-Za-z0-9._~+/=-]{12,}/i}],Kt={id:Pn,category:"security",severity:"error",title:"Secrets are not exposed",description:"Flags plaintext tokens, private keys, and authorization headers in MCP-visible text.",check(t){let e=[];return t.tools.forEach((r,n)=>{R(e,`tools[${n}].name`,r.name),R(e,`tools[${n}].description`,r.description),r.calls?.forEach((i,o)=>{A(e,`tools[${n}].calls[${o}].result`,i.result),A(e,`tools[${n}].calls[${o}].content`,i.content),A(e,`tools[${n}].calls[${o}].structuredContent`,i.structuredContent)})}),t.resources.forEach((r,n)=>{R(e,`resources[${n}].uri`,r.uri),R(e,`resources[${n}].name`,r.name),R(e,`resources[${n}].description`,r.description),r.reads?.forEach((i,o)=>{A(e,`resources[${n}].reads[${o}].result`,i.result)})}),t.prompts.forEach((r,n)=>{R(e,`prompts[${n}].name`,r.name),R(e,`prompts[${n}].description`,r.description),A(e,`prompts[${n}].getResult`,r.getResult)}),t.errors.forEach((r,n)=>{R(e,`errors[${n}].message`,r.message),A(e,`errors[${n}].data`,r.data)}),t.messages.forEach((r,n)=>{R(e,`messages[${n}].raw`,r.raw),A(e,`messages[${n}].message`,r.message)}),t.metadata.scanText?.forEach(r=>{R(e,r.path,r.text)}),e.flatMap(r=>Ss(r))}};function Ss(t){return _s.filter(e=>e.pattern.test(t.text)).map(e=>({message:`Potential plaintext secret detected: ${e.name}.`,location:t.path,evidence:V(t.text),fixHint:"Remove the secret from MCP-visible text and return a redacted placeholder instead."}))}function R(t,e,r){r!==void 0&&r.trim()!==""&&t.push({path:e,text:r})}function A(t,e,r){if(r!=null){if(typeof r=="string"){R(t,e,r);return}if(!(typeof r=="number"||typeof r=="boolean")){if(x(r)){r.forEach((n,i)=>{A(t,`${e}[${i}]`,n)});return}if(m(r))for(let[n,i]of X(r))A(t,`${e}.${n}`,i)}}}var Mn=[Gt,Yt,Xt,Kt];var Zt=[...fn,...xn,...Mn,...rn];var ue=class{#e;constructor(e=Zt){this.#e=Rs(e)}getRules(){return this.#e}getEnabledRules(e={}){let r=q(e);return this.#e.map(n=>Os(n,r)).filter(n=>n.enabled).map(n=>n.rule)}};function Nn(t=Zt){return new ue(t)}function Rs(t){let e=t.flatMap(n=>Vn(n)),r=new Set;for(let n of e){if(r.has(n.id))throw new Error(`Duplicate MCP lint rule id: ${n.id}`);r.add(n.id)}return e}function Vn(t){if(ws(t))return t;if(kn(t))return[t];if(!xs(t))return[];let e=[];return t.default!==void 0&&e.push(...Vn(t.default)),t.rule!==void 0&&e.push(t.rule),t.rules!==void 0&&e.push(...t.rules),e}function ws(t){return Array.isArray(t)}function xs(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!kn(t)}function Os(t,e){let r=new Set(e.includedRules),n=new Set(e.ignoredRules),i=e.ruleOverrides[t.id],o=(r.size===0||r.has(t.id))&&!n.has(t.id)&&i?.enabled!==!1,s=i?.severity??t.severity;return{rule:s===t.severity?t:{...t,severity:s},enabled:o}}function kn(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=t;return typeof e.id=="string"&&(e.category==="protocol"||e.category==="schema"||e.category==="security"||e.category==="performance")&&(e.severity==="error"||e.severity==="warning"||e.severity==="info")&&typeof e.title=="string"&&typeof e.description=="string"&&typeof e.check=="function"}var Qt=class{#e;#r;#t;constructor(e={}){this.#e=e.registry??new ue(e.rules),this.#r=q(e.config??{}),this.#t=e.now??(()=>new Date)}async run(e){let r=q(e.config??this.#r),n=Br(e.context,r),i=this.#e.getEnabledRules(r),o=[];for(let u of i)(Es(await u.check(n)).violations??[]).forEach((l,p)=>{o.push($s(u,l,p))});let s=Ee(o,{severityWeights:r.severityWeights}),a=r.failUnder??r.thresholds.minimumScore??0;return{id:ae({kind:"mcp-lint-result",transport:n.transport,protocolVersion:n.protocolVersion??null,score:s.score,violations:o.map(u=>u.id),rules:i.map(u=>u.id)}),server:Ts(n),score:s.score,maxScore:s.maxScore,passed:s.score>=a,violations:o,summary:ve(o),rulesRun:i.map(u=>u.id),lintedAt:this.#t().toISOString()}}};async function jn(t,e={}){return new Qt(e).run(t)}function Es(t){return vs(t)?{violations:t}:t}function vs(t){return Array.isArray(t)}function $s(t,e,r){return{id:ae({kind:"mcp-lint-violation",ruleId:t.id,category:t.category,severity:t.severity,message:e.message,location:e.location??null,evidence:e.evidence??null,index:r}),ruleId:t.id,category:t.category,severity:t.severity,message:e.message,fixHint:e.fixHint,...e.location!==void 0?{location:e.location}:{},...e.evidence!==void 0?{evidence:e.evidence}:{}}}function Ts(t){let e={transport:t.transport,capabilities:Object.keys(t.capabilities).sort(),toolCount:t.tools.length,resourceCount:t.resources.length,promptCount:t.prompts.length},r=Fn(t.serverInfo,"name"),n=Fn(t.serverInfo,"version");return t.protocolVersion!==void 0&&(e.protocolVersion=t.protocolVersion),r!==void 0&&(e.name=r),n!==void 0&&(e.version=n),e}function Fn(t,e){let r=t?.[e];return typeof r=="string"?r:void 0}var Q="1.0.0",z=["protocol","schema","security","performance"],E=["security","protocol","schema","performance"];var W={protocol:"Protocol",schema:"Schema",security:"Security",performance:"Performance"};function F(t){return[...t].sort(Hn)}function Hn(t,e){return ee(t.category)-ee(e.category)||k(t.severity)-k(e.severity)||t.ruleId.localeCompare(e.ruleId)||t.id.localeCompare(e.id)||t.message.localeCompare(e.message)||(t.location??"").localeCompare(e.location??"")||(t.evidence??"").localeCompare(e.evidence??"")}function k(t){return t==="error"?0:t==="warning"?1:2}function ee(t){let e=E.indexOf(t);return e===-1?E.length:e}function er(t){return{id:t.id,ruleId:t.ruleId,category:t.category,categoryLabel:W[t.category],severity:t.severity,message:t.message,fixHint:t.fixHint,...t.location!==void 0?{location:t.location}:{},...t.evidence!==void 0?{evidence:t.evidence}:{}}}function B(t){return{protocol:t.filter(e=>e.category==="protocol"),schema:t.filter(e=>e.category==="schema"),security:t.filter(e=>e.category==="security"),performance:t.filter(e=>e.category==="performance")}}function tr(t){let e=new Map;for(let r of F(t.violations)){let n=e.get(r.ruleId);n===void 0?e.set(r.ruleId,[r]):n.push(r)}return[...e.entries()].map(([r,n])=>Ls(r,n)).sort(Dn)}function Dn(t,e){return ee(t.category)-ee(e.category)||k(t.worstSeverity)-k(e.worstSeverity)||t.ruleId.localeCompare(e.ruleId)||t.message.localeCompare(e.message)}function Ls(t,e){let r=F(e),n=r[0];if(n===void 0)throw new Error(`Cannot summarize failing rule ${t} without violations.`);return{ruleId:t,category:n.category,categoryLabel:W[n.category],worstSeverity:Is(r),count:r.length,message:n.message,fixHint:n.fixHint,violationIds:r.map(i=>i.id)}}function Is(t){return t.reduce((e,r)=>k(r.severity)<k(e)?r.severity:e,"info")}function rr(t){return{protocol:Ie("protocol",t.violations),schema:Ie("schema",t.violations),security:Ie("security",t.violations),performance:Ie("performance",t.violations)}}function Ie(t,e){let r=e.filter(o=>o.category===t),n=Ee(r),i=ve(r);return{category:t,label:W[t],score:n.score,maxScore:n.maxScore,baseline:n.baseline,deduction:n.deduction,violationCount:i.violationCount,errorCount:i.errorCount,warningCount:i.warningCount,infoCount:i.infoCount,failingRuleIds:As(F(r))}}function As(t){let e=[],r=new Set;for(let n of t)r.has(n.ruleId)||(r.add(n.ruleId),e.push(n.ruleId));return e}function Un(t){return{score:t.score,maxScore:t.maxScore,passed:t.passed,totalViolationCount:t.violations.length,summary:{errorCount:t.summary.errorCount,warningCount:t.summary.warningCount,infoCount:t.summary.infoCount,violationCount:t.summary.violationCount}}}function v(t,e={}){return{schemaVersion:Q,id:t.id,server:Ps(t.server),score:t.score,maxScore:t.maxScore,passed:t.passed,compositeScore:Un(t),categorySubscores:rr(t),violations:F(t.violations).map(er),failingRules:tr(t),metadata:{lintResultId:t.id,lintedAt:t.lintedAt,schemaVersion:Q,rulesRun:[...t.rulesRun],...e.generatedAt!==void 0?{generatedAt:e.generatedAt}:{}},resultSummary:{errorCount:t.summary.errorCount,warningCount:t.summary.warningCount,infoCount:t.summary.infoCount,violationCount:t.summary.violationCount}}}function Ps(t){return{transport:t.transport,...t.protocolVersion!==void 0?{protocolVersion:t.protocolVersion}:{},...t.name!==void 0?{name:t.name}:{},...t.version!==void 0?{version:t.version}:{},capabilities:[...t.capabilities],toolCount:t.toolCount,resourceCount:t.resourceCount,promptCount:t.promptCount}}var te=class extends Error{exitCode;constructor(e,r=2){super(e),this.name="CliError",this.exitCode=r}};function ce(t){return new te(t,2)}function h(t){return new te(t,2)}function qn(t){return new te(t,3)}function Ae(t){return t instanceof Error?t.message:String(t)}function Pe(t){return t instanceof te?t.exitCode:t instanceof C?3:2}var j=".aimcp-lint.json",sr=["terminal","json","markdown"],ks={command:"node ./server.mjs",format:"terminal",failUnder:80,ignore:[],only:[],severityOverrides:{},ruleOverrides:{},thresholds:{},severityWeights:{},watch:{paths:["."]},detailed:!1,quiet:!1,verbose:!1};function Fs(t){return sr.includes(t)}function Bn(){return`${JSON.stringify(ks,null,2)}
36
+ `}async function re(t){let e=await js({cwd:t.cwd,...t.options.config!==void 0?{configPath:t.options.config}:{}}),r=e.config,n=t.options.format??r.format??"terminal",i=t.options.failUnder??r.failUnder,o=Ne(t.options.ignore??(t.options.only!==void 0?[]:[...r.ignore??[],...r.ignoredRules??[]])),s=Ne(t.options.only??[...r.only??[],...r.includedRules??[]]),a=t.options.quiet===!0||r.quiet===!0,u=a?!1:t.options.verbose===!0||r.verbose===!0,c=t.options.detailed??r.detailed??!1,d=Gs(r),l={ignoredRules:o,includedRules:s};i!==void 0&&(l.failUnder=i),r.severityOverrides!==void 0&&(l.severityOverrides=r.severityOverrides),r.ruleOverrides!==void 0&&(l.ruleOverrides=r.ruleOverrides),r.thresholds!==void 0&&(l.thresholds=r.thresholds),r.severityWeights!==void 0&&(l.severityWeights=r.severityWeights);let p=Ds(l),b={format:n,ignoredRules:o,includedRules:s,watchPaths:Xs(r.watch),configPath:e.sourcePath,configExists:e.exists,verbose:u,quiet:a,detailed:c,lintConfig:p,...d!==void 0?{commandTokens:d}:{}};return i!==void 0&&(b.failUnder=i),b}async function js(t){if(t.configPath!==void 0){let i=Hs(t.cwd,t.configPath),o;try{o=await Jn(i,"utf8")}catch(a){throw Wn(a,"ENOENT")?h(`Config file not found: ${i}`):h(`Could not read config file ${i}: ${ir(a)}`)}let s;try{s=JSON.parse(o)}catch(a){throw h(`Malformed ${j}: ${ir(a)}`)}return{config:zn(s,i),sourcePath:i,exists:!0}}let e=le(t.cwd),r=le("/"),n=[];for(;;){let i=le(e,j);n.push(i);try{let o=await Jn(i,"utf8"),s;try{s=JSON.parse(o)}catch(a){throw h(`Malformed ${i}: ${ir(a)}`)}return{config:zn(s,i),sourcePath:i,exists:!0}}catch(o){if(Wn(o,"ENOENT")){if(e===r||e==="/")return{config:{},sourcePath:n[0],exists:!1};e=Ns(e);continue}throw o}}}function Hs(t,e){return e!==void 0?Vs(e)?e:le(t,e):le(t,j)}function Ds(t){let e={ignoredRules:t.ignoredRules,includedRules:t.includedRules};return t.failUnder!==void 0&&(e.failUnder=t.failUnder),t.severityOverrides!==void 0&&(e.severityOverrides=t.severityOverrides),t.ruleOverrides!==void 0&&(e.ruleOverrides=t.ruleOverrides),t.thresholds!==void 0&&(e.thresholds=t.thresholds),t.severityWeights!==void 0&&(e.severityWeights=t.severityWeights),e}function zn(t,e){if(!P(t))throw h(`${e} must contain a JSON object.`);let r={};if(t.command!==void 0&&(r.command=Us(t.command,e)),t.format!==void 0){if(typeof t.format!="string"||!Fs(t.format))throw h(`${e}: format must be terminal, json, or markdown.`);r.format=t.format}if(Zs(t,"failUnder",e,n=>{r.failUnder=n}),Me(t,"ignore",e,n=>{r.ignore=n}),Me(t,"only",e,n=>{r.only=n}),Me(t,"ignoredRules",e,n=>{r.ignoredRules=n}),Me(t,"includedRules",e,n=>{r.includedRules=n}),t.severityOverrides!==void 0&&(r.severityOverrides=qs(t.severityOverrides,e)),t.ruleOverrides!==void 0&&(r.ruleOverrides=Js(t.ruleOverrides,e)),t.thresholds!==void 0&&(r.thresholds=zs(t.thresholds,e)),t.severityWeights!==void 0&&(r.severityWeights=Bs(t.severityWeights,e)),t.watch!==void 0&&(r.watch=Ys(t.watch,e)),t.detailed!==void 0){if(typeof t.detailed!="boolean")throw h(`${e}: detailed must be a boolean.`);r.detailed=t.detailed}if(t.quiet!==void 0){if(typeof t.quiet!="boolean")throw h(`${e}: quiet must be a boolean.`);r.quiet=t.quiet}if(t.verbose!==void 0){if(typeof t.verbose!="boolean")throw h(`${e}: verbose must be a boolean.`);r.verbose=t.verbose}return r}function Us(t,e){if(typeof t=="string"&&t.trim()!=="")return t.trim();if(Gn(t)&&t.length>0)return t;throw h(`${e}: command must be a non-empty string or a non-empty array of strings.`)}function qs(t,e){if(!P(t))throw h(`${e}: severityOverrides must be an object mapping rule IDs to error, warning, or info.`);let r=new Set(["error","warning","info"]);for(let[n,i]of Object.entries(t))if(!r.has(i))throw h(`${e}: severityOverrides.${n} must be error, warning, or info.`);return t}function Js(t,e){if(!P(t))throw h(`${e}: ruleOverrides must be an object.`);for(let[r,n]of Object.entries(t)){if(!P(n))throw h(`${e}: ruleOverrides.${r} must be an object.`);if(n.enabled!==void 0&&typeof n.enabled!="boolean")throw h(`${e}: ruleOverrides.${r}.enabled must be a boolean.`);if(n.severity!==void 0&&!new Set(["error","warning","info"]).has(n.severity))throw h(`${e}: ruleOverrides.${r}.severity must be error, warning, or info.`);if(n.thresholds!==void 0){if(!P(n.thresholds))throw h(`${e}: ruleOverrides.${r}.thresholds must be an object of numbers.`);for(let[i,o]of Object.entries(n.thresholds))if(typeof o!="number"||!Number.isFinite(o)||o<0)throw h(`${e}: ruleOverrides.${r}.thresholds.${i} must be a non-negative finite number.`)}}return t}function zs(t,e){if(!P(t))throw h(`${e}: thresholds must be an object of numbers.`);for(let[r,n]of Object.entries(t))if(typeof n!="number"||!Number.isFinite(n)||n<0)throw h(`${e}: thresholds.${r} must be a non-negative finite number.`);return t}var Ws=new Set(["error","warning","info"]);function Bs(t,e){if(!P(t))throw h(`${e}: severityWeights must be an object with optional error, warning, and info keys.`);for(let[r,n]of Object.entries(t)){if(!Ws.has(r))throw h(`${e}: severityWeights.${r} is not a valid key; expected error, warning, or info.`);if(typeof n!="number"||!Number.isFinite(n))throw h(`${e}: severityWeights.${r} must be a finite number.`)}return t}function Gs(t){if(t.command!==void 0)return typeof t.command=="string"?t.command.split(/\s+/u):t.command}function Ys(t,e){if(Array.isArray(t))return or(t,`${e}: watch`);if(!P(t))throw h(`${e}: watch must be an object or an array of paths.`);return t.paths===void 0?{}:{paths:or(t.paths,`${e}: watch.paths`)}}function Xs(t){return t===void 0?[]:Array.isArray(t)?Ne(t):Ne(Ks(t)?t.paths??[]:[])}function Ks(t){return!Array.isArray(t)}function Zs(t,e,r,n){let i=t[e];if(i!==void 0){if(typeof i!="number"||!Number.isFinite(i)||i<0)throw h(`${r}: ${e} must be a non-negative finite number.`);n(i)}}function Me(t,e,r,n){let i=t[e];i!==void 0&&n(or(i,`${r}: ${e}`))}function or(t,e){if(!Gn(t))throw h(`${e} must be an array of strings.`);return t.map(r=>r)}function Gn(t){return Array.isArray(t)&&t.every(e=>typeof e=="string")}function Ne(t){return Array.from(new Set(t.filter(e=>e.trim()!=="")))}function P(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Wn(t,e){return P(t)&&t.code===e}function ir(t){return t instanceof Error?t.message:String(t)}function Yn(){return new N("init").description(`create ${j} in the current directory`).option("--force","overwrite an existing config file").action(async t=>{ar.exitCode=await ta({force:t.force===!0})})}async function ta(t={}){let e=t.cwd??ar.cwd(),r=t.stdout??ar.stdout,n=ea(e,j);try{await Qs(n,Bn(),{encoding:"utf8",flag:t.force===!0?"w":"wx"})}catch(i){throw ra(i,"EEXIST")?h(`${j} already exists. Re-run with --force to overwrite it.`):i}return r.write(`Created ${j}
37
+ `),0}function ra(t,e){return typeof t=="object"&&t!==null&&"code"in t&&t.code===e}import fr from"process";import cr from"process";var na="NO_COLOR",Xn="FORCE_COLOR";function Kn(t){return cr.env[na]!==void 0?!1:cr.env[Xn]!==void 0?cr.env[Xn]!=="0":t.isTTY===!0}import{Buffer as ia}from"buffer";import{performance as dr}from"perf_hooks";var de="0.0.1";async function Qn(t){let e=oa(),r=t.verbose===!0&&t.stderr!==void 0,n=new xe({command:t.serverCommand.command,args:t.serverCommand.args,cwd:t.cwd,verbose:r,...r?{logger:Ca(t.stderr)}:{}});try{t.diagnostics?.(`Starting ${t.serverCommand.display}`),await n.connect(),t.diagnostics?.("Initializing MCP server");let i=await sa(n,e);t.diagnostics?.("Collecting tools/list");let o=await Ve(n,e,"tools/list","toolsListMs");t.diagnostics?.("Collecting resources/list");let s=await Ve(n,e,"resources/list","resourcesListMs");t.diagnostics?.("Collecting prompts/list");let a=await Ve(n,e,"prompts/list","promptsListMs");t.diagnostics?.("Checking unknown method behavior");let u=await Ve(n,e,"sherpa/unknownMethod");return u.observation!==void 0&&(e.unknownMethod=u.observation),Wr({transport:"stdio",initialize:i.observation,initializeResult:i.result,capabilities:i.result.capabilities??{},...i.result.serverInfo!==void 0?{serverInfo:i.result.serverInfo}:{},tools:da(ke(w(o.result)?.tools)),resources:fa(ke(w(s.result)?.resources)),prompts:ha(ke(w(a.result)?.prompts)),messages:e.messages,timings:e.timings,errors:e.errors,metadata:aa(e),config:t.config})}finally{await n.disconnect()}}async function ei(t){return await jn({context:t.context,config:t.config})}function oa(){let t=0;return{nextId:()=>(t+=1,t),messages:[],stdoutLines:[],errors:[],methodObservations:[],timings:{},listPayloadBytes:{}}}async function sa(t,e){let r=e.nextId(),n={protocolVersion:Y,capabilities:{},clientInfo:{name:"aimcp-lint",version:de}},i=ti(r,"initialize",n);e.messages.push({direction:"client-to-server",phase:"initialize",message:i});let o=dr.now(),s=await t.initialize(n);e.timings.initializeMs=lr(o);let a=ri(r,s);return e.messages.push({direction:"server-to-client",phase:"initialize",message:a}),e.stdoutLines.push(JSON.stringify(a)),e.messages.push({direction:"client-to-server",phase:"post-initialize",message:{jsonrpc:"2.0",method:"notifications/initialized"}}),{result:s,observation:{request:i,response:a,result:s,completed:!0,initializedNotificationSent:!0}}}async function Ve(t,e,r,n){let i=e.nextId(),o=ti(i,r);e.messages.push({direction:"client-to-server",phase:"post-initialize",message:o});let s=dr.now();try{let a=await t.request(r),u=lr(s);Zn(e.timings,n,u);let c=ri(i,a),d=me(a);e.messages.push({direction:"server-to-client",phase:"post-initialize",message:c}),e.stdoutLines.push(JSON.stringify(c)),la(e,r,a);let l={method:r,ok:!0,result:a,responseBytes:d};return e.methodObservations.push(l),{result:a,observation:l}}catch(a){let u=lr(s);if(Zn(e.timings,n,u),a instanceof H){let l=ua(i,a.responseError);e.messages.push({direction:"server-to-client",phase:"post-initialize",message:l}),e.stdoutLines.push(JSON.stringify(l));let p=ca(r,a.responseError),b={method:r,ok:!1,errorCode:a.responseError.code,responseBytes:me(l)};return e.errors.push(p),e.methodObservations.push(b),{result:void 0,observation:b}}let c={method:r,message:ba(a)},d={method:r,ok:!1};return e.errors.push(c),e.methodObservations.push(d),{result:void 0,observation:d}}}function aa(t){return{supportedProtocolVersions:[Y],stdio:{stdoutLines:t.stdoutLines,stdoutHadPartialLine:!1},methodObservations:t.methodObservations,listPayloadBytes:t.listPayloadBytes,...t.unknownMethod!==void 0?{unknownMethod:t.unknownMethod}:{}}}function ti(t,e,r){return{jsonrpc:"2.0",id:t,method:e,...r!==void 0?{params:r}:{}}}function ri(t,e){return{jsonrpc:"2.0",id:t,result:e}}function ua(t,e){return{jsonrpc:"2.0",id:t,error:{code:e.code,message:e.message,...e.data!==void 0?{data:e.data}:{}}}}function ca(t,e){return{method:t,code:e.code,message:e.message,...e.data!==void 0?{data:e.data}:{}}}function Zn(t,e,r){e!==void 0&&(t[e]=r)}function la(t,e,r){e==="tools/list"?t.listPayloadBytes.tools=me(w(r)?.tools??r):e==="resources/list"?t.listPayloadBytes.resources=me(w(r)?.resources??r):e==="prompts/list"&&(t.listPayloadBytes.prompts=me(w(r)?.prompts??r))}function da(t){return t.map(ma).filter(Fe)}function ma(t){let e=w(t);if(e===void 0)return;let r=w(e.annotations);return{...$(e,"name"),...$(e,"description"),...e.inputSchema!==void 0?{inputSchema:e.inputSchema}:{},...e.outputSchema!==void 0?{outputSchema:e.outputSchema}:{},...r!==void 0?{annotations:r}:{}}}function fa(t){return t.map(pa).filter(Fe)}function pa(t){let e=w(t);if(e!==void 0)return{...$(e,"uri"),...$(e,"name"),...$(e,"description"),...$(e,"mimeType"),...typeof e.size=="number"&&Number.isFinite(e.size)?{size:e.size}:{}}}function ha(t){return t.map(ga).filter(Fe)}function ga(t){let e=w(t);if(e===void 0)return;let r=ke(e.arguments).map(ya).filter(Fe);return{...$(e,"name"),...$(e,"description"),...r.length>0?{arguments:r}:{}}}function ya(t){let e=w(t);if(e!==void 0)return{...$(e,"name"),...$(e,"description"),...typeof e.required=="boolean"?{required:e.required}:{}}}function $(t,e){let r=t[e];return typeof r=="string"?{[e]:r}:{}}function ke(t){return Array.isArray(t)?t:[]}function w(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function lr(t){return Math.max(0,Math.round(dr.now()-t))}function me(t){return ia.byteLength(JSON.stringify(t)??"null","utf8")}function Fe(t){return t!==void 0}function ba(t){return t instanceof Error?t.message:String(t)}function Ca(t){let e="debug",r=(n,i,o)=>{let s=o===void 0?"":` ${JSON.stringify(o)}`;t.write(`${n.toUpperCase()} ${i}${s}
38
+ `)};return{debug:(n,i)=>{r("debug",n,i)},info:(n,i)=>{r("info",n,i)},warn:(n,i)=>{r("warn",n,i)},error:(n,i)=>{r("error",n,i)},getLevel:()=>e,setLevel:n=>{e=n}}}var si=yr(oi(),1);function ai(t,e){let r=v(t),n=si.default.createColors(e.colors),i=[];return wa(i,r,n),xa(i,r,n),Oa(i,r,n),Ea(i,r,e,n),va(i,r,n),$a(i,r,n),i.join(`
39
+ `)}function wa(t,e,r){let n=e.passed?"PASS":"FAIL",i=e.passed?r.green:r.red;t.push(""),t.push(i(r.bold("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"))),t.push(i(r.bold(`\u2502 Score: ${String(e.score).padStart(3)}/${String(e.maxScore).padEnd(3)} ${n.padEnd(17)} \u2502`))),t.push(i(r.bold("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518")))}function xa(t,e,r){let n=e.server;if(t.push(""),t.push(r.bold("Server")),t.push(` Transport: ${n.transport}${n.protocolVersion!==void 0?` (v${n.protocolVersion})`:""}`),n.name!==void 0){let o=n.version!==void 0?` v${n.version}`:"";t.push(` Name: ${n.name}${o}`)}let i=n.capabilities.length>0?n.capabilities.join(", "):"none";t.push(` Tools: ${n.toolCount} | Resources: ${n.resourceCount} | Prompts: ${n.promptCount}`),t.push(` Capabilities: ${i}`)}function Oa(t,e,r){t.push(""),t.push(r.bold("Category Subscores")),t.push(` ${r.dim("Category".padEnd(12))} ${r.dim("Score".padEnd(9))} ${r.dim("Violations".padEnd(11))} ${r.dim("Errors".padEnd(7))} ${r.dim("Warnings".padEnd(9))} ${r.dim("Info".padEnd(5))} ${r.dim("Failing Rules")}`);for(let n of z){let i=e.categorySubscores[n],o=`${i.score}/${i.maxScore}`,s=i.failingRuleIds.length===0?"-":i.failingRuleIds.join(", "),u=i.violationCount>0?r.yellow:r.green;t.push(` ${u(i.label.padEnd(12))} ${o.padEnd(9)} ${r.bold(String(i.violationCount).padEnd(11))} ${String(i.errorCount).padEnd(7)} ${String(i.warningCount).padEnd(9)} ${String(i.infoCount).padEnd(5)} ${s}`)}}function Ea(t,e,r,n){if(t.push(""),t.push(n.bold("Violations")),e.violations.length===0){t.push(` ${n.green("No violations found.")}`);return}let i=B(e.violations);for(let o of E){let s=i[o];if(s.length===0)continue;t.push("");let a=`${s[0]?.categoryLabel??o} (${s.length})`;t.push(` ${n.bold(a)}`);for(let u of s){let c=ui(u.severity,n),d=n.dim(`[${u.ruleId}]`),l=c(u.severity.toUpperCase());t.push(` ${d} ${l} ${u.message}`),u.location!==void 0&&t.push(` ${n.dim(`Location: ${u.location}`)}`),u.evidence!==void 0&&t.push(` Evidence: ${u.evidence}`),r.detailed&&t.push(` ${n.dim(`Fix: ${u.fixHint}`)}`)}}}function va(t,e,r){if(t.push(""),t.push(r.bold("Failing Rules")),e.failingRules.length===0){t.push(` ${r.green("None.")}`);return}for(let n of e.failingRules){let i=ui(n.worstSeverity,r);t.push(` ${r.dim(`[${n.ruleId}]`)} ${n.categoryLabel} ${i(n.worstSeverity)} x${n.count} - ${n.fixHint}`)}}function $a(t,e,r){let n=e.resultSummary;t.push(""),t.push(r.bold("Summary")),t.push(` ${r.dim("Total Errors".padEnd(15))} ${r.red(String(n.errorCount))}`),t.push(` ${r.dim("Total Warnings".padEnd(15))} ${r.yellow(String(n.warningCount))}`),t.push(` ${r.dim("Total Info".padEnd(15))} ${r.cyan(String(n.infoCount))}`),t.push(` ${r.dim("Total Violations".padEnd(15))} ${r.bold(String(n.violationCount))}`),t.push(` ${r.dim("Score".padEnd(15))} ${e.passed?r.green(`${e.score}/${e.maxScore}`):r.red(`${e.score}/${e.maxScore}`)}`),t.push(` ${r.dim("Result".padEnd(15))} ${e.passed?r.green("PASS"):r.red("FAIL")}`),t.push(` ${r.dim("Rules Run".padEnd(15))} ${e.metadata.rulesRun.length}`)}function ui(t,e){return t==="error"?e.red:t==="warning"?e.yellow:e.cyan}function ci(t,e={}){if(e.quiet)return JSON.stringify({score:t.score,max_score:t.maxScore,passed:t.passed},null,e.pretty===!1?0:2);let r=v(t),n=Ta(r);return JSON.stringify(n,null,e.pretty===!1?0:2)}function Ta(t){return{schema_version:t.schemaVersion,score:t.score,max_score:t.maxScore,passed:t.passed,violations:t.violations.map(La),summary:{error_count:t.resultSummary.errorCount,warning_count:t.resultSummary.warningCount,info_count:t.resultSummary.infoCount,violation_count:t.resultSummary.violationCount},category_subscores:Object.fromEntries(Object.entries(t.categorySubscores).map(([e,r])=>[e,{category:r.category,label:r.label,score:r.score,max_score:r.maxScore,baseline:r.baseline,deduction:r.deduction,violation_count:r.violationCount,error_count:r.errorCount,warning_count:r.warningCount,info_count:r.infoCount,failing_rule_ids:r.failingRuleIds}])),failing_rules:t.failingRules.map(Ia),server_info:{transport:t.server.transport,...t.server.protocolVersion!==void 0?{protocol_version:t.server.protocolVersion}:{},...t.server.name!==void 0?{name:t.server.name}:{},...t.server.version!==void 0?{version:t.server.version}:{},capabilities:t.server.capabilities,tool_count:t.server.toolCount,resource_count:t.server.resourceCount,prompt_count:t.server.promptCount},metadata:{schema_version:t.metadata.schemaVersion,linted_at:t.metadata.lintedAt,rules_run:t.metadata.rulesRun}}}function La(t){return{rule_id:t.ruleId,category:t.category,severity:t.severity,message:t.message,fix_hint:t.fixHint,...t.location!==void 0?{location:t.location}:{},...t.evidence!==void 0?{evidence:t.evidence}:{}}}function Ia(t){return{rule_id:t.ruleId,category:t.category,category_label:t.categoryLabel,worst_severity:t.worstSeverity,count:t.count,message:t.message,fix_hint:t.fixHint,violation_ids:t.violationIds}}function li(t,e={}){if(e.quiet)return`**Score:** \`${t.score}/${t.maxScore}\` - **${t.passed?"PASS":"FAIL"}**`;let r=v(t),n=[];return n.push("## MCP Lint Report"),n.push(""),Aa(n,r),Pa(n,r),Ma(n,r),Na(n,r),Va(n,r),ka(n,r),n.join(`
40
+ `)}function Aa(t,e){let r=e.passed?"\u2705 PASS":"\u274C FAIL";t.push(`### ${r} \u2014 Score: \`${e.score}/${e.maxScore}\``),t.push(""),t.push(`**Summary:** ${De(e.resultSummary.errorCount,"error")}, ${De(e.resultSummary.warningCount,"warning")}, ${De(e.resultSummary.infoCount,"info")}, ${De(e.resultSummary.violationCount,"violation")}`)}function Pa(t,e){let r=e.server;t.push(""),t.push("### Server Info"),t.push(""),t.push("| Property | Value |"),t.push("| --- | --- |"),t.push(`| Transport | \`${T(r.transport)}\` |`),r.protocolVersion!==void 0&&t.push(`| Protocol Version | \`${T(r.protocolVersion)}\` |`),r.name!==void 0&&t.push(`| Name | ${T(r.name)} |`),r.version!==void 0&&t.push(`| Version | \`${T(r.version)}\` |`),t.push(`| Tools | ${r.toolCount} |`),t.push(`| Resources | ${r.resourceCount} |`),t.push(`| Prompts | ${r.promptCount} |`),t.push(`| Capabilities | ${r.capabilities.length>0?r.capabilities.map(pe).join(", "):"none"} |`)}function Ma(t,e){t.push(""),t.push("### Category Subscores"),t.push(""),t.push("| Category | Score | Violations | Errors | Warnings | Info | Failing Rules |"),t.push("| --- | ---: | ---: | ---: | ---: | ---: | --- |");for(let r of z){let n=e.categorySubscores[r],i=n.failingRuleIds.length===0?"-":n.failingRuleIds.map(pe).join(", ");t.push(`| ${T(n.label)} | ${n.score}/${n.maxScore} | ${n.violationCount} | ${n.errorCount} | ${n.warningCount} | ${n.infoCount} | ${i} |`)}}function Na(t,e){if(t.push(""),t.push("### Violations"),e.violations.length===0){t.push(""),t.push("No violations found.");return}let r=B(e.violations);for(let n of E){let i=r[n];if(i.length===0)continue;let o=i[0]?.categoryLabel??n;t.push(""),i.length>3?(t.push(`<details${n==="security"?" open":""}>`),t.push(`<summary>${fe(o)} (${i.length})</summary>`),t.push("")):(t.push(`**${fe(o)} (${i.length})**`),t.push("")),t.push("| Rule | Severity | Message | Location |"),t.push("| --- | --- | --- | --- |");for(let s of i){let a=s.severity==="error"?"\u{1F534}":s.severity==="warning"?"\u{1F7E1}":"\u{1F535}",u=s.location===void 0?"-":pe(s.location);t.push(`| ${pe(s.ruleId)} | ${a} ${T(s.severity)} | ${T(s.message)} | ${u} |`),t.push(""),t.push(`> **Fix:** ${fe(s.fixHint)}`),s.evidence!==void 0&&t.push(`> **Evidence:** \`${fe(s.evidence)}\``),t.push("")}i.length>3&&t.push("</details>")}}function Va(t,e){if(t.push(""),t.push("### Failing Rules"),e.failingRules.length===0){t.push(""),t.push("None.");return}t.push(""),t.push("| Rule | Category | Severity | Count | Fix |"),t.push("| --- | --- | --- | ---: | --- |");for(let r of e.failingRules){let n=r.worstSeverity==="error"?"\u{1F534}":r.worstSeverity==="warning"?"\u{1F7E1}":"\u{1F535}";t.push(`| ${pe(r.ruleId)} | ${T(r.categoryLabel)} | ${n} ${T(r.worstSeverity)} | ${r.count} | ${T(r.fixHint)} |`)}}function ka(t,e){let r=e.resultSummary;t.push(""),t.push("### Summary"),t.push(""),t.push("| Metric | Value |"),t.push("| --- | ---: |"),t.push(`| Total Errors | ${r.errorCount} |`),t.push(`| Total Warnings | ${r.warningCount} |`),t.push(`| Total Info | ${r.infoCount} |`),t.push(`| Total Violations | ${r.violationCount} |`),t.push(`| Score | ${e.score}/${e.maxScore} |`),t.push(`| Result | ${e.passed?"PASS \u2705":"FAIL \u274C"} |`),t.push(`| Rules Run | ${e.metadata.rulesRun.length} |`)}function pe(t){return`\`${t.replace(/`/gu,"\\`")}\``}function T(t){return fe(t).replace(/\|/gu,"\\|").replace(/\n/gu,"<br>")}function fe(t){return t.replace(/\\/gu,"\\\\").replace(/</gu,"&lt;").replace(/>/gu,"&gt;").replace(/([*_`[\]])/gu,"\\$1")}function De(t,e){return`${t} ${t===1?e:`${e}s`}`}function di(t,e){return e.quiet&&e.format==="terminal"?`${t.passed?"PASS":"FAIL"} ${t.score}/${t.maxScore}`:e.format==="json"?ci(t,{quiet:e.quiet,pretty:!0}):e.format==="markdown"?li(t,{quiet:e.quiet}):ai(t,{colors:e.colors,detailed:e.detailed})}function mi(t,e){let r=t.map(n=>({id:n.id,category:n.category,severity:n.severity,title:n.title,description:n.description}));return e.format==="json"?JSON.stringify({count:r.length,rules:r},null,2):e.format==="markdown"?ja(r):e.quiet?r.map(n=>n.id).join(`
41
+ `):Fa(r)}function fi(t,e){e.write(`Error: ${Ae(t)}
42
+ `)}function Fa(t){let e=[`Available MCP lint rules (${t.length})`,""];e.push("ID Category Severity Title - Description");for(let r of t)e.push(`${r.id.padEnd(5)} ${r.category.padEnd(12)} ${r.severity.padEnd(9)} ${r.title} - ${r.description}`);return e.join(`
43
+ `)}function ja(t){let e=["# MCP Lint Rules","","| ID | Category | Severity | Title | Description |","| --- | --- | --- | --- | --- |"];for(let r of t)e.push(`| ${Ha(r.id)} | ${Ue(r.category)} | ${Ue(r.severity)} | ${Ue(r.title)} | ${Ue(r.description)} |`);return e.join(`
44
+ `)}function Ha(t){return`\`${t.replace(/`/gu,"\\`")}\``}function Ue(t){return t.replace(/\\/gu,"\\\\").replace(/\|/gu,"\\|").replace(/\n/gu,"<br>")}function qe(t){let e=t?.[0]==="--"?t.slice(1):t??[],r=e[0];if(r===void 0||r.trim()==="")throw ce("No MCP server command provided. Use: aimcp-lint -- node ./server.mjs");let n=e.slice(1);return{command:r,args:n,display:[r,...n].map(Da).join(" ")}}function Da(t){return/^[A-Za-z0-9_./:=@+-]+$/u.test(t)?t:`'${t.replace(/'/gu,"'\\''")}'`}var pi=["-","\\","|","/"];function hi(t){return t.format==="terminal"&&!t.quiet&&t.streamIsTTY===!0}var Je=class{#e;#r;#t;#n;#a=0;#s="";constructor(e){this.#e=e.enabled,this.#r=e.stream,this.#t=e.intervalMs??80}async run(e,r){this.start(e);try{let n=await r();return this.succeed(e),n}catch(n){throw this.fail(e),n}}start(e){this.#e&&(this.#s=e,this.#o(),this.#n=setInterval(()=>{this.#o()},this.#t))}succeed(e=this.#s){this.#e&&(this.stop(),this.#r.write(`\r\x1B[2KOK ${e}
45
+ `))}fail(e=this.#s){this.#e&&(this.stop(),this.#r.write(`\r\x1B[2KERR ${e}
46
+ `))}stop(){this.#n!==void 0&&(clearInterval(this.#n),this.#n=void 0),this.#e&&this.#r.write("\r\x1B[2K")}#o(){let e=pi[this.#a%pi.length]??"-";this.#a+=1,this.#r.write(`\r${e} ${this.#s}`)}};function gi(t,e){return{step(r){t&&e.write(`[aimcp-lint] ${r}
47
+ `)}}}function pr(t){return t.addOption(new Ar("--format <format>","output format: terminal, json, or markdown").choices([...sr]))}function ze(t){return pr(t).option("--fail-under <score>","exit with code 1 when score is below score",Ua).option("--ignore <ruleId...>","disable one or more rule IDs").option("--only <ruleId...>","run only one or more rule IDs").option("--config <path>","path to .aimcp-lint.json").option("--verbose","show connection and protocol diagnostics").option("--quiet","suppress normal terminal report details").option("--detailed","show fix hints in terminal output"),t}async function We(t){let e=t.cwd??fr.cwd(),r=t.stdout??fr.stdout,n=t.stderr??fr.stderr,i=await re({cwd:e,options:t.options}),o=(t.serverCommandTokens??[]).length>0?t.serverCommandTokens:void 0,s=i.commandTokens,a=o??s;if(a===void 0||a.length===0)throw o===void 0&&s===void 0?ce('No MCP server command provided. Pass one on the command line or set "command" in .aimcp-lint.json.'):ce(`MCP server command resolved to empty list. Check the "command" field in ${i.configPath}.`);let u=qe(a),c=gi(i.verbose,n);c.step(`Config: ${i.configPath}${i.configExists?"":" (not found, using defaults)"}`),c.step(`Format: ${i.format} | Quiet: ${i.quiet} | Detailed: ${i.detailed} | Fail under: ${i.failUnder??"none"}`),c.step(`Resolved server command: ${u.display}`);let d=new Je({stream:n,enabled:hi({format:i.format,quiet:i.quiet,...n.isTTY!==void 0?{streamIsTTY:n.isTTY}:{}})});c.step("Connecting to MCP server");let l;try{l=await d.run("Connecting to MCP server",async()=>Qn({serverCommand:u,cwd:e,config:i.lintConfig,verbose:i.verbose,stderr:n,...i.verbose?{diagnostics:b=>{c.step(b)}}:{}}))}catch(b){throw b instanceof C?qn(b.message):b}c.step(`Collected ${l.tools?.length??0} tools, ${l.resources?.length??0} resources, ${l.prompts?.length??0} prompts`),c.step("Running lint rules");let p=await d.run("Running lint rules",async()=>ei({context:l,config:i.lintConfig}));return c.step(`Score: ${p.score}/${p.maxScore} (${p.passed?"PASS":"FAIL"})`),c.step(`Violations: ${p.summary.violationCount} (${p.summary.errorCount} errors, ${p.summary.warningCount} warnings, ${p.summary.infoCount} info)`),c.step(`Rules run: ${p.rulesRun.length}`),c.step("Rendering output"),r.write(`${di(p,{format:i.format,quiet:i.quiet,colors:Kn(r),detailed:i.detailed})}
48
+ `),p.passed?0:1}function Ua(t){let e=Number(t);if(!Number.isFinite(e)||e<0)throw new Ir("score must be a non-negative finite number");return e}import yi from"process";function bi(){let t=pr(new N("rules").description("list all built-in MCP lint rules")).option("--quiet","print rule IDs only for terminal output");return t.action(()=>{yi.exitCode=qa(t.optsWithGlobals())}),t}function qa(t={}){let e=t.stdout??yi.stdout,r=Nn();return e.write(`${mi(r.getRules(),{format:t.format??"terminal",quiet:t.quiet===!0})}
49
+ `),0}import{watch as Ja}from"fs";import{resolve as za}from"path";import ne from"process";function Ci(){let t=ze(new N("watch").description("run aimcp-lint repeatedly when watched files change").usage("[options] [--] <server-command> [args...]").argument("[serverCommand...]","target MCP server command and arguments"));return t.action(async(e,r)=>{ne.exitCode=await Wa({serverCommandTokens:e,options:r})}),t}async function Wa(t){qe(t.serverCommandTokens);let e=t.cwd??ne.cwd(),r=t.stdout??ne.stdout,n=t.stderr??ne.stderr,i=await re({cwd:e,options:t.options}),o=Ga({cwd:e,configPath:i.configPath,configExists:i.configExists,configuredPaths:i.watchPaths}),s=t.signal??Ka();return i.quiet||n.write(`Watching ${o.join(", ")}
50
+ `),await Ba({watchPaths:o,signal:s,...t.createWatcher!==void 0?{createWatcher:t.createWatcher}:{},runOnce:async()=>{try{return await We({serverCommandTokens:t.serverCommandTokens,options:t.options,cwd:e,stdout:r,stderr:n})}catch(a){return n.write(`Error: ${Ae(a)}
51
+ `),Pe(a)}}}),0}async function Ba(t){let e=t.createWatcher??Ya,r=t.watchPaths.map(u=>e(u,()=>{t.onChange?.(u),a()})),n,i=!1,o=!1;async function s(){if(i){o=!0;return}i=!0;try{do o=!1,await t.runOnce();while(o&&t.signal?.aborted!==!0)}finally{i=!1}}function a(){n!==void 0&&clearTimeout(n),n=setTimeout(()=>{n=void 0,s()},t.debounceMs??100)}try{t.onWatching?.(t.watchPaths),await s(),await Xa(t.signal)}finally{n!==void 0&&clearTimeout(n);for(let u of r)u.close()}}function Ga(t){let e=[...t.configExists?[t.configPath]:[],...t.configuredPaths.map(n=>za(t.cwd,n))],r=e.length===0?[t.cwd]:e;return Array.from(new Set(r))}function Ya(t,e){let r=Ja(t,{persistent:!0},()=>{e()});return{close:()=>{r.close()}}}function Xa(t){return t===void 0?new Promise(()=>{}):t.aborted?Promise.resolve():new Promise(e=>{t.addEventListener("abort",()=>e(),{once:!0})})}function Ka(){let t=new AbortController,e=()=>{t.abort()};return ne.once("SIGINT",e),ne.once("SIGTERM",e),t.signal}var Za="aimcp-lint",Qa="MCP lint CLI for validating Model Context Protocol servers.",eu=["","Examples:"," aimcp-lint node ./server.mjs"," aimcp-lint -- node ./server.mjs --flag"," aimcp-lint watch -- node ./server.mjs"].join(`
52
+ `);function _i(){let t=new N;return ze(t).name(Za).description(Qa).usage("[options] [--] <server-command> [args...]").version(de,"-V, --version","display the aimcp-lint version").helpOption("-h, --help","display help for command").showHelpAfterError("(add --help for usage)").showSuggestionAfterError(!1).argument("[serverCommand...]","target MCP server command and arguments").addHelpText("after",eu).action(async(e,r)=>{let n=e!==void 0&&e.length>0?e:void 0;if(n===void 0){let i=await re({cwd:he.cwd(),options:r});if(i.commandTokens===void 0||i.commandTokens.length===0){t.outputHelp();return}}he.exitCode=await We({serverCommandTokens:n,options:r})}),t.addCommand(Ci()),t.addCommand(Yn()),t.addCommand(bi()),t}async function hr(t=he.argv){let e=_i();try{await e.parseAsync([...t])}catch(r){fi(r,he.stderr),he.exitCode=Pe(r)}}function ru(){let t=process.argv[1];if(t==null)return!1;try{return Si(tu(import.meta.url))===Si(t)}catch{return!1}}ru()&&await hr(process.argv);export{_i as createCli,de as packageVersion,hr as runCli};
@@ -0,0 +1,17 @@
1
+ import { type LintConfig, type LintContext, type LintResult } from '@sherpa-labs/core-mcp';
2
+ import type { WritableStreamLike } from './output.js';
3
+ import type { ServerCommand } from './server-command.js';
4
+ export interface CollectStdioLintContextInput {
5
+ readonly serverCommand: ServerCommand;
6
+ readonly cwd: string;
7
+ readonly config: LintConfig;
8
+ readonly verbose?: boolean;
9
+ readonly stderr?: WritableStreamLike;
10
+ readonly diagnostics?: (message: string) => void;
11
+ }
12
+ export declare function collectStdioLintContext(input: CollectStdioLintContextInput): Promise<LintContext>;
13
+ export declare function runLintEngine(input: {
14
+ readonly context: LintContext;
15
+ readonly config: LintConfig;
16
+ }): Promise<LintResult>;
17
+ //# sourceMappingURL=lint-runner.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lint-runner.d.ts","sourceRoot":"","sources":["../src/lint-runner.ts"],"names":[],"mappings":"AAGA,OAAO,EAML,KAAK,UAAU,EACf,KAAK,WAAW,EAQhB,KAAK,UAAU,EAIhB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAGzD,MAAM,WAAW,4BAA4B;IAC3C,QAAQ,CAAC,aAAa,EAAE,aAAa,CAAC;IACtC,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,MAAM,EAAE,UAAU,CAAC;IAC5B,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC;IAC3B,QAAQ,CAAC,MAAM,CAAC,EAAE,kBAAkB,CAAC;IACrC,QAAQ,CAAC,WAAW,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;CAClD;AAED,wBAAsB,uBAAuB,CAC3C,KAAK,EAAE,4BAA4B,GAClC,OAAO,CAAC,WAAW,CAAC,CA6DtB;AAED,wBAAsB,aAAa,CAAC,KAAK,EAAE;IACzC,QAAQ,CAAC,OAAO,EAAE,WAAW,CAAC;IAC9B,QAAQ,CAAC,MAAM,EAAE,UAAU,CAAC;CAC7B,GAAG,OAAO,CAAC,UAAU,CAAC,CAEtB"}
@@ -0,0 +1,20 @@
1
+ import { type LintResult, type LintRule } from '@sherpa-labs/core-mcp';
2
+ import type { OutputFormat } from './config.js';
3
+ export interface WritableStreamLike {
4
+ readonly isTTY?: boolean;
5
+ write(chunk: string): void;
6
+ }
7
+ export interface RenderLintOutputOptions {
8
+ readonly format: OutputFormat;
9
+ readonly quiet: boolean;
10
+ readonly colors: boolean;
11
+ readonly detailed: boolean;
12
+ }
13
+ export interface RenderRulesOutputOptions {
14
+ readonly format: OutputFormat;
15
+ readonly quiet: boolean;
16
+ }
17
+ export declare function renderLintOutput(result: LintResult, options: RenderLintOutputOptions): string;
18
+ export declare function renderRulesOutput(rules: readonly LintRule[], options: RenderRulesOutputOptions): string;
19
+ export declare function writeCliError(error: unknown, stream: WritableStreamLike): void;
20
+ //# sourceMappingURL=output.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"output.d.ts","sourceRoot":"","sources":["../src/output.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,UAAU,EAAE,KAAK,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAEvE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAMhD,MAAM,WAAW,kBAAkB;IACjC,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC;IACzB,KAAK,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;CAC5B;AAED,MAAM,WAAW,uBAAuB;IACtC,QAAQ,CAAC,MAAM,EAAE,YAAY,CAAC;IAC9B,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC;IACxB,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;IACzB,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;CAC5B;AAED,MAAM,WAAW,wBAAwB;IACvC,QAAQ,CAAC,MAAM,EAAE,YAAY,CAAC;IAC9B,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC;CACzB;AAED,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,UAAU,EAAE,OAAO,EAAE,uBAAuB,GAAG,MAAM,CAsB7F;AAED,wBAAgB,iBAAiB,CAC/B,KAAK,EAAE,SAAS,QAAQ,EAAE,EAC1B,OAAO,EAAE,wBAAwB,GAChC,MAAM,CAsBR;AAED,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,kBAAkB,GAAG,IAAI,CAE9E"}
@@ -0,0 +1,7 @@
1
+ export interface ServerCommand {
2
+ readonly command: string;
3
+ readonly args: readonly string[];
4
+ readonly display: string;
5
+ }
6
+ export declare function parseServerCommand(tokens: readonly string[] | undefined): ServerCommand;
7
+ //# sourceMappingURL=server-command.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server-command.d.ts","sourceRoot":"","sources":["../src/server-command.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,CAAC;IACjC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;CAC1B;AAED,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,GAAG,SAAS,GAAG,aAAa,CAevF"}
@@ -0,0 +1,26 @@
1
+ import type { OutputFormat } from './config.js';
2
+ export interface SpinnerStream {
3
+ readonly isTTY?: boolean;
4
+ write(chunk: string): void;
5
+ }
6
+ export interface SpinnerDecisionInput {
7
+ readonly format: OutputFormat;
8
+ readonly quiet: boolean;
9
+ readonly streamIsTTY?: boolean;
10
+ }
11
+ export interface SpinnerOptions {
12
+ readonly enabled: boolean;
13
+ readonly stream: SpinnerStream;
14
+ readonly intervalMs?: number;
15
+ }
16
+ export declare function shouldUseSpinner(input: SpinnerDecisionInput): boolean;
17
+ export declare class Spinner {
18
+ #private;
19
+ constructor(options: SpinnerOptions);
20
+ run<T>(message: string, task: () => Promise<T>): Promise<T>;
21
+ start(message: string): void;
22
+ succeed(message?: string): void;
23
+ fail(message?: string): void;
24
+ stop(): void;
25
+ }
26
+ //# sourceMappingURL=spinner.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"spinner.d.ts","sourceRoot":"","sources":["../src/spinner.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEhD,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC;IACzB,KAAK,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;CAC5B;AAED,MAAM,WAAW,oBAAoB;IACnC,QAAQ,CAAC,MAAM,EAAE,YAAY,CAAC;IAC9B,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC;IACxB,QAAQ,CAAC,WAAW,CAAC,EAAE,OAAO,CAAC;CAChC;AAED,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,QAAQ,CAAC,MAAM,EAAE,aAAa,CAAC;IAC/B,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;CAC9B;AAID,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,oBAAoB,GAAG,OAAO,CAErE;AAED,qBAAa,OAAO;;gBAQN,OAAO,EAAE,cAAc;IAM7B,GAAG,CAAC,CAAC,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;IAajE,KAAK,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAY5B,OAAO,CAAC,OAAO,SAAgB,GAAG,IAAI;IAStC,IAAI,CAAC,OAAO,SAAgB,GAAG,IAAI;IASnC,IAAI,IAAI,IAAI;CAgBb"}
@@ -0,0 +1,7 @@
1
+ import type { WritableStreamLike } from './output.js';
2
+ export interface VerboseLogger {
3
+ step(message: string): void;
4
+ }
5
+ export declare function createVerboseLogger(enabled: boolean, stream: WritableStreamLike): VerboseLogger;
6
+ export declare function noopVerboseLogger(): VerboseLogger;
7
+ //# sourceMappingURL=verbose.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"verbose.d.ts","sourceRoot":"","sources":["../src/verbose.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEtD,MAAM,WAAW,aAAa;IAC5B,IAAI,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;CAC7B;AAED,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,kBAAkB,GAAG,aAAa,CAS/F;AAED,wBAAgB,iBAAiB,IAAI,aAAa,CAIjD"}
@@ -1 +1 @@
1
- {"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../src/version.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,cAAc,QAA6B,CAAC"}
1
+ {"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../src/version.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,cAAc,QAC4D,CAAC"}
package/package.json CHANGED
@@ -1,8 +1,18 @@
1
1
  {
2
2
  "name": "@sherpa-labs/aimcp-lint",
3
- "version": "0.0.0",
4
- "description": "MCP lint CLI for validating Model Context Protocol servers.",
3
+ "version": "0.0.1",
4
+ "description": "Lint your MCP server for protocol compliance, schema violations, security issues, and performance best practices.",
5
5
  "license": "MIT",
6
+ "keywords": [
7
+ "mcp",
8
+ "model-context-protocol",
9
+ "lint",
10
+ "linter",
11
+ "cli",
12
+ "mcp-server",
13
+ "sherpa-labs"
14
+ ],
15
+ "author": "Sherpa Labs <hello@sherpalabs.dev>",
6
16
  "repository": {
7
17
  "type": "git",
8
18
  "url": "https://github.com/sherpa-labs-io/SherpaLabs.git",
@@ -27,8 +37,13 @@
27
37
  "dist",
28
38
  "LICENSE"
29
39
  ],
40
+ "engines": {
41
+ "node": ">=22.0.0"
42
+ },
30
43
  "dependencies": {
31
- "commander": "^13.1.0"
44
+ "commander": "^13.1.0",
45
+ "picocolors": "^1.1.1",
46
+ "@sherpa-labs/core-mcp": "0.0.0"
32
47
  },
33
48
  "devDependencies": {
34
49
  "@types/node": "^25.9.1",