stitch-sdk-usage

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Using the Stitch SDK

使用Stitch SDK

The Stitch SDK provides a TypeScript interface for Google Stitch, an AI-powered UI generation service.
Stitch SDK为Google Stitch(一款AI驱动的UI生成服务)提供TypeScript接口。

Installation

安装

bash
npm install @google/stitch-sdk
bash
npm install @google/stitch-sdk

Environment Variables

环境变量

bash
export STITCH_API_KEY="your-api-key"
bash
export STITCH_API_KEY="your-api-key"

Quick Start

快速开始

typescript
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.
typescript
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();     // HTML的下载链接
const imageUrl = await screen.getImage(); // 截图的下载链接
stitch
单例会从环境中读取
STITCH_API_KEY
,并在首次使用时自动连接——无需额外的设置代码。

Working with Projects

项目操作

typescript
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");
typescript
import { stitch } from '@google/stitch-sdk';

// 列出所有项目
const projects = await stitch.projects();

// 通过ID引用项目(无网络请求)
const project = stitch.project("4044680601076201931");

// 创建新项目
const newProject = await stitch.createProject("My App");

Generating and Iterating on Screens

界面生成与迭代

typescript
// 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"],
});
typescript
// 从文本提示生成新界面
const screen = await project.generate("Login page with email and password fields");

// 编辑现有界面
const edited = await screen.edit("Make the background dark and add a subtitle");

// 生成界面变体
const variants = await screen.variants("Try different color schemes", {
  variantCount: 2,
  creativeRange: "EXPLORE",
  aspects: ["COLOR_SCHEME", "LAYOUT"],
});

Retrieving Screen Assets

获取界面资源

typescript
// 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.
typescript
// 获取界面HTML的下载链接
const html = await screen.getHtml();

// 获取界面截图的下载链接
const imageUrl = await screen.getImage();
两种方法会优先使用生成响应中的缓存数据,必要时才会发起API请求。

Dynamic Tool Client (for agents)

动态工具客户端(适用于Agent)

For agents and orchestration scripts that forward JSON payloads to MCP tools:
typescript
import { StitchToolClient } from '@google/stitch-sdk';

const client = new StitchToolClient(); // reads STITCH_API_KEY from env
const tools = await client.listTools();
const result = await client.callTool("generate_screen_from_text", {
  projectId: "123", prompt: "A login page"
});
await client.close();
对于需要将JSON负载转发到MCP工具的Agent和编排脚本:
typescript
import { StitchToolClient } from '@google/stitch-sdk';

const client = new StitchToolClient(); // 从环境中读取STITCH_API_KEY
const tools = await client.listTools();
const result = await client.callTool("generate_screen_from_text", {
  projectId: "123", prompt: "A login page"
});
await client.close();

Error Handling

错误处理

All SDK methods throw
StitchError
on failure. Use try/catch:
typescript
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
所有SDK方法在失败时都会抛出
StitchError
。请使用try/catch进行处理:
typescript
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"等
    console.log(e.message);     // 易读的错误描述
    console.log(e.recoverable); // 是否重试可能成功
  }
}
错误码:
AUTH_FAILED
,
NOT_FOUND
,
PERMISSION_DENIED
,
RATE_LIMITED
,
NETWORK_ERROR
,
VALIDATION_ERROR
,
UNKNOWN_ERROR

API Reference

API参考

Stitch Class

Stitch类

MethodReturnsDescription
createProject(title)
Promise<Project>
Create a new project
projects()
Promise<Project[]>
List all projects
project(id)
Project
Reference a project by ID (no network call)
方法返回值描述
createProject(title)
Promise<Project>
创建新项目
projects()
Promise<Project[]>
列出所有项目
project(id)
Project
通过ID引用项目(无网络请求)

Project Class

Project类

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
deviceType
:
"MOBILE"
|
"DESKTOP"
|
"TABLET"
|
"AGNOSTIC"
方法返回值描述
generate(prompt, deviceType?)
Promise<Screen>
从文本提示生成界面
screens()
Promise<Screen[]>
列出项目中的所有界面
getScreen(screenId)
Promise<Screen>
通过ID获取指定界面
deviceType
:
"MOBILE"
|
"DESKTOP"
|
"TABLET"
|
"AGNOSTIC"

Screen Class

Screen类

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"
方法返回值描述
getHtml()
Promise<string>
获取界面HTML的下载链接
getImage()
Promise<string>
获取界面截图的下载链接
edit(prompt, deviceType?, modelId?)
Promise<Screen>
使用文本提示编辑界面
variants(prompt, options, deviceType?, modelId?)
Promise<Screen[]>
生成界面变体
modelId
:
"GEMINI_3_PRO"
|
"GEMINI_3_FLASH"

StitchToolClient (for agents)

StitchToolClient(适用于Agent)

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
方法返回值描述
callTool(name, args)
Promise<T>
通过名称调用任意MCP工具
listTools()
Promise<Tools>
发现可用工具
connect()
Promise<void>
建立MCP连接(
callTool
会自动调用)
close()
Promise<void>
关闭连接

Explicit Configuration

显式配置

typescript
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
apiKey
STITCH_API_KEY
API key for authentication
accessToken
STITCH_ACCESS_TOKEN
OAuth access token
projectId
GOOGLE_CLOUD_PROJECT
GCP project ID (required with OAuth)
baseUrl
MCP server URL (default:
https://stitch.googleapis.com/mcp
)
timeout
Request timeout in ms (default: 300000)
typescript
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();
选项环境变量描述
apiKey
STITCH_API_KEY
用于身份验证的API密钥
accessToken
STITCH_ACCESS_TOKEN
OAuth访问令牌
projectId
GOOGLE_CLOUD_PROJECT
GCP项目ID(使用OAuth时必填)
baseUrl
MCP服务器地址(默认:
https://stitch.googleapis.com/mcp
timeout
请求超时时间(毫秒,默认:300000)