# Build an MCP App

Add an interactive UI to your own MCP server or application and show it inside Pinter.

This guide is for developers of other applications and services who want their data to appear in Pinter as an interactive view instead of plain text. You do not need to change Pinter. You expose an MCP server, and Pinter renders the view.

## How it works

An MCP App is made of two pieces on your MCP server:

1. **A tool** that returns data, with metadata pointing at a view.
2. **A UI resource** at a `ui://` address that returns the view as an HTML document.

```
Agent ──calls──▶ tool sales_chart ──returns──▶ data
                     │
                     └─ _meta.ui.resourceUri = "ui://sales/dashboard"
Pinter ──reads──▶ resource ui://sales/dashboard ──▶ HTML
Pinter ──renders HTML in a sandboxed frame, sends it the tool input and result──▶ your view
your view ──tools/call──▶ Pinter ──▶ your server
```

A host that does not support MCP Apps ignores the metadata and shows the tool's normal result, so the same server also works elsewhere.

> **Info:** MCP Apps is an open extension, specified as [SEP-1865](https://github.com/modelcontextprotocol/ext-apps) (stable 2026-01-26). Pinter implements the core of it. The [support matrix](#what-pinter-supports) lists what is and is not covered.

## Requirements

- An MCP server reachable over `streamable_http` or `sse`. `stdio` cannot provide apps.
- A tool with `_meta.ui.resourceUri`, and a matching resource that returns `text/html;profile=mcp-app`.
- A view that is a single HTML document of at most **1 MiB**, with scripts and styles inline.

## Quick start with Python

This example uses the official `mcp` Python package (`FastMCP`). A complete, runnable version with a richer dashboard lives in `pinter-mcp-app-demo/server.py`.

```bash
pip install "mcp>=1.29"
```

```python server.py
from typing import Any

from mcp.server.fastmcp import FastMCP

RESOURCE_URI = "ui://sales/dashboard"
MIME = "text/html;profile=mcp-app"

mcp = FastMCP("sales-app", host="0.0.0.0", port=8765, stateless_http=True)

HTML = open("dashboard.html", encoding="utf-8").read()

@mcp.resource(RESOURCE_URI, name="sales_dashboard", mime_type=MIME)
def view() -> str:
    return HTML

@mcp.tool(
    title="Sales dashboard",
    description="Show sales per region as an interactive dashboard.",
    meta={"ui": {"resourceUri": RESOURCE_URI}},
    structured_output=True,
)
def sales_chart() -> dict[str, Any]:
    return {
        "title": "Sales per region (tons)",
        "items": [
            {"label": "Java", "value": 431},
            {"label": "Sumatra", "value": 260},
            {"label": "Kalimantan", "value": 180},
        ],
    }

if __name__ == "__main__":
    mcp.run(transport="streamable-http")
```

The server listens on `http://<host>:8765/mcp`.

> **Tip:** Return the data as `structuredContent` (`structured_output=True` above). The view reads it directly, and the agent still receives a text rendering to answer from.

## Write the view

The view is plain HTML that talks to Pinter with JSON-RPC 2.0 over `postMessage`. You do not need an SDK. This is a complete `dashboard.html`:

```html dashboard.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
  body { font: 14px system-ui; margin: 16px; }
  .row { display: flex; align-items: center; margin: 6px 0; }
  .label { width: 90px; }
  .bar { height: 16px; background: #4f46e5; border-radius: 3px; }
  .value { margin-left: 8px; }
</style>
</head>
<body>
  <h3 id="title">Loading…</h3>
  <div id="chart"></div>
  <button id="refresh">Refresh</button>
<script>
  let nextId = 1;
  const pending = {};

  function request(method, params) {
    return new Promise((resolve, reject) => {
      const id = nextId++;
      pending[id] = { resolve, reject };
      parent.postMessage({ jsonrpc: "2.0", id, method, params }, "*");
    });
  }
  function notify(method, params) {
    parent.postMessage({ jsonrpc: "2.0", method, params }, "*");
  }

  function render(data) {
    if (!data || !data.items) return;
    document.getElementById("title").textContent = data.title;
    const max = Math.max(...data.items.map((i) => i.value));
    document.getElementById("chart").innerHTML = data.items
      .map((i) => `<div class="row"><span class="label">${i.label}</span>` +
        `<div class="bar" style="width:${(i.value / max) * 200}px"></div>` +
        `<span class="value">${i.value}</span></div>`)
      .join("");
  }

  window.addEventListener("message", (event) => {
    const msg = event.data;
    if (!msg || msg.jsonrpc !== "2.0") return;

    if (msg.id !== undefined && pending[msg.id] && !msg.method) {
      const { resolve, reject } = pending[msg.id];
      delete pending[msg.id];
      msg.error ? reject(new Error(msg.error.message)) : resolve(msg.result);
      return;
    }
    if (msg.method === "ui/notifications/tool-result") {
      render(msg.params.structuredContent);
    }
  });

  document.getElementById("refresh").onclick = async () => {
    const result = await request("tools/call", { name: "sales_chart", arguments: {} });
    render(result.structuredContent);
  };

  new ResizeObserver(() =>
    notify("ui/notifications/size-changed", {
      height: document.documentElement.scrollHeight,
    })
  ).observe(document.body);

  request("ui/initialize", {
    protocolVersion: "2026-01-26",
    appInfo: { name: "sales-dashboard", version: "1.0.0" },
    appCapabilities: {},
  }).then(() => notify("ui/notifications/initialized", {}));
</script>
</body>
</html>
```

Three rules this example follows:

1. **Send `ui/initialize` first, then `ui/notifications/initialized`.** Pinter does not send the tool input or result until it receives the notification.
2. **Wait for `ui/notifications/tool-result`** before drawing. The view loads before the data is available.
3. **Report your height** with `ui/notifications/size-changed` so the frame fits the content.

## How the host talks to your app

### Pinter to your app

| Message | When | Payload |
| --- | --- | --- |
| Response to `ui/initialize` | Once, at start | `protocolVersion`, `hostInfo`, `hostCapabilities`, and `hostContext` (`theme`: `light` or `dark`, `displayMode`: `inline`). |
| `ui/notifications/tool-input` | After `initialized`, if the call had arguments | `{ arguments }` |
| `ui/notifications/tool-result` | After `initialized`, when the tool has a result | `{ content, structuredContent }` |

### Your app to Pinter

| Message | Type | Behavior |
| --- | --- | --- |
| `ui/initialize` | Request | Returns the host context above. |
| `ui/notifications/initialized` | Notification | Starts delivery of input and result. |
| `ui/notifications/size-changed` | Notification | Sets the frame height, capped at 800 px inline. In the side panel the frame fills the panel. |
| `tools/call` | Request | Runs a tool on **your** server through Pinter. Returns the tool result, or a JSON-RPC error. |
| Anything else | Request | Answered with an error (`-32000`, "Unsupported method"). |

### Theming

Read `hostContext.theme` from the `ui/initialize` response and switch your colors, for example with a `data-theme` attribute and CSS variables. Pinter does not push later theme changes.

## What Pinter supports

| Capability | Supported |
| --- | --- |
| `_meta.ui.resourceUri` on a tool (nested and flat `ui/resourceUri` forms) | Yes |
| `ui://` resources with `text` or `blob` HTML | Yes |
| `ui/initialize`, `initialized`, `size-changed`, `tool-input`, `tool-result` | Yes |
| `tools/call` from the view | Yes, with access and allowlist checks |
| Side panel | Yes (desktop) |
| `resources/read` from the view | No |
| `_meta.ui.csp`, `_meta.ui.permissions`, `_meta.ui.prefersBorder`, `_meta.ui.domain` | Read but not applied |
| Tool `visibility` (`model` / `app`) | Not enforced |
| `ui/message`, `ui/open-link`, `ui/request-display-mode`, `ui/update-model-context` | No |
| `tool-input-partial`, `tool-cancelled`, `host-context-changed`, `resource-teardown` | No |

Design for the supported set and degrade gracefully for the rest.

## Sandbox and security

Pinter renders your HTML in an iframe with `sandbox="allow-scripts"` and no `allow-same-origin`. In practice:

- Your view runs on an opaque origin. It has no cookies, `localStorage`, or access to the Pinter page.
- Ship everything inline. Do not depend on a CDN, and do not assume the view can call your API directly. Route data through tools.
- Every `tools/call` goes through Pinter, which checks that the signed-in user may access the server and that the tool passes the server's tool filter.
- Never put secrets in the HTML. Keep credentials on the server and authenticate the Pinter connection with headers (see below).
- Escape any text you insert with `innerHTML`. Tool results can contain user data.

## Add an app to an existing application

You do not need to rewrite your application. Pick the pattern that fits.

  
### New MCP server beside your service

    Create a small MCP server that calls your existing API. The tool fetches the data, and the resource serves the view. This is the least invasive route and keeps your app unchanged.

    Use a service token in an environment variable, and have the server verify the bearer token that Pinter sends.
  
  
### Add to an existing MCP server

    If you already expose an MCP server, add a resource and one line of `_meta` to the tools that should render a view. Existing clients keep working.
  
  
### Reuse your existing frontend

    Bundle your page into a single HTML file (for example with `vite-plugin-singlefile`) and return it from the resource. Replace direct API calls with `tools/call` through the host. Keep the bundle under 1 MiB.
  

## TypeScript example

The same app with the official TypeScript SDK. Treat this as a starting point and check the SDK version you install.

```typescript server.ts

const RESOURCE_URI = "ui://sales/dashboard";
const MIME = "text/html;profile=mcp-app";
const html = readFileSync("dashboard.html", "utf8");

function buildServer() {
  const server = new McpServer({ name: "sales-app", version: "1.0.0" });

  server.registerResource(
    "sales_dashboard",
    RESOURCE_URI,
    { mimeType: MIME },
    async (uri) => ({
      contents: [{ uri: uri.href, mimeType: MIME, text: html }],
    }),
  );

  server.registerTool(
    "sales_chart",
    {
      title: "Sales dashboard",
      description: "Show sales per region as an interactive dashboard.",
      inputSchema: {},
      _meta: { ui: { resourceUri: RESOURCE_URI } },
    },
    async () => {
      const data = {
        title: "Sales per region (tons)",
        items: [{ label: "Java", value: 431 }],
      };
      return {
        content: [{ type: "text", text: JSON.stringify(data) }],
        structuredContent: data,
      };
    },
  );
  return server;
}

const app = express();
app.use(express.json());
app.post("/mcp", async (req, res) => {
  const server = buildServer();
  const transport = new StreamableHTTPServerTransport({
    sessionIdGenerator: undefined,
  });
  await server.connect(transport);
  await transport.handleRequest(req, res, req.body);
});
app.listen(8765);
```

The official [`@modelcontextprotocol/ext-apps`](https://github.com/modelcontextprotocol/ext-apps) package provides helpers for both the server and the view. It follows the same specification, so views built with it use the same messages listed above.

## Connect it to Pinter

  
**Make the server reachable**

    Pinter's backend must be able to open a connection to your URL. A `localhost` server works for a local Pinter. For a deployed Pinter, host the server somewhere the backend can reach.
  
  
**Register it**

    Open **MCP servers** (`/mcp-servers`), choose **Add**, and enter the URL. Use **Test** to confirm that Pinter connects and lists your tools.

    Or call the API:

    ```bash
    curl -X POST "$PINTER_API/api/integrations/mcp-servers/" \
      -H "Authorization: Bearer $TOKEN" \
      -H "API-Version: 1" \
      -H "Content-Type: application/json" \
      -d '{
        "name": "Sales app",
        "description": "Sales dashboard",
        "transport": "streamable_http",
        "connection_config": {
          "url": "https://sales.example.com/mcp",
          "headers": { "X-API-Key": "..." }
        },
        "timeout": 30
      }'
    ```

    Do not send an empty `Authorization` header. Strict servers reject it before they check other credentials.
  
  
**Add it to an agent**

    In the agent builder, add the MCP server as a tool. If you use a tool allowlist, allow the app's tool and any tool the view calls.
  
  
**Try it in chat**

    Ask for what the tool provides. The app appears under the tool step. Use the expand icon to open it beside the chat.
  

## Test before you connect

Check the server with plain HTTP first.

```bash
H='-H content-type:application/json -H accept:application/json,text/event-stream'

# The tool must carry _meta.ui.resourceUri
curl -s -X POST http://localhost:8765/mcp $H \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'

# The resource must return text/html;profile=mcp-app
curl -s -X POST http://localhost:8765/mcp $H \
  -d '{"jsonrpc":"2.0","id":1,"method":"resources/read","params":{"uri":"ui://sales/dashboard"}}'
```

You can also use the MCP Inspector:

```bash
npx @modelcontextprotocol/inspector --cli http://localhost:8765/mcp \
  --transport http --method tools/list
```

### Checklist

- `tools/list` shows `_meta.ui.resourceUri` on the tool.
- `resources/read` returns the same URI, MIME type `text/html;profile=mcp-app`, and the HTML in `text` or `blob`.
- The HTML is under 1 MiB and does not load external scripts.
- The view sends `ui/initialize` and then `ui/notifications/initialized`.
- The view draws from `ui/notifications/tool-result` and handles an empty or missing result.
- Every tool the view calls is allowed by the server's tool filter.

## Troubleshooting

| Symptom | Cause and fix |
| --- | --- |
| Tool works but no app appears | `_meta.ui.resourceUri` is missing or does not start with `ui://`. Check `tools/list`. |
| "Failed to load the MCP App" | `resources/read` failed, the URI does not match exactly, the HTML is over 1 MiB, or you cannot access the server. |
| App shows but stays on "Loading" | The view never sent `ui/notifications/initialized`, or it ignores `tool-result`. |
| Button calls fail | The tool is blocked by the server's tool filter, or the server is inactive. |
| `421` or host errors from a deployed server | Your MCP framework rejects the `Host` header. Allow the public hostname in its transport security settings. |
| Chart is blank in dark mode | The view ignores `hostContext.theme`. |
| Works locally, fails after deploy | The Pinter backend cannot reach your URL. |

## Related pages

  - [MCP Apps in Pinter](/concepts/mcp-apps): What users see and how the side panel works.
  - [Tools and MCP servers](/concepts/tools-and-mcp): Register servers and assign them to agents.
