@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.
- package/README.md +51 -40
- package/dist/cli/update.d.ts +38 -0
- package/dist/cli/update.js +235 -0
- package/dist/engine/example-generator.js +2 -12
- package/dist/engine/index-builder.js +4 -28
- package/dist/engine/index.d.ts +4 -2
- package/dist/engine/index.js +3 -1
- package/dist/engine/lazy-expander.d.ts +37 -0
- package/dist/engine/lazy-expander.js +235 -0
- package/dist/engine/openapi-utils.d.ts +13 -0
- package/dist/engine/openapi-utils.js +48 -0
- package/dist/engine/query-sandbox.d.ts +8 -0
- package/dist/engine/query-sandbox.js +2 -0
- package/dist/engine/schema-index.js +2 -8
- package/dist/engine/spec-diagnostics.js +60 -19
- package/dist/engine/spec-diff.d.ts +1 -0
- package/dist/engine/spec-diff.js +25 -27
- package/dist/engine/spec-loader.d.ts +42 -1
- package/dist/engine/spec-loader.js +137 -93
- package/dist/index.d.ts +12 -0
- package/dist/index.js +79 -1
- package/dist/mcp/prompts.js +5 -5
- package/dist/mcp/resources.d.ts +5 -2
- package/dist/mcp/resources.js +47 -27
- package/dist/mcp/server.d.ts +46 -1
- package/dist/mcp/server.js +443 -56
- package/dist/telemetry/telemetry.d.ts +90 -0
- package/dist/telemetry/telemetry.js +299 -0
- package/docs/feature/README.md +18 -30
- package/docs/feature/getting-started.md +46 -10
- package/docs/feature/index-and-prompts.md +13 -10
- package/docs/feature/openapi-query.md +16 -11
- package/docs/feature/spec-loader.md +9 -8
- package/package.json +2 -2
- package/skills/use-openapi-mcp/SKILL.md +18 -17
package/dist/mcp/server.js
CHANGED
|
@@ -1,30 +1,36 @@
|
|
|
1
|
+
import { statSync } from 'node:fs';
|
|
2
|
+
import { relative } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
1
4
|
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
2
|
-
import { CallToolRequestSchema, GetPromptRequestSchema, ListPromptsRequestSchema, ListToolsRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
|
|
5
|
+
import { CallToolRequestSchema, GetPromptRequestSchema, ListPromptsRequestSchema, ListToolsRequestSchema, RootsListChangedNotificationSchema, } from '@modelcontextprotocol/sdk/types.js';
|
|
3
6
|
import { z } from 'zod';
|
|
4
7
|
import packageInfo from '../../package.json' with { type: 'json' };
|
|
5
8
|
import { MAX_RESULT_BYTES, enforceSerializedByteBudget } from '../engine/budget.js';
|
|
6
|
-
import { DEFAULT_MAX_BYTES, diffOpenApiSpecs, loadOpenApiSpec, } from '../engine/index.js';
|
|
9
|
+
import { DEFAULT_MAX_BYTES, assertWorkspaceRoot, buildEndpointIndex, buildRawEndpointSummary, buildSchemaIndex, diagnoseOpenApiSpec, diffOpenApiSpecs, expandPointerSubtree, extractSpecMetadata, loadOpenApiSpec, loadRawOpenApiDocument, scanWorkspaceSpecs, searchEndpoints, searchSchemas, } from '../engine/index.js';
|
|
7
10
|
import { isRecord } from '../engine/json.js';
|
|
8
11
|
import { MAX_QUERY_CODE_LENGTH, evaluateSandboxQuery } from '../engine/query-sandbox.js';
|
|
9
12
|
import { MissingReferenceError } from '../engine/spec-loader.js';
|
|
10
13
|
import { OPENAPI_PROMPTS, getOpenApiPrompt } from './prompts.js';
|
|
11
14
|
import { OPENAPI_RESOURCES, registerResourceHandlers } from './resources.js';
|
|
15
|
+
import { OpenApiTelemetry } from '../telemetry/telemetry.js';
|
|
12
16
|
export { OPENAPI_PROMPTS, OPENAPI_RESOURCES, getOpenApiPrompt };
|
|
13
17
|
export const OPENAPI_MCP_VERSION = packageInfo.version;
|
|
14
18
|
const QUERY_NAME = 'openapi_query';
|
|
15
19
|
const DIFF_NAME = 'openapi_diff';
|
|
20
|
+
const DIAGNOSTICS_NAME = 'openapi_diagnostics';
|
|
21
|
+
const INSPECT_NAME = 'openapi_inspect';
|
|
16
22
|
export const OPENAPI_MCP_INSTRUCTIONS = [
|
|
17
|
-
'Use openapi-mcp in local Code Mode (index-first,
|
|
18
|
-
'For monorepos read openapi://specs/catalog
|
|
19
|
-
'Discover endpoints with
|
|
20
|
-
'Inspect reusable models and reverse endpoint usage with openapi://schemas/index
|
|
21
|
-
'1. Read `openapi://endpoints/index`
|
|
22
|
-
'2.
|
|
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`).',
|
|
23
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.',
|
|
24
30
|
`4. Keep queries scoped to specific paths or schemas. The default \`max_bytes\` is ${DEFAULT_MAX_BYTES} UTF-8 bytes of result text.`,
|
|
25
31
|
].join('\n');
|
|
26
32
|
const QueryArgsSchema = z.strictObject({
|
|
27
|
-
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), e.g. helpers.op('POST', '/orders') or spec.paths['/users']?.get?.responses."),
|
|
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."),
|
|
28
34
|
spec_path: z.string().regex(/\S/).optional().describe('Optional path to the OpenAPI spec inside the selected workspace.'),
|
|
29
35
|
root: z.string().regex(/\S/).optional().describe('Workspace for this query. When a server root is configured, this path must remain within it.'),
|
|
30
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}).`),
|
|
@@ -33,8 +39,31 @@ const DiffArgsSchema = z.strictObject({
|
|
|
33
39
|
base_spec_path: z.string().regex(/\S/).describe('Path to the baseline OpenAPI spec inside the workspace.'),
|
|
34
40
|
target_spec_path: z.string().regex(/\S/).describe('Path to the target/updated OpenAPI spec inside the workspace.'),
|
|
35
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).'),
|
|
36
43
|
max_bytes: z.number().int().min(1).max(MAX_RESULT_BYTES).optional().describe(`UTF-8 budget for diff JSON (default: ${DEFAULT_MAX_BYTES}).`),
|
|
37
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
|
+
});
|
|
38
67
|
const READ_ONLY_ANNOTATIONS = {
|
|
39
68
|
readOnlyHint: true,
|
|
40
69
|
destructiveHint: false,
|
|
@@ -44,7 +73,7 @@ const READ_ONLY_ANNOTATIONS = {
|
|
|
44
73
|
export const OPENAPI_TOOLS = [
|
|
45
74
|
{
|
|
46
75
|
name: QUERY_NAME,
|
|
47
|
-
description: 'Query the resolved, read-only OpenAPI spec using synchronous JavaScript against `spec` and built-in `helpers` (`helpers.op`, `helpers.example`, `helpers.schemaRefs`).',
|
|
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`).',
|
|
48
77
|
inputSchema: z.toJSONSchema(QueryArgsSchema),
|
|
49
78
|
annotations: READ_ONLY_ANNOTATIONS,
|
|
50
79
|
},
|
|
@@ -54,6 +83,18 @@ export const OPENAPI_TOOLS = [
|
|
|
54
83
|
inputSchema: z.toJSONSchema(DiffArgsSchema),
|
|
55
84
|
annotations: READ_ONLY_ANNOTATIONS,
|
|
56
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
|
+
},
|
|
57
98
|
];
|
|
58
99
|
function formatInvalidArgsError(error, example) {
|
|
59
100
|
const issues = error.issues
|
|
@@ -64,6 +105,42 @@ function formatInvalidArgsError(error, example) {
|
|
|
64
105
|
content: [{ type: 'text', text: `INVALID_ARGUMENTS: ${issues}.\n\nExample: ${example}` }],
|
|
65
106
|
};
|
|
66
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
|
+
}
|
|
67
144
|
function formatBudgetedToolResult(value, text, maxBytes) {
|
|
68
145
|
const result = enforceSerializedByteBudget(value, text, maxBytes);
|
|
69
146
|
if (!result.ok) {
|
|
@@ -78,7 +155,7 @@ function formatBudgetedToolResult(value, text, maxBytes) {
|
|
|
78
155
|
...(isRecord(result.data) ? { structuredContent: result.data } : {}),
|
|
79
156
|
};
|
|
80
157
|
}
|
|
81
|
-
function buildActionableToolError(err) {
|
|
158
|
+
function buildActionableToolError(err, toolName = QUERY_NAME) {
|
|
82
159
|
const rawMessage = err instanceof Error ? err.message : String(err);
|
|
83
160
|
if (err instanceof MissingReferenceError) {
|
|
84
161
|
return { isError: true, content: [{ type: 'text', text: err.message }] };
|
|
@@ -104,6 +181,18 @@ function buildActionableToolError(err) {
|
|
|
104
181
|
recoveryHint =
|
|
105
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" }`.';
|
|
106
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
|
+
}
|
|
107
196
|
else {
|
|
108
197
|
recoveryHint =
|
|
109
198
|
'Verify arguments (`code`, optional `spec_path`, `root`, `max_bytes`). Example: `openapi_query({ code: "spec.paths[\'/users\']?.get?.responses" })`.';
|
|
@@ -115,21 +204,90 @@ function buildActionableToolError(err) {
|
|
|
115
204
|
}
|
|
116
205
|
export function createOpenApiMcpServer(options = {}) {
|
|
117
206
|
const configuredRoot = options.defaultRootDir?.trim() || undefined;
|
|
118
|
-
|
|
207
|
+
let dynamicDefaultRoot;
|
|
208
|
+
const getDefaultRoot = () => configuredRoot ?? dynamicDefaultRoot ?? process.cwd();
|
|
119
209
|
const defaultSpec = options.defaultSpecPath?.trim() || undefined;
|
|
120
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
|
+
}
|
|
121
216
|
function readSpec(root, specPath) {
|
|
217
|
+
const baseRoot = getDefaultRoot();
|
|
218
|
+
const targetRoot = root ?? baseRoot;
|
|
219
|
+
const effectiveDefaultSpec = root && root !== baseRoot ? undefined : defaultSpec;
|
|
122
220
|
return loadOpenApiSpec({
|
|
123
|
-
rootDir:
|
|
124
|
-
specPath: specPath ??
|
|
221
|
+
rootDir: targetRoot,
|
|
222
|
+
specPath: specPath ?? effectiveDefaultSpec,
|
|
125
223
|
allowedRootDir: configuredRoot,
|
|
126
224
|
});
|
|
127
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
|
+
}
|
|
128
242
|
const server = new Server({ name: 'openapi-mcp', version: OPENAPI_MCP_VERSION }, {
|
|
129
243
|
capabilities: { tools: {}, resources: {}, prompts: {} },
|
|
130
244
|
instructions: OPENAPI_MCP_INSTRUCTIONS,
|
|
131
245
|
});
|
|
132
|
-
|
|
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
|
+
});
|
|
133
291
|
server.setRequestHandler(ListPromptsRequestSchema, async () => ({
|
|
134
292
|
prompts: OPENAPI_PROMPTS.map((p) => ({
|
|
135
293
|
name: p.name,
|
|
@@ -148,54 +306,283 @@ export function createOpenApiMcpServer(options = {}) {
|
|
|
148
306
|
})),
|
|
149
307
|
}));
|
|
150
308
|
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
309
|
+
await ensureRootsReady();
|
|
310
|
+
const startedMs = performance.now();
|
|
151
311
|
const { name, arguments: rawArgs } = request.params;
|
|
152
|
-
|
|
153
|
-
|
|
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 ?? {});
|
|
154
540
|
if (!parsed.success) {
|
|
155
|
-
return formatInvalidArgsError(parsed.error,
|
|
541
|
+
return formatInvalidArgsError(parsed.error, `openapi_query({ code: "spec.paths['/users']?.get?.responses" })`);
|
|
156
542
|
}
|
|
157
|
-
const {
|
|
543
|
+
const { code, spec_path, root, max_bytes } = parsed.data;
|
|
158
544
|
try {
|
|
159
|
-
const
|
|
160
|
-
const
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
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;
|
|
166
570
|
}
|
|
167
571
|
catch (err) {
|
|
168
|
-
return buildActionableToolError(err);
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
if (name !== QUERY_NAME) {
|
|
172
|
-
return {
|
|
173
|
-
isError: true,
|
|
174
|
-
content: [{ type: 'text', text: `Unknown tool '${name}'. Available tools: ${QUERY_NAME}, ${DIFF_NAME}.` }],
|
|
175
|
-
};
|
|
176
|
-
}
|
|
177
|
-
const parsed = QueryArgsSchema.safeParse(rawArgs ?? {});
|
|
178
|
-
if (!parsed.success) {
|
|
179
|
-
return formatInvalidArgsError(parsed.error, `openapi_query({ code: "spec.paths['/users']?.get?.responses" })`);
|
|
180
|
-
}
|
|
181
|
-
const { code, spec_path, root, max_bytes } = parsed.data;
|
|
182
|
-
try {
|
|
183
|
-
const loaded = readSpec(root, spec_path);
|
|
184
|
-
let metadata = sandboxMetaCache.get(loaded.spec);
|
|
185
|
-
if (!metadata) {
|
|
186
|
-
metadata = { sourceLocations: loaded.sourceLocations, schemaUsages: loaded.schemaUsages };
|
|
187
|
-
sandboxMetaCache.set(loaded.spec, metadata);
|
|
572
|
+
return buildActionableToolError(err, QUERY_NAME);
|
|
188
573
|
}
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
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;
|
|
199
586
|
});
|
|
200
587
|
return server;
|
|
201
588
|
}
|