diff --git a/README.md b/README.md index e67496e..8be70f2 100644 --- a/README.md +++ b/README.md @@ -26,13 +26,13 @@ Manage multiple WordPress sites from a single MCP server: - `get_site`: Get details about a specific site configuration - `test_site`: Test connection to a specific WordPress site -All content and taxonomy tools support an optional `site_id` parameter to target specific sites. +All content, taxonomy, media, plugin, comment, and user tools support an optional `site_id` parameter to target specific sites. ### **Unified Content Management** (9 tools) Handles ALL content types (posts, pages, custom post types) with a single set of intelligent tools: -- `list_content`: List any content type with filtering and pagination +- `list_content`: List any content type with filtering and pagination. Supports `fields` to select which top-level fields come back (e.g. `["id", "slug", "meta"]`) — see [Selecting fields](#selecting-fields). - `get_content`: Get specific content by ID and type - `create_content`: Create new content of any type - `update_content`: Update existing content of any type, including targeted partial edits @@ -266,11 +266,68 @@ with rest_base `documentation-categories`). Tools resolve the identifier via `/wp/v2/taxonomies` and error on unknown taxonomies instead of guessing. `assign_terms_to_content` verifies the write against the WordPress response and reports an error if the terms were not actually saved. +`create_content` and `update_content` verify their `categories`/`tags` writes +the same way, but since the rest of the write (title, content, meta) did +apply, they report a warning alongside the successful result instead of an +error, naming the exact term IDs WordPress silently dropped. #### Recipe Cards (WP Recipe Maker) 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. +### Selecting fields + +`list_content` and `get_content` return every field by default, and for post types +that carry long bodies that is almost always more than the caller wants — a +listing of four neighbourhood guides can run to 90KB of rendered HTML. Pass +`fields` to ask WordPress for a subset: + +```json +{ "content_type": "post", "per_page": 20, "fields": ["id", "slug", "meta"] } +``` + +`get_content` takes the same parameter, which matters most on a single long post +where the rendered body is nearly the whole payload: + +```json +{ "content_type": "post", "id": 5575, "fields": ["id", "slug", "meta"] } +``` + +One restriction there: `include_raw_content` reads `content.raw` off the +response, so a selection that doesn't deliver the raw body would return +successfully with no `content_raw` and no explanation. Combining the two is +rejected unless the selection includes `content` or `content.raw` — note that +`content.rendered` does **not** qualify, since it is a sibling subfield and +carries no raw body. + +This maps to WordPress's own [`_fields`](https://developer.wordpress.org/rest-api/using-the-rest-api/global-parameters/#_fields) +parameter, so nested paths work too (`title.rendered`), and a requested field an +item doesn't have is simply absent rather than an error. + +Two behaviours worth knowing, both verified against a live site: + +- **A selection drops `_links`** unless you name it. The HAL `_links` block is a + field like any other, so `["id", "slug"]` returns no links. +- **A selection naming only fields that don't exist returns empty objects**, not + an error and not an empty list — `_fields=typo` on a listing of two posts comes + back as `[{}, {}]`. Read that as "your field names were wrong", not "no posts". + +Useful selections: + +| Goal | `fields` | +| --- | --- | +| Inspect metadata (SEO keys, custom fields) | `["id", "slug", "meta"]` | +| Build an index or a link list | `["id", "title", "link"]` | +| Check publication state | `["id", "status", "modified"]` | +| Read a body exactly, for editing | `["id", "content"]` with `include_raw_content` | + +Omit `fields` to get the full payload, which is the previous behaviour — minus +whatever `MCP_WP_STRIP_FIELDS` removes (`yoast_head` and `yoast_head_json` by +default). Those fields are deleted from every response after WordPress returns +them, so a selection asking only for them would come back as empty objects; +`list_content` errors in that case rather than returning a result that looks +like missing data. + **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. **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. diff --git a/src/tools/comments.ts b/src/tools/comments.ts index 99b313a..baaffa8 100644 --- a/src/tools/comments.ts +++ b/src/tools/comments.ts @@ -6,6 +6,7 @@ import { z } from 'zod'; // Schema for listing comments const listCommentsSchema = z.object({ + site_id: z.string().optional().describe("Site ID (for multi-site setups)"), page: z.coerce.number().optional().describe("Page number (default 1)"), per_page: z.coerce.number().min(1).max(100).optional().describe("Items per page (default 10, max 100)"), search: z.string().optional().describe("Search term for comment content"), @@ -22,11 +23,13 @@ const listCommentsSchema = z.object({ // Schema for getting a single comment const getCommentSchema = z.object({ + site_id: z.string().optional().describe("Site ID (for multi-site setups)"), id: z.coerce.number().describe("Comment ID") }).strict(); // Schema for creating a comment const createCommentSchema = z.object({ + site_id: z.string().optional().describe("Site ID (for multi-site setups)"), post: z.coerce.number().describe("The ID of the post object the comment is for"), author: z.coerce.number().optional().describe("The ID of the user object, if the author is a registered user"), author_name: z.string().optional().describe("Display name for the comment author"), @@ -39,6 +42,7 @@ const createCommentSchema = z.object({ // Schema for updating a comment const updateCommentSchema = z.object({ + site_id: z.string().optional().describe("Site ID (for multi-site setups)"), id: z.coerce.number().describe("Comment ID"), post: z.coerce.number().optional().describe("The ID of the post object the comment is for"), author: z.coerce.number().optional().describe("The ID of the user object, if the author is a registered user"), @@ -52,6 +56,7 @@ const updateCommentSchema = z.object({ // Schema for deleting a comment const deleteCommentSchema = z.object({ + site_id: z.string().optional().describe("Site ID (for multi-site setups)"), id: z.coerce.number().describe("Comment ID"), force: z.boolean().optional().describe("Whether to bypass trash and force deletion") }).strict(); @@ -96,7 +101,8 @@ export const commentTools: Tool[] = [ export const commentHandlers = { list_comments: async (params: ListCommentsParams) => { try { - const response = await makeWordPressRequest('GET', "comments", params); + const { site_id, ...query } = params; + const response = await makeWordPressRequest('GET', "comments", query, { siteId: site_id }); const comments: WPComment[] = response; return { toolResult: { @@ -116,7 +122,7 @@ export const commentHandlers = { get_comment: async (params: GetCommentParams) => { try { - const response = await makeWordPressRequest('GET', `comments/${params.id}`); + const response = await makeWordPressRequest('GET', `comments/${params.id}`, undefined, { siteId: params.site_id }); const comment: WPComment = response; return { toolResult: { @@ -136,7 +142,8 @@ export const commentHandlers = { create_comment: async (params: CreateCommentParams) => { try { - const response = await makeWordPressRequest('POST', "comments", params); + const { site_id, ...body } = params; + const response = await makeWordPressRequest('POST', "comments", body, { siteId: site_id }); const comment: WPComment = response; return { toolResult: { @@ -156,8 +163,8 @@ export const commentHandlers = { update_comment: async (params: UpdateCommentParams) => { try { - const { id, ...updateData } = params; - const response = await makeWordPressRequest('POST', `comments/${id}`, updateData); + const { id, site_id, ...updateData } = params; + const response = await makeWordPressRequest('POST', `comments/${id}`, updateData, { siteId: site_id }); const comment: WPComment = response; return { toolResult: { @@ -177,7 +184,7 @@ export const commentHandlers = { delete_comment: async (params: DeleteCommentParams) => { try { - const response = await makeWordPressRequest('DELETE', `comments/${params.id}`, { force: params.force }); + const response = await makeWordPressRequest('DELETE', `comments/${params.id}`, { force: params.force }, { siteId: params.site_id }); const comment: WPComment = response; return { toolResult: { diff --git a/src/tools/plugins.ts b/src/tools/plugins.ts index 4913b5e..b2c5465 100644 --- a/src/tools/plugins.ts +++ b/src/tools/plugins.ts @@ -11,22 +11,27 @@ import { zodToJsonSchema } from 'zod-to-json-schema'; // Make schema empty since the WordPress REST API plugins endpoint doesn't accept parameters // in the same way as other endpoints const listPluginsSchema = z.object({ + site_id: z.string().optional().describe("Site ID (for multi-site setups)"), status: z.enum(['active', 'inactive']).optional().default('active').describe("Filter plugins by status (active, inactive)") }).strict(); const getPluginSchema = z.object({ + site_id: z.string().optional().describe("Site ID (for multi-site setups)"), plugin: z.string().describe("Plugin slug (e.g., 'akismet', 'elementor', 'wordpress-seo')") }).strict(); const activatePluginSchema = z.object({ + site_id: z.string().optional().describe("Site ID (for multi-site setups)"), plugin: z.string().describe("Plugin slug (e.g., 'akismet', 'elementor', 'wordpress-seo')") }).strict(); const deactivatePluginSchema = z.object({ + site_id: z.string().optional().describe("Site ID (for multi-site setups)"), plugin: z.string().describe("Plugin slug (e.g., 'akismet', 'elementor', 'wordpress-seo')") }).strict(); const createPluginSchema = z.object({ + site_id: z.string().optional().describe("Site ID (for multi-site setups)"), slug: z.string({ required_error: "Plugin slug is required" }).describe("WordPress.org plugin directory slug, e.g., 'akismet', 'elementor', 'wordpress-seo'"), status: z.enum(['inactive', 'active']).optional().default('active').describe("Plugin activation status") }).strict(); @@ -70,7 +75,8 @@ export const pluginTools: Tool[] = [ export const pluginHandlers = { list_plugins: async (params: z.infer) => { try { - const response = await makeWordPressRequest("GET", "plugins", params); + const { site_id, ...query } = params; + const response = await makeWordPressRequest("GET", "plugins", query, { siteId: site_id }); return { toolResult: { content: [{ type: "text", text: JSON.stringify(response, null, 2) }] @@ -88,7 +94,7 @@ export const pluginHandlers = { }, get_plugin: async (params: z.infer) => { try { - const response = await makeWordPressRequest("GET", `plugins/${params.plugin}`); + const response = await makeWordPressRequest("GET", `plugins/${params.plugin}`, undefined, { siteId: params.site_id }); return { toolResult: { content: [{ type: "text", text: JSON.stringify(response, null, 2) }] @@ -106,7 +112,8 @@ export const pluginHandlers = { }, activate_plugin: async (params: z.infer) => { try { - const response = await makeWordPressRequest("POST", `plugins/${params.plugin}/activate`, params); + const { site_id, ...body } = params; + const response = await makeWordPressRequest("POST", `plugins/${params.plugin}/activate`, body, { siteId: site_id }); return { toolResult: { content: [{ type: "text", text: JSON.stringify(response, null, 2) }] @@ -124,7 +131,8 @@ export const pluginHandlers = { }, deactivate_plugin: async (params: z.infer) => { try { - const response = await makeWordPressRequest("POST", `plugins/${params.plugin}/deactivate`, params); + const { site_id, ...body } = params; + const response = await makeWordPressRequest("POST", `plugins/${params.plugin}/deactivate`, body, { siteId: site_id }); return { toolResult: { content: [{ type: "text", text: JSON.stringify(response, null, 2) }] @@ -142,7 +150,8 @@ export const pluginHandlers = { }, create_plugin: async (params: z.infer) => { try { - const response = await makeWordPressRequest("POST", "plugins", params); + const { site_id, ...body } = params; + const response = await makeWordPressRequest("POST", "plugins", body, { siteId: site_id }); return { toolResult: { content: [{ type: "text", text: JSON.stringify(response, null, 2) }] diff --git a/src/tools/unified-content.ts b/src/tools/unified-content.ts index 1f133be..7118585 100644 --- a/src/tools/unified-content.ts +++ b/src/tools/unified-content.ts @@ -1,6 +1,7 @@ // src/tools/unified-content.ts import { Tool } from '@modelcontextprotocol/sdk/types.js'; -import { makeWordPressRequest, logToFile } from '../wordpress.js'; +import { makeWordPressRequest, logToFile, resolveStripFields } from '../wordpress.js'; +import { siteManager } from '../config/site-manager.js'; import { z } from 'zod'; import * as fs from 'fs-extra'; import * as path from 'path'; @@ -16,11 +17,40 @@ const CACHE_DIR = process.env.UNIFIED_CONTENT_CACHE_DIR // Ensure the cache directory exists at module load time (best-effort) fs.ensureDir(CACHE_DIR).catch(() => {}); -// Cache for post types to reduce API calls -let postTypesCache: any = null; -let cacheTimestamp: number = 0; +// Cache for post types, keyed per site, to reduce API calls. +// Mirrors the per-site pattern in unified-taxonomies.ts: an unkeyed singleton +// here let one site's post types shadow another's (the memory cache was checked +// before the correctly-keyed disk cache), so endpoint resolution for custom +// post types could use the wrong site's rest_base until a forced refresh. +interface PostTypesCacheEntry { + data: any; + timestamp: number; +} +const postTypesCache = new Map(); const CACHE_DURATION = parseInt(process.env.WORDPRESS_CACHE_DURATION || '3600000'); // Default 1 hour, configurable +/** + * Resolve an optional siteId to the concrete id the cache layers key on. + * + * Callers reach the default site two ways — omitting site_id, or passing its + * actual id — and both must land in the same cache slot, or a forced refresh + * through one shape leaves the other stale (and, when a *non-default* site is + * explicitly named "default", the two sites would share a disk file). + * Exported for unified-taxonomies.ts, whose per-site cache has the same + * two-shapes property. + */ +export function resolveCacheSiteId(siteId?: string): string { + if (siteId) { + return siteId; + } + try { + return siteManager.getDefaultSiteId() || '__default__'; + } catch { + // Nothing configured yet (e.g. unit tests); still cache coherently. + return '__default__'; + } +} + // Helper function to load cache from disk async function loadCacheFromDisk(siteId?: string): Promise<{ data: any; timestamp: number } | null> { try { @@ -57,20 +87,21 @@ async function saveCacheToDisk(data: any, siteId?: string): Promise { // Helper function to get all post types with caching async function getPostTypes(forceRefresh = false, siteId?: string) { const now = Date.now(); + const cacheKey = resolveCacheSiteId(siteId); // Try memory cache first - if (!forceRefresh && postTypesCache && (now - cacheTimestamp) < CACHE_DURATION) { + const cached = postTypesCache.get(cacheKey); + if (!forceRefresh && cached && (now - cached.timestamp) < CACHE_DURATION) { logToFile('Using memory-cached post types', 'debug'); - return postTypesCache; + return cached.data; } // Try disk cache if memory cache is stale if (!forceRefresh) { - const diskCache = await loadCacheFromDisk(siteId); + const diskCache = await loadCacheFromDisk(cacheKey); if (diskCache && (now - diskCache.timestamp) < CACHE_DURATION) { logToFile('Using disk-cached post types', 'debug'); - postTypesCache = diskCache.data; - cacheTimestamp = diskCache.timestamp; + postTypesCache.set(cacheKey, { data: diskCache.data, timestamp: diskCache.timestamp }); return diskCache.data; } } @@ -79,11 +110,10 @@ async function getPostTypes(forceRefresh = false, siteId?: string) { try { logToFile('Fetching post types from API', 'info'); const response = await makeWordPressRequest('GET', 'types', undefined, { siteId }); - postTypesCache = response; - cacheTimestamp = now; + postTypesCache.set(cacheKey, { data: response, timestamp: now }); // Save to disk for persistence - await saveCacheToDisk(response, siteId); + await saveCacheToDisk(response, cacheKey); return response; } catch (error: any) { @@ -373,22 +403,19 @@ function convertHtmlToBlocks(html: string): string { blocks.push(`\n${element}\n`); break; case 'h1': - blocks.push(`\n${element}\n`); - break; case 'h2': - blocks.push(`\n${element}\n`); - break; case 'h3': - blocks.push(`\n${element}\n`); - break; case 'h4': - blocks.push(`\n${element}\n`); - break; case 'h5': - blocks.push(`\n${element}\n`); - break; case 'h6': - blocks.push(`\n${element}\n`); + // Always emit the level explicitly. h2 used to be the lone bare case + // (Gutenberg's serializer omits the default level), which made + // conversion output inconsistent across heading levels and read as + // "the {"level":2} attribute got stripped" when existing content was + // round-tripped through this converter. An explicit default attribute + // is valid for the block parser, and a single deterministic form is + // worth more here than canonical minimalism. + blocks.push(`\n${element}\n`); break; case 'ul': blocks.push(`\n${element}\n`); @@ -518,6 +545,61 @@ export function buildDroppedMetaWarning(droppedKeys: string[]): string { ); } +// One entry per term field whose write could not be confirmed from the +// response WordPress sent back. +export interface DroppedTermField { + field: 'categories' | 'tags'; + requested: number[]; + saved: number[] | null; // null: the response carries no such field at all + missing: number[]; +} + +// Compare the term IDs a write requested against the IDs the response reports +// as saved. wp_set_object_terms() silently skips IDs that do not exist, and +// /wp/v2 returns 200 with the survivors — so a partial term write is invisible +// unless the response is checked. Detection mirrors the response-derived +// check in assign_terms_to_content, but the SEVERITY deliberately diverges +// from it: that tool writes nothing but terms, so a dropped term is a failed +// call (isError). create/update also wrote title/content/etc., which DID +// land, so this follows the dropped-meta-keys warning precedent above +// instead — a loud warning on a successful result. +export function detectDroppedTerms( + requested: { categories?: number | number[]; tags?: number | number[] } | undefined, + response: any +): DroppedTermField[] { + const dropped: DroppedTermField[] = []; + for (const field of ['categories', 'tags'] as const) { + const value = requested?.[field]; + if (value === undefined) { + continue; + } + // Normalized defensively; the tool schemas only pass arrays here. + const ids = Array.isArray(value) ? value : [value]; + const echoed = response?.[field]; + const saved = Array.isArray(echoed) ? (echoed as number[]) : null; + const missing = saved === null ? [...ids] : ids.filter((id) => !saved.includes(id)); + if (missing.length > 0) { + dropped.push({ field, requested: [...ids], saved, missing }); + } + } + return dropped; +} + +export function buildDroppedTermsWarning(dropped: DroppedTermField[]): string { + return dropped + .map(({ field, requested, saved, missing }) => + saved === null + ? `Warning: the response reports no "${field}" field, so none of the requested ` + + `${field} [${requested.join(', ')}] can be confirmed as saved. The taxonomy may not be ` + + `registered for this content type, or not exposed in REST — assign_terms_to_content ` + + `resolves custom taxonomies by rest_base if that is the case.` + : `Warning: WordPress saved ${field} [${saved.join(', ')}] but silently dropped ` + + `[${missing.join(', ')}] — term IDs it does not know. The rest of the write was applied. ` + + `Verify the IDs (list_terms) or create the terms first, then retry.` + ) + .join('\n'); +} + function validateContentEdit(edit: ContentEditParams) { const targetedOperations = new Set(['insert_before', 'insert_after', 'replace']); @@ -616,12 +698,45 @@ async function fetchContentById( endpoint: string, id: number, siteId?: string, - includeRawContent: boolean = false + includeRawContent: boolean = false, + fields?: string[] ) { + const fieldsParam = buildFieldsParam(fields, 'get_content'); + + // withContentRawAlias reads content.raw off the response. A selection that + // doesn't deliver content.raw makes that silently produce nothing, so the + // caller would get a successful response with no content_raw and no + // explanation. Only 'content' and 'content.raw' qualify — 'content.rendered' + // is a sibling subfield and yields no raw body, so it must not pass here. + if (includeRawContent && fields?.length && + !fields.some(f => f === 'content' || f === 'content.raw')) { + throw new Error( + `include_raw_content needs the raw body, but the requested selection ` + + `(${fields.join(', ')}) does not include it — content_raw would be missing. ` + + `Add 'content' or 'content.raw' to fields, or drop include_raw_content.` + ); + } + + // The same stranding by another route: trimResponseFields runs on the way out + // of makeWordPressRequest, before withContentRawAlias reads content.raw. If + // `content` is stripped, the alias finds nothing and content_raw goes missing + // with isError false, whether or not a selection was requested. + if (includeRawContent && resolveStripFields(process.env.MCP_WP_STRIP_FIELDS).includes('content')) { + throw new Error( + `include_raw_content needs the raw body, but MCP_WP_STRIP_FIELDS removes ` + + `'content' from every response, so content_raw would be missing. ` + + `Narrow MCP_WP_STRIP_FIELDS to use include_raw_content.` + ); + } + + const params: Record = {}; + if (includeRawContent) params.context = 'edit'; + if (fieldsParam) params._fields = fieldsParam; + const response = await makeWordPressRequest( 'GET', `${endpoint}/${id}`, - includeRawContent ? { context: 'edit' } : undefined, + Object.keys(params).length > 0 ? params : undefined, { siteId } ); @@ -697,6 +812,44 @@ async function buildContentUpdateData( return updateData; } +/** + * Turn a `fields` selection into WordPress's `_fields` query value. + * + * Every response is run through trimResponseFields, which deletes the fields + * named by MCP_WP_STRIP_FIELDS *after* WordPress returns them. A selection made + * up entirely of those would come back as an empty object with isError false — + * indistinguishable from "the site has no such data", with nothing pointing at + * the cause. Fail loudly instead, and name the variable responsible. + * + * Returns undefined when no selection was requested, so the caller can leave + * `_fields` off the query entirely; WordPress ignores an empty `_fields` and + * returns the full payload, which would silently defeat the whole point. + */ +function buildFieldsParam(fields: string[] | undefined, toolName: string): string | undefined { + if (!fields?.length) return undefined; + + const stripped = resolveStripFields(process.env.MCP_WP_STRIP_FIELDS); + const conflicting = fields.filter(f => stripped.includes(f.split('.')[0])); + + if (conflicting.length === fields.length) { + throw new Error( + `Every requested field is removed from responses by MCP_WP_STRIP_FIELDS ` + + `(${conflicting.join(', ')}), so the result would be empty. ` + + `Unset or narrow MCP_WP_STRIP_FIELDS to read these fields.` + ); + } + + if (conflicting.length > 0) { + logToFile( + `${toolName}: requested field(s) ${conflicting.join(', ')} are removed by ` + + `MCP_WP_STRIP_FIELDS and will be absent from the result.`, + 'info' + ); + } + + return fields.join(','); +} + // Schema definitions const listContentSchema = z.object({ content_type: z.string().describe("The content type slug (e.g., 'post', 'page', 'product', 'documentation')"), @@ -713,7 +866,16 @@ const listContentSchema = z.object({ orderby: z.string().optional().describe("Sort content by parameter"), order: z.enum(['asc', 'desc']).optional().describe("Order sort attribute"), after: z.string().optional().describe("ISO8601 date string to get content published after this date"), - before: z.string().optional().describe("ISO8601 date string to get content published before this date") + before: z.string().optional().describe("ISO8601 date string to get content published before this date"), + fields: z.array(z.string().trim().min(1)).nonempty().optional().describe( + "Limit each item to these top-level fields (WordPress `_fields`). A listing " + + "returns every field by default, including fully rendered `content`, which is " + + "usually far larger than what the caller needs. Ask for ['id','slug','meta'] to " + + "inspect metadata, or ['id','title','link'] to build an index. Nested paths such " + + "as 'title.rendered' are supported by WordPress. Requested fields the item does " + + "not have are simply absent from the response. Note that a selection also drops " + + "the `_links` block unless you name it." + ) }); const getContentSchema = z.object({ @@ -722,6 +884,15 @@ const getContentSchema = z.object({ site_id: z.string().optional().describe("Site ID (for multi-site setups)"), include_raw_content: z.boolean().optional().default(false).describe( "Fetch the content with WordPress edit context and include a top-level content_raw field for exact matching" + ), + fields: z.array(z.string().trim().min(1)).nonempty().optional().describe( + "Limit the response to these top-level fields (WordPress `_fields`). A post " + + "returns every field by default, including fully rendered `content`, which " + + "dominates the payload on long posts. Ask for ['id','slug','meta'] to inspect " + + "metadata without pulling the body. Nested paths such as 'title.rendered' are " + + "supported. Note that a selection also drops the `_links` block unless named, " + + "and cannot be combined with include_raw_content unless 'content' or " + + "'content.raw' is selected — 'content.rendered' does not carry the raw body." ) }); @@ -882,12 +1053,12 @@ type GetContentBySlugParams = z.infer; export const unifiedContentTools: Tool[] = [ { name: "list_content", - description: "Lists content of any type (posts, pages, or custom post types) with filtering and pagination", + description: "Lists content of any type (posts, pages, or custom post types) with filtering and pagination. Returns every field of every item by default (minus anything MCP_WP_STRIP_FIELDS removes), including fully rendered content — pass `fields` to select only what you need (e.g. ['id','slug','meta']), which is dramatically cheaper on large posts.", inputSchema: { type: "object", properties: listContentSchema.shape } }, { name: "get_content", - description: "Gets specific content by ID and content type", + description: "Gets specific content by ID and content type. Returns every field by default (minus anything MCP_WP_STRIP_FIELDS removes), including fully rendered content — pass `fields` to select only what you need (e.g. ['id','slug','meta']).", inputSchema: { type: "object", properties: getContentSchema.shape } }, { @@ -933,9 +1104,18 @@ export const unifiedContentHandlers = { list_content: async (params: ListContentParams) => { try { const endpoint = await getContentEndpoint(params.content_type, params.site_id); - const { content_type, site_id, ...queryParams } = params; + const { content_type, site_id, fields, ...queryParams } = params; + + // WordPress spells this `_fields`, and ignores anything it doesn't + // recognise — so passing `fields` straight through would silently return + // the full payload instead of erroring. Map it explicitly. + const requestParams: Record = { ...queryParams }; + const fieldsParam = buildFieldsParam(fields, 'list_content'); + if (fieldsParam) { + requestParams._fields = fieldsParam; + } - const response = await makeWordPressRequest('GET', endpoint, queryParams, { siteId: site_id }); + const response = await makeWordPressRequest('GET', endpoint, requestParams, { siteId: site_id }); return { toolResult: { @@ -970,7 +1150,8 @@ export const unifiedContentHandlers = { endpoint, params.id, params.site_id, - params.include_raw_content || false + params.include_raw_content || false, + params.fields ); return { @@ -1051,6 +1232,12 @@ export const unifiedContentHandlers = { if (droppedMeta.length > 0) { responseContent.unshift({ type: 'text', text: buildDroppedMetaWarning(droppedMeta) }); } + // Check the assembled payload, not params: custom_fields can carry + // categories/tags into the request too. + const droppedTerms = detectDroppedTerms(contentData, response); + if (droppedTerms.length > 0) { + responseContent.unshift({ type: 'text', text: buildDroppedTermsWarning(droppedTerms) }); + } return { toolResult: { @@ -1089,6 +1276,12 @@ export const unifiedContentHandlers = { if (droppedMeta.length > 0) { responseContent.unshift({ type: 'text', text: buildDroppedMetaWarning(droppedMeta) }); } + // Check the assembled payload, not params: custom_fields can carry + // categories/tags into the request too. + const droppedTerms = detectDroppedTerms(updateData, response); + if (droppedTerms.length > 0) { + responseContent.unshift({ type: 'text', text: buildDroppedTermsWarning(droppedTerms) }); + } return { toolResult: { diff --git a/src/tools/unified-taxonomies.ts b/src/tools/unified-taxonomies.ts index e0ea63f..c913172 100644 --- a/src/tools/unified-taxonomies.ts +++ b/src/tools/unified-taxonomies.ts @@ -1,7 +1,7 @@ // src/tools/unified-taxonomies.ts import { Tool } from '@modelcontextprotocol/sdk/types.js'; import { makeWordPressRequest, logToFile } from '../wordpress.js'; -import { getContentEndpoint } from './unified-content.js'; +import { getContentEndpoint, resolveCacheSiteId } from './unified-content.js'; import { z } from 'zod'; // Cache for taxonomies, keyed per site, to reduce API calls @@ -14,7 +14,7 @@ const CACHE_DURATION = 5 * 60 * 1000; // 5 minutes // Helper function to get all taxonomies for a site with caching async function getTaxonomies(forceRefresh = false, siteId?: string) { - const cacheKey = siteId || '__default__'; + const cacheKey = resolveCacheSiteId(siteId); const now = Date.now(); const cached = taxonomiesCache.get(cacheKey); diff --git a/src/tools/users.ts b/src/tools/users.ts index 9e387be..a3f9ca4 100644 --- a/src/tools/users.ts +++ b/src/tools/users.ts @@ -6,6 +6,7 @@ import { z } from 'zod'; import { zodToJsonSchema } from 'zod-to-json-schema'; const listUsersSchema = z.object({ + site_id: z.string().optional().describe("Site ID (for multi-site setups)"), page: z.number().optional().describe("Page number (default 1)"), per_page: z.number().min(1).max(100).optional().describe("Items per page (default 10, max 100)"), search: z.string().optional().describe("Search term for user content or name"), @@ -16,11 +17,13 @@ const listUsersSchema = z.object({ }); const getUserSchema = z.object({ + site_id: z.string().optional().describe("Site ID (for multi-site setups)"), id: z.coerce.number().describe("User ID"), context: z.enum(['view', 'embed', 'edit']).optional().describe("Scope under which the request is made") }).strict(); const createUserSchema = z.object({ + site_id: z.string().optional().describe("Site ID (for multi-site setups)"), username: z.string().describe("User login name"), name: z.string().optional().describe("Display name for the user"), first_name: z.string().optional().describe("First name for the user"), @@ -36,6 +39,7 @@ const createUserSchema = z.object({ }).strict(); const updateUserSchema = z.object({ + site_id: z.string().optional().describe("Site ID (for multi-site setups)"), id: z.coerce.number().describe("User ID"), username: z.string().optional().describe("User login name"), name: z.string().optional().describe("Display name for the user"), @@ -52,6 +56,7 @@ const updateUserSchema = z.object({ }).strict(); const deleteUserSchema = z.object({ + site_id: z.string().optional().describe("Site ID (for multi-site setups)"), id: z.coerce.number().describe("User ID"), force: z.boolean().optional().describe("Whether to bypass trash and force deletion"), reassign: z.coerce.number().optional().describe("User ID to reassign posts to") @@ -94,7 +99,8 @@ export const userTools: Tool[] = [ export const userHandlers = { list_users: async (params: ListUsersParams) => { try { - const response = await makeWordPressRequest('GET', "users", params); + const { site_id, ...query } = params; + const response = await makeWordPressRequest('GET', "users", query, { siteId: site_id }); const users: WPUser[] = response; return { toolResult: { @@ -113,7 +119,7 @@ export const userHandlers = { }, get_user: async (params: GetUserParams) => { try { - const response = await makeWordPressRequest('GET', `users/${params.id}`, { context: params.context }); + const response = await makeWordPressRequest('GET', `users/${params.id}`, { context: params.context }, { siteId: params.site_id }); const user: WPUser = response; return { toolResult: { @@ -132,7 +138,8 @@ export const userHandlers = { }, create_user: async (params: CreateUserParams) => { try { - const response = await makeWordPressRequest('POST', "users", params); + const { site_id, ...body } = params; + const response = await makeWordPressRequest('POST', "users", body, { siteId: site_id }); const user: WPUser = response; return { toolResult: { @@ -151,8 +158,8 @@ export const userHandlers = { }, update_user: async (params: UpdateUserParams) => { try { - const { id, ...updateData } = params; - const response = await makeWordPressRequest('POST', `users/${id}`, updateData); + const { id, site_id, ...updateData } = params; + const response = await makeWordPressRequest('POST', `users/${id}`, updateData, { siteId: site_id }); const user: WPUser = response; return { toolResult: { @@ -174,7 +181,7 @@ export const userHandlers = { const response = await makeWordPressRequest('DELETE', `users/${params.id}`, { force: params.force, reassign: params.reassign - }); + }, { siteId: params.site_id }); const user: WPUser = response; return { toolResult: { diff --git a/tests/tools/get-content-fields.test.ts b/tests/tools/get-content-fields.test.ts new file mode 100644 index 0000000..8f3b890 --- /dev/null +++ b/tests/tools/get-content-fields.test.ts @@ -0,0 +1,204 @@ +import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest'; + +const requests: Array<{ method: string; endpoint: string; params: any }> = []; + +vi.mock('../../src/wordpress.js', () => ({ + makeWordPressRequest: vi.fn(async (method: string, endpoint: string, data?: any) => { + requests.push({ method, endpoint, params: data }); + if (endpoint === '/wp/v2/types') { + return { post: { slug: 'post', rest_base: 'posts' } }; + } + return { id: 5575, slug: 'a-post', content: { raw: 'RAW BODY', rendered: '

x

' } }; + }), + logToFile: vi.fn(), + resolveStripFields: (envValue?: string) => + envValue === undefined + ? ['yoast_head', 'yoast_head_json'] + : envValue.split(',').map(f => f.trim()).filter(Boolean), +})); + +let getContent: (params: any) => Promise; +let logToFile: any; + +beforeAll(async () => { + const mod = await import('../../src/tools/unified-content.js'); + getContent = (mod.unifiedContentHandlers as any).get_content; + logToFile = (await import('../../src/wordpress.js')).logToFile; +}); + +beforeEach(() => { + requests.length = 0; + logToFile.mockClear?.(); +}); + +function lastItemCall() { + const calls = requests.filter(r => r.method === 'GET' && !r.endpoint.includes('/types')); + return calls[calls.length - 1]; +} + +describe('get_content field selection', () => { + // The bug this catches: `fields` reaching WordPress under its own name. + // WordPress spells it `_fields` and ignores unknown query args, so a straight + // passthrough returns the whole post — including a body that can run to tens + // of KB — while appearing to succeed. + it('sends the selection as _fields, never as fields', async () => { + await getContent({ content_type: 'post', id: 5575, fields: ['id', 'meta'] }); + + const call = lastItemCall(); + expect(call.params._fields).toBe('id,meta'); + expect(call.params).not.toHaveProperty('fields'); + }); + + // The bug this catches: sending an empty or undefined _fields when no + // selection was asked for. WordPress ignores an empty _fields and returns the + // full payload, so this fails silently rather than loudly. + it('sends no params at all when nothing is requested', async () => { + await getContent({ content_type: 'post', id: 5575 }); + + expect(lastItemCall().params).toBeUndefined(); + }); + + // The bug this catches: a selection that omits `content` combined with + // include_raw_content. withContentRawAlias reads content.raw off the + // response, so the caller would get a 200 with no content_raw and no + // explanation — the exact silent-success shape this connector keeps hitting. + it('refuses a selection that would strand include_raw_content', async () => { + const result = await getContent({ + content_type: 'post', + id: 5575, + include_raw_content: true, + fields: ['id', 'meta'], + }); + + expect(result.toolResult.isError).toBe(true); + expect(result.toolResult.content[0].text).toContain('include_raw_content'); + }); + + it('allows include_raw_content when content is selected, and still sets edit context', async () => { + const result = await getContent({ + content_type: 'post', + id: 5575, + include_raw_content: true, + fields: ['id', 'content'], + }); + + expect(result.toolResult.isError).toBe(false); + const call = lastItemCall(); + expect(call.params.context).toBe('edit'); + expect(call.params._fields).toBe('id,content'); + expect(result.toolResult.content[0].text).toContain('RAW BODY'); + }); + + // The bug this catches: a guard that accepts any field under `content.`. + // content.rendered is a sibling of content.raw and carries no raw body, so a + // selection naming it passed the check and still returned isError false with + // content_raw absent — the exact silent success the guard exists to prevent. + // Confirmed against a live site before this was tightened. + it('rejects content.rendered, which carries no raw body', async () => { + const result = await getContent({ + content_type: 'post', + id: 5575, + include_raw_content: true, + fields: ['id', 'content.rendered'], + }); + + expect(result.toolResult.isError).toBe(true); + expect(result.toolResult.content[0].text).toContain('content.raw'); + }); + + it('accepts a nested content path for include_raw_content', async () => { + const result = await getContent({ + content_type: 'post', + id: 5575, + include_raw_content: true, + fields: ['id', 'content.raw'], + }); + + expect(result.toolResult.isError).toBe(false); + expect(lastItemCall().params._fields).toBe('id,content.raw'); + }); + + // The bug this catches: asking only for fields that trimResponseFields + // deletes on the way out. The response would be an empty object with + // isError false, indistinguishable from "this post has no such data". + it('errors when every requested field is stripped from responses', async () => { + const result = await getContent({ + content_type: 'post', + id: 5575, + fields: ['yoast_head'], + }); + + expect(result.toolResult.isError).toBe(true); + expect(result.toolResult.content[0].text).toContain('MCP_WP_STRIP_FIELDS'); + }); + + it('keeps edit context when raw content is requested without a selection', async () => { + await getContent({ content_type: 'post', id: 5575, include_raw_content: true }); + + const call = lastItemCall(); + expect(call.params.context).toBe('edit'); + expect(call.params).not.toHaveProperty('_fields'); + }); + + // The bug this catches: a guard matched with startsWith('content') rather + // than an exact comparison. `content_raw` is the name of the alias this tool + // adds to its own output, not a WordPress field — an easy thing for a caller + // to reach for, and it must not satisfy the guard. + it('rejects content_raw, which is this tool\'s output alias and not a WP field', async () => { + const result = await getContent({ + content_type: 'post', + id: 5575, + include_raw_content: true, + fields: ['id', 'content_raw'], + }); + + expect(result.toolResult.isError).toBe(true); + }); + + // The bug this catches: comparing whole field paths against the stripped list + // instead of their root. `yoast_head.title` is removed just as surely as + // `yoast_head`, because trimResponseFields deletes the top-level key. + it('errors on a nested path whose root field is stripped', async () => { + const result = await getContent({ + content_type: 'post', + id: 5575, + fields: ['yoast_head.title'], + }); + + expect(result.toolResult.isError).toBe(true); + expect(result.toolResult.content[0].text).toContain('MCP_WP_STRIP_FIELDS'); + }); + + // The bug this catches: the shared helper hardcoding one tool's name in the + // partial-overlap warning, so a get_content caller is told list_content ate + // their field. The toolName argument exists for exactly this and nothing + // else asserts it. + it('names get_content in the partial-overlap warning', async () => { + await getContent({ content_type: 'post', id: 5575, fields: ['id', 'yoast_head'] }); + + const messages = logToFile.mock.calls.map((c: any[]) => String(c[0])); + expect(messages.some(m => m.startsWith('get_content:'))).toBe(true); + }); + + // The bug this catches: MCP_WP_STRIP_FIELDS naming `content` strands + // include_raw_content by a second route — trimResponseFields deletes the + // field on the way out, before withContentRawAlias reads it, so content_raw + // goes missing with isError false even with no selection at all. + it('errors when MCP_WP_STRIP_FIELDS removes content and raw content is wanted', async () => { + const previous = process.env.MCP_WP_STRIP_FIELDS; + process.env.MCP_WP_STRIP_FIELDS = 'content'; + try { + const result = await getContent({ + content_type: 'post', + id: 5575, + include_raw_content: true, + }); + + expect(result.toolResult.isError).toBe(true); + expect(result.toolResult.content[0].text).toContain('MCP_WP_STRIP_FIELDS'); + } finally { + if (previous === undefined) delete process.env.MCP_WP_STRIP_FIELDS; + else process.env.MCP_WP_STRIP_FIELDS = previous; + } + }); +}); diff --git a/tests/tools/html-to-blocks-headings.test.ts b/tests/tools/html-to-blocks-headings.test.ts new file mode 100644 index 0000000..d06cc7d --- /dev/null +++ b/tests/tools/html-to-blocks-headings.test.ts @@ -0,0 +1,82 @@ +import { describe, it, expect, vi, beforeAll } from 'vitest'; + +// Captures the body of each write so tests can inspect the exact content the +// converter produced, without any WordPress on the other end. +const writes: Array<{ endpoint: string; data: any }> = []; + +vi.mock('../../src/wordpress.js', () => ({ + makeWordPressRequest: vi.fn(async (method: string, endpoint: string, data?: any) => { + if (method === 'POST' || method === 'PUT') { + writes.push({ endpoint, data }); + return { id: 1, ...data }; + } + return {}; + }), + logToFile: vi.fn(), +})); + +let createContent: (params: any) => Promise; + +beforeAll(async () => { + const mod = await import('../../src/tools/unified-content.js'); + createContent = (mod.unifiedContentHandlers as any).create_content; +}); + +async function convertViaCreate(content: string, extra: Record = {}): Promise { + const before = writes.length; + await createContent({ + content_type: 'post', + title: 'Heading conversion test', + content, + convert_to_blocks: true, + ...extra, + }); + expect(writes.length).toBe(before + 1); + return writes[writes.length - 1].data.content as string; +} + +describe('convertHtmlToBlocks heading levels', () => { + // The bug this catches:

was the one heading case that emitted a bare + // `` with no {"level":2}, while h1 and h3-h6 all carried + // their level. Converted documents came out inconsistent across heading + // levels, and content whose blocks previously carried an explicit + // {"level":2} appeared to have the attribute stripped after any + // convert_to_blocks round-trip — which is exactly how it was reported from + // the field ("stripped the level off every heading block"). + it('emits an explicit level attribute for every heading tag, h2 included', async () => { + const html = '

One

Two

Three

Four

Five
Six
'; + const blocks = await convertViaCreate(html); + + for (const level of [1, 2, 3, 4, 5, 6]) { + expect(blocks).toContain(``); + } + // No heading may fall through to the attribute-less form. + expect(blocks).not.toMatch(//); + }); + + it('keeps the original heading element as the block body', async () => { + const blocks = await convertViaCreate('

Section title

'); + + expect(blocks).toContain('\n

Section title

\n'); + }); + + it('markdown headings get the explicit level too', async () => { + // Markdown is the other route into the converter: ## →

→ wp:heading. + const blocks = await convertViaCreate('## From markdown\n\nBody text.', { + content_format: 'markdown', + }); + + expect(blocks).toContain(''); + expect(blocks).not.toMatch(//); + }); + + it('content already in block format is passed through untouched', async () => { + // Guards the pass-through: a document that already contains a bare + // `` (Gutenberg's own canonical h2 serialization) must + // not be rewritten — the converter only runs on non-block input. + const original = '\n

Existing

\n'; + const result = await convertViaCreate(original); + + expect(result).toBe(original); + }); +}); diff --git a/tests/tools/list-content-fields.test.ts b/tests/tools/list-content-fields.test.ts new file mode 100644 index 0000000..b24c65c --- /dev/null +++ b/tests/tools/list-content-fields.test.ts @@ -0,0 +1,135 @@ +import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest'; + +// Captures the outgoing GET so tests can assert on the exact query WordPress +// would receive, with no WordPress on the other end. +const requests: Array<{ method: string; endpoint: string; params: any }> = []; + +vi.mock('../../src/wordpress.js', () => ({ + makeWordPressRequest: vi.fn(async (method: string, endpoint: string, data?: any) => { + requests.push({ method, endpoint, params: data }); + if (endpoint === '/wp/v2/types') { + return { post: { slug: 'post', rest_base: 'posts' } }; + } + return []; + }), + logToFile: vi.fn(), + resolveStripFields: (envValue?: string) => + envValue === undefined + ? ['yoast_head', 'yoast_head_json'] + : envValue.split(',').map(f => f.trim()).filter(Boolean), +})); + +let listContent: (params: any) => Promise; + +beforeAll(async () => { + const mod = await import('../../src/tools/unified-content.js'); + listContent = (mod.unifiedContentHandlers as any).list_content; +}); + +beforeEach(() => { + requests.length = 0; +}); + +function lastListCall() { + const listCalls = requests.filter(r => r.method === 'GET' && !r.endpoint.includes('/types')); + return listCalls[listCalls.length - 1]; +} + +describe('list_content field selection', () => { + // The bug this catches: `fields` reaching WordPress under its own name. + // WordPress spells the parameter `_fields` and silently ignores query args it + // doesn't recognise, so a straight passthrough returns the complete payload + // while appearing to succeed. That failure is invisible at the call site and + // only shows up as a response tens of times larger than asked for — which is + // how it was hit in the field, a 90KB post body returned for a request that + // wanted three metadata keys. + it('sends the selection as _fields, never as fields', async () => { + await listContent({ content_type: 'post', fields: ['id', 'slug', 'meta'] }); + + const call = lastListCall(); + expect(call.params._fields).toBe('id,slug,meta'); + expect(call.params).not.toHaveProperty('fields'); + }); + + // The bug this catches: sending `_fields=` (or `_fields=undefined`) when the + // caller didn't ask for a selection. WordPress parses _fields with + // wp_parse_list and ignores an empty one, so this would not fail loudly — it + // would quietly return the entire payload the caller was trying to avoid, + // looking like success. Verified against a live site: `_fields=` returns a + // byte-identical response to sending no _fields at all. + it('omits _fields entirely when no selection is requested', async () => { + await listContent({ content_type: 'post', per_page: 5 }); + + const call = lastListCall(); + expect(call.params).not.toHaveProperty('_fields'); + expect(call.params.per_page).toBe(5); + }); + + it('preserves the other filters alongside the selection', async () => { + await listContent({ + content_type: 'post', + fields: ['id'], + per_page: 3, + status: 'publish', + search: 'wilmington', + }); + + const call = lastListCall(); + expect(call.params._fields).toBe('id'); + expect(call.params.per_page).toBe(3); + expect(call.params.status).toBe('publish'); + expect(call.params.search).toBe('wilmington'); + }); + + // The bug this catches: site_id or content_type leaking into the query string. + // Both are routing inputs, not WordPress query args; content_type selects the + // endpoint and site_id selects the client. + it('keeps routing inputs out of the query string', async () => { + await listContent({ content_type: 'post', fields: ['id'] }); + + const call = lastListCall(); + expect(call.params).not.toHaveProperty('content_type'); + expect(call.params).not.toHaveProperty('site_id'); + }); + + it('supports nested field paths verbatim', async () => { + await listContent({ content_type: 'post', fields: ['id', 'title.rendered'] }); + + expect(lastListCall().params._fields).toBe('id,title.rendered'); + }); + + // The bug this catches: every response passes through trimResponseFields, + // which deletes yoast_head/yoast_head_json (or whatever MCP_WP_STRIP_FIELDS + // names) AFTER WordPress returns them. A selection asking only for those came + // back as one empty object per item with isError false — indistinguishable + // from "this site has no Yoast data", and no way for the caller to tell. + it('errors instead of returning empty objects when every field is stripped', async () => { + const result = await listContent({ content_type: 'post', fields: ['yoast_head'] }); + + expect(result.toolResult.isError).toBe(true); + expect(result.toolResult.content[0].text).toContain('MCP_WP_STRIP_FIELDS'); + }); + + it('still serves a selection that only partly overlaps the stripped fields', async () => { + const result = await listContent({ + content_type: 'post', + fields: ['id', 'yoast_head'], + }); + + expect(result.toolResult.isError).toBe(false); + expect(lastListCall().params._fields).toBe('id,yoast_head'); + }); + + it('honours a narrowed MCP_WP_STRIP_FIELDS', async () => { + const previous = process.env.MCP_WP_STRIP_FIELDS; + process.env.MCP_WP_STRIP_FIELDS = 'something_else'; + try { + const result = await listContent({ content_type: 'post', fields: ['yoast_head'] }); + expect(result.toolResult.isError).toBe(false); + expect(lastListCall().params._fields).toBe('yoast_head'); + } finally { + if (previous === undefined) delete process.env.MCP_WP_STRIP_FIELDS; + else process.env.MCP_WP_STRIP_FIELDS = previous; + } + }); +}); diff --git a/tests/tools/post-types-cache.test.ts b/tests/tools/post-types-cache.test.ts new file mode 100644 index 0000000..c082b4b --- /dev/null +++ b/tests/tools/post-types-cache.test.ts @@ -0,0 +1,232 @@ +import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest'; +import * as fs from 'fs-extra'; +import * as path from 'path'; +import * as os from 'os'; + +// Each site answers /wp/v2/types with its own post types. Where two sites share +// a custom type slug it deliberately carries a different rest_base on each — +// that is the collision that made an unkeyed cache dangerous rather than +// merely stale. Every test uses its own site ids so each is self-contained and +// runnable in isolation (vitest -t) or under --sequence.shuffle. +const SITE_TYPES: Record = { + siteA: { + post: { rest_base: 'posts' }, + recipe: { rest_base: 'wprm-recipes' }, + }, + siteB: { + post: { rest_base: 'posts' }, + recipe: { rest_base: 'site-b-recipes' }, + }, + siteC: { + recipe: { rest_base: 'site-c-recipes' }, + }, + siteD: { + recipe: { rest_base: 'site-d-recipes' }, + }, + siteE: { + // No 'recipe' here: lookups for it must fall through, not borrow siteD's. + mih_guide: { rest_base: 'mih-guides' }, + }, + siteF: { + recipe: { rest_base: 'site-f-recipes' }, + }, + siteG: { + recipe: { rest_base: 'site-g-recipes' }, + }, + siteH: { + recipe: { rest_base: 'site-h-live' }, + }, + siteJ: { + recipe: { rest_base: 'site-j-live' }, + }, + siteK: { + recipe: { rest_base: 'site-k-live' }, + }, + // Served for requests with no siteId (the default site). + __default__: { + recipe: { rest_base: 'default-site-recipes' }, + }, +}; + +const requestLog: Array<{ endpoint: string; siteId?: string }> = []; +const typesFetchCount = () => requestLog.filter((r) => r.endpoint === 'types').length; + +vi.mock('../../src/wordpress.js', () => ({ + makeWordPressRequest: vi.fn(async (_method: string, endpoint: string, _data?: any, options?: { siteId?: string }) => { + requestLog.push({ endpoint, siteId: options?.siteId }); + if (endpoint === 'types') { + return SITE_TYPES[options?.siteId || '__default__'] ?? {}; + } + return {}; + }), + logToFile: vi.fn(), +})); + +// CACHE_DIR is resolved at module load time from UNIFIED_CONTENT_CACHE_DIR, so +// the env var must be set before the module under test is imported — hence the +// dynamic import below instead of a top-level one. WORDPRESS_API_URL is set so +// the site manager has a configured default site (id 'default', the legacy +// single-site shape), which the default-slot tests below rely on. +const ENV_KEYS = ['UNIFIED_CONTENT_CACHE_DIR', 'WORDPRESS_API_URL', 'WORDPRESS_USERNAME', 'WORDPRESS_PASSWORD']; +let envBackup: Record; + +let getContentEndpoint: (contentType: string, siteId?: string) => Promise; +let discoverContentTypes: (params: any) => Promise; +let cacheDir: string; + +const diskFile = (site: string) => path.join(cacheDir, `content-types-${site}.json`); + +beforeAll(async () => { + envBackup = {}; + for (const key of ENV_KEYS) envBackup[key] = process.env[key]; + + cacheDir = await fs.mkdtemp(path.join(os.tmpdir(), 'mcp-wp-cache-test-')); + process.env.UNIFIED_CONTENT_CACHE_DIR = cacheDir; + process.env.WORDPRESS_API_URL = 'https://default.test'; + process.env.WORDPRESS_USERNAME = 'admin'; + process.env.WORDPRESS_PASSWORD = 'pw'; + + const mod = await import('../../src/tools/unified-content.js'); + getContentEndpoint = mod.getContentEndpoint; + discoverContentTypes = (mod.unifiedContentHandlers as any).discover_content_types; +}); + +afterAll(async () => { + for (const key of ENV_KEYS) { + if (envBackup[key] === undefined) delete process.env[key]; + else process.env[key] = envBackup[key]; + } + await fs.remove(cacheDir); +}); + +describe('post types cache is keyed per site', () => { + // The bug this catches: postTypesCache was a single module-level value with + // no site key, checked BEFORE the correctly-keyed disk cache. After any call + // for site A, a call for site B within CACHE_DURATION returned A's post + // types — so discover_content_types listed the wrong site's types, and + // getContentEndpoint resolved custom-type rest_bases from the wrong site + // for every read AND write path that goes through it. + it('does not serve one site\'s post types to another site', async () => { + const before = typesFetchCount(); + + expect(await getContentEndpoint('recipe', 'siteA')).toBe('wprm-recipes'); + // On the unkeyed cache this returned 'wprm-recipes' from siteA's entry + // without ever asking siteB. + expect(await getContentEndpoint('recipe', 'siteB')).toBe('site-b-recipes'); + + expect(requestLog.filter((r) => r.endpoint === 'types').slice(before).map((r) => r.siteId)) + .toEqual(['siteA', 'siteB']); + }); + + it('serves a repeat lookup for the same site from the in-memory map', async () => { + // The bug this catches: a refactor that quietly drops the memory layer + // (every lookup becomes an fs read, or worse a refetch). The disk file is + // deleted between calls, so only the memory map can answer the second one. + expect(await getContentEndpoint('recipe', 'siteC')).toBe('site-c-recipes'); + await fs.remove(diskFile('siteC')); + + const before = typesFetchCount(); + expect(await getContentEndpoint('recipe', 'siteC')).toBe('site-c-recipes'); + expect(typesFetchCount()).toBe(before); + }); + + it('does not resolve a type missing from one site via another site\'s map', async () => { + // siteD knows 'recipe'; siteE does not. With a shared cache, siteE's + // lookup resolved to siteD's rest_base. Per-site it must fall through to + // the documented use-as-is fallback instead. + expect(await getContentEndpoint('recipe', 'siteD')).toBe('site-d-recipes'); + expect(await getContentEndpoint('recipe', 'siteE')).toBe('recipe'); + }); + + it('writes disk cache files under distinct per-site names', async () => { + // The disk cache was already keyed correctly; this pins that the rewiring + // of the memory layer did not regress it. + await getContentEndpoint('recipe', 'siteF'); + await getContentEndpoint('recipe', 'siteG'); + + const files = await fs.readdir(cacheDir); + expect(files).toContain('content-types-siteF.json'); + expect(files).toContain('content-types-siteG.json'); + }); + + it('a valid disk hit warms the in-memory map', async () => { + // The bug this catches: a disk hit that returns without populating the + // memory entry, so every subsequent lookup re-reads the file — and, once + // the file is gone or expired, refetches. The disk value differs from the + // API value so a refetch is visible as data, not just as a count. + await fs.writeJson(diskFile('siteK'), { + data: { recipe: { rest_base: 'site-k-disk' } }, + timestamp: Date.now(), + }); + expect(await getContentEndpoint('recipe', 'siteK')).toBe('site-k-disk'); + + await fs.remove(diskFile('siteK')); + const before = typesFetchCount(); + expect(await getContentEndpoint('recipe', 'siteK')).toBe('site-k-disk'); + expect(typesFetchCount()).toBe(before); + }); + + it('expired disk entries are refetched, not served', async () => { + // The bug this catches: a disk hit ignoring its stored timestamp. The file + // below is valid JSON but a full CACHE_DURATION stale. + await fs.writeJson(diskFile('siteH'), { + data: { recipe: { rest_base: 'site-h-stale' } }, + timestamp: Date.now() - 3600000 - 60000, + }); + + expect(await getContentEndpoint('recipe', 'siteH')).toBe('site-h-live'); + }); + + it('a disk hit keeps the disk timestamp, so the memory entry expires on schedule', async () => { + // The bug this catches: stamping the memory entry with `now` when warming + // it from disk, which would renew the TTL on every disk hit and make an + // old entry immortal in memory. + vi.useFakeTimers({ toFake: ['Date'] }); + try { + const t0 = Date.now(); + // 59 minutes old: valid for one more minute. + await fs.writeJson(diskFile('siteJ'), { + data: { recipe: { rest_base: 'site-j-stale' } }, + timestamp: t0 - 59 * 60000, + }); + expect(await getContentEndpoint('recipe', 'siteJ')).toBe('site-j-stale'); + + // Two minutes later both the disk file and the memory entry warmed from + // it are past the 1h TTL — the next lookup must hit the API. + vi.setSystemTime(t0 + 2 * 60000); + expect(await getContentEndpoint('recipe', 'siteJ')).toBe('site-j-live'); + } finally { + vi.useRealTimers(); + } + }); +}); + +describe('the default site occupies a single cache slot', () => { + // The bug these catch: keying on the raw parameter (`siteId || sentinel`) + // gives the default site TWO slots — one for calls that omit site_id and one + // for calls that pass its actual id ('default' in the legacy single-site + // config). A forced refresh through one shape then leaves the other stale + // for up to CACHE_DURATION. + it('omitted site_id and the explicit default id share one memory slot', async () => { + // Asserts consistency rather than a fixed value so it holds in any order + // relative to the refresh test below, which changes the default site's data. + const viaOmitted = await getContentEndpoint('recipe'); // no siteId → default site + await fs.remove(diskFile('default')); + + const before = typesFetchCount(); + expect(await getContentEndpoint('recipe', 'default')).toBe(viaOmitted); + expect(typesFetchCount()).toBe(before); + }); + + it('refresh_cache with no site_id also refreshes what the explicit id reads', async () => { + await getContentEndpoint('recipe'); // warm the slot + SITE_TYPES.__default__ = { recipe: { rest_base: 'default-site-recipes-v2' } }; + + const result = await discoverContentTypes({ refresh_cache: true }); + expect(JSON.stringify(result)).toContain('default-site-recipes-v2'); + + // Memory must answer with the refreshed data for the explicit-id shape too. + await fs.remove(diskFile('default')); + expect(await getContentEndpoint('recipe', 'default')).toBe('default-site-recipes-v2'); + }); +}); diff --git a/tests/tools/site-id-routing.test.ts b/tests/tools/site-id-routing.test.ts new file mode 100644 index 0000000..a117238 --- /dev/null +++ b/tests/tools/site-id-routing.test.ts @@ -0,0 +1,108 @@ +import { describe, it, expect, vi, beforeAll } from 'vitest'; + +// Records every request so each test can assert three things: the call carried +// { siteId } in its options exactly when site_id was supplied, site_id never +// leaked into the query/body sent to WordPress, and the payload is otherwise +// IDENTICAL to what the handler sent before site_id existed. +const calls: Array<{ method: string; endpoint: string; data: any; options: any }> = []; + +vi.mock('../../src/wordpress.js', () => ({ + makeWordPressRequest: vi.fn(async (method: string, endpoint: string, data?: any, options?: any) => { + calls.push({ method, endpoint, data, options }); + return { id: 1 }; + }), + logToFile: vi.fn(), +})); + +let pluginTools: any[], commentTools: any[], userTools: any[]; +let handlers: Record Promise>; + +beforeAll(async () => { + const plugins = await import('../../src/tools/plugins.js'); + const comments = await import('../../src/tools/comments.js'); + const users = await import('../../src/tools/users.js'); + pluginTools = plugins.pluginTools; + commentTools = comments.commentTools; + userTools = users.userTools; + handlers = { + ...(plugins.pluginHandlers as any), + ...(comments.commentHandlers as any), + ...(users.userHandlers as any), + }; +}); + +// For every handler: the minimal input beyond site_id, and the exact payload +// the pre-site_id implementation sent for that input. `undefined` means the +// handler passes no data argument at all. +const CASES: Record = { + list_plugins: { params: {}, expectData: {} }, + get_plugin: { params: { plugin: 'akismet' }, expectData: undefined }, + activate_plugin: { params: { plugin: 'akismet' }, expectData: { plugin: 'akismet' } }, + deactivate_plugin: { params: { plugin: 'akismet' }, expectData: { plugin: 'akismet' } }, + create_plugin: { params: { slug: 'akismet', status: 'active' }, expectData: { slug: 'akismet', status: 'active' } }, + list_comments: { params: { post: 5 }, expectData: { post: 5 } }, + get_comment: { params: { id: 7 }, expectData: undefined }, + create_comment: { params: { post: 5, content: 'hi' }, expectData: { post: 5, content: 'hi' } }, + update_comment: { params: { id: 7, content: 'edited' }, expectData: { content: 'edited' } }, + delete_comment: { params: { id: 7, force: true }, expectData: { force: true } }, + list_users: { params: { search: 'jon' }, expectData: { search: 'jon' } }, + get_user: { params: { id: 3, context: 'edit' }, expectData: { context: 'edit' } }, + create_user: { + params: { username: 'u', email: 'u@example.test', password: 'pw' }, + expectData: { username: 'u', email: 'u@example.test', password: 'pw' }, + }, + update_user: { params: { id: 3, name: 'New Name' }, expectData: { name: 'New Name' } }, + delete_user: { params: { id: 3, force: true, reassign: 1 }, expectData: { force: true, reassign: 1 } }, +}; + +async function invoke(name: string, params: any) { + const before = calls.length; + const result = await handlers[name](params); + expect(result?.toolResult?.isError, `${name} errored: ${JSON.stringify(result)}`).not.toBe(true); + expect(calls.length, `${name} made no request`).toBe(before + 1); + return calls[calls.length - 1]; +} + +// The bug this file catches: the fifteen plugin/comment/user tools accepted no +// site_id at all. The MCP SDK wraps each tool's zod shape in a plain (non- +// strict) z.object, so a supplied site_id was SILENTLY STRIPPED before the +// handler ran — the call went to the default site with no error, which is +// worse than a rejection. In a multi-site config there was no way to reach a +// secondary site's plugins, comments, or users. +describe('site_id routing', () => { + for (const [name, { params, expectData }] of Object.entries(CASES)) { + it(`${name} routes site_id to { siteId } and keeps it out of the payload`, async () => { + // Per-handler site id, so cross-wired or hardcoded routing can't pass. + const siteId = `site-${name}`; + const call = await invoke(name, { ...params, site_id: siteId }); + + expect(call.options?.siteId).toBe(siteId); + expect(call.data).toEqual(expectData); + if (call.data && typeof call.data === 'object') { + expect(call.data).not.toHaveProperty('site_id'); + } + }); + + it(`${name} without site_id sends the exact pre-change payload to the default site`, async () => { + // Guards existing callers: same data argument as before this feature, + // and no siteId option, so the default-site client is selected. + const call = await invoke(name, { ...params }); + + expect(call.options?.siteId).toBeUndefined(); + expect(call.data).toEqual(expectData); + }); + } + + it('every plugin, comment, and user tool declares site_id in its input schema', () => { + // Guards the schema half: the SDK builds its validator from + // inputSchema.properties, and a property missing there is stripped before + // the handler ever sees it — the silent default-site misroute again. + for (const tool of [...pluginTools, ...commentTools, ...userTools]) { + expect(tool.inputSchema?.properties, `inputSchema.properties for ${tool.name}`).toBeDefined(); + expect( + Object.keys(tool.inputSchema.properties), + `site_id missing from ${tool.name}` + ).toContain('site_id'); + } + }); +}); diff --git a/tests/tools/term-write-verification.test.ts b/tests/tools/term-write-verification.test.ts new file mode 100644 index 0000000..0d109d5 --- /dev/null +++ b/tests/tools/term-write-verification.test.ts @@ -0,0 +1,202 @@ +import { describe, it, expect, vi, beforeAll } from 'vitest'; + +// Simulates WordPress's real behaviour for term writes: wp_set_object_terms() +// silently skips term IDs that do not exist, and the REST response echoes only +// the survivors with a 200. VALID_TERMS is the set the fake site knows. +const VALID_TERMS = new Set([1, 2, 10, 11]); + +vi.mock('../../src/wordpress.js', () => ({ + makeWordPressRequest: vi.fn(async (method: string, endpoint: string, data?: any) => { + if (method === 'POST') { + const echo: any = { id: 42, ...data }; + for (const field of ['categories', 'tags']) { + if (data && field in data) { + const ids = Array.isArray(data[field]) ? data[field] : [data[field]]; + echo[field] = ids.filter((id: number) => VALID_TERMS.has(id)); + } + } + if (data?.meta?.omit_term_fields) { + // Simulates a content type whose REST response has no such field. + delete echo.categories; + delete echo.tags; + } + return echo; + } + return {}; + }), + logToFile: vi.fn(), +})); + +let updateContent: (params: any) => Promise; +let createContent: (params: any) => Promise; + +beforeAll(async () => { + const mod = await import('../../src/tools/unified-content.js'); + updateContent = (mod.unifiedContentHandlers as any).update_content; + createContent = (mod.unifiedContentHandlers as any).create_content; +}); + +function blocksOf(result: any): Array<{ type: string; text: string }> { + expect(result?.toolResult?.isError).not.toBe(true); + return result.toolResult.content; +} + +// The bug this file catches: update_content (and create_content) returned an +// unqualified success when WordPress silently dropped nonexistent term IDs — +// e.g. 6 tag IDs sent, 1 valid, HTTP 200, only the 1 saved, no indication of +// the other 5. assign_terms_to_content already derives success from the +// response; these handlers did not. A silent partial write is +// indistinguishable from success without this warning. +describe('update_content term verification', () => { + it('warns and names the exact IDs WordPress dropped', async () => { + const result = await updateContent({ + content_type: 'post', + id: 42, + tags: [1, 2, 3, 4, 5, 6], + }); + + const blocks = blocksOf(result); + expect(blocks.length).toBe(2); + expect(blocks[0].text).toContain('silently dropped'); + expect(blocks[0].text).toContain('[3, 4, 5, 6]'); + expect(blocks[0].text).toContain('saved tags [1, 2]'); + }); + + it('stays a plain success when every term ID exists', async () => { + const result = await updateContent({ + content_type: 'post', + id: 42, + tags: [1, 2], + categories: [10, 11], + }); + + const blocks = blocksOf(result); + expect(blocks.length).toBe(1); + expect(blocks[0].text).not.toContain('Warning'); + }); + + it('reports categories and tags independently', async () => { + const result = await updateContent({ + content_type: 'post', + id: 42, + tags: [1], + categories: [10, 99], + }); + + const blocks = blocksOf(result); + expect(blocks.length).toBe(2); + expect(blocks[0].text).toContain('categories'); + expect(blocks[0].text).toContain('[99]'); + expect(blocks[0].text).not.toContain('dropped [1]'); + }); + + it('names dropped IDs in BOTH fields when both drop', async () => { + // Kills the mutant that reports only the first dropped field: a write + // dropping IDs in categories AND tags must name both, or the second + // field's loss is exactly the silent partial write this feature exists + // to surface. + const result = await updateContent({ + content_type: 'post', + id: 42, + tags: [1, 3], + categories: [10, 99], + }); + + const blocks = blocksOf(result); + expect(blocks.length).toBe(2); + expect(blocks[0].text).toContain('categories [10] but silently dropped [99]'); + expect(blocks[0].text).toContain('tags [1] but silently dropped [3]'); + }); + + it('normalizes a bare number defensively (not reachable through the tool schema)', async () => { + const result = await updateContent({ + content_type: 'post', + id: 42, + tags: 999, + }); + + const blocks = blocksOf(result); + expect(blocks.length).toBe(2); + expect(blocks[0].text).toContain('[999]'); + }); + + it('clearing terms with an empty array is not a dropped write', async () => { + // Pins external behaviour only: an empty request has no IDs to go + // missing, so no code path should ever warn on a clear. + const result = await updateContent({ + content_type: 'post', + id: 42, + tags: [], + }); + + expect(blocksOf(result).length).toBe(1); + }); + + it('term IDs smuggled in via custom_fields are verified too', async () => { + // custom_fields is spread into the request payload, so tags sent that way + // reach WordPress and can be dropped just the same. Detection reads the + // assembled payload, not the top-level params. + const result = await updateContent({ + content_type: 'post', + id: 42, + custom_fields: { tags: [1, 500] }, + }); + + const blocks = blocksOf(result); + expect(blocks.length).toBe(2); + expect(blocks[0].text).toContain('[500]'); + }); + + it('warns when the response carries no term field at all', async () => { + // A content type without the taxonomy: WordPress ignores the field + // entirely, so nothing at all can be confirmed. + const result = await updateContent({ + content_type: 'post', + id: 42, + tags: [1, 2], + meta: { omit_term_fields: true }, + }); + + const blocks = blocksOf(result); + expect(blocks.length).toBe(2); + expect(blocks[0].text).toContain('no "tags" field'); + expect(blocks[0].text).toContain('[1, 2]'); + }); + + it('does not warn about term fields the caller never sent', async () => { + const result = await updateContent({ + content_type: 'post', + id: 42, + title: 'Only a title', + }); + + expect(blocksOf(result).length).toBe(1); + }); +}); + +describe('create_content term verification', () => { + it('warns on create too, not only on update', async () => { + const result = await createContent({ + content_type: 'post', + title: 'New post', + content: 'Body', + tags: [1, 7], + }); + + const blocks = blocksOf(result); + expect(blocks.length).toBe(2); + expect(blocks[0].text).toContain('[7]'); + }); + + it('is silent on create when the IDs are valid', async () => { + const result = await createContent({ + content_type: 'post', + title: 'New post', + content: 'Body', + tags: [1], + categories: [10], + }); + + expect(blocksOf(result).length).toBe(1); + }); +});