### Install the SDK Source: https://docs.mcp-b.ai/packages/webmcp-ts-sdk/reference Use npm to install the package in your project. ```bash npm install @mcp-b/webmcp-ts-sdk ``` -------------------------------- ### Install Package Source: https://docs.mcp-b.ai/packages/extension-tools/reference Command to install the extension tools and the MCP SDK. ```bash npm install @mcp-b/extension-tools @modelcontextprotocol/sdk ``` -------------------------------- ### Install usewebmcp package Source: https://docs.mcp-b.ai/packages/usewebmcp/reference Install the package and its React dependency using pnpm. ```bash pnpm add usewebmcp react ``` -------------------------------- ### Install @mcp-b/smart-dom-reader Source: https://docs.mcp-b.ai/packages/smart-dom-reader/reference Install the package via npm. ```bash npm install @mcp-b/smart-dom-reader ``` -------------------------------- ### Install usewebmcp dependencies Source: https://docs.mcp-b.ai/how-to/choose-runtime Install the core library and React peer dependency. ```bash npm install usewebmcp react ``` -------------------------------- ### Install @mcp-b/mcp-iframe Source: https://docs.mcp-b.ai/packages/mcp-iframe/reference Install the package and the required MCP SDK dependency. ```bash pnpm add @mcp-b/mcp-iframe @modelcontextprotocol/sdk ``` -------------------------------- ### Start development server Source: https://docs.mcp-b.ai/tutorials/first-react-tool Launch the local development server. ```bash npm run dev ``` -------------------------------- ### Scaffold and install dependencies Source: https://docs.mcp-b.ai/tutorials/first-react-tool Initialize a new Vite React project and install the required WebMCP packages. ```bash npm create vite@latest my-webmcp-react -- --template react-ts cd my-webmcp-react ``` ```bash npm install @mcp-b/webmcp-polyfill usewebmcp ``` -------------------------------- ### Install MCP-B Runtime Source: https://docs.mcp-b.ai/how-to/choose-runtime Install the full MCP-B runtime package. ```bash npm install @mcp-b/global ``` -------------------------------- ### Instantiate BrowserMcpServer Source: https://docs.mcp-b.ai/packages/webmcp-ts-sdk/reference Example of initializing the server with basic metadata and native context. ```ts import { BrowserMcpServer } from '@mcp-b/webmcp-ts-sdk'; const server = new BrowserMcpServer( { name: 'my-app', version: '1.0.0' }, { native: document.modelContext } ); ``` -------------------------------- ### Install @mcp-b/global Source: https://docs.mcp-b.ai/packages/global/reference Installation methods for the package using npm, pnpm, or direct script tags. ```bash npm install @mcp-b/global ``` ```bash pnpm add @mcp-b/global ``` ```html ``` ```html ``` -------------------------------- ### Install WebMCP Polyfill Source: https://docs.mcp-b.ai/how-to/choose-runtime Install the polyfill package to enable the WebMCP standard on the document object. ```bash npm install @mcp-b/webmcp-polyfill ``` -------------------------------- ### Install WebMCP Types Source: https://docs.mcp-b.ai/how-to/choose-runtime Install type definitions to enable argument inference for tools. ```bash npm install --save-dev @mcp-b/webmcp-types ``` -------------------------------- ### Install react-webmcp dependencies Source: https://docs.mcp-b.ai/packages/react-webmcp/reference Install the core package and Zod peer dependency. ```bash pnpm add @mcp-b/react-webmcp zod ``` -------------------------------- ### Install client functionality dependencies Source: https://docs.mcp-b.ai/packages/react-webmcp/reference Install additional packages required for client-side MCP functionality. ```bash pnpm add @mcp-b/transports @modelcontextprotocol/sdk ``` -------------------------------- ### Install WebMCP Runtime Source: https://docs.mcp-b.ai/how-to/add-tools-to-an-existing-app Install the runtime package via npm or include it via a script tag if no build step is present. ```bash npm install @mcp-b/global ``` ```typescript import '@mcp-b/global'; ``` ```html ``` -------------------------------- ### Using the test-webmcp-tool prompt Source: https://docs.mcp-b.ai/how-to/use-devtools-mcp Example of invoking the built-in test-webmcp-tool prompt with specific arguments. ```text Use the test-webmcp-tool prompt with toolName=search_products devServerUrl=http://localhost:5173 ``` -------------------------------- ### CLI Usage Examples Source: https://docs.mcp-b.ai/packages/webmcp-local-relay/reference Common command-line patterns for configuring ports, origins, and relay identification. ```bash # Custom port npx @mcp-b/webmcp-local-relay --port 9444 # Restrict to trusted origins npx @mcp-b/webmcp-local-relay --widget-origin https://myapp.com,https://other.com # Label and identify the relay for multi-relay selection npx @mcp-b/webmcp-local-relay --label "dev" --workspace "myapp" --relay-id "relay-01" ``` -------------------------------- ### initializeWebMCPPolyfill(options?) Source: https://docs.mcp-b.ai/packages/webmcp-polyfill/reference Installs the strict core polyfill on document.modelContext. This function is safe to call repeatedly and performs a no-op in non-browser environments. ```APIDOC ## initializeWebMCPPolyfill(options?) ### Description Installs the strict core polyfill on `document.modelContext`. If `document.modelContext` already exists, initialization is skipped. ### Parameters - **options** (object) - Optional - **autoInitialize** (boolean) - Default: true. Set false to disable auto-init from IIFE/import side effect. - **installTestingShim** (boolean | 'always' | 'if-missing') - Default: 'if-missing'. Controls installation of `navigator.modelContextTesting`. - **disableIframeTransportByDefault** (boolean) - Deprecated no-op. ### Usage Example ```ts import { initializeWebMCPPolyfill } from '@mcp-b/webmcp-polyfill'; initializeWebMCPPolyfill(); ``` ``` -------------------------------- ### Install React hooks packages Source: https://docs.mcp-b.ai/start-here/choose-your-path Install hooks for full MCP-B runtime support or strict core tool registration. ```bash # Full MCP-B hooks npm install @mcp-b/react-webmcp # Strict core hooks npm install usewebmcp ``` -------------------------------- ### Install @mcp-b/global runtime Source: https://docs.mcp-b.ai/how-to/frameworks Install the full WebMCP runtime using npm, pnpm, or a script tag. Note that this package accesses browser APIs on import and requires SSR guards. ```bash npm install @mcp-b/global ``` ```bash pnpm add @mcp-b/global ``` ```html ``` -------------------------------- ### Install @mcp-b/transports Source: https://docs.mcp-b.ai/packages/transports/reference Install the package using pnpm. Requires @mcp-b/webmcp-ts-sdk as a peer dependency. ```bash pnpm add @mcp-b/transports ``` -------------------------------- ### Install @mcp-b/react-webmcp dependencies Source: https://docs.mcp-b.ai/how-to/choose-runtime Install the full MCP-B React package along with the required global runtime and Zod for schema validation. ```bash npm install @mcp-b/react-webmcp @mcp-b/global zod ``` -------------------------------- ### Declare Extension Permissions Source: https://docs.mcp-b.ai/packages/extension-tools/reference Example of declaring required permissions and host permissions in a manifest.json file. ```json { "manifest_version": 3, "permissions": ["tabs", "bookmarks", "storage", "scripting"], "host_permissions": [""] } ``` -------------------------------- ### Verify connected WebMCP sources Source: https://docs.mcp-b.ai/tutorials/desktop-agent-relay Example output from the webmcp_list_sources tool showing connected browser tabs. ```json [ { "tabId": "abc123", "origin": "file://", "url": "file:///path/to/relay-demo.html", "title": "Relay Demo Page", "toolCount": 1 } ] ``` -------------------------------- ### Verify tools with standard consumer methods Source: https://docs.mcp-b.ai/how-to/add-tools-to-an-existing-app Use standard in-page consumer methods to retrieve and execute tools when the global package is installed. ```ts const tools = await document.modelContext.getTools(); const searchTool = tools.find((tool) => tool.name === 'search-products'); if (!searchTool) throw new Error('search-products is not available'); const resultJson = await document.modelContext.executeTool( searchTool, JSON.stringify({ query: 'laptop' }) ); const result = resultJson === null ? null : JSON.parse(resultJson); ``` -------------------------------- ### Install mcp-iframe dependencies Source: https://docs.mcp-b.ai/how-to/bridge-tools-across-iframes Install the required packages for bridging MCP tools across iframe boundaries. ```bash npm install @mcp-b/mcp-iframe @modelcontextprotocol/sdk ``` -------------------------------- ### Initialize the WebMCP polyfill Source: https://docs.mcp-b.ai/packages/webmcp-polyfill/reference Installs the strict core polyfill on document.modelContext. It is safe to call repeatedly and is a no-op in non-browser environments. ```ts import { initializeWebMCPPolyfill } from '@mcp-b/webmcp-polyfill'; initializeWebMCPPolyfill(); ``` -------------------------------- ### Package Metadata Source: https://docs.mcp-b.ai/packages/webmcp-local-relay/reference Basic package information including installation source, license, and Node.js version requirements. ```text npm: @mcp-b/webmcp-local-relay license: MIT node: >= 22 ``` -------------------------------- ### cleanupWebMCPPolyfill() Source: https://docs.mcp-b.ai/packages/webmcp-polyfill/reference Restores previous document.modelContext and navigator.modelContextTesting property descriptors and resets the polyfill install state. ```APIDOC ## cleanupWebMCPPolyfill() ### Description Restores previous `document.modelContext` and `navigator.modelContextTesting` property descriptors and resets the polyfill install state. ### Usage Example ```ts import { cleanupWebMCPPolyfill } from '@mcp-b/webmcp-polyfill'; cleanupWebMCPPolyfill(); ``` ``` -------------------------------- ### Install Chrome DevTools MCP Source: https://docs.mcp-b.ai/packages/chrome-devtools-mcp/overview Use this command to execute the latest version of the upstream Chrome DevTools MCP server via npx. ```bash npx -y chrome-devtools-mcp@latest ``` -------------------------------- ### Start Chrome with remote debugging enabled Source: https://docs.mcp-b.ai/how-to/use-devtools-mcp Launch Chrome with the --remote-debugging-port flag to enable external connections. Ensure the user-data-dir is specified to avoid conflicts with existing sessions. ```bash /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome \ --remote-debugging-port=9222 \ --user-data-dir=/tmp/chrome-profile-stable ``` ```bash google-chrome --remote-debugging-port=9222 \ --user-data-dir=/tmp/chrome-profile-stable ``` ```bash "C:\Program Files\Google\Chrome\Application\chrome.exe" ^ --remote-debugging-port=9222 ^ --user-data-dir="%TEMP%\chrome-profile-stable" ``` -------------------------------- ### new BrowserMcpServer(serverInfo, options) Source: https://docs.mcp-b.ai/packages/webmcp-ts-sdk/reference Initializes a new instance of the BrowserMcpServer with the specified server information and configuration options. ```APIDOC ## Constructor: new BrowserMcpServer(serverInfo, options) ### Description Creates a new BrowserMcpServer instance to handle MCP communication in the browser. ### Parameters - **serverInfo** (Implementation) - Required - Object containing the server name and version (e.g., { name: string; version: string }). - **options** (BrowserMcpServerOptions) - Optional - Configuration options including native context, capabilities, and JSON schema validators. ### BrowserMcpServerOptions - **native** (ModelContextCore) - Optional - Reference to the native/polyfill modelContext. - **capabilities** (ServerCapabilities) - Optional - Additional MCP capabilities for tools, resources, and prompts. - **jsonSchemaValidator** (JsonSchemaValidator) - Optional - Custom JSON Schema validator. ### Usage Example ```ts import { BrowserMcpServer } from '@mcp-b/webmcp-ts-sdk'; const server = new BrowserMcpServer( { name: 'my-app', version: '1.0.0' }, { native: document.modelContext } ); ``` ``` -------------------------------- ### Initialize in Frontend Frameworks Source: https://docs.mcp-b.ai/how-to/frameworks Standard entry point initialization for React, Vue, Svelte, and Angular applications. ```tsx import '@mcp-b/global'; import { createRoot } from 'react-dom/client'; import { App } from './App'; createRoot(document.getElementById('root')!).render(); ``` ```typescript import '@mcp-b/global'; import { createApp } from 'vue'; import App from './App.vue'; createApp(App).mount('#app'); ``` ```typescript import '@mcp-b/global'; import App from './App.svelte'; const app = new App({ target: document.getElementById('app')! }); export default app; ``` ```typescript import '@mcp-b/global'; import { bootstrapApplication } from '@angular/platform-browser'; import { AppComponent } from './app/app.component'; bootstrapApplication(AppComponent); ``` -------------------------------- ### Create the relay-demo.html file Source: https://docs.mcp-b.ai/tutorials/desktop-agent-relay This HTML file registers a tool and loads the embed script to connect to the local relay. Ensure the embed script is loaded after tool registration. ```html Relay Demo Page

Relay Demo

Registering tool...

``` -------------------------------- ### Initialize in Astro Source: https://docs.mcp-b.ai/how-to/frameworks Import via script tag or load the IIFE directly in the layout head. ```astro ``` ```astro ``` -------------------------------- ### Initialize BrowserMcpServer Constructor Source: https://docs.mcp-b.ai/packages/webmcp-ts-sdk/reference Defines the signature for creating a new BrowserMcpServer instance. ```ts new BrowserMcpServer(serverInfo: Implementation, options?: BrowserMcpServerOptions) ``` -------------------------------- ### Selector Ranking Examples Source: https://docs.mcp-b.ai/packages/smart-dom-reader/reference Examples of CSS selectors categorized by their stability score for reliable element identification. ```css #unique-id ``` ```css [data-testid="submit"] ``` ```css [role="button"][aria-label="Submit"] ``` ```css input[name="email"] ``` ```css .form-container .submit-btn ``` -------------------------------- ### initializeWebModelContext(options?) Source: https://docs.mcp-b.ai/packages/global/reference Initializes the global adapter and replaces document.modelContext with a BrowserMcpServer instance. This function is idempotent and safe for SSR environments. ```APIDOC ## initializeWebModelContext(options?) ### Description Initializes the global adapter, replacing `document.modelContext` with a `BrowserMcpServer` instance. It is idempotent and performs a no-op in non-browser environments. ### Parameters - **options** (object) - Optional - Configuration object for the transport layer, including `tabServer` settings like `allowedOrigins`. ``` -------------------------------- ### Discover WebMCP tools Source: https://docs.mcp-b.ai/how-to/use-devtools-mcp List tools available on a webpage that has @mcp-b/global installed. ```text Navigate to https://webmcp.sh and list the available tools ``` -------------------------------- ### Initialize HTML for WebMCP Source: https://docs.mcp-b.ai/tutorials/first-tool Create the base HTML structure and load the WebMCP polyfill via a script tag. ```html My First WebMCP Tool

My First WebMCP Tool

Loading...

``` -------------------------------- ### Get tool descriptors Source: https://docs.mcp-b.ai/packages/webmcp-ts-sdk/reference Retrieves WebMCP producer tool descriptors for registered tools. ```ts const tools = await server.getTools(); const searchTool = tools.find((tool) => tool.name === 'search'); if (!searchTool) throw new Error('search is not available'); ``` -------------------------------- ### CLI Help Output Source: https://docs.mcp-b.ai/packages/webmcp-local-relay/reference Displays the available command-line options and flags for the relay. ```text webmcp-local-relay [options] --host, -H Bind host for local websocket relay (default: 127.0.0.1) --port, -p Preferred root port for the local relay cluster (default: 9333) --widget-origin Allowed host page origin(s), comma-separated (default: *) --allowed-origin Alias for --widget-origin --ws-origin Alias for --widget-origin --label Human-readable relay label reported during discovery --workspace Optional workspace name reported during discovery --relay-id Stable relay identifier reported during discovery --help, -h Show help ``` -------------------------------- ### Complete index.html for WebMCP Tool Source: https://docs.mcp-b.ai/tutorials/first-tool A full HTML boilerplate including the WebMCP polyfill and a basic tool registration script. ```html My First WebMCP Tool

My First WebMCP Tool

Loading...

``` -------------------------------- ### Initialize in Vanilla JS Source: https://docs.mcp-b.ai/how-to/frameworks Import via module bundler or include the IIFE script directly in HTML. ```typescript import '@mcp-b/global'; ``` ```html ``` -------------------------------- ### Import useWebMCPPrompt hook Source: https://docs.mcp-b.ai/packages/react-webmcp/reference Import the hook for registering MCP prompts. ```ts import { useWebMCPPrompt } from '@mcp-b/react-webmcp'; ``` -------------------------------- ### Troubleshoot Common Test Issues Source: https://docs.mcp-b.ai/how-to/test-native-and-polyfill Commands to resolve environment conflicts or installation issues during test execution. ```bash lsof -ti:4173 | xargs kill ``` ```bash pnpm --filter mcp-e2e-tests exec playwright install chromium ``` -------------------------------- ### useWebMCPContext(name, description, getValue) Source: https://docs.mcp-b.ai/packages/react-webmcp/reference A convenience wrapper for creating read-only context tools that automatically set appropriate hints. ```APIDOC ## useWebMCPContext(name, description, getValue) ### Description Registers a read-only context tool. This is a shorthand for useWebMCP with pre-configured hints (readOnly, idempotent). ### Parameters - **name** (string) - Required - Tool identifier - **description** (string) - Required - Description for AI assistants - **getValue** (function) - Required - Function returning the current context value: () => T ``` -------------------------------- ### Get Feedback Source: https://docs.mcp-b.ai/llms.txt Retrieves user feedback from your documentation, including page ratings and code snippet feedback. ```APIDOC ## Get Feedback ### Description Retrieves user feedback from your documentation, including page ratings and code snippet feedback. ### Method GET ### Endpoint /api/analytics/feedback ### Parameters #### Query Parameters - **start_date** (string) - Optional - The start date for filtering feedback. - **end_date** (string) - Optional - The end date for filtering feedback. ``` -------------------------------- ### Enable experimental browser features via CLI Source: https://docs.mcp-b.ai/how-to/debug-and-troubleshoot Launches Chrome with the necessary experimental flags to support native WebMCP features. ```bash google-chrome --enable-experimental-web-platform-features http://localhost:3000 ``` -------------------------------- ### Cleanup the WebMCP polyfill Source: https://docs.mcp-b.ai/packages/webmcp-polyfill/reference Restores previous document.modelContext and navigator.modelContextTesting property descriptors and resets the polyfill install state. ```ts import { cleanupWebMCPPolyfill } from '@mcp-b/webmcp-polyfill'; cleanupWebMCPPolyfill(); ``` -------------------------------- ### Register Chrome Extension Tools Source: https://docs.mcp-b.ai/packages/extension-tools/reference Demonstrates how to initialize an McpServer and register specific Chrome API tool classes in a background script. ```typescript import { TabsApiTools, BookmarksApiTools, StorageApiTools } from '@mcp-b/extension-tools'; import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; const server = new McpServer({ name: 'chrome-extension-server', version: '1.0.0', }); const tabsTools = new TabsApiTools(server, { listActiveTabs: true, createTab: true, closeTabs: true, }); tabsTools.register(); const bookmarksTools = new BookmarksApiTools(server, { getBookmarks: true, createBookmark: true, }); bookmarksTools.register(); ``` -------------------------------- ### Register Tool with npm Source: https://docs.mcp-b.ai/llms.txt Install the `@mcp-b/global` package via npm and then register a tool using `navigator.modelContext.registerTool()` in your TypeScript code. ```bash npm install @mcp-b/global ``` ```typescript import '@mcp-b/global'; navigator.modelContext.registerTool({ name: 'get_weather', description: 'Get weather for a city', inputSchema: { type: 'object', properties: { city: { type: 'string' } }, required: ['city'] }, handler: async ({ city }) => ({ content: [{ type: 'text', text: `Weather in ${city}: 72F, sunny` }] }) }); ``` -------------------------------- ### Get Assistant Conversations Source: https://docs.mcp-b.ai/llms.txt Retrieves AI assistant conversation history including queries, responses, cited sources, and categories. ```APIDOC ## Get Assistant Conversations ### Description Retrieves AI assistant conversation history including queries, responses, cited sources, and categories. ### Method GET ### Endpoint /api/analytics/assistant-conversations ### Parameters #### Query Parameters - **start_date** (string) - Optional - The start date for filtering conversations. - **end_date** (string) - Optional - The end date for filtering conversations. ``` -------------------------------- ### Initialize WebMCP and Render App Source: https://docs.mcp-b.ai/tutorials/first-react-tool The entry point for the application where the WebMCP polyfill is initialized before the React root is rendered. ```tsx import { initializeWebMCPPolyfill } from '@mcp-b/webmcp-polyfill'; import { StrictMode } from 'react'; import { createRoot } from 'react-dom/client'; import { App } from './App'; initializeWebMCPPolyfill(); createRoot(document.getElementById('root')!).render( ); ``` -------------------------------- ### Import useWebMCPContext hook Source: https://docs.mcp-b.ai/packages/react-webmcp/reference Import the convenience wrapper for read-only context tools. ```ts import { useWebMCPContext } from '@mcp-b/react-webmcp'; ``` -------------------------------- ### Register an MCP prompt Source: https://docs.mcp-b.ai/packages/webmcp-ts-sdk/reference Registers a prompt with a name, description, optional argument schema, and a get handler that returns prompt messages. ```ts const handle = server.registerPrompt({ name: 'summarize', description: 'Summarize a document', argsSchema: { type: 'object', properties: { url: { type: 'string', description: 'Document URL' } }, required: ['url'], }, async get(args) { return { messages: [{ role: 'user', content: { type: 'text', text: `Summarize: ${args.url}` } }], }; }, }); ``` -------------------------------- ### Configure and load WebMCP Polyfill via script tag Source: https://docs.mcp-b.ai/packages/webmcp-polyfill/reference Use the window.__webMCPPolyfillOptions object to configure the polyfill before loading the IIFE script. ```html ``` -------------------------------- ### Get Agent Job Source: https://docs.mcp-b.ai/llms.txt Retrieves the status and details of a specific agent job, including progress, branch info, and pull request details. ```APIDOC ## Get Agent Job ### Description Retrieves the status and details of a specific agent job, including progress, branch info, and pull request details. ### Method GET ### Endpoint /api/agent/get-agent-job/{job_id} ### Parameters #### Path Parameters - **job_id** (string) - Required - The ID of the agent job to retrieve. ``` -------------------------------- ### Initialize WebMCP Polyfill Source: https://docs.mcp-b.ai/how-to/choose-runtime Initialize the polyfill and register a tool using the standard WebMCP interface. ```ts import { initializeWebMCPPolyfill } from '@mcp-b/webmcp-polyfill'; initializeWebMCPPolyfill(); document.modelContext.registerTool({ name: 'get-page-title', description: 'Get the current page title', inputSchema: { type: 'object', properties: {} }, async execute() { return { content: [{ type: 'text', text: document.title }], }; }, }); ``` -------------------------------- ### listPrompts() Source: https://docs.mcp-b.ai/packages/webmcp-ts-sdk/reference Retrieves metadata for all enabled prompts. ```APIDOC ## listPrompts() ### Description Returns metadata for all enabled prompts, including argument schemas. ``` -------------------------------- ### Initialize in Next.js Source: https://docs.mcp-b.ai/how-to/frameworks Import in a Client Component layout rather than the root layout to avoid disabling SSR. ```tsx 'use client'; import '@mcp-b/global'; export default function DashboardLayout({ children }) { return <>{children}; } ``` -------------------------------- ### List available demo tools Source: https://docs.mcp-b.ai/tutorials/first-native-preview Retrieve and log the metadata for tools registered by the current page. ```javascript const tools = navigator.modelContextTesting.listTools(); console.log(tools); ``` -------------------------------- ### Create tool component Source: https://docs.mcp-b.ai/tutorials/first-react-tool Implement a component that registers a tool using the useWebMCP hook and displays its execution state. ```tsx import { useWebMCP } from 'usewebmcp'; const INPUT_SCHEMA = { type: 'object', properties: { name: { type: 'string' }, }, } as const; export function App() { const helloTool = useWebMCP({ name: 'say_hello', description: 'Returns a hello message', inputSchema: INPUT_SCHEMA, execute: async (args) => ({ content: [{ type: 'text', text: `Hello ${args?.name ?? 'world'}!` }], }), }); return (

My First React WebMCP Tool

Tool "say_hello" registered.

Executions: {helloTool.state.executionCount}

Last result:{' '} {helloTool.state.lastResult ? JSON.stringify(helloTool.state.lastResult) : 'none'}

{helloTool.state.error && (

Error: {helloTool.state.error.message}

)}
); } ``` -------------------------------- ### Import useWebMCP hook Source: https://docs.mcp-b.ai/packages/react-webmcp/reference Import the primary hook for registering tools. ```ts import { useWebMCP } from '@mcp-b/react-webmcp'; ``` -------------------------------- ### Implement CounterTool with usewebmcp Source: https://docs.mcp-b.ai/how-to/choose-runtime Define a tool using the core usewebmcp hook. Requires document.modelContext to be provided by a polyfill or global provider. ```tsx import { useWebMCP } from 'usewebmcp'; export function CounterTool() { const counterTool = useWebMCP({ name: 'counter_get', description: 'Get current count', inputSchema: { type: 'object', properties: {} } as const, execute: async () => ({ count: 42 }), }); return (

Executions: {counterTool.state.executionCount}

); } ``` -------------------------------- ### Configure Auto-initialization Source: https://docs.mcp-b.ai/packages/global/reference Control the auto-initialization behavior of the global model context using the window.__webModelContextOptions object. ```html ``` ```html ``` -------------------------------- ### Initialize WebMCP polyfill Source: https://docs.mcp-b.ai/tutorials/first-react-tool Add the polyfill initialization to the main entry point before rendering the React app. ```tsx import { initializeWebMCPPolyfill } from '@mcp-b/webmcp-polyfill'; import { StrictMode } from 'react'; import { createRoot } from 'react-dom/client'; import { App } from './App'; initializeWebMCPPolyfill(); createRoot(document.getElementById('root')!).render( ); ``` -------------------------------- ### Discovering tools via AI agent Source: https://docs.mcp-b.ai/how-to/use-devtools-mcp Instruction for the agent to navigate to the development server and discover newly registered tools. ```text Navigate to http://localhost:3000 and list the available tools ``` -------------------------------- ### mcp-iframe-ready Source: https://docs.mcp-b.ai/packages/mcp-iframe/reference Fired when the element successfully connects to the iframe's MCP server and registers all tools, resources, and prompts on the parent. ```APIDOC ## Event: mcp-iframe-ready ### Description Fired when the element connects to the iframe's MCP server and registers all items on the parent. ### Detail Type - **tools** (string[]) - List of prefixed tool names. - **resources** (string[]) - List of prefixed resource URIs. - **prompts** (string[]) - List of prefixed prompt names. ``` -------------------------------- ### useWebMCPPrompt(config) Source: https://docs.mcp-b.ai/packages/react-webmcp/reference Registers an MCP prompt on the document model context. ```APIDOC ## useWebMCPPrompt(config) ### Description Registers an MCP prompt that can be used by AI assistants to generate structured messages. ### Parameters - **name** (string) - Required - Prompt identifier - **description** (string) - Optional - Human-readable description - **argsSchema** (JSON Schema/Standard Schema v1/Zod v3) - Optional - Argument schema - **get** (function) - Required - Message generator: (args) => { messages: PromptMessage[] } ``` -------------------------------- ### useWebMCP(config, deps?) Source: https://docs.mcp-b.ai/packages/usewebmcp/reference The primary hook for registering tools with the model context. It accepts a configuration object and an optional dependency array, returning state and control methods. ```APIDOC ## useWebMCP(config, deps?) ### Description Registers tools with `document.modelContext` on mount and unregisters them on unmount. Requires `document.modelContext` to be available at runtime. ### Parameters - **config** (WebMCPConfig) - Required - Tool configuration object. - **deps** (DependencyList) - Optional - Dependency array that triggers tool re-registration when values change. ### Returns - **state** (ToolExecutionState) - Current execution state. - **execute(input)** ((input) => Promise) - Manually invoke the tool from your UI or tests. - **reset()** (() => void) - Reset state to initial values. ``` -------------------------------- ### initializeWebModelContext Source: https://docs.mcp-b.ai/packages/global/reference Initializes the WebModelContext with specific transport configurations and behavior settings. ```APIDOC ## initializeWebModelContext ### Description Initializes the WebModelContext. Users can configure the transport layer, auto-initialization behavior, and native model context handling. ### Parameters #### Options (WebModelContextInitOptions) - **transport** (TransportConfiguration) - Optional - Transport layer configuration. - **autoInitialize** (boolean) - Optional - Whether to auto-initialize on import (Default: true). - **nativeModelContextBehavior** ('preserve' | 'patch') - Optional - How to handle an existing native modelContext (Default: 'preserve'). - **installTestingShim** (boolean | 'always' | 'if-missing') - Optional - Controls navigator.modelContextTesting installation (Default: 'if-missing'). ### TransportConfiguration - **tabServer** (Partial | false) - Optional - Tab transport options, or false to disable. - **iframeServer** (Partial | false) - Optional - Iframe transport options, or false to disable. ### Usage Example ```ts // Restrict to specific origins initializeWebModelContext({ transport: { tabServer: { allowedOrigins: ['https://myapp.com'] }, }, }); // Disable tab transport (iframe only) initializeWebModelContext({ transport: { tabServer: false }, }); ``` ``` -------------------------------- ### Launch Chromium with native API flags Source: https://docs.mcp-b.ai/how-to/test-native-and-polyfill Use these flags when running Chromium in headless CI environments to enable experimental features. ```bash chromium \ --headless=new \ --enable-experimental-web-platform-features \ --enable-features=WebMCPTesting,DevToolsWebMCPSupport \ --disable-gpu \ --no-sandbox ``` -------------------------------- ### Initialize Web Model Context Source: https://docs.mcp-b.ai/packages/global/reference Manually initialize the global adapter with specific transport options. ```ts import { initializeWebModelContext } from '@mcp-b/global'; initializeWebModelContext({ transport: { tabServer: { allowedOrigins: ['https://example.com'] }, }, }); ``` -------------------------------- ### Registering a Resource Source: https://docs.mcp-b.ai/how-to/register-prompts-and-resources Import the global module and use document.modelContext.registerResource to expose data to AI clients. ```typescript import '@mcp-b/global'; ``` ```typescript const { unregister } = document.modelContext.registerResource({ uri: 'app://config', name: 'App Configuration', description: 'Current application configuration', mimeType: 'application/json', read: async () => ({ contents: [{ uri: 'app://config', text: JSON.stringify(appConfig) }] }) }); ``` ```typescript unregister(); ``` -------------------------------- ### useWebMCP(options) Source: https://docs.mcp-b.ai/packages/usewebmcp/reference Registers an MCP tool with the provided configuration. The hook handles tool execution, state management, and schema validation. ```APIDOC ## useWebMCP(options) ### Description Registers an MCP tool. The hook manages the tool's lifecycle, including registration, execution, and state tracking. ### Parameters - **name** (string) - Required - The name of the tool. - **description** (string) - Required - A description of the tool's purpose. - **outputSchema** (JSON Schema) - Optional - Schema for validating and inferring the output type. - **execute** (function) - Required - The function to execute when the tool is called. ### Usage Example ```tsx const OUTPUT_SCHEMA = { type: 'object', properties: { total: { type: 'integer' }, }, required: ['total'], additionalProperties: false, } as const; const tool = useWebMCP({ name: 'count_items', description: 'Count items', outputSchema: OUTPUT_SCHEMA, execute: () => ({ total: 3 }), }); ``` ``` -------------------------------- ### Register existing tools with backfillTools Source: https://docs.mcp-b.ai/packages/webmcp-ts-sdk/reference Use this method to register tools already present on a native or polyfill context. It skips tools that are already registered on the server. ```ts const synced = server.backfillTools(existingTools, async (name, args) => { const tool = (await existingContext.getTools()).find((item) => item.name === name); if (!tool) throw new Error(`Tool not found: ${name}`); const resultJson = await existingContext.executeTool(tool, JSON.stringify(args)); return resultJson === null ? { content: [] } : JSON.parse(resultJson); }); ``` -------------------------------- ### useWebMCP(config, deps?) Source: https://docs.mcp-b.ai/packages/react-webmcp/reference Registers a tool with the MCP-B runtime. It supports Zod schemas and Standard Schema v1 for input/output validation. ```APIDOC ## useWebMCP(config, deps?) ### Description Registers a tool with the MCP-B runtime. The handler function is executed when the tool is invoked by an AI assistant. ### Parameters - **name** (string) - Required - Unique tool identifier - **description** (string) - Required - Human-readable description - **inputSchema** (JSON Schema/Standard Schema v1/Zod v3) - Optional - Input parameters schema - **outputSchema** (JSON Schema/Standard Schema v1/Zod v3) - Optional - MCP-B output helper metadata - **annotations** (ToolAnnotations) - Optional - Metadata hints - **handler** (function) - Required - Tool implementation function: (input) => T | Promise - **onSuccess** (function) - Optional - Success callback: (result, input) => void - **onError** (function) - Optional - Error callback: (error, input) => void ``` -------------------------------- ### Configure MCP-B Runtime Options Source: https://docs.mcp-b.ai/how-to/choose-runtime Set global options before loading the IIFE script to customize runtime behavior. ```html ```