Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

6.7 KB
Raw Blame
import { CURRENT_VERSION } from '@lobechat/const';
import type { McpAppDisplayMode } from '@lobechat/const/mcpApp';
import type { CallToolResult } from '@modelcontextprotocol/client';
import {
  AppBridge,
  type McpUiHostContext,
  type McpUiSizeChangedNotification,
  type McpUiUpdateModelContextRequest,
  PostMessageTransport,
} from '@modelcontextprotocol/ext-apps/app-bridge';

export interface AppDisplayContext {
  availableDisplayModes: McpAppDisplayMode[];
  containerDimensions?: McpUiHostContext['containerDimensions'];
  displayMode: McpAppDisplayMode;
}

export const buildHostContext = (
  isDark: boolean,
  display?: AppDisplayContext,
): McpUiHostContext => ({
  availableDisplayModes: display?.availableDisplayModes ?? ['inline'],
  displayMode: display?.displayMode ?? 'inline',
  ...(display?.containerDimensions && { containerDimensions: display.containerDimensions }),
  locale: navigator.language,
  platform: 'web',
  theme: isDark ? 'dark' : 'light',
  timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
});

export interface McpAppBridgeHost {
  /**
   * Call a tool on the server that rendered the view. `signal` aborts when the
   * view stops waiting for the answer (it timed out or cancelled the request).
   */
  callTool: (
    name: string,
    args: Record<string, unknown>,
    signal: AbortSignal,
  ) => Promise<CallToolResult>;
  /** Latest complete context, including theme changes after connection. */
  getHostContext?: () => McpUiHostContext;
  hostContext: McpUiHostContext;
  /** Only supplied by a feature-enabled host. */
  lifecycle?: {
    getDisplayContext: () => AppDisplayContext;
    onInitialized?: (appModes?: McpAppDisplayMode[]) => void;
    onRequestDisplayMode: (
      mode: McpAppDisplayMode,
      appModes?: McpAppDisplayMode[],
    ) => McpAppDisplayMode;
    onTeardown: () => void;
    onUpdateModelContext: (params: McpUiUpdateModelContextRequest['params']) => void;
  };
  onSizeChange: (height: number) => void;
  /**
   * Open an http(s) link the view asked for; resolves `false` when the host
   * declined it. `signal` aborts when the view stops waiting for the answer.
   */
  openLink: (url: string, signal: AbortSignal) => Promise<boolean>;
  /**
   * Post a user message into the conversation; resolves `false` when the host
   * declined it. `signal` aborts when the view stops waiting for the answer.
   */
  sendMessage: (text: string, signal: AbortSignal) => Promise<boolean | void> | boolean | void;
  toolInput: () => Record<string, unknown>;
  /** The result the view renders; may resolve later (stored media is read back first). */
  toolResult: () => CallToolResult | Promise<CallToolResult>;
}

/**
 * Connect LobeHub to an MCP Apps view living in `target` (the sandboxed
 * iframe's window). `dispose` closes the session at once; `teardown` first
 * lets the view finish, as MCP Apps asks before a view is removed.
 */
export const connectMcpAppBridge = (target: Window, host: McpAppBridgeHost) => {
  const bridge = new AppBridge(
    null,
    { name: 'LobeHub', version: CURRENT_VERSION },
    {
      message: { text: {} },
      openLinks: {},
      serverTools: {},
      ...(host.lifecycle && { updateModelContext: { text: {} } }),
    },
    { hostContext: host.hostContext },
  );

  if (host.lifecycle) {
    let teardownRequested = false;
    bridge.onrequestdisplaymode = async ({ mode }) => {
      const display = host.lifecycle!.getDisplayContext();
      const current = display.displayMode;
      const appModes = bridge.getAppCapabilities()?.availableDisplayModes;
      if (!display.availableDisplayModes.includes(mode) || (appModes && !appModes.includes(mode)))
        return { mode: current };
      const actual = host.lifecycle!.onRequestDisplayMode(mode, appModes);
      bridge.setHostContext({
        ...(host.getHostContext?.() ?? host.hostContext),
        ...display,
        displayMode: actual,
      });
      return { mode: actual };
    };
    bridge.onupdatemodelcontext = async (params) => {
      host.lifecycle!.onUpdateModelContext(params);
      return {};
    };
    bridge.onrequestteardown = () => {
      if (teardownRequested) return;
      teardownRequested = true;
      void teardown(3000).then(() => host.lifecycle!.onTeardown());
    };
  }

  bridge.oncalltool = ({ arguments: args, name }, { mcpReq }) =>
    host.callTool(name, args ?? {}, mcpReq.signal);

  bridge.onmessage = async ({ content }, { mcpReq }) => {
    const text = content
      .flatMap((block) => (block.type === 'text' ? [block.text] : []))
      .join('\n')
      .trim();
    if (!text) return { isError: true };

    const sent = await host.sendMessage(text, mcpReq.signal);
    return sent === false ? { isError: true } : {};
  };

  bridge.onopenlink = async ({ url }, { mcpReq }) => {
    if (!/^https?:\/\//i.test(url)) return { isError: true };

    return (await host.openLink(url, mcpReq.signal)) ? {} : { isError: true };
  };

  const handleSizeChange = ({ height }: McpUiSizeChangedNotification['params']) => {
    if (typeof height === 'number' && height > 0) host.onSizeChange(Math.ceil(height));
  };

  let initialized = false;
  const handleInitialized = () => {
    initialized = true;
    host.lifecycle?.onInitialized?.(bridge.getAppCapabilities()?.availableDisplayModes);
    void bridge.sendToolInput({ arguments: host.toolInput() });
    void Promise.resolve(host.toolResult()).then((result) => bridge.sendToolResult(result));
  };

  bridge.addEventListener('sizechange', handleSizeChange);
  bridge.addEventListener('initialized', handleInitialized);
  void bridge.connect(new PostMessageTransport(target, target));

  let disposed = false;
  const dispose = () => {
    if (disposed) return;
    disposed = true;
    bridge.removeEventListener('sizechange', handleSizeChange);
    bridge.removeEventListener('initialized', handleInitialized);
    void bridge.close();
  };

  /**
   * Tell the view it is going away (`ui/resource-teardown`) and give it up to
   * `timeoutMs` to finish (save pending edits) before the session closes. A
   * view that never initialized has nothing to finish.
   */
  let teardownPromise: Promise<void> | undefined;
  const teardown = (timeoutMs: number): Promise<void> => {
    // A notification and host unmount can race. They share one handshake and close.
    teardownPromise ??= (async () => {
      if (initialized && !disposed) {
        let timer: ReturnType<typeof setTimeout> | undefined;
        await Promise.race([
          bridge.teardownResource({}).catch(() => {}),
          new Promise<void>((resolve) => (timer = setTimeout(resolve, timeoutMs))),
        ]);
        clearTimeout(timer);
      }
      dispose();
    })();
    return teardownPromise;
  };
  return {
    bridge,
    dispose,
    teardown,
  };
};