使用说明
webmcp工具包
使用Zod键入安全的WebMCP工具。
什么是WebMCP?
WebMCP 是一个浏览器API,允许网站向人工智能代理公开工具,由WebML工作组开发。
API添加 navigator.modelContext,哪些网站用于注册代理可以发现和调用的工具。把它想象成让你的网站功能可供人工智能助手使用。
当前规范公开了一个方法-- navigator.modelContext.registerTool(tool, { signal }) --通过中止来注销工具 AbortSignal 你在注册时通过了。webmcp工具包为您处理控制器生命周期。
主要浏览器开始尝试实现。
- 铬:
- WebMCP可提前预览
- WebMCP早期预览
- TLDR:下载Chrome Canary(146+),转到
about:flags并设置WebMCP for testing启用
webmcp工具包做什么?
webmcp-kit包装了原始webmcp API,使构建工具更容易:
- Zod模式:定义一次输入,获得JSON模式转换和TypeScript推理
- 内置验证:输入之前会根据您的模式进行验证
execute跑 - 减少样板:为您处理功能检测、响应格式化和注册
- 自动特征检测:当API存在时有效,当它不存在时优雅地后退
- 开发面板:在浏览器中测试和调试工具,而不需要真正的代理
import { defineTool } from 'webmcp-kit';
import { z } from 'zod';
const addToCart = defineTool({
name: 'addToCart',
description: 'Add a product to cart',
inputSchema: z.object({
productId: z.string(),
quantity: z.number().min(1),
}),
execute: async ({ productId, quantity }) => {
// productId and quantity are typed
return `Added ${quantity}x ${productId}`;
},
});
addToCart.register();
安装
npm install webmcp-kit zod
需要Zod v4。
安装和使用 add-webmcp-tools 技能
使用Vercel的Skills CLI从该存储库安装技能:
npx skills add victorhuangwq/webmcp-kit
然后用以下请求调用它:
- “添加webmcp搜索工具”
- “调试为什么我的工具不在开发面板中”
- “更新工具架构和验证”
参考文献
- 技能定义:
skills/add-webmcp-tools/SKILL.md - 工作演示:
用法
定义工具
import { defineTool } from 'webmcp-kit';
import { z } from 'zod';
const searchProducts = defineTool({
name: 'searchProducts',
title: 'Search Products', // optional human-friendly label
description: 'Search the product catalog',
inputSchema: z.object({
query: z.string().describe('Search query'),
limit: z.number().optional().default(10),
}),
execute: async ({ query, limit }) => {
const results = await db.products.search(query, limit);
return JSON.stringify(results);
},
});
searchProducts.register();
模式转换为WebMCP API的JSON模式。你的 execute 函数接收键入的输入。Zod验证失败的输入永远不会到达 execute --试剂盒返回验证错误响应。内部抛出异常 execute 被捕获并作为错误响应浮出水面(isError: true),因此单个工具爆炸不会导致页面崩溃。
注释
使用 annotations 提示工具行为,符合规范 ToolAnnotations:
defineTool({
name: 'searchProducts',
description: 'Search the product catalog',
inputSchema: z.object({ query: z.string() }),
annotations: {
readOnlyHint: true, // tool does not modify state
untrustedContentHint: true, // surfaces third-party content the model should treat as untrusted
},
execute: async ({ query }) => { /* ... */ },
});
仅设置 readOnlyHint: true 真正不改变状态的工具。对于敏感突变,通过在线提示确认 client.requestUserInteraction(...) (见下文)。
测试工具
直接调用工具而无需注册。输入会根据Zod模式进行验证,您总是会得到一个 ToolResponse:
const response = await searchProducts.execute({ query: 'shoes', limit: 5 });
// response: { content: [...], isError?: boolean }
在测试之间,使用 unregisterAll() 取消工具包管理的注册和 resetMockModelContext() (从 webmcp-kit)重置进程中的模拟注册表。
响应助手
import { textContent, jsonContent, errorContent } from 'webmcp-kit';
// String responses are auto-wrapped, but you can be explicit:
return textContent('Done');
return jsonContent({ status: 'ok' });
return errorContent('Something went wrong');
开发面板
没有真实代理的测试工具:
import { enableDevMode } from 'webmcp-kit/devtools';
enableDevMode();
// or with a custom position:
enableDevMode({ position: { bottom: 24, right: 24 } });
这将注入一个面板,其中列出了您的工具,从模式生成输入表单,并允许您执行它们。如果本地 navigator.modelContextTesting API可用(Chrome 146+EPP),面板使用;否则,它将退回到工具包的模拟注册表。
为了获得更多的控制, injectDevPanel(options?) 和 removeDevPanel() 也出口自 webmcp-kit/devtools.
直接测试工具
tool.execute(input, client?) 运行WebMCP API使用的相同验证+执行管道,因此单元测试不需要注册任何内容:
import { createMockClient } from 'webmcp-kit';
const result = await checkout.execute(
{ cartId: 'abc' },
createMockClient({
onUserInteraction: async () => ({ confirmed: true }),
})
);
expect(result.isError).toBeUndefined();
这 client 参数是可选的——省略它并使用默认的模拟客户端。
API
defineTool(options)
const tool = defineTool({
name: string,
title?: string,
description: string,
inputSchema: ZodSchema,
execute: (input, client) => Promise<string | ToolResponse>,
annotations?: ToolAnnotations,
});
tool.register(); // Add to navigator.modelContext (mints an AbortController internally)
tool.unregister(); // Aborts the signal — removes the tool
tool.execute(input); // Validates input, returns Promise<ToolResponse> — useful in unit tests
tool.schema; // The original Zod schema (readonly)
execute 可以返回a string (自动包装通过 textContent)或一个完整的 ToolResponse 当您需要多内容输出或 isError: true.
annotations 接受WebMCP规范中的两个提示:
readOnlyHint--该工具不会修改外部状态。untrustedContentHint--该工具可能会向模型展示不可信的第三方内容。
在内部, tool.register() 电话 navigator.modelContext.registerTool(tool, { signal }) 拥有一个工具包 AbortController. tool.unregister() 中止它。您不需要自己管理控制器。
unregisterAll() / getRegisteredTools()
该套件跟踪您通过注册的每个工具 defineTool().register() 在整个过程中。这对于HMR、SPA路线拆卸和测试清理非常方便:
import { unregisterAll, getRegisteredTools } from 'webmcp-kit';
// e.g. on Vite HMR dispose
if (import.meta.hot) {
import.meta.hot.dispose(() => unregisterAll());
}
console.log(getRegisteredTools().map((t) => t.name));
enableDevMode()
import { enableDevMode } from 'webmcp-kit/devtools';
enableDevMode();
// or, with custom positioning:
enableDevMode({ position: { bottom: 16, right: 16 } });
webmcp-kit/devtools 也出口 injectDevPanel(options?) 和 removeDevPanel() 如果你想明确控制面板的装载和卸载时间。 injectDevPanel 返回一个清理函数。
运作原理
defineTool() 创建工具对象。当你打电话的时候 .register():
- 它薄荷味清新
AbortController对于此次注册。 - 它检查
isWebMCPSupported()(即是否navigator.modelContext存在)。 - 如果是,它会呼叫
navigator.modelContext.registerTool(tool, { signal })根据该控制器的信号。 - 如果没有,它会在内部模拟中注册,这样开发面板仍然可以工作。
- 它将该工具添加到工具包的全流程注册跟踪器中(由
unregisterAll()/getRegisteredTools()).
.unregister() 只需中止控制器-本地API和模拟侦听该信号,因此该工具从其注册的任何位置都会消失。跟踪器通过中止侦听器解除自身跟踪,因此即使信号从其他地方发出,它也会保持同步。
你的代码不会根据环境而改变。当浏览器提供WebMCP支持时,相同的代码将使用真正的API。 isWebMCPSupported() 如果您想自己在本机API上门控行为,也会导出。
如果你需要在功能上屏蔽UI, isWebMCPSupported() 和 isBrowser() 从以下来源导出 webmcp-kit.
例子
examples/pizza-shop:使用多种工具的披萨订购流程(getMenu,addToCart,getCart,clearCart,checkout).examples/flight-booking:多步骤航班购买流程(searchFlights,selectFlight,addTraveler,addExtras,reviewBooking,purchaseFlight).
这两个示例都包括使用本机WebMCP和模拟模式进行测试的设置说明。
支持
如果你觉得webmcp工具包有用:
- 标记回购:它帮助其他人发现项目
- 报告问题:发现错误或有功能请求? 打开一个问题
许可证
麻省理工学院
