Skip to content
Back to search

mcp-wp

MCP Server for WordPress

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/instawp--mcp-wp/badge.svg)](/listings/instawp--mcp-wp)

HTML

<a href="/listings/instawp--mcp-wp"><img src="/api/listings/instawp--mcp-wp/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

1. **Clone the Repository:**

```bash git clone <repository_url> cd wordpress-mcp-server ```

2. **Install Dependencies:**

```bash npm install ```

3. **Create a `.env` file:**

Create a `.env` file in the root of your project directory and add your WordPress API credentials.

For a single site:

```env WORDPRESS_API_URL=https://your-wordpress-site.com WORDPRESS_USERNAME=wp_username WORDPRESS_PASSWORD=wp_app_password ```

For multiple sites:

```env WORDPRESS_1_URL=https://site1.com WORDPRESS_1_USERNAME=admin WORDPRESS_1_PASSWORD=app_password_1 WORDPRESS_1_ID=site1 WORDPRESS_1_DEFAULT=true

WORDPRESS_2_URL=https://site2.com WORDPRESS_2_USERNAME=admin WORDPRESS_2_PASSWORD=app_password_2 WORDPRESS_2_ID=site2 ```

Replace the placeholders with your actual values.

4. **Build the Server:**

```bash npm run build ```

5. **Configure Claude Desktop:**

- Open Claude Desktop settings and navigate to the "Developer" tab. - Click "Edit Config" to open the `claude_desktop_config.json` file. - Add a new server configuration under the `mcpServers` section. You will need to provide the **absolute** path to the `build/server.js` file and your WordPress environment variables. - Save the configuration.

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 946 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # WordPress MCP Server
  2. This is a Model Context Protocol (MCP) server for WordPress, allowing you to interact with your WordPress site using natural language via an MCP-compatible client like Claude for Desktop. This server exposes various WordPress data and functionality as MCP tools.
  3. ## Usage
  4. ### Claude Desktop
  5. 1. Download and install [Claude Desktop](https://claude.ai/download).
  6. 2. Open Claude Desktop settings and navigate to the "Developer" tab.
  7. 3. Copy the contents of the `claude_desktop_config.json.example` file.
  8. 4. Click "Edit Config" to open the `claude_desktop_config.json` file.
  9. 5. Copy paste the contents of the example file into the config file. Make sure to replace the placeholder values with your actual values for the WordPress site. To generate the application keys, follow this guide - [Application Passwords](https://make.wordpress.org/core/2020/11/05/application-passwords-integration-guide#Getting-Credentials).
  10. 6. Save the configuration.
  11. 7. Restart Claude Desktop.
  12. ## Features
  13. This server provides tools to interact with core WordPress data and supports **multi-site management** - manage multiple WordPress sites from a single MCP server instance.
  14. ### **Multi-Site Management** (3 tools)
  15. Manage multiple WordPress sites from a single MCP server:
  16. - `list_sites`: List all configured WordPress sites
  17. - `get_site`: Get details about a specific site configuration
  18. - `test_site`: Test connection to a specific WordPress site
  19. All content and taxonomy tools support an optional `site_id` parameter to target specific sites.
  20. ### **Unified Content Management** (9 tools)
  21. Handles ALL content types (posts, pages, custom post types) with a single set of intelligent tools:
  22. - `list_content`: List any content type with filtering and pagination
  23. - `get_content`: Get specific content by ID and type
  24. - `create_content`: Create new content of any type
  25. - `update_content`: Update existing content of any type, including targeted partial edits
  26. - `delete_content`: Delete content of any type
  27. - `discover_content_types`: Find all available content types on your site
  28. - `find_content_by_url`: Smart URL resolver that can find and optionally update content from any WordPress URL, including targeted partial edits
  29. - `get_content_by_slug`: Search by slug across all content types
  30. - `get_content_summary`: Return a minimal summary (id, title, slug, status, excerpt, taxonomies, word count, Yoast SEO fields) for audit and lookup workflows. Look up by `id` or `url`.
  31. ### **Unified Taxonomy Management** (8 tools)
  32. Handles ALL taxonomies (categories, tags, custom taxonomies) with a single set of tools:
  33. - `discover_taxonomies`: Find all available taxonomies on your site
  34. - `list_terms`: List terms in any taxonomy
  35. - `get_term`: Get specific term by ID
  36. - `create_term`: Create new term in any taxonomy
  37. - `update_term`: Update existing term
  38. - `delete_term`: Delete term from any taxonomy
  39. - `assign_terms_to_content`: Assign terms to any content type
  40. - `get_content_terms`: Get all terms for any content
  41. ### **Specialized Tools**
  42. - **Media:**
  43. - `list_media`: List all media items (supports pagination and searching).
  44. - `get_media`: Retrieve a specific media item by ID.
  45. - `create_media`: Create a new media item from a URL or local file path.
  46. - `update_media`: Update an existing media item.
  47. - `delete_media`: Delete a media item.
  48. - `edit_media`: Legacy alias for `update_media` kept for backward compatibility.
  49. - **Users:**
  50. - `list_users`: List all users with filtering, sorting, and pagination options.
  51. - `get_user`: Retrieve a specific user by ID.
  52. - `create_user`: Create a new user.
  53. - `update_user`: Update an existing user.
  54. - `delete_user`: Delete a user.
  55. - **Comments:**
  56. - `list_comments`: List all comments with filtering, sorting, and pagination options.
  57. - `get_comment`: Retrieve a specific comment by ID.
  58. - `create_comment`: Create a new comment.
  59. - `update_comment`: Update an existing comment.
  60. - `delete_comment`: Delete a comment.
  61. - **Plugins:**
  62. - `list_plugins`: List all plugins installed on the site.
  63. - `get_plugin`: Retrieve details about a specific plugin.
  64. - `activate_plugin`: Activate a plugin.
  65. - `deactivate_plugin`: Deactivate a plugin.
  66. - `create_plugin`: Create a new plugin.
  67. - **Plugin Repository:**
  68. - `search_plugins`: Search for plugins in the WordPress.org repository.
  69. - `get_plugin_info`: Get detailed information about a plugin from the repository.
  70. - **Database Queries:**
  71. - `execute_sql_query`: Execute read-only SQL queries against the WordPress database (requires custom endpoint setup).
  72. ### **Key Advantages**
  73. #### Media Upload Workflows
  74. Upload a local screenshot from the same machine running the MCP server:
  75. ```json
  76. {
  77. "file_path": "./screenshots/homepage.png",
  78. "title": "Homepage Screenshot",
  79. "alt_text": "Homepage screenshot showing the hero section"
  80. }
  81. ```
  82. Upload media from a remote URL:
  83. ```json
  84. {
  85. "source_url": "https://example.com/assets/hero-image.png",
  86. "title": "Hero Image",
  87. "caption": "Imported from the design system"
  88. }
  89. ```
  90. Use the returned media ID as featured media on new content:
  91. ```json
  92. {
  93. "content_type": "post",
  94. "title": "Release Notes",
  95. "content": "<p>Launch summary...</p>",
  96. "featured_media": 123
  97. }
  98. ```
  99. #### Smart URL Resolution
  100. The `find_content_by_url` tool can:
  101. - Take any WordPress URL and automatically find the corresponding content
  102. - Detect content types from URL patterns (e.g., `/documentation/` → documentation custom post type)
  103. - Optionally update the content in a single operation
  104. - Works with posts, pages, and any custom post types
  105. #### Audit & Lookup Summaries
  106. The `get_content_summary` tool returns a minimal, fixed-shape representation of a single piece of content. Designed for audit and lookup workflows where the full WP REST response — which can exceed 50KB on recipe posts because of the rendered Recipe Maker card HTML — is overkill.
  107. **Look up by ID** (with optional `content_type`, defaulting to `post`):
  108. ```json
  109. {
  110. "id": 4274,
  111. "content_type": "post"
  112. }
  113. ```
  114. **Look up by URL** (content type is detected from the URL):
  115. ```json
  116. {
  117. "url": "https://example.com/blog/easy-smoked-asparagus/"
  118. }
  119. ```
  120. `id` and `url` are mutually exclusive — provide exactly one.
  121. The response shape is fixed:
  122. ```json
  123. {
  124. "id": 4274,
  125. "title": "Easy Smoked Asparagus & Hot Honey",
  126. "slug": "easy-smoked-asparagus",
  127. "status": "publish",
  128. "link": "https://example.com/blog/easy-smoked-asparagus/",
  129. "excerpt": "Smoky asparagus with hot honey.",
  130. "date_modified": "2026-04-30T10:14:00",
  131. "categories": [12, 7],
  132. "tags": [33],
  133. "featured_media": 9012,
  134. "word_count": 875,
  135. "yoast_focus_keyword": "smoked asparagus",
  136. "yoast_meta_title": "Easy Smoked Asparagus | Example",
  137. "yoast_meta_description": "Smoky charred asparagus finished with chili-lime hot honey."
  138. }
  139. ```
  140. Field notes:
  141. - `title` and `excerpt` are stripped to plain text (HTML tags removed, basic entities decoded).
  142. - `word_count` prefers `yoast_head_json.schema.@graph[].wordCount` when Yoast SEO is active; otherwise it is computed from the rendered post content with HTML stripped.
  143. - `yoast_meta_title` and `yoast_meta_description` are read from `yoast_head_json` on the post. They are `null` when Yoast SEO is not active.
  144. - `yoast_focus_keyword` is read from `meta._yoast_wpseo_focuskw`. WordPress core only exposes meta keys that are registered with `show_in_rest`, and Yoast SEO does not register this key by default — so this field will typically be `null` unless a companion plugin registers it (see PR #17 for context on the broader meta-key REST exposure issue).
  145. - This tool internally bypasses the response trimming added in PR #16 so it can read `yoast_head_json`. The trim still applies to all other tools.
  146. #### Universal Content Operations
  147. All content operations use a single `content_type` parameter:
  148. ```json
  149. {
  150. "content_type": "post", // for blog posts
  151. "content_type": "page", // for static pages
  152. "content_type": "product", // for WooCommerce products
  153. "content_type": "documentation" // for custom post types
  154. }
  155. ```
  156. #### Targeted Content Edits
  157. `update_content` and `find_content_by_url.update_fields` can patch the existing raw WordPress content without resending the full document.
  158. To make exact matching easier, `get_content` and `find_content_by_url` both accept `include_raw_content: true`. When enabled, the response is fetched with WordPress edit context and includes a top-level `content_raw` field that matches what `content_edit.target_text` needs.
  159. ```json
  160. {
  161. "content_type": "page",
  162. "id": 7,
  163. "include_raw_content": true
  164. }
  165. ```
  166. Append a short release note to the end of a post:
  167. ```json
  168. {
  169. "content_type": "post",
  170. "id": 42,
  171. "content_edit": {
  172. "operation": "append",
  173. "value": "\n<p>Update: Early access is now open.</p>",
  174. "content_format": "html"
  175. }
  176. }
  177. ```
  178. Replace a unique HTML fragment or marker comment in place:
  179. ```json
  180. {
  181. "content_type": "page",
  182. "id": 7,
  183. "content_edit": {
  184. "operation": "replace",
  185. "target_text": "<!-- pricing-card -->\n<p>Old price</p>\n<!-- /pricing-card -->",
  186. "value": "<!-- pricing-card -->\n<p>New price</p>\n<!-- /pricing-card -->",
  187. "content_format": "html"
  188. }
  189. }
  190. ```
  191. Notes:
  192. - Rendered WordPress HTML can differ from `content.raw` because entities may be escaped and markup may be expanded, so use `include_raw_content` when you need an exact `target_text`.
  193. - `target_text` matches the stored raw WordPress content exactly.
  194. - If the same `target_text` appears multiple times, pass `occurrence` to choose the 1-based match.
  195. - For posts stored as Gutenberg blocks, set `content_edit.convert_to_blocks` when inserting Markdown or HTML that should become blocks.
  196. #### Universal Taxonomy Operations
  197. All taxonomy operations use a single `taxonomy` parameter:
  198. ```json
  199. {
  200. "taxonomy": "category", // for categories
  201. "taxonomy": "post_tag", // for tags
  202. "taxonomy": "product_category", // for WooCommerce
  203. "taxonomy": "skill" // for custom taxonomies
  204. }
  205. ```
  206. The `taxonomy` parameter accepts either the taxonomy slug or its `rest_base`
  207. (they can differ for custom taxonomies, e.g. slug `documentation_category`
  208. with rest_base `documentation-categories`). Tools resolve the identifier via
  209. `/wp/v2/taxonomies` and error on unknown taxonomies instead of guessing.
  210. `assign_terms_to_content` verifies the write against the WordPress response
  211. and reports an error if the terms were not actually saved.
  212. #### Recipe Cards (WP Recipe Maker)
  213. Sites running [WP Recipe Maker](https://wordpress.org/plugins/wp-recipe-maker/) (WPRM) store recipe cards in a separate `wprm_recipe` custom post type referenced by shortcode from the surrounding blog post. The unified content tools handle these recipes directly — no recipe-specific tool family is needed.
  214. **Reading recipes** — `get_content`, `list_content`, `find_content_by_url`, and `get_content_by_slug` all work with `content_type: "wprm_recipe"`. WPRM exposes the full structured recipe payload as a `recipe` field on the REST response, including ingredients, instructions, times, equipment, nutrition, notes, and rating.
  215. **Writing recipes** — pass the recipe payload via `custom_fields.recipe` on `create_content` or `update_content`. WPRM hooks into the WordPress REST insert action (`rest_insert_wprm_recipe`) and reads `recipe` from the request body root, so any field documented by WPRM's data model is accepted.
  216. > The `recipe` payload must be passed via `custom_fields` (which spreads at the request body root). The `meta` parameter nests its values under a `meta` key, which never reaches WPRM's REST hook.
  217. Example update:
  218. ```json
  219. {
  220. "content_type": "wprm_recipe",
  221. "id": 4274,
  222. "custom_fields": {
  223. "recipe": {
  224. "name": "Easy Smoked Asparagus",
  225. "summary": "Smoky asparagus with hot honey.",
  226. "servings": "4",
  227. "servings_unit": "people",
  228. "prep_time": "5",
  229. "cook_time": "60",
  230. "total_time": "65",
  231. "ingredients": [
  232. {
  233. "name": "",
  234. "ingredients": [
  235. { "uid": 0, "amount": "1", "unit": "Bunch", "name": "Asparagus Spears", "notes": "" },
  236. { "uid": 1, "amount": "1", "unit": "tbsp", "name": "Olive Oil", "notes": "" }
  237. ]
  238. }
  239. ],
  240. "instructions": [
  241. {
  242. "name": "",
  243. "instructions": [
  244. { "uid": 0, "name": "", "text": "Preheat smoker to 225°F.", "ingredients": [] },
  245. { "uid": 1, "name": "", "text": "Drizzle with oil, season, smoke 1 hour.", "ingredients": [] }
  246. ]
  247. }
  248. ],
  249. "notes": "Thicker spears need more time."
  250. }
  251. }
  252. }
  253. ```
  254. **Grouped ingredients and instructions** — recipes can split items into named groups like "For the sauce" / "For the chicken". Each entry in the outer `ingredients` (or `instructions`) array is one group with its own `name` and inner array:
  255. ```json
  256. {
  257. "ingredients": [
  258. { "name": "For the sauce", "ingredients": [ /* items */ ] },
  259. { "name": "For the chicken", "ingredients": [ /* items */ ] }
  260. ]
  261. }
  262. ```
  263. Commonly used recipe fields:
  264. | Field | Type | Notes |
  265. | --------------- | --------------- | ---------------------------------------------------- |
  266. | `name` | string | Recipe card title |
  267. | `summary` | string | Short blurb (HTML allowed) |
  268. | `servings` | string | e.g. `"4"` |
  269. | `servings_unit` | string | e.g. `"people"`, `"servings"` |
  270. | `prep_time` | string | minutes, e.g. `"15"` |
  271. | `cook_time` | string | minutes |
  272. | `total_time` | string | minutes |
  273. | `ingredients` | array of groups | nested structure shown above |
  274. | `instructions` | array of groups | nested structure shown above |
  275. | `notes` | string | HTML allowed |
  276. | `equipment` | array | items shaped `{ id, name, notes, amount, uid }` |
  277. | `image_url` | string | upload-by-URL when no `image_id` is supplied |
  278. Course, cuisine, and keyword are stored as WPRM taxonomies (`wprm_course`, `wprm_cuisine`, `wprm_keyword`). Manage them with the unified taxonomy tools (`list_terms`, `create_term`, …) and link them to a recipe with `assign_terms_to_content`.
  279. WPRM auto-syncs `recipe.summary` back to the WordPress `post_content` field on save. If you want the post body and the recipe summary to differ, pass `content` explicitly alongside `custom_fields.recipe`.
  280. ## Configuration
  281. ### Single Site Configuration
  282. For managing a single WordPress site, use the following environment variables:
  283. ```env
  284. WORDPRESS_API_URL=https://your-wordpress-site.com
  285. WORDPRESS_USERNAME=wp_username
  286. WORDPRESS_PASSWORD=wp_app_password
  287. ```
  288. ### Multi-Site Configuration
  289. To manage multiple WordPress sites from a single MCP server, use numbered environment variables:
  290. ```env
  291. # Site 1 (Production)
  292. WORDPRESS_1_URL=https://production-site.com
  293. WORDPRESS_1_USERNAME=admin
  294. WORDPRESS_1_PASSWORD=app_password_1
  295. WORDPRESS_1_ID=production
  296. WORDPRESS_1_DEFAULT=true
  297. WORDPRESS_1_ALIASES=prod,main
  298. # Site 2 (Staging)
  299. WORDPRESS_2_URL=https://staging-site.com
  300. WORDPRESS_2_USERNAME=admin
  301. WORDPRESS_2_PASSWORD=app_password_2
  302. WORDPRESS_2_ID=staging
  303. WORDPRESS_2_ALIASES=stage,dev
  304. # Site 3 (Development)
  305. WORDPRESS_3_URL=https://dev-site.com
  306. WORDPRESS_3_USERNAME=admin
  307. WORDPRESS_3_PASSWORD=app_password_3
  308. WORDPRESS_3_ID=development
  309. ```
  310. **Multi-Site Configuration Options:**
  311. - `WORDPRESS_N_URL`: WordPress site URL (required)
  312. - `WORDPRESS_N_USERNAME`: WordPress username (required)
  313. - `WORDPRESS_N_PASSWORD`: WordPress application password (required)
  314. - `WORDPRESS_N_ID`: Site identifier (optional, defaults to `siteN`)
  315. - `WORDPRESS_N_DEFAULT`: Set to `true` to make this the default site (optional, first site is default)
  316. - `WORDPRESS_N_ALIASES`: Comma-separated aliases for site detection (optional)
  317. The server supports up to 10 sites. When using multi-site configuration, all tools accept an optional `site_id` parameter to target specific sites.
  318. ## Using with npx and .env file
  319. You can run this MCP server directly using npx without installing it globally:
  320. ```bash
  321. npx -y @instawp/mcp-wp
  322. ```
  323. Make sure you have a `.env` file in your current directory with the following variables:
  324. ```env
  325. WORDPRESS_API_URL=https://your-wordpress-site.com
  326. WORDPRESS_USERNAME=wp_username
  327. WORDPRESS_PASSWORD=wp_app_password
  328. # Optional: Custom SQL query endpoint (default: /mcp/v1/query)
  329. WORDPRESS_SQL_ENDPOINT=/mcp/v1/query
  330. # Optional: Comma-separated list of top-level fields to strip from
  331. # WordPress REST API responses before they are returned to the MCP
  332. # client. Defaults to "yoast_head,yoast_head_json" — read-only schema
  333. # markup that adds ~10KB to every response but is rarely useful to the
  334. # LLM. Set to an empty string to disable trimming.
  335. MCP_WP_STRIP_FIELDS=yoast_head,yoast_head_json
  336. ```
  337. ## User Agent
  338. Every outbound request this server makes — the WordPress REST client used by all tools, the SQL
  339. endpoint, the two api.wordpress.org lookups, and remote media downloads — sends axios's default
  340. `axios/<version>` user-agent.
  341. Set `WORDPRESS_USER_AGENT` to override it everywhere:
  342. ```
  343. WORDPRESS_USER_AGENT=MyAgency-MCP/1.0 (+https://example.com)
  344. ```
  345. Leave it unset unless a CDN or WAF in front of your site rejects the default; an empty or
  346. whitespace-only value is treated as unset. Avoid a bare `Mozilla/5.0` — it is a well-known bot
  347. signature and is exactly what several edges block (see #28), which is why nothing here sends one.
  348. ## Response Trimming
  349. By default the server strips the top-level `yoast_head` and `yoast_head_json`
  350. fields from every WordPress REST API response before returning it to the MCP
  351. client. These fields contain Yoast SEO's pre-rendered schema markup, which the
  352. LLM almost never needs but pays tokens for on every request.
  353. - The trim applies to both single-object responses and arrays of objects.
  354. - Only **top-level** fields are stripped; nested objects are left untouched.
  355. - Override the list with the `MCP_WP_STRIP_FIELDS` environment variable
  356. (comma-separated). Set it to an empty string to disable trimming entirely.
  357. ## Meta field limitations
  358. The `meta` parameter on `create_content`, `update_content`, and `find_content_by_url` (with `update_fields.meta`) forwards directly to the WordPress `/wp/v2/{type}/{id}` endpoint. WordPress core **silently drops** any meta key that has not been registered via `register_post_meta(..., ['show_in_rest' => true])`. The MCP server has no allowlist of its own — it relies on WordPress to enforce which keys persist.
  359. This means SEO plugin keys are **not writable through this MCP server by default**, including:
  360. - **Yoast SEO**: `_yoast_wpseo_*` (focuskw, metadesc, title, opengraph-*, twitter-*, canonical, meta-robots-*, primary_category, …)
  361. - **Rank Math**: `rank_math_*` (title, description, focus_keyword, robots, facebook_*, twitter_*, primary_category, …)
  362. - **All in One SEO (v4+)**: stores SEO data in a custom table (`wp_aioseo_posts`), not `wp_postmeta` — not addressable via the `meta` field by any means.
  363. The server detects when WordPress dropped any keys you sent and prepends a `Warning:` block to the tool result listing them. This makes the silent drop visible to the LLM caller, but it cannot make WordPress accept the keys.
  364. To enable SEO meta writes, install a small WordPress companion plugin that calls `register_post_meta` for each desired key with `show_in_rest => true` and an appropriate `auth_callback`. A separate `mcp-wp-seo-bridge` plugin is being scoped to do exactly this.
  365. ### Which keys DO work today
  366. Plugin keys that the plugin author already registered for REST — for example Genesis layout meta (`_genesis_layout`), WP Recipe Maker fields (`wprm-*`), or ConvertKit's `_wp_convertkit_post_meta`. To check which keys round-trip on your site, write a test value via `update_content` and inspect the `meta` block in the response — if the key appears, it persisted.
  367. The same limitation applies to term meta on `unified-taxonomies` tools (`create_term`, `update_term`).
  368. ## Enabling SQL Query Tool (Optional)
  369. The `execute_sql_query` tool allows you to run read-only SQL queries against your WordPress database. This is an optional feature that requires adding a custom REST API endpoint to your WordPress site.
  370. **Security Notes:**
  371. - This tool only accepts read-only queries (SELECT, WITH...SELECT, EXPLAIN) for safety
  372. - Queries containing INSERT, UPDATE, DELETE, DROP, or other modifying statements will be rejected
  373. - Multi-statement queries are blocked to prevent SQL injection
  374. - SELECT syntax that reaches the **filesystem of the database host** — `INTO OUTFILE`, `INTO DUMPFILE`,
  375. `LOAD_FILE()` — is rejected. These are valid inside a SELECT, so a "starts with SELECT" check alone
  376. does not stop an arbitrary file read, or a webshell being written into `wp-content/uploads`
  377. - A query that cannot be read unambiguously is rejected rather than guessed at: an unterminated string
  378. or comment; a backslash-escaped quote inside a literal (whose meaning depends on the server's
  379. `NO_BACKSLASH_ESCAPES` sql_mode — use `''` to embed a quote instead); a MySQL `/*!` or MariaDB `/*M!`
  380. executable comment, whose contents the server actually runs; a NUL byte; or a function called by a
  381. quoted name (`` `LOAD_FILE`('/etc/passwd') `` resolves to the builtin on both engines, so the quoted
  382. form is refused however it is separated from its parenthesis, comments included — call functions by
  383. their unquoted name). One consequence worth knowing before you file it as a bug: a **quoted column
  384. list** is refused too, since it is a quoted token before a `(` —
  385. ``WITH `cte`(`a`) AS (SELECT 1) …`` and ``SELECT * FROM (SELECT 1) AS `t`(`a`)`` both have to be
  386. written without the quotes
  387. - This tool requires admin-level permissions (`manage_options` capability)
  388. **Set the database privileges. That is the boundary; the checks above are not.** Give the endpoint a
  389. MySQL/MariaDB user with `SELECT` only and **no `FILE` privilege** (or set `secure_file_priv`), so a
  390. query that gets past a pattern has nothing left to reach. The checks are a guard against a model —
  391. including one under prompt injection — issuing something the tool description promised it would not;
  392. they are pattern matching over SQL text, and pattern matching over SQL text is not a parser. Known gaps
  393. left open on purpose: a `SELECT` can still be expensive (`SLEEP()`, `BENCHMARK()`, `GET_LOCK()`), and
  394. neither the client nor the endpoint limits how long a query runs. (`FOR UPDATE` is refused, as a side
  395. effect of the `UPDATE` keyword rule.)
  396. **And the client's checks are not a boundary at all**, because anything holding the credentials can
  397. call the REST endpoint directly. The endpoint must therefore enforce its own limits — the example below
  398. repeats them server-side, using the same scanner. The two are kept in step by a test that extracts the
  399. PHP from this file and drives both over one shared corpus, so a fix applied to only one of them fails
  400. CI. They are deliberately not byte-identical in one place: `$wpdb` connects with `DB_CHARSET`, and
  401. MySQL's "whitespace or control character" is charset-dependent (latin1 adds `0xA0`, cp850 `0xFF`), so
  402. the PHP matches the union of those sets. The client cannot produce those bytes at all — it emits UTF-8,
  403. where they are a syntax error.
  404. **Logging:** nothing is logged unless you set `WORDPRESS_LOG_LEVEL=debug` (the default is `error`).
  405. Debug output goes to **stderr**, which for a stdio MCP server the host client (Claude Desktop and
  406. others) captures into its own log files. Credential headers such as `Authorization` and `Cookie` are
  407. redacted, and so are credential-shaped request-body keys (`password`, `token`, `secret`, `api_key`
  408. and their siblings) — a `create_user` call used to log the new user's password in the clear one line
  409. below the header bag. Query text, request bodies that are not credential-shaped, and result rows are
  410. **not** redacted, so avoid putting sensitive data in queries.
  411. **Configuration:** By default, the tool expects the endpoint at `/mcp/v1/query`. You can customize this by setting the `WORDPRESS_SQL_ENDPOINT` environment variable (e.g., `WORDPRESS_SQL_ENDPOINT=/custom/v1/query`).
  412. To enable this feature, add the following code to your WordPress site (via a custom plugin or your theme's `functions.php`):
  413. ```php
  414. /**
  415. * Blank every string literal, quoted identifier and comment, or return null when
  416. * the query cannot be read unambiguously.
  417. *
  418. * A scanner rather than a list of regexes, because the order regexes run in is
  419. * itself a bypass: strip comments first and `SELECT '#' INTO OUTFILE '/x'` has
  420. * everything from the `#` onwards removed, so the INTO disappears from the text
  421. * you check while the server still runs it.
  422. *
  423. * This mirrors normalizeQuery() in the client's src/tools/sql-query.ts — keep the
  424. * two the same. Four things are refused rather than guessed at:
  425. * - an unterminated literal or block comment;
  426. * - a backslash before a quote, because where the literal ends then depends on
  427. * the server's NO_BACKSLASH_ESCAPES sql_mode (use '' to embed a quote);
  428. * - /*! ... *\/ (MySQL) and /*M! ... *\/ (MariaDB) executable comments, whose
  429. * contents the server RUNS — they are not comments and cannot be stripped;
  430. * - a quoted token followed by `(`, i.e. a function called by a quoted name.
  431. * Both engines resolve `LOAD_FILE`('/etc/passwd') exactly as the bare
  432. * builtin, so blanking the identifier would erase the keyword you are
  433. * looking for. That test runs at the END, on the finished string, where
  434. * comments have already become spaces — checking it inline against the raw
  435. * text would only cover the separators someone thought of, and a comment is
  436. * whitespace to the server.
  437. */
  438. function mcp_wp_normalize_sql($query) {
  439. // A raw NUL cannot be told apart from the marker used below for a blanked
  440. // quoted token, and nothing legitimate sends one.
  441. if (strpos($query, "\0") !== false) {
  442. return null;
  443. }
  444. $out = '';
  445. $len = strlen($query);
  446. $i = 0;
  447. while ($i < $len) {
  448. $ch = $query[$i];
  449. if ($ch === "'" || $ch === '"' || $ch === '`') {
  450. $quote = $ch;
  451. $i++;
  452. $closed = false;
  453. while ($i < $len) {
  454. $c = $query[$i];
  455. if ($c === '\\' && $quote !== '`') {
  456. $next = $i + 1 < $len ? $query[$i + 1] : '';
  457. if ($next === "'" || $next === '"' || $next === '`') {
  458. return null;
  459. }
  460. $i += 2;
  461. continue;
  462. }
  463. if ($c === $quote) {
  464. if ($i + 1 < $len && $query[$i + 1] === $quote) { $i += 2; continue; }
  465. $i++;
  466. $closed = true;
  467. break;
  468. }
  469. $i++;
  470. }
  471. if (!$closed) {
  472. return null;
  473. }
  474. // Marked rather than blanked, so the quoted-function-name test can
  475. // run once at the end over the finished string.
  476. $out .= "\0";
  477. continue;
  478. }
  479. if ($ch === '/' && $i + 1 < $len && $query[$i + 1] === '*') {
  480. if (preg_match('/^[Mm]?!/', substr($query, $i + 2, 2))) {
  481. return null;
  482. }
  483. $end = strpos($query, '*/', $i + 2);
  484. if ($end === false) {
  485. return null;
  486. }
  487. $i = $end + 2;
  488. $out .= ' ';
  489. continue;
  490. }
  491. // The server starts a `--` comment on whitespace OR a control character
  492. // (`my_isspace || my_iscntrl`); `a--b` is arithmetic. Below 0x80 that is
  493. // fixed, and it is `[\x00-\x20\x7F]`.
  494. //
  495. // At or above 0x80 it is decided by character_set_client — which $wpdb
  496. // takes from DB_CHARSET — and the two engines do not even agree with each
  497. // other. The same byte can be a comment starter, an ordinary identifier
  498. // character, or an error, depending on both. Neither answer is safe to
  499. // guess: treat it as a comment and `SELECT 1--<0xA0> ... INTO OUTFILE` has
  500. // its whole tail blanked while the server runs it; treat it as code and
  501. // `\`LOAD_FILE\`--<0xA0>\n(...)` keeps text the server drops, which pushes
  502. // the quoted name away from its `(` and defeats the check below. Both were
  503. // measured, in both directions.
  504. //
  505. // So it is refused, like every other construct here that cannot be read
  506. // unambiguously. Nothing legitimate puts a high byte straight after `--`.
  507. $next = $i + 2 < $len ? $query[$i + 2] : '';
  508. if ($ch === '-' && $i + 1 < $len && $query[$i + 1] === '-'
  509. && $next !== '' && preg_match('/[\x80-\xFF]/', $next)) {
  510. return null;
  511. }
  512. if ($ch === '-' && $i + 1 < $len && $query[$i + 1] === '-'
  513. && ($next === '' || preg_match('/[\x00-\x20\x7F]/', $next))) {
  514. $nl = strpos($query, "\n", $i);
  515. $i = $nl === false ? $len : $nl;
  516. $out .= ' ';
  517. continue;
  518. }
  519. if ($ch === '#') {
  520. $nl = strpos($query, "\n", $i);
  521. $i = $nl === false ? $len : $nl;
  522. $out .= ' ';
  523. continue;
  524. }
  525. $out .= $ch;
  526. $i++;
  527. }
  528. // A quoted token followed by `(` is a function called by a quoted name.
  529. // PCRE's \s is ASCII-only, and whether a high byte separates two tokens is
  530. // charset-dependent — a raw 0xA0 there calls the builtin on both engines
  531. // under latin1 — so every high byte counts as a separator. Unlike the `--`
  532. // class above, widening *here* only ever rejects more, and nothing
  533. // legitimate puts a non-ASCII byte between an identifier and its `(`.
  534. if (preg_match('/\x00[\s\x80-\xFF]*\(/', $out)) {
  535. return null;
  536. }
  537. return str_replace("\0", ' ', $out);
  538. }
  539. add_action('rest_api_init', function() {
  540. register_rest_route('mcp/v1', '/query', array(
  541. 'methods' => 'POST',
  542. 'callback' => function($request) {
  543. global $wpdb;
  544. $query = $request->get_param('query');
  545. // Additional security check
  546. if (!current_user_can('manage_options')) {
  547. return new WP_Error('unauthorized', 'Unauthorized', array('status' => 401));
  548. }
  549. // A JSON body can send anything; without this a `{"query": []}`
  550. // is a PHP TypeError and a 500 rather than a 400.
  551. if (!is_string($query)) {
  552. return new WP_Error('invalid_query', 'query must be a string', array('status' => 400));
  553. }
  554. // Read-only statements only. Checked on the raw query, like the
  555. // client, so a leading comment stays a rejection rather than
  556. // becoming allowed once comments are blanked below.
  557. $trimmed = ltrim($query, " \t\n\r\0\x0B\f");
  558. if (stripos($trimmed, 'SELECT') !== 0
  559. && stripos($trimmed, 'WITH ') !== 0
  560. && stripos($trimmed, 'EXPLAIN ') !== 0) {
  561. return new WP_Error('invalid_query', 'Only read-only queries (SELECT, WITH...SELECT, EXPLAIN) are allowed', array('status' => 400));
  562. }
  563. // Do not trust the caller's validation. Every check below runs against
  564. // the normalized query, so a keyword inside a literal is not a false
  565. // positive and one split by a comment is not a bypass (the server
  566. // treats a comment as whitespace).
  567. $normalized = mcp_wp_normalize_sql($query);
  568. if (!is_string($normalized)) {
  569. return new WP_Error('invalid_query', 'Query could not be validated', array('status' => 400));
  570. }
  571. // One statement only.
  572. if (preg_match('/;\s*\S/', $normalized)) {
  573. return new WP_Error('invalid_query', 'Only one statement is allowed', array('status' => 400));
  574. }
  575. // INTO OUTFILE / INTO DUMPFILE write a file on the database host and
  576. // LOAD_FILE() reads one; all three are valid SELECT syntax.
  577. if (preg_match('/\b(INTO|LOAD_FILE)\b/i', $normalized)) {
  578. return new WP_Error('invalid_query', 'Filesystem access is not allowed', array('status' => 400));
  579. }
  580. if (preg_match('/\b(DROP|DELETE|UPDATE|ALTER|CREATE|GRANT|REVOKE)\b/i', $normalized)) {
  581. return new WP_Error('invalid_query', 'Only read-only queries are allowed', array('status' => 400));
  582. }
  583. // INSERT(), TRUNCATE() and REPLACE() are also ordinary read-only
  584. // functions, so these three only count when no `(` follows.
  585. if (preg_match('/\b(INSERT|TRUNCATE|REPLACE)\b(?!\s*\()/i', $normalized)) {
  586. return new WP_Error('invalid_query', 'Only read-only queries are allowed', array('status' => 400));
  587. }
  588. $results = $wpdb->get_results($query, ARRAY_A);
  589. if ($wpdb->last_error) {
  590. return new WP_Error('query_error', $wpdb->last_error, array('status' => 400));
  591. }
  592. return array(
  593. 'results' => $results,
  594. 'num_rows' => count($results)
  595. );
  596. },
  597. 'permission_callback' => function() {
  598. return current_user_can('manage_options');
  599. }
  600. ));
  601. });
  602. ```
  603. After adding this code, you can use the `execute_sql_query` tool to run queries like:
  604. ```sql
  605. SELECT * FROM wp_posts WHERE post_type = 'post' AND post_status = 'publish' LIMIT 10
  606. ```
  607. ## Development
  608. ### Prerequisites
  609. - **Node.js and npm:** Ensure you have Node.js (version 18 or higher) and npm installed.
  610. Node 18 is enough to *run* the server. **Contributing** needs Node 20 or newer, because the
  611. test tooling (Vitest 4) requires it — CI runs 20.x and 22.x.
  612. - **WordPress Site:** You need an active WordPress site with the REST API enabled.
  613. - **WordPress API Authentication:** Set up authentication for the WordPress REST API. This typically requires an authentication plugin or method (like Application Passwords).
  614. - **MCP Client:** You need an application that can communicate with the MCP Server. Currently, Claude Desktop is recommended.
  615. ### Installation and Setup
  616. 1. **Clone the Repository:**
  617. ```bash
  618. git clone <repository_url>
  619. cd wordpress-mcp-server
  620. ```
  621. 2. **Install Dependencies:**
  622. ```bash
  623. npm install
  624. ```
  625. 3. **Create a `.env` file:**
  626. Create a `.env` file in the root of your project directory and add your WordPress API credentials.
  627. For a single site:
  628. ```env
  629. WORDPRESS_API_URL=https://your-wordpress-site.com
  630. WORDPRESS_USERNAME=wp_username
  631. WORDPRESS_PASSWORD=wp_app_password
  632. ```
  633. For multiple sites:
  634. ```env
  635. WORDPRESS_1_URL=https://site1.com
  636. WORDPRESS_1_USERNAME=admin
  637. WORDPRESS_1_PASSWORD=app_password_1
  638. WORDPRESS_1_ID=site1
  639. WORDPRESS_1_DEFAULT=true
  640. WORDPRESS_2_URL=https://site2.com
  641. WORDPRESS_2_USERNAME=admin
  642. WORDPRESS_2_PASSWORD=app_password_2
  643. WORDPRESS_2_ID=site2
  644. ```
  645. Replace the placeholders with your actual values.
  646. 4. **Build the Server:**
  647. ```bash
  648. npm run build
  649. ```
  650. 5. **Configure Claude Desktop:**
  651. - Open Claude Desktop settings and navigate to the "Developer" tab.
  652. - Click "Edit Config" to open the `claude_desktop_config.json` file.
  653. - Add a new server configuration under the `mcpServers` section. You will need to provide the **absolute** path to the `build/server.js` file and your WordPress environment variables.
  654. - Save the configuration.
  655. ### Running the Server
  656. Once you've configured Claude Desktop, the server should start automatically whenever Claude Desktop starts.
  657. You can also run the server directly from the command line for testing:
  658. ```bash
  659. npm start
  660. ```
  661. or in development mode:
  662. ```bash
  663. npm run dev
  664. ```
  665. ### Running Tests
  666. The repo uses [Vitest](https://vitest.dev/) for unit tests. Tests live under `tests/` and cover the
  667. multi-site `SiteManager` and the MCP tool registry wiring.
  668. ```bash
  669. npm test # one-shot run
  670. npm run test:watch # watch mode
  671. ```
  672. Tests run on `pull_request` and on pushes to `main` via `.github/workflows/test.yml`.
  673. ### Releasing
  674. Merging a fix does not reach anyone — npm keeps serving the last published version until a release
  675. runs. Publishing is automated by `.github/workflows/release.yml`, triggered by a version tag:
  676. ```bash
  677. # on main, with the fix already merged:
  678. # 1. move the CHANGELOG's [Unreleased] block under a `[x.y.z] - <date>` heading and commit it
  679. # 2. bump and tag — `npm version` writes package.json, commits, and creates the vx.y.z tag
  680. npm version patch # or minor / major
  681. # 3. push the commit and the tag; the tag is what triggers the publish
  682. git push origin main --follow-tags
  683. ```
  684. Do the CHANGELOG edit *before* `npm version`. Amending the commit afterwards leaves the tag pointing
  685. at the pre-amend commit, and the workflow would publish from that.
  686. The workflow refuses to publish if the tag and `package.json` disagree, or if that version is
  687. already on npm; it then builds, runs the tests, publishes with
  688. [provenance](https://docs.npmjs.com/generating-provenance-statements), and confirms the registry
  689. actually serves the new version before reporting success.
  690. If a tag exists but the publish failed (or predates this workflow), re-run it from
  691. **Actions → Release → Run workflow**, leaving the branch selector on `main` (that is where the
  692. workflow file is read from) and passing the tag name in the input. Two caveats: the tag's tree must
  693. already contain the `repository` field described below, and the provenance attestation records the
  694. ref the workflow was *dispatched from*, not the tag — so for a real release, prefer re-cutting a
  695. version and using the tag-push path.
  696. If the publish succeeds but the verification step goes red (a registry that stayed slow for more
  697. than two minutes), check npmjs.com before doing anything: the version is published, and re-running
  698. will now fail the already-on-npm guard by design. Nothing needs fixing in that case.
  699. **Setup, once:** the workflow needs an npm automation token with publish rights on the `@instawp`
  700. scope, stored as the repository secret `NPM_TOKEN` (Settings → Secrets and variables → Actions). An
  701. *automation* token specifically — a classic publish token fails in CI on a 2FA-enforced account.
  702. npm's [trusted publishing](https://docs.npmjs.com/trusted-publishers) would remove the stored token
  703. entirely, but it needs npm ≥ 11.5.1 and `setup-node` currently ships npm 10.x with Node 22, so it is
  704. not usable here without also upgrading npm inside the job.
  705. Publishing with provenance requires the `repository` field in `package.json` to match this repo — the
  706. registry rejects the publish otherwise. Don't remove it.
  707. ### Security
  708. - **Never commit your API keys or secrets to version control.**
  709. - **Use HTTPS for communication between the client and server.**
  710. - **Validate all inputs received from the client to prevent injection attacks.**
  711. - **Implement proper error handling and rate limiting.**
  712. ## Project Overview
  713. ### Architecture
  714. The server uses a **unified tool architecture** to reduce complexity:
  715. ```text
  716. src/
  717. ├── server.ts # MCP server entry point
  718. ├── wordpress.ts # WordPress REST API client
  719. ├── cli.ts # CLI interface
  720. ├── config/
  721. │ └── site-manager.ts # Multi-site management
  722. ├── types/
  723. │ └── wordpress-types.ts # TypeScript definitions
  724. └── tools/
  725. ├── index.ts # Tool aggregation
  726. ├── site-management.ts # Site management (3 tools)
  727. ├── unified-content.ts # Universal content management (8 tools)
  728. ├── unified-taxonomies.ts # Universal taxonomy management (8 tools)
  729. ├── media.ts # Media management (5 canonical tools + edit_media alias)
  730. ├── users.ts # User management (~5 tools)
  731. ├── comments.ts # Comment management (~5 tools)
  732. ├── plugins.ts # Plugin management (~5 tools)
  733. ├── plugin-repository.ts # WordPress.org plugin search (~2 tools)
  734. └── sql-query.ts # Database queries (1 tool)
  735. ```
  736. ### Key Features
  737. - **Multi-Site Support**: Manage multiple WordPress sites from a single MCP server instance
  738. - **Smart URL Resolution**: Automatically detect content types from URLs and find corresponding content
  739. - **Universal Content Management**: Single set of tools handles posts, pages, and custom post types
  740. - **Universal Taxonomy Management**: Single set of tools handles categories, tags, and custom taxonomies
  741. - **Type Safety**: Full TypeScript support with Zod schema validation
  742. - **Comprehensive Logging**: Detailed API request/response logging for debugging
  743. - **Error Handling**: Graceful error handling with informative messages
  744. ### Getting Started
  745. 1. Clone the repository and install dependencies with `npm install`
  746. 2. Create a `.env` file with your WordPress credentials
  747. 3. Build the project with `npm run build`
  748. 4. Configure Claude Desktop with the server
  749. 5. Start using natural language to manage your WordPress site!
  750. ### Contribution
  751. Feel free to open issues or make pull requests to improve this project. Check out `CLAUDE.md` for detailed development guidelines.

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.