SuperAPI AI Directory

wechat-devtools

General & other

View repository

Updated 10-15 23:40

About this skill

Wechat DevTools MCP Skill (v0.9.18)

Prerequisites

Step 0: Installation and configuration

pip install uv
uv tool install wechat-devtools-mcp --force
{
  "mcpServers": {
    "wechat-devtools-mcp": {
      "command": "uvx",
      "args": ["wechat-devtools-mcp"],
      "env": {
        "WECHAT_DEVTOOLS_CLI": "C:\\Program Files (x86)\\Tencent\\微信web开发者工具\\cli.bat",
        "WECHAT_PROJECT_PATH": "D:\\Your\\Project\\Path"
      }
    }
  }
}
  • Register the name as wechat-devtools-mcp(DevTools 2.x registers its own MCP bridge as wechat-devtools, and the same name will be overwritten). macOS CLI path /Applications/wechatwebdevtools.app/Contents/MacOS/cli. For editor configurations, see README。
  • The service port must be enabled:设置 → 安全设置 → 服务端口. If it is not enabled, all CLI operations report CLI_TIMEOUT。

Step 1: Runtime environment check

First call wechat_ide(action='status') once to confirm all prerequisites:

Check item Field On failure
CLI installed cli_exists: true Configure WECHAT_DEVTOOLS_CLI
Service port enabled service_port_enabled: true false necessarily CLI_TIMEOUT, open it in settings;null cannot be read, which does not mean it is disabled
Project path valid project_exists: true Configure WECHAT_PROJECT_PATH, must point to the root directory containing project.config.json root directory
Node.js available node_available: true Install Node.js
Versions consistent mcp_version == this file's version uv tool upgrade wechat-devtools-mcp or sync the skill copy
Logged in is_login → logged_in: true login(qr_format='terminal') scan the QR code
Official built-in MCP official_mcp.available See the routing rules below

Environment routing rules (IDE 2.x built-in MCP)

DevTools 2.x (official Stable as of 2026-08-18) has a built-in MCP Server in http://127.0.0.1:<ide_port>/mcp (47 atomic tools).official_mcp.available: true and the official MCP is already connected to the current agent:

Operation Handled by
Open/close project, login, compile, preview, upload, build npm, click/input/scroll, Cloud Development Prefer official tools; do not do the same operation on both sides
Stitched long screenshot This skill. Official simulator_screenshot only captures the viewport and compresses to long edge 1280 JPEG
CDP structured logs (inspector cdp / navigate) This skill. Can replay historical messages collected before and filter out noise
SOP C / D / I / J task-level flows Orchestrated by this skill; basic steps can call official tools

available: false(1.06, IDE not started, port drift) or when the official MCP is not connected, this skill takes over all capabilities; do not make users install the official MCP for basic operations.

Efficiency principles

  • The IDE only at session start open once; after changing code, only compile → page_data(automatically reconnects automator), do not open again.
  • If code has not changed and you switch pages, use evaluate(fn_source="function(){ wx.reLaunch({url:'/pages/x/index'}); return 'ok' }") → page_data。
  • If the connection drops, first start → page_data, do not go directly through the full recovery.

API quick reference

For complete parameters and return fields, see tool_reference.md。

wechat_ide

action Function Key parameters / returns
open Start the IDE and open the project.cdp_enabled=true(default) will kill the running IDE, restart with the CDP port, and perform a startup health check after the Mini Program target is ready cdp_port(default 9222; change it when occupied, and it must match inspector/navigate/compile); returns ide_runtime、cdp_ready、project_opened; when there is an error, success:false + startup_errors
login / is_login Scan QR code to log in / check login status qr_format;logged_in
close / quit Close the project window / exit the IDE None
status Environment diagnostics service_port_enabled、ide_port、official_mcp、mcp_version

wechat_build

action Function Key parameters / returns
compile Compile and capture Error/Warning; on success, automatically reconnect automator (default 9420 only) cdp_port; returns errors、warnings、wxml_errors、npm_warning、automator_verified、fatal_errors
preview Generate preview QR code qr_format、qr_output(relative paths are relative to the project root); returns qr_stale_warning indicates the bundle may not have refreshed
upload Upload to WeChat backend, production operation version required,desc
build_npm Build npm. Required after adding/updating dependencies, otherwise at runtime it reports module ... is not defined None
cache_clean Clear cache clean_type(default compile;all use with caution)

compile_condition for tabBar pages may be overridden by app route guards; using evaluate for navigation is more reliable.

wechat_automator

First call start to enable the automation port, once per session.

action Function Required / returns
start Enable the automation port, with triple verification of CLI + TCP + WS; automatically rerun when the window has not finished loading cli auto(up to 3 rounds) Returns verified;false when retry according to retry_after_ms retry
tap / input Click / input selector(input also requires value)
element_info element tagName/text/wxml/size/offset,style_prop when include style selector
set_data Hot-update page data without recompiling data_json; returns updated_keys
call_method Call page method method、args_json?; returns return_value、path
call_wx / mock_wx Call wx API / mock return value (valid for the current session) method(mock also requires result_json)
evaluate Execute JS in the logic layer fn_source(recommended) or expression; returns result、mode
page_stack Page stack Returns depth、pages
page_data Current page data expected_path? will poll and wait for the page to match; returns path、data、path_mismatch
system_info / storage System information / local cache storage pass key to get the value, if not passed list keys

evaluate usage:

  • fn_source pass the complete function source (function(){...} or arrow function), put the arguments in args_json(JSON array). Multiple statements, declarations,return are all determined by the function body,mode: "function"。
  • expression pass only a single expression. Multiple statements will fall back to statement mode (all executed,mode: "statement")), without return the result is null and include hint。
  • Example:fn_source="function(){ const p=getCurrentPages(); return p[p.length-1].route }"。

wechat_inspector

action Function Key parameters
cdp CDP collects WXML warnings, renderer errors, and Runtime errors.Can replay historical messages from before collection duration=10、detail_level、max_logs、cdp_port
console automator event collection collects console and JS exceptions. Only receives events after connection duration(troubleshoot exceptions ≥8s),log_type、tap_selector

To troubleshoot "the error just reported" use cdp; to strictly align the timeline with interactions use console。

wechat_screenshot

  • full_page(default true) long image stitching,false captures only the viewport, can be configured with scroll_top;page_path automatically navigates when there is no match;output_path leave blank to save to the project screenshots/。
  • Only take screenshots when the user requests it or visual confirmation is needed; fixed/absolute popup overlays may not be captured, use page_data as the standard.

First check message for ⚠. In the following cases the image looks continuous but is incomplete:

Return field Meaning Handling
is_scroll_view_page: true The page scrolls via scroll-view, so only the viewport is captured Use evaluate to read data instead of visual confirmation
truncated: true Exceeds the segment limit, the bottom was not captured full_page=false + scroll_top segmented capture
content_gaps: N Fixed header and footer consume the overlap, content is lost at N places Increase overlap(e.g. 150) and retry
detection_confident: false Fixed header and footer recognition is unreliable Results are for reference only

fixed_header / fixed_footer is the recognized fixed-area height (physical pixels).

wechat_navigate

  • page_path Required, may include query; tabBar pages automatically use switchTab, others use reLaunch(returns navigation_method)。
  • wait_ms Defaults to 2000; pages with network requests are recommended to use 3000.clear_logs=true Filter historical CDP logs before navigation.
  • Returns current_page、cdp_logs、navigation_mismatch; with query and check_data=true when data is largely empty will give warning(suspected wrong parameter name).
  • Prerequisite:start has been called and the project is opened with cdp_enabled=true . Cloud function calls on pages entered via reLaunch may lose context; for non-tabBar pages, prefer evaluate + wx.navigateTo。

wechat_file

action Features Required / Returns
project_info project_config、app_config、directory、app.js/app.wxss excerpt None
list_pages All pages in app.json, including file integrity Returns pages[{path, complete, missing}]、total
read_page Source code of the four page files page_path; returns files{文件名: 内容}、resolved_base
read_file Any single file, up to 800 lines file_path; returns content、resolved_path、truncated

Unified path convention: first resolve by miniprogramRoot then fall back to the project root,list_pages output can be fed directly to read_page。

For cloud functions and cloud database, please use CloudBase MCP。

SOP Standard Operating Procedure

SOP A: Initialization

wechat_ide(action='status')                    # 环境诊断
wechat_ide(action='is_login')                  # 未登录 → login(qr_format='terminal')
wechat_ide(action='open', cdp_enabled=True)    # 9222 被占用时加 cdp_port=9223
  ↳ success=false + startup_errors → 先修复再继续
wechat_automator(action='start')               # verified=false → 按 retry_after_ms 重试,期间可先 compile
wechat_build(action='compile')                 # 建立干净基线,自动重连 automator
wechat_automator(action='page_data')           # 验证连接;AppID undefined → project_path 指到子目录了

project_path must be the root directory containing project.config.json , for cloud development projects miniprogram/ is a subdirectory.

SOP A-2: After changing code

wechat_build(action='compile') → wechat_automator(action='page_data')

No need to reopen, and no need for cache_clean.

Page navigation

Scenario Method
Regular page evaluate(fn_source="function(){ wx.navigateTo({url:'/pages/x/x?id=1'}); return 'ok' }")
tabBar page wechat_navigate(page_path='pages/x/index')
Force reset Same as above, use wx.reLaunch
After navigation page_data(expected_path='pages/x/x'), verify path

SOP B: UI debugging

wechat_file(action='list_pages')                            # 拿有效路径
wechat_navigate(page_path='pages/x/index', wait_ms=3000)    # 跳转 + CDP 日志
wechat_automator(action='page_data')                        # path 必须等于目标页
  ↳ 数据异常 → set_data 热更新验证;元素问题 → element_info;需要看图才 screenshot

SOP C: Troubleshooting (errors / white screen / JS exceptions)

wechat_automator(action='page_data')                        # ① 关键字段 null → 数据没加载
wechat_automator(action='evaluate', fn_source='function(){ return wx.cloud.callFunction({name:"x",data:{}}) }')
                                                            # ② 直接调 API 拿完整返回,[object Object] 时必用
wechat_inspector(action='cdp', duration=5)                  # ③ 能回放刚才的错误
wechat_build(action='compile')                              # ④ 看 errors / wxml_errors

SOP D: Full-page inspection

wechat_build(action='compile')
wechat_file(action='list_pages')
# 逐页顺序执行(禁止并行):
wechat_navigate(page_path=page, wait_ms=3000)
wechat_automator(action='page_data', expected_path=page)    # path 不匹配 → 标记重定向;字段空 → evaluate 诊断
# 汇总:按 page_data 结果输出报告;只在异常页补截图

SOP E: Mock integration testing (payment / permissions / network / adaptation)

mock_wx(method='requestPayment', result_json='{"errMsg":"requestPayment:ok"}')
mock_wx(method='getLocation',    result_json='{"latitude":23.1,"longitude":113.3}')
mock_wx(method='request',        result_json='{"errMsg":"request:fail timeout"}')   # 模拟超时
mock_wx(method='getSystemInfo',  result_json='{"theme":"dark","windowWidth":1024}') # 暗色 / 宽屏适配
tap(selector='.pay-btn') → page_data                                                 # 触发并验证

Mock is only valid for the current session. Requests can be intercepted with fn_source="function(){ var o=wx.request; wx.request=function(p){ console.log(p.url); return o.apply(wx,arguments) }; return 'ok' }"。

SOP G: Subpages with query parameters

wechat_file(action='read_page', page_path='pages/x/x')      # 看 onLoad(options) 的参数名
wechat_navigate(page_path='pages/x/x?id=123', wait_ms=3000)
wechat_automator(action='page_data')                        # 大部分为 null → 参数名错,回到第一步

SOP I: Cross-page data consistency

wechat_file(action='list_pages')
# 逐页:navigate → page_data(expected_path=page),提取公共字段(如 points / level)记入比对表
# 比对同名字段:不一致 → evaluate 直接调 API 对比,检查子页面是否走了独立数据链路

SOP J: Parallel comparison of Mini Program + admin backend

The admin backend uses Playwright MCP, the Mini Program uses this MCP; the two have different ports and can extract in parallel, with comparison done serially in the main process. automator 9420 is exclusive; only one agent can operate this MCP at a time.

CDP log strategy

Scenario Parameter
Quick diagnosis duration=5, detail_level='concise', max_logs=20
In-depth troubleshooting duration=10, detail_level='full', max_logs=100
Page inspection duration=3, detail_level='concise', max_logs=30
  • concise only returns errors + warnings;summary.errors > 0 then use full to get source for locating, together with read_file。
  • cdp will replay the buffer before collection (errors from 12 seconds ago can also be obtained),console Only events after connection are collected.
  • Automatically filtered:[system]、WAService.js、WAWebview.js, IDE shell pages;open 's startup check also filters devtools:// and ide:///extensions/。
  • Need to exclude yourself:devtools:// from the source console.assert、SharedArrayBufferIssue、wx.saveFile 即将废弃 framework warnings of the class.
  • ide:///extensions/inject/… warning from the source is not noise, it is a real problem reported by the framework (invalid app.json fields, deprecated APIs, invalid WXSS selectors).
  • The count may be inflated by noise; ultimately refer to page_data .

page_data must verify that data.path equals the navigation target; common causes of mismatch: not logged in and blocked to the login page, cloud function failure falling back to the home page, misspelled page_path, conditional redirect in onLoad. Pass expected_path to poll and wait for a match,path_mismatch: true when page_stack use

Return values and recovery

Success {"success": true, "data": {...}, "message": "..."}, failure {"success": false, "error_code": "...", "message": "...", "hint": "..."}。 error_code has only 6 types:PARAM_MISSING、CLI_NOT_FOUND、PROJECT_PATH_MISSING、NODE_NOT_FOUND、CLI_TIMEOUT、UNKNOWN_ERROR. Connection failures, navigation failures, etc. all fall under UNKNOWN_ERROR, see message and hint。

Connection disconnection recovery has two levels:

  1. Quick:start → page_data。
  2. Full:open(cdp_enabled=True) → start → compile → page_data。

Troubleshooting quick reference

Symptom Cause Solution
CLI_TIMEOUT Service port not open / IDE not running status check service_port_enabled; open the port;open
open returns startup_errors Fatal error during mini program startup Fix the code first, then open
start consecutive verified=false Cold start automator WS handshake not ready According to retry_after_ms retry; in the meantime, compile / build_npm first
CLI auto 连续 3 次返回成功但端口未监听 Project window has not finished loading or has been closed (cli auto will falsely succeed; after pure CLI open it takes about 15s) Wait a bit and then start; if it still fails open(cdp_enabled=True) restart and then start
Any automator action reports Failed connecting to ws://localhost:9420 Project window has been closed or automation is not enabled (IDE 2.x occasionally closes the window by itself) According to the returned hint: first start, if it still fails open(cdp_enabled=True) reopen
Failed connecting to ws://localhost:9420 / Connection closed automator not started, disconnected, or the project window has been closed If quick recovery fails, do full recovery
CDP collection failed / what was collected is all something else Not opened with cdp_enabled , or 9222 is occupied by Chrome (curl 127.0.0.1:9222/json/version can confirm) open(cdp_port=9223), inspector / navigate / compile use the same port
Using AppID: undefined / appid missing project_path points to a subdirectory / not logged in Change to the root directory containing project.config.json ;is_login
After navigate page_data.path does not match the target page_path misspelled, redirected (not logged in / wrong parameters / cloud function failure), switchTab not completed list_pages check; check login state and onLoad logic; increase wait_ms
evaluate returns null and mode: "statement" expression went through statement mode without return Switch to fn_source and explicitly return
Element not found / Element is obfuscated Not on the current page, wrong selector, obscured page_stack Confirm the page;element_info verify; switch to the parent node
scroll-view long image is only one screen automator cannot capture scrolling inside scroll-view return is_scroll_view_page: true, switch to evaluate to read data
Long image looks continuous but is missing a section Fixed header and footer eat up the overlap check content_gaps, increase overlap
Screenshot doesn't show the popup / captures the wrong page overlay is not in the same rendering layer / the page is reset before the screenshot use page_data as the source of truth; pass page_path
compile succeeds but the IDE shows red WXML errors WXML errors go through the IDE's internal channel check wxml_errors; check for Chinese quotation marks and unclosed tags
Runtime reports @babel/runtime/helpers/xxx is not defined npm dependencies updated without build_npm build_npm → compile,console(duration≥8, log_type='exception') verify
Tool behaves abnormally / parameters don't match (IDE 2.x) Registration name collision: the official bridge is also called wechat-devtools Change the registration name to wechat-devtools-mcp;status 's mcp_version can confirm which one is being called
On Windows, open the project doesn't open after / CDP can't connect (IDE 2.x) The old Windows branch has no 1.x/2.x detection Upgrade to the latest version; if it still fails, attach ide_runtime feedback
ide:///extensions/inject/… 's warning A real application issue reported by the framework Treat it as a real alert, do not filter it out

Absolute red line

  • ❌ open returns startup_errors then continue testing
  • ❌ Without confirming logged_in: true then preview / upload
  • ❌ On a production project cache_clean(clean_type='all')
  • ❌ Guessing the runtime state; retrying the same failed operation more than 3 times (should switch to diagnosing the root cause)
  • ❌ Hard sleep waiting, use wait_ms or page_data(expected_path) polling
  • ❌ Taking screenshots proactively in the SOP; only take them when the user requests it or visual confirmation is needed
  • ❌ compile without changing the code
  • ❌ Not verifying after navigate page_data.path
  • ❌ Multiple agents using wechat_automatorin parallel (9420 is exclusive)
  • ❌ Using miniprogram/ subdirectory as project_path; using Chinese quotation marks in WXML attribute values (the tool cannot detect this)
  • ✅ Before automation / screenshots, first start;tap / input before, first element_info confirm the element
  • ✅ upload before, confirm the version number increments,build_npm has been executed
  • ✅ After compile, use page_data to confirm the automator connection