wechat-devtools
Original:🇨🇳 Chinese
Translated
WeChat DevTools MCP —— Mini Program Building, Preview, Debugging and Automated Testing
6installs
Added on
NPX Install
npx skill4agent add watertian/wechat-devtools-mcp wechat-devtoolsTags
Translated version includes tags in frontmatterSKILL.md Content (Chinese)
View Translation Comparison →Wechat DevTools MCP Skill (v0.9.5)
Prerequisites
Step 0: Installation and Configuration
bash
pip install uv # Install uv if not present
uv tool install wechat-devtools-mcp --force # Install wechat-devtools-mcp via uvEditor Configuration:
json
{
"mcpServers": {
"wechat-devtools": {
"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"
}
}
}
}See README.md for mainstream editor configurations
[!IMPORTANT] You must manually enable the service port of the developer tools:→Settings→Security Settings→Service Port. Failure to enable will cause all CLI operations to reportEnable.CLI_TIMEOUT
Step 1: Runtime Environment Check
First callto verify all prerequisites at once.wechat_ide(action='status')
| Check Item | Preferred Command | Action on Failure |
|---|---|---|
| CLI Installed | | Install the tool and configure |
| Project Path Configured | | Configure |
| Logged In | | |
| Node.js Available | | Install Node.js ≥ 8.0 |
Efficiency Principles
The IDE is opened only once at the start of the session, compile is executed only after code changes, and page navigation uses evaluate preferentially over navigate.
| Scenario | Correct Practice | Incorrect Practice |
|---|---|---|
| Testing different pages without code changes | | Re-open → compile |
| Code changed | | Re-open → compile |
| Connection disconnected | Quick recovery first (only | Directly perform full recovery |
API Cheat Sheet
wechat_ide
— IDE Lifecycle
wechat_ide| action | Function | Key Parameters |
|---|---|---|
| Open IDE/project (automatically performs startup health check when cdp_enabled) | |
| QR code login | |
| Check login status | — |
| Close project / Exit IDE | — |
| Environment diagnosis | — |
wechat_build
— Building and Publishing
wechat_build| action | Function | Key Parameters |
|---|---|---|
| Compilation check (captures errors/warnings, automatically reconnects automator after success) | — |
- Note: compile_condition may be invalid for tabBar pages (overridden by app route guards), using evaluate + wx.reLaunch for navigation is more reliable
| | Generate preview QR code | |
| | Upload to WeChat backend | (required), |
| | Build NPM dependencies (mandatory before upload) | — |
| | Clear cache | |
previewqr_format="terminal"uploadversiondesc?build_npmcache_cleanclean_type="compile"wechat_automator
— Automated Interaction
wechat_automatorPrerequisite: Callfirst to enable the automation port (only required once per session).start
| action | Function | Required Parameters |
|---|---|---|
| Enable automation port | — |
| Click element | |
| Input text | |
| Get element details (text/size/WXML) | |
| Hot update page data (no recompilation needed) | |
| Call page method | |
| Call wx API | |
| Mock wx API return value | |
| Execute JS expression (universal key for logic layer) | |
- Note: Declaration statements (const/let/var) are supported since v0.7.0
- v0.9.2: Automatically invalidates old cache connections and reconnects after compile, adds 3s timeout protection for daemon health check, and 2s independent timeout for navigate currentPage polling
- v0.9.0:底层改为持久化 Node daemon(NDJSON 协议),WS 连接按端口缓存复用,工具调用延迟 ~3ms
| | Get page stack | — |
| | Get current page data | (poll to verify page path) |
| | Get runtime system information | — |
| | Read local cache | (empty = list all) |
page_stackpage_dataexpected_path?system_infostoragekey?wechat_inspector
— Log Collection
wechat_inspector| action | Function | Key Parameters |
|---|---|---|
| Collect console logs and JS exceptions | |
| Collect underlying logs via CDP protocol (WXML/rendering layer) | |
CDP Prerequisite: Open the project withand ensure port 9222 is available.cdp_enabled=true
wechat_screenshot
— Screenshot
wechat_screenshot- (optional): Screenshot save path. Leave blank to automatically save to the
output_pathfolder under the project directoryscreenshots/ - (default
full_page): Set totrueto capture only the current viewportfalse - (optional): Position to scroll to before taking the screenshot (logical pixels), use with
scroll_topfull_page=false - (optional): Ensure being on the specified page before taking the screenshot, automatically navigate if current page does not match
page_path - Prerequisite: Call first
wechat_automator(action='start') - Note: Do not take screenshots actively, only call when explicitly requested by the user or visual confirmation is needed for troubleshooting
- Limitation: Pages using component cannot be stitched into long screenshots (automator SDK limitation), only the current viewport is captured
scroll-view - Limitation: Screenshots may not capture fixed/absolute overlays (pop-ups, masks), rely on instead
page_data - Path Convention: Recommended to use or explicit absolute path. Avoid writing to
<project>/screenshots/— this is the user image cache directory for Claude Code, mixing MCP screenshots will cause mutual contamination.claude/image-cache/
wechat_navigate
— Navigate and Collect Logs
wechat_navigate- (required): e.g.
page_pathpages/index/index - : Wait time in milliseconds, recommended 3000
wait_ms - : Whether to filter historical CDP logs, default
clear_logstrue - : Whether to check for empty page_data after navigation, default
check_datatrue - :
detail_level(only errors+warnings) orconcisefull - Added in v0.8.0: Automatically detects TabBar pages and uses instead of
switchTab, returnsreLaunchfieldnavigation_method - Prerequisite: Requires +
automator startcdp_enabled=true
wechat_file
— File Reading
wechat_file| action | Function | Required Parameters |
|---|---|---|
| Get complete project information (app.json + directory structure) | — |
| Get all page list (including file integrity check) | — |
| Read page source code (wxml/wxss/js/json) | |
| Read any single file (max 800 lines) | |
Cloud Function and Cloud Database Management: This MCP no longer providestools since v0.9.5. Please use CloudBase MCP instead (withwechat_cloud/manageFunctions/readNoSqlDatabaseContentetc.), which has no IDE dependency and covers more features.writeNoSqlDatabaseContent
SOP Standard Operating Procedures
SOP A: Initialization (Mandatory for New Environments)
wechat_ide(action='status') # Diagnose environment
wechat_ide(action='is_login') # Check login status
↳ Not logged in: wechat_ide(action='login', qr_format='terminal')
wechat_ide(action='open', cdp_enabled=True) # Launch IDE + CDP 9222 + automatic health check
↳ Returns success=false + startup_errors → Fatal error during mini program startup, must fix before proceeding
↳ Returns success=true → Startup normal, proceed to next steps
↳ Transient errors may occur during IDE cold start (simulator not found / subPackages of undefined), which is normal, ignore and continue to execute compile to refresh
wechat_automator(action='start') # Launch daemon + enable automation port 9420
wechat_file(action='project_info') # [Optional] Confirm project structure
wechat_build(action='cache_clean', clean_type='all') # Clear all cache
wechat_build(action='compile') # Compile to establish clean CDP baseline (automatically reconnects automator)
wechat_automator(action='page_data') # Verify connection availability
↳ ⚠ Check if AppID is undefined in the output
↳ If undefined → project_path may point to a subdirectory instead of the project root
↳ Cloud development project root directory contains project.config.json, miniprogram/ and cloudfunctions/
↳ Correct: project_path="D:/MyProject" Wrong: project_path="D:/MyProject/miniprogram"project_path Rule: Must point to the root directory containing. For cloud development projects,project.config.jsonis a subdirectory and cannot be used as project_path.miniprogram/
SOP A-2: Recompile After Code Changes (No Need to Re-open IDE)
wechat_build(action='compile') # Compile (automatically reconnects automator)
wechat_automator(action='page_data') # Verify connection availabilityNo need to re-open IDE or perform cache_clean. Only execute after modifying mini program source code.
Standard Page Navigation Methods
| Scenario | Method |
|---|---|
| Normal page | |
| TabBar page | |
| Force reset | |
| After navigation | Verify |
SOP B: UI Debugging (Data/Layout Issues)
wechat_file(action='list_pages') # ⓪ Before first navigation, get list of valid page paths
↳ TabBar page paths are usually pages/xxx/index (not pages/xxx/xxx)
wechat_navigate(page_path='pages/xxx/index', wait_ms=3000) # ① Navigate + CDP logs
wechat_automator(action='page_data') # ② Check data status
↳ ⚠ Must verify that data.path === expected page_path
↳ If not matching → Page navigation failed or redirected (see page_data notes)
↳ Data exception: set_data(data_json='{"key":"val"}') to hot update and verify
↳ Confirm element: element_info(selector='.target')
↳ Only when requested by user or visual confirmation is needed: wechat_screenshot() # Default saves to project screenshots/SOP C: Troubleshooting (Errors/White Screen/JS Exceptions)
wechat_automator(action='page_data') # ① Preferred: Directly check page data
↳ Key fields are null/empty → Data not loaded or parameter error
↳ Data normal → Proceed to step ④ to confirm it's not a data issue
wechat_automator(action='evaluate', expression='wx.cloud.callFunction({name:"xxx",data:{...}})')
# ② Directly call API to get complete return value
↳ Must use this step when encountering [object Object] to get complete JSON
wechat_inspector(action='cdp', duration=5, detail_level='concise')
# ③ CDP auxiliary reference
⚠ CDP error count may include historical cache, rely on page_data instead
wechat_build(action='compile') # ④ Capture compilation errors
↳ Check wxml_errors field; ⚠ Compilation errors like Chinese quotes "" cannot be captured by the toolSOP D: Full Page Inspection (Regression/Pre-release Acceptance)
wechat_build(action='cache_clean', clean_type='all') # Establish clean CDP baseline
wechat_build(action='compile')
↳ ⚠ Check if AppID is undefined
wechat_file(action='list_pages') # Get page list, confirm valid paths
# Execute sequentially for each page (parallel execution is prohibited):
wechat_navigate(page_path=page, wait_ms=3000) # Navigate + CDP logs
wechat_automator(action='page_data') # Core verification: Key fields are not null/empty
↳ ⚠ Must verify that data.path === expected page_path
↳ If not matching → Page navigation failed or redirected, mark as exception
↳ Fields normal and path matching → ✅ Page passed
↳ Fields empty → ⚠ Mark as exception, use evaluate for further diagnosis
↳ Only take supplementary screenshots when page_data is abnormal
# Summary: Output report sorted by page_data resultsSOP E: Mock Integration Testing (Payment/Permissions/Devices)
wechat_automator(action='mock_wx', method='requestPayment', result_json='{"errMsg":"requestPayment:ok"}')
wechat_automator(action='mock_wx', method='getUserProfile', result_json='{"userInfo":{"nickName":"Test User"}}')
wechat_automator(action='mock_wx', method='getLocation', result_json='{"latitude":23.099,"longitude":113.324}')
wechat_automator(action='tap', selector='.pay-btn') # Trigger interaction
wechat_automator(action='page_data') # Verify data changesMock is only valid for the current session, needs to be reset after restarting IDE.
SOP F: Network Debugging and UI Adaptation
① Network and API Debugging
# Intercept requests (logic layer injection)
evaluate(expression='var o=wx.request; wx.request=function(p){console.log(p.url);return o.apply(wx,arguments)}')
# Simulate timeout
mock_wx(method='request', result_json='{"errMsg":"request:fail timeout"}')② UI Adaptation Testing
mock_wx(method='getSystemInfo', result_json='{"theme":"dark"}') # Dark mode adaptation
mock_wx(method='getSystemInfo', result_json='{"platform":"mac","windowWidth":1024}') # iPad/PC adaptation
system_info() # Record windowWidth/HeightSOP G: Subpage Testing (Pages Requiring Query Parameters)
wechat_file(action='read_page', page_path='pages/xxx/xxx') # ① Check onLoad method
↳ Confirm query parameter names (such as id / matchId) from options parameter
wechat_navigate(page_path='pages/xxx/xxx?correct_param_name=value', wait_ms=3000) # ② Navigate
wechat_automator(action='page_data') # ③ Verify data
↳ Key fields not empty → ✅
↳ Most fields are null → Parameter name may be incorrect, go back to ①SOP I: Cross-page Data Consistency Verification
Applicable scenario: Verify whether the same data is displayed consistently across different pages (such as points, user status, level, etc.)
wechat_file(action='list_pages') # ① Get page list
# Define common fields to verify (such as points, phone_bound, level)
# ② Collect data page by page (execute sequentially, parallel execution is prohibited):
wechat_navigate(page_path=page, wait_ms=3000)
wechat_automator(action='page_data')
↳ Verify that data.path === expected page (mark and skip if navigation failed)
↳ Extract values of common fields, record to comparison table
# ③ Compare values of fields with the same name across pages
↳ Values consistent → ✅ Field passed
↳ Values inconsistent → ⚠ Mark as exception, use evaluate to directly call API for comparison
↳ When subpage data is abnormal, check if independent data acquisition link is usedSOP J: Parallel Data Comparison Between Mini Program and Management Backend
Applicable scenario: Verify consistency between mini program frontend data and management backend data
# Architecture:
# Management Backend → Playwright MCP (browser port)
# Mini Program → WeChat DevTools MCP (automator port 9420)
# They use different ports and can run in parallel
# ① Extract data from both ends respectively (can be parallel)
# Agent A: Operate management backend via Playwright, extract data
# Agent B: Operate mini program via WeChat MCP, extract page_data
# ② Perform data comparison in main process (serial)Port Exclusivity Rule: The automator port 9420 is exclusive, only one Agent can operate WeChat MCP at the same time. Playwright and WeChat MCP can be used simultaneously (different ports).
CDP Log Strategy
concise → Only errors + warnings (saves tokens, preferred)
↓ When summary.errors > 0
full → Complete logs + source location → wechat_file(action='read_file', file_path=source)| Scenario | Recommended Parameters |
|---|---|
| Quick diagnosis | |
| In-depth troubleshooting | |
| Page inspection | |
Important: CDP error count may include accumulated historical logs across pages.(default) in v0.4.0 filters historical logs based on timestamp, but it is still recommended to useclear_logs=trueas the final verification standard.page_data
CDP Log Noise Filtering
The following log sources are internal noise of the developer tools and do not represent application errors, should be excluded when judging:
| source Prefix | Description | Handling |
|---|---|---|
| Assertions/warnings from the developer tool itself | Ignore |
| Reminders injected by IDE extensions | Treat differently |
The following message patterns are framework-level reminders, not application errors:
| message Pattern | Description |
|---|---|
| Internal assertions of devtools |
| Browser engine warning |
| Deprecated API migration reminder |
| Framework API deprecation warning |
| Component property type mismatch warning |
Judgment Principle: The errors/warnings count in CDP may be inflated by the above noise, leading to misjudgment. Always use the actual data returned byas the final verification standard.page_data
page_data Notes
-
Must verify the path field: The returnedrepresents the current actual page. If it does not match the navigation target, it means the page navigation failed or was redirected.
data.path -
Common reasons for inconsistency:
- User not logged in, page intercepts and redirects to login/welcome page
- Cloud function call failed (AppID undefined), page falls back to homepage
- page_path spelling error, navigate fails silently (returns success: true)
- Conditional navigation logic exists in page onLoad
-
Recommended Pattern:
wechat_navigate(page_path='pages/xxx/index', wait_ms=3000) wechat_automator(action='page_data') ↳ data.path !== 'pages/xxx/index' → Page not loaded correctly ↳ Use page_stack to view complete page stack, locate redirection reason
Return Value Format
json
{"success": true, "data": {...}, "message": "Operation description"}
{"success": false, "error_code": "CLI_TIMEOUT", "message": "...", "hint": "Fix hint"}
{"success": false, "error_code": "UNKNOWN_ERROR", "message": "N errors detected during mini program startup...", "hint": "...", "startup_errors": [...], "cdp_summary": {...}}| error_code | Meaning | Handling |
|---|---|---|
| Required parameter missing | Check hint field |
| CLI not found | Check |
| Project path not configured | Check |
| Node.js not installed | Install Node.js ≥ 8.0 |
| CLI execution timeout | Enable service port; restart IDE |
Connection Recovery Tiers
Quick Recovery (try first):
wechat_automator(action='start') # Only reconnect
wechat_automator(action='page_data') # VerifyFull Recovery (when quick fails):
wechat_ide(action='open', cdp_enabled=True) # Re-open
wechat_automator(action='start') # Reconnect
wechat_build(action='compile') # Recompile (automatically reconnects automator)
wechat_automator(action='page_data') # VerifyTroubleshooting Quick Reference
| Symptom | Cause | Solution |
|---|---|---|
| CDP collection failed (port 9222 unresponsive) | IDE not started with cdp_enabled | Restart with |
| Blank screenshot / size 0 | automator not started or page not rendered | Confirm |
| page_path spelled incorrectly / not registered | Verify with |
| Element blocked or outside shadow-root | Check WXML structure, try parent node |
| Logic layer crashed / reloading | Retry after waiting 3s |
| Service port not enabled / IDE not running | Enable service port; |
| Element not found | Not on current page or selector wrong | Confirm page with |
| project_path points to subdirectory instead of project root | Change to directory containing |
| AppID not configured or not logged in | Check project_path + login status |
| automator WS connection disconnected (rare under v0.9.0 daemon architecture) | First perform quick recovery (only |
| automator not started or disconnected | Same as above |
| navigate returns success but page not navigated | page_path does not exist or spelled incorrectly | Confirm path with |
| page_data.path does not match navigate target | Page redirected (not logged in/parameter error/cloud function failed) | Check AppID, login status, page onLoad logic |
| CDP errors count includes console.assert | devtools internal noise | Filter |
| Subpage data inconsistent with main page | Subpage uses independent data acquisition link | Use |
| Bottom navigation bar repeated in long screenshot | Fixed area detection failed (fixed in v0.5.0) | Upgrade to latest version; feedback if still reproducible |
| Fatal error during mini program startup (page cannot be displayed) | Fix code according to error details in |
| Transient error during IDE cold start, not ready yet | Ignore, continue to execute compile to refresh |
| compile succeeds but IDE shows red WXML error | WXML compilation errors go through IDE internal channel | Check Chinese quotes |
| Internal variable scope bug in wechat_navigate (fixed in v0.7.0) | Upgrade to v0.7.0; or use evaluate + wx.reLaunch |
| compile_condition entry page overridden | App route guard overrides compilation entry | Compile default page, navigate with evaluate(wx.reLaunch) |
| switchTab ok but not switched | switchTab not completed asynchronously | Increase wait_ms; v0.8.0 navigate automatically handles TabBar pages |
evaluate reports | v0.6.0 only supports expressions (fixed in v0.7.0) | Upgrade to v0.7.0; or wrap with IIFE |
| Pop-ups/masks not visible in screenshot | fixed/absolute overlay not in same rendering layer | Rely on page_data |
call_method reports | v0.6.0 does not return path (fixed in v0.7.0) | Upgrade to v0.7.0; or confirm path with page_data first |
| navigate to TabBar page ineffective | TabBar pages do not support reLaunch/navigateTo | v0.8.0 automatically detects and uses switchTab; or manually |
| Screenshot shows wrong page | Page reset after screenshot connection | Use |
| Long screenshot of scroll-view page only shows one screen | automator SDK cannot capture internal scroll of scroll-view | Known limitation, returns |
Connection Disconnection Recovery Process
When screenshot or automation operation reports or connection failure, execute the following standard recovery process:
Connection closedws://localhost:9420wechat_ide(action='open', project_path='...', cdp_enabled=true) # ① Re-open project
wechat_automator(action='start', project_path='...') # ② Restart automator
wechat_build(action='compile', project_path='...') # ③ Recompile
# ④ Retry the failed operationAbsolute Red Lines
- ❌ Continue executing subsequent test operations after returns
open(must fix errors first)startup_errors - ❌ Call /
previewwithout confirminguploadis_login: true - ❌ Call on production projects
cache_clean(clean_type='all') - ❌ Execute or unsafe code in
eval()evaluate - ❌ Assume running status — must rely on actual data returned by MCP interfaces
- ❌ Retry the same failed operation more than 3 times (should switch to diagnosing root cause)
- ❌ Use hard wait in automated testing (use
sleepor pollwait_ms)page_data - ❌ Actively call screenshot in SOP process — only take screenshots when explicitly requested by user or visual confirmation is needed for troubleshooting
- ❌ Directly perform full recovery when connection is disconnected (should first perform quick recovery: only →
start)page_data - ❌ Compile without code changes (wastes time, directly navigate with evaluate)
- ❌ Do not verify automator connection after compile (v0.8.0 automatically reconnects, but need confirmation)
page_data - ❌ Use subdirectory as project_path for cloud development projects
miniprogram/ - ❌ Do not verify if matches expected page after navigate
page_data.path - ❌ Treat from
console.assertsource in CDP logs as application errorsdevtools:// - ❌ Use in multiple parallel Agents (port 9420 is exclusive)
wechat_automator - ✅ of
output_pathis optional, leave blank to automatically save to projectwechat_screenshotdirectoryscreenshots/ - ✅ Must call before using any automation/screenshot features
automator(action='start') - ✅ Use to confirm element exists before executing
element_info/tapinput - ✅ Confirm version number has been incremented and has been executed before
build_npmupload - ✅ Pay attention to marks in CDP logs (render blocking/performance issues)
[Violation] - ✅ Check if AppID is undefined after
compile - ❌ Use Chinese quotes or unescaped double quotes in WXML attribute values (compilation error that cannot be detected by tools)
"" - ✅ Execute →
open→startto restore connection after screenshot/operation failurecompile - ✅ Must verify current page path via or
page_dataafter navigatepage_stack - ✅ Compare consistency of fields with the same name in cross-page testing