stitch-sdk-usage

stitch-sdk-usage — 一个可安装的AI代理技能,由google-labs-code/stitch-sdk发布。

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("My App");
const screen = await project.generate("A settings page with dark theme");
const html = await screen.getHtml(); // download URL for the HTML
const imageUrl = await screen.getImage(); // download URL for the screenshot

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("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)
const screens = await ds.apply([
  { id: "instance-id", sourceScreen: "projects/123/screens/456" },
]);

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.uploadImage("./mockup.png", {
  title: "Home Screen",
});

console.log(screen.id);
const html = await screen.getHtml();
const imageUrl = await screen.getImage();

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
titlestringDisplay 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 a new screen from a prompt
const screen = await project.generate(
  "Login page with email and password fields",
);

// Edit an existing screen
const edited = await screen.edit("Make the background dark and add a subtitle");

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

Retrieving Screen Assets

// Get screen HTML download URL
const html = await screen.getHtml();

// Get screen screenshot download URL
const imageUrl = await screen.getImage();

Both methods use cached data from the generation response when available, falling back to an API call when needed.

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(title)Promise<Project>Create a new project
projects()Promise<Project[]>List all projects
project(id)ProjectReference a project by ID (no network call)

Project Class

MethodReturnsDescription
generate(prompt, deviceType?)Promise<Screen>Generate a screen from a text prompt
screens()Promise<Screen[]>List all screens in the project
getScreen(screenId)Promise<Screen>Retrieve a specific screen by ID
uploadImage(filePath, opts?)Promise<Screen[]>Upload an image file and create a screen 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"

uploadImage supported formats: .png .jpg .jpeg .webp

DesignSystem Class

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

Screen Class

MethodReturnsDescription
getHtml()Promise<string>Get the screen's HTML download URL
getImage()Promise<string>Get the screen's screenshot download URL
edit(prompt, deviceType?, modelId?)Promise<Screen>Edit the screen using a text prompt
variants(prompt, options, deviceType?, modelId?)Promise<Screen[]>Generate variants of the screen

modelId: "GEMINI_3_PRO" | "GEMINI_3_FLASH"

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)
baseUrlMCP server URL (default: https://stitch.googleapis.com/mcp)
timeoutRequest timeout in ms (default: 300000)

来自 google-labs-code 的更多技能

remotion
google-labs-code
使用Remotion从Stitch应用设计创建专业演示视频,包含流畅转场和文字叠加。从Stitch项目中获取屏幕画面,编排成Remotion视频合成,支持缩放效果、淡入淡出转场和上下文文字叠加。支持模块化组件架构,包含ScreenSlide和WalkthroughComposition组件,以及交互式热点和画外音集成等高级功能。生成屏幕清单,下载...
official
ink
google-labs-code
用于 json-render 的 Ink 终端渲染器,可将 JSON 规范转换为交互式终端用户界面。在使用 @json-render/ink 构建终端用户界面时使用。
official
stitch-sdk-pipeline
google-labs-code
运行完整的Stitch SDK生成流水线。当添加新工具或需要从头到尾重新生成SDK时使用。
official
stitch-sdk-readme
google-labs-code
为Stitch SDK生成或更新README。使用Bookstore Test结构,并从代码库中获取当前API。在README需要…时使用。
official
typed-service-contracts
google-labs-code
Architecture standard for building robust, type-safe TypeScript services using the "Spec and Handler" pattern. Use when building CLIs, libraries, or complex…
official
agent-dx-cli-scale
google-labs-code
一种评分量表,用于根据“为AI代理重写你的CLI”原则评估CLI为AI代理设计的优劣程度。
official
ink
google-labs-code
Ink terminal renderer for json-render that turns JSON specs into interactive terminal UIs. Use when working with @json-render/ink, building terminal UIs from…
official
stitch-sdk-bug-bash
google-labs-code
使用真实API密钥查找Stitch SDK中的错误。涵盖标准功能边界和棘手情况。
official