@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,207 @@
1
+ import { ListResourcesRequestSchema, ListResourceTemplatesRequestSchema, ReadResourceRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
2
+ import { z } from 'zod';
3
+ import { MAX_RESULT_BYTES } from '../engine/budget.js';
4
+ import { DEFAULT_SPEC_CANDIDATES, assertWorkspaceRoot, diagnoseOpenApiSpec, scanWorkspaceSpecs, searchEndpoints, searchSchemas, } from '../engine/index.js';
5
+ const INDEX_URI = 'openapi://endpoints/index';
6
+ const SEARCH_URI = 'openapi://endpoints/search';
7
+ const SCHEMAS_INDEX_URI = 'openapi://schemas/index';
8
+ const SCHEMAS_SEARCH_URI = 'openapi://schemas/search';
9
+ const DIAGNOSTICS_URI = 'openapi://spec/diagnostics';
10
+ const CATALOG_URI = 'openapi://specs/catalog';
11
+ const INDEX_SOFT_MAX_BYTES = 64 * 1024;
12
+ const RootParams = z.strictObject({ root: z.string().trim().min(1).optional() });
13
+ const SpecParams = RootParams.extend({ spec_path: z.string().trim().min(1).optional() });
14
+ const BooleanParam = z.enum(['true', 'false']).transform((v) => v === 'true');
15
+ const PaginationParams = {
16
+ offset: z.string().regex(/^\d+$/).pipe(z.coerce.number().int().nonnegative()).default(0),
17
+ limit: z.string().regex(/^\d+$/).pipe(z.coerce.number().int().min(1).max(100)).default(20),
18
+ };
19
+ const SearchParams = SpecParams.extend({
20
+ q: z.string().trim().optional(),
21
+ tag: z.string().trim().optional(),
22
+ method: z.string().trim().min(1).optional(),
23
+ pathPrefix: z.string().trim().min(1).optional(),
24
+ operationId: z.string().trim().optional(),
25
+ missingErrorContracts: BooleanParam.optional(),
26
+ ...PaginationParams,
27
+ });
28
+ const SchemaSearchParams = SpecParams.extend({
29
+ q: z.string().trim().optional(),
30
+ usedByPath: z.string().trim().optional(),
31
+ unusedOnly: BooleanParam.optional(),
32
+ ...PaginationParams,
33
+ });
34
+ export const OPENAPI_RESOURCES = [
35
+ {
36
+ uri: INDEX_URI,
37
+ name: 'OpenAPI Endpoints Index',
38
+ description: 'Compact index of all OpenAPI endpoints in `METHOD /path — summary — [200, 400, 404, 422, 500]` format, including all 4xx/5xx error status codes, auth schemes, and source locations.',
39
+ mimeType: 'application/json',
40
+ },
41
+ {
42
+ uri: SCHEMAS_INDEX_URI,
43
+ name: 'OpenAPI Component Schemas Index',
44
+ description: 'Compact index of `components.schemas` (or Swagger `definitions`) with required fields, property keys, source locations, and reverse references (`usedBy`) to endpoints.',
45
+ mimeType: 'application/json',
46
+ },
47
+ {
48
+ uri: DIAGNOSTICS_URI,
49
+ name: 'OpenAPI Spec Diagnostics',
50
+ description: 'Multi-issue validation & contract quality report: broken $refs, duplicate operationIds, undeclared path params, unknown security schemes, and missing error contracts.',
51
+ mimeType: 'application/json',
52
+ },
53
+ {
54
+ uri: CATALOG_URI,
55
+ name: 'Workspace OpenAPI files',
56
+ description: 'List conventional entry filenames relative to the workspace root.',
57
+ mimeType: 'application/json',
58
+ },
59
+ ];
60
+ const RESOURCE_TEMPLATES = [
61
+ {
62
+ uriTemplate: SEARCH_URI + '{?q,tag,method,pathPrefix,operationId,missingErrorContracts,offset,limit,root,spec_path}',
63
+ name: 'Search endpoint index',
64
+ description: 'Search method, path, summary, tags or operationId by substring. Optional exact tag, method, pathPrefix, operationId, and missingErrorContracts filters. Case-insensitive. Follow nextUri for more.',
65
+ mimeType: 'application/json',
66
+ },
67
+ {
68
+ uriTemplate: INDEX_URI + '{?root,spec_path}',
69
+ name: 'Selected endpoint index',
70
+ description: 'Read the full soft-capped endpoint index for an explicit workspace root and spec_path.',
71
+ mimeType: 'application/json',
72
+ },
73
+ {
74
+ uriTemplate: SCHEMAS_SEARCH_URI + '{?q,usedByPath,unusedOnly,offset,limit,root,spec_path}',
75
+ name: 'Search component schemas',
76
+ description: 'Search components.schemas by name, property, or description, filter by endpoint path usage or unused schemas. Follow nextUri for more.',
77
+ mimeType: 'application/json',
78
+ },
79
+ {
80
+ uriTemplate: SCHEMAS_INDEX_URI + '{?root,spec_path}',
81
+ name: 'Selected component schemas index',
82
+ description: 'Read the full soft-capped components.schemas/definitions index for an explicit workspace root and spec_path.',
83
+ mimeType: 'application/json',
84
+ },
85
+ {
86
+ uriTemplate: DIAGNOSTICS_URI + '{?root,spec_path}',
87
+ name: 'Selected spec diagnostics',
88
+ description: 'Run single-pass validation diagnostics on an explicit workspace root and spec_path.',
89
+ mimeType: 'application/json',
90
+ },
91
+ {
92
+ uriTemplate: CATALOG_URI + '{?root}',
93
+ name: 'Workspace OpenAPI files for root',
94
+ description: 'Discover conventional OpenAPI entry filenames inside an explicit workspace root.',
95
+ mimeType: 'application/json',
96
+ },
97
+ ];
98
+ function jsonResource(uri, text) {
99
+ return { contents: [{ uri, mimeType: 'application/json', text }] };
100
+ }
101
+ function buildPaginatedResponse(uri, url, page, pageLength, offset, limitErrorMessage) {
102
+ const next = offset + pageLength;
103
+ url.searchParams.set('offset', String(next));
104
+ const text = JSON.stringify({ ...page, nextUri: next < page.totalMatches ? url.href : null });
105
+ if (Buffer.byteLength(text) > MAX_RESULT_BYTES) {
106
+ throw new Error(limitErrorMessage);
107
+ }
108
+ return jsonResource(uri, text);
109
+ }
110
+ function buildSoftCappedIndexResponse(uri, url, payload, itemCount, itemLabel, filterHint) {
111
+ const text = JSON.stringify(payload, null, 2);
112
+ if (Buffer.byteLength(text) > INDEX_SOFT_MAX_BYTES) {
113
+ url.pathname = '/search';
114
+ url.searchParams.set('limit', '20');
115
+ throw new Error(`INDEX_LIMIT: Full ${itemLabel} index exceeds ${INDEX_SOFT_MAX_BYTES} bytes (${itemCount} ${itemLabel}s). Read ${url.href} and follow nextUri or add filters (${filterHint}).`);
116
+ }
117
+ return jsonResource(uri, text);
118
+ }
119
+ export function registerResourceHandlers(server, ctx) {
120
+ server.setRequestHandler(ListResourcesRequestSchema, async () => ({
121
+ resources: OPENAPI_RESOURCES.map((r) => ({ ...r })),
122
+ }));
123
+ server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => ({
124
+ resourceTemplates: RESOURCE_TEMPLATES.map((t) => ({ ...t })),
125
+ }));
126
+ server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
127
+ await ctx.ensureRootsReady();
128
+ const uri = request.params.uri;
129
+ const isCatalog = uri === CATALOG_URI || uri.startsWith(CATALOG_URI + '?');
130
+ const isSearch = uri === SEARCH_URI || uri.startsWith(SEARCH_URI + '?');
131
+ const isIndex = uri === INDEX_URI || uri.startsWith(INDEX_URI + '?');
132
+ const isSchemaIndex = uri === SCHEMAS_INDEX_URI || uri.startsWith(SCHEMAS_INDEX_URI + '?');
133
+ const isSchemaSearch = uri === SCHEMAS_SEARCH_URI || uri.startsWith(SCHEMAS_SEARCH_URI + '?');
134
+ const isDiagnostics = uri === DIAGNOSTICS_URI || uri.startsWith(DIAGNOSTICS_URI + '?');
135
+ if (isCatalog) {
136
+ const url = new URL(uri);
137
+ const { root } = RootParams.parse(Object.fromEntries(url.searchParams));
138
+ const targetRoot = assertWorkspaceRoot(root ?? ctx.getDefaultRoot(), ctx.configuredRoot);
139
+ const catalog = scanWorkspaceSpecs(targetRoot);
140
+ const payload = catalog.skippedDirCount > 0
141
+ ? {
142
+ specPaths: catalog.specPaths,
143
+ skippedDirCount: catalog.skippedDirCount,
144
+ skippedDirs: catalog.skippedDirs,
145
+ }
146
+ : { specPaths: catalog.specPaths };
147
+ const text = JSON.stringify(payload);
148
+ if (Buffer.byteLength(text) > MAX_RESULT_BYTES)
149
+ throw new Error('CATALOG_LIMIT: Select a narrower workspace root.');
150
+ return jsonResource(uri, text);
151
+ }
152
+ if (!isIndex && !isSearch && !isSchemaIndex && !isSchemaSearch && !isDiagnostics) {
153
+ throw new Error(`Unknown resource URI '${uri}'. Available resources: ${OPENAPI_RESOURCES.map((r) => r.uri).join(', ')}, and templates '${SEARCH_URI}{?q,tag,method,pathPrefix,operationId,missingErrorContracts,offset,limit,root,spec_path}', '${SCHEMAS_SEARCH_URI}{?q,usedByPath,unusedOnly,offset,limit,root,spec_path}', '${DIAGNOSTICS_URI}{?root,spec_path}', '${CATALOG_URI}{?root}'.`);
154
+ }
155
+ const url = new URL(uri);
156
+ const params = Object.fromEntries(url.searchParams);
157
+ const endpointFilters = isSearch ? SearchParams.parse(params) : undefined;
158
+ const schemaFilters = isSchemaSearch ? SchemaSearchParams.parse(params) : undefined;
159
+ const selected = endpointFilters ?? schemaFilters ?? SpecParams.parse(params);
160
+ const defaultRoot = ctx.getDefaultRoot();
161
+ const targetRoot = selected.root ?? defaultRoot;
162
+ try {
163
+ if (isDiagnostics) {
164
+ const effectiveSpec = selected.spec_path ?? (selected.root && selected.root !== defaultRoot ? undefined : ctx.defaultSpec);
165
+ const report = diagnoseOpenApiSpec({
166
+ rootDir: targetRoot,
167
+ specPath: effectiveSpec,
168
+ allowedRootDir: ctx.configuredRoot,
169
+ });
170
+ const text = JSON.stringify(report, null, 2);
171
+ if (Buffer.byteLength(text) > MAX_RESULT_BYTES) {
172
+ throw new Error('DIAGNOSTICS_LIMIT: Diagnostics payload exceeds response byte limit.');
173
+ }
174
+ return jsonResource(uri, text);
175
+ }
176
+ const loaded = ctx.readSpec(selected.root, selected.spec_path);
177
+ if (isSchemaIndex || isSchemaSearch) {
178
+ const schemaIndex = ctx.getSchemaIndex(loaded);
179
+ if (schemaFilters) {
180
+ const page = searchSchemas(schemaIndex.schemas, schemaFilters);
181
+ return buildPaginatedResponse(uri, url, page, page.schemas.length, schemaFilters.offset, 'INDEX_LIMIT: Reduce limit or narrow schema search filters.');
182
+ }
183
+ return buildSoftCappedIndexResponse(uri, url, schemaIndex, schemaIndex.totalSchemas, 'schema', 'q, usedByPath, unusedOnly');
184
+ }
185
+ const index = ctx.getEndpointIndex(loaded);
186
+ if (endpointFilters) {
187
+ const page = searchEndpoints(index.endpoints, endpointFilters);
188
+ return buildPaginatedResponse(uri, url, page, page.endpoints.length, endpointFilters.offset, 'INDEX_LIMIT: Reduce limit or narrow the filters. For a single oversized operation use openapi_query.');
189
+ }
190
+ return buildSoftCappedIndexResponse(uri, url, index, index.totalEndpoints, 'endpoint', 'q, tag, method, pathPrefix');
191
+ }
192
+ catch (err) {
193
+ const message = err instanceof Error ? err.message : String(err);
194
+ if (message.startsWith('SPEC_NOT_FOUND:') || message.startsWith('SPEC_FILE_NOT_FOUND:')) {
195
+ return jsonResource(uri, JSON.stringify({
196
+ status: 'spec_not_found',
197
+ workspaceRoot: targetRoot,
198
+ checkedCandidates: selected.spec_path || ctx.defaultSpec
199
+ ? [selected.spec_path ?? ctx.defaultSpec]
200
+ : [...DEFAULT_SPEC_CANDIDATES],
201
+ hint: 'Pass ?root=<repo_dir>&spec_path=<path>, read openapi://specs/catalog?root=<repo_dir>, or call openapi_inspect / openapi_diagnostics.',
202
+ }, null, 2));
203
+ }
204
+ throw err;
205
+ }
206
+ });
207
+ }
@@ -0,0 +1,88 @@
1
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
2
+ import { z } from 'zod';
3
+ import { OPENAPI_PROMPTS, getOpenApiPrompt } from './prompts.js';
4
+ import { OPENAPI_RESOURCES } from './resources.js';
5
+ export { OPENAPI_PROMPTS, OPENAPI_RESOURCES, getOpenApiPrompt };
6
+ export declare const OPENAPI_MCP_VERSION: string;
7
+ export declare const OPENAPI_MCP_INSTRUCTIONS: string;
8
+ export declare const OPENAPI_TOOLS: readonly [{
9
+ readonly name: "openapi_query";
10
+ readonly description: "Query the resolved, read-only OpenAPI spec using synchronous JavaScript against `spec` and built-in `helpers` (`helpers.op`, `helpers.example`, `helpers.schemaRefs`, `helpers.meta`).";
11
+ readonly inputSchema: z.core.ZodStandardJSONSchemaPayload<z.ZodObject<{
12
+ code: z.ZodString;
13
+ spec_path: z.ZodOptional<z.ZodString>;
14
+ root: z.ZodOptional<z.ZodString>;
15
+ max_bytes: z.ZodOptional<z.ZodNumber>;
16
+ }, z.core.$strict>>;
17
+ readonly annotations: {
18
+ readonly readOnlyHint: true;
19
+ readonly destructiveHint: false;
20
+ readonly idempotentHint: true;
21
+ readonly openWorldHint: false;
22
+ };
23
+ }, {
24
+ readonly name: "openapi_diff";
25
+ readonly description: "Compare two local OpenAPI specs (`base_spec_path` vs `target_spec_path`) and classify semantic contract changes into breaking vs non-breaking.";
26
+ readonly inputSchema: z.core.ZodStandardJSONSchemaPayload<z.ZodObject<{
27
+ base_spec_path: z.ZodString;
28
+ target_spec_path: z.ZodString;
29
+ root: z.ZodOptional<z.ZodString>;
30
+ include_non_breaking: z.ZodOptional<z.ZodBoolean>;
31
+ max_bytes: z.ZodOptional<z.ZodNumber>;
32
+ }, z.core.$strict>>;
33
+ readonly annotations: {
34
+ readonly readOnlyHint: true;
35
+ readonly destructiveHint: false;
36
+ readonly idempotentHint: true;
37
+ readonly openWorldHint: false;
38
+ };
39
+ }, {
40
+ readonly name: "openapi_diagnostics";
41
+ readonly description: "Run multi-issue contract diagnostics on a local OpenAPI spec (broken $refs, duplicate operationIds, undeclared path params, unknown security schemes, missing error/auth contracts) with explicit `root` and `spec_path` support.";
42
+ readonly inputSchema: z.core.ZodStandardJSONSchemaPayload<z.ZodObject<{
43
+ root: z.ZodOptional<z.ZodString>;
44
+ spec_path: z.ZodOptional<z.ZodString>;
45
+ max_bytes: z.ZodOptional<z.ZodNumber>;
46
+ }, z.core.$strict>>;
47
+ readonly annotations: {
48
+ readonly readOnlyHint: true;
49
+ readonly destructiveHint: false;
50
+ readonly idempotentHint: true;
51
+ readonly openWorldHint: false;
52
+ };
53
+ }, {
54
+ readonly name: "openapi_inspect";
55
+ readonly description: "Discover workspace OpenAPI files (`catalog`), inspect/search compact endpoint (`O(endpoints)` lazy load) and schema indexes, or lazily expand a single JSON Pointer subtree (`pointer`, e.g. \"/paths/~1users/get\") without resolving the entire spec.";
56
+ readonly inputSchema: z.core.ZodStandardJSONSchemaPayload<z.ZodObject<{
57
+ target: z.ZodDefault<z.ZodEnum<{
58
+ schemas: "schemas";
59
+ catalog: "catalog";
60
+ endpoints: "endpoints";
61
+ }>>;
62
+ root: z.ZodOptional<z.ZodString>;
63
+ spec_path: z.ZodOptional<z.ZodString>;
64
+ q: z.ZodOptional<z.ZodString>;
65
+ tag: z.ZodOptional<z.ZodString>;
66
+ method: z.ZodOptional<z.ZodString>;
67
+ pathPrefix: z.ZodOptional<z.ZodString>;
68
+ operationId: z.ZodOptional<z.ZodString>;
69
+ missingErrorContracts: z.ZodOptional<z.ZodBoolean>;
70
+ usedByPath: z.ZodOptional<z.ZodString>;
71
+ unusedOnly: z.ZodOptional<z.ZodBoolean>;
72
+ pointer: z.ZodOptional<z.ZodString>;
73
+ offset: z.ZodDefault<z.ZodNumber>;
74
+ limit: z.ZodOptional<z.ZodNumber>;
75
+ max_bytes: z.ZodOptional<z.ZodNumber>;
76
+ }, z.core.$strict>>;
77
+ readonly annotations: {
78
+ readonly readOnlyHint: true;
79
+ readonly destructiveHint: false;
80
+ readonly idempotentHint: true;
81
+ readonly openWorldHint: false;
82
+ };
83
+ }];
84
+ export interface OpenApiMcpServerOptions {
85
+ defaultRootDir?: string;
86
+ defaultSpecPath?: string;
87
+ }
88
+ export declare function createOpenApiMcpServer(options?: OpenApiMcpServerOptions): Server;