WebMCP 還在實驗階段,最常見的第一個錯誤就是:
console.log(document.modelContext)
// undefined
如果你看到 undefined,先不要開始懷疑 registerTool() 寫錯。這一篇會先建立最小環境檢查流程,確認瀏覽器支援、Origin Trial/實驗功能、安全來源與 API 名稱。
WebMCP 早期討論與舊文章中可能會看到:
navigator.modelContext
但目前 Chrome 文件已改以:
document.modelContext
為主。
所以第一個測試非常簡單:
if ('modelContext' in document) {
console.log('WebMCP available', document.modelContext);
} else {
console.warn('WebMCP is not available in this browser/context.');
}
先不要上 React、Laravel、WordPress。
建立:
webmcp-lab/
├── index.html
└── app.js
index.html:
<!doctype html>
<html lang="zh-Hant">
<head>
<meta charset="utf-8">
<title>WebMCP Lab</title>
</head>
<body>
<h1>WebMCP Lab</h1>
<pre id="status"></pre>
<script type="module" src="./app.js"></script>
</body>
</html>
app.js:
const status = document.querySelector('#status');
const info = {
modelContext: 'modelContext' in document,
protocol: location.protocol,
origin: location.origin,
userAgent: navigator.userAgent,
};
status.textContent = JSON.stringify(info, null, 2);
console.table(info);
雙擊 index.html 很方便,但實驗 Web API 時最好從本機 Server 開始。
例如:
python3 -m http.server 8080
然後開:
http://localhost:8080
localhost 在很多 Web Platform 安全情境中會被視為可信開發來源,比直接用 file:// 更接近真實網站行為。
Chrome WebMCP 文件目前仍標示為 Origin Trial/Intent to Experiment。實際啟用方式可能隨 Chrome 版本與 Trial 階段改變,所以不要把某一版的 Flag 名稱硬寫死成永久步驟。
我會建議每次測試都確認:
document.modelContext 是否真的存在。重點是:以 API feature detection 為準,不要只相信自己「應該已經打開 Flag」。
navigator.modelContext // 舊資料可能出現
目前系列統一:
document.modelContext
API 還在快速變動,Stable/Beta/Canary 狀態可能不同。
有些實驗功能不是打開一個設定就結束,部署到公開站時可能需要對應 Token。
如果 WordPress Theme、Vite、CSP、快取、Minify 全部混在一起,第一個錯很難找。
所以先用最小 HTML 驗證 API。
你不能:
npm install webmcp
然後就假設瀏覽器原生 document.modelContext 一定存在。官方 WebMCP 是瀏覽器能力,npm package 最多提供 typings、framework helper 或 polyfill 類輔助,不能把瀏覽器實作本身變出來。
每個 Demo 都先包一層檢查:
function assertWebMCP() {
if (!document.modelContext) {
throw new Error(
'WebMCP is unavailable. Check Chrome version / origin trial / experimental settings.'
);
}
}
至少錯誤會比:
Cannot read properties of undefined
有意義很多。
[ ] 使用目前支援 WebMCP 的 Chrome 環境
[ ] 用 http://localhost 而不是 file:// 測試
[ ] document.modelContext 存在
[ ] DevTools Console 沒有 API undefined
[ ] 知道目前功能仍屬實驗性
document.modelContext 為主,不要照抄舊版 API。