DEV Community

Cover image for Implement WebMCP in Next.js: Search, Filtering, and Dynamic Tools
Pravin kumar
Pravin kumar

Posted on

Implement WebMCP in Next.js: Search, Filtering, and Dynamic Tools

A practical guide to adding WebMCP tools, choosing between the Imperative and Declarative APIs, and registering search and filter tools only while a component is active.

WebMCP lets a web page expose selected capabilities to an AI agent as structured tools. Instead of asking an agent to guess which input or button controls a search, your page can expose a tool named search_products with a known input schema and a predictable result. If you are new to the idea, start with my earlier WebMCP overview for developers before working through this implementation guide.

This tutorial adds WebMCP to a Next.js client component. The example supports:

  • searching products by text;
  • filtering by category;
  • returning the same results that the human UI displays;
  • registering tools when the component mounts;
  • unregistering them when the component unmounts.

Note: WebMCP is still experimental. The WebMCP specification and browser support can change, so isolate the integration behind feature detection and keep the normal UI fully functional.

The two WebMCP APIs

There are two ways to describe a page capability.

Imperative API

The Imperative API registers a tool from JavaScript:

await document.modelContext.registerTool({
  name: "search_products",
  description: "Search products by text and category.",
  inputSchema: {
    type: "object",
    properties: {
      query: { type: "string", description: "Text to search for." },
      category: { type: "string", description: "Optional category filter." }
    }
  },
  execute: async ({ query, category }) => {
    return searchProducts(query, category);
  }
});
Enter fullscreen mode Exit fullscreen mode

Choose Imperative when the tool needs JavaScript behavior or application state. It is the right fit for:

  • client-side search and filtering;
  • navigation or state transitions;
  • tools that call an existing service function;
  • conditional tools that only make sense on one route or one step of a workflow;
  • tools that need custom validation, loading, or error handling.

For a React application, it also gives you a clean lifecycle: register the tool from an effect when a component is active, then abort that registration when the component leaves the page.

Declarative API

The Declarative API annotates a regular HTML form. The browser derives a tool from the form name, description, fields, and submit behavior:

<form
  toolname="search_products"
  tooldescription="Search products by text and category"
>
  <input
    name="query"
    type="search"
    toolparamdescription="Text to search for"
  />
  <select
    name="category"
    toolparamdescription="Optional product category"
  >
    <option value="all">All categories</option>
    <option value="books">Books</option>
    <option value="music">Music</option>
  </select>
  <button type="submit">Search</button>
</form>
Enter fullscreen mode Exit fullscreen mode

Choose Declarative when the capability is already a normal form submission and the browser can derive the inputs from the rendered controls. It keeps the markup close to the user-facing form and avoids duplicating a JSON schema in JavaScript.

Choose Imperative for this tutorial because filtering is not just form submission. The result list lives in React state, the tool needs to update that state, and the available tool should follow the lifecycle of the search component.

1. Make the page a client component

WebMCP is a browser API. A Next.js Server Component cannot access document.modelContext while rendering on the server. The Chrome WebMCP guide currently documents this browser integration as an experimental feature.

Start the component with:

'use client';

import { useEffect, useMemo, useState } from 'react';
Enter fullscreen mode Exit fullscreen mode

The important rule is simple: do not call document.modelContext at module scope or during server rendering. Register tools inside useEffect, after the component mounted in a browser.

2. Define one source of truth for filtering

The agent and the human should use same filtering function. That prevents a situation where the agent receives one result set while the screen shows another.

type Product = {
  id: string;
  name: string;
  category: 'books' | 'music' | 'games';
  price: number;
};

const products: Product[] = [
  { id: 'bk-1', name: 'Designing Data-Intensive Applications', category: 'books', price: 42 },
  { id: 'bk-2', name: 'The Pragmatic Programmer', category: 'books', price: 38 },
  { id: 'mu-1', name: 'Kind of Blue', category: 'music', price: 24 },
  { id: 'gm-1', name: 'Catan', category: 'games', price: 35 }
];

function filterProducts(query = '', category = 'all') {
  const normalizedQuery = query.trim().toLowerCase();

  return products.filter((product) => {
    const matchesQuery = !normalizedQuery ||
      product.name.toLowerCase().includes(normalizedQuery);
    const matchesCategory = category === 'all' || product.category === category;

    return matchesQuery && matchesCategory;
  });
}
Enter fullscreen mode Exit fullscreen mode

In a real application, replace the in-memory array with your existing search service. Keep authorization, pricing, inventory, and other business rules on the server even when the tool is registered in the browser.

3. Register tools when the component load

Here is the complete client component. It registers two tools:

  • search_products searches by text and category
  • set_product_filter changes the visible filter without making the agent repeat a UI interaction
'use client';

import { useEffect, useMemo, useState } from 'react';

export function ProductSearch() {
  const [query, setQuery] = useState('');
  const [category, setCategory] = useState('all');

  const results = useMemo(
    () => filterProducts(query, category),
    [query, category]
  );

  useEffect(() => {
    const modelContext = document.modelContext;

    // The normal UI still works when WebMCP is unavailable.
    if (!modelContext) return;

    const controller = new AbortController();

    const toolsReady = (async () => {
      await modelContext.registerTool({
        name: 'search_products',
        title: 'Search products',
        description: 'Search the product catalog by text and optional category.',
        inputSchema: {
          type: 'object',
          properties: {
            query: {
              type: 'string',
              description: 'Product name or phrase to search for.'
            },
            category: {
              type: 'string',
              enum: ['all', 'books', 'music', 'games'],
              description: 'Optional category filter.'
            }
          },
          required: ['query']
        },
        execute: async ({ query: nextQuery, category: nextCategory = 'all' }) => {
          const nextResults = filterProducts(nextQuery, nextCategory);

          setQuery(nextQuery);
          setCategory(nextCategory);

          return {
            content: [{
              type: 'text',
              text: JSON.stringify({
                query: nextQuery,
                category: nextCategory,
                count: nextResults.length,
                products: nextResults
              })
            }]
          };
        }
      }, { signal: controller.signal });

      await modelContext.registerTool({
        name: 'set_product_filter',
        title: 'Filter products by category',
        description: 'Show products from one category without changing the search text.',
        inputSchema: {
          type: 'object',
          properties: {
            category: {
              type: 'string',
              enum: ['all', 'books', 'music', 'games']
            }
          },
          required: ['category']
        },
        execute: async ({ category: nextCategory }) => {
          const nextResults = filterProducts(query, nextCategory);
          setCategory(nextCategory);

          return {
            content: [{
              type: 'text',
              text: JSON.stringify({
                category: nextCategory,
                count: nextResults.length,
                products: nextResults
              })
            }]
          };
        }
      }, { signal: controller.signal });
    })();

    // Tell a browser agent to wait if tool registration involves async work.
    modelContext.waitForToolsUntil?.(toolsReady);

    // Unregister both tools when this component is removed or the route changes.
    return () => controller.abort();
  }, [query]);

  return (
    <section>
      <label>
        Search
        <input
          value={query}
          onChange={(event) => setQuery(event.target.value)}
          placeholder="Try: programmer"
        />
      </label>

      <label>
        Category
        <select value={category} onChange={(event) => setCategory(event.target.value)}>
          <option value="all">All</option>
          <option value="books">Books</option>
          <option value="music">Music</option>
          <option value="games">Games</option>
        </select>
      </label>

      <p>{results.length} result(s)</p>
      <ul>
        {results.map((product) => (
          <li key={product.id}>
            {product.name} — ${product.price}
          </li>
        ))}
      </ul>
    </section>
  );
}
Enter fullscreen mode Exit fullscreen mode

The AbortController is doing two jobs. It stops registration when the component is unmounted, and it prevents stale tool definitions from staying available after navigation. This is particularly important in a singlepage app where the document itself may remain open while React replaces one route segment with another.

4. Avoid stale state in tool handlers

The example above includes query in the effect dependency list because set_product_filter reads the current query. That keeps the closure correct but it also re-registers both tools whenever the user types.

For a production component, prefer a ref for frequently changing values so tool registration happens once per mount:

const stateRef = useRef({ query: '', category: 'all' });

useEffect(() => {
  stateRef.current = { query, category };
}, [query, category]);
Enter fullscreen mode Exit fullscreen mode

Then read stateRef.current.query inside execute. Your effect can use [] as its dependency list, while the tool still sees current UI state.

execute: async ({ category: nextCategory }) => {
  const { query: currentQuery } = stateRef.current;
  const nextResults = filterProducts(currentQuery, nextCategory);

  stateRef.current = { query: currentQuery, category: nextCategory };
  setCategory(nextCategory);

  return {
    content: [{
      type: 'text',
      text: JSON.stringify({ count: nextResults.length, products: nextResults })
    }]
  };
}
Enter fullscreen mode Exit fullscreen mode

This pattern avoids unnecessary unregister/register cycles and keeps the agent-facing tool definition stable while the implementation reads changing application state.

5. Register tools only when they are useful

Do not register every capability your application has on every page. Tool descriptions and schemas consume agent context, and a large overlapping catalog makes tool selection harder.

For a complex application, register tools based on the active component or workflow:

useEffect(() => {
  if (!modelContext || !isSearchPanelOpen) return;

  const controller = new AbortController();

  modelContext.registerTool({
    name: 'search_products',
    description: 'Search products currently available in this panel.',
    inputSchema: searchSchema,
    execute: runSearch
  }, { signal: controller.signal });

  return () => controller.abort();
}, [isSearchPanelOpen]);
Enter fullscreen mode Exit fullscreen mode

This is a useful rule of thumb:

  • register stable, page-level read tools when the page loads;
  • register workflow-specific tools when the workflow starts;
  • unregister tools when the user leaves that workflow;
  • keep sensitive actions behind the same authorization and confirmation rules as the human UI.

6. Handle unsupported browsers safely

WebMCP is progressive enhancement. The page should not fail because the browser does not expose document.modelContext.

const modelContext = typeof document !== 'undefined'
  ? document.modelContext
  : undefined;

if (!modelContext) {
  // Continue with the normal UI and ordinary browser-agent fallback.
  return;
}
Enter fullscreen mode Exit fullscreen mode

Do not use a polyfill as if it were native browser-agent support. The official WebMCP repo can help you follow the evolving implementation, but an agent still needs a browser or host that knows how to discover and call WebMCP tools.

Imperative or Declarative: a quick decision

Use the Declarative API when a standard form already expresses the complete action and you want the browser to derive the input schema from the rendered controls.

Use the Imperative API when the action depends on JavaScript, React state, asynchronous services, custom validation, navigation, or dynamic registration. Search and filtering usually belong here because the tool should call the same stateful function as the visible results list.

It is also fine to use both. A product page might use an Imperative tool for search_products, while its newsletter signup uses a Declarative form. The two APIs are complementary, not competing versions of the same implementation.

Testing checklist

Before shipping an Imperative WebMCP tool, check:

  • Does the normal page work when document.modelContext is missing?
  • Is the tool name a clear action rather than an internal function name?
  • Does every input have a useful description and sensible enum values?
  • Does execute validate current authorization and state?
  • Does the visible UI update after the tool runs?
  • Are read-only and consequential actions clearly separated?
  • Does the cleanup abort the registration when the component unmounts?
  • Does the result contain enough information for the agent to continue?
  • Have you tested the tool with the browser or agent that will actually consume it?

The best WebMCP implementation is usually a thin adapter around existing application logic. Keep the human interface, server validation, and business rules as the source of truth. WebMCP should make those capabilities easier for an agent to discover and call, not create a second application to maintain. For React-specific lifecycle support the Chrome Imperative API React notes are a useful next reference.

Top comments (0)