@dimassetoid/openapi-mcp 0.0.0-stage → 0.1.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 +133 -2
- 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 +283 -0
- package/dist/engine/index-builder.d.ts +50 -0
- package/dist/engine/index-builder.js +179 -0
- package/dist/engine/index.d.ts +10 -0
- package/dist/engine/index.js +10 -0
- package/dist/engine/json.d.ts +1 -0
- package/dist/engine/json.js +3 -0
- package/dist/engine/query-sandbox.d.ts +21 -0
- package/dist/engine/query-sandbox.js +343 -0
- package/dist/engine/schema-index.d.ts +42 -0
- package/dist/engine/schema-index.js +151 -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 +352 -0
- package/dist/engine/spec-diff.d.ts +31 -0
- package/dist/engine/spec-diff.js +408 -0
- package/dist/engine/spec-loader.d.ts +59 -0
- package/dist/engine/spec-loader.js +484 -0
- package/dist/index.d.ts +37 -0
- package/dist/index.js +293 -0
- package/dist/mcp/prompts.d.ts +51 -0
- package/dist/mcp/prompts.js +161 -0
- package/dist/mcp/resources.d.ts +30 -0
- package/dist/mcp/resources.js +187 -0
- package/dist/mcp/server.d.ts +43 -0
- package/dist/mcp/server.js +201 -0
- package/docs/feature/README.md +65 -0
- package/docs/feature/getting-started.md +131 -0
- package/docs/feature/index-and-prompts.md +50 -0
- package/docs/feature/openapi-query.md +48 -0
- package/docs/feature/spec-loader.md +33 -0
- package/package.json +77 -4
- package/skills/use-openapi-mcp/SKILL.md +42 -0
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import { ListResourcesRequestSchema, ListResourceTemplatesRequestSchema, ReadResourceRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { MAX_RESULT_BYTES } from '../engine/budget.js';
|
|
4
|
+
import { DEFAULT_SPEC_CANDIDATES, buildEndpointIndex, buildSchemaIndex, diagnoseOpenApiSpec, scanWorkspaceSpecs, searchEndpoints, searchSchemas, } from '../engine/index.js';
|
|
5
|
+
const INDEX_URI = 'openapi://endpoints/index';
|
|
6
|
+
const SEARCH_URI = 'openapi://endpoints/search';
|
|
7
|
+
const SCHEMAS_INDEX_URI = 'openapi://schemas/index';
|
|
8
|
+
const SCHEMAS_SEARCH_URI = 'openapi://schemas/search';
|
|
9
|
+
const DIAGNOSTICS_URI = 'openapi://spec/diagnostics';
|
|
10
|
+
const CATALOG_URI = 'openapi://specs/catalog';
|
|
11
|
+
const INDEX_SOFT_MAX_BYTES = 64 * 1024;
|
|
12
|
+
const SpecParams = z.strictObject({ spec_path: z.string().trim().min(1).optional() });
|
|
13
|
+
const BooleanParam = z.enum(['true', 'false']).transform((v) => v === 'true');
|
|
14
|
+
const PaginationParams = {
|
|
15
|
+
offset: z.string().regex(/^\d+$/).pipe(z.coerce.number().int().nonnegative()).default(0),
|
|
16
|
+
limit: z.string().regex(/^\d+$/).pipe(z.coerce.number().int().min(1).max(100)).default(20),
|
|
17
|
+
};
|
|
18
|
+
const SearchParams = SpecParams.extend({
|
|
19
|
+
q: z.string().trim().optional(),
|
|
20
|
+
tag: z.string().trim().optional(),
|
|
21
|
+
method: z.string().trim().min(1).optional(),
|
|
22
|
+
pathPrefix: z.string().trim().min(1).optional(),
|
|
23
|
+
operationId: z.string().trim().optional(),
|
|
24
|
+
missingErrorContracts: BooleanParam.optional(),
|
|
25
|
+
...PaginationParams,
|
|
26
|
+
});
|
|
27
|
+
const SchemaSearchParams = SpecParams.extend({
|
|
28
|
+
q: z.string().trim().optional(),
|
|
29
|
+
usedByPath: z.string().trim().optional(),
|
|
30
|
+
unusedOnly: BooleanParam.optional(),
|
|
31
|
+
...PaginationParams,
|
|
32
|
+
});
|
|
33
|
+
export const OPENAPI_RESOURCES = [
|
|
34
|
+
{
|
|
35
|
+
uri: INDEX_URI,
|
|
36
|
+
name: 'OpenAPI Endpoints Index',
|
|
37
|
+
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.',
|
|
38
|
+
mimeType: 'application/json',
|
|
39
|
+
},
|
|
40
|
+
{
|
|
41
|
+
uri: SCHEMAS_INDEX_URI,
|
|
42
|
+
name: 'OpenAPI Component Schemas Index',
|
|
43
|
+
description: 'Compact index of `components.schemas` (or Swagger `definitions`) with required fields, property keys, source locations, and reverse references (`usedBy`) to endpoints.',
|
|
44
|
+
mimeType: 'application/json',
|
|
45
|
+
},
|
|
46
|
+
{
|
|
47
|
+
uri: DIAGNOSTICS_URI,
|
|
48
|
+
name: 'OpenAPI Spec Diagnostics',
|
|
49
|
+
description: 'Multi-issue validation & contract quality report: broken $refs, duplicate operationIds, undeclared path params, unknown security schemes, and missing error contracts.',
|
|
50
|
+
mimeType: 'application/json',
|
|
51
|
+
},
|
|
52
|
+
{
|
|
53
|
+
uri: CATALOG_URI,
|
|
54
|
+
name: 'Workspace OpenAPI files',
|
|
55
|
+
description: 'List conventional entry filenames relative to the workspace root.',
|
|
56
|
+
mimeType: 'application/json',
|
|
57
|
+
},
|
|
58
|
+
];
|
|
59
|
+
const RESOURCE_TEMPLATES = [
|
|
60
|
+
{
|
|
61
|
+
uriTemplate: SEARCH_URI + '{?q,tag,method,pathPrefix,operationId,missingErrorContracts,offset,limit,spec_path}',
|
|
62
|
+
name: 'Search endpoint index',
|
|
63
|
+
description: 'Search method, path, summary, tags or operationId by substring. Optional exact tag, method, pathPrefix, operationId, and missingErrorContracts filters. Case-insensitive. Follow nextUri for more.',
|
|
64
|
+
mimeType: 'application/json',
|
|
65
|
+
},
|
|
66
|
+
{ uriTemplate: INDEX_URI + '{?spec_path}', name: 'Selected endpoint index', mimeType: 'application/json' },
|
|
67
|
+
{
|
|
68
|
+
uriTemplate: SCHEMAS_SEARCH_URI + '{?q,usedByPath,unusedOnly,offset,limit,spec_path}',
|
|
69
|
+
name: 'Search component schemas',
|
|
70
|
+
description: 'Search components.schemas by name, property, or description, filter by endpoint path usage or unused schemas. Follow nextUri for more.',
|
|
71
|
+
mimeType: 'application/json',
|
|
72
|
+
},
|
|
73
|
+
{ uriTemplate: SCHEMAS_INDEX_URI + '{?spec_path}', name: 'Selected component schemas index', mimeType: 'application/json' },
|
|
74
|
+
{ uriTemplate: DIAGNOSTICS_URI + '{?spec_path}', name: 'Selected spec diagnostics', mimeType: 'application/json' },
|
|
75
|
+
];
|
|
76
|
+
function jsonResource(uri, text) {
|
|
77
|
+
return { contents: [{ uri, mimeType: 'application/json', text }] };
|
|
78
|
+
}
|
|
79
|
+
function buildPaginatedResponse(uri, url, page, pageLength, offset, limitErrorMessage) {
|
|
80
|
+
const next = offset + pageLength;
|
|
81
|
+
url.searchParams.set('offset', String(next));
|
|
82
|
+
const text = JSON.stringify({ ...page, nextUri: next < page.totalMatches ? url.href : null });
|
|
83
|
+
if (Buffer.byteLength(text) > MAX_RESULT_BYTES) {
|
|
84
|
+
throw new Error(limitErrorMessage);
|
|
85
|
+
}
|
|
86
|
+
return jsonResource(uri, text);
|
|
87
|
+
}
|
|
88
|
+
function buildSoftCappedIndexResponse(uri, url, payload, itemCount, itemLabel, filterHint) {
|
|
89
|
+
const text = JSON.stringify(payload, null, 2);
|
|
90
|
+
if (Buffer.byteLength(text) > INDEX_SOFT_MAX_BYTES) {
|
|
91
|
+
url.pathname = '/search';
|
|
92
|
+
url.searchParams.set('limit', '20');
|
|
93
|
+
throw new Error(`INDEX_LIMIT: Full ${itemLabel} index exceeds ${INDEX_SOFT_MAX_BYTES} bytes (${itemCount} ${itemLabel}s). Read ${url.href} and follow nextUri or add filters (${filterHint}).`);
|
|
94
|
+
}
|
|
95
|
+
return jsonResource(uri, text);
|
|
96
|
+
}
|
|
97
|
+
export function registerResourceHandlers(server, ctx) {
|
|
98
|
+
const indexes = new WeakMap();
|
|
99
|
+
const schemaIndexes = new WeakMap();
|
|
100
|
+
server.setRequestHandler(ListResourcesRequestSchema, async () => ({
|
|
101
|
+
resources: OPENAPI_RESOURCES.map((r) => ({ ...r })),
|
|
102
|
+
}));
|
|
103
|
+
server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => ({
|
|
104
|
+
resourceTemplates: RESOURCE_TEMPLATES.map((t) => ({ ...t })),
|
|
105
|
+
}));
|
|
106
|
+
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
|
|
107
|
+
const uri = request.params.uri;
|
|
108
|
+
const isSearch = uri === SEARCH_URI || uri.startsWith(SEARCH_URI + '?');
|
|
109
|
+
const isIndex = uri === INDEX_URI || uri.startsWith(INDEX_URI + '?');
|
|
110
|
+
const isSchemaIndex = uri === SCHEMAS_INDEX_URI || uri.startsWith(SCHEMAS_INDEX_URI + '?');
|
|
111
|
+
const isSchemaSearch = uri === SCHEMAS_SEARCH_URI || uri.startsWith(SCHEMAS_SEARCH_URI + '?');
|
|
112
|
+
const isDiagnostics = uri === DIAGNOSTICS_URI || uri.startsWith(DIAGNOSTICS_URI + '?');
|
|
113
|
+
if (uri === CATALOG_URI) {
|
|
114
|
+
const catalog = scanWorkspaceSpecs(ctx.defaultRoot);
|
|
115
|
+
const payload = catalog.skippedDirCount > 0
|
|
116
|
+
? {
|
|
117
|
+
specPaths: catalog.specPaths,
|
|
118
|
+
skippedDirCount: catalog.skippedDirCount,
|
|
119
|
+
skippedDirs: catalog.skippedDirs,
|
|
120
|
+
}
|
|
121
|
+
: { specPaths: catalog.specPaths };
|
|
122
|
+
const text = JSON.stringify(payload);
|
|
123
|
+
if (Buffer.byteLength(text) > MAX_RESULT_BYTES)
|
|
124
|
+
throw new Error('CATALOG_LIMIT: Select a narrower workspace root.');
|
|
125
|
+
return jsonResource(uri, text);
|
|
126
|
+
}
|
|
127
|
+
if (!isIndex && !isSearch && !isSchemaIndex && !isSchemaSearch && !isDiagnostics) {
|
|
128
|
+
throw new Error(`Unknown resource URI '${uri}'. Available resources: ${OPENAPI_RESOURCES.map((r) => r.uri).join(', ')}, and templates '${SEARCH_URI}{?q,tag,method,pathPrefix,operationId,missingErrorContracts,offset,limit,spec_path}', '${SCHEMAS_SEARCH_URI}{?q,usedByPath,unusedOnly,offset,limit,spec_path}', '${DIAGNOSTICS_URI}{?spec_path}'.`);
|
|
129
|
+
}
|
|
130
|
+
const url = new URL(uri);
|
|
131
|
+
const params = Object.fromEntries(url.searchParams);
|
|
132
|
+
const endpointFilters = isSearch ? SearchParams.parse(params) : undefined;
|
|
133
|
+
const schemaFilters = isSchemaSearch ? SchemaSearchParams.parse(params) : undefined;
|
|
134
|
+
const selected = endpointFilters ?? schemaFilters ?? SpecParams.parse(params);
|
|
135
|
+
try {
|
|
136
|
+
if (isDiagnostics) {
|
|
137
|
+
const report = diagnoseOpenApiSpec({
|
|
138
|
+
rootDir: ctx.defaultRoot,
|
|
139
|
+
specPath: selected.spec_path ?? ctx.defaultSpec,
|
|
140
|
+
allowedRootDir: ctx.configuredRoot,
|
|
141
|
+
});
|
|
142
|
+
const text = JSON.stringify(report, null, 2);
|
|
143
|
+
if (Buffer.byteLength(text) > MAX_RESULT_BYTES) {
|
|
144
|
+
throw new Error('DIAGNOSTICS_LIMIT: Diagnostics payload exceeds response byte limit.');
|
|
145
|
+
}
|
|
146
|
+
return jsonResource(uri, text);
|
|
147
|
+
}
|
|
148
|
+
const loaded = ctx.readSpec(undefined, selected.spec_path);
|
|
149
|
+
if (isSchemaIndex || isSchemaSearch) {
|
|
150
|
+
let schemaIndex = schemaIndexes.get(loaded.spec);
|
|
151
|
+
if (!schemaIndex) {
|
|
152
|
+
schemaIndex = buildSchemaIndex(loaded.spec, loaded.specPath, loaded.sourceLocations, loaded.schemaUsages);
|
|
153
|
+
schemaIndexes.set(loaded.spec, schemaIndex);
|
|
154
|
+
}
|
|
155
|
+
if (schemaFilters) {
|
|
156
|
+
const page = searchSchemas(schemaIndex.schemas, schemaFilters);
|
|
157
|
+
return buildPaginatedResponse(uri, url, page, page.schemas.length, schemaFilters.offset, 'INDEX_LIMIT: Reduce limit or narrow schema search filters.');
|
|
158
|
+
}
|
|
159
|
+
return buildSoftCappedIndexResponse(uri, url, schemaIndex, schemaIndex.totalSchemas, 'schema', 'q, usedByPath, unusedOnly');
|
|
160
|
+
}
|
|
161
|
+
let index = indexes.get(loaded.spec);
|
|
162
|
+
if (!index) {
|
|
163
|
+
index = buildEndpointIndex(loaded.spec, loaded.specPath, loaded.sourceLocations);
|
|
164
|
+
indexes.set(loaded.spec, index);
|
|
165
|
+
}
|
|
166
|
+
if (endpointFilters) {
|
|
167
|
+
const page = searchEndpoints(index.endpoints, endpointFilters);
|
|
168
|
+
return buildPaginatedResponse(uri, url, page, page.endpoints.length, endpointFilters.offset, 'INDEX_LIMIT: Reduce limit or narrow the filters. For a single oversized operation use openapi_query.');
|
|
169
|
+
}
|
|
170
|
+
return buildSoftCappedIndexResponse(uri, url, index, index.totalEndpoints, 'endpoint', 'q, tag, method, pathPrefix');
|
|
171
|
+
}
|
|
172
|
+
catch (err) {
|
|
173
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
174
|
+
if (message.startsWith('SPEC_NOT_FOUND:') || message.startsWith('SPEC_FILE_NOT_FOUND:')) {
|
|
175
|
+
return jsonResource(uri, JSON.stringify({
|
|
176
|
+
status: 'spec_not_found',
|
|
177
|
+
workspaceRoot: ctx.defaultRoot,
|
|
178
|
+
checkedCandidates: selected.spec_path || ctx.defaultSpec
|
|
179
|
+
? [selected.spec_path ?? ctx.defaultSpec]
|
|
180
|
+
: [...DEFAULT_SPEC_CANDIDATES],
|
|
181
|
+
hint: 'Read openapi://specs/catalog and select a spec_path, or configure the default spec.',
|
|
182
|
+
}, null, 2));
|
|
183
|
+
}
|
|
184
|
+
throw err;
|
|
185
|
+
}
|
|
186
|
+
});
|
|
187
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { OPENAPI_PROMPTS, getOpenApiPrompt } from './prompts.js';
|
|
4
|
+
import { OPENAPI_RESOURCES } from './resources.js';
|
|
5
|
+
export { OPENAPI_PROMPTS, OPENAPI_RESOURCES, getOpenApiPrompt };
|
|
6
|
+
export declare const OPENAPI_MCP_VERSION: string;
|
|
7
|
+
export declare const OPENAPI_MCP_INSTRUCTIONS: string;
|
|
8
|
+
export declare const OPENAPI_TOOLS: readonly [{
|
|
9
|
+
readonly name: "openapi_query";
|
|
10
|
+
readonly description: "Query the resolved, read-only OpenAPI spec using synchronous JavaScript against `spec` and built-in `helpers` (`helpers.op`, `helpers.example`, `helpers.schemaRefs`).";
|
|
11
|
+
readonly inputSchema: z.core.ZodStandardJSONSchemaPayload<z.ZodObject<{
|
|
12
|
+
code: z.ZodString;
|
|
13
|
+
spec_path: z.ZodOptional<z.ZodString>;
|
|
14
|
+
root: z.ZodOptional<z.ZodString>;
|
|
15
|
+
max_bytes: z.ZodOptional<z.ZodNumber>;
|
|
16
|
+
}, z.core.$strict>>;
|
|
17
|
+
readonly annotations: {
|
|
18
|
+
readonly readOnlyHint: true;
|
|
19
|
+
readonly destructiveHint: false;
|
|
20
|
+
readonly idempotentHint: true;
|
|
21
|
+
readonly openWorldHint: false;
|
|
22
|
+
};
|
|
23
|
+
}, {
|
|
24
|
+
readonly name: "openapi_diff";
|
|
25
|
+
readonly description: "Compare two local OpenAPI specs (`base_spec_path` vs `target_spec_path`) and classify semantic contract changes into breaking vs non-breaking.";
|
|
26
|
+
readonly inputSchema: z.core.ZodStandardJSONSchemaPayload<z.ZodObject<{
|
|
27
|
+
base_spec_path: z.ZodString;
|
|
28
|
+
target_spec_path: z.ZodString;
|
|
29
|
+
root: z.ZodOptional<z.ZodString>;
|
|
30
|
+
max_bytes: z.ZodOptional<z.ZodNumber>;
|
|
31
|
+
}, z.core.$strict>>;
|
|
32
|
+
readonly annotations: {
|
|
33
|
+
readonly readOnlyHint: true;
|
|
34
|
+
readonly destructiveHint: false;
|
|
35
|
+
readonly idempotentHint: true;
|
|
36
|
+
readonly openWorldHint: false;
|
|
37
|
+
};
|
|
38
|
+
}];
|
|
39
|
+
export interface OpenApiMcpServerOptions {
|
|
40
|
+
defaultRootDir?: string;
|
|
41
|
+
defaultSpecPath?: string;
|
|
42
|
+
}
|
|
43
|
+
export declare function createOpenApiMcpServer(options?: OpenApiMcpServerOptions): Server;
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
2
|
+
import { CallToolRequestSchema, GetPromptRequestSchema, ListPromptsRequestSchema, ListToolsRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import packageInfo from '../../package.json' with { type: 'json' };
|
|
5
|
+
import { MAX_RESULT_BYTES, enforceSerializedByteBudget } from '../engine/budget.js';
|
|
6
|
+
import { DEFAULT_MAX_BYTES, diffOpenApiSpecs, loadOpenApiSpec, } from '../engine/index.js';
|
|
7
|
+
import { isRecord } from '../engine/json.js';
|
|
8
|
+
import { MAX_QUERY_CODE_LENGTH, evaluateSandboxQuery } from '../engine/query-sandbox.js';
|
|
9
|
+
import { MissingReferenceError } from '../engine/spec-loader.js';
|
|
10
|
+
import { OPENAPI_PROMPTS, getOpenApiPrompt } from './prompts.js';
|
|
11
|
+
import { OPENAPI_RESOURCES, registerResourceHandlers } from './resources.js';
|
|
12
|
+
export { OPENAPI_PROMPTS, OPENAPI_RESOURCES, getOpenApiPrompt };
|
|
13
|
+
export const OPENAPI_MCP_VERSION = packageInfo.version;
|
|
14
|
+
const QUERY_NAME = 'openapi_query';
|
|
15
|
+
const DIFF_NAME = 'openapi_diff';
|
|
16
|
+
export const OPENAPI_MCP_INSTRUCTIONS = [
|
|
17
|
+
'Use openapi-mcp in local Code Mode (index-first, query-on-demand):',
|
|
18
|
+
'For monorepos read openapi://specs/catalog, then use the selected spec_path for index, search, schemas, diagnostics, and query.',
|
|
19
|
+
'Discover endpoints with openapi://endpoints/index or openapi://endpoints/search?q=orders&limit=20 (supports tag, method, pathPrefix, operationId, missingErrorContracts) and follow nextUri. Error status counts indicate declarations only; check errorBodies and query the response for field details.',
|
|
20
|
+
'Inspect reusable models and reverse endpoint usage with openapi://schemas/index or openapi://schemas/search?q=Order. Run multi-issue contract health checks with openapi://spec/diagnostics.',
|
|
21
|
+
'1. Read `openapi://endpoints/index` (or `openapi://endpoints/search`) for endpoints, 2xx/4xx/5xx status codes, auth schemes, and YAML/JSON `sourceLocation`.',
|
|
22
|
+
'2. Use `openapi_query` with targeted JavaScript against `spec` and read-only `helpers` (`helpers.op(method, path)` merges path+op parameters, auth, 2xx & 4xx/5xx responses; `helpers.example(method, path, status?)` or `helpers.example(schema)` synthesizes deterministic JSON fixtures; `helpers.schemaRefs(name)` lists reverse references).',
|
|
23
|
+
'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
|
+
`4. Keep queries scoped to specific paths or schemas. The default \`max_bytes\` is ${DEFAULT_MAX_BYTES} UTF-8 bytes of result text.`,
|
|
25
|
+
].join('\n');
|
|
26
|
+
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."),
|
|
28
|
+
spec_path: z.string().regex(/\S/).optional().describe('Optional path to the OpenAPI spec inside the selected workspace.'),
|
|
29
|
+
root: z.string().regex(/\S/).optional().describe('Workspace for this query. When a server root is configured, this path must remain within it.'),
|
|
30
|
+
max_bytes: z.number().int().min(1).max(MAX_RESULT_BYTES).optional().describe(`UTF-8 budget for successful query JSON (default: ${DEFAULT_MAX_BYTES}).`),
|
|
31
|
+
});
|
|
32
|
+
const DiffArgsSchema = z.strictObject({
|
|
33
|
+
base_spec_path: z.string().regex(/\S/).describe('Path to the baseline OpenAPI spec inside the workspace.'),
|
|
34
|
+
target_spec_path: z.string().regex(/\S/).describe('Path to the target/updated OpenAPI spec inside the workspace.'),
|
|
35
|
+
root: z.string().regex(/\S/).optional().describe('Workspace for both specs. 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 diff JSON (default: ${DEFAULT_MAX_BYTES}).`),
|
|
37
|
+
});
|
|
38
|
+
const READ_ONLY_ANNOTATIONS = {
|
|
39
|
+
readOnlyHint: true,
|
|
40
|
+
destructiveHint: false,
|
|
41
|
+
idempotentHint: true,
|
|
42
|
+
openWorldHint: false,
|
|
43
|
+
};
|
|
44
|
+
export const OPENAPI_TOOLS = [
|
|
45
|
+
{
|
|
46
|
+
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`).',
|
|
48
|
+
inputSchema: z.toJSONSchema(QueryArgsSchema),
|
|
49
|
+
annotations: READ_ONLY_ANNOTATIONS,
|
|
50
|
+
},
|
|
51
|
+
{
|
|
52
|
+
name: DIFF_NAME,
|
|
53
|
+
description: 'Compare two local OpenAPI specs (`base_spec_path` vs `target_spec_path`) and classify semantic contract changes into breaking vs non-breaking.',
|
|
54
|
+
inputSchema: z.toJSONSchema(DiffArgsSchema),
|
|
55
|
+
annotations: READ_ONLY_ANNOTATIONS,
|
|
56
|
+
},
|
|
57
|
+
];
|
|
58
|
+
function formatInvalidArgsError(error, example) {
|
|
59
|
+
const issues = error.issues
|
|
60
|
+
.map((issue) => `${issue.path.join('.') || 'arguments'}: ${issue.message}`)
|
|
61
|
+
.join('; ');
|
|
62
|
+
return {
|
|
63
|
+
isError: true,
|
|
64
|
+
content: [{ type: 'text', text: `INVALID_ARGUMENTS: ${issues}.\n\nExample: ${example}` }],
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
function formatBudgetedToolResult(value, text, maxBytes) {
|
|
68
|
+
const result = enforceSerializedByteBudget(value, text, maxBytes);
|
|
69
|
+
if (!result.ok) {
|
|
70
|
+
return {
|
|
71
|
+
isError: true,
|
|
72
|
+
content: [{ type: 'text', text: result.text }],
|
|
73
|
+
structuredContent: { ...result.errorPayload },
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
return {
|
|
77
|
+
content: [{ type: 'text', text: result.text }],
|
|
78
|
+
...(isRecord(result.data) ? { structuredContent: result.data } : {}),
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
function buildActionableToolError(err) {
|
|
82
|
+
const rawMessage = err instanceof Error ? err.message : String(err);
|
|
83
|
+
if (err instanceof MissingReferenceError) {
|
|
84
|
+
return { isError: true, content: [{ type: 'text', text: err.message }] };
|
|
85
|
+
}
|
|
86
|
+
let recoveryHint;
|
|
87
|
+
if (rawMessage.startsWith('SPEC_NOT_FOUND:') || rawMessage.startsWith('SPEC_FILE_NOT_FOUND:')) {
|
|
88
|
+
recoveryHint =
|
|
89
|
+
'Pass `root` pointing to the repository root and/or `spec_path` (e.g. `spec_path: "api/openapi.yml"`).';
|
|
90
|
+
}
|
|
91
|
+
else if (rawMessage.startsWith('PATH_TRAVERSAL_DENIED:') || rawMessage.startsWith('REMOTE_REF_DENIED:')) {
|
|
92
|
+
recoveryHint =
|
|
93
|
+
'Ensure `spec_path` and all `$ref` targets remain local files inside the configured workspace `root`.';
|
|
94
|
+
}
|
|
95
|
+
else if (rawMessage.startsWith('SANDBOX_FORBIDDEN_API:')) {
|
|
96
|
+
recoveryHint =
|
|
97
|
+
'Use pure synchronous JS reads on `spec` without Node/Bun/network globals, e.g. `{ code: "spec.paths[\'/users\']?.get?.responses" }`.';
|
|
98
|
+
}
|
|
99
|
+
else if (rawMessage.startsWith('SANDBOX_TIMEOUT:')) {
|
|
100
|
+
recoveryHint =
|
|
101
|
+
'Avoid unbounded loops or scanning huge trees; target a single endpoint or schema key, e.g. `{ code: "Object.keys(spec.paths ?? {})" }`.';
|
|
102
|
+
}
|
|
103
|
+
else if (rawMessage.startsWith('SANDBOX_SYNTAX_ERROR:') || rawMessage.startsWith('SANDBOX_RUNTIME_ERROR:')) {
|
|
104
|
+
recoveryHint =
|
|
105
|
+
'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
|
+
}
|
|
107
|
+
else {
|
|
108
|
+
recoveryHint =
|
|
109
|
+
'Verify arguments (`code`, optional `spec_path`, `root`, `max_bytes`). Example: `openapi_query({ code: "spec.paths[\'/users\']?.get?.responses" })`.';
|
|
110
|
+
}
|
|
111
|
+
return {
|
|
112
|
+
isError: true,
|
|
113
|
+
content: [{ type: 'text', text: `${rawMessage}\n\nNext step: ${recoveryHint}` }],
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
export function createOpenApiMcpServer(options = {}) {
|
|
117
|
+
const configuredRoot = options.defaultRootDir?.trim() || undefined;
|
|
118
|
+
const defaultRoot = configuredRoot ?? process.cwd();
|
|
119
|
+
const defaultSpec = options.defaultSpecPath?.trim() || undefined;
|
|
120
|
+
const sandboxMetaCache = new WeakMap();
|
|
121
|
+
function readSpec(root, specPath) {
|
|
122
|
+
return loadOpenApiSpec({
|
|
123
|
+
rootDir: root ?? defaultRoot,
|
|
124
|
+
specPath: specPath ?? (root ? undefined : defaultSpec),
|
|
125
|
+
allowedRootDir: configuredRoot,
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
const server = new Server({ name: 'openapi-mcp', version: OPENAPI_MCP_VERSION }, {
|
|
129
|
+
capabilities: { tools: {}, resources: {}, prompts: {} },
|
|
130
|
+
instructions: OPENAPI_MCP_INSTRUCTIONS,
|
|
131
|
+
});
|
|
132
|
+
registerResourceHandlers(server, { defaultRoot, configuredRoot, defaultSpec, readSpec });
|
|
133
|
+
server.setRequestHandler(ListPromptsRequestSchema, async () => ({
|
|
134
|
+
prompts: OPENAPI_PROMPTS.map((p) => ({
|
|
135
|
+
name: p.name,
|
|
136
|
+
title: p.title,
|
|
137
|
+
description: p.description,
|
|
138
|
+
arguments: p.arguments.map((a) => ({ ...a })),
|
|
139
|
+
})),
|
|
140
|
+
}));
|
|
141
|
+
server.setRequestHandler(GetPromptRequestSchema, async (request) => getOpenApiPrompt(request.params.name, request.params.arguments));
|
|
142
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
143
|
+
tools: OPENAPI_TOOLS.map((t) => ({
|
|
144
|
+
name: t.name,
|
|
145
|
+
description: t.description,
|
|
146
|
+
inputSchema: t.inputSchema,
|
|
147
|
+
annotations: { ...t.annotations },
|
|
148
|
+
})),
|
|
149
|
+
}));
|
|
150
|
+
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
151
|
+
const { name, arguments: rawArgs } = request.params;
|
|
152
|
+
if (name === DIFF_NAME) {
|
|
153
|
+
const parsed = DiffArgsSchema.safeParse(rawArgs ?? {});
|
|
154
|
+
if (!parsed.success) {
|
|
155
|
+
return formatInvalidArgsError(parsed.error, 'openapi_diff({ base_spec_path: "openapi.yml", target_spec_path: "docs/openapi.yml" })');
|
|
156
|
+
}
|
|
157
|
+
const { base_spec_path, target_spec_path, root, max_bytes } = parsed.data;
|
|
158
|
+
try {
|
|
159
|
+
const baseLoaded = readSpec(root, base_spec_path);
|
|
160
|
+
const targetLoaded = readSpec(root, target_spec_path);
|
|
161
|
+
const report = diffOpenApiSpecs(baseLoaded.spec, targetLoaded.spec, {
|
|
162
|
+
base: base_spec_path,
|
|
163
|
+
target: target_spec_path,
|
|
164
|
+
});
|
|
165
|
+
return formatBudgetedToolResult(report, JSON.stringify(report, null, 2), max_bytes);
|
|
166
|
+
}
|
|
167
|
+
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);
|
|
188
|
+
}
|
|
189
|
+
const queryResult = evaluateSandboxQuery(loaded.spec, code, { metadata });
|
|
190
|
+
const value = queryResult.text === undefined
|
|
191
|
+
? { result: null, note: 'Query evaluated to undefined. Use an expression or add a return statement.' }
|
|
192
|
+
: JSON.parse(queryResult.text);
|
|
193
|
+
const text = queryResult.text ?? JSON.stringify(value, null, 2);
|
|
194
|
+
return formatBudgetedToolResult(value, text, max_bytes);
|
|
195
|
+
}
|
|
196
|
+
catch (err) {
|
|
197
|
+
return buildActionableToolError(err);
|
|
198
|
+
}
|
|
199
|
+
});
|
|
200
|
+
return server;
|
|
201
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
# openapi-mcp: Implemented Features
|
|
2
|
+
|
|
3
|
+
This directory documents the implemented behavior, MCP contracts, security boundaries, and known limits in this checkout.
|
|
4
|
+
|
|
5
|
+
`openapi-mcp` separates its reusable OpenAPI engine ([src/engine/](../../src/engine/index.ts)) from the MCP server layer ([src/mcp/server.ts](../../src/mcp/server.ts)) and CLI/stdio entrypoint ([src/index.ts](../../src/index.ts)).
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## Feature Documents
|
|
10
|
+
|
|
11
|
+
| Document | Contents |
|
|
12
|
+
|---|---|
|
|
13
|
+
| [Installation and setup](getting-started.md) | Install the server, connect an MCP client, configure monorepos, and run CLI `check`/`diff` |
|
|
14
|
+
| [Spec Loader & `$ref` Resolver](spec-loader.md) | Candidate discovery, single-pass YAML/JSON source mapping, multi-file `$ref`, cycle guards, reverse usage tracking, `realpath` sandboxing, and freshness cache |
|
|
15
|
+
| [Code Mode Query & Diff (`openapi_query`, `openapi_diff`)](openapi-query.md) | Tool schemas, `ToolAnnotations`, QuickJS guest isolation, built-in `helpers` (`op`, `example`, `schemaRefs`), timeouts, byte budget, and semantic contract diffing |
|
|
16
|
+
| [Indexes, Diagnostics & Prompts](index-and-prompts.md) | Resilient workspace catalog, endpoint/schema indexes, paginated search, multi-issue diagnostics, and workflow prompts |
|
|
17
|
+
|
|
18
|
+
---
|
|
19
|
+
|
|
20
|
+
## Architecture Overview
|
|
21
|
+
|
|
22
|
+
```text
|
|
23
|
+
src/
|
|
24
|
+
├── engine/ # Reusable OpenAPI engine library (@dimassetoid/openapi-mcp/engine)
|
|
25
|
+
│ ├── source-map.ts # Single-pass yaml v2 parseDocument + LineCounter source locations
|
|
26
|
+
│ ├── spec-loader.ts # $ref resolver, security guards, reverse schema usage graph, LRU cache
|
|
27
|
+
│ ├── spec-catalog.ts # Resilient workspace discovery (EACCES-safe + default ignore dirs)
|
|
28
|
+
│ ├── index-builder.ts # Endpoint summaries (security, deprecated, sourceLocation) & search
|
|
29
|
+
│ ├── schema-index.ts # Component schema index, reverse references (usedBy), and search
|
|
30
|
+
│ ├── example-generator.ts # Deterministic OpenAPI 3.0/3.1 sample generator & merged operation helper
|
|
31
|
+
│ ├── spec-diagnostics.ts # Non-throwing multi-issue contract & $ref validator
|
|
32
|
+
│ ├── spec-diff.ts # Semantic breaking vs non-breaking OpenAPI diff engine
|
|
33
|
+
│ ├── query-sandbox.ts # Acorn AST checks and bounded QuickJS WASM execution + frozen helpers
|
|
34
|
+
│ ├── budget.ts # UTF-8 result-text budget and narrowing diagnostics
|
|
35
|
+
│ └── index.ts # Public engine exports
|
|
36
|
+
├── mcp/
|
|
37
|
+
│ ├── prompts.ts # 4 MCP prompts & renderer (sync, audit, diff, fixtures)
|
|
38
|
+
│ ├── resources.ts # Catalog, endpoint/schema indexes, paginated search, diagnostics
|
|
39
|
+
│ └── server.ts # MCP Server assembly (instructions, tools, error mapping)
|
|
40
|
+
└── index.ts # CLI (`serve`, `check`, `diff`) & stdio transport lifecycle
|
|
41
|
+
skills/
|
|
42
|
+
└── use-openapi-mcp/SKILL.md # Portable AI Agent Skill playbook
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
---
|
|
46
|
+
|
|
47
|
+
## MCP Primitives Summary
|
|
48
|
+
|
|
49
|
+
| Primitive | Name / URI | Purpose |
|
|
50
|
+
|---|---|---|
|
|
51
|
+
| Resource | `openapi://specs/catalog` | Sorted spec paths relative to workspace root (with `skippedDirs` when unreadable dirs are encountered) |
|
|
52
|
+
| Resource | `openapi://endpoints/index` | Compact endpoint index with `2xx`/`4xx`/`5xx`, `errorBodies`, `security`, `deprecated`, `tags`, and `sourceLocation` (64 KB soft cap) |
|
|
53
|
+
| Resource | `openapi://schemas/index` | Compact `components.schemas` / `definitions` index with `required`, `properties`, `unusedSchemas`, `sourceLocation`, and `usedBy` (64 KB soft cap) |
|
|
54
|
+
| Resource | `openapi://spec/diagnostics` | Multi-issue single-pass report of broken `$ref`s, duplicate `operationId`s, undeclared path params, unknown security schemes, and missing error contracts |
|
|
55
|
+
| Resource templates | `openapi://endpoints/search{?q,tag,method,pathPrefix,operationId,missingErrorContracts,offset,limit,spec_path}`<br>`openapi://endpoints/index{?spec_path}`<br>`openapi://schemas/search{?q,usedByPath,unusedOnly,offset,limit,spec_path}`<br>`openapi://schemas/index{?spec_path}`<br>`openapi://spec/diagnostics{?spec_path}` | Filtered pagination and monorepo `spec_path` selection |
|
|
56
|
+
| Tool | `openapi_query` | Read-only QuickJS query against frozen `spec` and `helpers` (`op`, `example`, `schemaRefs`) |
|
|
57
|
+
| Tool | `openapi_diff` | Read-only semantic breaking vs non-breaking diff between `base_spec_path` and `target_spec_path` |
|
|
58
|
+
| Prompts | `sync-frontend-api`, `audit-error-contracts`, `review-breaking-changes`, `generate-test-fixtures` | Guided agent workflows verified by anti-prompt-drift tests |
|
|
59
|
+
|
|
60
|
+
---
|
|
61
|
+
|
|
62
|
+
## Verification Scope
|
|
63
|
+
|
|
64
|
+
- Unit tests in [tests/engine.test.ts](../../tests/engine.test.ts) cover circular & multi-file `$ref` resolution, path traversal and symlink rejection, warm-cache invalidation (including deleted `$ref` files), `EACCES`-safe catalog scanning, YAML `sourceLocation` tracking, schema index reverse references, deterministic example generation, multi-issue diagnostics, semantic diffing, QuickJS sandbox isolation, and byte-budget enforcement.
|
|
65
|
+
- Protocol & CLI contract tests in [tests/mcp-contract.test.ts](../../tests/mcp-contract.test.ts) cover monorepo selection, search pagination, `initialize`, `tools/list` annotations, `resources/list` + `resources/templates/list` + `resources/read`, `prompts/list` + `prompts/get` anti-prompt-drift checks, `openapi_query` + `openapi_diff` over `InMemoryTransport`, and CLI (`serve`, `check`, `diff`, `--help`, `--version`, `stdio` lifecycle).
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
# Getting Started
|
|
2
|
+
|
|
3
|
+
## Installation
|
|
4
|
+
|
|
5
|
+
### Option 1: Standalone Binary (Linux, macOS, Windows)
|
|
6
|
+
|
|
7
|
+
Install a precompiled single-file executable with automatic SHA-256 checksum verification (no Node.js or Bun runtime required):
|
|
8
|
+
|
|
9
|
+
**Linux & macOS:**
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
curl -fsSL https://raw.githubusercontent.com/Shironim/openapi-mcp/master/scripts/install.sh | sh
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
**Windows (PowerShell):**
|
|
16
|
+
|
|
17
|
+
```powershell
|
|
18
|
+
irm https://raw.githubusercontent.com/Shironim/openapi-mcp/master/scripts/install.ps1 | iex
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Optional environment variables supported by both installers:
|
|
22
|
+
- `OPENAPI_MCP_VERSION` — Install a specific release tag (for example `v0.1.0`; defaults to latest).
|
|
23
|
+
- `OPENAPI_MCP_INSTALL_DIR` — Override the target installation directory.
|
|
24
|
+
- `OPENAPI_MCP_REPO` — Override the GitHub repository slug (defaults to `Shironim/openapi-mcp`).
|
|
25
|
+
|
|
26
|
+
> **Manual Downloads:** [GitHub Releases](https://github.com/Shironim/openapi-mcp/releases) provides binaries for `linux-x64`, `linux-arm64`, `darwin-x64`, `darwin-arm64`, and `windows-x64.exe`, along with `checksums.txt`.
|
|
27
|
+
|
|
28
|
+
### Option 2: npm or Bun (`@dimassetoid/openapi-mcp`)
|
|
29
|
+
|
|
30
|
+
Requires Node.js `>=18.20.0` or Bun `>=1.4.3`:
|
|
31
|
+
|
|
32
|
+
```sh
|
|
33
|
+
npm install -g @dimassetoid/openapi-mcp
|
|
34
|
+
# or
|
|
35
|
+
bun add -g @dimassetoid/openapi-mcp
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
You can also run without a global install via `npx @dimassetoid/openapi-mcp serve` or `bunx @dimassetoid/openapi-mcp serve`.
|
|
39
|
+
|
|
40
|
+
---
|
|
41
|
+
|
|
42
|
+
## MCP Client Configuration
|
|
43
|
+
|
|
44
|
+
Add `openapi-mcp` to `.mcp.json` or your MCP client configuration:
|
|
45
|
+
|
|
46
|
+
```json
|
|
47
|
+
{
|
|
48
|
+
"mcpServers": {
|
|
49
|
+
"openapi-mcp": {
|
|
50
|
+
"command": "openapi-mcp",
|
|
51
|
+
"args": ["serve"]
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Or run directly from source with Bun:
|
|
58
|
+
|
|
59
|
+
```json
|
|
60
|
+
{
|
|
61
|
+
"mcpServers": {
|
|
62
|
+
"openapi-mcp": {
|
|
63
|
+
"command": "bun",
|
|
64
|
+
"args": ["run", "/path/to/openapi-mcp/src/index.ts", "serve"]
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
To pin a workspace boundary and default spec file:
|
|
71
|
+
|
|
72
|
+
```sh
|
|
73
|
+
openapi-mcp serve --root /path/to/repo --spec api/openapi.yml
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## Working with Multiple Specs (Monorepos)
|
|
77
|
+
|
|
78
|
+
Start the server with `--root /path/to/repo`. Read `openapi://specs/catalog` to discover conventional spec paths across projects, then pass `spec_path` per request:
|
|
79
|
+
|
|
80
|
+
- **Endpoint index:** `openapi://endpoints/index?spec_path=apps/billing/openapi.yaml`
|
|
81
|
+
- **Endpoint search:** `openapi://endpoints/search?spec_path=apps/billing/openapi.yaml&q=invoice`
|
|
82
|
+
- **Query:** `openapi_query({ spec_path: "apps/billing/openapi.yaml", code: "spec.info.title" })`
|
|
83
|
+
|
|
84
|
+
URI-encode path values when needed. Without `spec_path`, the server uses `--spec` (if configured) or checks conventional filenames (`openapi.yml`, `openapi.yaml`, `openapi.json`) in the workspace root, `api/`, and `docs/`, in that order. Per-request `spec_path` selections do not mutate the server default.
|
|
85
|
+
|
|
86
|
+
The catalog skips symlinks, `.git`, and `node_modules` (along with other common build/cache directories) and stops with a diagnostic if traversal exceeds 250,000 entries or 1 MiB of output.
|
|
87
|
+
|
|
88
|
+
---
|
|
89
|
+
|
|
90
|
+
## CLI Reference
|
|
91
|
+
|
|
92
|
+
```text
|
|
93
|
+
openapi-mcp <command> [options]
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
| Command | Description |
|
|
97
|
+
| --- | --- |
|
|
98
|
+
| `openapi-mcp serve [--root <dir>] [--spec <path>]` | Start the MCP server over `stdio` |
|
|
99
|
+
| `openapi-mcp check [--root <dir>] [--spec <path>] [--strict] [--json]` | Validate an OpenAPI spec and report contract issues (exits `1` on errors, or warnings with `--strict`) |
|
|
100
|
+
| `openapi-mcp diff <base> <target> [--root <dir>] [--fail-on-breaking] [--json]` | Compare two local specs for breaking changes (exits `1` on breaking changes with `--fail-on-breaking`) |
|
|
101
|
+
| `openapi-mcp` (piped stdin) | Auto-start the MCP server over `stdio` |
|
|
102
|
+
| `openapi-mcp -h \| --help` | Show help message (written to `stderr`) |
|
|
103
|
+
| `openapi-mcp -v \| --version` | Show version number (written to `stderr`) |
|
|
104
|
+
|
|
105
|
+
Startup/shutdown logs, `--help`, and `--version` are written to `stderr`, keeping `stdout` clean for MCP JSON-RPC frames (`serve`) and machine-readable reports (`check`, `diff`).
|
|
106
|
+
|
|
107
|
+
---
|
|
108
|
+
|
|
109
|
+
## Agent Skill
|
|
110
|
+
|
|
111
|
+
Copy [skills/use-openapi-mcp/SKILL.md](../../skills/use-openapi-mcp/SKILL.md) into `.agents/skills/use-openapi-mcp/SKILL.md` (or your global agent skills directory) to provide AI coding agents with a concise routing guide for MCP resources, `helpers.*`, and `openapi_diff`.
|
|
112
|
+
|
|
113
|
+
## Inspecting an API Workflow
|
|
114
|
+
|
|
115
|
+
1. **Select a spec:** In a monorepo, read `openapi://specs/catalog` and pass the chosen `spec_path` to subsequent calls.
|
|
116
|
+
2. **Locate an operation:** Read `openapi://endpoints/index` or query `openapi://endpoints/search?q=orders&limit=20` (follow `nextUri` for additional pages).
|
|
117
|
+
3. **Inspect the contract:** Call `openapi_query` with `helpers.op('POST', '/orders')` or `helpers.example('POST', '/orders', '422')` to inspect merged parameters, auth, and response schemas.
|
|
118
|
+
|
|
119
|
+
Four built-in MCP prompts (`sync-frontend-api`, `audit-error-contracts`, `review-breaking-changes`, and `generate-test-fixtures`) provide step-by-step agent workflows.
|
|
120
|
+
|
|
121
|
+
---
|
|
122
|
+
|
|
123
|
+
## Development & Verification
|
|
124
|
+
|
|
125
|
+
```sh
|
|
126
|
+
bun test # Run engine unit tests and InMemoryTransport MCP contract tests
|
|
127
|
+
bun run typecheck # Run TypeScript strict type checking (tsc --noEmit)
|
|
128
|
+
bun run build # Emit npm JavaScript and type declarations to dist/
|
|
129
|
+
bun run compile:all # Build standalone binaries into release/
|
|
130
|
+
sh scripts/verify-package.sh # Pack, install, typecheck a TypeScript consumer, and smoke-test stdio
|
|
131
|
+
```
|