Metadata-Version: 2.5
Name: wechat-draft-editor
Version: 0.7.0
Summary: Edit and preview WeChat Official Account drafts through Microsoft Edge and MCP on Windows.
Project-URL: Repository, https://github.com/MosRat/wx_gzh_plugin
Project-URL: Issues, https://github.com/MosRat/wx_gzh_plugin/issues
License-Expression: MIT
License-File: LICENSE
Classifier: Operating System :: Microsoft :: Windows
Classifier: Programming Language :: Python :: 3
Requires-Python: >=3.10
Requires-Dist: mcp<2,>=1.12
Requires-Dist: playwright<2,>=1.50
Description-Content-Type: text/markdown

# WeChat Draft Editor for Edge and MCP

[![CI](https://github.com/MosRat/wx_gzh_plugin/actions/workflows/ci.yml/badge.svg)](https://github.com/MosRat/wx_gzh_plugin/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/wechat-draft-editor)](https://pypi.org/project/wechat-draft-editor/)
[![Release](https://img.shields.io/github/v/release/MosRat/wx_gzh_plugin)](https://github.com/MosRat/wx_gzh_plugin/releases/latest)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://github.com/MosRat/wx_gzh_plugin/blob/main/LICENSE)
![Platform: Windows / Edge](https://img.shields.io/badge/Platform-Windows%20%7C%20Edge-0078D4)

English | [简体中文](https://github.com/MosRat/wx_gzh_plugin/blob/main/README.zh-CN.md) | [Agent Guide (AGENTS.md)](https://github.com/MosRat/wx_gzh_plugin/blob/main/AGENTS.md)

Edit a WeChat Official Account article from a local AI agent while keeping the draft open in Microsoft Edge. Click the extension on the article you want to work on, then ask your agent to read a section, replace a paragraph, or check how a caption wraps on a phone. The extension uses your existing editor session. Saving a draft is an explicit tool call; publication stays in the WeChat interface.

```text
AI Agent (MCP Client) ──stdio──▶ agent.py ──Windows Named Pipe──▶ bridge.py (Native Host) ──Native Messaging──▶ Edge Extension (mp.weixin.qq.com)
```

## Install on Windows

You need **Windows**, **Microsoft Edge**, and **[uv](https://docs.astral.sh/uv/getting-started/installation/)**. You do **not** need to install or configure a standalone Python interpreter—`uv` automatically downloads and manages Python 3.10+ for you.

### 1. Install `uv`

Install `uv` in PowerShell using one of the following methods, then **reopen PowerShell** and verify with `uv --version`:

```powershell
# Official PowerShell installer (recommended)
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"

# Or via WinGet
winget install --id=astral-sh.uv -e

# Or via Scoop
scoop install main/uv
```

### 2. Load the Edge extension

Download the Edge ZIP from the [latest GitHub release](https://github.com/MosRat/wx_gzh_plugin/releases/latest) and extract it to a permanent folder. In `edge://extensions`, enable **Developer mode**, click **Load unpacked**, select the folder containing `manifest.json`, and copy the extension ID. From a source checkout, select the `extension` directory.

### 3. Install the native host and connect your agent

Choose one of the following installation paths. After registering the host, open your draft at `mp.weixin.qq.com` and click the extension icon. The **ON** badge identifies the connected tab.

#### Option A · PyPI (recommended)

Install the [Python package](https://pypi.org/project/wechat-draft-editor/) via `uv` and register the host. The last command configures Codex.

```powershell
uv tool install wechat-draft-editor
wechat-draft-editor install-host --extension-id (Read-Host 'Paste your Edge extension ID')
codex mcp add wechat-editor -- wechat-draft-editor serve
```

Other stdio clients can launch `wechat-draft-editor` with the argument `serve`. If the client cannot find the command, use the full path returned by `(Get-Command wechat-draft-editor).Source`. To upgrade, run `uv tool upgrade wechat-draft-editor`, then rerun `install-host` to update the registered copy of the native host.

#### Option B · MCP ZIP or source checkout

Download the MCP ZIP from the same release and extract it to a separate folder, or use the repository root. Open PowerShell in the folder containing `install.ps1` and register the host (`install.ps1` uses `uv` to locate or install Python 3.10+ automatically):

```powershell
.\install.ps1 -ExtensionId (Read-Host 'Paste the extension ID from Edge')
```

Then connect the ZIP or source installation to an agent. For Codex, run this from the folder containing `agent.py`, then start a new Codex session:

```powershell
codex mcp add wechat-editor -- uv run --locked --script "$PWD\agent.py"
```

For another stdio MCP client, set the command to `uv` and pass the arguments shown below. Replace the example script path with its absolute path on your machine. Keep the extracted MCP directory intact. On first launch, `uv` installs the locked dependencies.

```json
{
  "mcpServers": {
    "wechat-editor": {
      "command": "uv",
      "args": ["run", "--locked", "--script", "C:/Tools/wechat-editor/mcp/agent.py"]
    }
  }
}
```

### 4. Check the connection

Try this read-only request first:

> Read the connected draft and tell me its title. Find the last photo caption and show me how it wraps on an iPhone 13 in portrait orientation.

For an edit, quote the exact passage and its replacement. Ask the agent to read the edited paragraph back before saving. Local passage replacement requires a unique match, which helps preserve surrounding images and formatting.

## Tools

| Task | MCP tools and behavior |
| --- | --- |
| Inspect the draft | `mp_check_status` reports the connected title. `mp_get_regions` reads structured fields and their write status. `mp_get_draft` also returns body HTML. |
| Edit text | `mp_set_field` edits a writable title, author or summary. `mp_replace_passage` replaces a unique passage. `mp_write_body` appends plain text by default; its `replace` mode replaces the entire body, including images. |
| Import formatted HTML | `mp_import_rich_article` sanitizes a local HTML file, uploads referenced local PNG/JPEG images (`cid:` or `data:`) to WeChat via the editor session, and replaces the body after verifying the expected title. |
| Adjust supported templates | `mp_fit_banner` adjusts heading padding and spacing. `mp_fit_caption` groups caption text by phrase. `mp_align_credits` aligns the writing and layout credit separators. |
| Inspect the live editor | `mp_get_layout` returns paragraph bounds and image statistics. `mp_show_passage` scrolls to a unique passage. `mp_visual_verify` returns a JPEG of the visible editor tab, including its sidebars. Keep the tab selected for capture. |
| Preview the article at another size | `mp_device_preview` renders a copy of the draft in a separate Edge process. Choose `iPhone 13`, `Pixel 7`, or `iPad Mini`, with optional passage and landscape arguments. WeChat's mobile client can differ in font metrics and asset loading. |
| Save | `mp_save_draft` clicks the editor's save-draft button. Check the saved status in WeChat to confirm persistence. |

### Import a formatted article

Use the MCP tool `mp_import_rich_article(html_path, expected_title, images)` or run the CLI from an installation containing this feature:

```powershell
wechat-draft-editor import-html article.html --expected-title 'Current draft title' --image figure1 figure1.png
```

Use `<img src="cid:figure1">` for the example above. With MCP, pass `{"figure1": "C:/papers/figure1.png"}` as `images`. Embedded PNG/JPEG data URLs and existing WeChat CDN images also work. A single `<article>` selects the body inside a full HTML document. The importer preserves supported text formatting, inline layout and image order. It discards scripts, event attributes and unsupported styles. Local files are read on the MCP server machine.

The importer transfers up to 24 MiB of encoded input in chunks and uploads each distinct local image (up to 8 MiB) to the connected account before replacing the body. Uploads use the editor session and depend on WeChat's web upload interface. If an upload fails or the draft changes during import, the existing body stays in place. Already uploaded images may remain in the media library. A verification error after insertion means the body needs inspection. After success, inspect the draft and use the separate save tool. Update and reconnect the extension when updating the MCP server.

## Use the CLI without an agent

The CLI accepts UTF-8 text files via `--file` for text operations, or structured JSON arguments via `--payload`.

If you installed via **Option A (PyPI)**, use `wechat-draft-editor bridge`:

```powershell
wechat-draft-editor bridge status
wechat-draft-editor bridge regions
wechat-draft-editor bridge append --file paragraph.txt
wechat-draft-editor bridge read
wechat-draft-editor bridge save
```

Examples using `--payload` (PowerShell 7.3+ with standard native argument passing):

```powershell
wechat-draft-editor bridge layout --payload '{"offset":40}'
wechat-draft-editor bridge replace_passage --payload '{"oldText":"Original phrase","newText":""}'
wechat-draft-editor bridge fit_caption --payload '["First phrase ","second phrase"]'
wechat-draft-editor bridge align_credits
```

If you are running from **Option B (MCP ZIP or source checkout)**, invoke `bridge.py` via `uv` from that folder:

```powershell
uv run --no-project --python ">=3.10" bridge.py status
uv run --no-project --python ">=3.10" bridge.py append --file paragraph.txt
uv run --no-project --python ">=3.10" bridge.py layout --payload '{"offset":40}'
```

Use `wechat-draft-editor bridge --help` (or `uv run --no-project --python ">=3.10" bridge.py --help`) for the full list of browser operations, and `wechat-draft-editor import-html --help` for rich HTML import options. Device emulation runs in the MCP server, which reuses a headless Edge process and closes each isolated browser context after its screenshot.

## Connection and upgrades

- **Switch articles:** click the extension on the new editor tab. Clicking it again on the connected tab disconnects it. Within one browser session the extension restores the selected tab after a worker restart and retries temporary host failures up to five times. On refresh, it resumes only for the same editor URL with an existing numeric appmsgid. A new draft, changed URL, browser restart or extension reload requires a new click. The … badge indicates recovery. Read the draft before retrying an interrupted edit.
- **ERR badge:** hover over the icon for the reason. For host-registration errors, rerun the installer with the ID currently shown in Edge. If multiple editor regions match, place the caret in the article body and reconnect.
- **Managed Python runtime:** the installer resolves and records the base Python executable managed by `uv`. If you remove `uv`'s managed Python installations later, rerun `wechat-draft-editor install-host` (or `.\install.ps1`).
- **Key rotation:** to replace a potentially exposed key, disconnect the extension, run `wechat-draft-editor install-host --extension-id <extension-id> --rotate-key` (or `.\install.ps1 -ExtensionId <extension-id> -RotateKey` for ZIP/source installs), then reconnect. Regular reinstalls preserve the key.
- **Upgrade:** for PyPI installs, run `uv tool upgrade wechat-draft-editor`, reload the updated Edge extension, rerun `wechat-draft-editor install-host`, and restart the MCP session. For ZIP installs, extract the new files into their existing folders, reload the extension in Edge, rerun `.\install.ps1`, and restart the MCP session. Keeping the unpacked extension at the same path helps preserve its ID. See [CHANGELOG.md](https://github.com/MosRat/wx_gzh_plugin/blob/main/CHANGELOG.md) for version-specific upgrade notes (such as the v0.5 protocol change).

## How it works

The MCP server (`agent.py` / `wechat-draft-editor serve`) and CLI send requests through an authenticated Windows named pipe. Edge launches `bridge.py` as a Native Messaging host and restricts access to the extension ID registered by the installer. The host registration, scripts, and generated authentication key live under the current Windows user in `%LOCALAPPDATA%\WxDraftAgent`.

The extension binds requests to the selected tab and document, storing the tab ID, document ID and a prefixed SHA-256 hash of the editor URL in `chrome.storage.session` for in-session recovery. `extension/editor.js`, `extension/editor-support.js`, `extension/templates.js`, and `extension/rich-import.js` locate article fields, sanitize HTML imports, and apply supported edits. `wechat_draft_editor/rich_import.py` chunks local HTML and image payloads, and `wechat_draft_editor/device_preview.py` handles alternative viewport rendering.

## Security, privacy, and disclaimer

- **Local-only bridge:** Edge communicates with the native host over stdio. The MCP server connects to that host through an authenticated Windows named pipe. The installer restricts NTFS permissions on `%LOCALAPPDATA%\WxDraftAgent` and its key file to the installing Windows user.
- **Session recovery & permissions:** The extension uses `chrome.storage.session` (browser memory only) to persist tab and document IDs alongside a SHA-256 hash of the connected editor URL for automatic recovery; raw URLs, tokens, and draft contents are never written to extension storage.
- **Sanitized rich import & uploads:** `extension/rich-import.js` parses local HTML inside an inert `<template>`, strips scripts, event handlers, and unsupported styles, and allows only PNG/JPEG images or WeChat CDN URLs. Local image uploads run in the active `mp.weixin.qq.com` editor tab with `credentials: "same-origin"` and `redirect: "error"`.
- **Isolated device preview:** `wechat_draft_editor/device_preview.py` sanitizes draft HTML into a sandboxed page with a strict Content Security Policy (`default-src 'none'`) and allows only HTTPS image requests to `mmbiz.qpic.cn` and `mmbiz.qlogo.cn` with redirects blocked.
- **Data shared with your AI agent:** This project collects no telemetry and contacts no author-hosted servers. However, any draft text, HTML, or screenshots requested through MCP tools are sent to the MCP client and AI model provider you configure.
- **Timeout safety:** After a write timeout, read the current draft before retrying because the editor may already have applied the change.
- **Non-affiliation:** This is an independent open-source project and is not affiliated with, endorsed by, or supported by Tencent or WeChat. Changes to the WeChat Official Account editor DOM may require extension updates.

## Development and contributing

Issues and pull requests are welcome. From a source checkout on Windows, install the locked runtime and development dependencies with `uv` and run the validation suite:

```powershell
$env:UV_DEFAULT_INDEX = 'https://pypi.org/simple'
uv lock --check --script agent.py
uv sync --locked
uv run --locked python tests/check_locks.py
uv run --locked ruff check .
uv run --locked ruff format --check .
node --test tests/worker.test.cjs
uv run --locked python -m unittest discover -s tests -v
```

The browser tests require Microsoft Edge. For the worker tests, use Node 22 or later. If the default `uv` cache is inaccessible, set `UV_CACHE_DIR` to a writable user directory. Windows CI also runs `./tests/installer.ps1` under both Windows PowerShell and PowerShell 7 against a temporary profile and registry subtree. Keep the PEP 723 runtime requirements in `agent.py` and the dependencies in `pyproject.toml` in sync when updating `agent.py.lock` and `uv.lock`.

### Commit messages

Use Conventional Commits with an imperative subject, for example `fix(bridge): discard expired replies` or `test(editor): cover caption wrapping`. Use `chore(release): prepare vX.Y.Z` for release preparation. Describe incompatible protocol changes in the commit body and the release notes.

### Publishing a release

Publish a GitHub Release with a tag matching both the Python project and the extension version, for example `v0.6.0`. The release workflow runs Windows CI, builds the wheel and source distribution, uploads them to PyPI, and attaches both ZIP downloads and their checksums to the release. The upload step reads `UV_PUBLISH_TOKEN` from the GitHub Actions environment named `pypi`.

## License

Released under the [MIT License](https://github.com/MosRat/wx_gzh_plugin/blob/main/LICENSE).
