@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
@@ -0,0 +1,50 @@
1
+ # Indexes, Diagnostics & Workflow Prompts
2
+
3
+ Implemented in [src/engine/spec-catalog.ts](../../src/engine/spec-catalog.ts), [src/engine/index-builder.ts](../../src/engine/index-builder.ts), [src/engine/schema-index.ts](../../src/engine/schema-index.ts), [src/engine/spec-diagnostics.ts](../../src/engine/spec-diagnostics.ts), and [src/mcp/server.ts](../../src/mcp/server.ts).
4
+
5
+ ---
6
+
7
+ ## Workspace Catalog (`openapi://specs/catalog`)
8
+
9
+ Reads workspace-relative OpenAPI entry filenames (`openapi.yml`, `openapi.yaml`, `openapi.json`) without parsing file contents.
10
+ - Skips symlinks and common build/vendor/cache directories (`node_modules`, `vendor`, `.git`, `dist`, `build`, `storage`, `.next`, `.nuxt`, `.venv`, `target`, `coverage`, etc.).
11
+ - Gracefully skips unreadable or transient directories (`EACCES`, `EPERM`, `ENOENT`, `ENOTDIR`, `ELOOP`) and reports `skippedDirCount` + up to 25 sample `skippedDirs` instead of failing the whole scan.
12
+
13
+ ---
14
+
15
+ ## Endpoint Index & Search (`openapi://endpoints/index`, `openapi://endpoints/search`)
16
+
17
+ - **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).
20
+
21
+ ---
22
+
23
+ ## Component Schema Index & Search (`openapi://schemas/index`, `openapi://schemas/search`)
24
+
25
+ - 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}`.
28
+
29
+ ---
30
+
31
+ ## Multi-Issue Diagnostics (`openapi://spec/diagnostics{?spec_path}`)
32
+
33
+ Runs a non-throwing single-pass check collecting up to 200 issues:
34
+ - Broken/remote/escaping `$ref`s (`BROKEN_REF`, `REMOTE_REF_DENIED`, `PATH_TRAVERSAL_DENIED`, `REF_PARSE_ERROR`)
35
+ - Missing `openapi`/`swagger` version or `info.title`
36
+ - Duplicate `operationId` (`DUPLICATE_OPERATION_ID`)
37
+ - Path template `{param}` not declared in `in: "path"` parameters (`UNDECLARED_PATH_PARAMETER`)
38
+ - 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`)
40
+
41
+ ---
42
+
43
+ ## Workflow Prompts
44
+
45
+ 1. **`sync-frontend-api`** (`endpoint?`): Read endpoint/schema indexes → inspect merged contract via `helpers.op` → align frontend types, auth, and `4xx`/`5xx` branches.
46
+ 2. **`audit-error-contracts`** (`endpoint?`): Read `openapi://spec/diagnostics` + `openapi://endpoints/index` → inspect `4xx`/`5xx` schemas → report gaps with `sourceLocation`.
47
+ 3. **`review-breaking-changes`** (`base_spec_path?`, `target_spec_path?`): Call `openapi_diff` → inspect impacted endpoints/schemas with `helpers.op` / `helpers.schemaRefs` → summarize migration impact.
48
+ 4. **`generate-test-fixtures`** (`endpoint?`): Read endpoint index → synthesize deterministic `2xx` and `4xx`/`5xx` JSON fixtures via `helpers.example`.
49
+
50
+ All prompt references to tools, parameters, and resource URIs are verified against live server schemas in [tests/mcp-contract.test.ts](../../tests/mcp-contract.test.ts).
@@ -0,0 +1,48 @@
1
+ # Code Mode Query (`openapi_query`) & Semantic Diff (`openapi_diff`)
2
+
3
+ ## `openapi_query`
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`.
6
+
7
+ ```js
8
+ helpers.op('POST', '/orders')
9
+ ```
10
+
11
+ ```js
12
+ helpers.example('POST', '/orders', '422')
13
+ ```
14
+
15
+ ```js
16
+ helpers.schemaRefs('ProblemDetails')
17
+ ```
18
+
19
+ ### Built-in Read-Only `helpers`
20
+
21
+ Inside the QuickJS guest runtime, a frozen `helpers` global is exposed alongside `spec` (pure guest JS, zero host callbacks):
22
+
23
+ - `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
+ - `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
+ - `helpers.schemaRefs(schemaName?)`: Returns reverse references (`[{ method, path, section }]`) recorded during `$ref` resolution before inlining.
26
+
27
+ ### Execution & Resource Bounds
28
+
29
+ - **Isolated timeouts:** Guest spec bootstrap (`JSON.parse` + recursive `Object.freeze`) has a bounded 2,000 ms setup cap, separate from the query execution deadline (default **150 ms**). Large specs do not cause false `SANDBOX_TIMEOUT` failures before the query runs.
30
+ - **Memory & stack:** Guest memory is limited to 64 MiB and stack to 512 KiB. Promise/thenable return values are rejected.
31
+ - **Byte budget:** Successful result text defaults to 16 KiB UTF-8 (configurable up to 1 MiB). Oversized results return `RESPONSE_BUDGET_EXCEEDED` with available keys and narrowing hints.
32
+
33
+ ---
34
+
35
+ ## `openapi_diff`
36
+
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`).
38
+
39
+ ```json
40
+ {
41
+ "base_spec_path": "openapi.yml",
42
+ "target_spec_path": "docs/openapi.yml"
43
+ }
44
+ ```
45
+
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.
48
+ - **Non-breaking:** added endpoints, newly deprecated endpoints, new optional request parameters/properties, added response statuses or properties, new request media types.
@@ -0,0 +1,33 @@
1
+ # Specification Loader
2
+
3
+ The engine, indexes, search templates, and query sandbox use `loadOpenApiSpec` to select, parse, and resolve an immutable OpenAPI snapshot.
4
+
5
+ Discovery checks `openapi.yml`, `openapi.yaml`, and `openapi.json` in the workspace root, followed by `api/` and `docs/`. An explicit `spec_path` or `--spec` option takes precedence over convention-based discovery.
6
+
7
+ For monorepos or nested services, read `openapi://specs/catalog` and pass the desired path as `spec_path`.
8
+
9
+ ## Local `$ref` Resolution
10
+
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
+
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.
15
+
16
+ Cyclic references are tracked by object identity and replaced with a `[Circular: <ref>]` marker so recursive schemas remain inspectable without infinite expansion.
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.
19
+
20
+ ## Source Mapping & Reverse Schema Usage
21
+
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
+
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`.
25
+
26
+ ## Caching & Resource Limits
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.
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`
package/package.json CHANGED
@@ -1,6 +1,79 @@
1
1
  {
2
2
  "name": "@dimassetoid/openapi-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Local Code Mode MCP server and reusable OpenAPI engine for AI coding agents",
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "type": "module",
9
+ "main": "dist/index.js",
10
+ "types": "dist/index.d.ts",
11
+ "bin": {
12
+ "openapi-mcp": "dist/index.js"
13
+ },
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "default": "./dist/index.js"
18
+ },
19
+ "./engine": {
20
+ "types": "./dist/engine/index.d.ts",
21
+ "default": "./dist/engine/index.js"
22
+ }
23
+ },
24
+ "files": [
25
+ "dist/**/*.js",
26
+ "dist/**/*.d.ts",
27
+ "docs/feature",
28
+ "skills",
29
+ "README.md",
30
+ "LICENSE"
31
+ ],
32
+ "engines": {
33
+ "node": ">=18.20.0",
34
+ "bun": ">=1.4.3"
35
+ },
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "git+https://github.com/Shironim/openapi-mcp.git"
39
+ },
40
+ "homepage": "https://github.com/Shironim/openapi-mcp#readme",
41
+ "bugs": {
42
+ "url": "https://github.com/Shironim/openapi-mcp/issues"
43
+ },
44
+ "keywords": [
45
+ "mcp",
46
+ "model-context-protocol",
47
+ "openapi",
48
+ "swagger",
49
+ "code-mode",
50
+ "ai-agent",
51
+ "sandbox",
52
+ "schema-validation",
53
+ "api-contract"
54
+ ],
55
+ "author": "dimassetoid",
56
+ "license": "MIT",
57
+ "scripts": {
58
+ "start": "bun run src/index.ts",
59
+ "serve": "bun run src/index.ts serve",
60
+ "test": "bun test",
61
+ "typecheck": "tsc --noEmit",
62
+ "build": "tsc -p tsconfig.build.json",
63
+ "compile:all": "bun run scripts/compile.ts",
64
+ "prepublishOnly": "bun run typecheck && bun run build && bun test"
65
+ },
66
+ "dependencies": {
67
+ "@jitl/quickjs-singlefile-cjs-release-sync": "0.32.0",
68
+ "@modelcontextprotocol/sdk": "^1.6.0",
69
+ "acorn": "8.19.0",
70
+ "quickjs-emscripten-core": "0.32.0",
71
+ "yaml": "^2.7.0",
72
+ "zod": "4.6.7"
73
+ },
74
+ "devDependencies": {
75
+ "@types/bun": "^1.4.0",
76
+ "@types/node": "^22.13.4",
77
+ "typescript": "^5.7.3"
78
+ }
79
+ }
@@ -0,0 +1,42 @@
1
+ ---
2
+ name: use-openapi-mcp
3
+ description: >-
4
+ Inspect, validate, diff, and generate sample payloads from OpenAPI 3.0/3.1 and Swagger 2.0 specifications via openapi-mcp without loading raw YAML/JSON files into context. Use when listing endpoints or schemas, finding endpoints affected by a schema change, auditing 4xx/5xx error responses, syncing frontend/backend API contracts, comparing spec revisions for breaking changes, or working with multi-file $ref specs.
5
+ ---
6
+
7
+ # use-openapi-mcp
8
+
9
+ Prefer `openapi-mcp` over reading raw `openapi.yml`/`openapi.json` files directly. Reading raw spec files into context wastes tokens and commonly causes three issues:
10
+ 1. **Missed `$ref` targets and inherited rules:** Searching raw files often misses cross-file `$ref` targets, path-level `parameters` inherited from `paths[p].parameters`, and global `security` vs operation-level `security: []` overrides.
11
+ 2. **Missing error contracts:** Inspecting only `2xx` responses overlooks `4xx`/`5xx` error schemas, undocumented status codes, and `readOnly`/`writeOnly` field differences.
12
+ 3. **Lost component references after `$ref` expansion:** Expanding `$ref` inline removes component schema names, making it harder to see which endpoints depend on a shared schema.
13
+
14
+ ## Core Practices
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`.
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
+ - **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.
20
+
21
+ ## Intent-to-Primitive Routing
22
+
23
+ | Intent | MCP Resource / Tool | Purpose |
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. |
34
+
35
+ ## Client Compatibility
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>`