### Generate a UI Screen Source: https://github.com/google-labs-code/stitch-sdk/blob/main/packages/sdk/README.md Quick start example to set the API key, create a project, generate a screen from a text prompt, and retrieve its HTML and image URLs. ```typescript import { stitch } from "@google/stitch-sdk"; // STITCH_API_KEY must be set in the environment const project = await stitch.createProject("My App"); const screen = await project.generate( "A login page with email and password fields", ); const html = await screen.getHtml(); const imageUrl = await screen.getImage(); ``` -------------------------------- ### Install Dependencies Source: https://github.com/google-labs-code/stitch-sdk/blob/main/CONTRIBUTING.md Install project dependencies using Bun. ```bash bun install ``` -------------------------------- ### start(transport: Transport): Promise Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/proxy-server.md Connects to Stitch and starts the proxy server on the provided transport. This method initializes the Stitch connection and begins listening for incoming MCP requests. ```APIDOC ## start(transport: Transport): Promise ### Description Connects to Stitch and starts the proxy server on the provided transport. This method initializes the Stitch connection and begins listening for incoming MCP requests. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **transport** (Transport) - Required - The MCP transport to use (e.g., `StdioServerTransport`, `SSEServerTransport`). ### Behavior 1. Logs `[stitch-proxy] Connecting to ${url}...` to stderr. 2. Initializes connection to Stitch MCP server. 3. Connects the local MCP server to the transport. 4. Logs `[stitch-proxy] Proxy server running` to stderr. ### Throws Error if connection to Stitch fails (e.g., invalid credentials, network error). ### Request Example ```typescript import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; // Assuming 'proxy' is an instance of StitchProxy const transport = new StdioServerTransport(); await proxy.start(transport); ``` ``` -------------------------------- ### Install Stitch SDK Source: https://github.com/google-labs-code/stitch-sdk/blob/main/README.md Installs the Stitch SDK using npm. For Vercel AI SDK integration, also install the 'ai' package. ```bash npm install @google/stitch-sdk ``` ```bash npm install @google/stitch-sdk ai ``` -------------------------------- ### StitchProxy start Method Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/API-OVERVIEW.md Starts the Stitch proxy server. Requires a Transport object. ```typescript start(transport: Transport) ``` -------------------------------- ### Start MCP Proxy with StdioServerTransport Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/INDEX.md This code initializes and starts a `StitchProxy` using a `StdioServerTransport`. It's suitable for custom MCP servers, tool forwarding, and applications like Claude Desktop. ```typescript import { StitchProxy } from "@google/stitch-sdk"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; const proxy = new StitchProxy({ apiKey: "..." }); await proxy.start(new StdioServerTransport()); ``` -------------------------------- ### StitchToolClient Initialization with API Key Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/types.md Example of initializing StitchToolClient using an API key and a custom base URL. Ensure the apiKey is provided for authentication. ```typescript const client = new StitchToolClient({ apiKey: "your-key", baseUrl: "https://custom-stitch.example.com/mcp", timeout: 60000, }); ``` -------------------------------- ### Start StitchProxy with Transport Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/proxy-server.md Starts the StitchProxy server, connecting to Stitch and listening for incoming MCP requests on the specified transport. Ensure the transport is correctly initialized before calling this method. ```typescript import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; const transport = new StdioServerTransport(); await proxy.start(transport); // Proxy now forwards all MCP requests to Stitch ``` -------------------------------- ### Basic Setup with API Key Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/configuration.md Configure the Stitch SDK using an API key. The API key is automatically read from the environment variable STITCH_API_KEY. ```typescript import { stitch } from "@google/stitch-sdk"; // STITCH_API_KEY is read from env automatically const projects = await stitch.projects(); ``` ```dotenv STITCH_API_KEY=your-api-key-here ``` -------------------------------- ### OAuth Setup Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/configuration.md Configure the Stitch SDK for authentication using OAuth. Requires OAUTH_TOKEN and GCP_PROJECT environment variables. ```typescript import { Stitch, StitchToolClient } from "@google/stitch-sdk"; const client = new StitchToolClient({ accessToken: process.env.OAUTH_TOKEN, projectId: process.env.GCP_PROJECT, }); const sdk = new Stitch(client); const projects = await sdk.projects(); ``` ```dotenv STITCH_ACCESS_TOKEN=your-oauth-token GOOGLE_CLOUD_PROJECT=my-gcp-project ``` -------------------------------- ### Import Reference Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/MANIFEST.txt Guide to importing modules and components from the Stitch SDK package. ```APIDOC ## Import Reference ### Main Entry Point ```typescript import * as stitch from "@google/stitch-sdk"; ``` ### Subpaths ```typescript import "@google/stitch-sdk/ai"; import "@google/stitch-sdk/adk"; ``` ### CommonJS Compatibility - The package is compatible with CommonJS environments. ``` -------------------------------- ### StitchProxy Constructor Example Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/proxy-server.md Instantiate StitchProxy with configuration options like API key, name, and version. This is useful for setting up the proxy server with specific parameters. ```typescript import { StitchProxy } from "@google/stitch-sdk"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; const proxy = new StitchProxy({ apiKey: "your-api-key", name: "my-stitch-proxy", version: "1.0.0", }); const transport = new StdioServerTransport(); await proxy.start(transport); ``` -------------------------------- ### Agent with Context Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/adk-adapter.md Configure an `LlmAgent` with custom context, including a `systemPrompt`, to guide its behavior and expertise. ```typescript const agent = new LlmAgent({ name: "Designer", model: "gemini-2.5-pro", instruction: "Design mobile app screens", tools: stitchAdkTools(), context: { systemPrompt: "You are expert at UI/UX design.", }, }); ``` -------------------------------- ### StitchProxy with Stdio Transport Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/proxy-server.md Example of using StitchProxy with StdioServerTransport, suitable for Claude Desktop or CLI environments. It configures the proxy with an API key and starts it using the stdio transport. ```typescript import { StitchProxy } from "@google/stitch-sdk"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; async function main() { const proxy = new StitchProxy({ apiKey: process.env.STITCH_API_KEY, }); const transport = new StdioServerTransport(); await proxy.start(transport); } main().catch(console.error); ``` -------------------------------- ### StitchToolClient Initialization with OAuth Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/types.md Example of initializing StitchToolClient using an OAuth access token and a Google Cloud project ID. This method is used for authenticated access via OAuth. ```typescript const client = new StitchToolClient({ accessToken: "access-token", projectId: "my-gcp-project", }); ``` -------------------------------- ### Schema Cleaning Example Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/adk-adapter.md Demonstrates how the `cleanSchema()` function resolves `$ref` references and removes incompatible fields like `$defs` and `x-google-*` extensions. ```typescript // Before { type: "object", properties: { designSystem: { $ref: "#/$defs/DesignSystemInput" } }, $defs: { DesignSystemInput: { type: "object", properties: { colorMode: { type: "string" } } } } } // After (cleaned) { type: "object", properties: { designSystem: { type: "object", properties: { colorMode: { type: "string" } } } } } ``` -------------------------------- ### StitchToolClient Usage Source: https://github.com/google-labs-code/stitch-sdk/blob/main/packages/sdk/README.md Example of how to use the StitchToolClient for agents and orchestration scripts to interact with MCP tools. ```APIDOC ## StitchToolClient For agents and orchestration scripts that need direct MCP tool access: ```ts import { StitchToolClient } from "@google/stitch-sdk"; const client = new StitchToolClient({ apiKey: "your-api-key" }); // List available tools const { tools } = await client.listTools(); for (const tool of tools) { console.log(tool.name, tool.description); } // Call a tool directly — returns are now strongly typed! import { CreateProjectResponse } from "@google/stitch-sdk"; const result = await client.callTool("create_project", { title: "Agent Project", }); console.log(result.project?.projectId); await client.close(); ``` The client auto-connects on the first `callTool` or `listTools` call. No explicit `connect()` needed. All tool responses and input parameters are strictly typed and exported from the SDK. ``` -------------------------------- ### List, Get, and Generate Projects and Screens with Domain API Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/INDEX.md Use the high-level Domain API for synchronous project and screen operations. This is ideal for applications requiring straightforward interaction with project and screen data. ```typescript import { stitch } from "@google/stitch-sdk"; // List projects const projects = await stitch.projects(); // Get a project const project = stitch.project("my-project-id"); // Generate a screen const screen = await project.generate("A login page"); // Get HTML and image const html = await screen.getHtml(); const imageUrl = await screen.getImage(); ``` -------------------------------- ### Stitch SDK Data Flow Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/INDEX.md Illustrates the data flow within the Stitch SDK, starting from adapter functions like stitchTools() or stitchAdkTools() and progressing through client instantiation and server communication. ```text stitchTools() / stitchAdkTools() ↓ getOrCreateClient() [singleton] ↓ StitchToolClient ↓ callTool() [MCP] or httpPost() [REST] ↓ Stitch MCP Server ``` -------------------------------- ### Use the stitch Singleton Source: https://github.com/google-labs-code/stitch-sdk/blob/main/README.md Access the pre-configured stitch singleton instance for immediate use without explicit setup. It automatically reads the API key from the environment. ```ts import { stitch } from "@google/stitch-sdk"; // No setup needed — just use it const projects = await stitch.projects(); ``` -------------------------------- ### Initialize and Use StitchToolClient Source: https://github.com/google-labs-code/stitch-sdk/blob/main/packages/sdk/README.md Demonstrates how to initialize the StitchToolClient, list available tools, and call a tool with strongly typed responses. The client auto-connects on the first call. ```typescript import { StitchToolClient } from "@google/stitch-sdk"; const client = new StitchToolClient({ apiKey: "your-api-key" }); // List available tools const { tools } = await client.listTools(); for (const tool of tools) { console.log(tool.name, tool.description); } // Call a tool directly — returns are now strongly typed! import { CreateProjectResponse } from "@google/stitch-sdk"; const result = await client.callTool("create_project", { title: "Agent Project", }); console.log(result.project?.projectId); await client.close(); ``` -------------------------------- ### Manage Code Style Source: https://github.com/google-labs-code/stitch-sdk/blob/main/CONTRIBUTING.md Check or fix code formatting using Prettier. ```bash npm run format:check # check formatting npx prettier --write . # fix formatting ``` -------------------------------- ### Initialize StitchProxy Source: https://github.com/google-labs-code/stitch-sdk/blob/main/README.md Set up a StitchProxy to forward requests to Stitch. Requires an API key and a transport mechanism like StdioServerTransport. ```ts import { StitchProxy } from "@google/stitch-sdk"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; const proxy = new StitchProxy({ apiKey: "..." }); const transport = new StdioServerTransport(); await proxy.start(transport); ``` -------------------------------- ### Project.screens() Source: https://github.com/google-labs-code/stitch-sdk/blob/main/README.md Lists all screens within the current project. ```APIDOC ## Project.screens() ### Description Lists all screens in the project. ### Method (Implicitly called by SDK) ### Parameters None ### Returns `Promise` - A promise that resolves to an array of Screen objects. ``` -------------------------------- ### Get Project Reference by ID Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/stitch-main-api.md Get a reference to a project by its ID without making an immediate API call. The returned `Project` object can then be used to call methods like `screens()` or `generate()`. ```typescript const project = stitch.project("4044680601076201931"); const screens = await project.screens(); // API call happens here ``` -------------------------------- ### designSystem Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/project-class.md Gets a reference to a design system by its ID without making an API call. ```APIDOC ## designSystem ### Description Get a reference to a design system by ID without making an API call. ### Method Signature `designSystem(id: string): DesignSystem` ### Parameters #### Parameters - **id** (string) - Required - Design system asset ID ### Return Type DesignSystem — Design system handle (no API call) ### Example ```typescript const system = project.designSystem("asset-id"); await system.update({ colorMode: "DARK" }); ``` ``` -------------------------------- ### Project.listDesignSystems() Source: https://github.com/google-labs-code/stitch-sdk/blob/main/README.md Lists all design systems associated with the project. ```APIDOC ## Project.listDesignSystems() ### Description Lists all design systems in the project. ### Method (Implicitly called by SDK) ### Parameters None ### Returns `Promise` - A promise that resolves to an array of DesignSystem objects. ``` -------------------------------- ### Build Fife Suffix for Image Resizing Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/types.md Demonstrates how to use the buildFifeSuffix function to append image resizing parameters to a URL. Ensure the SDK is imported before use. ```typescript import { buildFifeSuffix } from "@google/stitch-sdk"; const imageUrl = "https://lh3.googleusercontent.com/..."; const suffix = buildFifeSuffix({ width: 780, height: 1200 }); const resizedUrl = imageUrl + suffix; // "...=w780-h1200" ``` -------------------------------- ### Get Specific Tool Information Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/API-OVERVIEW.md Access detailed information about a specific tool using its name. This includes its schema and parameters. ```typescript // Get info on specific tool const toolInfo = stitch.toolMap.get("generate_screen_from_text"); ``` -------------------------------- ### Project.generate(prompt, deviceType?) Source: https://github.com/google-labs-code/stitch-sdk/blob/main/README.md Generates a new screen within the project based on a text prompt and an optional device type. ```APIDOC ## Project.generate(prompt, deviceType?) ### Description Generates a screen from a text prompt. You can optionally specify the target device type. ### Method (Implicitly called by SDK) ### Parameters * **prompt** (string) - Required - The text description to generate the screen from. * **deviceType** (DeviceType) - Optional - The type of device for which to generate the screen. Possible values: "MOBILE", "DESKTOP", "TABLET", "AGNOSTIC". ### Returns `Promise` - A promise that resolves to the generated Screen object. ``` -------------------------------- ### Generate UI Screen from Prompt Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/project-class.md Generates a new UI screen based on a text description. Specify the device type and LLM model for customization. Requires the project ID to be initialized. ```typescript const project = stitch.project("my-project-id"); const screen = await project.generate( "A login page with email and password fields", "MOBILE" ); const html = await screen.getHtml(); const imageUrl = await screen.getImage(); ``` -------------------------------- ### Get All Stitch Tools for ADK Source: https://github.com/google-labs-code/stitch-sdk/blob/main/README.md Retrieve all available Stitch tools formatted for use with the ADK. These tools can then be passed to ADK agents. ```typescript import { stitchAdkTools } from "@google/stitch-sdk/adk"; import { LlmAgent } from "@google/adk"; // Get all Stitch tools formatted as ADK FunctionTools const tools = stitchAdkTools(); // You can now pass these tools to your ADK agents const designerAgent = new LlmAgent({ name: "Designer", model: "gemini-2.5-pro", instruction: "You are a designer. Create a project and generate a screen.", tools, }); ``` -------------------------------- ### Stitch Class - Main Entry Point Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/MANIFEST.txt Details on the Stitch class, which serves as the main entry point for the SDK, including methods for project management and accessing a pre-configured singleton instance. ```APIDOC ## Stitch Class ### Description The main entry point for the Stitch SDK, providing access to projects and a singleton instance. ### Methods - **projects(): Promise** - Lists all available projects. - **createProject(name: string): Promise** - Creates a new project. - **project(id: string): Project** - Retrieves a project instance by its ID. ### Singleton Instance - **stitch**: Stitch - A pre-configured, globally accessible instance of the Stitch class. ``` -------------------------------- ### High-Level Domain API Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/INDEX.md Provides methods for listing and getting projects, and generating screens. Ideal for synchronous project/screen operations in applications. ```APIDOC ## High-Level Domain API ### Description Provides methods for listing and getting projects, and generating screens. ### Methods #### `stitch.projects()` - **Description**: Lists all available projects. - **Returns**: A promise that resolves to a list of projects. #### `stitch.project(projectId)` - **Description**: Retrieves a specific project by its ID. - **Parameters**: - `projectId` (string) - Required - The ID of the project to retrieve. - **Returns**: A promise that resolves to the project object. #### `project.generate(prompt)` - **Description**: Generates a new screen based on the provided prompt. - **Parameters**: - `prompt` (string) - Required - A description of the screen to generate. - **Returns**: A promise that resolves to the generated screen object. #### `screen.getHtml()` - **Description**: Retrieves the HTML representation of a screen. - **Returns**: A promise that resolves to the HTML string. #### `screen.getImage()` - **Description**: Retrieves the image URL of a screen. - **Returns**: A promise that resolves to the image URL string. ``` -------------------------------- ### Node.js Version Requirement Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/INDEX.md Specifies the minimum required Node.js version for the project. Ensure your Node.js environment meets this requirement before installation or development. ```json // package.json "engines": { "node": ">=18" } ``` -------------------------------- ### Create a Project Source: https://github.com/google-labs-code/stitch-sdk/blob/main/README.md Creates a new project using the stitch tool client. This is useful if you need to set up a project before generating screens. ```typescript const result = await stitch.callTool("create_project", { title: "My App" }); ``` -------------------------------- ### Get Screen Image Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/API-OVERVIEW.md Retrieve the image representation of a UI screen. This method uses cached data or calls the get_screen MCP tool. ```typescript getImage() ``` -------------------------------- ### Get Screen HTML Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/API-OVERVIEW.md Retrieve the HTML content of a UI screen. This method uses cached data or calls the get_screen MCP tool. ```typescript getHtml() ``` -------------------------------- ### Create Project Design System Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/project-class.md Creates a new design system (visual theme) for the project, defining aspects like color mode, font, and custom colors. Requires a DesignSystemInput object. ```typescript const designSystem = await project.createDesignSystem({ colorMode: "LIGHT", font: "INTER", customColor: "#FF5733", }); ``` -------------------------------- ### Get or Create StitchToolClient Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/utilities.md Provides the signature for the getOrCreateClient function, which retrieves or initializes a shared StitchToolClient instance. It's primarily for internal use. ```typescript function getOrCreateClient(config?: { apiKey?: string }): StitchToolClient ``` -------------------------------- ### buildFifeSuffix Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/utilities.md Build a FIFE URL sizing suffix from options. Builds a FIFE (Fast Image Fetch Engine) sizing parameter for Google-hosted images. FIFE supports dynamic resizing by appending sizing parameters to the base URL. ```APIDOC ## buildFifeSuffix ### Description Build a FIFE URL sizing suffix from options. ### Method ```typescript function buildFifeSuffix(options?: FifeImageOptions): string ``` ### Parameters #### Query Parameters - **options** (FifeImageOptions) - Optional - Image sizing options - **width** (number) - Requested width in pixels - **height** (number) - Requested height in pixels ### Return Type string — Sizing suffix like `"=w780"`, `"=h1200"`, `"=w780-h1200"`, or `""` if no options ### Behavior Builds a FIFE (Fast Image Fetch Engine) sizing parameter for Google-hosted images. FIFE supports dynamic resizing by appending sizing parameters to the base URL. ### Examples ```typescript import { buildFifeSuffix } from "@google/stitch-sdk"; const imageUrl = "https://lh3.googleusercontent.com/..."; buildFifeSuffix({ width: 780 }) // → "=w780" buildFifeSuffix({ height: 1200 }) // → "=h1200" buildFifeSuffix({ width: 780, height: 1200 }) // → "=w780-h1200" buildFifeSuffix({}) // → "" buildFifeSuffix() // → "" // Usage const resizedUrl = imageUrl + buildFifeSuffix({ width: 780 }); // → "https://lh3.googleusercontent.com/...=w780" ``` ``` -------------------------------- ### List Projects and Screens Source: https://github.com/google-labs-code/stitch-sdk/blob/main/README.md Fetches all projects and iterates through them to log project IDs and the number of screens associated with each. Requires importing the stitch SDK. ```typescript import { stitch } from "@google/stitch-sdk"; const projects = await stitch.projects(); for (const project of projects) { console.log(project.id, project.projectId); const screens = await project.screens(); console.log(` ${screens.length} screens`); } ``` -------------------------------- ### stitch Singleton Usage Source: https://github.com/google-labs-code/stitch-sdk/blob/main/README.md Demonstrates the usage of the pre-configured `stitch` singleton instance for accessing Stitch projects. ```APIDOC ## `stitch.projects()` ### Description Retrieves a list of Stitch projects. The `stitch` singleton is pre-configured and reads `STITCH_API_KEY` from the environment, initializing lazily on first use. ### Method `projects` ### Response #### Success Response (200) - **Project[]** (array) - An array of Stitch project objects. ``` -------------------------------- ### generate Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/project-class.md Generates a new UI screen from a text prompt. Supports specifying device type and the LLM model to use. ```APIDOC ## generate ### Description Generate a new UI screen from a text prompt. ### Method Signature `generate(prompt: string, deviceType?: DeviceType, modelId?: ModelId): Promise` ### Parameters #### Parameters - **prompt** (string) - Required - Text description of the screen to generate - **deviceType** (DeviceType) - Optional - Target device type. Allowed values: "DEVICE_TYPE_UNSPECIFIED", "MOBILE", "DESKTOP", "TABLET", "AGNOSTIC". Defaults to "DEVICE_TYPE_UNSPECIFIED". - **modelId** (ModelId) - Optional - LLM model to use. Allowed values: "MODEL_ID_UNSPECIFIED", "GEMINI_3_PRO", "GEMINI_3_FLASH", "GEMINI_3_1_PRO". Defaults to "MODEL_ID_UNSPECIFIED". ### Return Type Promise — Generated Screen instance with HTML and image available ### Throws StitchError on generation failure ### Example ```typescript const project = stitch.project("my-project-id"); const screen = await project.generate( "A login page with email and password fields", "MOBILE" ); const html = await screen.getHtml(); const imageUrl = await screen.getImage(); ``` ``` -------------------------------- ### Introspect a Specific Tool Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/INDEX.md Get detailed information about a specific tool, including its name, parameters, and whether each parameter is required or optional. This requires the tool's identifier. ```typescript const toolInfo = stitch.toolMap.get("generate_screen_from_text"); if (toolInfo) { console.log(`Tool: ${toolInfo.name}`); for (const param of toolInfo.params) { console.log(` - ${param.name}: ${param.type} (${param.required ? "required" : "optional"})`); } } ``` -------------------------------- ### Stitch.project(id: string) Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/stitch-main-api.md Get a reference to a project by ID without making an API call. The returned Project can then call methods like `screens()`, `generate()`, etc. ```APIDOC ## GET /projects/{id} ### Description Get a reference to a project by ID. This method does not make an API call itself; the returned Project object can be used to interact with the project. ### Method GET ### Endpoint /projects/{id} ### Parameters #### Path Parameters - **id** (string) - Required - Bare project ID (e.g. "4044680601076201931") ### Request Example ```json {} ``` ### Response #### Success Response (200) - **project** (Project) - Project handle (no API call) #### Response Example ```json { "project": { "projectId": "4044680601076201931", "data": { "name": "Example Project" } } } ``` ``` -------------------------------- ### Resolve Entity with Referential Equality Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/utilities.md Use `resolve` to get an entity instance from the cache, ensuring referential equality for the same resource ID. This is primarily used internally by the Stitch SDK. ```typescript const project1 = client.entities.resolve(Project, ["projectId"], { projectId: "123" }); const project2 = client.entities.resolve(Project, ["projectId"], { projectId: "123" }); project1 === project2; // true (same instance) ``` -------------------------------- ### Screen Class Properties and Methods Source: https://github.com/google-labs-code/stitch-sdk/blob/main/packages/sdk/README.md Reference for the `Screen` class, representing a generated UI screen. ```APIDOC ### `Screen` A generated UI screen. Provides access to HTML and screenshots. | Property | Type | Description | | ----------- | -------- | -------------------- | | `id` | `string` | Alias for `screenId` | | `screenId` | `string` | Bare screen ID | | `projectId` | `string` | Parent project ID | | Method | Parameters | Returns | Description | | --------------------------------------------------------- | ------------------------------------------ | ------------------- | ---------------------------------------- | | `edit(prompt, deviceType?, modelId?)` | `prompt: string` | `Promise` | Edit the screen with a text prompt | | `variants(prompt, variantOptions, deviceType?, modelId?)` | `prompt: string`, `variantOptions: object` | `Promise` | Generate design variants | | `getHtml()` | — | `Promise` | Get the screen's HTML download URL | | `getImage()` | — | `Promise` | Get the screen's screenshot download URL | `getHtml()` and `getImage()` use cached data from the generation response when available. If the screen was loaded from `screens()` or `getScreen()`, they call the `get_screen` API automatically. `modelId`: `"GEMINI_3_PRO"` | `"GEMINI_3_FLASH"` ``` -------------------------------- ### Handle Stitch SDK Errors Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/INDEX.md Use a try-catch block to handle potential StitchErrors. This example demonstrates handling specific error codes like AUTH_FAILED, RATE_LIMITED, and NOT_FOUND. ```typescript import { stitch, StitchError, StitchErrorCode } from "@google/stitch-sdk"; try { const projects = await stitch.projects(); } catch (error) { if (error instanceof StitchError) { switch (error.code) { case "AUTH_FAILED": console.error("Invalid API key. Check STITCH_API_KEY"); break; case "RATE_LIMITED": // Retry with backoff break; case "NOT_FOUND": console.error("Resource not found"); break; default: console.error(`${error.code}: ${error.message}`); } } } ``` -------------------------------- ### apply Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/design-system-class.md Applies the current design system to one or more screens. It takes an array of SelectedScreenInstance objects and returns a Promise resolving to an array of updated Screen instances. ```APIDOC ## apply ### Description Apply this design system to one or more screens. ### Method apply ### Parameters #### Request Body - **selectedScreenInstances** (SelectedScreenInstance[]) - Required - Array of {id: string, sourceScreen: string} objects Each object must have: - `id: string` — Screen instance ID - `sourceScreen: string` — Source screen reference ### Return Type Promise — Array of updated Screen instances ### Throws StitchError on apply failure ### Example ```typescript const project = stitch.project("my-project"); const screens = await project.screens(); // Get screen instances from project metadata const instances = project.data.screenInstances || []; const toUpdate = instances.slice(0, 3); // Apply to first 3 instances const system = project.designSystem("design-system-id"); const updated = await system.apply(toUpdate); ``` ``` -------------------------------- ### Initialize Stitch SDK with Explicit Configuration Source: https://github.com/google-labs-code/stitch-sdk/blob/main/README.md Instantiate the Stitch SDK client with explicit configuration options. Authentication requires either an API key or both an access token and project ID. ```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(); ``` -------------------------------- ### Download All Screens and Assets Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/INDEX.md Export all screens from a project to a specified directory. This includes options to set file permissions and a subdirectory for assets. ```typescript const result = await project.downloadAssets("./output", { fileMode: 0o644, assetsSubdir: "public", }); for (const screen of result.screens) { console.log(`${screen.screenId} → ${screen.filePath}`); } ``` -------------------------------- ### Get Design System Reference Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/project-class.md Obtains a reference to a design system by its ID without making an immediate API call. This handle can then be used for further operations like updating the design system. ```typescript const system = project.designSystem("asset-id"); await system.update({ colorMode: "DARK" }); ``` -------------------------------- ### Instantiate StitchToolClient and Call a Tool Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/stitch-tool-client.md Instantiate the client with an API key and timeout, then use it to call a tool and close the connection. Ensure your API key is valid. ```typescript import { StitchToolClient } from "@google/stitch-sdk"; const client = new StitchToolClient({ apiKey: "your-api-key", timeout: 60000, }); const result = await client.callTool("list_projects", {}); await client.close(); ``` -------------------------------- ### Get Specific Screen by ID Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/project-class.md Fetches a single screen from the project using its unique ID. This method is useful when you need to access or modify a particular screen. Throws an error if the screen is not found. ```typescript const screen = await project.getScreen("my-screen-id"); const html = await screen.getHtml(); ``` -------------------------------- ### List Available Tools Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/API-OVERVIEW.md Retrieve a list of all available tools. The response includes tool names and other metadata. ```typescript // Get all tools const { tools } = await stitch.listTools(); ``` -------------------------------- ### Configure StitchToolClient Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/configuration.md Instantiate StitchToolClient with constructor options. Authentication requires either an apiKey or both accessToken and projectId. ```typescript const client = new StitchToolClient({ apiKey: "your-api-key", accessToken: "oauth-token", projectId: "gcp-project-id", baseUrl: "https://stitch.googleapis.com/mcp", timeout: 300000, localVirtualTools: [], }); ``` -------------------------------- ### Retrieve Screen Image Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/screen-class.md Use the `getImage` method to get a download URL for the screen's screenshot. It prioritizes cached images from the generation response and falls back to fetching via the `get_screen` API. ```typescript const screen = await project.generate("A dashboard"); const imageUrl = await screen.getImage(); // imageUrl can be appended with FIFE sizing: imageUrl + "=w780-h1200" ``` -------------------------------- ### Call an MCP Tool Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/stitch-tool-client.md Use `callTool` to invoke a named MCP tool on the Stitch server. It handles authentication, connection, and error parsing. This example demonstrates listing projects and handling potential StitchErrors. ```typescript const client = new StitchToolClient(); try { const projects = await client.callTool("list_projects", {}); console.log(projects); } catch (error) { if (error instanceof StitchError) { console.error(`Error [${error.code}]: ${error.message}`); if (error.recoverable) { // Retry logic for RATE_LIMITED } } } ``` -------------------------------- ### Project.createDesignSystem(designSystem) Source: https://github.com/google-labs-code/stitch-sdk/blob/main/README.md Creates a design system for the project using the provided design system object. ```APIDOC ## Project.createDesignSystem(designSystem) ### Description Creates a design system for this project. ### Method (Implicitly called by SDK) ### Parameters * **designSystem** (object) - Required - The design system object to create. ### Returns `Promise` - A promise that resolves to the created DesignSystem object. ``` -------------------------------- ### Parse Google API Resource Name Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/utilities.md Extracts the last segment from a Google API resource name. If the input contains no slashes, it is returned as-is. Use this to get a bare ID from a full resource name. ```typescript import { parseResourceName } from "@google/stitch-sdk"; parseResourceName("projects/123/screens/abc") // → "abc" parseResourceName("projects/123") // → "123" parseResourceName("abc123") // → "abc123" parseResourceName("") // → "" ``` -------------------------------- ### Upload a Design File Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/INDEX.md Import a design from a file (e.g., PNG) into your project. This will create new screens based on the uploaded design. ```typescript const screens = await project.upload("./my-design.png", { title: "Imported Design", }); ``` -------------------------------- ### Configure stitchTools Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/configuration.md Initialize stitchTools with an API key and optionally specify which tools to include. Requires importing from '@google/stitch-sdk/ai'. ```typescript import { stitchTools } from "@google/stitch-sdk/ai"; const tools = stitchTools({ apiKey: "custom-key", include: ["create_project", "generate_screen_from_text"], }); ``` -------------------------------- ### Configure stitchAdkTools Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/configuration.md Initialize stitchAdkTools with an API key and optionally specify which tools to include. Requires importing from '@google/stitch-sdk/adk'. ```typescript import { stitchAdkTools } from "@google/stitch-sdk/adk"; const tools = stitchAdkTools({ apiKey: "custom-key", include: ["create_project", "get_screen"], }); ``` -------------------------------- ### Instantiate StitchToolClient Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/API-OVERVIEW.md Create a new instance of the StitchToolClient. Configuration is optional. ```typescript new StitchToolClient(config?: Partial) ``` -------------------------------- ### Run Project Tests Source: https://github.com/google-labs-code/stitch-sdk/blob/main/CONTRIBUTING.md Execute various test suites including unit tests, script tests, smoke tests, and lock file validation. ```bash # Unit tests npm run test # Script tests (IR schema, codegen) npm run test:scripts # Smoke test (packaging verification) npm run test:smoke # Lock validation npm run validate:generated ``` -------------------------------- ### screens Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/project-class.md Lists all screens within the project. ```APIDOC ## screens ### Description List all screens in the project. ### Method Signature `screens(): Promise` ### Return Type Promise — Array of Screen instances ### Throws StitchError if project not found or network error ### Example ```typescript const screens = await project.screens(); console.log(`Project has ${screens.length} screens`); for (const screen of screens) { console.log(` - ${screen.screenId}`); } ``` ``` -------------------------------- ### Using getOrCreateClient Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/utilities.md Shows how to import and use the getOrCreateClient function, optionally providing an API key for client initialization. This function returns a cached instance if the API key is unchanged. ```typescript import { getOrCreateClient } from "@google/stitch-sdk"; const client = getOrCreateClient({ apiKey: "..." }); ``` -------------------------------- ### StitchProxy Constructor Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/API-OVERVIEW.md Instantiates a new StitchProxy server. Configuration is optional. ```typescript new StitchProxy(config?: Partial) ``` -------------------------------- ### Initialize and use StitchToolClient Source: https://github.com/google-labs-code/stitch-sdk/blob/main/packages/sdk/README.md Use StitchToolClient for direct authenticated access to the Stitch MCP server. Ensure to close the client connection after use. ```typescript import { StitchToolClient, GetScreenResponse } from "@google/stitch-sdk"; const client = new StitchToolClient({ apiKey: "..." }); const result = await client.callTool("get_screen", { projectId: "...", screenId: "...", }); await client.close(); ``` -------------------------------- ### stitch.listTools() Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/stitch-main-api.md Lists all available tools that can be called via the StitchToolClient. ```APIDOC ## GET /tools ### Description Lists all available tools that can be called via the StitchToolClient. ### Method GET ### Endpoint /tools ### Parameters None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **tools** (object) - An object containing information about available tools. #### Response Example ```json { "tools": { "list_projects": { "description": "Lists all Stitch projects.", "params": [] }, "create_project": { "description": "Creates a new Stitch project.", "params": [ { "name": "title", "type": "string", "optional": true } ] } } } ``` ``` -------------------------------- ### Project Class Methods Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/README.md The Project class allows for managing and interacting with projects, including generating and retrieving screens, uploading files, and managing design systems. ```APIDOC ## Project Class ### Description Represents and manages a project within the Stitch SDK. ### Methods #### `generate(prompt, deviceType?, modelId?)` - **Description**: Generates screens based on a prompt. - **Parameters**: - `prompt` (string): The prompt for screen generation. - `deviceType` (string, optional): The target device type. - `modelId` (string, optional): The model ID to use for generation. - **Returns**: A promise that resolves with the generated screen data. #### `screens()` - **Description**: Lists all screens within the project. - **Returns**: A promise that resolves with a list of screens. #### `getScreen(id)` - **Description**: Retrieves a specific screen by its ID. - **Parameters**: - `id` (string): The ID of the screen to retrieve. - **Returns**: A promise that resolves with the screen data. #### `upload(filePath, opts?)` - **Description**: Uploads a design file to the project. - **Parameters**: - `filePath` (string): The path to the file to upload. - `opts` (object, optional): Additional options for upload. - **Returns**: A promise that resolves upon successful upload. #### `downloadAssets(outputDir, opts?)` - **Description**: Downloads all assets for the project. - **Parameters**: - `outputDir` (string): The directory to save the downloaded assets. - `opts` (object, optional): Additional options for download. - **Returns**: A promise that resolves with information about the downloaded assets. #### Design System Methods ##### `createDesignSystem()` - **Description**: Creates a new design system for the project. - **Returns**: A promise that resolves with the created design system. ##### `listDesignSystems()` - **Description**: Lists all design systems associated with the project. - **Returns**: A promise that resolves with a list of design systems. ##### `designSystem(id)` - **Description**: Retrieves a specific design system by its ID. - **Parameters**: - `id` (string): The ID of the design system to retrieve. - **Returns**: A promise that resolves with the design system data. ``` -------------------------------- ### Download Project Assets Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/project-class.md Downloads all screens and referenced assets to a local directory, rewriting URLs for self-containment. Specify the output directory and optional settings like file mode and asset subdirectory. ```typescript const result = await project.downloadAssets("./output", { fileMode: 0o644, assetsSubdir: "public", }); console.log(`Downloaded ${result.screens.length} screen(s)`); for (const screen of result.screens) { console.log(` ${screen.screenSlug} → ${screen.filePath}`); } if (result.warnings.length > 0) { console.warn("Warnings:", result.warnings); } ``` -------------------------------- ### DesignSystem Class Methods Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/API-OVERVIEW.md Methods for managing and applying design systems. ```APIDOC ## Class: DesignSystem Represents a visual theme or branding applied to screens. ### Methods #### `update(designSystem: DesignSystemInput)` **Description**: Updates an existing design system with new input. **Returns**: Promise #### `apply(selectedScreenInstances: SelectedScreenInstance[])` **Description**: Applies the design system to a list of selected screen instances. **Returns**: Promise ``` -------------------------------- ### listDesignSystems Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/project-class.md Lists all design systems associated with the project. ```APIDOC ## listDesignSystems ### Description List all design systems in the project. ### Method Signature `listDesignSystems(): Promise` ### Return Type Promise — Array of DesignSystem instances ### Example ```typescript const systems = await project.listDesignSystems(); for (const system of systems) { console.log(system.assetId); } ``` ``` -------------------------------- ### downloadAssets Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/project-class.md Downloads all screens and their referenced assets to a local directory, rewriting URLs in HTML to be self-contained. ```APIDOC ## downloadAssets(outputDir: string, opts?: DownloadAssetsOptions): Promise ### Description Downloads all screens and their referenced assets to a local directory. Rewrites URLs in HTML to be self-contained. ### Method `downloadAssets` ### Parameters #### Path Parameters - **outputDir** (string) - Required - Directory to save assets to (must exist) #### Query Parameters - **opts.fileMode** (number) - Optional - Unix file permissions for downloaded files (default: 0o600) - **opts.tempDir** (string) - Optional - Temp directory for atomic writes (must be on same filesystem) (default: outputDir) - **opts.assetsSubdir** (string) - Optional - Subdirectory name for assets within outputDir (default: "assets") ### Return Type Promise - `screens` (DownloadedScreenTrace[]) - Array of {screenId, screenSlug, filePath} - `warnings` (string[]) - Non-fatal issues encountered ### Throws StitchError with code NOT_FOUND, NETWORK_ERROR, or VALIDATION_ERROR ### Example ```typescript const result = await project.downloadAssets("./output", { fileMode: 0o644, assetsSubdir: "public", }); console.log(`Downloaded ${result.screens.length} screen(s)`); for (const screen of result.screens) { console.log(` ${screen.screenSlug} → ${screen.filePath}`); } if (result.warnings.length > 0) { console.warn("Warnings:", result.warnings); } ``` ``` -------------------------------- ### StitchProxy Constructor Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/proxy-server.md Initializes a new instance of the StitchProxy. Accepts an optional configuration object to customize its behavior, including authentication credentials, target URL, and proxy server naming. ```APIDOC ## StitchProxy Constructor ### Description Initializes a new instance of the StitchProxy. Accepts an optional configuration object to customize its behavior, including authentication credentials, target URL, and proxy server naming. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **inputConfig** (Partial) - Optional - Configuration object for the proxy. - **inputConfig.apiKey** (string) - Optional - API key for Stitch authentication. Defaults to `process.env.STITCH_API_KEY`. - **inputConfig.accessToken** (string) - Optional - OAuth access token. Defaults to `process.env.STITCH_ACCESS_TOKEN`. - **inputConfig.quotaProjectId** (string) - Optional - Quota project ID for billing. Defaults to `process.env.STITCH_PROJECT_ID` or `process.env.GOOGLE_CLOUD_PROJECT`. - **inputConfig.url** (string) - Optional - Target Stitch MCP server URL. Defaults to `https://stitch.googleapis.com/mcp`. - **inputConfig.name** (string) - Optional - Name of the local proxy server. Defaults to `"stitch-proxy"`. - **inputConfig.version** (string) - Optional - Version of the local proxy server. Defaults to `"1.0.0"`. ### Authentication Requires either `apiKey` OR both `accessToken` + `quotaProjectId`. Will throw if neither is provided. ### Request Example ```typescript import { StitchProxy } from "@google/stitch-sdk"; const proxy = new StitchProxy({ apiKey: "your-api-key", name: "my-stitch-proxy", version: "1.0.0", }); ``` ``` -------------------------------- ### Set STITCH_ACCESS_TOKEN and GOOGLE_CLOUD_PROJECT Environment Variables Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/configuration.md Set STITCH_ACCESS_TOKEN and GOOGLE_CLOUD_PROJECT for OAuth authentication. The access token is required if not using an API key. ```bash export STITCH_ACCESS_TOKEN="your-access-token" export GOOGLE_CLOUD_PROJECT="your-gcp-project-id" ``` -------------------------------- ### Configure Stitch with StitchToolClient Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/configuration.md Initialize the Stitch singleton by passing a configured StitchToolClient instance. ```typescript const client = new StitchToolClient({ apiKey: "..." }); const sdk = new Stitch(client); ``` -------------------------------- ### Initialize StitchToolClient with API Key Source: https://github.com/google-labs-code/stitch-sdk/blob/main/_autodocs/API-OVERVIEW.md Use an API key for authentication. It can be provided directly during client initialization or set via an environment variable. ```typescript new StitchToolClient({ apiKey: "..." }) ``` ```typescript process.env.STITCH_API_KEY = "..."; const client = new StitchToolClient(); ```