Ver en Español
Designing Better WebMCP Tools: Self-Correcting Errors, Character Budgets, DevTools, and webmcp-evals
Nov 29, 2026
Updated: Nov 29, 2026

Designing Better WebMCP Tools: Self-Correcting Errors, Character Budgets, DevTools, and webmcp-evals

Registering a tool on document.modelContext takes twenty lines of JavaScript. Making sure an agent picks it reliably and recovers cleanly when it misses is a different engineering problem.

Teams usually hit this gap after their unit tests are green: the code throws zero exceptions, yet the live agent invents JSON fields or abandons a simple task on its first error.

The reason is plain: your JavaScript is deterministic, while the model invoking it is probabilistic. This final part covers four practices that hold up in practice: structured self-correcting errors, strict JSON Schema with Chrome Character Budgets, native Chrome DevTools debugging (debugging: true), and multi-run evaluations with webmcp-evals.

1. Dynamic Catalogs Without enum: Why "Not found" Makes Agents Give Up

In Part 1 we mapped enum: articles.map(a => a.id) because the catalog held four fixed items. In real apps (thousands of products or shifting records), stuffing every identifier into an inputSchema enum does not scale and bloats context.

Without an enum, your schema accepts a free-form string ({ articleId: string }). On Turn 1, the LLM often guesses a plausible slug (like "modelos-pequenos" instead of "art-slm-2026"), or asks for something absent from the catalog (like "gta6").

Return a bare { error: "Not found" } and the agent hits a dead end: it usually gives up and asks the user for the exact ID.

Validate before mutating state and return a stable error code, valid options, and retryable: true instead. Now the model has an exact map to correct itself on Turn 2:

function addArticle(args) {
  const rawId = typeof args?.articleId === "string" ? args.articleId.trim() : "";
  const match = catalog.find(a => a.id === rawId);

  if (!match) {
    return {
      code: rawId ? "UNKNOWN_ARTICLE" : "INVALID_ARGUMENT",
      error: `Unknown articleId "${rawId}". Pick an exact id from validOptions and retry the call.`,
      retryable: true,
      validOptions: catalog.map(a => ({ id: a.id, title: a.title }))
    };
  }

  return saveToReadingList(match);
}

The turn trace changes completely. On Turn 1, add_article({ articleId: "modelos-pequenos" }) returns UNKNOWN_ARTICLE without touching state. The LLM reads validOptions, sees retryable: true, and retries on Turn 2 with add_article({ articleId: "art-slm-2026" }). When the user asks for something missing like "gta6", the agent reports what actually exists instead of hallucinating.

demo-error-recovery-loop.gif

You can flip live between Naive and Guided error modes in Demo 02 · Error Recovery & Self-Correction.

2. Strict JSON Schema, outputSchema, and Chrome Character Budgets

Before a call reaches your execute callback, your schema should reject properties invented by the model. A compact helper enforces two habits on every tool: listing mandatory fields in required and closing the object with additionalProperties: false.

const schema = (properties, required = Object.keys(properties)) => ({
  type: "object",
  properties,
  required,
  additionalProperties: false
});

In Chrome 159+, you can pair inputSchema with outputSchema inside registerTool() to declare the response shape explicitly (for instance, find_demo returning { matches: [{ id, title }] }).

Contract size matters as much as shape. Chrome's safer WebMCP tools guide sets tight character budgets to keep tool selection sharp and stay clear of agent safety cutoffs:

That is the Chrome team's current guidance for a practical reason: longer titles risk getting truncated, and bloated descriptions get in the way instead of helping the agent complete the task.

3. Debugging Without Burning Tokens: Chrome DevTools and debugging: true

Testing every small code tweak by prompting a live LLM is slow and wastes quota.

Chrome ships a dedicated panel under DevTools → Application → WebMCP. It lists every registered imperative and declarative tool on the active page, its schema and annotations, and a live Tool Activity / Invoked Tools log (Completed, Error, Cancelled).

chrome-devtools-webmcp-pane.png

The Run tool button speeds up iteration immediately: you can pass raw JSON payloads (including edge cases like empty queries or invalid IDs) and inspect structured responses with zero LLM calls.

chrome-devtools-run-tool.png

chrome-devtools-invoked-history.png

From Chrome 156, you can also tag internal diagnostics with debugging: true. A tool like inspect_state dumps internal state machines without scattering console.log statements; user-facing agents can hide it while DevTools and test suites still access it:

await document.modelContext.registerTool({
  name: "inspect_state",
  description: "Return internal FSM and topic catalog state for developer diagnostics.",
  inputSchema: { type: "object", properties: {}, required: [], additionalProperties: false },
  annotations: {
    readOnlyHint: true,
    debugging: true
  },
  execute: () => ({
    time: new Date().toISOString(),
    topicCount: CONTENT_TOPICS.length,
    source: "local-debug-state",
    machines: inspectMachines()
  })
});

In Demo 04 · Tool Observatory, Budgets & Evals, you can inspect live budget bars (30 / 500 / 1500), toggle debugging: true to reveal inspect_state, and run three presets back-to-back: a valid query ({"query":"browser"}), an empty query (INVALID_QUERY with retryable: true), and broken JSON (SyntaxError).

demo-tool-observatory.gif

4. Why Unit Tests Are Not Enough: webmcp-evals

Unit tests confirm that add_to_route({ articleId: "models" }) mutates your reading list properly. They cannot guarantee that a live LLM will map a user's phrasing to that tool and those arguments consistently.

Language models are probabilistic: run the same prompt five times and the agent might succeed three times, stumble once, and take an unexpected route on the fifth attempt.

unit-tests-vs-probabilistic-evals.jpg

As Maud Nalpas explains in Chrome's official evaluations walkthrough, the open-source webmcp-evals CLI measures pass rates and trajectories across repeated runs:

npx webmcp-evals --evals evals.json --model gemini-3.6-flash --runs 5

Your evals.json file pairs user prompts with expected tool calls:

{
  "url": "http://localhost:8080/demos/reading-route.html",
  "runs": 5,
  "evals": [
    {
      "name": "add-small-models-article",
      "prompt": "Add the article about small models to my reading list",
      "expectedToolCalls": [
        { "name": "add_to_route", "arguments": { "articleId": "models" } }
      ]
    },
    {
      "name": "read-only-catalog-check",
      "prompt": "Which articles are currently in my reading list?",
      "expectedToolCalls": [
        { "name": "list_reading_route", "arguments": {} }
      ]
    }
  ]
}

The CLI supports two complementary modes:

  • Local mode (Evals-Driven Development). Tests your JSON tool definitions in isolation before you even wire up the UI, checking whether descriptions and parameters guide the model cleanly.
  • Browser mode. Loads your live page across multiple runs (--runs 5), drives real prompts against registered tools, and reports pass rates and full trajectories.

AI Can Write the Code; Contract Judgment Stays Yours

auditor-prompt-human-review.jpg

Using an assistant (or the WebMCP Auditor Prompt) removes the mechanical boilerplate. Contract design still stays on your desk: deciding which user task deserves a tool, shaping recoverable errors, marking untrusted content, and setting the pass rate you require before shipping.

If you want an easy place to start on Monday, pick an old side project or an abandoned web app you already have and modernize it for agents with WebMCP: you have nothing to lose.

If you try WebMCP on your own web app this week, start with one question: which existing function or HTML form would you expose as your first WebMCP tool?

Live Lab and References

Sebastian Gomez

Sebastian Gomez

Creador de contenido principalmente acerca de tecnología.

Leave a Reply

0 Comments

Advertisements

Related Posts

Categorías