Repository navigation
feat(plugin-mcp)!: mcp plugin refactor, add stdio mcp - #16726
Merged
Merged
Conversation
Snapshot the existing plugin so the rewrite can land in a fresh plugin-mcp folder while keeping the old version available locally for diffing.
AlessioGr
marked this pull request as ready for review
May 23, 2026 04:13
AlessioGr
requested review from
DanRibbens,
JarrodMFlesch,
denolfe and
jacobsfletch
as code owners
May 23, 2026 04:13
AlessioGr
enabled auto-merge (squash)
May 23, 2026 04:43
Contributor
|
Great changes @AlessioGr! I guess adding the missing parameters to the find tool is out of scope of this PR? #15880 |
Member
Author
Yep! The remaining planned improvements + all open MCP issues like this one are on my radar and will be done as individual PRs |
DanRibbens
reviewed
May 29, 2026
DanRibbens
approved these changes
May 29, 2026
This was referenced Jun 5, 2026
GermanJablo
added a commit
that referenced
this pull request
Jun 8, 2026
…16896) The `plugins/official/codegen/mcp` eval expected the per-collection shape `{ enabled: { find, create } }`, but `@payloadcms/plugin-mcp` configures per-collection tools via `{ tools: { find, create } }`. The `enabled` key was removed in the plugin refactor (#16726), so the rubric was penalizing output that correctly follows the current API. This updates the expected shape to `tools`. > Re-opened directly on the repo (previous PR #16895 was closed when the source fork was deleted). ## Open question How should evals (and skills) be maintained across versions, given v4 is still in beta while most users run 3.x? Some options: 1. **Track latest only (v4, even in beta).** Single source of truth and GA-ready, but most users are on 3.x today, so answers/evals serve a version almost nobody runs in prod yet. 2. **Track 3.x now, switch to v4 at GA.** Matches what most users run today, but doesn't help v4 early adopters and needs a coordinated switch at GA. 3. **Version-aware breaking-changes layer.** Feed a breaking-changes registry from the official v3 -> v4 migration guide and per-release notes (rather than maintaining it by hand); on each question the agent checks it and, if an API changed, warns that earlier versions may differ. My preference is option 3, but that can be implemented in a later PR. This is necessary to unlock the CI of the Payload Agent that runs these evaluations.
|
Hey, just wondering if there's a rough ETA for this landing in a published release of @payloadcms/plugin-mcp? Thanks! |
Member
Author
|
Will be part of v4, and is already part of internal v4 releases. This won't be released for v3 |
AlessioGr
pushed a commit
that referenced
this pull request
Sep 22, 2026
…eScript 6 ("use strict" prologue) (#17109)
## What & why
Fixes #16339 (and the duplicate #16743). On the `3.x` line, every
`@payloadcms/plugin-mcp` consumer using **TypeScript 6** gets a `500` on
the **first** `POST /api/mcp` request whenever an API key has `create`
or `update` enabled on a collection — no tools register at all:
```
APIError: Error registering tools for collection <slug>: TypeError: convertedFields.partial is not a function
status: 500
```
## Root cause
`convertCollectionSchemaToZod` builds the Zod schema by transpiling a
generated source string and `eval`ing it:
```ts
const transpileResult = ts.transpileModule(zodSchemaAsString, { compilerOptions: { module: CommonJS, ... } })
return new Function('z', `return ${transpileResult.outputText}`)(z)
```
**TypeScript 6 prepends a `"use strict";` directive** to the transpiled
module output that TypeScript 5 did not. The wrapper then evaluates as:
```js
function (z) {
return "use strict"; // ← returns the STRING
z.object({ ... }).strict(); // ← unreachable
}
```
so the function returns the **string** `"use strict"` instead of a
`ZodObject`. `resource/update.ts` (and `resource/create.ts`,
`global/update.ts`) then call `.partial()` / `.shape` on it and throw.
That throw propagates out of `getMcpHandler`'s per-collection
`try/catch` as `APIError(500)`, aborting tool registration for the whole
endpoint.
Secondary: the existing `catch` fallback returned `z.record(z.any())`, a
`ZodRecord` that also lacks `.partial()`/`.shape`, so genuine conversion
failures broke the same callers.
> **Why is CI green?** `test/plugin-mcp/config.ts` already enables
`update: true` (on `field-types`), but the suite only trips this under
TypeScript 6 — the prologue isn't emitted on TS 5. A minimal TS 6
reproduction: https://github.com/jhb-dev/payload-mcp-ts6-use-strict
## The fix (`convertCollectionSchemaToZod.ts`)
1. Strip the leading `"use strict";` directive **and the whitespace that
follows it** before the `return ${...}` wrapper. The transpiled output
is `"use strict";\n<expr>`; stripping only the directive leaves `return
\n<expr>`, where **ASI** inserts a semicolon after `return` and the
function returns `undefined` (→ an empty input schema, so create/update
silently accept no fields). Consuming the trailing whitespace keeps the
expression on the `return` line.
2. Guard the result: return `z.object({}).passthrough()` if the eval
somehow didn't produce a `ZodObject`, so callers that use
`.partial()`/`.shape` can't crash.
3. Change the `catch` fallback from `z.record(z.any())` to
`z.object({}).passthrough()` for the same reason.
No call sites change — centralizing the guarantee in the converter keeps
the `create`/`update`/`global` tools safe.
## Relation to `main` / v4
`main` (v4) is **not** affected: the breaking plugin refactor in #16726
**replaced** the transpile-and-`eval` conversion
(`convertCollectionSchemaToZod` → `new Function('z', 'return ' +
tsTranspiled)(z)`) with JSON-Schema-based input generation via Payload
core's `entityToStandaloneJSONSchema` + a new `toStandardSchema` helper,
so a `"use strict"` prologue can no longer reach an `eval`. That fix is
a breaking refactor (note the `!` in its title) and isn't
cherry-pickable onto `3.x` — and there is no smaller targeted commit
(the 3.x history on this file is only #16114, which added the `z.record`
fallback, #15705, and #15660). **This PR is the minimal equivalent for
the `3.x` line**: keep the existing conversion, just stop the prologue
from poisoning the `eval` and guarantee a populated `ZodObject` result.
## Testing
I wasn't able to run the full monorepo suite in my environment, so I
scoped this to the source fix, but I verified the behavior end-to-end by
applying it (via `patch-package`) to a downstream app on `3.84.1` +
`[email protected]` with a heavily block-based collection:
- **Before:** `POST /api/mcp` 500s on first request when a key grants
`update`.
- **With only step 1's directive stripped (no trailing whitespace):** no
500, but the converted schema is `undefined`→empty, so the update tool
registers with no field properties and silently drops all field data.
- **With the full fix:** `convertCollectionSchemaToZod` returns a
populated `ZodObject`, the update tool's input schema includes the
collection's fields, and an MCP `update` call persists field changes
(verified against the DB).
Happy to add a regression test (a TS 6 CI matrix entry, or a unit test
asserting `convertCollectionSchemaToZod(...) instanceof z.ZodObject`
**and** that its `.shape` is non-empty) in whatever form you prefer.
AlessioGr
added a commit
that referenced
this pull request
Oct 1, 2026
…ct inputs (#18436) Backport of #17026 to 3.x - `select` on the collection and global find/create/update tools is now an object instead of a JSON string - The `auth` tool's `headers` is now an object instead of a JSON string - Collection find tools accept `populate`, `joins`, `trash` and `pagination`; global find tools accept `populate` Clients that send `select` or `headers` as JSON strings now get an input validation error. `where` stays a JSON string on 3.x; main switched it to an object in the breaking #16726. Tested with the plugin-mcp int suite on MongoDB and Postgres, and end-to-end by running `claude -p` against the plugin-mcp dev config. Written by AI Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #16339
This PR refactors
@payloadcms/plugin-mcp. The public API and main ideas stay mostly the same, but the config shape, access model, and internals all changed. The new architecture lands in one PR; follow-up improvements are planned separately.Breaking changes
The plugin config API changed across the board, so most setups need updating.
Collections and globals are opt-out, not opt-in
Installing the plugin is now enough to get a working MCP server: every collection and global is exposed by default with the standard CRUD tools (find, create, update, delete). You opt OUT of what you don't want instead of opting IN to each piece.
After upgrading, collections you never listed before are reachable over MCP. Review what's exposed and disable anything that shouldn't be.
mcpPlugin({ collections: { - posts: { enabled: true }, - users: { enabled: { find: true } }, + // posts is exposed automatically, no entry needed + users: { tools: { create: false, update: false, delete: false } }, // find only }, })A consistent shape for tools, prompts and resources
Registering an MCP capability used to mean juggling three different API shapes:
collections.<slug>.enabled.<op>: built-in CRUD. Not keyed undertools.mcp.tools[]: custom tools. Keyed undertools, but as an array.experimental.tools.<kind>: auth and codegen. Keyed undertoolsagain, but as a nested map per kind.Now there's one shape everywhere: a
tools/prompts/resourcesmap, applied either nested under a collection or global (config.collections[slug].tools,config.globals[slug].tools) or at the top level (config.tools).Before.
After. One
name: valuemap at two scopes. The same map holds built-in tools, overrides, opt-in auth tools, and custom tools side by side:Fully typed tool handlers
The schema you pass as
inputflows into the handler's argument:Same inference for all four builders (
defineTool,defineCollectionTool,defineGlobalTool,definePrompt). Inputs accept any Standard Schema (Zod, Valibot, etc.) or a raw JSON Schema. The oldparameters: ZodRawShapeis gone, and handlers now take named arguments instead of positional ones.Nested instead of hoisted
Two places in the old plugin packed unrelated concepts into the same top-level namespace, which made name conflicts easy. Both are now nested by kind.
Tool inputs. The built-in
createandupdatetools used to place document fields right next to option fields likedepth,draft,localeandselect. A field literally calleddraftordepthwould collide with the option of the same name. Document fields now live under their owndatakey:_status,id,createdAtandupdatedAtare also stripped fromdatasince Payload manages them.API key access document. The old document hung every collection, global, tool, prompt and resource off the root, with custom items wedged under awkward
payload-mcp-tool/payload-mcp-resource/payload-mcp-promptkeys. Everything now goes into oneaccessJSON field, nested by kind:Auth tools are scoped and opt-in
The auth tools (
login,verify,forgotPassword,resetPassword,unlock,auth) used to be flat, development-only tools that took acollectionargument. They're now per-collection and bound to it:A leaner public surface
A handful of options got removed:
mcp.handlerOptionsis gone.verboseLogssurvived asmcp.verboseLogs;onEvent,maxDuration,disableSse,redisUrlandbasePathwere dropped (the new server has no SSE/Redis path).experimental.tools(the tools that scaffolded and edited collection, job and config files on disk) was removed entirely, with no replacement.GET /api/mcproute was dropped; onlyPOSTremains.API keys must be recreated
The
payload-mcp-api-keyscollection keeps its slug, but its fields changed completely. Access used to be defined via multiple group and checkbox fields. Now, the whole tree now lives in a singleaccessJSON field with a custom checkbox UI in the admin panel.The old layout meant that on a postgres/drizzle db, adding or removing a collection, tool, prompt or resource changed the schema, requiring a migration. With the access tree kept as JSON, the table schema stays stable and no migrations are required.
To migrate, delete your existing API keys after upgrading and create fresh ones.
Dependencies
Bundling
plugin-mcp/src/index.tswith esbuild (externalizingpayload,@payloadcms/ui,react):src/index.ts(minified)origin/mainfeat/mcp-localAbout a 9x smaller bundle, ~4.3 MB shaved off. The biggest single contributor was the runtime use of
convertCollectionSchemaToZod, which calledimport * as ts from 'typescript'. We were shipping the entire TypeScript package so we could transpile a generated source-code string at runtime and new Function()-eval it into a zod schema - now,z.fromJSONSchema()from zod v4 can now do this cleanly in a single call.The rest came from swapping the SDK.
@modelcontextprotocol/[email protected]was a bloated kitchen sink: Express 5, Hono,@hono/node-server,cors,express-rate-limit,jose,ajv+ajv-formats,pkce-challenge. 29 MB unpacked with dependencies, plusmcp-handler(which added Redis).@modelcontextprotocol/[email protected]is one runtime dependency (zod) and one optional peer (@cfworker/json-schema). 6 MB unpacked with dependencies.In the next 2.0 alpha release, we'll be able to get rid of @cfworker/json-schema to further cut bundle size.
@modelcontextprotocol/sdk@1.:
@modelcontextprotocol/server@2 alpha:
What else is new
npx payload-mcp. Nopluginsarray entry, HTTP server, or API key required.The internal refactor
The biggest internal wins are that the public API is now used internally, an improved, simpler folder structure, and the up-front sanitization into a flat
itemsarray that's much easier to work with.That collapses several parallel flows that used to coexist: a 545-line
getMcpHandler.tsthat hand-registered every kind, atools/resource/*family that rannew Function('z', ...)per request, three filesystem-codegen families (tools/collection/*,tools/config/*,tools/job/*, now gone), and inline auth checks scattered across tool files. Now the plugin runs through:sanitizeMCPConfigwalks the user config and thebuiltinTools.tsregistry, producing a flatitems: MCPItem[].mcpEndpointcallsgetAuthorizedMCPto resolve the API key (or dev-mode session) and filteritemsagainst the access document, thenbuildMcpServeriterates and registers each on mcp item. Auth lives in one single file (endpoint/access.ts).stdio.tssynthesizes a full-accessAuthorizedMCPand connects aStdioServerTransport.Per-request work, old vs new
The single biggest reduction is how tools get registered: the old plugin had a separate iteration and code branch for every kind of thing it could expose; the new one sanitizes all of them into one flat array at boot and walks it once.
Old: everything happens per request. Each config source resolves to its own bespoke tool file, and
mcpAccessSettings(a flat per-slug permissions object) is consulted at every register site to decide whether to expose that specific tool.flowchart TB subgraph perReqOld["Per request"] req[POST /api/mcp] req --> auth["getDefaultMcpAccessSettings<br/>Bearer + API key lookup"] auth --> mas["mcpAccessSettings<br/>(flat per-slug permissions)"] mas --> setup["mcp-handler invokes setup callback"] setup --> col["collections.<slug>.enabled.<op>"] setup --> glb["globals.<slug>.enabled.<op>"] setup --> exp["experimental.tools.{auth, collections, config, jobs}"] setup --> mct["mcp.tools[]"] setup --> mcpP["mcp.prompts[]"] setup --> mcr["mcp.resources[]"] col --> tr["tools/resource/{create,find,update,delete}.ts<br/>+ convertCollectionSchemaToZod (eval)"] glb --> tg["tools/global/{find,update}.ts"] exp --> texp["tools/auth/* · tools/collection/* (codegen)<br/>tools/config/* (codegen) · tools/job/* (codegen)"] mct --> uh1["user handler"] mcpP --> uh2["user handler"] mcr --> uh3["user handler"] mas -. access check .-> tr mas -. access check .-> tg mas -. access check .-> texp mas -. access check .-> uh1 mas -. access check .-> uh2 mas -. access check .-> uh3 tr --> RT[server.registerTool] tg --> RT texp --> RT uh1 --> RT uh2 --> RP[server.registerPrompt] uh3 --> RR[server.registerResource] endNew: sanitization during boot.
flowchart TB subgraph bootNew["Once at boot"] cfg[plugin config + builtinTools registry] --> san[sanitizeMCPConfig] san --> items["items: MCPItem[]"] end subgraph perReqNew["Per request"] req[POST /api/mcp] --> auth["getAuthorizedMCP<br/>fetch API key document, filter flat items[] array"] access["api-key.access JSON field"] --> auth auth --> build["buildMcpServer<br/>one switch on item.type"] build --> RT[server.registerTool] build --> RP[server.registerPrompt] build --> RR[server.registerResource] end items --> authThe MCP plugin is now also enabled across the monorepo test suites, so we exercise it internally.