@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.
Files changed (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +133 -2
  3. package/dist/engine/budget.d.ts +40 -0
  4. package/dist/engine/budget.js +96 -0
  5. package/dist/engine/example-generator.d.ts +47 -0
  6. package/dist/engine/example-generator.js +283 -0
  7. package/dist/engine/index-builder.d.ts +50 -0
  8. package/dist/engine/index-builder.js +179 -0
  9. package/dist/engine/index.d.ts +10 -0
  10. package/dist/engine/index.js +10 -0
  11. package/dist/engine/json.d.ts +1 -0
  12. package/dist/engine/json.js +3 -0
  13. package/dist/engine/query-sandbox.d.ts +21 -0
  14. package/dist/engine/query-sandbox.js +343 -0
  15. package/dist/engine/schema-index.d.ts +42 -0
  16. package/dist/engine/schema-index.js +151 -0
  17. package/dist/engine/source-map.d.ts +15 -0
  18. package/dist/engine/source-map.js +50 -0
  19. package/dist/engine/spec-catalog.d.ts +14 -0
  20. package/dist/engine/spec-catalog.js +99 -0
  21. package/dist/engine/spec-diagnostics.d.ts +28 -0
  22. package/dist/engine/spec-diagnostics.js +352 -0
  23. package/dist/engine/spec-diff.d.ts +31 -0
  24. package/dist/engine/spec-diff.js +408 -0
  25. package/dist/engine/spec-loader.d.ts +59 -0
  26. package/dist/engine/spec-loader.js +484 -0
  27. package/dist/index.d.ts +37 -0
  28. package/dist/index.js +293 -0
  29. package/dist/mcp/prompts.d.ts +51 -0
  30. package/dist/mcp/prompts.js +161 -0
  31. package/dist/mcp/resources.d.ts +30 -0
  32. package/dist/mcp/resources.js +187 -0
  33. package/dist/mcp/server.d.ts +43 -0
  34. package/dist/mcp/server.js +201 -0
  35. package/docs/feature/README.md +65 -0
  36. package/docs/feature/getting-started.md +131 -0
  37. package/docs/feature/index-and-prompts.md +50 -0
  38. package/docs/feature/openapi-query.md +48 -0
  39. package/docs/feature/spec-loader.md +33 -0
  40. package/package.json +77 -4
  41. package/skills/use-openapi-mcp/SKILL.md +42 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 dimassetoid
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,134 @@
1
- # Temporary Holding Version
1
+ # openapi-mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > **Local Code Mode OpenAPI server, CLI, and contract engine for AI coding agents and CI.**
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@dimassetoid/openapi-mcp)](https://www.npmjs.com/package/@dimassetoid/openapi-mcp)
6
+ [![Runtime: Bun](https://img.shields.io/badge/Runtime-Bun-black?logo=bun)](https://bun.sh)
7
+ [![Protocol: Model Context Protocol](https://img.shields.io/badge/Protocol-MCP-green)](https://modelcontextprotocol.io/)
8
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue)](LICENSE)
9
+
10
+ `openapi-mcp` is a local Model Context Protocol (MCP) server, CLI, and reusable TypeScript engine for OpenAPI 3.0/3.1 and Swagger 2.0 specifications. It lets AI coding agents and CI pipelines inspect endpoints, schemas, and contract diffs without loading entire specification files into context.
11
+
12
+ ## Key Capabilities
13
+
14
+ - **Monorepo Spec Discovery (`openapi://specs/catalog`)** — Scans workspaces for OpenAPI entry files while skipping symlinks, unreadable directories (`EACCES`/`EPERM`), and build or dependency folders (`node_modules`, `vendor`, `dist`, `.git`, etc.).
15
+ - **Indexed Endpoints & Paginated Search (`openapi://endpoints/index`, `openapi://endpoints/search`)** — Summarizes HTTP methods, paths, `2xx`/`4xx`/`5xx` status codes, error bodies, auth schemes, deprecation flags, and `{ file, line }` source locations, soft-capped at `64 KB`.
16
+ - **Schema Index & Reverse References (`openapi://schemas/index`, `openapi://schemas/search`)** — Lists `components.schemas` / `definitions` with required fields, properties, `unusedSchemas`, source locations, and reverse `usedBy` operation references.
17
+ - **Single-Pass Contract Diagnostics (`openapi://spec/diagnostics`, `openapi-mcp check`)** — Reports broken `$ref`s, duplicate `operationId`s, undeclared path parameters, unknown security schemes, and missing error contracts in one pass.
18
+ - **Sandboxed Query Engine (`openapi_query`)** — Runs read-only JavaScript in QuickJS WASM against frozen `spec` and built-in `helpers` (`helpers.op`, `helpers.example`, `helpers.schemaRefs`).
19
+ - **Semantic Contract Diff (`openapi_diff`, `openapi-mcp diff`)** — Compares two local specifications and classifies changes into `breaking` and `nonBreaking`.
20
+ - **MCP Prompts & Agent Skill** — Ships four guided prompts (`sync-frontend-api`, `audit-error-contracts`, `review-breaking-changes`, `generate-test-fixtures`) and a portable Agent Skill at [skills/use-openapi-mcp/SKILL.md](skills/use-openapi-mcp/SKILL.md).
21
+
22
+ ## Installation
23
+
24
+ ### Standalone Binary (Recommended)
25
+
26
+ Install precompiled single-file binaries for Linux, macOS, or Windows with SHA-256 verification (no Node.js or Bun required):
27
+
28
+ **Linux & macOS:**
29
+
30
+ ```sh
31
+ curl -fsSL https://raw.githubusercontent.com/Shironim/openapi-mcp/master/scripts/install.sh | sh
32
+ ```
33
+
34
+ **Windows (PowerShell):**
35
+
36
+ ```powershell
37
+ irm https://raw.githubusercontent.com/Shironim/openapi-mcp/master/scripts/install.ps1 | iex
38
+ ```
39
+
40
+ You can also download archives directly from [GitHub Releases](https://github.com/Shironim/openapi-mcp/releases) (`openapi-mcp-linux-x64`, `openapi-mcp-linux-arm64`, `openapi-mcp-darwin-x64`, `openapi-mcp-darwin-arm64`, `openapi-mcp-windows-x64.exe`, and `checksums.txt`).
41
+
42
+ ### Via npm or Bun
43
+
44
+ Requires Node.js `>=18.20.0` or Bun `>=1.4.3`:
45
+
46
+ ```sh
47
+ npm install -g @dimassetoid/openapi-mcp
48
+ # or
49
+ bun add -g @dimassetoid/openapi-mcp
50
+ ```
51
+
52
+ Or run without global installation:
53
+
54
+ ```sh
55
+ npx @dimassetoid/openapi-mcp serve
56
+ # or
57
+ bunx @dimassetoid/openapi-mcp serve
58
+ ```
59
+
60
+ ## Quick Start
61
+
62
+ ### MCP Client Setup
63
+
64
+ Add `openapi-mcp` to your MCP client configuration (for example `.mcp.json`):
65
+
66
+ ```json
67
+ {
68
+ "mcpServers": {
69
+ "openapi-mcp": {
70
+ "command": "openapi-mcp",
71
+ "args": ["serve", "--root", "/path/to/repo"]
72
+ }
73
+ }
74
+ }
75
+ ```
76
+
77
+ Once connected, ask your agent:
78
+
79
+ > Which endpoint creates an order, what does its `422` validation schema look like, and what is a valid example payload?
80
+
81
+ ### CI & Local CLI
82
+
83
+ Run contract diagnostics or breaking-change checks directly in your terminal or CI pipeline:
84
+
85
+ ```sh
86
+ openapi-mcp check --root . --spec openapi.yml --strict
87
+ openapi-mcp diff openapi.yml openapi-v2.yml --fail-on-breaking
88
+ ```
89
+
90
+ ## CLI Reference
91
+
92
+ ```text
93
+ openapi-mcp <command> [options]
94
+ ```
95
+
96
+ | Command | Description |
97
+ | --- | --- |
98
+ | `serve` | Start the MCP server over `stdio` (also starts automatically when stdin is piped) |
99
+ | `check` | Validate an OpenAPI spec and report contract issues |
100
+ | `diff <base> <target>` | Compare two local OpenAPI specs for breaking changes |
101
+
102
+ | Option | Description |
103
+ | --- | --- |
104
+ | `--root <dir>` | Workspace root directory (defaults to current directory) |
105
+ | `--spec <path>` | Path to OpenAPI spec file (`serve`, `check`) |
106
+ | `--strict` | Exit with code `1` if warnings are found (`check`) |
107
+ | `--fail-on-breaking` | Exit with code `1` if breaking changes are found (`diff`) |
108
+ | `--json` | Output results as JSON (`check`, `diff`) |
109
+ | `-h, --help` | Show help message (written to `stderr`) |
110
+ | `-v, --version` | Show version number (written to `stderr`) |
111
+
112
+ ## Documentation
113
+
114
+ - [Feature Overview & Architecture](docs/feature/README.md)
115
+ - [Getting Started, MCP Setup & CLI Reference](docs/feature/getting-started.md)
116
+ - [Specification Loader, `$ref` Resolution & Source Mapping](docs/feature/spec-loader.md)
117
+ - [Indexes, Diagnostics & Workflow Prompts](docs/feature/index-and-prompts.md)
118
+ - [Code Mode Query (`openapi_query`) & Semantic Diff (`openapi_diff`)](docs/feature/openapi-query.md)
119
+ - [Agent Skill Playbook (`use-openapi-mcp`)](skills/use-openapi-mcp/SKILL.md)
120
+
121
+ ## Development
122
+
123
+ ```sh
124
+ bun install
125
+ bun run typecheck
126
+ bun test
127
+ bun run build
128
+ bun run compile:all # Build standalone binaries into release/
129
+ sh scripts/verify-package.sh # Verify npm tarball, TypeScript consumer, and stdio smoke test
130
+ ```
131
+
132
+ ## License
133
+
134
+ [MIT](LICENSE)
@@ -0,0 +1,40 @@
1
+ export declare const DEFAULT_MAX_BYTES: number;
2
+ export declare const MAX_RESULT_BYTES: number;
3
+ export interface BudgetOkResult {
4
+ ok: true;
5
+ truncated: false;
6
+ byteLength: number;
7
+ maxBytes: number;
8
+ text: string;
9
+ data: unknown;
10
+ }
11
+ export interface BudgetExceededPayload {
12
+ error: 'RESPONSE_BUDGET_EXCEEDED';
13
+ truncated: true;
14
+ byteLength: number;
15
+ maxBytes: number;
16
+ summary: {
17
+ resultType: 'array' | 'object' | 'string' | 'primitive';
18
+ itemCount?: number;
19
+ availableKeys?: string[];
20
+ totalKeys?: number;
21
+ preview: string;
22
+ };
23
+ hint: string;
24
+ examples: string[];
25
+ }
26
+ export interface BudgetExceededResult {
27
+ ok: false;
28
+ truncated: true;
29
+ byteLength: number;
30
+ maxBytes: number;
31
+ text: string;
32
+ errorPayload: BudgetExceededPayload;
33
+ }
34
+ export type BudgetCheckResult = BudgetOkResult | BudgetExceededResult;
35
+ /**
36
+ * Enforces a strict UTF-8 byte budget on serialized query results.
37
+ * When exceeded, returns a compact diagnostic payload with available keys and actionable narrowing hints.
38
+ */
39
+ export declare function enforceByteBudget(data: unknown, maxBytes?: number): BudgetCheckResult;
40
+ export declare function enforceSerializedByteBudget(normalized: unknown, jsonText: string, maxBytes?: number): BudgetCheckResult;
@@ -0,0 +1,96 @@
1
+ import { isRecord } from './json.js';
2
+ export const DEFAULT_MAX_BYTES = 16 * 1024;
3
+ export const MAX_RESULT_BYTES = 1024 * 1024;
4
+ function buildPreviewSnippet(text, maxChars) {
5
+ if (text.length <= maxChars)
6
+ return text;
7
+ const lines = text.slice(0, maxChars).split('\n');
8
+ if (lines.length > 1) {
9
+ lines.pop();
10
+ return `${lines.join('\n')}\n... [truncated preview]`;
11
+ }
12
+ return `${text.slice(0, maxChars)}... [truncated]`;
13
+ }
14
+ /**
15
+ * Enforces a strict UTF-8 byte budget on serialized query results.
16
+ * When exceeded, returns a compact diagnostic payload with available keys and actionable narrowing hints.
17
+ */
18
+ export function enforceByteBudget(data, maxBytes = DEFAULT_MAX_BYTES) {
19
+ const normalized = data === undefined ? null : data;
20
+ return enforceSerializedByteBudget(normalized, JSON.stringify(normalized, null, 2) ?? 'null', maxBytes);
21
+ }
22
+ export function enforceSerializedByteBudget(normalized, jsonText, maxBytes = DEFAULT_MAX_BYTES) {
23
+ const effectiveMaxBytes = typeof maxBytes === 'number' && Number.isFinite(maxBytes) && maxBytes > 0
24
+ ? Math.min(MAX_RESULT_BYTES, Math.max(1, Math.floor(maxBytes)))
25
+ : DEFAULT_MAX_BYTES;
26
+ const byteLength = Buffer.byteLength(jsonText, 'utf8');
27
+ if (byteLength <= effectiveMaxBytes) {
28
+ return {
29
+ ok: true,
30
+ truncated: false,
31
+ byteLength,
32
+ maxBytes: effectiveMaxBytes,
33
+ text: jsonText,
34
+ data: normalized,
35
+ };
36
+ }
37
+ let summary;
38
+ const previewCap = Math.min(600, Math.max(120, Math.floor(effectiveMaxBytes / 4)));
39
+ if (Array.isArray(normalized)) {
40
+ const firstObjKeys = isRecord(normalized[0])
41
+ ? Object.keys(normalized[0]).slice(0, 20).map((key) => key.slice(0, 80))
42
+ : undefined;
43
+ summary = {
44
+ resultType: 'array',
45
+ itemCount: normalized.length,
46
+ ...(firstObjKeys ? { availableKeys: firstObjKeys } : {}),
47
+ preview: buildPreviewSnippet(jsonText, previewCap),
48
+ };
49
+ }
50
+ else if (isRecord(normalized)) {
51
+ const keys = Object.keys(normalized);
52
+ summary = {
53
+ resultType: 'object',
54
+ totalKeys: keys.length,
55
+ availableKeys: keys.slice(0, 30).map((key) => key.slice(0, 80)),
56
+ preview: buildPreviewSnippet(jsonText, previewCap),
57
+ };
58
+ }
59
+ else if (typeof normalized === 'string') {
60
+ summary = {
61
+ resultType: 'string',
62
+ preview: buildPreviewSnippet(normalized, previewCap),
63
+ };
64
+ }
65
+ else {
66
+ summary = {
67
+ resultType: 'primitive',
68
+ preview: buildPreviewSnippet(jsonText, previewCap),
69
+ };
70
+ }
71
+ const keySuggestion = summary.availableKeys && summary.availableKeys.length > 0
72
+ ? ` Available keys include: ${summary.availableKeys.slice(0, 8).join(', ')}.`
73
+ : '';
74
+ const errorPayload = {
75
+ error: 'RESPONSE_BUDGET_EXCEEDED',
76
+ truncated: true,
77
+ byteLength,
78
+ maxBytes: effectiveMaxBytes,
79
+ summary,
80
+ hint: `Query output (${byteLength} bytes) exceeds the ${effectiveMaxBytes}-byte response budget.${keySuggestion} ` +
81
+ `Narrow your openapi_query to a specific path, HTTP method, response status code, or schema—or pass a larger max_bytes.`,
82
+ examples: [
83
+ "Object.keys(spec.paths ?? {})",
84
+ "spec.paths['/users']?.get?.responses",
85
+ "Object.keys(spec.components?.schemas ?? {})",
86
+ ],
87
+ };
88
+ return {
89
+ ok: false,
90
+ truncated: true,
91
+ byteLength,
92
+ maxBytes: effectiveMaxBytes,
93
+ text: JSON.stringify(errorPayload, null, 2),
94
+ errorPayload,
95
+ };
96
+ }
@@ -0,0 +1,47 @@
1
+ import { type SourceLocation } from './source-map.js';
2
+ export interface ExampleGeneratorOptions {
3
+ maxDepth?: number;
4
+ maxNodes?: number;
5
+ includeReadOnly?: boolean;
6
+ includeWriteOnly?: boolean;
7
+ }
8
+ /**
9
+ * Deterministically synthesizes a valid sample JSON value from a resolved OpenAPI 3.0/3.1 schema.
10
+ * Safe against circular markers (`[Circular: ...]`) and bounded by depth and node count.
11
+ */
12
+ export declare function generateSchemaExample(schema: unknown, options?: ExampleGeneratorOptions): unknown;
13
+ export interface MergedOperationContract {
14
+ method: string;
15
+ path: string;
16
+ operationId?: string;
17
+ summary?: string;
18
+ description?: string;
19
+ tags?: string[];
20
+ deprecated?: boolean;
21
+ security?: unknown[];
22
+ parameters: unknown[];
23
+ requestBody?: unknown;
24
+ responses?: unknown;
25
+ sourceLocation?: SourceLocation;
26
+ }
27
+ /**
28
+ * Returns a single operation's complete contract with path-level + operation-level `parameters`
29
+ * merged (operation overrides path on matching `name`+`in`), effective `security`, and `sourceLocation`.
30
+ */
31
+ export declare function getMergedOperation(spec: Record<string, unknown>, method: string, path: string, sourceLocations?: Readonly<Record<string, SourceLocation>>): MergedOperationContract | null;
32
+ /**
33
+ * Generates deterministic request and response sample payloads for a given `method` + `path`
34
+ * (optionally filtered to a single response `statusCode`).
35
+ */
36
+ export declare function generateOperationExamples(spec: Record<string, unknown>, method: string, path: string, statusCode?: string): {
37
+ method: string;
38
+ path: string;
39
+ requestBody?: {
40
+ mediaType: string;
41
+ example: unknown;
42
+ };
43
+ responses: Record<string, {
44
+ mediaType?: string;
45
+ example: unknown;
46
+ }>;
47
+ } | null;
@@ -0,0 +1,283 @@
1
+ import { isRecord } from './json.js';
2
+ import { escapeJsonPointer } from './source-map.js';
3
+ const DEFAULT_MAX_DEPTH = 8;
4
+ const DEFAULT_MAX_NODES = 256;
5
+ function pickPrimaryType(typeField) {
6
+ if (typeof typeField === 'string')
7
+ return typeField;
8
+ if (Array.isArray(typeField)) {
9
+ const nonNull = typeField.find((t) => typeof t === 'string' && t !== 'null');
10
+ if (typeof nonNull === 'string')
11
+ return nonNull;
12
+ const first = typeField.find((t) => typeof t === 'string');
13
+ if (typeof first === 'string')
14
+ return first;
15
+ }
16
+ return undefined;
17
+ }
18
+ function synthesizeString(schema) {
19
+ const format = typeof schema.format === 'string' ? schema.format.toLowerCase() : '';
20
+ switch (format) {
21
+ case 'uuid':
22
+ return '00000000-0000-4000-8000-000000000000';
23
+ case 'email':
24
+ case 'idn-email':
25
+ return 'user@example.com';
26
+ case 'date-time':
27
+ return '2026-01-01T00:00:00Z';
28
+ case 'date':
29
+ return '2026-01-01';
30
+ case 'time':
31
+ return '00:00:00Z';
32
+ case 'uri':
33
+ case 'url':
34
+ case 'iri':
35
+ return 'https://example.com/resource';
36
+ case 'ipv4':
37
+ return '192.0.2.1';
38
+ case 'ipv6':
39
+ return '2001:db8::1';
40
+ case 'hostname':
41
+ case 'idn-hostname':
42
+ return 'example.com';
43
+ case 'byte':
44
+ return 'ZXhhbXBsZQ==';
45
+ default: {
46
+ const minLen = typeof schema.minLength === 'number' && schema.minLength > 0 ? Math.min(64, Math.floor(schema.minLength)) : 0;
47
+ const base = 'string';
48
+ return minLen > base.length ? base.padEnd(minLen, 'x') : base;
49
+ }
50
+ }
51
+ }
52
+ function synthesizeNumber(schema, integer) {
53
+ const min = typeof schema.minimum === 'number' ? schema.minimum : undefined;
54
+ const exMin = typeof schema.exclusiveMinimum === 'number' ? schema.exclusiveMinimum : undefined;
55
+ const max = typeof schema.maximum === 'number' ? schema.maximum : undefined;
56
+ let value = integer ? 1 : 0;
57
+ if (exMin !== undefined) {
58
+ value = integer ? Math.floor(exMin) + 1 : exMin + 0.5;
59
+ }
60
+ else if (min !== undefined && value < min) {
61
+ value = integer ? Math.ceil(min) : min;
62
+ }
63
+ if (max !== undefined && value > max) {
64
+ value = integer ? Math.floor(max) : max;
65
+ }
66
+ return value;
67
+ }
68
+ /**
69
+ * Deterministically synthesizes a valid sample JSON value from a resolved OpenAPI 3.0/3.1 schema.
70
+ * Safe against circular markers (`[Circular: ...]`) and bounded by depth and node count.
71
+ */
72
+ export function generateSchemaExample(schema, options = {}) {
73
+ const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH;
74
+ const maxNodes = options.maxNodes ?? DEFAULT_MAX_NODES;
75
+ const includeReadOnly = options.includeReadOnly ?? true;
76
+ const includeWriteOnly = options.includeWriteOnly ?? true;
77
+ let nodes = 0;
78
+ function visit(node, depth) {
79
+ if (++nodes > maxNodes || depth > maxDepth)
80
+ return null;
81
+ if (typeof node === 'string' && node.startsWith('[Circular:'))
82
+ return null;
83
+ if (typeof node === 'boolean')
84
+ return node ? {} : null;
85
+ if (!isRecord(node))
86
+ return null;
87
+ if (node.example !== undefined)
88
+ return node.example;
89
+ if (Array.isArray(node.examples) && node.examples.length > 0)
90
+ return node.examples[0];
91
+ if (node.const !== undefined)
92
+ return node.const;
93
+ if (node.default !== undefined)
94
+ return node.default;
95
+ if (Array.isArray(node.enum) && node.enum.length > 0)
96
+ return node.enum[0];
97
+ if (Array.isArray(node.allOf) && node.allOf.length > 0) {
98
+ const merged = {};
99
+ let anyObject = false;
100
+ for (const branch of node.allOf) {
101
+ const sample = visit(branch, depth + 1);
102
+ if (isRecord(sample)) {
103
+ Object.assign(merged, sample);
104
+ anyObject = true;
105
+ }
106
+ }
107
+ if (anyObject)
108
+ return merged;
109
+ return visit(node.allOf[0], depth + 1);
110
+ }
111
+ const unionBranches = Array.isArray(node.oneOf)
112
+ ? node.oneOf
113
+ : Array.isArray(node.anyOf)
114
+ ? node.anyOf
115
+ : undefined;
116
+ if (unionBranches && unionBranches.length > 0) {
117
+ const nonNull = unionBranches.find((b) => isRecord(b) && b.type !== 'null') ?? unionBranches[0];
118
+ return visit(nonNull, depth + 1);
119
+ }
120
+ const primaryType = pickPrimaryType(node.type) ?? (isRecord(node.properties) ? 'object' : node.items !== undefined ? 'array' : undefined);
121
+ switch (primaryType) {
122
+ case 'object': {
123
+ const out = {};
124
+ if (isRecord(node.properties)) {
125
+ for (const [key, propSchema] of Object.entries(node.properties)) {
126
+ if (isRecord(propSchema)) {
127
+ if (!includeReadOnly && propSchema.readOnly === true)
128
+ continue;
129
+ if (!includeWriteOnly && propSchema.writeOnly === true)
130
+ continue;
131
+ }
132
+ out[key] = visit(propSchema, depth + 1);
133
+ }
134
+ }
135
+ return out;
136
+ }
137
+ case 'array': {
138
+ if (Array.isArray(node.prefixItems) && node.prefixItems.length > 0) {
139
+ return node.prefixItems.map((item) => visit(item, depth + 1));
140
+ }
141
+ if (node.items === undefined)
142
+ return [];
143
+ const minItems = typeof node.minItems === 'number' && node.minItems > 0 ? Math.min(2, Math.floor(node.minItems)) : 1;
144
+ const arr = [];
145
+ for (let i = 0; i < minItems; i++) {
146
+ arr.push(visit(node.items, depth + 1));
147
+ }
148
+ return arr;
149
+ }
150
+ case 'string':
151
+ return synthesizeString(node);
152
+ case 'integer':
153
+ return synthesizeNumber(node, true);
154
+ case 'number':
155
+ return synthesizeNumber(node, false);
156
+ case 'boolean':
157
+ return true;
158
+ case 'null':
159
+ return null;
160
+ default:
161
+ return null;
162
+ }
163
+ }
164
+ return visit(schema, 0);
165
+ }
166
+ /**
167
+ * Returns a single operation's complete contract with path-level + operation-level `parameters`
168
+ * merged (operation overrides path on matching `name`+`in`), effective `security`, and `sourceLocation`.
169
+ */
170
+ export function getMergedOperation(spec, method, path, sourceLocations) {
171
+ const paths = isRecord(spec.paths) ? spec.paths : undefined;
172
+ const pathItem = paths && isRecord(paths[path]) ? paths[path] : undefined;
173
+ const lowerMethod = method.trim().toLowerCase();
174
+ const operation = pathItem && isRecord(pathItem[lowerMethod]) ? pathItem[lowerMethod] : undefined;
175
+ if (!pathItem || !operation)
176
+ return null;
177
+ const mergedParams = new Map();
178
+ const addParams = (list) => {
179
+ if (!Array.isArray(list))
180
+ return;
181
+ for (const param of list) {
182
+ if (isRecord(param) && typeof param.name === 'string' && typeof param.in === 'string') {
183
+ mergedParams.set(`${param.in}:${param.name}`, param);
184
+ }
185
+ }
186
+ };
187
+ addParams(pathItem.parameters);
188
+ addParams(operation.parameters);
189
+ const effectiveSecurity = Array.isArray(operation.security)
190
+ ? operation.security
191
+ : Array.isArray(spec.security)
192
+ ? spec.security
193
+ : undefined;
194
+ const sourceLocation = sourceLocations?.[`/paths/${escapeJsonPointer(path)}/${lowerMethod}`];
195
+ return {
196
+ method: lowerMethod.toUpperCase(),
197
+ path,
198
+ ...(typeof operation.operationId === 'string' ? { operationId: operation.operationId } : {}),
199
+ ...(typeof operation.summary === 'string' ? { summary: operation.summary } : {}),
200
+ ...(typeof operation.description === 'string' ? { description: operation.description } : {}),
201
+ ...(Array.isArray(operation.tags) ? { tags: operation.tags.filter((t) => typeof t === 'string') } : {}),
202
+ ...(operation.deprecated === true ? { deprecated: true } : {}),
203
+ ...(effectiveSecurity !== undefined ? { security: effectiveSecurity } : {}),
204
+ parameters: [...mergedParams.values()],
205
+ ...(operation.requestBody !== undefined ? { requestBody: operation.requestBody } : {}),
206
+ ...(operation.responses !== undefined ? { responses: operation.responses } : {}),
207
+ ...(sourceLocation ? { sourceLocation } : {}),
208
+ };
209
+ }
210
+ function pickMediaContent(content) {
211
+ if (isRecord(content['application/json'])) {
212
+ return { mediaType: 'application/json', media: content['application/json'] };
213
+ }
214
+ const jsonLike = Object.keys(content).find((k) => k.includes('json') && isRecord(content[k]));
215
+ if (jsonLike)
216
+ return { mediaType: jsonLike, media: content[jsonLike] };
217
+ const firstKey = Object.keys(content).find((k) => isRecord(content[k]));
218
+ if (firstKey)
219
+ return { mediaType: firstKey, media: content[firstKey] };
220
+ return undefined;
221
+ }
222
+ function extractMediaExample(media, opts) {
223
+ if (media.example !== undefined)
224
+ return media.example;
225
+ if (isRecord(media.examples)) {
226
+ for (const ex of Object.values(media.examples)) {
227
+ if (isRecord(ex) && ex.value !== undefined)
228
+ return ex.value;
229
+ }
230
+ }
231
+ if (media.schema !== undefined)
232
+ return generateSchemaExample(media.schema, opts);
233
+ return null;
234
+ }
235
+ /**
236
+ * Generates deterministic request and response sample payloads for a given `method` + `path`
237
+ * (optionally filtered to a single response `statusCode`).
238
+ */
239
+ export function generateOperationExamples(spec, method, path, statusCode) {
240
+ const op = getMergedOperation(spec, method, path);
241
+ if (!op)
242
+ return null;
243
+ let requestBody;
244
+ if (isRecord(op.requestBody) && isRecord(op.requestBody.content)) {
245
+ const picked = pickMediaContent(op.requestBody.content);
246
+ if (picked) {
247
+ requestBody = {
248
+ mediaType: picked.mediaType,
249
+ example: extractMediaExample(picked.media, { includeReadOnly: false, includeWriteOnly: true }),
250
+ };
251
+ }
252
+ }
253
+ const responses = {};
254
+ if (isRecord(op.responses)) {
255
+ const codes = statusCode ? [statusCode] : Object.keys(op.responses);
256
+ for (const code of codes) {
257
+ const res = op.responses[code];
258
+ if (!isRecord(res))
259
+ continue;
260
+ if (isRecord(res.content)) {
261
+ const picked = pickMediaContent(res.content);
262
+ if (picked) {
263
+ responses[code] = {
264
+ mediaType: picked.mediaType,
265
+ example: extractMediaExample(picked.media, { includeReadOnly: true, includeWriteOnly: false }),
266
+ };
267
+ continue;
268
+ }
269
+ }
270
+ if (res.schema !== undefined) {
271
+ responses[code] = {
272
+ example: generateSchemaExample(res.schema, { includeReadOnly: true, includeWriteOnly: false }),
273
+ };
274
+ }
275
+ }
276
+ }
277
+ return {
278
+ method: op.method,
279
+ path: op.path,
280
+ ...(requestBody ? { requestBody } : {}),
281
+ responses,
282
+ };
283
+ }
@@ -0,0 +1,50 @@
1
+ import { type SourceLocation } from './source-map.js';
2
+ export declare const HTTP_METHODS: readonly ["get", "post", "put", "patch", "delete", "options", "head", "trace"];
3
+ export interface EndpointSummaryItem {
4
+ method: string;
5
+ path: string;
6
+ operationId?: string;
7
+ summary: string;
8
+ tags?: string[];
9
+ deprecated?: boolean;
10
+ security?: string[];
11
+ statusCodes: string[];
12
+ errorStatusCodes: string[];
13
+ errorBodies: Record<string, {
14
+ schemaMediaTypes: string[];
15
+ hasSwaggerSchema?: boolean;
16
+ }>;
17
+ sourceLocation?: SourceLocation;
18
+ line: string;
19
+ }
20
+ export interface EndpointIndex {
21
+ title: string;
22
+ version: string;
23
+ openapiVersion: string;
24
+ specPath?: string;
25
+ totalEndpoints: number;
26
+ tags: string[];
27
+ endpointsWithErrorContracts: number;
28
+ endpointsMissingErrorContracts: string[];
29
+ lines: string[];
30
+ endpoints: EndpointSummaryItem[];
31
+ }
32
+ export interface EndpointSearchFilters {
33
+ q?: string;
34
+ tag?: string;
35
+ method?: string;
36
+ pathPrefix?: string;
37
+ operationId?: string;
38
+ missingErrorContracts?: boolean;
39
+ offset: number;
40
+ limit: number;
41
+ }
42
+ export declare function searchEndpoints(entries: EndpointSummaryItem[], filters: EndpointSearchFilters): {
43
+ endpoints: EndpointSummaryItem[];
44
+ totalMatches: number;
45
+ };
46
+ /**
47
+ * Builds a compact, token-lean index of all endpoints and their defined HTTP status codes
48
+ * (including all 4xx/5xx error responses) from a resolved OpenAPI specification.
49
+ */
50
+ export declare function buildEndpointIndex(spec: Record<string, unknown>, specPath?: string, sourceLocations?: Readonly<Record<string, SourceLocation>>): EndpointIndex;