@payloadcms/plugin-mcp 4.0.0-internal.5214550 → 4.0.0-internal.532221d

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 (99) 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.map +1 -1
  6. package/dist/mcp/buildMcpServer.d.ts.map +1 -1
  7. package/dist/mcp/builtin/collections/createTool.d.ts +1 -1
  8. package/dist/mcp/builtin/collections/createTool.d.ts.map +1 -1
  9. package/dist/mcp/builtin/collections/createTool.js +92 -41
  10. package/dist/mcp/builtin/collections/createTool.js.map +1 -1
  11. package/dist/mcp/builtin/collections/duplicateTool.js +1 -2
  12. package/dist/mcp/builtin/collections/duplicateTool.js.map +1 -1
  13. package/dist/mcp/builtin/collections/fileInput.d.ts +28 -0
  14. package/dist/mcp/builtin/collections/fileInput.d.ts.map +1 -0
  15. package/dist/mcp/builtin/collections/fileInput.js +124 -0
  16. package/dist/mcp/builtin/collections/fileInput.js.map +1 -0
  17. package/dist/mcp/builtin/collections/fileInput.spec.js +86 -0
  18. package/dist/mcp/builtin/collections/fileInput.spec.js.map +1 -0
  19. package/dist/mcp/builtin/collections/findTool.js +1 -1
  20. package/dist/mcp/builtin/collections/findTool.js.map +1 -1
  21. package/dist/mcp/builtin/collections/formatCollectionError.d.ts +1 -1
  22. package/dist/mcp/builtin/collections/formatCollectionError.d.ts.map +1 -1
  23. package/dist/mcp/builtin/collections/formatCollectionError.js +1 -1
  24. package/dist/mcp/builtin/collections/formatCollectionError.js.map +1 -1
  25. package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -1
  26. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +25 -4
  27. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -1
  28. package/dist/mcp/builtin/collections/updateTool.d.ts.map +1 -1
  29. package/dist/mcp/builtin/collections/updateTool.js +23 -12
  30. package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
  31. package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts +2 -0
  32. package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts.map +1 -0
  33. package/dist/mcp/builtin/collections/uploadInstructionsTool.js +55 -0
  34. package/dist/mcp/builtin/collections/uploadInstructionsTool.js.map +1 -0
  35. package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts.map +1 -1
  36. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js +1 -2
  37. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js.map +1 -1
  38. package/dist/mcp/builtin/globals/updateTool.js +1 -2
  39. package/dist/mcp/builtin/globals/updateTool.js.map +1 -1
  40. package/dist/mcp/builtin/validateEntityData.d.ts.map +1 -1
  41. package/dist/mcp/builtin/validateEntityData.js +1 -1
  42. package/dist/mcp/builtin/validateEntityData.js.map +1 -1
  43. package/dist/mcp/builtinTools.d.ts +6 -0
  44. package/dist/mcp/builtinTools.d.ts.map +1 -1
  45. package/dist/mcp/builtinTools.js +9 -3
  46. package/dist/mcp/builtinTools.js.map +1 -1
  47. package/dist/mcp/sanitizeMCPConfig.d.ts.map +1 -1
  48. package/dist/mcp/sanitizeMCPConfig.js +4 -1
  49. package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
  50. package/dist/stdio.d.ts.map +1 -1
  51. package/dist/stdio.js +2 -1
  52. package/dist/stdio.js.map +1 -1
  53. package/dist/utils/camelCase.d.ts.map +1 -1
  54. package/dist/utils/resolveProjectRoot.d.ts.map +1 -1
  55. package/dist/utils/toStandardSchema.d.ts.map +1 -1
  56. package/package.json +4 -4
  57. package/src/mcp/builtin/collections/createTool.ts +95 -38
  58. package/src/mcp/builtin/collections/duplicateTool.ts +5 -5
  59. package/src/mcp/builtin/collections/fileInput.spec.ts +93 -0
  60. package/src/mcp/builtin/collections/fileInput.ts +164 -0
  61. package/src/mcp/builtin/collections/findTool.ts +1 -1
  62. package/src/mcp/builtin/collections/formatCollectionError.ts +2 -2
  63. package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +19 -3
  64. package/src/mcp/builtin/collections/updateTool.ts +30 -13
  65. package/src/mcp/builtin/collections/uploadInstructionsTool.ts +64 -0
  66. package/src/mcp/builtin/globals/getGlobalSchemaTool.ts +1 -2
  67. package/src/mcp/builtin/globals/updateTool.ts +5 -5
  68. package/src/mcp/builtin/validateEntityData.ts +3 -7
  69. package/src/mcp/builtinTools.ts +9 -2
  70. package/src/mcp/sanitizeMCPConfig.ts +4 -1
  71. package/src/stdio.ts +2 -1
  72. package/dist/utils/getVirtualFieldNames.d.ts +0 -14
  73. package/dist/utils/getVirtualFieldNames.d.ts.map +0 -1
  74. package/dist/utils/getVirtualFieldNames.js +0 -35
  75. package/dist/utils/getVirtualFieldNames.js.map +0 -1
  76. package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts +0 -28
  77. package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts.map +0 -1
  78. package/dist/utils/schemaConversion/filterFieldsByAccess.js +0 -71
  79. package/dist/utils/schemaConversion/filterFieldsByAccess.js.map +0 -1
  80. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts +0 -13
  81. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts.map +0 -1
  82. package/dist/utils/schemaConversion/getEntityInputSchema.js +0 -66
  83. package/dist/utils/schemaConversion/getEntityInputSchema.js.map +0 -1
  84. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts +0 -10
  85. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts.map +0 -1
  86. package/dist/utils/schemaConversion/sanitizeEntitySchema.js +0 -384
  87. package/dist/utils/schemaConversion/sanitizeEntitySchema.js.map +0 -1
  88. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js +0 -133
  89. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js.map +0 -1
  90. package/dist/utils/transformPointDataToPayload.d.ts +0 -7
  91. package/dist/utils/transformPointDataToPayload.d.ts.map +0 -1
  92. package/dist/utils/transformPointDataToPayload.js +0 -28
  93. package/dist/utils/transformPointDataToPayload.js.map +0 -1
  94. package/src/utils/getVirtualFieldNames.ts +0 -53
  95. package/src/utils/schemaConversion/filterFieldsByAccess.ts +0 -123
  96. package/src/utils/schemaConversion/getEntityInputSchema.ts +0 -96
  97. package/src/utils/schemaConversion/sanitizeEntitySchema.spec.ts +0 -96
  98. package/src/utils/schemaConversion/sanitizeEntitySchema.ts +0 -432
  99. package/src/utils/transformPointDataToPayload.ts +0 -40
package/bin.js CHANGED
@@ -27,6 +27,13 @@ const start = async () => {
27
27
  return
28
28
  }
29
29
 
30
+ // tsx 4.22.4's synchronous loader leaks its namespace query onto Node built-ins on Node 23.5+.
31
+ // Force the stable asynchronous loader path, matching payload/bin.js.
32
+ const nodeModule = await import('node:module')
33
+ if (typeof nodeModule.default.registerHooks === 'function') {
34
+ nodeModule.default.registerHooks = undefined
35
+ }
36
+
30
37
  const { tsImport } = await import('tsx/esm/api')
31
38
  const { runMcpStdio } = await tsImport('./dist/stdio.js', baseURL)
32
39
  await runMcpStdio()
@@ -1 +1 @@
1
- {"version":3,"file":"defaultAccess.d.ts","sourceRoot":"","sources":["../src/defaultAccess.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAE/C,eAAO,MAAM,aAAa,GAAI,SAAS,aAAa,KAAG,OAA4B,CAAA"}
1
+ {"version":3,"file":"defaultAccess.d.ts","sourceRoot":"","sources":["../src/defaultAccess.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAE/C,eAAO,MAAM,aAAa,YAAa,aAAa,KAAG,OAA4B,CAAA"}
@@ -11,16 +11,16 @@ import type { CollectionTool, GlobalTool, Prompt, Tool, ToolInputSchema } from '
11
11
  * Config and handler signatures are derived from `Tool` / `CollectionTool` / `GlobalTool` /
12
12
  * `Prompt` via `Omit` + indexed access so there's no duplication with `types.ts`.
13
13
  */
14
- export declare const defineTool: <TSchema extends ToolInputSchema | undefined = ToolInputSchema | undefined>(args: Omit<Tool<TSchema>, "handler">) => {
15
- handler: (fn: Tool<TSchema>["handler"]) => Tool;
14
+ export declare const defineTool: <TSchema extends ToolInputSchema | undefined = ToolInputSchema | undefined>(args: Omit<Tool<TSchema>, 'handler'>) => {
15
+ handler: (fn: Tool<TSchema>['handler']) => Tool;
16
16
  };
17
- export declare const defineCollectionTool: <TSchema extends ToolInputSchema | undefined = ToolInputSchema | undefined>(args: Omit<CollectionTool<TSchema>, "handler">) => {
18
- handler: (fn: CollectionTool<TSchema>["handler"]) => CollectionTool;
17
+ export declare const defineCollectionTool: <TSchema extends ToolInputSchema | undefined = ToolInputSchema | undefined>(args: Omit<CollectionTool<TSchema>, 'handler'>) => {
18
+ handler: (fn: CollectionTool<TSchema>['handler']) => CollectionTool;
19
19
  };
20
- export declare const defineGlobalTool: <TSchema extends ToolInputSchema | undefined = ToolInputSchema | undefined>(args: Omit<GlobalTool<TSchema>, "handler">) => {
21
- handler: (fn: GlobalTool<TSchema>["handler"]) => GlobalTool;
20
+ export declare const defineGlobalTool: <TSchema extends ToolInputSchema | undefined = ToolInputSchema | undefined>(args: Omit<GlobalTool<TSchema>, 'handler'>) => {
21
+ handler: (fn: GlobalTool<TSchema>['handler']) => GlobalTool;
22
22
  };
23
- export declare const definePrompt: <TSchema extends ToolInputSchema = ToolInputSchema>(args: Omit<Prompt<TSchema>, "handler">) => {
24
- handler: (fn: Prompt<TSchema>["handler"]) => Prompt;
23
+ export declare const definePrompt: <TSchema extends ToolInputSchema = ToolInputSchema>(args: Omit<Prompt<TSchema>, 'handler'>) => {
24
+ handler: (fn: Prompt<TSchema>['handler']) => Prompt;
25
25
  };
26
26
  //# sourceMappingURL=defineTool.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"defineTool.d.ts","s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@
1
- {"version":3,"file":"access.d.ts","sourceRoot":"","sources":["../../src/endpoint/access.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAwB,MAAM,SAAS,CAAA;AAInE,OAAO,KAAK,EAAE,aAAa,EAAE,OAAO,EAAE,MAAM,aAAa,CAAA;AAIzD,MAAM,MAAM,oBAAoB,GAAG;IACjC,cAAc,EAAE,OAAO,CAAA;IACvB,GAAG,EAAE,cAAc,CAAA;CACpB,CAAA;AAED;;;GAGG;AACH,eAAO,MAAM,gBAAgB,EAAE,CAAC,IAAI,EAAE,oBAAoB,KAAK,OAAO,CAAC,aAAa,CAkCnF,CAAA;AAED,eAAO,MAAM,cAAc,GAAU,iCAIlC;IACD,KAAK,EAAE,OAAO,EAAE,CAAA;IAChB,cAAc,EAAE,OAAO,CAAA;IACvB,GAAG,EAAE,cAAc,CAAA;CACpB,KAAG,OAAO,CAAC,OAAO,EAAE,CAkBpB,CAAA"}
1
+ {"version":3,"file":"access.d.ts","sourceRoot":"","sources":["../../src/endpoint/access.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAwB,MAAM,SAAS,CAAA;AAInE,OAAO,KAAK,EAAE,aAAa,EAAE,OAAO,EAAE,MAAM,aAAa,CAAA;AAIzD,MAAM,MAAM,oBAAoB,GAAG;IACjC,cAAc,EAAE,OAAO,CAAA;IACvB,GAAG,EAAE,cAAc,CAAA;CACpB,CAAA;AAED;;;GAGG;AACH,eAAO,MAAM,gBAAgB,EAAE,CAAC,IAAI,EAAE,oBAAoB,KAAK,OAAO,CAAC,aAAa,CAkCnF,CAAA;AAED,eAAO,MAAM,cAAc,oCAIxB;IACD,KAAK,EAAE,OAAO,EAAE,CAAA;IAChB,cAAc,EAAE,OAAO,CAAA;IACvB,GAAG,EAAE,cAAc,CAAA;CACpB,KAAG,OAAO,CAAC,OAAO,EAAE,CAkBpB,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"buildMcpServer.d.ts","sourceRoot":"","sources":["../../src/mcp/buildMcpServer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAsB,MAAM,8BAA8B,CAAA;AAC5E,OAAO,EAAY,KAAK,cAAc,EAAE,MAAM,SAAS,CAAA;AAGvD,OAAO,KAAK,EACV,aAAa,EAMb,wBAAwB,EAEzB,MAAM,aAAa,CAAA;AAKpB;;;;;;;;;GASG;AACH,eAAO,MAAM,cAAc,GAAI,uCAI5B;IACD,aAAa,EAAE,aAAa,CAAA;IAC5B,YAAY,EAAE,wBAAwB,CAAA;IACtC,GAAG,EAAE,cAAc,CAAA;CACpB,KAAG,SAkNH,CAAA"}
1
+ {"version":3,"file":"buildMcpServer.d.ts","sourceRoot":"","sources":["../../src/mcp/buildMcpServer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAsB,MAAM,8BAA8B,CAAA;AAC5E,OAAO,EAAY,KAAK,cAAc,EAAE,MAAM,SAAS,CAAA;AAGvD,OAAO,KAAK,EACV,aAAa,EAMb,wBAAwB,EAEzB,MAAM,aAAa,CAAA;AAKpB;;;;;;;;;GASG;AACH,eAAO,MAAM,cAAc,0CAIxB;IACD,aAAa,EAAE,aAAa,CAAA;IAC5B,YAAY,EAAE,wBAAwB,CAAA;IACtC,GAAG,EAAE,cAAc,CAAA;CACpB,KAAG,SAkNH,CAAA"}
@@ -1,2 +1,2 @@
1
- export declare const createDocumentTool: import("../../../types.js").CollectionTool;
1
+ export declare const createDocumentsTool: import("../../../types.js").CollectionTool;
2
2
  //# sourceMappingURL=createTool.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"createTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/createTool.ts"],"names":[],"mappings":"AAkBA,eAAO,MAAM,kBAAkB,4CA4F7B,CAAA"}
1
+ {"version":3,"file":"createTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/createTool.ts"],"names":[],"mappings":"AAmBA,eAAO,MAAM,mBAAmB,4CAoJ9B,CAAA"}
@@ -1,28 +1,31 @@
1
+ import { getCollectionVirtualFieldNames, stripVirtualFields, transformPointDataToPayload } from 'payload';
1
2
  import { z } from 'zod';
2
3
  import { defaultAccess } from '../../../defaultAccess.js';
3
4
  import { defineCollectionTool } from '../../../defineTool.js';
4
5
  import { getLogger } from '../../../utils/getLogger.js';
5
- import { getCollectionVirtualFieldNames, stripVirtualFields } from '../../../utils/getVirtualFieldNames.js';
6
- import { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js';
7
6
  import { validateCollectionData } from '../validateEntityData.js';
7
+ import { fileInputSchema, resolveFile } from './fileInput.js';
8
8
  import { formatCollectionError } from './formatCollectionError.js';
9
- const DEFAULT_DESCRIPTION = 'Create a document in any collection by passing the collection slug and data.';
10
- export const createDocumentTool = defineCollectionTool({
9
+ const DEFAULT_DESCRIPTION = 'Create one or more documents. Each can have different data or a file. Prefer uploadReference after upload, externalURL for URLs, or base64 for small local files.';
10
+ export const createDocumentsTool = defineCollectionTool({
11
11
  access: (args)=>defaultAccess(args) && Boolean(args.permissions?.collections?.[args.collectionSlug]?.create),
12
12
  annotations: {
13
13
  destructiveHint: false,
14
14
  idempotentHint: false,
15
15
  openWorldHint: false,
16
16
  readOnlyHint: false,
17
- title: 'Create Document'
17
+ title: 'Create Documents'
18
18
  },
19
19
  description: DEFAULT_DESCRIPTION,
20
20
  input: z.object({
21
- data: z.record(z.string(), z.unknown()).describe('The document fields to create'),
22
21
  depth: z.number().int().min(0).max(10).describe('How many levels deep to populate relationships in response').optional().default(0),
23
- draft: z.boolean().describe('Whether to create the document as a draft').optional().default(false),
22
+ documents: z.array(z.object({
23
+ data: z.record(z.string(), z.unknown()).describe('The document fields to create. Only include fields permitted by the schema returned by getCollectionSchema.'),
24
+ file: fileInputSchema.optional()
25
+ })).min(1).describe('The documents to create, in order'),
26
+ draft: z.boolean().describe('Only if getCollectionSchema includes _status; otherwise _status does not exist. true forces data._status to "draft"; with false, data._status controls draft or published.').optional().default(false),
24
27
  fallbackLocale: z.string().describe('Optional: fallback locale code to use when requested locale is not available').optional(),
25
- locale: z.string().describe('Optional: locale code to create the document in (e.g., "en", "es"). Defaults to the default locale').optional(),
28
+ locale: z.string().describe('Optional: locale code to create the documents in (e.g., "en", "es"). Defaults to the default locale').optional(),
26
29
  select: z.record(z.string(), z.unknown()).describe('Optional: define exactly which fields you\'d like to return, e.g., {"title": true}').optional()
27
30
  })
28
31
  }).handler(async ({ authorizedMCP, collectionSlug, input, req })=>{
@@ -30,50 +33,98 @@ export const createDocumentTool = defineCollectionTool({
30
33
  const logger = getLogger({
31
34
  payload
32
35
  });
33
- const { data, depth, draft, fallbackLocale, locale, select } = input;
34
- logger.info(`Creating document in collection: ${collectionSlug}${locale ? ` with locale: ${locale}` : ''}`);
36
+ const { depth, documents, draft, fallbackLocale, locale, select } = input;
37
+ logger.info(`Creating ${documents.length} documents in collection: ${collectionSlug}`);
35
38
  try {
36
39
  const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, collectionSlug);
37
- const inputData = stripVirtualFields(data, virtualFieldNames);
38
- const validationError = validateCollectionData({
39
- collectionSlug,
40
- data: inputData,
41
- req
42
- });
43
- if (validationError) {
44
- return validationError;
40
+ const docs = [];
41
+ const errors = [];
42
+ let validationSchema;
43
+ for (const [index, document] of documents.entries()){
44
+ try {
45
+ const inputData = stripVirtualFields(document.data, virtualFieldNames);
46
+ const validationError = validateCollectionData({
47
+ collectionSlug,
48
+ data: inputData,
49
+ req
50
+ });
51
+ if (validationError) {
52
+ const firstContent = validationError.content[0];
53
+ const validationContent = validationError.structuredContent;
54
+ const schema = validationContent?.schema;
55
+ if (!validationSchema && schema && typeof schema === 'object') {
56
+ validationSchema = schema;
57
+ }
58
+ errors.push({
59
+ index,
60
+ message: firstContent?.type === 'text' ? firstContent.text.split('\n\nUse this schema')[0] ?? 'Invalid document data' : 'Invalid document data'
61
+ });
62
+ continue;
63
+ }
64
+ const parsedData = transformPointDataToPayload(inputData);
65
+ const file = await resolveFile({
66
+ collectionSlug,
67
+ input: document.file,
68
+ req
69
+ });
70
+ const result = await payload.create({
71
+ collection: collectionSlug,
72
+ data: parsedData,
73
+ depth,
74
+ draft,
75
+ overrideAccess: authorizedMCP.overrideAccess,
76
+ req,
77
+ ...file ? {
78
+ file
79
+ } : {},
80
+ ...locale ? {
81
+ locale
82
+ } : {},
83
+ ...fallbackLocale ? {
84
+ fallbackLocale
85
+ } : {},
86
+ ...select ? {
87
+ select: select
88
+ } : {}
89
+ });
90
+ docs.push({
91
+ doc: result,
92
+ index
93
+ });
94
+ } catch (error) {
95
+ const message = error instanceof Error ? error.message : 'Unknown error';
96
+ logger.error(`Error creating document at index ${index} in ${collectionSlug}: ${message}`);
97
+ errors.push({
98
+ index,
99
+ message
100
+ });
101
+ }
45
102
  }
46
- const parsedData = transformPointDataToPayload(inputData);
47
- const result = await payload.create({
48
- collection: collectionSlug,
49
- data: parsedData,
50
- depth,
51
- draft,
52
- overrideAccess: authorizedMCP.overrideAccess,
53
- req,
54
- ...locale ? {
55
- locale
56
- } : {},
57
- ...fallbackLocale ? {
58
- fallbackLocale
59
- } : {},
60
- ...select ? {
61
- select: select
62
- } : {}
63
- });
64
- logger.info(`Successfully created document in ${collectionSlug} with ID: ${result.id}`);
103
+ const batchResult = {
104
+ docs,
105
+ errors
106
+ };
107
+ const retryMessage = errors.length > 0 ? '\nRetry failed indexes only.' : '';
108
+ const schemaMessage = validationSchema ? `\n\nUse this schema for data:\n\`\`\`json\n${JSON.stringify(validationSchema)}\n\`\`\`` : '';
109
+ const structuredContent = validationSchema ? {
110
+ ...batchResult,
111
+ schema: validationSchema
112
+ } : batchResult;
113
+ logger.info(`Created ${docs.length} of ${documents.length} documents in ${collectionSlug}`);
65
114
  return {
66
115
  content: [
67
116
  {
68
117
  type: 'text',
69
- text: `Document created successfully in collection "${collectionSlug}"!\nCreated document:\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``
118
+ text: `Created ${docs.length} of ${documents.length} documents in collection "${collectionSlug}".${retryMessage}\nResults:\n\`\`\`json\n${JSON.stringify(batchResult)}\n\`\`\`${schemaMessage}`
70
119
  }
71
120
  ],
72
- doc: result
121
+ doc: structuredContent,
122
+ isError: docs.length === 0 && errors.length > 0,
123
+ structuredContent
73
124
  };
74
125
  } catch (error) {
75
- const errorMessage = error instanceof Error ? error.message : 'Unknown error';
76
- logger.error(`Error creating document in ${collectionSlug}: ${errorMessage}`);
126
+ const message = error instanceof Error ? error.message : 'Unknown error';
127
+ logger.error(`Error creating documents in ${collectionSlug}: ${message}`);
77
128
  return formatCollectionError({
78
129
  action: 'creating',
79
130
  collectionSlug,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/mcp/builtin/collections/createTool.ts"],"sourcesContent":["import type { 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 { validateCollectionData } from '../validateEntityData.js'\nimport { formatCollectionError } from './formatCollectionError.js'\n\nconst DEFAULT_DESCRIPTION =\n 'Create a document in any collection by passing the collection slug and data.'\n\nexport const createDocumentTool = 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: 'Create Document',\n },\n description: DEFAULT_DESCRIPTION,\n input: z.object({\n data: z.record(z.string(), z.unknown()).describe('The document fields to create'),\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 document 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 create the document in (e.g., \"en\", \"es\"). Defaults to the default locale',\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, e.g., {\"title\": true}',\n )\n .optional(),\n }),\n}).handler(async ({ authorizedMCP, collectionSlug, input, req }) => {\n const payload = req.payload\n const logger = getLogger({ payload })\n\n const { data, depth, draft, fallbackLocale, locale, select } = input\n\n logger.info(\n `Creating document in collection: ${collectionSlug}${locale ? ` with locale: ${locale}` : ''}`,\n )\n\n try {\n const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, collectionSlug)\n const inputData = stripVirtualFields(data, virtualFieldNames)\n const validationError = validateCollectionData({ collectionSlug, data: inputData, req })\n\n if (validationError) {\n return validationError\n }\n\n const parsedData = transformPointDataToPayload(inputData)\n\n const result = await payload.create({\n collection: collectionSlug,\n data: parsedData,\n depth,\n draft,\n overrideAccess: authorizedMCP.overrideAccess,\n req,\n ...(locale ? { locale } : {}),\n ...(fallbackLocale ? { fallbackLocale } : {}),\n ...(select ? { select: select as SelectType } : {}),\n })\n\n logger.info(`Successfully created document in ${collectionSlug} with ID: ${result.id}`)\n\n return {\n content: [\n {\n type: 'text',\n text: `Document created successfully in collection \"${collectionSlug}\"!\\nCreated 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 creating document in ${collectionSlug}: ${errorMessage}`)\n return formatCollectionError({ action: 'creating', collectionSlug, error, req })\n }\n})\n"],"names":["z","defaultAccess","defineCollectionTool","getLogger","getCollectionVirtualFieldNames","stripVirtualFields","transformPointDataToPayload","validateCollectionData","formatCollectionError","DEFAULT_DESCRIPTION","createDocumentTool","access","args","Boolean","permissions","collections","collectionSlug","create","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","object","data","record","string","unknown","describe","depth","number","int","min","max","optional","default","draft","boolean","fallbackLocale","locale","select","handler","authorizedMCP","req","payload","logger","info","virtualFieldNames","config","inputData","validationError","parsedData","result","collection","overrideAccess","id","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,sBAAsB,QAAQ,2BAA0B;AACjE,SAASC,qBAAqB,QAAQ,6BAA4B;AAElE,MAAMC,sBACJ;AAEF,OAAO,MAAMC,qBAAqBR,qBAAqB;IACrDS,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,MAAM3B,EAAE4B,MAAM,CAAC5B,EAAE6B,MAAM,IAAI7B,EAAE8B,OAAO,IAAIC,QAAQ,CAAC;QACjDC,OAAOhC,EACJiC,MAAM,GACNC,GAAG,GACHC,GAAG,CAAC,GACJC,GAAG,CAAC,IACJL,QAAQ,CAAC,8DACTM,QAAQ,GACRC,OAAO,CAAC;QACXC,OAAOvC,EACJwC,OAAO,GACPT,QAAQ,CAAC,6CACTM,QAAQ,GACRC,OAAO,CAAC;QACXG,gBAAgBzC,EACb6B,MAAM,GACNE,QAAQ,CAAC,gFACTM,QAAQ;QACXK,QAAQ1C,EACL6B,MAAM,GACNE,QAAQ,CACP,sGAEDM,QAAQ;QACX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mCAAmC,EAAE8C,KAAKC,SAAS,CAACR,QAAQ,QAAQ,CAAC;gBAC5I;aACD;YACDS,KAAKT;QACP;IACF,EAAE,OAAOU,OAAO;QACd,MAAMC,eAAeD,iBAAiBE,QAAQF,MAAMG,OAAO,GAAG;QAC9DpB,OAAOiB,KAAK,CAAC,CAAC,2BAA2B,EAAEjD,eAAe,EAAE,EAAEkD,cAAc;QAC5E,OAAO1D,sBAAsB;YAAE6D,QAAQ;YAAYrD;YAAgBiD;YAAOnB;QAAI;IAChF;AACF,GAAE"}
1
+ {"version":3,"sources":["../../../../src/mcp/builtin/collections/createTool.ts"],"sourcesContent":["import type { SelectType } from 'payload'\n\nimport {\n getCollectionVirtualFieldNames,\n stripVirtualFields,\n transformPointDataToPayload,\n} from 'payload'\nimport { z } from 'zod'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\nimport { validateCollectionData } from '../validateEntityData.js'\nimport { fileInputSchema, resolveFile } from './fileInput.js'\nimport { formatCollectionError } from './formatCollectionError.js'\n\nconst DEFAULT_DESCRIPTION =\n 'Create one or more documents. Each can have different data or a file. Prefer uploadReference after upload, externalURL for URLs, or base64 for small local files.'\n\nexport const createDocumentsTool = 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: 'Create Documents',\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 response')\n .optional()\n .default(0),\n documents: z\n .array(\n z.object({\n data: z\n .record(z.string(), z.unknown())\n .describe(\n 'The document fields to create. Only include fields permitted by the schema returned by getCollectionSchema.',\n ),\n file: fileInputSchema.optional(),\n }),\n )\n .min(1)\n .describe('The documents to create, in order'),\n draft: z\n .boolean()\n .describe(\n 'Only if getCollectionSchema includes _status; otherwise _status does not exist. true forces data._status to \"draft\"; with false, data._status controls draft or published.',\n )\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 create the documents in (e.g., \"en\", \"es\"). Defaults to the default locale',\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, e.g., {\"title\": true}',\n )\n .optional(),\n }),\n}).handler(async ({ authorizedMCP, collectionSlug, input, req }) => {\n const payload = req.payload\n const logger = getLogger({ payload })\n const { depth, documents, draft, fallbackLocale, locale, select } = input\n\n logger.info(`Creating ${documents.length} documents in collection: ${collectionSlug}`)\n\n try {\n const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, collectionSlug)\n const docs: Array<{ doc: Record<string, unknown>; index: number }> = []\n const errors: Array<{ index: number; message: string }> = []\n let validationSchema: Record<string, unknown> | undefined\n\n for (const [index, document] of documents.entries()) {\n try {\n const inputData = stripVirtualFields(document.data, virtualFieldNames)\n const validationError = validateCollectionData({ collectionSlug, data: inputData, req })\n\n if (validationError) {\n const firstContent = validationError.content[0]\n const validationContent = validationError.structuredContent as\n | Record<string, unknown>\n | undefined\n const schema = validationContent?.schema\n\n if (!validationSchema && schema && typeof schema === 'object') {\n validationSchema = schema as Record<string, unknown>\n }\n\n errors.push({\n index,\n message:\n firstContent?.type === 'text'\n ? (firstContent.text.split('\\n\\nUse this schema')[0] ?? 'Invalid document data')\n : 'Invalid document data',\n })\n continue\n }\n\n const parsedData = transformPointDataToPayload(inputData)\n const file = await resolveFile({ collectionSlug, input: document.file, req })\n const result = await payload.create({\n collection: collectionSlug,\n data: parsedData,\n depth,\n draft,\n overrideAccess: authorizedMCP.overrideAccess,\n req,\n ...(file ? { file } : {}),\n ...(locale ? { locale } : {}),\n ...(fallbackLocale ? { fallbackLocale } : {}),\n ...(select ? { select: select as SelectType } : {}),\n })\n\n docs.push({ doc: result as Record<string, unknown>, index })\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error'\n\n logger.error(`Error creating document at index ${index} in ${collectionSlug}: ${message}`)\n errors.push({ index, message })\n }\n }\n\n const batchResult = { docs, errors }\n const retryMessage = errors.length > 0 ? '\\nRetry failed indexes only.' : ''\n const schemaMessage = validationSchema\n ? `\\n\\nUse this schema for data:\\n\\`\\`\\`json\\n${JSON.stringify(validationSchema)}\\n\\`\\`\\``\n : ''\n const structuredContent = validationSchema\n ? { ...batchResult, schema: validationSchema }\n : batchResult\n\n logger.info(`Created ${docs.length} of ${documents.length} documents in ${collectionSlug}`)\n\n return {\n content: [\n {\n type: 'text',\n text: `Created ${docs.length} of ${documents.length} documents in collection \"${collectionSlug}\".${retryMessage}\\nResults:\\n\\`\\`\\`json\\n${JSON.stringify(batchResult)}\\n\\`\\`\\`${schemaMessage}`,\n },\n ],\n doc: structuredContent as unknown as Record<string, unknown>,\n isError: docs.length === 0 && errors.length > 0,\n structuredContent,\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error'\n\n logger.error(`Error creating documents in ${collectionSlug}: ${message}`)\n return formatCollectionError({ action: 'creating', collectionSlug, error, req })\n }\n})\n"],"names":["getCollectionVirtualFieldNames","stripVirtualFields","transformPointDataToPayload","z","defaultAccess","defineCollectionTool","getLogger","validateCollectionData","fileInputSchema","resolveFile","formatCollectionError","DEFAULT_DESCRIPTION","createDocumentsTool","access","args","Boolean","permissions","collections","collectionSlug","create","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","object","depth","number","int","min","max","describe","optional","default","documents","array","data","record","string","unknown","file","draft","boolean","fallbackLocale","locale","select","handler","authorizedMCP","req","payload","logger","info","length","virtualFieldNames","config","docs","errors","validationSchema","index","document","entries","inputData","validationError","firstContent","content","validationContent","structuredContent","schema","push","message","type","text","split","parsedData","result","collection","overrideAccess","doc","error","Error","batchResult","retryMessage","schemaMessage","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C,MAAM,CAAC,QAAQ,EAAEhB,KAAKH,MAAM,CAAC,IAAI,EAAElB,UAAUkB,MAAM,CAAC,0BAA0B,EAAErC,eAAe,EAAE,EAAEkE,aAAa,wBAAwB,EAAEE,KAAKC,SAAS,CAACJ,aAAa,QAAQ,EAAEE,eAAe;gBACjM;aACD;YACDL,KAAKX;YACLmB,SAAS9B,KAAKH,MAAM,KAAK,KAAKI,OAAOJ,MAAM,GAAG;YAC9Cc;QACF;IACF,EAAE,OAAOY,OAAO;QACd,MAAMT,UAAUS,iBAAiBC,QAAQD,MAAMT,OAAO,GAAG;QAEzDnB,OAAO4B,KAAK,CAAC,CAAC,4BAA4B,EAAE/D,eAAe,EAAE,EAAEsD,SAAS;QACxE,OAAO9D,sBAAsB;YAAE+E,QAAQ;YAAYvE;YAAgB+D;YAAO9B;QAAI;IAChF;AACF,GAAE"}
@@ -1,9 +1,8 @@
1
+ import { getCollectionVirtualFieldNames, stripVirtualFields, transformPointDataToPayload } from 'payload';
1
2
  import { z } from 'zod';
2
3
  import { defaultAccess } from '../../../defaultAccess.js';
3
4
  import { defineCollectionTool } from '../../../defineTool.js';
4
5
  import { getLogger } from '../../../utils/getLogger.js';
5
- import { getCollectionVirtualFieldNames, stripVirtualFields } from '../../../utils/getVirtualFieldNames.js';
6
- import { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js';
7
6
  import { formatCollectionError } from './formatCollectionError.js';
8
7
  const DEFAULT_DESCRIPTION = 'Duplicate a document in any collection by passing the collection slug and source document ID.';
9
8
  export const duplicateDocumentTool = defineCollectionTool({
@@ -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;AAEv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EA;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;YACLsC,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,gDAAgD,EAAEnD,eAAe,sCAAsC,EAAEoD,KAAKC,SAAS,CAACR,QAAQ,QAAQ,CAAC;gBAClJ;aACD;YACDS,KAAKT;QACP;IACF,EAAE,OAAOU,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 type { PopulateType, SelectType } from 'payload'\n\nimport {\n getCollectionVirtualFieldNames,\n stripVirtualFields,\n transformPointDataToPayload,\n} from 'payload'\nimport { z } from 'zod'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.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":["getCollectionVirtualFieldNames","stripVirtualFields","transformPointDataToPayload","z","defaultAccess","defineCollectionTool","getLogger","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,SACEA,8BAA8B,EAC9BC,kBAAkB,EAClBC,2BAA2B,QACtB,UAAS;AAChB,SAASC,CAAC,QAAQ,MAAK;AAEvB,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AACvD,SAASC,qBAAqB,QAAQ,6BAA4B;AAElE,MAAMC,sBACJ;AAEF,OAAO,MAAMC,wBAAwBJ,qBAAqB;IACxDK,QAAQ,CAACC,OACPP,cAAcO,SAASC,QAAQD,KAAKE,WAAW,EAAEC,aAAa,CAACH,KAAKI,cAAc,CAAC,EAAEC;IACvFC,aAAa;QACXC,iBAAiB;QACjBC,gBAAgB;QAChBC,eAAe;QACfC,cAAc;Q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AAC,8BAA8B,EAAEvD,eAAe,EAAE,EAAEwD,cAAc;QAC/E,OAAOhE,sBAAsB;YAAEmE,QAAQ;YAAe3D;YAAgBuD;YAAOnB;QAAI;IACnF;AACF,GAAE"}
@@ -0,0 +1,28 @@
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">;
21
+ type FileInput = z.infer<typeof fileInputSchema>;
22
+ export declare function resolveFile({ collectionSlug, input, req, }: {
23
+ collectionSlug: CollectionSlug;
24
+ input?: FileInput;
25
+ req: PayloadRequest;
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,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,CA8E5B"}
@@ -0,0 +1,124 @@
1
+ import { APIError } from 'payload';
2
+ import { getExternalFile, getFileFromUploadInstructions, isURLAllowed } from 'payload/internal';
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({
7
+ filename: z.string(),
8
+ mimeType: z.string(),
9
+ size: z.number().int().nonnegative(),
10
+ uploadReference: z.record(z.string(), z.unknown())
11
+ });
12
+ 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'),
17
+ source: z.literal('base64')
18
+ }),
19
+ z.object({
20
+ name: z.string().min(1).describe('Optional file name override').optional(),
21
+ source: z.literal('externalURL'),
22
+ url: z.url().describe('The http or https URL to download')
23
+ }),
24
+ z.object({
25
+ file: uploadFileSchema.describe('getUploadInstructions file field post-upload'),
26
+ source: z.literal('uploadReference')
27
+ })
28
+ ]).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.');
29
+ export async function resolveFile({ collectionSlug, input, req }) {
30
+ if (!input) {
31
+ return undefined;
32
+ }
33
+ if (input.source === 'uploadReference') {
34
+ try {
35
+ return await getFileFromUploadInstructions({
36
+ collectionSlug,
37
+ file: input.file,
38
+ req
39
+ });
40
+ } catch (error) {
41
+ if (error instanceof Error && error.message === 'Staged upload was not found.') {
42
+ throw new APIError('Staged upload not found. Complete the upload action first, or use base64 for small local files.', 400);
43
+ }
44
+ throw error;
45
+ }
46
+ }
47
+ const uploadConfig = req.payload.collections[collectionSlug]?.config.upload;
48
+ if (!uploadConfig) {
49
+ throw new APIError(`Collection "${collectionSlug}" does not support file uploads.`, 400);
50
+ }
51
+ const maxFileSize = req.payload.config.upload.limits?.fileSize;
52
+ let file;
53
+ if (input.source === 'base64') {
54
+ const data = decodeBase64({
55
+ maxFileSize,
56
+ value: input.data
57
+ });
58
+ file = {
59
+ name: sanitizeFilename(input.name),
60
+ data,
61
+ mimetype: input.mimeType,
62
+ size: data.length
63
+ };
64
+ } else {
65
+ if (uploadConfig.pasteURL === false) {
66
+ throw new APIError(`Uploading files from URLs is disabled for collection "${collectionSlug}".`, 400);
67
+ }
68
+ const url = new URL(input.url);
69
+ if (![
70
+ 'http:',
71
+ 'https:'
72
+ ].includes(url.protocol)) {
73
+ throw new APIError('File URLs must use http or https.', 400);
74
+ }
75
+ if (typeof uploadConfig.pasteURL === 'object' && !isURLAllowed(input.url, uploadConfig.pasteURL.allowList)) {
76
+ throw new APIError('The provided file URL is not allowed.', 400);
77
+ }
78
+ file = await getExternalFile({
79
+ data: {
80
+ filename: sanitizeFilename(input.name || getURLFilename(url)),
81
+ url: input.url
82
+ },
83
+ req,
84
+ uploadConfig: {
85
+ ...uploadConfig,
86
+ externalFileHeaderFilter: uploadConfig.externalFileHeaderFilter ?? (()=>({}))
87
+ }
88
+ });
89
+ file.mimetype = file.mimetype?.split(';')[0] || 'application/octet-stream';
90
+ file.size = file.data.length;
91
+ }
92
+ if (maxFileSize !== undefined && Number.isFinite(maxFileSize) && file.size > maxFileSize) {
93
+ throw new APIError(`File exceeds the ${maxFileSize} byte upload limit.`, 400);
94
+ }
95
+ return file;
96
+ }
97
+ function decodeBase64({ maxFileSize, value }) {
98
+ const normalized = value.replace(/\s/g, '');
99
+ if (!/^[a-z0-9+/]*={0,2}$/i.test(normalized) || normalized.length % 4 === 1) {
100
+ throw new APIError('File data must be valid base64.', 400);
101
+ }
102
+ if (maxFileSize !== undefined && Number.isFinite(maxFileSize)) {
103
+ const paddingLength = normalized.endsWith('==') ? 2 : normalized.endsWith('=') ? 1 : 0;
104
+ const decodedSize = Math.floor(normalized.length * 3 / 4) - paddingLength;
105
+ if (decodedSize > maxFileSize) {
106
+ throw new APIError(`File exceeds the ${maxFileSize} byte upload limit.`, 400);
107
+ }
108
+ }
109
+ const data = Buffer.from(normalized, 'base64');
110
+ if (data.toString('base64').replace(/=+$/, '') !== normalized.replace(/=+$/, '')) {
111
+ throw new APIError('File data must be valid base64.', 400);
112
+ }
113
+ return data;
114
+ }
115
+ function getURLFilename(url) {
116
+ const pathSegment = url.pathname.split('/').pop() || 'upload';
117
+ try {
118
+ return decodeURIComponent(pathSegment);
119
+ } catch {
120
+ return pathSegment;
121
+ }
122
+ }
123
+
124
+ //# sourceMappingURL=fileInput.js.map
@@ -0,0 +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('getUploadInstructions file field post-upload'),\n source: z.literal('uploadReference'),\n }),\n ])\n .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\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 try {\n return await getFileFromUploadInstructions({ collectionSlug, 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[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","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","path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