@dimassetoid/openapi-mcp 0.0.0-stage → 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.
Files changed (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +144 -2
  3. package/dist/cli/update.d.ts +38 -0
  4. package/dist/cli/update.js +235 -0
  5. package/dist/engine/budget.d.ts +40 -0
  6. package/dist/engine/budget.js +96 -0
  7. package/dist/engine/example-generator.d.ts +47 -0
  8. package/dist/engine/example-generator.js +273 -0
  9. package/dist/engine/index-builder.d.ts +50 -0
  10. package/dist/engine/index-builder.js +155 -0
  11. package/dist/engine/index.d.ts +12 -0
  12. package/dist/engine/index.js +12 -0
  13. package/dist/engine/json.d.ts +1 -0
  14. package/dist/engine/json.js +3 -0
  15. package/dist/engine/lazy-expander.d.ts +37 -0
  16. package/dist/engine/lazy-expander.js +235 -0
  17. package/dist/engine/openapi-utils.d.ts +13 -0
  18. package/dist/engine/openapi-utils.js +48 -0
  19. package/dist/engine/query-sandbox.d.ts +29 -0
  20. package/dist/engine/query-sandbox.js +345 -0
  21. package/dist/engine/schema-index.d.ts +42 -0
  22. package/dist/engine/schema-index.js +145 -0
  23. package/dist/engine/source-map.d.ts +15 -0
  24. package/dist/engine/source-map.js +50 -0
  25. package/dist/engine/spec-catalog.d.ts +14 -0
  26. package/dist/engine/spec-catalog.js +99 -0
  27. package/dist/engine/spec-diagnostics.d.ts +28 -0
  28. package/dist/engine/spec-diagnostics.js +393 -0
  29. package/dist/engine/spec-diff.d.ts +32 -0
  30. package/dist/engine/spec-diff.js +406 -0
  31. package/dist/engine/spec-loader.d.ts +100 -0
  32. package/dist/engine/spec-loader.js +528 -0
  33. package/dist/index.d.ts +49 -0
  34. package/dist/index.js +371 -0
  35. package/dist/mcp/prompts.d.ts +51 -0
  36. package/dist/mcp/prompts.js +161 -0
  37. package/dist/mcp/resources.d.ts +33 -0
  38. package/dist/mcp/resources.js +207 -0
  39. package/dist/mcp/server.d.ts +88 -0
  40. package/dist/mcp/server.js +588 -0
  41. package/dist/telemetry/telemetry.d.ts +90 -0
  42. package/dist/telemetry/telemetry.js +299 -0
  43. package/docs/feature/README.md +53 -0
  44. package/docs/feature/getting-started.md +167 -0
  45. package/docs/feature/index-and-prompts.md +53 -0
  46. package/docs/feature/openapi-query.md +53 -0
  47. package/docs/feature/spec-loader.md +34 -0
  48. package/package.json +77 -4
  49. package/skills/use-openapi-mcp/SKILL.md +43 -0
@@ -0,0 +1,393 @@
1
+ import { dirname, relative } from 'node:path';
2
+ import { HTTP_METHODS } from './index-builder.js';
3
+ import { isRecord } from './json.js';
4
+ import { extractSecuritySchemeNames, isErrorStatusCode } from './openapi-utils.js';
5
+ import { escapeJsonPointer, parseDocumentWithLocations } from './source-map.js';
6
+ import { MAX_SPEC_BYTES, MAX_SPEC_FILES, assertWorkspaceRoot, findOpenApiSpecFile, readBoundedFileSnapshot, resolveJsonPointerSafe, resolveSafeSpecPath, } from './spec-loader.js';
7
+ const MAX_DIAGNOSTIC_ISSUES = 200;
8
+ const MAX_DIAGNOSTIC_VISITS = 250_000;
9
+ const MAX_DIAGNOSTIC_DEPTH = 128;
10
+ function extractPathTemplateParams(pathKey) {
11
+ const params = [];
12
+ const regex = /\{([^}]+)\}/g;
13
+ let match;
14
+ while ((match = regex.exec(pathKey)) !== null) {
15
+ const name = match[1]?.trim();
16
+ if (name)
17
+ params.push(name);
18
+ }
19
+ return params;
20
+ }
21
+ /**
22
+ * Performs a non-throwing, multi-issue structural & contract diagnostic pass on an OpenAPI spec.
23
+ * Enforces the same workspace boundary, `O_NOFOLLOW`, cumulative byte (`MAX_SPEC_BYTES`),
24
+ * and file-count (`MAX_SPEC_FILES`) bounds as `loadOpenApiSpec`.
25
+ */
26
+ export function diagnoseOpenApiSpec(options = {}) {
27
+ const rootInput = options.rootDir?.trim() || process.cwd();
28
+ const rootReal = assertWorkspaceRoot(rootInput, options.allowedRootDir);
29
+ const entryPath = findOpenApiSpecFile(rootInput, options.specPath);
30
+ const relEntry = relative(rootReal, entryPath).replace(/\\/g, '/');
31
+ const issues = [];
32
+ let truncated = false;
33
+ const pushIssue = (issue) => {
34
+ if (issues.length >= MAX_DIAGNOSTIC_ISSUES) {
35
+ truncated = true;
36
+ return;
37
+ }
38
+ issues.push(issue);
39
+ };
40
+ const parsedCache = new Map();
41
+ let remainingBytes = MAX_SPEC_BYTES;
42
+ let loadedFiles = 0;
43
+ function loadRawFile(canonicalPath) {
44
+ const cached = parsedCache.get(canonicalPath);
45
+ if (cached)
46
+ return cached;
47
+ if (loadedFiles >= MAX_SPEC_FILES) {
48
+ const res = { error: `SPEC_LIMIT: At most ${MAX_SPEC_FILES} source files are supported.` };
49
+ parsedCache.set(canonicalPath, res);
50
+ return res;
51
+ }
52
+ try {
53
+ const file = readBoundedFileSnapshot(canonicalPath, remainingBytes);
54
+ remainingBytes -= file.size;
55
+ loadedFiles++;
56
+ const rel = relative(rootReal, canonicalPath).replace(/\\/g, '/');
57
+ const parsed = parseDocumentWithLocations(file.content, rel);
58
+ parsedCache.set(canonicalPath, parsed);
59
+ return parsed;
60
+ }
61
+ catch (err) {
62
+ const res = { error: err instanceof Error ? err.message.slice(0, 300) : String(err) };
63
+ parsedCache.set(canonicalPath, res);
64
+ return res;
65
+ }
66
+ }
67
+ const entryParsed = loadRawFile(entryPath);
68
+ if ('error' in entryParsed) {
69
+ pushIssue({
70
+ severity: 'error',
71
+ code: 'SPEC_PARSE_ERROR',
72
+ message: entryParsed.error,
73
+ location: { file: relEntry, line: 1, col: 1 },
74
+ });
75
+ return finalizeReport(entryPath, issues, truncated);
76
+ }
77
+ if (!isRecord(entryParsed.value)) {
78
+ pushIssue({
79
+ severity: 'error',
80
+ code: 'SPEC_PARSE_ERROR',
81
+ message: 'Root OpenAPI document must be a YAML/JSON object.',
82
+ location: { file: relEntry, line: 1, col: 1 },
83
+ });
84
+ return finalizeReport(entryPath, issues, truncated);
85
+ }
86
+ const doc = entryParsed.value;
87
+ const locMap = entryParsed.locations;
88
+ if (typeof doc.openapi !== 'string' && typeof doc.swagger !== 'string') {
89
+ pushIssue({
90
+ severity: 'error',
91
+ code: 'MISSING_OPENAPI_VERSION',
92
+ message: 'Document must declare either an "openapi" (3.x) or "swagger" ("2.0") version field.',
93
+ pointer: '',
94
+ });
95
+ }
96
+ if (!isRecord(doc.info) || typeof doc.info.title !== 'string' || !doc.info.title.trim()) {
97
+ pushIssue({
98
+ severity: 'warning',
99
+ code: 'MISSING_INFO_TITLE',
100
+ message: 'Document should declare a non-empty "info.title".',
101
+ pointer: '/info',
102
+ });
103
+ }
104
+ // 1. Walk raw document to detect all broken/remote/escaping $refs in one pass.
105
+ let visits = 0;
106
+ const seenObjects = new WeakSet();
107
+ function scanRefs(node, pointer, depth, inLiteral) {
108
+ if (++visits > MAX_DIAGNOSTIC_VISITS || depth > MAX_DIAGNOSTIC_DEPTH)
109
+ return;
110
+ if (node === null || typeof node !== 'object')
111
+ return;
112
+ if (seenObjects.has(node))
113
+ return;
114
+ seenObjects.add(node);
115
+ if (Array.isArray(node)) {
116
+ for (let i = 0; i < node.length; i++) {
117
+ scanRefs(node[i], `${pointer}/${i}`, depth + 1, inLiteral);
118
+ }
119
+ return;
120
+ }
121
+ const record = node;
122
+ if (!inLiteral && typeof record.$ref === 'string') {
123
+ const ref = record.$ref.trim();
124
+ const hash = ref.indexOf('#');
125
+ const filePart = hash < 0 ? ref : ref.slice(0, hash);
126
+ const fragment = hash < 0 ? '' : ref.slice(hash + 1);
127
+ const nearestLoc = findNearestLocation(locMap, pointer);
128
+ let targetDoc = doc;
129
+ if (filePart) {
130
+ try {
131
+ const targetCanonical = resolveSafeSpecPath(filePart, rootReal, dirname(entryPath), rootInput);
132
+ const loadedTarget = loadRawFile(targetCanonical);
133
+ if ('error' in loadedTarget) {
134
+ pushIssue({
135
+ severity: 'error',
136
+ code: 'REF_PARSE_ERROR',
137
+ message: `Referenced file '${filePart}' failed to parse: ${loadedTarget.error}`,
138
+ pointer,
139
+ ...(nearestLoc ? { location: nearestLoc } : {}),
140
+ });
141
+ return;
142
+ }
143
+ targetDoc = loadedTarget.value;
144
+ }
145
+ catch (err) {
146
+ const msg = err instanceof Error ? err.message : String(err);
147
+ const code = msg.startsWith('REMOTE_REF_DENIED:')
148
+ ? 'REMOTE_REF_DENIED'
149
+ : msg.startsWith('PATH_TRAVERSAL_DENIED:')
150
+ ? 'PATH_TRAVERSAL_DENIED'
151
+ : 'BROKEN_REF';
152
+ pushIssue({
153
+ severity: 'error',
154
+ code,
155
+ message: `Broken $ref '${ref}': ${msg}`,
156
+ pointer,
157
+ ...(nearestLoc ? { location: nearestLoc } : {}),
158
+ });
159
+ return;
160
+ }
161
+ }
162
+ const resolved = resolveJsonPointerSafe(targetDoc, fragment);
163
+ if (!resolved.ok) {
164
+ pushIssue({
165
+ severity: 'error',
166
+ code: 'BROKEN_REF',
167
+ message: `Unresolved $ref '${ref}': ${resolved.reason}`,
168
+ pointer,
169
+ ...(nearestLoc ? { location: nearestLoc } : {}),
170
+ });
171
+ }
172
+ return;
173
+ }
174
+ for (const [key, val] of Object.entries(record)) {
175
+ const nextLiteral = inLiteral || key === 'example' || key === 'value' || key.startsWith('x-');
176
+ scanRefs(val, `${pointer}/${escapeJsonPointer(key)}`, depth + 1, nextLiteral);
177
+ }
178
+ }
179
+ scanRefs(doc, '', 0, false);
180
+ // 2. Semantic & contract quality checks across paths/operations.
181
+ const securitySchemes = new Set(Object.keys(isRecord(doc.components) && isRecord(doc.components.securitySchemes)
182
+ ? doc.components.securitySchemes
183
+ : isRecord(doc.securityDefinitions)
184
+ ? doc.securityDefinitions
185
+ : {}));
186
+ const checkSecurity = (secField, pointer, location) => {
187
+ if (!Array.isArray(secField))
188
+ return;
189
+ for (const req of secField) {
190
+ if (!isRecord(req))
191
+ continue;
192
+ for (const schemeName of Object.keys(req)) {
193
+ if (!securitySchemes.has(schemeName)) {
194
+ pushIssue({
195
+ severity: 'error',
196
+ code: 'UNKNOWN_SECURITY_SCHEME',
197
+ message: `Security scheme '${schemeName}' is not declared in components.securitySchemes.`,
198
+ pointer,
199
+ ...(location ? { location } : {}),
200
+ });
201
+ }
202
+ }
203
+ }
204
+ };
205
+ checkSecurity(doc.security, '/security', locMap.get('/security'));
206
+ const globalSecurity = extractSecuritySchemeNames(doc.security);
207
+ const resolveRefObject = (candidate) => {
208
+ let current = candidate;
209
+ let currentFile = entryPath;
210
+ let currentDoc = doc;
211
+ const seen = new Set();
212
+ for (let depth = 0; depth < 8; depth++) {
213
+ if (!isRecord(current))
214
+ return undefined;
215
+ if (seen.has(current))
216
+ return undefined;
217
+ seen.add(current);
218
+ if (typeof current.$ref !== 'string')
219
+ return current;
220
+ const ref = current.$ref.trim();
221
+ const hash = ref.indexOf('#');
222
+ const filePart = hash < 0 ? ref : ref.slice(0, hash);
223
+ const fragment = hash < 0 ? '' : ref.slice(hash + 1);
224
+ let nextDoc = currentDoc;
225
+ let nextFile = currentFile;
226
+ if (filePart) {
227
+ try {
228
+ nextFile = resolveSafeSpecPath(filePart, rootReal, dirname(currentFile), rootInput);
229
+ const loadedTarget = loadRawFile(nextFile);
230
+ if ('error' in loadedTarget)
231
+ return undefined;
232
+ nextDoc = loadedTarget.value;
233
+ }
234
+ catch {
235
+ return undefined;
236
+ }
237
+ }
238
+ const resolved = resolveJsonPointerSafe(nextDoc, fragment);
239
+ if (!resolved.ok)
240
+ return undefined;
241
+ current = resolved.value;
242
+ currentFile = nextFile;
243
+ currentDoc = nextDoc;
244
+ }
245
+ return undefined;
246
+ };
247
+ const seenOperationIds = new Map();
248
+ const pathsObj = isRecord(doc.paths) ? doc.paths : {};
249
+ for (const [pathKey, pathItem] of Object.entries(pathsObj)) {
250
+ if (!isRecord(pathItem))
251
+ continue;
252
+ const escapedPath = escapeJsonPointer(pathKey);
253
+ const templateParams = extractPathTemplateParams(pathKey);
254
+ const pathLevelPathParams = new Set();
255
+ if (Array.isArray(pathItem.parameters)) {
256
+ for (const rawParam of pathItem.parameters) {
257
+ const param = resolveRefObject(rawParam);
258
+ if (param && param.in === 'path' && typeof param.name === 'string') {
259
+ pathLevelPathParams.add(param.name);
260
+ }
261
+ }
262
+ }
263
+ for (const httpMethod of HTTP_METHODS) {
264
+ const op = pathItem[httpMethod];
265
+ if (!isRecord(op))
266
+ continue;
267
+ const opPointer = `/paths/${escapedPath}/${httpMethod}`;
268
+ const opLoc = locMap.get(opPointer);
269
+ const opLabel = `${httpMethod.toUpperCase()} ${pathKey}`;
270
+ if (typeof op.operationId === 'string' && op.operationId.trim()) {
271
+ const opId = op.operationId.trim();
272
+ const existing = seenOperationIds.get(opId);
273
+ if (existing) {
274
+ pushIssue({
275
+ severity: 'error',
276
+ code: 'DUPLICATE_OPERATION_ID',
277
+ message: `Duplicate operationId '${opId}' on ${opLabel} (already used by ${existing}).`,
278
+ pointer: opPointer,
279
+ ...(opLoc ? { location: opLoc } : {}),
280
+ });
281
+ }
282
+ else {
283
+ seenOperationIds.set(opId, opLabel);
284
+ }
285
+ }
286
+ if (templateParams.length > 0) {
287
+ const declared = new Set(pathLevelPathParams);
288
+ if (Array.isArray(op.parameters)) {
289
+ for (const rawParam of op.parameters) {
290
+ const param = resolveRefObject(rawParam);
291
+ if (param && param.in === 'path' && typeof param.name === 'string') {
292
+ declared.add(param.name);
293
+ }
294
+ }
295
+ }
296
+ for (const tpl of templateParams) {
297
+ if (!declared.has(tpl)) {
298
+ pushIssue({
299
+ severity: 'error',
300
+ code: 'UNDECLARED_PATH_PARAMETER',
301
+ message: `Path template parameter '{${tpl}}' on ${opLabel} is not declared in parameters with in: "path".`,
302
+ pointer: opPointer,
303
+ ...(opLoc ? { location: opLoc } : {}),
304
+ });
305
+ }
306
+ }
307
+ }
308
+ checkSecurity(op.security, `${opPointer}/security`, opLoc);
309
+ const opSecurity = extractSecuritySchemeNames(op.security);
310
+ const effectiveSecurity = opSecurity !== undefined ? opSecurity : globalSecurity;
311
+ const requiresAuth = effectiveSecurity !== undefined && effectiveSecurity.length > 0;
312
+ const responses = isRecord(op.responses) ? op.responses : {};
313
+ const responseCodes = Object.keys(responses);
314
+ const errorCodes = responseCodes.filter(isErrorStatusCode);
315
+ if (requiresAuth && !responseCodes.some((c) => /^(?:401|403|4xx)$/i.test(c.trim()))) {
316
+ pushIssue({
317
+ severity: 'info',
318
+ code: 'AUTH_ENDPOINT_MISSING_401_403',
319
+ message: `Protected operation ${opLabel} declares security (${effectiveSecurity.join(', ')}) without a 401/403 response.`,
320
+ pointer: opPointer,
321
+ ...(opLoc ? { location: opLoc } : {}),
322
+ });
323
+ }
324
+ if (errorCodes.length === 0) {
325
+ pushIssue({
326
+ severity: 'warning',
327
+ code: 'MISSING_ERROR_CONTRACT',
328
+ message: `Operation ${opLabel} declares no 4xx/5xx error responses.`,
329
+ pointer: opPointer,
330
+ ...(opLoc ? { location: opLoc } : {}),
331
+ });
332
+ }
333
+ else {
334
+ for (const code of errorCodes) {
335
+ const resp = resolveRefObject(responses[code]);
336
+ if (!resp)
337
+ continue;
338
+ const content = isRecord(resp.content) ? resp.content : undefined;
339
+ const hasSchema = (content && Object.values(content).some((m) => isRecord(m) && (isRecord(m.schema) || typeof m.schema === 'boolean'))) ||
340
+ (doc.swagger === '2.0' && isRecord(resp.schema));
341
+ if (!hasSchema) {
342
+ pushIssue({
343
+ severity: 'warning',
344
+ code: 'ERROR_RESPONSE_MISSING_SCHEMA',
345
+ message: `Error response ${code} on ${opLabel} has no body schema declared.`,
346
+ pointer: `${opPointer}/responses/${escapeJsonPointer(code)}`,
347
+ ...(opLoc ? { location: opLoc } : {}),
348
+ });
349
+ }
350
+ }
351
+ }
352
+ }
353
+ }
354
+ return finalizeReport(entryPath, issues, truncated);
355
+ }
356
+ function findNearestLocation(locMap, pointer) {
357
+ let current = pointer;
358
+ while (current.length > 0) {
359
+ const hit = locMap.get(current);
360
+ if (hit)
361
+ return hit;
362
+ const idx = current.lastIndexOf('/');
363
+ if (idx <= 0)
364
+ break;
365
+ current = current.slice(0, idx);
366
+ }
367
+ return undefined;
368
+ }
369
+ function finalizeReport(specPath, issues, truncated) {
370
+ let errors = 0;
371
+ let warnings = 0;
372
+ let info = 0;
373
+ for (const issue of issues) {
374
+ if (issue.severity === 'error')
375
+ errors++;
376
+ else if (issue.severity === 'warning')
377
+ warnings++;
378
+ else
379
+ info++;
380
+ }
381
+ return {
382
+ valid: errors === 0,
383
+ specPath,
384
+ summary: {
385
+ errors,
386
+ warnings,
387
+ info,
388
+ totalIssues: issues.length,
389
+ truncated,
390
+ },
391
+ issues,
392
+ };
393
+ }
@@ -0,0 +1,32 @@
1
+ export type DiffClassification = 'breaking' | 'non_breaking';
2
+ export interface SpecDiffChange {
3
+ classification: DiffClassification;
4
+ code: string;
5
+ endpoint: string;
6
+ location?: string;
7
+ message: string;
8
+ }
9
+ export interface SpecDiffReport {
10
+ baseSpec?: string;
11
+ targetSpec?: string;
12
+ hasBreakingChanges: boolean;
13
+ summary: {
14
+ breakingCount: number;
15
+ nonBreakingCount: number;
16
+ addedEndpoints: number;
17
+ removedEndpoints: number;
18
+ totalChanges: number;
19
+ truncated: boolean;
20
+ };
21
+ breaking: SpecDiffChange[];
22
+ nonBreaking: SpecDiffChange[];
23
+ }
24
+ /**
25
+ * Semantically compares two resolved OpenAPI specifications and classifies changes into
26
+ * `breaking` vs `nonBreaking` using O(E + P + F) indexed lookups.
27
+ * Caps `breaking` and `nonBreaking` independently so non-breaking volume never starves breaking detections.
28
+ */
29
+ export declare function diffOpenApiSpecs(baseSpec: Record<string, unknown>, targetSpec: Record<string, unknown>, labels?: {
30
+ base?: string;
31
+ target?: string;
32
+ }): SpecDiffReport;