关于 stitch-sdk-usage
用于 Google Stitch AI UI 生成服务的 TypeScript SDK。开发者可创建项目、生成或编辑屏幕、管理设计系统、获取 HTML 和图像,并访问 Stitch MCP 工具。
主要功能
- 01根据文本提示生成屏幕
- 02编辑屏幕并生成变体
- 03上传图像资源创建屏幕
- 04获取 HTML、图像和下载 URL
- 05管理项目与设计系统
- 06发现并调用 MCP 工具
适用场景
- 01根据文字需求生成 UI 屏幕
- 02修改屏幕或探索设计变体
- 03从本地样稿创建屏幕
- 04让 Agent 发现并调用 Stitch 工具
MCP 相关
SDK 内含 StitchToolClient,可连接 Stitch MCP 服务、发现工具并以 JSON 参数调用。也可通过 Stitch 单例访问 MCP 工具。
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ google-labs-code/ stitch-sdk --skill stitch-sdk-usage安装后在 Claude Code 中输入/stitch-sdk-usage确认已加载。
详细介绍
使用 Stitch SDK
Stitch SDK 为 Google Stitch 提供 TypeScript 接口。这是一项由 AI 驱动的 UI 生成服务。
安装
npm install @google/stitch-sdk
环境变量
export STITCH_API_KEY="your-api-key"
快速入门
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)
stitch 单例会从环境中读取 STITCH_API_KEY,并在首次使用时建立连接——无需编写设置代码。
使用项目
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" });
设计系统
// 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;
上传图像
上传现有图像文件(PNG、JPG、JPEG、WEBP),直接根据模型图或素材创建屏幕。
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)
该方法会从磁盘读取文件,并将其直接发送到 Stitch REST API——不受输出令牌数量限制(与由 Agent 驱动的 MCP 调用不同)。
支持的格式: .png、.jpg、.jpeg、.webp
选项:
| 选项 | 类型 | 默认值 | 描述 |
|---|---|---|---|
title | string | — | 所创建屏幕的显示标题 |
createScreenInstances | boolean | true | 是否将屏幕添加到画布 |
抛出 带有以下代码的 StitchError:NOT_FOUND(未找到文件)、UNKNOWN_ERROR(格式不受支持或上传失败)、AUTH_FAILED(API 密钥无效)。
生成和迭代屏幕
// 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
获取屏幕素材
// 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 访问器会在可用时使用生成响应中的缓存数据,并将获取的响应写回缓存。缺少素材时会抛出代码为 NOT_FOUND 的 StitchError(绝不会静默返回空字符串)。
动态工具客户端(适用于 Agent)
对于将 JSON 负载转发给 MCP 工具的 Agent 和编排脚本:
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();
错误处理
所有 SDK 方法在失败时都会抛出 StitchError。请使用 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
}
}
错误代码:AUTH_FAILED、NOT_FOUND、PERMISSION_DENIED、RATE_LIMITED、NETWORK_ERROR、VALIDATION_ERROR、CLARIFICATION_REQUIRED、UNKNOWN_ERROR
CLARIFICATION_REQUIRED 错误可恢复:generate()/edit()/variants() 收到的是问题,而不是屏幕。读取 e.clarification.question / e.clarification.suggestions,然后使用能够回答该问题的提示词再次调用同一方法。
API 参考
Stitch 类
| 方法 | 返回值 | 描述 |
|---|---|---|
createProject(options?) | Promise<Project> | 创建新项目(options.title) |
projects() | Promise<Project[]> | 列出所有项目 |
project(id) | Project | 按 ID 引用项目(不进行网络调用) |
项目类
| 方法 | 返回值 | 说明 |
|---|---|---|
generate(prompt, options?) | Promise<Generation<Screen>> | 生成屏幕 — .screens、.first、.raw(options.deviceType、options.modelId) |
screens() | Promise<Screen[]> | 列出项目中的所有屏幕 |
getScreen(screenId) | Promise<Screen> | 按 ID 获取指定屏幕 |
upload(filePath, opts?) | Promise<Screen[]> | 上传图像/HTML 文件并据此创建屏幕 |
createDesignSystem(designSystem) | Promise<DesignSystem> | 为此项目创建设计系统 |
listDesignSystems() | Promise<DesignSystem[]> | 列出所有设计系统 |
designSystem(id) | DesignSystem | 按 ID 引用(不调用 API) |
deviceType:"MOBILE" | "DESKTOP" | "TABLET" | "AGNOSTIC"
upload 支持的格式:.png .jpg .jpeg .webp .html
设计系统类
| 方法 | 返回值 | 说明 |
|---|---|---|
update(designSystem) | Promise<DesignSystem> | 更新设计系统的主题 |
apply(selectedScreenInstances) | Promise<Generation<Screen>> | 将此设计系统应用于屏幕(.screens) |
屏幕类
| 方法 | 返回值 | 说明 |
|---|---|---|
getHtml() | Promise<string> | 获取屏幕的 HTML 内容 |
getImage() | Promise<Uint8Array> | 获取屏幕截图字节 |
getHtmlUrl() / getImageUrl() | Promise<string> | 带签名的下载 URL(支持缓存) |
edit(prompt, options?) | Promise<Generation<Screen>> | 使用文本提示词编辑屏幕 |
variants(prompt, variantOptions, options?) | Promise<Generation<Screen>> | 生成屏幕的变体 |
modelId:"GEMINI_3_8_FLASH" | "GEMINI_3_5_FLASH_LITE"(可选,默认为后端默认值)
StitchToolClient(供 Agent 使用)
| 方法 | 返回值 | 说明 |
|---|---|---|
callTool(name, args) | Promise<T> | 按名称调用任意 MCP 工具 |
listTools() | Promise<Tools> | 发现可用工具 |
connect() | Promise<void> | 建立 MCP 连接(由 callTool 自动调用) |
close() | Promise<void> | 关闭连接 |
显式配置
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 服务 URL(默认值:https://stitch.googleapis.com/mcp) |
timeout | — | 请求超时时间,单位为 ms(默认值:300000) |