@payloadcms/plugin-mcp 4.0.0-internal.fa345ef → 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 (182) hide show
  1. package/bin.js +7 -0
  2. package/dist/defaultAccess.d.ts.map +1 -1
  3. package/dist/defineTool.d.ts +8 -8
  4. package/dist/defineTool.d.ts.map +1 -1
  5. package/dist/endpoint/access.d.ts +2 -7
  6. package/dist/endpoint/access.d.ts.map +1 -1
  7. package/dist/endpoint/access.js +6 -13
  8. package/dist/endpoint/access.js.map +1 -1
  9. package/dist/mcp/buildMcpServer.d.ts +1 -1
  10. package/dist/mcp/buildMcpServer.d.ts.map +1 -1
  11. package/dist/mcp/buildMcpServer.js +35 -23
  12. package/dist/mcp/buildMcpServer.js.map +1 -1
  13. package/dist/mcp/builtin/collections/authTools.d.ts.map +1 -1
  14. package/dist/mcp/builtin/collections/authTools.js +79 -56
  15. package/dist/mcp/builtin/collections/authTools.js.map +1 -1
  16. package/dist/mcp/builtin/collections/countTool.d.ts.map +1 -1
  17. package/dist/mcp/builtin/collections/countTool.js +10 -16
  18. package/dist/mcp/builtin/collections/countTool.js.map +1 -1
  19. package/dist/mcp/builtin/collections/countVersionsTool.d.ts.map +1 -1
  20. package/dist/mcp/builtin/collections/countVersionsTool.js +10 -15
  21. package/dist/mcp/builtin/collections/countVersionsTool.js.map +1 -1
  22. package/dist/mcp/builtin/collections/createTool.d.ts +1 -1
  23. package/dist/mcp/builtin/collections/createTool.d.ts.map +1 -1
  24. package/dist/mcp/builtin/collections/createTool.js +104 -54
  25. package/dist/mcp/builtin/collections/createTool.js.map +1 -1
  26. package/dist/mcp/builtin/collections/deleteTool.d.ts.map +1 -1
  27. package/dist/mcp/builtin/collections/deleteTool.js +45 -45
  28. package/dist/mcp/builtin/collections/deleteTool.js.map +1 -1
  29. package/dist/mcp/builtin/collections/duplicateTool.d.ts.map +1 -1
  30. package/dist/mcp/builtin/collections/duplicateTool.js +32 -39
  31. package/dist/mcp/builtin/collections/duplicateTool.js.map +1 -1
  32. package/dist/mcp/builtin/collections/fileInput.d.ts +28 -0
  33. package/dist/mcp/builtin/collections/fileInput.d.ts.map +1 -0
  34. package/dist/mcp/builtin/collections/fileInput.js +88 -0
  35. package/dist/mcp/builtin/collections/fileInput.js.map +1 -0
  36. package/dist/mcp/builtin/collections/fileInput.spec.js +86 -0
  37. package/dist/mcp/builtin/collections/fileInput.spec.js.map +1 -0
  38. package/dist/mcp/builtin/collections/findDistinctTool.d.ts.map +1 -1
  39. package/dist/mcp/builtin/collections/findDistinctTool.js +12 -28
  40. package/dist/mcp/builtin/collections/findDistinctTool.js.map +1 -1
  41. package/dist/mcp/builtin/collections/findTool.d.ts.map +1 -1
  42. package/dist/mcp/builtin/collections/findTool.js +29 -48
  43. package/dist/mcp/builtin/collections/findTool.js.map +1 -1
  44. package/dist/mcp/builtin/collections/findVersionByIDTool.d.ts.map +1 -1
  45. package/dist/mcp/builtin/collections/findVersionByIDTool.js +18 -28
  46. package/dist/mcp/builtin/collections/findVersionByIDTool.js.map +1 -1
  47. package/dist/mcp/builtin/collections/findVersionsTool.d.ts.map +1 -1
  48. package/dist/mcp/builtin/collections/findVersionsTool.js +17 -32
  49. package/dist/mcp/builtin/collections/findVersionsTool.js.map +1 -1
  50. package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -1
  51. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +51 -11
  52. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -1
  53. package/dist/mcp/builtin/collections/restoreVersionTool.d.ts.map +1 -1
  54. package/dist/mcp/builtin/collections/restoreVersionTool.js +15 -28
  55. package/dist/mcp/builtin/collections/restoreVersionTool.js.map +1 -1
  56. package/dist/mcp/builtin/collections/updateTool.d.ts.map +1 -1
  57. package/dist/mcp/builtin/collections/updateTool.js +67 -87
  58. package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
  59. package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts +2 -0
  60. package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts.map +1 -0
  61. package/dist/mcp/builtin/collections/uploadInstructionsTool.js +55 -0
  62. package/dist/mcp/builtin/collections/uploadInstructionsTool.js.map +1 -0
  63. package/dist/mcp/builtin/formatEntityError.d.ts +16 -0
  64. package/dist/mcp/builtin/formatEntityError.d.ts.map +1 -0
  65. package/dist/mcp/builtin/formatEntityError.js +55 -0
  66. package/dist/mcp/builtin/formatEntityError.js.map +1 -0
  67. package/dist/mcp/builtin/getConfigInfoTool.d.ts.map +1 -1
  68. package/dist/mcp/builtin/getConfigInfoTool.js +5 -7
  69. package/dist/mcp/builtin/getConfigInfoTool.js.map +1 -1
  70. package/dist/mcp/builtin/globals/countVersionsTool.d.ts.map +1 -1
  71. package/dist/mcp/builtin/globals/countVersionsTool.js +10 -15
  72. package/dist/mcp/builtin/globals/countVersionsTool.js.map +1 -1
  73. package/dist/mcp/builtin/globals/findTool.d.ts.map +1 -1
  74. package/dist/mcp/builtin/globals/findTool.js +12 -18
  75. package/dist/mcp/builtin/globals/findTool.js.map +1 -1
  76. package/dist/mcp/builtin/globals/findVersionByIDTool.d.ts.map +1 -1
  77. package/dist/mcp/builtin/globals/findVersionByIDTool.js +14 -26
  78. package/dist/mcp/builtin/globals/findVersionByIDTool.js.map +1 -1
  79. package/dist/mcp/builtin/globals/findVersionsTool.d.ts.map +1 -1
  80. package/dist/mcp/builtin/globals/findVersionsTool.js +14 -31
  81. package/dist/mcp/builtin/globals/findVersionsTool.js.map +1 -1
  82. package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts.map +1 -1
  83. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js +28 -10
  84. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js.map +1 -1
  85. package/dist/mcp/builtin/globals/restoreVersionTool.d.ts.map +1 -1
  86. package/dist/mcp/builtin/globals/restoreVersionTool.js +16 -24
  87. package/dist/mcp/builtin/globals/restoreVersionTool.js.map +1 -1
  88. package/dist/mcp/builtin/globals/updateTool.d.ts.map +1 -1
  89. package/dist/mcp/builtin/globals/updateTool.js +28 -37
  90. package/dist/mcp/builtin/globals/updateTool.js.map +1 -1
  91. package/dist/mcp/builtinTools.d.ts +6 -0
  92. package/dist/mcp/builtinTools.d.ts.map +1 -1
  93. package/dist/mcp/builtinTools.js +9 -3
  94. package/dist/mcp/builtinTools.js.map +1 -1
  95. package/dist/mcp/sanitizeMCPConfig.d.ts.map +1 -1
  96. package/dist/mcp/sanitizeMCPConfig.js +4 -1
  97. package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
  98. package/dist/stdio.d.ts.map +1 -1
  99. package/dist/stdio.js +2 -1
  100. package/dist/stdio.js.map +1 -1
  101. package/dist/types.d.ts +48 -11
  102. package/dist/types.d.ts.map +1 -1
  103. package/dist/types.js +2 -4
  104. package/dist/types.js.map +1 -1
  105. package/dist/utils/camelCase.d.ts.map +1 -1
  106. package/dist/utils/resolveProjectRoot.d.ts.map +1 -1
  107. package/dist/utils/toStandardSchema.d.ts.map +1 -1
  108. package/package.json +5 -7
  109. package/src/endpoint/access.ts +5 -13
  110. package/src/mcp/buildMcpServer.ts +39 -29
  111. package/src/mcp/builtin/collections/authTools.ts +77 -69
  112. package/src/mcp/builtin/collections/countTool.ts +10 -23
  113. package/src/mcp/builtin/collections/countVersionsTool.ts +10 -23
  114. package/src/mcp/builtin/collections/createTool.ts +110 -77
  115. package/src/mcp/builtin/collections/deleteTool.ts +36 -65
  116. package/src/mcp/builtin/collections/duplicateTool.ts +36 -87
  117. package/src/mcp/builtin/collections/fileInput.spec.ts +93 -0
  118. package/src/mcp/builtin/collections/fileInput.ts +127 -0
  119. package/src/mcp/builtin/collections/findDistinctTool.ts +12 -64
  120. package/src/mcp/builtin/collections/findTool.ts +25 -108
  121. package/src/mcp/builtin/collections/findVersionByIDTool.ts +16 -60
  122. package/src/mcp/builtin/collections/findVersionsTool.ts +15 -87
  123. package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +48 -14
  124. package/src/mcp/builtin/collections/restoreVersionTool.ts +15 -58
  125. package/src/mcp/builtin/collections/updateTool.ts +63 -101
  126. package/src/mcp/builtin/collections/uploadInstructionsTool.ts +64 -0
  127. package/src/mcp/builtin/formatEntityError.ts +77 -0
  128. package/src/mcp/builtin/getConfigInfoTool.ts +4 -5
  129. package/src/mcp/builtin/globals/countVersionsTool.ts +10 -22
  130. package/src/mcp/builtin/globals/findTool.ts +14 -53
  131. package/src/mcp/builtin/globals/findVersionByIDTool.ts +14 -54
  132. package/src/mcp/builtin/globals/findVersionsTool.ts +15 -94
  133. package/src/mcp/builtin/globals/getGlobalSchemaTool.ts +30 -8
  134. package/src/mcp/builtin/globals/restoreVersionTool.ts +17 -48
  135. package/src/mcp/builtin/globals/updateTool.ts +39 -62
  136. package/src/mcp/builtinTools.ts +9 -2
  137. package/src/mcp/sanitizeMCPConfig.ts +4 -1
  138. package/src/stdio.ts +2 -1
  139. package/src/types.ts +47 -11
  140. package/dist/mcp/builtin/collections/formatCollectionError.d.ts +0 -9
  141. package/dist/mcp/builtin/collections/formatCollectionError.d.ts.map +0 -1
  142. package/dist/mcp/builtin/collections/formatCollectionError.js +0 -60
  143. package/dist/mcp/builtin/collections/formatCollectionError.js.map +0 -1
  144. package/dist/mcp/builtin/validateEntityData.d.ts +0 -14
  145. package/dist/mcp/builtin/validateEntityData.d.ts.map +0 -1
  146. package/dist/mcp/builtin/validateEntityData.js +0 -82
  147. package/dist/mcp/builtin/validateEntityData.js.map +0 -1
  148. package/dist/utils/getVirtualFieldNames.d.ts +0 -14
  149. package/dist/utils/getVirtualFieldNames.d.ts.map +0 -1
  150. package/dist/utils/getVirtualFieldNames.js +0 -35
  151. package/dist/utils/getVirtualFieldNames.js.map +0 -1
  152. package/dist/utils/localAPIDefaults.d.ts +0 -20
  153. package/dist/utils/localAPIDefaults.d.ts.map +0 -1
  154. package/dist/utils/localAPIDefaults.js +0 -19
  155. package/dist/utils/localAPIDefaults.js.map +0 -1
  156. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts +0 -11
  157. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts.map +0 -1
  158. package/dist/utils/schemaConversion/getEntityInputSchema.js +0 -32
  159. package/dist/utils/schemaConversion/getEntityInputSchema.js.map +0 -1
  160. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts +0 -10
  161. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts.map +0 -1
  162. package/dist/utils/schemaConversion/sanitizeEntitySchema.js +0 -384
  163. package/dist/utils/schemaConversion/sanitizeEntitySchema.js.map +0 -1
  164. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js +0 -133
  165. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js.map +0 -1
  166. package/dist/utils/transformPointDataToPayload.d.ts +0 -7
  167. package/dist/utils/transformPointDataToPayload.d.ts.map +0 -1
  168. package/dist/utils/transformPointDataToPayload.js +0 -28
  169. package/dist/utils/transformPointDataToPayload.js.map +0 -1
  170. package/dist/utils/whereSchema.d.ts +0 -9
  171. package/dist/utils/whereSchema.d.ts.map +0 -1
  172. package/dist/utils/whereSchema.js +0 -13
  173. package/dist/utils/whereSchema.js.map +0 -1
  174. package/src/mcp/builtin/collections/formatCollectionError.ts +0 -84
  175. package/src/mcp/builtin/validateEntityData.ts +0 -132
  176. package/src/utils/getVirtualFieldNames.ts +0 -53
  177. package/src/utils/localAPIDefaults.ts +0 -22
  178. package/src/utils/schemaConversion/getEntityInputSchema.ts +0 -62
  179. package/src/utils/schemaConversion/sanitizeEntitySchema.spec.ts +0 -96
  180. package/src/utils/schemaConversion/sanitizeEntitySchema.ts +0 -432
  181. package/src/utils/transformPointDataToPayload.ts +0 -40
  182. package/src/utils/whereSchema.ts +0 -24
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/mcp/builtin/collections/duplicateTool.ts"],"sourcesContent":["import type { PopulateType, SelectType } from 'payload'\n\nimport { z } from 'zod'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\nimport {\n getCollectionVirtualFieldNames,\n stripVirtualFields,\n} from '../../../utils/getVirtualFieldNames.js'\nimport { localAPIDefaults } from '../../../utils/localAPIDefaults.js'\nimport { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'\nimport { formatCollectionError } from './formatCollectionError.js'\n\nconst DEFAULT_DESCRIPTION =\n 'Duplicate a document in any collection by passing the collection slug and source document ID.'\n\nexport const duplicateDocumentTool = defineCollectionTool({\n access: (args) =>\n defaultAccess(args) && Boolean(args.permissions?.collections?.[args.collectionSlug]?.create),\n annotations: {\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'Duplicate Document',\n },\n description: DEFAULT_DESCRIPTION,\n input: z.object({\n id: z.union([z.string(), z.number()]).describe('The ID of the document to duplicate'),\n data: z\n .record(z.string(), z.unknown())\n .describe('Optional: fields to override on the duplicated document')\n .optional(),\n depth: z\n .number()\n .int()\n .min(0)\n .max(10)\n .describe('How many levels deep to populate relationships in response')\n .optional()\n .default(0),\n draft: z\n .boolean()\n .describe('Whether to create the duplicate as a draft')\n .optional()\n .default(false),\n fallbackLocale: z\n .string()\n .describe('Optional: fallback locale code to use when requested locale is not available')\n .optional(),\n locale: z\n .string()\n .describe(\n 'Optional: locale code to duplicate in (e.g., \"en\", \"es\"). Defaults to the default locale',\n )\n .optional(),\n populate: z\n .record(z.string(), z.unknown())\n .describe(\n 'Optional: control which fields to include from populated relationship or upload documents.',\n )\n .optional(),\n select: z\n .record(z.string(), z.unknown())\n .describe(\n 'Optional: define exactly which fields you\\'d like to return in the response, e.g., {\"title\": true}',\n )\n .optional(),\n selectedLocales: z\n .array(z.string())\n .describe('Optional: localized field locales to include in the duplicated document')\n .optional(),\n showHiddenFields: z\n .boolean()\n .describe('Optional: include hidden fields in the duplicated document response')\n .optional(),\n }),\n}).handler(async ({ authorizedMCP, collectionSlug, input, req }) => {\n const payload = req.payload\n const logger = getLogger({ payload })\n const {\n id,\n data,\n depth,\n draft,\n fallbackLocale,\n locale,\n populate,\n select,\n selectedLocales,\n showHiddenFields,\n } = input\n\n logger.info(`Duplicating document in collection: ${collectionSlug} with ID: ${id}`)\n\n try {\n const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, collectionSlug)\n const inputData = data ? stripVirtualFields(data, virtualFieldNames) : undefined\n const parsedData = inputData ? transformPointDataToPayload(inputData) : undefined\n\n const result = await payload.duplicate({\n id,\n collection: collectionSlug,\n depth,\n draft,\n req,\n ...localAPIDefaults(authorizedMCP),\n ...(parsedData ? { data: parsedData } : {}),\n ...(locale ? { locale } : {}),\n ...(fallbackLocale ? { fallbackLocale } : {}),\n ...(populate ? { populate: populate as PopulateType } : {}),\n ...(select ? { select: select as SelectType } : {}),\n ...(selectedLocales ? { selectedLocales } : {}),\n ...(showHiddenFields !== undefined ? { showHiddenFields } : {}),\n })\n\n logger.info(`Successfully duplicated document in ${collectionSlug} from ID: ${id}`)\n\n return {\n content: [\n {\n type: 'text',\n text: `Document duplicated successfully in collection \"${collectionSlug}\"!\\nDuplicated document:\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error duplicating document in ${collectionSlug}: ${errorMessage}`)\n return formatCollectionError({ action: 'duplicating', collectionSlug, error, req })\n }\n})\n"],"names":["z","defaultAccess","defineCollectionTool","getLogger","getCollectionVirtualFieldNames","stripVirtualFields","localAPIDefaults","transformPointDataToPayload","formatCollectionError","DEFAULT_DESCRIPTION","duplicateDocumentTool","access","args","Boolean","permissions","collections","collectionSlug","create","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","object","id","union","string","number","describe","data","record","unknown","optional","depth","int","min","max","default","draft","boolean","fallbackLocale","locale","populate","select","selectedLocales","array","showHiddenFields","handler","authorizedMCP","req","payload","logger","info","virtualFieldNames","config","inputData","undefined","parsedData","result","duplicate","collection","content","type","text","JSON","stringify","doc","error","errorMessage","Error","message","action"],"mappings":"AAEA,SAASA,CAAC,QAAQ,MAAK;AAEvB,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AACvD,SACEC,8BAA8B,EAC9BC,kBAAkB,QACb,yCAAwC;AAC/C,SAASC,gBAAgB,QAAQ,qCAAoC;AACrE,SAASC,2BAA2B,QAAQ,gDAA+C;AAC3F,SAASC,qBAAqB,QAAQ,6BAA4B;AAElE,MAAMC,sBACJ;AAEF,OAAO,MAAMC,wBAAwBR,qBAAqB;IACxDS,QAAQ,CAACC,OACPX,cAAcW,SAASC,QAAQD,KAAKE,WAAW,EAAEC,aAAa,CAACH,KAAKI,cAAc,CAAC,EAAEC;IACvFC,aAAa;QACXC,iBAAiB;QACjBC,gBAAgB;QAChBC,eAAe;QACfC,cAAc;QACdC,OAAO;IACT;IACAC,aAAaf;IACbgB,OAAOzB,EAAE0B,MAAM,CAAC;QACdC,IAAI3B,EAAE4B,KAAK,CAAC;YAAC5B,EAAE6B,MAAM;YAAI7B,EAAE8B,MAAM;SAAG,EAAEC,QAAQ,CAAC;QAC/CC,MAAMhC,EACHiC,MAAM,CAACjC,EAAE6B,MAAM,IAAI7B,EAAEkC,OAAO,IAC5BH,QAAQ,CAAC,2DACTI,QAAQ;QACXC,OAAOpC,EACJ8B,MAAM,GACNO,GAAG,GACHC,GAAG,CAAC,GACJC,GAAG,CAAC,IACJR,QAAQ,CAAC,8DACTI,QAAQ,GACRK,OAAO,CAAC;QACXC,OAAOzC,EACJ0C,OAAO,GACPX,QAAQ,CAAC,8CACTI,QAAQ,GACRK,OAAO,CAAC;QACXG,gBAAgB3C,EACb6B,MAAM,GACNE,QAAQ,CAAC,gFACTI,Q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AI,CAAC,CAAC;YAC5B,GAAID,iBAAiB;gBAAEA;YAAe,IAAI,CAAC,CAAC;YAC5C,GAAIE,WAAW;gBAAEA,UAAUA;YAAyB,IAAI,CAAC,CAAC;YAC1D,GAAIC,SAAS;gBAAEA,QAAQA;YAAqB,IAAI,CAAC,CAAC;YAClD,GAAIC,kBAAkB;gBAAEA;YAAgB,IAAI,CAAC,CAAC;YAC9C,GAAIE,qBAAqBU,YAAY;gBAAEV;YAAiB,IAAI,CAAC,CAAC;QAChE;QAEAK,OAAOC,IAAI,CAAC,CAAC,oCAAoC,EAAEvC,eAAe,UAAU,EAAEW,IAAI;QAElF,OAAO;YACLqC,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,gDAAgD,EAAElD,eAAe,sCAAsC,EAAEmD,KAAKC,SAAS,CAACP,QAAQ,QAAQ,CAAC;gBAClJ;aACD;YACDQ,KAAKR;QACP;IACF,EAAE,OAAOS,OAAO;QACd,MAAMC,eAAeD,iBAAiBE,QAAQF,MAAMG,OAAO,GAAG;QAC9DnB,OAAOgB,KAAK,CAAC,CAAC,8BAA8B,EAAEtD,eAAe,EAAE,EAAEuD,cAAc;QAC/E,OAAO/D,sBAAsB;YAAEkE,QAAQ;YAAe1D;YAAgBsD;YAAOlB;QAAI;IACnF;AACF,GAAE"}
1
+ {"version":3,"sources":["../../../../src/mcp/builtin/collections/duplicateTool.ts"],"sourcesContent":["import {\n duplicateDocumentInputSchema,\n getCollectionVirtualFieldNames,\n parseDocumentID,\n stripVirtualFields,\n transformPointDataToPayload,\n validateCollectionData,\n} from 'payload'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\nimport { formatEntityError } from '../formatEntityError.js'\n\nconst DEFAULT_DESCRIPTION =\n 'Duplicate a document in any collection by passing the collection slug and source document ID.'\n\nexport const duplicateDocumentTool = defineCollectionTool({\n access: (args) =>\n defaultAccess(args) && Boolean(args.permissions?.collections?.[args.slug]?.create),\n annotations: {\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'Duplicate Document',\n },\n description: DEFAULT_DESCRIPTION,\n input: duplicateDocumentInputSchema,\n}).handler(async ({ slug, authorizedMCP, input, req }) => {\n const payload = req.payload\n const logger = getLogger({ payload })\n const { id, data, depth, draft, fallbackLocale, locale, populate, select, selectedLocales } =\n input\n\n logger.info(`Duplicating document in collection: ${slug} with ID: ${id}`)\n\n try {\n const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, slug)\n const inputData = data ? stripVirtualFields(data, virtualFieldNames) : undefined\n\n if (inputData) {\n validateCollectionData({\n slug,\n data: inputData,\n partial: true,\n req,\n })\n }\n\n const parsedData = inputData ? transformPointDataToPayload(inputData) : undefined\n\n const result = await payload.duplicate({\n id: parseDocumentID({ id, collectionSlug: slug, payload }),\n collection: slug,\n depth,\n draft,\n overrideAccess: authorizedMCP.overrideAccess,\n req,\n ...(parsedData ? { data: parsedData } : {}),\n ...(locale ? { locale } : {}),\n ...(fallbackLocale !== undefined ? { fallbackLocale } : {}),\n ...(populate ? { populate } : {}),\n ...(select ? { select } : {}),\n ...(selectedLocales ? { selectedLocales } : {}),\n })\n\n logger.info(`Successfully duplicated document in ${slug} from ID: ${id}`)\n\n return {\n content: [\n {\n type: 'text',\n text: `Document duplicated successfully in collection \"${slug}\"!\\nDuplicated document:\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error duplicating document in ${slug}: ${errorMessage}`)\n return formatEntityError({ slug, action: 'duplicating', entity: 'collection', error, req })\n }\n})\n"],"names":["duplicateDocumentInputSchema","getCollectionVirtualFieldNames","parseDocumentID","stripVirtualFields","transformPointDataToPayload","validateCollectionData","defaultAccess","defineCollectionTool","getLogger","formatEntityError","DEFAULT_DESCRIPTION","duplicateDocumentTool","access","args","Boolean","permissions","collections","slug","create","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","handler","authorizedMCP","req","payload","logger","id","data","depth","draft","fallbackLocale","locale","populate","select","selectedLocales","info","virtualFieldNames","config","inputData","undefined","partial","parsedData","result","duplicate","collectionSlug","collection","overrideAccess","content","type","text","JSON","stringify","doc","error","errorMessage","Error","message","action","entity"],"mappings":"AAAA,SACEA,4BAA4B,EAC5BC,8BAA8B,EAC9BC,eAAe,EACfC,kBAAkB,EAClBC,2BAA2B,EAC3BC,sBAAsB,QACjB,UAAS;AAEhB,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AACvD,SAASC,iBAAiB,QAAQ,0BAAyB;AAE3D,MAAMC,sBACJ;AAEF,OAAO,MAAMC,wBAAwBJ,qBAAqB;IACxDK,QAAQ,CAACC,OACPP,cAAcO,SAASC,QAAQD,KAAKE,WAAW,EAAEC,aAAa,CAACH,KAAKI,IAAI,CAAC,EAAEC;IAC7EC,aAAa;QACXC,iBAAiB;QACjBC,gBAAgB;QAChBC,eAAe;QACfC,cAAc;QACdC,OAAO;IACT;IACAC,aAAaf;IACbgB,OAAO1B;AACT,GAAG2B,OAAO,CAAC,OAAO,EAAEV,IAAI,EAAEW,aAAa,EAAEF,KAAK,EAAEG,GAAG,EAAE;IACnD,MAAMC,UAAUD,IAAIC,OAAO;IAC3B,MAAMC,SAASvB,UAAU;QAAEsB;IAAQ;IACnC,MAAM,EAAEE,EAAE,EAAEC,IAAI,EAAEC,KAAK,EAAEC,KAAK,EAAEC,cAAc,EAAEC,MAAM,EAAEC,QAAQ,EAAEC,MAAM,EAAEC,eAAe,EAAE,GACzFd;IAEFK,OAAOU,IAAI,CAAC,CAAC,oCAAoC,EAAExB,KAAK,UAAU,EAAEe,IAAI;IAExE,IAAI;QACF,MAAMU,oBAAoBzC,+B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AAO9B;QAAI;IAC3F;AACF,GAAE"}
@@ -0,0 +1,28 @@
1
+ import type { CollectionSlug, File, PayloadRequest } from 'payload';
2
+ import { z } from 'payload';
3
+ export declare const fileInputSchema: z.ZodMiniDiscriminatedUnion<[z.ZodMiniObject<{
4
+ name: z.ZodMiniString<string>;
5
+ data: z.ZodMiniString<string>;
6
+ mimeType: z.ZodMiniString<string>;
7
+ source: z.ZodMiniLiteral<"base64">;
8
+ }, z.core.$strict>, z.ZodMiniObject<{
9
+ name: z.ZodMiniOptional<z.ZodMiniString<string>>;
10
+ source: z.ZodMiniLiteral<"externalURL">;
11
+ url: z.ZodMiniURL;
12
+ }, z.core.$strict>, z.ZodMiniObject<{
13
+ file: z.ZodMiniObject<{
14
+ filename: z.ZodMiniString<string>;
15
+ mimeType: z.ZodMiniString<string>;
16
+ size: z.ZodMiniInt;
17
+ uploadReference: z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>;
18
+ }, z.core.$strict>;
19
+ source: z.ZodMiniLiteral<"uploadReference">;
20
+ }, z.core.$strict>], "source">;
21
+ type FileInput = z.infer<typeof fileInputSchema>;
22
+ export declare function resolveFile({ slug, input, req, }: {
23
+ input?: FileInput;
24
+ req: PayloadRequest;
25
+ slug: CollectionSlug;
26
+ }): Promise<File | undefined>;
27
+ export {};
28
+ //# sourceMappingURL=fileInput.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fileInput.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/fileInput.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,IAAI,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAEnE,OAAO,EAAY,CAAC,EAAE,MAAM,SAAS,CAAA;AAwBrC,eAAO,MAAM,eAAe;;;;;;;;;;;;;;;;;8BAoBzB,CAAA;AAEH,KAAK,SAAS,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,eAAe,CAAC,CAAA;AAEhD,wBAAsB,WAAW,CAAC,EAChC,IAAI,EACJ,KAAK,EACL,GAAG,GACJ,EAAE;IACD,KAAK,CAAC,EAAE,SAAS,CAAA;IACjB,GAAG,EAAE,cAAc,CAAA;IACnB,IAAI,EAAE,cAAc,CAAA;CACrB,GAAG,OAAO,CAAC,IAAI,GAAG,SAAS,CAAC,CA2C5B"}
@@ -0,0 +1,88 @@
1
+ import { APIError, z } from 'payload';
2
+ import { externalURLInputSchema, getFileFromUploadInstructions, resolveURLUploadInput } from 'payload/internal';
3
+ import { sanitizeFilename } from 'payload/shared';
4
+ const mimeTypeSchema = z.string().check(z.regex(/^[!#$%&'*+.^`|~\w-]+\/[!#$%&'*+.^`|~\w-]+$/, 'MIME type must use the type/subtype format'));
5
+ const uploadFileSchema = z.strictObject({
6
+ filename: z.string(),
7
+ mimeType: z.string(),
8
+ size: z.int().check(z.nonnegative()),
9
+ uploadReference: z.record(z.string(), z.unknown())
10
+ });
11
+ export const fileInputSchema = z.discriminatedUnion('source', [
12
+ z.strictObject({
13
+ name: z.string().check(z.minLength(1), z.describe('The file name, including its extension.')),
14
+ data: z.string().check(z.describe('The base64-encoded file bytes, without a data URL prefix.')),
15
+ mimeType: mimeTypeSchema.check(z.describe('The file MIME type, for example image/png.')),
16
+ source: z.literal('base64')
17
+ }),
18
+ externalURLInputSchema,
19
+ z.strictObject({
20
+ file: uploadFileSchema.check(z.describe('getUploadInstructions file field post-upload.')),
21
+ source: z.literal('uploadReference')
22
+ })
23
+ ]).check(z.describe('A file for an upload collection. Prefer uploadReference after its upload succeeds; use base64 only for small local files or externalURL for an online file.'));
24
+ export async function resolveFile({ slug, input, req }) {
25
+ if (!input) {
26
+ return undefined;
27
+ }
28
+ if (input.source === 'uploadReference') {
29
+ try {
30
+ return await getFileFromUploadInstructions({
31
+ collectionSlug: slug,
32
+ file: input.file,
33
+ req
34
+ });
35
+ } catch (error) {
36
+ if (error instanceof Error && error.message === 'Staged upload was not found.') {
37
+ throw new APIError('Staged upload not found. Complete the upload action first, or use base64 for small local files.', 400);
38
+ }
39
+ throw error;
40
+ }
41
+ }
42
+ if (input.source === 'externalURL') {
43
+ return resolveURLUploadInput({
44
+ slug,
45
+ input,
46
+ req
47
+ });
48
+ }
49
+ const uploadConfig = req.payload.collections[slug]?.config.upload;
50
+ if (!uploadConfig) {
51
+ throw new APIError(`Collection "${slug}" does not support file uploads.`, 400);
52
+ }
53
+ const maxFileSize = req.payload.config.upload.limits?.fileSize;
54
+ const data = decodeBase64({
55
+ maxFileSize,
56
+ value: input.data
57
+ });
58
+ const file = {
59
+ name: sanitizeFilename(input.name),
60
+ data,
61
+ mimetype: input.mimeType,
62
+ size: data.length
63
+ };
64
+ if (maxFileSize !== undefined && Number.isFinite(maxFileSize) && file.size > maxFileSize) {
65
+ throw new APIError(`File exceeds the ${maxFileSize} byte upload limit.`, 400);
66
+ }
67
+ return file;
68
+ }
69
+ function decodeBase64({ maxFileSize, value }) {
70
+ const normalized = value.replace(/\s/g, '');
71
+ if (!/^[a-z0-9+/]*={0,2}$/i.test(normalized) || normalized.length % 4 === 1) {
72
+ throw new APIError('File data must be valid base64.', 400);
73
+ }
74
+ if (maxFileSize !== undefined && Number.isFinite(maxFileSize)) {
75
+ const paddingLength = normalized.endsWith('==') ? 2 : normalized.endsWith('=') ? 1 : 0;
76
+ const decodedSize = Math.floor(normalized.length * 3 / 4) - paddingLength;
77
+ if (decodedSize > maxFileSize) {
78
+ throw new APIError(`File exceeds the ${maxFileSize} byte upload limit.`, 400);
79
+ }
80
+ }
81
+ const data = Buffer.from(normalized, 'base64');
82
+ if (data.toString('base64').replace(/=+$/, '') !== normalized.replace(/=+$/, '')) {
83
+ throw new APIError('File data must be valid base64.', 400);
84
+ }
85
+ return data;
86
+ }
87
+
88
+ //# sourceMappingURL=fileInput.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/mcp/builtin/collections/fileInput.ts"],"sourcesContent":["import type { CollectionSlug, File, PayloadRequest } from 'payload'\n\nimport { APIError, z } from 'payload'\nimport {\n externalURLInputSchema,\n getFileFromUploadInstructions,\n resolveURLUploadInput,\n} from 'payload/internal'\nimport { sanitizeFilename } from 'payload/shared'\n\nconst mimeTypeSchema = z\n .string()\n .check(\n z.regex(\n /^[!#$%&'*+.^`|~\\w-]+\\/[!#$%&'*+.^`|~\\w-]+$/,\n 'MIME type must use the type/subtype format',\n ),\n )\n\nconst uploadFileSchema = z.strictObject({\n filename: z.string(),\n mimeType: z.string(),\n size: z.int().check(z.nonnegative()),\n uploadReference: z.record(z.string(), z.unknown()),\n})\n\nexport const fileInputSchema = z\n .discriminatedUnion('source', [\n z.strictObject({\n name: z.string().check(z.minLength(1), z.describe('The file name, including its extension.')),\n data: z\n .string()\n .check(z.describe('The base64-encoded file bytes, without a data URL prefix.')),\n mimeType: mimeTypeSchema.check(z.describe('The file MIME type, for example image/png.')),\n source: z.literal('base64'),\n }),\n externalURLInputSchema,\n z.strictObject({\n file: uploadFileSchema.check(z.describe('getUploadInstructions file field post-upload.')),\n source: z.literal('uploadReference'),\n }),\n ])\n .check(\n z.describe(\n 'A file for an upload collection. Prefer uploadReference after its upload succeeds; use base64 only for small local files or externalURL for an online file.',\n ),\n )\n\ntype FileInput = z.infer<typeof fileInputSchema>\n\nexport async function resolveFile({\n slug,\n input,\n req,\n}: {\n input?: FileInput\n req: PayloadRequest\n slug: CollectionSlug\n}): Promise<File | undefined> {\n if (!input) {\n return undefined\n }\n\n if (input.source === 'uploadReference') {\n try {\n return await getFileFromUploadInstructions({ collectionSlug: slug, file: input.file, req })\n } catch (error) {\n if (error instanceof Error && error.message === 'Staged upload was not found.') {\n throw new APIError(\n 'Staged upload not found. Complete the upload action first, or use base64 for small local files.',\n 400,\n )\n }\n throw error\n }\n }\n\n if (input.source === 'externalURL') {\n return resolveURLUploadInput({ slug, input, req })\n }\n\n const uploadConfig = req.payload.collections[slug]?.config.upload\n\n if (!uploadConfig) {\n throw new APIError(`Collection \"${slug}\" does not support file uploads.`, 400)\n }\n\n const maxFileSize = req.payload.config.upload.limits?.fileSize\n const data = decodeBase64({ maxFileSize, value: input.data })\n const file: File = {\n name: sanitizeFilename(input.name),\n data,\n mimetype: input.mimeType,\n size: data.length,\n }\n\n if (maxFileSize !== undefined && Number.isFinite(maxFileSize) && file.size > maxFileSize) {\n throw new APIError(`File exceeds the ${maxFileSize} byte upload limit.`, 400)\n }\n\n return file\n}\n\nfunction decodeBase64({ maxFileSize, value }: { maxFileSize?: number; value: string }): Buffer {\n const normalized = value.replace(/\\s/g, '')\n\n if (!/^[a-z0-9+/]*={0,2}$/i.test(normalized) || normalized.length % 4 === 1) {\n throw new APIError('File data must be valid base64.', 400)\n }\n\n if (maxFileSize !== undefined && Number.isFinite(maxFileSize)) {\n const paddingLength = normalized.endsWith('==') ? 2 : normalized.endsWith('=') ? 1 : 0\n const decodedSize = Math.floor((normalized.length * 3) / 4) - paddingLength\n\n if (decodedSize > maxFileSize) {\n throw new APIError(`File exceeds the ${maxFileSize} byte upload limit.`, 400)\n }\n }\n\n const data = Buffer.from(normalized, 'base64')\n\n if (data.toString('base64').replace(/=+$/, '') !== normalized.replace(/=+$/, '')) {\n throw new APIError('File data must be valid base64.', 400)\n }\n\n return data\n}\n"],"names":["APIError","z","externalURLInputSchema","getFileFromUploadInstructions","resolveURLUploadInput","sanitizeFilename","mimeTypeSchema","string","check","regex","uploadFileSchema","strictObject","filename","mimeType","size","int","nonnegative","uploadReference","record","unknown","fileInputSchema","discriminatedUnion","name","minLength","describe","data","source","literal","file","resolveFile","slug","input","req","undefined","collectionSlug","error","Error","message","uploadConfig","payload","collections","config","upload","maxFileSize","limits","fileSize","decodeBase64","value","mimetype","length","Number","isFinite","normalized","replace","test","paddingLength","endsWith","decodedSize","Math","floor","Buffer","from","toString"],"mappings":"AAEA,SAASA,QAAQ,EAAEC,CAAC,QAAQ,UAAS;AACrC,SACEC,sBAAsB,EACtBC,6BAA6B,EAC7BC,qBAAqB,QAChB,mBAAkB;AACzB,SAASC,gBAAgB,QAAQ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D,IAAIE,cAAcd,aAAa;YAC7B,MAAM,IAAI3C,SAAS,CAAC,iBAAiB,EAAE2C,YAAY,mBAAmB,CAAC,EAAE;QAC3E;IACF;IAEA,MAAMlB,OAAOmC,OAAOC,IAAI,CAACT,YAAY;IAErC,IAAI3B,KAAKqC,QAAQ,CAAC,UAAUT,OAAO,CAAC,OAAO,QAAQD,WAAWC,OAAO,CAAC,OAAO,KAAK;QAChF,MAAM,IAAIrD,SAAS,mCAAmC;IACxD;IAEA,OAAOyB;AACT"}
@@ -0,0 +1,86 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { fileInputSchema, resolveFile } from './fileInput.js';
3
+ describe('MCP file input', ()=>{
4
+ it('should reject malformed MIME types', ()=>{
5
+ const result = fileInputSchema.safeParse({
6
+ data: 'aGVsbG8=',
7
+ mimeType: 'text/plain\r\nx-test: value',
8
+ name: 'hello.txt',
9
+ source: 'base64'
10
+ });
11
+ expect(result.success).toBe(false);
12
+ });
13
+ it('should accept a prepared upload', ()=>{
14
+ const result = fileInputSchema.safeParse({
15
+ file: {
16
+ filename: 'image.png',
17
+ mimeType: 'image/png',
18
+ size: 123,
19
+ uploadReference: {
20
+ uploadId: 'upload-id'
21
+ }
22
+ },
23
+ source: 'uploadReference'
24
+ });
25
+ expect(result.success).toBe(true);
26
+ });
27
+ it('should reject oversized base64 files', async ()=>{
28
+ const req = createRequest({
29
+ maxFileSize: 4
30
+ });
31
+ await expect(resolveFile({
32
+ slug: 'media',
33
+ input: {
34
+ data: Buffer.from('hello').toString('base64'),
35
+ mimeType: 'text/plain',
36
+ name: 'hello.txt',
37
+ source: 'base64'
38
+ },
39
+ req
40
+ })).rejects.toThrow('File exceeds the 4 byte upload limit.');
41
+ });
42
+ it('should reject URLs outside the collection allowlist', async ()=>{
43
+ const req = createRequest({
44
+ allowList: [
45
+ {
46
+ hostname: 'assets.example.com',
47
+ protocol: 'https'
48
+ }
49
+ ]
50
+ });
51
+ await expect(resolveFile({
52
+ slug: 'media',
53
+ input: {
54
+ source: 'externalURL',
55
+ url: 'https://example.com/image.png'
56
+ },
57
+ req
58
+ })).rejects.toThrow('The provided file URL is not allowed.');
59
+ });
60
+ });
61
+ function createRequest({ allowList, maxFileSize }) {
62
+ return {
63
+ payload: {
64
+ collections: {
65
+ media: {
66
+ config: {
67
+ upload: allowList ? {
68
+ pasteURL: {
69
+ allowList
70
+ }
71
+ } : {}
72
+ }
73
+ }
74
+ },
75
+ config: {
76
+ upload: {
77
+ limits: {
78
+ fileSize: maxFileSize
79
+ }
80
+ }
81
+ }
82
+ }
83
+ };
84
+ }
85
+
86
+ //# sourceMappingURL=fileInput.spec.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/mcp/builtin/collections/fileInput.spec.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\n\nimport { describe, expect, it } from 'vitest'\n\nimport { fileInputSchema, resolveFile } from './fileInput.js'\n\ndescribe('MCP file input', () => {\n it('should reject malformed MIME types', () => {\n const result = fileInputSchema.safeParse({\n data: 'aGVsbG8=',\n mimeType: 'text/plain\\r\\nx-test: value',\n name: 'hello.txt',\n source: 'base64',\n })\n\n expect(result.success).toBe(false)\n })\n\n it('should accept a prepared upload', () => {\n const result = fileInputSchema.safeParse({\n file: {\n filename: 'image.png',\n mimeType: 'image/png',\n size: 123,\n uploadReference: { uploadId: 'upload-id' },\n },\n source: 'uploadReference',\n })\n\n expect(result.success).toBe(true)\n })\n\n it('should reject oversized base64 files', async () => {\n const req = createRequest({ maxFileSize: 4 })\n\n await expect(\n resolveFile({\n slug: 'media',\n input: {\n data: Buffer.from('hello').toString('base64'),\n mimeType: 'text/plain',\n name: 'hello.txt',\n source: 'base64',\n },\n req,\n }),\n ).rejects.toThrow('File exceeds the 4 byte upload limit.')\n })\n\n it('should reject URLs outside the collection allowlist', async () => {\n const req = createRequest({\n allowList: [{ hostname: 'assets.example.com', protocol: 'https' }],\n })\n\n await expect(\n resolveFile({\n slug: 'media',\n input: {\n source: 'externalURL',\n url: 'https://example.com/image.png',\n },\n req,\n }),\n ).rejects.toThrow('The provided file URL is not allowed.')\n })\n})\n\nfunction createRequest({\n allowList,\n maxFileSize,\n}: {\n allowList?: Array<{ hostname: string; protocol: 'http' | 'https' }>\n maxFileSize?: number\n}): PayloadRequest {\n return {\n payload: {\n collections: {\n media: {\n config: {\n upload: allowList ? { pasteURL: { allowList } } : {},\n },\n },\n },\n config: {\n upload: {\n limits: {\n fileSize: maxFileSize,\n },\n },\n },\n },\n } as unknown as PayloadRequest\n}\n"],"names":["describe","expect","it","fileInputSchema","resolveFile","result","safeParse","data","mimeType","name","source","success","toBe","file","filename","size","uploadReference","uploadId","req","createRequest","maxFileSize","slug","input","Buffer","from","toString","rejects","toThrow","allowList","hostname","protocol","url","payload","collections","media","config","upload","pasteURL","limits","fileSize"],"mappings":"AAEA,SAASA,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAQ;AAE7C,SAASC,eAAe,EAAEC,WAAW,QAAQ,iBAAgB;AAE7DJ,SAAS,kBAAkB;IACzBE,GAAG,sCAAsC;QACvC,MAAMG,SAASF,gBAAgBG,SAAS,CAAC;YACvCC,MAAM;YACNC,UAAU;YACVC,MAAM;YACNC,QAAQ;QACV;QAEAT,OAAOI,OAAOM,OAAO,EAAEC,IAAI,CAAC;IAC9B;IAEAV,GAAG,mCAAmC;QACpC,MAAMG,SAASF,gBAAgBG,SAAS,CAAC;YACvCO,MAAM;gBACJC,UAAU;gBACVN,UAAU;gBACVO,MAAM;gBACNC,iBAAiB;oBAAEC,UAAU;gBAAY;YAC3C;YACAP,QAAQ;QACV;QAEAT,OAAOI,OAAOM,OAAO,EAAEC,IAAI,CAAC;IAC9B;IAEAV,GAAG,wCAAwC;QACzC,MAAMgB,MAAMC,cAAc;YAAEC,aAAa;QAAE;QAE3C,MAAMnB,OACJG,YAAY;YACViB,MAAM;YACNC,OAAO;gBACLf,MAAMgB,OAAOC,IAAI,CAAC,SAASC,QAAQ,CAAC;gBACpCjB,UAAU;gBACVC,MAAM;gBACNC,QAAQ;YACV;YACAQ;QACF,IACAQ,OAAO,CAACC,OAAO,CAAC;IACpB;IAEAzB,GAAG,uDAAuD;QACxD,MAAMgB,MAAMC,cAAc;YACxBS,WAAW;gBAAC;oBAAEC,UAAU;oBAAsBC,UAAU;gBAAQ;aAAE;QACpE;QAEA,MAAM7B,OACJG,YAAY;YACViB,MAAM;YACNC,OAAO;gBACLZ,QAAQ;gBACRqB,KAAK;YACP;YACAb;QACF,IACAQ,OAAO,CAACC,OAAO,CAAC;IACpB;AACF;AAEA,SAASR,cAAc,EACrBS,SAAS,EACTR,WAAW,EAIZ;IACC,OAAO;QACLY,SAAS;YACPC,aAAa;gBACXC,OAAO;oBACLC,QAAQ;wBACNC,QAAQR,YAAY;4BAAES,UAAU;gCAAET;4BAAU;wBAAE,IAAI,CAAC;oBACrD;gBACF;YACF;YACAO,QAAQ;gBACNC,QAAQ;oBACNE,QAAQ;wBACNC,UAAUnB;oBACZ;gBACF;YACF;QACF;IACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"findDistinctTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/findDistinctTool.ts"],"names":[],"mappings":"AAaA,eAAO,MAAM,gBAAgB,4CAyG3B,CAAA"}
1
+ {"version":3,"file":"findDistinctTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/findDistinctTool.ts"],"names":[],"mappings":"AASA,eAAO,MAAM,gBAAgB,4CAyD3B,CAAA"}
@@ -1,12 +1,10 @@
1
- import { z } from 'zod';
1
+ import { findDistinctInputSchema } from 'payload';
2
2
  import { defaultAccess } from '../../../defaultAccess.js';
3
3
  import { defineCollectionTool } from '../../../defineTool.js';
4
4
  import { getLogger } from '../../../utils/getLogger.js';
5
- import { localAPIDefaults } from '../../../utils/localAPIDefaults.js';
6
- import { whereSchema } from '../../../utils/whereSchema.js';
7
5
  const DEFAULT_DESCRIPTION = 'Find distinct values for a field in any collection by passing the collection slug and field path.';
8
6
  export const findDistinctTool = defineCollectionTool({
9
- access: (args)=>defaultAccess(args) && Boolean(args.permissions?.collections?.[args.collectionSlug]?.read),
7
+ access: (args)=>defaultAccess(args) && Boolean(args.permissions?.collections?.[args.slug]?.read),
10
8
  annotations: {
11
9
  destructiveHint: false,
12
10
  idempotentHint: true,
@@ -15,32 +13,21 @@ export const findDistinctTool = defineCollectionTool({
15
13
  title: 'Find Distinct'
16
14
  },
17
15
  description: DEFAULT_DESCRIPTION,
18
- input: z.object({
19
- depth: z.number().int().min(0).max(10).describe('How many levels deep to populate relationships in distinct values').optional().default(0),
20
- field: z.string().describe('The field path to get distinct values for'),
21
- limit: z.number().int().min(1).max(100).describe('Maximum number of distinct values to return (max: 100)').optional(),
22
- locale: z.string().describe('Optional: locale code to retrieve data in (e.g., "en", "es"). Use "all" to retrieve all locales for localized fields').optional(),
23
- page: z.number().int().min(1).describe('Page number for pagination').optional(),
24
- populate: z.record(z.string(), z.unknown()).describe('Optional: control which fields to include from populated relationship or upload documents.').optional(),
25
- showHiddenFields: z.boolean().describe('Optional: include hidden fields in the distinct query').optional(),
26
- sort: z.string().describe('Field to sort by (e.g., "createdAt", "-updatedAt" for descending)').optional(),
27
- trash: z.boolean().describe('Optional: include soft-deleted documents when trash is enabled on the collection').optional(),
28
- where: whereSchema.describe('Optional: where clause for filtering. Use field names with Payload operators, and/or arrays for grouping. Example: {"title":{"contains":"test"}}').optional()
29
- })
30
- }).handler(async ({ authorizedMCP, collectionSlug, input, req })=>{
16
+ input: findDistinctInputSchema
17
+ }).handler(async ({ slug, authorizedMCP, input, req })=>{
31
18
  const payload = req.payload;
32
19
  const logger = getLogger({
33
20
  payload
34
21
  });
35
- const { depth, field, limit, locale, page, populate, showHiddenFields, sort, trash, where } = input;
36
- logger.info(`Finding distinct values in collection: ${collectionSlug}, field: ${field}`);
22
+ const { depth, field, limit, locale, page, populate, sort, trash, where } = input;
23
+ logger.info(`Finding distinct values in collection: ${slug}, field: ${field}`);
37
24
  try {
38
25
  const result = await payload.findDistinct({
39
- collection: collectionSlug,
26
+ collection: slug,
40
27
  depth,
41
28
  field,
29
+ overrideAccess: authorizedMCP.overrideAccess,
42
30
  req,
43
- ...localAPIDefaults(authorizedMCP),
44
31
  ...limit ? {
45
32
  limit
46
33
  } : {},
@@ -51,10 +38,7 @@ export const findDistinctTool = defineCollectionTool({
51
38
  page
52
39
  } : {},
53
40
  ...populate ? {
54
- populate: populate
55
- } : {},
56
- ...showHiddenFields !== undefined ? {
57
- showHiddenFields
41
+ populate
58
42
  } : {},
59
43
  ...sort ? {
60
44
  sort
@@ -70,19 +54,19 @@ export const findDistinctTool = defineCollectionTool({
70
54
  content: [
71
55
  {
72
56
  type: 'text',
73
- text: `Distinct values for "${field}" in collection "${collectionSlug}":\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``
57
+ text: `Distinct values for "${field}" in collection "${slug}":\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``
74
58
  }
75
59
  ],
76
60
  doc: result
77
61
  };
78
62
  } catch (error) {
79
63
  const errorMessage = error instanceof Error ? error.message : 'Unknown error';
80
- logger.error(`Error finding distinct values in ${collectionSlug}: ${errorMessage}`);
64
+ logger.error(`Error finding distinct values in ${slug}: ${errorMessage}`);
81
65
  return {
82
66
  content: [
83
67
  {
84
68
  type: 'text',
85
- text: `❌ **Error finding distinct values in collection "${collectionSlug}":** ${errorMessage}`
69
+ text: `❌ **Error finding distinct values in collection "${slug}":** ${errorMessage}`
86
70
  }
87
71
  ],
88
72
  isError: true
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/mcp/builtin/collections/findDistinctTool.ts"],"sourcesContent":["import type { PopulateType } from 'payload'\n\nimport { z } from 'zod'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\nimport { localAPIDefaults } from '../../../utils/localAPIDefaults.js'\nimport { whereSchema } from '../../../utils/whereSchema.js'\n\nconst DEFAULT_DESCRIPTION =\n 'Find distinct values for a field in any collection by passing the collection slug and field path.'\n\nexport const findDistinctTool = defineCollectionTool({\n access: (args) =>\n defaultAccess(args) && Boolean(args.permissions?.collections?.[args.collectionSlug]?.read),\n annotations: {\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n readOnlyHint: true,\n title: 'Find Distinct',\n },\n description: DEFAULT_DESCRIPTION,\n input: z.object({\n depth: z\n .number()\n .int()\n .min(0)\n .max(10)\n .describe('How many levels deep to populate relationships in distinct values')\n .optional()\n .default(0),\n field: z.string().describe('The field path to get distinct values for'),\n limit: z\n .number()\n .int()\n .min(1)\n .max(100)\n .describe('Maximum number of distinct values to return (max: 100)')\n .optional(),\n locale: z\n .string()\n .describe(\n 'Optional: locale code to retrieve data in (e.g., \"en\", \"es\"). Use \"all\" to retrieve all locales for localized fields',\n )\n .optional(),\n page: z.number().int().min(1).describe('Page number for pagination').optional(),\n populate: z\n .record(z.string(), z.unknown())\n .describe(\n 'Optional: control which fields to include from populated relationship or upload documents.',\n )\n .optional(),\n showHiddenFields: z\n .boolean()\n .describe('Optional: include hidden fields in the distinct query')\n .optional(),\n sort: z\n .string()\n .describe('Field to sort by (e.g., \"createdAt\", \"-updatedAt\" for descending)')\n .optional(),\n trash: z\n .boolean()\n .describe('Optional: include soft-deleted documents when trash is enabled on the collection')\n .optional(),\n where: whereSchema\n .describe(\n 'Optional: where clause for filtering. Use field names with Payload operators, and/or arrays for grouping. Example: {\"title\":{\"contains\":\"test\"}}',\n )\n .optional(),\n }),\n}).handler(async ({ authorizedMCP, collectionSlug, input, req }) => {\n const payload = req.payload\n const logger = getLogger({ payload })\n const { depth, field, limit, locale, page, populate, showHiddenFields, sort, trash, where } = input\n\n logger.info(`Finding distinct values in collection: ${collectionSlug}, field: ${field}`)\n\n try {\n const result = await payload.findDistinct({\n collection: collectionSlug,\n depth,\n field,\n req,\n ...localAPIDefaults(authorizedMCP),\n ...(limit ? { limit } : {}),\n ...(locale ? { locale } : {}),\n ...(page ? { page } : {}),\n ...(populate ? { populate: populate as PopulateType } : {}),\n ...(showHiddenFields !== undefined ? { showHiddenFields } : {}),\n ...(sort ? { sort } : {}),\n ...(trash !== undefined ? { trash } : {}),\n ...(where ? { where } : {}),\n })\n\n return {\n content: [\n {\n type: 'text',\n text: `Distinct values for \"${field}\" in collection \"${collectionSlug}\":\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as unknown as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error finding distinct values in ${collectionSlug}: ${errorMessage}`)\n return {\n content: [\n {\n type: 'text',\n text: `❌ **Error finding distinct values in collection \"${collectionSlug}\":** ${errorMessage}`,\n },\n ],\n isError: true,\n }\n }\n})\n"],"names":["z","defaultAccess","defineCollectionTool","getLogger","localAPIDefaults","whereSchema","DEFAULT_DESCRIPTION","findDistinctTool","access","args","Boolean","permissions","collections","collectionSlug","read","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","object","depth","number","int","min","max","describe","optional","default","field","string","limit","locale","page","populate","record","unknown","showHiddenFields","boolean","sort","trash","where","handler","authorizedMCP","req","payload","logger","info","result","findDistinct","collection","undefined","content","type","text","JSON","stringify","doc","error","errorMessage","Error","message","isError"],"mappings":"AAEA,SAASA,CAAC,QAAQ,MAAK;AAEvB,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AACvD,SAASC,gBAAgB,QAAQ,qCAAoC;AACrE,SAASC,WAAW,QAAQ,gCAA+B;AAE3D,MAAMC,sBACJ;AAEF,OAAO,MAAMC,mBAAmBL,qBAAqB;IACnDM,QAAQ,CAACC,OACPR,cAAcQ,SAASC,QAAQD,KAAKE,WAAW,EAAEC,aAAa,CAACH,KAAKI,cAAc,CAAC,EAAEC;IACvFC,aAAa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DistinctTool.ts"],"sourcesContent":["import { findDistinctInputSchema } from 'payload'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\n\nconst DEFAULT_DESCRIPTION =\n 'Find distinct values for a field in any collection by passing the collection slug and field path.'\n\nexport const findDistinctTool = defineCollectionTool({\n access: (args) =>\n defaultAccess(args) && Boolean(args.permissions?.collections?.[args.slug]?.read),\n annotations: {\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n readOnlyHint: true,\n title: 'Find Distinct',\n },\n description: DEFAULT_DESCRIPTION,\n input: findDistinctInputSchema,\n}).handler(async ({ slug, authorizedMCP, input, req }) => {\n const payload = req.payload\n const logger = getLogger({ payload })\n const { depth, field, limit, locale, page, populate, sort, trash, where } = input\n\n logger.info(`Finding distinct values in collection: ${slug}, field: ${field}`)\n\n try {\n const result = await payload.findDistinct({\n collection: slug,\n depth,\n field,\n overrideAccess: authorizedMCP.overrideAccess,\n req,\n ...(limit ? { limit } : {}),\n ...(locale ? { locale } : {}),\n ...(page ? { page } : {}),\n ...(populate ? { populate } : {}),\n ...(sort ? { sort } : {}),\n ...(trash !== undefined ? { trash } : {}),\n ...(where ? { where } : {}),\n })\n\n return {\n content: [\n {\n type: 'text',\n text: `Distinct values for \"${field}\" in collection \"${slug}\":\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as unknown as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error finding distinct values in ${slug}: ${errorMessage}`)\n return {\n content: [\n {\n type: 'text',\n text: `❌ **Error finding distinct values in collection \"${slug}\":** ${errorMessage}`,\n },\n ],\n isError: true,\n }\n }\n})\n"],"names":["findDistinctInputSchema","defaultAccess","defineCollectionTool","getLogger","DEFAULT_DESCRIPTION","findDistinctTool","access","args","Boolean","permissions","collections","slug","read","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","handler","authorizedMCP","req","payload","logger","depth","field","limit","locale","page","populate","sort","trash","where","info","result","findDistinct","collection","overrideAccess","undefined","content","type","text","JSON","stringify","doc","error","errorMessage","Error","message","isError"],"mappings":"AAAA,SAASA,uBAAuB,QAAQ,UAAS;AAEjD,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AAEvD,MAAMC,sBACJ;AAEF,OAAO,MAAMC,mBAAmBH,qBAAqB;IACnDI,QAAQ,CAACC,OACPN,cAAcM,SAASC,QAAQD,KAAKE,WAAW,EAAEC,aAAa,CAACH,KAAKI,IAAI,CAAC,EAAEC;IAC7EC,aAAa;QACXC,iBAAiB;QACjBC,gBAAgB;QAChBC,eAAe;QACfC,cAAc;QACdC,OAAO;IACT;IACAC,aAAaf;IACbgB,OAAOpB;AACT,GAAGqB,OAAO,CAAC,OAAO,EAAEV,IAAI,EAAEW,aAAa,EAAEF,KAAK,EAAEG,GAAG,EAAE;IACnD,MAAMC,UAAUD,IAAIC,OAAO;IAC3B,MAAMC,SAAStB,UAAU;QAAEqB;IAAQ;IACnC,MAAM,EAAEE,KAAK,EAAEC,KAAK,EAAEC,KAAK,EAAEC,MAAM,EAAEC,IAAI,EAAEC,QAAQ,EAAEC,IAAI,EAAEC,KAAK,EAAEC,KAAK,EAAE,GAAGd;IAE5EK,OAAOU,IAAI,CAAC,CAAC,uCAAuC,EAAExB,KAAK,SAAS,EAAEgB,OAAO;IAE7E,IAAI;QACF,MAAMS,SAAS,MAAMZ,QAAQa,YAAY,CAAC;YACxCC,YAAY3B;YACZe;YACAC;YACAY,gBAAgBjB,cAAciB,cAAc;YAC5ChB;YACA,GAAIK,QAAQ;gBAAEA;YAAM,IAAI,CAAC,CAAC;YAC1B,GAAIC,SAAS;gBAAEA;YAAO,IAAI,CAAC,CAAC;YAC5B,GAAIC,OAAO;gBAAEA;YAAK,IAAI,CAAC,CAAC;YACxB,GAAIC,WAAW;gBAAEA;YAAS,IAAI,CAAC,CAAC;YAChC,GAAIC,OAAO;gBAAEA;YAAK,IAAI,CAAC,CAAC;YACxB,GAAIC,UAAUO,YAAY;gBAAEP;YAAM,IAAI,CAAC,CAAC;YACxC,GAAIC,QAAQ;gBAAEA;YAAM,IAAI,CAAC,CAAC;QAC5B;QAEA,OAAO;YACLO,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,qBAAqB,EAAEhB,MAAM,iBAAiB,EAAEhB,KAAK,gBAAgB,EAAEiC,KAAKC,SAAS,CAACT,QAAQ,QAAQ,CAAC;gBAChH;aACD;YACDU,KAAKV;QACP;IACF,EAAE,OAAOW,OAAO;QACd,MAAMC,eAAeD,iBAAiBE,QAAQF,MAAMG,OAAO,GAAG;QAC9DzB,OAAOsB,KAAK,CAAC,CAAC,iCAAiC,EAAEpC,KAAK,EAAE,EAAEqC,cAAc;QACxE,OAAO;YACLP,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,iDAAiD,EAAEhC,KAAK,KAAK,EAAEqC,cAAc;gBACtF;aACD;YACDG,SAAS;QACX;IACF;AACF,GAAE"}
@@ -1 +1 @@
1
- {"version":3,"file":"findTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/findTool.ts"],"names":[],"mappings":"AAaA,eAAO,MAAM,iBAAiB,4CA2M5B,CAAA"}
1
+ {"version":3,"file":"findTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/findTool.ts"],"names":[],"mappings":"AASA,eAAO,MAAM,iBAAiB,4CA4H5B,CAAA"}
@@ -1,12 +1,10 @@
1
- import { z } from 'zod';
1
+ import { findDocumentsInputSchema, parseDocumentID } from 'payload';
2
2
  import { defaultAccess } from '../../../defaultAccess.js';
3
3
  import { defineCollectionTool } from '../../../defineTool.js';
4
4
  import { getLogger } from '../../../utils/getLogger.js';
5
- import { localAPIDefaults } from '../../../utils/localAPIDefaults.js';
6
- import { whereSchema } from '../../../utils/whereSchema.js';
7
5
  const DEFAULT_DESCRIPTION = 'Find documents in any collection by passing the collection slug and optional ID or where clause.';
8
6
  export const findDocumentsTool = defineCollectionTool({
9
- access: (args)=>defaultAccess(args) && Boolean(args.permissions?.collections?.[args.collectionSlug]?.read),
7
+ access: (args)=>defaultAccess(args) && Boolean(args.permissions?.collections?.[args.slug]?.read),
10
8
  annotations: {
11
9
  destructiveHint: false,
12
10
  idempotentHint: true,
@@ -15,57 +13,40 @@ export const findDocumentsTool = defineCollectionTool({
15
13
  title: 'Find Documents'
16
14
  },
17
15
  description: DEFAULT_DESCRIPTION,
18
- input: z.object({
19
- id: z.union([
20
- z.string(),
21
- z.number()
22
- ]).describe('Optional: specific document ID to retrieve. If not provided, returns all documents').optional(),
23
- depth: z.number().int().min(0).max(10).describe('How many levels deep to populate relationships (default: 0)').optional().default(0),
24
- draft: z.boolean().describe('Optional: whether the document should be queried from the versions table/collection or not.').optional(),
25
- fallbackLocale: z.string().describe('Optional: fallback locale code to use when requested locale is not available').optional(),
26
- joins: z.union([
27
- z.record(z.string(), z.unknown()),
28
- z.literal(false)
29
- ]).describe('Optional: configure join field queries, or pass false to disable all join fields.').optional(),
30
- limit: z.number().int().min(1).max(100).describe('Maximum number of documents to return (default: 10, max: 100)').optional().default(10),
31
- locale: z.string().describe('Optional: locale code to retrieve data in (e.g., "en", "es"). Use "all" to retrieve all locales for localized fields').optional(),
32
- page: z.number().int().min(1).describe('Page number for pagination (default: 1)').optional().default(1),
33
- pagination: z.boolean().describe('Optional: set to false to skip the count query overhead').optional(),
34
- populate: z.record(z.string(), z.unknown()).describe('Optional: control which fields to include from populated relationship or upload documents.').optional(),
35
- select: z.record(z.string(), z.unknown()).describe('Optional: define exactly which fields you\'d like to return in the response, e.g., {"title": true}').optional(),
36
- sort: z.string().describe('Field to sort by (e.g., "createdAt", "-updatedAt" for descending)').optional(),
37
- trash: z.boolean().describe('Optional: include soft-deleted documents when trash is enabled on the collection').optional(),
38
- where: whereSchema.describe('Optional: where clause for filtering. Use field names with Payload operators, and/or arrays for grouping. Example: {"title":{"contains":"test"}}').optional()
39
- })
40
- }).handler(async ({ authorizedMCP, collectionSlug, input, req })=>{
16
+ input: findDocumentsInputSchema
17
+ }).handler(async ({ slug, authorizedMCP, input, req })=>{
41
18
  const payload = req.payload;
42
19
  const logger = getLogger({
43
20
  payload
44
21
  });
45
22
  const { id, depth, draft, fallbackLocale, joins, limit, locale, page, pagination, populate, select, sort, trash, where } = input;
46
- logger.info(`Reading document from collection: ${collectionSlug}${id ? ` with ID: ${id}` : ''}, limit: ${limit}, page: ${page}${locale ? `, locale: ${locale}` : ''}`);
23
+ logger.info(`Reading document from collection: ${slug}${id ? ` with ID: ${id}` : ''}, limit: ${limit}, page: ${page}${locale ? `, locale: ${locale}` : ''}`);
47
24
  try {
48
- if (id) {
25
+ if (id !== undefined) {
49
26
  try {
50
27
  const doc = await payload.findByID({
51
- id,
52
- collection: collectionSlug,
28
+ id: parseDocumentID({
29
+ id,
30
+ collectionSlug: slug,
31
+ payload
32
+ }),
33
+ collection: slug,
53
34
  depth,
35
+ overrideAccess: authorizedMCP.overrideAccess,
54
36
  req,
55
- ...localAPIDefaults(authorizedMCP),
56
37
  ...select && {
57
- select: select
38
+ select
58
39
  },
59
40
  ...populate && {
60
- populate: populate
41
+ populate
61
42
  },
62
43
  ...joins !== undefined && {
63
- joins: joins
44
+ joins
64
45
  },
65
46
  ...locale && {
66
47
  locale
67
48
  },
68
- ...fallbackLocale && {
49
+ ...fallbackLocale !== undefined && {
69
50
  fallbackLocale
70
51
  },
71
52
  ...draft !== undefined && {
@@ -79,43 +60,43 @@ export const findDocumentsTool = defineCollectionTool({
79
60
  content: [
80
61
  {
81
62
  type: 'text',
82
- text: `Document from collection "${collectionSlug}":\n${JSON.stringify(doc)}`
63
+ text: `Document from collection "${slug}":\n${JSON.stringify(doc)}`
83
64
  }
84
65
  ],
85
66
  doc: doc
86
67
  };
87
68
  } catch {
88
- logger.warn(`Document not found with ID: ${id} in collection: ${collectionSlug}`);
69
+ logger.warn(`Document not found with ID: ${id} in collection: ${slug}`);
89
70
  return {
90
71
  content: [
91
72
  {
92
73
  type: 'text',
93
- text: `Error: Document with ID "${id}" not found in collection "${collectionSlug}"`
74
+ text: `Error: Document with ID "${id}" not found in collection "${slug}"`
94
75
  }
95
76
  ]
96
77
  };
97
78
  }
98
79
  }
99
80
  const findOptions = {
100
- collection: collectionSlug,
81
+ collection: slug,
101
82
  depth,
102
83
  limit,
84
+ overrideAccess: authorizedMCP.overrideAccess,
103
85
  page,
104
86
  req,
105
- ...localAPIDefaults(authorizedMCP),
106
87
  ...select && {
107
- select: select
88
+ select
108
89
  },
109
90
  ...populate && {
110
- populate: populate
91
+ populate
111
92
  },
112
93
  ...joins !== undefined && {
113
- joins: joins
94
+ joins
114
95
  },
115
96
  ...locale && {
116
97
  locale
117
98
  },
118
- ...fallbackLocale && {
99
+ ...fallbackLocale !== undefined && {
119
100
  fallbackLocale
120
101
  },
121
102
  ...draft !== undefined && {
@@ -135,7 +116,7 @@ export const findDocumentsTool = defineCollectionTool({
135
116
  findOptions.where = where;
136
117
  }
137
118
  const result = await payload.find(findOptions);
138
- let responseText = `Collection: "${collectionSlug}"\nTotal: ${result.totalDocs} documents\nPage: ${result.page} of ${result.totalPages}\n`;
119
+ let responseText = `Collection: "${slug}"\nTotal: ${result.totalDocs} documents\nPage: ${result.page} of ${result.totalPages}\n`;
139
120
  for (const doc of result.docs){
140
121
  responseText += `\n\`\`\`json\n${JSON.stringify(doc)}\n\`\`\``;
141
122
  }
@@ -150,12 +131,12 @@ export const findDocumentsTool = defineCollectionTool({
150
131
  };
151
132
  } catch (error) {
152
133
  const errorMessage = error instanceof Error ? error.message : 'Unknown error';
153
- logger.error(`Error reading documents from collection ${collectionSlug}: ${errorMessage}`);
134
+ logger.error(`Error reading documents from collection ${slug}: ${errorMessage}`);
154
135
  return {
155
136
  content: [
156
137
  {
157
138
  type: 'text',
158
- text: `❌ **Error reading documents from collection "${collectionSlug}":** ${errorMessage}`
139
+ text: `❌ **Error reading documents from collection "${slug}":** ${errorMessage}`
159
140
  }
160
141
  ]
161
142
  };