Skip to content

Add field selection to get_content - #43

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

kleintech wants to merge 16 commits into
InstaWP:mainfrom
kleintech:feat/get-content-field-selection

Conversation

@kleintech

Copy link
Copy Markdown
Contributor

What

Companion to #42. get_content gains the same optional fields array, mapping to WordPress's _fields.

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

Why

Same problem as #42, concentrated rather than spread out. get_content returns every field of a post, and on a long post the rendered body is essentially the payload — reading three metadata keys off one article means pulling tens of KB of HTML to get them. For a single item there's no per_page to turn down, so field selection is the only lever.

Implementation notes

The _fields mapping is now a shared helper. buildFieldsParam is used by both tools, so list_content is refactored onto it rather than keeping two copies. That also means the MCP_WP_STRIP_FIELDS guard from #42 — erroring when a selection consists entirely of fields trimResponseFields deletes on the way out — now covers get_content too, for free.

One interaction list_content doesn't have. include_raw_content asks WordPress for context=edit and then reads content.raw off the response to build the top-level content_raw alias. A selection that leaves content out makes that read find nothing, so the caller would get a successful response with content_raw quietly 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.

That failure mode is the reason this isn't just a copy of #42 — it's the third silent-success shape I've hit in this codebase, after invalid term IDs and the stripped-field case, and it seemed worth failing loudly rather than adding a footnote.

Default behaviour is unchanged for both tools. No fields, no _fields, and get_content sends no query params at all unless it needs to.

Tests

tests/tools/get-content-fields.test.ts, 7 tests, each naming the bug it catches:

  • sends the selection as _fields, never as fields
  • sends no params at all when nothing is requested — guards the unchanged default
  • refuses a selection that would strand include_raw_content
  • allows include_raw_content when content is selected, and still sets edit context
  • accepts a nested content.raw path
  • errors when every requested field is stripped by MCP_WP_STRIP_FIELDS
  • keeps edit context when raw content is requested without a selection

Verified: 105 passed / 2 skipped, tsc --noEmit clean, build clean. Mutation-checked — unmapping the selection fails 3 tests, removing the raw-content guard fails 1, and letting an empty _fields leak into the query fails 2.

Note on CI

The Node 22.x job on #42 failed with npm error Cannot read properties of null (reading 'edgesOut') during npm install --ignore-scripts. That's an npm/arborist fault in the runner, not a code failure: Node 20.x passes, neither PR touches package.json or package-lock.json, and the same failure appeared on an unrelated contributor's branch in the same window. I don't have rerun rights on this repo — a maintainer re-running the job should clear it.

🤖 Generated with Claude Code

https://claude.ai/code/session_0119LiiVk2S5wFVRT6ytEyha

kleintech and others added 14 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
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) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0119LiiVk2S5wFVRT6ytEyha
@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.

kleintech and others added 2 commits September 6, 2026 13:11
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) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0119LiiVk2S5wFVRT6ytEyha
…ants

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) <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, no session context: one mutating the code and diffing the refactor against main, one exercising the change against a live WordPress read-only. Findings reconciled — verified before acting. Everything surviving is fixed in 2001884 and eb0d681.

Both reviewers found the Blocking issue independently, by different methods.

Blocking — content.rendered passed the raw-content guard and returned nothing

src/tools/unified-content.ts — the guard accepted any field starting with content., but only content and content.raw deliver a raw body. fields: ["id","content.rendered"] with include_raw_content: true therefore passed the check and returned isError: false with content_raw absent and no explanation — the exact silent success the guard exists to prevent, reached by a plausible route: asking for the rendered body while flipping raw on as well. Same for content.protected and content.block_version.

Verified by: driving the built handler against a live post — isError=false, keys id,content, content carrying only rendered, content_raw present: false. Independently reproduced with a _fields-honouring mock.

Fix: exact match on content or content.raw. Error text, schema description and README now name content.raw rather than implying any content. subfield qualifies. A test covers it; reverting to startsWith fails.

Should-fix — MCP_WP_STRIP_FIELDS naming content strands include_raw_content by a second route

src/tools/unified-content.ts + src/wordpress.ts:152 — trimResponseFields runs on the way out of makeWordPressRequest, before withContentRawAlias reads content.raw. A stripped content therefore leaves content_raw missing with isError: false. This needs no fields at all, so it predates this branch — but this is where the guard for that class of failure was added, and it didn't cover it.

Verified by: call-order analysis, then a test with MCP_WP_STRIP_FIELDS=content and no selection at all.

Fix: fetchContentById errors and names the variable.

Should-fix — four surviving mutants

The suite passed under four mutations. Each now has a test naming the bug:

  • guard matched with startsWith('content'), which admits content_raw — the name of the alias this tool adds to its own output, so a natural thing for a caller to reach for
  • stripped-field check compared whole paths instead of their root, so yoast_head.title slipped past a check that yoast_head fails (trimResponseFields deletes the top-level key either way)
  • the shared helper's toolName argument was unasserted — hardcoding list_content: in the partial-overlap warning went unnoticed, which would tell a get_content caller the wrong tool ate their field
  • the new strip-content guard itself

Verified by: re-running all four mutations after the fix — each now fails the suite, having passed before.


Categories checked and clean

  • The list_content refactor onto the shared helper is a faithful extraction. Diffed against git show main:src/tools/unified-content.ts: error text, log text, split('.')[0] matching, all-vs-partial thresholds, and ordering (check before _fields assignment) byte-identical; only the tool-name prefix is now interpolated. One behavioural delta — fields:[''] previously sent _fields:'' and now omits it — is unreachable, since the MCP SDK enforces .trim().min(1).nonempty() before the handler runs, and both shapes yield the full payload from WordPress anyway.
  • No regression for the other fetchContentById callers. All three remaining call sites pass four arguments, so fields is undefined and the new params object reproduces the old includeRawContent ? {context:'edit'} : undefined exactly. Verified by probe, and the "always send the object" mutant is killed by the existing suite.
  • Default behaviour unchanged for both tools. get_content with no selection sends no query params at all; list_content sends its params with no _fields key.
  • Live behaviour. Size: post 5575 25,027 B → 1,453 B (−94%); another post 23,417 → 968 B; a custom-post-type entry 42,524 → 1,279 B. include_raw_content with ["id","content"] returns content_raw byte-identical to the unselected baseline (sha1 match, 18,122 chars). ["id","content.raw"] works: _fields and context=edit combine correctly on live WordPress. Edit context is doing real work under a selection — with raw requested content carries raw, rendered, protected, block_version; without it, only rendered, protected. Custom-post-type meta comes back intact under selection.
  • Suite. 110 passed / 2 skipped; tsc --noEmit clean; build clean.

Rejected

Three candidate findings, all raised and withdrawn by the reviewer that found them, and I agree: strip-field matching being case-sensitive (fields:["Yoast_head"] bypasses the conflict check — cosmetic, since WordPress returns nothing for a wrong-cased field anyway); fields elements containing commas (WordPress parses them identically); and unknown field names returning a bare {"id":…} (documented _fields semantics, already noted in the README).

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