@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.
@@ -1,7 +1,7 @@
1
1
  import { ListResourcesRequestSchema, ListResourceTemplatesRequestSchema, ReadResourceRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
2
2
  import { z } from 'zod';
3
3
  import { MAX_RESULT_BYTES } from '../engine/budget.js';
4
- import { DEFAULT_SPEC_CANDIDATES, buildEndpointIndex, buildSchemaIndex, diagnoseOpenApiSpec, scanWorkspaceSpecs, searchEndpoints, searchSchemas, } from '../engine/index.js';
4
+ import { DEFAULT_SPEC_CANDIDATES, assertWorkspaceRoot, diagnoseOpenApiSpec, scanWorkspaceSpecs, searchEndpoints, searchSchemas, } from '../engine/index.js';
5
5
  const INDEX_URI = 'openapi://endpoints/index';
6
6
  const SEARCH_URI = 'openapi://endpoints/search';
7
7
  const SCHEMAS_INDEX_URI = 'openapi://schemas/index';
@@ -9,7 +9,8 @@ const SCHEMAS_SEARCH_URI = 'openapi://schemas/search';
9
9
  const DIAGNOSTICS_URI = 'openapi://spec/diagnostics';
10
10
  const CATALOG_URI = 'openapi://specs/catalog';
11
11
  const INDEX_SOFT_MAX_BYTES = 64 * 1024;
12
- const SpecParams = z.strictObject({ spec_path: z.string().trim().min(1).optional() });
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() });
13
14
  const BooleanParam = z.enum(['true', 'false']).transform((v) => v === 'true');
14
15
  const PaginationParams = {
15
16
  offset: z.string().regex(/^\d+$/).pipe(z.coerce.number().int().nonnegative()).default(0),
@@ -58,20 +59,41 @@ export const OPENAPI_RESOURCES = [
58
59
  ];
59
60
  const RESOURCE_TEMPLATES = [
60
61
  {
61
- uriTemplate: SEARCH_URI + '{?q,tag,method,pathPrefix,operationId,missingErrorContracts,offset,limit,spec_path}',
62
+ uriTemplate: SEARCH_URI + '{?q,tag,method,pathPrefix,operationId,missingErrorContracts,offset,limit,root,spec_path}',
62
63
  name: 'Search endpoint index',
63
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.',
64
65
  mimeType: 'application/json',
65
66
  },
66
- { uriTemplate: INDEX_URI + '{?spec_path}', name: 'Selected endpoint index', mimeType: 'application/json' },
67
67
  {
68
- uriTemplate: SCHEMAS_SEARCH_URI + '{?q,usedByPath,unusedOnly,offset,limit,spec_path}',
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}',
69
75
  name: 'Search component schemas',
70
76
  description: 'Search components.schemas by name, property, or description, filter by endpoint path usage or unused schemas. Follow nextUri for more.',
71
77
  mimeType: 'application/json',
72
78
  },
73
- { uriTemplate: SCHEMAS_INDEX_URI + '{?spec_path}', name: 'Selected component schemas index', mimeType: 'application/json' },
74
- { uriTemplate: DIAGNOSTICS_URI + '{?spec_path}', name: 'Selected spec diagnostics', mimeType: 'application/json' },
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
+ },
75
97
  ];
76
98
  function jsonResource(uri, text) {
77
99
  return { contents: [{ uri, mimeType: 'application/json', text }] };
@@ -95,8 +117,6 @@ function buildSoftCappedIndexResponse(uri, url, payload, itemCount, itemLabel, f
95
117
  return jsonResource(uri, text);
96
118
  }
97
119
  export function registerResourceHandlers(server, ctx) {
98
- const indexes = new WeakMap();
99
- const schemaIndexes = new WeakMap();
100
120
  server.setRequestHandler(ListResourcesRequestSchema, async () => ({
101
121
  resources: OPENAPI_RESOURCES.map((r) => ({ ...r })),
102
122
  }));
@@ -104,14 +124,19 @@ export function registerResourceHandlers(server, ctx) {
104
124
  resourceTemplates: RESOURCE_TEMPLATES.map((t) => ({ ...t })),
105
125
  }));
106
126
  server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
127
+ await ctx.ensureRootsReady();
107
128
  const uri = request.params.uri;
129
+ const isCatalog = uri === CATALOG_URI || uri.startsWith(CATALOG_URI + '?');
108
130
  const isSearch = uri === SEARCH_URI || uri.startsWith(SEARCH_URI + '?');
109
131
  const isIndex = uri === INDEX_URI || uri.startsWith(INDEX_URI + '?');
110
132
  const isSchemaIndex = uri === SCHEMAS_INDEX_URI || uri.startsWith(SCHEMAS_INDEX_URI + '?');
111
133
  const isSchemaSearch = uri === SCHEMAS_SEARCH_URI || uri.startsWith(SCHEMAS_SEARCH_URI + '?');
112
134
  const isDiagnostics = uri === DIAGNOSTICS_URI || uri.startsWith(DIAGNOSTICS_URI + '?');
113
- if (uri === CATALOG_URI) {
114
- const catalog = scanWorkspaceSpecs(ctx.defaultRoot);
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);
115
140
  const payload = catalog.skippedDirCount > 0
116
141
  ? {
117
142
  specPaths: catalog.specPaths,
@@ -125,18 +150,21 @@ export function registerResourceHandlers(server, ctx) {
125
150
  return jsonResource(uri, text);
126
151
  }
127
152
  if (!isIndex && !isSearch && !isSchemaIndex && !isSchemaSearch && !isDiagnostics) {
128
- 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,spec_path}', '${SCHEMAS_SEARCH_URI}{?q,usedByPath,unusedOnly,offset,limit,spec_path}', '${DIAGNOSTICS_URI}{?spec_path}'.`);
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}'.`);
129
154
  }
130
155
  const url = new URL(uri);
131
156
  const params = Object.fromEntries(url.searchParams);
132
157
  const endpointFilters = isSearch ? SearchParams.parse(params) : undefined;
133
158
  const schemaFilters = isSchemaSearch ? SchemaSearchParams.parse(params) : undefined;
134
159
  const selected = endpointFilters ?? schemaFilters ?? SpecParams.parse(params);
160
+ const defaultRoot = ctx.getDefaultRoot();
161
+ const targetRoot = selected.root ?? defaultRoot;
135
162
  try {
136
163
  if (isDiagnostics) {
164
+ const effectiveSpec = selected.spec_path ?? (selected.root && selected.root !== defaultRoot ? undefined : ctx.defaultSpec);
137
165
  const report = diagnoseOpenApiSpec({
138
- rootDir: ctx.defaultRoot,
139
- specPath: selected.spec_path ?? ctx.defaultSpec,
166
+ rootDir: targetRoot,
167
+ specPath: effectiveSpec,
140
168
  allowedRootDir: ctx.configuredRoot,
141
169
  });
142
170
  const text = JSON.stringify(report, null, 2);
@@ -145,24 +173,16 @@ export function registerResourceHandlers(server, ctx) {
145
173
  }
146
174
  return jsonResource(uri, text);
147
175
  }
148
- const loaded = ctx.readSpec(undefined, selected.spec_path);
176
+ const loaded = ctx.readSpec(selected.root, selected.spec_path);
149
177
  if (isSchemaIndex || isSchemaSearch) {
150
- let schemaIndex = schemaIndexes.get(loaded.spec);
151
- if (!schemaIndex) {
152
- schemaIndex = buildSchemaIndex(loaded.spec, loaded.specPath, loaded.sourceLocations, loaded.schemaUsages);
153
- schemaIndexes.set(loaded.spec, schemaIndex);
154
- }
178
+ const schemaIndex = ctx.getSchemaIndex(loaded);
155
179
  if (schemaFilters) {
156
180
  const page = searchSchemas(schemaIndex.schemas, schemaFilters);
157
181
  return buildPaginatedResponse(uri, url, page, page.schemas.length, schemaFilters.offset, 'INDEX_LIMIT: Reduce limit or narrow schema search filters.');
158
182
  }
159
183
  return buildSoftCappedIndexResponse(uri, url, schemaIndex, schemaIndex.totalSchemas, 'schema', 'q, usedByPath, unusedOnly');
160
184
  }
161
- let index = indexes.get(loaded.spec);
162
- if (!index) {
163
- index = buildEndpointIndex(loaded.spec, loaded.specPath, loaded.sourceLocations);
164
- indexes.set(loaded.spec, index);
165
- }
185
+ const index = ctx.getEndpointIndex(loaded);
166
186
  if (endpointFilters) {
167
187
  const page = searchEndpoints(index.endpoints, endpointFilters);
168
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.');
@@ -174,11 +194,11 @@ export function registerResourceHandlers(server, ctx) {
174
194
  if (message.startsWith('SPEC_NOT_FOUND:') || message.startsWith('SPEC_FILE_NOT_FOUND:')) {
175
195
  return jsonResource(uri, JSON.stringify({
176
196
  status: 'spec_not_found',
177
- workspaceRoot: ctx.defaultRoot,
197
+ workspaceRoot: targetRoot,
178
198
  checkedCandidates: selected.spec_path || ctx.defaultSpec
179
199
  ? [selected.spec_path ?? ctx.defaultSpec]
180
200
  : [...DEFAULT_SPEC_CANDIDATES],
181
- hint: 'Read openapi://specs/catalog and select a spec_path, or configure the default spec.',
201
+ hint: 'Pass ?root=<repo_dir>&spec_path=<path>, read openapi://specs/catalog?root=<repo_dir>, or call openapi_inspect / openapi_diagnostics.',
182
202
  }, null, 2));
183
203
  }
184
204
  throw err;
@@ -7,7 +7,7 @@ export declare const OPENAPI_MCP_VERSION: string;
7
7
  export declare const OPENAPI_MCP_INSTRUCTIONS: string;
8
8
  export declare const OPENAPI_TOOLS: readonly [{
9
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`).";
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
11
  readonly inputSchema: z.core.ZodStandardJSONSchemaPayload<z.ZodObject<{
12
12
  code: z.ZodString;
13
13
  spec_path: z.ZodOptional<z.ZodString>;
@@ -27,6 +27,51 @@ export declare const OPENAPI_TOOLS: readonly [{
27
27
  base_spec_path: z.ZodString;
28
28
  target_spec_path: z.ZodString;
29
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>;
30
75
  max_bytes: z.ZodOptional<z.ZodNumber>;
31
76
  }, z.core.$strict>>;
32
77
  readonly annotations: {