Skip to content

feat(ui-plugins): add API To SDK (api-to-sdk) - #246

Open
ppppp2005-p wants to merge 11 commits into
zai-org:mainfrom
ppppp2005-p:feat/api-to-sdk
Open

ppppp2005-p wants to merge 11 commits into
zai-org:mainfrom
ppppp2005-p:feat/api-to-sdk

Conversation

@ppppp2005-p

Copy link
Copy Markdown

Plugin type (required) / 插件类型(必填)

  • UI Plugin / 是 UI 插件 — provides MCP Apps interactive pages / 提供 MCP Apps 交互页面
  • Standard plugin / 普通插件(非 UI)
  • Not applicable / 不适用

Affected plugin name(s) / 涉及的插件名称:api-to-sdk (UI Plugin, new)

What / 改动内容

New community UI plugin API To SDK / 接口转 SDK: an OpenAPI 3.0/3.1 spec becomes a typed, dependency-free TypeScript SDK package. It is verified by a strict TypeScript compile and by calling every operation against a mock server built from the spec.

Tools:

  • sdk_inspect (read-only), sdk_generate, sdk_test.
  • App-only: sdk_state.

How it works:

  • Spec model (src/openapi.ts):
    • YAML via yaml, or JSON.
    • Rejected with clear messages: Swagger 2 and other versions.
    • Local $ref resolution (#/..., ~0/~1 escapes). External refs produce warnings.
    • Operations: path-level and operation parameters merged; operationId kept or derived from method + path, with duplicates renamed.
    • Request body: JSON, then multipart, then form, then first entry. Responses: success, errors and default.
    • Security: per operation or global, with security: [] meaning none. Schemes: bearer, basic, apiKey (header/query/cookie), oauth2/OIDC (token).
  • Codegen (src/codegen.ts):
    • Schema → TS: $ref → named types; enum/const literals; oneOf/anyOf unions; allOf intersections; 3.0 nullable / 3.1 ["x","null"]; objects with optional/required properties and quoted keys; additionalProperties; arrays; binary → Blob.
    • Client class: one method per operation taking a single args object (path/query/header params by camelCased name, plus body) and { headers, signal }.
    • Shared request(): URL + query (arrays repeated); auth picked from the first satisfiable security alternative; bodies (JSON, FormData, URLSearchParams, raw); timeout via AbortSignal.timeout / AbortSignal.any.
    • Responses: JSON (falls back to text when the server isn't JSON), text, blob, 204. Non-2xx throws ApiError(status, body, operation, response).
    • Exported per operation: <Op>Args, <Op>Response, <Op>ErrorBody.
  • Package:
    • src/, pre-built dist/ (compiled in memory with the bundled TypeScript 6.0.2, strict, NodeNext; .js + .d.ts), package.json (exports/types), tsconfig.json, README.md (operation table).
    • examples/all-operations.ts: typed calls with spec examples. It is type-checked so that spec examples contradicting their schemas are reported.
    • mock/ (mock.mjs, server.mjs, openapi.json).
  • Mock (src/runtime/mock.mjs, plain JS, also used for verification):
    • Routing: route table with server base-path stripping; CORS preflight.
    • Request checks against the spec: required/typed path, query and header params; content type; JSON body via a light JSON-schema checker (types, required, enum, const, properties, items, additionalProperties, oneOf/anyOf/allOf, formats, pattern, ranges); multipart required parts.
    • Responses: example → examples[0] → schema-synthesised value, choosing the media type by Accept. Prefer: code=NNN / X-Mock-Status selects a documented status. Calls are recorded.
  • Verification (src/verify.ts):
    • Emitted JS is loaded from a fresh temp folder each run, to avoid the ESM module cache.
    • Each operation is called with example args. Checks: method, path params, query, headers, credentials and JSON body as passed; no mock validation errors; the response deep-equals what the mock sent (204 → undefined).
    • For the first documented 4xx/5xx, it expects ApiError with that status and the parsed body.

Panel:

  • Spec picker and Read spec.
  • API summary with warnings.
  • Output folder, package name and class name; Generate & verify.
  • Result banner, TypeScript diagnostics and example warnings.
  • Operation table (method badge, params/body, responses, auth, ✓/✗ with checks or problems).
  • src/client.ts preview.

Network / API / side effects: none. No API keys. Verification uses a mock on 127.0.0.1; the real API is never contacted. Writes the SDK folder and .api-to-sdk/sdks.json. No hooks. The plugin bundles TypeScript, so server.mjs is ~11 MB.

Testing:

  • vitest (9 tests):
    • Spec model (merged params, derived ids, security, multipart, 204, errors) and TS mapping.
    • Rejections and warnings (Swagger 2, version, bad YAML, external $ref, undeclared path param).
    • Harbor Bikes (fictional OpenAPI 3.1 sample covering the tricky features): 12/12 operations, no diagnostics or example warnings.
    • The generated package also builds with the real tsc CLI. The bundled mock runs standalone (example response, 400 with reasons, Prefer: code=404).
    • sdk_test catches a client that drops a query parameter and one that no longer compiles.
    • The real Swagger Petstore 3.0 spec: 19/19.
  • Chrome e2e:
    • The panel generates and verifies both specs (12/12, 19/19).
    • A browser page imports the generated ESM SDK and calls the bundled mock (CORS, bearer, query arrays, oneOf body, CSV, ApiError 404).

A ZCode Desktop demo recording is attached in the comments. / ZCode 桌面版演示录屏见评论。

Self-check / 自查清单

  • Plugin name is unique kebab-case; new external plugin directory is external_plugins/<name>/
  • Usage category is set (productivity)
  • Plugin type and affected names are declared above
  • version 0.1.0 in both plugin.json and marketplace.json
  • README.md (EN) and README_CN.md (中文) both provided and equivalent
  • description_i18n has both en and zh-CN
  • No secrets, machine-specific paths, or private dependencies
  • Model/API/network dependencies documented
  • python3 scripts/validate.py and python3 scripts/build_dist.py pass locally
  • Exercised in ZCode Desktop (ZCode 4.0.0, macOS arm64: installed from a local marketplace, asked it to read api/harbor-bikes-api.yaml and generate a TypeScript SDK; the agent ran sdk_inspect → sdk_generate → sdk_test: 12 methods / 14 types, strict TypeScript compile clean, 12/12 mock-server calls passed; demo video in the comments)

@ppppp2005-p

Copy link
Copy Markdown
Author

ZCode desktop demo (ZCode 4.0.0, macOS arm64)

api-to-sdk-demo.mp4

Flow shown:

  1. Installed api-to-sdk from a local marketplace built from this PR's branch.
  2. Asked ZCode to read api/harbor-bikes-api.yaml (Harbor Bikes Rental API 1.4.0, OpenAPI 3.1), generate a TypeScript SDK with package name harbor-bikes-sdk, run the SDK self-test, and report the output folder and test result.
  3. The agent called sdk_inspect (the side panel opens with the spec summary: 12 operations, 14 schemas, bearer + API-key auth, output folder, npm package name and client class name), then sdk_generate wrote sdk/harbor-bikes-rental/ (HarborBikesRentalClient, 12 methods, 14 types, plus a mock server).
  4. sdk_test compiled the SDK in TypeScript strict mode with no errors and called all 12 operations against the generated mock server: 12/12 passed in 1.6 s. The panel shows the green result box and the operation list. The last card is the final state.

演示流程:本地 marketplace 安装 → sdk_inspect 读取 OpenAPI 并打开面板 → sdk_generate 生成 TypeScript SDK(12 个方法、14 个类型)→ sdk_test 严格模式编译通过、模拟服务器 12/12 通过。

@panda920

Copy link
Copy Markdown
Collaborator

✅ Internal validation passed. A ZCode maintainer will review the change next; after acceptance, release checks run separately and this PR is closed automatically.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants