@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
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,145 @@
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 & Dynamic Root Discovery (`openapi://specs/catalog`, `openapi_inspect`)** — Scans workspaces for OpenAPI entry files while skipping symlinks, unreadable directories (`EACCES`/`EPERM`), and build or dependency folders (`node_modules`, `vendor`, `dist`, `.git`, etc.). Supports MCP `roots/list` auto-binding (when `--root` is not pinned) plus per-request `?root=`/`root` overrides.
15
+ - **Indexed Endpoints & Lazy Subtree Expansion (`openapi_inspect`, `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 (`openapi_inspect({ target: "endpoints" })` uses $O(\text{endpoints})$ lazy loading via `buildRawEndpointSummary`, while `openapi://endpoints/*` loads the full `$ref`-validated snapshot), plus lazy single-subtree `$ref` expansion via `openapi_inspect({ pointer: "/paths/~1users/get" })`.
16
+ - **Schema Index & Reverse References (`openapi://schemas/index`, `openapi://schemas/search`, `openapi_inspect`)** — 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_diagnostics`, `openapi-mcp check`)** — Reports broken `$ref`s, duplicate `operationId`s, undeclared path parameters (including external `$ref`s), unknown security schemes, missing error contracts, and protected operations missing `401`/`403` responses 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`, `helpers.meta`).
19
+ - **Semantic Contract Diff (`openapi_diff`, `openapi-mcp diff`)** — Compares two local specifications and classifies changes into `breaking` and `nonBreaking`, preserving all `breaking` findings even when `nonBreaking` exceeds the default `16 KiB` budget (via graceful compaction or `include_non_breaking: false`).
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 (4 Supported Harnesses)
63
+
64
+ Only **Antigravity**, **Claude Code**, **Codex**, and **OpenCode** are supported. Omit `--root` to auto-bind via MCP `roots/list` (or pass `root` per call), or pin `--root` to enforce a workspace boundary:
65
+
66
+ **Antigravity** (`~/.gemini/config/mcp_config.json` / `~/.gemini/antigravity/mcp_config.json` / `~/.gemini/antigravity-cli/mcp_config.json`) & **Claude Code** (`.mcp.json`):
67
+
68
+ ```json
69
+ {
70
+ "mcpServers": {
71
+ "openapi-mcp": {
72
+ "command": "openapi-mcp",
73
+ "args": ["serve"]
74
+ }
75
+ }
76
+ }
77
+ ```
78
+
79
+ **Codex** (`.codex/config.toml`):
80
+
81
+ ```toml
82
+ [mcp_servers.openapi-mcp]
83
+ command = "openapi-mcp"
84
+ args = ["serve"]
85
+ ```
86
+
87
+ **OpenCode** (`opencode.json`):
88
+
89
+ ```json
90
+ {
91
+ "mcp": {
92
+ "openapi-mcp": {
93
+ "type": "local",
94
+ "command": ["openapi-mcp", "serve"]
95
+ }
96
+ }
97
+ }
98
+ ```
99
+
100
+ Install the portable Agent Skill into `.agents/skills/use-openapi-mcp/SKILL.md` so all harnesses can discover it globally:
101
+
102
+ ```sh
103
+ mkdir -p .agents/skills/use-openapi-mcp && cp skills/use-openapi-mcp/SKILL.md .agents/skills/use-openapi-mcp/SKILL.md
104
+ ```
105
+
106
+ Verify the installation and ask your agent:
107
+
108
+ ```sh
109
+ openapi-mcp check --root /path/to/repo
110
+ ```
111
+
112
+ > Which endpoint creates an order, what does its `422` validation schema look like, and what is a valid example payload?
113
+
114
+ ### CLI Quick Reference
115
+
116
+ ```sh
117
+ openapi-mcp serve [--root <dir>] [--spec <path>]
118
+ openapi-mcp check --root . --spec openapi.yml --strict
119
+ openapi-mcp diff openapi.yml openapi-v2.yml --fail-on-breaking
120
+ openapi-mcp stats [--root <dir>] [--days <N>] [--json]
121
+ openapi-mcp update [version] [--check] [--json]
122
+ ```
123
+
124
+ See [Getting Started & CLI Reference](docs/feature/getting-started.md#cli-reference) for the full option table (`--json`, `-h`/`--help`, `-v`/`--version`) and monorepo setup.
125
+
126
+ ## Documentation
127
+
128
+ - [Feature Overview & Architecture](docs/feature/README.md)
129
+ - [Getting Started, MCP Setup & CLI Reference](docs/feature/getting-started.md)
130
+ - [Specification Loader, `$ref` Resolution & Source Mapping](docs/feature/spec-loader.md)
131
+ - [Indexes, Diagnostics & Workflow Prompts](docs/feature/index-and-prompts.md)
132
+ - [Code Mode Query (`openapi_query`), Diagnostics, Inspect & Semantic Diff (`openapi_diff`)](docs/feature/openapi-query.md)
133
+ - [Agent Skill Playbook (`use-openapi-mcp`)](skills/use-openapi-mcp/SKILL.md)
134
+
135
+ ## Development
136
+
137
+ Run the local verification suite (see [Getting Started](docs/feature/getting-started.md#development--verification) for all packaging and binary targets):
138
+
139
+ ```sh
140
+ bun install && bun run typecheck && bun test && bun run build
141
+ ```
142
+
143
+ ## License
144
+
145
+ [MIT](LICENSE)
@@ -0,0 +1,38 @@
1
+ import * as fs from 'node:fs';
2
+ export type InstallChannel = 'standalone' | 'bun-global' | 'npm-global';
3
+ export interface SelfUpdateOptions {
4
+ check?: boolean;
5
+ version?: string;
6
+ json?: boolean;
7
+ }
8
+ export interface SelfUpdateResult {
9
+ package_name: string;
10
+ github_repo: string;
11
+ channel: InstallChannel;
12
+ current_version: string;
13
+ target_version: string | null;
14
+ update_available: boolean;
15
+ updated: boolean;
16
+ message: string;
17
+ }
18
+ export interface SelfUpdateDeps {
19
+ execPath?: string;
20
+ entryPath?: string;
21
+ platform?: NodeJS.Platform;
22
+ arch?: string;
23
+ fetchFn?: typeof fetch;
24
+ runCommandFn?: (bin: string, args: string[]) => {
25
+ status: number;
26
+ stderr?: string;
27
+ stdout?: string;
28
+ };
29
+ fsOps?: Pick<typeof fs, 'writeFileSync' | 'chmodSync' | 'renameSync' | 'unlinkSync' | 'existsSync'>;
30
+ timeoutMs?: number;
31
+ }
32
+ export declare function normalizeVersion(raw: string): string;
33
+ export declare function parseSemver(v: string): [number, number, number];
34
+ export declare function isNewerVersion(current: string, latest: string): boolean;
35
+ export declare function detectInstallChannel(execPath?: string, entryPath?: string): InstallChannel;
36
+ export declare function resolveReleaseAssetName(binaryPrefix: string, platform?: NodeJS.Platform, arch?: string): string;
37
+ export declare function parseChecksumForAsset(checksumsText: string, assetName: string): string | null;
38
+ export declare function runOpenApiMcpUpdate(options?: SelfUpdateOptions, deps?: SelfUpdateDeps): Promise<SelfUpdateResult>;
@@ -0,0 +1,235 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { spawnSync } from 'node:child_process';
3
+ import * as fs from 'node:fs';
4
+ import * as path from 'node:path';
5
+ import { OPENAPI_MCP_VERSION } from '../mcp/server.js';
6
+ const PACKAGE_NAME = '@dimassetoid/openapi-mcp';
7
+ const GITHUB_REPO = 'Shironim/openapi-mcp';
8
+ const BINARY_PREFIX = 'openapi-mcp';
9
+ export function normalizeVersion(raw) {
10
+ return raw.trim().replace(/^v/, '');
11
+ }
12
+ export function parseSemver(v) {
13
+ const clean = normalizeVersion(v).split('-')[0].split('+')[0];
14
+ const parts = clean.split('.').map((n) => parseInt(n, 10));
15
+ return [
16
+ Number.isFinite(parts[0]) ? parts[0] : 0,
17
+ Number.isFinite(parts[1]) ? parts[1] : 0,
18
+ Number.isFinite(parts[2]) ? parts[2] : 0,
19
+ ];
20
+ }
21
+ export function isNewerVersion(current, latest) {
22
+ const [cMaj, cMin, cPatch] = parseSemver(current);
23
+ const [lMaj, lMin, lPatch] = parseSemver(latest);
24
+ if (lMaj !== cMaj)
25
+ return lMaj > cMaj;
26
+ if (lMin !== cMin)
27
+ return lMin > cMin;
28
+ return lPatch > cPatch;
29
+ }
30
+ export function detectInstallChannel(execPath = process.execPath, entryPath = process.argv[1] ?? '') {
31
+ const execBase = path.basename(execPath).toLowerCase();
32
+ const isRuntime = execBase === 'bun' ||
33
+ execBase === 'bun.exe' ||
34
+ execBase === 'node' ||
35
+ execBase === 'node.exe';
36
+ if (!isRuntime || entryPath.startsWith('/$bunfs/') || entryPath.startsWith('B:/~BUN/')) {
37
+ return 'standalone';
38
+ }
39
+ const normalizedEntry = entryPath.replace(/\\/g, '/');
40
+ if (execBase.startsWith('bun') || normalizedEntry.includes('/.bun/install/global/')) {
41
+ return 'bun-global';
42
+ }
43
+ return 'npm-global';
44
+ }
45
+ export function resolveReleaseAssetName(binaryPrefix, platform = process.platform, arch = process.arch) {
46
+ const osMap = {
47
+ linux: 'linux',
48
+ darwin: 'darwin',
49
+ win32: 'windows',
50
+ };
51
+ const archMap = { x64: 'x64', arm64: 'arm64' };
52
+ const targetOs = osMap[platform];
53
+ const targetArch = archMap[arch];
54
+ if (!targetOs || !targetArch) {
55
+ throw new Error(`Unsupported platform for standalone binary update: ${platform}/${arch}`);
56
+ }
57
+ if (platform === 'win32' && targetArch !== 'x64') {
58
+ throw new Error(`Unsupported Windows architecture: ${arch}`);
59
+ }
60
+ const ext = platform === 'win32' ? '.exe' : '';
61
+ return `${binaryPrefix}-${targetOs}-${targetArch}${ext}`;
62
+ }
63
+ export function parseChecksumForAsset(checksumsText, assetName) {
64
+ for (const line of checksumsText.split(/\r?\n/)) {
65
+ const trimmed = line.trim();
66
+ if (!trimmed)
67
+ continue;
68
+ const match = trimmed.match(/^([a-fA-F0-9]{64})\s+\*?(.+)$/);
69
+ if (match && path.basename(match[2].trim()) === assetName) {
70
+ return match[1].toLowerCase();
71
+ }
72
+ }
73
+ return null;
74
+ }
75
+ async function fetchLatestNpmVersion(pkgName, fetchFn, timeoutMs) {
76
+ const encoded = pkgName.startsWith('@')
77
+ ? `@${encodeURIComponent(pkgName.slice(1))}`
78
+ : encodeURIComponent(pkgName);
79
+ const controller = new AbortController();
80
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
81
+ try {
82
+ const res = await fetchFn(`https://registry.npmjs.org/${encoded}/latest`, {
83
+ signal: controller.signal,
84
+ headers: { Accept: 'application/json', 'User-Agent': `${BINARY_PREFIX}-self-update` },
85
+ });
86
+ if (!res.ok)
87
+ return null;
88
+ const data = (await res.json());
89
+ return typeof data.version === 'string' && data.version.trim()
90
+ ? normalizeVersion(data.version)
91
+ : null;
92
+ }
93
+ catch {
94
+ return null;
95
+ }
96
+ finally {
97
+ clearTimeout(timer);
98
+ }
99
+ }
100
+ async function fetchLatestGithubReleaseVersion(repo, fetchFn, timeoutMs) {
101
+ const controller = new AbortController();
102
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
103
+ try {
104
+ const res = await fetchFn(`https://api.github.com/repos/${repo}/releases/latest`, {
105
+ signal: controller.signal,
106
+ headers: { Accept: 'application/vnd.github+json', 'User-Agent': `${BINARY_PREFIX}-self-update` },
107
+ });
108
+ if (!res.ok)
109
+ return null;
110
+ const data = (await res.json());
111
+ return typeof data.tag_name === 'string' && data.tag_name.trim()
112
+ ? normalizeVersion(data.tag_name)
113
+ : null;
114
+ }
115
+ catch {
116
+ return null;
117
+ }
118
+ finally {
119
+ clearTimeout(timer);
120
+ }
121
+ }
122
+ export async function runOpenApiMcpUpdate(options = {}, deps = {}) {
123
+ const execPath = deps.execPath ?? process.execPath;
124
+ const entryPath = deps.entryPath ?? process.argv[1] ?? '';
125
+ const platform = deps.platform ?? process.platform;
126
+ const arch = deps.arch ?? process.arch;
127
+ const fetchFn = deps.fetchFn ?? fetch;
128
+ const fsOps = deps.fsOps ?? fs;
129
+ const timeoutMs = deps.timeoutMs ?? 15000;
130
+ const channel = detectInstallChannel(execPath, entryPath);
131
+ const requestedVersion = options.version ? normalizeVersion(options.version) : null;
132
+ const targetVersion = requestedVersion ??
133
+ (channel === 'standalone'
134
+ ? await fetchLatestGithubReleaseVersion(GITHUB_REPO, fetchFn, timeoutMs)
135
+ : await fetchLatestNpmVersion(PACKAGE_NAME, fetchFn, timeoutMs));
136
+ if (!targetVersion) {
137
+ throw new Error(`Unable to resolve latest version for ${PACKAGE_NAME} (${channel}).`);
138
+ }
139
+ const updateAvailable = requestedVersion
140
+ ? requestedVersion !== normalizeVersion(OPENAPI_MCP_VERSION)
141
+ : isNewerVersion(OPENAPI_MCP_VERSION, targetVersion);
142
+ if (options.check || !updateAvailable) {
143
+ return {
144
+ package_name: PACKAGE_NAME,
145
+ github_repo: GITHUB_REPO,
146
+ channel,
147
+ current_version: OPENAPI_MCP_VERSION,
148
+ target_version: targetVersion,
149
+ update_available: updateAvailable,
150
+ updated: false,
151
+ message: updateAvailable
152
+ ? `Update available: v${OPENAPI_MCP_VERSION} -> v${targetVersion} (${channel})`
153
+ : `Already up to date (v${OPENAPI_MCP_VERSION})`,
154
+ };
155
+ }
156
+ if (channel === 'standalone') {
157
+ const assetName = resolveReleaseAssetName(BINARY_PREFIX, platform, arch);
158
+ const baseUrl = `https://github.com/${GITHUB_REPO}/releases/download/v${targetVersion}`;
159
+ const checksumRes = await fetchFn(`${baseUrl}/checksums.txt`);
160
+ if (!checksumRes.ok) {
161
+ throw new Error(`Failed to fetch checksums.txt for v${targetVersion} (HTTP ${checksumRes.status}).`);
162
+ }
163
+ const expectedHash = parseChecksumForAsset(await checksumRes.text(), assetName);
164
+ if (!expectedHash) {
165
+ throw new Error(`Checksum entry for ${assetName} not found in v${targetVersion} checksums.txt.`);
166
+ }
167
+ const binRes = await fetchFn(`${baseUrl}/${assetName}`);
168
+ if (!binRes.ok) {
169
+ throw new Error(`Failed to download ${assetName} for v${targetVersion} (HTTP ${binRes.status}).`);
170
+ }
171
+ const bytes = Buffer.from(await binRes.arrayBuffer());
172
+ const actualHash = createHash('sha256').update(bytes).digest('hex').toLowerCase();
173
+ if (actualHash !== expectedHash) {
174
+ throw new Error(`SHA-256 checksum mismatch for ${assetName}: expected ${expectedHash}, got ${actualHash}.`);
175
+ }
176
+ const tmpPath = `${execPath}.tmp-${process.pid}`;
177
+ try {
178
+ fsOps.writeFileSync(tmpPath, bytes);
179
+ if (platform !== 'win32') {
180
+ fsOps.chmodSync(tmpPath, 0o755);
181
+ }
182
+ else if (fsOps.existsSync(execPath)) {
183
+ const oldPath = `${execPath}.old`;
184
+ if (fsOps.existsSync(oldPath))
185
+ fsOps.unlinkSync(oldPath);
186
+ fsOps.renameSync(execPath, oldPath);
187
+ }
188
+ fsOps.renameSync(tmpPath, execPath);
189
+ }
190
+ catch (err) {
191
+ if (fsOps.existsSync(tmpPath)) {
192
+ try {
193
+ fsOps.unlinkSync(tmpPath);
194
+ }
195
+ catch {
196
+ // ignore cleanup failure
197
+ }
198
+ }
199
+ throw err;
200
+ }
201
+ return {
202
+ package_name: PACKAGE_NAME,
203
+ github_repo: GITHUB_REPO,
204
+ channel,
205
+ current_version: OPENAPI_MCP_VERSION,
206
+ target_version: targetVersion,
207
+ update_available: true,
208
+ updated: true,
209
+ message: `Updated ${BINARY_PREFIX} standalone binary to v${targetVersion}`,
210
+ };
211
+ }
212
+ const pmBin = channel === 'bun-global' ? 'bun' : 'npm';
213
+ const pmArgs = channel === 'bun-global'
214
+ ? ['add', '-g', `${PACKAGE_NAME}@${targetVersion}`]
215
+ : ['install', '-g', `${PACKAGE_NAME}@${targetVersion}`];
216
+ const runCmd = deps.runCommandFn ??
217
+ ((bin, args) => {
218
+ const res = spawnSync(bin, args, { encoding: 'utf8' });
219
+ return { status: res.status ?? 1, stdout: res.stdout, stderr: res.stderr };
220
+ });
221
+ const proc = runCmd(pmBin, pmArgs);
222
+ if (proc.status !== 0) {
223
+ throw new Error(`Failed to update via '${pmBin} ${pmArgs.join(' ')}': ${proc.stderr || proc.stdout || `exit code ${proc.status}`}`);
224
+ }
225
+ return {
226
+ package_name: PACKAGE_NAME,
227
+ github_repo: GITHUB_REPO,
228
+ channel,
229
+ current_version: OPENAPI_MCP_VERSION,
230
+ target_version: targetVersion,
231
+ update_available: true,
232
+ updated: true,
233
+ message: `Updated ${PACKAGE_NAME} to v${targetVersion} via ${pmBin}`,
234
+ };
235
+ }
@@ -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;