Skip to content

refactor(plugin-mcp): reduced code and de-duplication - #15705

Merged
kendelljoseph merged 2 commits into
mainfrom
chore/mcp-code-quality-improvements
Feb 20, 2026
Merged

kendelljoseph merged 2 commits into
mainfrom
chore/mcp-code-quality-improvements

Conversation

@kendelljoseph

Copy link
Copy Markdown
Contributor

This is a simple refactor to clean up code.

  • No core CRUD tools were touched by this refactor other than a small change to convertCollectionSchemaToZod
  • Primarily experimental tools needing tidying that are used only when experiments are enabled, and only in development node environments.

const simplifiedSchema = simplifyRelationshipFields(pointTransformed)

const zodSchemaAsString = jsonSchemaToZod(simplifiedSchema)
const zodSchemaAsString = jsonSchemaToZod(simplifyRelationshipFields(pointTransformed))

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the only refactor change that effects core tools.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Refactors the plugin-mcp experimental tooling to reduce duplication by centralizing shared helpers (e.g., camelCase conversion, field-definition generation, config editing), while also tightening some validation logic.

Changes:

  • Inlined / simplified some schema conversion logic (convertCollectionSchemaToZod).
  • De-duplicated helpers by moving common logic into shared utility/helper modules (toCamelCase, generateFieldDefinitionString, removeCollectionFromConfig).
  • Refactored validation logic in fileValidation.ts (schema field validation helper; adjusted collection field type check; removed some workflow validation).

Reviewed changes

Copilot reviewed 12 out of 12 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
packages/plugin-mcp/src/utils/schemaConversion/convertCollectionSchemaToZod.ts Minor refactor to inline relationship-field simplification before Zod generation.
packages/plugin-mcp/src/mcp/tools/job/update.ts Uses shared toCamelCase; removes local helper; small arg/handler refactor.
packages/plugin-mcp/src/mcp/tools/job/run.ts Narrows input type to unknown and simplifies tool registration wrapper.
packages/plugin-mcp/src/mcp/tools/job/create.ts Uses shared toCamelCase; marks unused helper params; removes local helper.
packages/plugin-mcp/src/mcp/tools/config/update.ts Removes unused generalConfig plumbing from tool implementation.
packages/plugin-mcp/src/mcp/tools/collection/delete.ts Uses shared removeCollectionFromConfig helper instead of inline implementation.
packages/plugin-mcp/src/mcp/tools/collection/create.ts Uses shared generateFieldDefinitionString helper for field codegen.
packages/plugin-mcp/src/mcp/helpers/fileValidation.ts Refactors schema validation; changes collection field type check; removes some workflow validation.
packages/plugin-mcp/src/mcp/helpers/fields.ts Adds exported generateFieldDefinitionString and reuses it for field insertion.
packages/plugin-mcp/src/mcp/helpers/config.ts Removes unused types/functions (general config + collection-level config updates).
packages/plugin-mcp/src/mcp/helpers/validation.ts Deletes unused validation helpers.
packages/plugin-mcp/src/mcp/helpers/conversion.ts Deletes old toCamelCase helper (now centralized elsewhere).

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines 19 to 24
updateType: string,
collectionName?: string,
adminConfig?: any,
databaseConfig?: any,
pluginUpdates?: any,
generalConfig?: any,
newContent?: string,

Copilot AI Feb 20, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

generalConfig was removed from updateConfig / updateConfigTool’s implementation, but toolSchemas.updateConfig still documents a generalConfig parameter. This creates an API contract mismatch where callers may send generalConfig and it will be silently ignored. Either remove it from the schema or re-add handling for it.

Copilot uses AI. Check for mistakes.
Comment on lines +231 to +233
if (!('type' in field) || !field.type) {
return {
error: `Field at index ${i} has invalid type property`,
error: `Field at index ${i} is missing a valid type property`,

Copilot AI Feb 20, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

validateCollectionConfig uses the in operator / field.type on a value that is only checked for truthiness. If config.fields[i] is a non-null primitive (e.g. a string), ('type' in field) will throw a TypeError instead of returning a validation error. Add a typeof field === 'object' && field !== null guard before using in, and only then validate the type property.

Copilot uses AI. Check for mistakes.
success: false,
}
}

Copilot AI Feb 20, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WorkflowConfig includes an optional queue?: string, but validateWorkflowConfig no longer validates it. This means a workflow with a non-string queue value will incorrectly pass validation. Add a check like if (config.queue !== undefined && typeof config.queue !== 'string') and return a helpful error.

Suggested change
if (config.queue !== undefined && typeof config.queue !== 'string') {
return {
error: 'Workflow config queue must be a string if provided',
success: false,
}
}

Copilot uses AI. Check for mistakes.
Comment on lines +10 to +21
lines.push(` name: '${field.name}',`)
lines.push(` type: '${field.type}',`)

if (field.required) {
lines.push(` required: true,`)
}
fieldName: string

if (field.description || field.position) {
lines.push(` admin: {`)
if (field.description) {
lines.push(` description: '${field.description}',`)
}

Copilot AI Feb 20, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

generateFieldDefinitionString interpolates field.name, field.type, and other user-provided strings directly into single-quoted TS string literals. If any value contains a ', \n, or \\, the generated collection file will be invalid (and can lead to unintended code being written). Escape these values (e.g. via JSON.stringify(value) and trimming quotes, or a dedicated string-literal escape helper) before embedding them.

Copilot uses AI. Check for mistakes.
@github-actions

github-actions Bot commented Feb 20, 2026 •

Copy link
Copy Markdown
Contributor

📦 esbuild Bundle Analysis for payload

This analysis was generated by esbuild-bundle-analyzer. 🤖
This PR introduced no changes to the esbuild bundle! 🙌

@kendelljoseph
kendelljoseph marked this pull request as ready for review February 20, 2026 17:50
@kendelljoseph
kendelljoseph merged commit 039e6c9 into main Feb 20, 2026
150 checks passed
@kendelljoseph
kendelljoseph deleted the chore/mcp-code-quality-improvements branch February 20, 2026 19:31
@github-actions

Copy link
Copy Markdown
Contributor

🚀 This is included in version v3.78.0

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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants