---
title: "How to Test and Debug WebMCP Tools Using Chrome DevTools and TypeScript"
published_at: "2026-11-16T22:30:00+00:00"
modified_at: "2026-11-16T22:30:00+00:00"
url: "https://www.syncfusion.com/blogs/post/test-debug-webmcp-tools-chrome-devtools-typescript"
excerpt: "Learn to build, test, and debug WebMCP tools with TypeScript and Chrome DevTools. Troubleshoot registration, schema validation, invocation, and AI agent integration."
taxonomy_category:
  - "Developer Tools"
  - "Syncfusion"
  - "Web Development"
taxonomy_post_tag:
  - "AI Agents"
  - "Chrome DevTools"
  - "Debugging"
  - "JavaScript"
  - "Model Context Protocol"
  - "TypeScript"
  - "Web Development"
  - "WebMCP"
---

# How to Test and Debug WebMCP Tools Using Chrome DevTools and TypeScript

[Arunachalam Kandasamy Raja](https://www.syncfusion.com/blogs/author/arunachalam-kandasamy-raja)

![Test and debug WebMCP tools using Chrome DevTools and TypeScript](https://www.syncfusion.com/blogs/images/posts/test-debug-webmcp-tools-chrome-devtools-typescript/test-debug-webmcp-tools-chrome-devtools-typescript.png)

**TL;DR:** Learn how to build and debug a TypeScript WebMCP tool using Chrome DevTools. Follow seven lifecycle stages, test registration and execution manually, and use BoldCreate CLI with Chrome DevTools MCP to validate agent discovery and invocation.

A WebMCP tool can look correct in TypeScript but still fail when an AI agent tries to use it. The problem could be tool registration, discovery, input generation, invocation, or result handling.

These failures can look similar from the outside: a user asks an agent to perform an action, but nothing useful happens. Changing the handler without identifying the actual problem can waste time.

A better approach is to debug the tool through seven stages:

1. **Registration:** Was the tool registered successfully?

2. **Discovery:** Can the browser or agent find it?

3. **Selection:** Did the agent choose the right tool?

4. **Argument generation:** Did it provide valid input?

5. **Invocation:** Was the tool called?

6. **Handler execution:** Did the operation complete?

7. **Result processing:** Was the output interpreted correctly?

In this tutorial, you'll build a simple TypeScript tool, test it in the Chrome DevTools WebMCP panel, and then validate it through an AI coding agent using [BoldCreate CLI](https://boldcreate.ai/cli "Explore BoldCreate CLI") and Chrome DevTools MCP.

WebMCP is an experimental web capability that allows websites to expose browser-based functionality as structured tools for AI agents. It is not a backend MCP server. The tools run in the browser page and can interact with your application's client-side functionality.

## 1. Prepare Your Environment

WebMCP is available through a Chrome origin trial starting with Chrome 149 or later. For local development, you can enable it using Chrome's testing flag.

1. Open `chrome://flags/#enable-webmcp-testing`.

2. Set the WebMCP testing flag to Enabled.

3. Relaunch Chrome.

For the agent-assisted workflow, use a compatible Chrome build with the experimental WebMCP tools enabled in Chrome DevTools MCP.

![Enable the WebMCP testing flag in Chrome.](< https://www.syncfusion.com/blogs/images/posts/test-debug-webmcp-tools-chrome-devtools-typescript/enable-webmcp-testing-flag.png> "Enable the WebMCP testing flag in Chrome")

### Prerequisites

- Compatible Chrome browser and Chrome DevTools.

- Node.js and npm.

- TypeScript 5.x.

- `webmcp-types` for TypeScript declarations.

- BoldCreate CLI for agent-assisted testing.

- `chrome-devtools-mcp` for browser connectivity.

Install the required development packages:

```bash
npm install --save-dev typescript webmcp-types
```

If your TypeScript setup does not automatically include the WebMCP declarations, add them to `tsconfig.json`:

```json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "lib": ["ES2022", "DOM"],
    "types": ["webmcp-types"],
    "strict": true,
    "noUncheckedIndexedAccess": true
  }
}
```

Run your application from `localhost` or a secure HTTPS origin. Remember that `document.modelContext` belongs to the browser page, not the Node.js environment.

**Security note:** Never expose API secrets in client-side code. Use authenticated backend APIs for protected operations, enforce authorization on the server, and require confirmation for consequential actions.

## 2. Build a Working TypeScript WebMCP Tool

Start with a small working example. We'll create a read-only product lookup tool named `find_product`. It accepts a stock-keeping unit (SKU) and returns the matching product from an in-memory catalog.

### Define the types and sample data

```typescript
export type FindProductInput = {
  sku: string;
};

export type Product = {
  sku: string;
  name: string;
  stock: number;
};

export type FindProductResult =
  | { ok: true; product: Product }
  | { ok: false; error: string; availableSkus?: string[] };

const catalog: readonly Product[] = [
  { sku: "KB-100", name: "Compact Keyboard", stock: 12 },
  { sku: "MS-200", name: "Wireless Mouse", stock: 0 },
];
```

### Validate the received input

TypeScript types do not guarantee that runtime input has the expected structure. Validate the actual value received by the handler.

```typescript
function isFindProductInput(value: unknown): value is FindProductInput {
  if (typeof value !== "object" || value === null) {
    return false;
  }

  const candidate = value as Record<string, unknown>;
  return (
    typeof candidate["sku"] === "string" &&
    candidate["sku"].trim().length > 0
  );
}
```

### Register the tool

Current WebMCP examples use `document.modelContext`. Older guides may use `navigator.modelContext`; update those snippets before testing.

The application entry point calls the asynchronous registration function from `main.ts`. Load `main.ts` through an ES module, such as `<script type="module" src="/src/main.ts"></script>`.

The WebMCP Imperative API uses `document.modelContext.registerTool()`. Its definition includes a name, description, input schema, and execution handler.

```typescript
export async function registerFindProduct(
  signal: AbortSignal
): Promise<void> {
  if (!document.modelContext) {
    throw new Error("WebMCP is not available in this browser.");
  }

  await document.modelContext.registerTool(
    {
      name: "find_product",
      description:
        "Finds a product in the current catalog by SKU. Use when the user asks for product identity or current stock.",
      inputSchema: {
        type: "object",
        properties: {
          sku: {
            type: "string",
            minLength: 1,
            description: "Catalog SKU, such as KB-100.",
          },
        },
        required: ["sku"],
        additionalProperties: false,
      },
      annotations: {
        readOnlyHint: true,
      },
      execute(inputObject: unknown): FindProductResult {
        if (!isFindProductInput(inputObject)) {
          return {
            ok: false,
            error: "Provide a non-empty SKU string.",
          };
        }

        const normalizedSku = inputObject.sku.trim().toUpperCase();
        const product = catalog.find(
          (item) => item.sku === normalizedSku
        );

        if (!product) {
          return {
            ok: false,
            error: `No product was found for SKU ${normalizedSku}.`,
            availableSkus: catalog.map((item) => item.sku),
          };
        }

        return { ok: true, product };
      },
    },
    { signal }
  );
}
```

```typescript
import { registerFindProduct } from "./find-product.js";

const registrationController = new AbortController();

async function run(): Promise<void> {
  try {
    await registerFindProduct(registrationController.signal);
    console.info('[webmcp] Tool "find_product" registered successfully.');
  } catch (error: unknown) {
    console.error("[webmcp] Registration failed:", error);
  }
}

void run();
```

The feature check prevents registration attempts when WebMCP is unavailable.

A few important implementation details:

- The tool name and description help agents understand when to use it.

- The schema defines the expected input.

- Runtime validation checks the actual received value.

- Structured results make recoverable errors easier to handle.

- `readOnlyHint` identifies the tool as read-only.

- `AbortController` manages the registration lifecycle.

Do not rely on the browser to enforce every schema constraint or apply every default. Validate input inside the handler.

### Understand cancellation

The registration signal and execution signal have different purposes. Aborting the registration signal removes the tool. It does not automatically cancel an operation already running inside the handler.

For long-running operations, handle the execution signal separately:

```typescript
await document.modelContext.registerTool({
  name: "get_product_details",
  description: "Gets product details from the application API.",
  inputSchema: {
    type: "object",
    properties: {
      sku: { type: "string" },
    },
    required: ["sku"],
  },
  async execute({ sku }, { signal }) {
    const response = await fetch(
      `/api/products/${encodeURIComponent(sku)}`,
      { signal }
    );

    if (!response.ok) {
      return {
        ok: false,
        error: "Unable to retrieve product details.",
      };
    }

    return await response.json();
  },
});
```

Passing the execution `signal` to `fetch()` allows the browser to cancel the request when execution is canceled.

For more details, see the [WebMCP Imperative API documentation](https://developer.chrome.com/docs/ai/webmcp/imperative-api "Imperative API").

## 3. Test the Tool Manually in Chrome DevTools

Test the tool manually before involving an AI agent. This helps determine whether registration and execution work independently of agent behavior.

### Open the WebMCP panel

1. Open your application in Chrome.

2. Launch Chrome DevTools.

3. Select Application.

4. Select **WebMCP** from the sidebar.

The panel provides two useful views:

- **Available Tools:** Shows registered tools, descriptions, and invocation counters.

- **Invoked Tools:** Shows tool calls, their status, inputs, outputs, and errors.

![View the registered find_product tool in Chrome DevTools.](< https://www.syncfusion.com/blogs/images/posts/test-debug-webmcp-tools-chrome-devtools-typescript/webmcp-available-tools-panel.png> "View the registered find_product tool in Chrome DevTools")

### Run test cases

Select `find_product` under Available Tools, enter an input, and run it.

Use this test matrix:

| **Test case**        | **Input**            | **Expected result**                                                                 |
| -------------------- | -------------------- | ----------------------------------------------------------------------------------- |
| Available product    | `{"sku":"KB-100"}`   | Keyboard record with stock 12                                                       |
| Out-of-stock product | `{"sku":"MS-200"}`   | Mouse record with stock 0                                                           |
| Unknown product      | `{"sku":"XX-999"}`   | Completed invocation with ok: false, an explanatory message, and the available SKUs |
| Normalized input     | `{"sku":" kb-100 "}` | Keyboard record after trimming and normalization                                    |

![Test a successful invocation using KB-100](< https://www.syncfusion.com/blogs/images/posts/test-debug-webmcp-tools-chrome-devtools-typescript/webmcp-successful-invocation.png> "Test a successful invocation using KB-100")

![Inspect the structured result for the unknown SKU XX-999](< https://www.syncfusion.com/blogs/images/posts/test-debug-webmcp-tools-chrome-devtools-typescript/webmcp-unknown-sku-result.png> "Inspect the structured result for the unknown SKU XX-999")

### Understand the invocation status

The WebMCP panel displays states such as:

- **Completed:** The handler finished.

- **Canceled:** The execution was canceled.

- **In Progress:** The operation is still running.

- **Error:** The execution failed.

A Completed status does not always mean the business operation succeeded. For example, an unknown SKU can produce a completed invocation with `ok: false`. This is an expected, recoverable result.

If all manual tests work, move on to agent-assisted testing.

## 4. Debug WebMCP Tools by the First Failing Stage

When a tool fails, inspect the earliest stage that does not behave as expected.

| **Problem**                                        | **What to check**                                                                                                                |
| -------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| Tool is missing from Available Tools               | Chrome compatibility, WebMCP flag or origin trial, `document.modelContext`, registration errors, and aborted registration signal |
| Tool appears, but manual execution fails           | Input structure, runtime validation, application state, exceptions, and rejected promises                                        |
| Handler completes, but output is incorrect         | Missing return values, output structure, UI updates, and cancellation handling                                                   |
| Agent cannot discover the tool                     | MCP server configuration, experimental WebMCP category, browser target, and active page                                          |
| Agent discovers but does not execute the tool      | Generated arguments and invocation details                                                                                       |
| Agent skips the tool for natural-language requests | Tool name, description, parameter descriptions, and overlapping responsibilities                                                 |

**Example: Debug a handler failure**

The following example intentionally throws an error:

```typescript
await document.modelContext.registerTool({
  name: "find_product_broken_handler",
  description: "Finds a product by SKU.",
  inputSchema: {
    type: "object",
    properties: {
      sku: { type: "string" },
    },
    required: ["sku"],
  },
  execute({ sku }: FindProductInput) {
    throw new Error(`Simulated lookup failure for ${sku}`);
  },
});
```

The invocation will report an execution error.

For recoverable problems, return structured results instead. For example, an unknown SKU should return an error message and available alternatives. Unexpected programming errors should still be treated as failures rather than being disguised as successful results.

For tools that update the page, wait until the visible state matches the returned result. Handle canceled asynchronous operations to prevent stale updates.

If a tool returns external or user-generated content, consider the `untrustedContentHint` annotation. For significant or irreversible actions, use `consequentialHint` and implement an independent confirmation safeguard. These annotations do not replace authorization or validation.

## 5. Connect BoldCreate CLI to Chrome DevTools MCP

Once manual testing succeeds, validate the tool through an MCP-compatible AI agent.

This tutorial uses [BoldCreate CLI](https://boldcreate.ai/cli "Explore BoldCreate CLI") with Chrome DevTools MCP. The same approach can be used with other compatible agents.

Add the Chrome DevTools MCP server from your project terminal:

```bash
boldcreate mcp add chrome-devtools -- npx -y chrome-devtools-mcp@latest --categoryExperimentalWebmcp
```

The `--` separator passes the following command and arguments to the MCP server configuration.

Verify the server configuration:

```bash
boldcreate mcp list
```

For more details, refer to the [Setting Up MCP Servers](https://docs.boldcreate.ai/cli/extensibility/mcp-servers "Learn how to set up MCP servers in BoldCreate CLI") guide.

Start your application in a separate terminal:

```bash
npm run dev
```

Make sure the application is open in the Chrome instance accessible to Chrome DevTools MCP. The agent may use a different Chrome profile or page from the one used for manual testing.

Restart [BoldCreate CLI](https://boldcreate.ai/cli "Explore BoldCreate CLI") after adding the MCP server if it was already running.

**Security note:** Use an isolated test profile rather than a browser session containing sensitive authenticated accounts.

### Test discovery first

Do not begin with an open-ended request such as “Find the keyboard.” First confirm that the agent can discover the tool.

**Prompt 1:**

```text
List the WebMCP tools exposed by the current page. Confirm whether find_product is present, and summarize its description and input schema. Do not execute the tool.
```

This checks discovery without involving tool selection.

### Test explicit invocation

Once discovery succeeds, ask the agent to execute the tool with a known input.

**Prompt 2:**

```text
Execute the exposed find_product WebMCP tool on the selected page with {"sku":"KB-100"}. Use the WebMCP invocation capability rather than reading visible page text. Report the exact input, output, and invocation status.
```

The expected result is a completed invocation returning the Compact Keyboard record with stock 12.

![Invoke the find_product WebMCP tool using BoldCreate CLI](< https://www.syncfusion.com/blogs/images/posts/test-debug-webmcp-tools-chrome-devtools-typescript/boldcreate-cli-webmcp-invocation.png> "Invoke the find_product WebMCP tool using BoldCreate CLI")

### Test natural-language selection

Finally, check whether the agent selects the tool without being told its name.

**Prompt 3:**

```text
Check whether product KB-100 is in stock on this page. Use an available page tool when it is relevant.
```

If the agent does not select `find_product`, the tool may still be working correctly. The agent may simply have chosen not to invoke it for that request.

Repeat the prompt when evaluating selection behavior, and record each run separately. A small number of tests is not enough to establish a general reliability percentage.

## 6. Improve Tool Discovery and Selection

If an agent can list a tool but does not choose it, review the information available to it.

**Use focused names.** Prefer `find_product` over vague names such as `product_helper`.

**Write clear descriptions.** Explain what the tool does and when it should be used.

```text
description:
"Finds a product in the current catalog by SKU.
Use when the user asks for product identity or current
stock."
```

**Describe parameters.** Explain what each argument represents and provide an example.

```typescript
sku: {
  type: "string",
  minLength: 1,
  description: "Catalog SKU, such as KB-100."
}
```

**Register tools in relevant contexts.** Remove registrations when their associated page or application state is no longer available.

**Avoid overlapping responsibilities.** If `find_product`, `get_product`, and `search_catalog` perform similar tasks, clarify their purpose or consolidate them.

Keep the schema responsible for types, required properties, enum values, and constraints.

## 7. Prevent Common WebMCP Problems

Manual testing is useful, but reliable applications also need automated tests.

Include checks for:

- Valid, missing, empty, and incorrect input.

- Boundary values and structured error responses.

- Unavailable application state.

- Registration and cleanup during route changes.

- Cancellation of asynchronous operations.

- Authorization for state-changing actions.

- Confirmation for consequential operations.

- Safe handling of untrusted output.

- Visible UI state after execution.

Keep handler tests separate from agent-selection tests. A unit test can verify the output for `KB-100`, but it cannot prove that every AI agent will select the tool for every possible request.

## Frequently Asked Questions

### 1. How does WebMCP fit into React, Angular, or Vue?

Register tools when the required component or route becomes available, and clean them up when it is removed. WebMCP framework integrations can simplify this process.

For example, React, Angular, and Vue integrations provide lifecycle-aware ways to manage tool registration. Check the current framework integration documentation before adding a dependency.

### 2. Can a WebMCP tool call a backend API?

Yes. A WebMCP handler can use `fetch()` to access backend data or operations.

However, the backend must enforce authentication, authorization, input validation, rate limits, and business rules. Never expose privileged API credentials in browser code.

### 3. How can a single-page application prevent duplicate registrations?

Tie tool registration to the component or route lifecycle. Keep the registration `AbortController` and abort its `signal` when the tool is no longer needed.

Test route changes, hot reloads, and development-mode checks to identify stale or duplicate registrations.

### 4. Can WebMCP tools work inside an iframe?

Yes, subject to origin and Permissions Policy restrictions.

Cross-origin iframe access requires the embedding page to delegate the tools permission. The tool must also explicitly expose itself to the permitted origin through the `exposedTo` option. Verify current browser support before depending on iframe-based integrations.

### 5. Is WebMCP ready for production applications?

WebMCP is still experimental. Provide a non-WebMCP fallback for essential functionality, enforce authorization on the server, and require confirmation for consequential operations.

Treat WebMCP as a progressive enhancement rather than the only way users can access an essential feature.

## Conclusion

Debugging WebMCP tools becomes easier when you test each lifecycle stage in order.

First, confirm registration and discovery in Chrome DevTools. Next, validate the handler with controlled inputs. Once manual testing succeeds, use [BoldCreate CLI](https://boldcreate.ai/cli) with Chrome DevTools MCP to test agent discovery, explicit invocation, and natural-language selection.

Remember that successful manual execution proves the tool works for the tested input. Agent selection is a separate behavior influenced by the request, tool descriptions, available context, and the agent itself.

**Ready to test your WebMCP tools with an AI coding agent?** Try [BoldCreate CLI](https://boldcreate.ai/cli "Explore BoldCreate CLI") with the [Chrome WebMCP debugging guide](https://developer.chrome.com/docs/devtools/agents/webmcp-debugging "Debug WebMCP tools in Chrome DevTools") and apply the same process to your browser-based tools.
