JavascriptでのWebMCP(Imperative API)実装
webmcp-api.js では、JavaScriptを使用してレビューデータを抽出するWebMCPのツールを実装しています。
主な実装内容 (getProductReviews):
window.navigator.modelContext を使用して、モック環境を初期化しています。
getProductReviews
という名前のツールを定義し、ページ上の各レビュー項目(名前、評価、日付、コメントなど)のDOM操作を行い、AIが取得可能なJSON形式で返却する処理を実装しています。
- 作成したツールを
window.navigator.modelContext.registerTool()
を用いて登録し、外部のAIクライアントから呼び出せるようにしています。
JavaScriptでの実装例:
// ツールの定義
const getProductReviewsTool = {
name: "getProductReviews",
description: "Retrieve customer names, ratings, dates, and review comments from the product page.",
// 入出力スキーマ定義
inputSchema: {
type: "object",
properties: {
limit: {
type: "integer",
description: "The maximum number of reviews to return. Optional."
}
}
},
outputSchema: {
type: "object",
properties: {
content: {
type: "array",
items: {
type: "object",
properties: {
type: { type: "string" },
text: { type: "string" }
}
}
}
}
},
// 実行ロジック
execute: async function (params) {
// DOMからレビュー情報を取得
const reviews = [];
const reviewCards = document.querySelectorAll('.review-card');
// ... (抽出処理と整形) ...
return {
content: [{
type: "text",
text: JSON.stringify(reviews, null, 2)
}]
};
}
};
// ツールの登録
if (window.navigator.modelContext) {
window.navigator.modelContext.registerTool(getProductReviewsTool);
}