This is the abridged developer documentation for GGUI # Introduction > GGUI is an open, MCP-native protocol for AI agents to render interactive UI on demand. Public preview — hosted GGUI at mcp.ggui.ai via the GGUI console, or self-hosted via `ggui serve`. **GGUI** is an open protocol that lets AI agents render interactive UI on the fly. Your agent describes what it needs in natural language; GGUI compiles a typed component and returns it as an MCP-Apps resource (`ui://ggui/render/`) that your host mounts. The UI reports back typed events the next time your agent calls `ggui_consume`. Use **hosted GGUI** at `mcp.ggui.ai` — sign in at [the GGUI console](https://console.ggui.ai) and skip the infrastructure in minutes. Or run the whole protocol yourself with **`ggui serve`** — no account, no cloud, no API key. [Get UI in Claude Desktop — 3 minutes](/quickstart/claude-desktop/) [Build an agent on hosted GGUI](/quickstart/hosted-agent/) [Self-hosted quickstart](/quickstart/self-hosted/) ## Choose your path [Section titled “Choose your path”](#choose-your-path) Claude Desktop User No code, no terminal. [Use GGUI in Claude Desktop](/quickstart/claude-desktop/) connects your chat to hosted GGUI in about three minutes, then the [Todos playground](/hosted/playgrounds/todos/) — one more connector to add — gives you a real agent-driven interface to try it on. [Other MCP hosts](/clients/connect-other-hosts/) use the same endpoint with their own config shape. Agent Builder Wire GGUI into an MCP server. Start with the [hosted quickstart](/quickstart/hosted-agent/) (5 min, no infrastructure), then the [MCP protocol reference](/api/mcp-protocol/), the [Cookbook](/cookbook/feedback-form/), or a worked [example agent](/examples/claude-agent/). Browse shareable gadgets and blueprints at [hub.ggui.ai](https://hub.ggui.ai). Operator Self-host the stack. [`ggui serve`](/cli/serve/) is the local deployment guide, [reference deploys](/self-hosted/reference-deploys/) cover Docker, Fly.io, and Render, and the [Self-hosted Registry](/sdk/self-hosted-registry/) is the artifact layer for private gadgets and blueprints. Agentic App Builder Ship a SaaS or webapp and want agents to drive it without rewriting the frontend? See [Agentic App Builders](/agentic-app-builders/). Reading these docs as an LLM? Every page is also raw markdown at the same slug — start at [`/llms.txt`](/llms.txt) (index, per the [llms.txt convention](https://llmstxt.org/)), `/llms-full.txt` (whole site, one file), or `/llms-small.txt` (compact). The [LLM-agent track](/agents/) lists the full machine-readable surface. ## How GGUI works [Section titled “How GGUI works”](#how-ggui-works) A typical exchange is five moments — **handshake → render → interact → consume → reopen**. See [How GGUI works](/how-it-works/) for the full walk-through with code, or [a real turn, traced end to end](/protocol/showcase-trimly/) against the production demo agent. ## Key concepts [Section titled “Key concepts”](#key-concepts) A few terms recur across the docs: * **GguiSession** — one rendered UI, minted by `ggui_render` (*render* is the verb; the object it creates is a GguiSession). Each GguiSession carries a stable `sessionId`. * **Contract** — the typed agreement between agent and renderer for one GguiSession. * **Tool** — an agent-side action (`ggui_render`, `ggui_consume`, …) — the MCP surface. * **Gadget** — a renderer-side capability (Leaflet map, Stripe Checkout, …) the LLM can compose with. * **Blueprint** — a cached recipe — a UI promoted from one-shot to “use this exact screen next time.” → [Glossary](/glossary/) for everything else. # Use GGUI in Claude Desktop > Connect Claude Desktop to hosted GGUI and get generated UI in your chats in about three minutes — no code, no infrastructure. Claude answers in text. With GGUI connected, it can answer with a real interface — a form, a table, a picker — right inside the chat. Setup takes about three minutes and never leaves your browser and Claude Desktop. You don’t write any code and you don’t open a terminal. ## Step 1: Create your GGUI account [Section titled “Step 1: Create your GGUI account”](#step-1-create-your-ggui-account) Go to [console.ggui.ai](https://console.ggui.ai) and sign in with Google, GitHub, or email. That is your whole signup. New accounts start with a **one-time welcome credit** while it is available — no card — and render on it at the published per-render rates; the amount and the rates are on [ggui.ai/pricing](https://ggui.ai/pricing). When it is spent, top up on the console’s credits page or bring your own provider key — see [Credits, billing & BYOK](/hosted/billing/). ## Step 2: Add GGUI to Claude Desktop [Section titled “Step 2: Add GGUI to Claude Desktop”](#step-2-add-ggui-to-claude-desktop) In Claude Desktop, open **Settings → Connectors → Add custom connector**, and paste this address: ```plaintext https://mcp.ggui.ai ``` Leave the authentication fields blank, then save. Claude handles the sign-in for you on first use. ## Step 3: Approve the connection [Section titled “Step 3: Approve the connection”](#step-3-approve-the-connection) The first time Claude uses GGUI — or as soon as you click **Connect** on the new connector card — a browser window opens on the GGUI console. 1. Sign in with the same account you created in Step 1. 2. Click **Approve**. The console creates the access key for you and hands it to Claude Desktop automatically. There is nothing to copy and nothing to paste. The browser window closes on its own, and the connector card shows as connected. You can see that key later on [the connector keys page](/hosted/connector-keys/). Revoking one is a command-line step for now, and that page walks through it. ## Step 4: Ask for something you’d rather click than type [Section titled “Step 4: Ask for something you’d rather click than type”](#step-4-ask-for-something-youd-rather-click-than-type) Open a new chat and ask for something that wants an interface. For example: > Plan my week — give me a form to rank these five tasks: inbox triage, dentist, Q3 draft, gym, call Mum. Claude decides an interface is the better answer, asks GGUI to build one, and the form appears inline in the chat. It is generated for that request, not picked from a template library, so the first one takes a while: tens of seconds, not instant. Leave it running; asking for the same kind of thing again later is much faster, because GGUI reuses what it built. **Text instead of a card?** If Claude answered in plain words, ask again and name the interface (“show it as a form”). If it called GGUI and still no card appears, check that the connector card shows as connected and that Claude Desktop is up to date: a card needs a host that can mount it. [Troubleshooting](/clients/claude-desktop/#troubleshooting) covers the rest. ## Step 5: Use it, and let Claude read your answer [Section titled “Step 5: Use it, and let Claude read your answer”](#step-5-use-it-and-let-claude-read-your-answer) Drag the rows, tick the boxes, hit submit. Your input travels straight back to Claude as structured data, exactly as if you had typed it out — so Claude can act on it in the very next message. Ask for a variation and you get a new interface. Ask for the same kind of thing again later and it comes back faster, because GGUI reuses what it built the first time. ## Where to next [Section titled “Where to next”](#where-to-next) * **[Todos playground](/hosted/playgrounds/todos/)** — a live surface to try; one more connector to add, same three-minute ceremony. * **[Build an agent on hosted GGUI](/quickstart/hosted-agent/)** — put generated UI in front of your own users, in your own agent. * **[The GGUI console](/hosted/console/)** — manage your keys, credits, and apps. * **[Claude Desktop reference](/clients/claude-desktop/)** — other hosts, disconnecting, and what to do if nothing renders. * **[Trust & security](/hosted/trust/)** — what GGUI stores, what reaches a model, and how to delete your account. # Build an agent on hosted GGUI > Ship your first agent UI against hosted GGUI (mcp.ggui.ai) in under 5 minutes — no infrastructure required. New accounts start with a **one-time welcome credit** while it is available — no card — and render on it at the published per-render rates (the amount and the rates are on [ggui.ai/pricing](https://ggui.ai/pricing)). When it is spent, top up on the console’s credits page, or bring your own provider key — see [Credits, billing & BYOK](/hosted/billing/). In 5 minutes, your agent will negotiate a UI contract and put a generated form on the wire as an MCP-Apps resource — no React code, no front-end build, no infrastructure. One thing to know before you start, because it shapes what you see at the end: a render is a resource, not a URL, and something has to **mount** it before a human can fill it in. That something is an MCP-Apps host. Run this agent programmatically with no host attached and it will block at `ggui_consume`, waiting on a render nobody can see — correct behavior, but not a finished demo. The fastest way to watch the whole loop close is to run the same prompt inside Claude Desktop connected to GGUI ([three-minute setup](/quickstart/claude-desktop/), zero code); this page is the programmatic path that gets your own agent onto the same wire. ```plaintext Your Agent → mcp.ggui.ai → MCP-Apps render (ui://ggui/render/) → User submits → Agent gets typed data ``` ## Prerequisites [Section titled “Prerequisites”](#prerequisites) * **Node.js** 20+ * **A free GGUI console account.** Sign in at [the GGUI console](https://console.ggui.ai) with Google, GitHub, or email. (The GGUI console is the end-user dashboard for hosted GGUI — see the [glossary](/glossary/) if the `ggui` / `guuey` split confuses you.) ## Step 1: Pick an app and mint an SDK API key [Section titled “Step 1: Pick an app and mint an SDK API key”](#step-1-pick-an-app-and-mint-an-sdk-api-key) 1. Sign in at [the GGUI console](https://console.ggui.ai). You land on `/apps` — new accounts come pre-provisioned with one default app; create another with **New App** if you want to scope this quickstart to its own surface (e.g. `feedback-demo`). 2. Open the app and go to **Keys** (`/apps/[appId]/keys`). Name the key (e.g. `feedback-demo-sdk`) and click **Generate per-app key**. 3. The key reveals exactly once — **copy it (`ggui_user_…`) immediately.** Lose it and you generate a new one; there’s no recovery. You also need the app’s ID: it is an opaque 8-character string with no prefix, and the app’s overview page shows the full endpoint, `mcp.ggui.ai/apps/`, ready to copy. Caution Never commit `ggui_user_*` keys. Use `.env` files and a secret manager in production. ## Step 2: Install the dependencies [Section titled “Step 2: Install the dependencies”](#step-2-install-the-dependencies) ```bash npm install @anthropic-ai/claude-agent-sdk @ggui-ai/protocol # or: pnpm add @anthropic-ai/claude-agent-sdk @ggui-ai/protocol # or: yarn add @anthropic-ai/claude-agent-sdk @ggui-ai/protocol ``` * **`@anthropic-ai/claude-agent-sdk`** runs Claude as a tool-using agent and speaks MCP natively — no wrapper needed. * **`@ggui-ai/protocol`** exports `GGUI_AGENT_SYSTEM_PROMPT`, the canonical system prompt that teaches Claude the handshake → render → consume loop. ## Step 3: Write your agent [Section titled “Step 3: Write your agent”](#step-3-write-your-agent) Create `agent.ts`. The Claude Agent SDK connects to `mcp.ggui.ai` directly via its `mcpServers` config — your code just streams Claude’s messages and lets the model drive the GGUI tools. ```typescript import { query } from "@anthropic-ai/claude-agent-sdk"; import { GGUI_AGENT_SYSTEM_PROMPT } from "@ggui-ai/protocol"; // 1. Point Claude's MCP client at your app's hosted endpoint. Bearer-auth // with the `ggui_user_*` key you minted in Step 1. Note: the per-app // cloud endpoint is the bare `/apps/` path — NO `/mcp` suffix // (that suffix is local-`ggui serve`-only). const mcpServers = { ggui: { type: "http" as const, url: "https://mcp.ggui.ai/apps/", headers: { Authorization: `Bearer ${process.env.GGUI_MCP_BEARER!}` }, }, }; // 2. Allow Claude to call every ggui tool. The `mcp____` // naming is the SDK's convention — `` = `ggui` (the key above). const allowedTools = [ "mcp__ggui__ggui_handshake", "mcp__ggui__ggui_render", "mcp__ggui__ggui_update", "mcp__ggui__ggui_amend", "mcp__ggui__ggui_emit", "mcp__ggui__ggui_consume", "mcp__ggui__ggui_get_session", ]; async function main() { const prompt = "Collect product feedback from the user. Show a feedback form with a " + "1-5 star rating and a comments text area, wait for them to submit, " + "then summarize what they said."; // 3. Stream the conversation. Claude reads GGUI_AGENT_SYSTEM_PROMPT, // decides when to call ggui_handshake / ggui_render, // polls ggui_consume until the user submits, and reports back — // all without any wrapper SDK on your side. for await (const msg of query({ prompt, options: { mcpServers, allowedTools, systemPrompt: GGUI_AGENT_SYSTEM_PROMPT, }, })) { if (msg.type === "assistant") { for (const block of msg.message.content) { if (block.type === "text") console.log(block.text); } } else if (msg.type === "result") { console.log("Done:", msg.subtype); } } } main().catch(console.error); ``` ## Step 4: Run it [Section titled “Step 4: Run it”](#step-4-run-it) ```bash export ANTHROPIC_API_KEY="sk-ant-..." # for the Claude Agent SDK export GGUI_MCP_BEARER="ggui_user_..." # for mcp.ggui.ai npx tsx agent.ts ``` You’ll see Claude narrate the handshake, call `ggui_render` (which returns `{ sessionId, resourceUri }` — the render surfaces as an MCP-Apps resource at `ui://ggui/render/`, not a clickable link), and then **block on `ggui_consume`**, polling for the user’s submission. That block is the expected end of the programmatic path: the render exists, and nothing is mounting it. Two ways to close the loop, easiest first: * **Run the prompt in an MCP-Apps host** — no code at all. Claude Desktop or claude.ai connected to GGUI mounts the resource inline, you submit, and the agent’s `ggui_consume` returns. Setup is three minutes: [Use GGUI in Claude Desktop](/quickstart/claude-desktop/). * **Embed it in your own app** — Step 5 below mounts the render with the React host helpers. More wiring, and the right answer once you are putting this in front of your own users. ## Step 5 (optional): Embed in React [Section titled “Step 5 (optional): Embed in React”](#step-5-optional-embed-in-react) Want the UI inside your own app? Install the React host helpers and the MCP-Apps host: ```bash npm install @ggui-ai/mcp-apps-react @mcp-ui/client ``` A GGUI render is an **MCP-Apps resource**. You drive the conversation with the `useMcpAppsChat` hook and mount each render’s sandboxed iframe with `` (imported directly from `@mcp-ui/client` — GGUI doesn’t re-export it): ```tsx import { AppRenderer } from "@mcp-ui/client"; import { useMcpAppsChat } from "@ggui-ai/mcp-apps-react/chat-helpers"; function Chat({ agentUrl }: { agentUrl: string }) { const { entries, sessions, send, handleAppMessage } = useMcpAppsChat({ chatEndpoint: `${agentUrl}/agent`, }); // - render `entries` as chat bubbles; call `send(prompt)` to talk to the agent // - mount each `sessions` entry with — it needs a sandbox-proxy // origin + onReadResource / onCallTool relay + onMessage={handleAppMessage} } ``` `useMcpAppsChat` talks to your **agent backend** (the process running the Step-3 `query()` loop, exposed over HTTP — `@ggui-ai/agent-server` gives you a brand-neutral `POST /agent` endpoint for exactly this). ``’s sandbox + resource-read + tool-call relay wiring is non-trivial; the complete runnable reference is the [`ggui-basic-web`](https://github.com/ggui-ai/ggui/tree/main/samples/apps/ggui-basic-web) sample. **Start there.** ## What just happened [Section titled “What just happened”](#what-just-happened) Under the hood, Claude drove these MCP tool calls against `mcp.ggui.ai`: 1. **`ggui_handshake`** negotiated a **contract** from a natural-language intent + draft, returning a `handshakeId` + a server suggestion (cache / agent / synth). 2. **`ggui_render`** with `{ handshakeId, props }` materialized the contract: GGUI matched a cached **blueprint** (or synthesized a fresh React component), minted a `sessionId`, and returned `{ sessionId, resourceUri }` — the render is an MCP-Apps resource at `ui://ggui/render/`, surfaced on the tool result’s `_meta.ui.resourceUri`. (There is no clickable URL on the wire.) 3. A host mounted that resource — your app via `` (Step 5), or an MCP-Apps host like claude.ai inline — and the user submitted the form. 4. **`ggui_consume`** delivered the user’s submit gesture as a `ConsumeEventEntry` (`{ intent, actionData, uiContext, ... }`). There is no terminal `close` ceremony — a render simply stays reopenable (see [Rehydration](/concepts/rehydration/)). There is no per-render time limit. Everything above the wire is `GGUI_AGENT_SYSTEM_PROMPT` + the Claude Agent SDK’s tool loop — no ggui-specific client code on your side. ```plaintext Agent mcp.ggui.ai MCP-Apps host │ │ (your app / claude.ai) │── handshake ───────────→ │ │ │← { handshakeId, ─ │ │ │ suggestion } │ │ │── render(handshakeId, ─ │ │ │ props) ────────────→ │ │ │ │── match/synth blueprint │ │← { sessionId, ─ │ │ │ resourceUri } │ │ │ │── ui://ggui/render/ ──→│ (host mounts iframe) │ │ │ │── consume(sessionId) ───→ │ │ │ │←── submit gesture ────────│ │← { events } ──────────── │ │ │ │ │ │ (no explicit close — render stays reopenable) │ ``` ## Next steps [Section titled “Next steps”](#next-steps) * **[Claude agent example](/examples/claude-agent/)** — canonical reference implementation for the snippet above * **[MCP protocol reference](/api/mcp-protocol/)** — every `ggui_*` tool, request/response, and error code * **[React host helpers](/host-helpers/react/)** — embed GGUI renders directly in your own React app with `useMcpAppsChat` + `` * **[Other LLMs](/examples/generic-mcp/)** — raw `@modelcontextprotocol/sdk` recipe; also [OpenAI](/examples/openai-agent/), [Gemini](/examples/gemini-agent/) * **[Feedback-form cookbook](/cookbook/feedback-form/)** — the recipe above, with variations * **[Troubleshooting](/troubleshooting/)** — common issues and fixes * **[Glossary](/glossary/)** — gadget vs tool vs blueprint, GGUI vs guuey, and the rest * **[Agentic App Builders](/agentic-app-builders/)** — if your goal is to make an existing app agent-drivable rather than building a fresh agent. # Self-hosted quickstart > Start from the GGUI samples and run an agentic app locally — no account, no cloud, no GGUI API key. Run the entire protocol yourself — no account, no cloud. This is the same protocol the hosted quickstarts use — nothing about your agent changes between them — see [Portability](/hosted/portability/). Assemble a complete GGUI agentic app from the canonical samples and run it locally — your agent, the GGUI MCP server, a sample MCP server, and a web client. ```plaintext agent ── MCP ──→ ggui serve ──→ MCP-Apps resource ui://ggui/render/ ``` Two ways in — same protocol either way, in the same order as the [repo README](https://github.com/ggui-ai/ggui#quick-start--pick-your-path): 1. **Composed path, on guuey’s dev tooling:** published SDKs end-to-end. [guuey](https://guuey.com) is a separate agent-hosting platform; this path uses its dev tools to run the agent, and GGUI renders the UI. 2. **Bring your own framework:** compose the framework-native samples (Claude Agent SDK / OpenAI Agents SDK / Google ADK) into one workspace, with GGUI alone and no guuey dependency. ## Path 1: composed path, on guuey’s dev tooling [Section titled “Path 1: composed path, on guuey’s dev tooling”](#path-1-composed-path-on-guueys-dev-tooling) One flow from a `guuey.json` to a rendered, interactive todo UI — every piece a published SDK. [guuey](https://guuey.com)’s dev tooling runs the agent (`@guuey/cli` + `@guuey/worker`), the GGUI runtime is the dev router’s injected MCP default, and the web client talks to the router with `@guuey/agent-client`. Prerequisites: **Node.js 22+**, **pnpm**, and an **`ANTHROPIC_API_KEY`** (one key drives both the agent and GGUI’s UI generation). ```bash git clone https://github.com/ggui-ai/ggui && cd ggui pnpm install # workspace deps — `guuey dev` spawns the colocated # todo MCP from samples/mcp-servers/todo export ANTHROPIC_API_KEY=sk-ant-… # in every terminal below # terminal 1 — the ggui runtime MCP (guuey's dev router injects ggui → this port) npx -y @ggui-ai/cli serve --mcp-only --dev-allow-all # http://127.0.0.1:6781/mcp # terminal 2 — the agent half: guuey.json + a Claude agent worker cd samples/agents/with-guuey npm install npm run dev # guuey dev --serve → http://localhost:6790 # terminal 3 — the web half: chat + rendered ggui cards cd samples/apps/with-guuey-web npm install npm run dev # http://127.0.0.1:6890 ``` `--dev-allow-all` is what makes terminal 1 usable here: `/mcp` is bearer-gated by default, and both callers in this path arrive anonymous — the dev router’s own GGUI connection (it carries no dev token; only colocated servers get one) and the web half’s browser relay. Without the flag, the first `ggui_render` returns `401`. It is a loopback convenience — never put it on a public URL. Open **`http://127.0.0.1:6890`** and ask for your todos: the agent calls the todo MCP, renders an interactive todo UI through GGUI, and your clicks flow back to the agent. Prefer a scaffolded start? `npx @guuey/create-agentic-app` scaffolds a guuey agentic app of the same shape (agent + MCP + GGUI + web) in one command. **Before / after.** This is the composed path’s headline. The framework-native web client (`samples/apps/ggui-basic-web`) hand-rolls its agent loop in a 702-line `Chat.tsx` — SSE parsing, the per-turn status machine, the transcript fold, resource narrowing, and generative-UI recognition. The composed web half replaces all of that with `useAgentInvoke` from `@guuey/agent-client/react` plus `@guuey/mcp-apps-host`’s view-mount dispatcher (`toolResultViewMount` — inline mcp-ui resources first, GGUI renders second, bare `ui://` locators last); what remains in `samples/apps/with-guuey-web` is rendering — an `App.tsx` that is mostly JSX. Two per-path notes, stated where you hit them (full detail in the sample READMEs — [`samples/agents/with-guuey`](https://github.com/ggui-ai/ggui/tree/main/samples/agents/with-guuey) · [`samples/apps/with-guuey-web`](https://github.com/ggui-ai/ggui/tree/main/samples/apps/with-guuey-web)): * **Dev-server trust:** `guuey dev` runs your agent unjailed with your environment — standard dev-server trust; run it in a container if that posture doesn’t fit. * **Fresh sessions only:** `guuey dev --serve` keeps sessions in memory and serves no history endpoint — every page load starts a fresh thread. Durable state belongs in your MCP servers (the todo list survives reloads); reload-repaint of chat history is a hosted-platform feature. This path drives the GGUI protocol through guuey’s published SDKs. The protocol itself has no guuey dependency — path 2 below (and the self-host and hosted paths in the repo README) runs without it, and the framework-native samples stay first-class. ## Path 2: bring your own framework — framework-native samples [Section titled “Path 2: bring your own framework — framework-native samples”](#path-2-bring-your-own-framework--framework-native-samples) Compose the framework-native samples into one workspace — no guuey dependency. Composing is a real step, not a figure of speech; once the tree exists, a single `pnpm dev` runs all four services. ### Prerequisites [Section titled “Prerequisites”](#prerequisites) * **Node.js** 22+ — the repo declares `engines.node >= 22`. * **pnpm** 11+ — required, not a preference. The workspace carries pnpm-only settings (`nodeLinker: hoisted`, `autoInstallPeers`, `allowBuilds`) that npm and bun do not read. * An MCP-capable agent runtime (Claude Desktop, Claude Code, Cursor, or anything that reads `.mcp.json`). * No account, no GGUI API key. Everything is local (generation runs on your own LLM key — Step 2). ### Step 1: Clone the samples [Section titled “Step 1: Clone the samples”](#step-1-clone-the-samples) ```bash git clone https://github.com/ggui-ai/ggui && cd ggui pnpm install ``` The clone gives you the pieces, not a preassembled app. Four canonical samples compose into one small monorepo: `samples/agents//` → `servers/agent/` (your agent — `claude-agent-sdk` / `openai-agents-sdk` / `google-adk`), `samples/gguis/default/` → `servers/ggui/` (the GGUI MCP server config), `samples/mcp-servers/todo/` → `servers/mcps/todo/` (a sample MCP server), and `samples/apps/ggui-basic-web/` → `apps/web/` (a web client). ### Step 1.5: Compose them into one app [Section titled “Step 1.5: Compose them into one app”](#step-15-compose-them-into-one-app) Composing is a manual step today — the repo root has no `dev` script and no `servers/` directory until you make one. Two references ship in the repo, and they are the exact ones the project’s own end-to-end suite uses: * **`e2e/samples-render/app-shell/`** — the root wrapper: the `package.json` that carries `dev` plus the granular `dev:ggui` / `dev:agent` / `dev:mcps` / `dev:web` / `dev:stop` scripts, the `pnpm-workspace.yaml` describing the composed layout, and the `pnpm dev` orchestrator itself. * **`e2e/samples-render/scripts/compose-app.mjs`** — the copy plan, including the `workspace:*` → published-version rewrite each sample’s dependencies need once they live outside this repo’s workspace. Copy the wrapper to an empty directory, copy the four samples to the target paths above, and you have the tree the rest of this path describes. See the [samples quickstart in the repo README](https://github.com/ggui-ai/ggui#quick-start--pick-your-path) for the same layout in the repo’s own words. ### Step 2: Boot the composed app [Section titled “Step 2: Boot the composed app”](#step-2-boot-the-composed-app) Set an LLM key in `.env.local` at the composed app’s root (any one — the boot probe walks `anthropic` → `openai` → `google` → `openrouter`): .env.local ```bash ANTHROPIC_API_KEY=sk-ant-... ``` ```bash pnpm dev ``` From the composed root, `pnpm dev` boots the whole app together — the GGUI MCP server (`ggui serve` from [`@ggui-ai/cli`](https://www.npmjs.com/package/@ggui-ai/cli), embedding `@ggui-ai/mcp-server`), your agent, the sample MCP server, and the web client. The GGUI server (`servers/ggui`) defaults to `http://127.0.0.1:6781`: * **MCP endpoint:** `http://127.0.0.1:6781/mcp` * **WebSocket (live channel):** `ws://127.0.0.1:6781/ws` * **Operator console:** `http://127.0.0.1:6781/` Granular scripts (`dev:ggui`, `dev:agent`, `dev:mcps`, `dev:web`, `dev:stop`) run the pieces individually — they are declared in the wrapper’s `package.json`. ### Step 3: Point an agent runtime at the local MCP [Section titled “Step 3: Point an agent runtime at the local MCP”](#step-3-point-an-agent-runtime-at-the-local-mcp) Create `.mcp.json` at your project root with: ```json { "mcpServers": { "ggui": { "url": "http://127.0.0.1:6781/mcp", "headers": { "Authorization": "Bearer dev" } } } } ``` Claude Desktop, Claude Code, Cursor, and any runtime that reads `.mcp.json` will discover the agent-facing tool catalogue — `ggui_handshake` / `ggui_render` / `ggui_update` / `ggui_amend` / `ggui_emit` / `ggui_consume`, plus discovery tools (`ggui_get_session`, `ggui_list_sessions`, `ggui_list_gadgets`, `ggui_list_themes`, blueprint search/render). The flow is **`handshake` → `render`**, with `ggui_amend` to repaint props on the mounted card in place and `ggui_update` to mint a new history card when a change is worth its own transcript entry. Write a system prompt that tells the LLM when to render UIs — the [Examples](/examples/claude-agent/) section has working recipes per framework. ## What works today [Section titled “What works today”](#what-works-today) * ✅ **Local server + wsToken-gated WebSocket subscribe → ack** work end-to-end — the iframe receives `wsUrl`/`wsToken` on the `ai.ggui/render` slice. Render plumbing is production-shaped, not a mock. * ✅ **`handshake` → `render`** delivers an MCP-Apps resource (`ui://ggui/render/`) that an MCP-Apps host mounts. * ✅ **Component generation is wired via BYOK.** Export `ANTHROPIC_API_KEY` (or `OPENAI_API_KEY` / `GOOGLE_API_KEY` / `OPENROUTER_API_KEY`) before `ggui serve` and `ggui_render` runs the real `@ggui-ai/ui-gen` pipeline (blueprint match → synth). Without any key, `ggui_render` returns a “Connect Claude” card pointing at the local `/settings` page rather than failing. * ✅ **Per-app theming.** Your `servers/ggui/ggui.json` sets `theme: {preset: 'indigo', mode: 'dark'}`; agents can list presets via `ggui_list_themes` and override per render with `ggui_render({themeId})`. * 🔒 **Default auth is pair-minted.** `/mcp` rejects bearers that weren’t issued by the pairing flow. Pass `--dev-allow-all` to accept any non-empty bearer as `builder` (safe only on `127.0.0.1`), or swap in a real `AuthAdapter` via `createGguiServer({ auth })` before exposing the server beyond localhost. ## What this is not [Section titled “What this is not”](#what-this-is-not) * **Not a hosted service.** No GGUI cloud account, no billing, no managed dashboards. For those, see [Build an agent on hosted GGUI](/quickstart/hosted-agent/). * **Not a managed billing surface.** Generation runs on YOUR provider key (BYOK) — every `ggui_render` bills the provider directly. The hosted GGUI cloud bundles credit-metered billing and managed keys; this OSS path runs on your own provider key today. ## Vocabulary [Section titled “Vocabulary”](#vocabulary) * **Tool** — an agent-side action exposed over MCP (`ggui_render`, `ggui_handshake`, …). * **Gadget** — a renderer-side capability surfaced inside the viewer (formerly `clientLibraries`). * **Blueprint** — a cached component recipe matched before generation runs. Full definitions: [Glossary](/glossary/). ## Just the bare MCP server [Section titled “Just the bare MCP server”](#just-the-bare-mcp-server) The composed app orchestrates everything through `pnpm dev`. If you only want the OSS MCP server — no agent or web supervision — run [`ggui serve`](/cli/serve/) against a `ggui.json` directly (the same `ggui serve` the composed samples’ `servers/ggui` runs): ```bash # = ggui serve --mcp-only --dev-allow-all --port 6781 pnpm --filter ./servers/ggui start ``` Working from a monorepo clone rather than the published packages? Build the workspace copies first: ```bash pnpm --filter @ggui-ai/cli build node packages/ggui-cli/dist/cli.js serve --mcp-only ``` ## What’s next [Section titled “What’s next”](#whats-next) * **[MCP Protocol Reference](/api/mcp-protocol/)** — wire format and tool catalogue (same on OSS and hosted). * **[WebSocket Protocol](/api/websocket-protocol/)** — live-channel envelopes (`ActionEnvelope`, `StreamEnvelope`). * **[Examples](/examples/claude-agent/)** — MCP-config-only integrations with system-prompt recipes (Claude, OpenAI, Gemini, generic MCP). * **[Build an agent on hosted GGUI](/quickstart/hosted-agent/)** — managed generation and dashboards on GGUI cloud. * **[GitHub repo](https://github.com/ggui-ai/ggui)** — source, issue tracker, full monorepo walkthrough. # How GGUI works > The five moments of a GGUI exchange — handshake, render, interact, consume, reopen — explained end-to-end in five minutes. A walk-through for agent developers. You’ll come out of this with a working mental model of what happens between the moment your agent calls `ggui_handshake` and the moment the user submits the form. Five minutes. No setup required — this is conceptual. ## The five moments [Section titled “The five moments”](#the-five-moments) Every GGUI exchange is the same five moments, in order: ```plaintext 1. HANDSHAKE Post a draft contract; the server routes a suggestion 2. RENDER Accept or override; the server mints an MCP-Apps resource 3. INTERACT The host mounts it; the user fills the UI and submits 4. CONSUME Drain the user's gestures off a render-scoped pipe 5. REOPEN The card is durable — scroll back and it still works ``` The rest of this page expands those five moments into a story. ## 1. Handshake — the wire surface is negotiated [Section titled “1. Handshake — the wire surface is negotiated”](#1-handshake--the-wire-surface-is-negotiated) Your agent’s first call is `ggui_handshake` — the server runs blueprint search in its reuse layer, the semantic cache for generative UI, in parallel with contract validation, and returns a routed suggestion. (These are MCP tool calls the LLM emits; there is no client SDK — the shapes below are the tool input → output.) ```ts // ggui_handshake tool — input: ggui_handshake({ intent: "collect feedback after a support chat", blueprintDraft: { contract: {/* propsSpec, actionSpec, ... */}, }, }); // → { handshakeId, action, suggestion } ``` The returned `suggestion.origin` is `cache` (existing blueprint matched), `agent` (gen against the draft), or `synth` (gen against an amended draft). No UI is generated yet — the agent commits next, on render. Each render is independent: each `handshake → render` pair mints a fresh **GguiSession** — the protocol’s unit for one rendered UI — keyed by `sessionId`. There is no conversation-level session object; conversation-scoped grouping (sibling renders inside the same chat) flows through the `_meta["ai.ggui/host-session"]` slice — captured ONCE at creation. → See [`ggui_handshake`](/api/mcp-protocol/) for the wire shape. ## 2. Render — the UI gets generated (or matched) [Section titled “2. Render — the UI gets generated (or matched)”](#2-render--the-ui-gets-generated-or-matched) Now the agent commits against the prior handshake’s suggestion — `props` is required; omit `override` to accept the suggestion as-is: ```ts // ggui_render tool — props required; omitting `override` accepts // the handshake suggestion: ggui_render({ handshakeId, props: { question: "How did the session go?" }, // or re-aim: override: { contract: {...} } / { variance: {...} } }); // → { outcome: 'rendered' | 'failed' | 'refused', ... } // read `outcome` first — sessionId + resourceUri ride a rendered result ``` Server-side, materialisation runs one of two paths — the path was already chosen at handshake time, render just executes it: 1. **Cache delivery** (`suggestion.origin === 'cache'`). A matching blueprint was found during handshake; render serves the cached component — zero generation calls. 2. **Fresh generation** (`origin === 'agent'` or `'synth'`). The server runs the LLM-driven UI generator (`@ggui-ai/ui-gen`) — plan → impl → check → derive. The output is a TSX component compiled to JS, plus a typed **contract** describing the actions the user can take and the data they can submit. It takes tens of seconds. Either way, any gadgets the component imports (Leaflet, Stripe, Calendar, …) resolve from the app’s declared gadget set (stdlib floor + `ggui.json#app.gadgets`) and load SRI-verified at iframe boot. Every response leads with `outcome`. On a `rendered` one the agent gets back a `sessionId` (globally unique UUID for the delivered render) and a `resourceUri` (`ui://ggui/render/`). The render is an MCP-Apps resource — there is no clickable URL the agent forwards; a host mounts the resource. The other two outcomes carry no mount: `failed` means generation ran and produced nothing, and `refused` means the deployment declined before doing any work, so it carries only a `refusal` and leaves the handshake valid. → See [`ggui_render`](/api/mcp-protocol/) for the wire shape. ## 3. Interact — the user fills the UI [Section titled “3. Interact — the user fills the UI”](#3-interact--the-user-fills-the-ui) A host mounts the render — your app via ``, or an MCP-Apps host like claude.ai inline. The renderer: 1. Hits the **bootstrap channel** — fetches the compiled component bundle (SRI-verified) 2. Mounts the component in an iframe with the props the agent rendered 3. Connects the **live channel** — a WebSocket subscription scoped to this render 4. When the user submits, the component dispatches an `ActionEnvelope` like `{ type: "data:submit", payload: {...} }`. The server validates the payload against the contract’s `actionSpec`. The renderer is **stateless** between page loads — props come from the server, state comes from the user, and the server is the source of truth for the render’s state. → See [Envelopes](/protocol/envelopes/) for the live-channel wire reference. ## 4. Consume — the action lands back with the agent [Section titled “4. Consume — the action lands back with the agent”](#4-consume--the-action-lands-back-with-the-agent) Actions are agent-routed. The server queues every gesture on a render-scoped pipe; the agent drains it by calling `ggui_consume` (long-poll, keyed by `sessionId`): ```ts // ggui_consume tool (long-poll) — returns { events, status }: const { events, status } = ggui_consume({ sessionId, timeout: 25 }); for (const event of events) { if (event.intent === "submit_feedback") { await processFeedback(event.actionData); } } ``` Each row is a `ConsumeEventEntry`: `{ type: 'action', sessionId, intent, actionData, uiContext, actionId, firedAt }`. `intent` is the action key from the contract’s `actionSpec`; `actionData` is the typed payload (validated against `actionSpec[intent].schema`). Exit the loop when you have the events you need — that is the real terminal condition. `status` is the other exit: it stays `'active'` until the render’s TTL elapses, at which point `'expired'` means no more events will arrive. On hosted GGUI renders are retained indefinitely by default, so `'expired'` is a self-hosted concern. Do not write a loop that waits for it. An `actionSpec` entry may carry a `nextStep: ''` hint naming one of the contract’s `agentCapabilities.tools` — an **advisory** hint for the agent’s planner. Implementations MUST treat it as advisory; the agent owns the call decision. Agent-less `ggui serve` deployments take the same path: events queue on the consume buffer until an agent attaches and drains them — the server never invokes a tool on the user’s behalf. There is no second routing model. When the agent wants to refresh the visible card in response to an event (e.g. show a confirmation, splice in new data), it calls `ggui_amend` (keyed by `sessionId`, `kind: 'replace' | 'merge'`) — the iframe receives the new props on the live channel without a fresh `ggui_render`. Then loop back to `ggui_consume`. Rule of thumb: if your reaction ran a domain tool that changed what the card displays, call `ggui_amend` *before* re-calling `ggui_consume` — skipping it is the most common wire-compliance bug. Use `ggui_update` instead when the reaction is a state milestone worth minting as a new history card. → See [`ggui_consume`](/api/mcp-protocol/) and the `ConsumeEventEntry` row shape on the same page. ## 5. Reopen — the card survives the conversation [Section titled “5. Reopen — the card survives the conversation”](#5-reopen--the-card-survives-the-conversation) A GGUI render is not a disposable popup. It is a durable record addressed by a `ui://` locator, and that locator keeps working after your agent has moved on. Scroll back in the transcript, reload the page, or come back tomorrow: the host reads the same locator with `resources/read` and gets the view again. If the live render row has been evicted, the read re-mints the view — from the durable identity record when the deployment keeps one, or from the cached blueprint named by the locator’s second segment, which returns the original card with its default props rather than a typed failure. Two consequences worth designing around: * **There is no close ceremony**, because there is nothing to close. When an exchange is over, your agent simply stops addressing that `sessionId`. * **`ggui_update` writes history.** Each update mints a new epoch-numbered record and pins the previous one — old cards freeze rather than silently repainting with newer state, so the transcript stays an honest record of what the user actually saw. `ggui_amend` is the opposite move: it repaints the card in place and the history number does not advance. Retention is a deployment choice. Hosted GGUI retains renders indefinitely by default, so reopening an old card is the expected path, not a lucky one. There is no per-render time limit; a self-hosted server applies its own default. → See [Render locator grammar](/api/mcp-apps/#render-locator-grammar) for the URI shape, including the `#N` epoch pin. ## What you didn’t have to do [Section titled “What you didn’t have to do”](#what-you-didnt-have-to-do) Notice what your agent code did *not* have to handle: * **No UI authoring.** The component code was generated or matched from cache. * **No WebSocket plumbing.** The renderer connects to the live channel on its own; you didn’t open a socket. * **No state management.** The server holds render state. You called `ggui_consume` and got events. * **No SDK lock-in.** Everything above is plain MCP tool calls — works from any MCP client. That’s the protocol. The OSS `ggui serve` running locally (`ws://127.0.0.1:6781/ws`) is the reference implementation; hosted GGUI at `https://mcp.ggui.ai` (`wss://mcp.ggui.ai/ws`) is the managed one. Both speak the same wire. ## Next [Section titled “Next”](#next) * **See one traced end to end** — [Showcase: a real turn](/protocol/showcase-trimly/) walks these five moments as an actual recorded exchange with a live ggui-rendering agent, frame by frame off the wire. * **Build something** — [build an agent on hosted GGUI](/quickstart/hosted-agent/) against `https://mcp.ggui.ai` (no infrastructure), or the [self-hosted quickstart](/quickstart/self-hosted/) (local) * **See the wire** — [MCP Protocol](/api/mcp-protocol/), [Envelopes](/protocol/envelopes/), [WebSocket](/api/websocket-protocol/) * **Look up a term** — [Glossary](/glossary/) * **Look at example agents** — [Claude](/examples/claude-agent/), [OpenAI](/examples/openai-agent/), [Gemini](/examples/gemini-agent/), [raw MCP](/examples/generic-mcp/) * **Already shipped a SaaS?** — [Agentic App Builders](/agentic-app-builders/) covers the (in-design) path to make an existing app agent-drivable. # Blueprints and the cache > What a blueprint is, how the two-tier matcher decides to reuse one, what promotion and durability actually do, and which parts of the hit ratio you can see today. A blueprint is a render promoted to a reusable recipe. The first time your agent asks for a feedback card, GGUI generates one. The stored result — component code, the contract it satisfies, the intent that produced it — becomes a candidate the matcher can serve the next time an ask looks the same. Where **gadgets** are ingredients and **tools** are actions, blueprints are the already-solved screens. Blueprints live in a per-app pool. Matching them is the job of GGUI’s reuse layer, the **semantic cache for generative UI**. It runs at `ggui_handshake`, before any generation is attempted; `ggui_render` then executes whichever path the handshake chose. ## The reuse key [Section titled “The reuse key”](#the-reuse-key) Two values decide identity. `contractHash` is the canonical hash of the data contract — fields, types, specs — so the same hash means the same data flow. `variantKey` is the canonical hash of the design-time variance (persona, aesthetic, seed prompt, context). The pair is the reuse key: the same pair reuses one component, and a different variant of the same contract gets its own row. Passing `override.contract` on render re-aims: the render resolves at the new contract’s key and reuses the component stored there if one exists — an override identical to a cached contract serves that card. An override is a request for a different contract, not for new code; `forceCreate` on the handshake is the request for new code. ## The match pipeline [Section titled “The match pipeline”](#the-match-pipeline) Matching has two tiers, and they have very different costs and postures. **Tier 1 — exact contract-key equality.** When your agent supplied a contract, the matcher looks up the canonical key directly. It is deterministic and calls no model at all. A hit is wire-compatible, because the same canonical contract means the same data flow, but the contract is all the key compares. A fixed value that your request carries only in its intent is not compared: an interface built as a January calendar can be reused for a request that asks for March. Neither is the canvas the request mounts on or the design direction it asks for. An exact hit is served even when one of those differs. **Tier 2 — retrieval plus a rerank judge.** When tier 1 misses, candidates are retrieved by cosine similarity over embeddings and a fast model is asked to pick among them. The judge is shown your intent prose, a summary of your request’s contract and, for each candidate in your app’s own pool, its id, its similarity score, the intent it was stored with (truncated to 280 characters), and a one-line structural summary of its contract — `slots=name:type; actions=name(payloadFields); streams=name; props=name:type` — and nothing else. It never sees props values or event payloads. A judge that declines every candidate, or picks one below the confidence threshold, falls through to cold generation rather than serving a wrong blueprint. On hosted GGUI, TypeSafe AI’s Jev model makes this choice first. It is shown the same fields except the similarity scores, and its answer that none fits is final. When it does not answer in time, returns an error, or is not confident in its pick, the judge above decides instead. See [Trust & security](/hosted/trust/#what-generation-actually-sees). The reranker exists because raw cosine similarity cannot tell a `sendChip` action that carries `{chipText}` apart from a payload-less `sendChip` — and serving the wrong one silently drops the user’s input. The outcome surfaces on the handshake as `suggestion.origin`: `cache` (a blueprint matched), `agent` (generate against your draft), or `synth` (generate against an amended draft). See [How GGUI works](/how-it-works/) for the full five-moment walk-through. ## What a hit costs [Section titled “What a hit costs”](#what-a-hit-costs) Nothing. Only generation is priced, from the tokens of the LLM call it made — so a render matched against a cached blueprint has nothing to bill. Details on [Credits, billing & BYOK](/hosted/billing/). Be honest with yourself about what the cache buys: today it saves the generation charge, not wall-clock time. Treat it as a cost lever and a consistency lever — the same ask returns the same component — rather than a latency guarantee. ## Promotion [Section titled “Promotion”](#promotion) Promotion is **automatic and best-effort**, not something you call. When a render misses the cache, generates successfully, and the deployment has a blueprint cache bound, the produced component is registered into the pool as part of finishing that render. If the registry write fails — a full disk, a misconfigured vector index — the render still succeeds and returns normally. Only the future cache hit is lost, and a `cache_write_failed` event is logged. The registry write is a performance optimization, never a correctness dependency, which is why it can never fail a render that already produced working code. Two other write paths put rows in the same pool, and the matcher reads all three identically: | Path | Who triggers it | | ----------------------------- | -------------------------------------------------------------- | | Cold generation | Automatic, on a successful `ggui_render` that missed the cache | | `ggui_ops_register_blueprint` | You, deliberately — hand-authored or imported rows | | `ggui blueprint install` | You, installing a marketplace or local artifact | The pool is capped per kind and evicts the lowest-hit entry first when full. Installed rows are exempt from that eviction — the install bridge owns their lifecycle. ## Durability [Section titled “Durability”](#durability) Blueprints carry **no TTL**: a blueprint is not on a clock. A registration that mints a fresh row writes through to a durable pair: the compiled body goes to object storage keyed by its content hash, and the metadata row points at that hash. The body is written first, deliberately. An orphan body is invisible and reclaimable; a row naming a hash with no body behind it is a lie that fails later, at the exact point it looked like it would succeed. If the body write fails, the row is still recorded — without the code hash, a state the protocol already models as “metadata recorded, no body stored”. Reclamation is operator-invoked, never scheduled: a takedown, an app retirement, or collection of bodies that have gone unreferenced long enough to be safely orphaned. A takedown records the content hash as a tombstone, and **both** halves of the durable write consult it — body upload and metadata row alike, with a consistent read. That is what makes removal stick: bodies are content-addressed, so without the body-side gate a later cold generation producing byte-identical code would simply re-upload to the same key. Retention across renders, blueprints, and account deletion is laid out in [Trust & security](/hosted/trust/#deletion--retention). ## Sharing a pool [Section titled “Sharing a pool”](#sharing-a-pool) A pool is per-app by default, but it does not have to stay there. * **Between your own deployments.** `ggui export-pool` writes this deployment’s reusable blueprints as a directory artifact; another deployment loads it with `ggui serve --seed-pool `. Seed pools are read-only, additive, and exact-key only — they are never written at runtime. * **Publicly.** A blueprint repo carries a `ggui.blueprint.json` manifest and publishes as a signed, versioned, content-addressable artifact. Browse what others have published at [hub.ggui.ai](https://hub.ggui.ai), or install with `ggui blueprint install`. The mechanics, signing postures, and what a signature does and does not prove are on the [marketplace](/hosted/marketplace/) page. ## Measuring your hit ratio [Section titled “Measuring your hit ratio”](#measuring-your-hit-ratio) Three surfaces exist today, and none of them is a dashboard. **Per render, on the wire.** `ggui_render` returns a `cache` marker alongside the render: ```ts // ggui_render output — the cache marker: { hit: true, // a stored component was served, no code generated llmCallsAvoided: 1, // generation calls skipped (0 on a fresh generation) cachedBlueprintId: "bp_…", // the matched component id similarity: 0.91, // cosine similarity — semantic matches only kind: "full-template", // full-template = stored component served; cold = freshly generated reason: "match-exact: …" // why this render reused or generated } ``` Log `hit` and `llmCallsAvoided` per call and you have your own hit ratio, computed from the same values the server used. `reason` is available by default — you do not need a verbose trace to find out why a match was declined. **Per handshake.** `suggestion.origin` tells you the routing decision one call earlier, before you commit. **Per app, on the control plane.** `ggui_ops_list_blueprints` enumerates blueprint metadata under an app you operate, filterable by contract hash, generator, persona, or intent keywords. It returns metadata only — code bodies stay in the store and are fetched by a render on a hit. The GGUI console’s per-app **Blueprints** tab manages your named blueprint library — rename, edit metadata, view source, delete — and shows a render count per named blueprint. It is not a view of the auto-promoted generation pool, and it does not aggregate a hit rate. Vision An aggregate hit-rate and blueprint-reuse view in the console is not built. Until it is, the numbers above are the ones you can trust, and instrumenting them agent-side is the only way to see the ratio over time. # Gadgets — deterministic islands > Why third-party capability enters generated UI only through human-authored, operator-gated wrappers — and what that buys you in safety, caching, and LLM reliability. A generated interface is LLM-written React. That works for layout, forms, and state — but the moment a UI needs a real map, a checkout flow, or the camera, “generate it” stops being an option. Nobody wants an LLM improvising a payments integration, and no model reliably reinvents Leaflet’s lifecycle quirks on demand. Gadgets are how GGUI resolves that tension: **the LLM composes third-party capability but never authors it.** A gadget is a human-written, versioned, integrity-pinned wrapper around a browser library, exposed to generated code as a React hook with one uniform contract. The generated component calls `useLeafletMap(...)` the same way it calls `useState` — everything inside that hook is deterministic, reviewed code. ## One pattern, learned once [Section titled “One pattern, learned once”](#one-pattern-learned-once) Every third-party library enters the system through the same factory ([`createGguiGadget`](/sdk/gadgets/)), so every gadget presents the same hook shape: call it with options, get back `{ value, status, start, … }`. The generator never sees raw library APIs — not Leaflet’s imperative `L.map()` lifecycle, not Stripe’s redirect dance. It sees one hook convention, which means: * **Cold generations get it right more often.** The model pattern-matches against one shape it has seen many times, not N library idioms it has seen unevenly. * **A new gadget costs the model nothing to learn.** The wrapper’s teaching text — `description` (what), `usage` (when), `example` (a concrete call) — travels with the descriptor, and the generator reads it at synthesis time. Docs for the LLM are part of the spec, not an afterthought: a wrapper without them is rejected at module load. ## Two symmetric capability surfaces [Section titled “Two symmetric capability surfaces”](#two-symmetric-capability-surfaces) Gadgets are the renderer-side half of a symmetric design ([glossary](/glossary/#capabilities)): | | Renderer | Agent | | ------- | ---------------------------- | ------------------------- | | Unit | **gadget** | **tool** | | Catalog | `clientCapabilities.gadgets` | `agentCapabilities.tools` | | Gives | something to render with | something to act with | Both catalogs are declared per app and bounded by the **operator**, not the agent. An agent cannot smuggle a capability into a render by asking for it: a contract may only reference gadgets the operator registered on the app, and a render naming an unregistered one is rejected with `gadget_not_registered` before any code runs. ## The trust chain [Section titled “The trust chain”](#the-trust-chain) Generated code runs in a sandboxed iframe with a closed Content-Security-Policy. Each gadget widens that sandbox **declaratively, not implicitly**: * **Provenance** — the wrapper bundle is fetched by exact package + version, and marketplace-published bundles carry a `sha384` subresource-integrity pin stamped at publish time. What loads is byte-identical to what was published. * **Network** — a gadget declares the origins it talks to (`connect: ["https://tile.openstreetmap.org"]`); the renderer unions exactly those into the iframe’s CSP. A map gadget can fetch tiles; it cannot phone anywhere else, and neither can the generated code around it. * **Secrets** — wrappers that need a token (Mapbox, Stripe) declare the `GGUI_PUBLIC_APP_*` keys they consume, and the operator supplies values through the app’s public-env channel. Keys never appear in generated code. The result: the only non-generated code in a render is code an operator explicitly registered, at a pinned version, with a declared network footprint. ## Why versioning feeds the cache [Section titled “Why versioning feeds the cache”](#why-versioning-feeds-the-cache) A gadget’s `version` is part of the [blueprint cache key](/concepts/blueprints-and-the-cache/). Bump a wrapper and every cached generation built against the old version stops matching automatically — no stale UI silently calling a changed hook contract. This is the same discipline that makes blueprint reuse safe in general: the cache key captures everything the compiled component depends on. ## The standard library [Section titled “The standard library”](#the-standard-library) Browser capabilities that need no third-party code ship as **STDLIB hooks** — `useGeolocation`, `useCamera`, `useClipboardWrite`, `useClipboardPaste`, `useNotifications`, `useFilePicker`, `useMicrophone`. They follow the same hook contract but require no operator registration; the generator can reach for them whenever the ask calls for one. ## What a gadget is not [Section titled “What a gadget is not”](#what-a-gadget-is-not) * **Not a template.** A gadget renders one capability (a map, a chart, a checkout); the generated component decides where it sits, what feeds it, and what happens around it. Composition stays generative; capability stays deterministic. * **Not agent-side.** Gadgets never execute in the agent’s process and never see the conversation. Anything the agent should *do* is a tool. * **Not a behavior escape hatch.** The contract describes data flowing between agent and UI; gadgets extend what the *component code* can do. Neither is a channel for smuggling the other — see [Sessions & the event model](/concepts/sessions-and-the-event-model/) for the placement rule. ## Next [Section titled “Next”](#next) * **[Gadgets SDK](/sdk/gadgets/)** — author a wrapper: the `createGguiGadget` factory, teaching-text budgets, bundle + types publishing, operator registration. * **[Marketplace](/hosted/marketplace/)** — publish and install gadgets across apps. * **[Blueprints and the cache](/concepts/blueprints-and-the-cache/)** — how versioned capability feeds exact-match reuse. # Rehydration > Why an old GGUI card in chat history still works — how a resources/read on an evicted locator re-mints a live session with the same identity and a fresh channel token. Scroll back far enough in most agent chats and the interactive parts are dead. A form that submitted last month is now a grey rectangle, or a spinner that never resolves, because the thing behind it — a session, a socket, a signed URL — expired long ago. The transcript keeps the picture and loses the mechanism. GGUI is built so that does not happen. An old card is not a screenshot of a render; it is a **locator**, and reading the locator again is what brings the render back. ## What a read does [Section titled “What a read does”](#what-a-read-does) A GGUI render is addressed by an MCP-Apps resource URI: ```plaintext ui://ggui/render/[/][#] ``` When a host mounts a card from history, it issues an authenticated `resources/read` on that URI. The server tries three resolutions in order, and any of them can produce a live mount: | Order | Resolution | | ----- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | | 1 | **The render row itself**, when it is still there. A row past its expiry is put back into service, not refused. | | 2 | **A re-mint from the durable identity record**, when the row is gone. | | 3 | **The blueprint registry**, keyed by the locator’s own `blueprintKey` — the original card with authoring-time defaults, not the state the render last held. | The re-mint is the interesting one. The server reads the identity record for that `sessionId`, resolves the blueprint it names, pulls the compiled component body from content-addressed storage, and commits a fresh render row — **same `sessionId`, same `createdAt`, same props** — then mints a new `wsToken` for it. The host gets back a normal live mount. Nothing in the response says “this was resurrected”, because from the protocol’s side nothing was: the identity is continuous. The event ledger resumes rather than restarts. The identity record carries the render’s `eventSequence` at its last commit, and the re-minted row seeds its ledger above that floor, so a reader still holding a cursor from before the eviction sees new events instead of filtering them out as already-seen. Events appended between that last commit and the eviction are not reflected — the record samples the sequence at commit — so sequence reuse is narrowed to that window rather than eliminated. ## What persists, what is re-minted [Section titled “What persists, what is re-minted”](#what-persists-what-is-re-minted) Durable, written once and kept: * **The render row** — for as long as its retention allows (see below). * **The identity record** — one row per delivered render, keyed by `sessionId`: owning app, owning user, the blueprint id and the contract/variant keys, the props at the last commit, and the sequence floor. It deliberately carries no richer identity block than `userId`, because it is retained for as long as the render is addressable. * **The blueprint row and its body** — blueprints carry no TTL, and bodies are content-addressed in object storage so many renders share one. Re-minted per read, never stored: * **The `wsToken`** and its `wsUrl`, plus the token-bearing polling and SSE URLs. Tokens are short-lived by design; a card from six months ago gets a token minted at the moment you open it. * **The code URL** and its strict-CSP module twin. * **The presentation sidecars** — gadget descriptors and the theme overlay are re-resolved from the *current* app record rather than snapshotted, so a rehydrated render mounts under today’s configuration. These degrade quietly: a metadata lookup having a bad moment costs the render its theme, never its rehydrate. One thing the re-mint refuses to do: substitute authoring-time defaults for props the record does not have. A record with no props describes a render that had none, and it is given none. Nothing repopulates a defaults-booted card afterwards — props travel the session channel, and no agent turn runs at rehydration — so plausible-looking wrong state would sit there indefinitely. ## The retention posture that makes it work [Section titled “The retention posture that makes it work”](#the-retention-posture-that-makes-it-work) Rehydration is only worth building if the records are still around. On hosted ggui: * **The default render TTL is effectively indefinite** — 100 years, so `resources/read` on an old card finds the live row rather than falling through to the registry. One knob drives every lifecycle site: the wire-level `expiresAt`, the row’s TTL stamps, and the sliding extensions on heartbeat and consume. * **Resurrection can be capped.** A deployment running short TTLs can bound total render lifetime, so neither the expired-row extension nor a re-mint’s fresh commit pushes expiry past `createdAt` plus that cap. It is unset by default, which is the right pairing with indefinite retention. * **Deletion is by path, not by schedule.** Account erasure removes identity records by primary key alongside the renders they name; deleting an app removes its saved blueprints, its render identity rows and the reuse-cache blueprint rows it owns, but not its render records, which are deleted with your account or by an operator on request; and an operator takedown purges a blueprint body by content hash and writes a tombstone — there is no un-takedown operation. The full statement, including what survives an account deletion on purpose, is on [Trust & security](/hosted/trust/#deletion--retention). ## What the host has to do [Section titled “What the host has to do”](#what-the-host-has-to-do) Nothing special. Rehydration rides the standard MCP `resources/read` path — there is no ggui-specific “reopen” call, no extra capability to advertise beyond `io.modelcontextprotocol/ui`, and no separate endpoint. A host that can mount a fresh render can mount an old one with the same code. Two details are worth getting right: * **Read the per-render locator, not the declaration.** The per-render resource inlines the bootstrap slice, so an old card paints with no host relay. The declaration-level static shell paints too, but only through the host: it needs the forwarded tool result, and when that result carries only the locator, one host-proxied `resources/read` of it (the [read-plane door](/protocol/bootstrap-handshake/#the-read-plane-door)). * **Parse for the optional second segment.** Both the single-segment and two-segment forms resolve; the older single-segment shape stays registered so pre-resume-contract cards still in chat history rehydrate. A `#` fragment pins an immutable record, and a pinned read serves identical content forever. ## Honest limits [Section titled “Honest limits”](#honest-limits) Rehydration is not resurrection from nothing. Every failure is a typed JSON-RPC error rather than a shell that never paints: * **`NOT_FOUND` (`-32002`)** — nothing resolved the locator. It is also the answer for a caller who is *not allowed* to read a locator that does resolve, and the two are byte-identical by construction: the projection substitutes a constant message and drops any detail. A distinguishable refusal would turn this read into an oracle for the existence of other people’s renders, so the equality is a security property rather than a courtesy. * **`NOT_SUPPORTED` (`-32006`)** — the same two cases on a server that keeps no durable substrate, where an evicted locator can never come back. It replaces `NOT_FOUND` wholesale on such a server, for the same anti-oracle reason. A server that binds the substrate never emits it. * **`BLUEPRINT_UNRESOLVABLE` (`-32006`)** — a record named the render, but its component is gone: taken down, purged with a retired app, or collected as an orphaned body. The `detail` field names which link broke. * **`NOT_MOUNTABLE` (`-32006`)** — something resolved but nothing mountable came of it: no delivery channel wired, or a generation that never committed a component. And the access boundary holds through rehydration exactly as it does on a fresh render. The read gate fails closed without a request context, requires the row’s app to match the caller’s, and binds an end-user caller to the row’s subject. A render whose app was deleted, whose owner erased their account, or whose connector key no longer authenticates is not reachable by anyone — that is the retention story working, not a gap in it. The behavior on this page is arbitrated by the [conformance kit](/protocol/conformance/), which ships a `resources/read` binding driver: any successful `contents` result is a live mount, and every other outcome is one of the four codes above. # Sessions and the event model > What a GguiSession is, how the two inbound contract specs split, and why the interaction loop is driven by the agent rather than the server. Every GGUI exchange runs on two ideas: a **GguiSession** — one rendered UI with a stable id — and a **placement rule** that decides where each thing the user does shows up on the wire. Get both right and the loop is small: render, consume, react, repaint. This page is conceptual. The wire shapes live in [MCP Protocol](/api/mcp-protocol/) and [Envelopes](/protocol/envelopes/); nothing is duplicated here. ## A GguiSession is one rendered UI [Section titled “A GguiSession is one rendered UI”](#a-gguisession-is-one-rendered-ui) A GguiSession is minted server-side inside `ggui_render` — one per UI emission — and keyed by a stable `sessionId`. It carries the compiled component, the props the agent rendered, and the contract that pins the wire surface. The server is the authority on its state, not the agent. There is no conversation-level session object. Each `ggui_handshake` → `ggui_render` pair mints a fresh `sessionId`; sibling cards inside the same host chat are grouped through the `_meta["ai.ggui/host-session"]` slice, captured once at creation. Your agent never threads a conversation id. → [Glossary → GguiSession](/glossary/#gguisession-a-render) ## Two inbound specs, one test [Section titled “Two inbound specs, one test”](#two-inbound-specs-one-test) A contract has four specs. Two of them are inbound — they carry what the UI tells the agent’s side: | Spec | Direction | Cardinality | Drives an agent turn | | ------------- | ---------------------- | ---------------------- | -------------------- | | `actionSpec` | UI → agent | discrete events | Yes, every entry | | `contextSpec` | UI → server (mirrored) | state, last-write-wins | No, never | The placement test is one question: > Does this thing need the agent’s next-turn reasoning? Yes → `actionSpec`. No → `contextSpec`. There is no third inbound category, and no flag that softens one into the other. If you reach for `terminal: false` on an action to stop it waking the agent, the thing you are describing is state. ### Worked example [Section titled “Worked example”](#worked-example) A feedback card after a support chat. Three things happen in it, and each lands somewhere different: ```ts // contract sketch — the two inbound specs actionSpec: { submit: { label: "Send feedback", schema: { type: "object", properties: { rating: { type: "number" }, comments: { type: "string" } }, }, }, }, contextSpec: { category: { schema: { type: "string" }, default: "all" }, draft: { schema: { type: "string" }, default: "" }, } ``` * **The user presses Send.** That is an action. The agent must read the payload and decide what happens next, so `submit` lives on `actionSpec` and reaches the consume pipe as its own event. * **The user switches the category filter.** That is context. The agent does not react per switch, but when it next does work it wants to know what the user was looking at. It lives on `contextSpec` and is mirrored continuously. * **The card scrolls the newest comment into view.** That is neither. Nothing about it crosses the wire, so it is not on the contract at all — it is behavior, written into the generated component code. The third bullet is the split the placement rule sits inside: **the contract describes data flow; the component code describes behavior.** Scroll, focus, debounce, toast, animation, clipboard writes and local drafts are component decisions. Put them on the contract and every renderer has to honor them identically, and two contracts for the same logical UI stop hashing the same — which is how blueprint reuse fragments. If the agent genuinely must know that a behavior happened, the *signal* becomes an action or a context slot; the *mechanic* stays in component code. ## The loop is agent-driven [Section titled “The loop is agent-driven”](#the-loop-is-agent-driven) Actions do not call your tools. The server appends each gesture to a render-scoped pipe, and your agent drains it by calling `ggui_consume({ sessionId })` — a long-poll that returns on the first event or at timeout, with consume-once semantics. Each row carries the action key that fired, its validated payload, and `uiContext` — the `contextSpec` snapshot taken **at the moment the user acted**, not whatever the state had drifted to by the time consume returned. That is why context needs no event channel of its own: it rides along with the action that woke you. Two properties follow from the loop being yours: * **`nextStep` is advisory.** An `actionSpec` entry may name a tool to run next. Implementations must treat it as a hint; the agent owns the call decision. * **There is one routing model.** A deployment with no agent attached queues events on the same pipe until one attaches and drains them. The server never invokes a tool on the user’s behalf. Exit the loop when you have the events you need — that is the real terminal condition. `status: "expired"` is the other exit and only fires when a render’s TTL actually elapses. → [`ggui_consume`](/api/mcp-protocol/#ggui_consume) ## Amend repaints, update writes history [Section titled “Amend repaints, update writes history”](#amend-repaints-update-writes-history) After you react to an event you usually want the card to reflect it. Two tools, and the choice is about the transcript, not the mechanics: * **`ggui_amend`** repaints the already-mounted card in place. No new card appears, the history number does not advance, and scroll position, focus and uncommitted input survive. This is the default move in the gesture loop: consume → domain tool → amend → consume again. Skipping the amend is the most common wire-compliance bug. * **`ggui_update`** mints the updated state as a new card. The epoch advances by one and the previous card freezes as a history record, so the transcript stays an honest account of what the user actually saw. Use it for milestones worth showing. Neither changes the contract. When the surface itself must change shape, handshake and render a fresh session. → [`ggui_amend` and `ggui_update`](/api/mcp-protocol/#ggui_update) ## How long a session lives [Section titled “How long a session lives”](#how-long-a-session-lives) There is no close ceremony, because there is nothing to close. When an exchange is over, your agent stops addressing that `sessionId`. On hosted GGUI the default retention is effectively indefinite, so reopening an old card is the expected path rather than a lucky one. There is no per-render time limit, and self-hosted deployments set their own default. Because the record is durable, a host that reads the same `ui://` locator later gets the view back. If the live row has been evicted, the read re-mints it — from the stored identity record when the deployment keeps one, or from the blueprint named in the locator, which returns the original card with its default props rather than a typed failure. Old cards rehydrate; they do not go stale. → [Render locator grammar](/api/mcp-apps/#render-locator-grammar) for the URI shape, including the epoch pin ## See also [Section titled “See also”](#see-also) * [How GGUI works](/how-it-works/) — the same lifecycle as a narrative walkthrough * [MCP Protocol](/api/mcp-protocol/) — every tool’s input and output * [Envelopes](/protocol/envelopes/) — live-channel wire reference * [Glossary](/glossary/) — term lookup # Why generative UI > The technical argument for letting an agent render interfaces instead of answering in prose — what generation buys, what the typed action payload tells you, and where generative UI is the wrong tool. Your agent already works. The question this page answers is narrower: should it render an interface, or keep answering in text? The case for rendering is not that UI looks better. It is that a form returns a **typed payload** where prose returns a sentence you have to parse, and that generating the form costs you no frontend. ## The problem: prose round-trips [Section titled “The problem: prose round-trips”](#the-problem-prose-round-trips) An agent that only speaks has one way to collect structured input — ask, read the reply, guess what the user meant, ask again. Every field is a turn, every turn is an LLM call, and the answer arrives as free text that nothing validated. GGUI replaces that loop with one exchange. The agent declares a contract; the user fills the interface; the gesture comes back as a validated payload. The server checks the submitted data against the contract’s `actionSpec` before your agent ever sees it (see [How GGUI works](/how-it-works/#3-interact--the-user-fills-the-ui)). Five prose turns collapse into one render and one drain. ## What generation buys [Section titled “What generation buys”](#what-generation-buys) **One contract, many surfaces.** A render is an MCP-Apps resource (`ui://ggui/render/`), not a page you deploy. The same contract mounts inline in Claude Desktop and claude.ai, in your own React web app through ``, and in React Native through `` — see [React host helpers](/host-helpers/react/) and [React Native host helpers](/host-helpers/react-native/). You describe the data once; the surface is the host’s problem. **No frontend build.** There is no component to author, no route to add, no deploy to ship a screen your agent needed for the first time this morning. The generator takes the contract — `PropsSpec` + `ActionSpec` + `StreamSpec` + `ContextSpec` — and returns a compiled, contract-typed React module ([UI Generator](/architecture/ui-generator/)). **Blueprint reuse makes repeat renders cheap.** GGUI is blueprint-first: its reuse layer, the semantic cache for generative UI, runs before generating. An exact canonical-key lookup is deterministic and calls no model at all; when that misses, a fast reranking model chooses among cached candidates, and only a miss on both falls through to a cold generation that then caches its own result. On a cache hit the render is served with **zero generation calls** ([generation pipeline](/architecture/overview/#generation-pipeline)). The more an app reuses contract shapes, the more of its traffic takes the matched path. **Quality is measured, not asserted.** Generation quality runs nightly across a three-tier model matrix and is scored by a three-provider judge panel at temperature 0, with a pass threshold of 70 and the per-cell spread published alongside the mean. The methodology, the corpus, and how to reproduce a run are in [Benchmark methodology](/architecture/benchmarks/). ## What you learn [Section titled “What you learn”](#what-you-learn) This is the part that is easy to undersell. Web analytics infers intent from behavior — clicks, scroll depth, funnel drop-off, a session replay you watch and interpret. A GGUI action does not need interpreting, because the user’s intent is the wire format. Every gesture your agent drains from `ggui_consume` is a `ConsumeEventEntry`: | Field | What it tells you | | ------------ | ------------------------------------------------------------------------------------ | | `intent` | Which `actionSpec` entry the user fired — the named thing they chose to do | | `actionData` | The typed payload, already validated against `actionSpec[intent].schema` | | `uiContext` | The contract’s `contextSpec` slot values snapshotted at the instant of the gesture | | `actionId` | An 8-hex correlation id matching the iframe’s toast key and the server’s `drain_ack` | | `firedAt` | ISO 8601 timestamp of the gesture, from the iframe | That is ground truth about what a person decided, not an inference about what they probably meant. It arrives in your agent’s own loop, so you can act on it in the same turn — and store it, aggregate it, or feed it back into the next render however you like. Vision — not shipped There is no aggregate analytics surface in the GGUI console today. The console gives you the per-app blueprint library, gadgets, keys, theme, marketplace, and a credits ledger with per-render charges — not funnels, cohorts, or an action-event explorer. If you want aggregates over gestures, collect the `ggui_consume` rows yourself. A first-party analytics view is a direction, not a product you can switch on. ## The honest limits [Section titled “The honest limits”](#the-honest-limits) * **Cold generation is not instant.** A render that misses the cache runs the generator and takes tens of seconds ([How GGUI works](/how-it-works/#2-render--the-ui-gets-generated-or-matched)). A cache hit removes the generation call, which is a real cost saving — but as measured on the current warm path it does not yet buy you a proportional latency saving. Design the first render of a new shape as something the user is willing to wait a beat for. * **The code was written by a model, and it runs in a sandbox.** Generated components mount in an iframe with `allow-scripts allow-forms` and deliberately without `allow-same-origin`, so the frame cannot read the embedding page; capabilities like camera or clipboard-write are granted only when the contract asked for them. Inside a third-party host, that host owns the sandbox and its CSP, and that surface is opaque to ggui. Read [Trust & security](/hosted/trust/) before you decide this is acceptable for your data. * **Inline mounting depends on the host.** A host that does not advertise the MCP Apps capability still gets a working `ggui_render` — it just cannot mount the resource inline ([Connect other MCP hosts](/clients/connect-other-hosts/#things-every-host-needs)). * **Generation is not deterministic.** Two cold generations of the same intent are not guaranteed to produce the same component. Determinism comes from the exact-key blueprint path, not from the model. ## When not to use it [Section titled “When not to use it”](#when-not-to-use-it) Generative UI is the wrong tool when the interface itself is the product: * **Brand-critical static surfaces.** Marketing pages, pricing tables, anything a designer signed off on pixel by pixel. Build those; GGUI has nothing to add. * **Pixel-exact or regulated flows.** If a screen must be byte-stable across renders — a legal disclosure, a certified checkout, a screen an auditor compares against a spec — you want a committed component, not a generated one. * **One screen, used constantly, never varying.** If your agent renders the same shape a thousand times a day, the generation is pure overhead. Register that shape as a blueprint so the deterministic exact-key path serves it every time, or build it as a normal component and let your agent link to it. * **No structured decision to collect.** If the user’s next move really is a sentence, prose is the right interface. UI earns its place when there is a choice to make, a field to fill, or state to watch. The test is simple: does the turn end with the user *deciding* something? If yes, a render turns that decision into typed data. If no, keep talking. ## Next [Section titled “Next”](#next) * [How GGUI works](/how-it-works/) — the five moments of an exchange, end to end. * [Build an agent on hosted GGUI](/quickstart/hosted-agent/) — the shortest path to a first render against `https://mcp.ggui.ai`. * [Trust & security](/hosted/trust/) — what is stored, what reaches a model, and where the sandbox ends. # Credits, billing & BYOK > How hosted GGUI charges for renders — one product, pay-as-you-go from a prepaid credit balance at published rates per render kind, with no subscription of any kind — plus the welcome credit, top-ups, coupons, and what changes when you bring your own provider key. Hosted GGUI is **one product, paid as you go**: every render is charged to a prepaid credit balance at a published rate per render kind, and a one-time welcome credit on sign-up, while it is available, is the free entry — no card, no plan to pick. The rates, the welcome credit and the top-up presets live in one place, [ggui.ai/pricing](https://ggui.ai/pricing); this page is the mechanics. Everything on this page lives at `/credits`, `/keys/providers`, and each app’s **Billing** tab in [the GGUI console](/hosted/console/). ## One product, prepaid credit [Section titled “One product, prepaid credit”](#one-product-prepaid-credit) There are no plans to choose between and nothing is metered monthly. A render costs its per-kind rate, debited from the **app owner’s** prepaid balance at render time, and a balance at or below zero refuses the next render — on your own provider key too, since the platform lane is still charged — until you top up. Published rates, no subscription of any kind: there are no usage bands, and nothing is withheld from a small account. **Enterprise** is a conversation, not a price: negotiated rates, invoicing and terms through . **The free entry.** A new account receives a one-time welcome credit on first sign-in while it is available, with no card, and renders on it until it is spent — the same rates as purchased credit, the same product. It does not expire: there is no separate trial state, no render count to run out of and no day clock, and when the welcome credit is gone a top-up continues exactly where you were. ## What a render costs [Section titled “What a render costs”](#what-a-render-costs) Each render is priced by its kind — a **cold generation** (the LLM synthesized a component), a **cache hit** (the render matched an existing blueprint and skipped generation; cheaper, but not free — see the [generation pipeline](/architecture/overview/#generation-pipeline)), or a **BYOK render** (your own provider key paid for the model call, so GGUI charges only its platform lane). The three rates are on [ggui.ai/pricing](https://ggui.ai/pricing). The rates apply unless a model has its own rate set for your account, as when a premium model is enabled. Larger models are enabled per account on request, not by default, and charged at a per-model rate set for your account, in place of the render rate; that page does not list those rates (see [Premium models](#premium-models)). A pool-funded render that asks for a model other than the pool default, with no row, is refused with `model_not_allowed` rather than silently re-priced. Charges accrue per render and are debited to the app owner’s balance in whole cents, carrying sub-cent remainders forward — a render is never rounded up on its own. An app may also carry an optional hard monthly spending cap, set on request: write to with the app and the monthly amount, and we set, change or remove it for you. Once the app’s render spend for the month reaches the cap, generation is refused (`hard_cap_exceeded`) until the cap is raised or the month resets. Pool-funded renders draw on GGUI’s own platform pool, which covers Anthropic (direct or routed through Bedrock), OpenAI, Google, and OpenRouter. A render routed to any provider outside that set is refused with a `402` pointing you at BYOK. ### Premium models [Section titled “Premium models”](#premium-models) On a pool-funded render the model is resolved from the app’s generation setting, then the request’s `infra.model`, then the pool default. Any model other than the pool default must have its own **rate-card row for your account** — one row per model, carrying the three lanes above (cold generation, cache hit, BYOK platform lane). No premium model is enabled by default: every account starts with the pool model only, and a row is seeded for your account on request. A model with no row is refused before anything is read or spent, with `model_not_allowed` and a fix in the message: send the pool default (or omit `infra.model`), bring your own key for that model, or ask to enable it. The gate does not apply to BYOK renders — your key, your model — or to guuey-managed apps, which are metered to the platform under their own policy. The rows seeded for your account are listed in the console: the **Premium models** card on the app’s Billing tab (`console.ggui.ai/apps//billing`) shows one row per enabled model route, with the cold-generation, cache-hit and BYOK-lane rate per render — the same rows the gate prices from. A render on a listed model bills its row’s rate in place of the standard rate above. When no premium model is enabled the card says so; the pool model is always available, and to run another model on the app you bring your own key for it or write to . The Settings model picker is a different thing: it lists the model registry, not the rate-card rows, so a model picked there is still subject to the gate above. ### Effort add-on [Section titled “Effort add-on”](#effort-add-on) An app can ask for more effort on its fresh generations: more tries, more evaluation rounds, and a higher quality bar for the generator’s own check. The add-on is charged on top of the fresh-generation rate, at the level the generation applied. An app that sets no level pays no add-on, and neither do generations on your own model key or cache hits. | Level | Add-on | What it gets | | --------------- | --------- | ---------------------------------------------------------- | | `low` effort | no add-on | Up to 5 tries and 1 evaluation round, quality bar 65/100 | | `medium` effort | no add-on | Up to 8 tries and 2 evaluation rounds, quality bar 70/100 | | `high` effort | +2¢ | Up to 8 tries and 3 evaluation rounds, quality bar 75/100 | | `xhigh` effort | +9¢ | Up to 10 tries and 3 evaluation rounds, quality bar 80/100 | | `ultra` effort | +25¢ | Up to 12 tries and 4 evaluation rounds, quality bar 85/100 | ## Welcome credit [Section titled “Welcome credit”](#welcome-credit) New accounts receive a one-time welcome credit on first sign-in while it is available; it appears as a `Free credit` row in the transaction log, the amount shows on `/credits` (and on [ggui.ai/pricing](https://ggui.ai/pricing)), and it does not expire. It is the free entry: renders draw on it at the same rates as on purchased credit, and when it is spent a top-up continues from the same balance. The welcome credit is granted to a limited number of new accounts. Once that number is reached, a new account gets no credit, and the console says so instead of showing a $0 balance: “Welcome credit isn’t available right now. Top up to start rendering.” A top-up works the same way from there. ## Running out [Section titled “Running out”](#running-out) Before any render runs — pool-funded or on your own provider key, since a BYOK render still charges the platform lane — GGUI checks the **app owner’s** balance: the owner’s wallet, whichever key made the call. Above zero proceeds; at or below zero is refused with a `402` (`insufficient_credit`) and a fix hint that points at `/credits`, rather than a silent failure. The threshold is deliberately “above zero”, not “enough to cover this render”. A balance of a few cents still admits the next render, which can drive the balance negative and records the true debt; the next check sees a non-positive balance and refuses. You never get a free loop, and you never get a render cancelled halfway for being a cent short. ## The transaction log [Section titled “The transaction log”](#the-transaction-log) Every movement is one row: what it was, when, the signed amount, and the balance afterwards. Four kinds appear: | Kind | What it is | | ------------- | -------------------------------------------------------------- | | `Free credit` | The welcome credit on first sign-in | | `Render` | The charge for one render, tagged with the session it paid for | | `Top-up` | Credit purchased through Stripe | | `Refund` | Credit returned to the wallet | ## Topping up [Section titled “Topping up”](#topping-up) Click **Top up** on `/credits`, pick one of the preset amounts ($10, $50, $100) or type a custom one, and check out through Stripe. Credit lands when Stripe confirms the payment, which is usually a few seconds behind the redirect back to the console. The page keeps refreshing the balance for about half a minute after you return, and offers a manual refresh if the confirmation takes longer. A cancelled checkout charges nothing. ## Coupons [Section titled “Coupons”](#coupons) A coupon code (`cpn_…`) is redeemed from the same page. If you belong to any orgs, the redeem form lets you choose where the credit lands — your personal wallet, or any org wallet you are a member of. See [Orgs and teams](/hosted/orgs/) for how shared wallets work. ## Bring your own key (BYOK) [Section titled “Bring your own key (BYOK)”](#bring-your-own-key-byok) Store a provider API key and GGUI will call that provider on your account rather than out of its own pool. Four providers are supported, each with the console dialog’s get-a-key path: * **Anthropic** — Claude models. `console.anthropic.com` → Settings → API Keys. * **OpenAI** — GPT models. `platform.openai.com` → API Keys. * **Google** — Gemini models. `aistudio.google.com` → Get API key. * **OpenRouter** — multi-provider routing. `openrouter.ai` → Settings → Keys. ### How keys are stored [Section titled “How keys are stored”](#how-keys-are-stored) Submit the plaintext once. It is validated against the provider, encrypted with KMS under an encryption context bound to your account and the provider, and persisted as ciphertext — it is decrypted in memory only, on the request that needs it. Afterwards the console shows the provider, your label, the last four characters, and when the key was last used. The plaintext is never readable again, by you or by GGUI’s own console. Remove a key at any time from the same card. ### Account-wide keys and per-app overrides [Section titled “Account-wide keys and per-app overrides”](#account-wide-keys-and-per-app-overrides) `/keys/providers` holds your account-wide keys. An individual app can override them on its own **Keys** tab, and the app-level key wins for renders bound to that app — a published app can run on its own provider quota instead of drawing on yours. The two scopes are encrypted under different contexts, so an app’s stored key cannot be decrypted through the account-scoped path, or the reverse. ### What BYOK changes about billing [Section titled “What BYOK changes about billing”](#what-byok-changes-about-billing) When a render actually runs on your provider key, your provider account pays for the model call and GGUI does not charge for the generation — charging you again would be double billing. A BYOK render carries only GGUI’s platform lane rather than the cold-generation or cache-hit rate (rates on [ggui.ai/pricing](https://ggui.ai/pricing)) — and that lane is charged to the same prepaid balance, so the pre-render balance check applies to BYOK renders too: an owner at zero is refused `insufficient_credit` even on their own key. Bringing a key changes who pays for the model call, not whether the wallet is read. A stored key alone does not redirect billing Whether a given app’s generation routes to your key is an app-level setting (`generation.keySource`), and an app that has not opted into running on its own key stays pool-funded even with a provider key on file. Flip it in the console — the **Generation billing** card on the app’s **Keys** or **Settings** tab — or write it through the app-config API. If you expect BYOK to be paying and the transaction log still shows `Render` charges, this is why. Resolution is per provider, so mixing is fine: for an app running on its own key, a render routed to a provider you have a key for uses that key, and anything else falls back to the credit pool. # Connector keys > What a ggui_user_* connector key is, the three ways to mint one, how per-app scoping and revocation work, and why it is not the same thing as a marketplace publisher key. A **connector key** is the bearer token that authenticates something — your agent, or an MCP host acting on your behalf — to hosted GGUI at `mcp.ggui.ai`. Keys are prefixed `ggui_user_` and travel as an ordinary HTTP header: ```plaintext Authorization: Bearer ggui_user_… ``` That is the whole authentication story for the data plane. No client SDK, no session cookie, no signing step. ## Minting a key [Section titled “Minting a key”](#minting-a-key) Three paths mint the same kind of row, and all three land in the same list in [the GGUI console](/hosted/console/). ### From the console [Section titled “From the console”](#from-the-console) Open **Connector keys** (`/keys/connector`), optionally type a label (`Claude Desktop — laptop`), and click **Generate connector key**. The secret reveals exactly once — copy it before you dismiss the dialog. There is no recovery: lose it and you mint a new one. ### From an MCP host, through OAuth [Section titled “From an MCP host, through OAuth”](#from-an-mcp-host-through-oauth) When Claude Desktop or another MCP-Apps-aware client connects to `mcp.ggui.ai`, the [OAuth ceremony](/clients/claude-desktop/) sends your browser to the console’s consent screen. **Approve** mints a fresh key and hands it back to the client — you never see or paste it. The default label is built from the requesting client and the date: ```plaintext MCP — — ``` When the host asked for a specific app (an RFC 8707 `resource` indicator naming one of your apps), the app’s display name is folded into the same template: ```plaintext MCP — — — ``` The consent screen carries an optional **Key name** field that overrides the default before you approve. **Cancel** mints nothing — the client is redirected back with `error=access_denied` and the MCP server is never contacted. ### From the CLI [Section titled “From the CLI”](#from-the-cli) Sign the CLI in once with the device flow, then mint from your terminal: ```bash ggui login ggui keys create --name "my agent runtime" ``` The secret prints exactly once, GitHub-PAT style. Pass `--expires-at ` to give the key a hard expiry. See [`ggui login`](/cli/login/) for the full device-flow walkthrough and the `--keys-file` variant that needs no account at all. ## Account-wide and per-app keys [Section titled “Account-wide and per-app keys”](#account-wide-and-per-app-keys) `/keys/connector` mints **account-wide** keys — they resolve to your default app when a session binds. An app’s own **Keys** tab (`/apps/[appId]/keys`) mints keys bound to that `appId`, so a session opened with one is locked to that app. The programmatic endpoint for a per-app key carries the app in the path: ```plaintext https://mcp.ggui.ai/apps/ ``` OAuth flows that carried a per-app `resource` indicator bind the `appId` onto the minted row the same way. ## Listing and revoking [Section titled “Listing and revoking”](#listing-and-revoking) The console’s key list shows one row per key: the `ggui_user_` prefix, the label, created and last-used dates, and status (`active` or `revoked`). It is read-only today — revocation is a CLI operation: ```bash ggui keys list ggui keys revoke ``` Revoke is a soft delete. The row stays for audit, and every subsequent request presenting that key returns `401 Unauthorized`. There is no undo; generate a replacement and reconnect whatever you still want connected. Revocation is per key, not per host. Every host holding that key loses access at the same moment — which is the argument for issuing one key per host, so you can cut off one without disturbing the rest. Deleting an app revokes that app’s per-app keys as part of the cascade (the rows are kept for audit). ## Connector keys are not publisher keys [Section titled “Connector keys are not publisher keys”](#connector-keys-are-not-publisher-keys) Two different key systems live under the `ggui keys` command. They share a noun and nothing else. | | Connector key | Publisher key | | ------------- | ------------------------------------------ | -------------------------------------------------------------- | | Shape | `ggui_user_…` bearer secret | Ed25519 keypair on disk | | Purpose | Authenticate to `mcp.ggui.ai` | Sign marketplace artifacts | | Created by | Console, OAuth consent, `ggui keys create` | `ggui gadget publish` / `ggui blueprint publish`, on first run | | Registered by | Nothing — it works immediately | [`ggui keys register`](/cli/keys-register/) | If you are wiring an agent or an MCP host, you want a connector key. Publisher keys only matter when you [publish to the marketplace](/hosted/marketplace/). # console.ggui.ai > User dashboard for the hosted mcp.ggui.ai server — apps, orgs, connector keys, blueprints, credits, BYOK provider keys, and OAuth/CLI consent. [`console.ggui.ai`](https://console.ggui.ai) is the user-facing dashboard for the [`mcp.ggui.ai`](/clients/claude-desktop/) hosted MCP server. Sign in with Google, GitHub, or email (Cognito). The left-sidebar nav surfaces ten screens in three task-verb groups — Build, Configure, Account. Three more screens are deep-linked into by the OAuth ceremony, the CLI device flow, and an org-invite email — the last is separate from the **Invites** screen already in the nav, which lists your own pending invites rather than accepting one. | Group | Screen | Path | What lives here | | --------- | -------------- | --------------------- | --------------------------------------------------------------------------- | | Build | Apps | `/apps` | Per-app surfaces — keys, blueprints, gadgets, marketplace, theme, settings. | | Configure | Connector keys | `/keys/connector` | Mint and list `ggui_user_*` API keys (revoke via the CLI). | | Configure | Provider keys | `/keys/providers` | BYOK — paste your Anthropic / OpenAI / Google / OpenRouter keys. | | Configure | Author keys | `/keys/authors` | Publisher Ed25519 signing keys — list and two-step revoke. | | Configure | Credits | `/credits` | Balance, transaction log, coupon redeem, Stripe top-up. | | Account | Orgs | `/orgs` | Organizations you belong to; org-scoped wallets, invites, members. | | Account | Invites | `/invites` | Your own pending org invites, looked up by email. | | Account | Connected apps | `/connections` | OAuth clients that have access to your account — see below. | | Account | Account | `/account` | Email, default app, sign out. | | Account | Support | `/support` | Contact GGUI — one page, one email, no case system yet. | | — | OAuth consent | `/oauth/consent` | Approval landing for MCP-Apps-aware clients (Claude Desktop, etc.). | | — | CLI sign-in | `/cli-confirm/[code]` | Approval landing for the [`ggui` CLI’s](/cli/login/) device flow. | | — | Org invite | `/invites/[inviteId]` | Auto-accept landing for an org-invite email link. | The home path `/` redirects to `/apps` — apps are the primary primitive in the current IA (post-2026-05 apps pivot). You don’t visit `/oauth/consent` or `/cli-confirm/*` directly — the MCP host or the CLI navigates you there at the right moment. ## Apps (`/apps`) [Section titled “Apps (/apps)”](#apps-apps) Apps are the primary primitive. Each app is a scope that owns its own blueprints, theme, marketplace installs, and per-app API keys. New accounts land here with a single default app already provisioned; create more from this page. Per-app sub-routes (under `/apps/[appId]/`), in nav order: * **Overview** (`/apps/[appId]`) — the connect checklist, the MCP connect config snippet, and the app’s render activity. This is where the app id lands you. * **Blueprints** (`/blueprints`) — the app’s blueprint library: view source, rename, edit metadata, delete. * **Gadgets** (`/apps/[appId]/gadgets`) — the app’s resolved gadget catalog, exactly what agents receive from `ggui_list_gadgets`: the stdlib floor, web-installed rows, and the `ggui.json`-declared overlay (floor < installed < declared). Installed rows get a **Remove** action and a version-pin menu. * **Marketplace** (`/marketplace`) — browse and install published blueprints and gadgets; a kind toggle switches the search between the two. * **Keys** (`/keys`) — per-app connector keys (`ggui_user_*` rows bound to this `appId`, so the pod locks the session to this app) **and** per-app BYOK provider-key overrides (precedence over the user-pool BYOK keys for renders bound to this app). * **Theme** (`/theme`) — per-app theme overrides. * **Settings** (`/settings`) — display name, system prompt, per-key rate limit, delete app. Blueprints are matched during `ggui_handshake`, before any generation. Curated app blueprints match deterministically when the agent’s declared tools cover the blueprint’s `dataTools` (deterministic, zero-LLM); other cached blueprints are reused by contract similarity. Either way, a hit renders with zero generation cost. See the [generation pipeline](/architecture/overview/#generation-pipeline) for the matching flow and [Marketplace](/hosted/marketplace/) for authoring + distribution. ## Orgs (`/orgs`) [Section titled “Orgs (/orgs)”](#orgs-orgs) Organizations you belong to, each with its own credit wallet, member list, and invite flow. Per-org detail lives under `/orgs/[orgId]`, and invite-email links land at `/invites/[inviteId]`. See [Orgs and teams](/hosted/orgs/). ## Connector keys (`/keys/connector`) [Section titled “Connector keys (/keys/connector)”](#connector-keys-keysconnector) Every `ggui_user_*` key on your account, whichever path minted it — the console, an OAuth ceremony, or the CLI. See [Connector keys](/hosted/connector-keys/). ## Connected apps (`/connections`) [Section titled “Connected apps (/connections)”](#connected-apps-connections) OAuth clients (Claude Desktop, claude.ai, Goose, …) that have registered against your account via Dynamic Client Registration. The per-client list and per-row revoke aren’t available yet — OAuth-grant storage is pod-local and not scoped by user, so there is no per-user list to safely show today. Revocation works today at the **key** level instead: every OAuth approval, console mint, and CLI mint lands in the same table at [Connector keys](/hosted/connector-keys/) (`/keys/connector`). Revoke the `ggui_user_*` row there (via the CLI: `ggui keys revoke `) and every client holding that key loses access immediately — which is also the argument for minting one key per client, so you can cut off one without disturbing the rest. ## Credits (`/credits`) [Section titled “Credits (/credits)”](#credits-credits) Balance, transaction log, Stripe top-up, and coupon redemption. See [Credits, billing & BYOK](/hosted/billing/). ## Provider keys / BYOK (`/keys/providers`) [Section titled “Provider keys / BYOK (/keys/providers)”](#provider-keys--byok-keysproviders) Your account-wide Anthropic / OpenAI / Google / OpenRouter keys, so model calls run on your provider account instead of GGUI’s pool. See [Credits, billing & BYOK](/hosted/billing/#bring-your-own-key-byok). ## Account (`/account`) [Section titled “Account (/account)”](#account-account) Email, default app selection, sign out, and account deletion. ## Ask the console [Section titled “Ask the console”](#ask-the-console) A persistent agent helper is mounted in the sidebar (cmd-K to focus it; a floating **Ask** launcher opens the same input in a bottom sheet on mobile). Type a natural-language request and it renders its answer as a generative-UI surface inside the console itself — the console dogfooding the same generation it hosts. Saved results group under helper history in the app’s Blueprints tab (see [Apps](#apps-apps) above). ## OAuth consent (`/oauth/consent`) [Section titled “OAuth consent (/oauth/consent)”](#oauth-consent-oauthconsent) The browser landing for MCP-Apps-aware clients running through the [OAuth ceremony](/self-hosted/oauth/). When Claude Desktop (or any compatible host) asks `mcp.ggui.ai` to authorize, the server 302s the browser here with the OAuth params. You see: * The requesting client’s name (from DCR `client_name`). * The scope being requested (`mcp`). * Two buttons: **Approve** / **Cancel**. **Approve** mints a fresh `ggui_user_*` key (default label `MCP — — `, editable via the Key-name field; per-app flows that carried an RFC 8707 `resource` get the `appId` bound on the row so the session locks to that app) and posts it back to the MCP server through a cross-origin form POST. The server completes the OAuth flow and the client’s next `/mcp` request authenticates with the new key. **Cancel** redirects back to the client with `error=access_denied` per [RFC 6749 §4.1.2.1](https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.2.1). The MCP server is never contacted; nothing is minted. You don’t visit this URL directly — the MCP host sends you here at OAuth time. ## CLI sign-in (`/cli-confirm/[user_code]`) [Section titled “CLI sign-in (/cli-confirm/\[user\_code\])”](#cli-sign-in-cli-confirmuser_code) The browser landing for the [`ggui login`](/cli/login/) device flow. The CLI prints a URL like: ```plaintext https://console.ggui.ai/cli-confirm/AB12-CD34 ``` Open it, sign in if you aren’t already, confirm the codes match, click **Approve**. The CLI’s polling on `/v1/auth/poll` flips to `approved` and tokens land at `~/.ggui/auth.json`. Same trust model as the OAuth consent screen — confirm the code matches what the CLI printed before approving. ## Account model [Section titled “Account model”](#account-model) One Cognito user owns one GGUI account. User-scoped data on the dashboard (your keys, your blueprints, your personal credit balance, your provider keys) is visible only to you via owner-auth on every model. Org-scoped data (org wallet, org members, org-scoped blueprints) is gated by org membership. # Marketplace Registry > Publish and install gadgets + blueprints from the GGUI marketplace. Versioned, Ed25519-signed, content-addressable distribution for GGUI artifacts. The marketplace registry is where authors publish GGUI artifacts and consumers install them. It’s HTTP-only — distinct from the WebSocket protocol — and hosts immutable, signed, content-addressable bundles + manifests. The registry is for published, signed artifacts; to move your own deployment’s cached blueprints between servers, use `ggui export-pool` and load the pool on the other server with `ggui serve --seed-pool `. ## Three nouns, three roles [Section titled “Three nouns, three roles”](#three-nouns-three-roles) Marketplace docs and registry wire shapes use exactly three terms. Do not say “plugin” / “library” / “package” — see the [glossary](/glossary/) for the canonical vocabulary. | Noun | Role | Where it lives | | ------------- | ----------------------------------------- | ----------------------------------------------- | | **gadget** | ingredient — composed into a UI | `clientCapabilities.gadgets` (client-side hook) | | **tool** | action — invoked by the agent | `agentCapabilities.tools` (agent-side function) | | **blueprint** | recipe — returned directly as a cached UI | TSX source + optional contract + variance hints | A gadget is a `GadgetDescriptor` (see [Gadgets SDK](/sdk/gadgets/)) packaged for distribution. A blueprint is a `(source, contract?, fixtureProps?, variance?)` quad. Both ride `ArtifactManifest` — a discriminated union on `kind: "gadget" | "blueprint"`. ## Browse the registry [Section titled “Browse the registry”](#browse-the-registry) [hub.ggui.ai](https://hub.ggui.ai) is the public, unauthenticated browser over the same registry — no account, no CLI. It lists recently published artifacts, has a search page (`/search`) with filters for kind (blueprint / gadget) and MCP binding (`tool=`, `server=` — find every artifact that works with a given tool or server), and a per-version page for each artifact showing the manifest, signing metadata (algorithm, verified-publisher badge where applicable), and a ready-to-copy install command. It reads only the registry’s public CORS-open endpoints, so it shows exactly what `ggui gadget search` / `ggui blueprint search` show — same catalog, browsable form. ## Registry resolution [Section titled “Registry resolution”](#registry-resolution) The hosted registry lives at `registry.ggui.ai`; self-hosted registries work identically (see [Self-Hosted Registry](/sdk/self-hosted-registry/)). Every verb resolves the registry URL through the same chain (highest precedence first): `--registry ` flag → `GGUI_REGISTRY` env → `ggui.json#registry` (walking up from CWD). The verbs differ only on a full miss, following the npm model: * **Read verbs** (`install`, `search`) fall back to the public default `https://registry.ggui.ai` — zero config works out of the box. * **Write verbs** (`publish`, `keys register`) error if none is set — a publish target must be opted into explicitly. ## CLI surface — two sibling verbs [Section titled “CLI surface — two sibling verbs”](#cli-surface--two-sibling-verbs) Two parallel namespaces, one per artifact kind. Each verb hard-enforces its kind from the manifest — running a gadget verb in a blueprint repo (or vice versa) emits a friendly redirect and exits non-zero. | Verb | What it does | | ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `ggui gadget create ` | Scaffold `ggui.gadget.json` + `src/index.ts` hook stub | | `ggui gadget publish` | Bundle (esbuild), sign, upload from CWD | | `ggui gadget search [query]` | List gadgets (`--kind=gadget` hard-locked) | | `ggui gadget install @` | Verify + register into `ggui.json#app.gadgets[]` | | `ggui gadget uninstall @` | Remove the installed `(package, version)` entry from `ggui.json#app.gadgets[]` (reverse of install; the emptied array is dropped) | | `ggui blueprint create ` | Scaffold `ggui.blueprint.json` + `src/blueprint.tsx` + optional contract stub | | `ggui blueprint publish` | Sign + upload from CWD (no bundling — TSX rides inline on the manifest) | | `ggui blueprint search [query]` | List blueprints (`--kind=blueprint` hard-locked) | | `ggui blueprint install @` | Materialize to `.ggui/installed-blueprints/____/` for `discoverLocalUis` to pick up | | `ggui blueprint uninstall @` | Remove a locally-installed blueprint (deletes the materialized directory; when it was the last installed blueprint, also strips the install-managed glob from `ggui.json#blueprints.include`) | The two namespaces are deliberately separate sibling verbs — NOT an umbrella `ggui artifact` that auto-detects kind. Gadgets and blueprints share a registry but mean different things to the install flow, so the kind discriminator is surfaced at the verb level. ## Author workflow [Section titled “Author workflow”](#author-workflow) ```bash # === Gadget === # 1. Scaffold ggui gadget create @my-org/weather-card cd weather-card # 2. Implement the hook + edit ggui.gadget.json (description, usage, # example, gotchas — these are required and shape the LLM's prompt # at code-gen time, so write them carefully). # 3. Authenticate (the publish flow reuses the session `ggui login` # stores at ~/.ggui/auth.json, refreshing it automatically). ggui login # 4. Dry-run validates bundle + conformance preflight without # uploading. Recommended on every change. ggui gadget publish --dry-run # 5. Upload. First publish auto-generates an Ed25519 keypair and # registers your public key with the registry. ggui gadget publish # === Blueprint === # 1. Scaffold (different template — TSX source + contract stub) ggui blueprint create @my-org/login-form cd login-form # 2. Edit src/blueprint.tsx + the contract; manifest carries `variance` # hints that prime the matcher. # 3. Same auth setup as gadgets. # 4. Publish — no bundling step; TSX rides inline on the manifest. ggui blueprint publish ``` The publish CLIs run a shared internal pipeline that asserts `manifest.kind === verb-kind`, runs the registry’s conformance gate, signs (gadget: `sha384(bundleBytes)` of the compiled bundle; blueprint: canonical JSON of the manifest), and POSTs `{manifest, bundle?, signature}` to `/publish`. ## Consumer workflow [Section titled “Consumer workflow”](#consumer-workflow) ```bash # Search the registry — each namespace hard-locks its kind filter. ggui gadget search "weather" ggui gadget search --hook=useWeatherCard ggui blueprint search "login" # Install. Verifies signature + SRI before writing anything. ggui gadget install @my-org/weather-card@0.1.0 # → ggui.json#app.gadgets ggui blueprint install @my-org/login-form@0.1.0 # → .ggui/installed-blueprints/ ``` Install always runs both verification legs (bundleSha384 recompute + Ed25519). If the registry didn’t pin a public key on the version (legacy / pre-key-pinning artifacts), the default behavior is **warn-and-continue**; pass `--strict` to turn that into a hard exit 1 instead. ## Installing gadgets from the GGUI console [Section titled “Installing gadgets from the GGUI console”](#installing-gadgets-from-the-ggui-console) The CLI is the config-managed path (`ggui.json#app.gadgets[]`, versioned alongside your deployment). On hosted GGUI there’s also a per-app web path: an app’s **Marketplace** tab in the GGUI console has a Blueprints / Gadgets toggle over the same registry search — pick Gadgets, find a package, and Install. It writes the latest version onto that app’s row in a separate provenance-split table, distinct from the CLI-managed `ggui.json` column. The app’s **Gadgets** tab shows the resolved catalog an agent actually gets from `ggui_list_gadgets`, and lets you remove a web-installed gadget or pin it to a different version (re-installing at a picked version is the pin operation). Resolution when both paths touch the same package follows a fixed precedence, stdlib floor < console-installed < ggui.json-declared: * A package declared in `ggui.json` always wins, and the web install path never writes that column — attempting to install a package that’s already declared there is rejected with `package_declared`, pointing you back to the config-managed path instead. * A console-installed package overrides the stdlib floor but is itself overridden the moment the same package is declared in `ggui.json`. * Nothing installed anywhere falls through to the stdlib floor. Use the console path for exploration and per-app changes without a deploy; use `ggui gadget install` when the gadget set needs to be versioned with the rest of your app’s config. ## Auth [Section titled “Auth”](#auth) `publish` (always) and private-row reads accept `--auth=bearer --token=` (or `GGUI_REGISTRY_TOKEN`) for self-hosted / local-development flows. Without the flag, the CLI sends the access token from your stored [`ggui login`](/cli/login/) session (`~/.ggui/auth.json`), refreshing it automatically when expired. The hosted registry’s authenticated endpoints (`/publish`, `/conformance/check`, `/author-keys`) accept exactly this credential — run `ggui login` once and the default auth path works end-to-end. Third parties running their own [`@ggui-ai/registry-server`](/sdk/self-hosted-registry/) deployments pass `--auth=bearer`. ## Trust model [Section titled “Trust model”](#trust-model) The signing posture is determined by `manifest.visibility`. Both posters share the same `bundleSha384`-recompute fast leg; they differ only on the cryptographic verify leg. | `visibility` | Algorithm | Trust root | Key/identity binding | | ------------ | --------------- | ------------------------------------------- | ---------------------------------------------------------------------- | | `public` | sigstore-cosign | Fulcio cert + Rekor inclusion proof | OIDC subject embedded in the Fulcio leaf cert | | `private` | Ed25519 | AuthorKeys table (per-publisher pinned key) | `publicKeyId` = `base64(sha256(publicKey))[:16]` (16-char fingerprint) | The pairing is enforced **server-side at publish**, not just by the CLI: `POST /publish` rejects a mismatched pair with `400 visibility_algorithm_mismatch`. `public` requires `sigstore-cosign` so every publicly listable artifact has a transparency-log entry; `private` requires an Ed25519 author key. A hand-rolled request can’t opt a public artifact out of the transparency log by signing it with a private key. **Per-author Ed25519 keys (private gadgets).** On first publish, the CLI generates a 32-byte private key at `~/.ggui/keys//private.key`. The public key (`base64(pk)`) is registered with the registry under the publisher’s server-side account subject — see [`ggui keys register`](/cli/keys-register/) for the explicit verb and the registration error matrix. The registry copies the publishing key onto every `ArtifactVersionRow` it writes (field: `authorPublicKey`, base64-encoded raw Ed25519 public key bytes). A later key rotation does NOT invalidate historical versions — each version verifies against the exact key that signed it. **Sigstore (public gadgets).** Public artifacts sign via the keyless sigstore flow — the CLI obtains a short-lived Fulcio certificate bound to your OIDC identity and submits the signature to Rekor for a public transparency-log entry. There is no long-lived author key for the public path; trust roots in Fulcio + Rekor. **Two-leg verification on install.** Both must pass before any disk write: 1. **bundleSha384 recompute.** Compute `sha384(payload)`, compare against `signature.bundleSha384`. Fast tamper detection. Runs for both algorithms. 2. **Cryptographic verify.** Dispatches on `signature.algorithm`: * `ed25519` → `derivePublicKeyId(returnedPubkey) === signature.publicKeyId` (rejects key-swap attacks), then `verifyBundleEd25519`. If the registry didn’t pin a public key for the version, the CLI warns and continues by default; `--strict` turns the warn into a hard fail. * `sigstore-cosign` → `verifyBundleSigstore` validates the Fulcio cert chain + Rekor inclusion. By default any valid OIDC identity is accepted; pass `--verify-identity ` to additionally pin the Fulcio leaf’s subject claim. ## Subresource integrity (`bundleSri`) [Section titled “Subresource integrity (bundleSri)”](#subresource-integrity-bundlesri) Publish computes `sha384-` server-side. The read endpoint returns it; install writes it onto `GadgetDescriptor.bundleSri`; the iframe runtime emits a `` tag before dynamic-importing the bundle. A CDN compromise can’t silently swap the bundle without breaking SRI. CSP `script-src` auto-derives from each entry’s `bundleUrl` origin — no per-registry allowlist needed. ## Versioning [Section titled “Versioning”](#versioning) * **Semver.** `1.2.3-alpha.1+build.42` form. `parseArtifactManifest` rejects ranges, `latest`, leading zeros (applies to gadgets and blueprints alike). * **Immutable.** `POST /publish` of an existing `(scope, name, version)` triple returns `409 version_exists`. * **Yank, not delete.** Yanked versions return `410 Gone` with the manifest still in the body for audit. Hard delete is intentionally NOT supported. ## HTTP API surface (core routes) [Section titled “HTTP API surface (core routes)”](#http-api-surface-core-routes) The core routes (version-listing `GET /pkg/{scope}/{name}` and the `/bundles/*` fetch routes ride alongside): | Method | Path | Auth | Purpose | | ------ | ----------------------------------------------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `GET` | `/search?q=&kind=&hook=&tag=&author=&tool=&server=&…` | public | List artifacts. AND-semantics across filters. `tool` / `server` filter on an artifact’s MCP tool bindings (find everything that works with a given tool or server). | | `GET` | `/pkg/{scope}/{name}/{version}` | mixed[1](#user-content-fn-1) | Read a single version’s manifest + fetchable URLs + signing metadata. | | `POST` | `/publish` | CLI session | Upload `{manifest, bundle?, bundleSha384?, signature}`. | | `POST` | `/conformance/check` | CLI session | Dry-run the conformance gate without publishing. | Wire shapes are defined in `@ggui-ai/registry-core` (shared by the hosted cloud and the self-hosted server). ## What’s in `ggui.json` after install [Section titled “What’s in ggui.json after install”](#whats-in-gguijson-after-install) **Gadgets** land on `app.gadgets[]`: ```json { "app": { "gadgets": [ { "package": "@my-org/weather-card", "version": "0.1.0", "bundleUrl": "https://registry.ggui.ai/bundles/...", "bundleSri": "sha384-Wj1...", "exports": [ { "hook": "useWeatherCard", "description": "Renders a weather card.", "usage": "Use to surface current weather.", "example": { "city": "Berlin" } } ] } ] } } ``` **Blueprints** materialize to disk under `.ggui/installed-blueprints/____/`: ```plaintext .ggui/installed-blueprints/ └── my-org__weather-card__0.1.0/ ├── index.tsx # the published TSX source └── ggui.ui.json # generated UI manifest (id, contract, entryPoint) ``` The install adds `.ggui/installed-blueprints/**/ggui.ui.json` to `ggui.json#blueprints.include` automatically. The existing `discoverLocalUis` glob loader picks them up at boot — no special-case install path on the server side. ## Agent-facing MCP tools [Section titled “Agent-facing MCP tools”](#agent-facing-mcp-tools) The marketplace surface for the *agent* (not the publisher CLI) lives on the same MCP endpoint as everything else. Three tools enumerate and materialize blueprints from the registry-backed catalog: | Tool | Purpose | | ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | | `ggui_list_featured_blueprints` | Enumerate builder-curated featured blueprints (no filters; takes empty input). | | `ggui_search_blueprints` | Semantic search across the app’s blueprints (manifest + cached generations). | | `ggui_render_blueprint` | Resolve a registered blueprint by id to its compiled JS bundle — returns `{blueprintId, blueprintName, code, contentType}`; no session is created. | Full wire shapes + agent-side usage: [MCP Protocol Reference](/api/mcp-protocol/#ggui_list_featured_blueprints). Gadgets are advertised via [`ggui_list_gadgets`](/api/mcp-protocol/#ggui_list_gadgets) instead — the catalog rides on the contract, not as a separate “render” call. ## Roadmap [Section titled “Roadmap”](#roadmap) Tracked-but-not-yet-shipped surfaces, in rough priority order: * **Per-org private artifacts.** `visibility: "private"` reads are enforced per-subject today — the publisher or the scope owner reads a private version; everyone else gets an opaque `not_found`. Org-membership admission (a teammate reading an org-mate’s private versions) is the next step. * **Yank UX.** No `ggui gadget yank` subcommand yet — yanking goes through registry admin tooling. The read + install sides already handle `410 Gone` correctly (install exits 1 with a “yanked” message). * **Cross-registry federation / mirror.** Single-registry installs only; federated lookup is a separate slice. * **Per-user authentication.** Author identity is the hosted account’s subject today; team workflows share one account. Per-user identity within a team is future work. ## Reference [Section titled “Reference”](#reference) * **Browse.** [hub.ggui.ai](https://hub.ggui.ai) — the public registry browser (search, per-version manifests, install commands). * **Protocol spec.** [Protocol overview](/protocol/overview/) * **Self-hosting.** [Self-hosted registry](/sdk/self-hosted-registry/) — byte-compatible `@ggui-ai/registry-server` for air-gapped or local-dev use. * **Glossary.** [gadget / tool / blueprint](/glossary/) — the three-noun vocabulary used throughout. * **Author manifest.** [`@ggui-ai/artifact-manifest`](/sdk/gadgets/) — `gadgetManifestSchema` / `blueprintManifestSchema`. * **Signing.** [`@ggui-ai/gadget-signing`](/sdk/gadgets/) — universal Ed25519 (browser + Node). * **Publisher key registration.** [`ggui keys register`](/cli/keys-register/). ## Footnotes [Section titled “Footnotes”](#footnote-label) 1. Public for `visibility: "public"` artifacts. A `visibility: "private"` version is served only to the verified account that published it or that owns the artifact’s scope; every other request — anonymous or authenticated — receives the same `not_found` response as a genuinely missing artifact (the version list likewise filters versions you cannot read), so the API never confirms a private artifact exists. “CLI session” = the `ggui login` session token, verified at the hosted deployment’s gateway (see [Auth](#auth)). [↩](#user-content-fnref-1) # Orgs & teams > Shared workspaces on hosted GGUI — the pooled org wallet, the owner/admin/member role model, the email invite flow, and how an org is dissolved. An org is a shared workspace with a pooled credit wallet. Members you invite render against the org’s wallet, so nobody needs their own balance topped up individually, and a single coupon can credit the whole team. Orgs live at `/orgs` in [the GGUI console](/hosted/console/). Every org you belong to is listed there — the ones you created and the ones you were invited into — badged with your role. ## Creating an org [Section titled “Creating an org”](#creating-an-org) Give it a name and confirm. Left blank, it is created as “My GGUI org”. You are its first owner. ## Roles [Section titled “Roles”](#roles) Every membership carries one of three roles. | | member | admin | owner | | ------------------------------- | ------ | ----- | ----- | | Render against the org wallet | yes | yes | yes | | See the wallet balance | yes | yes | yes | | Redeem a coupon into the wallet | yes | yes | yes | | Invite members | no | yes | yes | | Rename the org | no | yes | yes | | Remove a member | no | yes | yes | | Remove an admin | no | no | yes | | Change someone’s role | no | no | yes | | Dissolve the org | no | no | yes | Anyone can leave an org on their own — an owner only once a second owner exists, so an org is never left ownerless. For the same reason the last remaining owner cannot be demoted; promote someone else first. Owners cannot remove other owners directly. Demote them to admin or member, then remove them. ## Inviting people [Section titled “Inviting people”](#inviting-people) Owners and admins invite by email from the org’s detail page, choosing the new member’s role (member or admin). The recipient gets an email with a one-time accept link. That link is the credential. The invite id in the URL is what authorizes the claim — anyone signed in who holds the link can accept it, and it is not matched against the recipient’s email address. Send it to the person, not to a channel. Invites expire, and pending ones are listed on the org page with their target email, role, and expiry, each with a **Revoke** action. Inviting the same address twice reuses the existing pending invite rather than issuing a second one. Following the link lands the recipient on `/invites/[inviteId]`. If they are not signed in they see the sign-in form first; once authenticated the invite accepts itself and drops them straight into the org. ## The org wallet [Section titled “The org wallet”](#the-org-wallet) Each org carries its own wallet, shown on the org page with the current balance alongside lifetime added and lifetime spent. “Added” counts every credit that reached the wallet, top-ups included. Any member can see it. Credit reaches an org wallet through coupon redemption: on `/credits`, the redeem form offers your personal wallet or any org you belong to as the destination. Personal balances and org balances are separate ledgers — see [Credits, billing & BYOK](/hosted/billing/) for how charges are priced. ## Members [Section titled “Members”](#members) The member list shows each person’s display name or email, their role, and when they joined. Owners change roles inline from that list. Removing someone takes effect immediately; your own row offers **Leave** instead. ## Dissolving an org [Section titled “Dissolving an org”](#dissolving-an-org) An owner can schedule dissolution from the org’s danger zone. The org is deleted after a seven-day grace period, and any owner can cancel during that window. While it is scheduled, the org shows a `dissolving` badge in the list and a banner on its detail page. # Million-Dollar Homepage playground > Hosted MCP service at mcp.ggui.ai/playground/the-million-dollar-homepage — shared 1000×1000 pixel grid. Demo of generative UI rendering globally shared mutable state. `mcp.ggui.ai/playground/the-million-dollar-homepage` is a first-party hosted MCP service that exposes a globally shared 1000×1000 pixel grid — a tribute to [Alex Tew’s 2005 Million-Dollar Homepage](https://en.wikipedia.org/wiki/The_Million_Dollar_Homepage). Every signed-in user reads and writes the same canvas. Where the [Todos playground](/hosted/playgrounds/todos/) demonstrates per-user persistent state, MDH demonstrates **globally shared mutable state** rendered as generative UI. Three tools, one canvas, last-write-wins semantics. The agent claims a pixel, the host renders the new region inline, the next user can claim right over the top. ## What it demonstrates [Section titled “What it demonstrates”](#what-it-demonstrates) * **Shared mutable state across users**: every claim is visible to every other signed-in caller immediately. * **Generative UI over a sparse data shape**: `mdh_read_region` returns only claimed cells, so the host renders a sparse grid — pure data, no markup decisions baked into the tool. * **Attribution without ownership**: each claimed cell records the writer’s `userId`, but anyone can overwrite. Identity is recorded; tenure is not. If you want the deep “why” of the service model behind this, see [MCP services](/architecture/mcp-services/) — `playground-mdh` is one of three reference services in `cloud/mcp-services/`. ## The three tools [Section titled “The three tools”](#the-three-tools) All three are Cognito-gated. Anonymous calls (no bearer token) return an explicit `authentication required` error. | Tool | Input | Output | Notes | | ----------------- | ------------------------- | ------------------------------------------------------ | --------------------------------------------------------------------------------- | | `mdh_read_region` | `{ x, y, width, height }` | `{ pixels: Pixel[] }` | Sparse — unclaimed cells omitted. Region capped at 100×100 cells per call. | | `mdh_claim_pixel` | `{ x, y, color }` | `{ pixel }` | Single-cell write. `color` is `#RRGGBB` hex. Last-write-wins (see warning below). | | `mdh_get_stats` | `{}` | `{ totalClaimed, uniqueUsers, gridWidth, gridHeight }` | Cheap aggregate read. `gridWidth` and `gridHeight` are always 1000. | A `Pixel` row is `{ x, y, color, userId, claimedAt }`. Coordinates are integers, `0 <= x < 1000` and `0 <= y < 1000`. `claimedAt` is ISO-8601. The region cap exists to bound payload size: a 100×100 fully-claimed read returns 10,000 entries. Agents wanting a wider view issue multiple reads — the sparse response means the cost scales with claimed density, not region size. Last-write-wins, no permanent ownership `mdh_claim_pixel` REPLACES any existing claim on that cell. The most recent writer’s `userId` overwrites the previous one. There is no “owned forever”, no allow-list, no first-claim precedence. Anyone signed in can paint over anything. The wire description on the tool itself spells this out so agents surface it before the user buys in. ## Auth model [Section titled “Auth model”](#auth-model) Cognito-gated. Every handler resolves `ctx.userId` from the bearer key minted by [console.ggui.ai](/hosted/console/) and rejects calls without one. On `mdh_claim_pixel`, that same `userId` is stamped on the resulting pixel row — that’s the attribution surface visible to subsequent `mdh_read_region` callers. Reads are gated too. The canvas is end-user surface, not a public dataset; anonymous reads are deliberately not exposed at this slice. ## Try it [Section titled “Try it”](#try-it) The wiring is identical to the [Todos playground](/hosted/playgrounds/todos/) — same auth header, same OAuth ceremony from MCP-Apps-aware hosts, different URL. **Claude Desktop**: Settings → Connectors → Add custom connector, paste: ```plaintext https://mcp.ggui.ai/playground/the-million-dollar-homepage ``` Approve the OAuth ceremony at `console.ggui.ai`; a new `ggui_user_*` row appears in [`/keys/connector`](https://console.ggui.ai/keys/connector). Then try prompts like: > Show me a 50×50 region around the center of the canvas. > Claim the pixel at (500, 500) in red. > How many pixels have been claimed total, and by how many users? **Claude Agent SDK** (or any host that takes a remote MCP URL): ```typescript import { query } from "@anthropic-ai/claude-agent-sdk"; const apiKey = process.env.GGUI_USER_KEY!; // ggui_user_* const mcpServers = { mdh: { type: "http" as const, url: "https://mcp.ggui.ai/playground/the-million-dollar-homepage", headers: { Authorization: `Bearer ${apiKey}` }, }, }; for await (const msg of query({ prompt: "Claim (500, 500) in #ff0044, then show me a 20×20 region around it.", options: { model: "claude-sonnet-5", mcpServers, allowedTools: [ "mcp__mdh__mdh_read_region", "mcp__mdh__mdh_claim_pixel", "mcp__mdh__mdh_get_stats", ], }, })) { // consume the SDK message stream } ``` The Claude Agent SDK namespaces every MCP tool as `mcp____` — with `serverName: "mdh"` here, the tool ids land as `mcp__mdh__mdh_read_region`, `mcp__mdh__mdh_claim_pixel`, and `mcp__mdh__mdh_get_stats`. For the full agent-side wiring (system prompt, error handling, streaming), see the [Claude Agent example](/examples/claude-agent/) and swap the URL + tool whitelist. ## How it’s built [Section titled “How it’s built”](#how-its-built) The service is closed-source (`@ggui-private/mcp-playground-mdh` — not published or mirrored), but its shape is simple enough to describe: * a package entry exporting a `createPlaygroundMdhHandlers({ grid })` convenience factory, * one file per tool (read-region / claim-pixel / get-stats), * a `PixelGrid` interface with an in-memory implementation. The grid is the single source of truth for its own dimensions and surfaces them on the wire via `mdh_get_stats`. To build your own globally shared state surface in this shape, use the OSS **`McpService` mount primitive** in [`@ggui-ai/mcp-server`](/architecture/mcp-services/) — the same seam this service mounts through. The [MCP services architecture](/architecture/mcp-services/) page covers mount points, the `AuthAdapter` contract, and how `ctx.userId` flows from the bearer header to the handler. # Todos playground > Hosted MCP service at mcp.ggui.ai/playground/todos — a per-user persistent todo list demo. Try generative UI rendering shared state. `mcp.ggui.ai/playground/todos` is a first-party hosted MCP service that exposes a per-user persistent todo list. Point an agent at it and watch the agent call a tool while GGUI renders the list inline as generative UI. State survives refresh, re-login, and host swaps — todos are pinned to your Cognito identity, not the session. ## Try it from Claude Desktop [Section titled “Try it from Claude Desktop”](#try-it-from-claude-desktop) This is one more connector on top of the [Claude Desktop walkthrough](/clients/claude-desktop/), not a zero-setup surface. If you’ve already connected `mcp.ggui.ai` there, Claude Desktop will pick up `playground-todos` once you add a second connector. In Settings → Connectors → Add custom connector, paste: ```plaintext https://mcp.ggui.ai/playground/todos ``` The OAuth ceremony runs again against `console.ggui.ai`; approve it the same way you did for the main `mcp.ggui.ai` connector. A new `ggui_user_*` row appears in [`/keys/connector`](https://console.ggui.ai/keys/connector) labelled with the connector name. Once connected, try prompts like: > What’s on my todo list? > Add “ship the launch post” to my todos, then show me everything pending. > Mark the first todo as done. Claude calls `todos_list` / `todos_add` / `todos_toggle`, and the table updates in the chat. Refresh Claude Desktop, ask again — same list comes back. ## Try it from your own agent [Section titled “Try it from your own agent”](#try-it-from-your-own-agent) The Todos playground is a vanilla remote MCP server. Anything that speaks `streamable-http` MCP + bearer auth works. For Claude Agent SDK: ```typescript import { query } from "@anthropic-ai/claude-agent-sdk"; const apiKey = process.env.GGUI_USER_KEY!; // ggui_user_* const mcpServers = { todos: { type: "http" as const, url: "https://mcp.ggui.ai/playground/todos", headers: { Authorization: `Bearer ${apiKey}` }, }, }; for await (const msg of query({ prompt: "Add 'try the playground' to my todos, then list everything.", options: { model: "claude-sonnet-5", mcpServers, allowedTools: [ "mcp__todos__todos_list", "mcp__todos__todos_add", "mcp__todos__todos_toggle", "mcp__todos__todos_delete", ], }, })) { // consume the SDK message stream } ``` The Claude Agent SDK namespaces every MCP tool as `mcp____` — with `serverName: "todos"` here, the tool ids land as `mcp__todos__todos_list`, `mcp__todos__todos_add`, and so on. The pattern is the same for any other host that takes an MCP-server URL. For the full agent-side wiring (system prompt, error handling, streaming), see the [Claude Agent example](/examples/claude-agent/). The same pattern applies — swap `mcp.ggui.ai` for `mcp.ggui.ai/playground/todos`, narrow the tool whitelist to the four todos tools. ## How it works [Section titled “How it works”](#how-it-works) This is the smallest “real” MCP-driven surface we ship. No code to write, no schema to learn — the four tools are described by the server’s `tools/list` response, and the host (Claude Desktop, Goose, your own agent) drives them. * **Agent → tool → generative UI**: the agent calls a tool, the runtime feeds the result into a blueprint, the host renders the resulting list inline. * **Per-user persistence**: log out, come back tomorrow from a different host — same todos. * **Cognito identity at the MCP edge**: tool handlers read `ctx.userId` directly. No second auth layer; the `Authorization: Bearer ggui_user_*` header that authenticated the MCP session also scopes the data. If you want the deep “why” of the service model that makes this work, see [MCP services](/architecture/mcp-services/) — `playground-todos` is one of three reference services in `cloud/mcp-services/`. ### The four tools [Section titled “The four tools”](#the-four-tools) All four are scoped to the caller’s `ctx.userId`. Anonymous calls (no bearer token) return an explicit `authentication required` error. | Tool | Input | Output | Notes | | -------------- | ---------- | -------------------------------------- | ---------------------------------------------------------------------------------- | | `todos_list` | `{}` | `{ todos: Todo[] }` | Oldest-first by `createdAt`. Empty array when the user has none — never `null`. | | `todos_add` | `{ text }` | `{ todo }` | `text` trimmed; empty or 500+ char bodies rejected at the schema boundary. | | `todos_toggle` | `{ id }` | `{ found: boolean, todo: Todo\|null }` | Flips `done`. Missing id and cross-user id collapse to one shape (see Auth model). | | `todos_delete` | `{ id }` | `{ ok: boolean }` | `ok: true` only when the caller owned a todo with that id. | A `Todo` row is `{ id, text, done, createdAt }`. `createdAt` is an ISO-8601 string; `id` is opaque (treat it as a black-box handle returned by `todos_add` or `todos_list`). ### Auth model [Section titled “Auth model”](#auth-model) Cognito-gated. Every handler resolves `ctx.userId` from the bearer key minted by [console.ggui.ai](/hosted/console/) and rejects calls without one. Those keys come from the console (mint at `/keys/connector` or approve an OAuth ceremony from an MCP-Apps-aware host) or from `ggui keys create` after [`ggui login`](/cli/login/). Cross-user probing is structurally prevented. `todos_toggle` and `todos_delete` collapse two failure modes into one wire shape: * The id doesn’t exist. * The id exists but belongs to a different user. Both return the same negative response (`found: false` / `ok: false`). A caller can’t enumerate other users’ id space. ### How it’s built [Section titled “How it’s built”](#how-its-built) The service is closed-source (`@ggui-private/mcp-playground-todos` — not published or mirrored), but its shape is simple enough to describe: * a package entry exporting a `createPlaygroundTodosHandlers({ store })` convenience factory, * one file per tool (list / add / toggle / delete), each \~50 lines, * a `TodoStore` interface with an in-memory implementation for tests; production swaps in a DynamoDB-backed store against the same interface. To build your own service in this shape, use the OSS **`McpService` mount primitive** in [`@ggui-ai/mcp-server`](/architecture/mcp-services/) — the same seam this service mounts through. The [MCP services architecture](/architecture/mcp-services/) page covers mount points, the `AuthAdapter` contract, and how `ctx.userId` is resolved end-to-end. # Portability > Hosted GGUI and a server you run yourself speak the same protocol — what moves across unchanged, and the few things that differ. Hosted GGUI runs the same protocol you can run yourself. There is no hosted-only dialect, no proprietary client library, and no lock-in step you would have to unwind later. If hosted GGUI stops suiting you, you point your agent at your own server and keep going. ## What moves unchanged [Section titled “What moves unchanged”](#what-moves-unchanged) * **Your agent.** It talks to an MCP endpoint. Change the URL and the credential; nothing else. There is [no client SDK wrapper](/quickstart/hosted-agent/) to swap out, because your agent never imported one. * **Your contracts.** `DataContract` is protocol, not product. The same `propsSpec` / `actionSpec` / `contextSpec` shapes are accepted by both sides, and the [conformance kit](/protocol/conformance/) is what settles any disagreement. * **Your blueprints.** Cached blueprints are exportable artefacts. `ggui export-pool` writes a pool you load on another server with `ggui serve --seed-pool `, so the work of generating them travels with you. * **Your gadgets.** Published gadgets are content-addressed, signed bundles installed by manifest. They resolve the same way on either side. ## What differs [Section titled “What differs”](#what-differs) | | Hosted | Your own server | | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- | | **Model access** | GGUI’s credit pool, or your own provider key | Always your own provider key | | **Billing** | Pay-as-you-go from a prepaid balance at published rates per render kind; a welcome credit to start, while it is available ([pricing](https://ggui.ai/pricing)) | Your provider’s bill, directly | | **Registry endpoint** | The hosted marketplace | The hosted marketplace, or [your own registry](/sdk/self-hosted-registry/) | Credentials do not carry over in either direction: a `ggui_user_*` connector key is meaningless to a server you run, and a self-hosted key is meaningless to `mcp.ggui.ai`. That is the boundary working correctly, not a migration cost. ## Going self-hosted [Section titled “Going self-hosted”](#going-self-hosted) Start with the [self-hosted quickstart](/quickstart/self-hosted/) — it runs the whole stack locally with no account. When you are ready to put it somewhere, the [reference deploys](/self-hosted/reference-deploys/) cover the shapes that are known to work. # Rate limits > How GGUI surfaces rate limits — the in-band render refusals on `ggui_render` (`app_rate_limited`, `issuer_rate_limited`), the HTTP 429 + Retry-After contract, and how host SDKs handle backoff. GGUI rate limiting is operator-configured: a `RateLimiter` seam the deployment wires (or doesn’t). This page covers the self-hosted defaults, the two enforcement layers and their wire shapes, and how to layer retry on top of whichever MCP host SDK you’re using. ## Self-hosted defaults [Section titled “Self-hosted defaults”](#self-hosted-defaults) * Default (strict) `ggui serve` wires **no** generation limiter — `ggui_render` is unlimited for paired callers. * `ggui serve --public-demo` binds a per-remote-IP fixed-window limiter to `ggui_render`: **30 generations / 10 minutes / IP** (operator-pays posture for public demos). * Library users wire their own `RateLimiter` into the render handler deps — the seam (`RateLimiter`, `RateLimitDecision`) lives in `@ggui-ai/mcp-server-core`. A denial is never thrown: the handler projects it as a refusal described below — `app_rate_limited` for the app’s own cap, or `issuer_rate_limited` when the limiter reports (`RateLimitDecision.scope: 'issuer'`) that the cap on the issuing identity behind the credential bound. ## Two enforcement layers [Section titled “Two enforcement layers”](#two-enforcement-layers) ### Tool-level: `ggui_render` refuses in-band [Section titled “Tool-level: ggui\_render refuses in-band”](#tool-level-ggui_render-refuses-in-band) When a rate limiter is wired into the render handler, a limited `ggui_render` call is **refused** — not a thrown tool error, not an HTTP 429. The tool result is a render-gate refusal like any other — `isError: true`, `structuredContent.outcome: 'refused'`, `refusal.code: 'app_rate_limited'` (or `issuer_rate_limited` when the issuing identity’s cap bound), `retry: 'later'` — with the wait in milliseconds carried by the refusal’s `message` and `fix`. The handshake stays intact, so the retry is the same call with the same `handshakeId` after the stated wait. Handle it in your agent loop the way you handle every render-gate refusal: read `refusal.retry`, wait, re-call. ### HTTP-level: 429 on auth/pairing endpoints [Section titled “HTTP-level: 429 on auth/pairing endpoints”](#http-level-429-on-authpairing-endpoints) The pairing/login routes enforce limits at the HTTP transport layer. Every limited request returns: | Field | Value | | -------------------- | ---------------------------------------------------------------------------------------------- | | HTTP status | `429` | | `Retry-After` header | Seconds before the next attempt is permitted. Optional — absent means use exponential backoff. | | Body | JSON `{ "error": { "code": "rate_limited", "message": "...", "retryAfter": } }`. | `Retry-After` is the authoritative signal. When present, honor it verbatim — the server has already computed the appropriate wait. The `retryAfter` field in the body mirrors the header for convenience when only the body is observable (e.g. some transport wrappers). ## Retry is the host SDK’s job [Section titled “Retry is the host SDK’s job”](#retry-is-the-host-sdks-job) GGUI has no first-party client SDK to wrap retries — your MCP host owns that loop. The pattern is the same regardless of host: catch the 429, read `Retry-After`, sleep, retry, cap attempts. For `ggui_render`, additionally check the tool result for a refusal — `isError: true` with `structuredContent.outcome: 'refused'` and a `refusal.code` of `'app_rate_limited'` or `'issuer_rate_limited'` — and back off for the wait its `message` states. ### Claude Agent SDK [Section titled “Claude Agent SDK”](#claude-agent-sdk) The Claude Agent SDK’s `query()` already retries transient transport errors (including 429) using the standard Anthropic SDK retry config. You generally don’t need to do anything — bursts within the retry window never surface to your code. To tune, pass `maxRetries` through the SDK’s options. See [Examples → Claude Agent](/examples/claude-agent/) for a runnable scaffold. ### `@modelcontextprotocol/sdk` (generic MCP) [Section titled “@modelcontextprotocol/sdk (generic MCP)”](#modelcontextprotocolsdk-generic-mcp) The official MCP SDK throws on HTTP errors without retrying. Wrap `callTool` (or whichever method you invoke) yourself: ```typescript import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; const client = new Client({ name: "my-agent", version: "1.0.0" }); await client.connect( new StreamableHTTPClientTransport(new URL("http://127.0.0.1:6781/mcp"), { requestInit: { headers: { Authorization: "Bearer dev" } }, }) ); async function callWithRetry( fn: () => Promise, { maxRetries = 3, baseDelayMs = 1000, maxDelayMs = 30000 } = {} ): Promise { for (let attempt = 0; attempt <= maxRetries; attempt++) { try { return await fn(); } catch (err) { // The MCP SDK surfaces HTTP errors with status + headers attached. const status = (err as { status?: number }).status; if (status !== 429 || attempt === maxRetries) throw err; const retryAfter = Number((err as { headers?: Record }).headers?.["retry-after"]) || undefined; const waitMs = retryAfter != null ? retryAfter * 1000 : Math.min(baseDelayMs * 2 ** attempt, maxDelayMs); await new Promise((r) => setTimeout(r, waitMs)); } } throw new Error("unreachable"); } const result = await callWithRetry(() => client.callTool({ name: "ggui_handshake", arguments: {/* ... */}, }) ); ``` Tune `maxRetries` per workload: lower on interactive (user-blocking) paths so failures bubble up fast; raise on background batch paths where backoff is cheaper than re-queuing. Note that a rate-limited `ggui_render` on a `--public-demo` server does NOT surface as an HTTP error — it resolves as a refusal (`isError: true`, `structuredContent.outcome: 'refused'`, `refusal.code: 'app_rate_limited'`); check the result before treating the call as a success. ## Raw HTTP [Section titled “Raw HTTP”](#raw-http) If you’re hitting the server directly without an MCP SDK, implement the same loop against `fetch`: 1. Read the `Retry-After` header on every 429 — a hosted 429 is the ingress backstop and carries no body. For a `ggui_render` refusal the wait is inside the refusal itself (`message` / `fix`, in milliseconds). 2. If present, sleep that many seconds, then retry. 3. If absent, sleep `min(baseDelay * 2^attempt, maxDelay)`, then retry. 4. Cap retries (3–5 is reasonable for interactive workloads, more for batch). 5. Stop retrying on non-429 4xx (those won’t resolve with backoff). 6. Treat a `503` whose JSON-RPC body carries `-32014` as the saturated generation queue — hosted GGUI always sends `Retry-After` on it; wait exactly that long. The server, not you, is the limit. The [generic MCP example](/examples/generic-mcp/) walks through raw-HTTP usage end-to-end. ## See also [Section titled “See also”](#see-also) * [Examples → Claude Agent](/examples/claude-agent/) — runnable scaffold with the host SDK’s native retry. * [Cookbook → Error handling](/cookbook/error-handling/) — retry, surfacing, and dead-letter patterns. * [Troubleshooting](/troubleshooting/) — common error patterns. * [MCP Protocol](/api/mcp-protocol/) — full JSON-RPC method reference. # Trust & security > What hosted GGUI stores, which of it reaches a language model, how keys and the render iframe are protected, and how to delete an account. Hosted GGUI sits between your agent and your user, so it necessarily handles both sides’ data. This page says what it holds, for how long, and which parts a language model sees. Where the honest answer is a limit rather than a guarantee — the host controls the sandbox, a signature is not an audit, one contract field can carry data into the prompt — it says that instead of reassuring you. ## Your data in hosted GGUI [Section titled “Your data in hosted GGUI”](#your-data-in-hosted-ggui) A render is one generated interface. Everything below is scoped to a render, an app, or your account. | Data | Stored where | Reaches a language model? | | --------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | | The intent and contract your agent sends | The render row in DynamoDB, and — if the render becomes a reusable blueprint — a blueprint row | **Yes.** This is the generation prompt | | The generated component code | Inline on the render row; durable blueprints go to S3 keyed by content hash; a copy of the TSX lands in a per-user render cache | It *is* the model’s output | | The props your agent renders with | On the render row, next to the code | **No.** Props values are not part of the generation prompt | | What your user does in the UI — action payloads and the context snapshot taken at that moment | Buffered on the render row until the agent consumes them, and appended to a per-render event log | **Not by ggui.** They are handed back to your agent, which is itself a model — see below | | The end-user identity your auth adapter supplies | An `endUserIdentity` column on the render row | No | | Connector keys (`ggui_user_*`) | A SHA-256 hash plus an 8-character prefix. Plaintext is returned once at mint time and never written | No | | Your own provider keys (BYOK) | KMS ciphertext, decrypted into memory for the duration of one call | No — the key authenticates the provider call, it is never prompt content | ### What generation actually sees [Section titled “What generation actually sees”](#what-generation-actually-sees) The generation prompt is built from your agent’s intent, the contract’s **schemas** (field names, JSON-Schema types, and any `default` / `example` values you declare on them — so treat contract examples as prompt content), the variance signals, the rendering context the host reports (device, shell, viewport), the gadget catalogue, and GGUI’s own design-system documentation. Runtime props are carried alongside the generation input and deliberately not spread into it. Blueprint matching, the semantic cache for generative UI, has two tiers. An exact contract-key match is deterministic and calls no model at all. When that misses, candidates from your app’s own pool are retrieved by embedding similarity (your intent against each blueprint’s intent and contract), computed with Amazon’s Titan Text Embeddings V2 model through Amazon Bedrock. TypeSafe AI’s Jev model then chooses among them, or decides that none fits. If Jev does not answer within 1.5 seconds, returns an error, or is not confident in the candidate it picked, GGUI’s LLM judge chooses instead. Whichever one decides is shown your intent, each candidate’s stored intent (truncated to 280 characters), and **summaries** of the contracts (`name:type` pairs), never props or event payloads. `ggui_amend` performs no generation. It swaps props and pushes them down the live channel; no model is involved. `ggui_update` is the same swap plus a new history card (it also mints no generation, but does advance the epoch). Two contract fields carry values into the prompt `variance` is meant for design-shaping signals only — persona, aesthetic, mood — and `variance.context` is serialized verbatim into the generation prompt. Separately, the `default` and `example` values you declare on a spec entry are rendered into the prompt as comments, so the model sees the exact sample data you wrote. Neither is a bug: examples exist to show the model the shape it must handle. But the rule that per-user runtime data belongs in `props` and `contextSpec` is documented guidance to your agent, not something the server structurally enforces. Keep real user data out of `variance`, `default`, and `example` — put it in `props`, which never enters the prompt. ### The event loop is a model, by design [Section titled “The event loop is a model, by design”](#the-event-loop-is-a-model-by-design) When your user submits a form, that payload travels back to your agent through `ggui_consume`. Your agent is a language model. That is the entire point of the protocol — the user’s answer becomes structured input to the next turn — but it means “does my user’s form input reach an LLM?” has the honest answer **yes, yours**. GGUI’s own generation and matching models never see it. ### What changes with your own key [Section titled “What changes with your own key”](#what-changes-with-your-own-key) If you store a provider key and the app is configured to use it, the generation call is made with your key, so the prompt goes to your provider account under your agreement with that provider rather than through GGUI’s pool. Storing a key alone does not do this — the app’s generation billing has to select it, via the **Generation billing** card on the app’s Keys or Settings tab in the console. See [Credits, billing & BYOK](/hosted/billing/#bring-your-own-key-byok) for that gate and what it does to billing. ## Keys [Section titled “Keys”](#keys) **Connector keys.** A key is 32 bytes of randomness prefixed `ggui_user_`. What gets stored is a SHA-256 hash of the whole string plus the first 8 characters, which is what the console lists. The plaintext is handed to you exactly once and is not recoverable afterwards — if you lose it, mint a new one. Revocation is a soft flag: the row survives for audit and later requests with that key are rejected. Full mechanics in [Connector keys](/hosted/connector-keys/). **Provider keys.** Keys you bring are validated, then encrypted with AWS KMS under an encryption context that binds them to their scope — `{userId, provider}` for an account-wide key, `{appId, provider}` for a per-app one. The plaintext is never persisted — only the KMS ciphertext, a hash, and the last four characters; decryption happens in memory for the call. Because the encryption context is cryptographically bound to the ciphertext, a key encrypted for one scope fails to decrypt in another rather than silently working. The console only ever displays the last four characters. **Publisher keys.** Signing keys for the marketplace are Ed25519 and stay on your machine; the registry holds the public half. See [`ggui keys register`](/cli/keys-register/). ## Sandboxing [Section titled “Sandboxing”](#sandboxing) Generated code is code a model wrote. It runs in an iframe, and it never runs with access to the host document. When GGUI mounts the iframe itself, the sandbox grants `allow-scripts allow-forms` and deliberately withholds `allow-same-origin`, so the frame cannot read the page that embeds it. Camera, microphone, geolocation, and clipboard-write are only enabled when the render’s contract asked for them. Component bundles are content-addressed and served with their SHA-256 alongside; gadgets load behind an SRI integrity gate at iframe boot. Three honest limits: * **In a third-party host, the host owns the sandbox.** When your interface renders inside Claude Desktop or claude.ai, that host sets the iframe’s sandbox tokens and Content-Security-Policy. GGUI declares which origins the frame needs to reach; enforcement is the host’s, and that surface is opaque to ggui. * **Marketplace gadgets are signed, not audited.** Signature verification proves a bundle came from the author who published it and has not been altered since. It says nothing about what the bundle does. Public gadgets verify through sigstore, private ones through a pinned Ed25519 key — the [marketplace](/hosted/marketplace/) page has both postures. * **The integrity gate is only as strong as the descriptor.** A gadget installed from the registry carries a SHA-384 SRI hash that the runtime enforces. A hand-authored gadget entry with no `bundleSri` falls back to an integrity-less dynamic import, and installing a legacy artifact whose version has no pinned public key warns and continues unless you pass `--strict`. See [Gadgets](/sdk/gadgets/). The channel model and where the SRI gate sits are in the [architecture overview](/architecture/overview/). ## Operator access [Section titled “Operator access”](#operator-access) A small operator group exists for support and monitoring, and it can read render records — the contract, the generated code, and event payloads — across accounts, through the same access-controlled admin surface that runs the service. Three facts bound it: * **Membership is manual.** The group has no self-join path; an operator is added by an infrastructure command, not a sign-up flow. * **It cannot read provider keys.** The BYOK key table deliberately carries no operator grant — an operator never sees your provider keys, even in encrypted form. * **Every read is individually audit-logged.** Operator reads of render data go through a single audited query — the underlying models carry no direct operator grant, so a read that skips the log is structurally impossible. Each entry records the operator’s identity and the target keys, and lands in a dedicated log group retained for two years. ## Deletion & retention [Section titled “Deletion & retention”](#deletion--retention) **Renders and their event logs.** A render (the request, including the data sent for display, the data contract, the generated interface code, and its interaction events) is kept until your account is deleted or an operator removes it at your request. There is no automatic expiry and no per-render time limit, so reopening an old card from chat history always finds it, which is the point of the protocol’s rehydration story. Deleting a single app does not delete its render records. **Blueprints.** The word covers two different things: * A **saved blueprint** is one kept in an app’s blueprint library under a name. It is deleted with the app, and with your account. * A **reuse-cache blueprint** is derived automatically from a render, so that similar requests can reuse a proven interface. It holds the request’s intent, the data contract, and the generated interface code, never the data displayed or interaction events. It carries no expiry and remains after your account is deleted unless an operator removes it. Its code is stored by content hash and can be shared by apps that generated the same component, so a code file is reclaimed only by an operator-invoked purge (a takedown, or collection of code no longer referenced by any blueprint), never on a schedule. **Backups.** Deleted data in our database tables can remain in point-in-time backups for up to 35 days. Generated code files and the reuse-cache index are not backed up. The binding list of what is kept and for how long, including short-lived records, is §7 of the [privacy policy](https://ggui.ai/privacy). **Your account.** `/account` in the console has a type-to-confirm **Delete account** control. It is blockers-first: the request is refused, with the reason stated and nothing deleted, if you own a platform-managed app or if you are the last owner of an org that still has other members. If it is accepted, the account is frozen immediately — global sign-out plus disable — and an asynchronous worker then walks the deletion in order: org memberships, then each app with its keys, saved and installed blueprints, and renders, then your connector keys, provider keys, render cache, credit balance, renders, coupon attribution, and status subscription, then your user row. Cognito sign-in is deleted last, and only after a verification pass re-runs every finder query and finds nothing left. If anything remains, the erasure is marked failed and sign-in is deliberately preserved so the leftover can be traced. Two things survive on purpose, both stated in the console’s own confirmation: billing records required for accounting are kept with your personal details scrubbed rather than deleted, and CLI session tokens are left to their own expiry (they are hashed and time-bounded) instead of being swept. One gap worth naming: if you were an **end user** of somebody else’s hosted app, your identity data on their render rows is not reachable by your own account erasure. It persists as long as those renders do — until the app owner deletes their account or an operator removes the rows. ## Policies and status [Section titled “Policies and status”](#policies-and-status) * [Privacy policy](https://ggui.ai/privacy) — the binding statement, including subprocessors and analytics. * [Terms of service](https://ggui.ai/terms) * [status.ggui.ai](https://status.ggui.ai) — live service status. For anything this page does not answer, the privacy policy lists a contact address. # For Agentic App Builders > Make your existing SaaS or webapp something an AI agent can drive — without rewriting the frontend. Vision page + waitlist for the agentic-app track, productized by guuey. Vision page This describes a direction, not a shipped product. If you’re building agents **today**, take the [hosted quickstart](/quickstart/hosted-agent/) or the [self-hosted one](/quickstart/self-hosted/) — those paths are live. The waitlist at the bottom is for early access to this track when its first adapter lands. ## What an agentic app is [Section titled “What an agentic app is”](#what-an-agentic-app-is) An agentic app is a product you have already shipped, driven by an agent instead of only by hands. The user asks for the outcome — “refund last month’s invoice for this customer” — and the agent works the real flows of your app to get there, in typed calls rather than simulated clicks. The part that matters commercially is what it does **not** require: a frontend rewrite. Your React app, your Rails views, your existing routes and permissions all stay. Agent access arrives as a second, parallel surface onto the same flows, not as a replacement for the one your users already know. Today agents reach existing SaaS through three unreliable layers: **reading screenshots** (vision models reasoning about pixels — brittle, slow, no typed I/O), **browser automation** (Playwright scripts that snap the moment a button moves, with no way for the agent to learn the contract changed), and **official APIs** (when they exist, and only for the slice they cover — most production apps keep a large share of their behavior in the UI). What’s missing between an agent and an app it did not generate is a **typed contract**. ## The adapter approach [Section titled “The adapter approach”](#the-adapter-approach) You add a GGUI adapter beside your existing app rather than inside it. The adapter reads your app’s routes and describes them in the protocol’s own terms: each navigable route becomes a **render** with a typed contract, form fields become **`actionSpec`** entries (typed inbound actions that drive turns), visible state becomes **`contextSpec`** (read-only state the agent observes), and browser-only libraries you depend on — Stripe Checkout, Mapbox, a calendar picker — are wrapped as **gadgets** so a model knows how to compose with them. From the agent’s side, nothing is special about your app. It drives it through `ggui_handshake`, `ggui_render`, and `ggui_consume` exactly as it drives a freshly generated GGUI UI: same MCP wire, same contract guarantees, same failure modes. From your users’ side, nothing changed at all — they keep clicking the buttons that were always there. ## What you’d write [Section titled “What you’d write”](#what-youd-write) The provisional shape is a `ggui.app.json` next to your existing app config: ```json { "name": "my-saas", "routes": [ { "path": "/invoices/new", "intent": "create an invoice", "agentCapabilities": { "tools": { "createInvoice": { "toolInfo": { "inputSchema": { "$ref": "./schemas/invoice.json" } } } } }, "actionSpec": { "submit": { "label": "Create invoice", "schema": { "$ref": "./schemas/invoice.json" }, "nextStep": "createInvoice" } }, "contextSpec": { "currentDraft": { "schema": { "$ref": "./schemas/invoice-draft.json" } } } } ] } ``` Your app code stays as-is. An agent runtime can now discover `/invoices/new` from the adapter’s catalog, `ggui_handshake` against its contract, and `ggui_render` with a typed payload — no clicking around. (Exact wire shape for app-catalog lookup is part of the SDK’s in-design surface.) ## Where this is built: GGUI vs guuey [Section titled “Where this is built: GGUI vs guuey”](#where-this-is-built-ggui-vs-guuey) The hosted product this track becomes is **guuey**’s — a separate agent-hosting platform, at [guuey.com](https://guuey.com), built on the GGUI protocol. GGUI (this site) documents the protocol; guuey productizes hosting. guuey is not a paid tier of GGUI, and it is not run from this site. The split is clean and worth internalizing before you plan against it: * **GGUI** (this site) is the open protocol and its hosted deployment. It defines the contract, the `ggui_*` tool surface, and the render lifecycle, and it documents both the [hosted](/quickstart/hosted-agent/) and [self-hosted](/quickstart/self-hosted/) ways to run it. The spec and the SDKs are open source. * **guuey** productizes hosting on top of that protocol: running your agent, the operational surface around it, and — for this track — the hosted service that keeps an adapter pointed at your live app. The protocol side of the adapter (contracts, gadgets, the wire shape above) belongs to GGUI and will be documented here. The hosted service that runs it for you belongs to guuey and will be documented there. If a future page tells you an agentic-app feature is “part of GGUI”, check which of those two it actually is. ## Three scenarios this unlocks [Section titled “Three scenarios this unlocks”](#three-scenarios-this-unlocks) 1. **Your support agent drives the app for the customer.** “Refund last month’s invoice for customer X” → agent navigates to `/invoices/`, finds the row, calls `refund` with the typed payload. No human-in-the-loop browsing. 2. **Your sales engineer runs an agent-narrated demo.** During a prospect call, the agent narrates while driving the form in real-time. The prospect sees the same UI any user sees, but the agent’s typed actions land like a polished guided tour. 3. **Power users hand work off to their AI.** “I have 40 of these to fill in — can my AI do it?” The AI has a typed surface to drive, not pixels to scrape. ## What’s shipping when [Section titled “What’s shipping when”](#whats-shipping-when) | Component | Owner | Status | | --------------------------------------------------------- | ----- | --------- | | GGUI protocol (this site) | GGUI | Live | | Building a ggui-native agent | GGUI | Live | | Agentic App SDK (the adapter you’d add to your app) | GGUI | In design | | Hosted service that runs an adapter against your live app | guuey | In design | | Reference adapters for Next.js / Rails / Django | GGUI | Planned | | Reference adapters for legacy stacks (Java EE, Drupal, …) | GGUI | Planned | No dates. Real engineering work, not a marketing roadmap. ## Waitlist [Section titled “Waitlist”](#waitlist) The adapter SDK half of this track is still in design here. The guuey platform is in open public beta at [guuey.com](https://guuey.com) — anyone can deploy a hosted agent today. If the hosted product is what you want, start there. If it’s the adapter itself you need — you’d rather run it yourself against the open protocol — drop your email below. We’ll write when the first adapter ships and we have an early-access slot to fill. Email Join waitlist Opens your mail client with a pre-filled message. We'll wire up a real intake form before the first adapter lands — until then this stays a direct mailto so nothing intermediates the signal. ## Related [Section titled “Related”](#related) * [How GGUI works](/how-it-works/) — the protocol’s five moments. The gguify pattern reuses the same handshake → render → interact → consume → reopen loop, just driven by your app’s routes instead of LLM-generated UI. * [Glossary](/glossary/) — `actionSpec`, `contextSpec`, `gadget`, `tool`, `blueprint`. * [The dev loop](/build/dev-loop/) — how a GGUI agent moves between a local runtime and hosted ggui. The adapter track inherits the same split. * [For LLM agents](/agents/) — machine-readable resources, including this page at [`/agentic-app-builders.md`](/agentic-app-builders.md). # For LLM agents > Machine-readable resources for LLMs and coding-assistant devtools reading GGUI docs programmatically — aggregated dumps, per-page .md companions, stable anchors, wire schemas. This page is for **non-human readers** — LLM agents, coding-assistant devtools (Claude Code, Cursor, Cline, Continue, Codeium), evaluators, and scrapers. Humans, the rest of the site is for you. ## What’s available [Section titled “What’s available”](#whats-available) | Resource | URL | When to fetch | | --------------------- | ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Dump pointer | [`/llms.txt`](/llms.txt) | First contact. A short [llms.txt](https://llmstxt.org/) file naming the two dumps below plus 11 per-section subsets, one per top-level sidebar group. It is not a per-page list — the finest granularity it indexes is the section. | | Whole-site dump | [`/llms-full.txt`](/llms-full.txt) | One-shot context loading. Every page in one file, sorted to lead with Get Started, Concepts, then the hosted track — around 800 KB, roughly 200K tokens. Check `Content-Length` before you load it. | | Compact dump | [`/llms-small.txt`](/llms-small.txt) | The same page set with navigational chrome stripped. Only about 15 percent smaller than the full dump — if full does not fit, this probably will not either. | | Per-section subset | `/_llms-txt/.txt` | One sidebar group at a time — `get-started`, `concepts`, `hosted`, `build`, `connect`, `self-host`, `protocol`, `api`, `cli`, `architecture`, `reference` (slugs listed in `/llms.txt`). A few pages are cross-listed in two sets where the sidebar itself repeats them (e.g. `cli/login` in both `hosted` and `cli`). | | Per-page raw markdown | `/.md` | Reading one specific page. No HTML, no chrome. | | Whole-site corpus | [`/docs-corpus.json`](/docs-corpus.json) | Every page as one JSON document — `{ schemaVersion, buildSha, builtAt, pages: [{ path, title, description, body }] }`, where each `body` is exactly the bytes that page’s `.md` companion serves. Built for the docs MCP service behind `mcp.ggui.ai/docs`; fetch it once and refresh on the `Cache-Control` TTL. | | Stable anchors | `/#` | Deep-linking to a section. Every H2/H3 has a Starlight-derived id. | Both dumps carry the site’s `404 — page not found` stub as an early section. It is navigation copy, not documentation — skip it. ## Per-page `.md` companions [Section titled “Per-page .md companions”](#per-page-md-companions) Every page is also served as raw markdown at the same slug with a `.md` extension. Examples: * [`/how-it-works.md`](/how-it-works.md) — the narrative walk-through * [`/api/mcp-protocol.md`](/api/mcp-protocol.md) — the wire reference * [`/protocol/envelopes.md`](/protocol/envelopes.md) — live-channel envelope shapes * [`/glossary.md`](/glossary.md) — terminology lookup * [`/cli/serve.md`](/cli/serve.md) — `ggui serve` command reference The `.md` response is the source markdown with a small `---\ntitle: ...\n---` envelope on top. For the markdown-authored pages — every page except the four named below — there is no other transformation. Four pages are authored in MDX and their companions carry that through: [`/index.md`](/index.md), [`/design/tokens.md`](/design/tokens.md), [`/protocol/showcase-trimly.md`](/protocol/showcase-trimly.md) and [`/build/dev-loop.md`](/build/dev-loop.md) keep their JSX component tags (``, ``, ``), and `showcase-trimly` also carries the inline JS block that computes its wire counts. The ESM import preamble is stripped, so the response opens on prose, but the components are not rendered. Prose and code blocks are intact on all four; layout wrappers are not. Fetch the HTML page when you need the rendered form — on `/design/tokens.md` and `/protocol/showcase-trimly.md` in particular, much of the substance lives inside the components. Fetch from any origin: ```bash curl https://docs.ggui.ai/protocol/envelopes.md ``` ```ts const res = await fetch("https://docs.ggui.ai/protocol/envelopes.md"); const body = await res.text(); ``` CORS is open (`Access-Control-Allow-Origin: *`); `Cache-Control` permits 5-minute CDN caching. ## Search docs via MCP [Section titled “Search docs via MCP”](#search-docs-via-mcp) Any LLM agent can connect to `mcp.ggui.ai/docs` and search / read these docs programmatically — no auth required. See [Docs MCP route](/api/mcp-docs/) for the tool catalog and connection details. ## When to use which [Section titled “When to use which”](#when-to-use-which) ```plaintext You want → Fetch ─────────────────────────────────────────── ────────────────────────────────── See which dumps and sets exist /llms.txt Orient quickly, plan a session /index.md, then /.md Drop everything into context (one-shot) /llms-full.txt (~800 KB) Load just one sidebar section /_llms-txt/.txt Read one specific page /.md Deep-link to a section in conversation //# ``` `/llms.txt`, `/llms-full.txt`, `/llms-small.txt`, the 11 `/_llms-txt/.txt` section subsets, and the per-page `.md` companions are the whole machine-readable surface. ## Stable anchors [Section titled “Stable anchors”](#stable-anchors) Every H2 and H3 has a stable `id` derived by Starlight from its text. Anchors don’t change between releases unless the heading text changes. Examples: * [`/glossary/#gguisession-a-render`](/glossary/#gguisession-a-render) — definition of the GguiSession (the “render”) * [`/protocol/envelopes/#actionenvelope`](/protocol/envelopes/#actionenvelope) — inbound live-channel envelope * [`/api/mcp-protocol/#ggui_render`](/api/mcp-protocol/#ggui_render) — the `ggui_render` MCP method The same anchors work on the `.md` companions: [`/protocol/envelopes.md#actionenvelope`](/protocol/envelopes.md#actionenvelope) — markdown clients with anchor-scroll support honor them. ## Wire schemas (roadmap) [Section titled “Wire schemas (roadmap)”](#wire-schemas-roadmap) The wire envelopes (`ActionEnvelope`, `StreamEnvelope`) and the MCP method shapes (`ggui_handshake`, `ggui_render`, `ggui_consume`, …) live in TypeScript in `@ggui-ai/protocol`. Protocol version: see `PROTOCOL_VERSION` in `@ggui-ai/protocol` (currently `draft-2026-09-10`). Standalone JSON-Schema endpoints at `/api/schemas/.json` are planned but not yet shipped. Until then, the canonical wire shapes live at: * [`/protocol/envelopes/`](/protocol/envelopes/) — envelope shapes, fields, validation rules * [`/api/mcp-protocol/`](/api/mcp-protocol/) — MCP methods, request/response shapes * [`/api/websocket-protocol/`](/api/websocket-protocol/) — live-channel framing For machine-parseable types, install the npm package: ```bash npm install @ggui-ai/protocol ``` ## Site conventions [Section titled “Site conventions”](#site-conventions) Things to know if you’re writing code against these docs: * **`ggui`** = the open protocol. Self-host with `ggui serve`, or use the hosted endpoint at `mcp.ggui.ai`. Open source at `github.com/ggui-ai/ggui`. Documented on this site. * **`guuey`** = a separate SaaS platform at `guuey.com`. Different surface, different docs. Don’t conflate the two. * **`gadget`** = renderer-side capability — a wrapped 3rd-party library (`Leaflet`, `Stripe`, …). Formerly called `clientLibraries`. * **`tool`** = agent-side action (an MCP tool the agent invokes). * **`blueprint`** = cached UI recipe (matched at `ggui_handshake` by intent + contract similarity). These three nouns are not interchangeable; mixing them in generated code will confuse readers. ## Page-level metadata [Section titled “Page-level metadata”](#page-level-metadata) Every page has frontmatter with at least `title` and `description`. Most also carry `audience` (one of `agent-builder`, `host`, `operator`, `llm-agent`, `agentic-app-builder`, `all`) and optionally `prereqs`. The `.md` companion re-emits `title` and `description` at the top of the response; other frontmatter fields (`audience`, `prereqs`) are only in the repo source. ## Telemetry [Section titled “Telemetry”](#telemetry) The site sends pageview events to PostHog and tags requests from known LLM-agent user-agents (`claude-bot`, `gptbot`, `perplexitybot`, `cursor`, `cline`, `continue`, `codeium`, …) with `is_bot: true`. No PII, no fingerprinting. Set a useful user-agent and you’ll show up in the bot-traffic dashboard — that helps us prioritize docs machine readers actually use. ## Reporting issues [Section titled “Reporting issues”](#reporting-issues) Found a page that’s hard for LLM consumption, or want a `.md` companion that’s missing something? Open an issue at [`github.com/ggui-ai/ggui/issues`](https://github.com/ggui-ai/ggui/issues) tagged `docs/llm-readability`. # Control MCP plane > MCP tools on the /control plane — design-time protocol tools (anonymous) plus operator actions (apps, orgs, connector keys, coupons, blueprints, provider keys, credits) for operator agents. The `/control` plane is one of GGUI’s two MCP surfaces. It carries everything called *around* a session rather than during one: * **Design-time `protocol` tools** — format references, example blueprints, validators. Answered **anonymously**, because an agent authoring a blueprint has no account yet. See [MCP protocol](/api/mcp-protocol/) for those tools. * **Operator-class `ops` tools** — the same actions the [console UI](/hosted/console/) exposes to a human (create an app, rename it, mint a connector key, redeem a coupon, …), exposed as MCP tools so an LLM acting as an operator agent can perform them on the user’s behalf. **Auth required**, and **confirm-gated** when state-changing. This page is the wire reference for the 16 ops-audience handlers across four domains that ship in the open `@ggui-ai/mcp-server-handlers` package, plus the 24 hosted-only ops tools that live directly in the cloud pod’s own tool registry and answer only on `mcp.ggui.ai` (see [Hosted-only ops](#hosted-only-ops) below). The agent-loop surface (handshake / render / consume / …) lives on the [`/mcp`](/api/mcp-protocol/) data plane and is documented separately — the two surfaces are strictly disjoint. ## What’s on /control [Section titled “What’s on /control”](#whats-on-control) The ops half is the destination for an **operator agent** — an LLM acting as the console’s hands. Typical caller: a Claude conversation that the user opens from `console.ggui.ai` and gives natural-language instructions like “create a new app called Inbox Triage and lock a connector key to it.” The agent calls `ggui_ops_create_app` followed by `ggui_ops_issue_connector_key`, never touching the AppSync GraphQL layer directly. Every tool here mirrors a UI action the console exposes. The open apps handlers in `@ggui-ai/mcp-server-handlers` are pure over typed seams (`AppsSource`, `UserDefaultAppSource`) — the cloud pod binds AppSync-backed adapters; OSS deployments leave the seams unwired and the surface stays narrow. Orgs, connector keys and coupons are hosted-only tools (see [Hosted-only ops](#hosted-only-ops)). ## Endpoint [Section titled “Endpoint”](#endpoint) ```plaintext POST http://127.0.0.1:6781/control ``` The route is **always mounted** — the control plane is part of what a GGUI server is, not an opt-in. A default self-hosted boot serves the 6 design-time `protocol` tools there. The `ggui_ops_*` families register when the operator seams are wired into `createGguiServer({opsApps})` (the ops-blueprint family additionally hangs off the `opsBlueprint` dep bundle). Hosted GGUI serves the same route at `https://mcp.ggui.ai/control`, with every domain bound — the full hosted surface is 46 tools: 6 protocol + 40 ops (the 16 handler-package tools below, including provider-keys and credits, plus the 24 hosted-only tools in [Hosted-only ops](#hosted-only-ops)). See “OSS vs hosted” below for what a self-hosted deployment gets instead. ## Authentication [Section titled “Authentication”](#authentication) `/control` is **anonymous-capable**: a request with no bearer is admitted with a synthesized anonymous identity so the design-time `protocol` tools answer. Every `ggui_ops_*` handler then re-imposes auth for itself — an anonymous caller gets an auth error naming the tool, not a silent no-op and not a transport-level 401. Authenticated callers present a bearer exactly as on [`/mcp`](/api/mcp-protocol/#authentication), via the same upstream `AuthAdapter`: ```plaintext Authorization: Bearer dev Content-Type: application/json ``` Self-hosted: with `ggui serve --dev-allow-all`, any bearer (or none) authenticates as the `builder` identity; default serve requires a pairing-minted bearer. Hosted GGUI runs the OAuth 2.0 Dynamic Client Registration ceremony (see [OAuth on mcp.ggui.ai](/self-hosted/oauth/)). The bearer presented on `/control` is the same bearer presented on `/mcp` — there is no separate “ops token”. Externally-federated end-user identities (`source: 'oidc'`) are rejected at the route with `403`, before MCP dispatch. The control plane is for the account holder and their operator agents, not for an app’s end users. ## Confirmation gate on state-changing tools [Section titled “Confirmation gate on state-changing tools”](#confirmation-gate-on-state-changing-tools) An `ops` tool that changes state answers the first call with a **preview** and mutates nothing. Only a second call carrying `confirm: true` commits: ```jsonc // 1st call → preview, nothing happens {"name": "ggui_ops_delete_app", "arguments": {"appId": "aB3kP9xY"}} // → {"confirmationRequired": true, "confirmationPrompt": "…"} // 2nd call → commits {"name": "ggui_ops_delete_app", "arguments": {"appId": "aB3kP9xY", "confirm": true}} ``` The gate exists so an agent cannot silently mint credentials, spend credits, or delete resources on the user’s behalf: it forces the agent to show the human what will happen and get explicit approval. Reads and lists are single-call. Classification is **default-deny** — an `ops` tool not on the read-only list is treated as state-changing. Deployments that register their own read-only ops tools declare them via `createGguiServer({control: {singleCallOps: [...]}})`. The single-call ops tools (`SINGLE_CALL_OPS`, 15 entries) are: `ggui_ops_list_apps`, `ggui_ops_list_orgs`, `ggui_ops_list_connector_keys`, `ggui_ops_list_blueprints`, `ggui_ops_list_my_apps`, `ggui_ops_list_my_blueprints`, `ggui_ops_list_provider_keys`, `ggui_ops_list_credit_transactions`, `ggui_ops_list_recent_renders`, `ggui_ops_get_credit_balance`, `ggui_ops_get_org_balance`, `ggui_ops_get_my_blueprint_source`, `ggui_ops_get_render_source`, `ggui_ops_setup_byok`, and `ggui_ops_save_library_blueprint`. Fourteen of those are genuine reads. `ggui_ops_save_library_blueprint` is the one deliberate exception — a MUTATION added to the single-call set by owner ruling (GGUI#525, 2026-08-16). It earns the exemption on three properties: it’s idempotent (same name ⇒ one row, a repeat is a no-op), it writes only to the caller’s own library (no cross-tenant or account-wide effect), and its primary caller is the console helper agent auto-saving after a render, where the confirm round-trip was an agent self-confirm with no human in the loop — it bought no safety and cost an extra call on every helper render. A future single-call entry that lacks any of those three properties does not inherit this ruling on its own. ## Identity model [Section titled “Identity model”](#identity-model) Every handler resolves the calling identity through a single helper: ```typescript function resolveOwnerSub(toolName: string, ctx: HandlerContext): string { const sub = ctx.userId ?? ctx.appId; if (!sub) throw new Error(`${toolName}: missing caller identity`); return sub; } ``` * **Hosted (multi-tenant):** `ctx.userId` is the caller’s Cognito sub, populated by the upstream auth adapter. * **OSS (single-tenant):** `ctx.userId` is undefined; `ctx.appId` (resolved by the auth adapter via `defaultAppIdFromIdentity` — typically `workspaceId ?? userId` for kind=user identities) serves as the identity. * **Neither set:** the handler throws — that means an unauthenticated caller slipped past auth, surfaced as a 5xx rather than masked as an empty list. ### Tenancy posture [Section titled “Tenancy posture”](#tenancy-posture) Every read and write is scoped by the resolved identity at the seam layer (`AppsSource.list(ownerSub)` returns only the caller’s rows; `AppsSource.get` returns `null` for foreign rows). Cross-tenant probes never reveal whether a given id exists on another user’s account — the handlers translate “row exists but you don’t own it” to the same shape as “no such row”: | Operation | Cross-tenant probe | | --------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | | `ggui_ops_list_apps` | Returns only caller’s rows; foreign rows invisible. | | `ggui_ops_update_app` / `ggui_ops_set_app_theme` / `ggui_ops_set_default_app` | Throws `app_not_found` — same as a genuinely missing id. | | `ggui_ops_delete_app` | Returns `{deleted: true}` without touching the foreign row. Uniform with “row didn’t exist.” | | `ggui_ops_rename_org` / `ggui_ops_remove_org_member` / `ggui_ops_get_org_balance` | Throws `org_not_found` for orgs the caller isn’t a member of — same as a missing id. | | `ggui_ops_invite_to_org` / `ggui_ops_revoke_invite` | Throws `org_invite_access_denied` for orgs the caller doesn’t administer. | | `ggui_ops_revoke_connector_key` | Throws `connector_key_access_denied` for keys owned by other users. | | `ggui_ops_redeem_coupon` | Throws `coupon_access_denied` for `targetOrgId` orgs the caller isn’t a member of. | | `ggui_ops_set_provider_key` / `ggui_ops_remove_provider_key` with `appId` | Throws `app_not_found` for apps the caller doesn’t own — same as a missing id. | ### One-time secret reveal [Section titled “One-time secret reveal”](#one-time-secret-reveal) Plaintext keys appear exactly once `ggui_ops_issue_connector_key` returns the plaintext `ggui_user_*` secret on its result — this is the **only call** that ever surfaces it. The adapter persists `sha256(plaintext)` hex plus the first \~8 plaintext characters (`apiKeyPrefix`); the plaintext is not stored anywhere. Subsequent `ggui_ops_list_connector_keys` responses carry the prefix and the metadata but never the full secret. The MCP caller (Claude Desktop conversation, console) is responsible for surfacing the plaintext to the user immediately. There is no recovery if it’s lost — the user must revoke and reissue. *** ## Tools by domain [Section titled “Tools by domain”](#tools-by-domain) Four domains, 16 handlers total. Each domain is optional: apps hangs off `CreateGguiServerOptions.opsApps`; ops-blueprint hangs off the `opsBlueprint` dep bundle on `defaultHandlers`; provider-keys and credits are bound by the hosted cloud pod. Leaving a domain unwired removes its tools from `tools/list` at registration time. ## Apps (`ops-apps`, 6 handlers) [Section titled “Apps (ops-apps, 6 handlers)”](#apps-ops-apps-6-handlers) Operator actions on `GguiApp` rows — the rows the universal MCP route resolves per-request to scope sessions. Each row carries `appId` (server-minted base62), `displayName`, optional `systemPrompt` override, optional `rateLimitPerMinute`, `createdAt`, `updatedAt`. Bound on the cloud pod via DDB adapters over the `GguiApp` table. ### `ggui_ops_list_apps` [Section titled “ggui\_ops\_list\_apps”](#ggui_ops_list_apps) Enumerate every `GguiApp` row owned by the calling user. Returns metadata only — same data the console’s Apps section renders. Use to discover ids before calling the mutating tools. **Inputs:** none. **Returns:** `{ apps: AppRecord[] }` ```typescript interface AppRecord { readonly appId: string; readonly displayName: string; readonly systemPrompt?: string; readonly createdAt: string; readonly updatedAt: string; } ``` **Tenancy:** scope is `ownerSub` from the bearer token. Cross-user listings are impossible by construction. ### `ggui_ops_create_app` [Section titled “ggui\_ops\_create\_app”](#ggui_ops_create_app) Provision a fresh `GguiApp` owned by the calling user. Wraps the cloud’s `provisionGguiApp` mutation — opaque base62 `appId` is minted server-side; argument-supplied `appId` is NEVER honored (tenant-takeover vector). | Field | Type | Required | Description | | ------------- | ---------------------- | -------- | -------------------------------------------------------------------------------------------------------------- | | `displayName` | `string` (1–120 chars) | No | Human-friendly label. Defaults to `'My GGUI app'` when absent — matches the auto-create path in `useGguiUser`. | **Returns:** the full `AppRecord` shape as above. **Follow-up:** call `ggui_ops_set_default_app({appId})` to promote the new app to the user’s default. ### `ggui_ops_update_app` [Section titled “ggui\_ops\_update\_app”](#ggui_ops_update_app) Partially update an app the caller owns — `displayName`, `systemPrompt`, and `rateLimitPerMinute` in one call. At least one field is required; an empty update is rejected before any store work. | Field | Type | Required | Description | | -------------------- | ------------------------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------- | | `appId` | `string` | Yes | Target `GguiApp.appId`. Discover via `ggui_ops_list_apps`. | | `displayName` | `string` (1–120 chars) | No | New display name. | | `systemPrompt` | `string` (≤10,000 chars) | No | Replacement text. Pass `""` to clear the override — renders then fall back to the universal default. | | `rateLimitPerMinute` | `integer` (≥ 0) | No | Per-API-key renders/minute. Pass `0` to clear the limit (unlimited). The stored column keeps ONE “unlimited” representation, server-side. | **Returns:** the updated `AppRecord` (with `systemPrompt` / `rateLimitPerMinute` omitted when cleared). **Errors:** | Code | When | | --------------- | ---------------------------------------------------------------------------------------- | | `app_not_found` | The id doesn’t exist OR exists under another tenant (uniform shape — no existence leak). | ### `ggui_ops_delete_app` [Section titled “ggui\_ops\_delete\_app”](#ggui_ops_delete_app) Hard-delete an app owned by the calling user. Idempotent — a second delete of the same id resolves cleanly. | Field | Type | Required | Description | | ------- | -------- | -------- | ----------------------- | | `appId` | `string` | Yes | Target `GguiApp.appId`. | **Returns:** `{ deleted: true }` **Tenancy:** cross-tenant probes return the success shape without touching the foreign row. Uniform with “row didn’t exist.” **Errors:** | Code | When | | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `default_app_delete_blocked` | The target is the caller’s default app. The universal route resolves `defaultAppId` on every request, so it must point at a live app — call `ggui_ops_set_default_app` first, then delete. | ### `ggui_ops_set_default_app` [Section titled “ggui\_ops\_set\_default\_app”](#ggui_ops_set_default_app) Set the calling user’s `GguiUser.defaultAppId` — the universal MCP route resolves this on every request to scope the session. The handler first verifies the caller owns the target `appId` before writing `User.defaultAppId`. | Field | Type | Required | Description | | ------- | -------- | -------- | ----------------------------------------- | | `appId` | `string` | Yes | Target app — must be owned by the caller. | **Returns:** `{ defaultAppId: string }` **Errors:** | Code | When | | --------------- | ----------------------------------------------------------- | | `app_not_found` | Target `appId` doesn’t exist OR is owned by another tenant. | ### `ggui_ops_set_app_theme` [Section titled “ggui\_ops\_set\_app\_theme”](#ggui_ops_set_app_theme) Replace the theme on an app the caller owns. The payload is validated with the protocol’s canonical `appThemeSchema` — the same validator every `GguiApp.theme` write surface runs — so no surface can persist a theme another surface would reject. | Field | Type | Required | Description | | ------- | ---------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | | `appId` | `string` | Yes | Target `GguiApp.appId`. | | `theme` | `AppTheme` | Yes | `{mode: 'light'\|'dark', cssVariables, name?}`. Keys must match `--ggui-*`; values ≤256 chars with breakout characters rejected; ≤200 variables total. | **Returns:** `{ appId, theme, updatedAt }` — the persisted theme echoed back. **Errors:** | Code | When | | --------------- | ----------------------------------------------------------- | | `app_not_found` | Target `appId` doesn’t exist OR is owned by another tenant. | *** ## Blueprints (`ops-blueprint`, 5 handlers) [Section titled “Blueprints (ops-blueprint, 5 handlers)”](#blueprints-ops-blueprint-5-handlers) Operator blueprint authorship — generate, register, list, update, delete cached blueprints for the calling app. Unlike the apps domain, this family registers on the OSS server via the `opsBlueprint` dep bundle on `defaultHandlers` (registry + blueprint store + search; `generate` additionally requires the `resolveLlm` + `blueprints` deps the render generation path reads). ### `ggui_ops_generate_blueprint` [Section titled “ggui\_ops\_generate\_blueprint”](#ggui_ops_generate_blueprint) Author a blueprint via the bound generator (LLM generation + validation). | Field | Type | Required | Description | | ---------------------- | --------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `appId` | `string` | No | Target app. Defaults to the caller’s bound app; a caller not bound to an app must pass it. | | `contract` | `object` | Yes | The `DataContract` to generate against. | | `generator` | `string` | No | Generator slug. Unknown slug fails with `generator_not_found`. | | `persona` | `string` | No | Variance axis — normalized lowercase + trimmed. | | `aesthetic` | `string` | No | Variance axis. | | `context` | `object` | No | Variance axis: a small structured signal. | | `seedPrompt` | `string` | No | Variance axis. | | `intent` | `string` | No | What to generate, in plain words: the prompt the generator composes from, at most 2,000 characters. Not part of the cache identity, so calls that differ only in `intent` share a variant key. When omitted, the generator falls back to `seedPrompt`. | | `setAsOperatorDefault` | `boolean` | No | Mark the result as the operator default for its contract (orders listings; does not decide what serves). | **Returns:** `{ blueprintId, codeHash?, source }` — `source` is the stamped provenance `{ kind: 'llm', generator, model }` from the engine’s own metadata stamp. **Errors:** `generator_not_found`; `missing_credentials` (BYOK fix: `ggui_ops_set_provider_key`); generation failure. ### `ggui_ops_register_blueprint` [Section titled “ggui\_ops\_register\_blueprint”](#ggui_ops_register_blueprint) Register pre-built component code verbatim — no LLM, no validator. Operator entry point for fixture seeding and export/reimport round-trips. | Field | Type | Required | Description | | --------------- | -------- | -------- | ----------------------------------------------------- | | `contract` | `object` | Yes | The `DataContract` the code implements. | | `componentCode` | `string` | Yes | The component code to register verbatim (min 1 char). | Plus the same optional `generator` / `persona` / `aesthetic` / `context` / `seedPrompt` / `setAsOperatorDefault` fields as `ggui_ops_generate_blueprint`, and four optional non-identity facts the semantic reuse pre-filter reads off the cache row (none is part of the cache identity; an omitted fact reads *not evaluated*, never a miss): | Field | Type | Required | Description | | ----------------- | ---------------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `intent` | `string` | No | What the interface is for, in the request’s own words — the sentence the semantic reuse judge compares. Falls back to `seedPrompt`, then `persona`. | | `judgedCanvases` | `string[]` | No | A non-empty list of the canvas classes the interface was judged on (e.g. `xs-chat-card`, `md`). A request on a canvas outside the list is not offered it for semantic reuse. | | `aestheticPreset` | `{ id: string, version?: string }` | No | The aesthetic preset (and resolved version, when known) it was generated under. A request under another preset, or a pinned version that differs, is not offered it. | | `directionDigest` | `string` (sha256 hex) | No | Digest of the direction text it was generated under, normalised (trimmed, whitespace collapsed, lowercased). A request whose direction digests differently is not offered it. | | `directionScope` | `'app' \| 'request'` | No | Which direction `directionDigest` hashes: `app` — the direction the app’s profile carries; `request` — a direction given with the request itself. Only beside `directionDigest` (refused without it). | | `clonedFrom` | `string` | No | When these bytes are a copy of a row this app already holds, that row’s `blueprintId`. The new row records it as provenance; nothing that serves reads it. Refused (`cloned_from_refused`, nothing persisted) when empty, the new row’s own id, not held, or another app’s row, with the same answer for a missing row as for another app’s. | **Returns:** `{ blueprintId, codeHash, source }` — `source` is always `{ kind: 'user' }`; hand-supplied bytes carry no engine claim, so none is recorded. ### `ggui_ops_list_blueprints` [Section titled “ggui\_ops\_list\_blueprints”](#ggui_ops_list_blueprints) | Field | Type | Required | Description | | ---------------- | ---------- | -------- | ----------------------------------------------------- | | `contractHash` | `string` | No | Filter by canonical contract hash. | | `generator` | `string` | No | Filter by generator slug. | | `persona` | `string` | No | Dispatches semantic search. | | `intentKeywords` | `string[]` | No | Dispatches semantic search. Filters are AND-composed. | **Returns:** `{ blueprints: Blueprint[] }` A row minted by a generation carries `build`: the minting engine’s version, design mode and template digests. Registered, installed and older rows carry none, and a reader treats that as an unknown build. ### `ggui_ops_update_blueprint` [Section titled “ggui\_ops\_update\_blueprint”](#ggui_ops_update_blueprint) | Field | Type | Required | Description | | ------------------- | -------------- | -------- | ---------------------------------------------------------------------------- | | `blueprintId` | `string` | Yes | Target blueprint. | | `isOperatorDefault` | `literal true` | No | Mark as the operator default (orders listings; does not decide what serves). | | `variance` | `object` | No | Partial-merge of variance axes; `{persona: ""}` clears the field. | **Returns:** `{ blueprintId, updatedAt }` ### `ggui_ops_delete_blueprint` [Section titled “ggui\_ops\_delete\_blueprint”](#ggui_ops_delete_blueprint) | Field | Type | Required | Description | | ------------- | -------- | -------- | ----------------- | | `blueprintId` | `string` | Yes | Target blueprint. | **Returns:** `{ deleted: true }` — idempotent. *** ## Provider keys (`provider-keys`, 3 handlers) — BYOK [Section titled “Provider keys (provider-keys, 3 handlers) — BYOK”](#provider-keys-provider-keys-3-handlers--byok) Operator actions on the caller’s BYOK LLM provider keys. Provider enum: `'anthropic' | 'openai' | 'google' | 'openrouter'`. The handler factories ship in `@ggui-ai/mcp-server-handlers`; they are bound today by the hosted cloud pod, which validates keys against the provider and encrypts at rest. ### `ggui_ops_set_provider_key` [Section titled “ggui\_ops\_set\_provider\_key”](#ggui_ops_set_provider_key) | Field | Type | Required | Description | | -------------- | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `provider` | `enum` | Yes | One of `anthropic` / `openai` / `google` / `openrouter`. | | `plaintextKey` | `string` | Yes | The provider API key (min 1 char). Re-set replaces (rotation). | | `label` | `string` | No | Human label. | | `appId` | `string` | No | Scope the key to ONE app the caller owns instead of the whole account. App key beats account key for that app’s renders. Requires app-scoped key storage; deployments without it reject with `app_scoped_keys_unavailable`. Foreign/missing apps answer `app_not_found`. | **Returns:** `{ provider, label?, lastFour, createdAt?, lastUsedAt? }` — never echoes the key. ### `ggui_ops_list_provider_keys` [Section titled “ggui\_ops\_list\_provider\_keys”](#ggui_ops_list_provider_keys) **Inputs:** none. **Returns:** `{ keys: [{ provider, label?, lastFour, createdAt?, lastUsedAt? }] }` ### `ggui_ops_remove_provider_key` [Section titled “ggui\_ops\_remove\_provider\_key”](#ggui_ops_remove_provider_key) | Field | Type | Required | Description | | ---------- | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | | `provider` | `enum` | Yes | Provider to remove. | | `appId` | `string` | No | Remove the key scoped to one app the caller owns instead of the account-level key. Same availability + tenancy rules as on `ggui_ops_set_provider_key`. | **Returns:** `{ deleted, provider }` *** ## Credits (`credits`, 2 handlers) [Section titled “Credits (credits, 2 handlers)”](#credits-credits-2-handlers) Read-only views over the caller’s prepaid credit wallet. Bound by the hosted cloud pod; self-hosted deployments have no credit plane. ### `ggui_ops_get_credit_balance` [Section titled “ggui\_ops\_get\_credit\_balance”](#ggui_ops_get_credit_balance) **Inputs:** none. **Returns:** `{ balanceCents, lifetimeGrantedCents, lifetimeSpentCents, updatedAt }` ### `ggui_ops_list_credit_transactions` [Section titled “ggui\_ops\_list\_credit\_transactions”](#ggui_ops_list_credit_transactions) | Field | Type | Required | Description | | -------- | -------- | -------- | ------------------ | | `limit` | `number` | No | 1–100, default 20. | | `cursor` | `string` | No | Pagination cursor. | **Returns:** `{ transactions: [{ transactionId, kind, deltaCents, balanceAfterCents, reason, createdAt, relatedSessionId? }], nextCursor? }` — `kind` is an open vocabulary: the known kinds are `free_credit`, `render_charge`, `topup` and `refund`, and a deployment may add others. Accept a kind you do not know, keep it as named, and never read it as a render charge. *** ## Hosted-only ops [Section titled “Hosted-only ops”](#hosted-only-ops) Twenty-four more `ops`-audience tools live directly in `cloud/ggui-protocol-pod/src/tools/` — the cloud pod’s own tool registry, not the open `@ggui-ai/mcp-server-handlers` package. They answer only on `https://mcp.ggui.ai/control`; a self-hosted `ggui serve` never registers them, because there is no seam to wire them through — they read and write cloud-pod-native tables directly. Thirteen back the chat-native experience (a Claude Desktop or claude.ai conversation acting as the user’s own agent) rather than a specific console UI action, so they’re absent from the [Console parity](#console-parity) table below. The other eleven — orgs, connector keys and coupons — mirror console actions and are listed there; they shipped in the open handler package before v0.25.0. ### App meta-tools [Section titled “App meta-tools”](#app-meta-tools) Universal connector key only (a per-app key is scoped to one app and structurally can’t enumerate or switch siblings). #### `ggui_ops_list_my_apps` [Section titled “ggui\_ops\_list\_my\_apps”](#ggui_ops_list_my_apps) Enumerate the caller’s apps, most-recently-touched first. **Inputs:** `limit` (`integer`, 1–500, optional, default 100). **Returns:** `{ apps: [{ appId, displayName, isDefault, createdAt, updatedAt }] }` — `isDefault` marks the app the universal `mcp.ggui.ai` endpoint currently resolves to. #### `ggui_ops_open_app` [Section titled “ggui\_ops\_open\_app”](#ggui_ops_open_app) Switch the caller’s default app. Writes `User.defaultAppId`; takes effect on the **next** connection — the calling Claude session keeps its already-bound `appId` for the life of the connection. | Field | Type | Required | Description | | ------- | -------- | -------- | ----------------------------------------------------------------------------------------------- | | `appId` | `string` | Yes | 8-char base62 target app id. Must be owned by the caller. Discover via `ggui_ops_list_my_apps`. | **Returns:** `{ appId, message }` — `message` reiterates the reconnect-to-switch caveat. ### Personal blueprint library [Section titled “Personal blueprint library”](#personal-blueprint-library) The caller’s own saved-blueprint library (Claude composes something useful in a conversation, saves it, renders it again later) — a different `GguiUserBlueprint` world from the `ops-blueprint` family’s app-scoped variant curation above, scoped per-app via `ctx.appId` rather than per-owner. #### `ggui_ops_list_my_blueprints` [Section titled “ggui\_ops\_list\_my\_blueprints”](#ggui_ops_list_my_blueprints) | Field | Type | Required | Description | | ------- | --------- | -------- | ------------------- | | `limit` | `integer` | No | 1–500, default 100. | **Returns:** `{ blueprints: [{ name, description?, tags?, usageCount, createdAt, updatedAt, lastUsedAt?, systemSourceId?, systemVersion? }] }` — definition bodies are omitted to keep the list lean; fetch one with `ggui_ops_get_my_blueprint_source`. #### `ggui_ops_get_my_blueprint_source` [Section titled “ggui\_ops\_get\_my\_blueprint\_source”](#ggui_ops_get_my_blueprint_source) | Field | Type | Required | Description | | ------ | -------- | -------- | ----------------------------------------------------------- | | `name` | `string` | Yes | Blueprint slug. Discover via `ggui_ops_list_my_blueprints`. | **Returns:** `{ name, definition: { source, contract?, fixtureProps? }, description?, tags?, updatedAt }`. **Errors:** `blueprint_not_found` (missing or foreign name — uniform, no existence leak); `blueprint_definition_invalid` (a stored row lost its source text). #### `ggui_ops_save_library_blueprint` [Section titled “ggui\_ops\_save\_library\_blueprint”](#ggui_ops_save_library_blueprint) Upsert a blueprint into the caller’s library, keyed on `(appId, name)` — same name replaces the existing row. Re-runs the canonical D16 validator (compile → self-check → runtime probe) server-side as defense-in-depth. Single-call by owner ruling; see the [confirmation-gate section](#confirmation-gate-on-state-changing-tools) above for why. | Field | Type | Required | Description | | ------------- | ---------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------- | | `name` | `string` | Yes | Slug 2–64 chars, kebab-case `[a-z0-9-]`, no underscores, no single-char names. | | `blueprint` | `object` | Yes | `{source, contract?, fixtureProps?}` — pass the object as-is, e.g. straight from `ggui_ops_get_render_source`’s `blueprint` field. | | `description` | `string` | No | Surfaces in the console’s miniapp library. | | `tags` | `string[]` | No | Organization tags. | **Returns:** `{ name, createdAt, updatedAt }`. **Errors:** the D16 validator’s tiered failure envelope (same shape as `ggui_protocol_validate_blueprint`) when validation fails. #### `ggui_ops_update_my_blueprint` [Section titled “ggui\_ops\_update\_my\_blueprint”](#ggui_ops_update_my_blueprint) Rename a library blueprint and/or replace its `description` / `tags` in one call — at least one of `newName`, `description`, `tags` is required. Rename applies first and refuses to overwrite an existing sibling name. | Field | Type | Required | Description | | ------------- | ---------- | -------- | ---------------------------------------------------------------------------------------- | | `name` | `string` | Yes | Current slug. Discover via `ggui_ops_list_my_blueprints`. | | `newName` | `string` | No | New slug, same rule as `name`. Same-name is a no-op. | | `description` | `string` | No | Replacement (≤4000 chars); empty string clears it. | | `tags` | `string[]` | No | Replacement list, trimmed/lowercased/deduped, ≤32 tags of ≤64 chars; empty array clears. | **Returns:** `{ name, updatedAt }` — `name` is the post-rename value. **Errors:** `blueprint_not_found`; `blueprint_name_taken` (rename collision, names the taken slug). #### `ggui_ops_delete_my_blueprint` [Section titled “ggui\_ops\_delete\_my\_blueprint”](#ggui_ops_delete_my_blueprint) Idempotent delete by name. | Field | Type | Required | Description | | ------ | -------- | -------- | ----------------------------------------------------------- | | `name` | `string` | Yes | Blueprint slug. Discover via `ggui_ops_list_my_blueprints`. | **Returns:** `{ name, deleted }` — `deleted: false` means no such blueprint existed; still a success. ### Render introspection [Section titled “Render introspection”](#render-introspection) Universal connector key only — same posture as the app meta-tools, since both read across every app the caller owns. #### `ggui_ops_list_recent_renders` [Section titled “ggui\_ops\_list\_recent\_renders”](#ggui_ops_list_recent_renders) | Field | Type | Required | Description | | ------------- | --------- | -------- | ---------------------------------------------------------------------------------------------- | | `limit` | `integer` | No | 1–100, default 20. | | `appId` | `string` | No | Narrow to one app. Omit to list across every app the caller owns. | | `erroredOnly` | `boolean` | No | Return only renders whose generation failed. Covers at most the 500 most-recent rows per call. | **Returns:** `{ renders: [{ sessionId, appId, createdAt, status, errorCode? }] }` — `status` is `active` or `expired`; an empty list is a valid “nothing yet” answer, not an error. #### `ggui_ops_get_render_source` [Section titled “ggui\_ops\_get\_render\_source”](#ggui_ops_get_render_source) Caller-gated source read for a render session — the link between a render and `ggui_ops_save_library_blueprint`. Only component-variant renders have source; MCP-Apps and system-card renders (and a render that hasn’t finished its first commit) answer a typed no-source error instead of an empty string. | Field | Type | Required | Description | | ----------- | -------- | -------- | -------------------------------------------------------------- | | `sessionId` | `string` | Yes | From `ggui_ops_list_recent_renders` or a `ggui_render` result. | **Returns:** `{ sessionId, blueprint: { source, contract?, fixtureProps? } }` — feed `blueprint` straight into `ggui_ops_save_library_blueprint`’s `blueprint` argument with no reshaping. **Errors:** `render_not_found` (missing or foreign session — uniform, no existence leak). ### BYOK setup card [Section titled “BYOK setup card”](#byok-setup-card) #### `ggui_ops_setup_byok` [Section titled “ggui\_ops\_setup\_byok”](#ggui_ops_setup_byok) Entry point for the BYOK provider-key MCP App card — the chat-native counterpart to `ggui_ops_list_provider_keys` above, shaped for inline card rendering rather than flat consumption. Declares `_meta.ui.resourceUri` so MCP-Apps-aware hosts pre-fetch the bundle and render the card on first call. **Inputs:** none. **Returns:** `{ kind: 'provider-key', configured: [{ provider, prefix }] }` — `prefix` is a display string like `sk-ant…abcd` (canonical provider prefix + the stored last-four), never the plaintext key. ### Registry scope administration [Section titled “Registry scope administration”](#registry-scope-administration) Platform-operator only — gated by `requireScopeOpsOperator` against the `REGISTRY_OPS_OPERATOR_SUBS` allowlist (checked against `ctx.userId`), on top of the normal auth + confirm gates. Scope **owners** publish through the ordinary publish flow and never call these; they exist for the registry operator to reassign or verify scope ownership (e.g. reclaiming a squatted `@scope` for its proven brand owner) and to record which signer identities may publish under a scope. All three mutate global registry state, are deliberately excluded from the single-call set, and emit a structured audit line (`scope_transfer` / `scope_verification_set` / `scope_san_allowlist_set` / `scope_ops_denied`) on every call. #### `ggui_ops_scope_transfer` [Section titled “ggui\_ops\_scope\_transfer”](#ggui_ops_scope_transfer) Reassign an existing scope’s ownership row, or seed one for a reserved scope that was never first-publish-claimable. The written row always lands `verification: 'unverified'` — a transfer moves ownership, it does not assert proof. | Field | Type | Required | Description | | ----------------- | -------- | -------- | --------------------------------------------------------- | | `scope` | `string` | Yes | Target scope, leading `@` included. | | `newOwnerSubject` | `string` | Yes | Auth subject that will own publishes under the scope. | | `reason` | `string` | Yes | Why ownership moves — recorded verbatim in the audit log. | **Returns:** `{ scope, ownerSubject, claimedAt, verification, previousOwnerSubject? }`. #### `ggui_ops_scope_set_verification` [Section titled “ggui\_ops\_scope\_set\_verification”](#ggui_ops_scope_set_verification) Record or withdraw the verified-domain proof on an existing ownership row. `verified` requires `verifiedDomain`; `unverified` forbids it (withdrawing clears both proof fields). | Field | Type | Required | Description | | ---------------- | ---------------------------- | ----------- | ------------------------------------------------------------------------------- | | `scope` | `string` | Yes | Must already have an ownership row — seed with `ggui_ops_scope_transfer` first. | | `verification` | `'unverified' \| 'verified'` | Yes | New label. | | `verifiedDomain` | `string` | Conditional | Required with `verified`; forbidden with `unverified`. | **Returns:** `{ scope, ownerSubject, claimedAt, verification, verifiedDomain?, verifiedAt? }`. #### `ggui_ops_scope_set_san_allowlist` [Section titled “ggui\_ops\_scope\_set\_san\_allowlist”](#ggui_ops_scope_set_san_allowlist) Set or clear the exact sigstore certificate identities (emails or CI workflow URIs) permitted to publish under a scope — pass exactly one of `sanAllowlist` (non-empty, to set) or `clear: true` (to remove); an empty array is refused rather than guessed at. Scopes without a list fall back to the deployment’s default identity rule (verified-email match, where wired). | Field | Type | Required | Description | | -------------- | ---------- | -------- | --------------------------------------------------------------------------------------------------- | | `scope` | `string` | Yes | Must already have an ownership row — seed with `ggui_ops_scope_transfer` first. | | `sanAllowlist` | `string[]` | No | Replacement allowlist, exact literal strings only (no regex/glob). Mutually exclusive with `clear`. | | `clear` | `boolean` | No | Remove the allowlist. Mutually exclusive with `sanAllowlist`. | **Returns:** `{ scope, ownerSubject, claimedAt, verification, verifiedDomain?, verifiedAt?, sanAllowlist? }` — `sanAllowlist` absent after a clear. ### Orgs (7 tools) [Section titled “Orgs (7 tools)”](#orgs-7-tools) Operator actions on `GguiOrg` + `GguiOrgMember` + `GguiOrgInvite` (+ the org credit-balance) rows. Orgs are the unit of multi-user collaboration; each row carries `orgId` (ULID), `name`, `ownerUserId`, plus per-membership role on the join rows. Bound on the cloud pod via DDB adapters over the same tables the console’s org mutations write. #### `ggui_ops_list_orgs` [Section titled “ggui\_ops\_list\_orgs”](#ggui_ops_list_orgs) Enumerate every org the calling user belongs to — owner + admin + member memberships in a single list, each row carrying the caller’s role. **Inputs:** none. **Returns:** `{ orgs: OrgMembershipRecord[] }` ```typescript interface OrgMembershipRecord { readonly orgId: string; readonly name: string; readonly ownerUserId: string; readonly role: "owner" | "admin" | "member"; readonly joinedAt: string; } ``` Mirrors the AppSync `fetchMyOrgs` custom resolver. Use to discover `orgId` before calling the invite tools. #### `ggui_ops_create_org` [Section titled “ggui\_ops\_create\_org”](#ggui_ops_create_org) Provision a fresh `GguiOrg` owned by the calling user. Wraps the cloud’s `provisionGguiOrg` mutation — ULID `orgId` minted server-side; an owner membership row and a zero-balance credit row are inserted atomically via TransactWrite. | Field | Type | Required | Description | | ------ | ---------------------- | -------- | ------------------------------------------------------------------------------------ | | `name` | `string` (1–120 chars) | Yes | Human-friendly display name. Required (no default — orgs are intentional creations). | **Returns:** ```typescript interface CreateOrgOutput { readonly orgId: string; readonly name: string; readonly ownerUserId: string; readonly createdAt: string; readonly updatedAt: string; } ``` #### `ggui_ops_rename_org` [Section titled “ggui\_ops\_rename\_org”](#ggui_ops_rename_org) Rename an org the caller owns or administers. Authorization is owner-OR-admin — an admin curates the org’s presentation just like the owner; member-role callers are rejected. | Field | Type | Required | Description | | ------- | ---------------------- | -------- | --------------------------------------------------------------------------------- | | `orgId` | `string` | Yes | Target org — caller must own or administer it. Discover via `ggui_ops_list_orgs`. | | `name` | `string` (1–120 chars) | Yes | New display name. Trimmed; cap matches org provisioning. | **Returns:** `{ orgId, name, updatedAt }` **Errors:** | Code | When | | ------------------- | -------------------------------------------------------------------------------- | | `org_not_found` | The id doesn’t exist OR the caller isn’t a member (uniform — no existence leak). | | `org_access_denied` | The caller is a member but not owner/admin. | #### `ggui_ops_remove_org_member` [Section titled “ggui\_ops\_remove\_org\_member”](#ggui_ops_remove_org_member) Remove a member from an org, or leave an org by removing yourself. Permission matrix (caller’s role × target’s role): | | target=owner | target=admin | target=member | | --------------- | ------------ | ------------ | ------------- | | `caller=owner` | no | yes | yes | | `caller=admin` | no | only-self | yes | | `caller=member` | no | no | only-self | The org **owner can never be removed** — ownership transfer is a separate flow. Matrix violations surface the specific rule that was hit; only non-member callers get the uniform not-found. | Field | Type | Required | Description | | -------------- | -------- | -------- | --------------------------------------------------------- | | `orgId` | `string` | Yes | Target org — the caller must be a member. | | `memberUserId` | `string` | Yes | Member to remove. Pass your own user id to leave the org. | **Returns:** `{ orgId, memberUserId, alreadyAbsent }` — `alreadyAbsent: true` means no membership row existed (idempotent; a parallel removal is not an error). **Errors:** | Code | When | | --------------------------- | -------------------------------------------------------------------------------- | | `org_not_found` | The id doesn’t exist OR the caller isn’t a member (uniform — no existence leak). | | `org_member_removal_denied` | The role matrix denies the removal — the message names the specific rule. | #### `ggui_ops_get_org_balance` [Section titled “ggui\_ops\_get\_org\_balance”](#ggui_ops_get_org_balance) Read the shared prepaid credit balance of an org the caller belongs to. **Any membership role** — every member can see how much shared credit there is to spend. Single-call (no confirmation gate). | Field | Type | Required | Description | | ------- | -------- | -------- | ----------------------------------------- | | `orgId` | `string` | Yes | Target org — the caller must be a member. | **Returns:** `{ orgId, balanceCents, lifetimeGrantedCents, lifetimeSpentCents, updatedAt }` — an org with no spend history reads as zeros (the balance value is the contract, not the row’s existence). **Errors:** | Code | When | | --------------- | -------------------------------------------------------------------------------- | | `org_not_found` | The id doesn’t exist OR the caller isn’t a member (uniform — no existence leak). | #### `ggui_ops_invite_to_org` [Section titled “ggui\_ops\_invite\_to\_org”](#ggui_ops_invite_to_org) Issue an `admin`- or `member`-role invite to a `GguiOrg` the caller can administer. The invite link in the recipient’s email points at the console: `console.ggui.ai/invites/`. | Field | Type | Required | Description | | ------- | --------------------- | -------- | --------------------------------------------------------------------------------------------------------------------- | | `orgId` | `string` | Yes | Target org — caller must own or administer it. Discover via `ggui_ops_list_orgs`. | | `email` | `string` (RFC 5322) | Yes | Recipient email — the invite link is sent here. | | `role` | `'admin' \| 'member'` | Yes | Role the recipient holds once they accept. Owner can’t be granted via invite — ownership transfer is a separate flow. | **Returns:** ```typescript interface InviteToOrgOutput { readonly inviteId: string; readonly orgId: string; readonly email: string; readonly role: "admin" | "member"; readonly inviterUserId: string; readonly status: "pending" | "accepted" | "revoked" | "expired"; readonly expiresAt: string; readonly createdAt: string; readonly reused: boolean; } ``` **Anti-double-issue:** an existing pending invite for the same `(orgId, email)` is reused — no new row, no second email. `reused: true` flags the dedup. **Errors:** | Code | When | | -------------------------- | -------------------------------------------- | | `org_invite_access_denied` | Caller is not owner/admin of the target org. | #### `ggui_ops_revoke_invite` [Section titled “ggui\_ops\_revoke\_invite”](#ggui_ops_revoke_invite) Invalidate a pending org invite — the bearer-secret link in the recipient’s email stops working immediately. | Field | Type | Required | Description | | ---------- | -------- | -------- | ---------------------------------------------------------------- | | `inviteId` | `string` | Yes | Target invite — must belong to an org the caller can administer. | **Returns:** ```typescript interface RevokeInviteOutput { readonly inviteId: string; readonly status: "pending" | "accepted" | "revoked" | "expired"; readonly alreadyRevoked: boolean; } ``` **Concurrency:** the adapter flips `status` from `pending` → `revoked` via a CAS `ConditionExpression`. A racing accept surfaces a clear conflict instead of silently overwriting. Already-revoked invites return `alreadyRevoked: true`; already-accepted invites reject. **Errors:** | Code | When | | -------------------------- | ------------------------------------------------------ | | `org_invite_access_denied` | Caller is not owner/admin of the invite’s org. | | `org_invite_not_found` | The id doesn’t exist OR isn’t reachable by the caller. | ### Connector keys (3 tools) [Section titled “Connector keys (3 tools)”](#connector-keys-3-tools) Operator actions on `GguiUserApiKey` rows — the user-facing `ggui_user_*` API key strings that Claude Desktop (and other Connectors) present to call the MCP routes on the user’s behalf. Bound on the cloud pod via the `issueGguiUserApiKey` AppSync mutation + the `apiKeysByUserId` GSI + raw DDB `UpdateItem` for revoke. #### `ggui_ops_list_connector_keys` [Section titled “ggui\_ops\_list\_connector\_keys”](#ggui_ops_list_connector_keys) Read the calling user’s `ggui_user_*` connector keys. **Metadata only — NEVER plaintext.** **Inputs:** none. **Returns:** `{ keys: ConnectorKeySummary[] }` ```typescript interface ConnectorKeySummary { readonly id: string; // stable id for revoke readonly apiKeyPrefix: string; // first ~8 chars of the secret (human re-identification) readonly name?: string; // user-supplied label readonly appId?: string; // optional FK — when set the key locks to that app readonly status: "active" | "revoked"; readonly createdAt: string; readonly lastUsedAt?: string; // from the last successful auth lookup readonly expiresAt?: string; // past timestamp ⇒ adapter rejects auth } ``` The hash itself is never returned on any tool. #### `ggui_ops_issue_connector_key` [Section titled “ggui\_ops\_issue\_connector\_key”](#ggui_ops_issue_connector_key) Mint a fresh `ggui_user_*` connector key. | Field | Type | Required | Description | | ----------- | ---------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `name` | `string` (1–120 chars) | No | Optional label, e.g. `'MacBook Claude Desktop'`. Surfaces on `ggui_ops_list_connector_keys`. | | `appId` | `string` | No | Lock the key to one app. When set, sessions opened with this key scope to the named app and meta-tools (`ggui_ops_open_app`, `ggui_ops_list_apps`) are NOT exposed. Absent ⇒ universal key (scopes to `User.defaultAppId` per request). | | `expiresAt` | `string` (ISO 8601) | No | Optional expiry. Past timestamps reject auth from the start. | **Returns:** ```typescript interface IssueConnectorKeyOutput { // metadata — same shape as a list row readonly id: string; readonly apiKeyPrefix: string; readonly name?: string; readonly appId?: string; readonly status: "active" | "revoked"; readonly createdAt: string; readonly lastUsedAt?: string; readonly expiresAt?: string; // ONE-TIME REVEAL — never returned again readonly plaintextKey: string; } ``` One-time reveal `plaintextKey` is the `ggui_user_` secret. It appears on this response and never again — the adapter persists `sha256(plaintextKey)` hex plus `apiKeyPrefix`, and the plaintext is not stored. The caller MUST surface it to the user immediately. #### `ggui_ops_revoke_connector_key` [Section titled “ggui\_ops\_revoke\_connector\_key”](#ggui_ops_revoke_connector_key) Soft-revoke a `GguiUserApiKey` row. The adapter sets `status='revoked'`; the auth path rejects revoked keys regardless of hash match. Rows are kept for audit (age-based sweep handles cleanup). | Field | Type | Required | Description | | ------- | -------- | -------- | ------------------------------------------------------------------------------------------ | | `keyId` | `string` | Yes | Stable id of the row (NOT the secret string). Discover via `ggui_ops_list_connector_keys`. | **Returns:** ```typescript interface RevokeConnectorKeyOutput { readonly id: string; readonly status: "active" | "revoked"; readonly alreadyRevoked: boolean; } ``` **Errors:** | Code | When | | ----------------------------- | ------------------------------------ | | `connector_key_access_denied` | The key belongs to another user. | | `connector_key_not_found` | No such key reachable by the caller. | Idempotent — re-revoking returns `alreadyRevoked: true`. ### Coupons (1 tool) [Section titled “Coupons (1 tool)”](#coupons-1-tool) Operator action on `GguiCoupon` rows — bearer-secret promo codes that credit user or org wallets. Bound on the cloud pod via the `redeemCoupon` AppSync mutation. #### `ggui_ops_redeem_coupon` [Section titled “ggui\_ops\_redeem\_coupon”](#ggui_ops_redeem_coupon) Redeem a `cpn_*` coupon code, crediting the caller’s wallet (default) or a target org’s wallet. The adapter runs an atomic three-leg `TransactWrite`: 1. Flip `GguiCoupon.status` from `issued` → `activated`. 2. Credit the wallet (user or org). 3. Insert a ledger row. Failure of any leg rolls all back — no half-credit, no double-spend. | Field | Type | Required | Description | | ------------- | -------- | -------- | --------------------------------------------------------------------------------------------------------------------- | | `couponCode` | `string` | Yes | The bearer-secret code in format `cpn_<8 chars>`. One-time redemption. | | `targetOrgId` | `string` | No | When set, credits the named org’s wallet instead of the caller’s personal wallet. Caller MUST be a member of the org. | **Returns:** ```typescript interface RedeemCouponOutput { readonly couponCode: string; readonly creditCents: number; readonly redeemedByPrincipalType: "user" | "org"; readonly redeemedByPrincipalId: string; readonly activatedAt: string; } ``` **Errors:** | Code | When | | ------------------------- | ---------------------------------------------------------------------- | | `coupon_not_found` | The code doesn’t exist. | | `coupon_already_redeemed` | The code was previously activated (one-time semantics). | | `coupon_expired` | The code is past its expiry. | | `coupon_access_denied` | `targetOrgId` was provided but the caller is not a member of that org. | *** ## OSS vs hosted [Section titled “OSS vs hosted”](#oss-vs-hosted) The apps domain is wired through an optional field on `CreateGguiServerOptions` (ops-blueprint hangs off the `opsBlueprint` dep bundle on `defaultHandlers`; provider-keys + credits are cloud-pod-bound): ```typescript interface CreateGguiServerOptions { readonly opsApps?: { readonly apps: AppsSource; readonly userDefaultApp: UserDefaultAppSource; }; } ``` * **Hosted (`mcp.ggui.ai`):** the cloud pod binds the apps domain — AppSync-backed adapters wrap the corresponding mutations. Provider-keys and credits (above) are also bound, and the pod additionally registers its own 24 hosted-only tools, orgs, connector keys and coupons among them (see [Hosted-only ops](#hosted-only-ops)) — the full ops surface is already live on `/control`. * **OSS (`ggui serve`):** every field is `undefined` by default. The route still mounts but `tools/list` rejects with `Method not found` — no tools capability is advertised when zero handlers are registered. Operator tools only make sense alongside a data model to operate on; the ops-blueprint family is the one most self-hosters wire (via the `opsBlueprint` dep bundle). * **Wiring apps:** a self-hosted deployment with its own `AppsSource` and `UserDefaultAppSource` binds `opsApps` and gets the six `ggui_ops_*_app` tools. * **Before v0.25.0:** orgs, connector keys and coupons were open handler families wired through `opsOrgs`, `opsConnectorKeys` and `opsCoupon`. Organisations, wallets and user API keys are features of the hosted service, so those families now ship only there; a deployment that bound them can stay on v0.24.0, or copy the handlers into its own code and register them through the `handlers` option. The seam interfaces (`AppsSource`, `UserDefaultAppSource`) are exported from `@ggui-ai/mcp-server-handlers` — implementing them against your own backend is the integration path for downstream forks. ## Console parity [Section titled “Console parity”](#console-parity) The [console UI](/hosted/console/) mirrors these tools 1:1 — every tool corresponds to one UI action: | Tool | Console surface | | ------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `ggui_ops_list_apps` | Apps section — main list. | | `ggui_ops_create_app` | Apps section — “New app” button. | | `ggui_ops_update_app` | Apps section — inline rename + System Prompt editor + rate-limit setting. | | `ggui_ops_set_app_theme` | Apps section → Theme editor. | | `ggui_ops_delete_app` | Apps section — row menu → Delete. Both paths converge on the app-delete cascade worker (see the tool’s section above); the console removes the app row synchronously, the tool’s dependent-row sweep is eventually consistent (seconds). | | `ggui_ops_set_default_app` | Apps section — “Set as default” toggle. | | `ggui_ops_list_orgs` | Orgs section — main list. | | `ggui_ops_create_org` | Orgs section — “New org” button. | | `ggui_ops_rename_org` | Orgs section — org header → Rename. | | `ggui_ops_remove_org_member` | Orgs section → Members → row menu → Remove / “Leave org”. | | `ggui_ops_get_org_balance` | Orgs section → Wallet balance readout. | | `ggui_ops_invite_to_org` | Orgs section → Members → Invite. | | `ggui_ops_revoke_invite` | Orgs section → Members → pending invite row → Revoke. | | `ggui_ops_list_connector_keys` | Account → Connector Keys list. | | `ggui_ops_issue_connector_key` | Account → Connector Keys → “Issue new key”. | | `ggui_ops_revoke_connector_key` | Account → Connector Keys → row menu → Revoke. | | `ggui_ops_redeem_coupon` | Billing → Redeem coupon. | | `ggui_ops_set_provider_key` / `ggui_ops_remove_provider_key` with `appId` | App settings → Provider Keys (per-app override). | The MCP surface and the UI surface are siblings over the same seam — they write the same rows — the console’s “New app” and `ggui_ops_create_app` both go through `AppsSource.create`, for example. There’s no privileged path on either side. *** ## Example: curl [Section titled “Example: curl”](#example-curl) This walkthrough targets a self-hosted server with the ops seams wired (started with `--dev-allow-all` for the `Bearer dev` shortcut). On hosted GGUI, the same calls go to `https://mcp.ggui.ai/control` with an OAuth bearer. Note the `confirm` argument on the state-changing steps — without it, each returns a preview instead of acting. ```bash # 1. Initialize curl -X POST http://127.0.0.1:6781/control \ -H "Authorization: Bearer dev" \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","clientInfo":{"name":"curl","version":"1.0"},"capabilities":{}}}' # 2. Enumerate the caller's apps curl -X POST http://127.0.0.1:6781/control \ -H "Authorization: Bearer dev" \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"ggui_ops_list_apps","arguments":{}}}' # 3. Create a fresh app curl -X POST http://127.0.0.1:6781/control \ -H "Authorization: Bearer dev" \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"ggui_ops_create_app","arguments":{"displayName":"Inbox Triage","confirm":true}}}' # 4. Promote the new app to default (use the appId from step 3's response) curl -X POST http://127.0.0.1:6781/control \ -H "Authorization: Bearer dev" \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"ggui_ops_set_default_app","arguments":{"appId":"","confirm":true}}}' ``` On hosted GGUI, a fifth call — `ggui_ops_issue_connector_key` with `{"name":"MacBook Claude Desktop","appId":"","confirm":true}` — mints a connector key locked to the new app; its response carries `plaintextKey`, to surface to the user immediately (see [Connector keys](#connector-keys-3-tools)). The same calls can be made through the [`@modelcontextprotocol/sdk`](https://github.com/modelcontextprotocol/typescript-sdk) client by pointing the transport at `/control` instead of `/mcp` — the tool registration shapes are standard. *** ## See Also [Section titled “See Also”](#see-also) * [Console](/hosted/console/) — the human-facing surface for the same actions. * [Audience Routes](/architecture/audience-routes/) — the `agent` / `runtime` / `protocol` / `ops` tag model and how it projects onto the two surfaces. * [MCP Protocol Reference](/api/mcp-protocol/) — the sibling agent-loop surface on `/mcp`. # MCP Apps support > How GGUI implements the io.modelcontextprotocol/ui capability so hosts like Claude Desktop, claude.ai, Goose, and VS Code Copilot render generative UIs inline. [MCP Apps](https://modelcontextprotocol.io/extensions/apps/overview) is the protocol extension that lets MCP servers ship interactive UI alongside structured data, and lets MCP hosts render those UIs inline in the chat surface. The OSS [`@ggui-ai/mcp-server`](/quickstart/self-hosted/) implements the wire format on both sides — as does the hosted GGUI server (`mcp.ggui.ai`) — so generative UIs render directly in chat instead of forcing a “click this link” detour to a browser tab. This page documents the protocol pieces GGUI implements. For end-user setup, see [Connect Claude Desktop](/clients/claude-desktop/). For the underlying transport, see [WebSocket protocol](/api/websocket-protocol/). ## What MCP Apps adds [Section titled “What MCP Apps adds”](#what-mcp-apps-adds) Without MCP Apps, an MCP tool that produces UI has to choose between: 1. Returning structured data and hoping the host formats it (no interactivity), or 2. Returning a URL the user clicks out to (interactive, but chat and UI live in separate windows). MCP Apps adds a third option: declare a UI resource alongside the tool result, the host sandboxes it in an iframe inside the chat, and a WebSocket channel carries data both ways — host to UI for live updates, UI to server for actions. ## What GGUI ships [Section titled “What GGUI ships”](#what-ggui-ships) When the server boots with `mcpApps` enabled, three things happen: 1. **`io.modelcontextprotocol/ui` is advertised** in the server’s `initialize` capabilities (under `experimental`). MCP-Apps-aware hosts read this and switch on inline rendering. 2. **`ui://ggui/render` is served** as a resource via `resources/read` — a minimal HTML shell that loads [`@ggui-ai/iframe-runtime`](https://www.npmjs.com/package/@ggui-ai/iframe-runtime) and opens the WebSocket channel. 3. **Every `ggui_render` tool result carries `_meta.ui.resourceUri`** — the `ui://` locator naming the view. Whether the result ALSO carries the `_meta["ai.ggui/render"]` bootstrap slice depends on the deployment posture; see [Tool result shape](#tool-result-shape) below. Hosted GGUI withholds it, self-hosted `ggui serve` inlines it. ### The bootstrap slice [Section titled “The bootstrap slice”](#the-bootstrap-slice) Wherever it is delivered — on the tool result, or inlined by a per-render shell — the `_meta["ai.ggui/render"]` slice is the same shape: `sessionId`, `appId`, `runtimeUrl`, `wsUrl`, a short-TTL `wsToken`, and `expiresAt` (ISO 8601 string) as top-level fields, alongside capability + render-state fields, plus theme fields (`themeId`, `themeMode`, `theme` — the app’s theme, its `--ggui-*` projection for both modes, which the iframe merges into the scoped token block the components read), a `pollingUrl` fallback for WS-blocked environments, `lastSequence` to seed replay cursors, and `epoch`. The iframe consumes the slice and opens the WebSocket with the `wsToken`, which it presents again on a reconnect. `epoch` is the history epoch this mount belongs to, and it is load-bearing rather than decorative. `ggui_render` mints epoch 0; each `ggui_update` result carries its new epoch; a pinned `#N` read carries N; absent reads as 0. The iframe records it at boot as its OWN epoch, and when a later [`props_update`](/api/websocket-protocol/#props_update) frame arrives carrying a HIGHER epoch, this mount has been superseded and freezes instead of applying the new props. A custom runtime that ignores `epoch` will happily repaint a stale history card with state that belongs to a newer one — the exact bug the freeze latch exists to prevent. ## Capability declaration [Section titled “Capability declaration”](#capability-declaration) On `initialize`, GGUI returns: ```json { "capabilities": { "tools": { "listChanged": true }, "resources": { "subscribe": false, "listChanged": false }, "experimental": { "io.modelcontextprotocol/ui": {} } } } ``` Hosts that recognize `io.modelcontextprotocol/ui` flip into inline-render mode. Hosts that don’t simply ignore the capability and skip inline rendering — the render is still delivered as a resource, addressed by `_meta.ui.resourceUri` (see [Render locator grammar](#render-locator-grammar)), but without MCP-Apps support there is nothing to mount it. There is no agent-returned URL to open instead. ## Tool result shape [Section titled “Tool result shape”](#tool-result-shape) Every UI-producing tool (today: `ggui_render`) stamps a locator on the result so the host knows where to load the UI from. There are **two postures**, and a host builder must handle the one their server runs. ### Read-plane-only — what `https://mcp.ggui.ai` returns [Section titled “Read-plane-only — what https://mcp.ggui.ai returns”](#read-plane-only--what-httpsmcpgguiai-returns) Hosted GGUI runs read-plane-only. The result publishes the durable identity and nothing else: no `ai.ggui/render` slice, no `wsToken`. No bootstrap token is minted for a slice nobody receives. ```json { "content": [{ "type": "text", "text": "Created render render_abc123" }], "structuredContent": { "sessionId": "render_abc123", "resourceUri": "ui://ggui/render/render_abc123/bp_9f2c" // … plus action / contractHash / blueprintId / variantKey / cache }, "_meta": { "ui": { "resourceUri": "ui://ggui/render/render_abc123/bp_9f2c" }, "ui/resourceUri": "ui://ggui/render/render_abc123/bp_9f2c" } } ``` The host MUST resolve the view by an authenticated `resources/read` on that locator. What comes back is a **per-render self-contained shell** — an HTML document that inlines the bootstrap slice synchronously on `globalThis.__GGUI_META__`, so the runtime reads it directly and never waits for a host relay. `ui/resourceUri` is the flat legacy alias of the same value, carried for hosts that read that slot. Reading the locator is the shortest path, not the only one. A host that mounts the **declaration-level** static shell instead, the `_meta.ui.resourceUri` announced on `tools/list`, still paints, provided it forwards this result via `ui/notifications/tool-result` and answers `resources/read` from the view. The shell finds only the locator on the result, asks the host to read it, and mounts from the envelope that comes back: the [read-plane door](/protocol/bootstrap-handshake/#the-read-plane-door). That costs one extra host-proxied round trip. A host that cannot proxy the read ends on a failure card after a bounded wait: it reports `MISSING_META_GGUI_BOOTSTRAP`, and its message names the `READ_DOOR_FAILED:` cause (see [the read-plane door](/protocol/bootstrap-handshake/#the-read-plane-door)). ### Inlined bootstrap — the self-hosted `ggui serve` default [Section titled “Inlined bootstrap — the self-hosted ggui serve default”](#inlined-bootstrap--the-self-hosted-ggui-serve-default) Without the withhold posture, the result carries the bootstrap slice inline and a host may mount directly, with no further round-trip: ```json { "content": [{ "type": "text", "text": "Created render render_abc123" }], "_meta": { "ui": { "resourceUri": "ui://ggui/render/render_abc123" }, "ai.ggui/render": { "sessionId": "render_abc123", "appId": "app_abc", "runtimeUrl": "https://your-server.example.com/_ggui/iframe-runtime.js", "wsUrl": "wss://your-server.example.com/ws", "wsToken": "btkn_…", "expiresAt": "2099-01-01T00:00:00.000Z", "epoch": 0 } } } ``` Any deployment can adopt the read-plane-only posture by setting `withholdResultMeta` on the server factory. The identity pointer stays in both postures — the identity IS the pointer, and spec-canonical hosts mount from it. The tool **declaration** (returned by `tools/list`) is what carries `_meta.ui.visibility: ["model"]` — the MCP Apps signal that this tool ships a renderable UI surface. Per-call **results** stamp the locator, as above. ### Render locator grammar [Section titled “Render locator grammar”](#render-locator-grammar) ```plaintext ui://ggui/render/[/][#] ``` | Segment | Presence | Meaning | | -------------- | ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `sessionId` | Always. | The render to resolve. | | `blueprintKey` | On every render since the resume contract landed. | Lets a read fall back to a registry-only mount (the original card with default props) when the render row is gone, instead of returning a typed failure. The segment is named for its domain; the record field it comes from is `contractKey`. | | `#` | On `ggui_update` results; absent means the live head. | Pins the immutable epoch-N record. Pinned reads serve identical content forever (conformance-pinned); the bare URI tracks the session’s current state. | Both the single-segment and two-segment shapes resolve. The single-segment form is kept registered so pre-resume-contract cards still in chat history rehydrate — parse for the optional second segment rather than assuming one is absent. ## The shell at `ui://ggui/render` [Section titled “The shell at ui://ggui/render”](#the-shell-at-uigguirender) Reading the resource returns a small HTML document — paper-themed, full-bleed, no chrome — whose only job is: 1. Obtain the `ai.ggui/render` slice — from the host via `postMessage`, or, for a per-render self-contained shell, from the `globalThis.__GGUI_META__` global it inlines synchronously before the bundle loads. 2. Dynamically load `runtimeUrl` (the iframe-runtime bundle). 3. Hand the slice to the runtime, which opens the WebSocket and starts rendering. The shell is intentionally minimal. The actual rendering work — component resolution, contract validation, action dispatch, gadget loading — lives in [`@ggui-ai/iframe-runtime`](https://www.npmjs.com/package/@ggui-ai/iframe-runtime), which the shell loads on demand. This keeps the shell payload tiny and lets the runtime version-bump independently of host caches. ### Three shell registrations [Section titled “Three shell registrations”](#three-shell-registrations) Reading traffic against a real server, you will see more than one shell URI. There are three registrations, and they all serve the same current shell: | URI | Who asks for it | | ----------------------------- | --------------------------------------------------------------------------------------- | | `ui://ggui/render` | Grandfathered sessions and hosts that read the bare URI directly. | | `ui://ggui/render/rt-` | The content-addressed twin. **Tool declarations advertise THIS URI**, not the bare one. | | `ui://ggui/render/rt-` | Stale-hash grandfather template — serves the current shell under any prior hash. | The hash covers the full served representation: the shell bytes AND the `_meta.ui.csp` declaration the response carries. Hosts cache the prefetched shell keyed on the resource URI, so the URI must change exactly when the content or the CSP policy does — and never otherwise. The meta has to be in the hash input because hosts cache the declaration alongside the bytes: a policy-only change would otherwise ship under an old URI and never reach cached frames. The grandfather template exists because hosts snapshot tool declarations. After a shell-changing deploy they keep asking for the previous deploy’s `rt-` URI; without the template that read falls through to the per-session template (a bare `rt-abc…` segment parses as a `sessionId`), resolves no render, and the host shows a mount failure. ### The `_meta.ui.csp` declaration [Section titled “The \_meta.ui.csp declaration”](#the-_metauicsp-declaration) Shell responses carry a `_meta.ui.csp` block with `connectDomains`. Hosts derive the frame’s `connect-src` from it — claude.ai applies a restrictive default (`connect-src 'none'`) unless the resource declares otherwise, which blocks the cross-origin runtime ` ``` The `event.source` check is non-optional — without it, any window can spoof renderer envelopes. Production hosts SHOULD also validate `msg` against [the lifecycle envelope schema](https://github.com/ggui-ai/ggui/blob/main/packages/protocol/src/integrations/mcp-apps.ts) before mirroring state into trusted UI. *** ## Host obligations summary [Section titled “Host obligations summary”](#host-obligations-summary) A host that implements the JSON-RPC methods above plus the four postMessage event handlers honors the protocol’s bootstrap contract. The MUST / SHOULD breakdown: 1. **MUST** honor `_meta["ai.ggui/render"].runtimeUrl` from the resource — the iframe-runtime bundle URL. 2. **MUST** classify `ggui:bootstrap-failed` onto `BootstrapFailureReason` (or render the raw string for unknown values). 3. **MUST** surface `ggui:bootstrap-failed` as a user-visible error. 4. **SHOULD** surface `ggui:observe` events to host telemetry. 5. **MUST NOT** intercept `tools/call` JSON-RPC traffic — forward to the MCP server’s tool registry verbatim. 6. **MUST** narrow `event.source` to the iframe’s `contentWindow` before reading any postMessage data. Part of this is graded by the [conformance kit](/protocol/conformance/)’s host-helper catalog (`host-helper-conformance`): a well-formed `ui/initialize`, truthful capability advertisement (a host that advertises `serverResources` must answer `resources/read`), honest and bounded refusals, and an unmodified `tools/call` relay. The DOM-level obligations above (`runtimeUrl`, bootstrap-failure surfacing, `ggui:observe`, the `event.source` check) are not graded by the kit. *** ## See also [Section titled “See also”](#see-also) * [Protocol overview](/protocol/overview/) — three-channel topology; bootstrap is the path into the live channel. * [Envelopes](/protocol/envelopes/) — live-channel wire shapes (post-bootstrap traffic). * [Conformance](/protocol/conformance/) — the bar a host implementation must pass. * [`@ggui-ai/iframe-runtime` on GitHub](https://github.com/ggui-ai/ggui/tree/main/packages/iframe-runtime) — `ProtocolError` union, full `ObservabilityEvent` catalog, boot-sequence source. * [`useMcpAppsChat`](/host-helpers/react/) (from `@ggui-ai/mcp-apps-react/chat-helpers`) + `` (from `@mcp-ui/client`) — the web React surface that boxes everything above (React Native’s host is ``). * [`packages/console/src/routes/GguiSessions.tsx`](https://github.com/ggui-ai/ggui/blob/main/packages/console/src/routes/GguiSessions.tsx) — production reference implementation. # Conformance > What it means to be ggui-conformant — the 4-criterion contract bar, 6-criterion protocol bar, and the conformance kit as arbiter. > An implementation is ggui-conformant iff it passes the [conformance kit](https://github.com/ggui-ai/ggui/tree/main/packages/protocol-conformance) — a fixture-based test suite a candidate runs against. Opinion, intent, and prose-level reading of this site are NOT the arbiter; the kit is. This page describes what the GGUI protocol promises in exchange for the name “protocol”, what each contract inside it must satisfy, and how the kit makes those promises observable. ## What conformance means [Section titled “What conformance means”](#what-conformance-means) Conformance for GGUI means three concrete things: 1. **A third-party implementation can replace the first-party one** — agents, hosts, and ops tools that work against the OSS `ggui serve` work against the third-party server too, without source-level changes. 2. **Every named failure mode produces an observable signal** — operators see violations without running a debugger. 3. **Every breaking change to the protocol is reproducible** — “is this PR breaking?” resolves to a kit run, not a debate. If a layer that calls itself a “protocol” can’t honor these three promises, the layer is something else (a shape, an SDK feature, an author convention) and should be named accordingly. ## The Contract Bar — 4 criteria [Section titled “The Contract Bar — 4 criteria”](#the-contract-bar--4-criteria) A **runtime contract** in GGUI MUST satisfy all four. Three of four is not a contract. Documenting a fourth in prose without mechanism is not a contract. ### 1. Named parties [Section titled “1. Named parties”](#1-named-parties) The contract states WHO is on each side. Not “producer” and “consumer” in the abstract — the concrete roles. The `ggui_runtime_submit_action` handler and the consume-buffer pipe. The iframe-runtime and the render-channel server. The contract author and the platform validator. If you can’t name the parties in one sentence, there is no contract — only a data type adrift. * ✅ “The `ggui_runtime_submit_action` handler appends every valid `kind: 'dispatch'` envelope to the render-keyed pending-events pipe; the agent drains it via `ggui_consume`.” * ❌ “Clients should respect the ordering semantics.” ### 2. Explicit obligations per party [Section titled “2. Explicit obligations per party”](#2-explicit-obligations-per-party) Each party has a list of MUSTs and MUST-NOTs. SHOULDs are discipline, not contract — a SHOULD belongs in a style guide. The obligations must be specific enough that a reviewer can literally check a diff against them. * ✅ “Agent-authored `streamSpec` MUST NOT declare a channel whose name starts with `_ggui:`.” * ❌ “Handlers should behave predictably.” An obligation without a verifiable test is a hope, not a contract. ### 3. Defined failure mode per obligation [Section titled “3. Defined failure mode per obligation”](#3-defined-failure-mode-per-obligation) When the obligation breaks, there is a **named, typed, observable failure**. Generic `throw new Error()` is not a failure mode. `console.warn()` is not a failure mode. “Log the outcome to telemetry and carry on” is not a failure mode. Acceptable mechanisms: * A canonical error-code union (`CONTRACT_VIOLATION`, `SESSION_NOT_FOUND`, `SCHEMA_MISMATCH_ERROR`, the runtime-tool rejection codes `INVALID_ACTION_KIND` / `PIPE_NOT_FOUND` / `CONTEXT_TOO_LARGE`). * A typed rejection frame the caller receives on the call that caused it (e.g. a `CONTRACT_VIOLATION` error frame on the live channel, or a `{ok:false, code}` `structuredContent` rejection on a runtime tool). * Boot-time refusal with a message naming the offender (e.g. mount tool-name collision). * Compile-time impossibility (the type has no field → consumers can’t read it). Unacceptable: silent noop, silent degradation, swallowed exception, “it’ll surface in the next call if it’s a real problem.” ### 4. Observable violation [Section titled “4. Observable violation”](#4-observable-violation) An operator can **see the violation without running a debugger**. Surfaces: * An error envelope/frame the caller observes synchronously (the gold standard — a `CONTRACT_VIOLATION` error frame on the live channel when an inbound action violates the contract). * A validation response the caller receives synchronously. * An operator UI that reads the above. * A structured log emitted at a known event name, documented as the contract’s telemetry point. A contract whose violations only show up in production stack traces fails this bar — an operator who inherits the system in six months can’t tell what’s working and what’s silently degraded. *** ## The Protocol Bar — 6 criteria [Section titled “The Protocol Bar — 6 criteria”](#the-protocol-bar--6-criteria) A **protocol** is the emergent layer above a set of contracts. Every layer called “a protocol” MUST satisfy all six. Five of six is a protocol-in-progress; the gap MUST be flagged explicitly and the layer treated as experimental until closed. ### 1. Wire-format specification [Section titled “1. Wire-format specification”](#1-wire-format-specification) A canonical prose spec describing every envelope shape, every field, every value constraint, and — critically — every intentional omission and why. Not just TypeScript types. Types say the shape; the spec says the **semantics**. For GGUI, this lives in the site-level wire references — [Envelopes](/protocol/envelopes/), [MCP Protocol](/api/mcp-protocol/), [WebSocket Protocol](/api/websocket-protocol/) — which document every envelope shape, field, and intentional omission. ### 2. Message sequencing and state [Section titled “2. Message sequencing and state”](#2-message-sequencing-and-state) Given envelope X at time T in state S, which transitions are legal? What happens on reconnect? On resume? On concurrent emission? Crash recovery? Out-of-order delivery? A protocol without sequencing is a data type with pretensions. GGUI’s sequencing lives in the [three-channel topology](/protocol/overview/) + the `GguiSessionStreamBuffer` interface + the `fromSeq` replay contract. Any new channel or envelope class MUST answer the sequencing question explicitly. ### 3. Version negotiation [Section titled “3. Version negotiation”](#3-version-negotiation) Producer and consumer MUST be able to agree on what version they speak, or explicitly refuse. Stamping a version on every envelope is infrastructure; actually rejecting a mismatched peer is the protocol feature. Pre-launch “advisory stamp only” is acceptable IF the launch-cutover plan names the policy flip (producer-stamp + consumer-reject). Anti-pattern: calling version-stamping “versioning” and shipping. See [Version policy](/protocol/version-policy/) for the post-launch handshake semantics. ### 4. Conformance testability at the seam [Section titled “4. Conformance testability at the seam”](#4-conformance-testability-at-the-seam) A third-party implementer can verify their implementation without running the GGUI server. This means: * A public fixture table of envelopes and expected behaviors. * An executable conformance kit (a test package a third party `pnpm add`s and runs). * Coverage of every canonical failure mode — a third-party implementation that passes the kit can be used interchangeably with the first-party one. Without this, “third party adopts the protocol” means “third party reads the spec and hopes.” ### 5. Named failure modes — closed, or extensibly-closed [Section titled “5. Named failure modes — closed, or extensibly-closed”](#5-named-failure-modes--closed-or-extensibly-closed) Every way the protocol can fail has a name, a code, and a shape. Acceptable forms: * **Closed union** — exhaustive by design. Bumping requires a major version bump. Use when the set of values is fixed by an external spec or by a pre-launch design decision the protocol owners control end-to-end. * **Extensibly-closed** — e.g. the `channel_error` code union `'CHANNEL_UNKNOWN' | 'SESSION_NOT_FOUND' | 'SUBSCRIBE_UNAUTHORIZED' | 'POLL_FAILED' | (string & {})`, or the open `code: string` on the WS `error` frame whose canonical literals include `CONTRACT_VIOLATION` and `UPGRADE_REQUIRED`. Consumers MUST handle unknown values gracefully. Adding new values does NOT bump the protocol version. Use when producer-side failure modes are expected to grow (new tool classes, new transports, new preconditions) without consumers needing a new version to render them. Unacceptable: ad-hoc `message: string` as the only failure surface. ### 6. Vendor-neutral separation from implementation [Section titled “6. Vendor-neutral separation from implementation”](#6-vendor-neutral-separation-from-implementation) The protocol package imports nothing from a specific runtime, transport, cloud vendor, or framework. `@ggui-ai/protocol` MUST remain consumable by a third-party implementation that has never seen `@ggui-ai/mcp-server`. Violation of this criterion is the loudest signal that what you have is an SDK feature pretending to be a protocol. *** ## The conformance kit [Section titled “The conformance kit”](#the-conformance-kit) The kit lives at [`packages/protocol-conformance`](https://github.com/ggui-ai/ggui/tree/main/packages/protocol-conformance) in the open repo — a fixture-based test suite a candidate implementation runs against to demonstrate conformance. ```bash pnpm add -D @ggui-ai/protocol-conformance ``` Beyond the WS runner, the package ships a sub-entrypoint per catalog that is not a WS fixture. The [package README](https://github.com/ggui-ai/ggui/tree/main/packages/protocol-conformance#conformance-status) says what each is graded against. Among them: | Entrypoint | Kind | Covers | | ---------------------------------- | -------------------------------------- | -------------------------------------------------------------------------------------------------- | | `schema-conformance` | Pure function | Gadget schema obligations. | | `registration-conformance` | Pure function | Gadget registration obligations. | | `resolution-conformance` | Pure function | Gadget resolution obligations. | | `binding-conformance` | Pure function | MCP tool-binding resolution and search-filter semantics. | | `resource-read-conformance` | Driver (live MCP server) | A `resources/read` catalog — the kit’s first MCP-binding driver. | | `domain-error-conformance` | Driver (`tools/call`) | Domain errors as tool results whose text leads with the registered slug (§7.9 Plane 2). | | `dispatch-idempotency-conformance` | Driver (`tools/call`) + a session seam | A retried `ggui_runtime_submit_action` dispatch is one gesture (§11.1); SHOULD level this release. | Import them as `@ggui-ai/protocol-conformance/`. The raw fixture catalog is also exported at `@ggui-ai/protocol-conformance/fixtures`. Programmatic and CLI entry points: ```ts import { runConformance } from "@ggui-ai/protocol-conformance"; const result = await runConformance({ serverUrl: "http://localhost:3000", auth: { kind: "bearer", token: process.env.TOKEN! }, }); if (result.failed.length > 0) process.exit(1); ``` ```bash npx ggui-protocol-conformance --url http://localhost:3000 --auth bearer:$TOKEN ``` A fixture grades a MUST unless it declares `"level": "should"`. An unmet SHOULD is a **warning**: it lands in `result.warned` with the same evidence a failure carries and never fails a run, so the exit code above ignores it. The first SHOULD case is `fresh-subscribe-replays-reserved-preview` (SPEC §12.2.1): a fresh subscribe replays a known-reserved channel’s retained envelopes after the ack. `serverUrl` / `--url` take the implementation’s **base** `http://` / `https://` URL — the runner appends `/ws` and derives the `ws://` / `wss://` scheme itself. **Transport.** The behavioral fixture catalog is **WebSocket-only** — the canonical GGUI transport (see the [WebSocket Protocol reference](/api/websocket-protocol/)). `resource-read-conformance` adds a second binding: an MCP `resources/read` catalog driven against a live MCP server. The kit’s `TransportConfig` is an extensibly-closed union, so further bindings (stdio MCP, HTTP long-poll) can be added without breaking the public API. **Path-A vs Path-B fixtures.** The fixture catalog spans both wire-observable claims and surface-observable claims. The runner handles **Path-A** — behaviors a runner can assert from WS frames alone (no MCP-Apps-host adapter, no Playwright). **Path-B** fixtures (e.g., `bootstrap-failure`, `props-update`) require a browser-host harness driving Playwright + `page.route()` fault injection + DOM assertion; they are recorded as SKIP on the WS runner, not FAIL. The partition is intentional: Path-A FAILs are vendor-neutrality bugs the server owns; Path-B SKIPs are claims a different driver is responsible for. The kit covers: * **Envelope round-trip** — every fixture in the table can be emitted, observed, validated, and round-tripped. * **Reserved-channel authority** — the implementation rejects agent-authored `streamSpec` entries in the `_ggui:` namespace and validates the platform-owned shapes (`_ggui:preview`, `_ggui:lifecycle`). * **Schema enforcement** — `actionSpec[action].schema` ⊆ the hinted tool’s `inputSchema`, with a `SCHEMA_MISMATCH_ERROR` push-time rejection on violation. * **Sequencing** — `seq` is gap-free per-session, `fromSeq` replay returns the right tail, `replayTruncated` is honored when the requested cursor is unrecoverable. * **Version handshake** — schema-version stamping on every envelope; `UPGRADE_REQUIRED` emission on mismatch (post-launch — pre-launch is advisory). * **Action persistence** — an action frame round-trips to an ack carrying `payload.sequence`, proving the event landed on the GguiSession’s consume buffer (append-then-ack). * **Contract enforcement at receipt** — an action for an undeclared name is rejected with a `CONTRACT_VIOLATION` error frame and nothing reaches the consume buffer. A change is **breaking** iff at least one fixture that passed against version N now fails against version N+1 when the only change is the protocol version. See [Version policy → §2](/protocol/version-policy/#2-breaking-change-definition--the-kit-is-the-arbiter) for the policy this anchors. *** ## Pre-launch vs launch posture [Section titled “Pre-launch vs launch posture”](#pre-launch-vs-launch-posture) Pre-launch (`draft-` versions), some protocol criteria are intentionally at ⚠️ — flagged gaps with owners and closing slices. The point is not zero gaps forever; it is **zero silent gaps**. | Criterion | Pre-launch posture | Launch (v1.0) | | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | | Version negotiation | Envelope `schemaVersion`: advisory stamp; consumers MUST NOT reject on mismatch. Subscribe handshake (`supportedVersions` / `serverVersion`): server default `versionPolicy: 'reject'` — emits `UPGRADE_REQUIRED` and closes; `'advisory'` is a legacy opt-out for migration windows. | Same mechanisms; envelope stamps stay advisory, the subscribe handshake stays the rejection point. Mismatched majors surface as `UPGRADE_REQUIRED`. | | Conformance kit | Optional today; available for first-party servers + early third-party implementers. | Required before third-party implementers are invited to build on the protocol. | | Schema-compat checker | Render-time + console blueprint-try (`SCHEMA_MISMATCH_ERROR` rejection on the `ggui_render` tool result); operator policy `'reject' \| 'warn' \| 'off'` (default `'reject'`). | Same; default unchanged. | At launch, all load-bearing boundaries MUST be at 4/4 contract + 6/6 protocol for any layer described as a public interop surface. Load-bearing = any boundary a third-party implementer is expected to adopt. Internal-only boundaries may sit at lower scores if the gap is explicitly scoped to internal use. *** ## Anti-patterns [Section titled “Anti-patterns”](#anti-patterns) Things that feel contract-shaped but fail the bar: | Looks like | Is actually | Why | | ------------------------------------- | ---------------------------- | ---------------------------------------------------------- | | “TypeScript type is the contract” | Shape-only | Types say what, not who/when/what-on-violation | | “Docstring says MUST” | Author discipline | Prose without mechanism decays | | “A validator function exists” | Half-contract | Validator without observable failure path wastes the check | | “Error gets logged” | Not observable | Logs aren’t observability unless somebody reads them | | “Pre-launch advisory” | Infrastructure, not contract | Valid interim stance; MUST flag the gap + name the flip | | “We cover the common cases” | Denylist discipline | Rock-paper-scissors with future adversaries | | “Three similar implementations agree” | Folklore | Interop-by-intuition is not interop | If a new “contract” maps to a row here, either strengthen it to meet the bar or pick a different word. *** ## Vocabulary [Section titled “Vocabulary”](#vocabulary) Used precisely throughout this site: * **Shape** — a TypeScript type with no enforcement story. * **Convention** — author discipline; no mechanism. * **Contract** — passes the 4-criterion bar. * **Protocol** — passes the 6-criterion bar; a set of contracts with sequencing + versioning + conformance-kit. If a doc says “this contract is enforced by convention” — that’s a category error and either the contract framing or the convention framing is wrong. *** ## See also [Section titled “See also”](#see-also) * [Protocol overview](/protocol/overview/) — three-channel topology and reference implementation. * [Version policy](/protocol/version-policy/) — semver semantics, breaking-change definition, deprecation timeline. * [Envelopes](/protocol/envelopes/) — wire shapes the conformance kit asserts on. * [Conformance kit on GitHub](https://github.com/ggui-ai/ggui/tree/main/packages/protocol-conformance) — the test package itself. # Live-channel envelopes > Wire shapes for ActionEnvelope (inbound), StreamEnvelope (outbound), and the reserved _ggui namespace. The live WebSocket carries three body shapes: | Shape | Direction | Carries | | -------------------- | --------------- | -------------------------------------------------------------- | | `ActionEnvelope` | client → server | A canonical user action (form submit, click, …) | | `StreamEnvelope` | server → client | An outbound delivery on a named stream channel | | `PropsUpdatePayload` | server → client | The full replacement props state for an already-mounted render | The first two are the envelopes an agent-declared contract validates against. `PropsUpdatePayload` carries no contract-declared channel — it is the state fan-out — but it rides the same socket, so it is documented here too. For the complete frame catalog (`subscribe`, `ack`, `render`, `render_event`, `channel_*`, …) see the [WebSocket Protocol reference](/api/websocket-protocol/#frame-catalog). Canonical wire reference. Shapes below mirror the TypeScript in [`@ggui-ai/protocol`](https://github.com/ggui-ai/ggui/tree/main/packages/protocol/src) verbatim: `types/events.ts` (ActionEnvelope), `types/live-channel.ts` (StreamEnvelope, PropsUpdatePayload). *** ## ActionEnvelope [Section titled “ActionEnvelope”](#actionenvelope) Inbound live-channel envelope — the body of a `type: 'action'` WebSocket message. Flat, narrow, limited to fields the server actually enforces or diagnostic fields real consumers populate today. ```ts interface ActionEnvelope { sessionId: string; // required — render identity type: EventType; // required — see EventType below payload?: TPayload; // shape depends on `type` clientSeq?: number; // client-monotonic dedup hint schemaVersion?: string; // producer's PROTOCOL_SCHEMA_VERSION (advisory pre-launch) } ``` | Field | Type | Required | Semantics | | --------------- | ----------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `sessionId` | `string` | Yes | Server enforces subscriber-render binding — envelopes whose `sessionId` doesn’t match the render the WebSocket subscriber is bound to are rejected with `SESSION_MISMATCH`. | | `type` | `EventType` | Yes | Always `data:submit` — the only member of the `EventType` union (see below). The active render’s `actionSpec` gates which action names are accepted. (The pre-actionSpec `EventSubscription` / `DEFAULT_SUBSCRIPTION` gating shapes were deleted from `@ggui-ai/protocol` — there is no subscription gating on the wire.) | | `payload` | `TPayload?` | No | For `type: 'data:submit'` this carries an `ActionEventValue` shape (`{action, data, tool?}`) whose `data` field is validated against the render’s `actionSpec[action].schema`. | | `clientSeq` | `number?` | No | Client-monotonic sequence number for at-least-once dedup. Declared shape; no server enforcement today (no inbound dedup infrastructure yet). Clients SHOULD populate when their transport can replay (e.g., reconnect-with-backfill). | | `schemaVersion` | `string?` | No | Protocol schema version stamped by the producer. Pre-launch: advisory — consumers MUST NOT reject on mismatch. Post-launch: receiving major mismatches surface as `UPGRADE_REQUIRED`. | ### Fields intentionally NOT on the envelope [Section titled “Fields intentionally NOT on the envelope”](#fields-intentionally-not-on-the-envelope) These fields appear on neighboring shapes but are excluded from `ActionEnvelope` by design: | Field | Why omitted | | --------------------------------- | ------------------------------------------------------------------------------------------------------- | | `appId` | Server resolves it from the render; client-claimed values are ignored for enforcement. | | `userId` / `user` | Diagnostic render metadata captured at subscribe time, not per-delivery. | | `deviceInfo` / `interfaceContext` | Same as above — render-level, not action-level. | | `componentId` / `contractHash` | Diagnostic; no enforcement consumer today. | | `timestamp` | Server uses its own clock for ordering + log emission; client-supplied timestamps aren’t authoritative. | | `correlationId` | The doctrine names this for agent-push ↔ user-action pairing; `sessionId` covers the narrow case today. | ### `EventType` [Section titled “EventType”](#eventtype) `EventType` is a single-member union — `'data:submit'` is the only action type the protocol recognizes: | Type | Notes | | ------------- | ----------------------------------------------------------------------- | | `data:submit` | Carries `ActionEventValue` (`{action, data, tool?}`); schema-validated. | The old `data:change` / `lifecycle:focus` / `lifecycle:blur` / `interaction:click` / `interaction:hover` / `interaction:scroll` / `error:validation` / `error:connection` members were removed in `draft-2026-06-12` — they had no producers. ### `ActionEventValue` [Section titled “ActionEventValue”](#actioneventvalue) Payload shape for `data:submit`: ```ts interface ActionEventValue { action: string; // action ID from the contract (e.g. "submit", "archive") data: TData; // action payload (e.g. form data) tool?: string; // MCP tool name mirrored from actionSpec[action].nextStep (when declared) } ``` **Derivation.** `tool` is derived server-side from `actionSpec[action].nextStep` at event-build time — clients do not populate it. When the action has no declared `nextStep`, `tool` is absent — the agent decides the next tool freely from broader context. The hint is advisory either way; the agent owns the call decision. *** ## StreamEnvelope [Section titled “StreamEnvelope”](#streamenvelope) Outbound live-channel envelope — the body of a `type: 'data'` WebSocket message. Carries a single delivery on a named stream channel. ```ts interface StreamEnvelope { sessionId: string; // required channel: string; // required — keys into streamSpec mode: StreamChannelMode; // required — 'append' | 'replace' payload: JsonValue; // required — channel-specific shape complete?: boolean; // terminal marker for completable channels seq?: number; // server-assigned monotonic outbound sequence schemaVersion?: string; // producer's PROTOCOL_SCHEMA_VERSION } ``` | Field | Type | Required | Semantics | | --------------- | ------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `sessionId` | `string` | Yes | Render this delivery belongs to. | | `channel` | `string` | Yes | Channel name. Keys into the agent’s declared `streamSpec`. Names starting with `_ggui:` are server-owned (see [Reserved channels](#reserved-channels)). | | `mode` | `StreamChannelMode` | Yes | State-folding mode. `'append'` (default for narrative streams — message log, telemetry) accumulates deliveries; `'replace'` (default for snapshot streams — task progress, session state) replaces the current value. Senders declare; receivers honor. Typically equals the channel’s declared `mode` on the spec, but the envelope is the authoritative per-delivery signal. | | `payload` | `JsonValue` | Yes | Validated against `streamSpec[channel].schema`. Shape is channel-specific; consumers typecheck via contract inference when they use `defineContract` + `useStream`. | | `complete` | `boolean?` | No | Terminal completion marker — truthy on the last delivery for a completable channel (one declared with `complete: true` on the spec). Consumers use this to transition subscribers into a “channel closed” state. Absent on non-terminal deliveries. | | `seq` | `number?` | No | Render-scoped monotonic outbound sequence. Server-assigned; clients MUST NOT populate it on producer-side inputs. Gap-free within a single render, starting at 1. Used by the client to track `lastSeenSeq`, the highest `seq` it has applied, for reconnect (pass it back as `SubscribePayload.fromSeq`), and to dedupe deliveries against it (at-least-once semantics), never against the ack’s `streamSeq` (SPEC §12.2.1). OPTIONAL because stamping is best-effort: both OSS `@ggui-ai/mcp-server` and hosted cloud stamp `seq` on every successfully buffered delivery, but a delivery whose buffer record failed ships unstamped rather than blocking the emit. A future slice promotes this to required once buffering is guaranteed non-lossy. | | `schemaVersion` | `string?` | No | Same advisory-pre-launch / `UPGRADE_REQUIRED`-post-launch semantics as on `ActionEnvelope`. | ### Fields intentionally NOT on the envelope [Section titled “Fields intentionally NOT on the envelope”](#fields-intentionally-not-on-the-envelope-1) | Field | Why omitted | | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | `replay` | Per-channel policy declared on `streamSpec[channel].replay`. A per-delivery field would imply replay can vary message-to-message, which it can’t. | | `timestamp` | Replay correctness needs `seq` only; timestamp is a future optional addition driven by a concrete client-UX need. | *** ## PropsUpdatePayload [Section titled “PropsUpdatePayload”](#propsupdatepayload) Server → client. The body of a `type: 'props_update'` message — the `ggui_update` / `ggui_amend` fan-out. Replaces props on an already-rendered component without re-generation. ```ts interface PropsUpdatePayload { sessionId: string; props: JsonObject; epoch?: number; } ``` | Field | Type | Required | Description | | ----------- | ------------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `sessionId` | `string` | Yes | The render being updated. | | `props` | `JsonObject` | Yes | **Full replacement state**, not a patch — post-merge for `kind: "merge"` updates. Persistence is the source of truth; this frame is the latency optimization. | | `epoch` | `number?` | No | The commit-time history epoch. `ggui_update` stamps its just-advanced epoch; `ggui_amend` stamps the unchanged head. | `epoch` is the **freeze-latch signal**. A mount whose own epoch is lower than the frame’s has been superseded and MUST freeze rather than apply — that is what keeps an old history card from silently repainting with state belonging to a newer one. Absent `epoch` reads as `0`: pre-epoch producers and amends against an epoch-0 head omit it. Consumers MUST tolerate the absence rather than reject the frame. *** ## Reserved channels [Section titled “Reserved channels”](#reserved-channels) Channel names starting with `_ggui:` are **reserved** for the server. Agent-authored `streamSpec` MUST NOT declare any name in this namespace; structural validation rejects every reserved-prefix entry with the message `Stream channel '' is in the reserved '_ggui:' namespace — server-owned channels cannot be declared in agent streamSpec`. Two channel names are recognized today: | Channel | Owner | Payload shape | Purpose | | ----------------- | ------------- | -------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `_ggui:preview` | Server (A2UI) | A2UI `ServerMessage` — see `@ggui-ai/preview-a2ui` | Provisional A2UI assembly stream emitted by the server during fresh-gen `ggui_render` flows. The renderer subscribes implicitly and dispatches the payload through its preview surface. | | `_ggui:lifecycle` | Server | `GguiLifecyclePayload` | Generation-progress lifecycle kinds (`handshake_started`, `handshake_completed`, `render_started`, `consume_polling`) the renderer surfaces as a progress affordance. | A typo inside the reserved namespace (e.g. `_ggui:preveiw`) is NOT recognized — delivery falls through to the normal “unknown channel” rejection rather than silently passing as a reserved channel. The `_ggui:contract-error` channel was a reserved channel in earlier drafts but was removed entirely in `draft-2026-06-11` — the channel, its payload shape, and its validator are gone. Contract violations now surface as a typed `CONTRACT_VIOLATION` error frame on the live channel on the call that caused them; nothing lands on the consume buffer. *** ## Schema versioning [Section titled “Schema versioning”](#schema-versioning) The `schemaVersion` field is present on both envelopes. It carries the producer’s `PROTOCOL_SCHEMA_VERSION` constant. **Pre-launch (`draft-` versions):** advisory. Consumers MUST NOT reject on mismatch; missing `schemaVersion` fields are normal. **Post-launch:** receiving an envelope whose major version diverges from the consumer’s known major surfaces as a live-channel error with `code: UPGRADE_REQUIRED`. The handshake resolution flow is documented in the [WebSocket Protocol](/api/websocket-protocol/) reference. See [Version policy](/protocol/version-policy/) for the full mapping of what counts as a major / minor / patch bump. *** ## See also [Section titled “See also”](#see-also) * [WebSocket Protocol](/api/websocket-protocol/) — live-channel message types (`subscribe`, `action`, `ack`, `render`, `data`, `error`) that carry these envelope payloads. * [MCP Protocol](/api/mcp-protocol/) — MCP JSON-RPC methods (`ggui_handshake`, `ggui_render`, `ggui_consume`, etc.). * [Protocol overview](/protocol/overview/) — the three-channel topology. * [Version policy](/protocol/version-policy/) — semver semantics, breaking-change definition, deprecation timeline. * [`@ggui-ai/protocol` source](https://github.com/ggui-ai/ggui/tree/main/packages/protocol/src) — canonical TypeScript definitions. # Protocol overview > GGUI is an open protocol for AI agents to render interactive UIs over three wire channels. MCP-native, framework-agnostic, server-enforced. `ggui` is an **open protocol** that lets AI agents render interactive UIs to humans. An agent describes what it needs in natural language; GGUI generates React components, delivers them over a typed live channel, and routes user actions back through a server-side enforcement point. This site documents the protocol itself, version `draft-2026-09-10` (see `PROTOCOL_SCHEMA_VERSION` in [`@ggui-ai/protocol`](https://github.com/ggui-ai/ggui/tree/main/packages/protocol/src/version.ts)). Everything below is implementable from the spec — the open-source [`ggui serve`](/cli/serve/) is the reference conformant implementation, and hosted GGUI at `https://mcp.ggui.ai` runs the same protocol. The `@ggui-ai/*` packages are the reference implementations. ## Three parties, three channels [Section titled “Three parties, three channels”](#three-parties-three-channels) ```plaintext ┌───────────────────────┐ │ user client │ │ (React / RN / web) │ └─────┬────────────┬────┘ │ │ chat live (WebSocket) (HTTP SSE) ↑↓ │ │ ┌────────▼────┐ ┌───▼────────────┐ │ wrapped- │ │ │ │ agent │ │ core-mcp │ │ (developer │───▶ (session │ │ code) │ MCP authority) │ └─────────────┘ └────────────────┘ MCP (over HTTP) ``` | Channel | Direction | Transport | Purpose | Status | | ------- | ---------------------- | ------------- | ------------------------------------------------- | --------- | | Chat | user ↔ wrapped-agent | HTTP SSE | Conversational surface (chat-completion style) | Optional | | MCP | agent ↔ core-mcp | MCP over HTTP | Tool control + session mutation | Mandatory | | Live | core-mcp ↔ user client | WebSocket | Live UI session delivery + canonical user actions | Mandatory | The MCP and live channels are the **protocol kernel** — every conformant implementation MUST provide them. The chat channel is product-mandatory (the OSS `ggui serve` ships a chat surface) but protocol-optional: an embed that uses GGUI purely for typed live UIs, with no conversational chat, is still conformant. The WebSocket endpoint is `ws://127.0.0.1:6781/ws` (default) when running `ggui serve` locally; self-hosters expose it as `wss:///ws`. (The hosted endpoint is `wss://mcp.ggui.ai/ws`.) ## Why the live channel is mandatory [Section titled “Why the live channel is mandatory”](#why-the-live-channel-is-mandatory) The typed live-channel contract needs a server-side enforcement point. That point is the live channel itself. A `streamSpec` declares named streams, payload schemas (validated as `StreamEnvelope`s), replay policy, ordering, and completion semantics. Subscriptions declare which events the client UI consumes. None of that means anything unless a non-agent authority validates it on the wire. If the agent shipped bytes directly to the user, the “contract” would be documentation, not contract — see [Conformance](/protocol/conformance/) for the 4-criterion contract bar this enforces. So **no live channel, no enforcement point, no contract.** The live channel and the typed live-channel contract are a pair — reconsider one, you reconsider the other. ## Wire surfaces [Section titled “Wire surfaces”](#wire-surfaces) Each channel maps to a documented wire surface on this site: | Surface | Channel | What it covers | | --------------------------------------------------- | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [MCP Protocol](/api/mcp-protocol/) | MCP | JSON-RPC methods (canonical lifecycle order): `ggui_handshake`, `ggui_render`, `ggui_consume`, `ggui_update`, `ggui_amend`, `ggui_emit`, `ggui_get_session`, `ggui_get_render_source`, `ggui_list_sessions`, plus gadget/theme/blueprint discovery (`ggui_list_gadgets`, `ggui_list_themes`, `ggui_list_featured_blueprints`, `ggui_search_blueprints`, `ggui_render_blueprint`) | | [WebSocket Protocol](/api/websocket-protocol/) | Live | Subscribe / `ActionEnvelope` / ack / render / `StreamEnvelope`; replay; reconnection | | [MCP Apps support](/api/mcp-apps/) | MCP + Live | Resource shape (`{contents:[{uri,mimeType,text}]}`); host-side iframe-runtime boot | | [OAuth (`ggui serve --oauth`)](/self-hosted/oauth/) | MCP | OAuth 2.1 + PKCE + Dynamic Client Registration for hosts with no pre-shared bearer | ## Reference implementation [Section titled “Reference implementation”](#reference-implementation) The open implementation lives at [`github.com/ggui-ai/ggui`](https://github.com/ggui-ai/ggui): * `packages/mcp-server` — the MCP + live-channel server. * `packages/mcp-apps-react` / `packages/mcp-apps-react-native` — the web and React Native MCP-Apps host helpers. They wrap the host side of the handshake; rendering semantics live in the mounted view, not in these packages. * `packages/ggui-cli` — ships [`ggui serve`](/cli/serve/), which runs the whole protocol locally on one command. The self-hosted open-source path runs the whole protocol on one command via `ggui serve`. Hosted GGUI at `https://mcp.ggui.ai` runs the same protocol on managed infrastructure, with no self-host required. ## Core vocabulary [Section titled “Core vocabulary”](#core-vocabulary) Three nouns recur on every page. Get them right and the rest of the spec falls into place — see the [glossary](/glossary/) for the full list. * **Gadget** — a renderer-side capability (Mapbox, Leaflet, a charting library). Declared per-app in `ggui.json#app.gadgets` (the `@ggui-ai/gadgets` stdlib is always the floor); loaded at iframe boot. The agent never touches gadget code. * **Tool** — an agent-side action exposed over MCP (`ggui_render`, `ggui_update`, `ggui_amend`, etc.). Tools mutate session state. * **Blueprint** — a cached recipe (component code + contract) keyed by intent. Matched on the reuse path; generated on miss. Gadgets and tools are the protocol’s two **symmetric capability surfaces** — gadgets give the renderer something to render with; tools give the agent something to act with. Both are operator-bounded and declared per-app (`clientCapabilities.gadgets`, `agentCapabilities.tools`). See [glossary → Capabilities](/glossary/#capabilities). ## What the protocol is not [Section titled “What the protocol is not”](#what-the-protocol-is-not) * **Not a renderer.** The protocol carries component code and props; how the host evaluates that code is its concern. The reference implementation uses dynamic ESM import plus the `@ggui-ai/iframe-runtime` bundle (the self-contained ESM bundle that boots inside the MCP-Apps iframe), but a conformant host can swap in a sandboxed iframe, a server-rendered HTML pipeline, or anything else. * **Not a UI library.** Components are generated per render by the agent; GGUI ships no fixed component set. Primitives (Button, Input) are catalog-declared, not protocol-declared. * **Not framework-coupled.** The wire is JSON over HTTP and WebSocket. React has the most-developed host helpers today, but `@ggui-ai/protocol` types and `@modelcontextprotocol/sdk` (Anthropic’s official MCP TypeScript SDK) are framework-neutral. ## Versioning + conformance [Section titled “Versioning + conformance”](#versioning--conformance) The protocol follows semver. The arbiter for “what counts as a breaking change” is the **conformance kit** at [`packages/protocol-conformance`](https://github.com/ggui-ai/ggui/tree/main/packages/protocol-conformance) — a fixture-based test suite that any candidate implementation runs against. A change is **major** iff at least one conformance fixture that passed against version N now fails against version N+1, with the protocol version as the only delta. See the [Version policy](/protocol/version-policy/) for the full semver mapping, deprecation timeline, and version support matrix. ## See also [Section titled “See also”](#see-also) * [MCP Protocol reference](/api/mcp-protocol/) — MCP wire grammar. * [WebSocket Protocol reference](/api/websocket-protocol/) — live-channel wire grammar. * [Envelopes](/protocol/envelopes/) — the live-channel wire shapes: `ActionEnvelope` (inbound) and `StreamEnvelope` (outbound), plus the reserved `_ggui:` channel namespace. * [Bootstrap handshake](/protocol/bootstrap-handshake/) — host-side postMessage + JSON-RPC contract for mounting a session in an iframe. * [Conformance](/protocol/conformance/) — the kit, the bar, and how to claim conformance. * [`ggui serve`](/cli/serve/) — run the protocol locally. # Showcase: a real turn > One real conversation with a live ggui-rendering agent, narrated beat by beat — every "On the wire" panel is a frame recorded off the wire, not prose about what would happen. Two turns, one thread, two rendered surfaces. Read the story; open any **On the wire** panel to see exactly what crossed the wire at that beat. Nothing on this page is typed by hand: each panel is read out of the committed recording at build time, and a panel that names a frame the recording does not contain fails the build rather than quietly showing you prose. ## 1 · The ask [Section titled “1 · The ask”](#1--the-ask) A visitor — anonymous, no account — types *"What does Sam's week look like for a haircut?"*. The rig behind this recording invoked the agent the way that visitor would: over the host’s guest wire, with no sign-in and no bearer token. One POST goes out, and the first frame back is the `session`, which is where that shows up on the wire: `authMode: "anonymous"`, a caller id standing in for the guest hash the real exchange carried (placeholdered here like every other id), and the `threadId` that names the durable thread every later turn replays against. ## 2 · Handshake — the contract, negotiated [Section titled “2 · Handshake — the contract, negotiated”](#2--handshake--the-contract-negotiated) Before any UI exists, the agent calls **`ggui_handshake`** with an *intent* and a *draft contract*. The draft is the interesting half: the agent describes, in schema, the surface it wants. The server answers with a **proposed** contract, an `action` (here `reuse`), and an `origin` — `cache` (a similar UI was built before and is reused), `agent` (the draft was already clean), or `synth` (the server repaired it). Open the panel to read the server’s rationale: which blueprint it matched, at what confidence, and every coverage gap between the draft and the cached surface. The contract is where the protocol’s placement rule lives: `actionSpec` = discrete events that drive the agent’s next turn, `contextSpec` = observable state the agent reads when it next works, and there is no third category — see [the placement test](/glossary/#contract) and [Envelopes](/protocol/envelopes/). Watch what the two frames in the panel do with that. This ask wanted an action: the draft declares `actionSpec.pickSlot` alongside its props. The contract the server proposed — reused from a cached blueprint — carries no such thing: `slots=∅; actions=selectSlot(date,dayName,time); streams=∅; props=days:array!,personName:string!,service:string!,weekLabel:string!`. The differences come back as 2 `COVERAGE_GAP` findings at `warn` — `actionSpec.pickSlot`, `propsSpec.properties.apptLabel` — never a veto, with the server's own counsel attached: "Default to ACCEPT (reuse-and-refine) — override only if the user must directly see or act on this surface". The agent accepted, so the grid this recording mounted is a read-only card. Re-aiming the contract instead is a call the protocol gives it — beat 6 is where that lever appears. One detail the raw frames show and this page smooths over: hosts may namespace MCP tool names. In these recordings the wire name is `mcp__ggui__ggui_handshake`; the protocol name is `ggui_handshake`, and readers of the stream should match on the bare name. ## 3 · Render — and the contract check that refuses a bad one [Section titled “3 · Render — and the contract check that refuses a bad one”](#3--render--and-the-contract-check-that-refuses-a-bad-one) **`ggui_render`** commits the contract and returns the view’s **identity** — not its material. On this host’s stream that arrives as a `tool.done` frame carrying the render’s JSON both as text and as the result’s `structuredContent`: `resourceUri`, the view’s durable `ui://` identity; `action`, reporting whether the surface was created or reused; `contractHash`; and a `cache` record. What is deliberately **not** on the wire is the mount material — the bootstrap that boots the runtime and opens the live channel, the compiled component, the theme. A host resolves those by reading `resourceUri` (MCP `resources/read`), the read-plane-only posture: the tool result names the view, the read plane serves it — see [Bootstrap handshake](/protocol/bootstrap-handshake/). Note what the agent never writes: component code. Its call is `handshakeId` plus `props` — and, when it wants to re-aim the contract it was offered, an `override` — but read the assembled-arguments frame in the panel and you will not find markup, styling, or a component anywhere in it. Authoring the UI is not the agent’s job. So where is the code? Not in the panel — and that is the point. Under the read-plane-only posture the tool result carries no `ai.ggui/render` slice at all: the host takes the `resourceUri` above to MCP `resources/read` and receives the shell — the bootstrap (which runtime to load, which live channel to open), the compiled component, the theme — from the read plane, cached and content-addressed. The agent's stream stays small and identity-shaped; the multi-kilobyte material never rides the conversation. It was generated server-side, from the contract; the agent neither wrote it nor saw it. A negotiated contract is enforced, not advised. When the props an agent commits violate the contract it just agreed to, the render is **refused** with a typed error naming the exact offending path, and the agent repairs the call and renders again — no human in the loop. That is the check working, not the agent failing. In this turn the check fired. The panel below carries every render call and result in wire order: the first result is a refusal, and the last is the success. The violation is worth reading in full — it names a path and the vocabulary the contract declared: `days[0].slots[0].note: Undeclared field 'note' at 'days[0].slots[0]'. Declared keys: [time, status]. (expected: , got: string)`. Other violations take the same shape: a field the contract never declared, a string where an object was specified, each reported by path. ## 4 · The view boots [Section titled “4 · The view boots”](#4--the-view-boots) The host mounts the material; the runtime inside the frame answers the MCP-Apps `ui/initialize` handshake, posts `ggui:renderer-ready`, and opens the live WebSocket named in the bootstrap. This beat happens **inside the host page**, not on the agent’s SSE stream — which is why there is no wire panel here: the recorded stream shows the agent’s side only. The exact boot flow and host obligations are specified in [Bootstrap handshake → the boot flow](/protocol/bootstrap-handshake/#the-boot-flow). ## 5 · The gesture (and how a real one arrives) [Section titled “5 · The gesture (and how a real one arrives)”](#5--the-gesture-and-how-a-real-one-arrives) A surface that declares an action routes a tap this way: the visitor taps, the runtime emits an `ActionEnvelope` on the live channel, and the agent drains it with **`ggui_consume`** and reasons about it on its next turn — see [Envelopes → ActionEnvelope](/protocol/envelopes/#actionenvelope). This recording was made by a script that sent no gesture, so there is no `ggui_consume` frame to show and nothing here claims one happened. What the frames do show is the end of the turn: the agent hands control back with a next step, offering to take the conversation further. ## 6 · Turn 2 — a second ask on the same thread [Section titled “6 · Turn 2 — a second ask on the same thread”](#6--turn-2--a-second-ask-on-the-same-thread) *"Compare Thursday afternoon against Friday morning for me."* The invoke carries the `threadId` learned in beat 1, so the agent has the whole conversation. The panel below opens turn 2 with its own `session` frame — naming the same `thread_1` you read in beat 1, and the numbering is what makes that evidence rather than coincidence: one placeholder map spans the whole recording, so turn 2's ids *continue* turn 1's instead of restarting at `_1` (blueprint\_2, call\_5, handshake\_2). Equal placeholders therefore mean equal ids, and this thread is on screen four times across the panels on this page — both `session` frames and both `done` frames, all agreeing. The handshake that follows it negotiates a contract for the new ask. One caution if you open the raw fixtures: two different id spaces share the key name `threadId`. The `session` frame's is the platform's durable conversation thread — the one a replayed turn rejoins, and the one every claim on this page is about. The message-stream frames (`turn.start`, `message.start`) carry the AgJSON stream's own per-turn thread id under the same key: `thread_2` in turn 1 and `thread_3` in turn 2, neither of them `thread_1`. Different spaces, same spelling; compare session frames to session frames. **This recording shows a second render.** The agent negotiated again — a second `ggui_handshake` on the same thread — and rendered a fresh comparison surface. That is a legitimate choice for a *different* surface: a two-option slot comparison is not the week grid. The contract check from beat 3 applies here too. This time nothing was refused — the agent's props conformed on the first call, so the panel holds one call and one successful result. Beat 3 is where you can see the check turn a call back. **What it would look like if the agent mutated the mounted surface instead.** When the right move is to change what an already-mounted view shows — the same grid, different week — the rule is *never re-render to mutate*. The agent calls [`ggui_amend`](/api/mcp-protocol/): no generation runs, the props are swapped and pushed down the live channel, and the card the user is looking at updates in place — no new card, the history number does not advance, and it updates *without losing scroll position, focus, or uncommitted input*. `ggui_update` is that same swap plus a new history card, and it advances the epoch. Either way the wire shape is one message — a [`props_update`](/api/websocket-protocol/#props_update) on the live WebSocket carrying `{sessionId, props, epoch}`, a full props replacement rather than a patch. The agent-side loop is written up in [How it works](/how-it-works/). This recording exercises neither call; nothing here claims it does. ## 7 · What a conforming implementation had to do [Section titled “7 · What a conforming implementation had to do”](#7--what-a-conforming-implementation-had-to-do) At each beat above, an implementation either did the specified thing or the turn would not have completed: answered the handshake with a conforming contract (beat 2), validated the committed props against that contract before mounting anything (beat 3), returned a durable identity the host resolves to mount material through the read plane (beat 3), booted and negotiated inside the frame (beat 4), and — for a surface that declares an action — would route a gesture back as an `ActionEnvelope` (beat 5). Validation is the one of those you can watch happen rather than take on faith: one call in this recording was refused for violating the contract, and the repair that followed is in beat 3's panel, one frame later. The arbiter of “conforming” is not this page — it is the [conformance kit](/protocol/conformance/); the fixtures behind these panels are the kind of input it runs. ## 8 · Run it yourself, check yours [Section titled “8 · Run it yourself, check yours”](#8--run-it-yourself-check-yours) * **See it live:** [guuey.com/demos/scheduler](https://guuey.com/demos/scheduler) — run the same ask and watch a negotiation of your own. * **Check your implementation:** take the recording itself — [turn 1](/showcase/trimly/turn-1.frames.json), [turn 2](/showcase/trimly/turn-2.frames.json), and its [manifest](/showcase/trimly/manifest.json) — and feed the frames to your host or server as fixtures. They are the same files these panels are built from, ids placeholdered, nothing else altered. * **Build your own agent on the protocol:** [Build an agent on hosted GGUI](/quickstart/hosted-agent/) or [self-host](/quickstart/self-hosted/). # Version policy > Major / minor / patch semantics for the GGUI protocol, deprecation timeline, support matrix, and CI enforcement. > **Semver promise:** a change to `@ggui-ai/protocol` is breaking if-and-only-if a consumer built against the prior version now fails the conformance kit. This page defines “major”, “minor”, and “patch” on the GGUI protocol, how deprecation windows work, which server ↔ client pairs are supported, and how a breaking change is migrated. The canonical version constant is `PROTOCOL_SCHEMA_VERSION` (an alias of `PROTOCOL_VERSION` in [`@ggui-ai/protocol`](https://github.com/ggui-ai/ggui/blob/main/packages/protocol/src/version.ts)). Current value: `draft-2026-09-10`. Wire-level negotiation runs through the schema-version handshake; mismatches surface as the `UPGRADE_REQUIRED` error. The current server default is `versionPolicy: 'reject'` — on mismatch the server emits `UPGRADE_REQUIRED` and closes the connection; `'advisory'` is a legacy opt-out that keeps it open. *** ## 1. Semver semantics applied to the protocol [Section titled “1. Semver semantics applied to the protocol”](#1-semver-semantics-applied-to-the-protocol) The protocol follows semver. What counts as each bump kind is defined by the **conformance kit** ([`packages/protocol-conformance`](https://github.com/ggui-ai/ggui/tree/main/packages/protocol-conformance)), not by surface-syntax changes in the `@ggui-ai/protocol` package. ### Major (N → N+1) [Section titled “Major (N → N+1)”](#major-n--n1) A bump is **major** iff at least one conformance-kit fixture that passed against version N now fails against version N+1 when the only change is the protocol version. Examples of changes that are major: * Renaming a **reserved channel** (e.g., `_ggui:preview` → `_ggui:assembly`). * Removing a canonical live-channel error code that the kit asserts (e.g., deleting `CONTRACT_VIOLATION`). * **Narrowing** an extensibly-closed union (e.g., collapsing `SubmitActionKind` variants so previously-recognized kinds now fail validation). * Changing the shape of an **envelope** (`ActionEnvelope`, `StreamEnvelope`) in a way that invalidates fixtures emitted by prior-version producers — required-field additions, required-field renames, required-field type changes. * Tightening a `MUST` / `MUST NOT` clause in the spec such that prior-conformant implementations become non-conformant. * Changing handshake semantics in a way that rejects a subscribe that would previously have succeeded (e.g., the `versionPolicy` default flip `advisory` → `reject` — already shipped on 2026-04-24 as a pre-launch config-default change with its own release note; post-v1.0, a flip of this shape is major). * Removing or replacing a **transport binding** previously declared conformant. ### Minor (N.x → N.(x+1)) [Section titled “Minor (N.x → N.(x+1))”](#minor-nx--nx1) A bump is **minor** iff every conformance-kit fixture that passed against N.x still passes against N.(x+1), and the delta is additive. Examples of changes that are minor: * Adding a new **`channel_error` code** literal (consumers that don’t recognize it degrade per the extensibly-closed union rule). * Adding a new **observability event kind** to the renderer’s `ggui:observe` postMessage union (extensibly-closed — see the [Bootstrap handshake](/protocol/bootstrap-handshake/) page). * Adding an **optional field** on an envelope. Pre-existing consumers see `undefined` and MUST behave as before. * Adding a new **reserved channel** whose absence is not a failure mode for prior-version consumers. * Adding a new **canonical live-channel error code** (the `code` field is typed open). * Adding a new **transport binding** (e.g., stdio MCP, HTTP long-poll) while keeping WebSocket canonical. ### Patch (N.x.y → N.x.(y+1)) [Section titled “Patch (N.x.y → N.x.(y+1))”](#patch-nxy--nxy1) A bump is **patch** iff the only changes are documentation clarifications, fixture additions that do not change assertions on prior-version consumers, or internal implementation adjustments to first-party packages that do not affect the wire or the kit. Examples: * Spec prose clarifications that close a reader-ambiguity without changing obligations. * New conformance-kit fixtures that assert behavior already required by the prior version’s spec text. * Bug fixes in first-party servers / clients that bring them back into conformance (the bar was always there — the code now honors it). ### The `draft-` prefix [Section titled “The draft- prefix”](#the-draft--prefix) Pre-v1 versions use a `draft-` prefix (e.g., `draft-2026-06-12`). While `draft-`, the semver rules above describe **intent**, not **obligation** — the protocol reserves the right to ship breaking changes without a migration doc until the first stable release tags `v1.0`. **Rule flip at v1.0:** once `PROTOCOL_SCHEMA_VERSION` drops the `draft-` prefix, every major bump MUST have a migration doc (CI-enforced) and every deprecation MUST honor the window described in §3. *** ## 2. Breaking change definition — the kit is the arbiter [Section titled “2. Breaking change definition — the kit is the arbiter”](#2-breaking-change-definition--the-kit-is-the-arbiter) > **A change is breaking if-and-only-if a consumer built against the prior version now fails the conformance kit.** Anchor every future “is this breaking?” debate to a kit run. Opinion, intent, and prose-level spec reading are NOT the arbiter — the kit is. Operational consequences: 1. If you’re unsure whether a PR is breaking, **run the kit** against the prior-version tag and against the PR branch. If fixtures that passed before now fail, the PR is major. 2. If the kit passes but you “feel” the change is risky, **add a fixture** that captures the worry. Either the fixture passes (the change is not breaking) or it fails (the change is breaking and you just found out) — both outcomes are productive. 3. If you think a change is major but the kit disagrees, the kit has a gap. Patch the kit in the same PR; the patched kit decides. This anchor means every change’s breaking-ness is **observable and reproducible**, not a matter of taste. *** ## 3. Deprecation timeline [Section titled “3. Deprecation timeline”](#3-deprecation-timeline) Deprecation is the only graceful path from a minor-version ship to a major-version removal. ### The window [Section titled “The window”](#the-window) * **v(N)** — the version in which a surface is first tagged `@deprecated` (in TSDoc) AND documented in the release notes as deprecated. The surface MUST continue to work identically to the prior version; `@deprecated` is a signal to consumers, not a behavior change. * **v(N+1)** — deprecated surface still works. Callers SHOULD migrate in this window. Release notes repeat the deprecation warning. * **v(N+2)** — removal is allowed here at the earliest. Removal is a major bump, so this version is v(N+2) = major. The two-minor window guarantees consumers saw at least one full minor cycle with the `@deprecated` warning before removal. ### Minimum [Section titled “Minimum”](#minimum) **At least two minor versions MUST elapse between `@deprecated` and removal.** If N is the first deprecated version and N+2 is the major that removes it, the intermediate v(N+1) minor MUST ship. Shorter windows (v(N) deprecated → v(N+1) removed) are NOT allowed for non-security changes. ### Security-fix escape hatch [Section titled “Security-fix escape hatch”](#security-fix-escape-hatch) A **critical security fix** MAY skip the window — shipping a breaking change without a prior `@deprecated` minor — if and only if: 1. The release note explicitly names the CVE or security class. 2. The release note explains why the window was skipped. 3. A migration doc per §5 ships alongside the release. Non-security urgency (e.g., “this mistake is embarrassing”) is NOT grounds for skipping the window. ### What “deprecated” means on the wire [Section titled “What “deprecated” means on the wire”](#what-deprecated-means-on-the-wire) The protocol does not have a wire-level “deprecated field” marker. Deprecation lives in TSDoc on the `@ggui-ai/protocol` types and in the release notes. Consumers parsing the wire cannot detect a field is `@deprecated` from the frame alone — they learn it from the package changelog. ### Policy-default flips count as breaking [Section titled “Policy-default flips count as breaking”](#policy-default-flips-count-as-breaking) Changing a **default** that the wire handshake depends on is breaking under §2 because consumers that relied on the prior default observably fail against the new default. The canonical example already happened pre-launch: the `versionPolicy` default flip `advisory` → `reject` shipped on 2026-04-24 as a config-default change with its own release note. Post-v1.0, a flip of that shape MUST use the same window: ship the new value as an opt-in in v(N), document the flip in the release notes, then flip the default in v(N+2). *** ## 4. Version support matrix [Section titled “4. Version support matrix”](#4-version-support-matrix) Which server versions support which client versions. Populated at launch (v1.0); the row below is illustrative — the protocol is pre-v1 (`draft-2026-09-10`) today: | Server `PROTOCOL_SCHEMA_VERSION` | Min client | Max client | Status | EOL date | | -------------------------------- | ---------- | ---------- | ------------------------ | -------- | | *`1.0.x`* | *`1.0.0`* | *`1.0.x`* | *current (illustrative)* | — | ### Column meanings [Section titled “Column meanings”](#column-meanings) * **Server version** — the `PROTOCOL_SCHEMA_VERSION` the server emits in the subscribe-ack payload’s `serverVersion`. * **Min client / Max client** — the lowest / highest entries in the client’s `CLIENT_SUPPORTED_VERSIONS` set guaranteed to subscribe successfully. * **Status** — one of: * `current` — actively maintained; all fixes land here. * `security-only` — no new features; only security patches. * `EOL` — no longer maintained. Servers on EOL versions MAY refuse to start. * **EOL date** — the date `current` transitions to `security-only`, or `security-only` transitions to EOL. ### Matrix update cadence [Section titled “Matrix update cadence”](#matrix-update-cadence) * New **minor** ship → append a row; prior row may update Max client. * New **major** ship → append a new row; prior-major row transitions to `security-only` for at least 6 months before EOL. * Security-only → EOL → at least 6 additional months. ### Out-of-matrix clients [Section titled “Out-of-matrix clients”](#out-of-matrix-clients) If a client targets a version outside the matrix, the server emits `UPGRADE_REQUIRED`. Whether the connection stays open depends on the server’s `versionPolicy` at the time. *** ## 5. Migration-guide requirement [Section titled “5. Migration-guide requirement”](#5-migration-guide-requirement) Every major bump MUST ship a migration doc at `docs/protocol/migrations/v-to-v.md`. (Current pre-v1 drafts use date-named migration docs — e.g. `2026-06-05-gguisession-reintroduction.md`; the `v-to-v.md` pattern applies from v1.0.) The CI check (§7) enforces the file’s existence; content follows a standard template with required sections: * **What changed** — 1–2 paragraph summary. * **Why** — motivation (conformance-kit failure mode that drove the change). * **Breaking-change summary** — bullet list of renamed / removed / tightened surfaces. * **Migration steps per consumer kind** — fixture authors, ConformanceHost implementers, agent builders, SDK consumers. * **Timeline** — dates for v(N) deprecation ship, v(N+1) soft cut, v(N+2) removal. * **Rollback procedure** — how to pin to prior version if a consumer can’t migrate fast enough. *** ## 6. Release cadence expectations [Section titled “6. Release cadence expectations”](#6-release-cadence-expectations) These are targets, not promises: * **Minor (N.x → N.(x+1)):** roughly monthly. Additive adjustments driven by conformance-kit fixture gaps, new observability events, or new canonical error codes tend to accumulate on this cadence. Empty minor cycles are skipped rather than force-shipped. * **Major (N → N+1):** annual or slower. Rare and pre-announced. A major ship is a disruption event for every downstream — the protocol leans hard on minor + deprecation windows to defer majors. * **Patch (N.x.y → N.x.(y+1)):** ad hoc. Doc corrections, fixture additions that tighten existing assertions, and first-party impl bug fixes ship when ready. Announcements ship in the version history maintained in [`@ggui-ai/protocol`’s `version.ts`](https://github.com/ggui-ai/ggui/blob/main/packages/protocol/src/version.ts) and in the public protocol release notes. *** ## 7. CI enforcement [Section titled “7. CI enforcement”](#7-ci-enforcement) Two workflows guard this policy: * **Spec drift** — ensures spec envelope code blocks match the `@ggui-ai/protocol` types. Catches structural drift that would otherwise ship as silent breakage. * **Version migration** — reads `PROTOCOL_SCHEMA_VERSION` on the PR head and on the base ref; if the **major** component changed, asserts the migration doc exists in the PR diff. The second check is the policy’s teeth: you cannot ship a major bump without the migration doc the policy requires. *** ## Appendix: Worked examples [Section titled “Appendix: Worked examples”](#appendix-worked-examples) ### A.1 Adding a new live-channel error code [Section titled “A.1 Adding a new live-channel error code”](#a1-adding-a-new-live-channel-error-code) **Scenario:** a new failure mode — `TOOL_DENIED` — needs to land alongside the existing canonical literals on the WS `error` / `channel_error` frame. * **Bump kind:** minor. Prior-version consumers that don’t know `TOOL_DENIED` see an extensibly-closed (`code: string`) value and MUST degrade gracefully. No kit fixture asserting the prior closed set should fail. * **Required work:** add the constant to `@ggui-ai/protocol`, document it as a canonical live-channel error-code literal, add a conformance-kit fixture asserting the new code round-trips. * **Migration doc:** none needed (not a major bump). ### A.2 Removing a canonical error-code literal [Section titled “A.2 Removing a canonical error-code literal”](#a2-removing-a-canonical-error-code-literal) **Scenario:** `SCHEMA_MISMATCH_ERROR` is merged into `CONTRACT_VIOLATION` with a structured `causedBy`. * **Bump kind:** major. A consumer that pattern-matches on `SCHEMA_MISMATCH_ERROR` now never sees it, fails its fixture. * **Required work:** first ship `@deprecated SCHEMA_MISMATCH_ERROR` in v(N), continue emitting both `SCHEMA_MISMATCH_ERROR` and the new shape during v(N+1), then remove `SCHEMA_MISMATCH_ERROR` emission in v(N+2). * **Migration doc:** `vN-to-v(N+1).md` (enforced by CI on the major-bump PR). Covers the `causedBy` shape, fixture changes, and consumer-side pattern-match migration. ### A.3 Renaming a reserved channel [Section titled “A.3 Renaming a reserved channel”](#a3-renaming-a-reserved-channel) **Scenario:** `_ggui:preview` → `_ggui:assembly` for parity with transport-layer conventions. * **Bump kind:** major. Every consumer that subscribes to the old name now fails. Every fixture that references the old name needs updating. * **Required work:** can NOT ship via deprecation (reserved-channel names are matched verbatim). Must bundle with other breaking changes into the next major. Migration doc is non-trivial — every producer AND consumer changes. * **Operational note:** changes of this shape are exactly why the protocol prefers extensibly-closed unions + additive fields + separate channels over in-place renames. ### A.4 Clarifying a spec MUST [Section titled “A.4 Clarifying a spec MUST”](#a4-clarifying-a-spec-must) **Scenario:** the spec’s `refresh` semantics paragraph has two readings; the kit’s fixture matched only one. * **Bump kind:** patch IF the kit’s existing assertion already covered the intended reading (prose clarifies code); minor IF the clarification surfaces a new required behavior that prior-version impls weren’t necessarily honoring (new assertion); major IF the clarification tightens behavior such that previously-conformant impls now fail. * **Test:** run the kit against the prior-version tag. If it passes, the clarification is patch/minor. If it fails, it was major all along — the original spec text was ambiguous and shipping the clarification is a breaking change. *** ## See also [Section titled “See also”](#see-also) * [Protocol overview](/protocol/overview/) — three-channel topology and reference implementation. * [Conformance kit](https://github.com/ggui-ai/ggui/tree/main/packages/protocol-conformance) — the test suite this policy treats as the arbiter. * [Conformance](/protocol/conformance/) — the 4-criteria contract bar + 6-criteria protocol bar this policy gates. # Gadgets SDK > Wrap any 3rd-party browser library (Leaflet, Mapbox, Stripe, …) into an LLM-callable React hook with `createGguiGadget` from `@ggui-ai/gadgets`. `@ggui-ai/gadgets` is the standard library of browser-capability hooks **and** the wrapper SDK that lets you bind any 3rd-party library into the same uniform contract the LLM already knows. * **STDLIB hooks** — `useGeolocation`, `useCamera`, `useClipboardWrite`, `useClipboardPaste`, `useNotifications`, `useFilePicker`, `useMicrophone`. * **Wrapper SDK** — `createGguiGadget` for Leaflet, Mapbox, Stripe, Chart.js, Three.js, or anything else with a browser API. See [Gadgets — deterministic islands](/concepts/gadgets/) for why the wrapper-only design exists, [Glossary](/glossary/) for the gadget / tool / blueprint vocabulary, and [Marketplace Registry](/hosted/marketplace/) for distribution. ## Installation [Section titled “Installation”](#installation) ```bash npm install @ggui-ai/gadgets ``` ## Authoring a wrapper [Section titled “Authoring a wrapper”](#authoring-a-wrapper) ```ts import { createGguiGadget } from "@ggui-ai/gadgets"; export const useLeafletMap = createGguiGadget< // TOutput — what the hook resolves with on `status: 'completed'`. { containerRef: (el: HTMLDivElement | null) => void }, // TOptions — what the calling component passes in. { center: [number, number]; zoom: number } >({ // Canonical hook name — the export name a contract references // under clientCapabilities.gadgets[][]. The // `use`-prefixed camelCase name marks this export as a hook. hook: "useLeafletMap", // REQUIRED teaching text. Synth + decision LLM both see this with // a 300-char per-entry budget; description is preserved, usage // truncates first when over budget. description: "Render an interactive Leaflet map with tile layer and pan/zoom controls. Returns a container ref to attach to a
.", usage: "Mount when the intent names a rendered map (location browsing, route preview, points-of-interest grid). Pass `center: [lat, lng]` + `zoom: 2..20`.", // REQUIRED example. JsonValue — concrete shape the LLM uses to // pattern-match on cold gen. example: { call: "const map = useLeafletMap({ center: [37.7749, -122.4194], zoom: 12 });", returns: { status: "completed", value: { containerRef: "" }, }, }, // Optional anti-patterns / library quirks. Surfaces in the // boilerplate generator's prompt; the LLM uses them to avoid known // misuse patterns. gotchas: "Leaflet requires the container
to have a non-zero height before the map mounts — apply `style={{ height: 400 }}` (or similar) directly. Default-marker icons require leaflet.css to be in the document; the styleUrl on this descriptor covers that.", // REQUIRED. `version` is part of the blueprint cache key, so a // wrapper bump automatically invalidates stale cached generations. version: "0.0.1", // `package` AND `version` are both REQUIRED — bare npm name, exact // semver pin (no URLs, no ranges). `bundleUrl` is optional; when // set it wins for boilerplate import emission. // // Resolution order (operator wins over author wins over spec // default): explicit `bundleUrl` → operator `bundleHost` override // → author `bundleHost` → spec default `registry.ggui.ai`. With // `bundleHost` + `package` + `version` the server assembles // `https:///bundles////bundle.js` // — prefer this over hardcoded `bundleUrl`. package: "@my-org/ggui-leaflet", bundleHost: "registry.ggui.ai", // Optional companion CSS bundle. The wrapper SHOULD self-inject // any required CSS in its hook; the styleUrl is purely an origin // declaration so the renderer's CSP allows the load. Same // `bundleHost`-based resolution applies — explicit `styleUrl` // overrides the host-derived `style.css` path. // API-call origins (XHR / fetch / WebSocket / ``). The // renderer's Content-Security-Policy unions these into BOTH // connect-src AND img-src so map tiles loaded via work. connect: ["https://tile.openstreetmap.org"], // Public env keys this wrapper consumes (see "Public env channel" // below). Both wire + registry zod schemas enforce the same // `GGUI_PUBLIC_APP_[A-Z0-9_]+` prefix as App.publicEnv. Leaflet // doesn't need a token; Mapbox does. // requires: ["GGUI_PUBLIC_APP_MAPBOX_TOKEN"], // The React hook. Wrappers bundle their underlying library at // build time (esbuild / tsup) and `import` it inside the hook. // The function MUST return the standard `{value, status, start, …}` // shape that satisfies `GadgetHook`. hookImpl: (props) => { // … wrap Leaflet's lifecycle into ggui's stable hook contract … return { value: { containerRef: () => undefined }, status: "completed", start: async () => undefined, }; }, }); ``` The factory **synchronously zod-validates** the spec at module load. Missing `description` / `usage` / `example`, or a missing `package` / `version`, throws `WrapperConformanceError` with the field path. Authors see the error at import time — not at runtime. `useLeafletMap` is a callable hook; the immutable wrapper descriptor is attached as `useLeafletMap.descriptor`. Operators register the descriptor on `App.gadgets`. For distribution, wrappers ship as a `ggui.gadget.json` manifest (see [Marketplace Registry](/hosted/marketplace/)). The registry’s publish endpoint computes the bundle’s `sha384` and stamps it on the registered entry’s `bundleSri`; `ggui gadget install` writes the descriptor (including `bundleSri` + resolved `bundleUrl`) into `ggui.json#app.gadgets[]`. Hand-authored entries omit `bundleSri` — the iframe runtime falls back to integrity-less dynamic `import()`. Non-stdlib registered descriptors also carry `typesUrl` (HTTPS URL to the wrapper’s `.d.ts`) and `typesSri` (SHA-384 SRI over those types), so the generator can type-check against the wrapper’s real surface. `typesUrl` is REQUIRED at registration time for any non-stdlib package; `typesSri` is stamped by the registry on publish (optional for hand-authored entries). ## Multi-export and component packages [Section titled “Multi-export and component packages”](#multi-export-and-component-packages) `createGguiGadget` is the single-hook convenience — it authors exactly one hook export. For a package that ships more than one export, or a **component** export (like the `LeafletMap` component referenced later on this page), author it with `defineGadgetPackage` instead — the general builder for hook and/or component gadget packages, also from `@ggui-ai/gadgets`: ```ts import { defineGadgetPackage } from "@ggui-ai/gadgets"; import type { ComponentType } from "react"; // Export each impl directly — the builder never wraps or re-types it. export const LeafletMap: ComponentType<{ center: [number, number]; zoom: number }> = (props) => { // … render the map … }; export const useLeafletMap = (options: { center: [number, number]; zoom: number }) => { // … the hook version, same lifecycle as the wrapper example above … }; export const leafletDescriptor = defineGadgetPackage({ package: "@my-org/ggui-leaflet", version: "0.0.1", bundleHost: "registry.ggui.ai", connect: ["https://tile.openstreetmap.org"], exports: [ { // PascalCase `component` key ⇒ a component export. component: "LeafletMap", impl: LeafletMap, description: "Render an interactive Leaflet map with tile layer and pan/zoom controls.", usage: "Mount when the intent names a rendered map (location browsing, route preview).", example: { call: "", returns: null }, }, { // `use`-prefixed `hook` key ⇒ a hook export, same shape createGguiGadget produces. hook: "useLeafletMap", impl: useLeafletMap, description: "Render an interactive Leaflet map. Returns a container ref to attach to a
.", usage: "Mount when the intent names a rendered map (location browsing, route preview).", example: { call: "const map = useLeafletMap({ center: [37.7749, -122.4194], zoom: 12 });", returns: { status: "completed", value: { containerRef: "" } }, }, }, ], }); ``` Both exports share one package identity and one set of transport metadata (`bundleHost`, `connect`), declared once. `defineGadgetPackage` synchronously zod-validates each export’s teaching text and name grammar the same way `createGguiGadget` does, throwing `WrapperConformanceError` at module load on a malformed spec. ## Operator registration [Section titled “Operator registration”](#operator-registration) Add the descriptor (or its JSON shape) to `ggui.json#app.gadgets`: A `GadgetDescriptor` is a PACKAGE — `package` + `version` + transport metadata declared once, plus an `exports[]` array carrying each export’s teaching text: ```json { "app": { "slug": "leaflet-demo", "name": "Leaflet gadget demo", "gadgets": [ { "package": "@my-org/ggui-leaflet", "version": "0.0.1", "bundleHost": "registry.ggui.ai", "connect": ["https://tile.openstreetmap.org"], "exports": [ { "hook": "useLeafletMap", "description": "Render an interactive Leaflet map…", "usage": "Mount when the intent names a rendered map…", "example": { "call": "const map = useLeafletMap({ center: [37.7749, -122.4194], zoom: 12 });", "returns": { "status": "completed", "value": { "containerRef": "" } } }, "gotchas": "Leaflet requires the container
…" } ] } ] } } ``` A package that ships more than one export (two hooks, or a hook plus a React `component`) adds further entries to the same `exports` array — the transport metadata is declared once and shared. The CLI threads `app.gadgets` into the in-process `AppMetadataStore` so the same singleton powers `ggui_list_gadgets`, handshake-time prompt injection, render-time validation + enrichment, and CSP derivation. ### From the console [Section titled “From the console”](#from-the-console) Editing `ggui.json` by hand isn’t the only install path for a hosted app. The [GGUI console](https://console.ggui.ai)’s per-app **Gadgets** tab (`/apps/[appId]/gadgets`) shows exactly what agents receive from `ggui_list_gadgets` — the same three-tier catalog, resolved with the same precedence the server uses at render time: stdlib floor < web-installed < `ggui.json`-declared. * **stdlib** rows are the seven always-on hooks — action-free. * **installed** rows were added through the console’s own search + install flow (not `ggui.json`). Each row carries a version menu — picking a version re-installs at that pin — and a two-step-confirm Remove that uninstalls it. * **declared** rows came from `ggui.json#app.gadgets`. The console never edits `ggui.json` for you; a declared package always wins over an installed one on an exact `package` collision, so a declared row is display-only here. Use the console tab for hosted apps where you’d rather browse + click-install a registry package than hand-edit JSON; use `ggui.json#app.gadgets` (above) when you’re checking gadget config into source control or self-hosting. ## Contract gadget refs vs `GadgetDescriptor` [Section titled “Contract gadget refs vs GadgetDescriptor”](#contract-gadget-refs-vs-gadgetdescriptor) Two distinct shapes — do not confuse them. One is the wire map a host agent authors on a contract; the other is the registry-side package descriptor an operator registers. Both are organized around a gadget **package** that ships one or more **exports**, where each export is either a hook (a `use`-prefixed camelCase name) or a component (a PascalCase name): * **Contract gadget refs** — `clientCapabilities.gadgets` on a `DataContract` is a **package-keyed two-level map** carrying IDENTITY ONLY. The outer key is the npm package name; the inner key is the export name; the inner value is a `GadgetExportUse` — `{ description?, usage? }`, usually just `{}` (optional intent-specific override prose). There is NO `hook` / `component` field on the wire — the export-name GRAMMAR is the discriminator: `useGeolocation` is a hook, `LeafletMap` is a component. There is NO `version`, NO `permission`, NO transport metadata, and NO `binding` key. The wire carries `(package, exportName)` and nothing else. * **`GadgetDescriptor`** — the full registry-side PACKAGE descriptor (what operators register on `App.gadgets`). Package-level identity (`package` + `version`) plus transport metadata (bundle URLs, `connect`, `typesUrl` / `typesSri`) declared once, plus an `exports: GadgetExport[]` array (≥1). Each `GadgetExport` is a field-presence-discriminated union — a hook export `{ hook, … }` or a component export `{ component, … }` — carrying that export’s teaching text + per-export `permission`. `version`, transport metadata, `permission`, and `requires` ALL resolve server-side from this descriptor at render time; the contract author never restates them. `createGguiGadget` authors a single-export package; multi-export packages add further `exports` entries. ## Agent reference shape [Section titled “Agent reference shape”](#agent-reference-shape) Once a package is registered on `App.gadgets`, contracts reference its exports through the package-keyed `clientCapabilities.gadgets` map — outer key = package name, inner key = export name: ```ts const contract = { // … propsSpec / actionSpec / contextSpec … clientCapabilities: { gadgets: { "@my-org/ggui-leaflet": { // PascalCase key ⇒ a component export. Empty value is the // common case; an optional `{ description?, usage? }` override // sharpens the teaching text for this specific intent. LeafletMap: {}, }, "@ggui-ai/gadgets": { // `use`-prefixed camelCase key ⇒ a hook export. useGeolocation: {}, }, }, }, }; ``` The wire is identity-only: render resolves each `(package, exportName)` pair against the registered `GadgetDescriptor` and enriches the persisted `ComponentGguiSession` with the canonical `version`, transport metadata, teaching text, and `permission`. To walk the map in code, call `listContractGadgets(contract)` — it flattens the package-keyed map into a `readonly GadgetUse[]`, each entry `{ package, name, description?, usage? }`. References to unregistered exports reject at render validation with `gadget_not_registered` and a did-you-mean hint when a close stdlib match exists (Levenshtein < 3 cutoff). Render also rejects with `gadget_package_mismatch` when a referenced export name belongs to a different registered package than the one keyed. ## What the renderer derives [Section titled “What the renderer derives”](#what-the-renderer-derives) When ANY gadget in `clientCapabilities.gadgets` declares `bundleUrl` / `styleUrl` / `connect[]`, the render’s spec-canonical `_meta.ui.csp` block carries the derived `{ connectDomains, resourceDomains }` (per the MCP Apps spec). The MCP-Apps host applies them to the sandboxed iframe as a Content-Security-Policy — conceptually: ```plaintext script-src 'self' 'unsafe-inline' ; style-src 'self' 'unsafe-inline' ; connect-src 'self' ; img-src 'self' data: ``` * `'unsafe-inline'` on `script-src` is needed because the render shell embeds the bootstrap as an inline `