Skip to content

Add field selection to list_content - #42

Open
kleintech wants to merge 12 commits into
InstaWP:mainfrom
kleintech:feat/list-content-field-selection
Open

kleintech wants to merge 12 commits into
InstaWP:mainfrom
kleintech:feat/list-content-field-selection

Conversation

@kleintech

Copy link
Copy Markdown
Contributor

What

list_content gains an optional fields array that maps to WordPress's global _fields parameter.

{ "content_type": "post", "per_page": 20, "fields": ["id", "slug", "meta"] }

Why

list_content returns every field of every item, including fully rendered content. 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 fields under 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 through trimResponseFields, which deletes yoast_head / yoast_head_json after WordPress returns them. A selection naming only stripped fields therefore came back as one empty object per item with isError: false — indistinguishable from "this site has no Yoast data". list_content now 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:

  • sends the selection as _fields, never as fields — the silent-full-payload bug above
  • omits _fields entirely when no selection is requested — guards the unchanged default
  • errors rather than returning empty objects when every requested field is stripped
  • keeps routing inputs (content_type, site_id) out of the query string
  • honours a narrowed MCP_WP_STRIP_FIELDS

Verified: 98 passed / 2 skipped, tsc --noEmit clean, build clean. Mutation-checked rather than trusted — seven mutations (unmapped passthrough, raw array instead of a joined string, _fields always set, inverted guard, | separator, mapped-but-also-left-in, only fields[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_list ignores an empty list. It does not mean "no fields". Byte-identical to sending no _fields at all.
  • A selection whose names are all wrong returns [{}, {}] — 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-TotalPages are unaffected, and meta comes back byte-identical to its full-payload form.

Not in this PR

get_content has the same problem for single large posts, but it routes through fetchContentById with the content.raw aliasing, so it deserves its own change rather than being bolted on here.

🤖 Generated with Claude Code

https://claude.ai/code/session_0119LiiVk2S5wFVRT6ytEyha

kleintech and others added 12 commits September 1, 2026 12:54
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
@kleintech

Copy link
Copy Markdown
Contributor Author

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 3040837.

Should-fix — a selection naming only stripped fields returned nothing, silently

src/tools/unified-content.ts + src/wordpress.ts:152 — makeWordPressRequest runs trimResponseFields on every response, deleting yoast_head / yoast_head_json (or whatever MCP_WP_STRIP_FIELDS names) after WordPress returns them. So fields: ["yoast_head"] produced [{}, {}, …] with isError: false — the caller cannot distinguish "this site has no Yoast data" from "the server removed it", and nothing points at the cause.

Verified by: running the real handler with siteManager mocked to return [{yoast_head:'<meta>', yoast_head_json:{t:1}}] → [{}], isError=false.

Fix: the handler now errors when the whole selection is stripped, naming MCP_WP_STRIP_FIELDS. A partial overlap still succeeds and logs a note, since the rest of the selection is worth returning.

Should-fix — my justification for rejecting an empty selection was factually wrong

tests/tools/list-content-fields.test.ts — the comment claimed WordPress treats an empty _fields as "no fields", so items would come back stripped. It does the opposite: _fields goes through wp_parse_list, and an empty list returns the full object.

Verified by: curl '…/wp/v2/posts?per_page=2&_fields=' → 200, 39,421 bytes, all 25 keys — byte-identical to sending no _fields at all. Also _fields=id,,slug → ["id","slug"], empty elements ignored.

No behavioural bug — if (fields?.length) skips the param and .nonempty() rejects [] at the MCP layer — but the test named a bug that doesn't exist. Reworded to the true rationale: _fields= is silently ignored and returns the whole payload the caller was trying to avoid, looking like success, so the schema surfaces it instead.

Nit — whitespace-only entries passed validation

z.string().min(1) accepts " ", so fields: [" "] sent _fields=" ". Verified by driving the tool through a real McpServer/Client pair. Now z.string().trim().min(1), which also trims padding on valid entries.

Nit — "returns every field by default" was untrue

Both the tool description and the README said so, while MCP_WP_STRIP_FIELDS removes yoast_head / yoast_head_json by default. Reworded in both, with a cross-reference.

Nit — two undocumented WordPress behaviours

A selection drops the _links block unless named, and a selection whose names are all wrong returns [{}, {}] rather than an error or an empty list. Both verified live, both now in the README — the second especially, since it reads as "no posts".


Categories checked and clean

  • Test quality. All seven mutations applied to a scratch copy were killed: unmapped passthrough; _fields set to the raw array; _fields always set; guard inverted; | separator; mapped and left in the query; only fields[0] sent. No surviving mutant. (An eighth, against the new strip-conflict guard, is also killed.)
  • Schema exposure. server.tool() does a real zod→JSON Schema conversion, so a client sees {"type":"array","items":{"type":"string","minLength":1},"minItems":1}. Verified through an in-memory McpServer + Client and listTools(). I had flagged this as a risk on the assumption that inputSchema: { properties: schema.shape } was published as-is; that premise was wrong.
  • Input validation. Errors are useful, and the SDK validates before the handler so no fields.join is not a function path exists: [] → "Array must contain at least 1 element(s) at fields"; [""] → "String must contain at least 1 character(s) at fields[0]"; "id,slug" → "Expected array, received string"; ["id",5] → "Expected string, received number at fields[1]".
  • Internal callers. None — list_content is only reached via unifiedContentHandlers, so nothing else breaks.
  • Live behaviour. Nested paths work (title.rendered, and one level into meta). Pagination headers identical with and without a selection (X-WP-Total: 131, X-WP-TotalPages: 66). meta byte-identical to its full-payload form, all 30 Rank Math / Genesis keys present, authed and unauthed. Size: 71,739 B → 4,976 B on a four-post listing; 23,984 B → 1,513 B on pages.
  • Suite. 98 passed / 2 skipped; tsc --noEmit exit 0; build clean.

Rejected

Nothing 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-bot

kilo-code-bot Bot commented Sep 6, 2026

Copy link
Copy Markdown

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant