@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,588 @@
1
+ import { statSync } from 'node:fs';
2
+ import { relative } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
5
+ import { CallToolRequestSchema, GetPromptRequestSchema, ListPromptsRequestSchema, ListToolsRequestSchema, RootsListChangedNotificationSchema, } from '@modelcontextprotocol/sdk/types.js';
6
+ import { z } from 'zod';
7
+ import packageInfo from '../../package.json' with { type: 'json' };
8
+ import { MAX_RESULT_BYTES, enforceSerializedByteBudget } from '../engine/budget.js';
9
+ import { DEFAULT_MAX_BYTES, assertWorkspaceRoot, buildEndpointIndex, buildRawEndpointSummary, buildSchemaIndex, diagnoseOpenApiSpec, diffOpenApiSpecs, expandPointerSubtree, extractSpecMetadata, loadOpenApiSpec, loadRawOpenApiDocument, scanWorkspaceSpecs, searchEndpoints, searchSchemas, } from '../engine/index.js';
10
+ import { isRecord } from '../engine/json.js';
11
+ import { MAX_QUERY_CODE_LENGTH, evaluateSandboxQuery } from '../engine/query-sandbox.js';
12
+ import { MissingReferenceError } from '../engine/spec-loader.js';
13
+ import { OPENAPI_PROMPTS, getOpenApiPrompt } from './prompts.js';
14
+ import { OPENAPI_RESOURCES, registerResourceHandlers } from './resources.js';
15
+ import { OpenApiTelemetry } from '../telemetry/telemetry.js';
16
+ export { OPENAPI_PROMPTS, OPENAPI_RESOURCES, getOpenApiPrompt };
17
+ export const OPENAPI_MCP_VERSION = packageInfo.version;
18
+ const QUERY_NAME = 'openapi_query';
19
+ const DIFF_NAME = 'openapi_diff';
20
+ const DIAGNOSTICS_NAME = 'openapi_diagnostics';
21
+ const INSPECT_NAME = 'openapi_inspect';
22
+ export const OPENAPI_MCP_INSTRUCTIONS = [
23
+ 'Use openapi-mcp in local Code Mode (index-first, lazy-expand on demand):',
24
+ 'For monorepos read openapi://specs/catalog (or call openapi_inspect with target="catalog"), then pass root/spec_path consistently.',
25
+ 'Discover endpoints with openapi_inspect (target="endpoints", O(endpoints) lazy load; supports q, tag, method, pathPrefix, operationId, missingErrorContracts) or openapi://endpoints/index / openapi://endpoints/search. Expand a single operation/schema subtree lazily with openapi_inspect({ pointer: "/paths/~1users/get" }) before running full-spec queries.',
26
+ 'Inspect reusable models and reverse endpoint usage with openapi://schemas/index, openapi://schemas/search?q=Order, or openapi_inspect(target="schemas"). Run multi-issue contract health checks with openapi://spec/diagnostics or openapi_diagnostics.',
27
+ '1. Read `openapi://endpoints/index` or call `openapi_inspect({ target: "endpoints" })` for endpoints, 2xx/4xx/5xx status codes, auth schemes, and YAML/JSON `sourceLocation`.',
28
+ '2. Expand one path/schema lazily via `openapi_inspect({ pointer: "/paths/~1users/get" })`, or run `openapi_query` with targeted JS against resolved `spec` and `helpers` (`helpers.op`, `helpers.example`, `helpers.schemaRefs`, `helpers.meta`).',
29
+ '3. Use `openapi_diff` to compare two local specs (`base_spec_path` vs `target_spec_path`) and detect breaking vs non-breaking contract changes.',
30
+ `4. Keep queries scoped to specific paths or schemas. The default \`max_bytes\` is ${DEFAULT_MAX_BYTES} UTF-8 bytes of result text.`,
31
+ ].join('\n');
32
+ const QueryArgsSchema = z.strictObject({
33
+ code: z.string().regex(/\S/).max(MAX_QUERY_CODE_LENGTH).describe("JavaScript expression or function body evaluated against `spec` and read-only `helpers` (op, example, schemaRefs, meta), e.g. helpers.op('POST', '/orders') or spec.paths['/users']?.get?.responses."),
34
+ spec_path: z.string().regex(/\S/).optional().describe('Optional path to the OpenAPI spec inside the selected workspace.'),
35
+ root: z.string().regex(/\S/).optional().describe('Workspace for this query. When a server root is configured, this path must remain within it.'),
36
+ max_bytes: z.number().int().min(1).max(MAX_RESULT_BYTES).optional().describe(`UTF-8 budget for successful query JSON (default: ${DEFAULT_MAX_BYTES}).`),
37
+ });
38
+ const DiffArgsSchema = z.strictObject({
39
+ base_spec_path: z.string().regex(/\S/).describe('Path to the baseline OpenAPI spec inside the workspace.'),
40
+ target_spec_path: z.string().regex(/\S/).describe('Path to the target/updated OpenAPI spec inside the workspace.'),
41
+ root: z.string().regex(/\S/).optional().describe('Workspace for both specs. When a server root is configured, this path must remain within it.'),
42
+ include_non_breaking: z.boolean().optional().describe('Set false to return breaking items and aggregate non-breaking counts only (default: true).'),
43
+ max_bytes: z.number().int().min(1).max(MAX_RESULT_BYTES).optional().describe(`UTF-8 budget for diff JSON (default: ${DEFAULT_MAX_BYTES}).`),
44
+ });
45
+ const DiagnosticsArgsSchema = z.strictObject({
46
+ root: z.string().regex(/\S/).optional().describe('Workspace root directory. When a server root is configured, this path must remain within it.'),
47
+ spec_path: z.string().regex(/\S/).optional().describe('Optional path to the OpenAPI spec inside the selected workspace.'),
48
+ max_bytes: z.number().int().min(1).max(MAX_RESULT_BYTES).optional().describe(`UTF-8 budget for diagnostics JSON (default: ${DEFAULT_MAX_BYTES}).`),
49
+ });
50
+ const InspectArgsSchema = z.strictObject({
51
+ target: z.enum(['catalog', 'endpoints', 'schemas']).default('endpoints').describe("Inspection target: 'catalog' (workspace OpenAPI files), 'endpoints' (index/search), or 'schemas' (components/definitions index/search)."),
52
+ root: z.string().regex(/\S/).optional().describe('Workspace root directory. When a server root is configured, this path must remain within it.'),
53
+ spec_path: z.string().regex(/\S/).optional().describe('Optional path to the OpenAPI spec inside the selected workspace (used for endpoints/schemas).'),
54
+ q: z.string().trim().optional().describe('Case-insensitive substring search filter.'),
55
+ tag: z.string().trim().optional().describe('Exact tag filter (endpoints target).'),
56
+ method: z.string().trim().min(1).optional().describe('HTTP method filter (endpoints target).'),
57
+ pathPrefix: z.string().trim().min(1).optional().describe('Path prefix filter (endpoints target).'),
58
+ operationId: z.string().trim().optional().describe('Exact operationId filter (endpoints target).'),
59
+ missingErrorContracts: z.boolean().optional().describe('Filter endpoints missing (true) or having (false) 4xx/5xx error responses.'),
60
+ usedByPath: z.string().trim().optional().describe('Filter schemas used by endpoints matching this path substring (schemas target).'),
61
+ unusedOnly: z.boolean().optional().describe('Filter schemas with zero (true) or >=1 (false) endpoint usages (schemas target).'),
62
+ pointer: z.string().trim().min(1).optional().describe('Optional JSON Pointer (e.g. "/paths/~1users/get" or "/components/schemas/Order") for lazy single-subtree expansion.'),
63
+ offset: z.number().int().min(0).default(0).describe('Pagination offset (default: 0).'),
64
+ limit: z.number().int().min(1).max(100).optional().describe('Maximum items per page when filtering or paginating (default: 20 when paginated).'),
65
+ max_bytes: z.number().int().min(1).max(MAX_RESULT_BYTES).optional().describe(`UTF-8 budget for inspect JSON (default: ${DEFAULT_MAX_BYTES}).`),
66
+ });
67
+ const READ_ONLY_ANNOTATIONS = {
68
+ readOnlyHint: true,
69
+ destructiveHint: false,
70
+ idempotentHint: true,
71
+ openWorldHint: false,
72
+ };
73
+ export const OPENAPI_TOOLS = [
74
+ {
75
+ name: QUERY_NAME,
76
+ 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`).',
77
+ inputSchema: z.toJSONSchema(QueryArgsSchema),
78
+ annotations: READ_ONLY_ANNOTATIONS,
79
+ },
80
+ {
81
+ name: DIFF_NAME,
82
+ description: 'Compare two local OpenAPI specs (`base_spec_path` vs `target_spec_path`) and classify semantic contract changes into breaking vs non-breaking.',
83
+ inputSchema: z.toJSONSchema(DiffArgsSchema),
84
+ annotations: READ_ONLY_ANNOTATIONS,
85
+ },
86
+ {
87
+ name: DIAGNOSTICS_NAME,
88
+ 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.',
89
+ inputSchema: z.toJSONSchema(DiagnosticsArgsSchema),
90
+ annotations: READ_ONLY_ANNOTATIONS,
91
+ },
92
+ {
93
+ name: INSPECT_NAME,
94
+ 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.',
95
+ inputSchema: z.toJSONSchema(InspectArgsSchema),
96
+ annotations: READ_ONLY_ANNOTATIONS,
97
+ },
98
+ ];
99
+ function formatInvalidArgsError(error, example) {
100
+ const issues = error.issues
101
+ .map((issue) => `${issue.path.join('.') || 'arguments'}: ${issue.message}`)
102
+ .join('; ');
103
+ return {
104
+ isError: true,
105
+ content: [{ type: 'text', text: `INVALID_ARGUMENTS: ${issues}.\n\nExample: ${example}` }],
106
+ };
107
+ }
108
+ function resolveEffectiveMaxBytes(maxBytes) {
109
+ return typeof maxBytes === 'number' && Number.isFinite(maxBytes) && maxBytes > 0
110
+ ? Math.min(MAX_RESULT_BYTES, Math.max(1, Math.floor(maxBytes)))
111
+ : DEFAULT_MAX_BYTES;
112
+ }
113
+ function summarizeDiffChangesByCode(changes) {
114
+ const counts = {};
115
+ for (const change of changes) {
116
+ counts[change.code] = (counts[change.code] ?? 0) + 1;
117
+ }
118
+ return counts;
119
+ }
120
+ function formatBudgetedDiffResult(report, includeNonBreaking, maxBytes) {
121
+ const effectiveMaxBytes = resolveEffectiveMaxBytes(maxBytes);
122
+ if (!includeNonBreaking) {
123
+ const omittedPayload = {
124
+ ...report,
125
+ nonBreaking: [],
126
+ nonBreakingOmitted: true,
127
+ nonBreakingSummary: summarizeDiffChangesByCode(report.nonBreaking),
128
+ };
129
+ return formatBudgetedToolResult(omittedPayload, JSON.stringify(omittedPayload, null, 2), maxBytes);
130
+ }
131
+ const fullText = JSON.stringify(report, null, 2);
132
+ if (Buffer.byteLength(fullText, 'utf8') <= effectiveMaxBytes) {
133
+ return formatBudgetedToolResult(report, fullText, maxBytes);
134
+ }
135
+ const compacted = {
136
+ ...report,
137
+ nonBreaking: [],
138
+ nonBreakingTruncatedByBudget: true,
139
+ nonBreakingSummary: summarizeDiffChangesByCode(report.nonBreaking),
140
+ hint: `Non-breaking details (${report.summary.nonBreakingCount} changes) were summarized to fit the ${effectiveMaxBytes}-byte budget while preserving all breaking changes. Pass a larger max_bytes to inspect individual non-breaking items.`,
141
+ };
142
+ return formatBudgetedToolResult(compacted, JSON.stringify(compacted, null, 2), maxBytes);
143
+ }
144
+ function formatBudgetedToolResult(value, text, maxBytes) {
145
+ const result = enforceSerializedByteBudget(value, text, maxBytes);
146
+ if (!result.ok) {
147
+ return {
148
+ isError: true,
149
+ content: [{ type: 'text', text: result.text }],
150
+ structuredContent: { ...result.errorPayload },
151
+ };
152
+ }
153
+ return {
154
+ content: [{ type: 'text', text: result.text }],
155
+ ...(isRecord(result.data) ? { structuredContent: result.data } : {}),
156
+ };
157
+ }
158
+ function buildActionableToolError(err, toolName = QUERY_NAME) {
159
+ const rawMessage = err instanceof Error ? err.message : String(err);
160
+ if (err instanceof MissingReferenceError) {
161
+ return { isError: true, content: [{ type: 'text', text: err.message }] };
162
+ }
163
+ let recoveryHint;
164
+ if (rawMessage.startsWith('SPEC_NOT_FOUND:') || rawMessage.startsWith('SPEC_FILE_NOT_FOUND:')) {
165
+ recoveryHint =
166
+ 'Pass `root` pointing to the repository root and/or `spec_path` (e.g. `spec_path: "api/openapi.yml"`).';
167
+ }
168
+ else if (rawMessage.startsWith('PATH_TRAVERSAL_DENIED:') || rawMessage.startsWith('REMOTE_REF_DENIED:')) {
169
+ recoveryHint =
170
+ 'Ensure `spec_path` and all `$ref` targets remain local files inside the configured workspace `root`.';
171
+ }
172
+ else if (rawMessage.startsWith('SANDBOX_FORBIDDEN_API:')) {
173
+ recoveryHint =
174
+ 'Use pure synchronous JS reads on `spec` without Node/Bun/network globals, e.g. `{ code: "spec.paths[\'/users\']?.get?.responses" }`.';
175
+ }
176
+ else if (rawMessage.startsWith('SANDBOX_TIMEOUT:')) {
177
+ recoveryHint =
178
+ 'Avoid unbounded loops or scanning huge trees; target a single endpoint or schema key, e.g. `{ code: "Object.keys(spec.paths ?? {})" }`.';
179
+ }
180
+ else if (rawMessage.startsWith('SANDBOX_SYNTAX_ERROR:') || rawMessage.startsWith('SANDBOX_RUNTIME_ERROR:')) {
181
+ recoveryHint =
182
+ 'Check endpoint/schema keys via `openapi://endpoints/index` or `{ code: "Object.keys(spec.paths ?? {})" }`, then retry with valid JS such as `{ code: "spec.paths[\'/users\']?.post" }`.';
183
+ }
184
+ else if (toolName === INSPECT_NAME) {
185
+ recoveryHint =
186
+ 'Verify `openapi_inspect` arguments (`target`, optional `pointer`, `spec_path`, `root`, `offset`, `limit`, `max_bytes`). Example: `openapi_inspect({ target: "endpoints", q: "users" })` or `openapi_inspect({ pointer: "/paths/~1users/get" })`.';
187
+ }
188
+ else if (toolName === DIFF_NAME) {
189
+ recoveryHint =
190
+ 'Verify `base_spec_path` and `target_spec_path` inside the workspace. Example: `openapi_diff({ base_spec_path: "openapi.yml", target_spec_path: "docs/openapi.yml" })`.';
191
+ }
192
+ else if (toolName === DIAGNOSTICS_NAME) {
193
+ recoveryHint =
194
+ 'Verify `root` and optional `spec_path`. Example: `openapi_diagnostics({ spec_path: "openapi.yml" })`.';
195
+ }
196
+ else {
197
+ recoveryHint =
198
+ 'Verify arguments (`code`, optional `spec_path`, `root`, `max_bytes`). Example: `openapi_query({ code: "spec.paths[\'/users\']?.get?.responses" })`.';
199
+ }
200
+ return {
201
+ isError: true,
202
+ content: [{ type: 'text', text: `${rawMessage}\n\nNext step: ${recoveryHint}` }],
203
+ };
204
+ }
205
+ export function createOpenApiMcpServer(options = {}) {
206
+ const configuredRoot = options.defaultRootDir?.trim() || undefined;
207
+ let dynamicDefaultRoot;
208
+ const getDefaultRoot = () => configuredRoot ?? dynamicDefaultRoot ?? process.cwd();
209
+ const defaultSpec = options.defaultSpecPath?.trim() || undefined;
210
+ const sandboxMetaCache = new WeakMap();
211
+ const endpointIndexCache = new WeakMap();
212
+ const schemaIndexCache = new WeakMap();
213
+ function getRelativeSpecPath(loaded) {
214
+ return relative(loaded.rootDir, loaded.specPath).replace(/\\/g, '/') || loaded.specPath;
215
+ }
216
+ function readSpec(root, specPath) {
217
+ const baseRoot = getDefaultRoot();
218
+ const targetRoot = root ?? baseRoot;
219
+ const effectiveDefaultSpec = root && root !== baseRoot ? undefined : defaultSpec;
220
+ return loadOpenApiSpec({
221
+ rootDir: targetRoot,
222
+ specPath: specPath ?? effectiveDefaultSpec,
223
+ allowedRootDir: configuredRoot,
224
+ });
225
+ }
226
+ function getEndpointIndex(loaded) {
227
+ let index = endpointIndexCache.get(loaded.spec);
228
+ if (!index) {
229
+ index = buildEndpointIndex(loaded.spec, loaded.specPath, loaded.sourceLocations);
230
+ endpointIndexCache.set(loaded.spec, index);
231
+ }
232
+ return index;
233
+ }
234
+ function getSchemaIndex(loaded) {
235
+ let schemaIndex = schemaIndexCache.get(loaded.spec);
236
+ if (!schemaIndex) {
237
+ schemaIndex = buildSchemaIndex(loaded.spec, loaded.specPath, loaded.sourceLocations, loaded.schemaUsages);
238
+ schemaIndexCache.set(loaded.spec, schemaIndex);
239
+ }
240
+ return schemaIndex;
241
+ }
242
+ const server = new Server({ name: 'openapi-mcp', version: OPENAPI_MCP_VERSION }, {
243
+ capabilities: { tools: {}, resources: {}, prompts: {} },
244
+ instructions: OPENAPI_MCP_INSTRUCTIONS,
245
+ });
246
+ let pendingRootsRefresh;
247
+ const refreshClientRoots = async () => {
248
+ if (configuredRoot)
249
+ return;
250
+ try {
251
+ if (!server.getClientCapabilities()?.roots)
252
+ return;
253
+ const { roots } = await server.listRoots();
254
+ for (const entry of roots) {
255
+ if (typeof entry.uri === 'string' && entry.uri.startsWith('file://')) {
256
+ try {
257
+ dynamicDefaultRoot = assertWorkspaceRoot(fileURLToPath(entry.uri));
258
+ return;
259
+ }
260
+ catch {
261
+ // Try next root if entry does not exist locally.
262
+ }
263
+ }
264
+ }
265
+ }
266
+ catch {
267
+ // Ignore clients that advertise roots capability without answering roots/list.
268
+ }
269
+ };
270
+ const ensureRootsReady = async () => {
271
+ if (pendingRootsRefresh) {
272
+ await pendingRootsRefresh;
273
+ }
274
+ };
275
+ server.oninitialized = () => {
276
+ pendingRootsRefresh = refreshClientRoots();
277
+ };
278
+ server.setNotificationHandler(RootsListChangedNotificationSchema, async () => {
279
+ pendingRootsRefresh = refreshClientRoots();
280
+ await pendingRootsRefresh;
281
+ });
282
+ registerResourceHandlers(server, {
283
+ getDefaultRoot,
284
+ configuredRoot,
285
+ defaultSpec,
286
+ ensureRootsReady,
287
+ readSpec,
288
+ getEndpointIndex,
289
+ getSchemaIndex,
290
+ });
291
+ server.setRequestHandler(ListPromptsRequestSchema, async () => ({
292
+ prompts: OPENAPI_PROMPTS.map((p) => ({
293
+ name: p.name,
294
+ title: p.title,
295
+ description: p.description,
296
+ arguments: p.arguments.map((a) => ({ ...a })),
297
+ })),
298
+ }));
299
+ server.setRequestHandler(GetPromptRequestSchema, async (request) => getOpenApiPrompt(request.params.name, request.params.arguments));
300
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
301
+ tools: OPENAPI_TOOLS.map((t) => ({
302
+ name: t.name,
303
+ description: t.description,
304
+ inputSchema: t.inputSchema,
305
+ annotations: { ...t.annotations },
306
+ })),
307
+ }));
308
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
309
+ await ensureRootsReady();
310
+ const startedMs = performance.now();
311
+ const { name, arguments: rawArgs } = request.params;
312
+ const argsObj = isRecord(rawArgs) ? rawArgs : {};
313
+ const telemetryCtx = {
314
+ workspaceRoot: typeof argsObj.root === 'string' && argsObj.root.trim() ? argsObj.root.trim() : getDefaultRoot(),
315
+ action: typeof argsObj.target === 'string' ? argsObj.target : undefined,
316
+ };
317
+ const readSpecWithTelemetry = (root, specPath) => {
318
+ const loaded = readSpec(root, specPath);
319
+ telemetryCtx.workspaceRoot = loaded.rootDir;
320
+ telemetryCtx.specPath = getRelativeSpecPath(loaded);
321
+ try {
322
+ const st = statSync(loaded.specPath);
323
+ if (st.isFile() && st.size > 0) {
324
+ telemetryCtx.sourceBytes = (telemetryCtx.sourceBytes ?? 0) + st.size;
325
+ }
326
+ }
327
+ catch {
328
+ // Ignore stat failures for telemetry.
329
+ }
330
+ return loaded;
331
+ };
332
+ const readRawSpecWithTelemetry = (root, specPath) => {
333
+ const baseRoot = getDefaultRoot();
334
+ const targetRoot = root ?? baseRoot;
335
+ const effectiveDefaultSpec = root && root !== baseRoot ? undefined : defaultSpec;
336
+ const rawDoc = loadRawOpenApiDocument({
337
+ rootDir: targetRoot,
338
+ specPath: specPath ?? effectiveDefaultSpec,
339
+ allowedRootDir: configuredRoot,
340
+ });
341
+ telemetryCtx.workspaceRoot = rawDoc.rootDir;
342
+ telemetryCtx.specPath = relative(rawDoc.rootDir, rawDoc.entryPath).replace(/\\/g, '/') || rawDoc.entryPath;
343
+ if (rawDoc.entryFingerprint.size > 0) {
344
+ telemetryCtx.sourceBytes = (telemetryCtx.sourceBytes ?? 0) + rawDoc.entryFingerprint.size;
345
+ }
346
+ return rawDoc;
347
+ };
348
+ const executeToolCall = async () => {
349
+ if (name === DIFF_NAME) {
350
+ const parsed = DiffArgsSchema.safeParse(rawArgs ?? {});
351
+ if (!parsed.success) {
352
+ return formatInvalidArgsError(parsed.error, 'openapi_diff({ base_spec_path: "openapi.yml", target_spec_path: "docs/openapi.yml" })');
353
+ }
354
+ const { base_spec_path, target_spec_path, root, include_non_breaking, max_bytes } = parsed.data;
355
+ try {
356
+ const baseLoaded = readSpecWithTelemetry(root, base_spec_path);
357
+ const targetLoaded = readSpecWithTelemetry(root, target_spec_path);
358
+ const report = diffOpenApiSpecs(baseLoaded.spec, targetLoaded.spec, {
359
+ base: base_spec_path,
360
+ target: target_spec_path,
361
+ });
362
+ return formatBudgetedDiffResult(report, include_non_breaking !== false, max_bytes);
363
+ }
364
+ catch (err) {
365
+ return buildActionableToolError(err, DIFF_NAME);
366
+ }
367
+ }
368
+ if (name === DIAGNOSTICS_NAME) {
369
+ const parsed = DiagnosticsArgsSchema.safeParse(rawArgs ?? {});
370
+ if (!parsed.success) {
371
+ return formatInvalidArgsError(parsed.error, 'openapi_diagnostics({ root: "/path/to/repo", spec_path: "openapi.yml" })');
372
+ }
373
+ const { root, spec_path, max_bytes } = parsed.data;
374
+ try {
375
+ const baseRoot = getDefaultRoot();
376
+ const targetRoot = root ?? baseRoot;
377
+ const effectiveSpec = spec_path ?? (root && root !== baseRoot ? undefined : defaultSpec);
378
+ telemetryCtx.workspaceRoot = targetRoot;
379
+ const report = diagnoseOpenApiSpec({
380
+ rootDir: targetRoot,
381
+ specPath: effectiveSpec,
382
+ allowedRootDir: configuredRoot,
383
+ });
384
+ return formatBudgetedToolResult(report, JSON.stringify(report, null, 2), max_bytes);
385
+ }
386
+ catch (err) {
387
+ return buildActionableToolError(err, DIAGNOSTICS_NAME);
388
+ }
389
+ }
390
+ if (name === INSPECT_NAME) {
391
+ const parsed = InspectArgsSchema.safeParse(rawArgs ?? {});
392
+ if (!parsed.success) {
393
+ return formatInvalidArgsError(parsed.error, 'openapi_inspect({ target: "endpoints", root: "/path/to/repo", q: "orders", limit: 20 })');
394
+ }
395
+ const { target, root, spec_path, q, tag, method, pathPrefix, operationId, missingErrorContracts, usedByPath, unusedOnly, pointer, offset, limit, max_bytes, } = parsed.data;
396
+ telemetryCtx.action = target;
397
+ try {
398
+ if (target === 'catalog') {
399
+ if (pointer) {
400
+ throw new Error('INVALID_ARGUMENT: `pointer` cannot be combined with `target: "catalog"`. Omit `pointer` for workspace discovery or use `target: "endpoints"` / `"schemas"` with `pointer`.');
401
+ }
402
+ const targetRoot = assertWorkspaceRoot(root ?? getDefaultRoot(), configuredRoot);
403
+ telemetryCtx.workspaceRoot = targetRoot;
404
+ const catalog = scanWorkspaceSpecs(targetRoot);
405
+ const payload = catalog.skippedDirCount > 0
406
+ ? {
407
+ rootDir: targetRoot,
408
+ specPaths: catalog.specPaths,
409
+ skippedDirCount: catalog.skippedDirCount,
410
+ skippedDirs: catalog.skippedDirs,
411
+ }
412
+ : { rootDir: targetRoot, specPaths: catalog.specPaths };
413
+ return formatBudgetedToolResult(payload, JSON.stringify(payload, null, 2), max_bytes);
414
+ }
415
+ if (pointer) {
416
+ const rawDoc = readRawSpecWithTelemetry(root, spec_path);
417
+ const relSpecPath = relative(rawDoc.rootDir, rawDoc.entryPath).replace(/\\/g, '/') || rawDoc.entryPath;
418
+ const expanded = expandPointerSubtree(rawDoc, pointer);
419
+ const payload = {
420
+ specPath: relSpecPath,
421
+ pointer: expanded.pointer,
422
+ nodeVisits: expanded.nodeVisits,
423
+ fromCache: expanded.fromCache,
424
+ value: expanded.value,
425
+ };
426
+ return formatBudgetedToolResult(payload, JSON.stringify(payload, null, 2), max_bytes);
427
+ }
428
+ if (target !== 'schemas') {
429
+ const rawDoc = readRawSpecWithTelemetry(root, spec_path);
430
+ const relSpecPath = relative(rawDoc.rootDir, rawDoc.entryPath).replace(/\\/g, '/') || rawDoc.entryPath;
431
+ const effectiveMaxBytes = resolveEffectiveMaxBytes(max_bytes);
432
+ const hasEndpointFilters = q !== undefined || tag !== undefined || method !== undefined || pathPrefix !== undefined ||
433
+ operationId !== undefined || missingErrorContracts !== undefined;
434
+ const isPaginatedRequest = offset > 0 || limit !== undefined;
435
+ const endpointIndex = buildRawEndpointSummary(rawDoc);
436
+ const makePaged = (pageLimit, truncatedByBudget = false) => {
437
+ const page = searchEndpoints(endpointIndex.endpoints, {
438
+ q,
439
+ tag,
440
+ method,
441
+ pathPrefix,
442
+ operationId,
443
+ missingErrorContracts,
444
+ offset,
445
+ limit: pageLimit,
446
+ });
447
+ return {
448
+ specPath: relSpecPath,
449
+ title: endpointIndex.title,
450
+ version: endpointIndex.version,
451
+ openapiVersion: endpointIndex.openapiVersion,
452
+ totalEndpoints: endpointIndex.totalEndpoints,
453
+ tags: endpointIndex.tags,
454
+ endpointsWithErrorContracts: endpointIndex.endpointsWithErrorContracts,
455
+ endpointsMissingErrorContracts: endpointIndex.endpointsMissingErrorContracts,
456
+ offset,
457
+ limit: pageLimit,
458
+ totalMatches: page.totalMatches,
459
+ hasMore: offset + page.endpoints.length < page.totalMatches,
460
+ ...(truncatedByBudget
461
+ ? { truncatedByBudget: true, hint: 'Full endpoint index exceeded max_bytes; returning paginated slice. Pass offset/limit or filters (q, tag, method, pathPrefix).' }
462
+ : {}),
463
+ endpoints: page.endpoints,
464
+ };
465
+ };
466
+ if (hasEndpointFilters || isPaginatedRequest) {
467
+ const payload = makePaged(limit ?? 20);
468
+ return formatBudgetedToolResult(payload, JSON.stringify(payload, null, 2), max_bytes);
469
+ }
470
+ const fullPayload = { ...endpointIndex, specPath: relSpecPath };
471
+ const fullText = JSON.stringify(fullPayload, null, 2);
472
+ if (Buffer.byteLength(fullText, 'utf8') <= effectiveMaxBytes) {
473
+ return formatBudgetedToolResult(fullPayload, fullText, max_bytes);
474
+ }
475
+ const pagedFallback = makePaged(20, true);
476
+ return formatBudgetedToolResult(pagedFallback, JSON.stringify(pagedFallback, null, 2), max_bytes);
477
+ }
478
+ const loaded = readSpecWithTelemetry(root, spec_path);
479
+ const relSpecPath = getRelativeSpecPath(loaded);
480
+ const effectiveMaxBytes = resolveEffectiveMaxBytes(max_bytes);
481
+ const hasSchemaFilters = q !== undefined || usedByPath !== undefined || unusedOnly !== undefined;
482
+ const isPaginatedRequest = offset > 0 || limit !== undefined;
483
+ if (target === 'schemas') {
484
+ const schemaIndex = getSchemaIndex(loaded);
485
+ const makePaged = (pageLimit, truncatedByBudget = false) => {
486
+ const page = searchSchemas(schemaIndex.schemas, {
487
+ q,
488
+ usedByPath,
489
+ unusedOnly,
490
+ offset,
491
+ limit: pageLimit,
492
+ });
493
+ return {
494
+ specPath: relSpecPath,
495
+ title: schemaIndex.title,
496
+ version: schemaIndex.version,
497
+ openapiVersion: schemaIndex.openapiVersion,
498
+ totalSchemas: schemaIndex.totalSchemas,
499
+ unusedSchemas: schemaIndex.unusedSchemas,
500
+ offset,
501
+ limit: pageLimit,
502
+ totalMatches: page.totalMatches,
503
+ hasMore: offset + page.schemas.length < page.totalMatches,
504
+ ...(truncatedByBudget
505
+ ? { truncatedByBudget: true, hint: 'Full schema index exceeded max_bytes; returning paginated slice. Pass offset/limit or filters (q, usedByPath, unusedOnly).' }
506
+ : {}),
507
+ schemas: page.schemas,
508
+ };
509
+ };
510
+ if (hasSchemaFilters || isPaginatedRequest) {
511
+ const payload = makePaged(limit ?? 20);
512
+ return formatBudgetedToolResult(payload, JSON.stringify(payload, null, 2), max_bytes);
513
+ }
514
+ const fullPayload = { ...schemaIndex, specPath: relSpecPath };
515
+ const fullText = JSON.stringify(fullPayload, null, 2);
516
+ if (Buffer.byteLength(fullText, 'utf8') <= effectiveMaxBytes) {
517
+ return formatBudgetedToolResult(fullPayload, fullText, max_bytes);
518
+ }
519
+ const pagedFallback = makePaged(20, true);
520
+ return formatBudgetedToolResult(pagedFallback, JSON.stringify(pagedFallback, null, 2), max_bytes);
521
+ }
522
+ throw new Error(`Unsupported inspect target '${target}'.`);
523
+ }
524
+ catch (err) {
525
+ return buildActionableToolError(err, INSPECT_NAME);
526
+ }
527
+ }
528
+ if (name !== QUERY_NAME) {
529
+ return {
530
+ isError: true,
531
+ content: [
532
+ {
533
+ type: 'text',
534
+ text: `Unknown tool '${name}'. Available tools: ${OPENAPI_TOOLS.map((t) => t.name).join(', ')}.`,
535
+ },
536
+ ],
537
+ };
538
+ }
539
+ const parsed = QueryArgsSchema.safeParse(rawArgs ?? {});
540
+ if (!parsed.success) {
541
+ return formatInvalidArgsError(parsed.error, `openapi_query({ code: "spec.paths['/users']?.get?.responses" })`);
542
+ }
543
+ const { code, spec_path, root, max_bytes } = parsed.data;
544
+ try {
545
+ const loaded = readSpecWithTelemetry(root, spec_path);
546
+ const relSpecPath = getRelativeSpecPath(loaded);
547
+ let metadata = sandboxMetaCache.get(loaded.spec);
548
+ if (!metadata) {
549
+ metadata = {
550
+ sourceLocations: loaded.sourceLocations,
551
+ schemaUsages: loaded.schemaUsages,
552
+ specMeta: {
553
+ specPath: relSpecPath,
554
+ rootDir: loaded.rootDir,
555
+ ...extractSpecMetadata(loaded.spec),
556
+ },
557
+ };
558
+ sandboxMetaCache.set(loaded.spec, metadata);
559
+ }
560
+ const queryResult = evaluateSandboxQuery(loaded.spec, code, { metadata });
561
+ const value = queryResult.text === undefined
562
+ ? { result: null, note: 'Query evaluated to undefined. Use an expression or add a return statement.' }
563
+ : JSON.parse(queryResult.text);
564
+ const text = queryResult.text ?? JSON.stringify(value, null, 2);
565
+ const result = formatBudgetedToolResult(value, text, max_bytes);
566
+ if (!result.isError && !spec_path) {
567
+ result.content.push({ type: 'text', text: `Resolved spec: ${relSpecPath}` });
568
+ }
569
+ return result;
570
+ }
571
+ catch (err) {
572
+ return buildActionableToolError(err, QUERY_NAME);
573
+ }
574
+ };
575
+ const finalResult = await executeToolCall();
576
+ OpenApiTelemetry.recordToolResponse({
577
+ tool: name,
578
+ action: telemetryCtx.action,
579
+ durationMs: Math.round(performance.now() - startedMs),
580
+ workspaceRoot: telemetryCtx.workspaceRoot,
581
+ specPath: telemetryCtx.specPath,
582
+ sourceBytes: telemetryCtx.sourceBytes,
583
+ errorCode: name !== DIFF_NAME && name !== DIAGNOSTICS_NAME && name !== INSPECT_NAME && name !== QUERY_NAME ? 'UNKNOWN_TOOL' : undefined,
584
+ }, finalResult);
585
+ return finalResult;
586
+ });
587
+ return server;
588
+ }