Skip to content

create a mcp server #2

@LEO0331

Description

@LEO0331

using nodejs to create a mcp server without paid official plugin
reference: https://github.com/NTU-Sherlock/wp-publisher-mcp
official plugin: https://developer.wordpress.org/plugins/wordpress-org/using-the-mcp-server/?utm_source=threads&utm_medium=social&utm_campaign=fedica-DevDocs


要建立一個能讀取 WordPress 資料的 MCP 伺服器,最快的方式是使用 Python (FastMCP) 結合 WordPress REST API。
以下是完整的實作邏輯與程式碼:

1. 準備工作

你需要 WordPress 的 應用程式密碼 (Application Password):

  • 登入 WordPress 後台 -> 用戶 -> 個人資料。
  • 捲到最下方找到「應用程式密碼」,新增一個名稱(如 mcp-server),記下生成的 24 位字元密碼。

2. 安裝必要套件

pip install fastmcp requests

3. 撰寫 MCP 伺服器代碼 (wp_mcp.py)

這段代碼會暴露兩個工具:get_latest_posts(獲取文章列表)和 get_post_content(讀取特定文章內容)。

import requestsfrom fastmcp import FastMCP

配置 WordPress 資訊WP_URL = "https://your-site.com"WP_USER = "your_username"WP_APP_PWD = "xxxx xxxx xxxx xxxx xxxx xxxx" # 剛才生成的密碼

mcp = FastMCP("WordPress-Reader")
def fetch_wp(endpoint, params=None):
response = requests.get(
f"{WP_URL}/{endpoint}",
auth=(WP_USER, WP_APP_PWD),
params=params
)
response.raise_for_status()
return response.json()

@mcp.tool()def list_wp_posts(per_page: int = 5) -> str:
"""獲取 WordPress 最近的文章列表"""
try:
posts = fetch_wp("posts", params={"per_page": per_page, "_fields": "id,title,date"})
result = "最近文章列表:\n"
for p in posts:
result += f"ID: {p['id']} | 標題: {p['title']['rendered']} | 日期: {p['date']}\n"
return result
except Exception as e:
return f"讀取失敗: {str(e)}"

@mcp.tool()def read_wp_post(post_id: int) -> str:
"""根據 ID 讀取特定文章的完整內文"""
try:
post = fetch_wp(f"posts/{post_id}", params={"_fields": "title,content"})
title = post['title']['rendered']
content = post['content']['rendered']
# 簡單清除 HTML 標籤(實際應用建議用 BeautifulSoup)
import re
clean_content = re.sub('<[^<]+?>', '', content)
return f"標題:{title}\n\n內容:\n{clean_content}"
except Exception as e:
return f"讀取文章 {post_id} 失敗: {str(e)}"
if name == "main":
mcp.run(transport="stdio")

4. 測試與整合

  • 本地測試:
    執行 mcp dev wp_mcp.py,你會看到一個介面讓你直接點擊 list_wp_posts 測試 API 是否通暢。
  • 整合進 Claude Desktop / Cursor:
    在設定檔的 mcpServers 區塊加入:

"wordpress-reader": {
"command": "python",
"args": ["/絕對路徑/到/wp_mcp.py"]
}

5. AI 如何使用它?

一旦設定完成,你可以在對話框直接下令:

「幫我看看我的 WordPress 最近發了什麼文章,並總結最後一篇的內容。」or help me post or draft sth in md format to publish

AI 會自動呼叫 list_wp_posts 取得 ID,再呼叫 read_wp_post 讀取內容並回報給你。

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions