@payloadcms/plugin-mcp 4.0.0-internal.9726517 → 4.0.0-internal.a1317b2

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 (165) hide show
  1. package/dist/endpoint/access.js +2 -2
  2. package/dist/endpoint/access.js.map +1 -1
  3. package/dist/mcp/buildMcpServer.d.ts +1 -1
  4. package/dist/mcp/buildMcpServer.d.ts.map +1 -1
  5. package/dist/mcp/buildMcpServer.js +35 -23
  6. package/dist/mcp/buildMcpServer.js.map +1 -1
  7. package/dist/mcp/builtin/collections/authTools.d.ts.map +1 -1
  8. package/dist/mcp/builtin/collections/authTools.js +79 -56
  9. package/dist/mcp/builtin/collections/authTools.js.map +1 -1
  10. package/dist/mcp/builtin/collections/countTool.d.ts.map +1 -1
  11. package/dist/mcp/builtin/collections/countTool.js +9 -14
  12. package/dist/mcp/builtin/collections/countTool.js.map +1 -1
  13. package/dist/mcp/builtin/collections/countVersionsTool.d.ts.map +1 -1
  14. package/dist/mcp/builtin/collections/countVersionsTool.js +9 -13
  15. package/dist/mcp/builtin/collections/countVersionsTool.js.map +1 -1
  16. package/dist/mcp/builtin/collections/createTool.d.ts +1 -1
  17. package/dist/mcp/builtin/collections/createTool.d.ts.map +1 -1
  18. package/dist/mcp/builtin/collections/createTool.js +100 -62
  19. package/dist/mcp/builtin/collections/createTool.js.map +1 -1
  20. package/dist/mcp/builtin/collections/deleteTool.d.ts.map +1 -1
  21. package/dist/mcp/builtin/collections/deleteTool.js +40 -43
  22. package/dist/mcp/builtin/collections/deleteTool.js.map +1 -1
  23. package/dist/mcp/builtin/collections/duplicateTool.d.ts.map +1 -1
  24. package/dist/mcp/builtin/collections/duplicateTool.js +26 -36
  25. package/dist/mcp/builtin/collections/duplicateTool.js.map +1 -1
  26. package/dist/mcp/builtin/collections/fileInput.d.ts +21 -21
  27. package/dist/mcp/builtin/collections/fileInput.d.ts.map +1 -1
  28. package/dist/mcp/builtin/collections/fileInput.js +30 -24
  29. package/dist/mcp/builtin/collections/fileInput.js.map +1 -1
  30. package/dist/mcp/builtin/collections/fileInput.spec.js +2 -2
  31. package/dist/mcp/builtin/collections/fileInput.spec.js.map +1 -1
  32. package/dist/mcp/builtin/collections/findDistinctTool.d.ts.map +1 -1
  33. package/dist/mcp/builtin/collections/findDistinctTool.js +11 -26
  34. package/dist/mcp/builtin/collections/findDistinctTool.js.map +1 -1
  35. package/dist/mcp/builtin/collections/findTool.d.ts.map +1 -1
  36. package/dist/mcp/builtin/collections/findTool.js +21 -43
  37. package/dist/mcp/builtin/collections/findTool.js.map +1 -1
  38. package/dist/mcp/builtin/collections/findVersionByIDTool.d.ts.map +1 -1
  39. package/dist/mcp/builtin/collections/findVersionByIDTool.js +17 -26
  40. package/dist/mcp/builtin/collections/findVersionByIDTool.js.map +1 -1
  41. package/dist/mcp/builtin/collections/findVersionsTool.d.ts.map +1 -1
  42. package/dist/mcp/builtin/collections/findVersionsTool.js +16 -30
  43. package/dist/mcp/builtin/collections/findVersionsTool.js.map +1 -1
  44. package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -1
  45. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +12 -12
  46. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -1
  47. package/dist/mcp/builtin/collections/restoreVersionTool.d.ts.map +1 -1
  48. package/dist/mcp/builtin/collections/restoreVersionTool.js +14 -26
  49. package/dist/mcp/builtin/collections/restoreVersionTool.js.map +1 -1
  50. package/dist/mcp/builtin/collections/updateTool.d.ts.map +1 -1
  51. package/dist/mcp/builtin/collections/updateTool.js +40 -85
  52. package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
  53. package/dist/mcp/builtin/collections/uploadInstructionsTool.js +13 -13
  54. package/dist/mcp/builtin/collections/uploadInstructionsTool.js.map +1 -1
  55. package/dist/mcp/builtin/formatEntityError.d.ts +16 -0
  56. package/dist/mcp/builtin/formatEntityError.d.ts.map +1 -0
  57. package/dist/mcp/builtin/formatEntityError.js +55 -0
  58. package/dist/mcp/builtin/formatEntityError.js.map +1 -0
  59. package/dist/mcp/builtin/getConfigInfoTool.d.ts.map +1 -1
  60. package/dist/mcp/builtin/getConfigInfoTool.js +3 -2
  61. package/dist/mcp/builtin/getConfigInfoTool.js.map +1 -1
  62. package/dist/mcp/builtin/globals/countVersionsTool.d.ts.map +1 -1
  63. package/dist/mcp/builtin/globals/countVersionsTool.js +9 -13
  64. package/dist/mcp/builtin/globals/countVersionsTool.js.map +1 -1
  65. package/dist/mcp/builtin/globals/findTool.d.ts.map +1 -1
  66. package/dist/mcp/builtin/globals/findTool.js +10 -16
  67. package/dist/mcp/builtin/globals/findTool.js.map +1 -1
  68. package/dist/mcp/builtin/globals/findVersionByIDTool.d.ts.map +1 -1
  69. package/dist/mcp/builtin/globals/findVersionByIDTool.js +13 -24
  70. package/dist/mcp/builtin/globals/findVersionByIDTool.js.map +1 -1
  71. package/dist/mcp/builtin/globals/findVersionsTool.d.ts.map +1 -1
  72. package/dist/mcp/builtin/globals/findVersionsTool.js +13 -29
  73. package/dist/mcp/builtin/globals/findVersionsTool.js.map +1 -1
  74. package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts.map +1 -1
  75. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js +11 -11
  76. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js.map +1 -1
  77. package/dist/mcp/builtin/globals/restoreVersionTool.d.ts.map +1 -1
  78. package/dist/mcp/builtin/globals/restoreVersionTool.js +15 -22
  79. package/dist/mcp/builtin/globals/restoreVersionTool.js.map +1 -1
  80. package/dist/mcp/builtin/globals/updateTool.d.ts.map +1 -1
  81. package/dist/mcp/builtin/globals/updateTool.js +27 -36
  82. package/dist/mcp/builtin/globals/updateTool.js.map +1 -1
  83. package/dist/mcp/builtinTools.d.ts.map +1 -1
  84. package/dist/mcp/builtinTools.js +3 -3
  85. package/dist/mcp/builtinTools.js.map +1 -1
  86. package/dist/stdio.d.ts.map +1 -1
  87. package/dist/stdio.js +2 -1
  88. package/dist/stdio.js.map +1 -1
  89. package/dist/types.d.ts +4 -4
  90. package/dist/types.d.ts.map +1 -1
  91. package/dist/types.js.map +1 -1
  92. package/package.json +5 -7
  93. package/src/endpoint/access.ts +2 -3
  94. package/src/mcp/buildMcpServer.ts +39 -29
  95. package/src/mcp/builtin/collections/authTools.ts +77 -69
  96. package/src/mcp/builtin/collections/countTool.ts +9 -21
  97. package/src/mcp/builtin/collections/countVersionsTool.ts +9 -18
  98. package/src/mcp/builtin/collections/createTool.ts +96 -85
  99. package/src/mcp/builtin/collections/deleteTool.ts +36 -64
  100. package/src/mcp/builtin/collections/duplicateTool.ts +33 -84
  101. package/src/mcp/builtin/collections/fileInput.spec.ts +2 -2
  102. package/src/mcp/builtin/collections/fileInput.ts +40 -25
  103. package/src/mcp/builtin/collections/findDistinctTool.ts +11 -63
  104. package/src/mcp/builtin/collections/findTool.ts +21 -103
  105. package/src/mcp/builtin/collections/findVersionByIDTool.ts +15 -58
  106. package/src/mcp/builtin/collections/findVersionsTool.ts +14 -85
  107. package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +11 -11
  108. package/src/mcp/builtin/collections/restoreVersionTool.ts +14 -56
  109. package/src/mcp/builtin/collections/updateTool.ts +49 -107
  110. package/src/mcp/builtin/collections/uploadInstructionsTool.ts +15 -15
  111. package/src/mcp/builtin/formatEntityError.ts +77 -0
  112. package/src/mcp/builtin/getConfigInfoTool.ts +2 -1
  113. package/src/mcp/builtin/globals/countVersionsTool.ts +9 -17
  114. package/src/mcp/builtin/globals/findTool.ts +12 -51
  115. package/src/mcp/builtin/globals/findVersionByIDTool.ts +13 -52
  116. package/src/mcp/builtin/globals/findVersionsTool.ts +14 -92
  117. package/src/mcp/builtin/globals/getGlobalSchemaTool.ts +10 -10
  118. package/src/mcp/builtin/globals/restoreVersionTool.ts +14 -45
  119. package/src/mcp/builtin/globals/updateTool.ts +37 -60
  120. package/src/mcp/builtinTools.ts +2 -2
  121. package/src/stdio.ts +2 -1
  122. package/src/types.ts +4 -4
  123. package/dist/mcp/builtin/collections/formatCollectionError.d.ts +0 -9
  124. package/dist/mcp/builtin/collections/formatCollectionError.d.ts.map +0 -1
  125. package/dist/mcp/builtin/collections/formatCollectionError.js +0 -60
  126. package/dist/mcp/builtin/collections/formatCollectionError.js.map +0 -1
  127. package/dist/mcp/builtin/validateEntityData.d.ts +0 -14
  128. package/dist/mcp/builtin/validateEntityData.d.ts.map +0 -1
  129. package/dist/mcp/builtin/validateEntityData.js +0 -82
  130. package/dist/mcp/builtin/validateEntityData.js.map +0 -1
  131. package/dist/utils/getVirtualFieldNames.d.ts +0 -14
  132. package/dist/utils/getVirtualFieldNames.d.ts.map +0 -1
  133. package/dist/utils/getVirtualFieldNames.js +0 -35
  134. package/dist/utils/getVirtualFieldNames.js.map +0 -1
  135. package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts +0 -28
  136. package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts.map +0 -1
  137. package/dist/utils/schemaConversion/filterFieldsByAccess.js +0 -71
  138. package/dist/utils/schemaConversion/filterFieldsByAccess.js.map +0 -1
  139. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts +0 -13
  140. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts.map +0 -1
  141. package/dist/utils/schemaConversion/getEntityInputSchema.js +0 -66
  142. package/dist/utils/schemaConversion/getEntityInputSchema.js.map +0 -1
  143. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts +0 -10
  144. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts.map +0 -1
  145. package/dist/utils/schemaConversion/sanitizeEntitySchema.js +0 -384
  146. package/dist/utils/schemaConversion/sanitizeEntitySchema.js.map +0 -1
  147. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js +0 -133
  148. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js.map +0 -1
  149. package/dist/utils/transformPointDataToPayload.d.ts +0 -7
  150. package/dist/utils/transformPointDataToPayload.d.ts.map +0 -1
  151. package/dist/utils/transformPointDataToPayload.js +0 -28
  152. package/dist/utils/transformPointDataToPayload.js.map +0 -1
  153. package/dist/utils/whereSchema.d.ts +0 -9
  154. package/dist/utils/whereSchema.d.ts.map +0 -1
  155. package/dist/utils/whereSchema.js +0 -13
  156. package/dist/utils/whereSchema.js.map +0 -1
  157. package/src/mcp/builtin/collections/formatCollectionError.ts +0 -84
  158. package/src/mcp/builtin/validateEntityData.ts +0 -132
  159. package/src/utils/getVirtualFieldNames.ts +0 -53
  160. package/src/utils/schemaConversion/filterFieldsByAccess.ts +0 -123
  161. package/src/utils/schemaConversion/getEntityInputSchema.ts +0 -96
  162. package/src/utils/schemaConversion/sanitizeEntitySchema.spec.ts +0 -96
  163. package/src/utils/schemaConversion/sanitizeEntitySchema.ts +0 -432
  164. package/src/utils/transformPointDataToPayload.ts +0 -40
  165. package/src/utils/whereSchema.ts +0 -24
@@ -1,11 +1,10 @@
1
- import { z } from 'zod';
1
+ import { deleteDocumentsInputSchema } 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 { whereSchema } from '../../../utils/whereSchema.js';
6
5
  const DEFAULT_DESCRIPTION = 'Delete documents in any collection by passing the collection slug and ID or where clause.';
7
6
  export const deleteDocumentsTool = defineCollectionTool({
8
- access: (args)=>defaultAccess(args) && Boolean(args.permissions?.collections?.[args.collectionSlug]?.delete),
7
+ access: (args)=>defaultAccess(args) && Boolean(args.permissions?.collections?.[args.slug]?.delete),
9
8
  annotations: {
10
9
  destructiveHint: true,
11
10
  idempotentHint: false,
@@ -14,25 +13,40 @@ export const deleteDocumentsTool = defineCollectionTool({
14
13
  title: 'Delete Documents'
15
14
  },
16
15
  description: DEFAULT_DESCRIPTION,
17
- input: z.object({
18
- id: z.union([
19
- z.string(),
20
- z.number()
21
- ]).describe('Optional: specific document ID to delete').optional(),
22
- depth: z.number().int().min(0).max(10).describe('Depth of population for relationships in response').optional().default(0),
23
- fallbackLocale: z.string().describe('Optional: fallback locale code to use when requested locale is not available').optional(),
24
- locale: z.string().describe('Optional: locale code for the operation (e.g., "en", "es"). Defaults to the default locale').optional(),
25
- where: whereSchema.describe('Optional: where clause to delete multiple documents. Use field names with Payload operators, and/or arrays for grouping. Example: {"title":{"contains":"test"}}').optional()
26
- })
27
- }).handler(async ({ authorizedMCP, collectionSlug, input, req })=>{
16
+ input: deleteDocumentsInputSchema
17
+ }).handler(async ({ slug, authorizedMCP, input, req })=>{
28
18
  const payload = req.payload;
29
19
  const logger = getLogger({
30
20
  payload
31
21
  });
32
22
  const { id, depth, fallbackLocale, locale, where } = input;
33
- logger.info(`Deleting document from collection: ${collectionSlug}${id ? ` with ID: ${id}` : ' with where clause'}${locale ? `, locale: ${locale}` : ''}`);
23
+ logger.info(`Deleting document from collection: ${slug}${id ? ` with ID: ${id}` : ' with where clause'}${locale ? `, locale: ${locale}` : ''}`);
34
24
  try {
35
- if (!id && !where) {
25
+ if (id !== undefined) {
26
+ const result = await payload.delete({
27
+ id,
28
+ collection: slug,
29
+ depth,
30
+ overrideAccess: authorizedMCP.overrideAccess,
31
+ req,
32
+ ...locale && {
33
+ locale
34
+ },
35
+ ...fallbackLocale !== undefined && {
36
+ fallbackLocale
37
+ }
38
+ });
39
+ return {
40
+ content: [
41
+ {
42
+ type: 'text',
43
+ text: `Document deleted successfully from collection "${slug}"!\nDeleted document:\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``
44
+ }
45
+ ],
46
+ doc: result
47
+ };
48
+ }
49
+ if (where === undefined) {
36
50
  return {
37
51
  content: [
38
52
  {
@@ -42,39 +56,22 @@ export const deleteDocumentsTool = defineCollectionTool({
42
56
  ]
43
57
  };
44
58
  }
45
- const deleteOptions = {
46
- collection: collectionSlug,
59
+ const result = await payload.delete({
60
+ collection: slug,
47
61
  depth,
48
62
  overrideAccess: authorizedMCP.overrideAccess,
49
63
  req,
64
+ where,
50
65
  ...locale && {
51
66
  locale
52
67
  },
53
- ...fallbackLocale && {
68
+ ...fallbackLocale !== undefined && {
54
69
  fallbackLocale
55
70
  }
56
- };
57
- if (id) {
58
- deleteOptions.id = id;
59
- } else {
60
- deleteOptions.where = where;
61
- }
62
- const result = await payload.delete(deleteOptions);
63
- if (id) {
64
- return {
65
- content: [
66
- {
67
- type: 'text',
68
- text: `Document deleted successfully from collection "${collectionSlug}"!\nDeleted document:\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``
69
- }
70
- ],
71
- doc: result
72
- };
73
- }
74
- const bulkResult = result;
75
- const docs = bulkResult.docs || [];
76
- const errors = bulkResult.errors || [];
77
- let responseText = `Document deleted successfully from collection "${collectionSlug}"!\nDeleted: ${docs.length} documents\nErrors: ${errors.length}\n---`;
71
+ });
72
+ const docs = result.docs || [];
73
+ const errors = result.errors || [];
74
+ let responseText = `Document deleted successfully from collection "${slug}"!\nDeleted: ${docs.length} documents\nErrors: ${errors.length}\n---`;
78
75
  if (docs.length > 0) {
79
76
  responseText += `\n\nDeleted documents:\n\`\`\`json\n${JSON.stringify(docs)}\n\`\`\``;
80
77
  }
@@ -95,12 +92,12 @@ export const deleteDocumentsTool = defineCollectionTool({
95
92
  };
96
93
  } catch (error) {
97
94
  const errorMessage = error instanceof Error ? error.message : 'Unknown error';
98
- logger.error(`Error deleting document from ${collectionSlug}: ${errorMessage}`);
95
+ logger.error(`Error deleting document from ${slug}: ${errorMessage}`);
99
96
  return {
100
97
  content: [
101
98
  {
102
99
  type: 'text',
103
- text: `Error deleting document from collection "${collectionSlug}": ${errorMessage}`
100
+ text: `Error deleting document from collection "${slug}": ${errorMessage}`
104
101
  }
105
102
  ]
106
103
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/mcp/builtin/collections/deleteTool.ts"],"sourcesContent":["import { z } from 'zod'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\nimport { whereSchema } from '../../../utils/whereSchema.js'\n\nconst DEFAULT_DESCRIPTION =\n 'Delete documents in any collection by passing the collection slug and ID or where clause.'\n\nexport const deleteDocumentsTool = defineCollectionTool({\n access: (args) =>\n defaultAccess(args) && Boolean(args.permissions?.collections?.[args.collectionSlug]?.delete),\n annotations: {\n destructiveHint: true,\n idempotentHint: false,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'Delete Documents',\n },\n description: DEFAULT_DESCRIPTION,\n input: z.object({\n id: z\n .union([z.string(), z.number()])\n .describe('Optional: specific document ID to delete')\n .optional(),\n depth: z\n .number()\n .int()\n .min(0)\n .max(10)\n .describe('Depth of population for relationships in response')\n .optional()\n .default(0),\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 for the operation (e.g., \"en\", \"es\"). Defaults to the default locale',\n )\n .optional(),\n where: whereSchema\n .describe(\n 'Optional: where clause to delete multiple documents. 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\n const { id, depth, fallbackLocale, locale, where } = input\n\n logger.info(\n `Deleting document from collection: ${collectionSlug}${id ? ` with ID: ${id}` : ' with where clause'}${locale ? `, locale: ${locale}` : ''}`,\n )\n\n try {\n if (!id && !where) {\n return {\n content: [{ type: 'text', text: 'Error: Either id or where clause must be provided' }],\n }\n }\n\n const deleteOptions: Record<string, unknown> = {\n collection: collectionSlug,\n depth,\n overrideAccess: authorizedMCP.overrideAccess,\n req,\n ...(locale && { locale }),\n ...(fallbackLocale && { fallbackLocale }),\n }\n\n if (id) {\n deleteOptions.id = id\n } else {\n deleteOptions.where = where\n }\n\n const result = await payload.delete(deleteOptions as Parameters<typeof payload.delete>[0])\n\n if (id) {\n return {\n content: [\n {\n type: 'text',\n text: `Document deleted successfully from collection \"${collectionSlug}\"!\\nDeleted document:\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as Record<string, unknown>,\n }\n }\n\n const bulkResult = result as { docs?: unknown[]; errors?: unknown[] }\n const docs = bulkResult.docs || []\n const errors = bulkResult.errors || []\n\n let responseText = `Document deleted successfully from collection \"${collectionSlug}\"!\\nDeleted: ${docs.length} documents\\nErrors: ${errors.length}\\n---`\n if (docs.length > 0) {\n responseText += `\\n\\nDeleted documents:\\n\\`\\`\\`json\\n${JSON.stringify(docs)}\\n\\`\\`\\``\n }\n if (errors.length > 0) {\n responseText += `\\n\\nErrors:\\n\\`\\`\\`json\\n${JSON.stringify(errors)}\\n\\`\\`\\``\n }\n\n return {\n content: [{ type: 'text', text: responseText }],\n doc: { docs, errors } as unknown as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error deleting document from ${collectionSlug}: ${errorMessage}`)\n return {\n content: [\n {\n type: 'text',\n text: `Error deleting document from collection \"${collectionSlug}\": ${errorMessage}`,\n },\n ],\n }\n }\n})\n"],"names":["z","defaultAccess","defineCollectionTool","getLogger","whereSchema","DEFAULT_DESCRIPTION","deleteDocumentsTool","access","args","Boolean","permissions","collections","collectionSlug","delete","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","object","id","union","string","number","describe","optional","depth","int","min","max","default","fallbackLocale","locale","where","handler","authorizedMCP","req","payload","logger","info","content","type","text","deleteOptions","collection","overrideAccess","result","JSON","stringify","doc","bulkResult","docs","errors","responseText","length","error","errorMessage","Error","message"],"mappings":"AAAA,SAASA,CAAC,QAAQ,MAAK;AAEvB,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AACvD,SAASC,WAAW,QAAQ,gCAA+B;AAE3D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,OAAO,GAAG;QAC9DpB,OAAOiB,KAAK,CAAC,CAAC,6BAA6B,EAAE9C,eAAe,EAAE,EAAE+C,cAAc;QAC9E,OAAO;YACLhB,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,yCAAyC,EAAEjC,eAAe,GAAG,EAAE+C,cAAc;gBACtF;aACD;QACH;IACF;AACF,GAAE"}
1
+ {"version":3,"sources":["../../../../src/mcp/builtin/collections/deleteTool.ts"],"sourcesContent":["import { deleteDocumentsInputSchema } from 'payload'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\n\nconst DEFAULT_DESCRIPTION =\n 'Delete documents in any collection by passing the collection slug and ID or where clause.'\n\nexport const deleteDocumentsTool = defineCollectionTool({\n access: (args) =>\n defaultAccess(args) && Boolean(args.permissions?.collections?.[args.slug]?.delete),\n annotations: {\n destructiveHint: true,\n idempotentHint: false,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'Delete Documents',\n },\n description: DEFAULT_DESCRIPTION,\n input: deleteDocumentsInputSchema,\n}).handler(async ({ slug, authorizedMCP, input, req }) => {\n const payload = req.payload\n const logger = getLogger({ payload })\n\n const { id, depth, fallbackLocale, locale, where } = input\n\n logger.info(\n `Deleting document from collection: ${slug}${id ? ` with ID: ${id}` : ' with where clause'}${locale ? `, locale: ${locale}` : ''}`,\n )\n\n try {\n if (id !== undefined) {\n const result = await payload.delete({\n id,\n collection: slug,\n depth,\n overrideAccess: authorizedMCP.overrideAccess,\n req,\n ...(locale && { locale }),\n ...(fallbackLocale !== undefined && { fallbackLocale }),\n })\n\n return {\n content: [\n {\n type: 'text',\n text: `Document deleted successfully from collection \"${slug}\"!\\nDeleted document:\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as Record<string, unknown>,\n }\n }\n\n if (where === undefined) {\n return {\n content: [{ type: 'text', text: 'Error: Either id or where clause must be provided' }],\n }\n }\n\n const result = await payload.delete({\n collection: slug,\n depth,\n overrideAccess: authorizedMCP.overrideAccess,\n req,\n where,\n ...(locale && { locale }),\n ...(fallbackLocale !== undefined && { fallbackLocale }),\n })\n const docs = result.docs || []\n const errors = result.errors || []\n\n let responseText = `Document deleted successfully from collection \"${slug}\"!\\nDeleted: ${docs.length} documents\\nErrors: ${errors.length}\\n---`\n if (docs.length > 0) {\n responseText += `\\n\\nDeleted documents:\\n\\`\\`\\`json\\n${JSON.stringify(docs)}\\n\\`\\`\\``\n }\n if (errors.length > 0) {\n responseText += `\\n\\nErrors:\\n\\`\\`\\`json\\n${JSON.stringify(errors)}\\n\\`\\`\\``\n }\n\n return {\n content: [{ type: 'text', text: responseText }],\n doc: { docs, errors } as unknown as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error deleting document from ${slug}: ${errorMessage}`)\n return {\n content: [\n {\n type: 'text',\n text: `Error deleting document from collection \"${slug}\": ${errorMessage}`,\n },\n ],\n }\n }\n})\n"],"names":["deleteDocumentsInputSchema","defaultAccess","defineCollectionTool","getLogger","DEFAULT_DESCRIPTION","deleteDocumentsTool","access","args","Boolean","permissions","collections","slug","delete","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","handler","authorizedMCP","req","payload","logger","id","depth","fallbackLocale","locale","where","info","undefined","result","collection","overrideAccess","content","type","text","JSON","stringify","doc","docs","errors","responseText","length","error","errorMessage","Error","message"],"mappings":"AAAA,SAASA,0BAA0B,QAAQ,UAAS;AAEpD,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AAEvD,MAAMC,sBACJ;AAEF,OAAO,MAAMC,sBAAsBH,qBAAqB;IACtDI,QAAQ,CAACC,OACPN,cAAcM,SAASC,QAAQD,KAAKE,WAAW,EAAEC,aAAa,CAACH,KAAKI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AAEA;YAAO,CAAC;YACxB,GAAID,mBAAmBI,aAAa;gBAAEJ;YAAe,CAAC;QACxD;QACA,MAAMc,OAAOT,OAAOS,IAAI,IAAI,EAAE;QAC9B,MAAMC,SAASV,OAAOU,MAAM,IAAI,EAAE;QAElC,IAAIC,eAAe,CAAC,+CAA+C,EAAEjC,KAAK,aAAa,EAAE+B,KAAKG,MAAM,CAAC,oBAAoB,EAAEF,OAAOE,MAAM,CAAC,KAAK,CAAC;QAC/I,IAAIH,KAAKG,MAAM,GAAG,GAAG;YACnBD,gBAAgB,CAAC,oCAAoC,EAAEL,KAAKC,SAAS,CAACE,MAAM,QAAQ,CAAC;QACvF;QACA,IAAIC,OAAOE,MAAM,GAAG,GAAG;YACrBD,gBAAgB,CAAC,yBAAyB,EAAEL,KAAKC,SAAS,CAACG,QAAQ,QAAQ,CAAC;QAC9E;QAEA,OAAO;YACLP,SAAS;gBAAC;oBAAEC,MAAM;oBAAQC,MAAMM;gBAAa;aAAE;YAC/CH,KAAK;gBAAEC;gBAAMC;YAAO;QACtB;IACF,EAAE,OAAOG,OAAO;QACd,MAAMC,eAAeD,iBAAiBE,QAAQF,MAAMG,OAAO,GAAG;QAC9DxB,OAAOqB,KAAK,CAAC,CAAC,6BAA6B,EAAEnC,KAAK,EAAE,EAAEoC,cAAc;QACpE,OAAO;YACLX,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,yCAAyC,EAAE3B,KAAK,GAAG,EAAEoC,cAAc;gBAC5E;aACD;QACH;IACF;AACF,GAAE"}
@@ -1 +1 @@
1
- {"version":3,"file":"duplicateTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/duplicateTool.ts"],"names":[],"mappings":"AAiBA,eAAO,MAAM,qBAAqB,4CAoHhC,CAAA"}
1
+ {"version":3,"file":"duplicateTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/duplicateTool.ts"],"names":[],"mappings":"AAgBA,eAAO,MAAM,qBAAqB,4CAkEhC,CAAA"}
@@ -1,13 +1,11 @@
1
- import { z } from 'zod';
1
+ import { duplicateDocumentInputSchema, getCollectionVirtualFieldNames, stripVirtualFields, transformPointDataToPayload, validateCollectionData } 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 { getCollectionVirtualFieldNames, stripVirtualFields } from '../../../utils/getVirtualFieldNames.js';
6
- import { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js';
7
- import { formatCollectionError } from './formatCollectionError.js';
5
+ import { formatEntityError } from '../formatEntityError.js';
8
6
  const DEFAULT_DESCRIPTION = 'Duplicate a document in any collection by passing the collection slug and source document ID.';
9
7
  export const duplicateDocumentTool = defineCollectionTool({
10
- access: (args)=>defaultAccess(args) && Boolean(args.permissions?.collections?.[args.collectionSlug]?.create),
8
+ access: (args)=>defaultAccess(args) && Boolean(args.permissions?.collections?.[args.slug]?.create),
11
9
  annotations: {
12
10
  destructiveHint: false,
13
11
  idempotentHint: false,
@@ -16,35 +14,29 @@ export const duplicateDocumentTool = defineCollectionTool({
16
14
  title: 'Duplicate Document'
17
15
  },
18
16
  description: DEFAULT_DESCRIPTION,
19
- input: z.object({
20
- id: z.union([
21
- z.string(),
22
- z.number()
23
- ]).describe('The ID of the document to duplicate'),
24
- data: z.record(z.string(), z.unknown()).describe('Optional: fields to override on the duplicated document').optional(),
25
- depth: z.number().int().min(0).max(10).describe('How many levels deep to populate relationships in response').optional().default(0),
26
- draft: z.boolean().describe('Whether to create the duplicate as a draft').optional().default(false),
27
- fallbackLocale: z.string().describe('Optional: fallback locale code to use when requested locale is not available').optional(),
28
- locale: z.string().describe('Optional: locale code to duplicate in (e.g., "en", "es"). Defaults to the default locale').optional(),
29
- populate: z.record(z.string(), z.unknown()).describe('Optional: control which fields to include from populated relationship or upload documents.').optional(),
30
- 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(),
31
- selectedLocales: z.array(z.string()).describe('Optional: localized field locales to include in the duplicated document').optional(),
32
- showHiddenFields: z.boolean().describe('Optional: include hidden fields in the duplicated document response').optional()
33
- })
34
- }).handler(async ({ authorizedMCP, collectionSlug, input, req })=>{
17
+ input: duplicateDocumentInputSchema
18
+ }).handler(async ({ slug, authorizedMCP, input, req })=>{
35
19
  const payload = req.payload;
36
20
  const logger = getLogger({
37
21
  payload
38
22
  });
39
- const { id, data, depth, draft, fallbackLocale, locale, populate, select, selectedLocales, showHiddenFields } = input;
40
- logger.info(`Duplicating document in collection: ${collectionSlug} with ID: ${id}`);
23
+ const { id, data, depth, draft, fallbackLocale, locale, populate, select, selectedLocales } = input;
24
+ logger.info(`Duplicating document in collection: ${slug} with ID: ${id}`);
41
25
  try {
42
- const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, collectionSlug);
26
+ const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, slug);
43
27
  const inputData = data ? stripVirtualFields(data, virtualFieldNames) : undefined;
28
+ if (inputData) {
29
+ validateCollectionData({
30
+ slug,
31
+ data: inputData,
32
+ partial: true,
33
+ req
34
+ });
35
+ }
44
36
  const parsedData = inputData ? transformPointDataToPayload(inputData) : undefined;
45
37
  const result = await payload.duplicate({
46
38
  id,
47
- collection: collectionSlug,
39
+ collection: slug,
48
40
  depth,
49
41
  draft,
50
42
  overrideAccess: authorizedMCP.overrideAccess,
@@ -55,38 +47,36 @@ export const duplicateDocumentTool = defineCollectionTool({
55
47
  ...locale ? {
56
48
  locale
57
49
  } : {},
58
- ...fallbackLocale ? {
50
+ ...fallbackLocale !== undefined ? {
59
51
  fallbackLocale
60
52
  } : {},
61
53
  ...populate ? {
62
- populate: populate
54
+ populate
63
55
  } : {},
64
56
  ...select ? {
65
- select: select
57
+ select
66
58
  } : {},
67
59
  ...selectedLocales ? {
68
60
  selectedLocales
69
- } : {},
70
- ...showHiddenFields !== undefined ? {
71
- showHiddenFields
72
61
  } : {}
73
62
  });
74
- logger.info(`Successfully duplicated document in ${collectionSlug} from ID: ${id}`);
63
+ logger.info(`Successfully duplicated document in ${slug} from ID: ${id}`);
75
64
  return {
76
65
  content: [
77
66
  {
78
67
  type: 'text',
79
- text: `Document duplicated successfully in collection "${collectionSlug}"!\nDuplicated document:\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``
68
+ text: `Document duplicated successfully in collection "${slug}"!\nDuplicated document:\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``
80
69
  }
81
70
  ],
82
71
  doc: result
83
72
  };
84
73
  } catch (error) {
85
74
  const errorMessage = error instanceof Error ? error.message : 'Unknown error';
86
- logger.error(`Error duplicating document in ${collectionSlug}: ${errorMessage}`);
87
- return formatCollectionError({
75
+ logger.error(`Error duplicating document in ${slug}: ${errorMessage}`);
76
+ return formatEntityError({
77
+ slug,
88
78
  action: 'duplicating',
89
- collectionSlug,
79
+ entity: 'collection',
90
80
  error,
91
81
  req
92
82
  });
@@ -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 { 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 overrideAccess: authorizedMCP.overrideAccess,\n req,\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","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","overrideAccess","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,2BAA2B,QAAQ,gDAA+C;AAC3F,SAASC,qBAAqB,QAAQ,6BAA4B;AAElE,MAAMC,sBACJ;AAEF,OAAO,MAAMC,wBAAwBP,qBAAqB;IACxDQ,QAAQ,CAACC,OACPV,cAAcU,SAASC,QAAQD,KAAKE,WAAW,EAAEC,aAAa,C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AAOU,OAAO;QACd,MAAMC,eAAeD,iBAAiBE,QAAQF,MAAMG,OAAO,GAAG;QAC9DpB,OAAOiB,KAAK,CAAC,CAAC,8BAA8B,EAAEvD,eAAe,EAAE,EAAEwD,cAAc;QAC/E,OAAOhE,sBAAsB;YAAEmE,QAAQ;YAAe3D;YAAgBuD;YAAOnB;QAAI;IACnF;AACF,GAAE"}
1
+ {"version":3,"sources":["../../../../src/mcp/builtin/collections/duplicateTool.ts"],"sourcesContent":["import {\n duplicateDocumentInputSchema,\n getCollectionVirtualFieldNames,\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,\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","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","collection","overrideAccess","content","type","text","JSON","stringify","doc","error","errorMessage","Error","message","action","entity"],"mappings":"AAAA,SACEA,4BAA4B,EAC5BC,8BAA8B,EAC9BC,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,EAA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B;gBAAEA;YAAgB,IAAI,CAAC,CAAC;QAChD;QAEAT,OAAOU,IAAI,CAAC,CAAC,oCAAoC,EAAExB,KAAK,UAAU,EAAEe,IAAI;QAExE,OAAO;YACLoB,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,gDAAgD,EAAErC,KAAK,sCAAsC,EAAEsC,KAAKC,SAAS,CAACR,QAAQ,QAAQ,CAAC;gBACxI;aACD;YACDS,KAAKT;QACP;IACF,EAAE,OAAOU,OAAO;QACd,MAAMC,eAAeD,iBAAiBE,QAAQF,MAAMG,OAAO,GAAG;QAC9D9B,OAAO2B,KAAK,CAAC,CAAC,8BAA8B,EAAEzC,KAAK,EAAE,EAAE0C,cAAc;QACrE,OAAOlD,kBAAkB;YAAEQ;YAAM6C,QAAQ;YAAeC,QAAQ;YAAcL;YAAO7B;QAAI;IAC3F;AACF,GAAE"}
@@ -1,28 +1,28 @@
1
1
  import type { CollectionSlug, File, PayloadRequest } from 'payload';
2
- import { z } from 'zod';
3
- export declare const fileInputSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
4
- name: z.ZodString;
5
- data: z.ZodString;
6
- mimeType: z.ZodString;
7
- source: z.ZodLiteral<"base64">;
8
- }, z.core.$strip>, z.ZodObject<{
9
- name: z.ZodOptional<z.ZodString>;
10
- source: z.ZodLiteral<"externalURL">;
11
- url: z.ZodURL;
12
- }, z.core.$strip>, z.ZodObject<{
13
- file: z.ZodObject<{
14
- filename: z.ZodString;
15
- mimeType: z.ZodString;
16
- size: z.ZodNumber;
17
- uploadReference: z.ZodRecord<z.ZodString, z.ZodUnknown>;
18
- }, z.core.$strip>;
19
- source: z.ZodLiteral<"uploadReference">;
20
- }, z.core.$strip>], "source">;
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
21
  type FileInput = z.infer<typeof fileInputSchema>;
22
- export declare function resolveFile({ collectionSlug, input, req, }: {
23
- collectionSlug: CollectionSlug;
22
+ export declare function resolveFile({ slug, input, req, }: {
24
23
  input?: FileInput;
25
24
  req: PayloadRequest;
25
+ slug: CollectionSlug;
26
26
  }): Promise<File | undefined>;
27
27
  export {};
28
28
  //# sourceMappingURL=fileInput.d.ts.map
@@ -1 +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,EAAY,cAAc,EAAE,MAAM,SAAS,CAAA;AAK7E,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAavB,eAAO,MAAM,eAAe;;;;;;;;;;;;;;;;;6BAoBzB,CAAA;AAEH,KAAK,SAAS,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,eAAe,CAAC,CAAA;AAEhD,wBAAsB,WAAW,CAAC,EAChC,cAAc,EACd,KAAK,EACL,GAAG,GACJ,EAAE;IACD,cAAc,EAAE,cAAc,CAAA;IAC9B,KAAK,CAAC,EAAE,SAAS,CAAA;IACjB,GAAG,EAAE,cAAc,CAAA;CACpB,GAAG,OAAO,CAAC,IAAI,GAAG,SAAS,CAAC,CAoE5B"}
1
+ {"version":3,"file":"fileInput.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/fileInput.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,IAAI,EAAY,cAAc,EAAE,MAAM,SAAS,CAAA;AAE7E,OAAO,EAAY,CAAC,EAAE,MAAM,SAAS,CAAA;AAoBrC,eAAO,MAAM,eAAe;;;;;;;;;;;;;;;;;8BAwBzB,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,CA2E5B"}
@@ -1,45 +1,51 @@
1
- import { APIError } from 'payload';
1
+ import { APIError, z } from 'payload';
2
2
  import { getExternalFile, getFileFromUploadInstructions, isURLAllowed } from 'payload/internal';
3
3
  import { sanitizeFilename } from 'payload/shared';
4
- import { z } from 'zod';
5
- const mimeTypeSchema = z.string().regex(/^[!#$%&'*+.^`|~\w-]+\/[!#$%&'*+.^`|~\w-]+$/, 'MIME type must use the type/subtype format');
6
- const uploadFileSchema = z.object({
4
+ const mimeTypeSchema = z.string().check(z.regex(/^[!#$%&'*+.^`|~\w-]+\/[!#$%&'*+.^`|~\w-]+$/, 'MIME type must use the type/subtype format'));
5
+ const uploadFileSchema = z.strictObject({
7
6
  filename: z.string(),
8
7
  mimeType: z.string(),
9
- size: z.number().int().nonnegative(),
8
+ size: z.int().check(z.nonnegative()),
10
9
  uploadReference: z.record(z.string(), z.unknown())
11
10
  });
12
11
  export const fileInputSchema = z.discriminatedUnion('source', [
13
- z.object({
14
- name: z.string().min(1).describe('The file name, including its extension'),
15
- data: z.string().describe('The base64-encoded file bytes, without a data URL prefix'),
16
- mimeType: mimeTypeSchema.describe('The file MIME type, for example image/png'),
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.')),
17
16
  source: z.literal('base64')
18
17
  }),
19
- z.object({
20
- name: z.string().min(1).describe('Optional file name override').optional(),
18
+ z.strictObject({
19
+ name: z.optional(z.string().check(z.minLength(1))).check(z.describe('File name override.')),
21
20
  source: z.literal('externalURL'),
22
- url: z.url().describe('The http or https URL to download')
21
+ url: z.url().check(z.describe('The http or https URL to download.'))
23
22
  }),
24
- z.object({
25
- file: uploadFileSchema.describe('The file value returned by getUploadInstructions'),
23
+ z.strictObject({
24
+ file: uploadFileSchema.check(z.describe('getUploadInstructions file field post-upload.')),
26
25
  source: z.literal('uploadReference')
27
26
  })
28
- ]).describe('A file for an upload collection. Use externalURL for an online file, base64 for local file bytes, or uploadReference after following getUploadInstructions. Usage of getUploadInstructions and uploadReference is recommended.');
29
- export async function resolveFile({ collectionSlug, input, req }) {
27
+ ]).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.'));
28
+ export async function resolveFile({ slug, input, req }) {
30
29
  if (!input) {
31
30
  return undefined;
32
31
  }
33
32
  if (input.source === 'uploadReference') {
34
- return getFileFromUploadInstructions({
35
- collectionSlug,
36
- file: input.file,
37
- req
38
- });
33
+ try {
34
+ return await getFileFromUploadInstructions({
35
+ collectionSlug: slug,
36
+ file: input.file,
37
+ req
38
+ });
39
+ } catch (error) {
40
+ if (error instanceof Error && error.message === 'Staged upload was not found.') {
41
+ throw new APIError('Staged upload not found. Complete the upload action first, or use base64 for small local files.', 400);
42
+ }
43
+ throw error;
44
+ }
39
45
  }
40
- const uploadConfig = req.payload.collections[collectionSlug]?.config.upload;
46
+ const uploadConfig = req.payload.collections[slug]?.config.upload;
41
47
  if (!uploadConfig) {
42
- throw new APIError(`Collection "${collectionSlug}" does not support file uploads.`, 400);
48
+ throw new APIError(`Collection "${slug}" does not support file uploads.`, 400);
43
49
  }
44
50
  const maxFileSize = req.payload.config.upload.limits?.fileSize;
45
51
  let file;
@@ -56,7 +62,7 @@ export async function resolveFile({ collectionSlug, input, req }) {
56
62
  };
57
63
  } else {
58
64
  if (uploadConfig.pasteURL === false) {
59
- throw new APIError(`Uploading files from URLs is disabled for collection "${collectionSlug}".`, 400);
65
+ throw new APIError(`Uploading files from URLs is disabled for collection "${slug}".`, 400);
60
66
  }
61
67
  const url = new URL(input.url);
62
68
  if (![
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/mcp/builtin/collections/fileInput.ts"],"sourcesContent":["import type { CollectionSlug, File, FileData, PayloadRequest } from 'payload'\n\nimport { APIError } from 'payload'\nimport { getExternalFile, getFileFromUploadInstructions, isURLAllowed } from 'payload/internal'\nimport { sanitizeFilename } from 'payload/shared'\nimport { z } from 'zod'\n\nconst mimeTypeSchema = z\n .string()\n .regex(/^[!#$%&'*+.^`|~\\w-]+\\/[!#$%&'*+.^`|~\\w-]+$/, 'MIME type must use the type/subtype format')\n\nconst uploadFileSchema = z.object({\n filename: z.string(),\n mimeType: z.string(),\n size: z.number().int().nonnegative(),\n uploadReference: z.record(z.string(), z.unknown()),\n})\n\nexport const fileInputSchema = z\n .discriminatedUnion('source', [\n z.object({\n name: z.string().min(1).describe('The file name, including its extension'),\n data: z.string().describe('The base64-encoded file bytes, without a data URL prefix'),\n mimeType: mimeTypeSchema.describe('The file MIME type, for example image/png'),\n source: z.literal('base64'),\n }),\n z.object({\n name: z.string().min(1).describe('Optional file name override').optional(),\n source: z.literal('externalURL'),\n url: z.url().describe('The http or https URL to download'),\n }),\n z.object({\n file: uploadFileSchema.describe('The file value returned by getUploadInstructions'),\n source: z.literal('uploadReference'),\n }),\n ])\n .describe(\n 'A file for an upload collection. Use externalURL for an online file, base64 for local file bytes, or uploadReference after following getUploadInstructions. Usage of getUploadInstructions and uploadReference is recommended.',\n )\n\ntype FileInput = z.infer<typeof fileInputSchema>\n\nexport async function resolveFile({\n collectionSlug,\n input,\n req,\n}: {\n collectionSlug: CollectionSlug\n input?: FileInput\n req: PayloadRequest\n}): Promise<File | undefined> {\n if (!input) {\n return undefined\n }\n\n if (input.source === 'uploadReference') {\n return getFileFromUploadInstructions({ collectionSlug, file: input.file, req })\n }\n\n const uploadConfig = req.payload.collections[collectionSlug]?.config.upload\n\n if (!uploadConfig) {\n throw new APIError(`Collection \"${collectionSlug}\" does not support file uploads.`, 400)\n }\n\n const maxFileSize = req.payload.config.upload.limits?.fileSize\n let file: File\n\n if (input.source === 'base64') {\n const data = decodeBase64({ maxFileSize, value: input.data })\n\n file = {\n name: sanitizeFilename(input.name),\n data,\n mimetype: input.mimeType,\n size: data.length,\n }\n } else {\n if (uploadConfig.pasteURL === false) {\n throw new APIError(\n `Uploading files from URLs is disabled for collection \"${collectionSlug}\".`,\n 400,\n )\n }\n\n const url = new URL(input.url)\n\n if (!['http:', 'https:'].includes(url.protocol)) {\n throw new APIError('File URLs must use http or https.', 400)\n }\n\n if (\n typeof uploadConfig.pasteURL === 'object' &&\n !isURLAllowed(input.url, uploadConfig.pasteURL.allowList)\n ) {\n throw new APIError('The provided file URL is not allowed.', 400)\n }\n\n file = await getExternalFile({\n data: {\n filename: sanitizeFilename(input.name || getURLFilename(url)),\n url: input.url,\n } as FileData,\n req,\n uploadConfig: {\n ...uploadConfig,\n externalFileHeaderFilter: uploadConfig.externalFileHeaderFilter ?? (() => ({})),\n },\n })\n file.mimetype = file.mimetype?.split(';')[0] || 'application/octet-stream'\n file.size = file.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\nfunction getURLFilename(url: URL): string {\n const pathSegment = url.pathname.split('/').pop() || 'upload'\n\n try {\n return decodeURIComponent(pathSegment)\n } catch {\n return pathSegment\n }\n}\n"],"names":["APIError","getExternalFile","getFileFromUploadInstructions","isURLAllowed","sanitizeFilename","z","mimeTypeSchema","string","regex","uploadFileSchema","object","filename","mimeType","size","number","int","nonnegative","uploadReference","record","unknown","fileInputSchema","discriminatedUnion","name","min","describe","data","source","literal","optional","url","file","resolveFile","collectionSlug","input","req","undefined","uploadConfig","payload","collections","config","upload","maxFileSize","limits","fileSize","decodeBase64","value","mimetype","length","pasteURL","URL","includes","protocol","allowList","getURLFilename","externalFileHeaderFilter","split","Number","isFinite","normalized","replace","test","paddingLength","endsWith","decodedSize","Math","floor","Buffer","from","toString","pathSegment","pathname","pop","decodeURIComponent"],"mappings":"AAEA,SAASA,QAAQ,QAAQ,UAAS;AAClC,SAASC,eAAe,EAAEC,6BAA6B,EAAEC,YAAY,QAAQ,mBAAkB;AAC/F,SAASC,gBAAgB,QAAQ,iBAAgB;AACjD,SAASC,CAAC,QAAQ,MAAK;AAEvB,MAAMC,iBAAiBD,EACpBE,MAAM,GACNC,KAAK,CAAC,8CAA8C;AAEvD,MAAMC,mBAAmBJ,EA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B,OAAOC,QAAQ,CAAChB,gBAAgBX,KAAKjB,IAAI,GAAG4B,aAAa;QACxF,MAAM,IAAIzC,SAAS,CAAC,iBAAiB,EAAEyC,YAAY,mBAAmB,CAAC,EAAE;IAC3E;IAEA,OAAOX;AACT;AAEA,SAASc,aAAa,EAAEH,WAAW,EAAEI,KAAK,EAA2C;IACnF,MAAMa,aAAab,MAAMc,OAAO,CAAC,OAAO;IAExC,IAAI,CAAC,uBAAuBC,IAAI,CAACF,eAAeA,WAAWX,MAAM,GAAG,MAAM,GAAG;QAC3E,MAAM,IAAI/C,SAAS,mCAAmC;IACxD;IAEA,IAAIyC,gBAAgBN,aAAaqB,OAAOC,QAAQ,CAAChB,cAAc;QAC7D,MAAMoB,gBAAgBH,WAAWI,QAAQ,CAAC,QAAQ,IAAIJ,WAAWI,QAAQ,CAAC,OAAO,IAAI;QACrF,MAAMC,cAAcC,KAAKC,KAAK,CAAC,AAACP,WAAWX,MAAM,GAAG,IAAK,KAAKc;QAE9D,IAAIE,cAActB,aAAa;YAC7B,MAAM,IAAIzC,SAAS,CAAC,iBAAiB,EAAEyC,YAAY,mBAAmB,CAAC,EAAE;QAC3E;IACF;IAEA,MAAMhB,OAAOyC,OAAOC,IAAI,CAACT,YAAY;IAErC,IAAIjC,KAAK2C,QAAQ,CAAC,UAAUT,OAAO,CAAC,OAAO,QAAQD,WAAWC,OAAO,CAAC,OAAO,KAAK;QAChF,MAAM,IAAI3D,SAAS,mCAAmC;IACxD;IAEA,OAAOyB;AACT;AAEA,SAAS4B,eAAexB,GAAQ;IAC9B,MAAMwC,cAAcxC,IAAIyC,QAAQ,CAACf,KAAK,CAAC,KAAKgB,GAAG,MAAM;IAErD,IAAI;QACF,OAAOC,mBAAmBH;IAC5B,EAAE,OAAM;QACN,OAAOA;IACT;AACF"}
1
+ {"version":3,"sources":["../../../../src/mcp/builtin/collections/fileInput.ts"],"sourcesContent":["import type { CollectionSlug, File, FileData, PayloadRequest } from 'payload'\n\nimport { APIError, z } from 'payload'\nimport { getExternalFile, getFileFromUploadInstructions, isURLAllowed } 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 z.strictObject({\n name: z.optional(z.string().check(z.minLength(1))).check(z.describe('File name override.')),\n source: z.literal('externalURL'),\n url: z.url().check(z.describe('The http or https URL to download.')),\n }),\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 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 let file: File\n\n if (input.source === 'base64') {\n const data = decodeBase64({ maxFileSize, value: input.data })\n\n file = {\n name: sanitizeFilename(input.name),\n data,\n mimetype: input.mimeType,\n size: data.length,\n }\n } else {\n if (uploadConfig.pasteURL === false) {\n throw new APIError(`Uploading files from URLs is disabled for collection \"${slug}\".`, 400)\n }\n\n const url = new URL(input.url)\n\n if (!['http:', 'https:'].includes(url.protocol)) {\n throw new APIError('File URLs must use http or https.', 400)\n }\n\n if (\n typeof uploadConfig.pasteURL === 'object' &&\n !isURLAllowed(input.url, uploadConfig.pasteURL.allowList)\n ) {\n throw new APIError('The provided file URL is not allowed.', 400)\n }\n\n file = await getExternalFile({\n data: {\n filename: sanitizeFilename(input.name || getURLFilename(url)),\n url: input.url,\n } as FileData,\n req,\n uploadConfig: {\n ...uploadConfig,\n externalFileHeaderFilter: uploadConfig.externalFileHeaderFilter ?? (() => ({})),\n },\n })\n file.mimetype = file.mimetype?.split(';')[0] || 'application/octet-stream'\n file.size = file.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\nfunction getURLFilename(url: URL): string {\n const pathSegment = url.pathname.split('/').pop() || 'upload'\n\n try {\n return decodeURIComponent(pathSegment)\n } catch {\n return pathSegment\n }\n}\n"],"names":["APIError","z","getExternalFile","getFileFromUploadInstructions","isURLAllowed","sanitizeFilename","mimeTypeSchema","string","check","regex","uploadFileSchema","strictObject","filename","mimeType","size","int","nonnegative","uploadReference","record","unknown","fileInputSchema","discriminatedUnion","name","minLength","describe","data","source","literal","optional","url","file","resolveFile","slug","input","req","undefined","collectionSlug","error","Error","message","uploadConfig","payload","collections","config","upload","maxFileSize","limits","fileSize","decodeBase64","value","mimetype","length","pasteURL","URL","includes","protocol","allowList","getURLFilename","externalFileHeaderFilter","split","Number","isFinite","normalized","replace","test","paddingLength","endsWith","decodedSize","Math","floor","Buffer","from","toString","pathSegment","pathname","pop","decodeURIComponent"],"mappings":"AAEA,SAASA,QAAQ,EAAEC,CAAC,QAAQ,UAAS;AACrC,SAASC,eAAe,EAAEC,6BAA6B,EAAEC,YAAY,QAAQ,mBAAkB;AAC/F,SAASC,gBAAgB,QAAQ,iBAAgB;AAEjD,MAAMC,iBAAiBL,EACpBM,MAAM,GACNC,KAAK,CACJP,EAAEQ,KAAK,CACL,8CACA;AAIN,MAAMC,mBAAmBT,EAAEU,YAAY,CAAC;IACtCC,UAAUX,EAAEM,MAAM;IAClBM,UAAUZ,EAAEM,MAAM;IAClBO,MAAMb,EAAEc,GAAG,GAAGP,KAAK,CAACP,EAAEe,WAAW;IACjCC,iBAAiBhB,EAAEiB,MAAM,CAACjB,EAAEM,MAAM,IAAIN,EAAEkB,OAAO;AACjD;AAEA,OAAO,MAAMC,kBAAkBnB,EAC5BoB,kBAAkB,CAAC,UAAU;IAC5BpB,EAAEU,YAAY,CAAC;QACbW,MAAMrB,EAAEM,MAAM,GAAGC,KAAK,CAACP,EAAEsB,SAAS,CAAC,IAAItB,EAA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ChB,gBAAgBf,KAAKhB,IAAI,GAAG+B,aAAa;QACxF,MAAM,IAAI7C,SAAS,CAAC,iBAAiB,EAAE6C,YAAY,mBAAmB,CAAC,EAAE;IAC3E;IAEA,OAAOf;AACT;AAEA,SAASkB,aAAa,EAAEH,WAAW,EAAEI,KAAK,EAA2C;IACnF,MAAMa,aAAab,MAAMc,OAAO,CAAC,OAAO;IAExC,IAAI,CAAC,uBAAuBC,IAAI,CAACF,eAAeA,WAAWX,MAAM,GAAG,MAAM,GAAG;QAC3E,MAAM,IAAInD,SAAS,mCAAmC;IACxD;IAEA,IAAI6C,gBAAgBV,aAAayB,OAAOC,QAAQ,CAAChB,cAAc;QAC7D,MAAMoB,gBAAgBH,WAAWI,QAAQ,CAAC,QAAQ,IAAIJ,WAAWI,QAAQ,CAAC,OAAO,IAAI;QACrF,MAAMC,cAAcC,KAAKC,KAAK,CAAC,AAACP,WAAWX,MAAM,GAAG,IAAK,KAAKc;QAE9D,IAAIE,cAActB,aAAa;YAC7B,MAAM,IAAI7C,SAAS,CAAC,iBAAiB,EAAE6C,YAAY,mBAAmB,CAAC,EAAE;QAC3E;IACF;IAEA,MAAMpB,OAAO6C,OAAOC,IAAI,CAACT,YAAY;IAErC,IAAIrC,KAAK+C,QAAQ,CAAC,UAAUT,OAAO,CAAC,OAAO,QAAQD,WAAWC,OAAO,CAAC,OAAO,KAAK;QAChF,MAAM,IAAI/D,SAAS,mCAAmC;IACxD;IAEA,OAAOyB;AACT;AAEA,SAASgC,eAAe5B,GAAQ;IAC9B,MAAM4C,cAAc5C,IAAI6C,QAAQ,CAACf,KAAK,CAAC,KAAKgB,GAAG,MAAM;IAErD,IAAI;QACF,OAAOC,mBAAmBH;IAC5B,EAAE,OAAM;QACN,OAAOA;IACT;AACF"}
@@ -29,7 +29,7 @@ describe('MCP file input', ()=>{
29
29
  maxFileSize: 4
30
30
  });
31
31
  await expect(resolveFile({
32
- collectionSlug: 'media',
32
+ slug: 'media',
33
33
  input: {
34
34
  data: Buffer.from('hello').toString('base64'),
35
35
  mimeType: 'text/plain',
@@ -49,7 +49,7 @@ describe('MCP file input', ()=>{
49
49
  ]
50
50
  });
51
51
  await expect(resolveFile({
52
- collectionSlug: 'media',
52
+ slug: 'media',
53
53
  input: {
54
54
  source: 'externalURL',
55
55
  url: 'https://example.com/image.png'
@@ -1 +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 collectionSlug: '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 collectionSlug: '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","collectionSlug","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,gBAAgB;YAChBC,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,gBAAgB;YAChBC,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
+ {"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":"AAYA,eAAO,MAAM,gBAAgB,4CA0G3B,CAAA"}
1
+ {"version":3,"file":"findDistinctTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/findDistinctTool.ts"],"names":[],"mappings":"AASA,eAAO,MAAM,gBAAgB,4CAyD3B,CAAA"}