@dimassetoid/openapi-mcp 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
+ }
@@ -10,37 +10,21 @@ This directory documents the implemented behavior, MCP contracts, security bound
10
10
 
11
11
  | Document | Contents |
12
12
  |---|---|
13
- | [Installation and setup](getting-started.md) | Install the server, connect an MCP client, configure monorepos, and run CLI `check`/`diff` |
13
+ | [Installation and setup](getting-started.md) | Install the server, connect an MCP client, configure monorepos, and run CLI `check`/`diff`/`stats`/`update` |
14
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 |
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
16
  | [Indexes, Diagnostics & Prompts](index-and-prompts.md) | Resilient workspace catalog, endpoint/schema indexes, paginated search, multi-issue diagnostics, and workflow prompts |
17
17
 
18
18
  ---
19
19
 
20
20
  ## Architecture Overview
21
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
- ```
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 |
44
28
 
45
29
  ---
46
30
 
@@ -49,12 +33,14 @@ skills/
49
33
  | Primitive | Name / URI | Purpose |
50
34
  |---|---|---|
51
35
  | 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) |
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) |
54
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 |
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` |
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 |
58
44
  | Prompts | `sync-frontend-api`, `audit-error-contracts`, `review-breaking-changes`, `generate-test-fixtures` | Guided agent workflows verified by anti-prompt-drift tests |
59
45
 
60
46
  ---
@@ -62,4 +48,6 @@ skills/
62
48
  ## Verification Scope
63
49
 
64
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.
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).
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`.
@@ -19,7 +19,7 @@ irm https://raw.githubusercontent.com/Shironim/openapi-mcp/master/scripts/instal
19
19
  ```
20
20
 
21
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).
22
+ - `OPENAPI_MCP_VERSION` — Install a specific release tag (for example `v0.2.0`; defaults to latest).
23
23
  - `OPENAPI_MCP_INSTALL_DIR` — Override the target installation directory.
24
24
  - `OPENAPI_MCP_REPO` — Override the GitHub repository slug (defaults to `Shironim/openapi-mcp`).
25
25
 
@@ -39,9 +39,11 @@ You can also run without a global install via `npx @dimassetoid/openapi-mcp serv
39
39
 
40
40
  ---
41
41
 
42
- ## MCP Client Configuration
42
+ ## MCP Client Configuration (4 Supported Harnesses)
43
43
 
44
- Add `openapi-mcp` to `.mcp.json` or your MCP client configuration:
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`):
45
47
 
46
48
  ```json
47
49
  {
@@ -54,6 +56,27 @@ Add `openapi-mcp` to `.mcp.json` or your MCP client configuration:
54
56
  }
55
57
  ```
56
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
+
57
80
  Or run directly from source with Bun:
58
81
 
59
82
  ```json
@@ -73,12 +96,22 @@ To pin a workspace boundary and default spec file:
73
96
  openapi-mcp serve --root /path/to/repo --spec api/openapi.yml
74
97
  ```
75
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
+
76
108
  ## Working with Multiple Specs (Monorepos)
77
109
 
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:
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:
79
111
 
80
- - **Endpoint index:** `openapi://endpoints/index?spec_path=apps/billing/openapi.yaml`
112
+ - **Endpoint index:** `openapi://endpoints/index?spec_path=apps/billing/openapi.yaml` (or `openapi_inspect({ target: "endpoints", spec_path: "apps/billing/openapi.yaml" })`)
81
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" })`)
82
115
  - **Query:** `openapi_query({ spec_path: "apps/billing/openapi.yaml", code: "spec.info.title" })`
83
116
 
84
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.
@@ -98,11 +131,13 @@ openapi-mcp <command> [options]
98
131
  | `openapi-mcp serve [--root <dir>] [--spec <path>]` | Start the MCP server over `stdio` |
99
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`) |
100
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 |
101
136
  | `openapi-mcp` (piped stdin) | Auto-start the MCP server over `stdio` |
102
137
  | `openapi-mcp -h \| --help` | Show help message (written to `stderr`) |
103
138
  | `openapi-mcp -v \| --version` | Show version number (written to `stderr`) |
104
139
 
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`).
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`).
106
141
 
107
142
  ---
108
143
 
@@ -112,9 +147,9 @@ Copy [skills/use-openapi-mcp/SKILL.md](../../skills/use-openapi-mcp/SKILL.md) in
112
147
 
113
148
  ## Inspecting an API Workflow
114
149
 
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.
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.
118
153
 
119
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.
120
155
 
@@ -123,8 +158,9 @@ Four built-in MCP prompts (`sync-frontend-api`, `audit-error-contracts`, `review
123
158
  ## Development & Verification
124
159
 
125
160
  ```sh
126
- bun test # Run engine unit tests and InMemoryTransport MCP contract tests
161
+ bun install # Install dependencies from bun.lock
127
162
  bun run typecheck # Run TypeScript strict type checking (tsc --noEmit)
163
+ bun test # Run engine unit tests and InMemoryTransport MCP contract tests
128
164
  bun run build # Emit npm JavaScript and type declarations to dist/
129
165
  bun run compile:all # Build standalone binaries into release/
130
166
  sh scripts/verify-package.sh # Pack, install, typecheck a TypeScript consumer, and smoke-test stdio
@@ -4,9 +4,9 @@ Implemented in [src/engine/spec-catalog.ts](../../src/engine/spec-catalog.ts), [
4
4
 
5
5
  ---
6
6
 
7
- ## Workspace Catalog (`openapi://specs/catalog`)
7
+ ## Workspace Catalog (`openapi://specs/catalog{?root}`, `openapi_inspect`)
8
8
 
9
- Reads workspace-relative OpenAPI entry filenames (`openapi.yml`, `openapi.yaml`, `openapi.json`) without parsing file contents.
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
10
  - Skips symlinks and common build/vendor/cache directories (`node_modules`, `vendor`, `.git`, `dist`, `build`, `storage`, `.next`, `.nuxt`, `.venv`, `target`, `coverage`, etc.).
11
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
12
 
@@ -14,29 +14,32 @@ Reads workspace-relative OpenAPI entry filenames (`openapi.yml`, `openapi.yaml`,
14
14
 
15
15
  ## Endpoint Index & Search (`openapi://endpoints/index`, `openapi://endpoints/search`)
16
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.
17
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`).
18
- - **Context-safe soft cap:** Full `openapi://endpoints/index` enforces a **64 KB** soft limit and directs agents to `openapi://endpoints/search?limit=20` when exceeded.
19
- - **Search template:** `openapi://endpoints/search{?q,tag,method,pathPrefix,operationId,missingErrorContracts,offset,limit,spec_path}` supports case-insensitive substring matching (`q`), exact `tag`/`method`/`operationId`, `pathPrefix`, boolean `missingErrorContracts`, and `nextUri` pagination (`limit` 1–100, default 20).
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).
20
21
 
21
22
  ---
22
23
 
23
24
  ## Component Schema Index & Search (`openapi://schemas/index`, `openapi://schemas/search`)
24
25
 
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)"`).
26
- - Also lists `unusedSchemas` and enforces the same **64 KB** soft cap with redirect to `openapi://schemas/search?limit=20`.
27
- - **Search template:** `openapi://schemas/search{?q,usedByPath,unusedOnly,offset,limit,spec_path}`.
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"`).
28
29
 
29
30
  ---
30
31
 
31
- ## Multi-Issue Diagnostics (`openapi://spec/diagnostics{?spec_path}`)
32
+ ## Multi-Issue Diagnostics (`openapi://spec/diagnostics{?root,spec_path}`, `openapi_diagnostics`)
32
33
 
33
- Runs a non-throwing single-pass check collecting up to 200 issues:
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`)
34
36
  - Broken/remote/escaping `$ref`s (`BROKEN_REF`, `REMOTE_REF_DENIED`, `PATH_TRAVERSAL_DENIED`, `REF_PARSE_ERROR`)
35
37
  - Missing `openapi`/`swagger` version or `info.title`
36
38
  - Duplicate `operationId` (`DUPLICATE_OPERATION_ID`)
37
- - Path template `{param}` not declared in `in: "path"` parameters (`UNDECLARED_PATH_PARAMETER`)
39
+ - Path template `{param}` not declared in `in: "path"` parameters (`UNDECLARED_PATH_PARAMETER`, resolving both local `#/...` and external relative `$ref` parameters)
38
40
  - Referenced `security` scheme missing from `components.securitySchemes` (`UNKNOWN_SECURITY_SCHEME`)
39
- - Operations missing `4xx`/`5xx` contracts (`MISSING_ERROR_CONTRACT`) or error responses without schemas (`ERROR_RESPONSE_MISSING_SCHEMA`)
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`)
40
43
 
41
44
  ---
42
45