> ## Documentation Index
> Fetch the complete documentation index at: https://sunpeak.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# MCP App Lifecycle - Discovery to Teardown

> Understand the complete MCP App lifecycle: tool and resource discovery, ui/initialize handshake, tool input and result delivery, interactive phase with bidirectional communication, and graceful teardown.

An MCP App goes through five stages: discovery, initialization, data delivery, interactive phase, and teardown. The host orchestrates this lifecycle, and the [App class](/mcp-apps/app/app-class) handles most of it automatically via `connect()`.

## Sequence

```mermaid theme={null}
sequenceDiagram
    participant H as Host
    participant V as View (iframe)
    participant S as MCP Server

    Note over H,S: 1. Discovery
    S-->>H: tools/list (with UI metadata)

    Note over H,V: 2. Initialization
    H->>H: Render iframe with UI resource
    V->>H: ui/initialize
    H-->>V: host context, capabilities
    V->>H: ui/notifications/initialized

    Note over H,V: 3. Data Delivery
    H-->>V: ui/notifications/tool-input
    H-->>V: ui/notifications/tool-result

    Note over H,V: 4. Interactive Phase
    loop User Interaction
        V->>H: tools/call
        H->>S: tools/call
        S-->>H: result
        H-->>V: result
    end

    Note over H,V: 5. Teardown
    H->>V: ui/resource-teardown
    V-->>H: acknowledgment
```

This sequence builds on standard [MCP tool](/mcp-apps/mcp/tools) and [resource](/mcp-apps/mcp/resources) discovery.

## 1. Discovery

The Host learns about tools and their UI resources via the MCP [`tools/list`](/mcp-apps/mcp/tools#discovery-toolslist) call when connecting to the server. Tools with `_meta.ui.resourceUri` are identified as MCP App tools.

```ts theme={null}
registerAppTool(server, "weather", {
  description: "Get weather forecast",
  _meta: { ui: { resourceUri: "ui://weather/view.html" } },
}, handler);
```

The Host reads the tool's `_meta.ui.resourceUri` to determine which resource to fetch and render.

## 2. Initialization

When a UI tool is called, the Host renders the iframe. The View sends `ui/initialize` with its app info and capabilities. The Host responds with:

* **Protocol version** -- Negotiated protocol version
* **Host info** -- Host name and version
* **Host capabilities** -- What the host supports (tool proxying, messages, links, etc.)
* **Host context** -- Theme, locale, display mode, container dimensions, safe area insets

The View then sends `ui/notifications/initialized` to signal readiness.

<Info>
  The `App` class handles this handshake automatically in `connect()`. Register event handlers **before** calling `connect()` to avoid missing notifications.
</Info>

## 3. Data Delivery

The Host sends tool arguments and results to the View:

* **`ui/notifications/tool-input`** -- Complete tool arguments after the tool call begins
* **`ui/notifications/tool-input-partial`** -- Streaming partial arguments (healed JSON) for progressive rendering
* **`ui/notifications/tool-result`** -- Tool execution result from the server, including both `content` (text for model context) and `structuredContent` (data optimized for UI rendering)
* **`ui/notifications/tool-cancelled`** -- Notification that tool execution was cancelled

## 4. Interactive Phase

The user interacts with the View. The View can:

| Action                 | Method                                                                      |
| ---------------------- | --------------------------------------------------------------------------- |
| Call server tools      | [`callServerTool()`](/mcp-apps/app/requests/call-server-tool)               |
| Read server resources  | [`readServerResource()`](/mcp-apps/app/requests/read-server-resource)       |
| List server resources  | [`listServerResources()`](/mcp-apps/app/requests/list-server-resources)     |
| Send chat messages     | [`sendMessage()`](/mcp-apps/app/requests/send-message)                      |
| Update model context   | [`updateModelContext()`](/mcp-apps/app/requests/update-model-context)       |
| Request LLM completion | [`createSamplingMessage()`](/mcp-apps/app/requests/create-sampling-message) |
| Open external links    | [`openLink()`](/mcp-apps/app/requests/open-link)                            |
| Download files         | [`downloadFile()`](/mcp-apps/app/requests/download-file)                    |
| Change display mode    | [`requestDisplayMode()`](/mcp-apps/app/requests/request-display-mode)       |
| Send logs              | [`sendLog()`](/mcp-apps/app/requests/send-log)                              |

The Host proxies [tool calls](/mcp-apps/mcp/tools#invocation-toolscall) to the MCP server and forwards responses back to the View.

## 5. Teardown

Before unmounting the iframe, the Host sends `ui/resource-teardown`. The View can save state or release resources before returning an acknowledgment. See [Event Handlers](/mcp-apps/app/event-handlers#onteardown) for handling teardown.

```ts theme={null}
app.onteardown = async () => {
  await saveState();
  closeConnections();
  return {};
};
```

## Host Context Updates

At any point during the interactive phase, the Host may send `ui/notifications/host-context-changed` when the environment changes (theme toggle, resize, locale change). The `App` class automatically merges these updates into its internal context, which you can read via [`getHostContext()`](/mcp-apps/app/accessors/get-host-context).

Host context also drives layout. Use [Layout and Display](/mcp-apps/layout) when you need to handle `containerDimensions`, auto-resize, safe areas, or display mode changes.
