@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.
@@ -1,19 +1,14 @@
1
- # Code Mode Query (`openapi_query`) & Semantic Diff (`openapi_diff`)
1
+ # Code Mode Query, Diagnostics, Inspect & Semantic Diff
2
2
 
3
3
  ## `openapi_query`
4
4
 
5
- `openapi_query` evaluates synchronous JavaScript expressions, arrow functions, or statement bodies with `return`. The tool accepts `code` (required, up to 16,384 characters), optional `root` and `spec_path`, and optional integer `max_bytes`.
5
+ `openapi_query` evaluates synchronous JavaScript expressions, arrow functions, or statement bodies with `return`. The tool accepts non-empty `code` (required, 1–16,384 characters with at least one non-whitespace character), optional `root` and `spec_path`, and optional integer `max_bytes` (1–1,048,576; default `16384`). When `spec_path` is omitted, a non-breaking `Resolved spec: <path>` text note is appended in a second content block while `content[0].text` and `structuredContent` remain pure query JSON.
6
6
 
7
7
  ```js
8
8
  helpers.op('POST', '/orders')
9
- ```
10
-
11
- ```js
12
9
  helpers.example('POST', '/orders', '422')
13
- ```
14
-
15
- ```js
16
10
  helpers.schemaRefs('ProblemDetails')
11
+ helpers.meta()
17
12
  ```
18
13
 
19
14
  ### Built-in Read-Only `helpers`
@@ -23,6 +18,7 @@ Inside the QuickJS guest runtime, a frozen `helpers` global is exposed alongside
23
18
  - `helpers.op(method, path)`: Returns the merged operation contract with path-level + operation-level `parameters` combined (operation overrides path on matching `in` + `name`), effective `security` (inheriting top-level `spec.security` unless overridden), and `sourceLocation`.
24
19
  - `helpers.example(method, path, statusCode?)` or `helpers.example(schema)`: Deterministically synthesizes JSON sample payloads (honoring `example`/`examples` → `const` → `default` → `enum` → `format` → `type`, merging `allOf`, respecting `readOnly`/`writeOnly`, and safely terminating `[Circular: ...]` markers).
25
20
  - `helpers.schemaRefs(schemaName?)`: Returns reverse references (`[{ method, path, section }]`) recorded during `$ref` resolution before inlining.
21
+ - `helpers.meta()`: Returns `{ specPath, rootDir, title, version, openapiVersion }` for the active loaded specification.
26
22
 
27
23
  ### Execution & Resource Bounds
28
24
 
@@ -32,9 +28,16 @@ Inside the QuickJS guest runtime, a frozen `helpers` global is exposed alongside
32
28
 
33
29
  ---
34
30
 
31
+ ## `openapi_diagnostics` & `openapi_inspect`
32
+
33
+ - `openapi_diagnostics({ root?, spec_path?, max_bytes? })`: Runs `diagnoseOpenApiSpec` directly as an MCP tool, supporting explicit `root` overrides (within `--root` when pinned) for clients that do not expose resource templates.
34
+ - `openapi_inspect({ target?, root?, spec_path?, q?, tag?, method?, pathPrefix?, operationId?, missingErrorContracts?, usedByPath?, unusedOnly?, pointer?, offset?, limit?, max_bytes? })`: Discovers workspace specs (`target: "catalog"`), queries endpoint (`target: "endpoints"`, $O(\text{endpoints})$ lazy load) or schema (`target: "schemas"`) indexes (`limit` `1–100`, default `20` when paginated), or lazily resolves a single JSON Pointer subtree (`pointer`, e.g. `"/paths/~1users/get"` or `"/components/schemas/Order"`, invalid when combined with `target: "catalog"`). When an unfiltered index exceeds `max_bytes`, it automatically falls back to a paginated slice (`limit: 20`).
35
+
36
+ ---
37
+
35
38
  ## `openapi_diff`
36
39
 
37
- `openapi_diff` compares two local OpenAPI specifications inside the configured workspace (`base_spec_path` vs `target_spec_path`, plus optional `root` and `max_bytes`).
40
+ `openapi_diff` compares two local OpenAPI specifications inside the configured workspace (`base_spec_path` vs `target_spec_path`, plus optional `root`, `include_non_breaking`, and `max_bytes`).
38
41
 
39
42
  ```json
40
43
  {
@@ -43,6 +46,8 @@ Inside the QuickJS guest runtime, a frozen `helpers` global is exposed alongside
43
46
  }
44
47
  ```
45
48
 
46
- It returns `hasBreakingChanges`, `summary` (`breakingCount`, `nonBreakingCount`, `addedEndpoints`, `removedEndpoints`, `truncated`), `breaking[]`, and `nonBreaking[]`, classifying:
47
- - **Breaking:** removed endpoints, removed response status codes or media types, new required parameters or request properties, optional-to-required request changes, required-to-optional response changes, schema type changes, removed request enum values, added response enum values.
49
+ It returns `hasBreakingChanges`, `summary` (`breakingCount`, `nonBreakingCount`, `addedEndpoints`, `removedEndpoints`, `totalChanges`, `truncated`), `breaking[]`, and `nonBreaking[]`, capping `breaking` and `nonBreaking` at 250 items independently so non-breaking volume never starves breaking detections. If serialized JSON exceeds `max_bytes` (default 16 KiB) or `include_non_breaking: false` is passed, all `breaking` entries are preserved while `nonBreaking` is returned empty with `nonBreakingSummary` (counts by change code) and `nonBreakingTruncatedByBudget: true` or `nonBreakingOmitted: true`.
50
+
51
+ Classifications:
52
+ - **Breaking:** removed endpoints, removed parameters, removed response status codes or media types, new required parameters or request properties, optional-to-required request changes, required-to-optional response changes, schema type changes, removed request enum values, added response enum values.
48
53
  - **Non-breaking:** added endpoints, newly deprecated endpoints, new optional request parameters/properties, added response statuses or properties, new request media types.
@@ -11,23 +11,24 @@ For monorepos or nested services, read `openapi://specs/catalog` and pass the de
11
11
  Relative `$ref` paths are resolved from the referring file. The loader accepts local regular files inside the workspace and resolves JSON Pointer fragments, including percent-encoding, escaped keys (`~0`, `~1`), and empty keys. Remote references and paths whose canonical `realpath` escapes the workspace boundary are rejected.
12
12
 
13
13
  - Missing referenced files raise `REF_FILE_NOT_FOUND`, identifying both the referring file and missing target.
14
- - Missing entry specifications cause index and search resources to return `status: "spec_not_found"` with the candidate paths checked.
14
+ - When an entry specification is missing, `openapi://endpoints/*`, `openapi://schemas/*`, and `openapi://spec/diagnostics` resources return `status: "spec_not_found"` with checked candidates, whereas MCP tools (`openapi_query`, `openapi_diagnostics`, `openapi_inspect`) return `isError: true` (`SPEC_NOT_FOUND` / `SPEC_FILE_NOT_FOUND`) and `openapi-mcp check` exits `1`.
15
15
 
16
16
  Cyclic references are tracked by object identity and replaced with a `[Circular: <ref>]` marker so recursive schemas remain inspectable without infinite expansion.
17
17
 
18
- For OpenAPI 3.1 Schema Objects with sibling keywords alongside `$ref`, the target schema is preserved via `allOf` alongside the local keywords. Schema-resource identifiers (`$id`), named anchors (`$anchor`), and dynamic references (`$dynamicRef`) are outside the supported resolver subset and raise an error if encountered.
18
+ For OpenAPI 3.1 Schema Objects with sibling keywords alongside `$ref`, the target schema is preserved via `allOf` alongside the local keywords. Schema-resource identifiers (`$id`) and dynamic references (`$dynamicRef`) are outside the supported resolver subset and raise `INVALID_REF`; named `$anchor` definitions are not resolved as fragment anchors.
19
19
 
20
20
  ## Source Mapping & Reverse Schema Usage
21
21
 
22
22
  `loadOpenApiSpec` parses each YAML/JSON file once using `yaml` v2 `parseDocument` and `LineCounter` ([source-map.ts](../../src/engine/source-map.ts)), producing 1-based `{ file, line, col }` `sourceLocations` for paths, operations, and component schemas without a second parse pass.
23
23
 
24
- During `$ref` expansion, before inlining removes reference boundaries, the loader builds a reverse usage map (`schemaUsages`) linking each local `components.schemas` / `definitions` entry to the operations and sections (`requestBody`, `parameters`, `response:<status>`) that reference it. Both `sourceLocations` and `schemaUsages` are frozen and exposed to indexes and sandbox `helpers`.
24
+ During `$ref` expansion, before inlining removes reference boundaries, the loader builds a reverse usage map (`schemaUsages`) linking each local `components.schemas` / `definitions` entry to the operations and sections (`requestBody`, `parameters`, `response:<status>`, or `operation`) that reference it. Both `sourceLocations` and `schemaUsages` are frozen and exposed to indexes and sandbox `helpers`.
25
25
 
26
26
  ## Caching & Resource Limits
27
27
 
28
- The loader caches up to eight entry specifications keyed by workspace root and canonical entry path (`${root}\0${entry}`). On a cache hit, an `O(F)` `statSync` check compares `mtimeMs`, `ctimeMs`, and `size` across all dependencies before falling back to a full read and SHA-256 verification. Deleted `$ref` files and retargeted symlinks invalidate stale cache entries automatically.
28
+ The loader caches resolved entry specifications keyed by workspace root and canonical entry path (`${root}\0${entry}`), while `loadRawOpenApiDocument` ([lazy-expander.ts](../../src/engine/lazy-expander.ts)) caches raw parsed documents for $O(\text{endpoints})$ shallow indexing (`buildRawEndpointSummary`) and single-pointer lazy `$ref` expansion (`expandPointerSubtree`, 64-entry subtree cache). On a cache hit, an `O(F)` `statSync` check compares `mtimeMs`, `ctimeMs`, and `size` across all dependencies before falling back to a full read and SHA-256 verification. Deleted `$ref` files and retargeted symlinks invalidate stale cache entries automatically.
29
29
 
30
- Safety limits enforced during loading:
31
- - **Source files:** max 128 files, max 8 MiB cumulative input
32
- - **Expansion:** max 250,000 node visits, max depth 128, max 8 MiB serialized snapshot
33
- - **Error codes:** `SPEC_NOT_FOUND`, `REF_FILE_NOT_FOUND`, `INVALID_REF`, `PATH_TRAVERSAL_DENIED`, `SPEC_LIMIT`
30
+ Safety limits enforced during loading (default / bounded environment overrides via `resolveSpecLimits`):
31
+ - **Source files:** max `128` files (`OPENAPI_MCP_MAX_SPEC_FILES`, `1..1024`), max `8 MiB` cumulative input (`OPENAPI_MCP_MAX_SPEC_BYTES`, `1 KiB..64 MiB`)
32
+ - **Expansion & caching:** max `250,000` node visits (`OPENAPI_MCP_MAX_NODE_VISITS`, `1,000..2,000,000`), max depth `128`, max `8 MiB` serialized snapshot, max `8` cached specs (`OPENAPI_MCP_MAX_CACHED_SPECS`, `1..32`)
33
+ - **Telemetry override:** `OPENAPI_MCP_LOG_PATH` overrides the default log path (`<workspaceRoot>/.openapi-mcp/openapi.log` when `.openapi-mcp/` exists, otherwise `~/.openapi-mcp/openapi.log`)
34
+ - **Error codes:** `WORKSPACE_NOT_FOUND`, `INVALID_SPEC_PATH`, `SPEC_NOT_FOUND`, `SPEC_FILE_NOT_FOUND`, `REF_FILE_NOT_FOUND`, `INVALID_REF`, `REMOTE_REF_DENIED`, `PATH_TRAVERSAL_DENIED`, `SPEC_PARSE_ERROR`, `SPEC_CHANGED`, `SPEC_LIMIT`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dimassetoid/openapi-mcp",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Local Code Mode MCP server and reusable OpenAPI engine for AI coding agents",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -59,7 +59,7 @@
59
59
  "serve": "bun run src/index.ts serve",
60
60
  "test": "bun test",
61
61
  "typecheck": "tsc --noEmit",
62
- "build": "tsc -p tsconfig.build.json",
62
+ "build": "tsc -p tsconfig.build.json && node -e \"if(process.platform!=='win32')require('node:fs').chmodSync('dist/index.js',0o755)\"",
63
63
  "compile:all": "bun run scripts/compile.ts",
64
64
  "prepublishOnly": "bun run typecheck && bun run build && bun test"
65
65
  },
@@ -13,30 +13,31 @@ Prefer `openapi-mcp` over reading raw `openapi.yml`/`openapi.json` files directl
13
13
 
14
14
  ## Core Practices
15
15
 
16
- - **Read indexes before querying details:** Start with compact indexes (`endpoints/index`, `schemas/index`) before querying individual operations. Narrow `openapi_query` expressions to the specific operation or status code rather than increasing `max_bytes`.
16
+ - **Read indexes before querying details:** Start with compact indexes (`openapi_inspect({ target: "endpoints" })` / `openapi://endpoints/index` or `schemas/index`) before querying details. Prefer `openapi_inspect({ pointer: "/paths/~1users/get" })` for fast lazy single-subtree `$ref` expansion, and reserve `openapi_query` for custom expressions or `helpers.example` / `helpers.schemaRefs`. Narrow scopes rather than inflating `max_bytes`.
17
17
  - **Validate the spec before relying on it:** Existing specs can contain broken `$ref`s, undeclared `{path}` parameters, unknown `security` schemes, or missing error schemas. Run diagnostics before treating a spec as accurate.
18
18
  - **Check schema consumers before editing:** Use pre-expansion usage tracking (`schemas/index` or `helpers.schemaRefs`) to identify all affected endpoints before modifying a shared schema.
19
- - **Fallback when MCP is unavailable:** Prefer `openapi-mcp` MCP resources/tools when connected. If no MCP server is attached, use the `openapi-mcp check` / `openapi-mcp diff` CLI commands if installed, or fall back to targeted `rg` and file reads while manually checking path-level parameters, `$ref` targets, and `4xx`/`5xx` responses.
19
+ - **Fallback when MCP is unavailable:** Prefer `openapi-mcp` MCP resources/tools when connected. If no MCP server is attached, use the `openapi-mcp check`, `openapi-mcp diff`, `openapi-mcp stats`, or `openapi-mcp update` CLI commands if installed, or fall back to targeted `rg` and file reads while manually checking path-level parameters, `$ref` targets, and `4xx`/`5xx` responses.
20
20
 
21
21
  ## Intent-to-Primitive Routing
22
22
 
23
23
  | Intent | MCP Resource / Tool | Purpose |
24
24
  | --- | --- | --- |
25
- | **Discover specs in a monorepo** | `read_resource("openapi://specs/catalog")` | Finds entry specs while skipping unreadable (`EACCES`) and build/vendor directories; pass the chosen `spec_path` consistently thereafter. |
26
- | **List endpoints & error coverage** | `read_resource("openapi://endpoints/index")` | Lists methods, paths, `2xx`/`4xx`/`5xx` codes, `errorBodies`, `security`, `deprecated`, `tags`, and `sourceLocation` (`{ file, line }`). Soft-capped at `64 KB`. |
27
- | **Filter & paginate large indexes** | `read_resource("openapi://endpoints/search?q=orders&method=POST&pathPrefix=/api&tag=Checkout&missingErrorContracts=false&limit=20&offset=0&spec_path=...")` | Avoids oversized responses; follow `nextUri` for subsequent pages. |
28
- | **List schemas & their consumers** | `read_resource("openapi://schemas/index")` or `openapi://schemas/search?q=Order&unusedOnly=false&usedByPath=/orders` | Exposes `required`, `properties`, `sourceLocation`, and pre-expansion `usedBy` references. |
29
- | **Validate contract health** | `read_resource("openapi://spec/diagnostics")` (`?spec_path=...`) | Reports all broken `$ref`s, duplicate `operationId`, undeclared `{path}` params, unknown `security` schemes, and missing error contracts in one pass. |
30
- | **Inspect one merged operation** | `openapi_query({ code: "helpers.op('POST', '/orders')", spec_path? })` | Merges path + operation `parameters`, resolves effective `security` (respecting `[]`), and attaches `sourceLocation` for direct YAML/JSON navigation. |
31
- | **Generate deterministic sample payloads** | `openapi_query({ code: "helpers.example('POST', '/orders', '201')", spec_path? })` | Generates format-aware, circular-safe JSON samples respecting `readOnly`/`writeOnly` fields (also accepts `helpers.example(schema)`). |
32
- | **Find endpoints using a schema** | `openapi_query({ code: "helpers.schemaRefs('Order')", spec_path? })` | Returns `[{ method, path, section }]` captured prior to `$ref` expansion. |
33
- | **Detect breaking changes** | `openapi_diff({ base_spec_path, target_spec_path })` | Classifies `breaking` vs `non_breaking` changes across endpoints, parameters, request bodies, and responses. |
25
+ | **Discover specs in a monorepo** | `read_resource("openapi://specs/catalog")` or `openapi_inspect({ target: "catalog", root? })` | Finds entry specs while skipping unreadable (`EACCES`) and build/vendor directories; pass `root` and `spec_path` consistently thereafter. |
26
+ | **List endpoints & error coverage** | `read_resource("openapi://endpoints/index")` or `openapi_inspect({ target: "endpoints", root?, spec_path? })` | Lists methods, paths, `2xx`/`4xx`/`5xx` codes, `errorBodies`, `security`, `deprecated`, `tags`, and `sourceLocation` (`{ file, line }`). |
27
+ | **Filter & paginate large indexes** | `openapi_inspect({ target: "endpoints", q?, method?, pathPrefix?, tag?, operationId?, missingErrorContracts?, limit: 20, offset: 0, root?, spec_path? })` or `openapi://endpoints/search?...` | Avoids oversized responses; follow `nextUri` (resource) or `hasMore`/`offset` (tool) for subsequent pages. |
28
+ | **List schemas & their consumers** | `openapi_inspect({ target: "schemas", q?, unusedOnly?, usedByPath?, root?, spec_path? })` or `openapi://schemas/index` / `openapi://schemas/search` | Exposes `required`, `properties`, `sourceLocation`, and pre-expansion `usedBy` references. |
29
+ | **Validate contract health** | `openapi_diagnostics({ root?, spec_path? })` or `read_resource("openapi://spec/diagnostics?root=...&spec_path=...")` | Reports all broken `$ref`s, duplicate `operationId`, undeclared `{path}` params, unknown `security` schemes, missing error contracts, and auth `401`/`403` coverage in one pass. |
30
+ | **Inspect one merged operation lazily** | `openapi_inspect({ pointer: "/paths/~1orders/post", root?, spec_path? })` or `openapi_query({ code: "helpers.op('POST', '/orders')", root?, spec_path? })` | `pointer` expands **only** that JSON Pointer subtree without resolving the rest of a huge spec; `helpers.op` runs against full resolved spec with merged parameters, effective `security`, and `sourceLocation`. |
31
+ | **Generate deterministic sample payloads** | `openapi_query({ code: "helpers.example('POST', '/orders', '201')", root?, spec_path? })` | Generates format-aware, circular-safe JSON samples respecting `readOnly`/`writeOnly` fields (also accepts `helpers.example(schema)`). |
32
+ | **Find endpoints using a schema** | `openapi_query({ code: "helpers.schemaRefs('Order')", root?, spec_path? })` | Returns `[{ method, path, section }]` captured prior to `$ref` expansion. |
33
+ | **Detect breaking changes** | `openapi_diff({ base_spec_path, target_spec_path, root?, include_non_breaking? })` | Classifies `breaking` vs `non_breaking` changes across endpoints, parameters, request bodies, and responses; preserves all `breaking` items even when `non_breaking` exceeds `max_bytes`. |
34
34
 
35
35
  ## Client Compatibility
36
36
 
37
- MCP clients that only expose `resources/list` (and not `resources/templates/list`) can still pass query parameters directly to `read_resource`:
38
- - `openapi://endpoints/index?spec_path=<path>`
39
- - `openapi://endpoints/search?q=<term>&limit=20&spec_path=<path>`
40
- - `openapi://schemas/index?spec_path=<path>`
41
- - `openapi://schemas/search?q=<term>&limit=20&spec_path=<path>`
42
- - `openapi://spec/diagnostics?spec_path=<path>`
37
+ MCP clients that only expose `resources/list` (and not `resources/templates/list`) can pass query parameters directly to `read_resource` or use the `openapi_inspect` / `openapi_diagnostics` tools with `root` and `spec_path`:
38
+ - `openapi://specs/catalog?root=<dir>`
39
+ - `openapi://endpoints/index?root=<dir>&spec_path=<path>`
40
+ - `openapi://endpoints/search?q=<term>&limit=20&root=<dir>&spec_path=<path>`
41
+ - `openapi://schemas/index?root=<dir>&spec_path=<path>`
42
+ - `openapi://schemas/search?q=<term>&limit=20&root=<dir>&spec_path=<path>`
43
+ - `openapi://spec/diagnostics?root=<dir>&spec_path=<path>`