@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,151 @@
1
+ import { isRecord } from './json.js';
2
+ import { escapeJsonPointer } from './source-map.js';
3
+ const MAX_LISTED_PROPERTIES = 40;
4
+ const MAX_LISTED_ENUM = 20;
5
+ function inferSchemaType(schema) {
6
+ if (typeof schema === 'boolean')
7
+ return schema ? 'any' : 'never';
8
+ if (!isRecord(schema))
9
+ return 'unknown';
10
+ if (typeof schema.type === 'string')
11
+ return schema.type;
12
+ if (Array.isArray(schema.type)) {
13
+ const types = schema.type.filter((t) => typeof t === 'string');
14
+ if (types.length > 0)
15
+ return types.join(' | ');
16
+ }
17
+ if (Array.isArray(schema.oneOf))
18
+ return 'oneOf';
19
+ if (Array.isArray(schema.anyOf))
20
+ return 'anyOf';
21
+ if (Array.isArray(schema.allOf))
22
+ return 'allOf';
23
+ if (Array.isArray(schema.enum))
24
+ return 'enum';
25
+ if (isRecord(schema.properties))
26
+ return 'object';
27
+ if (schema.items !== undefined)
28
+ return 'array';
29
+ return 'unknown';
30
+ }
31
+ function collectObjectProperties(schema) {
32
+ const properties = new Set();
33
+ const required = new Set();
34
+ const visit = (node, depth) => {
35
+ if (depth > 4 || !isRecord(node))
36
+ return;
37
+ if (isRecord(node.properties)) {
38
+ for (const key of Object.keys(node.properties))
39
+ properties.add(key);
40
+ }
41
+ if (Array.isArray(node.required)) {
42
+ for (const req of node.required) {
43
+ if (typeof req === 'string' && req.trim())
44
+ required.add(req);
45
+ }
46
+ }
47
+ if (Array.isArray(node.allOf)) {
48
+ for (const branch of node.allOf)
49
+ visit(branch, depth + 1);
50
+ }
51
+ };
52
+ visit(schema, 0);
53
+ return { properties: [...properties], required };
54
+ }
55
+ function formatUsage(usage) {
56
+ return `${usage.method} ${usage.path} (${usage.section})`;
57
+ }
58
+ /**
59
+ * Builds a compact index of `components.schemas` (OpenAPI 3.x) or `definitions` (Swagger 2.0),
60
+ * enriched with reverse references (`usedBy`) and YAML/JSON `sourceLocation`.
61
+ */
62
+ export function buildSchemaIndex(spec, specPath, sourceLocations, schemaUsages) {
63
+ const info = isRecord(spec.info) ? spec.info : {};
64
+ const title = typeof info.title === 'string' && info.title.trim() ? info.title.trim() : 'Untitled API';
65
+ const version = typeof info.version === 'string' && info.version.trim() ? info.version.trim() : 'unknown';
66
+ const openapiVersion = typeof spec.openapi === 'string'
67
+ ? spec.openapi
68
+ : typeof spec.swagger === 'string'
69
+ ? spec.swagger
70
+ : 'unknown';
71
+ const components = isRecord(spec.components) ? spec.components : undefined;
72
+ const schemasObj = isRecord(components?.schemas)
73
+ ? components.schemas
74
+ : isRecord(spec.definitions)
75
+ ? spec.definitions
76
+ : {};
77
+ const pointerBase = isRecord(components?.schemas) ? '/components/schemas' : '/definitions';
78
+ const schemas = [];
79
+ const unusedSchemas = [];
80
+ for (const name of Object.keys(schemasObj).sort()) {
81
+ const schema = schemasObj[name];
82
+ const type = inferSchemaType(schema);
83
+ const description = isRecord(schema) && typeof schema.description === 'string' && schema.description.trim()
84
+ ? schema.description.trim().split(/\r?\n/)[0].trim().slice(0, 140)
85
+ : undefined;
86
+ const { properties, required } = collectObjectProperties(schema);
87
+ const reqList = [...required].sort();
88
+ const enumValues = isRecord(schema) && Array.isArray(schema.enum)
89
+ ? schema.enum.slice(0, MAX_LISTED_ENUM)
90
+ : undefined;
91
+ const usages = schemaUsages?.[name] ?? [];
92
+ const usedBy = usages.map(formatUsage);
93
+ if (usedBy.length === 0)
94
+ unusedSchemas.push(name);
95
+ const sourceLocation = sourceLocations?.[`${pointerBase}/${escapeJsonPointer(name)}`];
96
+ schemas.push({
97
+ name,
98
+ type,
99
+ ...(description ? { description } : {}),
100
+ ...(reqList.length > 0 ? { required: reqList } : {}),
101
+ ...(properties.length > 0
102
+ ? {
103
+ properties: properties.slice(0, MAX_LISTED_PROPERTIES),
104
+ ...(properties.length > MAX_LISTED_PROPERTIES ? { totalProperties: properties.length } : {}),
105
+ }
106
+ : {}),
107
+ ...(enumValues && enumValues.length > 0 ? { enumValues } : {}),
108
+ usedBy,
109
+ ...(sourceLocation ? { sourceLocation } : {}),
110
+ });
111
+ }
112
+ return {
113
+ title,
114
+ version,
115
+ openapiVersion,
116
+ ...(specPath ? { specPath } : {}),
117
+ totalSchemas: schemas.length,
118
+ unusedSchemas,
119
+ schemas,
120
+ };
121
+ }
122
+ export function searchSchemas(entries, filters) {
123
+ const query = filters.q?.toLowerCase();
124
+ const usedByPath = filters.usedByPath?.toLowerCase();
125
+ const schemas = [];
126
+ let totalMatches = 0;
127
+ for (const entry of entries) {
128
+ if (filters.unusedOnly === true && entry.usedBy.length > 0)
129
+ continue;
130
+ if (filters.unusedOnly === false && entry.usedBy.length === 0)
131
+ continue;
132
+ if (usedByPath && !entry.usedBy.some((ref) => ref.toLowerCase().includes(usedByPath)))
133
+ continue;
134
+ if (query) {
135
+ const haystacks = [
136
+ entry.name,
137
+ entry.type,
138
+ entry.description ?? '',
139
+ ...(entry.properties ?? []),
140
+ ...(entry.required ?? []),
141
+ ];
142
+ if (!haystacks.some((value) => value.toLowerCase().includes(query)))
143
+ continue;
144
+ }
145
+ if (totalMatches >= filters.offset && schemas.length < filters.limit) {
146
+ schemas.push(entry);
147
+ }
148
+ totalMatches++;
149
+ }
150
+ return { schemas, totalMatches };
151
+ }
@@ -0,0 +1,15 @@
1
+ export interface SourceLocation {
2
+ file: string;
3
+ line: number;
4
+ col: number;
5
+ }
6
+ export interface ParsedDocumentWithLocations {
7
+ value: unknown;
8
+ locations: Map<string, SourceLocation>;
9
+ }
10
+ export declare function escapeJsonPointer(segment: string): string;
11
+ /**
12
+ * Parses YAML/JSON once using `yaml` v2 `parseDocument` + `LineCounter` to produce both
13
+ * the JS value and 1-based `{ file, line, col }` source locations for endpoints and components.
14
+ */
15
+ export declare function parseDocumentWithLocations(content: string, relativeFile: string): ParsedDocumentWithLocations;
@@ -0,0 +1,50 @@
1
+ import { LineCounter, isMap, isPair, isScalar, parseDocument } from 'yaml';
2
+ export function escapeJsonPointer(segment) {
3
+ return segment.replace(/~/g, '~0').replace(/\//g, '~1');
4
+ }
5
+ function collectMapLocations(node, prefix, depth, maxDepth, file, lineCounter, out) {
6
+ if (!node || depth > maxDepth || !isMap(node))
7
+ return;
8
+ for (const item of node.items) {
9
+ if (!isPair(item) || !isScalar(item.key))
10
+ continue;
11
+ const rawKey = item.key.value;
12
+ if (typeof rawKey !== 'string' && typeof rawKey !== 'number')
13
+ continue;
14
+ const key = String(rawKey);
15
+ const pointer = `${prefix}/${escapeJsonPointer(key)}`;
16
+ const rangeStart = item.key.range?.[0] ?? item.value?.range?.[0];
17
+ if (typeof rangeStart === 'number') {
18
+ const pos = lineCounter.linePos(rangeStart);
19
+ out.set(pointer, { file, line: pos.line, col: pos.col });
20
+ }
21
+ if (depth < maxDepth && item.value && isMap(item.value)) {
22
+ // Only descend into structural OpenAPI containers to keep map size O(E + S).
23
+ const shouldDescend = depth === 0
24
+ ? key === 'paths' || key === 'components' || key === 'definitions'
25
+ : depth === 1
26
+ ? prefix === '/paths' || prefix === '/components'
27
+ : false;
28
+ if (shouldDescend) {
29
+ collectMapLocations(item.value, pointer, depth + 1, maxDepth, file, lineCounter, out);
30
+ }
31
+ }
32
+ }
33
+ }
34
+ /**
35
+ * Parses YAML/JSON once using `yaml` v2 `parseDocument` + `LineCounter` to produce both
36
+ * the JS value and 1-based `{ file, line, col }` source locations for endpoints and components.
37
+ */
38
+ export function parseDocumentWithLocations(content, relativeFile) {
39
+ const lineCounter = new LineCounter();
40
+ const doc = parseDocument(content, { lineCounter, prettyErrors: true });
41
+ if (doc.errors.length > 0) {
42
+ throw doc.errors[0];
43
+ }
44
+ const locations = new Map();
45
+ collectMapLocations(doc.contents, '', 0, 2, relativeFile, lineCounter, locations);
46
+ return {
47
+ value: doc.toJS(),
48
+ locations,
49
+ };
50
+ }
@@ -0,0 +1,14 @@
1
+ export declare const DEFAULT_IGNORED_DIRS: Set<string>;
2
+ export interface WorkspaceSpecCatalog {
3
+ specPaths: string[];
4
+ skippedDirs: string[];
5
+ skippedDirCount: number;
6
+ }
7
+ /**
8
+ * Scan workspace for conventional OpenAPI entry filenames without loading or resolving contents.
9
+ * Unreadable or transient directories (EACCES/EPERM/ENOENT/ENOTDIR/ELOOP) are skipped and reported
10
+ * rather than aborting the entire catalog scan.
11
+ */
12
+ export declare function scanWorkspaceSpecs(root: string): WorkspaceSpecCatalog;
13
+ /** List conventional entry filenames without loading or resolving their contents. */
14
+ export declare function listWorkspaceSpecs(root: string): string[];
@@ -0,0 +1,99 @@
1
+ import { opendirSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ export const DEFAULT_IGNORED_DIRS = new Set([
4
+ '.git',
5
+ 'node_modules',
6
+ 'vendor',
7
+ 'dist',
8
+ 'build',
9
+ 'out',
10
+ 'target',
11
+ 'coverage',
12
+ 'storage',
13
+ '.next',
14
+ '.nuxt',
15
+ '.output',
16
+ '.svelte-kit',
17
+ '.turbo',
18
+ '.cache',
19
+ '.parcel-cache',
20
+ '.venv',
21
+ 'venv',
22
+ '__pycache__',
23
+ '.pytest_cache',
24
+ '.mypy_cache',
25
+ '.idea',
26
+ '.vscode',
27
+ '.gradle',
28
+ 'tmp',
29
+ '.tmp',
30
+ ]);
31
+ const specNames = new Set(['openapi.yml', 'openapi.yaml', 'openapi.json']);
32
+ const SKIPPABLE_DIR_ERROR_CODES = new Set(['EACCES', 'EPERM', 'ENOENT', 'ENOTDIR', 'ELOOP']);
33
+ const MAX_SKIPPED_DIRS_SAMPLE = 25;
34
+ function isSkippableDirError(error) {
35
+ const code = error?.code;
36
+ return typeof code === 'string' && SKIPPABLE_DIR_ERROR_CODES.has(code);
37
+ }
38
+ /**
39
+ * Scan workspace for conventional OpenAPI entry filenames without loading or resolving contents.
40
+ * Unreadable or transient directories (EACCES/EPERM/ENOENT/ENOTDIR/ELOOP) are skipped and reported
41
+ * rather than aborting the entire catalog scan.
42
+ */
43
+ export function scanWorkspaceSpecs(root) {
44
+ const directories = [''];
45
+ const paths = [];
46
+ const skippedDirs = [];
47
+ let skippedDirCount = 0;
48
+ let visited = 0;
49
+ while (directories.length) {
50
+ const relative = directories.pop();
51
+ let dir;
52
+ try {
53
+ dir = opendirSync(join(root, relative));
54
+ }
55
+ catch (error) {
56
+ if (relative !== '' && isSkippableDirError(error)) {
57
+ skippedDirCount++;
58
+ if (skippedDirs.length < MAX_SKIPPED_DIRS_SAMPLE)
59
+ skippedDirs.push(relative);
60
+ continue;
61
+ }
62
+ throw error;
63
+ }
64
+ try {
65
+ for (let entry = dir.readSync(); entry; entry = dir.readSync()) {
66
+ if (++visited > 250_000) {
67
+ throw new Error('CATALOG_LIMIT: Select a narrower workspace root or pass spec_path directly.');
68
+ }
69
+ const path = relative ? `${relative}/${entry.name}` : entry.name;
70
+ if (entry.isDirectory() && !DEFAULT_IGNORED_DIRS.has(entry.name))
71
+ directories.push(path);
72
+ if (entry.isFile() && specNames.has(entry.name))
73
+ paths.push(path);
74
+ }
75
+ }
76
+ catch (error) {
77
+ if (relative !== '' && isSkippableDirError(error)) {
78
+ skippedDirCount++;
79
+ if (skippedDirs.length < MAX_SKIPPED_DIRS_SAMPLE)
80
+ skippedDirs.push(relative);
81
+ }
82
+ else {
83
+ throw error;
84
+ }
85
+ }
86
+ finally {
87
+ dir.closeSync();
88
+ }
89
+ }
90
+ return {
91
+ specPaths: paths.sort(),
92
+ skippedDirs: skippedDirs.sort(),
93
+ skippedDirCount,
94
+ };
95
+ }
96
+ /** List conventional entry filenames without loading or resolving their contents. */
97
+ export function listWorkspaceSpecs(root) {
98
+ return scanWorkspaceSpecs(root).specPaths;
99
+ }
@@ -0,0 +1,28 @@
1
+ import { type SourceLocation } from './source-map.js';
2
+ import { type LoadOpenApiSpecOptions } from './spec-loader.js';
3
+ export type DiagnosticSeverity = 'error' | 'warning' | 'info';
4
+ export interface SpecDiagnosticIssue {
5
+ severity: DiagnosticSeverity;
6
+ code: string;
7
+ message: string;
8
+ pointer?: string;
9
+ location?: SourceLocation;
10
+ }
11
+ export interface SpecDiagnosticsReport {
12
+ valid: boolean;
13
+ specPath: string;
14
+ summary: {
15
+ errors: number;
16
+ warnings: number;
17
+ info: number;
18
+ totalIssues: number;
19
+ truncated: boolean;
20
+ };
21
+ issues: SpecDiagnosticIssue[];
22
+ }
23
+ /**
24
+ * Performs a non-throwing, multi-issue structural & contract diagnostic pass on an OpenAPI spec.
25
+ * Enforces the same workspace boundary, `O_NOFOLLOW`, cumulative byte (`MAX_SPEC_BYTES`),
26
+ * and file-count (`MAX_SPEC_FILES`) bounds as `loadOpenApiSpec`.
27
+ */
28
+ export declare function diagnoseOpenApiSpec(options?: LoadOpenApiSpecOptions): SpecDiagnosticsReport;