@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.
- package/LICENSE +21 -0
- package/README.md +144 -2
- package/dist/cli/update.d.ts +38 -0
- package/dist/cli/update.js +235 -0
- package/dist/engine/budget.d.ts +40 -0
- package/dist/engine/budget.js +96 -0
- package/dist/engine/example-generator.d.ts +47 -0
- package/dist/engine/example-generator.js +273 -0
- package/dist/engine/index-builder.d.ts +50 -0
- package/dist/engine/index-builder.js +155 -0
- package/dist/engine/index.d.ts +12 -0
- package/dist/engine/index.js +12 -0
- package/dist/engine/json.d.ts +1 -0
- package/dist/engine/json.js +3 -0
- 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 +29 -0
- package/dist/engine/query-sandbox.js +345 -0
- package/dist/engine/schema-index.d.ts +42 -0
- package/dist/engine/schema-index.js +145 -0
- package/dist/engine/source-map.d.ts +15 -0
- package/dist/engine/source-map.js +50 -0
- package/dist/engine/spec-catalog.d.ts +14 -0
- package/dist/engine/spec-catalog.js +99 -0
- package/dist/engine/spec-diagnostics.d.ts +28 -0
- package/dist/engine/spec-diagnostics.js +393 -0
- package/dist/engine/spec-diff.d.ts +32 -0
- package/dist/engine/spec-diff.js +406 -0
- package/dist/engine/spec-loader.d.ts +100 -0
- package/dist/engine/spec-loader.js +528 -0
- package/dist/index.d.ts +49 -0
- package/dist/index.js +371 -0
- package/dist/mcp/prompts.d.ts +51 -0
- package/dist/mcp/prompts.js +161 -0
- package/dist/mcp/resources.d.ts +33 -0
- package/dist/mcp/resources.js +207 -0
- package/dist/mcp/server.d.ts +88 -0
- package/dist/mcp/server.js +588 -0
- package/dist/telemetry/telemetry.d.ts +90 -0
- package/dist/telemetry/telemetry.js +299 -0
- package/docs/feature/README.md +53 -0
- package/docs/feature/getting-started.md +167 -0
- package/docs/feature/index-and-prompts.md +53 -0
- package/docs/feature/openapi-query.md +53 -0
- package/docs/feature/spec-loader.md +34 -0
- package/package.json +77 -4
- package/skills/use-openapi-mcp/SKILL.md +43 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { realpathSync } from 'node:fs';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
5
|
+
import { diagnoseOpenApiSpec, diffOpenApiSpecs, loadOpenApiSpec, } from './engine/index.js';
|
|
6
|
+
import { OPENAPI_MCP_INSTRUCTIONS, OPENAPI_MCP_VERSION, OPENAPI_PROMPTS, OPENAPI_RESOURCES, OPENAPI_TOOLS, createOpenApiMcpServer, getOpenApiPrompt, } from './mcp/server.js';
|
|
7
|
+
import { runOpenApiMcpUpdate } from './cli/update.js';
|
|
8
|
+
import { formatOpenApiStatsText, OpenApiTelemetry } from './telemetry/telemetry.js';
|
|
9
|
+
export * from './engine/index.js';
|
|
10
|
+
export { OPENAPI_MCP_INSTRUCTIONS, OPENAPI_MCP_VERSION, OPENAPI_PROMPTS, OPENAPI_RESOURCES, OPENAPI_TOOLS, createOpenApiMcpServer, getOpenApiPrompt, };
|
|
11
|
+
function writeStderr(message) {
|
|
12
|
+
process.stderr.write(message.endsWith('\n') ? message : `${message}\n`);
|
|
13
|
+
}
|
|
14
|
+
function writeStdout(message) {
|
|
15
|
+
process.stdout.write(message.endsWith('\n') ? message : `${message}\n`);
|
|
16
|
+
}
|
|
17
|
+
function getHelpText() {
|
|
18
|
+
return [
|
|
19
|
+
`openapi-mcp v${OPENAPI_MCP_VERSION} — Local OpenAPI MCP server and contract CLI`,
|
|
20
|
+
'',
|
|
21
|
+
'Usage:',
|
|
22
|
+
' openapi-mcp <command> [options]',
|
|
23
|
+
'',
|
|
24
|
+
'Commands:',
|
|
25
|
+
' serve Start the MCP server over stdio (default when stdin is piped)',
|
|
26
|
+
' check Validate an OpenAPI spec and report contract issues',
|
|
27
|
+
' diff <base> <target> Compare two OpenAPI specs for breaking changes',
|
|
28
|
+
' stats Show persisted MCP telemetry and context savings (--root, --days, --json)',
|
|
29
|
+
' update [version] Update openapi-mcp to latest (or specified) version (--check, --json)',
|
|
30
|
+
'',
|
|
31
|
+
'Options:',
|
|
32
|
+
' --root <dir> Workspace root directory (defaults to current directory)',
|
|
33
|
+
' --spec <path> Path to OpenAPI spec file (serve, check)',
|
|
34
|
+
' --strict Exit with code 1 if warnings are found (check)',
|
|
35
|
+
' --fail-on-breaking Exit with code 1 if breaking changes are found (diff)',
|
|
36
|
+
' --json Output results as JSON (check, diff, stats, update)',
|
|
37
|
+
' -h, --help Show this help message',
|
|
38
|
+
' -v, --version Show version number',
|
|
39
|
+
'',
|
|
40
|
+
'Examples:',
|
|
41
|
+
' openapi-mcp serve --root . --spec openapi.yml',
|
|
42
|
+
' openapi-mcp check --root . --strict',
|
|
43
|
+
' openapi-mcp diff openapi.yml openapi-v2.yml --fail-on-breaking',
|
|
44
|
+
].join('\n');
|
|
45
|
+
}
|
|
46
|
+
function pluralize(count, singular, plural = `${singular}s`) {
|
|
47
|
+
return `${count} ${count === 1 ? singular : plural}`;
|
|
48
|
+
}
|
|
49
|
+
function readFlagValue(argv, index, flag, valueLabel, placeholder) {
|
|
50
|
+
const arg = argv[index];
|
|
51
|
+
if (arg === flag) {
|
|
52
|
+
const value = argv[index + 1];
|
|
53
|
+
if (!value) {
|
|
54
|
+
throw new Error(`Missing ${valueLabel} for '${flag}'. Pass '${flag} ${placeholder}'.`);
|
|
55
|
+
}
|
|
56
|
+
return { value, nextIndex: index + 1 };
|
|
57
|
+
}
|
|
58
|
+
if (arg.startsWith(`${flag}=`)) {
|
|
59
|
+
const value = arg.slice(flag.length + 1);
|
|
60
|
+
if (!value) {
|
|
61
|
+
throw new Error(`Missing ${valueLabel} for '${flag}'. Pass '${flag} ${placeholder}'.`);
|
|
62
|
+
}
|
|
63
|
+
return { value, nextIndex: index };
|
|
64
|
+
}
|
|
65
|
+
return undefined;
|
|
66
|
+
}
|
|
67
|
+
export function parseCliArgs(argv, isTTY) {
|
|
68
|
+
if (argv.length === 0) {
|
|
69
|
+
return isTTY
|
|
70
|
+
? { action: 'help', options: {} }
|
|
71
|
+
: { action: 'serve', options: {} };
|
|
72
|
+
}
|
|
73
|
+
if (argv[0] === 'check') {
|
|
74
|
+
const checkOptions = {};
|
|
75
|
+
for (let i = 1; i < argv.length; i++) {
|
|
76
|
+
const arg = argv[i];
|
|
77
|
+
if (arg === '--help' || arg === '-h')
|
|
78
|
+
return { action: 'help', options: {} };
|
|
79
|
+
if (arg === '--strict') {
|
|
80
|
+
checkOptions.strict = true;
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
if (arg === '--json') {
|
|
84
|
+
checkOptions.json = true;
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
const rootFlag = readFlagValue(argv, i, '--root', 'directory path', '<dir>');
|
|
88
|
+
if (rootFlag) {
|
|
89
|
+
checkOptions.rootDir = rootFlag.value;
|
|
90
|
+
i = rootFlag.nextIndex;
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
const specFlag = readFlagValue(argv, i, '--spec', 'file path', '<path>');
|
|
94
|
+
if (specFlag) {
|
|
95
|
+
checkOptions.specPath = specFlag.value;
|
|
96
|
+
i = specFlag.nextIndex;
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
throw new Error(`Unknown option for 'check': '${arg}'. Run 'openapi-mcp --help' for usage.`);
|
|
100
|
+
}
|
|
101
|
+
return { action: 'check', options: checkOptions };
|
|
102
|
+
}
|
|
103
|
+
if (argv[0] === 'diff') {
|
|
104
|
+
const positionals = [];
|
|
105
|
+
let rootDir;
|
|
106
|
+
let failOnBreaking = false;
|
|
107
|
+
let json = false;
|
|
108
|
+
for (let i = 1; i < argv.length; i++) {
|
|
109
|
+
const arg = argv[i];
|
|
110
|
+
if (arg === '--help' || arg === '-h')
|
|
111
|
+
return { action: 'help', options: {} };
|
|
112
|
+
if (arg === '--fail-on-breaking') {
|
|
113
|
+
failOnBreaking = true;
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
if (arg === '--json') {
|
|
117
|
+
json = true;
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
const rootFlag = readFlagValue(argv, i, '--root', 'directory path', '<dir>');
|
|
121
|
+
if (rootFlag) {
|
|
122
|
+
rootDir = rootFlag.value;
|
|
123
|
+
i = rootFlag.nextIndex;
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
if (arg.startsWith('-')) {
|
|
127
|
+
throw new Error(`Unknown option for 'diff': '${arg}'. Run 'openapi-mcp --help' for usage.`);
|
|
128
|
+
}
|
|
129
|
+
positionals.push(arg);
|
|
130
|
+
}
|
|
131
|
+
if (positionals.length < 2) {
|
|
132
|
+
throw new Error("Missing spec path(s) for 'diff'. Usage: openapi-mcp diff <base> <target> [options]");
|
|
133
|
+
}
|
|
134
|
+
if (positionals.length > 2) {
|
|
135
|
+
throw new Error(`Unexpected argument '${positionals[2]}' for 'diff'. Expected two spec paths: <base> <target>.`);
|
|
136
|
+
}
|
|
137
|
+
return {
|
|
138
|
+
action: 'diff',
|
|
139
|
+
options: {
|
|
140
|
+
baseSpecPath: positionals[0],
|
|
141
|
+
targetSpecPath: positionals[1],
|
|
142
|
+
...(rootDir ? { rootDir } : {}),
|
|
143
|
+
failOnBreaking,
|
|
144
|
+
json,
|
|
145
|
+
},
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
if (argv[0] === 'update') {
|
|
149
|
+
const updateOptions = {};
|
|
150
|
+
for (let i = 1; i < argv.length; i++) {
|
|
151
|
+
const arg = argv[i];
|
|
152
|
+
if (arg === '--help' || arg === '-h')
|
|
153
|
+
return { action: 'help', options: {} };
|
|
154
|
+
if (arg === '--check') {
|
|
155
|
+
updateOptions.check = true;
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
if (arg === '--json') {
|
|
159
|
+
updateOptions.json = true;
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
if (arg.startsWith('-')) {
|
|
163
|
+
throw new Error(`Unknown option for 'update': '${arg}'. Run 'openapi-mcp --help' for usage.`);
|
|
164
|
+
}
|
|
165
|
+
if (updateOptions.version) {
|
|
166
|
+
throw new Error(`Unexpected argument '${arg}' for 'update'. Expected at most one [version].`);
|
|
167
|
+
}
|
|
168
|
+
updateOptions.version = arg;
|
|
169
|
+
}
|
|
170
|
+
return { action: 'update', options: updateOptions };
|
|
171
|
+
}
|
|
172
|
+
if (argv[0] === 'stats') {
|
|
173
|
+
const statsOptions = {};
|
|
174
|
+
for (let i = 1; i < argv.length; i++) {
|
|
175
|
+
const arg = argv[i];
|
|
176
|
+
if (arg === '--help' || arg === '-h')
|
|
177
|
+
return { action: 'help', options: {} };
|
|
178
|
+
if (arg === '--json') {
|
|
179
|
+
statsOptions.json = true;
|
|
180
|
+
continue;
|
|
181
|
+
}
|
|
182
|
+
if (arg === '--days' || arg.startsWith('--days=')) {
|
|
183
|
+
const raw = arg === '--days' ? argv[++i] : arg.slice('--days='.length);
|
|
184
|
+
const parsed = raw ? Number(raw) : NaN;
|
|
185
|
+
if (!Number.isFinite(parsed) || parsed <= 0) {
|
|
186
|
+
throw new Error("Flag '--days' requires a positive number.");
|
|
187
|
+
}
|
|
188
|
+
statsOptions.days = parsed;
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
const rootFlag = readFlagValue(argv, i, '--root', 'directory path', '<dir>');
|
|
192
|
+
if (rootFlag) {
|
|
193
|
+
statsOptions.rootDir = rootFlag.value;
|
|
194
|
+
i = rootFlag.nextIndex;
|
|
195
|
+
continue;
|
|
196
|
+
}
|
|
197
|
+
throw new Error(`Unknown option for 'stats': '${arg}'. Run 'openapi-mcp --help' for usage.`);
|
|
198
|
+
}
|
|
199
|
+
return { action: 'stats', options: statsOptions };
|
|
200
|
+
}
|
|
201
|
+
let i = 0;
|
|
202
|
+
const options = {};
|
|
203
|
+
if (argv[0] === 'serve') {
|
|
204
|
+
i = 1;
|
|
205
|
+
}
|
|
206
|
+
for (; i < argv.length; i++) {
|
|
207
|
+
const arg = argv[i];
|
|
208
|
+
if (arg === '--help' || arg === '-h') {
|
|
209
|
+
return { action: 'help', options: {} };
|
|
210
|
+
}
|
|
211
|
+
if (arg === '--version' || arg === '-v') {
|
|
212
|
+
if (argv.length > 1) {
|
|
213
|
+
throw new Error(`Unexpected arguments alongside '${arg}': ${argv.join(' ')}`);
|
|
214
|
+
}
|
|
215
|
+
return { action: 'version', options: {} };
|
|
216
|
+
}
|
|
217
|
+
const rootFlag = readFlagValue(argv, i, '--root', 'directory path', '<dir>');
|
|
218
|
+
if (rootFlag) {
|
|
219
|
+
options.defaultRootDir = rootFlag.value;
|
|
220
|
+
i = rootFlag.nextIndex;
|
|
221
|
+
continue;
|
|
222
|
+
}
|
|
223
|
+
const specFlag = readFlagValue(argv, i, '--spec', 'file path', '<path>');
|
|
224
|
+
if (specFlag) {
|
|
225
|
+
options.defaultSpecPath = specFlag.value;
|
|
226
|
+
i = specFlag.nextIndex;
|
|
227
|
+
continue;
|
|
228
|
+
}
|
|
229
|
+
throw new Error(`Unknown command or option: '${arg}'. Run 'openapi-mcp --help' for usage.`);
|
|
230
|
+
}
|
|
231
|
+
return { action: 'serve', options };
|
|
232
|
+
}
|
|
233
|
+
export function runCheckCommand(options) {
|
|
234
|
+
const report = diagnoseOpenApiSpec({
|
|
235
|
+
rootDir: options.rootDir,
|
|
236
|
+
specPath: options.specPath,
|
|
237
|
+
allowedRootDir: options.rootDir,
|
|
238
|
+
});
|
|
239
|
+
if (options.json) {
|
|
240
|
+
writeStdout(JSON.stringify(report, null, 2));
|
|
241
|
+
}
|
|
242
|
+
else {
|
|
243
|
+
const status = report.valid ? 'OK' : 'FAILED';
|
|
244
|
+
writeStdout(`[openapi-mcp check] ${status} — ${pluralize(report.summary.errors, 'error')}, ${pluralize(report.summary.warnings, 'warning')} (${report.specPath})`);
|
|
245
|
+
for (const issue of report.issues) {
|
|
246
|
+
const loc = issue.location ? ` (${issue.location.file}:${issue.location.line})` : '';
|
|
247
|
+
writeStdout(` [${issue.severity.toUpperCase()}] ${issue.code}${loc}: ${issue.message}`);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
if (!report.valid)
|
|
251
|
+
return 1;
|
|
252
|
+
if (options.strict && report.summary.warnings > 0)
|
|
253
|
+
return 1;
|
|
254
|
+
return 0;
|
|
255
|
+
}
|
|
256
|
+
export function runDiffCommand(options) {
|
|
257
|
+
const rootDir = options.rootDir ?? process.cwd();
|
|
258
|
+
const baseLoaded = loadOpenApiSpec({ rootDir, specPath: options.baseSpecPath, allowedRootDir: options.rootDir });
|
|
259
|
+
const targetLoaded = loadOpenApiSpec({ rootDir, specPath: options.targetSpecPath, allowedRootDir: options.rootDir });
|
|
260
|
+
const report = diffOpenApiSpecs(baseLoaded.spec, targetLoaded.spec, {
|
|
261
|
+
base: options.baseSpecPath,
|
|
262
|
+
target: options.targetSpecPath,
|
|
263
|
+
});
|
|
264
|
+
if (options.json) {
|
|
265
|
+
writeStdout(JSON.stringify(report, null, 2));
|
|
266
|
+
}
|
|
267
|
+
else {
|
|
268
|
+
writeStdout(`[openapi-mcp diff] ${options.baseSpecPath} -> ${options.targetSpecPath}: ${report.summary.breakingCount} breaking, ${report.summary.nonBreakingCount} non-breaking`);
|
|
269
|
+
for (const change of report.breaking) {
|
|
270
|
+
writeStdout(` [BREAKING] ${change.code} (${change.endpoint}): ${change.message}`);
|
|
271
|
+
}
|
|
272
|
+
for (const change of report.nonBreaking) {
|
|
273
|
+
writeStdout(` [NON_BREAKING] ${change.code} (${change.endpoint}): ${change.message}`);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
return options.failOnBreaking && report.hasBreakingChanges ? 1 : 0;
|
|
277
|
+
}
|
|
278
|
+
export async function runStdioServer(options = {}) {
|
|
279
|
+
const server = createOpenApiMcpServer(options);
|
|
280
|
+
const transport = new StdioServerTransport();
|
|
281
|
+
let shuttingDown = false;
|
|
282
|
+
const shutdown = async (reason, exitCode = 0) => {
|
|
283
|
+
if (shuttingDown)
|
|
284
|
+
return;
|
|
285
|
+
shuttingDown = true;
|
|
286
|
+
writeStderr(`[openapi-mcp] Shutting down (${reason})...`);
|
|
287
|
+
try {
|
|
288
|
+
await server.close();
|
|
289
|
+
}
|
|
290
|
+
catch {
|
|
291
|
+
// Ignore close errors during shutdown
|
|
292
|
+
}
|
|
293
|
+
process.exit(exitCode);
|
|
294
|
+
};
|
|
295
|
+
process.on('SIGINT', () => void shutdown('SIGINT', 0));
|
|
296
|
+
process.on('SIGTERM', () => void shutdown('SIGTERM', 0));
|
|
297
|
+
process.stdin.on('close', () => void shutdown('stdin:close', 0));
|
|
298
|
+
process.stdin.on('end', () => void shutdown('stdin:end', 0));
|
|
299
|
+
transport.onclose = () => void shutdown('transport:close', 0);
|
|
300
|
+
server.onclose = () => void shutdown('server:close', 0);
|
|
301
|
+
transport.onerror = (err) => {
|
|
302
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
303
|
+
writeStderr(`[openapi-mcp] Transport error: ${message}`);
|
|
304
|
+
};
|
|
305
|
+
await server.connect(transport);
|
|
306
|
+
writeStderr(`[openapi-mcp] stdio server ready (v${OPENAPI_MCP_VERSION}, pid=${process.pid}).`);
|
|
307
|
+
}
|
|
308
|
+
const isDirectExecution = (() => {
|
|
309
|
+
try {
|
|
310
|
+
const entryPath = fileURLToPath(import.meta.url);
|
|
311
|
+
if (entryPath.includes('$bunfs') || entryPath.includes('~BUN'))
|
|
312
|
+
return true;
|
|
313
|
+
return Boolean(process.argv[1] && realpathSync(process.argv[1]) === realpathSync(entryPath));
|
|
314
|
+
}
|
|
315
|
+
catch {
|
|
316
|
+
return false;
|
|
317
|
+
}
|
|
318
|
+
})();
|
|
319
|
+
if (isDirectExecution) {
|
|
320
|
+
const argv = process.argv.slice(2);
|
|
321
|
+
try {
|
|
322
|
+
const parsed = parseCliArgs(argv, Boolean(process.stdin.isTTY));
|
|
323
|
+
if (parsed.action === 'help') {
|
|
324
|
+
writeStderr(getHelpText());
|
|
325
|
+
process.exit(0);
|
|
326
|
+
}
|
|
327
|
+
else if (parsed.action === 'version') {
|
|
328
|
+
writeStderr(OPENAPI_MCP_VERSION);
|
|
329
|
+
process.exit(0);
|
|
330
|
+
}
|
|
331
|
+
else if (parsed.action === 'check') {
|
|
332
|
+
process.exit(runCheckCommand(parsed.options));
|
|
333
|
+
}
|
|
334
|
+
else if (parsed.action === 'diff') {
|
|
335
|
+
process.exit(runDiffCommand(parsed.options));
|
|
336
|
+
}
|
|
337
|
+
else if (parsed.action === 'stats') {
|
|
338
|
+
const summary = OpenApiTelemetry.getSummary({
|
|
339
|
+
workspaceRoot: parsed.options.rootDir ?? process.cwd(),
|
|
340
|
+
filterWorkspace: parsed.options.rootDir,
|
|
341
|
+
days: parsed.options.days,
|
|
342
|
+
});
|
|
343
|
+
writeStdout(parsed.options.json ? JSON.stringify(summary, null, 2) : formatOpenApiStatsText(summary));
|
|
344
|
+
process.exit(0);
|
|
345
|
+
}
|
|
346
|
+
else if (parsed.action === 'update') {
|
|
347
|
+
runOpenApiMcpUpdate(parsed.options)
|
|
348
|
+
.then((result) => {
|
|
349
|
+
writeStdout(parsed.options.json ? JSON.stringify(result, null, 2) : result.message);
|
|
350
|
+
process.exit(0);
|
|
351
|
+
})
|
|
352
|
+
.catch((err) => {
|
|
353
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
354
|
+
writeStderr(`[openapi-mcp] ${message}`);
|
|
355
|
+
process.exit(1);
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
else {
|
|
359
|
+
runStdioServer(parsed.options).catch((err) => {
|
|
360
|
+
const message = err instanceof Error ? err.stack || err.message : String(err);
|
|
361
|
+
writeStderr(`[openapi-mcp] Fatal server error: ${message}`);
|
|
362
|
+
process.exit(1);
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
catch (err) {
|
|
367
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
368
|
+
writeStderr(`[openapi-mcp] ${message}`);
|
|
369
|
+
process.exit(1);
|
|
370
|
+
}
|
|
371
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
export declare const OPENAPI_PROMPTS: readonly [{
|
|
2
|
+
readonly name: "sync-frontend-api";
|
|
3
|
+
readonly title: "Sync Frontend API Contract";
|
|
4
|
+
readonly description: "Guide frontend-backend contract sync: read endpoint/schema indexes, query merged operation + 2xx + 4xx/5xx error schemas with openapi_query, and update frontend callers.";
|
|
5
|
+
readonly arguments: readonly [{
|
|
6
|
+
readonly name: "endpoint";
|
|
7
|
+
readonly description: "Optional endpoint filter or path (e.g. 'POST /orders' or '/users').";
|
|
8
|
+
readonly required: false;
|
|
9
|
+
}];
|
|
10
|
+
}, {
|
|
11
|
+
readonly name: "audit-error-contracts";
|
|
12
|
+
readonly title: "Audit OpenAPI Error Contracts";
|
|
13
|
+
readonly description: "Audit completeness and schema consistency of 4xx/5xx error responses across OpenAPI endpoints using spec diagnostics and openapi_query.";
|
|
14
|
+
readonly arguments: readonly [{
|
|
15
|
+
readonly name: "endpoint";
|
|
16
|
+
readonly description: "Optional endpoint filter or path (e.g. 'POST /orders' or '/users') to scope the audit.";
|
|
17
|
+
readonly required: false;
|
|
18
|
+
}];
|
|
19
|
+
}, {
|
|
20
|
+
readonly name: "review-breaking-changes";
|
|
21
|
+
readonly title: "Review OpenAPI Breaking Changes";
|
|
22
|
+
readonly description: "Compare two local OpenAPI specs with openapi_diff, inspect impacted schemas/endpoints, and summarize breaking vs non-breaking contract changes.";
|
|
23
|
+
readonly arguments: readonly [{
|
|
24
|
+
readonly name: "base_spec_path";
|
|
25
|
+
readonly description: "Optional baseline spec path relative to workspace root (e.g. 'openapi.yml').";
|
|
26
|
+
readonly required: false;
|
|
27
|
+
}, {
|
|
28
|
+
readonly name: "target_spec_path";
|
|
29
|
+
readonly description: "Optional target spec path relative to workspace root (e.g. 'docs/openapi.yml').";
|
|
30
|
+
readonly required: false;
|
|
31
|
+
}];
|
|
32
|
+
}, {
|
|
33
|
+
readonly name: "generate-test-fixtures";
|
|
34
|
+
readonly title: "Generate Deterministic API Test Fixtures";
|
|
35
|
+
readonly description: "Synthesize deterministic request, 2xx success, and 4xx/5xx error JSON fixtures from resolved OpenAPI schemas using helpers.example.";
|
|
36
|
+
readonly arguments: readonly [{
|
|
37
|
+
readonly name: "endpoint";
|
|
38
|
+
readonly description: "Optional endpoint filter or path (e.g. 'POST /orders' or '/users').";
|
|
39
|
+
readonly required: false;
|
|
40
|
+
}];
|
|
41
|
+
}];
|
|
42
|
+
export declare function getOpenApiPrompt(name: string, args?: Record<string, string | undefined>): {
|
|
43
|
+
description: string;
|
|
44
|
+
messages: {
|
|
45
|
+
role: "user";
|
|
46
|
+
content: {
|
|
47
|
+
type: "text";
|
|
48
|
+
text: string;
|
|
49
|
+
};
|
|
50
|
+
}[];
|
|
51
|
+
};
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { HTTP_METHODS } from '../engine/index.js';
|
|
2
|
+
const METHOD_PREFIX = new RegExp(`^(?:${HTTP_METHODS.join('|')})\\s+`, 'i');
|
|
3
|
+
const METHOD_AND_PATH = new RegExp(`^(${HTTP_METHODS.join('|')})\\s+(.+)$`, 'i');
|
|
4
|
+
export const OPENAPI_PROMPTS = [
|
|
5
|
+
{
|
|
6
|
+
name: 'sync-frontend-api',
|
|
7
|
+
title: 'Sync Frontend API Contract',
|
|
8
|
+
description: 'Guide frontend-backend contract sync: read endpoint/schema indexes, query merged operation + 2xx + 4xx/5xx error schemas with openapi_query, and update frontend callers.',
|
|
9
|
+
arguments: [
|
|
10
|
+
{
|
|
11
|
+
name: 'endpoint',
|
|
12
|
+
description: "Optional endpoint filter or path (e.g. 'POST /orders' or '/users').",
|
|
13
|
+
required: false,
|
|
14
|
+
},
|
|
15
|
+
],
|
|
16
|
+
},
|
|
17
|
+
{
|
|
18
|
+
name: 'audit-error-contracts',
|
|
19
|
+
title: 'Audit OpenAPI Error Contracts',
|
|
20
|
+
description: 'Audit completeness and schema consistency of 4xx/5xx error responses across OpenAPI endpoints using spec diagnostics and openapi_query.',
|
|
21
|
+
arguments: [
|
|
22
|
+
{
|
|
23
|
+
name: 'endpoint',
|
|
24
|
+
description: "Optional endpoint filter or path (e.g. 'POST /orders' or '/users') to scope the audit.",
|
|
25
|
+
required: false,
|
|
26
|
+
},
|
|
27
|
+
],
|
|
28
|
+
},
|
|
29
|
+
{
|
|
30
|
+
name: 'review-breaking-changes',
|
|
31
|
+
title: 'Review OpenAPI Breaking Changes',
|
|
32
|
+
description: 'Compare two local OpenAPI specs with openapi_diff, inspect impacted schemas/endpoints, and summarize breaking vs non-breaking contract changes.',
|
|
33
|
+
arguments: [
|
|
34
|
+
{
|
|
35
|
+
name: 'base_spec_path',
|
|
36
|
+
description: "Optional baseline spec path relative to workspace root (e.g. 'openapi.yml').",
|
|
37
|
+
required: false,
|
|
38
|
+
},
|
|
39
|
+
{
|
|
40
|
+
name: 'target_spec_path',
|
|
41
|
+
description: "Optional target spec path relative to workspace root (e.g. 'docs/openapi.yml').",
|
|
42
|
+
required: false,
|
|
43
|
+
},
|
|
44
|
+
],
|
|
45
|
+
},
|
|
46
|
+
{
|
|
47
|
+
name: 'generate-test-fixtures',
|
|
48
|
+
title: 'Generate Deterministic API Test Fixtures',
|
|
49
|
+
description: 'Synthesize deterministic request, 2xx success, and 4xx/5xx error JSON fixtures from resolved OpenAPI schemas using helpers.example.',
|
|
50
|
+
arguments: [
|
|
51
|
+
{
|
|
52
|
+
name: 'endpoint',
|
|
53
|
+
description: "Optional endpoint filter or path (e.g. 'POST /orders' or '/users').",
|
|
54
|
+
required: false,
|
|
55
|
+
},
|
|
56
|
+
],
|
|
57
|
+
},
|
|
58
|
+
];
|
|
59
|
+
export function getOpenApiPrompt(name, args = {}) {
|
|
60
|
+
const endpoint = args.endpoint?.trim();
|
|
61
|
+
const methodMatch = endpoint?.match(METHOD_AND_PATH);
|
|
62
|
+
const parsedMethod = methodMatch?.[1]?.toUpperCase();
|
|
63
|
+
const parsedPath = methodMatch?.[2]?.trim() ?? endpoint?.replace(METHOD_PREFIX, '');
|
|
64
|
+
const pathLookup = parsedPath ? `spec.paths[${JSON.stringify(parsedPath)}]` : undefined;
|
|
65
|
+
const helperOpLookup = parsedMethod && parsedPath
|
|
66
|
+
? `helpers.op(${JSON.stringify(parsedMethod)}, ${JSON.stringify(parsedPath)})`
|
|
67
|
+
: undefined;
|
|
68
|
+
const helperExampleLookup = parsedMethod && parsedPath
|
|
69
|
+
? `helpers.example(${JSON.stringify(parsedMethod)}, ${JSON.stringify(parsedPath)})`
|
|
70
|
+
: undefined;
|
|
71
|
+
switch (name) {
|
|
72
|
+
case 'sync-frontend-api': {
|
|
73
|
+
const targetLabel = endpoint ? `for '${endpoint}'` : 'for the target endpoint';
|
|
74
|
+
const querySnippet = helperOpLookup ?? pathLookup ?? "helpers.op('POST', '/your-endpoint')";
|
|
75
|
+
return {
|
|
76
|
+
description: 'Frontend–backend API contract synchronization workflow covering request, 2xx success, and 4xx/5xx error contracts.',
|
|
77
|
+
messages: [
|
|
78
|
+
{
|
|
79
|
+
role: 'user',
|
|
80
|
+
content: {
|
|
81
|
+
type: 'text',
|
|
82
|
+
text: [
|
|
83
|
+
`Synchronize frontend API integration ${targetLabel} using the OpenAPI spec as SSOT:`,
|
|
84
|
+
'1. Read resource `openapi://endpoints/index` or call `openapi_inspect({ target: "endpoints" })` (plus `openapi://schemas/index` if shared models are involved) to verify exact path, HTTP method, auth `security`, `sourceLocation`, and declared status codes (`2xx`, `4xx`, `5xx`).',
|
|
85
|
+
`2. Expand a single subtree lazily with \`openapi_inspect({ pointer: "/paths/..." })\` or call \`openapi_query\` with \`${querySnippet}\` to inspect merged path+operation \`parameters\`, \`requestBody\`, \`2xx\` responses, AND every \`4xx\`/\`5xx\` error schema.`,
|
|
86
|
+
'3. Compare request payloads, auth headers, success DTOs, and error handling branches (status codes, error codes, ProblemDetails/validation fields) in the frontend codebase against the queried OpenAPI contract and align any mismatches.',
|
|
87
|
+
].join('\n'),
|
|
88
|
+
},
|
|
89
|
+
},
|
|
90
|
+
],
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
case 'audit-error-contracts': {
|
|
94
|
+
const scopeLabel = endpoint ? `for endpoint '${endpoint}'` : 'across all endpoints';
|
|
95
|
+
const queryExample = helperOpLookup ?? pathLookup ??
|
|
96
|
+
'Object.entries(spec.paths ?? {}).map(([path, item]) => ({ path, methods: Object.keys(item ?? {}) }))';
|
|
97
|
+
return {
|
|
98
|
+
description: 'Audit completeness and consistency of 4xx/5xx error response contracts in the OpenAPI specification.',
|
|
99
|
+
messages: [
|
|
100
|
+
{
|
|
101
|
+
role: 'user',
|
|
102
|
+
content: {
|
|
103
|
+
type: 'text',
|
|
104
|
+
text: [
|
|
105
|
+
`Audit 4xx/5xx error contracts ${scopeLabel}:`,
|
|
106
|
+
'1. Read `openapi://spec/diagnostics` and `openapi://endpoints/index` (or call `openapi_diagnostics` / `openapi_inspect`) to inspect `MISSING_ERROR_CONTRACT`, `ERROR_RESPONSE_MISSING_SCHEMA`, `endpointsMissingErrorContracts`, and each endpoint\'s `errorStatusCodes` / `errorBodies`.',
|
|
107
|
+
`2. Expand specific operations lazily with \`openapi_inspect({ pointer: "/paths/..." })\` or call \`openapi_query\` with \`code\` (e.g. \`${queryExample}\`) to verify consistent error structures (ProblemDetails / validation fields) for 400, 401, 403, 404, 422, and 500 responses.`,
|
|
108
|
+
'3. Summarize gaps, missing status codes, and schema inconsistencies with exact `sourceLocation` and concrete remediation steps.',
|
|
109
|
+
].join('\n'),
|
|
110
|
+
},
|
|
111
|
+
},
|
|
112
|
+
],
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
case 'review-breaking-changes': {
|
|
116
|
+
const basePath = args.base_spec_path?.trim() || 'openapi.yml';
|
|
117
|
+
const targetPath = args.target_spec_path?.trim() || 'docs/openapi.yml';
|
|
118
|
+
return {
|
|
119
|
+
description: 'Compare two local OpenAPI specs and assess breaking vs non-breaking contract changes.',
|
|
120
|
+
messages: [
|
|
121
|
+
{
|
|
122
|
+
role: 'user',
|
|
123
|
+
content: {
|
|
124
|
+
type: 'text',
|
|
125
|
+
text: [
|
|
126
|
+
`Review contract changes between '${basePath}' and '${targetPath}':`,
|
|
127
|
+
'1. If you are unsure of the spec paths in this workspace, read `openapi://specs/catalog` first.',
|
|
128
|
+
`2. Call \`openapi_diff\` with \`base_spec_path\`: ${JSON.stringify(basePath)} and \`target_spec_path\`: ${JSON.stringify(targetPath)} (plus optional \`root\` / \`max_bytes\`) to classify \`breaking\` vs \`nonBreaking\` changes.`,
|
|
129
|
+
'3. For each breaking change, read `openapi://schemas/index` or call `openapi_query` with `helpers.op(method, path)` / `helpers.schemaRefs(name)` to assess caller blast radius and propose backward-compatible migrations.',
|
|
130
|
+
].join('\n'),
|
|
131
|
+
},
|
|
132
|
+
},
|
|
133
|
+
],
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
case 'generate-test-fixtures': {
|
|
137
|
+
const targetLabel = endpoint ? `for '${endpoint}'` : 'for the target endpoint';
|
|
138
|
+
const exampleSnippet = helperExampleLookup ?? "helpers.example('POST', '/your-endpoint')";
|
|
139
|
+
const opSnippet = helperOpLookup ?? pathLookup ?? "helpers.op('POST', '/your-endpoint')";
|
|
140
|
+
return {
|
|
141
|
+
description: 'Generate deterministic request and response JSON test fixtures from resolved OpenAPI schemas.',
|
|
142
|
+
messages: [
|
|
143
|
+
{
|
|
144
|
+
role: 'user',
|
|
145
|
+
content: {
|
|
146
|
+
type: 'text',
|
|
147
|
+
text: [
|
|
148
|
+
`Generate deterministic API test fixtures ${targetLabel}:`,
|
|
149
|
+
'1. Read `openapi://endpoints/index` or call `openapi_inspect({ target: "endpoints" })` (plus `openapi_inspect({ pointer: "/paths/..." })` for lazy subtree details) to verify exact method, path, auth requirements, and declared `2xx` / `4xx` / `5xx` status codes.',
|
|
150
|
+
`2. Call \`openapi_query\` with \`code\`: \`${exampleSnippet}\` (and \`${opSnippet}\` for required parameters/headers) to synthesize deterministic JSON payloads for request bodies, success responses, and error responses.`,
|
|
151
|
+
'3. Convert the generated payloads into unit, integration, or E2E test fixtures covering both happy-path `2xx` responses and `4xx`/`5xx` error branches.',
|
|
152
|
+
].join('\n'),
|
|
153
|
+
},
|
|
154
|
+
},
|
|
155
|
+
],
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
default:
|
|
159
|
+
throw new Error(`Unknown prompt '${name}'. Available prompts: ${OPENAPI_PROMPTS.map((p) => p.name).join(', ')}.`);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
2
|
+
import { buildEndpointIndex, buildSchemaIndex, type LoadedOpenApiSpec } from '../engine/index.js';
|
|
3
|
+
export declare const OPENAPI_RESOURCES: readonly [{
|
|
4
|
+
readonly uri: "openapi://endpoints/index";
|
|
5
|
+
readonly name: "OpenAPI Endpoints Index";
|
|
6
|
+
readonly 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.";
|
|
7
|
+
readonly mimeType: "application/json";
|
|
8
|
+
}, {
|
|
9
|
+
readonly uri: "openapi://schemas/index";
|
|
10
|
+
readonly name: "OpenAPI Component Schemas Index";
|
|
11
|
+
readonly description: "Compact index of `components.schemas` (or Swagger `definitions`) with required fields, property keys, source locations, and reverse references (`usedBy`) to endpoints.";
|
|
12
|
+
readonly mimeType: "application/json";
|
|
13
|
+
}, {
|
|
14
|
+
readonly uri: "openapi://spec/diagnostics";
|
|
15
|
+
readonly name: "OpenAPI Spec Diagnostics";
|
|
16
|
+
readonly description: "Multi-issue validation & contract quality report: broken $refs, duplicate operationIds, undeclared path params, unknown security schemes, and missing error contracts.";
|
|
17
|
+
readonly mimeType: "application/json";
|
|
18
|
+
}, {
|
|
19
|
+
readonly uri: "openapi://specs/catalog";
|
|
20
|
+
readonly name: "Workspace OpenAPI files";
|
|
21
|
+
readonly description: "List conventional entry filenames relative to the workspace root.";
|
|
22
|
+
readonly mimeType: "application/json";
|
|
23
|
+
}];
|
|
24
|
+
export interface ResourceHandlerContext {
|
|
25
|
+
getDefaultRoot: () => string;
|
|
26
|
+
configuredRoot?: string;
|
|
27
|
+
defaultSpec?: string;
|
|
28
|
+
ensureRootsReady: () => Promise<void>;
|
|
29
|
+
readSpec: (root?: string, specPath?: string) => LoadedOpenApiSpec;
|
|
30
|
+
getEndpointIndex: (loaded: LoadedOpenApiSpec) => ReturnType<typeof buildEndpointIndex>;
|
|
31
|
+
getSchemaIndex: (loaded: LoadedOpenApiSpec) => ReturnType<typeof buildSchemaIndex>;
|
|
32
|
+
}
|
|
33
|
+
export declare function registerResourceHandlers(server: Server, ctx: ResourceHandlerContext): void;
|