@payloadcms/plugin-mcp 4.0.0-internal.a0ef1b8 → 4.0.0-internal.a6582c6

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 (250) hide show
  1. package/LICENSE.md +1 -1
  2. package/bin.js +7 -0
  3. package/dist/defaultAccess.d.ts +3 -0
  4. package/dist/defaultAccess.d.ts.map +1 -0
  5. package/dist/defaultAccess.js +3 -0
  6. package/dist/defaultAccess.js.map +1 -0
  7. package/dist/defineTool.d.ts +8 -8
  8. package/dist/defineTool.d.ts.map +1 -1
  9. package/dist/endpoint/access.d.ts +12 -5
  10. package/dist/endpoint/access.d.ts.map +1 -1
  11. package/dist/endpoint/access.js +75 -88
  12. package/dist/endpoint/access.js.map +1 -1
  13. package/dist/endpoint/index.d.ts +1 -1
  14. package/dist/endpoint/index.d.ts.map +1 -1
  15. package/dist/endpoint/index.js +68 -17
  16. package/dist/endpoint/index.js.map +1 -1
  17. package/dist/exports/client.d.ts +1 -1
  18. package/dist/exports/client.d.ts.map +1 -1
  19. package/dist/exports/client.js +1 -1
  20. package/dist/exports/client.js.map +1 -1
  21. package/dist/exports/internal.d.ts +2 -0
  22. package/dist/exports/internal.d.ts.map +1 -0
  23. package/dist/exports/internal.js +3 -0
  24. package/dist/exports/internal.js.map +1 -0
  25. package/dist/index.d.ts +2 -2
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +15 -20
  28. package/dist/index.js.map +1 -1
  29. package/dist/mcp/buildMcpServer.d.ts +4 -4
  30. package/dist/mcp/buildMcpServer.d.ts.map +1 -1
  31. package/dist/mcp/buildMcpServer.js +133 -80
  32. package/dist/mcp/buildMcpServer.js.map +1 -1
  33. package/dist/mcp/builtin/collections/authTools.d.ts.map +1 -1
  34. package/dist/mcp/builtin/collections/authTools.js +44 -6
  35. package/dist/mcp/builtin/collections/authTools.js.map +1 -1
  36. package/dist/mcp/builtin/collections/countTool.d.ts +2 -0
  37. package/dist/mcp/builtin/collections/countTool.d.ts.map +1 -0
  38. package/dist/mcp/builtin/collections/countTool.js +68 -0
  39. package/dist/mcp/builtin/collections/countTool.js.map +1 -0
  40. package/dist/mcp/builtin/collections/countVersionsTool.d.ts +2 -0
  41. package/dist/mcp/builtin/collections/countVersionsTool.d.ts.map +1 -0
  42. package/dist/mcp/builtin/collections/countVersionsTool.js +64 -0
  43. package/dist/mcp/builtin/collections/countVersionsTool.js.map +1 -0
  44. package/dist/mcp/builtin/collections/createTool.d.ts +1 -1
  45. package/dist/mcp/builtin/collections/createTool.d.ts.map +1 -1
  46. package/dist/mcp/builtin/collections/createTool.js +110 -63
  47. package/dist/mcp/builtin/collections/createTool.js.map +1 -1
  48. package/dist/mcp/builtin/collections/deleteTool.d.ts +1 -1
  49. package/dist/mcp/builtin/collections/deleteTool.d.ts.map +1 -1
  50. package/dist/mcp/builtin/collections/deleteTool.js +15 -22
  51. package/dist/mcp/builtin/collections/deleteTool.js.map +1 -1
  52. package/dist/mcp/builtin/collections/duplicateTool.d.ts +2 -0
  53. package/dist/mcp/builtin/collections/duplicateTool.d.ts.map +1 -0
  54. package/dist/mcp/builtin/collections/duplicateTool.js +96 -0
  55. package/dist/mcp/builtin/collections/duplicateTool.js.map +1 -0
  56. package/dist/mcp/builtin/collections/fileInput.d.ts +28 -0
  57. package/dist/mcp/builtin/collections/fileInput.d.ts.map +1 -0
  58. package/dist/mcp/builtin/collections/fileInput.js +124 -0
  59. package/dist/mcp/builtin/collections/fileInput.js.map +1 -0
  60. package/dist/mcp/builtin/collections/fileInput.spec.js +86 -0
  61. package/dist/mcp/builtin/collections/fileInput.spec.js.map +1 -0
  62. package/dist/mcp/builtin/collections/findDistinctTool.d.ts +2 -0
  63. package/dist/mcp/builtin/collections/findDistinctTool.d.ts.map +1 -0
  64. package/dist/mcp/builtin/collections/findDistinctTool.js +92 -0
  65. package/dist/mcp/builtin/collections/findDistinctTool.js.map +1 -0
  66. package/dist/mcp/builtin/collections/findTool.d.ts +1 -1
  67. package/dist/mcp/builtin/collections/findTool.d.ts.map +1 -1
  68. package/dist/mcp/builtin/collections/findTool.js +52 -47
  69. package/dist/mcp/builtin/collections/findTool.js.map +1 -1
  70. package/dist/mcp/builtin/collections/findVersionByIDTool.d.ts +2 -0
  71. package/dist/mcp/builtin/collections/findVersionByIDTool.d.ts.map +1 -0
  72. package/dist/mcp/builtin/collections/findVersionByIDTool.js +83 -0
  73. package/dist/mcp/builtin/collections/findVersionByIDTool.js.map +1 -0
  74. package/dist/mcp/builtin/collections/findVersionsTool.d.ts +2 -0
  75. package/dist/mcp/builtin/collections/findVersionsTool.d.ts.map +1 -0
  76. package/dist/mcp/builtin/collections/findVersionsTool.js +98 -0
  77. package/dist/mcp/builtin/collections/findVersionsTool.js.map +1 -0
  78. package/dist/mcp/builtin/collections/formatCollectionError.d.ts +9 -0
  79. package/dist/mcp/builtin/collections/formatCollectionError.d.ts.map +1 -0
  80. package/dist/mcp/builtin/collections/formatCollectionError.js +60 -0
  81. package/dist/mcp/builtin/collections/formatCollectionError.js.map +1 -0
  82. package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts +2 -0
  83. package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -0
  84. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +87 -0
  85. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -0
  86. package/dist/mcp/builtin/collections/restoreVersionTool.d.ts +2 -0
  87. package/dist/mcp/builtin/collections/restoreVersionTool.d.ts.map +1 -0
  88. package/dist/mcp/builtin/collections/restoreVersionTool.js +81 -0
  89. package/dist/mcp/builtin/collections/restoreVersionTool.js.map +1 -0
  90. package/dist/mcp/builtin/collections/updateTool.d.ts +1 -1
  91. package/dist/mcp/builtin/collections/updateTool.d.ts.map +1 -1
  92. package/dist/mcp/builtin/collections/updateTool.js +106 -93
  93. package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
  94. package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts +2 -0
  95. package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts.map +1 -0
  96. package/dist/mcp/builtin/collections/uploadInstructionsTool.js +55 -0
  97. package/dist/mcp/builtin/collections/uploadInstructionsTool.js.map +1 -0
  98. package/dist/mcp/builtin/getConfigInfoTool.d.ts +2 -0
  99. package/dist/mcp/builtin/getConfigInfoTool.d.ts.map +1 -0
  100. package/dist/mcp/builtin/getConfigInfoTool.js +68 -0
  101. package/dist/mcp/builtin/getConfigInfoTool.js.map +1 -0
  102. package/dist/mcp/builtin/globals/countVersionsTool.d.ts +2 -0
  103. package/dist/mcp/builtin/globals/countVersionsTool.d.ts.map +1 -0
  104. package/dist/mcp/builtin/globals/countVersionsTool.js +64 -0
  105. package/dist/mcp/builtin/globals/countVersionsTool.js.map +1 -0
  106. package/dist/mcp/builtin/globals/findTool.d.ts.map +1 -1
  107. package/dist/mcp/builtin/globals/findTool.js +20 -23
  108. package/dist/mcp/builtin/globals/findTool.js.map +1 -1
  109. package/dist/mcp/builtin/globals/findVersionByIDTool.d.ts +2 -0
  110. package/dist/mcp/builtin/globals/findVersionByIDTool.d.ts.map +1 -0
  111. package/dist/mcp/builtin/globals/findVersionByIDTool.js +79 -0
  112. package/dist/mcp/builtin/globals/findVersionByIDTool.js.map +1 -0
  113. package/dist/mcp/builtin/globals/findVersionsTool.d.ts +2 -0
  114. package/dist/mcp/builtin/globals/findVersionsTool.d.ts.map +1 -0
  115. package/dist/mcp/builtin/globals/findVersionsTool.js +94 -0
  116. package/dist/mcp/builtin/globals/findVersionsTool.js.map +1 -0
  117. package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts +2 -0
  118. package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts.map +1 -0
  119. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js +65 -0
  120. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js.map +1 -0
  121. package/dist/mcp/builtin/globals/restoreVersionTool.d.ts +2 -0
  122. package/dist/mcp/builtin/globals/restoreVersionTool.d.ts.map +1 -0
  123. package/dist/mcp/builtin/globals/restoreVersionTool.js +77 -0
  124. package/dist/mcp/builtin/globals/restoreVersionTool.js.map +1 -0
  125. package/dist/mcp/builtin/globals/updateTool.d.ts.map +1 -1
  126. package/dist/mcp/builtin/globals/updateTool.js +33 -42
  127. package/dist/mcp/builtin/globals/updateTool.js.map +1 -1
  128. package/dist/mcp/builtin/validateEntityData.d.ts +14 -0
  129. package/dist/mcp/builtin/validateEntityData.d.ts.map +1 -0
  130. package/dist/mcp/builtin/validateEntityData.js +82 -0
  131. package/dist/mcp/builtin/validateEntityData.js.map +1 -0
  132. package/dist/mcp/builtinTools.d.ts +150 -19
  133. package/dist/mcp/builtinTools.d.ts.map +1 -1
  134. package/dist/mcp/builtinTools.js +125 -20
  135. package/dist/mcp/builtinTools.js.map +1 -1
  136. package/dist/mcp/sanitizeMCPConfig.d.ts +0 -1
  137. package/dist/mcp/sanitizeMCPConfig.d.ts.map +1 -1
  138. package/dist/mcp/sanitizeMCPConfig.js +124 -58
  139. package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
  140. package/dist/stdio.d.ts +3 -3
  141. package/dist/stdio.d.ts.map +1 -1
  142. package/dist/stdio.js +84 -46
  143. package/dist/stdio.js.map +1 -1
  144. package/dist/types.d.ts +112 -110
  145. package/dist/types.d.ts.map +1 -1
  146. package/dist/types.js +2 -4
  147. package/dist/types.js.map +1 -1
  148. package/dist/utils/camelCase.d.ts.map +1 -1
  149. package/dist/utils/getPluginConfig.d.ts +1 -1
  150. package/dist/utils/getPluginConfig.js +1 -1
  151. package/dist/utils/getPluginConfig.js.map +1 -1
  152. package/dist/utils/resolveProjectRoot.d.ts.map +1 -1
  153. package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts +28 -0
  154. package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts.map +1 -0
  155. package/dist/utils/schemaConversion/filterFieldsByAccess.js +71 -0
  156. package/dist/utils/schemaConversion/filterFieldsByAccess.js.map +1 -0
  157. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts +13 -0
  158. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts.map +1 -0
  159. package/dist/utils/schemaConversion/getEntityInputSchema.js +66 -0
  160. package/dist/utils/schemaConversion/getEntityInputSchema.js.map +1 -0
  161. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts +5 -10
  162. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts.map +1 -1
  163. package/dist/utils/schemaConversion/sanitizeEntitySchema.js +15 -95
  164. package/dist/utils/schemaConversion/sanitizeEntitySchema.js.map +1 -1
  165. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js +15 -40
  166. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js.map +1 -1
  167. package/dist/utils/toStandardSchema.d.ts.map +1 -1
  168. package/dist/utils/whereSchema.d.ts +9 -0
  169. package/dist/utils/whereSchema.d.ts.map +1 -0
  170. package/dist/utils/whereSchema.js +13 -0
  171. package/dist/utils/whereSchema.js.map +1 -0
  172. package/package.json +10 -15
  173. package/src/defaultAccess.ts +3 -0
  174. package/src/endpoint/access.ts +81 -101
  175. package/src/endpoint/index.ts +58 -16
  176. package/src/exports/client.ts +2 -1
  177. package/src/exports/internal.ts +1 -0
  178. package/src/index.ts +12 -20
  179. package/src/mcp/buildMcpServer.ts +170 -115
  180. package/src/mcp/builtin/collections/authTools.ts +45 -9
  181. package/src/mcp/builtin/collections/countTool.ts +73 -0
  182. package/src/mcp/builtin/collections/countVersionsTool.ts +69 -0
  183. package/src/mcp/builtin/collections/createTool.ts +130 -78
  184. package/src/mcp/builtin/collections/deleteTool.ts +20 -18
  185. package/src/mcp/builtin/collections/duplicateTool.ts +134 -0
  186. package/src/mcp/builtin/collections/fileInput.spec.ts +93 -0
  187. package/src/mcp/builtin/collections/fileInput.ts +164 -0
  188. package/src/mcp/builtin/collections/findDistinctTool.ts +119 -0
  189. package/src/mcp/builtin/collections/findTool.ts +66 -37
  190. package/src/mcp/builtin/collections/findVersionByIDTool.ts +109 -0
  191. package/src/mcp/builtin/collections/findVersionsTool.ts +154 -0
  192. package/src/mcp/builtin/collections/formatCollectionError.ts +84 -0
  193. package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +80 -0
  194. package/src/mcp/builtin/collections/restoreVersionTool.ts +107 -0
  195. package/src/mcp/builtin/collections/updateTool.ts +132 -115
  196. package/src/mcp/builtin/collections/uploadInstructionsTool.ts +64 -0
  197. package/src/mcp/builtin/getConfigInfoTool.ts +67 -0
  198. package/src/mcp/builtin/globals/countVersionsTool.ts +68 -0
  199. package/src/mcp/builtin/globals/findTool.ts +28 -19
  200. package/src/mcp/builtin/globals/findVersionByIDTool.ts +103 -0
  201. package/src/mcp/builtin/globals/findVersionsTool.ts +147 -0
  202. package/src/mcp/builtin/globals/getGlobalSchemaTool.ts +63 -0
  203. package/src/mcp/builtin/globals/restoreVersionTool.ts +99 -0
  204. package/src/mcp/builtin/globals/updateTool.ts +52 -57
  205. package/src/mcp/builtin/validateEntityData.ts +132 -0
  206. package/src/mcp/builtinTools.ts +118 -41
  207. package/src/mcp/sanitizeMCPConfig.ts +120 -78
  208. package/src/stdio.ts +79 -46
  209. package/src/types.ts +128 -115
  210. package/src/utils/getPluginConfig.ts +1 -1
  211. package/src/utils/schemaConversion/filterFieldsByAccess.ts +123 -0
  212. package/src/utils/schemaConversion/getEntityInputSchema.ts +96 -0
  213. package/src/utils/schemaConversion/sanitizeEntitySchema.spec.ts +12 -19
  214. package/src/utils/schemaConversion/sanitizeEntitySchema.ts +17 -114
  215. package/src/utils/whereSchema.ts +24 -0
  216. package/dist/@types/assets.d.js +0 -2
  217. package/dist/@types/assets.d.js.map +0 -1
  218. package/dist/collection/getAccessField.d.ts +0 -12
  219. package/dist/collection/getAccessField.d.ts.map +0 -1
  220. package/dist/collection/getAccessField.js +0 -57
  221. package/dist/collection/getAccessField.js.map +0 -1
  222. package/dist/collection/index.d.ts +0 -6
  223. package/dist/collection/index.d.ts.map +0 -1
  224. package/dist/collection/index.js +0 -60
  225. package/dist/collection/index.js.map +0 -1
  226. package/dist/components/AccessField/index.client.d.ts +0 -10
  227. package/dist/components/AccessField/index.client.d.ts.map +0 -1
  228. package/dist/components/AccessField/index.client.js +0 -305
  229. package/dist/components/AccessField/index.client.js.map +0 -1
  230. package/dist/components/AccessField/index.css +0 -93
  231. package/dist/utils/localAPIDefaults.d.ts +0 -20
  232. package/dist/utils/localAPIDefaults.d.ts.map +0 -1
  233. package/dist/utils/localAPIDefaults.js +0 -19
  234. package/dist/utils/localAPIDefaults.js.map +0 -1
  235. package/dist/utils/schemaConversion/buildToolInput.d.ts +0 -29
  236. package/dist/utils/schemaConversion/buildToolInput.d.ts.map +0 -1
  237. package/dist/utils/schemaConversion/buildToolInput.js +0 -51
  238. package/dist/utils/schemaConversion/buildToolInput.js.map +0 -1
  239. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.d.ts +0 -7
  240. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.d.ts.map +0 -1
  241. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.js +0 -20
  242. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.js.map +0 -1
  243. package/src/@types/assets.d.ts +0 -3
  244. package/src/collection/getAccessField.ts +0 -64
  245. package/src/collection/index.ts +0 -64
  246. package/src/components/AccessField/index.client.tsx +0 -344
  247. package/src/components/AccessField/index.css +0 -93
  248. package/src/utils/localAPIDefaults.ts +0 -22
  249. package/src/utils/schemaConversion/buildToolInput.ts +0 -68
  250. package/src/utils/schemaConversion/removeVirtualFieldsFromSchema.ts +0 -27
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/utils/schemaConversion/sanitizeEntitySchema.ts"],"sourcesContent":["import type { JsonSchemaType } from '../../types.js'\n\n/**\n * Turns the JSON Schema that Payload generates for a collection or global into the input schema for\n * an MCP create/update tool. In short, it:\n *\n * - drops fields a client can't set (`id`, `createdAt`, the draft `_status`, …),\n * - rewrites Payload-specific field shapes (points, relationships) into plain JSON the model can fill,\n * - and shrinks the result so it's cheaper for the model to read,\n *\n * while keeping every node valid JSON Schema draft 2020-12. Each step below is tagged with why it runs -\n * **Correctness** (valid input the API accepts), **Size** (equivalence-preserving shrink), or **LLM\n * ergonomics** (easier for the model to read/fill) - and carries 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 // Correctness — drop the fields a client can't set (id, createdAt, updatedAt, draft _status) + collapse nullable types.\n result = removeManagedFields(result)\n\n // LLM ergonomics — rewrite point fields from a `[number, number]` tuple into a `{ longitude, latitude }` object.\n result = pointFieldsToObjects(result)\n\n // Correctness — a relationship value can be an ID or a populated doc; on input only the ID is valid, so keep that.\n result = relationshipsToIds(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 as JsonSchemaType)\n}\n\n// Payload sets these on every document, so an MCP client never provides them when creating/updating.\nconst PAYLOAD_MANAGED_FIELDS = new Set(['_status', 'createdAt', 'id', 'updatedAt'])\n\n/**\n * **Correctness.** Removes the fields a client can't set on create/update - `id`, `createdAt`, `updatedAt`, and the draft\n * `_status` - from every field object's `properties` and `required` (recursing into nested objects and\n * array items). Along the way it also collapses optional array/object types via {@link collapseNullableType}.\n *\n * @example\n * { properties: { id: { type: 'string' }, tags: { type: ['array', 'null'], items: {} } }, required: ['id', 'tags'] }\n * → { properties: { tags: { type: 'array', items: {} } }, required: ['tags'] }\n */\nconst removeManagedFields = (schema: JsonSchemaType): JsonSchemaType => {\n if (schema.properties && typeof schema.properties === 'object') {\n for (const field of PAYLOAD_MANAGED_FIELDS) {\n delete schema.properties[field]\n }\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 removeManagedFields(prop)\n }\n if (prop.items && typeof prop.items === 'object' && !Array.isArray(prop.items)) {\n removeManagedFields(prop.items)\n }\n }\n }\n\n if (Array.isArray(schema.required)) {\n schema.required = schema.required.filter((name) => !PAYLOAD_MANAGED_FIELDS.has(name))\n if (schema.required.length === 0) {\n delete schema.required\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 * **Correctness.** Reduces relationship/upload fields to the IDs a client actually sends. Payload types the value as\n * \"an ID or the full related document\" - but the populated-document form only appears in read responses;\n * on create/update you always reference a relationship by its ID. So we drop that `$ref` option, leaving\n * the bare ID. A single remaining target collapses inline (with a description naming the target\n * collection); several targets become an `anyOf` of IDs.\n *\n * @example\n * { oneOf: [{ type: 'string' }, { $ref: '#/$defs/posts' }] }\n * → { type: 'string', description: 'The ID of the related \"posts\" document.' }\n */\nconst relationshipsToIds = (schema: JsonSchemaType): JsonSchemaType => {\n if (!schema || typeof schema !== 'object') {\n return schema\n }\n\n const processed = { ...schema }\n\n if (Array.isArray(processed.oneOf)) {\n const isRelatedDocRef = (option: unknown): option is { $ref: string } =>\n !!option && typeof option === 'object' && '$ref' in option\n\n if (processed.oneOf.some(isRelatedDocRef)) {\n // A relationship value is \"an ID, or the populated related document\". Keep the ID option(s) and\n // drop the `$ref`s to the related collections, since a client only ever sends the ID.\n const idOptions = processed.oneOf\n .filter((option) => !isRelatedDocRef(option))\n .map((option) => (typeof option === 'object' ? relationshipsToIds(option) : option))\n const targetCollections = processed.oneOf\n .filter(isRelatedDocRef)\n .map((option) => option.$ref.replace('#/$defs/', ''))\n\n if (idOptions.length === 1) {\n delete processed.oneOf\n Object.assign(processed, idOptions[0])\n if (targetCollections.length > 0 && !processed.description) {\n processed.description = `The ID of the related \"${targetCollections.join('\" or \"')}\" document.`\n }\n } else if (idOptions.length > 1) {\n delete processed.oneOf\n processed.anyOf = idOptions\n }\n } else {\n processed.oneOf = processed.oneOf.map((option) =>\n typeof option === 'object' ? relationshipsToIds(option) : option,\n )\n }\n }\n\n if (processed.properties && typeof processed.properties === 'object') {\n processed.properties = Object.fromEntries(\n Object.entries(processed.properties).map(([key, value]) => [\n key,\n typeof value === 'object' ? relationshipsToIds(value) : value,\n ]),\n )\n }\n\n if (processed.items && typeof processed.items === 'object' && !Array.isArray(processed.items)) {\n processed.items = relationshipsToIds(processed.items)\n }\n\n // Lexical node unions and blocks live under `$defs` and have their own relationship fields, so walk\n // those too — otherwise their `$ref`s would dangle once we don't bundle the related collections.\n if (processed.$defs && typeof processed.$defs === 'object') {\n processed.$defs = Object.fromEntries(\n Object.entries(processed.$defs).map(([key, value]) => [\n key,\n typeof value === 'object' ? relationshipsToIds(value) : value,\n ]),\n )\n }\n\n return processed\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 as JsonSchemaType\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","removeManagedFields","pointFieldsToObjects","relationshipsToIds","removeTypeGenArtifacts","dropRedundantConstType","mergeConstDiscriminatedUnions","deduplicateIntoDefinitions","shortenDefinitionNames","mapNodes","node","visit","Array","isArray","map","child","out","key","value","Object","entries","PAYLOAD_MANAGED_FIELDS","Set","properties","field","keys","prop","isRequired","required","includes","collapseNullableType","items","filter","name","has","length","type","nonNullTypes","t","transformed","fromEntries","isArrayType","isPointField","every","item","isNullable","description","latitude","longitude","processed","oneOf","isRelatedDocRef","option","some","idOptions","targetCollections","$ref","replace","assign","join","anyOf","$defs","tsType","keyword","members","merged","mergeMembersByConst","objects","member","discriminator","constValues","everyMemberPinsConst","push","const","fingerprintWithoutDiscriminator","_discriminator","otherProperties","JSON","stringify","size","uniqueConstValues","discriminatorProp","enum","MIN_SHARED_SIZE","isShareable","Boolean","counts","Map","count","set","get","forEach","values","n","sharedEntries","nameByKey","share","childKey","definitions","shortNameFor","definition","constString","undefined","isNodeUnion","m","prefix","usedNames","rename","shortName","used","startsWith","slice","body"],"mappings":"AAEA;;;;;;;;;;;CAWC,GACD,OAAO,MAAMA,uBAAuB,CAACC;IACnC,8FAA8F;IAC9F,IAAIC,SAASC,gBAAgBF;IAE7B,wHAAwH;IACxHC,SAASE,oBAAoBF;IAE7B,iHAAiH;IACjHA,SAASG,qBAAqBH;IAE9B,mHAAmH;IACnHA,SAASI,mBAAmBJ;IAE5B,sGAAsG;IACtGA,SAASK,uBAAuBL;IAEh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A,MAAM;QACpD;QACA,OAAOvB;IACT;IACAX,OAAO8D,KAAK,GAAG1C,OAAOqB,WAAW,CAC/BrB,OAAOC,OAAO,CAACrB,OAAO8D,KAAK,EAAG/C,GAAG,CAAC,CAAC,CAACmB,MAAM+E,KAAK,GAAK;YAACL,OAAOjB,GAAG,CAACzD,SAASA;YAAM+E;SAAK;IAEtF,OAAOjH;AACT"}
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","usedNames","rename","shortName","used","startsWith","slice","body"],"mappings":"AAEA;;;;;;CAMC,GACD,OAAO,MAAMA,uBAAuB,CAACC;IACnC,8FAA8F;IAC9F,IAAIC,SAASC,gBAAgBF;IAE7B,8GAA8G;IAC9GC,SAASE,+BAA+BF;IAExC,iHAAiH;IACjHA,SAASG,qBAAqBH;IAE9B,sGAAsG;IACtGA,SAASI,uBAAuBJ;IAEhC,2FAA2F;IAC3FA,SAASK,uBAAuBL;IAEhC,4GAA4G;IAC5GA,SAASM,8BAA8BN;IAEvC,4FAA4F;IAC5FA,SAASO,2BAA2BP;IAEpC,gHAAgH;IAChHA,SAASQ,uBAAuBR;IAEhC,OAAOA;AACT,EAAC;AAED;;;CAGC,GACD,MAAMS,WAAW,CAACC,MAAeC;IAC/B,IAAIC,MAAMC,OAAO,CAACH,OAAO;QACvB,OAAOA,KAAKI,GAAG,CAAC,CAACC,QAAUN,SAASM,OAAOJ;IAC7C;IACA,IAAI,CAACD,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,GAAIuB;QAC5E,MAAMC,cACJjF,MAAMC,OAAO,CAACiC,YACdA,QAAQiC,IAAI,CAAC,CAACe,IAAM,OAAOA,MAAM,YAAYvB,QAAQuB,EAAET,IAAI,IAAIS,EAAEzE,UAAU,EAAEQ;QAC/E,OACE8D,YAAY,gBACZA,YAAY,WACXE,CAAAA,cAAc,SAASD,SAAQ,KAChCR,KAAKW,OAAO,CAAC,mBAAmB;IAEpC;IAEA,MAAMC,SAAS;IACf,MAAMC,YAAY,IAAIxB;IACtB,MAAMyB,SAAS,IAAIzB;IACnB,KAAK,MAAM,CAACW,MAAMM,WAAW,IAAIvE,OAAOC,OAAO,CAACoE,aAAc;QAC5D,MAAMW,YAAYV,aAAaL,MAAMM;QACrC,MAAMU,OAAOH,UAAUrB,GAAG,CAACuB,cAAc;QACzCF,UAAUtB,GAAG,CAACwB,WAAWC,OAAO;QAChCF,OAAOvB,GAAG,CAACS,MAAMgB,SAAS,IAAID,YAAY,GAAGA,YAAYC,OAAO,GAAG;IACrE;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,10 +1,11 @@
1
1
  import { describe, expect, it } from 'vitest';
2
2
  import { sanitizeEntitySchema } from './sanitizeEntitySchema.js';
3
3
  describe('sanitizeEntitySchema', ()=>{
4
- it('keeps a Lexical node union strict (oneOf) while simplifying relationship values to IDs', ()=>{
5
- // Shaped like the schema the MCP server prepares for a collection with a Lexical richText field:
6
- // a `$defs` node union (a `oneOf` of node shapes) where a relationship node's `value` is either
7
- // an ID or a `$ref` to the populated related collection.
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.
8
9
  const standalone = {
9
10
  type: 'object',
10
11
  $defs: {
@@ -30,14 +31,8 @@ describe('sanitizeEntitySchema', ()=>{
30
31
  const: 'relationship'
31
32
  },
32
33
  value: {
33
- oneOf: [
34
- {
35
- type: 'string'
36
- },
37
- {
38
- $ref: '#/$defs/posts'
39
- }
40
- ]
34
+ type: 'string',
35
+ description: 'The related document ID.'
41
36
  }
42
37
  },
43
38
  required: [
@@ -45,18 +40,6 @@ describe('sanitizeEntitySchema', ()=>{
45
40
  ]
46
41
  }
47
42
  ]
48
- },
49
- posts: {
50
- type: 'object',
51
- additionalProperties: false,
52
- properties: {
53
- id: {
54
- type: 'string'
55
- },
56
- title: {
57
- type: 'string'
58
- }
59
- }
60
43
  }
61
44
  },
62
45
  properties: {
@@ -85,7 +68,7 @@ describe('sanitizeEntitySchema', ()=>{
85
68
  type: 'object',
86
69
  $defs: {
87
70
  // The node union is renamed to a short, readable `node`, and stays a strict discriminated
88
- // `oneOf` - not loosened to `anyOf`...
71
+ // `oneOf` - not loosened to `anyOf`.
89
72
  node: {
90
73
  oneOf: [
91
74
  {
@@ -107,10 +90,10 @@ describe('sanitizeEntitySchema', ()=>{
107
90
  type: {
108
91
  const: 'relationship'
109
92
  },
110
- // ...while the relationship `value` is simplified to a bare ID (the populated-doc `$ref` is dropped).
93
+ // The value is already ID-only from the input variant - left as-is.
111
94
  value: {
112
95
  type: 'string',
113
- description: 'The ID of the related "posts" document.'
96
+ description: 'The related document ID.'
114
97
  }
115
98
  },
116
99
  required: [
@@ -118,22 +101,14 @@ describe('sanitizeEntitySchema', ()=>{
118
101
  ]
119
102
  }
120
103
  ]
121
- },
122
- posts: {
123
- type: 'object',
124
- additionalProperties: false,
125
- properties: {
126
- id: {
127
- type: 'string'
128
- },
129
- title: {
130
- type: 'string'
131
- }
132
- }
133
104
  }
134
105
  },
135
106
  properties: {
136
- // `id` is dropped - it's a Payload-managed field MCP clients never set.
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
+ },
137
112
  content: {
138
113
  type: 'object',
139
114
  properties: {
@@ -1 +1 @@
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('keeps a Lexical node union strict (oneOf) while simplifying relationship values to IDs', () => {\n // Shaped like the schema the MCP server prepares for a collection with a Lexical richText field:\n // a `$defs` node union (a `oneOf` of node shapes) where a relationship node's `value` is either\n // an ID or a `$ref` to the populated related collection.\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: { oneOf: [{ type: 'string' }, { $ref: '#/$defs/posts' }] },\n },\n required: ['type'],\n },\n ],\n },\n posts: {\n type: 'object',\n additionalProperties: false,\n properties: { id: { type: 'string' }, title: { type: 'string' } },\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 // ...while the relationship `value` is simplified to a bare ID (the populated-doc `$ref` is dropped).\n value: { type: 'string', description: 'The ID of the related \"posts\" document.' },\n },\n required: ['type'],\n },\n ],\n },\n posts: {\n type: 'object',\n additionalProperties: false,\n properties: { id: { type: 'string' }, title: { type: 'string' } },\n },\n },\n properties: {\n // `id` is dropped - it's a Payload-managed field MCP clients never set.\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","$ref","posts","id","title","content","root","children","items","toStrictEqual","node","description"],"mappings":"AAAA,SAASA,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAQ;AAI7C,SAASC,oBAAoB,QAAQ,4BAA2B;AAEhEH,SAAS,wBAAwB;IAC/BE,GAAG,0FAA0F;QAC3F,iGAAiG;QACjG,gGAAgG;QAChG,yDAAyD;QACzD,MAAME,aAA6B;YACjCC,MAAM;YACNC,OAAO;gBACLC,uBAAuB;oBACrBC,OAAO;wBACL;4BACEH,MAAM;4BACNI,sBAAsB;4BACtBC,YAAY;gCAAEL,MAAM;oCAAEM,OAAO;gCAAY;4BAAE;4BAC3CC,UAAU;gCAAC;6BAAO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oBAAE;gBAClE;YACF;YACAK,YAAY;gBACV,wEAAwE;gBACxEQ,SAAS;oBACPb,MAAM;oBACNK,YAAY;wBACVS,MAAM;4BACJd,MAAM;4BACNK,YAAY;gCACVU,UAAU;oCAAEf,MAAM;oCAASgB,OAAO;wCAAEP,MAAM;oCAAe;gCAAE;4BAC7D;wBACF;oBACF;gBACF;YACF;QACF;IACF;AACF"}
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,EAAEC,EAAE,QAAQ,SAAQ;AAI7C,SAASC,oBAAoB,QAAQ,4BAA2B;AAEhEH,SAAS,wBAAwB;IAC/BE,GAAG,yFAAyF;QAC1F,gGAAgG;QAChG,kGAAkG;QAClG,mGAAmG;QACnG,uFAAuF;QACvF,MAAME,aAA6B;YACjCC,MAAM;YACNC,OAAO;gBACLC,uBAAuB;oBACrBC,OAAO;wBACL;4BACEH,MAAM;4BACNI,sBAAsB;4BACtBC,YAAY;gCAAEL,MAAM;oCAAEM,OAAO;gCAAY;4BAAE;4BAC3CC,UAAU;gCAAC;6BAAO;wBACpB;wBACA;4BACEP,MAAM;4BACNI,sBAAsB;4BACtBC,YAAY;gCACVL,MAAM;oCAAEM,OAAO;gCAAe;gCAC9BE,OAAO;oCAAER,MAAM;oCAAUS,aAAa;gCAA2B;4BACnE;4BACAF,UAAU;gCAAC;6BAAO;wBACpB;qBACD;gBACH;YACF;YACAF,YAAY;gBACVK,IAAI;oBAAEV,MAAM;gBAAS;gBACrBW,SAAS;oBACPX,MAAM;oBACNK,YAAY;wBACVO,MAAM;4BACJZ,MAAM;4BACNK,YAAY;gCACVQ,UAAU;oCAAEb,MAAM;oCAASc,OAAO;wCAAEC,MAAM;oCAAgC;gCAAE;4BAC9E;wBACF;oBACF;gBACF;YACF;QACF;QAEAnB,OAAOE,qBAAqBC,aAAaiB,aAAa,CAAC;YACrDhB,MAAM;YACNC,OAAO;gBACL,0FAA0F;gBAC1F,qCAAqC;gBACrCgB,MAAM;oBACJd,OAAO;wBACL;4BACEH,MAAM;4BACNI,sBAAsB;4BACtBC,YAAY;gCAAEL,MAAM;oCAAEM,OAAO;gCAAY;4BAAE;4BAC3CC,UAAU;gCAAC;6BAAO;wBACpB;wBACA;4BACEP,MAAM;4BACNI,sBAAsB;4BACtBC,YAAY;gCACVL,MAAM;oCAAEM,OAAO;gCAAe;gCAC9B,oEAAoE;gCACpEE,OAAO;oCAAER,MAAM;oCAAUS,aAAa;gCAA2B;4BACnE;4BACAF,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 +1 @@
1
- {"version":3,"file":"toStandardSchema.d.ts","sourceRoot":"","sources":["../../src/utils/toStandardSchema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,KAAK,sBAAsB,EAAE,MAAM,8BAA8B,CAAA;AAE1F,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAElD,gIAAgI;AAChI,eAAO,MAAM,gBAAgB,GAAI,QAAQ,eAAe,KAAG,sBAG/B,CAAA"}
1
+ {"version":3,"file":"toStandardSchema.d.ts","sourceRoot":"","sources":["../../src/utils/toStandardSchema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,KAAK,sBAAsB,EAAE,MAAM,8BAA8B,CAAA;AAE1F,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAElD,gIAAgI;AAChI,eAAO,MAAM,gBAAgB,WAAY,eAAe,KAAG,sBAG/B,CAAA"}
@@ -0,0 +1,9 @@
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
@@ -0,0 +1 @@
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"}
@@ -0,0 +1,13 @@
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
@@ -0,0 +1 @@
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"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@payloadcms/plugin-mcp",
3
- "version": "4.0.0-internal.a0ef1b8",
3
+ "version": "4.0.0-internal.a6582c6",
4
4
  "description": "MCP (Model Context Protocol) capabilities with Payload",
5
5
  "keywords": [
6
6
  "plugin",
@@ -21,9 +21,6 @@
21
21
  "url": "https://payloadcms.com"
22
22
  }
23
23
  ],
24
- "sideEffects": [
25
- "*.css"
26
- ],
27
24
  "type": "module",
28
25
  "exports": {
29
26
  ".": {
@@ -40,6 +37,11 @@
40
37
  "import": "./dist/stdio.js",
41
38
  "types": "./dist/stdio.d.ts",
42
39
  "default": "./dist/stdio.js"
40
+ },
41
+ "./internal": {
42
+ "import": "./dist/exports/internal.js",
43
+ "types": "./dist/exports/internal.d.ts",
44
+ "default": "./dist/exports/internal.js"
43
45
  }
44
46
  },
45
47
  "main": "./dist/index.js",
@@ -53,26 +55,19 @@
53
55
  "bin.js"
54
56
  ],
55
57
  "dependencies": {
56
- "@cfworker/json-schema": "^4.1.1",
57
- "@modelcontextprotocol/server": "2.0.0-alpha.2",
58
+ "@modelcontextprotocol/server": "2.0.0-beta.3",
58
59
  "tsx": "4.22.4",
59
- "zod": "^4.0.0"
60
+ "zod": "^4.2.0"
60
61
  },
61
62
  "devDependencies": {
62
- "@types/react": "19.2.14",
63
- "react": "^19.0.1 || ^19.1.2 || ^19.2.1",
64
63
  "@payloadcms/eslint-config": "3.28.0",
65
- "payload": "4.0.0-internal.a0ef1b8",
66
- "@payloadcms/ui": "4.0.0-internal.a0ef1b8"
64
+ "payload": "4.0.0-internal.a6582c6"
67
65
  },
68
66
  "peerDependencies": {
69
- "react": "^19.0.1 || ^19.1.2 || ^19.2.1",
70
- "@payloadcms/ui": "4.0.0-internal.a0ef1b8",
71
- "payload": "4.0.0-internal.a0ef1b8"
67
+ "payload": "4.0.0-internal.a6582c6"
72
68
  },
73
69
  "//deps_notes": {
74
70
  "zod": "zod is a hard dependency of @modelcontextprotocol/server, thus we can safely use it without it impacting bundle size. Make extra sure the zod version here matches exactly what's defined in the dependencies of @modelcontextprotocol/server to avoid duplicate versions being installed.",
75
- "@cfworker/json-schema": "Should be able to remove in next @modelcontextprotocol/server alpha release. Marked as an optional peer of @modelcontextprotocol/server, but its bundle does an eager top-level `import { Validator } from '@cfworker/json-schema'`, so it must be installed even when only zod-registered tools are used. Drop once upstream lazy-loads the validator. See: https://github.com/modelcontextprotocol/typescript-sdk",
76
71
  "tsx": "Required by the `bin.js` stdio mcp. Keep the version pinned to whatever `payload` ships to avoid duplicate installs."
77
72
  },
78
73
  "homepage:": "https://payloadcms.com",
@@ -0,0 +1,3 @@
1
+ import type { MCPAccessArgs } from './types.js'
2
+
3
+ export const defaultAccess = ({ req }: MCPAccessArgs): boolean => Boolean(req.user)
@@ -1,132 +1,112 @@
1
- import type { DefaultDocumentIDType, PayloadRequest, TypedUser } from 'payload'
1
+ import type { PayloadRequest, SanitizedPermissions } from 'payload'
2
2
 
3
- import crypto from 'crypto'
4
- import { UnauthorizedError } from 'payload'
3
+ import { getAccessResults, UnauthorizedError } from 'payload'
5
4
 
6
- import type { AuthorizedMCP, MCPAPIKeysDoc } from '../types.js'
5
+ import type { AuthorizedMCP, MCPItem } from '../types.js'
7
6
 
8
- import { getLogger } from '../utils/getLogger.js'
9
7
  import { getPluginConfig } from '../utils/getPluginConfig.js'
10
8
 
9
+ export type GetAuthorizedMCPArgs = {
10
+ overrideAccess: boolean
11
+ req: PayloadRequest
12
+ }
13
+
11
14
  /**
12
- * Resolves the API key (or dev-mode session) and returns the items the caller
13
- * may use. Denied items are dropped from the array.
15
+ * Authenticates an MCP request and removes items the user cannot access.
16
+ * `overrideAccess` skips Payload and MCP item access checks.
14
17
  */
15
- export const getAuthorizedMCP: (args: { req: PayloadRequest }) => Promise<AuthorizedMCP> = async ({
18
+ export const getAuthorizedMCP: (args: GetAuthorizedMCPArgs) => Promise<AuthorizedMCP> = async ({
19
+ overrideAccess,
16
20
  req,
17
21
  }) => {
18
- const logger = getLogger({ payload: req.payload })
19
22
  const pluginConfig = getPluginConfig({ config: req.payload.config })
20
23
 
21
- const authHeader = req.headers.get('Authorization')
22
- const hasBearerToken = authHeader?.startsWith('Bearer ')
23
-
24
- const buildAuthorized = (apiKeyDoc: MCPAPIKeysDoc): AuthorizedMCP => ({
25
- items: pluginConfig.items.filter((item) => {
26
- switch (item.type) {
27
- case 'collectionTool':
28
- return apiKeyDoc.access.collections?.[item.collectionSlug]?.[item.key] !== false
29
- case 'globalTool':
30
- return apiKeyDoc.access.globals?.[item.globalSlug]?.[item.key] !== false
31
- case 'prompt':
32
- return apiKeyDoc.access.prompts?.[item.key] !== false
33
- case 'resource':
34
- return apiKeyDoc.access.resources?.[item.key] !== false
35
- case 'tool':
36
- return apiKeyDoc.access.tools?.[item.key] !== false
37
- }
38
- }),
39
- overrideAccess:
40
- typeof apiKeyDoc.overrideAccess === 'boolean' ? apiKeyDoc.overrideAccess : false,
41
- user: apiKeyDoc.user,
42
- })
43
-
44
- if (pluginConfig.overrideAuth) {
45
- return await pluginConfig.overrideAuth({
46
- getAPIKeyDoc: (overrideApiKey) => getAPIKeyDoc({ logger, overrideApiKey, pluginConfig, req }),
47
- getAuthorizedMCP: ({ apiKeyDoc }) => buildAuthorized(apiKeyDoc),
24
+ if (pluginConfig.overrideGetAuthorizedMCP) {
25
+ return await pluginConfig.overrideGetAuthorizedMCP({
26
+ overrideAccess,
48
27
  pluginConfig,
49
28
  req,
50
29
  })
51
30
  }
52
31
 
53
- if (process.env.NODE_ENV === 'development' && !hasBearerToken) {
54
- logger.info('Dev mode: skipping API key check, using session user')
55
- return buildAuthorized({
56
- id: -1,
57
- access: {},
58
- overrideAccess: true,
59
- user: req.user ?? null,
60
- })
32
+ if (req.headers) {
33
+ const headers = new Headers(req.headers)
34
+ const hasAuthorization = headers.has('Authorization')
35
+
36
+ headers.set('DisableAutologin', 'true')
37
+ req.user = (await req.payload.auth({ headers, req })).user
38
+
39
+ if (hasAuthorization && !req.user) {
40
+ throw new UnauthorizedError(req.t)
41
+ }
61
42
  }
62
43
 
63
- return buildAuthorized(await getAPIKeyDoc({ logger, pluginConfig, req }))
44
+ return {
45
+ items: await filterMCPItems({
46
+ items: pluginConfig.items,
47
+ overrideAccess,
48
+ req,
49
+ }),
50
+ overrideAccess,
51
+ }
64
52
  }
65
53
 
66
- const getAPIKeyDoc = async ({
67
- logger,
68
- overrideApiKey,
69
- pluginConfig,
54
+ export const filterMCPItems = async ({
55
+ items,
56
+ overrideAccess,
70
57
  req,
71
58
  }: {
72
- logger: ReturnType<typeof getLogger>
73
- overrideApiKey?: string
74
- pluginConfig: ReturnType<typeof getPluginConfig>
59
+ items: MCPItem[]
60
+ overrideAccess: boolean
75
61
  req: PayloadRequest
76
- }): Promise<MCPAPIKeysDoc> => {
77
- const authHeader = req.headers.get('Authorization')
78
- const hasBearerToken = authHeader?.startsWith('Bearer ')
79
-
80
- const apiKey =
81
- overrideApiKey ?? (hasBearerToken ? authHeader?.replace('Bearer ', '').trim() || null : null)
82
-
83
- if (!apiKey) {
84
- throw new UnauthorizedError()
85
- }
86
-
87
- const sha256APIKeyIndex = crypto
88
- .createHmac('sha256', req.payload.secret)
89
- .update(apiKey)
90
- .digest('hex')
91
-
92
- const doc = await req.payload.db.findOne<MCPAPIKeysDoc>({
93
- collection: 'payload-mcp-api-keys',
94
- req,
95
- where: {
96
- apiKeyIndex: { equals: sha256APIKeyIndex },
97
- },
98
- })
99
-
100
- if (!doc || !doc.user) {
101
- throw new UnauthorizedError()
62
+ }): Promise<MCPItem[]> => {
63
+ // Match Payload core: overrideAccess bypasses access evaluation
64
+ if (overrideAccess) {
65
+ return items
102
66
  }
103
67
 
104
- logger.info('API Key is valid')
68
+ const authorizedItems: MCPItem[] = []
105
69
 
106
- const userRef = doc.user
107
- const userID =
108
- typeof userRef === 'object' && userRef !== null && 'id' in userRef
109
- ? userRef.id
110
- : (userRef as unknown as DefaultDocumentIDType)
70
+ const permissions = await getAccessResults({ req })
111
71
 
112
- const user = (await req.payload.findByID({
113
- id: userID,
114
- collection: pluginConfig.userCollection,
115
- depth: 0,
116
- disableErrors: true,
117
- req,
118
- })) as null | TypedUser
119
-
120
- if (!user) {
121
- throw new UnauthorizedError()
72
+ for (const item of items) {
73
+ if (!(await checkItemAccess({ item, permissions, req }))) {
74
+ continue
75
+ }
76
+ authorizedItems.push(item)
122
77
  }
123
78
 
124
- return {
125
- ...doc,
126
- user: {
127
- ...user,
128
- _strategy: 'mcp-api-key' as const,
129
- collection: pluginConfig.userCollection,
130
- },
79
+ return authorizedItems
80
+ }
81
+
82
+ /**
83
+ * Runs MCP item access callbacks
84
+ */
85
+ const checkItemAccess = async ({
86
+ item,
87
+ permissions,
88
+ req,
89
+ }: {
90
+ item: MCPItem
91
+ permissions?: SanitizedPermissions
92
+ req: PayloadRequest
93
+ }): Promise<boolean> => {
94
+ switch (item.type) {
95
+ case 'collectionTool':
96
+ return (
97
+ !item.tool.access ||
98
+ (await item.tool.access({ collectionSlug: item.collectionSlug, permissions, req }))
99
+ )
100
+ case 'globalTool':
101
+ return (
102
+ !item.tool.access ||
103
+ (await item.tool.access({ globalSlug: item.globalSlug, permissions, req }))
104
+ )
105
+ case 'prompt':
106
+ return !item.prompt.access || (await item.prompt.access({ permissions, req }))
107
+ case 'resource':
108
+ return !item.resource.access || (await item.resource.access({ permissions, req }))
109
+ case 'tool':
110
+ return !item.tool.access || (await item.tool.access({ permissions, req }))
131
111
  }
132
112
  }