CodexでWordPressブログを安全に執筆・管理する方法|Easy MCP AIで投稿・更新をつなぐ

WordPress MCPを使ったバックアップ・差分確認・安全更新の図 AI活用

このブログでは、僕の開発メモや検証コードをもとに、Codexと一緒に原稿を整理し、WordPressへ反映しています。便利なのは、本文を書き換えるだけでなく、画像、内部リンク、検索向けの説明文まで一つの作業として確認できることです。ここでは、この環境を自分のブログに用意する手順を紹介します。

僕のブログでは、記事の相談、リサーチ、執筆、画像の登録、投稿、既存記事の修正までをCodexと進めています。この記事では、その作業環境を自分のWordPressに作り、下書き1本を保存して、確認後に公開するところまでを説明します。

使うのは、Codexのクラウド環境、GitHub、WordPressプラグインのEasy MCP AI、そしてPythonの小さな運用コードです。CocoonのSEO設定も扱いたい場合だけ、僕の環境で使っている追加プラグインを入れます。

対象は、プラグインを導入できるWordPressをすでに持っている人です。コマンドはCodexに実行してもらえます。ローカルPCへCodex CLIをインストールする手順とは異なります。

先に完成形:自分のメモを渡す → Codexが原稿と画像を用意する → WordPressへ下書き保存 → 内容と画面を確認 → 公開 → 原稿・変更記録・引き継ぎを非公開GitHubへ保存、という流れを作ります。

Easy MCP AI 2.1.1、Cocoon Child 1.1.3、Python 3.12の環境で検証。画面名や提供範囲は更新されることがあるため、設定箇所には公式資料も併記します。

1.このブログでは、何をCodexに任せているのか

たとえば、実験レポートの骨格を作るワークフローの記事は、僕が「何を面倒だと感じたか」「どこまで試したか」「実際の大学のPDFは公開できない」という情報を伝え、公開可能な架空サンプルを使って記事にしました。

Codex側では、公開リポジトリと説明の照合、原稿、画像登録、下書き保存、表示検査、投稿、関連記事へのリンク、GitHubへの記録を進めています。本人しか分からない体験や公開範囲は、僕が伝えます。

Codex CloudのPythonクライアントからEasy MCP AIを通してWordPressへ投稿し、原稿と履歴は非公開GitHubへ保存する構成図
このブログの構成。図中のGitHubは原稿と記録の保存先で、pushしただけで記事が投稿される仕組みではありません。
部品 担当すること
Codex Cloud 調査・原稿・コード実行・検証を行う作業場所
非公開GitHub 原稿、執筆方針、コード、変更前後、次の作業を保存
Pythonクライアント 接続確認、変更計画、WordPressへの送信、保存結果の再取得
Easy MCP AI WordPress側のMCP接続口。ユーザーとトークンに応じて操作を制限
Cocoon SEO Bridge〈任意〉 CocoonのSEOタイトルと説明文の2項目をAPIへ登録

MCPは、AIが外部の道具を使うための接続方式です。この構成では、CodexがPythonを実行し、そのコードがWordPressのMCP接続口へ通信します。チャット画面にWordPressの操作ボタンが直接増える方式ではありません。

記事・画像・内部リンクは扱えますが、ASP管理画面の操作、Search Consoleの分析、テーマの自由な変更、サーバー全体の復元まで、この接続だけで完了するわけではありません。必要な道具と権限を、その作業ごとに確認します。

2.必要なものと、記事内のコード

  • HTTPSで公開しているWordPress:最初にプラグインを入れられる管理者権限が必要です。WordPress.comなどでは、利用プランのプラグイン対応も確認します。
  • Codex Cloudを利用できるアカウント:クラウド環境とGitHub接続を使えることを確認します。利用枠・料金は契約によって異なります。
  • GitHubアカウント:運用用には非公開リポジトリを使います。
  • Python 3.12以上:自分のPCではなく、今回使うクラウド環境に用意します。掲載コードの投稿処理は標準ライブラリだけで動きます。

接続用のEasy MCP AIはWordPress公式ディレクトリで配布されています。この記事のテンプレートとSEO Bridgeは本文からコードを保存して使えます。WordPressのサーバー・ドメイン費用やCodexの利用料金は別です。

必要なファイルは、この記事の入門テンプレートのコードから、ファイル名をそろえて保存できます。CocoonのSEO連携には、本文掲載のPHPを使います。

記事内のコードには、ダミーの接続先、サンプル原稿、AGENTS.md、Pythonコード、テスト、空の引き継ぎを用意しています。このブログの下書き、広告コード、認証情報は含みません。使用後は自分の非公開データが増えるため、作業リポジトリを公開しないでください。

僕の運用環境にはサイト全体の表示検査などもありますが、入門テンプレートは投稿・PNG画像・更新・任意のCocoon SEO・変更前後の照合に絞っています。ブラウザの自動検査や売上計測は同梱していません。

3.Easy MCP AIを導入し、APIトークンを作る

プラグインを有効化する

  1. WordPress管理画面を開き、プラグイン → 新規追加へ進みます。
  2. Easy MCP AIを検索し、公式ディレクトリのプラグインと一致することを確認します。
  3. 「今すぐインストール」→「有効化」を選びます。
  4. 管理画面のEasy MCP AI → Connectionsを開き、サイトの接続先を確認します。

ドメイン直下のWordPressなら、接続先は次の形式です。example.comは自分のサイトへ置き換えます。WordPressをサブディレクトリへ設置している場合は、管理画面が示すURLを優先してください。

https://example.com/wp-json/easy-mcp-ai/v1/mcp

このURLをブラウザで開けるかだけでは、認証付きの投稿ができるかは分かりません。後で掲載コードのdoctorを使って接続を確認します。

投稿に使うユーザーとCustom権限を選ぶ

Connections → API tokens → Create tokenを開きます。Token NameにはCodex Blogなど用途が分かる名前を付けます。WordPress Userには、これからCodexが操作するときのユーザーを選びます。

自分が作成した投稿だけなら「投稿者」、他の投稿も含めた編集なら「編集者」が候補です。既存の本人名義の記事を更新する場合は、その記事を編集できるユーザーかも確認します。最初のプラグイン導入に使う管理者と、日常の執筆用ユーザーは分けて考えられます。

Access levelはCustomを選び、次を許可します。表示名が違っても、ツール名で照合してください。

用途 必要なツール
記事を探す・読む wp_list_posts、wp_get_post
カテゴリを調べる wp_list_categories
下書き作成・記事更新・公開 wp_create_post、wp_update_post
画像登録・登録結果の確認 wp_upload_media、wp_get_media
CocoonのSEOを扱う場合だけ追加 wp_get_post_meta。書き込みは上記のwp_update_postを使用

有効期限もこの画面で設定します。期限を設けた場合は、失効時に接続できなくなることを運用記録へ残します。作成後に表示されるトークンは、次の節のNetwork secretのValue欄へ保存してください。会話、GitHub、記事、スクリーンショットには載せません。

今回使うのはEasy MCP AIが発行するAPIトークンです。WordPressのアプリケーションパスワードやOpenAI APIキーを追加発行する手順ではありません。

設定画面の実物は、公式のAPIトークン作成ガイド(画面画像付き)でも確認できます。

僕の環境で詰まったのは、サイト全体の許可設定だった

このブログでは、トークンで編集操作を選んだ後も、必要な編集ツールを取得できない段階がありました。Easy MCP AI全体のWhitelist ToolsとDisabled Toolsも確認する必要があったためです。

Easy MCP AI → Settingsで、必要な操作が全体設定で除外されていないか見ます。Whitelist Toolsを使う場合は、上の表のツールを許可対象に含めます。たとえば読み取り用のwp_get_*、wp_list_*だけでは、記事の作成・更新はできません。

操作できる範囲は、WordPressユーザーの権限・トークンの許可・サイト全体の設定がすべて通る範囲です。必要な投稿・画像操作だけを通し、削除やユーザー管理までまとめて有効化する必要はありません。

「Force Draft on Create」を使うと新規作成を下書きにできます。ただし、更新ツールによる公開まで禁止する設定ではありません。下書き運用と公開権限を同じものとして扱わないことが大切です。

参考:許可したツールが表示されない場合の公式ガイド

4.GitHubとCodex Cloudに作業環境を作る

テンプレートを非公開リポジトリへ保存する

  1. GitHubの「New repository」で、たとえばmy-wordpress-opsというリポジトリを作ります。公開範囲はPrivateです。
  2. この記事末尾のコードを、記載したファイル名で保存します。
  3. GitHubのAdd file → Upload filesから、作成したフォルダの中身をアップロードしてコミットします。最初にREADMEを作ってリポジトリを初期化しても構いません。
  4. Code画面の直下にAGENTS.md、README.md、scripts、configがあることを確認します。.gitignoreも含めます。

外側のcodex-wordpress-starterフォルダを丸ごと1階層余分に入れた場合は、その中へ移動してコマンドを実行する必要があります。この記事ではリポジトリ直下へ配置した前提で進めます。GitHubの基本操作が不安なら、GitHubへコードをアップロードする手順も参照してください。

my-wordpress-ops/
├── AGENTS.md
├── README.md
├── config/site.json
├── scripts/article.py
├── scripts/wpops.py
├── content/demo/article.json
├── content/demo/body.html
├── tests/
└── state/handoff.json

Cloud環境を作り、Network secretを登録する

CodexでSettings → Codex Cloud → Environments → Create environmentへ進み、GitHubを接続して、作った非公開リポジトリを選びます。チャットの「Work in → Cloud」から環境を作成する入口もあります。表示が違う場合は現在の公式Cloud環境ガイドと照合してください。

環境の設定でNetwork secrets → Manageを開き、次を登録します。

項目 設定値
Key WP_MCP_TOKEN
Value Easy MCP AIで発行したトークン。秘密の入力欄にだけ貼る
Allowed domains example.comなど自分のWordPressのホスト名。https://やパスは付けない

Internet accessでは、WordPressのホストへの通信が許可されていることも確認します。Network secretは、プログラムに渡る代替値を、許可したHTTPSの宛先への通信時にプロキシが秘密の値へ置き換える仕組みです。掲載コードは環境標準のHTTPSプロキシと証明書検証を使います。

環境の準備中に「Python 3.12以上で、このリポジトリのテストを実行できるようにして」とCodexへ頼みます。設定を保存し、Publishしてから、その環境を選んだ新しいタスクを開始します。ここでのPublishは作業環境の保存・利用開始であり、ブログ記事の公開ではありません。

このブログはエックスサーバーを使っていますが、記事の執筆・投稿用にXServerのAPIキーは不要です。WordPress側の接続だけで進めます。

接続先を設定し、読めることを確かめる

ここからのコマンドは、Codex Cloud内のリポジトリ直下で実行します。下の例を貼り、「example.comを自分のサイトに置き換えて実行して」とCodexへ依頼できます。

python scripts/article.py configure --site https://example.com
python -m unittest discover -s tests -v
python scripts/wpops.py doctor
python scripts/article.py catalog

configureはconfig/site.jsonの接続先を変えます。トークンはこのJSONへ書きません。doctorでconnected: true、write_tools_missing: []になり、作成・更新・画像登録の3つがwrite_tools_availableにあれば、必要なツールが見えています。

catalogには記事とカテゴリが表示されます。自分のブログの記事が返ること、使いたいカテゴリのIDを確認してください。ツール数やカテゴリIDはサイトごとに違い、このブログと同じ数である必要はありません。

5.まず、WordPressへ下書き1本を保存する

タイトル・URL・カテゴリ・本文を用意する

content/demo/article.jsonを編集します。category_idには、先ほど調べた実在する整数のIDを入れます。次の1は例です。

{
  "title": "CodexとWordPressの接続を試す",
  "slug": "codex-connection-demo",
  "category_id": 1
}

slugはURLに使う短い英数字です。新しい記事ごとに変え、すでにある記事の修正では変えません。本文は同じフォルダのbody.htmlへ書きます。

<p>この記事では、CodexからWordPressへ下書きを保存する流れを確認します。</p>
<h2>確認すること</h2>
<ul>
  <li>タイトルと本文が保存されること</li>
  <li>投稿の状態が下書きであること</li>
</ul>

この記事タイトルはWordPress側にあるので、本文に同じh1は入れません。上のサンプルは動作確認用です。実際に公開するときは、自分が読者へ伝えたい内容に書き換えます。

計画を確認してから保存する

python scripts/article.py prepare content/demo
python scripts/wpops.py plan content/demo/plan.json
python scripts/wpops.py apply content/demo/plan.json

ここまでではWordPressへ書き込みません。最初のコマンドは変更計画を作り、最後もmode: previewです。plan.jsonで接続先とタイトルを確認し、wp_create_postのstatusがdraftになっていることを見ます。

保存する内容が合っていれば、次を実行します。

python scripts/wpops.py apply content/demo/plan.json --apply

status: verifiedが返ったら、保存後の値も取得できた状態です。WordPressの投稿 → 投稿一覧を開き、同じタイトルの下書きがあるか確認します。

投稿IDはstate/deployments/article-[slug]-first-draft/journal.jsonのreferences.article、保存後の本文と状態は同じフォルダのcreate.after.jsonに記録されます。次のコマンドでも再取得できます。123は自分の投稿IDに置き換えます。

python scripts/article.py read 123

全文はruntime/post-123.jsonへ保存されます。同じ投稿IDの本文とstatusを読み返せば、保存した下書きを続けて編集できます。

今回の実サイトでの結果:最初のテンプレートの動作検証で、このページの下書きを投稿ID421として作成しました。図解を添付ID422で登録し、同じ投稿へ本文とアイキャッチを更新して、保存後の値を再取得しています。ここまではCocoon用のSEO連携を無効にした状態で確認しました。

下書き作成  → verified / 投稿ID 421 / status: draft
図解の登録  → verified / 添付ID 422
同じ記事の更新 → verified / 投稿ID 421 / status: draft

これは今回の結果を抜粋したものです。自分のサイトでは、返されたIDを使ってください。

6.画像を登録して、本文とアイキャッチへ使う

公開できるPNG画像をcontent/demo/example.pngへ置きます。配布テンプレートは2MBまでのPNGに絞っています。ファイル自体を処理時に変換するため、長いbase64文字列をチャットへ貼る必要はありません。

python scripts/article.py media content/demo/example.png --alt 'CodexとWordPressの接続結果を説明する図'

plans/media-…/plan.jsonという計画のパスが返ります。下のmedia-…は、実際に表示された文字列に置き換えます。

python scripts/wpops.py apply plans/media-…/plan.json
python scripts/wpops.py apply plans/media-…/plan.json --apply

登録後はstate/deployments/media-…/upload.after.jsonを読みます。source_urlが画像URL、idが添付IDです。本文ではURLを使います。

<figure>
  <img src="登録結果のsource_url" alt="図が伝えている内容"
       width="画像の実際の幅" height="画像の実際の高さ" loading="lazy">
  <figcaption>図の説明</figcaption>
</figure>

アイキャッチにする場合は、article.jsonへ"featured_media": 123を追加します。ここでの123は投稿IDではなく添付IDです。変更後にもう一度prepareとapplyを行うと、同じ下書きへ反映できます。

このブログでは、Cocoonがアイキャッチのキャプションを画像上に重ねることも確認しました。そのため、掲載コードのアップロードではcaptionを空にしています。説明は本文のfigcaptionなどへ書き、画像そのものに作業メモを重ねないようにしています。

画像が大きい場合や別形式を使う場合は、Easy MCP AI公式の画像アップロード説明と、サーバー側の上限・ツール仕様を確認してください。テンプレートが対応する2MBと、WordPressの上限は別です。

7.CocoonのSEO設定も更新したい場合

Cocoon以外を使う人は、この節を飛ばせます。通常タイトルと本文の投稿に、追加のSEO Bridgeは必要ありません。

このブログでは、記事の通常タイトルを直した後も、Cocoonの検索向けタイトルに古い値が残る問題がありました。本文の見出しだけを見ても気づけないため、SEOタイトルと説明文を別に確認する仕組みを加えました。

ここに掲載するKatasuke Codex SEO Bridgeは、次の2項目だけをWordPress REST APIへ登録する小さなプラグインです。MCP接続そのものはEasy MCP AIが担当します。

  • the_page_seo_title:検索向けタイトル
  • the_page_meta_description:検索向け説明文
  1. SEO BridgeのPHPコードを、katasuke-codex-seo-bridge.phpとして保存します。
  2. サーバーのファイル管理機能でwp-content/mu-plugins/へ配置します。フォルダがなければ作成します。通常プラグイン版をすでに使っている場合は、同じコードを二重に置かず既存の版を使ってください。
  3. Easy MCP AIのトークンでwp_get_post_metaを許可します。
  4. config/site.jsonのcocoon_seoをtrueへ変更します。
  5. 記事のarticle.jsonにseo_descriptionを追加します。
"seo_description": "この記事で解決する疑問と、実際に説明する範囲を簡潔に書きます。"

JSONの最後の項目でない場合はカンマが必要です。Codexにファイル全体の形式も確認してもらってください。

掲載コードは最初の下書きを作った後、次の更新時にSEOを反映します。SEOタイトルを空文字にして通常タイトルを継承させ、説明文を明示的に保存します。プラグインが未導入などでメタ項目が登録されていなければ、処理を止めます。

Bridgeは、対象記事を編集できるユーザーかを確認し、登録済みの設定を上書きしないようにしています。ただし、すべてのテーマやSEOプラグインに対応するものではありません。他のSEOプラグインを併用している場合は、公開HTMLでどの設定が出ているかも確認します。

最後に、公開ページのHTMLソースで<title>と<meta name="description">を確認します。WordPressに値が保存されたことと、テーマがその値を表示していることの両方を見るのがポイントです。

8.内容と画面を確認して公開する

原稿と画面の確認を分ける

WordPressの投稿一覧から下書きを開き、プレビューで確認します。本文を直した場合は、先にprepareとapplyで下書きへ反映します。

  • 本人の体験と調査した情報が混ざっていないか。試していないことを成功談にしていないか。
  • コードの保存先・実行場所・成功した状態が説明されているか。
  • 画像に個人情報がなく、文字が読めるか。実画面と説明用イラストを区別しているか。
  • 内部リンクが目的に合っていて、広告の正規コードが保持されているか。
  • PCとスマホ幅で、表・コード・ボタンが本文からはみ出していないか。

プレビューでは、スマホ幅とPC幅の両方で読みます。表の右端、コードの横スクロール、画像の文字、リンクの押しやすさが確認ポイントです。入門テンプレートなら、まずWordPressのプレビューを自分のブラウザで開いて進められます。

スマホ幅のプレビューで比較表がはみ出した場合は、WordPressの比較表を折り返し・横スクロールで直す手順を参照してください。表の用途に合う表示を選び、ほかの記事の表に影響を広げずに修正する例を用意しています。

配布テンプレートで保存したWordPress下書きのPC表示画面
配布テンプレートで下書き保存した際のプレビュー画面(PC表示)。
配布テンプレートで保存したWordPress下書きのスマホ表示画面
配布テンプレートで下書き保存した際のプレビュー画面(スマホ表示)。

この撮影ではEasy MCP AIの一時プレビューを利用しました。公式のプレビュー機能はリンクを知る人が期限内に閲覧できる仕組みなので、URL自体は記事や公開GitHubへ載せていません。通常の導入手順では、管理画面からのプレビューで確認できます。

確認した本文を記録して、公開する

内容を確認し、本人がこの記事の公開を決めたら、その最終本文についてcontent/demo/review.jsonを作ります。これはレビュー結果と、確認した本文のハッシュを記録するファイルです。

{
  "ok": true,
  "publication_authorized": true,
  "source_sha256": {
    "content/demo/body.html": "実際に確認した本文のSHA-256"
  }
}

SHA-256はファイルから計算します。自分で確認する場合のコマンドは次です。

python -c "import hashlib; from pathlib import Path; print(hashlib.sha256(Path('content/demo/body.html').read_bytes()).hexdigest())"

Codexには、次のように依頼できます。

この下書きの内容と表示を確認しました。この記事を公開して。確認済みの最終本文のハッシュをreview.jsonへ記録し、計画と変更前のWordPress本文を照合してから反映して。公開後の本文・画像・SEO・URL・新着も確認し、結果をGitHubへ保存して。

公開のコマンドは次の3つです。

python scripts/article.py prepare content/demo --publish
python scripts/wpops.py apply content/demo/plan.json
python scripts/wpops.py apply content/demo/plan.json --apply

ハッシュは、確認後に本文が変わった場合に止めるためのものです。ok: trueを書くだけで、内容の正しさや表示が確認されるわけではありません。

公開後は、保存結果のstatusがpublishになり、返されたlinkをログアウト状態でも開けるか確認します。本文、画像、title・description、ホームの新着、カテゴリ一覧まで見れば、原稿から読者の入口までを一巡できます。

9.既存のHTMLブロックと内部リンクを保って更新する

既存記事では、最初に投稿IDを指定して最新のWordPress本文を取得します。次に、ローカル原稿との差分を確認し、修正する箇所だけを反映します。別の人が管理画面で直した内容を、古い原稿で消さないためです。

投稿ID123の記事を最新のWordPress本文から確認して。この補足を該当する見出しへ追記し、読者が次の作業へ進める関連記事を1つ追加して。URLと公開状態、元のコード例、広告コードを保ち、差分と表示を確認してから公開記事へ反映して。

テンプレートはapply直前にも変更元を照合します。計画を作った後に別の編集が入った場合は止まります。ただし、計画作成前からローカル原稿が古い可能性もあるため、最初に最新本文と読み比べることは省略できません。

公開済み記事の通常のprepareでは公開状態を保ちます。修正した最終本文のレビューは必要ですが、意図せず下書きへ戻す操作にはしません。新しい記事用フォルダを複製するときは、古いwp_idを持ち越さず、別のslugにします。

過去記事を直すときは、本文だけでなく、見出しのID、画像、HTMLブロック、内部リンクを先に保存します。文章の修正でコード例やリンク先まで変わっていないか、Gitの差分で確認します。WordPressへ保存した後は本文を読み戻し、ブロックが壊れていないか、目次や関連記事から目的の場所へ進めるかを実際のページで確かめます。

関連記事も全記事へ機械的に並べず、「この説明を読んだ人が次に何をしたいか」でつなぎます。たとえばこの記事なら、GitHubの保存方法や、スマホでの比較表の直し方の記事が自然な行き先です。

10.動かないときは、ここから確認する

症状 確認する場所と次の行動
読めるのに更新できない WordPressユーザーの編集権限、トークンのCustom、全体のWhitelist/Disabledを照合。変更後にdoctorで一覧を取り直す
Network secretが見つからない 同じクラウド環境を選んだか、KeyがWP_MCP_TOKENか、保存・Publish後のタスクかを確認
401・403・通信失敗 接続先ホスト、宛先許可、トークン、WordPress/WAFを切り分ける。403だけでサーバー障害と判断しない
タイトルは直ったが検索向け表示が古い 通常タイトルとは別に、Cocoonメタと公開HTMLのtitle・descriptionを見る
画像が登録できない PNG形式・2MB以内・upload権限・サーバー上限を確認。登録済みならIDと実際の画像URLを読む
Concurrent changeと出る 別の編集が入っている。最新本文と差分を確認し、改めて計画を作る
途中で切れた/uncertainと出る 投稿一覧・slug・作成時刻・本文・journalで保存の有無を調べる。同じ新規作成を無条件に再送しない
回数制限に当たる MCP操作を並行実行せず、間隔を空ける。掲載コードは読み取りだけを待機再試行し、書き込みは自動再送しない

このブログでも接続のタイムアウトは発生しています。重要なのは、エラーが出たときに「送られていないはず」と決めつけず、保存結果を確認することです。履歴を消して再実行すると、二重投稿の原因になります。

トークンの値、認証ヘッダー、環境変数の全一覧をエラー調査のために貼る必要はありません。秘密を除いたエラーと対象の操作名で切り分けます。

11.次のチャットでも続きを書けるようにする

運用を続けるには、接続できることに加えて、何を決め、どこまで反映したかを残す必要があります。僕の環境では次のように分けています。

  • AGENTS.md:記事の書き方、秘密の扱い、下書きと公開、検証と記録のルール。
  • 記事フォルダ:本文、タイトル、投稿ID、調査元、公開できる素材、確認結果。
  • state/deployments:操作前後の本文、保存結果、再開時に見るjournal。
  • state/handoff.json:公開済みのURL、未反映の作業、次に確認すること。

記事を書き終えたら、原稿と記録を非公開GitHubへコミット・pushします。新しいチャットでは、同じクラウド環境と最新の保存ブランチを選び、次のように依頼します。

AGENTS.md、README.md、state/handoff.jsonを読み、接続確認から再開して。公開済みの内容と、まだローカルにある内容を区別し、今回のメモから記事の構成を作って。僕が書いていない体験や成果は補わないで。

AGENTS.mdは作業方針であり、サーバー側のアクセス権限の代わりではありません。トークンやWordPressユーザーの権限も必要な範囲にします。また、Gitに残した本文と変更履歴は、データベース・全画像・テーマまで含むWordPress全体のバックアップとは別です。

僕が伝える部分と、Codexが実行する部分をこのように分けると、「記事を書いて」で終わらず、根拠、画像、投稿、更新、次のチャットへの引き継ぎまで一つの流れとして扱えます。最初は下書き1本で、保存された本文と実際の画面が合うところまで確かめてみてください。

この運用とあわせて役立つ関連ガイド

入門テンプレートを、ファイルごとに保存する

下のコードは、記事のコマンドで使うテンプレート本体です。各欄を開き、見出しにあるパスでUTF-8保存してください。秘密の値は入っていないので、接続先のexample.comを自分のサイトへ合わせ、トークンはNetwork secretへ登録します。長いPythonコードは折りたたみ、普段の操作から必要になったときに読み返せる形にしました。

config/site.json
{
  "endpoint": "https://example.com/wp-json/easy-mcp-ai/v1/mcp",
  "site_url": "https://example.com",
  "token_env": "WP_MCP_TOKEN",
  "timezone": "Asia/Tokyo",
  "minimum_call_interval_seconds": 6.1,
  "write_tools": [
    "wp_create_post",
    "wp_update_post",
    "wp_upload_media"
  ],
  "forbidden_tools": [
    "wp_rest_write",
    "wp_rest_delete",
    "wp_send_feedback",
    "wp_get_easy_mcp_diagnostics"
  ],
  "cocoon_seo": false
}
AGENTS.md
# WordPress執筆・公開

最初にREADME.md、config/site.json、state/handoff.jsonを読む。接続前にNetwork secretと標準HTTPSプロキシを確認し、python scripts/wpops.py doctorを実行する。秘密の値を表示・チャット・ファイル・Gitへ保存しない。TLS検証や通信許可を迂回しない。

原稿は本人のメモと確認した資料に基づく。経験・使用実績・成果を創作しない。自分のブログの一人称・分野・文体は本人の方針で補う。写真は実画面、説明図、生成画像を区別する。

最初は下書き。今回の記事について公開の指示がある場合は、レビュー後に公開まで進める。公開許可があるのに機械的に毎回質問しない。review.jsonは事実・画像・リンク・表示を確認した最終本文のハッシュと、実際の公開指示に基づいて作る。

操作はscripts/article.pyで計画を用意し、scripts/wpops.pyで確認・反映する。--applyがないものはプレビュー。投稿の既存ID・slugを照合し、編集前に最新本文を読み、古いローカル原稿で他の編集を消さない。応答不明の書き込みを再送しない。MCP操作は逐次実行する。

更新後に本文・状態・メタを再取得し、公開URLの画面・画像・リンク・SEO・新着を確認する。自動検査をした場合も、実機確認や成果計測とは区別する。トークンの権限、プラグイン、テーマ、サイト設定、DNSは日常の投稿手順に含めない。

ASP素材がある場合は正規コードを保持し、追跡パラメータや文言を作り直さない。料金は確認日・適用条件・期限を記録する。自分で広告をクリックして成果テストしない。

原稿・変更前後・投稿ID・検証結果・未確認事項・次にすることを非公開GitHubへ保存する。公開状態とGit保存状態を区別する。この指示ファイルはサーバー側のアクセス制御の代用ではない。
.gitignore
.env
.env.*
__pycache__/
*.pyc
.venv/
runtime/
*.log
state/handoff.json
{
  "status": "not_connected",
  "article_ids": {},
  "pending": [
    "Set site URL and Network secret; run doctor."
  ],
  "last_verified_url": null
}
content/demo/article.json
{
  "title": "CodexとWordPressの接続を試す",
  "slug": "codex-connection-demo",
  "category_id": null
}
content/demo/body.html
<p>これは接続確認用の下書きです。自分の記事に書き換えてから公開します。</p>
<h2>できるようになったこと</h2>
<p>ローカルのHTMLをWordPressへ保存し、投稿IDと保存された本文を確認します。</p>
scripts/wpops.py
#!/usr/bin/env python3
"""Small, standard-library WordPress MCP client. Secrets exist only in memory."""
import argparse
import base64
import hashlib
import json
import os
from pathlib import Path
import re
import ssl
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime
from zoneinfo import ZoneInfo

ROOT = Path(__file__).resolve().parents[1]
CONFIG = json.loads((ROOT / "config/site.json").read_text())
BODY_FIELDS = ("id", "title", "content", "excerpt", "status", "slug", "date", "modified", "categories", "tags", "featured_media", "author", "link", "parent", "menu_order", "template", "comment_status", "ping_status")
MEDIA_FIELDS = ("id", "title", "alt_text", "caption", "description", "mime_type", "source_url", "media_type", "width", "height", "file_size")
HASH_FIELDS = ("id", "title", "content", "excerpt", "status", "slug", "categories", "tags", "featured_media", "parent", "menu_order", "template")
TERM_FIELDS = ("id", "name", "slug", "description", "parent")
SETTINGS_FIELDS = ("title", "description", "show_on_front", "page_on_front", "page_for_posts", "posts_per_page")
SEO_META_KEYS = ('the_page_seo_title', 'the_page_meta_description')
SEO_META_KINDS = ('post_meta', 'page_meta')

def scrub(text):
    for name in (CONFIG["token_env"],):
        value = os.environ.get(name)
        if value:
            text = text.replace(value, "[REDACTED]")
    text = re.sub(r"Bearer\s+[A-Za-z0-9][A-Za-z0-9._~+/-]{8,}=*", "Bearer [REDACTED]", text, flags=re.I)
    text = re.sub(r"wpmcp_[A-Za-z0-9_-]{12,}", "[REDACTED]", text)
    return text

def redact_values(data):
    if isinstance(data, str):
        return scrub(data)
    if isinstance(data, dict):
        return {key: redact_values(value) for key, value in data.items()}
    if isinstance(data, (list, tuple)):
        return [redact_values(value) for value in data]
    return data

def emit(data):
    print(json.dumps(redact_values(data), ensure_ascii=False), flush=True)

def save(path, data):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    temp = path.with_suffix(path.suffix + ".tmp")
    temp.write_text(json.dumps(redact_values(data), ensure_ascii=False, indent=2) + "\n")
    temp.replace(path)

def stamp():
    return datetime.now(ZoneInfo("Asia/Tokyo")).isoformat(timespec="seconds")

def fingerprint(data, kind=None):
    fields = TERM_FIELDS if kind in ("category", "tag") else SETTINGS_FIELDS if kind == "settings" else ('id', 'meta') if kind in SEO_META_KINDS else HASH_FIELDS
    subset = {k: data[k] for k in fields if k in data}
    return hashlib.sha256(json.dumps(subset, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()).hexdigest()

def digest(data):
    return hashlib.sha256(json.dumps(data, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()).hexdigest()

def content_equivalent(expected, observed):
    if expected == observed:
        return True
    if not isinstance(expected, str) or not isinstance(observed, str):
        return False
    # WordPress encodes emoji as numeric character references on storage.
    # Preserve ASCII references and HTML structure; never equate escaped markup
    # with executable tags, or normalize raw script/style text.
    if re.search(r"<(?:script|style)\b", expected+observed, re.I):
        return False
    def normalize(text):
        def replace(match):
            point = int(match[1], 16) if match[1] else int(match[2])
            return chr(point) if 127 < point <= 0x10FFFF else match[0]
        return re.sub(r"&#(?:x([0-9a-fA-F]+)|([0-9]+));", replace, text)
    return normalize(expected) == normalize(observed)

def snapshot_matches(current, op):
    kind = op['target']['kind']
    if fingerprint(current, kind) == op.get('before_sha256'):
        return True
    if kind not in ('post', 'page') or not op.get('baseline_file'):
        return False
    path = (Path(op['_root']) / op['baseline_file']).resolve()
    if not path.is_relative_to(ROOT):
        raise ValueError('Baseline path escapes repository')
    baseline = json.loads(path.read_text())
    if fingerprint(baseline, kind) != op.get('before_sha256'):
        raise RuntimeError('Baseline does not match the frozen snapshot hash')
    def ordered(data):
        data = dict(data)
        for field in ('tags', 'categories'):
            if field in data:
                data[field] = sorted(data[field])
        return data
    # WordPress can return term IDs in a different order after cache invalidation.
    # Compare membership while retaining strict comparison of all other fields.
    return fingerprint(ordered(current), kind) == fingerprint(ordered(baseline), kind)

def validate_arguments(schema, args):
    if not isinstance(args, dict):
        raise ValueError("Tool arguments must be an object")
    props = schema.get("properties", {})
    missing = set(schema.get("required", [])) - set(args)
    unknown = set(args) - set(props)
    if missing or unknown:
        raise ValueError(f"Schema mismatch: missing={sorted(missing)}, unknown={sorted(unknown)}")
    types = {"string": str, "integer": int, "boolean": bool, "array": list, "object": dict, "number": (float, int)}
    for key, value in args.items():
        prop = props[key]
        expected = prop.get("type")
        if isinstance(expected, str) and expected in types:
            if not isinstance(value, types[expected]) or (expected in ("integer", "number") and isinstance(value, bool)):
                raise ValueError(f"Wrong argument type: {key}")
        if "enum" in prop and value not in prop["enum"]:
            raise ValueError(f"Value outside enum: {key}")
        if isinstance(value, (int, float)) and not isinstance(value, bool):
            if value < prop.get("minimum", value) or value > prop.get("maximum", value):
                raise ValueError(f"Value outside bounds: {key}")

class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, *args, **kwargs):
        return None

class MCP:
    def __init__(self):
        token = os.environ.get(CONFIG["token_env"])
        proxy = os.environ.get("HTTPS_PROXY")
        if not token or not proxy:
            raise RuntimeError("Network secret or standard HTTPS proxy unavailable. Select the configured cloud environment; do not paste a token.")
        context = ssl.create_default_context(cafile=os.environ.get("REQUESTS_CA_BUNDLE") or os.environ.get("SSL_CERT_FILE"))
        self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({"https": proxy}), urllib.request.HTTPSHandler(context=context), NoRedirect())
        self.headers = {"Authorization": "Bearer " + token, "Content-Type": "application/json", "Accept": "application/json, text/event-stream"}
        self.sequence = 0
        self.last_call = 0.0
        self.tools = {}

    def rpc(self, method, params=None, _rate_attempt=0):
        time.sleep(max(0, CONFIG["minimum_call_interval_seconds"] - (time.monotonic() - self.last_call)))
        self.last_call = time.monotonic()
        self.sequence += 1
        message = {"jsonrpc": "2.0", "method": method}
        if not method.startswith("notifications/"):
            message["id"] = self.sequence
        if params is not None:
            message["params"] = params
        request = urllib.request.Request(CONFIG["endpoint"], data=json.dumps(message).encode(), headers=self.headers, method="POST")
        try:
            response = self.opener.open(request, timeout=45)
        except urllib.error.HTTPError as error:
            raise RuntimeError(f"MCP HTTP {error.code}: {method}; response body intentionally omitted") from None
        except (urllib.error.URLError, TimeoutError) as error:
            raise RuntimeError(scrub(f"MCP connection failed: {error}")) from None
        with response:
            raw = response.read(8_000_000)
            if response.headers.get("Mcp-Session-Id"):
                self.headers["Mcp-Session-Id"] = response.headers["Mcp-Session-Id"]
        if not raw:
            return {}
        try:
            result = json.loads(raw)
        except ValueError:
            matches = []
            for line in raw.decode("utf-8").splitlines():
                if line.startswith("data:"):
                    item = json.loads(line[5:].strip())
                    if item.get("id") == self.sequence:
                        matches.append(item)
            if not matches:
                raise RuntimeError("MCP returned no matching JSON/SSE result")
            result = matches[-1]
        if "error" in result:
            error = result['error']
            read_rpc = method in ('initialize', 'notifications/initialized', 'tools/list') or (method == 'tools/call' and self.tools.get((params or {}).get('name'), {}).get('annotations', {}).get('readOnlyHint') is True)
            if isinstance(error, dict) and error.get('code') == -32003 and 'rate limit' in error.get('message', '').lower() and read_rpc and _rate_attempt < 2:
                emit({'status': 'read_rate_limit_cooldown', 'retry': _rate_attempt + 1,
                      'wait_seconds': 61})
                # Allow the documented per-minute window to expire. Keep waits
                # bounded while the invoking process can yield progress.
                time.sleep(30)
                time.sleep(31)
                return self.rpc(method, params, _rate_attempt+1)
            raise RuntimeError(scrub(json.dumps(result["error"], ensure_ascii=False)))
        return result.get("result", {})

    def initialize(self):
        result = self.rpc("initialize", {"protocolVersion": "2025-03-26", "capabilities": {}, "clientInfo": {"name": "codex-wordpress-starter", "version": "1.0.0"}})
        self.headers["MCP-Protocol-Version"] = result["protocolVersion"]
        self.rpc("notifications/initialized")
        cursor = None
        for _ in range(100):
            page = self.rpc("tools/list", {"cursor": cursor} if cursor else {})
            self.tools.update({t["name"]: t for t in page.get("tools", [])})
            cursor = page.get("nextCursor")
            if not cursor:
                return self
        raise RuntimeError("tools/list pagination exceeded limit")

    def check_tool(self, name, write=False):
        if name not in self.tools:
            raise RuntimeError(f"Tool unavailable: {name}. Enable it in Easy MCP AI and this token's permissions.")
        if name in CONFIG["forbidden_tools"] or (name.startswith("wp_delete_") and name != "wp_delete_tag"):
            raise RuntimeError(f"Tool intentionally outside editorial scope: {name}")
        if write:
            if name not in CONFIG["write_tools"]:
                raise RuntimeError(f"Write tool outside explicit allowlist: {name}")
        elif self.tools[name].get("annotations", {}).get("readOnlyHint") is not True:
            raise RuntimeError(f"Read operation refused: tool not annotated read-only: {name}")

    def call(self, name, args=None, write=False):
        self.check_tool(name, write=write)
        args = args or {}
        validate_arguments(self.tools[name].get("inputSchema", {}), args)
        result = self.rpc("tools/call", {"name": name, "arguments": args})
        if result.get("isError"):
            raise RuntimeError(scrub(json.dumps(result, ensure_ascii=False)))
        if isinstance(result.get("structuredContent"), dict):
            return result["structuredContent"]
        for block in result.get("content", []):
            if block.get("type") == "text":
                try:
                    return json.loads(block["text"])
                except ValueError:
                    raise RuntimeError("Tool result was text, not an inspectable object") from None
        raise RuntimeError("Tool returned no inspectable result")

    def body(self, kind, ident):
        if kind in SEO_META_KINDS:
            data = self.call('wp_get_post_meta', {'post_id': ident, 'post_type': 'posts' if kind == 'post_meta' else 'pages'})
            meta = data.get('meta', {})
            if not all(key in meta for key in SEO_META_KEYS):
                raise RuntimeError('Cocoon SEO metadata is not registered for the REST API; activate the reviewed Katasuke Codex SEO Bridge before applying SEO updates')
            return {'id': ident, 'meta': {key: meta[key] for key in SEO_META_KEYS}}
        if kind == "media":
            data = self.call("wp_get_media", {"media_id": ident})
            return {k: data[k] for k in MEDIA_FIELDS if k in data}
        if kind == "settings":
            data = self.call("wp_get_site_settings")
            return {k: data[k] for k in SETTINGS_FIELDS if k in data}
        if kind in ("category", "tag"):
            data = self.call("wp_get_" + kind, {kind + "_id": ident})
            return {k: data[k] for k in (*TERM_FIELDS, "count") if k in data}
        if kind == "menu":
            return self.call("wp_list_menu_items", {"menu_id": ident})
        if kind not in ("post", "page") or not isinstance(ident, int):
            raise ValueError("Unknown content kind or missing numeric ID")
        name = "wp_get_post" if kind == "post" else "wp_get_page"
        key = "post_id" if kind == "post" else "page_id"
        data = self.call(name, {key: ident})
        return {k: data[k] for k in BODY_FIELDS if k in data}

    def paged(self, name, field, args=None):
        rows = []
        for page in range(1, 1001):
            result = self.call(name, {**(args or {}), "page": page, "per_page": 10})
            batch = result.get(field, [])
            rows.extend(batch)
            if not batch or page >= result.get("total_pages", 1000) or len(batch) < 10:
                return rows
        raise RuntimeError("Content pagination exceeded limit")

def load_plan(path):
    path = Path(path).resolve()
    if not path.is_relative_to(ROOT):
        raise ValueError("Plan path escapes repository")
    data = json.loads(path.read_text())
    if data.get("site_url") != CONFIG["site_url"]:
        raise ValueError("Plan is for a different site")
    if not re.fullmatch(r"[a-z0-9][a-z0-9_-]*", data.get("id", "")):
        raise ValueError("Invalid plan ID")
    keys = set()
    for op in data["operations"]:
        if not re.fullmatch(r"[a-z0-9][a-z0-9_-]*", op.get("key", "")) or op["key"] in keys:
            raise ValueError("Invalid or duplicated operation key")
        keys.add(op["key"])
        op["_root"] = str(path.parent)
    return data

def resolve_args(op, references):
    args = dict(op.get("args", {}))
    if op.get("upload_file"):
        path = (Path(op["_root"]) / op["upload_file"]).resolve()
        if op["tool"] != "wp_upload_media" or not path.is_relative_to(ROOT):
            raise ValueError("Media upload path outside editorial scope")
        binary = path.read_bytes()
        if path.suffix.lower() != ".png" or not binary.startswith(b"\x89PNG\r\n\x1a\n"):
            raise ValueError("Verified screenshot upload requires a PNG image")
        args["content_base64"] = base64.b64encode(binary).decode("ascii")
    if op.get("content_file"):
        root = Path(op["_root"]).resolve()
        path = (root / op["content_file"]).resolve()
        if not path.is_relative_to(ROOT):
            raise ValueError("Content path escapes repository")
        args["content"] = path.read_text()
    def resolve(value):
        if isinstance(value, str) and value.startswith("$ref:"):
            name = value[5:]
            if name not in references:
                raise ValueError(f"Reference not created yet: {name}")
            return references[name]
        if isinstance(value, dict):
            return {k: resolve(v) for k, v in value.items()}
        if isinstance(value, list):
            return [resolve(v) for v in value]
        return value
    return resolve(args)

def required_tools(plan):
    return sorted({op["tool"] for op in plan["operations"] if not op.get("hold")})

def check_editorial_scope(op, args):
    if 'meta' in args and (op.get('target') or {}).get('kind') not in SEO_META_KINDS:
        raise ValueError('Metadata edits require a separate, snapshotted SEO-only operation')
    if (op.get('target') or {}).get('kind') in SEO_META_KINDS:
        kind = op['target']['kind']
        id_key = 'post_id' if kind == 'post_meta' else 'page_id'
        tool = 'wp_update_post' if kind == 'post_meta' else 'wp_update_page'
        if op['tool'] != tool or set(args) != {id_key, 'meta'} or args[id_key] != op['target']['id']:
            raise ValueError('SEO-only updates must target one snapshotted post or page')
        if not isinstance(args['meta'], dict) or set(args['meta']) != set(SEO_META_KEYS):
            raise ValueError('SEO-only updates are limited to the reviewed Cocoon title and description keys')
        for key, limit in zip(SEO_META_KEYS, (300, 500)):
            if not isinstance(args['meta'][key], str) or len(args['meta'][key]) > limit:
                raise ValueError('SEO value has an invalid type or exceeds its length limit')
    if op["tool"] == "wp_delete_tag" and (set(args) - {"tag_id", "force"} or (op.get("target") or {}).get("kind") != "tag" or args.get("tag_id") != op["target"]["id"]):
        raise ValueError("Tag cleanup must target one snapshotted tag")
    if op.get("snapshot_only") and (op.get("target") or {}).get("kind") != "menu":
        raise ValueError("Snapshot-only targets are limited to menu layout changes")
    if op["tool"] == "wp_update_site_settings" and set(args) - {"description", "show_on_front", "page_on_front", "page_for_posts", "posts_per_page"}:
        raise ValueError("Site settings outside planned editorial scope")
    if "status" in args and args["status"] not in ("draft", "publish", "pending", "private", "future"):
        raise ValueError("Status outside reversible editorial scope")
    if op["tool"] in ("wp_create_post", "wp_create_page") and args.get("status", "draft") != "draft":
        raise ValueError("Create content as draft before publishing")
    if op["tool"] in ("wp_update_post", "wp_update_page") and op.get("target") is None and not any(isinstance(v, str) and v.startswith("$ref:") for v in op.get("args", {}).values()):
        raise ValueError("Existing content update needs a snapshot and target")

def operation_digest(op):
    refs = {v[5:]: 1 for v in op.get("args", {}).values() if isinstance(v, str) and v.startswith("$ref:")}
    return digest({"tool":op["tool"], "args":resolve_args(op, refs), "unresolved_args":op.get("args",{}), "target":op.get("target"), "before_sha256":op.get("before_sha256")})

def unwrap_ident(result):
    for container in (result, result.get("post", {}), result.get("page", {}), result.get("item", {}), result.get("media", {})):
        for field in ("id", "post_id", "page_id", "menu_item_id", "item_id", "media_id"):
            if isinstance(container, dict) and isinstance(container.get(field), int):
                return container[field]
    return None

def apply_plan(client, plan, apply=False, only=None):
    selected = [op for op in plan["operations"] if not op.get("hold") and (not only or op["key"] in only)]
    if only and set(only) - {op["key"] for op in selected}:
        raise ValueError("Requested operation unknown or on hold")
    # Validate ALL permissions, schemas and reference order before any mutation.
    mock_refs = {}
    if apply:
        preexisting_journal = ROOT / "state/deployments" / plan["id"] / "journal.json"
        if preexisting_journal.exists():
            mock_refs.update(json.loads(preexisting_journal.read_text()).get("references", {}))
    for op in selected:
        client.check_tool(op["tool"], write=True)
        args = resolve_args(op, mock_refs)
        validate_arguments(client.tools[op["tool"]].get("inputSchema", {}), args)
        check_editorial_scope(op, args)
        if op.get("reference"):
            mock_refs[op["reference"]] = 1
    if not apply:
        emit({"mode": "preview", "operations": [{"key": o["key"], "tool": o["tool"]} for o in selected], "holds": [o["key"] for o in plan["operations"] if o.get("hold")]})
        return
    for check in plan.get("quality_checks", []):
        report_path = (ROOT / check["path"]).resolve()
        if not report_path.is_relative_to(ROOT):
            raise ValueError("Quality report path escapes repository")
        report = json.loads(report_path.read_text())
        if not report.get("ok"):
            raise RuntimeError("A required quality check has not passed")
        for source, expected in report.get("source_sha256", {}).items():
            path = (ROOT/source).resolve()
            if not path.is_relative_to(ROOT) or hashlib.sha256(path.read_bytes()).hexdigest() != expected:
                raise RuntimeError("Verified content changed; repeat the affected quality check")
    run_dir = ROOT / "state/deployments" / plan["id"]
    journal_path = run_dir / "journal.json"
    journal = json.loads(journal_path.read_text()) if journal_path.exists() else {"site_url": CONFIG["site_url"], "references": {}, "operations": {}}
    if journal["site_url"] != CONFIG["site_url"]:
        raise ValueError("Deployment journal is for a different site")
    # Layout baselines are checked once per batch and backed up before changes.
    if not journal["operations"]:
        for target in plan.get("preconditions", []):
            before = client.body(target["kind"], target["id"])
            if digest(before) != target["sha256"]:
                raise RuntimeError("Layout changed since snapshot; review the new layout before applying")
            save(run_dir / (target["key"] + ".before.json"), before)
    for op in selected:
        op_hash = operation_digest(op)
        previous = journal["operations"].get(op["key"], {})
        if previous and previous.get("payload_sha256") != op_hash:
            raise RuntimeError("Operation changed after deployment began; use a reviewed new plan")
        if previous.get("status") in ("verified", "applied_needs_public_check"):
            emit({"operation": op["key"], "status": "already_verified"})
            continue
        if previous.get("status") in ("started", "uncertain"):
            raise RuntimeError(f"Previous response uncertain for {op['key']}; reconcile remote state before retrying")
        args = resolve_args(op, journal["references"])
        validate_arguments(client.tools[op["tool"]]["inputSchema"], args)
        if op.get("target"):
            before = client.body(op["target"]["kind"], op["target"]["id"])
            if not op.get("snapshot_only") and not snapshot_matches(before, op):
                raise RuntimeError(f"Concurrent change found: {op['key']}; refresh snapshot and review differences")
            save(run_dir / (op["key"] + ".before.json"), before)
            if op["tool"] == "wp_delete_tag" and before.get("count") != 0:
                raise RuntimeError("Tag is still in use; do not delete it")
        journal["operations"][op["key"]] = {"status": "started", "at": stamp(), "payload_sha256":op_hash}
        save(journal_path, journal)
        try:
            result = client.call(op["tool"], args, write=True)
            ident = unwrap_ident(result)
            if op.get("reference"):
                if not isinstance(ident, int):
                    raise RuntimeError("Created object's ID unavailable; do not resend creation")
                journal["references"][op["reference"]] = ident
            kind = op.get("verify_kind") or (op.get("target") or {}).get("kind")
            if op["tool"] == "wp_delete_tag":
                tags = client.paged("wp_list_tags", "tags", {"hide_empty":False})
                if any(t["id"] == args["tag_id"] for t in tags):
                    raise RuntimeError("Tag remains after deletion; inspect before retrying")
                save(run_dir / (op["key"] + ".after.json"), {"id":args["tag_id"],"deleted":True})
            elif kind in ("post", "page", "category", "tag", "settings", "menu", "media", *SEO_META_KINDS):
                ident = (op.get("target") or {}).get("id") if kind == "menu" else ident or (op.get("target") or {}).get("id") or args.get("post_id") or args.get("page_id")
                after = client.body(kind, ident)
                for field in (("title", "content", "status", "slug", "categories", "tags", "excerpt", "featured_media") if kind in ("post", "page") else ('meta',) if kind in SEO_META_KINDS else ("title", "alt_text", "caption") if kind == "media" else TERM_FIELDS if kind in ("category", "tag") else SETTINGS_FIELDS if kind == "settings" else ()):
                    matches = content_equivalent(args[field], after.get(field)) if field == "content" and field in args else after.get(field) == args.get(field)
                    if field in args and not matches:
                        raise RuntimeError(f"Read-back mismatch in {field}; operation needs inspection")
                save(run_dir / (op["key"] + ".after.json"), after)
            journal["operations"][op["key"]] = {"status": "verified" if kind in ("post", "page", "category", "tag", "settings", "media", *SEO_META_KINDS) else "applied_needs_public_check", "at": stamp(), "payload_sha256":op_hash, "result_id":ident}
            save(journal_path, journal)
            emit({"operation": op["key"], "status": journal["operations"][op["key"]]["status"]})
        except Exception:
            journal["operations"][op["key"]] = {"status": "uncertain", "at": stamp(), "payload_sha256":op_hash}
            save(journal_path, journal)
            raise

def main():
    parser = argparse.ArgumentParser(description=__doc__)
    sub = parser.add_subparsers(dest="command", required=True)
    sub.add_parser("doctor")
    sub.add_parser("tools")
    export = sub.add_parser("export")
    export.add_argument("--output", default="snapshots/current")
    plan = sub.add_parser("plan")
    plan.add_argument("path")
    apply = sub.add_parser("apply")
    apply.add_argument("path")
    apply.add_argument("--apply", action="store_true")
    apply.add_argument("--only", nargs="+")
    new = sub.add_parser("new")
    new.add_argument("slug")
    new.add_argument("--title", required=True)
    args = parser.parse_args()
    if args.command == "new":
        if not re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", args.slug):
            raise ValueError("Use a lowercase ASCII slug")
        folder = ROOT / "content/new" / args.slug
        folder.mkdir(parents=True, exist_ok=False)
        save(folder / "article.json", {"title": args.title, "slug": args.slug, "status": "draft", "category_id": None, "evidence": [], "sources": [], "user_confirmation_required": [], "publish_ready": False})
        (folder / "body.html").write_text("<p>読者の問題と、この記事でできるようになることを記述する。</p>\n<h2>手順と確認結果</h2>\n<p>未執筆</p>\n")
        emit({"created": str(folder), "status": "local_draft_only"})
        return
    if args.command == "plan":
        data = load_plan(args.path)
        emit({"id": data["id"], "required_tools": required_tools(data), "operations": len(data["operations"]), "on_hold": [o["key"] for o in data["operations"] if o.get("hold")]})
        return
    client = MCP().initialize()
    if args.command == "doctor":
        emit({"connected": True, "site": CONFIG["site_url"], "tool_count": len(client.tools), "write_tools_available": [n for n in CONFIG["write_tools"] if n in client.tools], "write_tools_missing": [n for n in CONFIG["write_tools"] if n not in client.tools], "non_readonly": [n for n, t in client.tools.items() if t.get("annotations", {}).get("readOnlyHint") is not True]})
    elif args.command == "tools":
        save(ROOT / "runtime/tools.json", list(client.tools.values()))
        emit({"saved": "runtime/tools.json", "count": len(client.tools)})
    elif args.command == "export":
        out = (ROOT / args.output).resolve()
        if not out.is_relative_to(ROOT):
            raise ValueError("Export path escapes repository")
        inventory = {}
        for kind, name, field in (("post", "wp_list_posts", "posts"), ("page", "wp_list_pages", "pages")):
            rows = client.paged(name, field, {"status": "any"})
            inventory[kind] = rows
            for item in rows:
                body = client.body(kind, item["id"])
                save(out / f"{kind}-{item['id']}.json", body)
                emit({"exported": kind, "id": item["id"]})
        for key, name in (("categories", "wp_list_categories"), ("tags", "wp_list_tags")):
            inventory[key] = client.paged(name, key, {"hide_empty": False})
        save(out / "inventory.json", inventory)
        emit({"export_complete": str(out), "at": stamp()})
    elif args.command == "apply":
        apply_plan(client, load_plan(args.path), apply=args.apply, only=args.only)

if __name__ == "__main__":
    try: main()
    except Exception as error:
        emit({"ok": False, "error": scrub(str(error))})
        sys.exit(1)
scripts/article.py
#!/usr/bin/env python3
"""Prepare a small post/media plan; wpops.py apply is the only write command."""
import argparse
import hashlib
import json
import re
from pathlib import Path
from urllib.parse import urlsplit
import wpops as w


def inside(path):
    p = Path(path).resolve()
    if not p.is_relative_to(w.ROOT):
        raise ValueError('Path must be inside this repository')
    return p


def configure(site):
    u = urlsplit(site)
    if u.scheme != 'https' or not u.hostname or u.username or u.password or u.query or u.fragment:
        raise ValueError('Use the canonical HTTPS WordPress URL, without credentials/query/fragment')
    if u.port not in (None, 443):
        raise ValueError('Network secrets use HTTPS port 443')
    config = dict(w.CONFIG)
    config.update(site_url=site.rstrip('/'), endpoint=site.rstrip('/')+'/wp-json/easy-mcp-ai/v1/mcp')
    w.save(w.ROOT/'config/site.json', config)
    return {'configured': config['site_url'], 'secret_allowed_domain': u.hostname}


def prepare(folder, publish=False, client=None):
    folder = inside(folder)
    meta = json.loads((folder/'article.json').read_text())
    body = (folder/'body.html').read_text()
    if not body.strip() or not meta.get('title', '').strip():
        raise ValueError('Provide a title and body')
    slug = meta.get('slug', '')
    if not re.fullmatch(r'[a-z0-9]+(?:-[a-z0-9]+)*', slug):
        raise ValueError('Use a stable lowercase ASCII slug')
    if type(meta.get('category_id')) is not int or meta['category_id'] <= 0:
        raise ValueError('Set category_id to an existing WordPress category ID from catalog')
    client = client or w.MCP().initialize()
    first_id = 'article-'+slug+'-first-draft'
    journal_path = w.ROOT/'state/deployments'/first_id/'journal.json'
    ident = meta.get('wp_id')
    if journal_path.exists():
        journal = json.loads(journal_path.read_text())
        if journal.get('site_url') != w.CONFIG['site_url']:
            raise ValueError('Journal belongs to another site')
        if any(x['status'] in ('started', 'uncertain') for x in journal['operations'].values()):
            raise RuntimeError('Uncertain creation: inspect WordPress and journal; do not resend')
        recovered = journal.get('references', {}).get('article')
        if ident and recovered and ident != recovered:
            raise ValueError('Post ID differs from the creation journal')
        ident = ident or recovered
    fields = {'title': meta['title'], 'categories': [meta['category_id']]}
    if 'featured_media' in meta:
        if type(meta['featured_media']) is not int or meta['featured_media'] < 0:
            raise ValueError('featured_media must be a nonnegative attachment ID')
        fields['featured_media'] = meta['featured_media']
    seo_op = None
    if ident:
        before = client.body('post', ident)
        if before['slug'] != slug:
            raise ValueError('wp_id and slug identify different articles')
        if before['status'] not in ('draft', 'publish'):
            raise ValueError('Only draft/published posts are handled by this starter')
        fields['status'] = 'publish' if publish else before['status']
        w.save(folder/'before.json', before)
        if w.CONFIG.get('cocoon_seo'):
            description = meta.get('seo_description', '')
            if not description or len(description) > 500:
                raise ValueError('Cocoon mode requires seo_description (1-500 characters)')
            prior_meta = client.body('post_meta', ident)
            desired = {'the_page_seo_title': '', 'the_page_meta_description': description}
            if prior_meta['meta'] != desired:
                seo_op = {'key':'seo', 'tool':'wp_update_post',
                    'args':{'post_id':ident, 'meta':desired},
                    'target':{'kind':'post_meta', 'id':ident},
                    'before_sha256':w.fingerprint(prior_meta, 'post_meta')}
        op = {'key':'update', 'tool':'wp_update_post', 'args':{'post_id':ident, **fields},
              'content_file':'body.html', 'target':{'kind':'post','id':ident},
              'before_sha256':w.fingerprint(before)}
        plan_id = 'article-'+slug+'-'+w.digest({'body':body,'fields':fields,'before':w.fingerprint(before),'seo':seo_op})[:12]
        meta['wp_id'] = ident
        w.save(folder/'article.json', meta)
    else:
        if publish:
            raise ValueError('Save and check a WordPress draft first')
        posts = client.paged('wp_list_posts', 'posts', {'status':'any'})
        if any(p['slug'] == slug for p in posts):
            raise ValueError('Slug already exists: inspect it and set wp_id rather than create a duplicate')
        fields['status'] = 'draft'
        op = {'key':'create', 'tool':'wp_create_post', 'args':{**fields,'slug':slug},
              'content_file':'body.html', 'reference':'article','verify_kind':'post'}
        plan_id = first_id
    plan = {'id':plan_id, 'site_url':w.CONFIG['site_url'], 'operations':[op]+([seo_op] if seo_op else [])}
    if fields['status'] == 'publish':
        review_path = folder/'review.json'
        review = json.loads(review_path.read_text()) if review_path.exists() else {}
        relative = str((folder/'body.html').relative_to(w.ROOT))
        if not review.get('ok') or not review.get('publication_authorized') or review.get('source_sha256',{}).get(relative) != hashlib.sha256(body.encode()).hexdigest():
            raise ValueError('Review the final body and publication authorization, then save review.json with its SHA-256')
        plan['quality_checks'] = [{'path':str(review_path.relative_to(w.ROOT))}]
    w.save(folder/'plan.json', plan)
    return {'prepared_only':True,'plan':str((folder/'plan.json').relative_to(w.ROOT)), 'wp_id':ident,'status':fields['status']}


def media(file, alt):
    path = inside(file)
    if path.suffix.lower() != '.png' or not path.read_bytes().startswith(b'\x89PNG\r\n\x1a\n'):
        raise ValueError('Use a PNG file')
    if path.stat().st_size > 2_000_000:
        raise ValueError('This starter limits PNG uploads to 2 MB; resize your image')
    if not alt.strip():
        raise ValueError('Describe the image with --alt')
    ident = 'media-'+w.digest({'bytes':hashlib.sha256(path.read_bytes()).hexdigest(),'alt':alt,'name':path.name})[:16]
    target = w.ROOT/'plans'/ident/'plan.json'
    # Paths are relative to this generated plan, and remain confined to the repo.
    import os
    op = {'key':'upload','tool':'wp_upload_media','args':{'filename':path.name,'title':path.stem,'alt_text':alt,'caption':''},
          'upload_file':os.path.relpath(path,target.parent),'reference':'image','verify_kind':'media'}
    w.save(target, {'id':ident,'site_url':w.CONFIG['site_url'],'operations':[op]})
    return {'prepared_only':True,'plan':str(target.relative_to(w.ROOT))}


def main():
    p = argparse.ArgumentParser(description=__doc__)
    sub = p.add_subparsers(dest='command',required=True)
    c=sub.add_parser('configure');c.add_argument('--site',required=True)
    sub.add_parser('catalog')
    c=sub.add_parser('prepare');c.add_argument('folder');c.add_argument('--publish',action='store_true')
    c=sub.add_parser('read');c.add_argument('post_id',type=int)
    c=sub.add_parser('media');c.add_argument('file');c.add_argument('--alt',required=True)
    a=p.parse_args()
    if a.command=='configure':result=configure(a.site)
    elif a.command=='prepare':result=prepare(a.folder,a.publish)
    elif a.command=='media':result=media(a.file,a.alt)
    elif a.command=='catalog':
        client=w.MCP().initialize()
        result={'categories':client.paged('wp_list_categories','categories',{'hide_empty':False}),
                'recent_posts':client.call('wp_list_posts',{'status':'any','per_page':10})}
    else:
        result=w.MCP().initialize().body('post',a.post_id)
        w.save(w.ROOT/'runtime'/f'post-{a.post_id}.json',result)
        # Keep nonpublic body out of the terminal transcript.
        result={k:result[k] for k in ('id','title','slug','status','link') if k in result}
    w.emit(result)


if __name__ == '__main__':
    try: main()
    except Exception as error:
        w.emit({'ok':False,'error':str(error)})
        raise SystemExit(1)
tests/test_starter.py
import contextlib
import copy
import hashlib
import io
import json
from pathlib import Path
import sys
import tempfile
import unittest
from unittest.mock import patch
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'scripts'))
import wpops as w
import article as a


class Fake(w.MCP):
    def __init__(self):
        props={k:{'type':v} for k,v in {'title':'string','content':'string','slug':'string','status':'string','categories':'array','post_id':'integer','meta':'object'}.items()}
        self.tools={name:{'inputSchema':{'properties':props},'annotations':{'readOnlyHint':False}}
                    for name in ['wp_create_post','wp_update_post']}
        self.post={'id':71,'title':'Original','content':'<p>original</p>','slug':'demo','status':'draft','categories':[1]}
        self.posts=[];self.writes=[];self.lose_response=False;self.meta_reads=0
    def paged(self,*args): return copy.deepcopy(self.posts)
    def body(self,kind,ident):
        if kind=='post_meta':
            self.meta_reads+=1
            return {'id':ident,'meta':{'the_page_seo_title':'Old title','the_page_meta_description':'Old description'}}
        return copy.deepcopy(self.post)
    def call(self,name,args=None,write=False):
        self.check_tool(name,write)
        self.writes.append((name,args))
        self.post.update({k:v for k,v in args.items() if k!='post_id'})
        if self.lose_response: raise TimeoutError('Response lost after successful creation')
        return {'id':71}


class Tests(unittest.TestCase):
    def test_snapshot_keeps_literal_python_source_as_valid_json(self):
        code='text = re.sub(r"Bearer\\s+[^\\s\\\"<>]+", "Bearer [REDACTED]", text)'
        with tempfile.TemporaryDirectory() as folder:
            path=Path(folder)/'source.json'
            w.save(path,{'content':code})
            self.assertEqual(json.loads(path.read_text())['content'],code)
    def setUp(self):
        self.tmp=tempfile.TemporaryDirectory();self.root=Path(self.tmp.name)
        self.patch=patch.object(w,'ROOT',self.root);self.patch.start()
        self.configpatch=patch.object(w,'CONFIG',{**w.CONFIG,'cocoon_seo':False});self.configpatch.start()
        self.folder=self.root/'content/demo';self.folder.mkdir(parents=True)
        w.save(self.folder/'article.json',{'title':'Demo','slug':'demo','category_id':1})
        (self.folder/'body.html').write_text('<p>Reviewed example</p>')
        self.client=Fake();self.redirect=contextlib.redirect_stdout(io.StringIO());self.redirect.__enter__()
    def tearDown(self):
        self.redirect.__exit__(None,None,None);self.configpatch.stop();self.patch.stop();self.tmp.cleanup()
    def plan(self,publish=False):
        a.prepare(self.folder,publish,self.client)
        return w.load_plan(self.folder/'plan.json')
    def existing(self):
        m=json.loads((self.folder/'article.json').read_text());m['wp_id']=71;w.save(self.folder/'article.json',m)
    def review(self):
        w.save(self.folder/'review.json',{'ok':True,'publication_authorized':True,'source_sha256':{'content/demo/body.html':hashlib.sha256((self.folder/'body.html').read_bytes()).hexdigest()}})
    def test_prepare_and_preview_never_write(self):
        plan=self.plan();w.apply_plan(self.client,plan)
        self.assertEqual(self.client.writes,[])
    def test_draft_readback_and_resume_do_not_duplicate(self):
        plan=self.plan();w.apply_plan(self.client,plan,True);w.apply_plan(self.client,plan,True)
        self.assertEqual(len(self.client.writes),1)
        self.assertEqual(self.client.post['status'],'draft')
        self.assertEqual(self.plan()['operations'][0]['tool'],'wp_update_post')
    def test_generic_update_does_not_require_cocoon(self):
        self.existing();self.plan();self.assertEqual(self.client.meta_reads,0)
    def test_cocoon_mode_adds_separate_meta_operation(self):
        self.existing();w.CONFIG['cocoon_seo']=True
        m=json.loads((self.folder/'article.json').read_text());m['seo_description']='Accurate summary';w.save(self.folder/'article.json',m)
        self.assertEqual(len(self.plan()['operations']),2)
        self.assertEqual(self.client.meta_reads,1)
    def test_publish_requires_review_then_changes_status(self):
        self.existing()
        with self.assertRaises(ValueError):self.plan(True)
        self.review();plan=self.plan(True);w.apply_plan(self.client,plan,True)
        self.assertEqual(self.client.post['status'],'publish')
    def test_review_cannot_be_reused_after_body_changed(self):
        self.existing();self.review();plan=self.plan(True)
        (self.folder/'body.html').write_text('<p>Unreviewed</p>')
        with self.assertRaises(RuntimeError):w.apply_plan(self.client,plan,True)
        self.assertEqual(self.client.writes,[])
    def test_concurrent_change_blocks_write(self):
        self.existing();plan=self.plan();self.client.post['content']='Another editor changed this'
        with self.assertRaises(RuntimeError):w.apply_plan(self.client,plan,True)
        self.assertEqual(self.client.writes,[])
    def test_uncertain_creation_is_not_repeated(self):
        plan=self.plan();self.client.lose_response=True
        with self.assertRaises(TimeoutError):w.apply_plan(self.client,plan,True)
        with self.assertRaises(RuntimeError):w.apply_plan(self.client,plan,True)
        with self.assertRaises(RuntimeError):self.plan()
        self.assertEqual(len(self.client.writes),1)
    def test_duplicate_slug_is_not_created(self):
        self.client.posts=[{'id':71,'slug':'demo'}]
        with self.assertRaises(ValueError):self.plan()
    def test_update_keeps_existing_publication_state(self):
        self.existing();self.client.post['status']='publish';self.review()
        self.assertEqual(self.plan()['operations'][0]['args']['status'],'publish')
    def test_meta_unavailable_does_not_write(self):
        self.existing();w.CONFIG['cocoon_seo']=True
        with self.assertRaises(ValueError):self.plan()
        self.assertEqual(self.client.writes,[])
    def test_media_path_and_file_validation(self):
        file=self.root/'secret.txt';file.write_text('not an image')
        with self.assertRaises(ValueError):a.media(file,'Example')
        with self.assertRaises(ValueError):a.media(self.root/'../outside.png','Example')
    def test_disallowed_tool_cannot_be_written(self):
        self.client.tools['wp_delete_post']={}
        with self.assertRaises(RuntimeError):self.client.check_tool('wp_delete_post',True)
    def test_no_token_or_credentials_in_config_url(self):
        for u in ['http://example.com','https://user:password@example.com','https://example.com/?token=example']:
            with self.assertRaises(ValueError):a.configure(u)


if __name__=='__main__':unittest.main()

README.mdには、このページのURLと自分の操作手順を残します。コードのライセンスはGPL-2.0です。

Cocoon SEO BridgeのPHPコード

記事タイトルと説明文の2項目を、対象記事を編集できるユーザーに限ってREST APIから扱います。通常の本文投稿には不要で、Cocoonの検索向け設定を連携したいときに使います。

katasuke-codex-seo-bridge.php
<?php
/**
 * Plugin Name: Katasuke Codex SEO Bridge
 * Description: Cocoonの記事タイトルと説明文だけを、編集権限付きWordPress REST APIで扱えるようにします。
 * Version: 1.0.0
 * Requires at least: 6.0
 * Requires PHP: 7.4
 * Author: Katasuke
 * License: GPL-2.0-or-later
 */

defined( 'ABSPATH' ) || exit;

function katasuke_codex_register_cocoon_seo_meta() {
    // These keys are owned and rendered by the active Cocoon theme.
    if ( ! function_exists( 'get_the_page_seo_title' ) ) {
        return;
    }

    foreach ( array( 'post', 'page' ) as $post_type ) {
        if ( ! post_type_supports( $post_type, 'custom-fields' ) ) {
            continue;
        }
        $registered = get_registered_meta_keys( 'post', $post_type );
        foreach ( array( 'the_page_seo_title' => 300, 'the_page_meta_description' => 500 ) as $key => $limit ) {
            // Preserve any registration supplied by another plugin or theme.
            if ( isset( $registered[ $key ] ) ) {
                continue;
            }
            register_post_meta(
                $post_type,
                $key,
                array(
                    'type'              => 'string',
                    'single'            => true,
                    'default'           => '',
                    'sanitize_callback' => 'sanitize_text_field',
                    'auth_callback'     => static function ( $allowed, $meta_key, $post_id, $user_id ) {
                        return $post_id > 0 && user_can( $user_id, 'edit_post', $post_id );
                    },
                    'show_in_rest'      => array(
                        'schema' => array(
                            'type'      => 'string',
                            'context'   => array( 'edit' ),
                            'maxLength' => $limit,
                        ),
                    ),
                )
            );
        }
    }
}

add_action( 'init', 'katasuke_codex_register_cocoon_seo_meta', 20 );

参考資料と入門テンプレート

設定とAPIの仕様は、以下の一次資料と実際のツール一覧・保存結果を照合しました。

本文掲載のテンプレートは、今回も15件のPythonテストを通し、二重投稿・変更元の不一致・確認後の本文変更・Cocoon連携の有無などを検証しました。SEO Bridgeの登録・権限チェックもPHP 8.3の隔離した環境で確認しています。さらに、このブログへの接続、下書き作成、PNG登録、更新を実行し、保存結果を照合しました。

掲載した画像は、このブログの記事を下書きプレビューで開いた画面です。本文を保存しただけで作業を終えず、見出し・画像・表がどう並ぶかまで確かめる流れにしています。

次に読む記事

GitHubへコードを保存する|初回pushの手順では、公開前に確認する情報と、コードをGitHubへ保存する手順を学べます。

タイトルとURLをコピーしました