document.modelContext API. There is no SDK to install, no native app to ship, and no new framework to learn. You simply call one browser API from your own JavaScript.Not the same as the Wearables Documentation MCP Server. The Wearables Documentation MCP Server page is about connecting your coding assistant to our documentation server while you build. This page, on the other hand, focuses on your shipped Web App offering tools to the assistant on the glasses. The two are unrelated.
Read the Web Apps build guide at https://wearables.developer.meta.com/docs/develop/webapps/build/overview/ and use the Wearables MCP endpoint at https://mcp.developer.meta.com/wearables to call search_webapps_docs. If that tool is unavailable, say so explicitly before continuing and note which of your conclusions are therefore unverified. Inspect this project before changing anything and report back on every way the app's state can change today, including buttons, key handlers, timers and network calls; which of those a person would plausibly ask for out loud; and whether an agent surface is already present and what it exposes. Then extend the app so Meta AI can operate it. Keep the first change small: one or two tools that complete one real task end to end, not a tool per function. Adding an agent must not remove the ability to use the app by hand. The page is the referee. Tools return facts the page can verify and never accept the model's account of what happened. If an outcome can be scored, the page scores it. If the model reports what the user said, fuse the report and the action into a single call so there is no path to a result that skips the check. Speech ends the turn. The model speaks and its turn closes, so any instruction shaped "say X, then call Y" never reaches Y. End every non-terminal result with an explicit next_action saying whether to call another tool or stop and talk, and make everything the model owes the user deliverable in one utterance. Say less than the screen shows. The user is looking at the app, so tools put the detail on screen while the spoken line stays one short sentence and never reads the display back. Write the tool surface so the model succeeds by default. Name tools for the user's intent rather than the internal function. Put the contract in the tool result and not only in the description, because descriptions are read once and the freshest result is what the model actually steers on. Never use a real answer, or any value the model must not guess, as an example in a parameter description, because a model will send the example. Return the new state with every mutation so the model never has to ask what happened. Make the failure modes explicit in the result, including wrong turn, nothing found, and not your move. Add a page-instructions file the agent reads on load covering identity, what is on screen, the actions available, and the two or three rules that are easy to get wrong. Keep it short, because it is prefill on every turn. Finally, run the relevant local checks and drive the tools the way the host calls them rather than the way your code calls them. State plainly which behaviour you verified and which you only reasoned about.
document.modelContext.registerTool() for each tool.execute callback runs in your page, with access to your DOM, state, and APIs.if (document.modelContext) {
registerMyTools();
}
await document.modelContext.registerTool({
// Name the tool for the user's intent, not for your internal function.
name: 'add_to_cart',
description: 'Adds a product to the shopping cart by product ID.',
inputSchema: {
type: 'object',
properties: {
productId: { type: 'string', description: 'The product identifier.' },
quantity: { type: 'number', description: 'How many to add. Defaults to 1.' }
},
required: ['productId']
},
async execute(input, { signal }) {
const res = await fetch('/api/cart', {
method: 'POST',
body: JSON.stringify(input),
signal
});
const cart = await res.json();
return { content: [{ type: 'text', text: `Added. Cart now has ${cart.count} items.` }] };
}
});
| Member | Required | Notes |
|---|---|---|
name | Yes | 1–128 characters of A–Z, a–z, 0–9, _, -, or .. See the length limit below. |
description | Yes | Non-empty. What the tool does, written for the assistant to read. |
execute | Yes | async (input, { signal }) => CallToolResult. |
inputSchema | No | A JSON Schema object describing input. Must be JSON-serializable. Consumes only top-level properties, like type and description. Constraints like enum, ranges, patterns, $ref, and nested schemas are not forwarded. Arrays/objects transported as strings. |
annotations | No | readOnlyHint and untrustedContentHint. Both default to false. |
title | No | Accepted and reported by getTools(), but not passed to Meta AI. description is what it reads. |
name, description, or execute; or gives any of them the wrong type throws a TypeError synchronously rather than rejecting the promise. Wrap registration in try/catch if you build tool definitions dynamically.name accepts up to 128 characters, but the assistant registers your tool under a prefixed name with a 64-character budget, which leaves 57 characters for yours. Longer names are shortened to fit.cart_add and cart_remove, not a long shared prefix with the distinguishing word at the end.description is bounded at 1024 characters, including annotation markers and separators. Each parameter description is bounded at 256 characters. Text beyond those limits is dropped, so include the most important sentence first.openUrl, goBack, goForward, reload, getCurrentUrl, getPageTitle, getPageText.registerTool() has already resolved, so this failure is silent from the page’s point of view — the promise fulfills and the tool simply never reaches Meta AI. Do not use these names.required in inputSchemarequired array. An absent or empty required array means nothing is required, per JSON Schema.execute has to cope.| Annotation | Set it when |
|---|---|
readOnlyHint | The tool only reads. It does not change state, spend money, send anything, or modify data. |
untrustedContentHint | The tool’s result can contain text your app did not author — user-generated content, third-party API responses, scraped pages. |
untrustedContentHint honestly, since it’s not an enforced security boundary. Your tool’s result text goes into the assistant’s context, so returning unmarked untrusted content is how a prompt injection reaches the model. If any part of the text you return originates outside your own app, set the hint, but in general, you must still minimize and sanitize untrusted content.AbortSignal and abort it when the tool no longer applies:// Register on mount, unregister on unmount.
useEffect(() => {
const controller = new AbortController();
registerCheckoutTools(controller.signal);
return () => controller.abort();
}, []);
executeexecute is called with two arguments, and the second is a dictionary whose signal member is required by the specification:async execute(input, { signal }) { /* ... */ }
AbortController, and signal is aborted when the invocation is cancelled. Forward it to any fetch or long-running work, or else your tool will keep going after the assistant has stopped waiting for it. The current fixed deadline for assistant-originated calls is 10 seconds. On expiry, native reports a timeout, aborts the invocation signal on a best-effort basis, and ignores a late result.execute with a single parameter is valid. In this case, you simply never see the signal, and cancellation has no effect on your tool.JSON.stringify and Meta AI sees the JSON. This is the shape used throughout this page, because it carries structured fields like next_action that steer the next turn.content array (MCP-style). Only the entries whose type is text are read, and since their text values are concatenated, Meta AI sees just that string. Everything else — non-text content, structured fields, and the isError flag — is dropped. In particular, isError: true is ignored: a fulfilled result is reported as success no matter what it contains.// Structured — Meta AI sees the JSON, including next_action.
return { placed: true, items: 2, next_action: 'Confirm the order is placed.' };
// Content array — Meta AI sees only "Order placed for 2 items."
return { content: [{ type: 'text', text: 'Order placed for 2 items.' }] };
isError included, that marks it as a failure. Throwing (or rejecting) is the only way to tell Meta AI the call did not succeed.{ error, message, next_action } from a handled condition is usually better than throwing. It is not a protocol-level failure; it is a normal result whose JSON happens to describe what went wrong, so Meta AI can explain it and follow the next_action — for example a drink that is not on the menu. Throw or reject for conditions the model cannot act on, and to signal cancellation.inputSchema — treat input as untrusted and validate it in execute, exactly as you would a request body from the network. Never take a destructive or irreversible action solely because a tool was called with plausible-looking arguments.document.modelContext.getTools() returns a promise for the tools this document has registered. It does not report tools from other origins or other documents; the fromOrigins option is accepted and ignored.toolchange event fires when your registrations change. You can also assign document.modelContext.ontoolchange.description is read once, when Meta AI is deciding which tool to call. After that it steers on the most recent result. So:next_action saying whether to call another tool or stop and talk.move description that teaches the model how they compose:| Tool | What it does |
|---|---|
get_state | Return the board state, including the list of legal moves |
move | Move one piece |
undo | Take back the last move |
new_game | Start a new game |
move:Make a chess move as White, then the AI replies automatically. Pass from/to in algebraic notation (e.g. from e2 to e4) OR a combined UCI string in move (e.g. e2e4, e7e8q to promote). Pick a move from get_state's legal list. Returns the position after the AI has replied.
executeTool the way the host does, not by calling your execute function directly.const tools = await document.modelContext.getTools();
const tool = tools.find((t) => t.name === 'add_to_order');
// The input argument is a JSON string, and the result resolves to one too.
const raw = await document.modelContext.executeTool(
tool,
JSON.stringify({ drink: 'Caramel Macchiato', size: 'grande' }),
);
console.log(JSON.parse(raw));
document.modelContext, so a page under test automation cannot rely on the host to provide it. For a smoke test, define a small stub that behaves the way the host calls your tools, then drive your tool through it the same way:// A smoke-test stub, not a conformance suite: it exercises your tool the way
// the host does, but it cannot prove the assistant will choose it.
const tools = new Map();
document.modelContext = {
registerTool: async (tool) => void tools.set(tool.name, tool),
getTools: async () => [...tools.values()],
executeTool: async (tool, inputArguments, { signal } = {}) => {
const entry = tools.get(tool.name);
if (signal?.aborted) throw signal.reason;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 10_000);
const cancelled = new Promise((_, reject) => {
controller.signal.addEventListener('abort', () => reject(signal?.reason ?? controller.signal.reason), {
once: true,
});
signal?.addEventListener('abort', () => controller.abort(signal.reason), { once: true });
});
try {
const result = await Promise.race([
entry.execute(JSON.parse(inputArguments), { signal: controller.signal }),
cancelled,
]);
return JSON.stringify(result);
} finally {
clearTimeout(timer);
}
},
};
getTools(); executeTool resolves to JSON within 10 seconds; and the app still works with document.modelContext deleted.await registerTool(), getTools(), and toolchange reflect the polyfill’s local registry. Native/provider rejection is not acknowledged back to the page, so these do not prove the assistant can see the tool.execute has not resolved by then, the call is abandoned. Do the slow part asynchronously and return promptly with a state Meta AI can act on.registerTool() rejects rather than throwing for these, in the following order:| Condition | Rejection |
|---|---|
A tool with that name is already registered. | InvalidStateError |
name or description is an empty string. | InvalidStateError |
name is too long or contains invalid characters. | InvalidStateError |
inputSchema cannot be serialized. | TypeError |
The signal you passed is already aborted. | signal.reason |
name rejects — it does not replace the existing tool. Unregister first before re-registering.inputSchema runs JSON.stringify, so a circular reference rejects with a TypeError. On the other hand, a toJSON method that throws surfaces its own exception instead, and because serialization happens before the promise is returned, it can throw synchronously rather than reject. In turn, a pre-aborted signal rejects with whatever signal.reason holds, which is an AbortError only when the signal was aborted without an explicit reason. AbortController.abort(myError) makes myError the rejection. And finally, do not branch on the rejection being an AbortError.| Consider | Avoid |
|---|---|
Feature-detecting document.modelContext before registering | Assuming WebMCP is available, or making it required |
Keeping every tool’s action reachable in your UI too | Shipping a flow that only works by voice |
Short, distinct tool names under 57 characters | Long names sharing a prefix, which can collide after shortening |
Descriptions written for the assistant to choose between tools | Descriptions copied from your internal API docs |
Listing genuinely mandatory parameters in required | Assuming an absent required means everything is required |
Setting untrustedContentHint on anything you did not author | Returning third-party text unmarked |
Validating input inside execute | Trusting the arguments because a schema exists |
Forwarding signal to fetch and long work | Ignoring cancellation |
Unregistering tools that no longer apply | Leaving stale tools registered for the whole session |
Result text a wearer can hear or glance at | Returning raw JSON as the result text |
| Symptom | Likely cause |
|---|---|
document.modelContext is undefined. | WebMCP is not enabled on this device, or the page is not running as a Web App. |
Registration succeeds, but the assistant never offers the tool. | Registered after eligibility was decided for the session, or else the description does not make the tool’s purpose clear enough to choose. |
TypeError on registerTool. | The definition is not an object, or a required member ( name, description, or execute) is missing or the wrong type. This throws synchronously. |
InvalidStateError: Tool already registered. | Re-registering a name without unregistering it first. |
Your tool keeps working after the assistant gave up. | signal was not forwarded to fetch or to your long-running work. |
Your tool runs with a missing parameter. | The parameter is not listed in inputSchema.required. |
Two tools behave as one. | Their names agree in the first 57 characters and collided after shortening. |