@payloadcms/plugin-mcp 4.0.0-internal.fa183d3 → 4.0.0-internal.fec2230

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/dist/endpoint/access.js +2 -2
  2. package/dist/endpoint/access.js.map +1 -1
  3. package/dist/mcp/buildMcpServer.d.ts +1 -1
  4. package/dist/mcp/buildMcpServer.d.ts.map +1 -1
  5. package/dist/mcp/buildMcpServer.js +35 -23
  6. package/dist/mcp/buildMcpServer.js.map +1 -1
  7. package/dist/mcp/builtin/collections/authTools.d.ts.map +1 -1
  8. package/dist/mcp/builtin/collections/authTools.js +79 -56
  9. package/dist/mcp/builtin/collections/authTools.js.map +1 -1
  10. package/dist/mcp/builtin/collections/countTool.d.ts.map +1 -1
  11. package/dist/mcp/builtin/collections/countTool.js +9 -14
  12. package/dist/mcp/builtin/collections/countTool.js.map +1 -1
  13. package/dist/mcp/builtin/collections/countVersionsTool.d.ts.map +1 -1
  14. package/dist/mcp/builtin/collections/countVersionsTool.js +9 -13
  15. package/dist/mcp/builtin/collections/countVersionsTool.js.map +1 -1
  16. package/dist/mcp/builtin/collections/createTool.d.ts +1 -1
  17. package/dist/mcp/builtin/collections/createTool.d.ts.map +1 -1
  18. package/dist/mcp/builtin/collections/createTool.js +104 -63
  19. package/dist/mcp/builtin/collections/createTool.js.map +1 -1
  20. package/dist/mcp/builtin/collections/deleteTool.d.ts.map +1 -1
  21. package/dist/mcp/builtin/collections/deleteTool.js +44 -43
  22. package/dist/mcp/builtin/collections/deleteTool.js.map +1 -1
  23. package/dist/mcp/builtin/collections/duplicateTool.d.ts.map +1 -1
  24. package/dist/mcp/builtin/collections/duplicateTool.js +31 -37
  25. package/dist/mcp/builtin/collections/duplicateTool.js.map +1 -1
  26. package/dist/mcp/builtin/collections/fileInput.d.ts +21 -13
  27. package/dist/mcp/builtin/collections/fileInput.d.ts.map +1 -1
  28. package/dist/mcp/builtin/collections/fileInput.js +52 -64
  29. package/dist/mcp/builtin/collections/fileInput.js.map +1 -1
  30. package/dist/mcp/builtin/collections/fileInput.spec.js +20 -6
  31. package/dist/mcp/builtin/collections/fileInput.spec.js.map +1 -1
  32. package/dist/mcp/builtin/collections/findDistinctTool.d.ts.map +1 -1
  33. package/dist/mcp/builtin/collections/findDistinctTool.js +11 -26
  34. package/dist/mcp/builtin/collections/findDistinctTool.js.map +1 -1
  35. package/dist/mcp/builtin/collections/findTool.d.ts.map +1 -1
  36. package/dist/mcp/builtin/collections/findTool.js +27 -45
  37. package/dist/mcp/builtin/collections/findTool.js.map +1 -1
  38. package/dist/mcp/builtin/collections/findVersionByIDTool.d.ts.map +1 -1
  39. package/dist/mcp/builtin/collections/findVersionByIDTool.js +17 -26
  40. package/dist/mcp/builtin/collections/findVersionByIDTool.js.map +1 -1
  41. package/dist/mcp/builtin/collections/findVersionsTool.d.ts.map +1 -1
  42. package/dist/mcp/builtin/collections/findVersionsTool.js +16 -30
  43. package/dist/mcp/builtin/collections/findVersionsTool.js.map +1 -1
  44. package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -1
  45. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +15 -14
  46. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -1
  47. package/dist/mcp/builtin/collections/restoreVersionTool.d.ts.map +1 -1
  48. package/dist/mcp/builtin/collections/restoreVersionTool.js +14 -26
  49. package/dist/mcp/builtin/collections/restoreVersionTool.js.map +1 -1
  50. package/dist/mcp/builtin/collections/updateTool.d.ts.map +1 -1
  51. package/dist/mcp/builtin/collections/updateTool.js +58 -90
  52. package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
  53. package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts +2 -0
  54. package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts.map +1 -0
  55. package/dist/mcp/builtin/collections/uploadInstructionsTool.js +55 -0
  56. package/dist/mcp/builtin/collections/uploadInstructionsTool.js.map +1 -0
  57. package/dist/mcp/builtin/formatEntityError.d.ts +16 -0
  58. package/dist/mcp/builtin/formatEntityError.d.ts.map +1 -0
  59. package/dist/mcp/builtin/formatEntityError.js +55 -0
  60. package/dist/mcp/builtin/formatEntityError.js.map +1 -0
  61. package/dist/mcp/builtin/getConfigInfoTool.d.ts.map +1 -1
  62. package/dist/mcp/builtin/getConfigInfoTool.js +3 -2
  63. package/dist/mcp/builtin/getConfigInfoTool.js.map +1 -1
  64. package/dist/mcp/builtin/globals/countVersionsTool.d.ts.map +1 -1
  65. package/dist/mcp/builtin/globals/countVersionsTool.js +9 -13
  66. package/dist/mcp/builtin/globals/countVersionsTool.js.map +1 -1
  67. package/dist/mcp/builtin/globals/findTool.d.ts.map +1 -1
  68. package/dist/mcp/builtin/globals/findTool.js +10 -16
  69. package/dist/mcp/builtin/globals/findTool.js.map +1 -1
  70. package/dist/mcp/builtin/globals/findVersionByIDTool.d.ts.map +1 -1
  71. package/dist/mcp/builtin/globals/findVersionByIDTool.js +13 -24
  72. package/dist/mcp/builtin/globals/findVersionByIDTool.js.map +1 -1
  73. package/dist/mcp/builtin/globals/findVersionsTool.d.ts.map +1 -1
  74. package/dist/mcp/builtin/globals/findVersionsTool.js +13 -29
  75. package/dist/mcp/builtin/globals/findVersionsTool.js.map +1 -1
  76. package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts.map +1 -1
  77. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js +11 -11
  78. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js.map +1 -1
  79. package/dist/mcp/builtin/globals/restoreVersionTool.d.ts.map +1 -1
  80. package/dist/mcp/builtin/globals/restoreVersionTool.js +15 -22
  81. package/dist/mcp/builtin/globals/restoreVersionTool.js.map +1 -1
  82. package/dist/mcp/builtin/globals/updateTool.d.ts.map +1 -1
  83. package/dist/mcp/builtin/globals/updateTool.js +27 -36
  84. package/dist/mcp/builtin/globals/updateTool.js.map +1 -1
  85. package/dist/mcp/builtinTools.d.ts +6 -0
  86. package/dist/mcp/builtinTools.d.ts.map +1 -1
  87. package/dist/mcp/builtinTools.js +9 -3
  88. package/dist/mcp/builtinTools.js.map +1 -1
  89. package/dist/mcp/sanitizeMCPConfig.js +4 -1
  90. package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
  91. package/dist/stdio.d.ts.map +1 -1
  92. package/dist/stdio.js +2 -1
  93. package/dist/stdio.js.map +1 -1
  94. package/dist/types.d.ts +4 -4
  95. package/dist/types.d.ts.map +1 -1
  96. package/dist/types.js.map +1 -1
  97. package/package.json +5 -7
  98. package/src/endpoint/access.ts +2 -3
  99. package/src/mcp/buildMcpServer.ts +39 -29
  100. package/src/mcp/builtin/collections/authTools.ts +77 -69
  101. package/src/mcp/builtin/collections/countTool.ts +9 -21
  102. package/src/mcp/builtin/collections/countVersionsTool.ts +9 -18
  103. package/src/mcp/builtin/collections/createTool.ts +110 -86
  104. package/src/mcp/builtin/collections/deleteTool.ts +36 -64
  105. package/src/mcp/builtin/collections/duplicateTool.ts +35 -85
  106. package/src/mcp/builtin/collections/fileInput.spec.ts +20 -6
  107. package/src/mcp/builtin/collections/fileInput.ts +64 -76
  108. package/src/mcp/builtin/collections/findDistinctTool.ts +11 -63
  109. package/src/mcp/builtin/collections/findTool.ts +23 -105
  110. package/src/mcp/builtin/collections/findVersionByIDTool.ts +15 -58
  111. package/src/mcp/builtin/collections/findVersionsTool.ts +14 -85
  112. package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +16 -12
  113. package/src/mcp/builtin/collections/restoreVersionTool.ts +14 -56
  114. package/src/mcp/builtin/collections/updateTool.ts +57 -111
  115. package/src/mcp/builtin/collections/uploadInstructionsTool.ts +64 -0
  116. package/src/mcp/builtin/formatEntityError.ts +77 -0
  117. package/src/mcp/builtin/getConfigInfoTool.ts +2 -1
  118. package/src/mcp/builtin/globals/countVersionsTool.ts +9 -17
  119. package/src/mcp/builtin/globals/findTool.ts +12 -51
  120. package/src/mcp/builtin/globals/findVersionByIDTool.ts +13 -52
  121. package/src/mcp/builtin/globals/findVersionsTool.ts +14 -92
  122. package/src/mcp/builtin/globals/getGlobalSchemaTool.ts +10 -10
  123. package/src/mcp/builtin/globals/restoreVersionTool.ts +14 -45
  124. package/src/mcp/builtin/globals/updateTool.ts +37 -60
  125. package/src/mcp/builtinTools.ts +9 -2
  126. package/src/mcp/sanitizeMCPConfig.ts +4 -1
  127. package/src/stdio.ts +2 -1
  128. package/src/types.ts +4 -4
  129. package/dist/mcp/builtin/collections/formatCollectionError.d.ts +0 -9
  130. package/dist/mcp/builtin/collections/formatCollectionError.d.ts.map +0 -1
  131. package/dist/mcp/builtin/collections/formatCollectionError.js +0 -60
  132. package/dist/mcp/builtin/collections/formatCollectionError.js.map +0 -1
  133. package/dist/mcp/builtin/validateEntityData.d.ts +0 -14
  134. package/dist/mcp/builtin/validateEntityData.d.ts.map +0 -1
  135. package/dist/mcp/builtin/validateEntityData.js +0 -82
  136. package/dist/mcp/builtin/validateEntityData.js.map +0 -1
  137. package/dist/utils/getVirtualFieldNames.d.ts +0 -14
  138. package/dist/utils/getVirtualFieldNames.d.ts.map +0 -1
  139. package/dist/utils/getVirtualFieldNames.js +0 -35
  140. package/dist/utils/getVirtualFieldNames.js.map +0 -1
  141. package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts +0 -28
  142. package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts.map +0 -1
  143. package/dist/utils/schemaConversion/filterFieldsByAccess.js +0 -71
  144. package/dist/utils/schemaConversion/filterFieldsByAccess.js.map +0 -1
  145. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts +0 -13
  146. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts.map +0 -1
  147. package/dist/utils/schemaConversion/getEntityInputSchema.js +0 -66
  148. package/dist/utils/schemaConversion/getEntityInputSchema.js.map +0 -1
  149. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts +0 -10
  150. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts.map +0 -1
  151. package/dist/utils/schemaConversion/sanitizeEntitySchema.js +0 -384
  152. package/dist/utils/schemaConversion/sanitizeEntitySchema.js.map +0 -1
  153. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js +0 -133
  154. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js.map +0 -1
  155. package/dist/utils/transformPointDataToPayload.d.ts +0 -7
  156. package/dist/utils/transformPointDataToPayload.d.ts.map +0 -1
  157. package/dist/utils/transformPointDataToPayload.js +0 -28
  158. package/dist/utils/transformPointDataToPayload.js.map +0 -1
  159. package/dist/utils/whereSchema.d.ts +0 -9
  160. package/dist/utils/whereSchema.d.ts.map +0 -1
  161. package/dist/utils/whereSchema.js +0 -13
  162. package/dist/utils/whereSchema.js.map +0 -1
  163. package/src/mcp/builtin/collections/formatCollectionError.ts +0 -84
  164. package/src/mcp/builtin/validateEntityData.ts +0 -132
  165. package/src/utils/getVirtualFieldNames.ts +0 -53
  166. package/src/utils/schemaConversion/filterFieldsByAccess.ts +0 -123
  167. package/src/utils/schemaConversion/getEntityInputSchema.ts +0 -96
  168. package/src/utils/schemaConversion/sanitizeEntitySchema.spec.ts +0 -96
  169. package/src/utils/schemaConversion/sanitizeEntitySchema.ts +0 -432
  170. package/src/utils/transformPointDataToPayload.ts +0 -40
  171. package/src/utils/whereSchema.ts +0 -24
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../src/utils/schemaConversion/sanitizeEntitySchema.ts"],"sourcesContent":["import type { JsonSchemaType } from '../../types.js'\n\n/**\n * Refines Payload's `input`-variant JSON Schema into an MCP create/update tool's input schema. The\n * variant already covers correctness (ID-only relationships, no managed/virtual/join fields); the\n * passes here are MCP-specific - reshaping fields for the model and shrinking the result - and keep\n * every node valid JSON Schema draft 2020-12. Each is tagged **Correctness**, **Size**, or **LLM\n * ergonomics**, with a before/after example on its definition.\n */\nexport const sanitizeEntitySchema = (schema: JsonSchemaType): JsonSchemaType => {\n // Work on a copy — the caller reuses the original schema elsewhere (e.g. when listing tools).\n let result = structuredClone(schema)\n\n // LLM ergonomics — drop the redundant `'null'` from optional arrays/objects (`['array','null']` → `'array'`).\n result = collapseOptionalContainerTypes(result)\n\n // LLM ergonomics — rewrite point fields from a `[number, number]` tuple into a `{ longitude, latitude }` object.\n result = pointFieldsToObjects(result)\n\n // Size — strip inert type-gen leftovers that only bloat the schema (`tsType`, block-collision notes).\n result = removeTypeGenArtifacts(result)\n\n // Size — where a `const` already pins a value, the sibling `type` is redundant; remove it.\n result = dropRedundantConstType(result)\n\n // Size — fold per-collection relationship/upload variants (identical but for `relationTo`) into one `enum`.\n result = mergeConstDiscriminatedUnions(result)\n\n // Size — pull any subschema that appears more than once into a single shared `$defs` entry.\n result = deduplicateIntoDefinitions(result)\n\n // LLM ergonomics — give `$defs` short, readable names (`Code`, `paragraph`, `node`) so the `$ref`s read nicely.\n result = shortenDefinitionNames(result)\n\n return result\n}\n\n/**\n * Rebuilds a schema bottom-up, calling `visit` on each node after its children. Shared by the\n * transforms that need to touch every node in the tree.\n */\nconst mapNodes = (node: unknown, visit: (node: JsonSchemaType) => JsonSchemaType): unknown => {\n if (Array.isArray(node)) {\n return node.map((child) => mapNodes(child, visit))\n }\n if (!node || typeof node !== 'object') {\n return node\n }\n const out: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(node)) {\n out[key] = mapNodes(value, visit)\n }\n return visit(out)\n}\n\n/**\n * **LLM ergonomics.** Collapses optional array/object types (`['array', 'null']` → `'array'`) via\n * {@link collapseNullableType}, recursing through `properties` and array items. The `required` list\n * already conveys optionality, so the `'null'` is redundant noise for the model.\n *\n * @example\n * { properties: { tags: { type: ['array', 'null'], items: {} } }, required: [] }\n * → { properties: { tags: { type: 'array', items: {} } }, required: [] }\n */\nconst collapseOptionalContainerTypes = (schema: JsonSchemaType): JsonSchemaType => {\n if (schema.properties && typeof schema.properties === 'object') {\n for (const key of Object.keys(schema.properties)) {\n const prop = schema.properties[key] as JsonSchemaType\n if (!prop || typeof prop !== 'object') {\n continue\n }\n const isRequired = Array.isArray(schema.required) && schema.required.includes(key)\n collapseNullableType(prop, isRequired)\n if (prop.properties) {\n collapseOptionalContainerTypes(prop)\n }\n if (prop.items && typeof prop.items === 'object' && !Array.isArray(prop.items)) {\n collapseOptionalContainerTypes(prop.items)\n }\n }\n }\n\n return schema\n}\n\n/**\n * Drops the `'null'` from an optional array/object type (`['array', 'null']` → `'array'`, likewise\n * `'object'`). Payload marks a field optional by unioning its type with `'null'`, but a create/update\n * tool already conveys \"optional\" through the `required` list - the client just omits the field - so the\n * `'null'` is redundant here. Dropping it shows the model a plain `type: 'array'` instead of implying it\n * should send a literal `null`.\n *\n * We never touch the `required` list, so this can't change whether a field is required. And we skip fields\n * that ARE required (`isRequired`): there a `'null'` is a value the field genuinely accepts, not optionality\n * encoding. Nullable scalars (`['string', 'null']`) are also left alone - they read fine as `string | null`.\n *\n * @example\n * optional { type: ['array', 'null'] } → { type: 'array' } (still optional, just no longer null-valued)\n * required { type: ['array', 'null'] } → unchanged\n * { type: ['string', 'null'] } → unchanged\n */\nconst collapseNullableType = (schema: JsonSchemaType, isRequired: boolean): void => {\n if (isRequired || !Array.isArray(schema.type)) {\n return\n }\n const nonNullTypes = schema.type.filter((t) => t !== 'null')\n if (nonNullTypes.length === 1 && (nonNullTypes[0] === 'array' || nonNullTypes[0] === 'object')) {\n schema.type = nonNullTypes[0]\n }\n}\n\n/**\n * **LLM ergonomics.** Rewrites a point field (stored as a two-number tuple) into a `{ longitude, latitude }` object, which\n * is far easier for the model to fill in than a positional array. This is input-only and lossless: the\n * create/update handler converts the object back to the `[longitude, latitude]` tuple Payload stores,\n * via `transformPointDataToPayload`.\n *\n * @example\n * { type: 'array', items: [{ type: 'number' }, { type: 'number' }] }\n * → { type: 'object', properties: { longitude: { type: 'number' }, latitude: { type: 'number' } }, required: ['longitude', 'latitude'] }\n */\nconst pointFieldsToObjects = (schema: JsonSchemaType): JsonSchemaType => {\n if (!schema || typeof schema !== 'object') {\n return schema\n }\n\n const transformed = { ...schema }\n\n if (transformed.properties && typeof transformed.properties === 'object') {\n transformed.properties = Object.fromEntries(\n Object.entries(transformed.properties).map(([key, value]) => {\n if (!value || typeof value !== 'object') {\n return [key, value]\n }\n const isArrayType =\n value.type === 'array' || (Array.isArray(value.type) && value.type.includes('array'))\n const isPointField =\n isArrayType &&\n Array.isArray(value.items) &&\n value.items.length === 2 &&\n value.items.every((item) => item && typeof item === 'object' && item.type === 'number')\n\n if (isPointField) {\n const isNullable = Array.isArray(value.type) && value.type.includes('null')\n return [\n key,\n {\n type: isNullable ? ['object', 'null'] : 'object',\n description: value.description || 'Geographic coordinates (longitude, latitude)',\n properties: {\n latitude: { type: 'number', description: 'Latitude coordinate' },\n longitude: { type: 'number', description: 'Longitude coordinate' },\n },\n required: ['longitude', 'latitude'],\n },\n ]\n }\n\n return [key, pointFieldsToObjects(value)]\n }),\n )\n }\n\n if (\n transformed.items &&\n typeof transformed.items === 'object' &&\n !Array.isArray(transformed.items)\n ) {\n transformed.items = pointFieldsToObjects(transformed.items)\n }\n\n return transformed\n}\n\n/**\n * **Size.** Strips type-generation leftovers that bloat the schema without helping the model: the `tsType`\n * hint (a `json-schema-to-typescript` extension; JSON Schema validators just ignore it, they don't reject it)\n * and the block-interface-collision note Payload adds to some block descriptions (the\n * `block-interface-name-collisions` docs link set in `registerBlockInterface`, see configToJSONSchema.ts).\n * Both are inert here - removing them only shrinks the schema (and spares the model irrelevant noise).\n *\n * @example\n * { type: 'object', tsType: 'SerializedBlockNode', description: 'see …#block-interface-name-collisions' }\n * → { type: 'object' }\n */\nconst removeTypeGenArtifacts = (schema: JsonSchemaType): JsonSchemaType =>\n mapNodes(schema, (node) => {\n delete (node as { tsType?: unknown }).tsType\n const { description } = node as { description?: string }\n if (\n typeof description === 'string' &&\n description.includes('block-interface-name-collisions')\n ) {\n delete (node as { description?: unknown }).description\n }\n return node\n }) as JsonSchemaType\n\n/**\n * **Size.** Removes `type` whenever a `const` sits next to it — the constant already fixes the value.\n *\n * @example\n * { type: 'string', const: 'paragraph' } → { const: 'paragraph' }\n */\nconst dropRedundantConstType = (schema: JsonSchemaType): JsonSchemaType =>\n mapNodes(schema, (node) => {\n if ('const' in node && 'type' in node) {\n delete (node as { type?: unknown }).type\n }\n return node\n }) as JsonSchemaType\n\n/**\n * **Size.** Merges the members of a `oneOf`/`anyOf` that are identical except for one `const`-valued property\n * into a single member with that property as an `enum`. Since the members differ only by that one\n * constant, the `enum` form accepts exactly the same values - it's just smaller. This folds the\n * per-collection relationship and upload variants, which differ only in their `relationTo` constant.\n *\n * @example\n * { oneOf: [\n * { properties: { relationTo: { const: 'posts' }, value: { type: 'string' } } },\n * { properties: { relationTo: { const: 'pages' }, value: { type: 'string' } } },\n * ] }\n * → { properties: { relationTo: { enum: ['posts', 'pages'] }, value: { type: 'string' } } }\n */\nconst mergeConstDiscriminatedUnions = (schema: JsonSchemaType): JsonSchemaType =>\n mapNodes(schema, (node) => {\n for (const keyword of ['oneOf', 'anyOf'] as const) {\n const members = node[keyword]\n if (Array.isArray(members) && members.length > 1) {\n const merged = mergeMembersByConst(members)\n if (merged) {\n delete node[keyword]\n Object.assign(node, merged)\n }\n }\n }\n return node\n }) as JsonSchemaType\n\n/** Returns the merged member for {@link mergeConstDiscriminatedUnions}, or `null` if they can't merge. */\nconst mergeMembersByConst = (members: Array<boolean | JsonSchemaType>): JsonSchemaType | null => {\n const objects = members.filter(\n (member): member is JsonSchemaType =>\n typeof member === 'object' && member !== null && typeof member.properties === 'object',\n )\n if (objects.length < 2 || objects.length !== members.length) {\n return null\n }\n\n for (const discriminator of Object.keys(objects[0]!.properties!)) {\n // Each member must pin this property to a `const`...\n const constValues: unknown[] = []\n const everyMemberPinsConst = objects.every((member) => {\n const prop = member.properties![discriminator]\n if (prop && typeof prop === 'object' && 'const' in prop) {\n constValues.push(prop.const)\n return true\n }\n return false\n })\n if (!everyMemberPinsConst) {\n continue\n }\n\n // ...and be otherwise identical (compare each member with the discriminator removed).\n const fingerprintWithoutDiscriminator = (member: JsonSchemaType): string => {\n const { [discriminator]: _discriminator, ...otherProperties } = member.properties!\n return JSON.stringify({ ...member, properties: otherProperties })\n }\n if (new Set(objects.map(fingerprintWithoutDiscriminator)).size !== 1) {\n continue\n }\n\n const uniqueConstValues = [...new Set(constValues)]\n if (uniqueConstValues.length < 2) {\n continue\n }\n\n // Replace the per-member `const` with a single `enum` of every value.\n const merged = structuredClone(objects[0]!)\n const discriminatorProp = merged.properties![discriminator]\n if (discriminatorProp && typeof discriminatorProp === 'object') {\n delete discriminatorProp.const\n discriminatorProp.enum = uniqueConstValues as NonNullable<typeof discriminatorProp.enum>\n }\n return merged\n }\n return null\n}\n\n// A `$ref` costs ~30 characters once names are shortened, so sharing a subschema only pays off when\n// it's larger than that and appears more than once.\nconst MIN_SHARED_SIZE = 64\n\n/** A subschema worth sharing: a standalone object/union/described schema, not a `$ref` or a primitive. */\nconst isShareable = (node: unknown): node is Record<string, unknown> => {\n if (!node || typeof node !== 'object' || Array.isArray(node) || '$ref' in node) {\n return false\n }\n const schema = node as JsonSchemaType\n return (\n Array.isArray(schema.oneOf) ||\n Array.isArray(schema.anyOf) ||\n Boolean(schema.properties) ||\n Boolean(schema.items) ||\n typeof schema.description === 'string'\n )\n}\n\n/**\n * **Size.** Replaces any subschema that appears more than once with a single shared `$defs` entry referenced by\n * `$ref`. Lossless — only the serialized size shrinks. A collection with several rich-text fields, for\n * example, inlines the same large lexical node schema once per field; this collapses them into one.\n *\n * @example\n * { properties: { billing: address, shipping: address } }\n * → { properties: { billing: { $ref: '#/$defs/shared_0' }, shipping: { $ref: '#/$defs/shared_0' } }, $defs: { shared_0: address } }\n */\nconst deduplicateIntoDefinitions = (schema: JsonSchemaType): JsonSchemaType => {\n // Count how often each shareable subschema appears, keyed by its serialized form.\n const counts = new Map<string, number>()\n const count = (node: unknown): void => {\n if (isShareable(node)) {\n const key = JSON.stringify(node)\n if (key.length >= MIN_SHARED_SIZE) {\n counts.set(key, (counts.get(key) ?? 0) + 1)\n }\n }\n if (Array.isArray(node)) {\n node.forEach(count)\n } else if (node && typeof node === 'object') {\n Object.values(node).forEach(count)\n }\n }\n count(schema)\n\n if (![...counts.values()].some((n) => n >= 2)) {\n return schema\n }\n\n // Replace each subschema seen 2+ times with a `$ref`. The first time we meet one it becomes a shared\n // entry; we never descend into a stored entry, so shared entries never reference one another.\n const sharedEntries: Record<string, JsonSchemaType> = {}\n const nameByKey = new Map<string, string>()\n const share = (node: unknown): unknown => {\n if (isShareable(node)) {\n const key = JSON.stringify(node)\n if ((counts.get(key) ?? 0) >= 2) {\n let name = nameByKey.get(key)\n if (!name) {\n name = `shared_${nameByKey.size}`\n nameByKey.set(key, name)\n sharedEntries[name] = node\n }\n return { $ref: `#/$defs/${name}` }\n }\n }\n if (Array.isArray(node)) {\n return node.map(share)\n }\n if (node && typeof node === 'object') {\n return Object.fromEntries(\n Object.entries(node).map(([childKey, value]) => [childKey, share(value)]),\n )\n }\n return node\n }\n\n const result = share(schema) as JsonSchemaType\n result.$defs = { ...result.$defs, ...sharedEntries }\n return result\n}\n\n/**\n * **LLM ergonomics.** Renames `$defs` entries to short, readable names so the `$ref`s stay legible to the model: a block's\n * `blockType` (`Code`), a node's `type` (`paragraph`), `node` for a rich-text node union, otherwise the\n * generated name with its disambiguating hash dropped. A numeric suffix keeps collisions unique.\n *\n * @example\n * { properties: { body: { $ref: '#/$defs/LexicalNodes_9FBEC708' } }, $defs: { LexicalNodes_9FBEC708: {} } }\n * → { properties: { body: { $ref: '#/$defs/node' } }, $defs: { node: {} } }\n */\nconst shortenDefinitionNames = (schema: JsonSchemaType): JsonSchemaType => {\n const definitions = schema.$defs\n if (!definitions || Object.keys(definitions).length === 0) {\n return schema\n }\n\n const shortNameFor = (name: string, definition: boolean | JsonSchemaType): string => {\n const properties = (typeof definition === 'object' && definition.properties) || {}\n const constString = (key: string): string | undefined => {\n const prop = properties[key]\n return prop && typeof prop === 'object' && typeof prop.const === 'string'\n ? prop.const\n : undefined\n }\n const members =\n typeof definition === 'object' ? (definition.anyOf ?? definition.oneOf) : undefined\n const isNodeUnion =\n Array.isArray(members) &&\n members.some((m) => typeof m === 'object' && Boolean(m.$ref || m.properties?.type))\n return (\n constString('blockType') ??\n constString('type') ??\n (isNodeUnion ? 'node' : undefined) ??\n name.replace(/_[0-9A-F]{6,}$/i, '')\n )\n }\n\n const prefix = '#/$defs/'\n const usedNames = new Map<string, number>()\n const rename = new Map<string, string>()\n for (const [name, definition] of Object.entries(definitions)) {\n const shortName = shortNameFor(name, definition)\n const used = usedNames.get(shortName) ?? 0\n usedNames.set(shortName, used + 1)\n rename.set(name, used === 0 ? shortName : `${shortName}${used + 1}`)\n }\n\n const result = mapNodes(schema, (node) => {\n if (typeof node.$ref === 'string' && node.$ref.startsWith(prefix)) {\n const name = node.$ref.slice(prefix.length)\n node.$ref = `${prefix}${rename.get(name) ?? name}`\n }\n return node\n }) as JsonSchemaType\n result.$defs = Object.fromEntries(\n Object.entries(result.$defs!).map(([name, body]) => [rename.get(name) ?? name, body]),\n )\n return result\n}\n"],"names":["sanitizeEntitySchema","schema","result","structuredClone","collapseOptionalContainerTypes","pointFieldsToObjects","removeTypeGenArtifacts","dropRedundantConstType","mergeConstDiscriminatedUnions","deduplicateIntoDefinitions","shortenDefinitionNames","mapNodes","node","visit","Array","isArray","map","child","out","key","value","Object","entries","properties","keys","prop","isRequired","required","includes","collapseNullableType","items","type","nonNullTypes","filter","t","length","transformed","fromEntries","isArrayType","isPointField","every","item","isNullable","description","latitude","longitude","tsType","keyword","members","merged","mergeMembersByConst","assign","objects","member","discriminator","constValues","everyMemberPinsConst","push","const","fingerprintWithoutDiscriminator","_discriminator","otherProperties","JSON","stringify","Set","size","uniqueConstValues","discriminatorProp","enum","MIN_SHARED_SIZE","isShareable","oneOf","anyOf","Boolean","counts","Map","count","set","get","forEach","values","some","n","sharedEntries","nameByKey","share","name","$ref","childKey","$defs","definitions","shortNameFor","definition","constString","undefined","isNodeUnion","m","replace","prefix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;IAEA,MAAMpG,SAASS,SAASV,QAAQ,CAACW;QAC/B,IAAI,OAAOA,KAAK2E,IAAI,KAAK,YAAY3E,KAAK2E,IAAI,CAACgB,UAAU,CAACL,SAAS;YACjE,MAAMZ,OAAO1E,KAAK2E,IAAI,CAACiB,KAAK,CAACN,OAAO/D,MAAM;YAC1CvB,KAAK2E,IAAI,GAAG,GAAGW,SAASE,OAAOtB,GAAG,CAACQ,SAASA,MAAM;QACpD;QACA,OAAO1E;IACT;IACAV,OAAOuF,KAAK,GAAGpE,OAAOgB,WAAW,CAC/BhB,OAAOC,OAAO,CAACpB,OAAOuF,KAAK,EAAGzE,GAAG,CAAC,CAAC,CAACsE,MAAMmB,KAAK,GAAK;YAACL,OAAOtB,GAAG,CAACQ,SAASA;YAAMmB;SAAK;IAEtF,OAAOvG;AACT"}
@@ -1,133 +0,0 @@
1
- import { describe, expect, it } from 'vitest';
2
- import { sanitizeEntitySchema } from './sanitizeEntitySchema.js';
3
- describe('sanitizeEntitySchema', ()=>{
4
- it('renames the Lexical node-union definition to a short name and keeps it a strict oneOf', ()=>{
5
- // Shaped like the schema the MCP server prepares for a collection with a Lexical richText field
6
- // (Payload's `input` variant): a `$defs` node union (a `oneOf` of node shapes). The input variant
7
- // already types the relationship node's `value` as a bare ID - there is no populated-doc `$ref` to
8
- // reduce here (the variant did that upstream), so sanitize leaves the value untouched.
9
- const standalone = {
10
- type: 'object',
11
- $defs: {
12
- LexicalNodes_ABCDEF12: {
13
- oneOf: [
14
- {
15
- type: 'object',
16
- additionalProperties: false,
17
- properties: {
18
- type: {
19
- const: 'paragraph'
20
- }
21
- },
22
- required: [
23
- 'type'
24
- ]
25
- },
26
- {
27
- type: 'object',
28
- additionalProperties: false,
29
- properties: {
30
- type: {
31
- const: 'relationship'
32
- },
33
- value: {
34
- type: 'string',
35
- description: 'The related document ID.'
36
- }
37
- },
38
- required: [
39
- 'type'
40
- ]
41
- }
42
- ]
43
- }
44
- },
45
- properties: {
46
- id: {
47
- type: 'string'
48
- },
49
- content: {
50
- type: 'object',
51
- properties: {
52
- root: {
53
- type: 'object',
54
- properties: {
55
- children: {
56
- type: 'array',
57
- items: {
58
- $ref: '#/$defs/LexicalNodes_ABCDEF12'
59
- }
60
- }
61
- }
62
- }
63
- }
64
- }
65
- }
66
- };
67
- expect(sanitizeEntitySchema(standalone)).toStrictEqual({
68
- type: 'object',
69
- $defs: {
70
- // The node union is renamed to a short, readable `node`, and stays a strict discriminated
71
- // `oneOf` - not loosened to `anyOf`.
72
- node: {
73
- oneOf: [
74
- {
75
- type: 'object',
76
- additionalProperties: false,
77
- properties: {
78
- type: {
79
- const: 'paragraph'
80
- }
81
- },
82
- required: [
83
- 'type'
84
- ]
85
- },
86
- {
87
- type: 'object',
88
- additionalProperties: false,
89
- properties: {
90
- type: {
91
- const: 'relationship'
92
- },
93
- // The value is already ID-only from the input variant - left as-is.
94
- value: {
95
- type: 'string',
96
- description: 'The related document ID.'
97
- }
98
- },
99
- required: [
100
- 'type'
101
- ]
102
- }
103
- ]
104
- }
105
- },
106
- properties: {
107
- // Managed timestamps are excluded upstream by the `input` variant. `id` stays because it's
108
- // a valid optional input (a client may supply a custom ID).
109
- id: {
110
- type: 'string'
111
- },
112
- content: {
113
- type: 'object',
114
- properties: {
115
- root: {
116
- type: 'object',
117
- properties: {
118
- children: {
119
- type: 'array',
120
- items: {
121
- $ref: '#/$defs/node'
122
- }
123
- }
124
- }
125
- }
126
- }
127
- }
128
- }
129
- });
130
- });
131
- });
132
-
133
- //# sourceMappingURL=sanitizeEntitySchema.spec.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../src/utils/schemaConversion/sanitizeEntitySchema.spec.ts"],"sourcesContent":["import { describe, expect, it } from 'vitest'\n\nimport type { JsonSchemaType } from '../../types.js'\n\nimport { sanitizeEntitySchema } from './sanitizeEntitySchema.js'\n\ndescribe('sanitizeEntitySchema', () => {\n it('renames the Lexical node-union definition to a short name and keeps it a strict oneOf', () => {\n // Shaped like the schema the MCP server prepares for a collection with a Lexical richText field\n // (Payload's `input` variant): a `$defs` node union (a `oneOf` of node shapes). The input variant\n // already types the relationship node's `value` as a bare ID - there is no populated-doc `$ref` to\n // reduce here (the variant did that upstream), so sanitize leaves the value untouched.\n const standalone: JsonSchemaType = {\n type: 'object',\n $defs: {\n LexicalNodes_ABCDEF12: {\n oneOf: [\n {\n type: 'object',\n additionalProperties: false,\n properties: { type: { const: 'paragraph' } },\n required: ['type'],\n },\n {\n type: 'object',\n additionalProperties: false,\n properties: {\n type: { const: 'relationship' },\n value: { type: 'string', description: 'The related document ID.' },\n },\n required: ['type'],\n },\n ],\n },\n },\n properties: {\n id: { type: 'string' },\n content: {\n type: 'object',\n properties: {\n root: {\n type: 'object',\n properties: {\n children: { type: 'array', items: { $ref: '#/$defs/LexicalNodes_ABCDEF12' } },\n },\n },\n },\n },\n },\n }\n\n expect(sanitizeEntitySchema(standalone)).toStrictEqual({\n type: 'object',\n $defs: {\n // The node union is renamed to a short, readable `node`, and stays a strict discriminated\n // `oneOf` - not loosened to `anyOf`.\n node: {\n oneOf: [\n {\n type: 'object',\n additionalProperties: false,\n properties: { type: { const: 'paragraph' } },\n required: ['type'],\n },\n {\n type: 'object',\n additionalProperties: false,\n properties: {\n type: { const: 'relationship' },\n // The value is already ID-only from the input variant - left as-is.\n value: { type: 'string', description: 'The related document ID.' },\n },\n required: ['type'],\n },\n ],\n },\n },\n properties: {\n // Managed timestamps are excluded upstream by the `input` variant. `id` stays because it's\n // a valid optional input (a client may supply a custom ID).\n id: { type: 'string' },\n content: {\n type: 'object',\n properties: {\n root: {\n type: 'object',\n properties: {\n children: { type: 'array', items: { $ref: '#/$defs/node' } },\n },\n },\n },\n },\n },\n })\n })\n})\n"],"names":["describe","expect","it","sanitizeEntitySchema","standalone","type","$defs","LexicalNodes_ABCDEF12","oneOf","additionalProperties","properties","const","required","value","description","id","content","root","children","items","$ref","toStrictEqual","node"],"mappings":"AAAA,SAASA,QAAQ,EAAEC,MAAM,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F,UAAU;gCAAC;6BAAO;wBACpB;qBACD;gBACH;YACF;YACAF,YAAY;gBACV,2FAA2F;gBAC3F,4DAA4D;gBAC5DK,IAAI;oBAAEV,MAAM;gBAAS;gBACrBW,SAAS;oBACPX,MAAM;oBACNK,YAAY;wBACVO,MAAM;4BACJZ,MAAM;4BACNK,YAAY;gCACVQ,UAAU;oCAAEb,MAAM;oCAASc,OAAO;wCAAEC,MAAM;oCAAe;gCAAE;4BAC7D;wBACF;oBACF;gBACF;YACF;QACF;IACF;AACF"}
@@ -1,7 +0,0 @@
1
- /**
2
- * Transforms incoming MCP tool data from object format to tuple array format.
3
- * Converts { longitude: number, latitude: number } back to [longitude, latitude]
4
- * for Payload's internal point field representation.
5
- */
6
- export declare function transformPointDataToPayload(data: Record<string, unknown>): Record<string, unknown>;
7
- //# sourceMappingURL=transformPointDataToPayload.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"transformPointDataToPayload.d.ts","sourceRoot":"","sources":["../../src/utils/transformPointDataToPayload.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,wBAAgB,2BAA2B,CACzC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC5B,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAgCzB"}
@@ -1,28 +0,0 @@
1
- /**
2
- * Transforms incoming MCP tool data from object format to tuple array format.
3
- * Converts { longitude: number, latitude: number } back to [longitude, latitude]
4
- * for Payload's internal point field representation.
5
- */ export function transformPointDataToPayload(data) {
6
- if (!data || typeof data !== 'object') {
7
- return data;
8
- }
9
- const transformed = {};
10
- for (const [key, value] of Object.entries(data)){
11
- if (value && typeof value === 'object' && 'longitude' in value && 'latitude' in value && typeof value.longitude === 'number' && typeof value.latitude === 'number') {
12
- // Transform to tuple array [longitude, latitude]
13
- transformed[key] = [
14
- value.longitude,
15
- value.latitude
16
- ];
17
- } else if (Array.isArray(value)) {
18
- transformed[key] = value.map((item)=>typeof item === 'object' ? transformPointDataToPayload(item) : item);
19
- } else if (value && typeof value === 'object') {
20
- transformed[key] = transformPointDataToPayload(value);
21
- } else {
22
- transformed[key] = value;
23
- }
24
- }
25
- return transformed;
26
- }
27
-
28
- //# sourceMappingURL=transformPointDataToPayload.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/utils/transformPointDataToPayload.ts"],"sourcesContent":["/**\n * Transforms incoming MCP tool data from object format to tuple array format.\n * Converts { longitude: number, latitude: number } back to [longitude, latitude]\n * for Payload's internal point field representation.\n */\nexport function transformPointDataToPayload(\n data: Record<string, unknown>,\n): Record<string, unknown> {\n if (!data || typeof data !== 'object') {\n return data\n }\n\n const transformed: Record<string, unknown> = {}\n\n for (const [key, value] of Object.entries(data)) {\n if (\n value &&\n typeof value === 'object' &&\n 'longitude' in value &&\n 'latitude' in value &&\n typeof value.longitude === 'number' &&\n typeof value.latitude === 'number'\n ) {\n // Transform to tuple array [longitude, latitude]\n transformed[key] = [value.longitude, value.latitude]\n } else if (Array.isArray(value)) {\n transformed[key] = value.map((item) =>\n typeof item === 'object'\n ? transformPointDataToPayload(item as Record<string, unknown>)\n : item,\n )\n } else if (value && typeof value === 'object') {\n transformed[key] = transformPointDataToPayload(value as Record<string, unknown>)\n } else {\n transformed[key] = value\n }\n }\n\n return transformed\n}\n"],"names":["transformPointDataToPayload","data","transformed","key","value","Object","entries","longitude","latitude","Array","isArray","map","item"],"mappings":"AAAA;;;;CAIC,GACD,OAAO,SAASA,4BACdC,IAA6B;IAE7B,IAAI,CAACA,QAAQ,OAAOA,SAAS,UAAU;QACrC,OAAOA;IACT;IAEA,MAAMC,cAAuC,CAAC;IAE9C,KAAK,MAAM,CAACC,KAAKC,MAAM,IAAIC,OAAOC,OAAO,CAACL,MAAO;QAC/C,IACEG,SACA,OAAOA,UAAU,YACjB,eAAeA,SACf,cAAcA,SACd,OAAOA,MAAMG,SAAS,KAAK,YAC3B,OAAOH,MAAMI,QAAQ,KAAK,UAC1B;YACA,iDAAiD;YACjDN,WAAW,CAACC,IAAI,GAAG;gBAACC,MAAMG,SAAS;gBAAEH,MAAMI,QAAQ;aAAC;QACtD,OAAO,IAAIC,MAAMC,OAAO,CAACN,QAAQ;YAC/BF,WAAW,CAACC,IAAI,GAAGC,MAAMO,GAAG,CAAC,CAACC,OAC5B,OAAOA,SAAS,WACZZ,4BAA4BY,QAC5BA;QAER,OAAO,IAAIR,SAAS,OAAOA,UAAU,UAAU;YAC7CF,WAAW,CAACC,IAAI,GAAGH,4BAA4BI;QACjD,OAAO;YACLF,WAAW,CAACC,IAAI,GAAGC;QACrB;IACF;IAEA,OAAOF;AACT"}
@@ -1,9 +0,0 @@
1
- import type { Where } from 'payload';
2
- import { z } from 'zod';
3
- /**
4
- * - Validates the `where` input of collection tools against Payload's `Where` shape
5
- * - Field keys map to operator objects restricted to `validOperators`
6
- * - `and` / `or` nest recursively
7
- */
8
- export declare const whereSchema: z.ZodType<Where>;
9
- //# sourceMappingURL=whereSchema.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"whereSchema.d.ts","sourceRoot":"","sources":["../../src/utils/whereSchema.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAGpC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAMvB;;;;GAIG;AACH,eAAO,MAAM,WAAW,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,CASqD,CAAA"}
@@ -1,13 +0,0 @@
1
- import { validOperators } from 'payload/shared';
2
- import { z } from 'zod';
3
- const whereFieldSchema = z.partialRecord(z.enum(validOperators), z.unknown()).describe('Field query operators');
4
- /**
5
- * - Validates the `where` input of collection tools against Payload's `Where` shape
6
- * - Field keys map to operator objects restricted to `validOperators`
7
- * - `and` / `or` nest recursively
8
- */ export const whereSchema = z.lazy(()=>z.object({
9
- and: z.array(whereSchema).optional(),
10
- or: z.array(whereSchema).optional()
11
- }).catchall(whereFieldSchema)).describe('Where clause using field names with Payload query operators, plus and/or groups');
12
-
13
- //# sourceMappingURL=whereSchema.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/utils/whereSchema.ts"],"sourcesContent":["import type { Where } from 'payload'\n\nimport { validOperators } from 'payload/shared'\nimport { z } from 'zod'\n\nconst whereFieldSchema = z\n .partialRecord(z.enum(validOperators), z.unknown())\n .describe('Field query operators')\n\n/**\n * - Validates the `where` input of collection tools against Payload's `Where` shape\n * - Field keys map to operator objects restricted to `validOperators`\n * - `and` / `or` nest recursively\n */\nexport const whereSchema: z.ZodType<Where> = z\n .lazy(() =>\n z\n .object({\n and: z.array(whereSchema).optional(),\n or: z.array(whereSchema).optional(),\n })\n .catchall(whereFieldSchema),\n )\n .describe('Where clause using field names with Payload query operators, plus and/or groups')\n"],"names":["validOperators","z","whereFieldSchema","partialRecord","enum","unknown","describe","whereSchema","lazy","object","and","array","optional","or","catchall"],"mappings":"AAEA,SAASA,cAAc,QAAQ,iBAAgB;AAC/C,SAASC,CAAC,QAAQ,MAAK;AAEvB,MAAMC,mBAAmBD,EACtBE,aAAa,CAACF,EAAEG,IAAI,CAACJ,iBAAiBC,EAAEI,OAAO,IAC/CC,QAAQ,CAAC;AAEZ;;;;CAIC,GACD,OAAO,MAAMC,cAAgCN,EAC1CO,IAAI,CAAC,IACJP,EACGQ,MAAM,CAAC;QACNC,KAAKT,EAAEU,KAAK,CAACJ,aAAaK,QAAQ;QAClCC,IAAIZ,EAAEU,KAAK,CAACJ,aAAaK,QAAQ;IACnC,GACCE,QAAQ,CAACZ,mBAEbI,QAAQ,CAAC,mFAAkF"}
@@ -1,84 +0,0 @@
1
- import type { CollectionSlug, PayloadRequest } from 'payload'
2
-
3
- import type { MCPToolResponse } from '../../../types.js'
4
-
5
- import { getCollectionInputSchema } from '../../../utils/schemaConversion/getEntityInputSchema.js'
6
-
7
- const getValidationErrors = (error: unknown): undefined | unknown[] => {
8
- if (!error || typeof error !== 'object') {
9
- return undefined
10
- }
11
-
12
- const data = 'data' in error ? error.data : undefined
13
- if (!data || typeof data !== 'object' || !('errors' in data) || !Array.isArray(data.errors)) {
14
- return undefined
15
- }
16
-
17
- return data.errors
18
- }
19
-
20
- const isSchemaError = (error: unknown, message: string): boolean => {
21
- if (getValidationErrors(error)) {
22
- return true
23
- }
24
-
25
- const name = error && typeof error === 'object' && 'name' in error ? error.name : undefined
26
-
27
- return (
28
- name === 'CastError' ||
29
- name === 'ValidationError' ||
30
- message.includes('Cast to ') ||
31
- message.includes('validation failed')
32
- )
33
- }
34
-
35
- export const formatCollectionError = ({
36
- action,
37
- collectionSlug,
38
- error,
39
- req,
40
- }: {
41
- action: 'creating' | 'duplicating' | 'updating'
42
- collectionSlug: CollectionSlug
43
- error: unknown
44
- req: PayloadRequest
45
- }): MCPToolResponse => {
46
- const errorMessage = error instanceof Error ? error.message : 'Unknown error'
47
- const errors = getValidationErrors(error) ?? [{ message: errorMessage }]
48
-
49
- if (!isSchemaError(error, errorMessage)) {
50
- return {
51
- content: [
52
- {
53
- type: 'text',
54
- text: `Error ${action} document in collection "${collectionSlug}": ${errorMessage}`,
55
- },
56
- ],
57
- isError: true,
58
- }
59
- }
60
-
61
- const schema = getCollectionInputSchema({ collectionSlug, req })
62
- const schemaText = schema
63
- ? `\n\nUse this schema for data:\n\`\`\`json\n${JSON.stringify(schema)}\n\`\`\``
64
- : ''
65
-
66
- return {
67
- content: [
68
- {
69
- type: 'text',
70
- text: `Error ${action} document in collection "${collectionSlug}": ${errorMessage}${schemaText}`,
71
- },
72
- ],
73
- isError: true,
74
- ...(schema
75
- ? {
76
- structuredContent: {
77
- collectionSlug,
78
- errors,
79
- schema,
80
- },
81
- }
82
- : {}),
83
- }
84
- }
@@ -1,132 +0,0 @@
1
- import type { CollectionSlug, GlobalSlug, PayloadRequest, SanitizedConfig } from 'payload'
2
-
3
- import { CfWorkerJsonSchemaValidator } from '@modelcontextprotocol/server/validators/cf-worker'
4
-
5
- import type { JsonSchemaType, MCPToolResponse } from '../../types.js'
6
-
7
- import {
8
- getCollectionInputSchema,
9
- getGlobalInputSchema,
10
- } from '../../utils/schemaConversion/getEntityInputSchema.js'
11
-
12
- /**
13
- * Keep the default `shortcircuit: true` - `false` makes validating nested rich text exponentially slow.
14
- */
15
- const validator = new CfWorkerJsonSchemaValidator({ shortcircuit: true })
16
-
17
- type EntityValidator = {
18
- schema: JsonSchemaType
19
- validate: ReturnType<(typeof validator)['getValidator']>
20
- }
21
-
22
- /**
23
- * - Caches each entity's schema and validator, so both are only built on the first request.
24
- * - Keyed by payload config, then by entity type, slug, partial and language.
25
- */
26
- const validatorCache = new WeakMap<SanitizedConfig, Map<string, EntityValidator>>()
27
-
28
- export const validateCollectionData = ({
29
- collectionSlug,
30
- data,
31
- partial,
32
- req,
33
- }: {
34
- collectionSlug: CollectionSlug
35
- data: Record<string, unknown>
36
- partial?: boolean
37
- req: PayloadRequest
38
- }): MCPToolResponse | null =>
39
- validateData({
40
- slug: collectionSlug,
41
- buildSchema: () => getCollectionInputSchema({ collectionSlug, req }),
42
- data,
43
- entity: 'collection',
44
- partial,
45
- req,
46
- })
47
-
48
- export const validateGlobalData = ({
49
- data,
50
- globalSlug,
51
- req,
52
- }: {
53
- data: Record<string, unknown>
54
- globalSlug: GlobalSlug
55
- req: PayloadRequest
56
- }): MCPToolResponse | null =>
57
- validateData({
58
- slug: globalSlug,
59
- buildSchema: () => getGlobalInputSchema({ globalSlug, req }),
60
- data,
61
- entity: 'global',
62
- partial: true,
63
- req,
64
- })
65
-
66
- const validateData = ({
67
- slug,
68
- buildSchema,
69
- data,
70
- entity,
71
- partial,
72
- req,
73
- }: {
74
- buildSchema: () => JsonSchemaType | null
75
- data: Record<string, unknown>
76
- entity: 'collection' | 'global'
77
- partial?: boolean
78
- req: PayloadRequest
79
- slug: string
80
- }): MCPToolResponse | null => {
81
- let cache = validatorCache.get(req.payload.config)
82
- if (!cache) {
83
- cache = new Map()
84
- validatorCache.set(req.payload.config, cache)
85
- }
86
-
87
- const cacheKey = `${entity}:${slug}:${partial ? 'partial' : 'full'}:${req.i18n.language}`
88
- let entityValidator = cache.get(cacheKey)
89
-
90
- if (!entityValidator) {
91
- const schema = buildSchema()
92
-
93
- if (!schema) {
94
- return null
95
- }
96
-
97
- entityValidator = {
98
- schema,
99
- validate: validator.getValidator(partial ? withoutRequired(schema) : schema),
100
- }
101
- cache.set(cacheKey, entityValidator)
102
- }
103
-
104
- const result = entityValidator.validate(data)
105
-
106
- if (result.valid) {
107
- return null
108
- }
109
-
110
- const { schema } = entityValidator
111
-
112
- return {
113
- content: [
114
- {
115
- type: 'text',
116
- text: `Invalid data for ${entity} "${slug}": ${result.errorMessage}\n\nUse this schema for data:\n\`\`\`json\n${JSON.stringify(schema)}\n\`\`\``,
117
- },
118
- ],
119
- isError: true,
120
- structuredContent: {
121
- [`${entity}Slug`]: slug,
122
- errors: [{ message: result.errorMessage }],
123
- schema,
124
- },
125
- }
126
- }
127
-
128
- /** Updates are partial — drop the schema's top-level `required` before validating. */
129
- const withoutRequired = (schema: JsonSchemaType): JsonSchemaType => {
130
- const { required: _required, ...rest } = schema
131
- return rest
132
- }
@@ -1,53 +0,0 @@
1
- import type { SanitizedConfig } from 'payload'
2
-
3
- import { fieldIsVirtual } from 'payload/shared'
4
-
5
- /**
6
- * Returns the names of all top-level virtual fields for a given collection slug.
7
- */
8
- export function getCollectionVirtualFieldNames(config: SanitizedConfig, slug: string): string[] {
9
- const collection = config.collections.find((c) => c.slug === slug)
10
-
11
- if (!collection) {
12
- return []
13
- }
14
-
15
- return collection.flattenedFields
16
- .filter((field) => 'name' in field && fieldIsVirtual(field))
17
- .map((field) => (field as { name: string }).name)
18
- }
19
-
20
- /**
21
- * Returns the names of all top-level virtual fields for a given global slug.
22
- */
23
- export function getGlobalVirtualFieldNames(config: SanitizedConfig, slug: string): string[] {
24
- const global = config.globals.find((g) => g.slug === slug)
25
-
26
- if (!global) {
27
- return []
28
- }
29
-
30
- return global.flattenedFields
31
- .filter((field) => 'name' in field && fieldIsVirtual(field))
32
- .map((field) => (field as { name: string }).name)
33
- }
34
-
35
- /**
36
- * Strips virtual field values from a data object given a list of virtual field names.
37
- */
38
- export function stripVirtualFields(
39
- data: Record<string, unknown>,
40
- virtualFieldNames: string[],
41
- ): Record<string, unknown> {
42
- if (virtualFieldNames.length === 0) {
43
- return data
44
- }
45
-
46
- const stripped = { ...data }
47
-
48
- for (const name of virtualFieldNames) {
49
- delete stripped[name]
50
- }
51
-
52
- return stripped
53
- }