IM-MCP Agent Operations and Data Lifecycle Management Guide
This skill guides the agent in managing the im-mcp toolset (including WeChat MCP and DingTalk MCP) on Windows and macOS, covering pre-flight environment checks, offline database initialization and decryption, chat data retrieval, and secure cleanup after task completion.
1. Core Principles & Execution Strategy
1.1 Runtime Mode Priority and Execution Policy
When guiding or assisting the user with deployment, the agent should follow these execution strategies:
- Prefer Persistent Installation: In environments like Claude Desktop, Cursor, or other desktop clients that support persistent tools, recommend using
uv tool install "git+https://github.com/stkoecn/im-mcp.git" --with "im-mcp[all]"; - Sandbox/Restricted Environment Fallback: If the current AI client environment (e.g., Pi sandbox) blocks global tool installation (prompting
Blocked ... use uvx), follow the environment's security policy and use the ad-hocuvx --from "git+https://github.com/stkoecn/im-mcp.git[all]"approach to run commands; - Domestic Network Mirror Alternative (Gitee Source): If the user is on a domestic network or has restricted/slow access to GitHub, replace the Git address with the Gitee mirror:
- Persistent:
uv tool install "git+https://gitee.com/ws4m/im-mcp.git" --with "im-mcp[all]" - Ad-hoc:
uvx --from "git+https://gitee.com/ws4m/im-mcp.git[all]" <command>
- Persistent:
- No Custom Protocol Test Scripts: After installation and initialization (
wechat-initanddingtalk-init), never write custom scripts or code to simulate the underlying JSON-RPC/stdio protocol tests. Directly deliver the output to the user and provide client activation guidance; - Host Environment Awareness and Delivery Guidance: Based on the current client environment (e.g., Pi, Claude Code/Desktop, Cursor, Cline), the agent should autonomously determine and prompt the user with the specific skill and MCP activation steps (e.g., telling them to enter
/reload, restart the client, or enable trust in the sidebar), and directly provide 1-2 usage examples for daily conversations.
1.2 Command Matrix and Permissions Overview
# Method A: Global persistent installation of CLI toolchain (recommended first choice)
uv tool install "git+https://github.com/stkoecn/im-mcp.git" --with "im-mcp[all]"
Command Matrix:
| Command | Call Method (Global Install) | Ad-hoc uvx Method (Sandbox/Restricted) | Use Case | Permission Requirements | Key Output / Path |
|---|---|---|---|---|---|
wechat-init | wechat-init | uvx --from "git+https://github.com/stkoecn/im-mcp.git[all]" wechat-init | Extract WeChat DBKey and decrypt offline to SQLite database | Windows requires Admin (memory scan); macOS supports --passphrase or persistent config | ~/.wechat_mcp/decrypted/, ~/.wechat_mcp/app.db |
dingtalk-init | dingtalk-init | uvx --from "git+https://github.com/stkoecn/im-mcp.git[all]" dingtalk-init | Extract DingTalk keys offline, decrypt DB and merge WAL transactions | Normal user permissions | ~/.dingtalk_mcp/decrypted/dingtalk.db |
im-clean | im-clean | uvx --from "git+https://github.com/stkoecn/im-mcp.git[all]" im-clean | One-click secure cleanup of all exported plaintext data, keys, and cache | Normal/Admin permissions | Clears decrypted databases and global data directories for both platforms |
wechat-mcp | wechat-mcp | uvx --from "git+https://github.com/stkoecn/im-mcp.git[all]" wechat-mcp | WeChat FastMCP standard server entry point | Normal user permissions | stdio interface |
dingtalk-mcp | dingtalk-mcp | uvx --from "git+https://github.com/stkoecn/im-mcp.git[all]" dingtalk-mcp | DingTalk FastMCP standard server entry point | Normal user permissions | stdio interface |
2. Agent Operation Workflows (Lifecycle Workflows)
2.1 Before Task Start: Automatic Database Initialization (Pre-flight Initialization)
When the user requests actions like "analyze recent WeChat/DingTalk communication", "generate a weekly report", or "find a file in a group chat", and the MCP reports errors like "database not found" or returns empty results, the agent should autonomously perform initialization:
DingTalk Database Initialization
DingTalk uses pure Python local offline decryption, nearly 100% automated, requiring no admin permissions:
# Agent executes initialization
dingtalk-init
- Expected Output: Detects an active UID and outputs
🎉 DingTalk data initialization sync successful!. - Environment Pre-check (No Blind Scanning): If the output indicates no data directory or UID is found, the agent must not blindly recursively deep-scan processes or disks on the host machine. Immediately pause and explain the situation to the user, asking them to confirm that the DingTalk client is logged in on this machine.
WeChat Database Initialization
WeChat requires a key to decrypt and validate the WCDB database:
- Windows:
WeChat needs to extract the key from the memory of the running client process and perform validation. The WeChat client must be launched and logged in. If WeChat is not running,# Windows: Run as Administrator wechat-initwechat-initwill report an error. - macOS:
The tool automatically locates the macOS WeChat data directory (# macOS: Supports directly passing a 64-bit passphrase wechat-init --passphrase <64_byte_hex_passphrase>~/Library/Containers/com.tencent.xinWeChat/Data/Documents/xwechat_files/*/db_storage), uses the system-nativeCommonCrypto(CCCrypt) to derive the key, and completes decryption. - WeChat Runtime Pre-check (No Blind Scanning):
- Important Constraint: If the WeChat process cannot be found or key material is missing, the agent must not attempt to guess, scan unrelated system processes, or traverse global system directories!
- Correct Action: Actively explain the current environment state to the user and guide them to prepare the environment or provide the passphrase.
- Permission Check: If Windows reports
Access Denied, explain the reason to the user and suggest running as Administrator. - Success Indicator: A decrypted database is generated in the user data directory
~/.wechat_mcp/decrypted/, and FTS5 index cleanup is completed in~/.wechat_mcp/app.db. If only re-running data cleanup and indexing is needed, executewechat-init --etl-only.
2.2 During Task Execution: MCP Tool Usage Guidelines
After successful initialization, the agent should prioritize using MCP tools for retrieval, avoiding raw SQL queries:
WeChat Recommended Call Order:
list_wechat_sessions(limit=20): List recent active sessions/group chats to get the keysession_id(e.g.,xxx@chatroomor WeChat ID).search_wechat_messages(query="keyword", limit=50): Global full-text search across chat content (supportsoffsetpagination).get_session_history(session_id="...", limit=100): Get the context message stream for a target session.get_message_image(message_id=...): Decrypt chat images on demand. When searched or historical messages contain[Image], call this tool with the corresponding messageid.- Default mode: Returns the local absolute file path of the decrypted image (cached in
~/.wechat_mcp/images/), preventing Base64 of large images from blowing up the agent context; - Multimodal image analysis mode: If the current agent needs visual image analysis, set
include_base64=Trueto extract the Base64 string for model understanding.
- Default mode: Returns the local absolute file path of the decrypted image (cached in
search_shared_files(keyword="...", limit=20): Locate file paths shared in groups or private chats.
WeChat also provides: get_messages_by_date / get_messages_by_range (retrieve by date or time range), search_contacts (look up contacts), list_chatroom_members (list group members), search_media_files (paths for images/videos on disk), list_favorites (favorites), list_emoticons (emoticons), get_chat_activity_stats (activity statistics), get_persona_style (communication style distillation), get_sync_status (index freshness). get_messages_by_date / get_messages_by_range and search_wechat_messages all support offset pagination.
DingTalk Recommended Call Order:
list_dingtalk_conversations(limit=20): Get a list of recent group chats and private messages (automatically mapped to latest real names and group names).search_dingtalk_messages(keyword="keyword", limit=50): Aggregate search across 128 sub-tables for text retrieval.get_dingtalk_messages(cid="...", limit=100): View conversation details for a specific DingTalk group or private chat.list_dingtalk_contacts(keyword="name/pinyin"): Quickly look up contact UID and real name.
2.3 Version Upgrade & Maintenance (Project Upgrade & Version Maintenance)
When the user requests "update im-mcp", "upgrade WeChat/DingTalk MCP", "pull the latest fixes", or when new features/bug fixes are released, the agent should perform a smooth upgrade based on the current installation method:
1. Upgrade with Global Persistent Installation (Recommended):
If the user previously installed via uv tool install, use uv tool update or reinstall from the Git repository:
# Standard global one-click update
uv tool upgrade im-mcp
# Or force re-install with the latest remote repository version (supports latest Git HEAD)
uv tool install --force "git+https://github.com/stkoecn/im-mcp.git" --with "im-mcp[all]"
# Domestic network (Gitee source)
uv tool install --force "git+https://gitee.com/ws4m/im-mcp.git" --with "im-mcp[all]"
2. Ad-hoc Runtime Mode (uvx):
If running via uvx in a sandbox, uvx may cache the old version Wheel. To upgrade or force refresh the version cache:
# Clean uvx temporary tool cache to ensure the latest Git code is pulled
uv cache clean im-mcp
# Or append the --refresh parameter on the next uvx call to force pulling the latest version
uvx --refresh --from "git+https://github.com/stkoecn/im-mcp.git[all]" <command>
3. Smooth Reload After Upgrade:
After the upgrade is complete, the agent should proactively remind the user to refresh or reload the client to load the latest version of the MCP service definitions and toolset:
- Pi / Pebrel: Prompt to enter
/reload; - Claude Desktop / Cursor / WorkBuddy: Prompt to restart the client or reconnect the MCP server;
- If the upgrade involves changes to the underlying database cleaning logic, execute
wechat-init --etl-onlyto rebuild the latest FTS index non-destructively in 2 seconds, without needing a time-consuming re-extraction or decryption.
2.4 After Task Completion: Data Privacy & Storage Cleanup (Post-flight Cleanup)
After completing tasks like weekly reports, timesheet summaries, or when the user explicitly requests "clean up the environment" or "delete exported chat records", the agent should proactively call im-clean:
Preview files to be cleaned (read-only safety check):
im-clean --dry-run
Execute thorough cleanup:
# Use -y for silent cleanup of all exported plaintext SQLite, keys, and intermediate cache (supports auto-detection and handling of persistent process locks)
im-clean -y
# If residual handles are locked, add --force to force-terminate MCP services and complete the deletion
im-clean -y --force
Clean only specific platform data:
# Clean only WeChat data, preserve DingTalk
im-clean --scope wechat -y
# Clean only DingTalk data, preserve WeChat
im-clean --scope dingtalk -y
2.5 Full Uninstallation & Client Cleanup Coordination (Full Uninstallation Guidance)
When the user explicitly requests "fully uninstall this MCP" or "completely delete the chat tool and its configuration", the agent should assist the user with the following standard sequential cleanup steps, and proactively inform the user which steps they need to perform manually in the client interface:
- Exit the client or stop the service: Remind the user to exit the current AI client first, or let
im-clean -y --forcehandle residual MCP processes automatically; - Automatically clean data: The agent executes
im-clean -y --forceto thoroughly delete~/.wechat_mcpand~/.dingtalk_mcp(ensure the return code is 0; never falsely report success if it is not 0); - Automatically uninstall dependencies: The agent executes
uv tool uninstall im-mcporuv cache cleanto clean the environment and cache; - Proactively output client manual cleanup reminders to the user:
- Based on the current host client, the agent should prompt the user to manually clean up configuration files (refer to [Appendix: Reference Directories for Mainstream Agent Host Environments] at the end of this skill document for common paths).
3. Common Troubleshooting & Agent Behavior Rules (Troubleshooting & Agent Rules)
-
Core Prohibition: Stop Immediately on Error, Never Analyze Code or Blindly Tinker:
- If any unknown error, environment conflict, or execution anomaly occurs during installation, initialization, or test invocation:
- Absolutely Prohibited: The agent must never delve into the source code, write patches, repeatedly guess retry, or blindly investigate the system environment;
- Must Do: Immediately stop at the error step, display the core error summary, and explicitly ask the user:
"An error occurred at the current step:
[brief error description]. Would you like to troubleshoot and resolve the issue yourself, or stop the operation and not proceed?" - Hand control back to the user and take action only after the user confirms to continue or exit.
-
Deliver to User Immediately After Initialization, Never Write Custom Code to Simulate Protocol Repeatedly:
- Once the agent completes tool installation (e.g.,
uv tool install), configuration file writing, andinitinitialization, the entire deployment process is finished. - Absolutely Prohibited: The agent must never privately write Python/Node test scripts to simulate JSON-RPC 2.0 handshakes, pipe communication, or explore protocol internals. This not only wastes tokens and introduces uncontrollable error risks but also deprives the user of real-time awareness and control.
- Must Do: After installation and initialization are complete, directly deliver and provide the most concise and user-friendly usage guidance:
- Clearly prompt the user to enable/trust this MCP in the current client (e.g., tell Pi users to execute
/reload, Claude Desktop / Cursor users to restart the client for it to take effect); - Provide 1-2 simple, intuitive natural language examples to guide the user experience, for example:
*"Installation and initialization are ready! Please confirm trust/activation of this MCP in your client (e.g., execute
/reload). Then you can start using it by saying something like:" *👉 'Check what was discussed in the recent project group'" *👉 'Find the report statistics sent by Cheng Peng in DingTalk'" *👉 'Summarize last week's communication records about requirement X for a weekly report'"
- Clearly prompt the user to enable/trust this MCP in the current client (e.g., tell Pi users to execute
- Once the agent completes tool installation (e.g.,
-
Client and Application Authorization/Trust (Autonomous Host Environment Identification and Activation Guidance):
- The agent must autonomously identify the client host the user is currently using based on the session characteristics;
- Never vaguely say "enable it in your client"; instead, provide the specific activation method for the corresponding client based on the current host (e.g., prompt Pi to enter
/reload, or prompt desktop apps to restart for changes to take effect; refer to the appendix at the end of this document for specific characteristics).
-
Behavior Constraints When WeChat/DingTalk Process Not Found:
- Never autonomously perform time-consuming and intrusive full-disk brute-force scans or guess other system processes on the host machine;
- Must immediately pause and politely ask the user to confirm the client login status.
-
WeChat Incremental Message Sync Issue: When the WeChat client is online, new messages are written to the original encrypted database. To retrieve newly generated messages, the agent can prompt the user to "re-run
wechat-init" to update the local decrypted database. -
DingTalk WAL Lock Issue:
dingtalk-inithas a built-in automatic copy mechanism, so even if DingTalk is running and in a WAL transaction, SQLite lock conflicts will not occur. -
Privacy Security Principle: Decrypted SQLite databases are sensitive local private data. In public machines or multi-tenant environments, always guide or automatically execute
im-clean -yafter task completion. -
Deployment Feedback Report & Community Auto-Development Mechanism (Deployment Feedback & Auto-Development):
- Whether the deployment and initialization succeed or fail, at the end of the process, the agent should proactively organize and generate a structured, concise "Deployment and Operations Feedback Brief" for the user, and prompt them that they can copy it and submit an Issue on GitHub.
- ⚠️ Core Highlighting Principle (Must be prominently marked, never vague):
- The report title and first status line must use highly visible visual markers (e.g.,
[Status: 🟢 Deployment Successful / SUCCESS]or[Status: 🔴 Deployment Blocked / FAILED]); - Strictly avoid ambiguous or neutral language, so that the user and any diagnosing agent can immediately see success or failure.
- The report title and first status line must use highly visible visual markers (e.g.,
- Agent Auto-Ops Commitment: Prompt the user: "This project is connected to a GitHub Agent automation collaboration pipeline. Issues you submit will be automatically reproduced, diagnosed, and fixed by a dedicated agent, which will also merge the pull request!"
- Brief Generation Standard Template:
- If SUCCESS:
### 📋 im-mcp Deployment Feedback Report [Status: 🟢 Deployment Successful / SUCCESS] > **Final Conclusion**: ✅ All dependencies installed successfully, data extraction and index synchronization completed. Service is ready for immediate invocation! - **Core Status**: 🟢 SUCCESS - **Environment Info**: OS version (e.g., Win11 23H2), Client host (e.g., WorkBuddy / Pi / Claude Desktop), Python and uv versions - **Installation Mode**: `uv tool install` / `uvx` / local source code - **Initialization Metrics**: Time (e.g., WeChat 12s / DingTalk 3s), Number of contacts/sessions/messages synced - **Usage Suggestions**: Cold start experience, incremental sync guidance, or desired future features - **Feedback Entry**: Go to [GitHub Issues](https://github.com/stkoecn/im-mcp/issues) to share your experience. The community agent will automatically track and optimize! - If FAILED:
### ⚠️ im-mcp Deployment Feedback Report [Status: 🔴 Deployment Blocked / FAILED] > **Final Conclusion**: ❌ The process was interrupted mid-step. Core services cannot start normally. Please refer to the following troubleshooting details. - **Core Status**: 🔴 FAILED - **Blocked Phase**: Dependency installation / WeChat key extraction / DingTalk decryption / Database index building / Client mounting - **Environment Characteristics**: OS version, Client host, WeChat version (e.g., 4.x / 3.x), DingTalk version (e.g., 7.x V3) - **Key Error Summary**: Extract the core error stack or system prompt (e.g., Access Denied / Process not running / File lock rejected) - **Attempted Measures**: Was privilege escalation tried? Was `--force` or `--etl-only` attempted? - **Improvement Suggestions**: Point out steps in the current process that were not smooth or where automated fault tolerance is needed. - **One-Click Feedback**: Please copy this report and submit it at [GitHub Issues](https://github.com/stkoecn/im-mcp/issues). The repo's dedicated agent will automatically analyze the logs and start fixing!
- If SUCCESS:
4. Appendix: Reference Directories for Mainstream Agent Host Environments (For Reference Only)
💡 Disclaimer: This directory lists the default behaviors and configuration characteristics of current mainstream AI client/agent environments for reference only. These may change with platform version updates. Please refer to the corresponding platform's official documentation for the most recent information.
| Client Environment | Typical Identification Features | Configuration / Activation Method Reference | Uninstall & Cleanup Method Reference |
|---|---|---|---|
| Pi / Pebrel | PI_* environment variables or ~/.pi/ directory | Edit ~/.pi/agent/mcp.json, enter /reload in the session to reload | Remove entry from mcp.json, delete ~/.agents/skills/im-mcp, enter /reload |
| Claude Desktop | Claude configuration in local AppData | Edit %APPDATA%\Claude\claude_desktop_config.json. Fully restart the client application. | Remove the entry from the mcpServers in the config file and restart the software. Clean the skill directory. |
| Cursor | VS Code derivative with Cursor configuration | Add in Settings ➔ Features ➔ MCP Servers. Mounts instantly via the UI. | Click Delete / Remove on the corresponding entry in the MCP server list. |
| Cline / Roo Code | VS Code extension panel | Add configuration in the extension sidebar's MCP tab. Toggle to "Enabled" to activate and authorize. | Turn off the toggle or click the trash icon to remove in the sidebar MCP list. |
| Cherry Studio | Desktop multi-model management tool | Add a stdio command in Settings ➔ MCP Server. Save to apply. | Select the entry in the MCP server list and click "Delete", then save settings. |
| WorkBuddy | ~/.workbuddy/ directory or related configuration | Edit ~/.workbuddy/mcp.json. Manually click "Trust/Enable" in the connector management interface. | Remove the configuration block from mcp.json and remove the connector in the interface. |