stitch-sdk-domain-design

작성자: google-labs-code

Stitch SDK의 도메인 모델을 설계합니다. MCP 도구를 domain-map.json의 도메인 클래스 및 바인딩에 매핑할 때 사용합니다. 이는 생성의 2단계입니다…

npx skills add https://github.com/google-labs-code/stitch-sdk --skill stitch-sdk-domain-design

Stitch SDK Domain Design

This skill teaches you how to perform Stage 2 of the generation pipeline: reading tool schemas and producing domain-map.json — the intermediate representation that drives codegen.


Your Inputs

  1. tools-manifest.json — raw MCP tool schemas captured from the server (includes outputSchema)
  2. ir-schema.ts — Zod schema defining valid domain-map structure (the canonical contract)
  3. Existing domain-map.json — the current IR (if extending, not starting fresh)
  4. The stitch-sdk-development skill — for understanding the pipeline context

Your Output

A valid domain-map.json with two sections: classes and bindings, validated by ir-schema.ts.

[!IMPORTANT] Your output is validated twice by the codegen: structurally (Zod IR schema) and semantically (projection steps verified against outputSchema from the tools-manifest).


Designing Classes

Each class represents a domain entity. Ask: "What noun does the user interact with?"

{
  "Stitch": {
    "description": "Main entry point. Manages projects.",
    "constructorParams": [],
    "isRoot": true,
    "factories": [
      {
        "method": "project",
        "returns": "Project",
        "description": "Create a Project handle from an ID."
      }
    ]
  }
}

Key decisions:

FieldPurposeExample
constructorParamsFields stored on the instance["projectId", "screenId"]
referenceIdentity-map keys (.id aliases the LAST key){ "keys": ["projectId", "screenId"] }
parentFieldWhich param is injected from a parent class"projectId"
factoriesLocal factory methods (no API call)[{ "method": "project", "returns": "Project" }]
sideEffectsHandwritten extension methods (declared, never generated)[{ "method": "upload", "reason": "private_rest", "specPath": "src/spec/upload.ts" }]
extensionPathModule re-exporting the class with handwritten methods"../../src/project-ext.js"

[!IMPORTANT] The IR schema is STRICT. Unknown keys are hard validation errors, not silently ignored. Per-field source-mapping helpers described in older docs were never implemented and do not exist — identity fields are populated by the EntityManager from reference.keys, resource name parsing, and id fallback. If validation rejects a key you expected to exist, the feature does not exist — do not work around it.


Designing Bindings

Each binding maps one MCP tool to one class method. Ask: "Who owns this action?"

Arg routing

TypeMeaningCode generated
selfFrom this.fieldprojectId: this.projectId
paramFrom method parameterprompt: prompt
computedtemplate interpolation ("template": "projects/{projectId}")name: \projects/${this.projectId}/screens/${screenId}``
selfArrayWrap self field as arrayselectedScreenIds: [this.screenId]

Optional params use "optional": true. Renamed params use "rename": "newName". A "default": "VALUE" (requires optional: true) is sent when the caller omits the value: deviceType: options?.deviceType ?? "DESKTOP".

[!IMPORTANT] Method signature shape (D12): required params are positional, in IR order; ALL optional params are emitted into a single trailing options?: { ... } object. generate(prompt, options?), never generate(prompt, deviceType?).

Response Projections

The returns.projection array tells codegen how to navigate the API response. Each step is a ProjectionStep:

{ prop: string; index?: number; each?: boolean; find?: string; acknowledgeSingle?: boolean }
ProjectionGenerated codeUse when
[] (empty)rawDirect return (whole response)
[{ "prop": "projects" }]raw.projectsArray inside object
[{ "prop": "outputComponents", "index": 0 }, { "prop": "design" }, { "prop": "screens", "index": 0 }]raw.outputComponents[0].design.screens[0]Deeply nested single item
[{ "prop": "outputComponents", "each": true }, { "prop": "design" }, { "prop": "screens", "each": true }]flatMap chainCollect all items across arrays
[{ "prop": "screenshot" }, { "prop": "downloadUrl" }]raw.screenshot.downloadUrlNavigate nested properties

Decision: Use "index": 0 when extracting a single item. Use "each": true when collecting all items (array result). You cannot use both on the same step. "find": "a.b" scans an array for the first element whose nested path is non-null.

[!TIP] Every prop in a projection is validated against the tool's outputSchema at codegen time. If you typo a property name, codegen will fail with a diagnostic listing the available properties. Stepping THROUGH an array without index/each/find is also a codegen error — the emitted chain would be undefined at runtime.

[!WARNING] Truncation lint: using index or find on an UNBOUNDED array emits a warning — every other element is silently dropped (this exact pattern caused project.generate() to return one screen of many). Prefer "each": true + "array": true. Only if the result is semantically singular, acknowledge it with "acknowledgeSingle": true on the step.

Return class wrapping

When returns.class is set, the extracted data is wrapped in a domain class constructor:

{
  "returns": {
    "class": "Screen",
    "projection": [{ "prop": "screens" }],
    "array": true
  }
}

The codegen automatically spreads parentField into the data if the child class declares one.

Cache-aware methods

Add a cache field with a structured projection to check this.data before calling the API:

{
  "cache": {
    "projection": [{ "prop": "htmlCode" }, { "prop": "downloadUrl" }],
    "description": "Use cached HTML download URL from generation response if available"
  }
}

When the cached property is a nested object (like File with a downloadUrl), use multiple projection steps to drill into it.

Generated code:

if (this.data?.htmlCode?.downloadUrl) return this.data?.htmlCode?.downloadUrl;
// ... else call API

Decision Framework

When mapping a new tool, answer these questions:

  1. Which class? Look at which fields the tool requires. If it needs projectId from self, it belongs on Project or Screen. If it needs nothing from self, it belongs on Stitch.

  2. Which method name? Use the verb from the tool name, simplified. generate_screen_from_text → generate. edit_screens → edit.

  3. Arguments from self or param? If the caller already has the data (because they're calling a method on themselves), use self. If they need to provide it, use param.

  4. How deep is the return? Check the tool's outputSchema in tools-manifest.json. Build the projection array step-by-step to navigate to the useful data.

  5. Should it cache? If the data is available from a previous response (like generation), add a cache field with the projection path.


Validation

After editing domain-map.json:

bun scripts/generate-sdk.ts     # Validates IR + projections, then generates
npx tsc --noEmit                 # Type check
npx vitest run                   # Unit tests
bun scripts/e2e-test.ts          # E2E tests
bun scripts/validate-generated.ts  # Lock integrity

If a projection is invalid, you'll see:

❌ Binding "Project.generate" projection step 2:
   property "screenz" not found in outputSchema.
   Available properties: screens, components, metadata

google-labs-code의 다른 스킬

typed-service-contracts
google-labs-code
Spec and Handler" 패턴을 사용하여 견고하고 타입 안전한 TypeScript 서비스를 구축하기 위한 아키텍처 표준입니다. CLI, 라이브러리 또는 복잡한…
stitch::code-to-design
google-labs-code
프론트엔드 코드(Vite, React 등)를 정적 HTML 추출, 디자인 시스템 추출, 파일 업로드를 연쇄적으로 수행하여 Stitch Design으로 변환합니다. **항상** 이 방법을 사용하세요…
react-vite-dashboard
google-labs-code
Stitch 디자인을 TanStack Query, DESIGN.md의 접근 가능한 토큰, Web3 준비 패턴(ethers/viem)과 함께 프로덕션 React + Vite 대시보드로 변환합니다.
stitch::extract-design-md
google-labs-code
프론트엔드 소스 코드(React, Vue, Svelte, Angular, 일반 HTML/CSS 또는 모든 웹 프레임워크)로부터 포괄적인 디자인 시스템(DESIGN.md)을 직접 추출합니다.
remotion
google-labs-code
Stitch 앱 디자인에서 Remotion을 사용하여 부드러운 전환과 텍스트 오버레이가 포함된 전문 워크스루 비디오를 제작합니다. Stitch 프로젝트에서 화면을 가져와 확대 효과, 페이드 전환, 상황별 텍스트 오버레이와 함께 Remotion 비디오 구성으로 오케스트레이션합니다. ScreenSlide 및 WalkthroughComposition 컴포넌트를 포함한 모듈식 컴포넌트 아키텍처와 대화형 핫스팟 및 음성 해설 통합과 같은 고급 기능을 지원합니다. 화면 매니페스트를 생성하고 다운로드합니다...
ink
google-labs-code
Ink 터미널 렌더러로, JSON 사양을 대화형 터미널 UI로 변환합니다. @json-render/ink로 작업하거나 터미널 UI를 구축할 때 사용하세요.
tdd-red-green-refactor
google-labs-code
이 스킬은 AI 지원 프로그래밍을 위한 구조적 프레임워크를 구현하여 모든 코드 라인이 검증 가능하고, 타입이 지정되며, 목적에 부합하도록 보장합니다.
automate-github-issues
google-labs-code
병렬 Jules 코딩 에이전트를 사용하여 자동화된 GitHub 이슈 분류 및 해결 설정