WebMCP 讓網頁把一組工具交給 AI 代理:也就是具名函式,附帶描述與其輸入的 JSON Schema,註冊在 document.modelContext 上。一個有四個工具的待辦頁面,大約 95 行純 JavaScript,就足以涵蓋整個 API:命令式工具、唯讀註記、錯誤路徑,以及宣告式表單工具。
這裡的每項檢查都不需要模型或 API 金鑰。tsc 會透過 webmcp-types 檢查每個工具的處理器是否符合自己的 schema。無頭 Chrome 測試會透過 puppeteer 呼叫全部四個工具,並通過 4 項測試。Google 的 webmcp-evals smoke runner 通過 5/5 個腳本化工具呼叫。make demo 會開啟一個 Chrome 視窗,並啟用 WebMCP 與裝置端工具呼叫,且載入代理擴充功能。
接著由模型驅動這個頁面。透過 Google 的 webmcp-extension 代理與 gemini-3.6-flash,4 個白話英文請求各執行 5 次,在 20/20 次對話中都做出了所有預期的工具呼叫;而對「還有多少專案未完成?」的 5 個答案,也都引用了頁面計算出的數字。在每個權限提示都被拒絕的情況下,沒有任何寫入到達頁面,但唯讀工具仍然可以執行。
本文將一步一步說明如何在 Chrome 158 中建立、驗證與測試一個最小的 WebMCP 頁面,並使用 Chrome WebMCP 團隊釋出的三個工具:webmcp-types、webmcp-extension 與 webmcp-tools 中的 evals。
https://github.com/xbill9/webmcp-mvp
透過 puppeteer 讀取時,Chrome 回報工具的方式與頁面寫入的不同。 頁面設定的是 readOnlyHint: true;工具回傳時變成 readOnly: true。回傳 JSON 文字的處理器,回傳時 output 已經被解析成物件。拋出例外的處理器,回傳時 status: "Error"、errorText 為空字串,而訊息則在 exception.description 中。
品牌版 Chrome 158 會忽略 --load-extension。 用它啟動時,Chrome 沒有啟動任何擴充功能。透過 puppeteer 的 enableExtensions 載入時,代理擴充功能的 service worker 才有啟動。
Chrome 旗標可以隨設定檔一起部署。 把 enable-webmcp-testing 和 prompt-api-tool-use 寫入一個新設定檔的 Local State 檔案,就能開啟 WebMCP 與 AIPromptAPIToolUse,效果和在 chrome://flags 裡點選相同。
代理依照工具描述所要求的方式使用了這些工具。 它用 add_todo 新增專案,從結果中讀出每個新 id,完成正確的那一項,並用 list_todos 與 status: "open" 回答計數問題。
readOnlyHint 決定代理可以在未請求下執行哪些工具。 在每個權限提示都回答「拒絕」的情況下,add_todo 與 complete_todo 在 3 次執行中都沒有到達頁面,而 list_todos 執行了 4 次。
webmcp-types 0.2.1 只會為命令式 API 提供型別。 Schema 推斷可用:若某個處理器從宣告 id 的 schema 中讀取 idx,型別檢查就會失敗。宣告式表單 API 的 SubmitEvent.agentInvoked 與 respondWith 需要一個三行的宣告檔。
status: "all" 來計數,卻把結果稱作「open」。unavailable,所以代理改用擴充功能伺服器上的 Gemini。gh,用來抓取代理擴充功能gh repo clone xbill9/webmcp-mvp ~/webmcp
cd ~/webmcp
make install # puppeteer-core, typescript, webmcp-types, webmcp-evals, oxlint
make extension # once: clones GoogleChromeLabs/webmcp-extension at f5681de and builds it
本文實際使用的版本:
Google Chrome 158.0.8127.88
node v26.9.0
puppeteer-core 25.19.0
typescript 5.9.3
webmcp-types 0.2.1
webmcp-evals 0.1.1
oxlint 1.95.0
webmcp-extension commit f5681debc5203dc50872f6364f77ca3ad8718e24
這個頁面用 JavaScript 註冊三個工具,並在 HTML 中宣告第四個工具。list_todos 會在頁面內過濾,並與專案一起回傳精確數量,而它的描述會告訴代理要引用那個數字:
document.modelContext.registerTool({
name: "list_todos",
description:
"Lists to-do items. Filter with status; the response includes the exact count, so never count items yourself.",
inputSchema: {
type: "object",
properties: {
status: { type: "string", enum: ["all", "open", "done"], description: "Which items to return. Default all." },
},
},
annotations: { readOnlyHint: true },
execute: async ({ status = "all" }) => {
const items = todos.filter((t) => status === "all" || (status === "done") === t.done);
return JSON.stringify({ status, count: items.length, items });
},
});
add_todo 與 complete_todo 也採用相同模式;complete_todo 會在找不到 id 時拋出例外。表單工具則是頁面自己的表單,具備三個屬性:
<form id="add-form" toolname="add_todo_form"
tooldescription="Adds a to-do item through the page's form.">
<label for="title">Title</label>
<input id="title" name="title" required
toolparamdescription="Text of the to-do item.">
<button>Add</button>
</form>
人類與代理都透過同一個處理器提交它。當 e.agentInvoked 為 true 時,處理器會透過 e.respondWith(...) 回應代理。
make demo
node test/demo.mjs
Page: http://localhost:8137/ (4 WebMCP tools)
Extension: loaded from /home/xbill/webmcp-extension/dist
Close the Chrome window to stop.
這個視窗使用自己獨立的設定檔,位於 ~/.cache/webmcp-demo,因此日常使用的 Chrome 設定檔會保留原本設定。當 document.modelContext 存在時,頁面橫幅會變成綠色。
在 demo 視窗中按 F12,開啟 Application → WebMCP。Available tools 會列出四個工具。選擇 add_todo,輸入 {"title": "milk"} 並點擊 Run tool:頁面上會出現 "#1 milk",而 Invoked tools 會記錄輸入、輸出與狀態。
| 工具 | 輸入 | 頁面上的結果 |
|---|---|---|
add_todo |
{"title": "milk"} |
出現 "#1 milk" |
complete_todo |
{"id": 1} |
milk 被劃掉 |
list_todos |
{"status": "done"} |
回傳 "count":1 |
complete_todo |
{"id": 99} |
錯誤:"No to-do with id 99" |
add_todo_form |
{"title": "bread"} |
表單會自動填入並等待按下 Add |
public/app.js 以 // @ts-check 開頭,並參考 webmcp-types,因此 tsc 不需要建置步驟就能檢查它:
{
"compilerOptions": {
"lib": ["ES2022", "DOM"],
"types": ["webmcp-types"],
"allowJs": true,
"checkJs": true,
"noEmit": true,
"strict": true
},
"include": ["public/**/*.js", "public/**/*.d.ts"]
}
webmcp-types 會從內嵌的 inputSchema 推斷每個處理器的參數。若複製一份頁面,並讓 complete_todo 的處理器讀取 idx,型別檢查就會失敗:
public/app.js(87,23): error TS2339: Property 'idx' does not exist on type '{ id: number; }'.
public/app.js(88,47): error TS2304: Cannot find name 'id'.
public/app.js(89,54): error TS2304: Cannot find name 'id'.
tsc exit 2
表單工具的兩個 SubmitEvent 成員來自 public/declarative.d.ts:
interface SubmitEvent {
readonly agentInvoked?: boolean;
respondWith?(result: Promise<unknown>): void;
}
puppeteer-core 25 會把頁面工具暴露為 page.webmcp.tools(),每個工具都有 execute() 方法。Chrome 需要 --enable-features=WebMCP:
browser = await puppeteer.launch({
executablePath: CHROME,
headless: true,
args: ["--enable-features=WebMCP"],
});
測試會檢查工具列表、唯讀註記、一次新增-完成-篩選的往返流程與頁面中的精確計數及劃線專案,以及未知 id 的錯誤:
make test
✔ page registers the three imperative tools and the form tool (301.283997ms)
✔ list_todos is annotated read-only (0.381584ms)
✔ add, complete and filter round-trip with exact counts (22.129657ms)
✔ complete_todo reports an error for an unknown id (1.261671ms)
ℹ tests 4
ℹ suites 0
ℹ pass 4
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 618.089012
webmcp-evals 會把測試案例讀成一則使用者訊息,以及它應該產生的工具呼叫。它的 smoke 指令會略過模型,直接在真實頁面上按順序執行那些呼叫,因此同一份檔案之後也能驅動模型執行:
{
"name": "Add then complete",
"messages": [{ "role": "user", "type": "message", "content": "Add eggs and tick it off." }],
"expectedCall": [
{ "functionName": "add_todo", "arguments": { "title": "eggs" } },
{ "functionName": "complete_todo", "arguments": { "id": 1 } }
]
}
make smoke 會在自己的空閒埠上提供頁面,並執行三個案例:
Smoke Test Summary for http://localhost:40061/
┌───────────────────┬──────┬────────┬───────────────┬───────┐
│ Case │ Step │ Status │ Tool │ Error │
├───────────────────┼──────┼────────┼───────────────┼───────┤
│ Add then list │ 1 │ PASS │ add_todo │ - │
├───────────────────┼──────┼────────┼───────────────┼───────┤
│ Add then list │ 2 │ PASS │ list_todos │ - │
├───────────────────┼──────┼────────┼───────────────┼───────┤
│ Add then complete │ 1 │ PASS │ add_todo │ - │
├───────────────────┼──────┼────────┼───────────────┼───────┤
│ Add then complete │ 2 │ PASS │ complete_todo │ - │
├───────────────────┼──────┼────────┼───────────────┼───────┤
│ Use the form │ 1 │ PASS │ add_todo_form │ - │
└───────────────────┴──────┴────────┴───────────────┴───────┘
Passed steps: 5/5 across 3 case(s).
make check 會一起執行 lint、型別檢查、測試與 smoke test。
webmcp-extension 會把代理放到 Chrome 側邊欄。它會讀取頁面的工具、把對話送到模型,並執行模型呼叫的工具。它可以透過 Prompt API 使用 Chrome 的裝置端模型,或透過一個小型本機伺服器使用雲端模型。在這台機器上,裝置端模型不可用:
node docs/webmcp-mvp/evidence/check-ondevice.mjs
headless=true LanguageModel.availability(): unavailable
headless=false LanguageModel.availability(): unavailable
所以擴充功能伺服器改用 Gemini 回應。把金鑰放到 ~/webmcp-extension/.env,格式為 GEMINI_API_KEY=,然後啟動它:
cd ~/webmcp-extension && npm run server
🤖 Answering with google:gemini-3.6-flash
🚀 Backend model server listening on http://127.0.0.1:3100
同一個 .env 裡的 PORT=3100 會把伺服器從 3000 埠移到其他埠;接著 npm run build 會讓擴充功能指向它。
webmcp-evals browser --extension 會在無頭 Chrome 中驅動擴充功能的側邊欄:它會送出 evals/agent.json 中的每個請求、回應權限提示,並記錄代理在頁面上做出的每一次工具呼叫。make agent 會提供頁面並執行它:
RUNS=5 make agent
以下是 4 個請求,以及代理做了什麼,來自 agent-summary.py 對已儲存報告的彙整:
| 請求 | 每次執行是否都有所有預期呼叫 | 每次執行中代理做出的呼叫 |
|---|---|---|
| 幫我的清單加上牛奶。 | 5/5 | add_todo milk |
| 幫我的清單加上牛奶、蛋和麵包。 | 5/5 | add_todo ×3 |
| 幫我的清單加上牛奶和蛋,然後把蛋標記為已完成。 | 5/5 | add_todo ×2,complete_todo id 2 |
| 幫我的清單加上牛奶、蛋和麵包,把蛋標記為已完成,然後告訴我還有多少專案未完成。 | 5/5 | add_todo ×3,complete_todo id 2,list_todos open |
calls by tool, all runs: {'add_todo': 45, 'complete_todo': 10, 'list_todos': 5}
list_todos status sent: {'open': 5}
每一次計數答案都引用了工具回傳的數字:
answer: 'I have added milk, eggs, and bread to your to-do list, and marked eggs as done.\n\nThere are currently 2 items still open (milk and bread).'
count in answer: [2] | count list_todos returned: 2 | match: True
代理從未選擇 add_todo_form:因為命令式工具會回傳新的 id,而這正是 complete_todo 所需要的。
同一個計數請求,在 CONFIRM=deny 下執行 3 次,可以看出 readOnlyHint 的作用。擴充功能會在每個沒有它的工具之前詢問,所以所有寫入都被拒絕,而 list_todos 則在不詢問的情況下執行:
== Count what is open: 0 of 3 runs passed every required call
run 1: 2 calls, 3 turns: list_todos({"status":"open"}) -> list_todos({"status":"all"})
run 2: 1 calls, 2 turns: list_todos({"status":"all"})
answer: 'I tried to add "milk", "eggs", and "bread" to your to-do list, but the action was denied.\n\nAs a result, no items were added, and there are currently 0 open items in the list.'
run 3: 1 calls, 2 turns: list_todos({"status":"open"})
在第 2 次執行中,代理要求所有專案,卻把結果當成 open 的數量來回報。清單是空的,所以這個數字只是碰巧正確。
如果想手動試試看,請開啟步驟 3 的 demo 視窗,點擊拼圖圖示,接著點 WebMCP Extension、Got it,然後在側邊欄輸入請求。
node docs/webmcp-mvp/evidence/check-results.mjs
tools: add_todo, add_todo_form, complete_todo, list_todos
list_todos annotations: {"readOnly":true,"untrustedContent":false,"consequential":false,"debugging":false}
add_todo status: Completed | typeof output: object | output: {"id":1,"title":"milk","done":false}
complete_todo(999) status: Error | errorText: "" | exception.description: "Error: No to-do with id 999"
若測試去檢查 annotations.readOnlyHint、呼叫 JSON.parse(output) 或比對 errorText,在 Chrome 158 上都會失敗。請改讀 readOnly、接受物件,並從 exception.description 取錯誤訊息。
chrome://flags 會把選項存到設定檔的 Local State 檔案。若在 Chrome 第一次啟動前先寫入,視窗就會帶著這些旗標啟動:
writeFileSync(join(PROFILE, "Local State"), JSON.stringify({
browser: { enabled_labs_experiments: ["enable-webmcp-testing@1", "prompt-api-tool-use@1"] },
}));
flag switches: --flag-switches-begin --enable-features=PdfOopif,AIApiFoundationalModel:model_version/v4,AIPromptAPIToolUse,OnDeviceModelConversationBackend --enable-features=PdfOopif,AIApiFoundationalModel:model_version/v4,AIPromptAPIToolUse,OnDeviceModelConversationBackend,WebMCP --flag-switches-end
typeof document.modelContext: object
擴充功能是透過 puppeteer 載入,而這需要 pipe: true:
--load-extension: extension targets = []
enableExtensions: extension targets = ["service_worker"]
list_todos 回傳的是頁面內計算出的 count,而它的描述會告訴代理要引用這個數字。由程式碼完成的篩選與計數,會給代理一個精確可重複的數值。在 5 次允許的執行中,代理都送出 status: "open",並引用回傳的 2。檢查代理答案時,除了它引用的數字,也要看它送出的篩選條件:在一次被拒絕的執行裡,它送出 status: "all",卻把結果稱為 open count——那是對錯誤集合而言剛好正確的精確數字。
| 檢查專案 | 需要模型或金鑰 | 需要視窗 | 涵蓋內容 |
|---|---|---|---|
make typecheck |
否 🥇 | 否 | 每個處理器是否符合其 schema |
make test |
否 🥇 | 否 | 發現、結果、計數、錯誤、頁面狀態 |
make smoke |
否 🥇 | 否 | 來自 eval 檔案、依順序執行的腳本化呼叫 |
| DevTools WebMCP 面板 | 否 | 是 | 一次一個呼叫,手動執行 |
make agent |
需要金鑰或裝置端模型 | 否 | 模型是否選對工具與參數 |
webmcp-extension 側邊欄 |
需要金鑰或裝置端模型 | 是 | 同樣的流程,但由手動輸入 |
每次改動都先跑 make check:它除了 Chrome 與 Node 之外不需要任何東西,卻能涵蓋工具合約。撰寫工具時使用 DevTools 面板。當問題變成「模型是否按照你想要的方式理解描述」時,就跑 make agent:同一種 eval 格式可以直接驅動它,而報告會顯示模型送出的參數。把提示拒絕一次,確認代理在不詢問的情況下能執行哪些工具。
本文的目標,是建立一個最小化的 WebMCP 頁面:它可以在不需要模型的情況下完成設定、驗證與測試,接著再交給代理。解法的關鍵是透過 Chrome 本身來測試工具:webmcp-types 用於 schema、puppeteer 的 page.webmcp 用於呼叫、webmcp-evals smoke 用於腳本化案例,以及 webmcp-evals browser --extension 用於代理。結果如下:
webmcp-types 的 tsc 抓到了處理器讀取 schema 未宣告欄位的錯誤。make demo 會開啟已可使用 WebMCP、裝置端工具呼叫與代理擴充功能的 Chrome。webmcp-types 0.2.1 需要一個宣告檔來支援表單 API。webmcp-extension 與 gemini-3.6-flash,20/20 次對話都做出了所有預期的工具呼叫。list_todos 回傳的數字。list_todos 仍然能執行。status: "all" 來計數,卻把它叫做 open count。unavailable。範圍:一台 Linux 機器,在 2026-11-29 上,Chrome 158.0.8127.88 stable、Node 26.9.0、puppeteer-core 25.19.0、webmcp-types 0.2.1、webmcp-evals 0.1.1,以及位於 commit f5681de 的 webmcp-extension,且步驟 5 到 7 的檢查各執行一次。代理透過 webmcp-evals browser --extension 在無頭模式下運作,使用擴充功能伺服器提供的 google:gemini-3.6-flash:4 個請求各執行 5 次且提示允許,以及計數請求在提示拒絕下執行 3 次,每次對話都在全新的頁面上。單一機器上的單一模型、20 次提示允許的對話與 3 次提示拒絕的對話,展示了該模型如何使用這些工具;其他模型可能會做出不同選擇。WebMCP 從 Chrome 149 起就受旗標與 origin trial 保護,且仍是提案中的網頁標準,因此上述結果格式可能會隨 Chrome 版本而改變。
透過漸進式、一步一步的方法來建置與測試 WebMCP 工具、且不依賴模型的策略,已經獲得驗證。
原文出處:https://dev.to/gde/a-minimal-webmcp-demo-in-chrome-typed-tested-headless-and-driven-by-an-agent-109e