# Routing

An Angular application with the router works as an MCP App. Three things are worth knowing: how the router keeps
its address inside the frame, how the model chooses the view the app opens on, and how the app tells the model
where the user went.

The application below has a list of trips and a page for each trip. It is built into one HTML file and runs in an
iframe; this page plays the chat host.

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

## Try this

- **Click a trip, then Back.** The line "Route" follows. Only the app changes: the address of this page stays the
  same.
- **Look at the dark column.** After each navigation the app sends `ui/update-model-context`, and the sentence it
  sent appears under the app as "Added to the model context".
- **Press "Show me my trips"** under the app. The app starts again, and this time the tool call has no `open`
  argument, so it opens on the list. "Show me the Lisbon trip" sends `{ "open": "trip/2" }` and the app opens
  there.

## 1. Use the hash for the address

A host shows the app in a frame of its own: the address of that frame is the host's, not a path on your site. So
the router must not write paths into it. With `withHashLocation()` the router keeps the route in the part after
`#`, which a page can always change in its own address. Links (`routerLink`) and Back then work inside the frame.

```ts
bootstrapApplication(App, {
  providers: [
    provideMcpApp({ name: 'trips', version: '1.0.0' }),
    provideRouter(routes, withHashLocation(), withComponentInputBinding()),
  ],
});
```

`withComponentInputBinding()` is not needed for MCP: it only passes `:id` to the trip component as an input.

Lazy routes work too. `loadComponent`, `loadChildren` and `@defer` make separate files, which one HTML file cannot
fetch, so the builder merges them back into the file: they are loaded with the app instead of on demand. This
example uses static routes because there is nothing to gain from lazy ones here. See [The builder](builder.md).

```ts
const routes: Routes = [
  { path: '', component: Trips },
  { path: 'trip/:id', component: Trip },
  { path: '**', redirectTo: '' },
];
```

## 2. Let the model open a view

The model opens the app by calling a tool, and the arguments of that call reach the app in `mcp.toolInput()`. Give
your tool an argument that names the view, and navigate when it arrives. The value is written by the model, so
check it before you use it: here only `trip/` followed by a number is accepted, anything else opens the list.

```ts
const isView = (v: unknown): v is string => typeof v === 'string' && /^trip\/\d{1,3}$/.test(v);

effect(() => {
  const input = this.mcp.toolInput();
  if (!input || this.opened()) return;
  const open = input['open'];
  void this.router.navigateByUrl(isView(open) ? `/${open}` : '/').then(() => this.opened.set(true));
});
```

`toolInput()` is `undefined` until the host sends the arguments, which happens a moment after the app has started.
The signal `opened` makes the effect navigate once, and lets the next step wait for it.

## 3. Tell the model where the user is

The model does not see the screen. After each navigation the app sends one sentence with
`mcp.updateModelContext(...)`: the host keeps the latest one and the model reads it on its next turn, so "tell me
more about this one" has an answer. It is silent: nothing appears in the conversation.

```ts
private readonly place = computed(() => {
  const id = /^\/trip\/(\d+)$/.exec(this.url())?.[1];
  const trip = TRIPS.find((t) => t.id === id);
  return trip ? `the trip to ${trip.city} (route ${this.url()})` : 'the list of trips (route /)';
});

effect(() => {
  const place = this.place();
  if (!this.opened() || !this.mcp.connected()) return;
  this.mcp.updateModelContext(`The user is looking at ${place}.`).catch(() => {
    /* a host may refuse: the app works the same */
  });
});
```

`url` is a signal set from the router's `NavigationEnd` event. `updateModelContext` rejects when the app is not
connected to a host or the host refuses, which is why the call is guarded and the error is caught.

## Limits

- Lazy routes are merged into the file: they work, but they are loaded with the app, as said above.
- The Back button of this example counts the navigations made inside the app and is disabled at the first one. A
  step further back would leave the app, and what the host does then is up to the host.
- The example was tried in the host of this page. Try your own app in the hosts you care about.

## The whole file

`main.ts`

```ts
/**
 * An MCP App with the Angular router
 *
 * A list of trips and a page for each trip. The router uses the part of the address after `#`, the model
 * chooses the first view with the arguments of the tool call, and the app tells the model where the user
 * is after every navigation.
 */
import { Location } from '@angular/common';
import {
  Component,
  ViewEncapsulation,
  computed,
  effect,
  inject,
  input,
  signal,
} from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import {
  NavigationEnd,
  NavigationStart,
  Router,
  RouterLink,
  RouterOutlet,
  Routes,
  provideRouter,
  withComponentInputBinding,
  withHashLocation,
} from '@angular/router';
import { McpApp, provideMcpApp } from 'ngx-mcp-apps';

const TRIPS = [
  { id: '1', city: 'Porto', days: 3, plan: 'Train from Lisbon, two nights near the river.' },
  { id: '2', city: 'Lisbon', days: 2, plan: 'A weekend on foot: Alfama, then the coast.' },
  { id: '3', city: 'Madeira', days: 5, plan: 'Flight on Monday, walking boots needed.' },
];

@Component({
  selector: 'app-trips',
  imports: [RouterLink],
  template: `
    <h1>Your trips</h1>
    <ul>
      @for (trip of trips; track trip.id) {
        <li>
          <a [routerLink]="['/trip', trip.id]">{{ trip.city }}</a>
          <span class="quiet">{{ trip.days }} days</span>
        </li>
      }
    </ul>
  `,
})
class Trips {
  protected readonly trips = TRIPS;
}

@Component({
  selector: 'app-trip',
  imports: [RouterLink],
  template: `
    @if (trip(); as trip) {
      <h1>{{ trip.city }}</h1>
      <p>{{ trip.days }} days. {{ trip.plan }}</p>
    } @else {
      <h1>No such trip</h1>
    }
    <p><a routerLink="/">All trips</a></p>
  `,
})
class Trip {
  /** The `:id` of the route, bound as an input by `withComponentInputBinding()`. */
  readonly id = input('');
  protected readonly trip = computed(() => TRIPS.find((trip) => trip.id === this.id()));
}

const routes: Routes = [
  { path: '', component: Trips },
  { path: 'trip/:id', component: Trip },
  { path: '**', redirectTo: '' },
];

/** The views the model may open. The argument comes from the model: it is checked, not trusted. */
const isView = (v: unknown): v is string => typeof v === 'string' && /^trip\/\d{1,3}$/.test(v);

@Component({
  selector: 'app-root',
  imports: [RouterOutlet],
  template: `
    <nav>
      <button type="button" [disabled]="depth() === 0" (click)="location.back()">Back</button>
      <span class="quiet"
        >Route: <code>{{ url() }}</code></span
      >
    </nav>
    <router-outlet />
  `,
  // One stylesheet for the three components of this file
  encapsulation: ViewEncapsulation.None,
  styles: `
    app-root {
      display: grid;
      gap: 0.6rem;
      padding: 1rem;
      font:
        15px/1.5 system-ui,
        sans-serif;
      /* No background: the host draws it */
      color: light-dark(#16203a, #e6eaf5);
    }
    app-root nav {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      gap: 0.75rem;
    }
    app-root button {
      font: inherit;
      color: inherit;
      cursor: pointer;
      padding: 0.25em 0.8em;
      border-radius: 6px;
      background: transparent;
      border: 1px solid color-mix(in srgb, currentColor 30%, transparent);
    }
    app-root button:disabled {
      opacity: 0.45;
      cursor: default;
    }
    app-root h1 {
      margin: 0 0 0.4rem;
      font-size: 1.25rem;
    }
    app-root p,
    app-root ul {
      margin: 0 0 0.4rem;
    }
    app-root ul {
      padding: 0;
      list-style: none;
    }
    app-root li {
      display: flex;
      gap: 0.75rem;
      align-items: baseline;
      padding: 0.2rem 0;
    }
    app-root a {
      color: inherit;
    }
    app-root .quiet {
      font-size: 0.88em;
      opacity: 0.8;
    }
  `,
})
class App {
  private readonly mcp = inject(McpApp);
  private readonly router = inject(Router);
  protected readonly location = inject(Location);

  /** The current route, and how many steps Back can undo inside this app. */
  protected readonly url = signal('/');
  protected readonly depth = signal(0);
  /** True once the view asked by the model is on screen. */
  private readonly opened = signal(false);

  /** Where the user is, in words for the model. */
  private readonly place = computed(() => {
    const id = /^\/trip\/(\d+)$/.exec(this.url())?.[1];
    const trip = TRIPS.find((t) => t.id === id);
    return trip ? `the trip to ${trip.city} (route ${this.url()})` : 'the list of trips (route /)';
  });

  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'));

    let back = false;
    this.router.events.subscribe((event) => {
      if (event instanceof NavigationStart) back = event.navigationTrigger === 'popstate';
      if (!(event instanceof NavigationEnd)) return;
      this.url.set(event.urlAfterRedirects);
      // The first navigation is the start of the app, not a step to undo
      if (event.id > 1) this.depth.update((depth) => Math.max(0, depth + (back ? -1 : 1)));
    });

    // 2. The model opens a view: the arguments of the tool call choose the first route
    effect(() => {
      const input = this.mcp.toolInput();
      if (!input || this.opened()) return;
      const open = input['open'];
      void this.router
        .navigateByUrl(isView(open) ? `/${open}` : '/')
        .then(() => this.opened.set(true));
    });

    // 3. The app tells the model where the user is, after every navigation
    effect(() => {
      const place = this.place();
      if (!this.opened() || !this.mcp.connected()) return;
      this.mcp.updateModelContext(`The user is looking at ${place}.`).catch(() => {
        /* a host may refuse: the app works the same */
      });
    });
  }
}

bootstrapApplication(App, {
  providers: [
    provideMcpApp({ name: 'trips', version: '1.0.0' }),
    // 1. Hash routing: the address of the frame belongs to the host
    provideRouter(routes, withHashLocation(), withComponentInputBinding()),
  ],
}).catch((e) => console.error(e));
```

