Skip to main content
Glama
weinh

wechat-mcp-publisher

by weinh

wechat-mcp-publisher

Локальный MCP-инструмент для публикации черновиков в официальном аккаунте WeChat. Превращает «готовый HTML → черновик официального аккаунта» в один вызов инструмента LLM: загрузка изображений, замена встроенных изображений в тексте на URL WeChat, материалы обложки и создание черновика — всё выполняется автоматически.

Построен на официальном SDK mcp (2.x MCPServer), транспорт stdio, один аккаунт, зависимости управляются через uv.

Инструменты (5)

Инструмент

Назначение

create_news_draft

Черновик статьи: принимает HTML (или путь к файлу .html) + изображение обложки; встроенные <img> автоматически загружаются и заменяются на URL WeChat

create_newspic_draft

Черновик сообщения с изображением: текстовое описание + 1–20 изображений (по порядку)

list_drafts

Постраничный просмотр черновиков

get_draft

Детали черновика (включая содержимое)

delete_draft

Удаление черновика (без удаления материалов)

access_token получается внутри, кэшируется и самовосстанавливается при истечении (stable_token + автоматическое обновление и повторная попытка при кодах 40001/42001), не предоставляется как инструмент. Ошибки единообразно преобразуются в сообщения на китайском языке с подсказками по устранению (например, 40164 — добавить IP в белый список, 48001 — нужна верифицированная учётная запись) и не содержат учётных данных.

Related MCP server: WeChat Official Account MCP Server

Установка

uv sync
cp .env.example .env   # 填入 WECHAT_APP_ID / WECHAT_APP_SECRET

Получение учётных данных: mp.weixin.qq.com → «Настройки и разработка» → «Основная конфигурация». На той же странице необходимо добавить публичный IP этой машины в IP-белый список, иначе при получении token будет ошибка 40164.

После публикации на PyPI также можно запускать без клонирования (в каталоге с .env):

uvx wechat-mcp-publisher
# 或 pip install wechat-mcp-publisher && wechat-mcp-publisher

В этом случае конфигурация MCP-клиента упрощается до "command": "uvx", "args": ["wechat-mcp-publisher"].

Подключение MCP-клиента

Claude Code (рекомендуется, одна команда):

claude mcp add wechat-mcp-publisher -- uv run --directory /你的路径/wechat-mcp-publisher python -m wechat_mcp_publisher

Конфигурация уровня проекта (в этом репозитории уже есть .mcp.json; Claude Code активирует её при открытии каталога репозитория, при первом запуске нужно подтвердить доверие в /mcp): добавлять вручную не требуется.

Claude Desktop / другие клиенты: вставьте фрагмент из examples/mcp-client-config.example.json в соответствующий конфигурационный файл.

Примеры использования

Скажите LLM:

Помоги мне отправить /path/article.html как черновик статьи официального аккаунта, обложка — /path/cover.jpg

Или сообщение с изображениями:

Отправь эти три изображения /a.jpg /b.jpg /c.jpg как черновик сообщения с картинками, пояснение: кадры выходных

Демонстрация реальной цепочки API — в examples/simple_usage.py (token → загрузка → создание черновика, используется также как smoke-тест на реальном устройстве).

Тестирование

uv run pytest

Все интерфейсы замоканы через responses, для прохождения не нужен реальный аккаунт.

Область применения и известные ограничения

  • Не выполняет преобразование markdown→HTML: на входе — HTML; для преобразования используйте уже имеющийся у вас инструмент md→html

  • Не выполняет публикацию (freepublish): сейчас работает только до черновика; публикация остаётся на потом, после верификации аккаунта

  • Личный неверифицированный подписной аккаунт: API материалов/черновиков возвращает 48001; для проверки на реальном устройстве нужен верифицированный аккаунт (на разработку и тестирование не влияет)

  • Совместимость HTML с WeChat: редактор WeChat распознаёт только подмножество HTML с инлайновыми стилями; адаптацию вёрстки выполняет вышестоящий инструмент преобразования; данный инструмент не проверяет и не исправляет

  • Накопление материалов: удаление черновика не удаляет занятые им постоянные изображения; при длительном использовании нужно периодически чистить их в панели управления официального аккаунта

  • Один аккаунт: учётные данные берутся из .env, переключение между аккаунтами не предусмотрено

Available Tools

5 tools
create_news_draftA

创建图文草稿(news),成功返回 {"media_id": ..., "title": ..., "cover_url": ...}。

参数:
  title: 文章标题(必填)
  content: 正文。支持两种形态——HTML 字符串,或本地 .html 文件路径
           (若该路径存在则自动读取文件,否则按 HTML 内容处理)
  cover: 封面图片(必填):本地文件路径或 http(s) URL,自动上传为封面素材
  author: 作者名(可选)
  digest: 摘要(可选,留空时微信自动截取正文)
  content_source_url: 原文链接(可选)

正文 HTML 中的 <img> 会自动上传到微信并替换 src 为微信托管的 URL;
已指向微信域名(mmbiz.qpic.cn / mp.weixin.qq.com)的图片保持不变。
NameRequiredDescriptionDefault
coverYes
titleYes
authorNo
digestNo
contentYes
content_source_urlNo

Output Schema

NameRequiredDescription

No output parameters

TDQS

A4.6/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are present, so the description carries full responsibility. It discloses several non-obvious behaviors: content may be a file path that is auto-read, cover is auto-uploaded, <img> URLs are rewritten to WeChat-hosted URLs while WeChat-domain images are left intact, and an empty digest triggers automatic extraction. This is well beyond baseline.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is front-loaded with purpose and return value, then organized as a labeled parameter list. Every sentence adds operational value, including the image-handling note, with no filler.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a 6-parameter creation tool with an output schema, the description covers input formats, side effects, image handling, and return shape. No gaps remain for an agent to call it correctly.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema descriptions are 0% covered, and the description compensates fully by explaining each parameter (title, content with dual forms, cover with path/URL and auto-upload, author, digest fallback, content_source_url). It adds requiredness and behavioral nuances the schema lacks.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description opens with a specific verb ('创建' - create) and resource ('图文草稿(news)'), and names the successful return fields. It clearly identifies the tool's function and is distinguishable from sibling tools like delete_draft or list_drafts by the create/news-specific framing.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No explicit comparison to siblings is provided. The intended use case (creating a news draft) is implied by the name and the headline phrase, but the description does not state when to choose this over create_newspic_draft or when not to use it.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

create_newspic_draftA

创建图片消息草稿(newspic),成功返回 {"media_id": ..., "title": ..., "image_count": ...}。

参数:
  title: 消息标题(必填)
  images: 1~20 张图片,按传入顺序展示;每项为本地文件路径或 http(s) URL
  content: 图片下方的纯文字说明(可选,注意不是 HTML)

与图文消息不同:图片消息的 content 是纯文本,图片本体在 images 中,
全部经永久素材接口上传后按序组装。
NameRequiredDescriptionDefault
titleYes
imagesYes
contentNo

Output Schema

NameRequiredDescription

No output parameters

TDQS

A4.8/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full disclosure burden. It goes beyond basics by stating the success return structure, the 1-20 image limit, the ordering behavior, the plain-text nature of content, and that images are uploaded via the permanent material interface and assembled in order. This gives an agent a strong mental model of what invoking the tool does.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-structured and front-loaded: purpose and return format come first, followed by a concise parameter list and a clarifying note about the difference from news messages. Every sentence adds value, with no filler or repetition.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a 3-parameter draft creation tool with an output schema, the description covers purpose, parameters with constraints, return format, and behavioral nuances. It also addresses the sibling distinction. Nothing essential for an agent to correctly select and invoke the tool is missing.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Input schema coverage is 0%, so the description must fully explain parameters. It does: title is required, images allows 1-20 items with local file path or http(s) URL and ordering, content is optional plain text (explicitly not HTML). This adds substantial meaning beyond the raw schema fields.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description opens with a specific verb and resource: '创建图片消息草稿' (create image message draft), which clearly states what the tool does. It also distinguishes itself from the related '图文消息' (news/image-text) concept, helping an agent differentiate it from sibling tools without ambiguity.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides clear context by contrasting with 图文消息: it explicitly notes that image message content is plain text and the images are in the images parameter, which implies when this tool is appropriate. However, it does not explicitly name the sibling tool (create_news_draft) or state a direct 'use this when, use that instead' rule, so it falls just short of fully explicit guidance.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

delete_draftA

删除指定草稿,成功返回 {"media_id": ..., "deleted": true}。

注意:删除草稿不会连带删除其占用的永久素材图片(微信行为)。
参数:
  media_id: 草稿 ID
NameRequiredDescriptionDefault
media_idYes

Output Schema

NameRequiredDescription

No output parameters

TDQS

A4.2/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden. It does disclose a critical behavioral trait beyond the schema: deleting a draft does not delete the associated permanent materials (微信行为). It also shows the success return shape. For a tool with zero annotations, this is meaningful behavioral disclosure, although it falls short of full transparency (e.g., no error behavior, no idempotency note, no permission requirements).

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is compact: two sentences plus a one-item parameter list. The key behavioral warning (does not delete associated permanent materials) is front-loaded in the attention paragraph before the parameter list. Every sentence earns its place; no filler or redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

The tool has only one parameter, an output schema exists, and the description adds the success return and the critical non-cascade deletion behavior. For a simple delete tool, this is largely complete. Missing minor items could include error conditions, idempotency, or permission requirements, but the description's length and clarity are appropriate for the level of complexity.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must compensate. It does add meaning by explaining media_id is the draft ID and it's the sole parameter, and the success response references it. However, it only repeats the schema's 'Media Id' notion with '草稿 ID' and doesn't add more depth such as where to find this ID or constraints on the value. Basic useful compensation for one required parameter, but not rich enough for a higher score.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description uses a specific verb ('删除') with a clear resource ('指定草稿'), satisfying the purpose statement requirement of verb+resource. It explicitly states the success return value, and although siblings exist for managing drafts (create, list, get), this delete operation is clearly distinguished by the delete semantics and the mention of behavior that only deletion triggers (永久素材 not being released).

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides clear context for when to use the tool: when deleting a specified draft by media_id. It does not explicitly name alternatives or exclusions, but sibling tools are self-evidently create/list/get, and the delete action is unambiguous. Strong context for a simple delete router, though it could have explicitly said 'use get_draft/list_drafts to find drafts, not this tool.'

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

get_draftA

查询草稿详情(含 news_item 全部字段:标题、正文 HTML、封面等)。

参数:
  media_id: 草稿 ID(由 create_news_draft / create_newspic_draft 返回,或从 list_drafts 获取)
NameRequiredDescriptionDefault
media_idYes

Output Schema

NameRequiredDescription

No output parameters

TDQS

A4.1/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the burden of disclosing behavior. It discloses the output contents—title, body HTML, cover—and implies a read-only operation via '查询', but it does not mention error cases, permissions, or side effects. This is acceptable for a simple retrieval tool but not exhaustive.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is compact and front-loaded: one sentence states the purpose and return contents, and one line defines the parameter. There is no redundant phrasing or repetition of schema information.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a simple retrieval tool with one required parameter and an output schema, the description is nearly complete: it covers what is returned and where the ID comes from. The remaining gaps are explicit usage differentiation from sibling tools and edge-case behavior, which are minor but would improve completeness.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0% and the schema only provides type/title. The description compensates fully by explaining that media_id is the draft ID returned by the draft-creation tools or obtainable from list_drafts, which is exactly the semantic information an agent needs to populate the parameter correctly.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

States a specific action (查询草稿详情) on a specific resource (draft identified by media_id), and further specifies that it returns the full news_item fields including title, body HTML, and cover. This clearly distinguishes it from the sibling create/list/delete tools.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description gives useful operational guidance by explaining where media_id comes from (create_news_draft, create_newspic_draft, or list_drafts). However, it does not explicitly state when to prefer get_draft over list_drafts or how it differs from them; the when-to-use context is only implied by the verb 'get' and the mention of '详情'.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

list_draftsA

分页查询草稿箱列表,返回 {"total": 总数, "offset": 当前偏移, "items": [{media_id, title, update_time}]}。

参数:
  offset: 起始位置(默认 0)
  count: 每页数量(默认 20,最大 20)
NameRequiredDescriptionDefault
countNo
offsetNo

Output Schema

NameRequiredDescription

No output parameters

TDQS

A4.3/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

无 annotations,描述承担了行为披露责任。它补充了分页行为(offset/count 默认值、count 上限 20)以及返回结构(total/offset/items 及字段),足以让代理理解这是只读查询并预知响应。但未说明排序、错误处理或鉴权等边界情况。

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

描述采用两段式结构:先给出返回格式,再列出参数说明。没有冗余内容,信息密度高且易于扫描。

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

对于只有两个可选参数的列表查询工具,描述覆盖了调用所需的核心信息:分页参数、默认值、上限和返回结构。虽然未涉及排序或错误处理,但结合输出 schema 已足以支持正确调用。

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

输入 schema 的参数没有描述,覆盖率为 0%,但描述为 offset 提供了“起始位置”的语义,为 count 提供了“每页数量”的语义,并补充了最大值为 20 的限制。描述有效补偿了 schema 的空白。

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

描述明确说明工具用于“分页查询草稿箱列表”,动词和资源清晰,且与兄弟工具(创建草稿、获取单个草稿、删除草稿)形成明显区分。即使不看名字,也能知道这是列表查询操作。

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

描述隐含了“需要草稿列表时使用此工具”的用法,但未显式说明何时不该使用,也未与 get_draft 或创建类工具做取舍对比。用法可推断,但缺少明确指引。

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

  1. 5 tool updatesv0.1.0
    • First observedcreate_news_draft
    • First observedcreate_newspic_draft
    • First observeddelete_draft
    • First observedget_draft
    • First observedlist_drafts

TDQS

A4.3/5.0

Scored across 5 tools

Disambiguation5/5

The two create tools are clearly separated by draft type (newspic vs news) with distinct parameter semantics, while list, get, and delete have unambiguous scopes. No two tools appear to overlap in purpose.

Naming Consistency4/5

Most tools follow a verb_noun snake_case pattern such as list_drafts, get_draft, and delete_draft. The create tools also align with verb+type+draft, though 'newspic' vs 'news' is a slightly non-parallel naming choice.

Tool Count5/5

Five tools is well-scoped for a draft-management server: two creation variants plus standard list, get, and delete operations. Each tool earns its place without unnecessary overlap or bloat.

Completeness3/5

The set covers create, read/list, and delete for drafts, but lacks an update_draft operation, forcing agents to delete and recreate to modify content. Additionally, despite the 'publisher' name, there is no publish/send tool, leaving a notable gap in the apparent domain.

Maintenance

ActivityStale
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers