Skip to main content
Integrate the Char agent into your Svelte application using bind:this for element references.

Installation

Svelte 4

<script lang="ts">
  import { onMount } from 'svelte';
  import '@mcp-b/char/web-component';
  import type { WebMCPAgentElement } from '@mcp-b/char/web-component';

  export let idToken: string;
  export let clientId: string;
  let agentEl: WebMCPAgentElement;

  onMount(() => {
    agentEl?.connect({ idToken, clientId });
  });

  $: if (agentEl && idToken && clientId) {
    agentEl.connect({ idToken, clientId });
  }
</script>

<char-agent bind:this={agentEl} />

Svelte 5 (Runes)

<script lang="ts">
  import { onMount } from 'svelte';
  import '@mcp-b/char/web-component';
  import type { WebMCPAgentElement } from '@mcp-b/char/web-component';

  let { idToken, clientId }: { idToken: string; clientId: string } = $props();
  let agentEl: WebMCPAgentElement | undefined = $state();

  onMount(() => {
    agentEl?.connect({ idToken, clientId });
  });

  $effect(() => {
    if (agentEl && idToken && clientId) {
      agentEl.connect({ idToken, clientId });
    }
  });
</script>

<char-agent bind:this={agentEl} />

SvelteKit (SSR)

For SvelteKit with server-side rendering, use the ticket exchange pattern:
<!-- src/routes/dashboard/+page.svelte -->
<script lang="ts">
  import { onMount } from 'svelte';
  import type { PageData } from './$types';
  import type { WebMCPAgentElement } from '@mcp-b/char/web-component';

  export let data: PageData;
  let agentEl: WebMCPAgentElement;

  onMount(async () => {
    await import('@mcp-b/char/web-component');
    agentEl?.connect({ ticketAuth: data.ticketAuth });
  });
</script>

<char-agent bind:this={agentEl} />
// src/routes/dashboard/+page.server.ts
import type { PageServerLoad } from './$types';
import { redirect } from '@sveltejs/kit';

export const load: PageServerLoad = async ({ locals }) => {
  const session = await locals.getSession();
  if (!session?.idToken) {
    throw redirect(302, '/login');
  }

  const response = await fetch('https://api.usechar.ai/api/auth/ticket', {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${session.idToken}`,
    },
  });

  const ticketAuth = await response.json();
  return { ticketAuth };
};

TypeScript Support

Add types to your app.d.ts:
/// <reference types="@mcp-b/char/web-component" />

See Also