@dimassetoid/openapi-mcp 0.0.0-stage → 0.1.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.
Files changed (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +133 -2
  3. package/dist/engine/budget.d.ts +40 -0
  4. package/dist/engine/budget.js +96 -0
  5. package/dist/engine/example-generator.d.ts +47 -0
  6. package/dist/engine/example-generator.js +283 -0
  7. package/dist/engine/index-builder.d.ts +50 -0
  8. package/dist/engine/index-builder.js +179 -0
  9. package/dist/engine/index.d.ts +10 -0
  10. package/dist/engine/index.js +10 -0
  11. package/dist/engine/json.d.ts +1 -0
  12. package/dist/engine/json.js +3 -0
  13. package/dist/engine/query-sandbox.d.ts +21 -0
  14. package/dist/engine/query-sandbox.js +343 -0
  15. package/dist/engine/schema-index.d.ts +42 -0
  16. package/dist/engine/schema-index.js +151 -0
  17. package/dist/engine/source-map.d.ts +15 -0
  18. package/dist/engine/source-map.js +50 -0
  19. package/dist/engine/spec-catalog.d.ts +14 -0
  20. package/dist/engine/spec-catalog.js +99 -0
  21. package/dist/engine/spec-diagnostics.d.ts +28 -0
  22. package/dist/engine/spec-diagnostics.js +352 -0
  23. package/dist/engine/spec-diff.d.ts +31 -0
  24. package/dist/engine/spec-diff.js +408 -0
  25. package/dist/engine/spec-loader.d.ts +59 -0
  26. package/dist/engine/spec-loader.js +484 -0
  27. package/dist/index.d.ts +37 -0
  28. package/dist/index.js +293 -0
  29. package/dist/mcp/prompts.d.ts +51 -0
  30. package/dist/mcp/prompts.js +161 -0
  31. package/dist/mcp/resources.d.ts +30 -0
  32. package/dist/mcp/resources.js +187 -0
  33. package/dist/mcp/server.d.ts +43 -0
  34. package/dist/mcp/server.js +201 -0
  35. package/docs/feature/README.md +65 -0
  36. package/docs/feature/getting-started.md +131 -0
  37. package/docs/feature/index-and-prompts.md +50 -0
  38. package/docs/feature/openapi-query.md +48 -0
  39. package/docs/feature/spec-loader.md +33 -0
  40. package/package.json +77 -4
  41. package/skills/use-openapi-mcp/SKILL.md +42 -0
@@ -0,0 +1,484 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { closeSync, constants, fstatSync, openSync, readSync, realpathSync, statSync } from 'node:fs';
3
+ import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
4
+ import { isRecord } from './json.js';
5
+ import { parseDocumentWithLocations } from './source-map.js';
6
+ export const DEFAULT_SPEC_CANDIDATES = [
7
+ 'openapi.yml', 'openapi.yaml', 'openapi.json',
8
+ 'api/openapi.yml', 'api/openapi.yaml', 'api/openapi.json',
9
+ 'docs/openapi.yml', 'docs/openapi.yaml', 'docs/openapi.json',
10
+ ];
11
+ export const MAX_SPEC_BYTES = 8 * 1024 * 1024;
12
+ export const MAX_SPEC_FILES = 128;
13
+ const MAX_NODE_VISITS = 250_000;
14
+ const MAX_DEPTH = 128;
15
+ const MAX_CACHED_SPECS = 8;
16
+ export class MissingReferenceError extends Error {
17
+ code = 'REF_FILE_NOT_FOUND';
18
+ constructor(target, source) {
19
+ super(`REF_FILE_NOT_FOUND: Reference '${target}' from '${source}' does not exist. Restore the file or correct the reference.`);
20
+ }
21
+ }
22
+ const specCache = new Map();
23
+ const snapshotJson = new WeakMap();
24
+ /** Serialize loader-owned snapshots once. Library callers can also supply their own data. */
25
+ export function serializeSpec(spec) {
26
+ const cached = spec !== null && typeof spec === 'object' ? snapshotJson.get(spec) : undefined;
27
+ if (cached !== undefined)
28
+ return cached;
29
+ 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.`);
32
+ }
33
+ return text;
34
+ }
35
+ function isPathInside(root, candidate) {
36
+ const rel = relative(root, candidate);
37
+ return rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
38
+ }
39
+ function isMissing(error) {
40
+ const code = error?.code;
41
+ return code === 'ENOENT' || code === 'ENOTDIR';
42
+ }
43
+ function resolveRoot(path) {
44
+ try {
45
+ const canonicalPath = realpathSync(path);
46
+ if (statSync(canonicalPath).isDirectory())
47
+ return canonicalPath;
48
+ }
49
+ catch (error) {
50
+ if (!isMissing(error))
51
+ throw error;
52
+ }
53
+ throw new Error(`WORKSPACE_NOT_FOUND: Workspace directory '${path}' does not exist.`);
54
+ }
55
+ function resolveFile(target, root, base, rawRoot) {
56
+ const path = target.trim();
57
+ if (!path)
58
+ throw new Error('INVALID_SPEC_PATH: File path cannot be empty.');
59
+ const windowsDrivePath = process.platform === 'win32' && /^[a-z]:[\\/]/i.test(path);
60
+ if (!windowsDrivePath && /^[a-z][a-z\d+.-]*:/i.test(path)) {
61
+ throw new Error(`REMOTE_REF_DENIED: Only local workspace paths are permitted ('${target}').`);
62
+ }
63
+ const candidate = resolve(base, path);
64
+ if (!isPathInside(root, candidate) && !(rawRoot && isPathInside(resolve(rawRoot), candidate))) {
65
+ throw new Error(`PATH_TRAVERSAL_DENIED: Path '${target}' escapes workspace root '${root}'.`);
66
+ }
67
+ try {
68
+ const canonical = realpathSync(candidate);
69
+ if (!isPathInside(root, canonical)) {
70
+ throw new Error(`PATH_TRAVERSAL_DENIED: Resolved path '${target}' escapes workspace root '${root}'.`);
71
+ }
72
+ return { candidate, canonical };
73
+ }
74
+ catch (error) {
75
+ if (isMissing(error))
76
+ return undefined;
77
+ throw error;
78
+ }
79
+ }
80
+ function requireFile(target, root, base, rawRoot) {
81
+ const location = resolveFile(target, root, base, rawRoot);
82
+ if (location)
83
+ return location;
84
+ throw new Error(`SPEC_FILE_NOT_FOUND: File '${target}' does not exist inside workspace '${root}'.`);
85
+ }
86
+ export function resolveSafeSpecPath(targetPath, rootRealPath, baseDir = rootRealPath, rawRootDir) {
87
+ return requireFile(targetPath, rootRealPath, baseDir, rawRootDir).canonical;
88
+ }
89
+ function discoverSpec(root, rawRoot, explicitPath) {
90
+ if (explicitPath?.trim())
91
+ return requireFile(explicitPath, root, root, rawRoot).canonical;
92
+ for (const candidate of DEFAULT_SPEC_CANDIDATES) {
93
+ const location = resolveFile(candidate, root, root);
94
+ if (location)
95
+ return location.canonical;
96
+ }
97
+ throw new Error(`SPEC_NOT_FOUND: No OpenAPI spec in '${root}'. Checked: ${DEFAULT_SPEC_CANDIDATES.join(', ')}.`);
98
+ }
99
+ export function assertWorkspaceRoot(rootInput, allowedRootDir) {
100
+ const root = resolveRoot(rootInput);
101
+ if (allowedRootDir && allowedRootDir !== rootInput &&
102
+ !isPathInside(resolveRoot(allowedRootDir), root)) {
103
+ throw new Error('PATH_TRAVERSAL_DENIED: Requested root is outside the configured workspace.');
104
+ }
105
+ return root;
106
+ }
107
+ export function findOpenApiSpecFile(rootDir, explicitPath) {
108
+ return discoverSpec(resolveRoot(rootDir), rootDir, explicitPath);
109
+ }
110
+ export function readBoundedFileSnapshot(path, availableBytes) {
111
+ const fd = openSync(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0) | (constants.O_NOFOLLOW ?? 0));
112
+ try {
113
+ const before = fstatSync(fd);
114
+ if (!before.isFile())
115
+ throw new Error(`INVALID_SPEC_PATH: '${path}' must be a regular file.`);
116
+ if (before.size > availableBytes)
117
+ throw new Error(`SPEC_LIMIT: Source files exceed ${MAX_SPEC_BYTES} bytes.`);
118
+ const bytes = Buffer.allocUnsafe(before.size + 1);
119
+ let count = 0;
120
+ while (count < bytes.length) {
121
+ const moved = readSync(fd, bytes, count, bytes.length - count, null);
122
+ if (moved === 0)
123
+ break;
124
+ count += moved;
125
+ }
126
+ const after = fstatSync(fd);
127
+ if (count !== before.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs) {
128
+ throw new Error(`SPEC_CHANGED: '${path}' changed during read. Retry the query.`);
129
+ }
130
+ const content = bytes.subarray(0, count);
131
+ return {
132
+ fingerprint: {
133
+ filePath: path,
134
+ mtimeMs: after.mtimeMs,
135
+ ctimeMs: after.ctimeMs,
136
+ size: count,
137
+ sha256: createHash('sha256').update(content).digest('hex'),
138
+ },
139
+ content: content.toString('utf8'),
140
+ size: count,
141
+ };
142
+ }
143
+ finally {
144
+ closeSync(fd);
145
+ }
146
+ }
147
+ export function resolveJsonPointerSafe(document, fragment) {
148
+ let pointer;
149
+ try {
150
+ pointer = decodeURIComponent(fragment);
151
+ }
152
+ catch {
153
+ return { ok: false, reason: 'Invalid URI encoding in JSON Pointer.' };
154
+ }
155
+ if (pointer === '')
156
+ return { ok: true, value: document };
157
+ if (!pointer.startsWith('/'))
158
+ return { ok: false, reason: 'Fragment must use a JSON Pointer starting with "/".' };
159
+ let value = document;
160
+ for (const segment of pointer.slice(1).split('/')) {
161
+ if (/~(?![01])/.test(segment))
162
+ return { ok: false, reason: `Invalid pointer escape in '${segment}'.` };
163
+ const key = segment.replace(/~1/g, '/').replace(/~0/g, '~');
164
+ if (Array.isArray(value) && /^(0|[1-9]\d*)$/.test(key) && Number(key) < value.length) {
165
+ value = value[Number(key)];
166
+ }
167
+ else if (isRecord(value) && Object.hasOwn(value, key)) {
168
+ value = value[key];
169
+ }
170
+ else {
171
+ return { ok: false, reason: `Unresolved JSON Pointer segment '${key}'.` };
172
+ }
173
+ }
174
+ return { ok: true, value };
175
+ }
176
+ function resolvePointer(document, fragment, ref) {
177
+ const result = resolveJsonPointerSafe(document, fragment);
178
+ if (!result.ok) {
179
+ throw new Error(`INVALID_REF: '${ref}': ${result.reason}`);
180
+ }
181
+ return result.value;
182
+ }
183
+ export function deepFreeze(value, seen = new WeakSet()) {
184
+ if (value === null || typeof value !== 'object' || seen.has(value))
185
+ return value;
186
+ seen.add(value);
187
+ for (const child of Object.values(value))
188
+ deepFreeze(child, seen);
189
+ return Object.freeze(value);
190
+ }
191
+ const schemaMaps = new Set(['properties', 'patternProperties', 'dependentSchemas', '$defs', 'definitions']);
192
+ const schemaLists = new Set(['allOf', 'anyOf', 'oneOf', 'prefixItems']);
193
+ const schemaChildren = new Set([
194
+ 'items', 'additionalItems', 'additionalProperties', 'unevaluatedItems', 'unevaluatedProperties',
195
+ 'contains', 'propertyNames', 'not', 'if', 'then', 'else', 'contentSchema',
196
+ ]);
197
+ const annotations = new Set([
198
+ 'title', 'description', '$comment', 'examples', 'example', 'default', 'deprecated',
199
+ 'readOnly', 'writeOnly', 'externalDocs', 'xml',
200
+ ]);
201
+ const OPERATION_METHODS = new Set(['get', 'post', 'put', 'patch', 'delete', 'options', 'head', 'trace']);
202
+ function decodePointerSegment(segment) {
203
+ return segment.replace(/~1/g, '/').replace(/~0/g, '~');
204
+ }
205
+ function extractLocalSchemaName(fragment) {
206
+ for (const prefix of ['/components/schemas/', '/definitions/']) {
207
+ if (fragment.startsWith(prefix)) {
208
+ const rest = fragment.slice(prefix.length);
209
+ const firstSegment = rest.split('/')[0];
210
+ if (!firstSegment)
211
+ return undefined;
212
+ try {
213
+ return decodePointerSegment(decodeURIComponent(firstSegment));
214
+ }
215
+ catch {
216
+ return decodePointerSegment(firstSegment);
217
+ }
218
+ }
219
+ }
220
+ return undefined;
221
+ }
222
+ function nextOperationContext(current, inEntryFile, pointer, key) {
223
+ if (!inEntryFile)
224
+ return current;
225
+ if (!current) {
226
+ if (pointer.startsWith('/paths/')) {
227
+ const segments = pointer.slice('/paths/'.length).split('/');
228
+ if (segments.length === 1 && OPERATION_METHODS.has(key.toLowerCase())) {
229
+ return { method: key.toUpperCase(), path: decodePointerSegment(segments[0]) };
230
+ }
231
+ }
232
+ return undefined;
233
+ }
234
+ if (current.section)
235
+ return current;
236
+ if (key === 'requestBody' || key === 'parameters') {
237
+ return { ...current, section: key };
238
+ }
239
+ if (pointer.endsWith('/responses')) {
240
+ return { ...current, section: `response:${key}` };
241
+ }
242
+ return current;
243
+ }
244
+ function childPosition(parent, key, pointer) {
245
+ if (parent === 'named-map')
246
+ return 'document';
247
+ if (parent === 'example-map')
248
+ return 'example-object';
249
+ if (parent === 'example-object' && key === 'value')
250
+ return 'literal';
251
+ if (parent === 'schema-map' || parent === 'schema-list')
252
+ return 'schema';
253
+ if (parent === 'schema') {
254
+ if (schemaMaps.has(key))
255
+ return 'schema-map';
256
+ if (schemaLists.has(key))
257
+ return 'schema-list';
258
+ if (schemaChildren.has(key))
259
+ return 'schema';
260
+ return 'literal';
261
+ }
262
+ if (key === 'example' || key.startsWith('x-'))
263
+ return 'literal';
264
+ if (key === 'examples')
265
+ return 'example-map';
266
+ if (key === 'headers')
267
+ return 'named-map';
268
+ if (key === 'schema')
269
+ return 'schema';
270
+ if (pointer === '/components' && key === 'schemas')
271
+ return 'schema-map';
272
+ return 'document';
273
+ }
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);
348
+ const ancestors = new WeakSet();
349
+ const schemaUsageMap = new Map();
350
+ let visits = 0;
351
+ let expandedBytes = 0;
352
+ function recordSchemaUsage(schemaName, opCtx) {
353
+ if (!opCtx)
354
+ return;
355
+ const section = opCtx.section ?? 'operation';
356
+ const key = `${opCtx.method} ${opCtx.path}\0${section}`;
357
+ let usages = schemaUsageMap.get(schemaName);
358
+ if (!usages) {
359
+ usages = new Map();
360
+ schemaUsageMap.set(schemaName, usages);
361
+ }
362
+ if (!usages.has(key)) {
363
+ usages.set(key, { method: opCtx.method, path: opCtx.path, section });
364
+ }
365
+ }
366
+ function countBytes(bytes) {
367
+ expandedBytes += bytes;
368
+ if (expandedBytes > MAX_SPEC_BYTES)
369
+ throw new Error(`SPEC_LIMIT: Expanded spec exceeds ${MAX_SPEC_BYTES} bytes.`);
370
+ }
371
+ 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.`);
374
+ }
375
+ countBytes(4);
376
+ if (node === null || typeof node !== 'object') {
377
+ if (typeof node === 'string' || typeof node === 'number') {
378
+ if (typeof node === 'number' && !Number.isFinite(node)) {
379
+ throw new Error(`SPEC_PARSE_ERROR: Non-finite number at '${pointer}'.`);
380
+ }
381
+ countBytes(Buffer.byteLength(JSON.stringify(node)));
382
+ }
383
+ return Object.is(node, -0) ? 0 : node;
384
+ }
385
+ if (ancestors.has(node))
386
+ return `[Circular: #${pointer}]`;
387
+ ancestors.add(node);
388
+ try {
389
+ if (Array.isArray(node)) {
390
+ const itemPosition = position === 'schema-list' ? 'schema' : position;
391
+ return node.map((item, index) => expand(item, file, `${pointer}/${index}`, depth + 1, itemPosition, opCtx));
392
+ }
393
+ const prototype = Object.getPrototypeOf(node);
394
+ if (prototype !== Object.prototype && prototype !== null) {
395
+ throw new Error(`SPEC_PARSE_ERROR: Expected a JSON object at '${pointer}'.`);
396
+ }
397
+ const object = node;
398
+ if (schema31 && position === 'schema' && ('$id' in object || '$dynamicRef' in object)) {
399
+ throw new Error('INVALID_REF: Schema resource identifiers ($id) and dynamic references ($dynamicRef) are unsupported.');
400
+ }
401
+ const ref = position !== 'literal' && typeof object.$ref === 'string' ? object.$ref.trim() : undefined;
402
+ const siblings = Object.entries(object).filter(([key]) => ref === undefined || key !== '$ref');
403
+ const inEntryFile = file === entry;
404
+ const expandEntries = (entries) => Object.fromEntries(entries.map(([key, value]) => {
405
+ countBytes(Buffer.byteLength(JSON.stringify(key)));
406
+ const escaped = key.replace(/~/g, '~0').replace(/\//g, '~1');
407
+ const next = position === 'literal' ? 'literal' : childPosition(position, key, pointer);
408
+ const nextOp = nextOperationContext(opCtx, inEntryFile, pointer, key);
409
+ return [key, expand(value, file, `${pointer}/${escaped}`, depth + 1, next, nextOp)];
410
+ }));
411
+ if (ref === undefined)
412
+ return expandEntries(siblings);
413
+ const hash = ref.indexOf('#');
414
+ const path = hash < 0 ? ref : ref.slice(0, hash);
415
+ const fragment = hash < 0 ? '' : ref.slice(hash + 1);
416
+ let targetFile = file;
417
+ if (path) {
418
+ const location = resolveFile(path, root, dirname(file));
419
+ if (!location)
420
+ throw new MissingReferenceError(path, file);
421
+ locations.set(location.candidate, location.canonical);
422
+ targetFile = location.canonical;
423
+ }
424
+ if (targetFile === entry && opCtx) {
425
+ const schemaName = extractLocalSchemaName(fragment);
426
+ if (schemaName)
427
+ recordSchemaUsage(schemaName, opCtx);
428
+ }
429
+ const target = resolvePointer(parseFile(targetFile), fragment, ref);
430
+ if (target !== null && typeof target === 'object' && ancestors.has(target)) {
431
+ countBytes(Buffer.byteLength(ref));
432
+ return `[Circular: ${ref}]`;
433
+ }
434
+ const resolved = expand(target, targetFile, fragment, depth + 1, position, opCtx);
435
+ if (siblings.length === 0)
436
+ return resolved;
437
+ if (schema31 && position === 'schema') {
438
+ if (siblings.some(([key]) => !annotations.has(key)) || !isRecord(resolved)) {
439
+ const local = expandEntries(siblings);
440
+ if (local.allOf !== undefined && !Array.isArray(local.allOf)) {
441
+ throw new Error('INVALID_REF: Schema keyword allOf must be an array.');
442
+ }
443
+ // Keep local keywords adjacent to the reference applicator. In particular,
444
+ // unevaluatedProperties can observe properties evaluated by that applicator.
445
+ return { ...local, allOf: [resolved, ...(local.allOf ?? [])] };
446
+ }
447
+ }
448
+ return isRecord(resolved) ? { ...resolved, ...expandEntries(siblings) } : resolved;
449
+ }
450
+ finally {
451
+ ancestors.delete(node);
452
+ }
453
+ }
454
+ const resolved = expand(document, entry, '', 0, 'document');
455
+ if (!isRecord(resolved))
456
+ throw new Error('SPEC_PARSE_ERROR: Resolved entry specification must be an object.');
457
+ const spec = deepFreeze(resolved);
458
+ snapshotJson.set(spec, serializeSpec(spec));
459
+ const dependencies = [...parsedFiles.keys()].map((path) => snapshot(path).fingerprint);
460
+ const cacheKey = createHash('sha256').update(JSON.stringify(dependencies)).digest('hex');
461
+ const entryLocations = fileSourceLocations.get(entry);
462
+ const sourceLocations = entryLocations
463
+ ? Object.fromEntries(entryLocations.entries())
464
+ : {};
465
+ const schemaUsages = {};
466
+ for (const [schemaName, usages] of schemaUsageMap.entries()) {
467
+ schemaUsages[schemaName] = [...usages.values()].sort((a, b) => `${a.method} ${a.path} ${a.section}`.localeCompare(`${b.method} ${b.path} ${b.section}`));
468
+ }
469
+ // Freeze the cache's validation inputs and metadata so library callers cannot mutate them.
470
+ deepFreeze(dependencies);
471
+ deepFreeze(sourceLocations);
472
+ deepFreeze(schemaUsages);
473
+ const loaded = { spec, specPath: entry, rootDir: root, dependencies, cacheKey, sourceLocations, schemaUsages };
474
+ specCache.set(cacheId, { loaded, locations });
475
+ if (specCache.size > MAX_CACHED_SPECS)
476
+ specCache.delete(specCache.keys().next().value);
477
+ return { ...loaded, fromCache: false };
478
+ }
479
+ export function clearSpecCache() {
480
+ specCache.clear();
481
+ }
482
+ export function getSpecCacheStats() {
483
+ return { size: specCache.size, entries: [...specCache.keys()] };
484
+ }
@@ -0,0 +1,37 @@
1
+ #!/usr/bin/env node
2
+ import { OPENAPI_MCP_INSTRUCTIONS, OPENAPI_MCP_VERSION, OPENAPI_PROMPTS, OPENAPI_RESOURCES, OPENAPI_TOOLS, createOpenApiMcpServer, getOpenApiPrompt, type OpenApiMcpServerOptions } from './mcp/server.js';
3
+ export * from './engine/index.js';
4
+ export { OPENAPI_MCP_INSTRUCTIONS, OPENAPI_MCP_VERSION, OPENAPI_PROMPTS, OPENAPI_RESOURCES, OPENAPI_TOOLS, createOpenApiMcpServer, getOpenApiPrompt, type OpenApiMcpServerOptions, };
5
+ export interface CheckCliOptions {
6
+ rootDir?: string;
7
+ specPath?: string;
8
+ strict?: boolean;
9
+ json?: boolean;
10
+ }
11
+ export interface DiffCliOptions {
12
+ baseSpecPath: string;
13
+ targetSpecPath: string;
14
+ rootDir?: string;
15
+ failOnBreaking?: boolean;
16
+ json?: boolean;
17
+ }
18
+ export type ParsedCliCommand = {
19
+ action: 'help';
20
+ options: OpenApiMcpServerOptions;
21
+ } | {
22
+ action: 'version';
23
+ options: OpenApiMcpServerOptions;
24
+ } | {
25
+ action: 'serve';
26
+ options: OpenApiMcpServerOptions;
27
+ } | {
28
+ action: 'check';
29
+ options: CheckCliOptions;
30
+ } | {
31
+ action: 'diff';
32
+ options: DiffCliOptions;
33
+ };
34
+ export declare function parseCliArgs(argv: string[], isTTY: boolean): ParsedCliCommand;
35
+ export declare function runCheckCommand(options: CheckCliOptions): number;
36
+ export declare function runDiffCommand(options: DiffCliOptions): number;
37
+ export declare function runStdioServer(options?: OpenApiMcpServerOptions): Promise<void>;