本项目是一个Chrome扩展,借助WebSocket连接在网页和本地MCP服务器之间搭建桥梁。这一设计让您能够从mcp服务器访问网页资源并执行函数,为网页操作带来更多便利。
受playcanvas/editor-mcp-server项目的启发而开发。
window.editor控制像 https://threejs.org/editor/ 这样的编辑器,就如同 playcanvas/editor-mcp-server 一样。git clone https://github.com/yourusername/chrome-extension-socket-mcp.git
cd chrome-extension-socket-mcp
npm install
运行以下命令以开发模式构建扩展:
npm run debug
chrome://extensions/。extension 文件夹。import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import { Client } from "../src/client";
// 定义 WebSocket 连接端口
// 该端口应与Chrome扩展中的WebSocket连接匹配
const port = 54319;
const client = new Client(port);
// 建立与Chrome扩展的连接
await client.connect();
// 创建一个新的MCP服务器实例,指定名称和版本
const server = new McpServer({
name: "Extension-Socket-Server",
version: "1.0.0",
});
// 注册一个工具,用于在浏览器中执行window.alert函数
// 这展示了如何从服务器访问浏览器API
server.tool(
"alert", // 工具名称
"调用浏览器中的 alert 函数",
{
description: "显示一条警报消息。",
params: []
},
async () => {
return true;
}
);
// 注册一个资源,用于获取用户代理字符串
server.resource(
"navigator.userAgent",
async () => {
return navigator.userAgent;
}
);
// 启动服务器以侦听连接
server.listen(port);
// 在网页中注入的脚本
const client = new Client();
// 调用资源获取用户代理字符串
client.getResource("navigator.userAgent").then(userAgent => {
console.log("User Agent:", userAgent);
});
// 调用工具执行 alert
client.tool("alert");
扩展使用简单的JSON-RPC协议:
请求:
{
"id": "唯一的请求标识符",
"method": "mcp:resource.navigator.userAgent",
"params": {}
}
响应:
{
"id": "唯一的请求标识符",
"result": "Mozilla/5.0 ..."
}
MIT