@dimassetoid/openapi-mcp 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -11,8 +11,24 @@ export const DEFAULT_SPEC_CANDIDATES = [
11
11
  export const MAX_SPEC_BYTES = 8 * 1024 * 1024;
12
12
  export const MAX_SPEC_FILES = 128;
13
13
  const MAX_NODE_VISITS = 250_000;
14
- const MAX_DEPTH = 128;
14
+ export const MAX_DEPTH = 128;
15
15
  const MAX_CACHED_SPECS = 8;
16
+ function parseBoundedEnvInt(raw, fallback, min, max) {
17
+ if (!raw || !raw.trim())
18
+ return fallback;
19
+ const parsed = Number.parseInt(raw.trim(), 10);
20
+ if (!Number.isFinite(parsed) || parsed < min)
21
+ return fallback;
22
+ return Math.min(parsed, max);
23
+ }
24
+ export function resolveSpecLimits(env = process.env) {
25
+ return {
26
+ maxSpecBytes: parseBoundedEnvInt(env.OPENAPI_MCP_MAX_SPEC_BYTES, MAX_SPEC_BYTES, 1024, 64 * 1024 * 1024),
27
+ maxSpecFiles: parseBoundedEnvInt(env.OPENAPI_MCP_MAX_SPEC_FILES, MAX_SPEC_FILES, 1, 1024),
28
+ maxNodeVisits: parseBoundedEnvInt(env.OPENAPI_MCP_MAX_NODE_VISITS, MAX_NODE_VISITS, 1000, 2_000_000),
29
+ maxCachedSpecs: parseBoundedEnvInt(env.OPENAPI_MCP_MAX_CACHED_SPECS, MAX_CACHED_SPECS, 1, 32),
30
+ };
31
+ }
16
32
  export class MissingReferenceError extends Error {
17
33
  code = 'REF_FILE_NOT_FOUND';
18
34
  constructor(target, source) {
@@ -23,12 +39,13 @@ const specCache = new Map();
23
39
  const snapshotJson = new WeakMap();
24
40
  /** Serialize loader-owned snapshots once. Library callers can also supply their own data. */
25
41
  export function serializeSpec(spec) {
42
+ const limits = resolveSpecLimits();
26
43
  const cached = spec !== null && typeof spec === 'object' ? snapshotJson.get(spec) : undefined;
27
44
  if (cached !== undefined)
28
45
  return cached;
29
46
  const text = JSON.stringify(spec) ?? 'null';
30
- if (Buffer.byteLength(text) > MAX_SPEC_BYTES) {
31
- throw new Error(`SPEC_LIMIT: Serialized spec exceeds ${MAX_SPEC_BYTES} bytes.`);
47
+ if (Buffer.byteLength(text) > limits.maxSpecBytes) {
48
+ throw new Error(`SPEC_LIMIT: Serialized spec exceeds ${limits.maxSpecBytes} bytes.`);
32
49
  }
33
50
  return text;
34
51
  }
@@ -36,23 +53,23 @@ function isPathInside(root, candidate) {
36
53
  const rel = relative(root, candidate);
37
54
  return rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
38
55
  }
39
- function isMissing(error) {
56
+ export function isSpecFileMissingError(error) {
40
57
  const code = error?.code;
41
58
  return code === 'ENOENT' || code === 'ENOTDIR';
42
59
  }
43
- function resolveRoot(path) {
60
+ export function resolveSpecWorkspaceRoot(path) {
44
61
  try {
45
62
  const canonicalPath = realpathSync(path);
46
63
  if (statSync(canonicalPath).isDirectory())
47
64
  return canonicalPath;
48
65
  }
49
66
  catch (error) {
50
- if (!isMissing(error))
67
+ if (!isSpecFileMissingError(error))
51
68
  throw error;
52
69
  }
53
70
  throw new Error(`WORKSPACE_NOT_FOUND: Workspace directory '${path}' does not exist.`);
54
71
  }
55
- function resolveFile(target, root, base, rawRoot) {
72
+ export function resolveLocalSpecFile(target, root, base, rawRoot) {
56
73
  const path = target.trim();
57
74
  if (!path)
58
75
  throw new Error('INVALID_SPEC_PATH: File path cannot be empty.');
@@ -72,11 +89,14 @@ function resolveFile(target, root, base, rawRoot) {
72
89
  return { candidate, canonical };
73
90
  }
74
91
  catch (error) {
75
- if (isMissing(error))
92
+ if (isSpecFileMissingError(error))
76
93
  return undefined;
77
94
  throw error;
78
95
  }
79
96
  }
97
+ const isMissing = isSpecFileMissingError;
98
+ const resolveRoot = resolveSpecWorkspaceRoot;
99
+ const resolveFile = resolveLocalSpecFile;
80
100
  function requireFile(target, root, base, rawRoot) {
81
101
  const location = resolveFile(target, root, base, rawRoot);
82
102
  if (location)
@@ -86,7 +106,7 @@ function requireFile(target, root, base, rawRoot) {
86
106
  export function resolveSafeSpecPath(targetPath, rootRealPath, baseDir = rootRealPath, rawRootDir) {
87
107
  return requireFile(targetPath, rootRealPath, baseDir, rawRootDir).canonical;
88
108
  }
89
- function discoverSpec(root, rawRoot, explicitPath) {
109
+ export function discoverSpec(root, rawRoot, explicitPath) {
90
110
  if (explicitPath?.trim())
91
111
  return requireFile(explicitPath, root, root, rawRoot).canonical;
92
112
  for (const candidate of DEFAULT_SPEC_CANDIDATES) {
@@ -107,14 +127,14 @@ export function assertWorkspaceRoot(rootInput, allowedRootDir) {
107
127
  export function findOpenApiSpecFile(rootDir, explicitPath) {
108
128
  return discoverSpec(resolveRoot(rootDir), rootDir, explicitPath);
109
129
  }
110
- export function readBoundedFileSnapshot(path, availableBytes) {
130
+ export function readBoundedFileSnapshot(path, availableBytes, maxSpecBytes = resolveSpecLimits().maxSpecBytes) {
111
131
  const fd = openSync(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0) | (constants.O_NOFOLLOW ?? 0));
112
132
  try {
113
133
  const before = fstatSync(fd);
114
134
  if (!before.isFile())
115
135
  throw new Error(`INVALID_SPEC_PATH: '${path}' must be a regular file.`);
116
136
  if (before.size > availableBytes)
117
- throw new Error(`SPEC_LIMIT: Source files exceed ${MAX_SPEC_BYTES} bytes.`);
137
+ throw new Error(`SPEC_LIMIT: Source files exceed ${maxSpecBytes} bytes.`);
118
138
  const bytes = Buffer.allocUnsafe(before.size + 1);
119
139
  let count = 0;
120
140
  while (count < bytes.length) {
@@ -173,13 +193,20 @@ export function resolveJsonPointerSafe(document, fragment) {
173
193
  }
174
194
  return { ok: true, value };
175
195
  }
176
- function resolvePointer(document, fragment, ref) {
196
+ export function resolvePointer(document, fragment, ref) {
177
197
  const result = resolveJsonPointerSafe(document, fragment);
178
198
  if (!result.ok) {
179
199
  throw new Error(`INVALID_REF: '${ref}': ${result.reason}`);
180
200
  }
181
201
  return result.value;
182
202
  }
203
+ export function inferPointerPosition(pointer) {
204
+ if (pointer === '' || pointer === '/')
205
+ return 'document';
206
+ if (pointer.startsWith('/components/schemas/') || pointer.startsWith('/definitions/'))
207
+ return 'schema';
208
+ return 'document';
209
+ }
183
210
  export function deepFreeze(value, seen = new WeakSet()) {
184
211
  if (value === null || typeof value !== 'object' || seen.has(value))
185
212
  return value;
@@ -271,86 +298,13 @@ function childPosition(parent, key, pointer) {
271
298
  return 'schema-map';
272
299
  return 'document';
273
300
  }
274
- /**
275
- * Returns a bounded, immutable snapshot shared by library, index, and query consumers.
276
- */
277
- export function loadOpenApiSpec(options = {}) {
278
- const rootInput = options.rootDir?.trim() || process.cwd();
279
- const root = assertWorkspaceRoot(rootInput, options.allowedRootDir);
280
- const entry = discoverSpec(root, rootInput, options.specPath);
281
- const snapshots = new Map();
282
- let remainingBytes = MAX_SPEC_BYTES;
283
- function snapshot(path) {
284
- const existing = snapshots.get(path);
285
- if (existing)
286
- return existing;
287
- if (snapshots.size >= MAX_SPEC_FILES)
288
- throw new Error(`SPEC_LIMIT: At most ${MAX_SPEC_FILES} source files are supported.`);
289
- const loaded = readBoundedFileSnapshot(path, remainingBytes);
290
- remainingBytes -= loaded.size;
291
- snapshots.set(path, loaded);
292
- return loaded;
293
- }
294
- const cacheId = `${root}\0${entry}`;
295
- const cached = specCache.get(cacheId);
296
- if (cached?.loaded.rootDir === root) {
297
- let fresh = false;
298
- try {
299
- const locationsMatch = [...cached.locations].every(([alias, canonical]) => resolveFile(alias, root, root)?.canonical === canonical);
300
- fresh = locationsMatch && cached.loaded.dependencies.every((dependency) => {
301
- // Fast-path O(1) stat check avoids re-reading and hashing unchanged files on every query.
302
- const st = statSync(dependency.filePath);
303
- if (st.mtimeMs === dependency.mtimeMs && st.ctimeMs === dependency.ctimeMs && st.size === dependency.size) {
304
- return true;
305
- }
306
- const { mtimeMs, sha256 } = snapshot(dependency.filePath).fingerprint;
307
- return mtimeMs === dependency.mtimeMs && sha256 === dependency.sha256;
308
- });
309
- }
310
- catch (error) {
311
- if (!isMissing(error) && !(error instanceof Error && error.message.startsWith('SPEC_CHANGED:'))) {
312
- throw error;
313
- }
314
- fresh = false;
315
- }
316
- specCache.delete(cacheId);
317
- if (fresh) {
318
- specCache.set(cacheId, cached);
319
- return { ...cached.loaded, fromCache: true };
320
- }
321
- // Reset snapshot accounting so deleted/unused dependencies from the stale cache do not consume byte budget.
322
- snapshots.clear();
323
- remainingBytes = MAX_SPEC_BYTES;
324
- }
325
- const parsedFiles = new Map();
326
- const fileSourceLocations = new Map();
327
- const locations = new Map();
328
- function parseFile(path) {
329
- if (parsedFiles.has(path))
330
- return parsedFiles.get(path);
331
- const file = snapshot(path);
332
- try {
333
- const relFile = relative(root, path).replace(/\\/g, '/');
334
- const parsedDoc = parseDocumentWithLocations(file.content, relFile);
335
- parsedFiles.set(path, parsedDoc.value);
336
- fileSourceLocations.set(path, parsedDoc.locations);
337
- return parsedDoc.value;
338
- }
339
- catch (error) {
340
- const message = error instanceof Error ? error.message : String(error);
341
- throw new Error(`SPEC_PARSE_ERROR: Failed to parse '${path}': ${message.slice(0, 400)}`);
342
- }
343
- }
344
- const document = parseFile(entry);
345
- if (!isRecord(document))
346
- throw new Error(`SPEC_PARSE_ERROR: Entry specification '${entry}' must be an object.`);
347
- const schema31 = typeof document.openapi === 'string' && /^3\.(?:[1-9]|\d{2,})\./.test(document.openapi);
301
+ export function createSpecNodeExpander(options) {
302
+ const { root, entry, schema31, limits, parseFile, locations, schemaUsageMap } = options;
348
303
  const ancestors = new WeakSet();
349
- const schemaUsageMap = new Map();
350
304
  let visits = 0;
351
305
  let expandedBytes = 0;
352
306
  function recordSchemaUsage(schemaName, opCtx) {
353
- if (!opCtx)
307
+ if (!opCtx || !schemaUsageMap)
354
308
  return;
355
309
  const section = opCtx.section ?? 'operation';
356
310
  const key = `${opCtx.method} ${opCtx.path}\0${section}`;
@@ -365,12 +319,12 @@ export function loadOpenApiSpec(options = {}) {
365
319
  }
366
320
  function countBytes(bytes) {
367
321
  expandedBytes += bytes;
368
- if (expandedBytes > MAX_SPEC_BYTES)
369
- throw new Error(`SPEC_LIMIT: Expanded spec exceeds ${MAX_SPEC_BYTES} bytes.`);
322
+ if (expandedBytes > limits.maxSpecBytes)
323
+ throw new Error(`SPEC_LIMIT: Expanded spec exceeds ${limits.maxSpecBytes} bytes.`);
370
324
  }
371
325
  function expand(node, file, pointer, depth, position, opCtx) {
372
- if (++visits > MAX_NODE_VISITS || depth > MAX_DEPTH) {
373
- throw new Error(`SPEC_LIMIT: Spec expansion exceeds ${MAX_NODE_VISITS} nodes or ${MAX_DEPTH} levels.`);
326
+ if (++visits > limits.maxNodeVisits || depth > MAX_DEPTH) {
327
+ throw new Error(`SPEC_LIMIT: Spec expansion exceeds ${limits.maxNodeVisits} nodes or ${MAX_DEPTH} levels.`);
374
328
  }
375
329
  countBytes(4);
376
330
  if (node === null || typeof node !== 'object') {
@@ -451,6 +405,96 @@ export function loadOpenApiSpec(options = {}) {
451
405
  ancestors.delete(node);
452
406
  }
453
407
  }
408
+ return {
409
+ expand,
410
+ getStats: () => ({ nodeVisits: visits, expandedBytes }),
411
+ };
412
+ }
413
+ /**
414
+ * Returns a bounded, immutable snapshot shared by library, index, and query consumers.
415
+ */
416
+ export function loadOpenApiSpec(options = {}) {
417
+ const limits = resolveSpecLimits();
418
+ const rootInput = options.rootDir?.trim() || process.cwd();
419
+ const root = assertWorkspaceRoot(rootInput, options.allowedRootDir);
420
+ const entry = discoverSpec(root, rootInput, options.specPath);
421
+ const snapshots = new Map();
422
+ let remainingBytes = limits.maxSpecBytes;
423
+ function snapshot(path) {
424
+ const existing = snapshots.get(path);
425
+ if (existing)
426
+ return existing;
427
+ if (snapshots.size >= limits.maxSpecFiles)
428
+ throw new Error(`SPEC_LIMIT: At most ${limits.maxSpecFiles} source files are supported.`);
429
+ const loaded = readBoundedFileSnapshot(path, remainingBytes, limits.maxSpecBytes);
430
+ remainingBytes -= loaded.size;
431
+ snapshots.set(path, loaded);
432
+ return loaded;
433
+ }
434
+ const cacheId = `${root}\0${entry}`;
435
+ const cached = specCache.get(cacheId);
436
+ if (cached?.loaded.rootDir === root) {
437
+ let fresh = false;
438
+ try {
439
+ const locationsMatch = [...cached.locations].every(([alias, canonical]) => resolveFile(alias, root, root)?.canonical === canonical);
440
+ fresh = locationsMatch && cached.loaded.dependencies.every((dependency) => {
441
+ // Fast-path O(1) stat check avoids re-reading and hashing unchanged files on every query.
442
+ const st = statSync(dependency.filePath);
443
+ if (st.mtimeMs === dependency.mtimeMs && st.ctimeMs === dependency.ctimeMs && st.size === dependency.size) {
444
+ return true;
445
+ }
446
+ const { mtimeMs, sha256 } = snapshot(dependency.filePath).fingerprint;
447
+ return mtimeMs === dependency.mtimeMs && sha256 === dependency.sha256;
448
+ });
449
+ }
450
+ catch (error) {
451
+ if (!isMissing(error) && !(error instanceof Error && error.message.startsWith('SPEC_CHANGED:'))) {
452
+ throw error;
453
+ }
454
+ fresh = false;
455
+ }
456
+ specCache.delete(cacheId);
457
+ if (fresh) {
458
+ specCache.set(cacheId, cached);
459
+ return { ...cached.loaded, fromCache: true };
460
+ }
461
+ // Reset snapshot accounting so deleted/unused dependencies from the stale cache do not consume byte budget.
462
+ snapshots.clear();
463
+ remainingBytes = limits.maxSpecBytes;
464
+ }
465
+ const parsedFiles = new Map();
466
+ const fileSourceLocations = new Map();
467
+ const locations = new Map();
468
+ function parseFile(path) {
469
+ if (parsedFiles.has(path))
470
+ return parsedFiles.get(path);
471
+ const file = snapshot(path);
472
+ try {
473
+ const relFile = relative(root, path).replace(/\\/g, '/');
474
+ const parsedDoc = parseDocumentWithLocations(file.content, relFile);
475
+ parsedFiles.set(path, parsedDoc.value);
476
+ fileSourceLocations.set(path, parsedDoc.locations);
477
+ return parsedDoc.value;
478
+ }
479
+ catch (error) {
480
+ const message = error instanceof Error ? error.message : String(error);
481
+ throw new Error(`SPEC_PARSE_ERROR: Failed to parse '${path}': ${message.slice(0, 400)}`);
482
+ }
483
+ }
484
+ const document = parseFile(entry);
485
+ if (!isRecord(document))
486
+ throw new Error(`SPEC_PARSE_ERROR: Entry specification '${entry}' must be an object.`);
487
+ const schema31 = typeof document.openapi === 'string' && /^3\.(?:[1-9]|\d{2,})\./.test(document.openapi);
488
+ const schemaUsageMap = new Map();
489
+ const { expand } = createSpecNodeExpander({
490
+ root,
491
+ entry,
492
+ schema31,
493
+ limits,
494
+ parseFile,
495
+ locations,
496
+ schemaUsageMap,
497
+ });
454
498
  const resolved = expand(document, entry, '', 0, 'document');
455
499
  if (!isRecord(resolved))
456
500
  throw new Error('SPEC_PARSE_ERROR: Resolved entry specification must be an object.');
@@ -472,7 +516,7 @@ export function loadOpenApiSpec(options = {}) {
472
516
  deepFreeze(schemaUsages);
473
517
  const loaded = { spec, specPath: entry, rootDir: root, dependencies, cacheKey, sourceLocations, schemaUsages };
474
518
  specCache.set(cacheId, { loaded, locations });
475
- if (specCache.size > MAX_CACHED_SPECS)
519
+ if (specCache.size > limits.maxCachedSpecs)
476
520
  specCache.delete(specCache.keys().next().value);
477
521
  return { ...loaded, fromCache: false };
478
522
  }
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { OPENAPI_MCP_INSTRUCTIONS, OPENAPI_MCP_VERSION, OPENAPI_PROMPTS, OPENAPI_RESOURCES, OPENAPI_TOOLS, createOpenApiMcpServer, getOpenApiPrompt, type OpenApiMcpServerOptions } from './mcp/server.js';
3
+ import { type SelfUpdateOptions } from './cli/update.js';
3
4
  export * from './engine/index.js';
4
5
  export { OPENAPI_MCP_INSTRUCTIONS, OPENAPI_MCP_VERSION, OPENAPI_PROMPTS, OPENAPI_RESOURCES, OPENAPI_TOOLS, createOpenApiMcpServer, getOpenApiPrompt, type OpenApiMcpServerOptions, };
5
6
  export interface CheckCliOptions {
@@ -15,6 +16,11 @@ export interface DiffCliOptions {
15
16
  failOnBreaking?: boolean;
16
17
  json?: boolean;
17
18
  }
19
+ export interface StatsCliOptions {
20
+ rootDir?: string;
21
+ days?: number;
22
+ json?: boolean;
23
+ }
18
24
  export type ParsedCliCommand = {
19
25
  action: 'help';
20
26
  options: OpenApiMcpServerOptions;
@@ -30,6 +36,12 @@ export type ParsedCliCommand = {
30
36
  } | {
31
37
  action: 'diff';
32
38
  options: DiffCliOptions;
39
+ } | {
40
+ action: 'stats';
41
+ options: StatsCliOptions;
42
+ } | {
43
+ action: 'update';
44
+ options: SelfUpdateOptions;
33
45
  };
34
46
  export declare function parseCliArgs(argv: string[], isTTY: boolean): ParsedCliCommand;
35
47
  export declare function runCheckCommand(options: CheckCliOptions): number;
package/dist/index.js CHANGED
@@ -4,6 +4,8 @@ import { fileURLToPath } from 'node:url';
4
4
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
5
5
  import { diagnoseOpenApiSpec, diffOpenApiSpecs, loadOpenApiSpec, } from './engine/index.js';
6
6
  import { OPENAPI_MCP_INSTRUCTIONS, OPENAPI_MCP_VERSION, OPENAPI_PROMPTS, OPENAPI_RESOURCES, OPENAPI_TOOLS, createOpenApiMcpServer, getOpenApiPrompt, } from './mcp/server.js';
7
+ import { runOpenApiMcpUpdate } from './cli/update.js';
8
+ import { formatOpenApiStatsText, OpenApiTelemetry } from './telemetry/telemetry.js';
7
9
  export * from './engine/index.js';
8
10
  export { OPENAPI_MCP_INSTRUCTIONS, OPENAPI_MCP_VERSION, OPENAPI_PROMPTS, OPENAPI_RESOURCES, OPENAPI_TOOLS, createOpenApiMcpServer, getOpenApiPrompt, };
9
11
  function writeStderr(message) {
@@ -23,13 +25,15 @@ function getHelpText() {
23
25
  ' serve Start the MCP server over stdio (default when stdin is piped)',
24
26
  ' check Validate an OpenAPI spec and report contract issues',
25
27
  ' diff <base> <target> Compare two OpenAPI specs for breaking changes',
28
+ ' stats Show persisted MCP telemetry and context savings (--root, --days, --json)',
29
+ ' update [version] Update openapi-mcp to latest (or specified) version (--check, --json)',
26
30
  '',
27
31
  'Options:',
28
32
  ' --root <dir> Workspace root directory (defaults to current directory)',
29
33
  ' --spec <path> Path to OpenAPI spec file (serve, check)',
30
34
  ' --strict Exit with code 1 if warnings are found (check)',
31
35
  ' --fail-on-breaking Exit with code 1 if breaking changes are found (diff)',
32
- ' --json Output results as JSON (check, diff)',
36
+ ' --json Output results as JSON (check, diff, stats, update)',
33
37
  ' -h, --help Show this help message',
34
38
  ' -v, --version Show version number',
35
39
  '',
@@ -141,6 +145,59 @@ export function parseCliArgs(argv, isTTY) {
141
145
  },
142
146
  };
143
147
  }
148
+ if (argv[0] === 'update') {
149
+ const updateOptions = {};
150
+ for (let i = 1; i < argv.length; i++) {
151
+ const arg = argv[i];
152
+ if (arg === '--help' || arg === '-h')
153
+ return { action: 'help', options: {} };
154
+ if (arg === '--check') {
155
+ updateOptions.check = true;
156
+ continue;
157
+ }
158
+ if (arg === '--json') {
159
+ updateOptions.json = true;
160
+ continue;
161
+ }
162
+ if (arg.startsWith('-')) {
163
+ throw new Error(`Unknown option for 'update': '${arg}'. Run 'openapi-mcp --help' for usage.`);
164
+ }
165
+ if (updateOptions.version) {
166
+ throw new Error(`Unexpected argument '${arg}' for 'update'. Expected at most one [version].`);
167
+ }
168
+ updateOptions.version = arg;
169
+ }
170
+ return { action: 'update', options: updateOptions };
171
+ }
172
+ if (argv[0] === 'stats') {
173
+ const statsOptions = {};
174
+ for (let i = 1; i < argv.length; i++) {
175
+ const arg = argv[i];
176
+ if (arg === '--help' || arg === '-h')
177
+ return { action: 'help', options: {} };
178
+ if (arg === '--json') {
179
+ statsOptions.json = true;
180
+ continue;
181
+ }
182
+ if (arg === '--days' || arg.startsWith('--days=')) {
183
+ const raw = arg === '--days' ? argv[++i] : arg.slice('--days='.length);
184
+ const parsed = raw ? Number(raw) : NaN;
185
+ if (!Number.isFinite(parsed) || parsed <= 0) {
186
+ throw new Error("Flag '--days' requires a positive number.");
187
+ }
188
+ statsOptions.days = parsed;
189
+ continue;
190
+ }
191
+ const rootFlag = readFlagValue(argv, i, '--root', 'directory path', '<dir>');
192
+ if (rootFlag) {
193
+ statsOptions.rootDir = rootFlag.value;
194
+ i = rootFlag.nextIndex;
195
+ continue;
196
+ }
197
+ throw new Error(`Unknown option for 'stats': '${arg}'. Run 'openapi-mcp --help' for usage.`);
198
+ }
199
+ return { action: 'stats', options: statsOptions };
200
+ }
144
201
  let i = 0;
145
202
  const options = {};
146
203
  if (argv[0] === 'serve') {
@@ -277,6 +334,27 @@ if (isDirectExecution) {
277
334
  else if (parsed.action === 'diff') {
278
335
  process.exit(runDiffCommand(parsed.options));
279
336
  }
337
+ else if (parsed.action === 'stats') {
338
+ const summary = OpenApiTelemetry.getSummary({
339
+ workspaceRoot: parsed.options.rootDir ?? process.cwd(),
340
+ filterWorkspace: parsed.options.rootDir,
341
+ days: parsed.options.days,
342
+ });
343
+ writeStdout(parsed.options.json ? JSON.stringify(summary, null, 2) : formatOpenApiStatsText(summary));
344
+ process.exit(0);
345
+ }
346
+ else if (parsed.action === 'update') {
347
+ runOpenApiMcpUpdate(parsed.options)
348
+ .then((result) => {
349
+ writeStdout(parsed.options.json ? JSON.stringify(result, null, 2) : result.message);
350
+ process.exit(0);
351
+ })
352
+ .catch((err) => {
353
+ const message = err instanceof Error ? err.message : String(err);
354
+ writeStderr(`[openapi-mcp] ${message}`);
355
+ process.exit(1);
356
+ });
357
+ }
280
358
  else {
281
359
  runStdioServer(parsed.options).catch((err) => {
282
360
  const message = err instanceof Error ? err.stack || err.message : String(err);
@@ -81,8 +81,8 @@ export function getOpenApiPrompt(name, args = {}) {
81
81
  type: 'text',
82
82
  text: [
83
83
  `Synchronize frontend API integration ${targetLabel} using the OpenAPI spec as SSOT:`,
84
- '1. Read resource `openapi://endpoints/index` (and `openapi://schemas/index` if shared models are involved) to verify exact path, HTTP method, auth `security`, `sourceLocation`, and all declared status codes (`2xx`, `4xx`, `5xx`).',
85
- `2. Call \`openapi_query\` with \`code\` (and optional \`spec_path\` / \`root\` / \`max_bytes\`) using \`${querySnippet}\` to inspect merged path+operation \`parameters\`, \`requestBody\`, \`2xx\` responses, AND every \`4xx\`/\`5xx\` error schema.`,
84
+ '1. Read resource `openapi://endpoints/index` or call `openapi_inspect({ target: "endpoints" })` (plus `openapi://schemas/index` if shared models are involved) to verify exact path, HTTP method, auth `security`, `sourceLocation`, and declared status codes (`2xx`, `4xx`, `5xx`).',
85
+ `2. Expand a single subtree lazily with \`openapi_inspect({ pointer: "/paths/..." })\` or call \`openapi_query\` with \`${querySnippet}\` to inspect merged path+operation \`parameters\`, \`requestBody\`, \`2xx\` responses, AND every \`4xx\`/\`5xx\` error schema.`,
86
86
  '3. Compare request payloads, auth headers, success DTOs, and error handling branches (status codes, error codes, ProblemDetails/validation fields) in the frontend codebase against the queried OpenAPI contract and align any mismatches.',
87
87
  ].join('\n'),
88
88
  },
@@ -103,8 +103,8 @@ export function getOpenApiPrompt(name, args = {}) {
103
103
  type: 'text',
104
104
  text: [
105
105
  `Audit 4xx/5xx error contracts ${scopeLabel}:`,
106
- '1. Read `openapi://spec/diagnostics` and `openapi://endpoints/index` to inspect `MISSING_ERROR_CONTRACT`, `ERROR_RESPONSE_MISSING_SCHEMA`, `endpointsMissingErrorContracts`, and each endpoint\'s `errorStatusCodes` / `errorBodies`.',
107
- `2. Call \`openapi_query\` with \`code\` (and optional \`spec_path\` / \`root\` / \`max_bytes\`) to inspect error response schemas (e.g. \`${queryExample}\`) and verify consistent error structures (such as ProblemDetails / validation error fields) for 400, 401, 403, 404, 422, and 500 responses.`,
106
+ '1. Read `openapi://spec/diagnostics` and `openapi://endpoints/index` (or call `openapi_diagnostics` / `openapi_inspect`) to inspect `MISSING_ERROR_CONTRACT`, `ERROR_RESPONSE_MISSING_SCHEMA`, `endpointsMissingErrorContracts`, and each endpoint\'s `errorStatusCodes` / `errorBodies`.',
107
+ `2. Expand specific operations lazily with \`openapi_inspect({ pointer: "/paths/..." })\` or call \`openapi_query\` with \`code\` (e.g. \`${queryExample}\`) to verify consistent error structures (ProblemDetails / validation fields) for 400, 401, 403, 404, 422, and 500 responses.`,
108
108
  '3. Summarize gaps, missing status codes, and schema inconsistencies with exact `sourceLocation` and concrete remediation steps.',
109
109
  ].join('\n'),
110
110
  },
@@ -146,7 +146,7 @@ export function getOpenApiPrompt(name, args = {}) {
146
146
  type: 'text',
147
147
  text: [
148
148
  `Generate deterministic API test fixtures ${targetLabel}:`,
149
- '1. Read `openapi://endpoints/index` to verify exact method, path, auth requirements, and declared `2xx` / `4xx` / `5xx` status codes.',
149
+ '1. Read `openapi://endpoints/index` or call `openapi_inspect({ target: "endpoints" })` (plus `openapi_inspect({ pointer: "/paths/..." })` for lazy subtree details) to verify exact method, path, auth requirements, and declared `2xx` / `4xx` / `5xx` status codes.',
150
150
  `2. Call \`openapi_query\` with \`code\`: \`${exampleSnippet}\` (and \`${opSnippet}\` for required parameters/headers) to synthesize deterministic JSON payloads for request bodies, success responses, and error responses.`,
151
151
  '3. Convert the generated payloads into unit, integration, or E2E test fixtures covering both happy-path `2xx` responses and `4xx`/`5xx` error branches.',
152
152
  ].join('\n'),
@@ -1,5 +1,5 @@
1
1
  import type { Server } from '@modelcontextprotocol/sdk/server/index.js';
2
- import { type LoadedOpenApiSpec } from '../engine/index.js';
2
+ import { buildEndpointIndex, buildSchemaIndex, type LoadedOpenApiSpec } from '../engine/index.js';
3
3
  export declare const OPENAPI_RESOURCES: readonly [{
4
4
  readonly uri: "openapi://endpoints/index";
5
5
  readonly name: "OpenAPI Endpoints Index";
@@ -22,9 +22,12 @@ export declare const OPENAPI_RESOURCES: readonly [{
22
22
  readonly mimeType: "application/json";
23
23
  }];
24
24
  export interface ResourceHandlerContext {
25
- defaultRoot: string;
25
+ getDefaultRoot: () => string;
26
26
  configuredRoot?: string;
27
27
  defaultSpec?: string;
28
+ ensureRootsReady: () => Promise<void>;
28
29
  readSpec: (root?: string, specPath?: string) => LoadedOpenApiSpec;
30
+ getEndpointIndex: (loaded: LoadedOpenApiSpec) => ReturnType<typeof buildEndpointIndex>;
31
+ getSchemaIndex: (loaded: LoadedOpenApiSpec) => ReturnType<typeof buildSchemaIndex>;
29
32
  }
30
33
  export declare function registerResourceHandlers(server: Server, ctx: ResourceHandlerContext): void;