stitch-sdk-usage

작성자: google-labs-code

stitch-sdk-usage — google-labs-code/stitch-sdk에서 게시한 AI 에이전트용 설치 가능한 스킬입니다.

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

Using the Stitch SDK

The Stitch SDK provides a TypeScript interface for Google Stitch, an AI-powered UI generation service.

Installation

npm install @google/stitch-sdk

Environment Variables

export STITCH_API_KEY="your-api-key"

Quick Start

import { stitch } from "@google/stitch-sdk";

const project = await stitch.createProject({ title: "My App" });
const generation = await project.generate("A settings page with dark theme");
const screen = generation.first; // all screens: generation.screens
const html = await screen.getHtml(); // the HTML content
const png = await screen.getImage(); // screenshot bytes (Uint8Array)

The stitch singleton reads STITCH_API_KEY from the environment and connects on first use — no setup code required.

Working with Projects

import { stitch } from "@google/stitch-sdk";

// List all projects
const projects = await stitch.projects();

// Reference a project by ID (no network call)
const project = stitch.project("4044680601076201931");

// Create a new project
const newProject = await stitch.createProject({ title: "My App" });

Design Systems

// Create a design system for a project
const ds = await project.createDesignSystem({ displayName: "My Theme" });

// List design systems
const systems = await project.listDesignSystems();

// Reference by ID (no network call)
const dsRef = project.designSystem("existing-asset-id");

// Update a design system
const updated = await ds.update({ displayName: "Updated Theme" });

// Apply to screens (requires SelectedScreenInstance objects from project.data.screenInstances)
// Returns a Generation — all updated screens are in .screens
const applied = await ds.apply([
  { id: "instance-id", sourceScreen: "projects/123/screens/456" },
]);
applied.screens;

Uploading Images

Upload an existing image file (PNG, JPG, JPEG, WEBP) to create a screen directly from a mockup or asset.

import { stitch } from "@google/stitch-sdk";

const project = stitch.project("your-project-id");

// Upload a local image file
const [screen] = await project.upload("./mockup.png", {
  title: "Home Screen",
});

console.log(screen.id);
const html = await screen.getHtml(); // HTML content
const png = await screen.getImage(); // screenshot bytes (Uint8Array)

The method reads the file from disk and posts it directly to the Stitch REST API — no output token constraints apply (unlike agent-driven MCP calls).

Supported formats: .png, .jpg, .jpeg, .webp

Options:

OptionTypeDefaultDescription
titlestring—Display title for the created screen
createScreenInstancesbooleantrueWhether to add the screen to the canvas

Throws StitchError with codes: NOT_FOUND (file not found), UNKNOWN_ERROR (unsupported format or upload failure), AUTH_FAILED (invalid API key).

Generating and Iterating on Screens

// Generate screens from a prompt. Stitch can return MANY screens per
// generation — a Generation carries all of them plus the raw response.
const generation = await project.generate(
  "Login page with email and password fields",
);
generation.screens; // every generated Screen
generation.first; // convenience: the first screen
generation.raw; // full typed tool response

// Optional settings go in a trailing options object
const mobile = await project.generate("A settings page", {
  deviceType: "MOBILE",
});

// Edit an existing screen (also returns a Generation)
const edited = await generation.first.edit(
  "Make the background dark and add a subtitle",
);

// Generate variants of a screen
const variants = await generation.first.variants(
  "Try different color schemes",
  {
    variantCount: 2,
    creativeRange: "EXPLORE",
    aspects: ["COLOR_SCHEME", "LAYOUT"],
  },
);
variants.screens; // all variant Screens

Retrieving Screen Assets

// CONTENT (fetched for you)
const html = await screen.getHtml(); // HTML string
const png = await screen.getImage(); // Uint8Array

// Or just the signed download URLs
const htmlUrl = await screen.getHtmlUrl();
const imageUrl = await screen.getImageUrl();

URL accessors use cached data from the generation response when available and write fetched responses back to the cache. A missing artifact throws StitchError with code NOT_FOUND (never a silent empty string).

Dynamic Tool Client (for agents)

For agents and orchestration scripts that forward JSON payloads to MCP tools:

import { stitch } from "@google/stitch-sdk";

// Find available tools
const { tools } = await stitch.listTools();
for (const tool of tools) {
  console.log(`${tool.name}: ${tool.description}`);
}
// Call a tool with a JSON payload
const result = await stitch.callTool("generate_screen_from_text", {
  projectId: "123",
  prompt: "A login page",
});
await stitch.close();

Error Handling

All SDK methods throw StitchError on failure. Use try/catch:

import { stitch, StitchError } from "@google/stitch-sdk";

try {
  const project = stitch.project("bad-id");
  await project.screens();
} catch (e) {
  if (e instanceof StitchError) {
    console.log(e.code); // "AUTH_FAILED", "NOT_FOUND", etc.
    console.log(e.message); // Human-readable description
    console.log(e.recoverable); // Whether retrying might succeed
  }
}

Error codes: AUTH_FAILED, NOT_FOUND, PERMISSION_DENIED, RATE_LIMITED, NETWORK_ERROR, VALIDATION_ERROR, UNKNOWN_ERROR

API Reference

Stitch Class

MethodReturnsDescription
createProject(options?)Promise<Project>Create a new project (options.title)
projects()Promise<Project[]>List all projects
project(id)ProjectReference a project by ID (no network call)

Project Class

MethodReturnsDescription
generate(prompt, options?)Promise<Generation<Screen>>Generate screens — .screens, .first, .raw (options.deviceType, options.modelId)
screens()Promise<Screen[]>List all screens in the project
getScreen(screenId)Promise<Screen>Retrieve a specific screen by ID
upload(filePath, opts?)Promise<Screen[]>Upload an image/HTML file and create screen(s) from it
createDesignSystem(designSystem)Promise<DesignSystem>Create a design system for this project
listDesignSystems()Promise<DesignSystem[]>List all design systems
designSystem(id)DesignSystemReference by ID (no API call)

deviceType: "MOBILE" | "DESKTOP" | "TABLET" | "AGNOSTIC"

upload supported formats: .png .jpg .jpeg .webp .html

DesignSystem Class

MethodReturnsDescription
update(designSystem)Promise<DesignSystem>Update the design system's theme
apply(selectedScreenInstances)Promise<Generation<Screen>>Apply this design system to screens (.screens)

Screen Class

MethodReturnsDescription
getHtml()Promise<string>Fetch the screen's HTML content
getImage()Promise<Uint8Array>Fetch the screenshot bytes
getHtmlUrl() / getImageUrl()Promise<string>Signed download URLs (cache-aware)
edit(prompt, options?)Promise<Generation<Screen>>Edit the screen using a text prompt
variants(prompt, variantOptions, options?)Promise<Generation<Screen>>Generate variants of the screen

modelId: "GEMINI_3_8_FLASH" | "GEMINI_3_5_FLASH_LITE" (optional, defaults to backend default)

StitchToolClient (for agents)

MethodReturnsDescription
callTool(name, args)Promise<T>Call any MCP tool by name
listTools()Promise<Tools>Discover available tools
connect()Promise<void>Establish MCP connection (auto-called by callTool)
close()Promise<void>Close the connection

Explicit Configuration

import { Stitch, StitchToolClient } from "@google/stitch-sdk";

const client = new StitchToolClient({
  apiKey: "your-api-key",
  baseUrl: "https://stitch.googleapis.com/mcp",
  timeout: 300_000,
});

const sdk = new Stitch(client);
const projects = await sdk.projects();
OptionEnv VariableDescription
apiKeySTITCH_API_KEYAPI key for authentication
accessTokenSTITCH_ACCESS_TOKENOAuth access token
projectIdGOOGLE_CLOUD_PROJECTGCP project ID (required with OAuth)
baseUrl—MCP server URL (default: https://stitch.googleapis.com/mcp)
timeout—Request timeout in ms (default: 300000)

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 이슈 분류 및 해결 설정