@mcp-b/char
v0.0.6
Published
Char - AI chat agent for React and web components. Drop-in widget with MCP tool support.
Readme
@mcp-b/char
An Intercom-like AI chat widget with MCP tool support and voice mode. Drop it into your app and you're done.
Styles are isolated using Shadow DOM. Customize appearance by setting CSS variables on the host page.
Build Architecture
This package provides the <char-agent> custom element in two formats:
| Export | Format | Use Case |
|--------|--------|----------|
| @mcp-b/char / @mcp-b/char/web-component | ESM web component | Bundlers, monorepo dev |
| @mcp-b/char/standalone | IIFE web component | <script> tag embeds |
Bundle Sizes
| Build | Size | Gzipped | Use Case | |-------|------|---------|----------| | ESM | ~560 KB | ~115 KB | Bundlers (React externalized) | | Standalone IIFE | ~2.2 MB | ~400 KB | Script tag embeds |
The standalone IIFE includes React, so it's larger but works on any website without dependencies.
Why Two Builds?
ESM Build (root export or /web-component)
- Web component entrypoint for bundlers
- React is externalized via
peerDependencies(installreactandreact-dom) - Smaller bundle; no duplicate React if the host already uses it
- Uses Shadow DOM for style isolation
- Use for: bundlers, monorepo consumers
Standalone IIFE Build (/standalone)
- Web component via
<script>tag - React is bundled inside the package
- Uses Shadow DOM for complete JS/CSS isolation
- Separate React instances in separate DOM trees = no conflict
- Use for:
<script>tag embedding on any website (React or not)
The "Two Reacts" Problem
When a React app loads the standalone bundle, you get duplicate React instances which causes the infamous "hooks can only be called inside a function component" error.
Shadow DOM solves this: Each React instance manages its own separate DOM tree inside the shadow boundary, so they never conflict.
Host Page (React 18)
├── <div id="root"> ← Host's React
│ └── ... host app ...
│
└── <char-agent>
└── #shadow-root ← Isolation boundary
└── <div> ← Bundled React 19
└── ... widget ...Installation
npm install @mcp-b/charUsage
<char-agent> renders as a full-viewport overlay.
Recommended: Imperative Authentication (Secure)
The connect() method is the recommended way to authenticate. It keeps tokens out of DOM attributes, preventing exposure to session replay tools, error reporters, and DOM inspectors.
import { useRef, useEffect } from "react";
import "@mcp-b/char/web-component";
import type { CharAgentElement } from "@mcp-b/char/web-component";
function App() {
const { session } = useOktaAuth(); // or Azure, Auth0, Google, etc.
const agentRef = useRef<CharAgentElement>(null);
useEffect(() => {
if (agentRef.current && session?.idToken) {
agentRef.current.connect({ idToken: session.idToken });
}
}, [session?.idToken]);
return <char-agent ref={agentRef} />;
}Vanilla JavaScript
<char-agent></char-agent>
<script type="module">
import "@mcp-b/char/web-component";
const agent = document.querySelector("char-agent");
// Call connect() when you have the token
agent.connect({ idToken: "eyJhbGciOi..." });
</script>Monorepo Dogfooding
import { useRef, useEffect } from "react";
import "@mcp-b/char/web-component";
import type { CharAgentElement } from "@mcp-b/char/web-component";
const authToken = session?.idToken ?? "";
const agentRef = useRef<CharAgentElement>(null);
useEffect(() => {
const agent = agentRef.current ?? document.querySelector("char-agent");
if (!agent) {
const newAgent = document.createElement("char-agent");
document.body.appendChild(newAgent);
// Connect after element is in DOM
(newAgent as CharAgentElement).connect({ idToken: authToken });
} else if (authToken) {
(agent as CharAgentElement).connect({ idToken: authToken });
}
// Set other attributes (these don't contain sensitive data)
agent?.setAttribute("dev-mode", JSON.stringify({ useLocalApi: true }));
agent?.setAttribute("enable-debug-tools", String(import.meta.env.DEV));
}, [authToken]);
return <char-agent ref={agentRef} />;Script Tag (Any Website)
Use defer for best performance - it loads the script without blocking page rendering:
<!-- Recommended: defer loads async, executes after DOM ready -->
<script src="https://unpkg.com/@mcp-b/char/dist/web-component-standalone.iife.js" defer></script>
<char-agent></char-agent>
<script>
// Authenticate after the page loads (tokens not in DOM attributes)
document.addEventListener('DOMContentLoaded', () => {
const agent = document.querySelector('char-agent');
// Get your token from your auth provider
agent.connect({ idToken: yourIdpToken });
});
</script>Alternative CDN (jsdelivr):
<script src="https://cdn.jsdelivr.net/npm/@mcp-b/char/dist/web-component-standalone.iife.js" defer></script>Pin to a specific version for production:
<script src="https://unpkg.com/@mcp-b/[email protected]/dist/web-component-standalone.iife.js" defer></script>Web Component Attributes
<!-- PREFERRED: Use connect() method instead of auth-token attribute -->
<char-agent
dev-mode='{"anthropicApiKey": "sk-ant-..."}'
enable-debug-tools="true"
></char-agent>
<script>
const agent = document.querySelector('char-agent');
agent.connect({ idToken: 'eyJhbGciOi...' });
</script>SSR Frameworks (Astro, Next.js, etc.)
Char requires a browser environment — it uses Shadow DOM, custom elements, and other browser APIs. In SSR frameworks, you must ensure Char only renders on the client.
Astro
Use client:only="react" to skip server-side rendering entirely:
---
import { Char } from '@mcp-b/char'
---
<Char
client:only="react"
devMode={{ anthropicApiKey: import.meta.env.PUBLIC_ANTHROPIC_API_KEY }}
open={true}
/>client:load or client:visible will not work because Astro still attempts to render the component on the server first. client:only="react" skips SSR entirely and renders only in the browser.
Next.js
Use dynamic imports with ssr: false:
import dynamic from 'next/dynamic'
const Char = dynamic(() => import('@mcp-b/char').then(m => ({ default: m.Char })), {
ssr: false,
})
export default function Page() {
return <Char open={true} devMode={{ anthropicApiKey: process.env.NEXT_PUBLIC_ANTHROPIC_API_KEY }} />
}Props / Attributes
| Prop | Attribute | Type | Description |
|------|-----------|------|-------------|
| - | - | method | connect({ idToken }) - Secure authentication (token not in DOM) |
| - | - | method | connect({ ticketAuth }) - SSR-friendly authentication (pre-fetched ticket) |
| - | - | method | disconnect() - Clear authentication |
| open | open | boolean | Controlled open state (optional) |
| devMode | dev-mode | object/JSON | Development mode config (optional) |
| enableDebugTools | enable-debug-tools | boolean | Enable debug tools (default: false) |
Customization
Customize appearance by setting CSS variables on the host page:
char-agent {
/* Brand colors */
--wm-color-primary: #8b5cf6;
--wm-color-primary-foreground: #ffffff;
/* Layout */
--wm-radius: 12px;
--wm-font-sans: 'Inter', sans-serif;
/* Backgrounds */
--wm-color-background: #ffffff;
--wm-color-foreground: #1a1a1a;
--wm-color-muted: #f5f5f5;
/* Messages */
--wm-user-bubble-bg: #8b5cf6;
--wm-user-bubble-text: #ffffff;
--wm-assistant-bubble-bg: #f5f5f5;
--wm-assistant-bubble-text: #1a1a1a;
/* Composer */
--wm-composer-bg: #ffffff;
--wm-composer-border: #e5e5e5;
--wm-composer-button-bg: #8b5cf6;
/* Tools */
--wm-tool-bg: #f9fafb;
--wm-tool-border: #e5e7eb;
--wm-tool-approve-bg: #10b981;
--wm-tool-deny-bg: #ef4444;
/* Code blocks */
--wm-code-bg: #1e1e1e;
--wm-code-text: #d4d4d4;
/* Font sizes */
--wm-font-size-xs: 0.75rem;
--wm-font-size-sm: 0.875rem;
--wm-font-size-base: 1rem;
--wm-font-size-lg: 1.125rem;
}
/* Dark mode */
char-agent.dark {
--wm-color-background: #1a1a1a;
--wm-color-foreground: #ffffff;
--wm-color-muted: #2a2a2a;
/* ... other dark mode overrides */
}Development Mode
Use your own API keys during development (stateless):
<char-agent
dev-mode='{"anthropicApiKey":"sk-ant-...","openaiApiKey":"sk-...","useLocalApi":true}'
></char-agent>Development modes:
anthropicApiKey: Use your own Anthropic API key (falls back to Gemini if not provided)openaiApiKey: Enable voice mode with your OpenAI keyuseLocalApi: Point to localhost instead of production API
Common combinations:
{ useLocalApi: true }- Internal monorepo development{ anthropicApiKey: "sk-ant-..." }- External dev with your own key{ anthropicApiKey: "...", openaiApiKey: "...", useLocalApi: true }- Full stack local dev
Performance
Script Loading
Always use defer or async when embedding the standalone script to avoid blocking page rendering:
<!-- GOOD: defer - loads in parallel, executes after DOM ready -->
<script src="https://unpkg.com/@mcp-b/char/dist/web-component-standalone.iife.js" defer></script>
<!-- GOOD: async - loads in parallel, executes ASAP -->
<script src="https://unpkg.com/@mcp-b/char/dist/web-component-standalone.iife.js" async></script>
<!-- BAD: blocks page rendering until script loads -->
<script src="https://unpkg.com/@mcp-b/char/dist/web-component-standalone.iife.js"></script>When to use which:
defer(recommended) - Script executes after HTML is parsed, preserves execution orderasync- Script executes as soon as it loads, good for independent widgets
Preconnect Hint
Speed up loading by adding a preconnect hint in your <head>:
<link rel="preconnect" href="https://unpkg.com" crossorigin>Features
- MCP Tool Support - Connect to any MCP server
- Voice Mode - Talk to your AI assistant
- Action-First UI - Shows what the AI is doing
- Shadow DOM Isolation - Styles don't leak in or out
- Stateful Sessions - Messages persist across page refreshes (when authToken is provided)
- CSS Variable Theming - Customize appearance without JavaScript
Migration Guide
Upgrading from Previous Versions
Removed props:
apiKey/userId- Replaced byauthToken(use your existing IDP token)appId- No longer needed (removed dead code)siteId- Org-level routing in SSO-first mode (no site scoping)theme- Use CSS variables instead (see Customization section)isolateStyles- Always enabled (Shadow DOM is always used)disableShadowDOM- Removed (Shadow DOM is always enabled)
Migration examples:
<!-- OLD: -->
<char-agent
app-id="app_123"
site-id="site_123"
api-key="sk_live_xxx"
theme='{"primaryColor":"#ff0000","mode":"dark"}'
isolate-styles="false"
></char-agent>
<!-- NEW (SSO-first with connect method): -->
<char-agent></char-agent>
<script>
const agent = document.querySelector('char-agent');
agent.connect({ idToken: 'eyJhbGciOi...' });
</script>
<!-- NEW (anonymous dev mode): -->
<char-agent dev-mode='{"anthropicApiKey":"sk-ant-..."}'></char-agent>
<!-- Customize via CSS: -->
<style>
char-agent {
--wm-color-primary: #ff0000;
}
char-agent.dark {
--wm-color-background: #1a1a1a;
}
</style>Benefits:
- Smaller bundle size (~200 lines removed)
- Simpler API (fewer required attributes)
- More flexible styling (CSS variables work everywhere)
- Consistent Shadow DOM isolation (no edge cases)
- No API keys to manage (uses existing IDP tokens)
Development
pnpm --filter @mcp-b/char dev # Watch TS build
pnpm --filter @mcp-b/char dev:css # Watch Tailwind CSS
pnpm --filter @mcp-b/char storybook # http://localhost:6006
pnpm --filter @mcp-b/char build
pnpm --filter @mcp-b/char check:types
pnpm --filter @mcp-b/char test