572

useWebMCP

Registers a WebMCP tool for the component lifecycle

browserlowtest coverage

API not supported, make sure to check for compatibility with different browsers when using this API

import { useWebMCP } from '@siberiacancode/reactuse';
import { BotIcon } from 'lucide-react';

const Demo = () => {
  const webMCP = useWebMCP({
    name: 'get-react-hooks',
    title: 'Get React hooks',
    description: 'Returns all React hooks available in the reactuse documentation',
    inputSchema: { type: 'object', properties: {} },
    annotations: { readOnlyHint: true },
    execute: () => {
      const hooks = Array.from(
        document.querySelectorAll<HTMLAnchorElement>('a[href*="/functions/hooks/"]')
      )
        .map((link) => link.href.split('/').filter(Boolean).at(-1))
        .filter((name) => !!name!.startsWith('use'));

      const uniqueHooks = [...new Set(hooks)].sort();

      return {
        count: uniqueHooks.length,
        hooks: uniqueHooks
      };
    }
  });

  if (!webMCP.supported) {
    return (
      <p>
        API not supported, make sure to check for compatibility with different browsers when using
        this{' '}
        <a href='https://developer.chrome.com/docs/ai/webmcp' rel='noreferrer' target='_blank'>
          API
        </a>
      </p>
    );
  }

  return (
    <section className='flex w-full max-w-md flex-col items-center gap-4 p-4 text-center'>
      <div className='bg-muted flex size-14 items-center justify-center rounded-full'>
        <BotIcon className='size-7' />
      </div>

      <div className='flex flex-col gap-1'>
        <h3 className='text-xl!'>React hooks for your agent</h3>
        <p className='text-muted-foreground text-sm'>Get the complete list of reactuse hooks.</p>
      </div>
    </section>
  );
};

export default Demo;
This hook uses WebMCP browser api to provide enhanced functionality. Make sure to check for compatibility with different browsers when using this api

Installation

pnpm add @siberiacancode/reactuse

Usage

const { supported, registered, error, register, unregister } = useWebMCP({ name: 'add-todo', description: 'Adds a todo item', inputSchema: { type: 'object', properties: { text: { type: 'string' } }, required: ['text'] }, execute: ({ text }) => addTodo(text) });

Type Declarations

export interface WebMCPToolExecuteOptions {
  signal: AbortSignal;
}

export type WebMCPToolExecuteCallback = (
  input: Record<string, unknown>,
  options: WebMCPToolExecuteOptions
) => unknown | Promise<unknown>;

export interface WebMCPToolAnnotations {
  consequentialHint?: boolean;
  debugging?: boolean;
  readOnlyHint?: boolean;
  untrustedContentHint?: boolean;
}

export interface WebMCPModelContextTool {
  annotations?: WebMCPToolAnnotations;
  description: string;
  execute: WebMCPToolExecuteCallback;
  inputSchema?: object;
  name: string;
  title?: string;
}

export interface WebMCPModelContextRegisterToolOptions {
  exposedTo?: string[];
  signal?: AbortSignal;
}

export interface WebMCPModelContext {
  registerTool: (
    tool: WebMCPModelContextTool,
    options?: WebMCPModelContextRegisterToolOptions
  ) => Promise<void>;
}

interface Document {
    readonly modelContext?: WebMCPModelContext;
  }

export type UseWebMCPCommonOptions = Omit<WebMCPModelContextRegisterToolOptions, 'signal'> & {
  /** Whether the tool should be registered immediately */
  immediately?: boolean;
};

export type UseWebMCPOptions = WebMCPModelContextTool & UseWebMCPCommonOptions;

export interface UseWebMCPReturn {
  /** Registration error */
  error?: Error;
  /** Whether the tool is currently registered */
  registered: boolean;
  /** Whether the WebMCP API is supported */
  supported: boolean;
  /** Register the tool again with the latest options */
  register: () => Promise<void>;
  /** Unregister the tool */
  unregister: () => void;
}

API

Parameters

NameTypeDefaultNote
optionsUseWebMCPOptions-The tool definition and registration options
options.namestring-The tool name
options.titlestring-The human-readable tool title
options.descriptionstring-The tool description
options.inputSchemaobject-The JSON schema describing the tool input
options.executeFunction-The function to execute when the tool is called
options.annotationsobject-The metadata describing the tool behavior
options.immediatelybooleantrueWhether the tool should be registered immediately
options.exposedTostring[]-The origins allowed to call the tool

Returns

UseWebMCPReturn

Contributors

ddebabin

Last updated on