@dimassetoid/openapi-mcp 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +144 -2
  3. package/dist/cli/update.d.ts +38 -0
  4. package/dist/cli/update.js +235 -0
  5. package/dist/engine/budget.d.ts +40 -0
  6. package/dist/engine/budget.js +96 -0
  7. package/dist/engine/example-generator.d.ts +47 -0
  8. package/dist/engine/example-generator.js +273 -0
  9. package/dist/engine/index-builder.d.ts +50 -0
  10. package/dist/engine/index-builder.js +155 -0
  11. package/dist/engine/index.d.ts +12 -0
  12. package/dist/engine/index.js +12 -0
  13. package/dist/engine/json.d.ts +1 -0
  14. package/dist/engine/json.js +3 -0
  15. package/dist/engine/lazy-expander.d.ts +37 -0
  16. package/dist/engine/lazy-expander.js +235 -0
  17. package/dist/engine/openapi-utils.d.ts +13 -0
  18. package/dist/engine/openapi-utils.js +48 -0
  19. package/dist/engine/query-sandbox.d.ts +29 -0
  20. package/dist/engine/query-sandbox.js +345 -0
  21. package/dist/engine/schema-index.d.ts +42 -0
  22. package/dist/engine/schema-index.js +145 -0
  23. package/dist/engine/source-map.d.ts +15 -0
  24. package/dist/engine/source-map.js +50 -0
  25. package/dist/engine/spec-catalog.d.ts +14 -0
  26. package/dist/engine/spec-catalog.js +99 -0
  27. package/dist/engine/spec-diagnostics.d.ts +28 -0
  28. package/dist/engine/spec-diagnostics.js +393 -0
  29. package/dist/engine/spec-diff.d.ts +32 -0
  30. package/dist/engine/spec-diff.js +406 -0
  31. package/dist/engine/spec-loader.d.ts +100 -0
  32. package/dist/engine/spec-loader.js +528 -0
  33. package/dist/index.d.ts +49 -0
  34. package/dist/index.js +371 -0
  35. package/dist/mcp/prompts.d.ts +51 -0
  36. package/dist/mcp/prompts.js +161 -0
  37. package/dist/mcp/resources.d.ts +33 -0
  38. package/dist/mcp/resources.js +207 -0
  39. package/dist/mcp/server.d.ts +88 -0
  40. package/dist/mcp/server.js +588 -0
  41. package/dist/telemetry/telemetry.d.ts +90 -0
  42. package/dist/telemetry/telemetry.js +299 -0
  43. package/docs/feature/README.md +53 -0
  44. package/docs/feature/getting-started.md +167 -0
  45. package/docs/feature/index-and-prompts.md +53 -0
  46. package/docs/feature/openapi-query.md +53 -0
  47. package/docs/feature/spec-loader.md +34 -0
  48. package/package.json +77 -4
  49. package/skills/use-openapi-mcp/SKILL.md +43 -0
@@ -0,0 +1,90 @@
1
+ export interface OpenApiToolCallEvent {
2
+ timestamp: string;
3
+ server: 'openapi-mcp';
4
+ event: 'tool_call_completed' | 'tool_call_failed';
5
+ tool: string;
6
+ action?: string;
7
+ duration_ms: number;
8
+ status: 'success' | 'error';
9
+ workspace_name: string;
10
+ workspace_id: string;
11
+ spec_path?: string;
12
+ metrics: {
13
+ bytes_out: number;
14
+ lines_out: number;
15
+ estimated_tokens: number;
16
+ response_bytes: number;
17
+ source_bytes?: number;
18
+ };
19
+ bloat_alert: boolean;
20
+ empty_result?: boolean;
21
+ error?: {
22
+ code?: string;
23
+ message: string;
24
+ };
25
+ }
26
+ export interface OpenApiToolMetricSummary {
27
+ calls: number;
28
+ errors: number;
29
+ avgDurationMs: number;
30
+ p50DurationMs: number;
31
+ p95DurationMs: number;
32
+ totalBytesOut: number;
33
+ }
34
+ export interface OpenApiObservabilitySummary {
35
+ logPath: string;
36
+ totalCalls: number;
37
+ successCount: number;
38
+ errorCount: number;
39
+ errorRatePercent: number;
40
+ avgDurationMs: number;
41
+ p50DurationMs: number;
42
+ p95DurationMs: number;
43
+ slowCallsCount: number;
44
+ totalBytesOut: number;
45
+ totalSourceBytes: number;
46
+ contextSavingsPercent: number | null;
47
+ bloatAlertsCount: number;
48
+ emptyResultsCount: number;
49
+ toolBreakdown: Record<string, OpenApiToolMetricSummary>;
50
+ recentErrors: Array<{
51
+ timestamp: string;
52
+ tool: string;
53
+ code?: string;
54
+ message: string;
55
+ }>;
56
+ }
57
+ export declare function computeOpenApiWorkspaceIdentity(workspaceRoot?: string): {
58
+ workspace_name: string;
59
+ workspace_id: string;
60
+ };
61
+ export declare function resolveOpenApiLogPath(workspaceRoot?: string): string;
62
+ export declare class OpenApiTelemetry {
63
+ static readonly MAX_LOG_SIZE_BYTES: number;
64
+ static readonly MAX_EVENT_BYTES = 4096;
65
+ static readonly SLOW_EXECUTION_THRESHOLD_MS = 250;
66
+ static readonly BLOAT_BYTE_THRESHOLD: number;
67
+ static recordToolResponse(meta: {
68
+ tool: string;
69
+ action?: string;
70
+ durationMs: number;
71
+ workspaceRoot: string;
72
+ specPath?: string;
73
+ sourceBytes?: number;
74
+ errorCode?: string;
75
+ errorMessage?: string;
76
+ }, response: {
77
+ isError?: boolean;
78
+ content?: Array<{
79
+ type?: string;
80
+ text?: unknown;
81
+ }>;
82
+ }): void;
83
+ static getSummary(options?: {
84
+ workspaceRoot?: string;
85
+ filterWorkspace?: string;
86
+ days?: number;
87
+ limit?: number;
88
+ }): OpenApiObservabilitySummary;
89
+ }
90
+ export declare function formatOpenApiStatsText(summary: OpenApiObservabilitySummary): string;
@@ -0,0 +1,299 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, realpathSync, renameSync, statSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { basename, dirname, join, resolve } from 'node:path';
5
+ export function computeOpenApiWorkspaceIdentity(workspaceRoot = process.cwd()) {
6
+ let canonical = resolve(workspaceRoot);
7
+ try {
8
+ canonical = realpathSync(canonical);
9
+ }
10
+ catch {
11
+ // Fallback to resolved path when transient.
12
+ }
13
+ const digest = createHash('sha256').update(canonical).digest('hex').slice(0, 12);
14
+ return {
15
+ workspace_name: (basename(canonical) || 'workspace').slice(0, 64),
16
+ workspace_id: digest,
17
+ };
18
+ }
19
+ export function resolveOpenApiLogPath(workspaceRoot = process.cwd()) {
20
+ const envPath = process.env.OPENAPI_MCP_LOG_PATH?.trim();
21
+ if (envPath)
22
+ return envPath;
23
+ const localDir = join(workspaceRoot, '.openapi-mcp');
24
+ if (existsSync(localDir)) {
25
+ return join(localDir, 'openapi.log');
26
+ }
27
+ return join(homedir(), '.openapi-mcp', 'openapi.log');
28
+ }
29
+ function calcPercentile(values, p) {
30
+ if (values.length === 0)
31
+ return 0;
32
+ const sorted = [...values].sort((a, b) => a - b);
33
+ const idx = Math.ceil((p / 100) * sorted.length) - 1;
34
+ return sorted[Math.max(0, Math.min(idx, sorted.length - 1))] ?? 0;
35
+ }
36
+ function extractErrorCode(text) {
37
+ const match = text.match(/^([A-Z][A-Z0-9_]{2,48}):/);
38
+ return match?.[1];
39
+ }
40
+ export class OpenApiTelemetry {
41
+ static MAX_LOG_SIZE_BYTES = 2 * 1024 * 1024;
42
+ static MAX_EVENT_BYTES = 4096;
43
+ static SLOW_EXECUTION_THRESHOLD_MS = 250;
44
+ static BLOAT_BYTE_THRESHOLD = 16 * 1024;
45
+ static recordToolResponse(meta, response) {
46
+ try {
47
+ const texts = (response.content ?? [])
48
+ .map((c) => (typeof c.text === 'string' ? c.text : ''))
49
+ .filter(Boolean);
50
+ const combinedText = texts.join('\n');
51
+ const bytesOut = Buffer.byteLength(combinedText, 'utf8');
52
+ const linesOut = combinedText ? combinedText.split('\n').length : 0;
53
+ const responseBytes = Buffer.byteLength(JSON.stringify(response), 'utf8');
54
+ const bloatAlert = responseBytes >= this.BLOAT_BYTE_THRESHOLD;
55
+ const isError = Boolean(response.isError);
56
+ const isEmpty = !isError && (combinedText.trim() === '' || combinedText.trim() === 'null' || combinedText.trim() === '[]') ? true : undefined;
57
+ const identity = computeOpenApiWorkspaceIdentity(meta.workspaceRoot);
58
+ const derivedErrorCode = isError
59
+ ? meta.errorCode ?? extractErrorCode(combinedText.trim()) ?? 'TOOL_ERROR'
60
+ : undefined;
61
+ const safeErrorMsg = isError
62
+ ? (meta.errorMessage ?? combinedText.trim().split('\n')[0] ?? 'Tool failed').slice(0, 256)
63
+ : undefined;
64
+ const payload = {
65
+ timestamp: new Date().toISOString(),
66
+ server: 'openapi-mcp',
67
+ event: isError ? 'tool_call_failed' : 'tool_call_completed',
68
+ tool: meta.tool.slice(0, 64),
69
+ ...(meta.action ? { action: meta.action.slice(0, 64) } : {}),
70
+ duration_ms: Math.max(0, Math.round(meta.durationMs)),
71
+ status: isError ? 'error' : 'success',
72
+ workspace_name: identity.workspace_name,
73
+ workspace_id: identity.workspace_id,
74
+ ...(meta.specPath ? { spec_path: meta.specPath.slice(0, 120) } : {}),
75
+ metrics: {
76
+ bytes_out: bytesOut,
77
+ lines_out: linesOut,
78
+ estimated_tokens: Math.round(bytesOut / 4),
79
+ response_bytes: responseBytes,
80
+ ...(typeof meta.sourceBytes === 'number' && meta.sourceBytes > 0 ? { source_bytes: meta.sourceBytes } : {}),
81
+ },
82
+ bloat_alert: bloatAlert,
83
+ ...(isEmpty ? { empty_result: true } : {}),
84
+ ...(isError
85
+ ? {
86
+ error: {
87
+ ...(derivedErrorCode ? { code: derivedErrorCode.slice(0, 64) } : {}),
88
+ message: safeErrorMsg ?? 'Tool failed',
89
+ },
90
+ }
91
+ : {}),
92
+ };
93
+ let line = JSON.stringify(payload);
94
+ if (Buffer.byteLength(line, 'utf8') + 1 > this.MAX_EVENT_BYTES) {
95
+ if (payload.error)
96
+ payload.error.message = payload.error.message.slice(0, 96);
97
+ line = JSON.stringify(payload);
98
+ }
99
+ if (Buffer.byteLength(line, 'utf8') + 1 > this.MAX_EVENT_BYTES)
100
+ return;
101
+ if (payload.status === 'error') {
102
+ process.stderr.write(`[openapi-telemetry ERROR] ${line}\n`);
103
+ }
104
+ else if (payload.bloat_alert) {
105
+ process.stderr.write(`[openapi-telemetry BLOAT_WARN] ${line}\n`);
106
+ }
107
+ else if (payload.duration_ms >= this.SLOW_EXECUTION_THRESHOLD_MS) {
108
+ process.stderr.write(`[openapi-telemetry SLOW_WARN] ${line}\n`);
109
+ }
110
+ const logPath = resolveOpenApiLogPath(meta.workspaceRoot);
111
+ const logDir = dirname(logPath);
112
+ if (!existsSync(logDir)) {
113
+ mkdirSync(logDir, { recursive: true, mode: 0o700 });
114
+ }
115
+ if (existsSync(logPath)) {
116
+ const st = statSync(logPath);
117
+ if (st.size + Buffer.byteLength(line, 'utf8') + 1 > this.MAX_LOG_SIZE_BYTES) {
118
+ renameSync(logPath, `${logPath}.1`);
119
+ }
120
+ }
121
+ appendFileSync(logPath, `${line}\n`, { encoding: 'utf8', mode: 0o600 });
122
+ }
123
+ catch {
124
+ // Telemetry failures must never impact MCP responses.
125
+ }
126
+ }
127
+ static getSummary(options = {}) {
128
+ const workspaceRoot = options.workspaceRoot ?? process.cwd();
129
+ const logPath = resolveOpenApiLogPath(workspaceRoot);
130
+ const limit = options.limit ?? 500;
131
+ const cutoffMs = typeof options.days === 'number' && options.days > 0
132
+ ? Date.now() - options.days * 24 * 60 * 60 * 1000
133
+ : null;
134
+ const targetWorkspaceId = options.filterWorkspace
135
+ ? computeOpenApiWorkspaceIdentity(options.filterWorkspace).workspace_id
136
+ : undefined;
137
+ const emptySummary = {
138
+ logPath,
139
+ totalCalls: 0,
140
+ successCount: 0,
141
+ errorCount: 0,
142
+ errorRatePercent: 0,
143
+ avgDurationMs: 0,
144
+ p50DurationMs: 0,
145
+ p95DurationMs: 0,
146
+ slowCallsCount: 0,
147
+ totalBytesOut: 0,
148
+ totalSourceBytes: 0,
149
+ contextSavingsPercent: null,
150
+ bloatAlertsCount: 0,
151
+ emptyResultsCount: 0,
152
+ toolBreakdown: {},
153
+ recentErrors: [],
154
+ };
155
+ const rawLines = [];
156
+ for (const candidate of [`${logPath}.1`, logPath]) {
157
+ if (!existsSync(candidate))
158
+ continue;
159
+ try {
160
+ const lines = readFileSync(candidate, 'utf8').split('\n').filter((l) => l.trim().length > 0);
161
+ rawLines.push(...lines);
162
+ }
163
+ catch {
164
+ // Ignore unreadable backup slices.
165
+ }
166
+ }
167
+ if (rawLines.length === 0)
168
+ return emptySummary;
169
+ const events = [];
170
+ for (const line of rawLines.slice(-limit)) {
171
+ try {
172
+ const parsed = JSON.parse(line);
173
+ if (parsed.event !== 'tool_call_completed' && parsed.event !== 'tool_call_failed')
174
+ continue;
175
+ if (cutoffMs !== null && parsed.timestamp) {
176
+ const ms = Date.parse(parsed.timestamp);
177
+ if (Number.isFinite(ms) && ms < cutoffMs)
178
+ continue;
179
+ }
180
+ if (targetWorkspaceId && parsed.workspace_id !== targetWorkspaceId)
181
+ continue;
182
+ events.push(parsed);
183
+ }
184
+ catch {
185
+ // Ignore malformed lines.
186
+ }
187
+ }
188
+ if (events.length === 0)
189
+ return emptySummary;
190
+ let successCount = 0;
191
+ let errorCount = 0;
192
+ let slowCallsCount = 0;
193
+ let totalBytesOut = 0;
194
+ let totalSourceBytes = 0;
195
+ let sourceOutputBytes = 0;
196
+ let bloatAlertsCount = 0;
197
+ let emptyResultsCount = 0;
198
+ const durations = [];
199
+ const recentErrors = [];
200
+ const toolMap = {};
201
+ for (const ev of events) {
202
+ const toolName = ev.tool || 'unknown';
203
+ if (!toolMap[toolName]) {
204
+ toolMap[toolName] = { calls: 0, errors: 0, durations: [], bytesOut: 0 };
205
+ }
206
+ toolMap[toolName].calls++;
207
+ toolMap[toolName].durations.push(ev.duration_ms || 0);
208
+ durations.push(ev.duration_ms || 0);
209
+ const bytes = ev.metrics?.bytes_out ?? 0;
210
+ totalBytesOut += bytes;
211
+ toolMap[toolName].bytesOut += bytes;
212
+ if (typeof ev.metrics?.source_bytes === 'number' && ev.metrics.source_bytes > 0) {
213
+ totalSourceBytes += ev.metrics.source_bytes;
214
+ sourceOutputBytes += bytes;
215
+ }
216
+ if (ev.duration_ms >= this.SLOW_EXECUTION_THRESHOLD_MS)
217
+ slowCallsCount++;
218
+ if (ev.bloat_alert)
219
+ bloatAlertsCount++;
220
+ if (ev.empty_result)
221
+ emptyResultsCount++;
222
+ if (ev.status === 'error') {
223
+ errorCount++;
224
+ toolMap[toolName].errors++;
225
+ recentErrors.push({
226
+ timestamp: ev.timestamp || '',
227
+ tool: toolName,
228
+ ...(ev.error?.code ? { code: ev.error.code } : {}),
229
+ message: ev.error?.message || 'Unknown error',
230
+ });
231
+ }
232
+ else {
233
+ successCount++;
234
+ }
235
+ }
236
+ const toolBreakdown = {};
237
+ for (const [tool, st] of Object.entries(toolMap)) {
238
+ toolBreakdown[tool] = {
239
+ calls: st.calls,
240
+ errors: st.errors,
241
+ avgDurationMs: st.durations.length
242
+ ? Math.round(st.durations.reduce((a, b) => a + b, 0) / st.durations.length)
243
+ : 0,
244
+ p50DurationMs: calcPercentile(st.durations, 50),
245
+ p95DurationMs: calcPercentile(st.durations, 95),
246
+ totalBytesOut: st.bytesOut,
247
+ };
248
+ }
249
+ const contextSavingsPercent = totalSourceBytes > 0
250
+ ? Math.round(((totalSourceBytes - sourceOutputBytes) / totalSourceBytes) * 1000) / 10
251
+ : null;
252
+ return {
253
+ logPath,
254
+ totalCalls: events.length,
255
+ successCount,
256
+ errorCount,
257
+ errorRatePercent: Math.round((errorCount / events.length) * 1000) / 10,
258
+ avgDurationMs: durations.length ? Math.round(durations.reduce((a, b) => a + b, 0) / durations.length) : 0,
259
+ p50DurationMs: calcPercentile(durations, 50),
260
+ p95DurationMs: calcPercentile(durations, 95),
261
+ slowCallsCount,
262
+ totalBytesOut,
263
+ totalSourceBytes,
264
+ contextSavingsPercent,
265
+ bloatAlertsCount,
266
+ emptyResultsCount,
267
+ toolBreakdown,
268
+ recentErrors: recentErrors.slice(-10).reverse(),
269
+ };
270
+ }
271
+ }
272
+ export function formatOpenApiStatsText(summary) {
273
+ const lines = [
274
+ '# OpenAPI-MCP Observability Telemetry',
275
+ `- Log: ${summary.logPath}`,
276
+ `- Calls: ${summary.totalCalls} (${summary.successCount} succeeded, ${summary.errorCount} failed, ${summary.errorRatePercent}% error rate)`,
277
+ `- Latency (p50 / p95 / avg): ${summary.p50DurationMs}ms / ${summary.p95DurationMs}ms / ${summary.avgDurationMs}ms`,
278
+ `- Slow (>=250ms) / Bloat (>=16KB) / Empty: ${summary.slowCallsCount} slow, ${summary.bloatAlertsCount} bloat, ${summary.emptyResultsCount} empty`,
279
+ `- Payload Streamed: ${(summary.totalBytesOut / 1024).toFixed(1)} KB`,
280
+ ...(summary.contextSavingsPercent !== null
281
+ ? [`- Context Savings (Query vs Raw Spec): ${summary.contextSavingsPercent}% (${(summary.totalSourceBytes / 1024).toFixed(1)} KB raw spec)`]
282
+ : []),
283
+ ];
284
+ const tools = Object.keys(summary.toolBreakdown).sort();
285
+ if (tools.length > 0) {
286
+ lines.push('', 'Per-Tool Breakdown:');
287
+ for (const tool of tools) {
288
+ const t = summary.toolBreakdown[tool];
289
+ lines.push(` - ${tool}: ${t.calls} calls (${t.errors} err), p50/p95 ${t.p50DurationMs}/${t.p95DurationMs}ms, ${(t.totalBytesOut / 1024).toFixed(1)} KB`);
290
+ }
291
+ }
292
+ if (summary.recentErrors.length > 0) {
293
+ lines.push('', 'Recent Errors:');
294
+ for (const err of summary.recentErrors) {
295
+ lines.push(` - [${err.timestamp}] ${err.tool}${err.code ? ` (${err.code})` : ''}: ${err.message}`);
296
+ }
297
+ }
298
+ return lines.join('\n');
299
+ }
@@ -0,0 +1,53 @@
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`/`stats`/`update` |
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, Diagnostics, Inspect & Diff](openapi-query.md) | Tool schemas, `ToolAnnotations`, QuickJS guest isolation, built-in `helpers` (`op`, `example`, `schemaRefs`, `meta`), `openapi_diagnostics`, `openapi_inspect`, 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
+ | Layer | Entry / Module | Responsibility |
23
+ |---|---|---|
24
+ | **Engine (`@dimassetoid/openapi-mcp/engine`)** | [src/engine/index.ts](../../src/engine/index.ts) | Pure OpenAPI parsing & `$ref` expansion (`spec-loader.ts`), lazy pointer expansion & $O(\text{endpoints})$ summary (`lazy-expander.ts`), source mapping (`source-map.ts`), catalog/indexes (`spec-catalog.ts`, `index-builder.ts`, `schema-index.ts`), diagnostics (`spec-diagnostics.ts`), semantic diff (`spec-diff.ts`), example generation (`example-generator.ts`), QuickJS sandbox (`query-sandbox.ts`), and UTF-8 byte budget (`budget.ts`) |
25
+ | **MCP Server** | [src/mcp/server.ts](../../src/mcp/server.ts), [resources.ts](../../src/mcp/resources.ts), [prompts.ts](../../src/mcp/prompts.ts) | `roots/list` auto-binding, `?root=` resource validation, tools (`openapi_query`, `openapi_diff`, `openapi_diagnostics`, `openapi_inspect`), and 4 guided prompts |
26
+ | **CLI & Stdio** | [src/index.ts](../../src/index.ts) | `serve`, `check`, `diff`, `stats`, `update`, `--help`/`--version` on `stderr`, and graceful stdio shutdown |
27
+ | **Agent Skill** | [skills/use-openapi-mcp/SKILL.md](../../skills/use-openapi-mcp/SKILL.md) | Portable routing playbook for AI coding agents |
28
+
29
+ ---
30
+
31
+ ## MCP Primitives Summary
32
+
33
+ | Primitive | Name / URI | Purpose |
34
+ |---|---|---|
35
+ | Resource | `openapi://specs/catalog` | Sorted spec paths relative to workspace root (with `skippedDirs` when unreadable dirs are encountered) |
36
+ | Resource | `openapi://endpoints/index` | Compact endpoint index with `2xx`/`4xx`/`5xx`, `errorBodies`, `security`, `deprecated`, `tags`, and `sourceLocation` (64 KiB soft cap) |
37
+ | Resource | `openapi://schemas/index` | Compact `components.schemas` / `definitions` index with `required`, `properties`, `unusedSchemas`, `sourceLocation`, and `usedBy` (64 KiB soft cap) |
38
+ | 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 |
39
+ | Resource templates | `openapi://endpoints/search{?q,tag,method,pathPrefix,operationId,missingErrorContracts,offset,limit,root,spec_path}`<br>`openapi://endpoints/index{?root,spec_path}`<br>`openapi://schemas/search{?q,usedByPath,unusedOnly,offset,limit,root,spec_path}`<br>`openapi://schemas/index{?root,spec_path}`<br>`openapi://spec/diagnostics{?root,spec_path}`<br>`openapi://specs/catalog{?root}` | Filtered pagination, per-request `root` override, and monorepo `spec_path` selection |
40
+ | Tool | `openapi_query` | Read-only QuickJS query against frozen `spec` and `helpers` (`op`, `example`, `schemaRefs`, `meta`) |
41
+ | Tool | `openapi_diff` | Read-only semantic breaking vs non-breaking diff between `base_spec_path` and `target_spec_path` with graceful compaction |
42
+ | Tool | `openapi_diagnostics` | Non-throwing multi-issue contract & `$ref` diagnostics with explicit `root` and `spec_path` |
43
+ | Tool | `openapi_inspect` | Tool counterpart for `catalog`, `endpoints` ($O(\text{endpoints})$ lazy load), and `schemas` indexes plus single-`pointer` lazy `$ref` expansion with `root`, `spec_path`, filters, and pagination |
44
+ | Prompts | `sync-frontend-api`, `audit-error-contracts`, `review-breaking-changes`, `generate-test-fixtures` | Guided agent workflows verified by anti-prompt-drift tests |
45
+
46
+ ---
47
+
48
+ ## Verification Scope
49
+
50
+ - 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.
51
+ - Protocol & CLI contract tests in [tests/mcp-contract.test.ts](../../tests/mcp-contract.test.ts) cover monorepo selection, `?root=` overrides, `roots/list` negotiation, 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` + `openapi_diagnostics` + `openapi_inspect` over `InMemoryTransport`, and CLI (`serve`, `check`, `diff`, `--help`, `--version`, `stdio` lifecycle).
52
+ - Self-update tests in [tests/self-update.test.ts](../../tests/self-update.test.ts) cover install channel detection (`standalone`, `bun-global`, `npm-global`), release asset/checksum parsing, and verified binary replacement.
53
+ - Telemetry tests in [tests/telemetry.test.ts](../../tests/telemetry.test.ts) cover tool-call observability logging, `source_bytes`/context-savings calculation, and `openapi-mcp stats --json`.
@@ -0,0 +1,167 @@
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.2.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 (4 Supported Harnesses)
43
+
44
+ Only **Antigravity**, **Claude Code**, **Codex**, and **OpenCode** are supported:
45
+
46
+ **Antigravity** (`~/.gemini/config/mcp_config.json` / `~/.gemini/antigravity/mcp_config.json` / `~/.gemini/antigravity-cli/mcp_config.json`) & **Claude Code** (`.mcp.json`):
47
+
48
+ ```json
49
+ {
50
+ "mcpServers": {
51
+ "openapi-mcp": {
52
+ "command": "openapi-mcp",
53
+ "args": ["serve"]
54
+ }
55
+ }
56
+ }
57
+ ```
58
+
59
+ **Codex** (`.codex/config.toml`):
60
+
61
+ ```toml
62
+ [mcp_servers.openapi-mcp]
63
+ command = "openapi-mcp"
64
+ args = ["serve"]
65
+ ```
66
+
67
+ **OpenCode** (`opencode.json`):
68
+
69
+ ```json
70
+ {
71
+ "mcp": {
72
+ "openapi-mcp": {
73
+ "type": "local",
74
+ "command": ["openapi-mcp", "serve"]
75
+ }
76
+ }
77
+ }
78
+ ```
79
+
80
+ Or run directly from source with Bun:
81
+
82
+ ```json
83
+ {
84
+ "mcpServers": {
85
+ "openapi-mcp": {
86
+ "command": "bun",
87
+ "args": ["run", "/path/to/openapi-mcp/src/index.ts", "serve"]
88
+ }
89
+ }
90
+ }
91
+ ```
92
+
93
+ To pin a workspace boundary and default spec file:
94
+
95
+ ```sh
96
+ openapi-mcp serve --root /path/to/repo --spec api/openapi.yml
97
+ ```
98
+
99
+ When `--root` is not pinned and the MCP client advertises the `roots` capability (`roots/list` and `notifications/roots/list_changed`), `openapi-mcp` automatically binds its default workspace root to the client's first local `file://` root.
100
+
101
+ Verify the binary and run a quick contract check against a local workspace:
102
+
103
+ ```sh
104
+ openapi-mcp --version
105
+ openapi-mcp check --root /path/to/repo
106
+ ```
107
+
108
+ ## Working with Multiple Specs (Monorepos)
109
+
110
+ Start the server with `--root /path/to/repo` (or pass `root` per request). Read `openapi://specs/catalog` (or call `openapi_inspect({ target: "catalog", root })`) to discover conventional spec paths across projects, then pass `root` and `spec_path` per request:
111
+
112
+ - **Endpoint index:** `openapi://endpoints/index?spec_path=apps/billing/openapi.yaml` (or `openapi_inspect({ target: "endpoints", spec_path: "apps/billing/openapi.yaml" })`)
113
+ - **Endpoint search:** `openapi://endpoints/search?spec_path=apps/billing/openapi.yaml&q=invoice`
114
+ - **Diagnostics:** `openapi://spec/diagnostics?spec_path=apps/billing/openapi.yaml` (or `openapi_diagnostics({ spec_path: "apps/billing/openapi.yaml" })`)
115
+ - **Query:** `openapi_query({ spec_path: "apps/billing/openapi.yaml", code: "spec.info.title" })`
116
+
117
+ 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.
118
+
119
+ 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.
120
+
121
+ ---
122
+
123
+ ## CLI Reference
124
+
125
+ ```text
126
+ openapi-mcp <command> [options]
127
+ ```
128
+
129
+ | Command | Description |
130
+ | --- | --- |
131
+ | `openapi-mcp serve [--root <dir>] [--spec <path>]` | Start the MCP server over `stdio` |
132
+ | `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`) |
133
+ | `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`) |
134
+ | `openapi-mcp stats [--root <dir>] [--days <N>] [--json]` | Summarize persisted MCP telemetry and context savings from `.openapi-mcp/` or `OPENAPI_MCP_LOG_PATH` |
135
+ | `openapi-mcp update [version] [--check] [--json]` | Self-update `openapi-mcp` (`standalone` binary, `bun-global`, or `npm-global`) or check release availability |
136
+ | `openapi-mcp` (piped stdin) | Auto-start the MCP server over `stdio` |
137
+ | `openapi-mcp -h \| --help` | Show help message (written to `stderr`) |
138
+ | `openapi-mcp -v \| --version` | Show version number (written to `stderr`) |
139
+
140
+ Startup/shutdown logs, `--help`, and `--version` are written to `stderr`, keeping `stdout` clean for MCP JSON-RPC frames (`serve`) and command outputs/JSON reports (`check`, `diff`, `stats`, `update`).
141
+
142
+ ---
143
+
144
+ ## Agent Skill
145
+
146
+ 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`.
147
+
148
+ ## Inspecting an API Workflow
149
+
150
+ 1. **Select a spec:** In a monorepo, read `openapi://specs/catalog` (optionally `?root=...`) or call `openapi_inspect({ target: "catalog", root })` and pass the chosen `spec_path` to subsequent calls.
151
+ 2. **Locate an operation:** Read `openapi://endpoints/index`, query `openapi://endpoints/search?q=orders&limit=20`, or call `openapi_inspect({ target: "endpoints", q: "orders", limit: 20 })`.
152
+ 3. **Inspect the contract:** Expand a single subtree lazily via `openapi_inspect({ pointer: "/paths/~1orders/post" })` or call `openapi_query` with `helpers.op('POST', '/orders')` / `helpers.example('POST', '/orders', '422')` to inspect merged parameters, auth, and response schemas.
153
+
154
+ Four built-in MCP prompts (`sync-frontend-api`, `audit-error-contracts`, `review-breaking-changes`, and `generate-test-fixtures`) provide step-by-step agent workflows.
155
+
156
+ ---
157
+
158
+ ## Development & Verification
159
+
160
+ ```sh
161
+ bun install # Install dependencies from bun.lock
162
+ bun run typecheck # Run TypeScript strict type checking (tsc --noEmit)
163
+ bun test # Run engine unit tests and InMemoryTransport MCP contract tests
164
+ bun run build # Emit npm JavaScript and type declarations to dist/
165
+ bun run compile:all # Build standalone binaries into release/
166
+ sh scripts/verify-package.sh # Pack, install, typecheck a TypeScript consumer, and smoke-test stdio
167
+ ```
@@ -0,0 +1,53 @@
1
+ # Indexes, Diagnostics & Workflow Prompts
2
+
3
+ Implemented in [src/engine/spec-catalog.ts](../../src/engine/spec-catalog.ts), [src/engine/index-builder.ts](../../src/engine/index-builder.ts), [src/engine/schema-index.ts](../../src/engine/schema-index.ts), [src/engine/spec-diagnostics.ts](../../src/engine/spec-diagnostics.ts), and [src/mcp/server.ts](../../src/mcp/server.ts).
4
+
5
+ ---
6
+
7
+ ## Workspace Catalog (`openapi://specs/catalog{?root}`, `openapi_inspect`)
8
+
9
+ Reads workspace-relative OpenAPI entry filenames (`openapi.yml`, `openapi.yaml`, `openapi.json`) without parsing file contents. Accepts optional `root` (validated within `--root` when configured).
10
+ - Skips symlinks and common build/vendor/cache directories (`node_modules`, `vendor`, `.git`, `dist`, `build`, `storage`, `.next`, `.nuxt`, `.venv`, `target`, `coverage`, etc.).
11
+ - Gracefully skips unreadable or transient directories (`EACCES`, `EPERM`, `ENOENT`, `ENOTDIR`, `ELOOP`) and reports `skippedDirCount` + up to 25 sample `skippedDirs` instead of failing the whole scan.
12
+
13
+ ---
14
+
15
+ ## Endpoint Index & Search (`openapi://endpoints/index`, `openapi://endpoints/search`)
16
+
17
+ - **Lazy vs. Eager Resolution:** Prefer `openapi_inspect({ target: "endpoints" })` and `openapi_inspect({ pointer: "/paths/~1users/get" })` ([lazy-expander.ts](../../src/engine/lazy-expander.ts)) on large specs for $O(\text{endpoints})$ shallow indexing and on-demand single-subtree `$ref` expansion; `openapi://endpoints/*` resources load and validate the full `$ref`-expanded spec snapshot.
18
+ - **Fields returned:** `title`, `version`, `openapiVersion`, `specPath`, `totalEndpoints`, `tags`, `endpointsWithErrorContracts`, `endpointsMissingErrorContracts`, `lines`, and `endpoints[]` (each with `method`, `path`, `operationId`, `summary`, `tags`, `deprecated`, effective `security`, `statusCodes`, `errorStatusCodes`, `errorBodies`, `sourceLocation`, and `line`).
19
+ - **Context-safe soft cap:** Full `openapi://endpoints/index` enforces a **64 KiB** soft limit and directs agents to `openapi://endpoints/search?limit=20` when exceeded.
20
+ - **Search template:** `openapi://endpoints/search{?q,tag,method,pathPrefix,operationId,missingErrorContracts,offset,limit,root,spec_path}` (also exposed via `openapi_inspect` with `target: "endpoints"`) supports case-insensitive substring matching (`q`), exact `tag`/`method`/`operationId`, `pathPrefix`, boolean `missingErrorContracts`, and `nextUri` pagination (`limit` 1–100, default 20).
21
+
22
+ ---
23
+
24
+ ## Component Schema Index & Search (`openapi://schemas/index`, `openapi://schemas/search`)
25
+
26
+ - Indexes `components.schemas` (OpenAPI 3.x) or `definitions` (Swagger 2.0) with `name`, `type`, `description`, `required`, `properties`, `enumValues`, `sourceLocation`, and reverse references (`usedBy`: e.g. `"POST /orders (requestBody)"`).
27
+ - Also lists `unusedSchemas` and enforces the same **64 KiB** soft cap with redirect to `openapi://schemas/search?limit=20`.
28
+ - **Search template:** `openapi://schemas/search{?q,usedByPath,unusedOnly,offset,limit,root,spec_path}` (also exposed via `openapi_inspect` with `target: "schemas"`).
29
+
30
+ ---
31
+
32
+ ## Multi-Issue Diagnostics (`openapi://spec/diagnostics{?root,spec_path}`, `openapi_diagnostics`)
33
+
34
+ Collects up to 200 parse, `$ref`, and contract issues in a single pass without stopping at the first broken `$ref` (still throws `WORKSPACE_NOT_FOUND`, `PATH_TRAVERSAL_DENIED`, or `SPEC_NOT_FOUND`/`SPEC_FILE_NOT_FOUND` when the workspace root or entry file is missing/invalid; the `openapi://spec/diagnostics` resource maps missing entry specs to `status: "spec_not_found"`):
35
+ - Entry parse or size-limit failures (`SPEC_PARSE_ERROR`)
36
+ - Broken/remote/escaping `$ref`s (`BROKEN_REF`, `REMOTE_REF_DENIED`, `PATH_TRAVERSAL_DENIED`, `REF_PARSE_ERROR`)
37
+ - Missing `openapi`/`swagger` version or `info.title`
38
+ - Duplicate `operationId` (`DUPLICATE_OPERATION_ID`)
39
+ - Path template `{param}` not declared in `in: "path"` parameters (`UNDECLARED_PATH_PARAMETER`, resolving both local `#/...` and external relative `$ref` parameters)
40
+ - Referenced `security` scheme missing from `components.securitySchemes` (`UNKNOWN_SECURITY_SCHEME`)
41
+ - Operations missing `4xx`/`5xx` contracts (`MISSING_ERROR_CONTRACT`) or error responses without schemas (`ERROR_RESPONSE_MISSING_SCHEMA`, resolving both local and external `$ref` response objects)
42
+ - Protected operations (effective `security` non-empty, excluding `security: []`) missing `401`/`403` responses (`AUTH_ENDPOINT_MISSING_401_403`, severity `info`)
43
+
44
+ ---
45
+
46
+ ## Workflow Prompts
47
+
48
+ 1. **`sync-frontend-api`** (`endpoint?`): Read endpoint/schema indexes → inspect merged contract via `helpers.op` → align frontend types, auth, and `4xx`/`5xx` branches.
49
+ 2. **`audit-error-contracts`** (`endpoint?`): Read `openapi://spec/diagnostics` + `openapi://endpoints/index` → inspect `4xx`/`5xx` schemas → report gaps with `sourceLocation`.
50
+ 3. **`review-breaking-changes`** (`base_spec_path?`, `target_spec_path?`): Call `openapi_diff` → inspect impacted endpoints/schemas with `helpers.op` / `helpers.schemaRefs` → summarize migration impact.
51
+ 4. **`generate-test-fixtures`** (`endpoint?`): Read endpoint index → synthesize deterministic `2xx` and `4xx`/`5xx` JSON fixtures via `helpers.example`.
52
+
53
+ All prompt references to tools, parameters, and resource URIs are verified against live server schemas in [tests/mcp-contract.test.ts](../../tests/mcp-contract.test.ts).