Search K
Appearance
Appearance
WebMCP(Web Model Context Protocol)是 Chrome 浏览器内置的一套新 API,允许网页向浏览器注册工具(Tools),然后外部 AI 智能体(如 Claude、ChatGPT、本地 Agent 等)可以通过 Chrome DevTools Protocol 远程调用这些工具,实现 网页与 AI 的双向通信。
核心 API 挂载在 navigator.modelContext 上。
registerTool() navigator.modelContext.registerTool({
name: "my_tool", // 工具名(唯一标识)
description: "工具描述(给 AI 看)", // AI 根据描述决定何时调用
inputSchema: { // JSON Schema 定义输入参数
type: "object",
properties: {
query: { type: "string", description: "搜索关键词" }
},
required: ["query"]
},
execute: async (args) => { // AI 调用时执行的函数
// args 是 JSON 字符串,需手动 parse
const { query } = JSON.parse(args)
return { result: `你搜的是: ${query}` }
}
})getTools() const tools = await navigator.modelContext.getTools()
// [{ name: "my_tool", description: "...", inputSchema: "...", ... }]executeTool() const tools = await navigator.modelContext.getTools()
const tool = tools[0]
// ⚠️ 第二个参数必须是 JSON 字符串,不能直接传 JS 对象
const result = await navigator.modelContext.executeTool(tool, '{"query":"hello"}')以下是一个完整的 Vue 3 组件示例,直接在 Markdown 中嵌入:
<script setup>
import { ref, onMounted } from 'vue'
const statusMessage = ref('等待 AI 连接...')
onMounted(() => {
if (navigator.modelContext) {
navigator.modelContext.registerTool({
name: "fetch_vitepress_info",
description: "抓取当前 VitePress 文章的作者、环境和状态",
inputSchema: {
type: "object",
properties: {}
},
execute: async () => {
statusMessage.value = 'AI 正在读取页面数据!'
return {
framework: "VitePress (Vue 3 Inside)",
author: "极客站长",
page_url: window.location.href,
timestamp: new Date().toLocaleString()
}
}
})
}
})
</script>
<template>
<div>
<p>{{ statusMessage }}</p>
</div>
</template>executeTool 参数必须是 JSON 字符串 // ❌ 错误:直接传 JS 对象会报 "Failed to parse input arguments"
await mc.executeTool(tool, {})
await mc.executeTool(tool, { query: "hello" })
// ✅ 正确:传 JSON 字符串
await mc.executeTool(tool, '{}')
await mc.executeTool(tool, '{"query":"hello"}')getTools() 返回的 inputSchema 是字符串 const tools = await navigator.modelContext.getTools()
typeof tools[0].inputSchema // "string",不是 object目前 WebMCP 可能还需要在 chrome://flags 中开启相关实验性功能(如 #model-context-api 或类似 flag)。
┌──────────────┐ registerTool() ┌──────────────────┐
│ 网页 (JS) │ ───────────────────▶ │ Chrome 浏览器 │
│ VitePress │ │ navigator. │
│ Vue 3 │ │ modelContext │
└──────────────┘ └────────┬─────────┘
│ CDP / DevTools
▼
┌──────────────────┐
│ 外部 AI 智能体 │
│ (Claude/GPT/ │
│ 本地 Agent) │
└──────────────────┘registerTool() 注册工具到 ChromeApplication → WebMCP 面板展示已注册的工具传统上,AI 和网页的交互是单向的——AI 只能"看"网页内容。WebMCP 让网页可以主动向 AI 暴露可调用的能力,实现:
这是 Web 从"给人看"走向"给 AI 用"的关键一步。