# Building Apps and App Blocks

> Build a block with your AI agent: one HTML file written with the MCP Apps SDK, its state, theme, size and integration data, previewed on your machine, then registered, opened in a chat and published.

Source: https://infa.ai/docs/building

Building blocks is available on all Infa plans (Free, Pro, and Enterprise). Integration data needs a board connection, a Pro and Enterprise feature.

Anyone can build an App Block: it is one HTML file plus a handful of MCP tool calls. The fastest way is to hand the work to an AI agent. Infa gives you a ready-to-paste prompt, and the MCP server exposes the whole lifecycle from register to publish. This page describes the same contract the server hands to agents, so you can also write a block by hand.

## Overview

We at Infa write every block as a standard **MCP App** (the open format AI chats use for interactive panels, built on the `@modelcontextprotocol/ext-apps` SDK). That is what lets one file run in three places without a change: on your board (in a document, on a canvas, or as an [App](https://infa.ai/docs/apps)), on your machine with the Infa CLI, and inside an AI chat that renders MCP Apps.

## Build with an AI Agent

Copy Infa's ready-made prompt, which includes connection steps, this contract and your board ID:

- On an App's picker, **Generate this App** copies a prompt that ends with the block set as that App's body. See [Apps](https://infa.ai/docs/apps).
- In the App Block picker (insert menu → **App Block** → **Community** tab), **Copy prompt for your agent** copies a prompt for a block you insert into a paper. The **On this board** tab has the same action in its footer.
- Or copy it from [infa.ai/profile?tab=blocks](https://infa.ai/profile?tab=blocks).

Paste the prompt into Claude Code, Cursor, or any MCP-enabled agent and describe what the block should do. With the [Infa plugin for Claude Code](https://infa.ai/docs/claude-plugin), the `/infa:apps` skill walks your agent through the same steps.

To set an agent up by hand instead:

1. Connect it to the Infa MCP server (HTTP transport, OAuth login on first call, no API key):

    ```bash title="Claude Code"
    claude mcp add --transport http Infa https://infa.ai/api/mcp
    ```

    Other MCP clients: add an HTTP server with the URL `https://infa.ai/api/mcp`. For stdio-only clients, use `npx -y mcp-remote https://infa.ai/api/mcp`. See [MCP Server](https://infa.ai/docs/mcp).

2. Have the agent call the `infa_appBlockGuide` tool. It returns the server's current version of the contract below. Fetch it before building or updating a block.

## Talk to the Host with the SDK

A block is one self-contained HTML document: inline CSS and JavaScript. The one import is the MCP Apps SDK, imported by its bare name. Infa adds the import map that resolves it to a copy Infa serves, so the file needs no network for it.

```html title="block.html"
<!doctype html>
<html>
<head>
<style>
    html, body { margin: 0; background: var(--color-background-primary, #fff); }
    body { font: 14px/1.5 var(--font-sans, system-ui, sans-serif); color: var(--color-text-primary, #161616); padding: 16px; }
</style>
</head>
<body>
<div id="root">Set a label in the block's settings.</div>
<script type="module">
import { App, applyDocumentTheme, applyHostStyleVariables } from "@modelcontextprotocol/ext-apps";

const app = new App({ name: "Label", version: "1.0.0" });
const root = document.getElementById("root");

function applyContext(ctx) {
    if (!ctx) return;
    if (ctx.theme) applyDocumentTheme(ctx.theme);
    if (ctx.styles?.variables) applyHostStyleVariables(ctx.styles.variables);
}
function render(props) {
    // textContent escapes untrusted data: settings come from people
    root.textContent = props.label ?? "Set a label in the block's settings.";
}

app.ontoolinput = ({ arguments: props }) => render(props || {});
app.onhostcontextchanged = applyContext;
await app.connect();
applyContext(app.getHostContext());
</script>
</body>
</html>
```

- **Settings (props)** arrive as the tool input, through `ontoolinput`. A change of settings reloads the block.
- **Host context** comes from `app.getHostContext()`, then `onhostcontextchanged` on every change: `theme` (light or dark), `styles.variables` (the host's colours, fonts and corner radii), `containerDimensions`, `locale` and `timeZone`.
- **Links** open with `app.openLink({ url })`, never with `<a target="_blank">`.

## Match the Host's Theme

A block runs in a sandbox: it cannot read Infa's styles, and `prefers-color-scheme` follows the operating system, not Infa's light or dark setting. Take every colour from the host instead:

- Apply `styles.variables` with `applyHostStyleVariables`, as above, and style with them: `var(--color-background-primary)` for the page, `var(--color-background-secondary)` for cards, `var(--color-text-primary)` and `var(--color-text-secondary)` for text, `var(--color-border-secondary)` for borders, `var(--color-text-info)` for accents, `var(--border-radius-lg)` for corners, `var(--font-sans)` for type.
- Give each variable a fallback, such as `var(--color-text-primary, #161616)`, for a host that sends none.
- Give `html` and `body` the page background and no border, so the block reads as part of the page.

## Fit the Frame

- **On an App page** the block is the page. It gets a **4:3** frame as wide as the page column (in Full view, as large as fits the screen), and `containerDimensions` has its width and height. Fill exactly that: `height: 100%` from `html` down and a grid that divides the height, with no page scrollbar. Let long lists scroll inside their own panel. Check it at 1024 × 768 and at 480 × 360.
- **In a document, on a canvas or in a chat** the frame follows the block's height. The SDK reports the height on its own.

## Save State

A block keeps state through two tools Infa answers for it:

```js title="state"
const read = await app.callServerTool({ name: "infa_getAppState", arguments: {} });
let count = read.structuredContent?.state?.count ?? 0;

await app.callServerTool({ name: "infa_setAppState", arguments: { key: "count", value: count + 1 } });
// or replace all of it: arguments: { state: { count: 0, done: [] } }
```

There is one state per block on the board, shared by everyone who sees it and saved with the block. In a chat it is saved in the App's paper. Where state cannot be saved (a guest on a published board, a reader who cannot edit), `infa_setAppState` answers with an error, so show the read-only state.

## Read Your Board

A block can read its own board's components, screens and flows as they are right now, so an App can show a component's anatomy, a screen's states or a flow's scenarios its own way, with real data:

```js title="board data"
// The board's components: id, title, description, default picture, page link
const list = await app.callServerTool({ name: "infa_listBoardData", arguments: { kind: "component" } });

// One component: its views (screenshot, anatomy, the screen each is used on) and its props
const read = await app.callServerTool({ name: "infa_readBoardData", arguments: { kind: "component", id: props.componentId } });
if (read.isError) showError(read.content?.[0]?.text);
else render(read.structuredContent.item);
```

| `kind` | `infa_readBoardData` returns |
| ------ | ---------------------------- |
| `component` | its `views` (title, `isDefault`, `screenshot`, `anatomy`: its parts with their boxes, `screenId`: where it is used) and its declared `props` |
| `screen` | its `views`: its states, each with its `screenshot` and `persona` |
| `flow` | its `scenarios` (kind, persona, `lastRun`, the `screenIds` they pass through) and its `screens` |

A block reads only its own board, as the person viewing it. A member sees what they see on the board; a guest on a published board sees what guests may, which leaves out flow scenarios. On your machine a block has no board, so these calls answer with an error.

To let people choose what the block reads, declare the setting with `"format": "infa-component-id"` (or `"infa-screen-id"`, `"infa-flow-id"`). **Configure** then shows a picker of the board's components, screens or flows.

## Keep the HTML a Template

We at Infa recommend putting no data in a block's HTML. Read everything when the block loads: board data, integration data (below), several requests at once with `Promise.all`. Offer a **Refresh** button that reads it all again, so the block always shows what is true now, and a change on the board or in GitHub shows up without anyone editing the block.

## Get Integration Data

A block cannot fetch a provider's API itself. Ask Infa, which calls the provider with the viewing person's session and the connection bound in the block's settings:

```js title="connection request"
const result = await app.callServerTool({
    name: "infa_connectorRequest",
    arguments: {
        connectorId: props.connectorId, // always from a setting, never hardcoded
        path: "/repos/owner/repo/pulls?state=open",
        // method: "POST", body: { ... } for providers that need it
    },
});
if (result.isError) showError(result.content?.[0]?.text);
else render(result.structuredContent.data);
```

Supported: GitHub, Figma and Slack (GET); Notion (GET and POST); Linear (POST `/graphql`). The connection must be on the block's own board.

Never hardcode a connection ID or a credential. Take the connection as a setting, and declare it in `inputSchema` with `"format": "infa-connector-id"`, so Infa shows a dropdown of the board's connections:

```json title="inputSchema excerpt"
{
    "type": "object",
    "properties": {
        "connectorId": {
            "type": "string",
            "title": "GitHub connection",
            "format": "infa-connector-id"
        }
    },
    "required": ["connectorId"]
}
```

Declare the providers you use in `contextHints.connections` (for example `["github"]`), so listings badge the block as needing a connection.

## Ask an Agent

A block can hand a request to an agent:

```js title="ask an agent"
if (app.getHostCapabilities()?.message) {
    await app.sendMessage({ role: "user", content: [{ type: "text", text: "Summarize the failing checks" }] });
}
app.ontoolresult = (result) => showAnswer(result.content?.[0]?.text);
```

On an App the board agent chosen under **Answered by** in **Configure** answers. The person confirms each message, a run is queued, and the agent's report comes back through `ontoolresult`. In a chat the message lands in the conversation. Offer the action only when `getHostCapabilities()?.message` says the host takes messages. To tell the agent what the block shows without sending a message, call `app.updateModelContext(...)`; it goes with the next message.

A block reaches only `infa_getAppState`, `infa_setAppState`, `infa_connectorRequest`, `infa_listBoardData` and `infa_readBoardData`. Any other tool is refused.

## Name What a Comment Is On

People can pin comments on an App, on its page and in a chat. A pin is most useful when it says what it is on, so give the block a tool of its own, `describe_point`. Infa calls it with the click in the block's CSS pixels (`x`, `y`) and in percent (`xPercent`, `yPercent`), and the `label` you return names the pin: "Checkout card" instead of "pin (40%, 22%)". There is no zod in the sandbox, so describe the arguments with a small schema of your own:

```js title="describe_point"
const pointArgs = { "~standard": { version: 1, vendor: "app",
    validate: (value) => ({ value }),
    jsonSchema: {
        input: () => ({ type: "object", properties: { x: { type: "number" }, y: { type: "number" } } }),
        output: () => ({ type: "object" }),
    } } };

app.registerTool("describe_point", { description: "What the App shows at a point", inputSchema: pointArgs }, ({ x, y }) => {
    const el = document.elementFromPoint(x, y)?.closest("[data-name]");
    if (!el) throw new Error("Nothing named here");
    return {
        content: [{ type: "text", text: el.dataset.name }],
        structuredContent: { label: el.dataset.name, detail: el.dataset.id },
    };
});
await app.connect();
```

Register it before `app.connect()`, so the host knows about it, and answer within a second and a half. Where there is nothing worth naming, throw: the pin is still placed, without a name. Infa also keeps the block's saved state with each comment, so the agent knows what the person was looking at.

## What a Block May Load

Infa runs every block under a security policy:

- ✓ Inline scripts and styles, and the SDK Infa serves
- ✓ Fonts and stylesheets from Google Fonts
- ✓ Images and media from any `https:` address, `data:` and `blob:`
- ✗ `fetch`, XHR or WebSocket requests to anywhere
- ✗ A script from a CDN, such as a charting library loaded with `<script src>`
- ✗ Nested frames, form submissions and `eval`

These are refused silently, so a block that loads a library from a CDN shows up blank. Paste the library inline or draw with SVG, and get data from settings, state or `infa_connectorRequest`.

## Build and Preview Locally

You can build and check a block on your machine before anything reaches a board, with no Infa account:

1. Save the block as a file whose name ends in `.app.html`, anywhere in your repository (for example `apps/release-checklist.app.html`).
2. Run the Infa CLI on it:

    ```bash
    npx infa preview apps/release-checklist.app.html
    ```

3. Your browser opens the local board at `infa.ai/local` with the App in the same 4:3 frame and theme a board App gets. Save the file and the page reloads it.

The local board lists every `.app.html` file of the repository beside your docs and components. A local App keeps its state for the open page only; it has no connections and no agent. A file larger than 5 MB is refused.

## Lifecycle (Infa MCP Tools)

| Step | Tool |
| ---- | ---- |
| Fetch the contract | `infa_appBlockGuide`: the server's current version of this page |
| Register | `infa_registerAppBlock` `{ boardId, name, description, icon, category, sourceHtml, inputSchema?, defaultProps?, contextHints? }`: returns a `blockTypeId` and installs the block on the board |
| Preview | `infa_appBlockPreview` `{ blockTypeId, props?, storage? }`: runs the block in a chat panel |
| Iterate | `infa_updateAppBlock` `{ blockTypeId, ...changedFields }`: updates in place; never register duplicates |
| Make it an App | `infa_createPaper` `{ type: "app", app: { appBlockTypeId, props?, state? } }`: a new App page with the block as its body, starting from `state` |
| Insert in a paper | `infa_insertAppBlock`: embeds the block in a document or canvas paper |
| Open in a chat | `infa_openApp` `{ paperId }` for an App, or `{ blockTypeId, props? }` for a block type. Open it by its App to see real data: a block type on its own has no board, so no board or integration data |
| Read comments | `infa_getAppFeedback` `{ paperId }`: the comments people pinned on the App, with where each sits, what the block said is there and its state at the time; reply with `infa_createCommentReply`, then resolve with `infa_resolveCommentThread` |
| List connections | `infa_listConnections` `{ boardId }`: the board's connections, bound to a block in its settings |
| Publish | `infa_publishAppBlock` `{ blockTypeId, visibility: "published" }`: shares the block with the community; `"board"` takes it back |

**Updates apply immediately** There is no version pinning yet: every existing install renders the new source the moment you update it, including installs on other people's boards if the block is published. Preview before updating a widely installed block.

## Quality Bar

Before publishing to the community, check that your block clears the same bar as Infa's own blocks:

- **Escape all data you put into HTML** (use `textContent` or an `esc()` helper). Settings, state and API responses are untrusted.
- **Follow the host's theme**: every colour from a host variable, updated on every context change. Do not rely on `prefers-color-scheme`.
- **Fill the 4:3 frame on an App page** with no page scrollbar.
- **Handle the empty state** (no settings yet) with a short placeholder that says what to configure.
- **Validate settings**, and list required ones in `inputSchema.required`.
- **Never embed credentials, tokens, or personal data** in the source. Published blocks are public.

## Blocks Written Before the SDK

Older blocks talk to the host with Infa's own `infa:*` messages instead of the SDK, and every Infa surface still answers them. `infa_registerAppBlock` warns when a block uses them. Write new blocks with the SDK; to keep an older one working:

**The infa:* messages**
A block receives (on `window`, as `message` events): `infa:props` (its settings, on load and on every edit), `infa:theme` (Infa's light or dark theme as CSS values), `infa:context` (where it is shown, and its frame) and `infa:storage` (its saved state).

It sends with `window.parent.postMessage(message, "*")`: `{ type: "infa:ready" }` once its listener is set (Infa then sends the theme, context, settings and state again, so a block that starts listening late misses nothing), `{ type: "infa:resize", height }` after each render (not on an App page), `{ type: "infa:storage-update", detail: { key, value } }` to save one key, and `{ type: "infa:connector-request", requestId, connectorId, request: { path, method?, body? } }` for integration data, answered with `infa:connector-response`.

## Related Topics

- [Apps](https://infa.ai/docs/apps)
- [Apps and App Blocks overview](https://infa.ai/docs/app-blocks)
- [MCP Server](https://infa.ai/docs/mcp)
