stitch-mcp

repository·main·Indexed 21 days ago

https://github.com/davideast/stitch-mcp

A CLI tool and MCP proxy designed to bridge AI-generated UI designs in Google's Stitch platform with local development workflows. It automates Google Cloud authentication, allows developers to preview project screens on a local Vite server, and generates Astro sites by mapping screens to routes. It provides an MCP proxy to expose Stitch tools and virtual tools (like build_site, get_screen_code, and get_screen_image) to coding agents such as Cursor, VS Code, and Claude Code.

Tokens
40.5K
Snippets
152
Records
193
Agent score
75%

What's inside stitch-mcp

  1. Choose a workflow for stitch-mcp

    main

    Depending on your goal, follow one of these primary workflows:

    1. Give your coding agent design context

    Use this to feed Stitch design data directly into AI coding agents.

    • Set up authentication
    • Connect your agent
    • Use Stitch tools in agents

    2. Build agent skills with Stitch data

    Use this to create custom capabilities (Agent Skills) for your AI agents using Stitch data.

    • Set up authentication
    • Connect your agent
    • Use Stitch tools in agents
    • Understand Agent Skills
    • Build an Agent Skill

    3. Preview and build from designs locally

    Use this to view designs in a local dev server or generate an Astro site from them.

    • Set up authentication
    • Preview designs
    • Build a site

    4. Extend Stitch with custom tools

    Use this to build and register your own virtual tools.

    • View the Tool Catalog
    • Reference Virtual Tools
    • Build a Virtual Tool
  2. How agents use the `build_site` virtual tool

    main

    Agents can programmatically build sites using the build_site virtual tool (available via the MCP proxy). The typical workflow for an agent is:

    1. Use list_screens to discover available screens.
    2. Analyze screen titles and metadata to decide on route assignments.
    3. Call build_site with the chosen mapping to retrieve the design HTML for each page.
    4. Use the provided HTML as context to generate framework-specific code.
  3. Virtual Tool Implementation Patterns

    main

    When building virtual tools, follow one of these three common architectural patterns depending on your complexity requirements:

    1. Wrapper Pattern

    Use case: Simplest implementation. Call one upstream tool and augment the result with additional data (e.g., downloading a file from a URL provided by the upstream tool).

    2. Orchestrator Pattern

    Use case: Complex operations. Coordinate multiple fetches, perform input validation, and manage concurrency.

    • Best Practice: Use pLimit(3) to cap concurrent network requests.
    • Best Practice: Validate inputs early and collect/throw errors collectively rather than failing on the first error.

    3. Passthrough Pattern

    Use case: Direct delegation. When you simply need to expose a specific method from the StitchMCPClient directly to the agent.

    // Wrapper Pattern Example
    execute: async (client: StitchMCPClient, args: any) => {
      const { projectId, screenId } = args;
      const screen = await client.callTool('get_screen', { projectId, screenId }) as any;
      let htmlContent: string | null = null;
      if (screen.htmlCode?.downloadUrl) {
        htmlContent = await downloadText(screen.htmlCode.downloadUrl);
      }
      return { ...screen, htmlContent };
    }
    
    // Orchestrator Pattern Example (Concurrency & Validation)
    execute: async (client: StitchMCPClient, args: any) => {
      const { projectId, routes } = args;
      if (!Array.isArray(routes)) throw new Error('routes must be an array');
      
      const limit = pLimit(3);
      await Promise.all(routes.map((r: any) => limit(async () => { /* fetch logic */ })));
      // ... return structured result
    }
    
    // Passthrough Pattern Example
    execute: async (client: StitchMCPClient, _args: any) => {
      const result = await client.getCapabilities();
      return result.tools || [];
    }
  4. What are Virtual Tools and how do they work?

    main

    A Virtual Tool is a custom operation registered with the Stitch MCP proxy that allows agents to perform complex tasks by combining multiple upstream Stitch API calls.

    Virtual tools are implemented as TypeScript objects that receive an authenticated StitchMCPClient during execution. This client allows the tool to invoke standard Stitch tools (like get_screen) while the proxy handles authentication, connection management, and error parsing. This abstraction allows you to expose high-level workflows (e.g., downloading code and images simultaneously) as single, atomic tools to an AI agent.

    // Example of how a virtual tool interacts with the client
    // The 'client' is provided by the proxy during execution
    const screen = await client.callTool('get_screen', { projectId, screenId });
  5. Configure `allowed-tools` for Agent Skills

    main

    The allowed-tools field lists tools the agent is pre-approved to call without prompting the user. The format depends on how the agent accesses the tools:

    • MCP tools: Use the MCP tool name (e.g., mcp__stitch__get_screen) if the agent is connected via the stitch-mcp server.
    • CLI tools: Use Bash(stitch:*) or Bash(npx:*) if the skill relies on stitch tool ... commands.
    • File access: Use Read and Write to allow the agent to read user code or write reports.
    allowed-tools: mcp__stitch__get_screen mcp__stitch__list_screens Bash(stitch:*) Read
  6. How Agent Skills are loaded by agents

    main

    Agent Skills use a progressive disclosure model to prevent large skill files from bloating every conversation. Agents load content in three distinct stages:

    1. Metadata (~100 tokens): The name and description are loaded at startup for all installed skills. This is the only part loaded in every session.
    2. Instructions (< 5000 tokens): The full content of the SKILL.md file is loaded only when the skill is specifically activated by the user.
    3. Resources (on demand): Additional files like scripts/, references/, or assets/ are loaded only when explicitly referenced by the instructions.
  7. Compare Proxy (stdio) vs Direct (HTTP) connection modes

    main

    Choose between the two modes based on your workflow requirements:

    FeatureProxy (stdio)Direct (HTTP)
    Virtual toolsAvailable (build_site, get_screen_code, get_screen_image)Not available (upstream tools only)
    Token refreshAutomatic (every 55 min)Manual (tokens expire after 1 hour)
    API key authSupportedSupported
    SetupRun npx @_davideast/stitch-mcp proxyProvide URL and headers
  8. Understand Agent Skills and their relationship with Stitch

    main

    An Agent Skill is a reusable set of instructions (defined in a SKILL.md file) that tells a coding agent how to use Stitch's MCP tools to perform complex workflows.

    While Stitch provides the raw material via MCP tools (such as screen HTML, images, and project metadata), Agent Skills provide the recipes. Instead of manually prompting an agent to "fetch the screen and compare it to my code" every session, you can use a skill that automates this logic.

    Key Workflow Example: Design Review A design review skill uses Stitch tools to:

    1. Retrieve design HTML via get_screen_code (to extract colors, spacing, and layout tokens).
    2. Fetch a visual reference via get_screen_image (to provide a screenshot of the intended design).
    3. Compare these against your local implementation (e.g., src/pages/index.tsx) to report discrepancies in CSS classes, spacing, or hex codes.
  9. Resilient tool discovery with `@google/stitch-sdk`

    main

    The @google/stitch-sdk includes a resilience layer within the StitchToolClient.listTools() method. This layer automatically intercepts remote tool schemas at runtime and injects missing $defs declarations (such as ScreenInstance or File).

    This mechanism prevents strict AJV validation crashes during tool discovery and compilation, ensuring that client-side applications and CI environments remain stable even if the backend provides incomplete or malformed schema payloads.

  10. Understand the Astro project structure

    main

    Astro projects follow a specific directory convention for routing and assets:

    • src/pages/: Contains .astro or .md files. Each file is automatically exposed as a route based on its filename (e.g., src/pages/about.astro becomes /about).
    • src/components/: A recommended location for UI components (Astro, React, Vue, Svelte, or Preact).
    • public/: A directory for static assets like images that should be served as-is.
    • package.json: Defines project dependencies and scripts.
    /
    ├── public/
    ├── src/
    │   └── pages/
    │       └── index.astro
    └── package.json
  11. Configure Stitch MCP for Cursor

    main

    Add the Stitch configuration to .cursor/mcp.json.

    • Proxy: Use command: "npx" and args: ["@_davideast/stitch-mcp", "proxy"]. Set STITCH_API_KEY or STITCH_PROJECT_ID in the env object.
    • Direct: Use url: "https://stitch.googleapis.com/mcp" and provide the X-Goog-Api-Key in the headers object.
    {
      "mcpServers": {
        "stitch": {
          "command": "npx",
          "args": ["@_davideast/stitch-mcp", "proxy"],
          "env": {
            "STITCH_API_KEY": "YOUR_API_KEY"
          }
        }
      }
    }
  12. Quick start with stitch-mcp

    main

    To begin using stitch-mcp, initialize the project using npx. This is the first step for previewing designs, building sites, or connecting your coding agent to Stitch data.

    Prerequisites

    • Node.js 18+
    • A Google Cloud project with billing enabled
    • A Stitch account with at least one project
    npx @_davideast/stitch-mcp init