Puppeteer 中文文档v25.8.0

WebMCP

⚠️警告

WebMCP 是一个实验性 API,可能会发生变化。目前仅在 Chrome 151+ 中受支持,并且需要启用特定标志。

WebMCP 是一个实验性 API,允许页面注册可由浏览器或外部代理(如 LLM)发现和调用的工具。Puppeteer 提供了一个实验性 API,用于与启用了 WebMCP 的页面交互。

前提条件

要将 WebMCP 与 Puppeteer 一起使用,你需要:

  1. Chrome 151+:浏览器必须支持 WebMCP CDP 域。
  2. 启用标志:你必须使用以下标志启动浏览器:
    • --enable-features=WebMCP

启用 WebMCP

在 Puppeteer 中,WebMCP 支持可通过 page.webmcp 属性获得。如果浏览器支持,当你导航到页面时,它会自动初始化。

import puppeteer from 'puppeteer';

const browser = await puppeteer.launch({
  args: ['--enable-features=WebMCP'],
});
const page = await browser.newPage();

// page.webmcp is now available
console.log(page.webmcp);

发现工具

你可以使用 page.webmcp.tools() 获取页面上注册的所有工具列表。你还可以监听 toolsaddedtoolsremoved 事件,以响应已注册工具的变化。

// Get currently registered tools
const tools = page.webmcp.tools();
for (const tool of tools) {
  console.log(`Tool found: ${tool.name} - ${tool.description}`);
}

// Listen for new tools
page.webmcp.on('toolsadded', event => {
  for (const tool of event.tools) {
    console.log(`New tool added: ${tool.name}`);
  }
});

// Listen for removed tools
page.webmcp.on('toolsremoved', event => {
  for (const tool of event.tools) {
    console.log(`Tool removed: ${tool.name}`);
  }
});

执行工具

你可以使用 WebMCPTool 对象上的 execute 方法执行发现的工具。该方法返回一个 Promise,解析为该工具的结果。

const tools = page.webmcp.tools();
const tool = tools.find(t => t.name === 'calculate_sum');

if (tool) {
  const result = await tool.execute({a: 5, b: 10});
  if (result.status === 'Completed') {
    console.log('Result:', result.output);
  } else {
    console.log('Error:', result.errorText);
  }
}

处理工具调用

你可以观察工具何时被页面或浏览器调用,以及它何时响应。

page.webmcp.on('toolinvoked', call => {
  console.log(`Tool ${call.tool.name} was invoked with input:`, call.input);
});

page.webmcp.on('toolresponded', response => {
  console.log(
    `Tool ${response.call?.tool.name} responded with status: ${response.status}`,
  );
  if (response.status === 'Completed') {
    console.log('Output:', response.output);
  } else {
    console.log('Error:', response.errorText);
  }
});

在页面中注册工具

工具既可以通过 JavaScript 以命令式方式注册到页面中,也可以通过 HTML 表单以声明式方式注册。

命令式注册

await page.evaluate(async () => {
  await document.modelContext?.registerTool({
    name: 'calculate_sum',
    description: 'Calculates the sum of two numbers',
    inputSchema: {
      type: 'object',
      properties: {
        a: {type: 'number'},
        b: {type: 'number'},
      },
      required: ['a', 'b'],
    },
    execute: ({a, b}) => {
      return a + b;
    },
  });
});

声明式注册

WebMCP 还支持发现以带有特定属性的 HTML 表单定义的工具。

await page.setContent(`
  <form
    toolname="search_products"
    tooldescription="Search for products in the catalog"
  >
    <input name="query" type="text" />
    <button type="submit">Search</button>
  </form>
`);

当工具通过表单注册时,你可以使用 tool.formElement 访问相应的 ElementHandle

const tools = page.webmcp.tools();
const searchTool = tools.find(t => t.name === 'search_products');
const formHandle = await searchTool.formElement;