From 2e358a2d6599288bfce8f1287b4f738350e72122 Mon Sep 17 00:00:00 2001 From: Jon Klein Date: Tue, 1 Sep 2026 12:54:32 -0400 Subject: [PATCH 01/11] fix(unified-content): key the in-memory post types cache by site MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The disk cache for /wp/v2/types was already keyed per site (content-types-.json), but the in-memory cache in front of it was a single module-level value with no site key — and it is checked first. After any call for site A, every call for any other site within CACHE_DURATION (default 1h) returned A's post types. Observed as discover_content_types returning the wrong site's types on a cold start, but the exposure is wider: getContentEndpoint() resolves custom post types' rest_base through this cache for every read and write path (create/update/delete content, assign_terms_to_content, get_content_terms, content summaries), and find_content_by_url enumerates the cached type list to search. With a poisoned cache those resolve against the wrong site's type map — a type missing from it falls back to the raw slug (404s), a slug present on both sites with a different rest_base resolves to the wrong endpoint path, and URL lookups can report "not found" for content that exists. Built-in post/page are unaffected (short-circuited before the cache). Fix mirrors the per-site Map pattern unified-taxonomies.ts already uses for its taxonomies cache. Disk cache behaviour and key names are unchanged; a disk hit now populates the per-site entry instead of a shared singleton. Regression test drives getContentEndpoint through the mocked transport with two sites whose shared custom type slug carries different rest_bases: verified failing (3/4) against the previous implementation and passing with this one. Co-Authored-By: Claude --- src/tools/unified-content.ts | 25 +++++--- tests/tools/post-types-cache.test.ts | 95 ++++++++++++++++++++++++++++ 2 files changed, 111 insertions(+), 9 deletions(-) create mode 100644 tests/tools/post-types-cache.test.ts diff --git a/src/tools/unified-content.ts b/src/tools/unified-content.ts index 1f133be..9165780 100644 --- a/src/tools/unified-content.ts +++ b/src/tools/unified-content.ts @@ -16,9 +16,16 @@ 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 // Helper function to load cache from disk @@ -57,11 +64,13 @@ 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 = siteId || '__default__'; // 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 @@ -69,8 +78,7 @@ async function getPostTypes(forceRefresh = false, siteId?: string) { const diskCache = await loadCacheFromDisk(siteId); 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,8 +87,7 @@ 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); diff --git a/tests/tools/post-types-cache.test.ts b/tests/tools/post-types-cache.test.ts new file mode 100644 index 0000000..331f0bc --- /dev/null +++ b/tests/tools/post-types-cache.test.ts @@ -0,0 +1,95 @@ +import { describe, it, expect, vi, beforeAll } 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. The same custom type +// slug deliberately carries a different rest_base on each site — that is the +// collision that made the unkeyed cache dangerous rather than merely stale. +const SITE_TYPES: Record = { + siteA: { + post: { rest_base: 'posts' }, + recipe: { rest_base: 'wprm-recipes' }, + feast_layout: { rest_base: 'feast-layouts' }, + }, + siteB: { + post: { rest_base: 'posts' }, + recipe: { rest_base: 'site-b-recipes' }, + mih_guide: { rest_base: 'mih-guides' }, + }, +}; + +const requestLog: Array<{ endpoint: string; siteId?: string }> = []; + +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. +let getContentEndpoint: (contentType: string, siteId?: string) => Promise; +let cacheDir: string; + +beforeAll(async () => { + cacheDir = await fs.mkdtemp(path.join(os.tmpdir(), 'mcp-wp-cache-test-')); + process.env.UNIFIED_CONTENT_CACHE_DIR = cacheDir; + ({ getContentEndpoint } = await import('../../src/tools/unified-content.js')); +}); + +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 a = await getContentEndpoint('recipe', 'siteA'); + expect(a).toBe('wprm-recipes'); + + // On the unkeyed cache this returned 'wprm-recipes' from siteA's entry + // without ever asking siteB. + const b = await getContentEndpoint('recipe', 'siteB'); + expect(b).toBe('site-b-recipes'); + + const typesCalls = requestLog.filter((r) => r.endpoint === 'types'); + expect(typesCalls.map((r) => r.siteId)).toEqual(['siteA', 'siteB']); + }); + + it('still serves repeat lookups for the same site from cache', async () => { + const before = requestLog.filter((r) => r.endpoint === 'types').length; + + // feast_layout exists only on siteA; a cache hit must resolve it without + // another network fetch. + const a = await getContentEndpoint('feast_layout', 'siteA'); + expect(a).toBe('feast-layouts'); + + const after = requestLog.filter((r) => r.endpoint === 'types').length; + expect(after).toBe(before); + }); + + it('falls through per site: a type unknown to that site is not resolved from another site\'s map', async () => { + // mih_guide exists only on siteB. With the unkeyed cache holding siteA's + // map, this returned the raw slug via the "use as-is" fallback — or worse, + // a collision resolved to siteA's rest_base. Per-site it must resolve from + // siteB's own map. + const b = await getContentEndpoint('mih_guide', 'siteB'); + expect(b).toBe('mih-guides'); + }); + + it('writes disk cache files under distinct per-site names', async () => { + // The disk cache was already keyed correctly; this pins that the fix did + // not regress it while rewiring the memory layer that shadowed it. + const files = (await fs.readdir(cacheDir)).sort(); + expect(files).toContain('content-types-siteA.json'); + expect(files).toContain('content-types-siteB.json'); + }); +}); From 0e7738da4e3aad210ff548486a108b62faac7d83 Mon Sep 17 00:00:00 2001 From: Jon Klein Date: Tue, 1 Sep 2026 13:03:50 -0400 Subject: [PATCH 02/11] fix(unified-content): resolve the default site to one cache slot; pin the cache in tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adversarial review of the previous commit (2 fresh reviewers) found: - The per-site keying gave the default site TWO memory slots: one for calls omitting site_id, one for calls passing its actual id ('default' in the legacy single-site config). A refresh_cache through one shape left the other stale for up to CACHE_DURATION. Reproduced against the previous commit; the shape-coherence tests here fail on it (2/9). - In a multi-site config whose default site is not named 'default' while another site explicitly is, both wrote content-types-default.json — a disk-level bleed the memory fix alone did not cover. - The test suite did not pin the in-memory layer at all: deleting the entire Map (never read, never populated) left the whole suite green, because the disk cache satisfied every assertion. Several TTL and refresh behaviours were similarly unpinned, and two tests were order-dependent under --sequence.shuffle. Both cache layers now key on resolveCacheSiteId(): the explicit siteId, else the configured default site's real id (sentinel '__default__' only when nothing is configured). unified-taxonomies.ts had the identical two-shapes split in its per-site cache and now uses the same resolver. Disk file names change for a non-'default' default site (one-time cache miss, then refetch). Tests rewritten to be self-contained per test (own site ids, delta-based request counting): green under --sequence.shuffle and per-test -t runs, and each test kills a named mutation — cross-site keying, memory-layer removal (set/get/fetch-populate separately), disk-warm population, disk-timestamp expiry (fake Date), refresh coherence across call shapes, and default-slot sharing. Verified: 7/9 fail against origin/main, 2/9 fail against the previous commit, 0 mutations from the review survive. Temp dirs and env vars are now restored in afterAll. Co-Authored-By: Claude --- src/tools/unified-content.ts | 29 +++- src/tools/unified-taxonomies.ts | 4 +- tests/tools/post-types-cache.test.ts | 205 ++++++++++++++++++++++----- 3 files changed, 199 insertions(+), 39 deletions(-) diff --git a/src/tools/unified-content.ts b/src/tools/unified-content.ts index 9165780..b7ad110 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 { siteManager } from '../config/site-manager.js'; import { z } from 'zod'; import * as fs from 'fs-extra'; import * as path from 'path'; @@ -28,6 +29,28 @@ interface PostTypesCacheEntry { 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 { @@ -64,7 +87,7 @@ 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 = siteId || '__default__'; + const cacheKey = resolveCacheSiteId(siteId); // Try memory cache first const cached = postTypesCache.get(cacheKey); @@ -75,7 +98,7 @@ async function getPostTypes(forceRefresh = false, siteId?: string) { // 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.set(cacheKey, { data: diskCache.data, timestamp: diskCache.timestamp }); @@ -90,7 +113,7 @@ async function getPostTypes(forceRefresh = false, siteId?: string) { 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) { 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/tests/tools/post-types-cache.test.ts b/tests/tools/post-types-cache.test.ts index 331f0bc..c082b4b 100644 --- a/tests/tools/post-types-cache.test.ts +++ b/tests/tools/post-types-cache.test.ts @@ -1,25 +1,55 @@ -import { describe, it, expect, vi, beforeAll } from 'vitest'; +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. The same custom type -// slug deliberately carries a different rest_base on each site — that is the -// collision that made the unkeyed cache dangerous rather than merely stale. +// 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' }, - feast_layout: { rest_base: 'feast-layouts' }, }, 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 }) => { @@ -34,14 +64,39 @@ vi.mock('../../src/wordpress.js', () => ({ // 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. +// 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; - ({ getContentEndpoint } = await import('../../src/tools/unified-content.js')); + 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', () => { @@ -52,44 +107,126 @@ describe('post types cache is keyed per site', () => { // 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 a = await getContentEndpoint('recipe', 'siteA'); - expect(a).toBe('wprm-recipes'); + 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. - const b = await getContentEndpoint('recipe', 'siteB'); - expect(b).toBe('site-b-recipes'); + expect(await getContentEndpoint('recipe', 'siteB')).toBe('site-b-recipes'); - const typesCalls = requestLog.filter((r) => r.endpoint === 'types'); - expect(typesCalls.map((r) => r.siteId)).toEqual(['siteA', 'siteB']); + expect(requestLog.filter((r) => r.endpoint === 'types').slice(before).map((r) => r.siteId)) + .toEqual(['siteA', 'siteB']); }); - it('still serves repeat lookups for the same site from cache', async () => { - const before = requestLog.filter((r) => r.endpoint === 'types').length; - - // feast_layout exists only on siteA; a cache hit must resolve it without - // another network fetch. - const a = await getContentEndpoint('feast_layout', 'siteA'); - expect(a).toBe('feast-layouts'); + 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 after = requestLog.filter((r) => r.endpoint === 'types').length; - expect(after).toBe(before); + const before = typesFetchCount(); + expect(await getContentEndpoint('recipe', 'siteC')).toBe('site-c-recipes'); + expect(typesFetchCount()).toBe(before); }); - it('falls through per site: a type unknown to that site is not resolved from another site\'s map', async () => { - // mih_guide exists only on siteB. With the unkeyed cache holding siteA's - // map, this returned the raw slug via the "use as-is" fallback — or worse, - // a collision resolved to siteA's rest_base. Per-site it must resolve from - // siteB's own map. - const b = await getContentEndpoint('mih_guide', 'siteB'); - expect(b).toBe('mih-guides'); + 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 fix did - // not regress it while rewiring the memory layer that shadowed it. - const files = (await fs.readdir(cacheDir)).sort(); - expect(files).toContain('content-types-siteA.json'); - expect(files).toContain('content-types-siteB.json'); + // 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'); }); }); From 4245d8ea96da08ac9ff44d94e64971e53a9c9891 Mon Sep 17 00:00:00 2001 From: Jon Klein Date: Tue, 1 Sep 2026 14:10:31 -0400 Subject: [PATCH 03/11] fix(unified-content): emit an explicit level for every converted heading MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit convertHtmlToBlocks() emitted for h1 and h3-h6, but a bare for h2. Bare-for-h2 matches Gutenberg's own canonical serialization (default attributes are omitted), but a converter with one implicit case among six explicit ones produces inconsistent output across heading levels — and when existing content whose blocks carried an explicit {"level":2} was round-tripped through convert_to_blocks, the attribute vanished, which was reported from the field as "the level got stripped off every heading block". All six heading tags now share one case that emits the level explicitly; an explicit default attribute is valid for the block parser. Content already in block format is untouched (pass-through happens before the converter), covered by a test. Tests drive create_content with convert_to_blocks through the mocked transport and inspect the written content: 3/4 fail against the previous implementation. Co-Authored-By: Claude --- src/tools/unified-content.ts | 19 ++--- tests/tools/html-to-blocks-headings.test.ts | 82 +++++++++++++++++++++ 2 files changed, 90 insertions(+), 11 deletions(-) create mode 100644 tests/tools/html-to-blocks-headings.test.ts diff --git a/src/tools/unified-content.ts b/src/tools/unified-content.ts index 1f133be..c19496e 100644 --- a/src/tools/unified-content.ts +++ b/src/tools/unified-content.ts @@ -373,22 +373,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`); 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..5587f3b --- /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('{"level":2}'); + 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); + }); +}); From 6cd52a746627f754066b044013db4ba8a49e94c2 Mon Sep 17 00:00:00 2001 From: Jon Klein Date: Tue, 1 Sep 2026 14:14:33 -0400 Subject: [PATCH 04/11] test: assert the full heading comment on the markdown route Review nit: the bare '{"level":2}' substring could pass via some other block type; use the file's stronger exact-comment idiom. Co-Authored-By: Claude --- tests/tools/html-to-blocks-headings.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/tools/html-to-blocks-headings.test.ts b/tests/tools/html-to-blocks-headings.test.ts index 5587f3b..d06cc7d 100644 --- a/tests/tools/html-to-blocks-headings.test.ts +++ b/tests/tools/html-to-blocks-headings.test.ts @@ -66,7 +66,7 @@ describe('convertHtmlToBlocks heading levels', () => { content_format: 'markdown', }); - expect(blocks).toContain('{"level":2}'); + expect(blocks).toContain(''); expect(blocks).not.toMatch(//); }); From d06ec68e79937a1d502cae6d03e55c3e886bc5ef Mon Sep 17 00:00:00 2001 From: Jon Klein Date: Tue, 1 Sep 2026 14:13:03 -0400 Subject: [PATCH 05/11] feat(plugins,comments,users): accept site_id so multi-site configs can target any site MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The plugin, comment, and user tools were the only WordPress-hitting tools without a site_id parameter. The MCP SDK builds its validator from each tool's inputSchema.properties as a plain (non-strict) z.object, so a supplied site_id was SILENTLY STRIPPED before the handler ran and the call went to the default site with no error — in a multi-site configuration there was no way to inspect or moderate a secondary site's plugins, comments, or users, and no signal that the wrong site had answered. The README's multi-site section already promises "all tools accept an optional site_id parameter". Each of the fifteen schemas now declares the same optional site_id used by the other tool groups, and each handler threads it through as the request's { siteId } option, excluding it from the query/body sent to WordPress (handlers passed `params` straight through as the payload, so site_id would otherwise have leaked into the REST request). With site_id omitted, every handler's payload is byte-identical to before — verified by capturing all fifteen call shapes on both revisions and diffing. README's tool-overview line now names all six groups. Tests cover all fifteen handlers through the mocked transport, each with a per-handler site id (so cross-wired or hardcoded routing cannot pass), asserting: siteId lands in the request options; the payload deep-equals the exact pre-change payload both with and without site_id; site_id never appears in the payload; and every tool's input schema declares site_id (a property missing from the schema is stripped by the SDK before the handler sees it). Co-Authored-By: Claude --- README.md | 2 +- src/tools/comments.ts | 19 +++-- src/tools/plugins.ts | 19 +++-- src/tools/users.ts | 19 +++-- tests/tools/site-id-routing.test.ts | 108 ++++++++++++++++++++++++++++ 5 files changed, 149 insertions(+), 18 deletions(-) create mode 100644 tests/tools/site-id-routing.test.ts diff --git a/README.md b/README.md index e67496e..6037fa9 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ 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) 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/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/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'); + } + }); +}); From f017798f146bf72cb7fa920e501ea2c02ee35a72 Mon Sep 17 00:00:00 2001 From: Jon Klein Date: Tue, 1 Sep 2026 14:17:05 -0400 Subject: [PATCH 06/11] fix(unified-content): surface term IDs WordPress silently drops on create/update MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Sending nonexistent term IDs through update_content or create_content returned an unqualified success: wp_set_object_terms() skips integer IDs that do not exist ("Skip if a non-existent term ID is passed."), /wp/v2 responds 200 with only the survivors, and the handlers never looked. Observed in the field as 6 tag IDs sent, 5 nonexistent, success reported, 1 saved — a silent partial write indistinguishable from success. detectDroppedTerms() compares the categories/tags in the ASSEMBLED request payload (params alone would miss term fields smuggled in via custom_fields, which spreads into the body) against what the response reports as saved. The handlers prepend a warning block naming the exact dropped IDs — or, when the response has no such field at all (a content type without the taxonomy), saying nothing could be confirmed and pointing at assign_terms_to_content's rest_base resolution. Detection mirrors the response-derived check assign_terms_to_content already does; severity deliberately does NOT. That tool writes nothing but terms, so a dropped term is a failed call (isError: true, and the README documents that guarantee). create/update also wrote title/content/meta, which DID land — erroring would misreport them — so this follows the dropped-meta-keys warning precedent instead: a loud warning block ahead of the successful result. README updated to state both behaviours side by side. find_content_by_url's update_fields shape has no categories/tags (and the SDK's non-strict schema strips unknown keys), so there is nothing to verify on that path. Tests simulate core's skip-the-unknown-IDs behaviour: exact dropped IDs named, per-field independence AND the both-fields-drop message, the custom_fields route, absent-field responses, empty-array clears not flagged, defensive bare-number normalization (unreachable through the tool schema, which is arrays-only), and no warning when all IDs are valid. The warning-path tests fail against the previous implementation; the no-warning tests guard against over-warning. Co-Authored-By: Claude --- README.md | 4 + src/tools/unified-content.ts | 67 +++++++ tests/tools/term-write-verification.test.ts | 202 ++++++++++++++++++++ 3 files changed, 273 insertions(+) create mode 100644 tests/tools/term-write-verification.test.ts diff --git a/README.md b/README.md index e67496e..3d7a838 100644 --- a/README.md +++ b/README.md @@ -266,6 +266,10 @@ 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) diff --git a/src/tools/unified-content.ts b/src/tools/unified-content.ts index 1f133be..faba78f 100644 --- a/src/tools/unified-content.ts +++ b/src/tools/unified-content.ts @@ -518,6 +518,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']); @@ -1051,6 +1106,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 +1150,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/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); + }); +}); From f41dd0eaade60a8de8e186f70da9e1765c867ac0 Mon Sep 17 00:00:00 2001 From: Jon Klein Date: Sun, 6 Sep 2026 12:46:41 -0400 Subject: [PATCH 07/11] Add field selection to list_content MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit list_content returns every field of every item, including fully rendered content. On post types that carry long bodies that is overwhelmingly more than the caller usually wants: listing four neighbourhood guides on a real site returned 90KB of HTML for a request that needed three metadata keys, which is large enough to exceed an MCP client's output limit and fail the call outright. WordPress already solves this with the global _fields parameter. This exposes it as a `fields` array on list_content and maps it explicitly. The mapping has to be explicit. The handler spreads its remaining params into the query string, and WordPress ignores query args it doesn't recognise — so passing `fields` under its own name would return the complete payload while appearing to succeed. That failure is invisible at the call site, which is what the regression test pins. Default behaviour is unchanged: no `fields`, no `_fields`, full payload. An empty selection is rejected by the schema rather than sent, since WordPress reads an empty _fields as a request for no fields at all. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_0119LiiVk2S5wFVRT6ytEyha --- README.md | 27 ++++++- src/tools/unified-content.ts | 24 +++++-- tests/tools/list-content-fields.test.ts | 93 +++++++++++++++++++++++++ 3 files changed, 139 insertions(+), 5 deletions(-) create mode 100644 tests/tools/list-content-fields.test.ts diff --git a/README.md b/README.md index 34087f8..87ea338 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ All content, taxonomy, media, plugin, comment, and user tools support an optiona 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 @@ -275,6 +275,31 @@ error, naming the exact term IDs WordPress silently dropped. 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` returns every field of every item 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"] } +``` + +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. + +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"]` | + +Omit `fields` to get the full payload, which is the previous behaviour. + **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/unified-content.ts b/src/tools/unified-content.ts index f347cd4..2d828d4 100644 --- a/src/tools/unified-content.ts +++ b/src/tools/unified-content.ts @@ -795,7 +795,15 @@ 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().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." + ) }); const getContentSchema = z.object({ @@ -964,7 +972,7 @@ 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, 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 } }, { @@ -1015,9 +1023,17 @@ 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 }; + if (fields?.length) { + requestParams._fields = fields.join(','); + } - const response = await makeWordPressRequest('GET', endpoint, queryParams, { siteId: site_id }); + const response = await makeWordPressRequest('GET', endpoint, requestParams, { siteId: site_id }); return { toolResult: { diff --git a/tests/tools/list-content-fields.test.ts b/tests/tools/list-content-fields.test.ts new file mode 100644 index 0000000..5fdb999 --- /dev/null +++ b/tests/tools/list-content-fields.test.ts @@ -0,0 +1,93 @@ +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(), +})); + +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 treats an empty _fields as a + // request for no fields, so every item would come back stripped. + 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'); + }); +}); From 30408377b05b4ba11b766e82c1439ba6ef5ab5ec Mon Sep 17 00:00:00 2001 From: Jon Klein Date: Sun, 6 Sep 2026 12:53:25 -0400 Subject: [PATCH 08/11] Address review: stripped-field conflict, trimmed entries, honest docs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Findings from the adversarial review round. Should-fix — a selection naming only stripped fields returned nothing. Every response passes through trimResponseFields, which deletes yoast_head and yoast_head_json (or whatever MCP_WP_STRIP_FIELDS names) after WordPress returns them. So `fields: ["yoast_head"]` came back as one empty object per item with isError false — indistinguishable from "this site has no Yoast data", with nothing pointing at the cause. It now errors and names the variable. A partial overlap still succeeds and logs a note, since the rest of the selection is still worth returning. Should-fix — the earlier justification for rejecting an empty selection was factually wrong. WordPress parses _fields with wp_parse_list and ignores an empty one, returning the FULL payload; it does not return "no fields". Verified against a live site: `_fields=` and no _fields at all produce byte-identical responses. The schema behaviour is unchanged and still correct — an empty array is a caller mistake that would silently return the payload they were trying to avoid — but the comment now says why truthfully. Nit — whitespace-only entries passed validation, so `fields: [" "]` sent `_fields=" "`. Now z.string().trim().min(1), which also trims padding. Nit — "returns every field by default" was untrue given MCP_WP_STRIP_FIELDS. Reworded in both the tool description and the README. Nit — a selection drops the _links block unless named, and a selection whose names are all wrong returns empty objects rather than an error. Both are WordPress behaviours, both verified live, both now documented. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_0119LiiVk2S5wFVRT6ytEyha --- README.md | 15 +++++++- src/tools/unified-content.ts | 29 +++++++++++++--- tests/tools/list-content-fields.test.ts | 46 +++++++++++++++++++++++-- 3 files changed, 83 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 87ea338..adc069f 100644 --- a/README.md +++ b/README.md @@ -290,6 +290,14 @@ This maps to WordPress's own [`_fields`](https://developer.wordpress.org/rest-ap 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` | @@ -298,7 +306,12 @@ Useful selections: | Build an index or a link list | `["id", "title", "link"]` | | Check publication state | `["id", "status", "modified"]` | -Omit `fields` to get the full payload, which is the previous behaviour. +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. diff --git a/src/tools/unified-content.ts b/src/tools/unified-content.ts index 2d828d4..d2a7f41 100644 --- a/src/tools/unified-content.ts +++ b/src/tools/unified-content.ts @@ -1,6 +1,6 @@ // 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'; @@ -796,13 +796,14 @@ const listContentSchema = z.object({ 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"), - fields: z.array(z.string().min(1)).nonempty().optional().describe( + 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." + "not have are simply absent from the response. Note that a selection also drops " + + "the `_links` block unless you name it." ) }); @@ -972,7 +973,7 @@ 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. Returns every field of every item by default, including fully rendered content — pass `fields` to select only what you need (e.g. ['id','slug','meta']), which is dramatically cheaper on large posts.", + 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 } }, { @@ -1030,6 +1031,26 @@ export const unifiedContentHandlers = { // the full payload instead of erroring. Map it explicitly. const requestParams: Record = { ...queryParams }; if (fields?.length) { + // Every response is run through trimResponseFields, so a field named + // there is deleted after WordPress returns it. Asking for one would + // otherwise come back as an empty object per item with isError false — + // indistinguishable from "the site has no such data". + 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( + `list_content: requested field(s) ${conflicting.join(', ')} are removed by ` + + `MCP_WP_STRIP_FIELDS and will be absent from the result.`, + 'info' + ); + } requestParams._fields = fields.join(','); } diff --git a/tests/tools/list-content-fields.test.ts b/tests/tools/list-content-fields.test.ts index 5fdb999..b24c65c 100644 --- a/tests/tools/list-content-fields.test.ts +++ b/tests/tools/list-content-fields.test.ts @@ -13,6 +13,10 @@ vi.mock('../../src/wordpress.js', () => ({ 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; @@ -48,8 +52,11 @@ describe('list_content field selection', () => { }); // The bug this catches: sending `_fields=` (or `_fields=undefined`) when the - // caller didn't ask for a selection. WordPress treats an empty _fields as a - // request for no fields, so every item would come back stripped. + // 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 }); @@ -90,4 +97,39 @@ describe('list_content field selection', () => { 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; + } + }); }); From d17f2a4034afb32a14b62c782720a5bca8dc60dc Mon Sep 17 00:00:00 2001 From: Jon Klein Date: Sun, 6 Sep 2026 13:08:20 -0400 Subject: [PATCH 09/11] Add field selection to get_content MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Companion to the list_content change. get_content returns every field of a post, and on long posts the rendered body is nearly the whole payload — the same problem, concentrated in a single item rather than spread across a page of them. `fields` maps to WordPress's _fields, exactly as it does for list_content. The mapping logic is now a shared helper rather than duplicated, so the MCP_WP_STRIP_FIELDS guard covers both tools: a selection made up entirely of fields that trimResponseFields deletes on the way out would return an empty object with isError false, and now errors instead. get_content carries one interaction list_content does not. include_raw_content asks WordPress for edit context and then reads content.raw off the response to build content_raw. A selection that leaves `content` out makes that read find nothing, so the caller would get a successful response with content_raw missing and no indication why. That combination is now rejected, naming both parameters. Selecting `content` or `content.raw` alongside it works normally and still sets edit context. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_0119LiiVk2S5wFVRT6ytEyha --- README.md | 15 ++- src/tools/unified-content.ts | 99 ++++++++++++++------ tests/tools/get-content-fields.test.ts | 122 +++++++++++++++++++++++++ 3 files changed, 209 insertions(+), 27 deletions(-) create mode 100644 tests/tools/get-content-fields.test.ts diff --git a/README.md b/README.md index adc069f..6f9de53 100644 --- a/README.md +++ b/README.md @@ -277,7 +277,7 @@ Sites running [WP Recipe Maker](https://wordpress.org/plugins/wp-recipe-maker/) ### Selecting fields -`list_content` returns every field of every item by default, and for post types +`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: @@ -286,6 +286,18 @@ listing of four neighbourhood guides can run to 90KB of rendered HTML. Pass { "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 leaves `content` out would return successfully +with no `content_raw` and no explanation. Combining the two without selecting +`content` is rejected rather than silently returning less than you asked for. + 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. @@ -305,6 +317,7 @@ Useful selections: | 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 diff --git a/src/tools/unified-content.ts b/src/tools/unified-content.ts index d2a7f41..02bda9f 100644 --- a/src/tools/unified-content.ts +++ b/src/tools/unified-content.ts @@ -698,12 +698,31 @@ 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 + // leaves `content` out makes that silently produce nothing, so the caller + // would get a successful response with no content_raw and no explanation. + if (includeRawContent && fields?.length && + !fields.some(f => f === 'content' || f.startsWith('content.'))) { + throw new Error( + `include_raw_content needs the 'content' field, but the requested selection ` + + `(${fields.join(', ')}) leaves it out — content_raw would be missing. ` + + `Add 'content' to fields, or drop 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 } ); @@ -779,6 +798,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')"), @@ -813,6 +870,14 @@ 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' is selected." ) }); @@ -978,7 +1043,7 @@ export const unifiedContentTools: Tool[] = [ }, { 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 } }, { @@ -1030,28 +1095,9 @@ export const unifiedContentHandlers = { // recognise — so passing `fields` straight through would silently return // the full payload instead of erroring. Map it explicitly. const requestParams: Record = { ...queryParams }; - if (fields?.length) { - // Every response is run through trimResponseFields, so a field named - // there is deleted after WordPress returns it. Asking for one would - // otherwise come back as an empty object per item with isError false — - // indistinguishable from "the site has no such data". - 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( - `list_content: requested field(s) ${conflicting.join(', ')} are removed by ` + - `MCP_WP_STRIP_FIELDS and will be absent from the result.`, - 'info' - ); - } - requestParams._fields = fields.join(','); + const fieldsParam = buildFieldsParam(fields, 'list_content'); + if (fieldsParam) { + requestParams._fields = fieldsParam; } const response = await makeWordPressRequest('GET', endpoint, requestParams, { siteId: site_id }); @@ -1089,7 +1135,8 @@ export const unifiedContentHandlers = { endpoint, params.id, params.site_id, - params.include_raw_content || false + params.include_raw_content || false, + params.fields ); return { diff --git a/tests/tools/get-content-fields.test.ts b/tests/tools/get-content-fields.test.ts new file mode 100644 index 0000000..c597cb1 --- /dev/null +++ b/tests/tools/get-content-fields.test.ts @@ -0,0 +1,122 @@ +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; + +beforeAll(async () => { + const mod = await import('../../src/tools/unified-content.js'); + getContent = (mod.unifiedContentHandlers as any).get_content; +}); + +beforeEach(() => { + requests.length = 0; +}); + +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'); + }); + + 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'); + }); +}); From 2001884612f26fa31af33696b6e892a607b23fbd Mon Sep 17 00:00:00 2001 From: Jon Klein Date: Sun, 6 Sep 2026 13:11:55 -0400 Subject: [PATCH 10/11] Fix: content.rendered passed the raw-content guard and returned nothing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Blocking finding from live review. The guard accepted any field beginning with `content.`, but only `content` and `content.raw` actually deliver a raw body. `fields: ["id","content.rendered"]` with include_raw_content: true therefore sailed past the check and returned isError false with content_raw absent and no explanation — exactly the silent success the guard exists to prevent, reached by a plausible route: asking for the rendered body while flipping raw on as well. Confirmed against a live site before the fix: the response came back with keys id and content, content carrying only `rendered`, and no content_raw. Tightened to an exact match on 'content' or 'content.raw'. The error message, schema description and README all now name content.raw rather than implying any content subfield will do. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_0119LiiVk2S5wFVRT6ytEyha --- README.md | 8 +++++--- src/tools/unified-content.ts | 17 ++++++++++------- tests/tools/get-content-fields.test.ts | 17 +++++++++++++++++ 3 files changed, 32 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 6f9de53..8be70f2 100644 --- a/README.md +++ b/README.md @@ -294,9 +294,11 @@ where the rendered body is nearly the whole payload: ``` One restriction there: `include_raw_content` reads `content.raw` off the -response, so a selection that leaves `content` out would return successfully -with no `content_raw` and no explanation. Combining the two without selecting -`content` is rejected rather than silently returning less than you asked for. +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 diff --git a/src/tools/unified-content.ts b/src/tools/unified-content.ts index 02bda9f..b2f9d15 100644 --- a/src/tools/unified-content.ts +++ b/src/tools/unified-content.ts @@ -704,14 +704,16 @@ async function fetchContentById( const fieldsParam = buildFieldsParam(fields, 'get_content'); // withContentRawAlias reads content.raw off the response. A selection that - // leaves `content` out makes that silently produce nothing, so the caller - // would get a successful response with no content_raw and no explanation. + // 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.startsWith('content.'))) { + !fields.some(f => f === 'content' || f === 'content.raw')) { throw new Error( - `include_raw_content needs the 'content' field, but the requested selection ` + - `(${fields.join(', ')}) leaves it out — content_raw would be missing. ` + - `Add 'content' to fields, or drop include_raw_content.` + `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.` ); } @@ -877,7 +879,8 @@ const getContentSchema = z.object({ "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' is selected." + "and cannot be combined with include_raw_content unless 'content' or " + + "'content.raw' is selected — 'content.rendered' does not carry the raw body." ) }); diff --git a/tests/tools/get-content-fields.test.ts b/tests/tools/get-content-fields.test.ts index c597cb1..6447111 100644 --- a/tests/tools/get-content-fields.test.ts +++ b/tests/tools/get-content-fields.test.ts @@ -86,6 +86,23 @@ describe('get_content field selection', () => { 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', From eb0d68178384adeb79f56ef01c0f7725b28f1715 Mon Sep 17 00:00:00 2001 From: Jon Klein Date: Sun, 6 Sep 2026 13:13:15 -0400 Subject: [PATCH 11/11] Address review: strip-content stranding, and cover four surviving mutants MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Should-fix — MCP_WP_STRIP_FIELDS naming `content` strands include_raw_content by a second route. trimResponseFields runs on the way out of makeWordPressRequest, before withContentRawAlias reads content.raw, so a stripped `content` leaves content_raw missing with isError false — and unlike the selection case this needs no `fields` at all, so it was reachable before this branch existed. fetchContentById now errors and names the variable. Should-fix — four mutants survived the suite. Each now has a test that names the bug it catches: - the raw-content guard matched with startsWith('content'), which admits `content_raw` — the name of the alias this tool adds to its own output, and an easy thing for a caller to reach for - the stripped-field check compared whole paths instead of their root, so `yoast_head.title` slipped past a check that `yoast_head` fails, though trimResponseFields deletes the top-level key either way - the shared helper's toolName argument was unasserted, so hardcoding `list_content:` in the warning went unnoticed — a get_content caller would be told the wrong tool ate their field - the new strip-content guard itself Verified by mutation: all four now fail the suite, having passed it before. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_0119LiiVk2S5wFVRT6ytEyha --- src/tools/unified-content.ts | 12 +++++ tests/tools/get-content-fields.test.ts | 65 ++++++++++++++++++++++++++ 2 files changed, 77 insertions(+) diff --git a/src/tools/unified-content.ts b/src/tools/unified-content.ts index b2f9d15..7118585 100644 --- a/src/tools/unified-content.ts +++ b/src/tools/unified-content.ts @@ -717,6 +717,18 @@ async function fetchContentById( ); } + // 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; diff --git a/tests/tools/get-content-fields.test.ts b/tests/tools/get-content-fields.test.ts index 6447111..8f3b890 100644 --- a/tests/tools/get-content-fields.test.ts +++ b/tests/tools/get-content-fields.test.ts @@ -18,14 +18,17 @@ vi.mock('../../src/wordpress.js', () => ({ })); 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() { @@ -136,4 +139,66 @@ describe('get_content field selection', () => { 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; + } + }); });