Repository navigation
Conversation
The disk cache for /wp/v2/types was already keyed per site (content-types-<siteId>.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 <noreply@anthropic.com>
… the cache in tests
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 <noreply@anthropic.com>
convertHtmlToBlocks() emitted <!-- wp:heading {"level":N} --> for h1 and
h3-h6, but a bare <!-- wp:heading --> 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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
…n target any site
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 <noreply@anthropic.com>
…eate/update
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 <noreply@anthropic.com>
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) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0119LiiVk2S5wFVRT6ytEyha
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) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0119LiiVk2S5wFVRT6ytEyha
Adversarial review — round 1 (reconciled)Two fresh reviewers with no session context: one mutating the code to find tests that don't bite, one exercising the change against a live WordPress read-only. Findings reconciled — verified first, false positives discarded. Everything surviving is fixed in Should-fix — a selection naming only stripped fields returned nothing, silently
Verified by: running the real handler with Fix: the handler now errors when the whole selection is stripped, naming Should-fix — my justification for rejecting an empty selection was factually wrong
Verified by: No behavioural bug — Nit — whitespace-only entries passed validation
Nit — "returns every field by default" was untrueBoth the tool description and the README said so, while Nit — two undocumented WordPress behavioursA selection drops the Categories checked and clean
RejectedNothing was rejected this round — both reviewers' findings held up under verification, including the one that corrected a factual claim I'd made from reasoning rather than measurement. |
|
Kilo Code Review could not run — your account is out of credits. Add credits or switch to a free model to enable reviews on this change. |
What
list_contentgains an optionalfieldsarray that maps to WordPress's global_fieldsparameter.{ "content_type": "post", "per_page": 20, "fields": ["id", "slug", "meta"] }Why
list_contentreturns every field of every item, including fully renderedcontent. On post types that carry long bodies that's overwhelmingly more than the caller wants — and it isn't merely wasteful, it can fail the call outright.Concretely, from real use: listing four custom-post-type entries on a live site returned 90KB of rendered HTML for a request that needed three metadata keys. That exceeded the MCP client's output limit, so the tool call failed and the work had to be redone with raw REST calls outside the connector. Measured on the same site with this change: 71,739 B → 4,976 B for a four-post listing, a 14× reduction. Pages: 23,984 B → 1,513 B.
Implementation notes
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
fieldsunder its own name would return the complete payload while appearing to succeed. That failure is invisible at the call site, and it's what the main regression test pins.Interaction with
MCP_WP_STRIP_FIELDS. Every response runs throughtrimResponseFields, which deletesyoast_head/yoast_head_jsonafter WordPress returns them. A selection naming only stripped fields therefore came back as one empty object per item withisError: false— indistinguishable from "this site has no Yoast data".list_contentnow errors and names the variable. A partial overlap still succeeds and logs a note.Default behaviour is unchanged. No
fields, no_fields, same payload as before.Tests
tests/tools/list-content-fields.test.ts, 8 tests, each naming the bug it catches. The load-bearing ones:_fields, never asfields— the silent-full-payload bug above_fieldsentirely when no selection is requested — guards the unchanged defaultcontent_type,site_id) out of the query stringMCP_WP_STRIP_FIELDSVerified: 98 passed / 2 skipped,
tsc --noEmitclean, build clean. Mutation-checked rather than trusted — seven mutations (unmapped passthrough, raw array instead of a joined string,_fieldsalways set, inverted guard,|separator, mapped-but-also-left-in, onlyfields[0]sent) are all killed by the new tests, plus an eighth against the strip-conflict guard.Behaviour was also verified against a live WordPress rather than reasoned about, which corrected two claims I'd have otherwise shipped wrong:
_fields=(empty) returns the full payload —wp_parse_listignores an empty list. It does not mean "no fields". Byte-identical to sending no_fieldsat all.[{}, {}]— not an error, not an empty list. Documented, since it reads as "no posts".Also confirmed live: nested paths (
title.rendered) work,X-WP-Total/X-WP-TotalPagesare unaffected, andmetacomes back byte-identical to its full-payload form.Not in this PR
get_contenthas the same problem for single large posts, but it routes throughfetchContentByIdwith thecontent.rawaliasing, so it deserves its own change rather than being bolted on here.🤖 Generated with Claude Code
https://claude.ai/code/session_0119LiiVk2S5wFVRT6ytEyha