{"id":"webmcp-tutorial","title":"How to add WebMCP to your website: a step-by-step tutorial with code","searchTitle":"How to Add WebMCP to Your Website: Step-by-Step Tutorial","cheat":["Write each tool as a plain function first. Registering it is the easy part.","Return errors as sentences. The browser hides thrown ones from the agent.","Keep answers under 1,500 characters and end each one with a link."],"description":"A step-by-step WebMCP tutorial with code: write a tool, register it with registerTool, return errors an agent can read, test it in Chrome and serve it over MCP.","topic":"building","tags":["builders"],"published":"2026-11-16","updated":"2026-11-16","minutes":6,"terms":[{"id":"tool-calling","term":"Tool calling"},{"id":"mcp-server","term":"MCP server"},{"id":"model-context-protocol","term":"Model Context Protocol"},{"id":"browser-agent","term":"Browser agent"},{"id":"human-in-the-loop","term":"Human in the loop"}],"tools":[{"label":"Repos worth building on","path":"/repos"}],"sources":[{"label":"WebMCP: Draft Community Group Report","url":"https://webmachinelearning.github.io/webmcp/"},{"label":"Chrome for Developers: WebMCP best practices","url":"https://developer.chrome.com/docs/ai/webmcp/best-practices"},{"label":"Chrome for Developers: WebMCP tool security","url":"https://developer.chrome.com/docs/ai/webmcp/secure-tools"},{"label":"Chrome for Developers: Test WebMCP with evals","url":"https://developer.chrome.com/docs/ai/webmcp/evals"},{"label":"Chrome for Developers: Join the WebMCP origin trial","url":"https://developer.chrome.com/blog/ai-webmcp-origin-trial"},{"label":"Model Context Protocol: Streamable HTTP, revision 2026-07-28","url":"https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/streamable-http"}],"blocks":[{"type":"p","children":[{"type":"text","text":"To add WebMCP to a website you write each tool as a plain function, register it with "},{"type":"code","text":"document.modelContext.registerTool"},{"type":"text","text":", return errors as text, and test it in Chrome with a flag switched on. This tutorial does that in eight steps, with code."}]},{"type":"p","children":[{"type":"text","text":"It is the hands-on companion to "},{"type":"link","href":"/learn/webmcp","children":[{"type":"text","text":"what WebMCP is and why it matters"}]},{"type":"text","text":". It follows what this site did in November 2026, including the mistakes its first version made. By the end you will have one working tool an AI agent in Chrome can find and call, and the same tool ready for agents that never open a browser."}]},{"type":"h2","children":[{"type":"text","text":"What do you need before you start?"}]},{"type":"p","children":[{"type":"text","text":"You need a site you can add JavaScript to, and Chrome 149 or later. Nothing else is installed: no library, no account, no server."}]},{"type":"p","children":[{"type":"text","text":"WebMCP is a draft, and its API has changed once already. The code here matches the draft as it stood on 13 November 2026."}]},{"type":"h2","children":[{"type":"text","text":"Step 1: Choose what agents can ask"}]},{"type":"p","children":[{"type":"text","text":"Start with questions. The API comes later. Write down the three questions people most often bring to your site. For a shop: is this in stock, what does delivery cost, where is my order. For this site: what does this AI term mean, what happened in AI today, which guide should I read."}]},{"type":"p","children":[{"type":"text","text":"Each question becomes one tool. Give each tool one job, and avoid two tools that do nearly the same thing, because the agent chooses by reading the descriptions."}]},{"type":"p","children":[{"type":"text","text":"Start read-only. A tool that looks something up cannot hurt anyone."}]},{"type":"h2","children":[{"type":"text","text":"Step 2: Write the tool as a function"}]},{"type":"p","children":[{"type":"text","text":"Write a plain function that takes input and returns text, and keep it away from the page for now. It is easy to test and you can reuse it later."}]},{"type":"pre","text":"// tools.js\nconst LIMIT = 1500\n\nexport async function searchGlossary({ query }) {\n  if (typeof query !== 'string' || !query.trim()) {\n    throw new Error('\"query\" is required: the term to look up.')\n  }\n  const terms = await fetch('/data/glossary.json').then(r => r.json())\n  const hits = terms.filter(t => t.name.toLowerCase().includes(query.toLowerCase()))\n  if (!hits.length) return `No term matches \"${query}\". All terms: https://example.com/glossary`\n  const first = hits[0]\n  return `${first.name}\\n${first.definition}\\nhttps://example.com/glossary/${first.id}`.slice(0, LIMIT)\n}"},{"type":"p","children":[{"type":"text","text":"Three habits are already in there:"}]},{"type":"ul","items":[[{"type":"strong","children":[{"type":"text","text":"Check the input again in code."}]},{"type":"text","text":" The schema you publish is a hint. Anything can arrive."}],[{"type":"strong","children":[{"type":"text","text":"Say what was wrong in a sentence"}]},{"type":"text","text":" the agent can act on."}],[{"type":"strong","children":[{"type":"text","text":"End with a link"}]},{"type":"text","text":" to the page the answer came from."}]]},{"type":"h2","children":[{"type":"text","text":"Step 3: Register it with registerTool"}]},{"type":"p","children":[{"type":"text","text":"Call "},{"type":"code","text":"document.modelContext.registerTool"},{"type":"text","text":" once per tool, with a name, a description, an input schema and the function. Check first that the API exists, because most browsers do not have it."}]},{"type":"pre","text":"// register.js\nimport { searchGlossary } from './tools.js'\n\nif ('modelContext' in document) {\n  const controller = new AbortController()\n  document.modelContext.registerTool({\n    name: 'search_glossary',\n    title: 'Look up a term',\n    description: 'Look up a term in the glossary. Returns the definition and the address of its page.',\n    inputSchema: {\n      type: 'object',\n      properties: { query: { type: 'string', description: 'The term, for example \"RAG\".' } },\n      required: ['query'],\n    },\n    annotations: { readOnlyHint: true },\n    async execute(input) {\n      try {\n        return await searchGlossary(input)\n      } catch (error) {\n        return `Could not answer: ${error.message}`\n      }\n    },\n  }, { signal: controller.signal })\n  // To take the tool back later: controller.abort()\n}"},{"type":"figure","src":"/images/learn/webmcp-tutorial/anatomy-of-a-webmcp-tool.webp?v=0ab4a0a2b6eaaba7","alt":"Annotated code for registering a WebMCP tool. Four numbered parts: the name (up to 30 characters), the description (500), the input schema (150 per input) and the execute function (answers up to 1,500).","caption":"The four parts of a tool, and the room each one gets","width":1440,"height":1062,"narrow":{"src":"/images/learn/webmcp-tutorial/anatomy-of-a-webmcp-tool-narrow.webp?v=9a6b9cb80e5a095b","width":720,"height":1002}},{"type":"p","children":[{"type":"text","text":"What matters here:"}]},{"type":"ul","items":[[{"type":"strong","children":[{"type":"text","text":"The page must work exactly as before"}]},{"type":"text","text":" in browsers without the API."}],[{"type":"strong","children":[{"type":"code","text":"readOnlyHint"}]},{"type":"text","text":" tells the agent the tool changes nothing."}],[{"type":"strong","children":[{"type":"text","text":"Catch errors and return them as text."}]},{"type":"text","text":" When a tool throws, the browser tells the agent only that it failed, and the agent has nothing to correct. The draft does this on purpose, to keep a site's internals private."}],[{"type":"strong","children":[{"type":"text","text":"The signal is how you take a tool back."}]},{"type":"text","text":" There is no unregister call."}]]},{"type":"h2","children":[{"type":"text","text":"Step 4: Keep to Chrome's limits"}]},{"type":"p","children":[{"type":"text","text":"Chrome's guidance gives a tool's answer about 1,500 characters, its description 500, each input's description 150, and a name 30. Chrome says these numbers may change."}]},{"type":"figure","src":"/images/learn/webmcp-tutorial/webmcp-character-limits.webp?v=249ca4904a150f45","alt":"Bar chart of Chrome's guidance for a WebMCP tool, in characters: the answer up to 1,500, the tool's description up to 500, each input's description up to 150, and a name up to 30.","caption":"Chrome's guidance in characters: most of the room goes to the answer","width":1440,"height":770,"narrow":{"src":"/images/learn/webmcp-tutorial/webmcp-character-limits-narrow.webp?v=0d87beb0c7d29653","width":720,"height":838}},{"type":"p","children":[{"type":"text","text":"The same page has naming advice: use a verb, and make it plain whether the tool does the thing or only starts it. In Chrome's own example, "},{"type":"code","text":"create-event"},{"type":"text","text":" creates an event, while "},{"type":"code","text":"start-event-creation-process"},{"type":"text","text":" sends the person to a form."}]},{"type":"p","children":[{"type":"text","text":"Write these limits into your tests. They are easy to break by accident."}]},{"type":"h2","children":[{"type":"text","text":"Step 5: Test your tools in Chrome"}]},{"type":"p","children":[{"type":"text","text":"Switch on Chrome's testing flag, open your page, and call the tool from the DevTools console."}]},{"type":"ol","items":[[{"type":"text","text":"Open "},{"type":"code","text":"chrome://flags/#enable-webmcp-testing"},{"type":"text","text":", switch it on and restart Chrome."}],[{"type":"text","text":"Open your page, then the DevTools console."}],[{"type":"text","text":"List the tools and call one, as below."}]]},{"type":"pre","text":"const tools = await document.modelContext.getTools()\ntools.map(tool => tool.name)\nawait document.modelContext.executeTool(tools[0], { query: 'RAG' })"},{"type":"p","children":[{"type":"text","text":"Try bad input as well, and read the answer the way an agent would. If it does not tell you what to fix, rewrite it."}]},{"type":"p","children":[{"type":"text","text":"Chrome's documentation also describes evals: test files that check whether a model picks the right tool for a request. Add them once you have more than a handful of tools."}]},{"type":"h2","children":[{"type":"text","text":"Step 6: Add one action, carefully"}]},{"type":"p","children":[{"type":"text","text":"An action tool may change what the visitor is looking at, and anything with a consequence must stop at a step the visitor confirms. Lookups are safe. Actions need that rule."}]},{"type":"p","children":[{"type":"text","text":"This site has two actions. One shows a page of the site in the tab. The other opens the message window with a draft in it. The visitor reads the draft and presses Send. The tool has no way to send."}]},{"type":"figure","src":"/images/learn/webmcp-tutorial/agent-draft-in-the-message-window.webp?v=a6991835d50e9ac2","alt":"Screenshot of the message window on theglitch.ai after an agent's tool opened it. The draft reads: Hi Rabin. An agent drafted this for me. I will read it before I press Send. A Send button sits beside it.","caption":"An agent wrote the draft. A person presses Send.","width":1072,"height":990,"narrow":{"src":"/images/learn/webmcp-tutorial/agent-draft-in-the-message-window-narrow.webp?v=b3f40f4e3cc190d1","width":760,"height":1080}},{"type":"p","children":[{"type":"text","text":"Name such a tool for what it really does: "},{"type":"code","text":"start_message"},{"type":"text","text":", never "},{"type":"code","text":"send_message"},{"type":"text","text":". If the visitor has already typed something, leave it alone."}]},{"type":"h2","children":[{"type":"text","text":"Step 7: Serve the same tools over MCP"}]},{"type":"p","children":[{"type":"text","text":"Put the same function behind an "},{"type":"link","href":"/ai-glossary/mcp-server","children":[{"type":"text","text":"MCP server"}]},{"type":"text","text":" and agents that never open a browser can use it too. Assistants and coding tools connect over the network, with no tab involved."}]},{"type":"figure","src":"/images/learn/webmcp-tutorial/one-tool-three-doors.webp?v=01143e32a6643c0b","alt":"Diagram of one function, searchGlossary, served through three doors: WebMCP for an agent in the browser tab, an MCP endpoint for assistants and coding agents, and a tools page for people.","caption":"One function, three doors: the tab, the server and a page for people","width":1440,"height":902,"narrow":{"src":"/images/learn/webmcp-tutorial/one-tool-three-doors-narrow.webp?v=b7014e6f2dceef62","width":720,"height":1118}},{"type":"p","children":[{"type":"text","text":"The current revision of the "},{"type":"link","href":"/ai-glossary/model-context-protocol","children":[{"type":"text","text":"Model Context Protocol"}]},{"type":"text","text":", dated 28 July 2026, removed the opening handshake and sessions. One request comes in and one answer goes out. That makes a small read-only server a modest piece of work: accept a POST, check that the headers match the body, run the function, return the text."}]},{"type":"p","children":[{"type":"text","text":"Offer lookups there and keep page actions out. There is no page to act on."}]},{"type":"h2","children":[{"type":"text","text":"Step 8: Go live and count calls"}]},{"type":"p","children":[{"type":"text","text":"Join Chrome's origin trial so the feature is on for your visitors, and count tool calls by name so you learn what agents ask for."}]},{"type":"ul","items":[[{"type":"strong","children":[{"type":"text","text":"Join the origin trial."}]},{"type":"text","text":" Without it, only people who switch the flag on get your tools."}],[{"type":"strong","children":[{"type":"text","text":"Count calls by tool name."}]},{"type":"text","text":" Do not record what was asked or answered."}],[{"type":"strong","children":[{"type":"text","text":"Tell agents the tools exist"}]},{"type":"text","text":" in whatever file you keep for them, such as "},{"type":"link","href":"/ai-glossary/llms-txt","children":[{"type":"text","text":"llms.txt"}]},{"type":"text","text":"."}],[{"type":"strong","children":[{"type":"text","text":"Give people a way to see the tools."}]},{"type":"text","text":" This site lists its own and lets anyone "},{"type":"link","href":"https://www.theglitch.ai/?view=machine&tab=tools","children":[{"type":"text","text":"run them by hand"}]},{"type":"text","text":"."}]]},{"type":"p","children":[{"type":"text","text":"Then watch what gets called, and write the next tool for the question people ask most."}]},{"type":"h2","children":[{"type":"text","text":"What mistakes should you avoid?"}]},{"type":"p","children":[{"type":"text","text":"The four most likely are the four this site made first. Its first version failed Chrome's guidance in these ways:"}]},{"type":"ul","items":[[{"type":"strong","children":[{"type":"text","text":"It threw errors."}]},{"type":"text","text":" The agent saw \"failed\" and nothing else. The fix is the "},{"type":"code","text":"try"},{"type":"text","text":" and "},{"type":"code","text":"catch"},{"type":"text","text":" in step 3."}],[{"type":"strong","children":[{"type":"text","text":"One answer ran to 2,284 characters."}]},{"type":"text","text":" A search returned too much. Now each tool ranks its results, cuts to fit and links to the rest."}],[{"type":"strong","children":[{"type":"text","text":"A description carried a caveat."}]},{"type":"text","text":" A description says what the tool is for. The caveat moved into the answer."}],[{"type":"strong","children":[{"type":"text","text":"A tool was called "},{"type":"code","text":"work_with_rabin"},{"type":"text","text":"."}]},{"type":"text","text":" That does not say what it does. It became "},{"type":"code","text":"get_rabin_profile"},{"type":"text","text":"."}]]}],"table":{"caption":"What this site's first version got wrong","head":["First try","What happened","The fix"],"rows":[["Threw an error on bad input","The agent saw only that it failed","Return the reason as text"],["Returned every match","One answer ran to 2,284 characters","Rank, cut to fit, link to the rest"],["Put a caveat in a description","Longer text, no clearer choice","Say the caveat in the answer"],["Named a tool work_with_rabin","The name did not say what it does","A verb first: get_rabin_profile"]]},"faq":[{"q":"How do I add WebMCP to my website?","a":"Write each tool as a plain function that takes input and returns text. Then, where the browser has document.modelContext, call registerTool with a name, a description, an input schema and that function. Check that the API exists first, because most browsers do not have it, and the page must work the same without it."},{"q":"How do I test WebMCP tools in Chrome?","a":"In Chrome 149 or later, switch on chrome://flags/#enable-webmcp-testing and restart. Open your page and the DevTools console, call document.modelContext.getTools() to list what the page registered, then executeTool with one of them and some input. Try bad input too and read what comes back."},{"q":"Why does my WebMCP tool only say it failed?","a":"When a tool's function throws, the browser passes the agent the name of the error and nothing else. The draft does this on purpose, so a site's internals stay private. Catch the error inside the tool and return a sentence that says what to fix, so the agent can correct its input and try again."},{"q":"How long can a WebMCP tool's answer be?","a":"Chrome's guidance, which it says may change, is about 1,500 characters per answer. It also suggests up to 30 characters for tool and parameter names, 500 for a tool's description and 150 for a parameter's. Rank your results, cut them to fit and end with a link to the page that holds the rest."},{"q":"Do I need an MCP server as well as WebMCP?","a":"Only if you want agents that never open a browser to use your tools, such as assistants and coding tools that connect over the network. If your tools are plain functions, the same code can serve both. Offer lookups on the server and keep actions that change the page in the page."},{"q":"Should a WebMCP tool be able to submit a form?","a":"Be careful with it. A tool that fills in a form and leaves the last click to the visitor is easy to defend. A tool that submits on its own can buy, book or send without anyone looking. Name a tool for what it really does, start with ones that only prepare a draft, and mark anything irreversible as consequential."}],"card":{"code":"LRN 36/38","rarity":"holo rare","type":"equip","name":"Labelled keys","image":"/images/cards/learn/webmcp-tutorial.webp?v=1bb6a6e395d1c041","share":"/images/cards/learn/webmcp-tutorial.jpg?v=1bb6a6e395d1c041","alt":"Labelled keys, a holo rare equip card for the guide “How to add WebMCP to your website: a step-by-step tutorial with code”: Pop-art key board with blank coloured tags: a hand hangs up one key while a small robot hand takes the tagged key beside it."},"partOf":{"id":"forward-deployed-engineer","title":"What is a forward deployed engineer? The ultimate guide to becoming one in 2027"},"fresh":[{"week":"2026-W47","title":"Gemini API adds Tool Retrieval to load tool schemas on demand","path":"/radar/2026-w47#story-wire-056cf0b58a3dbace6833","date":"2026-11-22"},{"week":"2026-W45","title":"Claude plugins can now auto-connect when users log in","path":"/radar/2026-w45#story-wire-1531bfded28896bda868","date":"2026-11-08"}]}
