# web-debug-mcp **Repository Path**: codelint/web-debug-mcp ## Basic Information - **Project Name**: web-debug-mcp - **Description**: 用来debug页面的mcp服务 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-01-05 - **Last Updated**: 2026-05-14 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # Web Debug MCP Server 一个独立的 MCP(Model Context Protocol)服务器,使用 Playwright 进行网页调试。 ## 功能特性 - **navigate**: 导航到新URL(唯一可以重置/改变当前页面的工具) - **fetch_page**: 获取并解析当前页面,返回 HTML 内容、标题和元数据 - **screenshot**: 截取当前页面截图(视口或整页) - **query_dom**: 使用 CSS 选择器或 XPath 查询当前页面的 DOM 元素 - **execute_js**: 在当前页面上执行 JavaScript 代码 - **click**: 使用 CSS 选择器或 XPath 点击当前页面上的元素 - **wait_for**: 等待当前页面上的元素出现或变为可见 - **page_monitor**: 统一页面监控接口 - 网络请求、控制台日志、错误监控和性能指标一体化工具 - **keyboard_action**: 执行键盘操作(单键、组合键、文本输入) - **keyboard_shortcut**: 执行常用键盘快捷键 - **headers 支持**: navigate 工具支持自定义 HTTP headers(如 Authorization) - **cookies 支持**: navigate 工具支持设置 cookies ## 目录结构 ``` web-debug-mcp/ ├── web-debug-cli.py # 主命令行入口(推荐使用) ├── mcp_config.ini # 配置文件 ├── README.md # 项目主文档 ├── requirements.txt # Python 依赖列表 ├── doc/ # 文档目录 │ ├── config-guide.md # 配置文件使用指南 │ ├── HowTo.md # 使用指南 │ ├── HowToTest.md # 测试指南 │ └── mcp.md # MCP 协议规范文档 ├── console/ # CLI 命令实现 │ ├── Kernel.py │ ├── Command.py │ └── Commands/ │ ├── Serve.py # serve 命令(启动/停止/重启) │ └── Stdio.py # stdio 命令 └── src/ # 源代码目录 └── python/ # Python 源代码 ├── server.py # MCP 服务器主入口 ├── mcp_server.py # MCP 服务器核心实现 ├── http_handler.py # HTTP 请求处理器 ├── stdio_handler.py # stdio 通信处理器 ├── config_loader.py # 配置加载器 ├── error_response.py # 错误响应构建器 ├── page_network.py # 网络请求监控 ├── page_log.py # 控制台日志监控 └── page_errors.py # 错误监控 ``` **代码组织原则:** - 每个类都有独立的文件,遵循单一职责原则 - 错误处理统一通过 ErrorResponseBuilder 类 - HTTP 和 stdio 传输模式分离到不同的处理器类 - 核心业务逻辑集中在 mcp_server.py 中 **MCP 协议规范:** 关于 MCP 协议的详细规范、JSON-RPC 2.0 规范、传输模式和错误处理等内容,请参阅 [doc/mcp.md](doc/mcp.md) 文档。 ## 安装 1. 创建虚拟环境: ```bash cd web-debug-mcp python3 -m venv venv source venv/bin/activate ``` 2. 安装依赖: ```bash pip install -r requirements.txt playwright install chromium ``` ## 使用方法 ### 启动服务器 使用 `web-debug-cli.py` 管理服务(推荐): ```bash # 启动服务(HTTP 模式,端口 8082) ./web-debug-cli.py serve start # 指定端口 ./web-debug-cli.py serve start --port 9000 # 显示浏览器窗口(非无头模式) ./web-debug-cli.py serve start --headless # 启用调试模式(自动启动网络/日志/错误监控并禁止缓存) ./web-debug-cli.py serve start --debug-mode # 指定配置文件 ./web-debug-cli.py serve start --config my_config.ini # 列出所有可用工具 ./web-debug-cli.py serve list-tools ``` 其他服务管理命令: ```bash # 停止服务 ./web-debug-cli.py serve stop # 重启服务 ./web-debug-cli.py serve restart # 查看服务状态 ./web-debug-cli.py serve status ``` ### 验证服务器运行状态 ```bash curl http://127.0.0.1:8082/health ``` 预期响应: ```json { "status": "ok", "server": "web-debug-mcp", "version": "1.0.0" } ``` ## 在 Trae-IDE 中配置 ### 步骤 1:启动 MCP 服务器 在配置 Trae-IDE 之前,确保服务器正在运行: ```bash cd <项目目录> ./web-debug-cli.py serve start ``` 服务器将在 `http://127.0.0.1:8082` 上启动 ### 步骤 2:定位 Trae-IDE 配置文件 Trae-IDE 将 MCP 服务器配置存储在 JSON 文件中。配置文件位置取决于您的操作系统: - **macOS**: `~/Library/Application Support/Trae-IDE/mcp-servers.json` - **Linux**: `~/.config/Trae-IDE/mcp-servers.json` - **Windows**: `%APPDATA%\Trae-IDE\mcp-servers.json` 如果文件不存在,请创建它。 ### 步骤 3:添加服务器配置 打开配置文件并添加以下配置: ```json { "mcpServers": { "web-debug-mcp": { "url": "http://127.0.0.1:8082/mcp/tools/call", "transport": "http", "headers": { "Content-Type": "application/json" } } } } ``` **配置说明:** - `web-debug-mcp`: 此 MCP 服务器的唯一标识符 - `url`: MCP 服务器监听工具调用的端点 - `transport`: 传输协议(此服务器必须为 "http") - `headers`: 请求中包含的 HTTP 头 ### 步骤 4:重启 Trae-IDE 保存配置文件后,重启 Trae-IDE 以加载新的 MCP 服务器。 ### 步骤 5:验证连接 在 Trae-IDE 中,您可以通过以下方式验证连接: 1. 打开与 AI 的聊天会话 2. 要求 AI 使用网页调试工具,例如: ``` 帮我查看 https://example.com 的页面结构 ``` 3. AI 应该会自动使用 web-debug-mcp 服务器来获取页面 ### 可选:登录时自动启动服务器 要在登录时自动启动 MCP 服务器,请使用 `web-debug-cli.py`: **macOS:** 1. 打开系统设置 → 用户与群组 → 登录项 2. 点击 + 按钮并添加: ``` <项目目录>/web-debug-cli.py ``` 参数:`serve start` **Linux:** 添加到您的 `~/.bashrc` 或 `~/.zshrc`: ```bash if [ -z "$(pgrep -f 'python.*web-debug-mcp')" ]; then cd /path/to/web-debug-mcp ./web-debug-cli.py serve start fi ``` **注意:** 请将 `/path/to/web-debug-mcp` 替换为实际的项目目录路径。 ## 配置 MCP 客户端 对于其他 MCP 客户端,添加到您的配置: ```json { "mcpServers": { "web-debug-mcp": { "url": "http://127.0.0.1:8082/mcp/tools/call", "transport": "http", "headers": { "Content-Type": "application/json" } } } } ``` ## 可用工具 ### navigate 导航到新URL。这是唯一可以重置/更改当前页面的工具。 **参数:** - `url`(必需):要导航到的URL - `headers`(可选):自定义HTTP头,默认为 `{}` - `cookies`(可选):要设置的cookies(如 `{"name": "value"}`),默认为 `{}` - `timeout`(可选):超时时间,单位毫秒(默认:30000) - `wait_after_load`(可选):页面加载后等待的额外时间(毫秒,默认:3000) **返回:** - `url`: 请求的URL - `current_url`: 实际导航到的URL(可能因重定向而不同) - `title`: 页面标题 - `status`: 'success' 或 'error' ### fetch_page 获取并解析当前页面内容。 **参数:** - 无(此工具在当前页面上运行,不需要URL参数) **返回:** - `url`: 当前页面URL - `title`: 页面标题 - `html`: HTML内容 - `status`: 'success' 或 'error' ### screenshot 截取当前页面截图。 **参数:** - `full_page`(可选):是否截取整页(默认:false) - `width`(可选):视口宽度,单位像素(默认:1280) - `height`(可选):视口高度,单位像素(默认:720) **返回:** - `url`: 当前页面URL - `screenshot`: Base64 编码的 PNG 图片 - `format`: 图片格式('png') - `width`: 图片宽度(实际使用的宽度,可能因最大分辨率限制而调整) - `height`: 图片高度(实际使用的高度,可能因最大分辨率限制而调整) - `full_page`: 是否为整页截图 - `status`: 'success' 或 'error' **最大分辨率限制:** 服务器启动时可以设置最大分辨率限制(默认:1440x960)。如果请求的 `width` 或 `height` 超过最大分辨率,系统会自动将其限制为最大分辨率。 示例: ```bash # 在配置文件中设置最大分辨率为 1920x1080 # mcp_config.ini 中添加: # max_resolution = 1920x1080 # 或使用命令行: # ./web-debug-cli.py serve start --max-resolution 1920x1080 # 请求 2560x1440 的截图,实际会被限制为 1920x1080 screenshot 工具调用:width=2560, height=1440 实际返回:width=1920, height=1080 ``` ### query_dom 使用 CSS 选择器或 XPath 查询当前页面的 DOM 元素。 **参数:** - `selector`(必需):CSS 选择器或 XPath 查询 - `selector_type`(可选):选择器类型 - 'css' 或 'xpath'(默认:'css') **返回:** - `url`: 当前页面URL - `selector`: 使用的选择器 - `selector_type`: 选择器类型 - `count`: 匹配元素的数量 - `elements`: 元素对象数组,包含: - `index`: 元素索引 - `text`: 元素文本内容 - `inner_html`: 元素内部 HTML - `outer_html`: 元素外部 HTML - `position`: 元素位置(x, y, width, height) - `status`: 'success' 或 'error' ### execute_js 在当前页面上执行 JavaScript 代码。 **参数:** - `code`(必需):要执行的 JavaScript 代码 - `timeout`(可选):超时时间,单位毫秒(默认:30000) **返回:** - `url`: 当前页面URL - `result`: 执行结果 - `status`: 'success' 或 'error' ### click 使用 CSS 选择器或 XPath 点击当前页面上的元素。 **参数:** - `selector`(必需):CSS 选择器或 XPath 的元素 - `selector_type`(可选):选择器类型 - 'css' 或 'xpath'(默认:'css') - `timeout`(可选):超时时间,单位毫秒(默认:30000) - `wait_for_navigation`(可选):点击后是否等待导航(默认:false) - `verify_before_click`(可选):点击前是否验证元素信息(默认:true) **返回:** - `url`: 当前页面URL - `selector`: 使用的选择器 - `selector_type`: 选择器类型 - `clicked`: 是否成功点击 - `element_info`: 元素信息(如果验证) - `status`: 'success' 或 'error' ### wait_for 等待元素出现或变为可见。 **参数:** - `selector`(必需):CSS 选择器或 XPath - `selector_type`(可选):选择器类型 - 'css' 或 'xpath'(默认:'css') - `timeout`(可选):超时时间,单位毫秒(默认:30000) - `state`(可选):等待状态 - 'attached'、'detached'、'visible'、'hidden'(默认:'visible') **返回:** - `url`: 当前页面URL - `selector`: 使用的选择器 - `selector_type`: 选择器类型 - `state`: 等待的状态 - `found`: 是否找到元素 - `status`: 'success' 或 'error' ### page_monitor 统一页面监控接口 - 网络请求、控制台日志、错误监控和性能指标一体化工具。 **支持的命令:** - `start`: 启动监控 - `stop`: 停止监控 - `pause`: 暂停监控 - `resume`: 恢复监控 - `get`: 获取监控数据 - `clear`: 清除监控数据 - `status`: 获取监控状态 - `config`: 更新监控配置 - `snapshot`: 创建监控数据快照 - `export`: 导出监控数据 - `mock`: 模拟请求响应 - `block`: 阻止请求 **监控类型:** - `network`: 网络请求监控 - `console`: 控制台日志监控 - `errors`: 错误监控 - `performance`: 性能指标监控 - `resources`: 资源监控 - `elements`: 元素监控 **参数:** - `command`(必需):要执行的监控命令,默认为 'get' - `monitors`(可选):要启用的监控类型数组,默认为 ['network', 'console', 'errors'] - `types`(可选):网络请求捕获类型数组,默认为 ['request', 'response', 'failed'] - `resourceTypes`(可选):资源类型数组,默认为 ['xhr', 'fetch', 'document', 'script'] - `captureBody`(可选):是否捕获请求体,默认为 false - `captureHeaders`(可选):是否捕获请求头,默认为 true - `filters`(可选):数据过滤器对象,支持按多种维度过滤监控数据 - `exportFormat`(可选):导出格式('json'、'har'、'csv'、'html'),默认为 'json' - `url`(可选):要模拟或阻止的请求 URL 模式 - `response`(可选):模拟响应数据(用于 mock 命令) **过滤功能:** 支持按以下维度过滤监控数据: 1. **时间范围过滤** (`timeRange`) - `start`: 开始时间(ISO 8601 格式,如 '2024-01-01T00:00:00Z') - `end`: 结束时间(ISO 8601 格式) - `last`: 相对时间范围(如 '5m' 表示最近5分钟,'1h' 表示最近1小时,'1d' 表示最近1天) 2. **网络请求过滤** (`network`) - `urlPattern`: URL 正则表达式模式 - `methods`: HTTP 方法数组(如 ['GET', 'POST']) - `statusCodes`: 状态码范围(如 `{'min': 200, 'max': 299}`) - `requestTypes`: 请求类型数组(如 ['request', 'response', 'failed']) - `resourceTypes`: 资源类型数组(如 ['xhr', 'fetch', 'script', 'document']) - `requestSize`: 请求大小范围(字节,如 `{'min': 1000, 'max': 10000}`) - `responseTime`: 响应时间范围(毫秒,如 `{'min': 100, 'max': 1000}`) - `responseHeaders`: 响应头过滤(如 `{'Content-Type': 'application/json'}`) 3. **控制台日志过滤** (`console`) - `levels`: 日志级别数组(如 ['error', 'warn', 'info', 'log', 'debug']) - `contains`: 日志内容包含的字符串 4. **错误过滤** (`errors`) - `types`: 错误类型数组(如 ['javascript', 'network', 'resource']) **过滤示例:** 按时间范围过滤: ```bash curl -X POST http://127.0.0.1:8082/mcp/tools/call \ -H "Content-Type: application/json" \ -d '{ "name": "page_monitor", "arguments": { "command": "get", "monitors": ["network"], "filters": { "timeRange": { "last": "5m" } } } }' ``` 按 URL 模式和 HTTP 方法过滤: ```bash curl -X POST http://127.0.0.1:8082/mcp/tools/call \ -H "Content-Type: application/json" \ -d '{ "name": "page_monitor", "arguments": { "command": "get", "monitors": ["network"], "filters": { "network": { "urlPattern": "api\\.example\\.com", "methods": ["GET", "POST"] } } } }' ``` 按状态码和响应时间过滤: ```bash curl -X POST http://127.0.0.1:8082/mcp/tools/call \ -H "Content-Type: application/json" \ -d '{ "name": "page_monitor", "arguments": { "command": "get", "monitors": ["network"], "filters": { "network": { "statusCodes": {"min": 200, "max": 299}, "responseTime": {"min": 100, "max": 1000} } } } }' ``` 按日志级别过滤控制台日志: ```bash curl -X POST http://127.0.0.1:8082/mcp/tools/call \ -H "Content-Type: application/json" \ -d '{ "name": "page_monitor", "arguments": { "command": "get", "monitors": ["console"], "filters": { "console": { "levels": ["error", "warn"] } } } }' ``` 组合多个过滤条件: ```bash curl -X POST http://127.0.0.1:8082/mcp/tools/call \ -H "Content-Type: application/json" \ -d '{ "name": "page_monitor", "arguments": { "command": "get", "monitors": ["network"], "filters": { "timeRange": {"last": "1h"}, "network": { "urlPattern": "api\\.example\\.com", "methods": ["GET"], "statusCodes": {"min": 200, "max": 299}, "resourceTypes": ["xhr"] } } } }' ``` **独立监控工具的过滤器结构:** 对于独立的监控工具(`page_network`、`page_log`、`page_errors`),所有工具都使用统一的嵌套过滤器结构: - `page_network`: 过滤器参数放在 `filters` 对象的 `network` 键下 - 示例:`{"filters": {"network": {"methods": ["GET"], "statusCodes": {"min": 200, "max": 299}}}}` - `page_log`: 过滤器参数放在 `filters` 对象的 `console` 键下 - 示例:`{"filters": {"console": {"levels": ["error", "warn"]}}}` - `page_errors`: 过滤器参数放在 `filters` 对象的 `errors` 键下 - 示例:`{"filters": {"errors": {"types": ["javascript"]}}}` **独立监控工具过滤示例:** 过滤网络请求: ```bash curl -X POST http://127.0.0.1:8082/mcp/tools/call \ -H "Content-Type: application/json" \ -d '{ "name": "page_network", "arguments": { "command": "get", "filters": { "network": { "methods": ["GET"], "statusCodes": {"min": 200, "max": 299} } } } }' ``` 按 URL 模式和资源类型过滤: ```bash curl -X POST http://127.0.0.1:8082/mcp/tools/call \ -H "Content-Type: application/json" \ -d '{ "name": "page_network", "arguments": { "command": "get", "filters": { "network": { "urlPattern": "api\\.example\\.com", "resourceTypes": ["xhr", "fetch"] } } } }' ``` 按请求大小和响应时间过滤: ```bash curl -X POST http://127.0.0.1:8082/mcp/tools/call \ -H "Content-Type: application/json" \ -d '{ "name": "page_network", "arguments": { "command": "get", "filters": { "network": { "requestSize": {"min": 1000, "max": 10000}, "responseTime": {"min": 100, "max": 1000} } } } }' ``` 按响应头过滤: ```bash curl -X POST http://127.0.0.1:8082/mcp/tools/call \ -H "Content-Type: application/json" \ -d '{ "name": "page_network", "arguments": { "command": "get", "filters": { "network": { "responseHeaders": { "Content-Type": "application/json" } } } } }' ``` 过滤控制台日志: ```bash curl -X POST http://127.0.0.1:8082/mcp/tools/call \ -H "Content-Type: application/json" \ -d '{ "name": "page_log", "arguments": { "command": "get", "filters": { "console": { "levels": ["error", "warn"], "contains": "error" } } } }' ``` 过滤错误: ```bash curl -X POST http://127.0.0.1:8082/mcp/tools/call \ -H "Content-Type: application/json" \ -d '{ "name": "page_errors", "arguments": { "command": "get", "filters": { "errors": { "types": ["javascript"], "messagePattern": "error" } } } }' ``` **返回:** - `success`: 操作是否成功 - `command`: 执行的命令 - `data`: 返回的数据(根据命令不同而变化) - `error`: 错误信息(如果失败) **示例:** 启动监控: ```bash curl -X POST http://127.0.0.1:8082/mcp/tools/call \ -H "Content-Type: application/json" \ -d '{ "name": "page_monitor", "arguments": { "command": "start", "monitors": ["network", "console", "errors"] } }' ``` 获取监控数据: ```bash curl -X POST http://127.0.0.1:8082/mcp/tools/call \ -H "Content-Type: application/json" \ -d '{ "name": "page_monitor", "arguments": { "command": "get", "monitors": ["network"] } }' ``` 导出监控数据: ```bash curl -X POST http://127.0.0.1:8082/mcp/tools/call \ -H "Content-Type: application/json" \ -d '{ "name": "page_monitor", "arguments": { "command": "export", "exportFormat": "har" } }' ``` ### keyboard_action 执行键盘操作(单键、组合键、文本输入)。 **参数:** - `actionType`(必需):操作类型 - `press`: 按下并释放按键 - `type`: 输入文本 - `down`: 按下按键不放 - `up`: 释放按键 - `sequence`: 按键组合序列 - `key`(可选):单个按键(如 'Enter'、'Control+A'),当 actionType 为 press 时使用 - `text`(可选):要输入的文本,当 actionType 为 type 时使用 - `keys`(可选):按键序列,如 ['Control', 'Shift', 'P'],当 actionType 为 sequence 时使用 - `delay`(可选):按键之间的延迟(毫秒),默认为 0 - `targetSelector`(可选):目标元素选择器,不指定时在当前焦点元素操作 - `modifiers`(可选):修饰键数组,可选值为 ['Control', 'Shift', 'Alt', 'Meta'] **返回:** - `url`: 当前页面URL - `action_type`: 执行的操作类型 - `status`: 'success' 或 'error' **示例:** 输入文本: ```bash curl -X POST http://127.0.0.1:8082/mcp/tools/call \ -H "Content-Type: application/json" \ -d '{ "name": "keyboard_action", "arguments": { "actionType": "type", "text": "Hello World" } }' ``` 按下回车键: ```bash curl -X POST http://127.0.0.1:8082/mcp/tools/call \ -H "Content-Type: application/json" \ -d '{ "name": "keyboard_action", "arguments": { "actionType": "press", "key": "Enter" } }' ``` 执行组合键: ```bash curl -X POST http://127.0.0.1:8082/mcp/tools/call \ -H "Content-Type: application/json" \ -d '{ "name": "keyboard_action", "arguments": { "actionType": "sequence", "keys": ["Control", "A"] } }' ``` 在指定元素中输入文本: ```bash curl -X POST http://127.0.0.1:8082/mcp/tools/call \ -H "Content-Type: application/json" \ -d '{ "name": "keyboard_action", "arguments": { "actionType": "type", "text": "test", "targetSelector": "input#username" } }' ``` ### keyboard_shortcut 执行常用键盘快捷键。 **参数:** - `shortcut`(可选):预定义的快捷键 - `save`: 保存(Control+S) - `copy`: 复制(Control+C) - `paste`: 粘贴(Control+V) - `cut`: 剪切(Control+X) - `selectAll`: 全选(Control+A) - `find`: 查找(Control+F) - `refresh`: 刷新(F5) - `newTab`: 新标签页(Control+T) - `closeTab`: 关闭标签页(Control+W) - `reopenTab`: 重新打开标签页(Control+Shift+T) - `devTools`: 开发者工具(F12) - `fullscreen`: 全屏(F11) - `customShortcut`(可选):自定义快捷键,如 'Control+Shift+K' - `targetSelector`(可选):目标元素选择器 **返回:** - `url`: 当前页面URL - `shortcut`: 执行的快捷键 - `keys_pressed`: 实际按下的按键 - `status`: 'success' 或 'error' **示例:** 使用预定义快捷键: ```bash curl -X POST http://127.0.0.1:8082/mcp/tools/call \ -H "Content-Type: application/json" \ -d '{ "name": "keyboard_shortcut", "arguments": { "shortcut": "selectAll" } }' ``` 使用自定义快捷键: ```bash curl -X POST http://127.0.0.1:8082/mcp/tools/call \ -H "Content-Type: application/json" \ -d '{ "name": "keyboard_shortcut", "arguments": { "customShortcut": "Control+Shift+K" } }' ``` 在指定元素上执行快捷键: ```bash curl -X POST http://127.0.0.1:8082/mcp/tools/call \ -H "Content-Type: application/json" \ -d '{ "name": "keyboard_shortcut", "arguments": { "shortcut": "selectAll", "targetSelector": "textarea#content" } }' ``` ## 使用示例 ### 使用 curl ```bash # 导航到页面 curl -X POST http://127.0.0.1:8082/mcp/tools/call \ -H "Content-Type: application/json" \ -d '{ "name": "navigate", "arguments": { "url": "https://example.com" } }' # 获取当前页面内容 curl -X POST http://127.0.0.1:8082/mcp/tools/call \ -H "Content-Type: application/json" \ -d '{ "name": "fetch_page", "arguments": {} }' # 导航到需要认证的页面(使用 headers) curl -X POST http://127.0.0.1:8082/mcp/tools/call \ -H "Content-Type: application/json" \ -d '{ "name": "navigate", "arguments": { "url": "https://api.example.com/protected", "headers": { "Authorization": "Bearer your-token-here" } } }' # 导航到需要登录的页面(使用 cookies) curl -X POST http://127.0.0.1:8082/mcp/tools/call \ -H "Content-Type: application/json" \ -d '{ "name": "navigate", "arguments": { "url": "https://example.com/dashboard", "cookies": { "session_id": "your-session-id", "user_token": "your-token" } } }' # 截取当前页面截图 curl -X POST http://127.0.0.1:8082/mcp/tools/call \ -H "Content-Type: application/json" \ -d '{ "name": "screenshot", "arguments": { "full_page": false } }' # 查询当前页面的 DOM curl -X POST http://127.0.0.1:8082/mcp/tools/call \ -H "Content-Type: application/json" \ -d '{ "name": "query_dom", "arguments": { "selector": "h1" } }' # 在当前页面执行 JavaScript curl -X POST http://127.0.0.1:8082/mcp/tools/call \ -H "Content-Type: application/json" \ -d '{ "name": "execute_js", "arguments": { "code": "document.title" } }' # 点击当前页面上的元素 curl -X POST http://127.0.0.1:8082/mcp/tools/call \ -H "Content-Type: application/json" \ -d '{ "name": "click", "arguments": { "selector": "button.submit" } }' # 等待元素出现 curl -X POST http://127.0.0.1:8082/mcp/tools/call \ -H "Content-Type: application/json" \ -d '{ "name": "wait_for", "arguments": { "selector": ".loading", "state": "hidden" } }' # 启动页面监控 curl -X POST http://127.0.0.1:8082/mcp/tools/call \ -H "Content-Type: application/json" \ -d '{ "name": "page_monitor", "arguments": { "command": "start", "monitors": ["network", "console", "errors"] } }' # 获取监控数据 curl -X POST http://127.0.0.1:8082/mcp/tools/call \ -H "Content-Type: application/json" \ -d '{ "name": "page_monitor", "arguments": { "command": "get", "monitors": ["network"] } }' # 导出监控数据为 HAR 格式 curl -X POST http://127.0.0.1:8082/mcp/tools/call \ -H "Content-Type: application/json" \ -d '{ "name": "page_monitor", "arguments": { "command": "export", "exportFormat": "har" } }' ``` ### 与 AI 配合使用 AI 可以使用这些工具来: - 导航到指定页面 - 查看网页并理解其结构 - 截取截图以查看视觉外观 - 查询特定元素以提取信息 - 执行 JavaScript 以与页面交互 - 点击页面元素 - 等待特定元素出现 - 监控网络请求、控制台日志和错误 - 收集性能指标 - 导出和分析监控数据 - 执行键盘操作(输入文本、按键、组合键) - 执行常用键盘快捷键 对话示例: ``` 用户:帮我看看 http://localhost:8000 的导航栏样式 AI:[调用navigate] 导航到页面 [调用screenshot] 这是首页截图 [调用query_dom] 导航栏的HTML结构是... [调用execute_js] 导航栏的计算样式是... ``` ``` 用户:帮我监控这个页面的网络请求和错误 AI:[调用navigate] 导航到页面 [调用page_monitor start] 启动监控(network, console, errors) [等待一段时间] [调用page_monitor get] 获取监控数据 [调用page_monitor export] 导出为HAR格式 ``` ## 重要使用模式 ### 工具调用顺序 **关键规则**: - **navigate** 是唯一可以重置/改变当前页面的工具 - 所有其他工具(fetch_page、screenshot、query_dom、execute_js、click、wait_for、keyboard_action、keyboard_shortcut)都基于当前页面执行 - 如果不先调用navigate,其他工具没有意义 **正确的使用顺序**: 1. 首先调用 `navigate` 设置当前页面 2. 然后可以调用其他工具操作当前页面 3. 如需切换页面,再次调用 `navigate` **示例流程**: ```bash # 1. 导航到页面 navigate(url="https://example.com") # 2. 获取页面内容 fetch_page() # 3. 截取截图 screenshot(full_page=false) # 4. 查询 DOM query_dom(selector="h1") # 5. 执行 JavaScript execute_js(code="document.title") # 6. 点击元素 click(selector="button.submit") # 7. 等待元素 wait_for(selector=".result", state="visible") # 8. 输入文本 keyboard_action(actionType="type", text="Hello World") # 9. 按下回车键 keyboard_action(actionType="press", key="Enter") # 10. 执行快捷键 keyboard_shortcut(shortcut="selectAll") # 11. 切换到新页面 navigate(url="https://example.com/page2") ``` ## 架构 - **传输协议**: HTTP 和 stdio - **浏览器**: Playwright with Chromium - **协议**: JSON-RPC 2.0 - **隔离性**: 完全独立于 Trac 插件 ## 错误处理规范 ### 错误响应格式 所有工具调用(成功或失败)都返回包含 `content` 字段的响应,确保客户端能够统一处理响应。 **成功响应示例:** ```json { "content": [ { "type": "text", "text": "{\"url\": \"https://example.com\", \"status\": \"success\"}" } ] } ``` **错误响应示例:** ```json { "content": [ { "type": "text", "text": "{\"status\": \"error\", \"error\": \"selector is required\", \"error_code\": -32603}" } ] } ``` ### 错误代码规范 使用 JSON-RPC 2.0 标准错误代码: - `-32700`: Parse error - 无效的 JSON - `-32600`: Invalid Request - 无效的请求 - `-32601`: Method not found - 方法不存在 - `-32602`: Invalid params - 无效的参数 - `-32603`: Internal error - 内部错误(工具执行错误) ### 错误处理实现 所有错误响应通过 `ErrorResponseBuilder` 类统一生成,确保错误信息格式一致。 **错误响应构建方法:** - `build(message, request_id)`: 构建通用错误响应 - `build_invalid_request(message, request_id)`: 构建无效请求错误 - `build_method_not_found(method, request_id)`: 构建方法未找到错误 - `build_invalid_params(message, request_id)`: 构建无效参数错误 - `build_internal_error(message, request_id)`: 构建内部错误 ### 参数验证 所有工具处理器都包含必需参数的验证,在执行前检查参数是否存在: ```python async def _handle_click(self, args: Dict[str, Any]) -> Dict[str, Any]: selector = args.get('selector') if not selector: return { 'error': 'selector is required', 'status': 'error' } ``` ### 超时处理 所有异步操作都设置超时时间,防止请求无限期挂起: ```python future = asyncio.run_coroutine_threadsafe( self.handle_tool_call(tool_name, arguments), self.loop ) result = future.result(timeout=60) ``` ### 异常捕获 所有工具方法都包含异常捕获,将异常转换为标准错误响应: ```python try: result = await page.evaluate(code) return {'url': page.url, 'result': result, 'status': 'success'} except Exception as e: logger.error(f"Error executing JavaScript: {e}") return {'url': page.url, 'error': str(e), 'status': 'error'} ``` ## 代码规范 ### 文件组织 - **单一职责原则**: 每个文件只包含一个主要类 - **模块化设计**: 相关功能组织在同一个模块中 - **清晰的命名**: 文件名与类名保持一致 ### 类职责划分 - **WebDebugMCPServer** (mcp_server.py): 核心服务器实现,包含工具注册和处理器 - **MCPRequestHandler** (http_handler.py): HTTP 请求处理,解析和响应 HTTP 请求 - **MCPServerStdioHandler** (stdio_handler.py): stdio 通信处理,读取和写入标准输入输出 - **ErrorResponseBuilder** (error_response.py): 错误响应构建,统一错误格式 - **PageMonitor** (page_monitor.py): 页面监控功能,网络、控制台、错误监控 ### 导入规范 - 使用绝对导入而非相对导入 - 按照标准库、第三方库、本地模块的顺序组织导入 - 每个导入分组之间空一行 ### 日志规范 - 使用 `logging` 模块记录日志 - 错误日志使用 `logger.error()` - 信息日志使用 `logger.info()` - 调试日志使用 `logger.debug()` ### 异步编程规范 - 所有 I/O 操作使用异步方法 - 使用 `asyncio.run_coroutine_threadsafe` 在不同线程间调度协程 - 所有异步操作设置合理的超时时间 ### 类型注解 - 所有函数参数和返回值使用类型注解 - 使用 `Dict[str, Any]` 表示字典类型 - 使用 `Optional[Type]` 表示可选类型 ### 常量定义 - 超时时间等配置参数使用常量定义 - 避免在代码中硬编码魔法数字 ## 系统要求 - Python 3.7+ - Playwright 1.40.0+ - Chromium 浏览器(通过 Playwright 安装) ## 许可证 MIT License