# Security

An MCP App runs inside a chat host, and the host is trusted: it decides what the app may do, and the app talks only
to it. The content is another matter. The data a tool returns comes from your server and, through it, from the
model, and a model can be led to write anything: a wrong shape, a very long text, a piece of HTML. An app is safe
when bad data cannot break it and cannot run.

The application below shows a contact card from a tool result. Under the card it prints the log of the library, so
you can see what arrived. The buttons make this page, which plays the host, send it different things.

(A live demo is shown here in the HTML page: https://umb0o.github.io/ngx-mcp-apps/security.html)

## Try this

- **A valid result.** The card changes. The log says `tool-result` with the data.
- **The wrong shape.** The message is a correct tool result, but the name is a number and the note is missing. The
  check of the app refuses it: the card keeps the last valid contact and a line says so.
- **HTML in the text.** The name is `<img src=x onerror=alert(1)>` and the note holds a `<script>` and a
  `javascript:` link. They pass the check, because they are strings, and they appear on the card as the characters
  they are. No image, no link, no dialog: nothing runs.
- **A broken message.** A tool result whose `content` is not a list. The library drops it before the app sees it,
  and the log says `invalid tool-result dropped`.
- **Not a protocol message.** An object that is not JSON-RPC 2.0. The library ignores it: nothing changes, not even
  the log.

## The check of the app

The library checks the messages of the protocol. It cannot know the shape of your own data, so that check is
yours: a function that says whether a value is what the template expects. Check every field the template reads,
and put a limit on what could be too long.

```ts
interface Contact {
  name: string;
  note: string;
}
const isContact = (v: unknown): v is Contact =>
  isObject(v) &&
  typeof v['name'] === 'string' &&
  v['name'].length <= 80 &&
  typeof v['note'] === 'string' &&
  v['note'].length <= 300;
```

`structuredContentAs(isContact)` gives the data when it passes and `undefined` when it does not. This example
keeps the last valid contact on screen with a linked signal (Angular 19 or later):

```ts
private readonly checked = this.mcp.structuredContentAs(isContact);
protected readonly contact = linkedSignal<Contact | undefined, Contact | undefined>({
  source: this.checked,
  computation: (next, previous) => next ?? previous?.value,
});
protected readonly refused = computed(() => !!this.mcp.toolResult() && !this.checked());
```

Any function of the form `(value: unknown) => value is T` works: written by hand as here, or made by a library
such as typia or valibot.

## Text stays text

The template uses Angular's `{{ }}`. Angular writes the value as text, so markup inside it is shown, not
interpreted.

```html
<article>
  <h1>{{ contact.name }}</h1>
  <p>{{ contact.note }}</p>
</article>
```

The way to lose this protection is to ask for it: `[innerHTML]`, `bypassSecurityTrustHtml`, or writing to the DOM
by hand. Do not use them with tool data. The same goes for addresses: do not put a string from a tool result into
`href` or `src` without checking that it starts with `https://`.

## The log

`provideMcpApp({ ..., log: true })` keeps the last 50 protocol events in the signal `mcp.events()`, each cut at
1000 characters. The example shows the newest four. The log repeats the data that arrived, so it is a tool for
debugging: leave it off in an app that real users open.

## The checklist

What the library does:

- accepts messages only from the parent window, and ignores anything that is not JSON-RPC 2.0;
- checks the shape of every notification and result before exposing it; invalid data is dropped or raised as `McpError`;
- never evaluates code and never writes host data into the DOM (no `eval`, no `innerHTML`; host styles are not applied);
- bounds what it keeps: 50 log entries, each cut at 1000 characters, and a minimum polling interval of 100 ms;
- has no runtime dependencies.

What is up to you:

- **The host is trusted, the content is not.** Tool results come from your server and, through it, from the model:
  render them with Angular bindings (`{{ }}`), not with `[innerHTML]`.
- **Do not put secrets in the HTML.** Whoever can read the resource from your MCP server can read the whole app.
- **Outgoing messages go to any parent origin by default**, because hosts wrap the app in a
  sandbox whose origin you usually do not know. If you do know it, set `allowedOrigins`.
- **Protect your MCP server.** An unauthenticated server lets anyone with the URL call its tools.
- `log: true` stores host and server data in memory to show it: use it while debugging.

## The server side

The app is one half. The other half is the MCP server that serves it and answers its tool calls, and an MCP server
without authentication is public: anyone who has its address can call its tools. The MCP specification defines
authorization based on OAuth 2.1 for servers reached over HTTP; use it, or another control you trust, before you
put real data behind a tool. More in [Things that go wrong](server.md#things-that-go-wrong).

## The whole file

`main.ts`

```ts
/**
 * An MCP App that checks its data
 *
 * A contact card. The data comes from a tool result, so it is checked by a guard before the template
 * uses it and it is rendered as text. Under the card, the log of the library shows what arrived.
 */
import { Component, computed, effect, inject, linkedSignal } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { McpApp, isObject, provideMcpApp } from 'ngx-mcp-apps';

interface Contact {
  name: string;
  note: string;
}
/** Every field the template reads, with its type and a limit on its length. */
const isContact = (v: unknown): v is Contact =>
  isObject(v) &&
  typeof v['name'] === 'string' &&
  v['name'].length <= 80 &&
  typeof v['note'] === 'string' &&
  v['note'].length <= 300;

@Component({
  selector: 'app-root',
  template: `
    @if (contact(); as contact) {
      <article>
        <h1>{{ contact.name }}</h1>
        <p>{{ contact.note }}</p>
      </article>
    } @else {
      <p aria-live="polite">Waiting for a contact</p>
    }
    @if (refused()) {
      <p class="warning" role="status">
        The last result did not pass the check of the app. The card shows the last valid one.
      </p>
    }

    <h2>Log of the library, newest first</h2>
    <ol>
      @for (line of log(); track $index) {
        <li>{{ line }}</li>
      } @empty {
        <li>Nothing yet</li>
      }
    </ol>
  `,
  styles: `
    :host {
      display: grid;
      gap: 0.7rem;
      padding: 1rem;
      font:
        15px/1.5 system-ui,
        sans-serif;
      /* No background: the host draws it */
      color: light-dark(#16203a, #e6eaf5);
      --line: color-mix(in srgb, currentColor 28%, transparent);
    }
    article {
      padding: 0.8rem 1rem;
      border: 1px solid var(--line);
      border-radius: 10px;
    }
    h1 {
      margin: 0 0 0.25rem;
      font-size: 1.2rem;
    }
    h2 {
      margin: 0.4rem 0 0;
      font-size: 0.88rem;
      font-weight: 600;
    }
    p,
    ol {
      margin: 0;
    }
    h1,
    p,
    li {
      overflow-wrap: anywhere;
    }
    .warning {
      padding: 0.45rem 0.75rem;
      border-left: 3px solid light-dark(#b80f4a, #ff86ab);
      font-size: 0.9em;
    }
    ol {
      padding: 0;
      list-style: none;
      min-height: 9.5em;
      font:
        12px/1.5 ui-monospace,
        Consolas,
        monospace;
      opacity: 0.85;
    }
    li {
      padding: 0.15rem 0;
      border-top: 1px solid var(--line);
    }
  `,
})
class App {
  private readonly mcp = inject(McpApp);

  /** The data of the tool result, or undefined when it does not pass the guard. */
  private readonly checked = this.mcp.structuredContentAs(isContact);
  /** What the card shows: the checked data, and the last valid one when a later result is refused. */
  protected readonly contact = linkedSignal<Contact | undefined, Contact | undefined>({
    source: this.checked,
    computation: (next, previous) => next ?? previous?.value,
  });
  /** A result arrived, but not with the shape this app expects. */
  protected readonly refused = computed(() => !!this.mcp.toolResult() && !this.checked());

  /** The last lines of the log, each cut short: the log repeats the data it received. */
  protected readonly log = computed(() =>
    this.mcp
      .events()
      .slice(0, 4)
      .map((line) => (line.length > 150 ? line.slice(0, 150) + '…' : line)),
  );

  constructor() {
    // The theme of the host on the page itself, so the frame stays transparent
    effect(() => (document.documentElement.style.colorScheme = this.mcp.theme() ?? 'light dark'));
  }
}

bootstrapApplication(App, {
  // log: true keeps the last protocol events in mcp.events(). It is for debugging: here it is the demo.
  providers: [provideMcpApp({ name: 'contact-card', version: '1.0.0', log: true })],
}).catch((e) => console.error(e));
```

