@payloadcms/plugin-mcp 4.0.0-internal.8ba6b5b → 4.0.0-internal.9726517

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 (56) 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.map +1 -1
  8. package/dist/mcp/builtin/collections/createTool.js +14 -4
  9. package/dist/mcp/builtin/collections/createTool.js.map +1 -1
  10. package/dist/mcp/builtin/collections/fileInput.d.ts +28 -0
  11. package/dist/mcp/builtin/collections/fileInput.d.ts.map +1 -0
  12. package/dist/mcp/builtin/collections/fileInput.js +117 -0
  13. package/dist/mcp/builtin/collections/fileInput.js.map +1 -0
  14. package/dist/mcp/builtin/collections/fileInput.spec.js +86 -0
  15. package/dist/mcp/builtin/collections/fileInput.spec.js.map +1 -0
  16. package/dist/mcp/builtin/collections/findTool.js +1 -1
  17. package/dist/mcp/builtin/collections/findTool.js.map +1 -1
  18. package/dist/mcp/builtin/collections/formatCollectionError.d.ts +1 -1
  19. package/dist/mcp/builtin/collections/formatCollectionError.d.ts.map +1 -1
  20. package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -1
  21. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +24 -2
  22. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -1
  23. package/dist/mcp/builtin/collections/updateTool.d.ts.map +1 -1
  24. package/dist/mcp/builtin/collections/updateTool.js +22 -9
  25. package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
  26. package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts +2 -0
  27. package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts.map +1 -0
  28. package/dist/mcp/builtin/collections/uploadInstructionsTool.js +55 -0
  29. package/dist/mcp/builtin/collections/uploadInstructionsTool.js.map +1 -0
  30. package/dist/mcp/builtin/validateEntityData.d.ts.map +1 -1
  31. package/dist/mcp/builtinTools.d.ts +6 -0
  32. package/dist/mcp/builtinTools.d.ts.map +1 -1
  33. package/dist/mcp/builtinTools.js +6 -0
  34. package/dist/mcp/builtinTools.js.map +1 -1
  35. package/dist/mcp/sanitizeMCPConfig.d.ts.map +1 -1
  36. package/dist/mcp/sanitizeMCPConfig.js +4 -1
  37. package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
  38. package/dist/utils/camelCase.d.ts.map +1 -1
  39. package/dist/utils/resolveProjectRoot.d.ts.map +1 -1
  40. package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts.map +1 -1
  41. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts.map +1 -1
  42. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts.map +1 -1
  43. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js +2 -2
  44. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js.map +1 -1
  45. package/dist/utils/toStandardSchema.d.ts.map +1 -1
  46. package/package.json +5 -5
  47. package/src/mcp/builtin/collections/createTool.ts +14 -4
  48. package/src/mcp/builtin/collections/fileInput.spec.ts +93 -0
  49. package/src/mcp/builtin/collections/fileInput.ts +154 -0
  50. package/src/mcp/builtin/collections/findTool.ts +1 -1
  51. package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +18 -1
  52. package/src/mcp/builtin/collections/updateTool.ts +24 -7
  53. package/src/mcp/builtin/collections/uploadInstructionsTool.ts +64 -0
  54. package/src/mcp/builtinTools.ts +7 -0
  55. package/src/mcp/sanitizeMCPConfig.ts +4 -1
  56. package/src/utils/schemaConversion/sanitizeEntitySchema.spec.ts +2 -2
@@ -11,10 +11,11 @@ import {
11
11
  } from '../../../utils/getVirtualFieldNames.js'
12
12
  import { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'
13
13
  import { validateCollectionData } from '../validateEntityData.js'
14
+ import { fileInputSchema, resolveFile } from './fileInput.js'
14
15
  import { formatCollectionError } from './formatCollectionError.js'
15
16
 
16
17
  const DEFAULT_DESCRIPTION =
17
- 'Create a document in any collection by passing the collection slug and data.'
18
+ 'Create a document in any collection. Files can use a URL, base64, or an upload prepared by getUploadInstructions.'
18
19
 
19
20
  export const createDocumentTool = defineCollectionTool({
20
21
  access: (args) =>
@@ -28,7 +29,11 @@ export const createDocumentTool = defineCollectionTool({
28
29
  },
29
30
  description: DEFAULT_DESCRIPTION,
30
31
  input: z.object({
31
- data: z.record(z.string(), z.unknown()).describe('The document fields to create'),
32
+ data: z
33
+ .record(z.string(), z.unknown())
34
+ .describe(
35
+ 'The document fields to create. Only include fields permitted by the schema returned by getCollectionSchema.',
36
+ ),
32
37
  depth: z
33
38
  .number()
34
39
  .int()
@@ -39,13 +44,16 @@ export const createDocumentTool = defineCollectionTool({
39
44
  .default(0),
40
45
  draft: z
41
46
  .boolean()
42
- .describe('Whether to create the document as a draft')
47
+ .describe(
48
+ 'Only if getCollectionSchema includes _status; otherwise _status does not exist. true forces data._status to "draft"; with false, data._status controls draft or published.',
49
+ )
43
50
  .optional()
44
51
  .default(false),
45
52
  fallbackLocale: z
46
53
  .string()
47
54
  .describe('Optional: fallback locale code to use when requested locale is not available')
48
55
  .optional(),
56
+ file: fileInputSchema.optional(),
49
57
  locale: z
50
58
  .string()
51
59
  .describe(
@@ -63,7 +71,7 @@ export const createDocumentTool = defineCollectionTool({
63
71
  const payload = req.payload
64
72
  const logger = getLogger({ payload })
65
73
 
66
- const { data, depth, draft, fallbackLocale, locale, select } = input
74
+ const { data, depth, draft, fallbackLocale, file: fileInput, locale, select } = input
67
75
 
68
76
  logger.info(
69
77
  `Creating document in collection: ${collectionSlug}${locale ? ` with locale: ${locale}` : ''}`,
@@ -79,6 +87,7 @@ export const createDocumentTool = defineCollectionTool({
79
87
  }
80
88
 
81
89
  const parsedData = transformPointDataToPayload(inputData)
90
+ const file = await resolveFile({ collectionSlug, input: fileInput, req })
82
91
 
83
92
  const result = await payload.create({
84
93
  collection: collectionSlug,
@@ -87,6 +96,7 @@ export const createDocumentTool = defineCollectionTool({
87
96
  draft,
88
97
  overrideAccess: authorizedMCP.overrideAccess,
89
98
  req,
99
+ ...(file ? { file } : {}),
90
100
  ...(locale ? { locale } : {}),
91
101
  ...(fallbackLocale ? { fallbackLocale } : {}),
92
102
  ...(select ? { select: select as SelectType } : {}),
@@ -0,0 +1,93 @@
1
+ import type { PayloadRequest } from 'payload'
2
+
3
+ import { describe, expect, it } from 'vitest'
4
+
5
+ import { fileInputSchema, resolveFile } from './fileInput.js'
6
+
7
+ describe('MCP file input', () => {
8
+ it('should reject malformed MIME types', () => {
9
+ const result = fileInputSchema.safeParse({
10
+ data: 'aGVsbG8=',
11
+ mimeType: 'text/plain\r\nx-test: value',
12
+ name: 'hello.txt',
13
+ source: 'base64',
14
+ })
15
+
16
+ expect(result.success).toBe(false)
17
+ })
18
+
19
+ it('should accept a prepared upload', () => {
20
+ const result = fileInputSchema.safeParse({
21
+ file: {
22
+ filename: 'image.png',
23
+ mimeType: 'image/png',
24
+ size: 123,
25
+ uploadReference: { uploadId: 'upload-id' },
26
+ },
27
+ source: 'uploadReference',
28
+ })
29
+
30
+ expect(result.success).toBe(true)
31
+ })
32
+
33
+ it('should reject oversized base64 files', async () => {
34
+ const req = createRequest({ maxFileSize: 4 })
35
+
36
+ await expect(
37
+ resolveFile({
38
+ collectionSlug: 'media',
39
+ input: {
40
+ data: Buffer.from('hello').toString('base64'),
41
+ mimeType: 'text/plain',
42
+ name: 'hello.txt',
43
+ source: 'base64',
44
+ },
45
+ req,
46
+ }),
47
+ ).rejects.toThrow('File exceeds the 4 byte upload limit.')
48
+ })
49
+
50
+ it('should reject URLs outside the collection allowlist', async () => {
51
+ const req = createRequest({
52
+ allowList: [{ hostname: 'assets.example.com', protocol: 'https' }],
53
+ })
54
+
55
+ await expect(
56
+ resolveFile({
57
+ collectionSlug: 'media',
58
+ input: {
59
+ source: 'externalURL',
60
+ url: 'https://example.com/image.png',
61
+ },
62
+ req,
63
+ }),
64
+ ).rejects.toThrow('The provided file URL is not allowed.')
65
+ })
66
+ })
67
+
68
+ function createRequest({
69
+ allowList,
70
+ maxFileSize,
71
+ }: {
72
+ allowList?: Array<{ hostname: string; protocol: 'http' | 'https' }>
73
+ maxFileSize?: number
74
+ }): PayloadRequest {
75
+ return {
76
+ payload: {
77
+ collections: {
78
+ media: {
79
+ config: {
80
+ upload: allowList ? { pasteURL: { allowList } } : {},
81
+ },
82
+ },
83
+ },
84
+ config: {
85
+ upload: {
86
+ limits: {
87
+ fileSize: maxFileSize,
88
+ },
89
+ },
90
+ },
91
+ },
92
+ } as unknown as PayloadRequest
93
+ }
@@ -0,0 +1,154 @@
1
+ import type { CollectionSlug, File, FileData, PayloadRequest } from 'payload'
2
+
3
+ import { APIError } from 'payload'
4
+ import { getExternalFile, getFileFromUploadInstructions, isURLAllowed } from 'payload/internal'
5
+ import { sanitizeFilename } from 'payload/shared'
6
+ import { z } from 'zod'
7
+
8
+ const mimeTypeSchema = z
9
+ .string()
10
+ .regex(/^[!#$%&'*+.^`|~\w-]+\/[!#$%&'*+.^`|~\w-]+$/, 'MIME type must use the type/subtype format')
11
+
12
+ const uploadFileSchema = z.object({
13
+ filename: z.string(),
14
+ mimeType: z.string(),
15
+ size: z.number().int().nonnegative(),
16
+ uploadReference: z.record(z.string(), z.unknown()),
17
+ })
18
+
19
+ export const fileInputSchema = z
20
+ .discriminatedUnion('source', [
21
+ z.object({
22
+ name: z.string().min(1).describe('The file name, including its extension'),
23
+ data: z.string().describe('The base64-encoded file bytes, without a data URL prefix'),
24
+ mimeType: mimeTypeSchema.describe('The file MIME type, for example image/png'),
25
+ source: z.literal('base64'),
26
+ }),
27
+ z.object({
28
+ name: z.string().min(1).describe('Optional file name override').optional(),
29
+ source: z.literal('externalURL'),
30
+ url: z.url().describe('The http or https URL to download'),
31
+ }),
32
+ z.object({
33
+ file: uploadFileSchema.describe('The file value returned by getUploadInstructions'),
34
+ source: z.literal('uploadReference'),
35
+ }),
36
+ ])
37
+ .describe(
38
+ '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.',
39
+ )
40
+
41
+ type FileInput = z.infer<typeof fileInputSchema>
42
+
43
+ export async function resolveFile({
44
+ collectionSlug,
45
+ input,
46
+ req,
47
+ }: {
48
+ collectionSlug: CollectionSlug
49
+ input?: FileInput
50
+ req: PayloadRequest
51
+ }): Promise<File | undefined> {
52
+ if (!input) {
53
+ return undefined
54
+ }
55
+
56
+ if (input.source === 'uploadReference') {
57
+ return getFileFromUploadInstructions({ collectionSlug, file: input.file, req })
58
+ }
59
+
60
+ const uploadConfig = req.payload.collections[collectionSlug]?.config.upload
61
+
62
+ if (!uploadConfig) {
63
+ throw new APIError(`Collection "${collectionSlug}" does not support file uploads.`, 400)
64
+ }
65
+
66
+ const maxFileSize = req.payload.config.upload.limits?.fileSize
67
+ let file: File
68
+
69
+ if (input.source === 'base64') {
70
+ const data = decodeBase64({ maxFileSize, value: input.data })
71
+
72
+ file = {
73
+ name: sanitizeFilename(input.name),
74
+ data,
75
+ mimetype: input.mimeType,
76
+ size: data.length,
77
+ }
78
+ } else {
79
+ if (uploadConfig.pasteURL === false) {
80
+ throw new APIError(
81
+ `Uploading files from URLs is disabled for collection "${collectionSlug}".`,
82
+ 400,
83
+ )
84
+ }
85
+
86
+ const url = new URL(input.url)
87
+
88
+ if (!['http:', 'https:'].includes(url.protocol)) {
89
+ throw new APIError('File URLs must use http or https.', 400)
90
+ }
91
+
92
+ if (
93
+ typeof uploadConfig.pasteURL === 'object' &&
94
+ !isURLAllowed(input.url, uploadConfig.pasteURL.allowList)
95
+ ) {
96
+ throw new APIError('The provided file URL is not allowed.', 400)
97
+ }
98
+
99
+ file = await getExternalFile({
100
+ data: {
101
+ filename: sanitizeFilename(input.name || getURLFilename(url)),
102
+ url: input.url,
103
+ } as FileData,
104
+ req,
105
+ uploadConfig: {
106
+ ...uploadConfig,
107
+ externalFileHeaderFilter: uploadConfig.externalFileHeaderFilter ?? (() => ({})),
108
+ },
109
+ })
110
+ file.mimetype = file.mimetype?.split(';')[0] || 'application/octet-stream'
111
+ file.size = file.data.length
112
+ }
113
+
114
+ if (maxFileSize !== undefined && Number.isFinite(maxFileSize) && file.size > maxFileSize) {
115
+ throw new APIError(`File exceeds the ${maxFileSize} byte upload limit.`, 400)
116
+ }
117
+
118
+ return file
119
+ }
120
+
121
+ function decodeBase64({ maxFileSize, value }: { maxFileSize?: number; value: string }): Buffer {
122
+ const normalized = value.replace(/\s/g, '')
123
+
124
+ if (!/^[a-z0-9+/]*={0,2}$/i.test(normalized) || normalized.length % 4 === 1) {
125
+ throw new APIError('File data must be valid base64.', 400)
126
+ }
127
+
128
+ if (maxFileSize !== undefined && Number.isFinite(maxFileSize)) {
129
+ const paddingLength = normalized.endsWith('==') ? 2 : normalized.endsWith('=') ? 1 : 0
130
+ const decodedSize = Math.floor((normalized.length * 3) / 4) - paddingLength
131
+
132
+ if (decodedSize > maxFileSize) {
133
+ throw new APIError(`File exceeds the ${maxFileSize} byte upload limit.`, 400)
134
+ }
135
+ }
136
+
137
+ const data = Buffer.from(normalized, 'base64')
138
+
139
+ if (data.toString('base64').replace(/=+$/, '') !== normalized.replace(/=+$/, '')) {
140
+ throw new APIError('File data must be valid base64.', 400)
141
+ }
142
+
143
+ return data
144
+ }
145
+
146
+ function getURLFilename(url: URL): string {
147
+ const pathSegment = url.pathname.split('/').pop() || 'upload'
148
+
149
+ try {
150
+ return decodeURIComponent(pathSegment)
151
+ } catch {
152
+ return pathSegment
153
+ }
154
+ }
@@ -39,7 +39,7 @@ export const findDocumentsTool = defineCollectionTool({
39
39
  draft: z
40
40
  .boolean()
41
41
  .describe(
42
- 'Optional: whether the document should be queried from the versions table/collection or not.',
42
+ 'For versioned collections, true returns the latest draft version when available. False reads the main document.',
43
43
  )
44
44
  .optional(),
45
45
  fallbackLocale: z
@@ -48,16 +48,33 @@ export const getCollectionSchemaTool = defineCollectionTool({
48
48
  }
49
49
  }
50
50
 
51
+ const uploadConfig = req.payload.collections[collectionSlug]?.config.upload
52
+ const maxFileSize = req.payload.config.upload.limits?.fileSize
53
+ const upload = uploadConfig
54
+ ? {
55
+ enabled: true,
56
+ filesRequiredOnCreate: uploadConfig.filesRequiredOnCreate !== false,
57
+ mimeTypes: uploadConfig.mimeTypes ?? ['*/*'],
58
+ sources: [
59
+ ...(uploadConfig.pasteURL !== false ? ['externalURL'] : []),
60
+ 'base64',
61
+ 'uploadReference',
62
+ ],
63
+ ...(typeof maxFileSize === 'number' && Number.isFinite(maxFileSize) ? { maxFileSize } : {}),
64
+ }
65
+ : { enabled: false }
66
+
51
67
  return {
52
68
  content: [
53
69
  {
54
70
  type: 'text',
55
- text: `Schema for collection "${collectionSlug}":\n\`\`\`json\n${JSON.stringify(inputSchema)}\n\`\`\``,
71
+ text: `Schema for collection "${collectionSlug}":\n\`\`\`json\n${JSON.stringify(inputSchema)}\n\`\`\`\nUpload configuration:\n\`\`\`json\n${JSON.stringify(upload)}\n\`\`\``,
56
72
  },
57
73
  ],
58
74
  structuredContent: {
59
75
  collectionSlug,
60
76
  schema: inputSchema,
77
+ upload,
61
78
  },
62
79
  }
63
80
  })
@@ -13,10 +13,11 @@ import { getCollectionInputSchema } from '../../../utils/schemaConversion/getEnt
13
13
  import { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'
14
14
  import { whereSchema } from '../../../utils/whereSchema.js'
15
15
  import { validateCollectionData } from '../validateEntityData.js'
16
+ import { fileInputSchema, resolveFile } from './fileInput.js'
16
17
  import { formatCollectionError } from './formatCollectionError.js'
17
18
 
18
19
  const DEFAULT_DESCRIPTION =
19
- 'Update documents in any collection by passing the collection slug and data.'
20
+ 'Update documents in any collection. Files can use a URL, base64, or an upload prepared by getUploadInstructions.'
20
21
 
21
22
  export const updateDocumentTool = defineCollectionTool({
22
23
  access: (args) =>
@@ -31,7 +32,11 @@ export const updateDocumentTool = defineCollectionTool({
31
32
  description: DEFAULT_DESCRIPTION,
32
33
  input: z.object({
33
34
  id: z.union([z.string(), z.number()]).describe('The ID of the document to update').optional(),
34
- data: z.record(z.string(), z.unknown()).describe('The fields to update'),
35
+ data: z
36
+ .record(z.string(), z.unknown())
37
+ .describe(
38
+ 'The fields to update. Only include fields permitted by the schema returned by getCollectionSchema.',
39
+ ),
35
40
  depth: z
36
41
  .number()
37
42
  .describe('How many levels deep to populate relationships')
@@ -39,14 +44,16 @@ export const updateDocumentTool = defineCollectionTool({
39
44
  .default(0),
40
45
  draft: z
41
46
  .boolean()
42
- .describe('Whether to update the document as a draft')
47
+ .describe(
48
+ 'Only if getCollectionSchema includes _status; otherwise _status does not exist. true saves only a draft version; false updates main and versions. data._status: "published" overrides true.',
49
+ )
43
50
  .optional()
44
51
  .default(false),
45
52
  fallbackLocale: z
46
53
  .string()
47
54
  .describe('Optional: fallback locale code to use when requested locale is not available')
48
55
  .optional(),
49
- filePath: z.string().describe('File path for file uploads').optional(),
56
+ file: fileInputSchema.optional(),
50
57
  locale: z
51
58
  .string()
52
59
  .describe(
@@ -63,6 +70,12 @@ export const updateDocumentTool = defineCollectionTool({
63
70
  .describe('Whether to overwrite existing files')
64
71
  .optional()
65
72
  .default(false),
73
+ publishAllLocales: z
74
+ .boolean()
75
+ .describe(
76
+ 'For collections with localized publishing status, whether publishing should affect every locale. Set false with locale to publish only that locale.',
77
+ )
78
+ .optional(),
66
79
  select: z
67
80
  .record(z.string(), z.unknown())
68
81
  .describe(
@@ -85,10 +98,11 @@ export const updateDocumentTool = defineCollectionTool({
85
98
  depth,
86
99
  draft,
87
100
  fallbackLocale,
88
- filePath,
101
+ file: fileInput,
89
102
  locale,
90
103
  overrideLock,
91
104
  overwriteExistingFiles,
105
+ publishAllLocales,
92
106
  select,
93
107
  where,
94
108
  } = input
@@ -118,6 +132,7 @@ export const updateDocumentTool = defineCollectionTool({
118
132
  }
119
133
 
120
134
  const parsedData = transformPointDataToPayload(inputData)
135
+ const file = await resolveFile({ collectionSlug, input: fileInput, req })
121
136
 
122
137
  const whereClause: Where = where ?? {}
123
138
 
@@ -131,8 +146,9 @@ export const updateDocumentTool = defineCollectionTool({
131
146
  overrideAccess: authorizedMCP.overrideAccess,
132
147
  overrideLock,
133
148
  req,
134
- ...(filePath ? { filePath } : {}),
149
+ ...(file ? { file } : {}),
135
150
  ...(overwriteExistingFiles ? { overwriteExistingFiles } : {}),
151
+ ...(publishAllLocales !== undefined ? { publishAllLocales } : {}),
136
152
  ...(locale ? { locale } : {}),
137
153
  ...(fallbackLocale ? { fallbackLocale } : {}),
138
154
  ...(select ? { select: select as SelectType } : {}),
@@ -158,8 +174,9 @@ export const updateDocumentTool = defineCollectionTool({
158
174
  overrideLock,
159
175
  req,
160
176
  where: whereClause,
161
- ...(filePath ? { filePath } : {}),
177
+ ...(file ? { file } : {}),
162
178
  ...(overwriteExistingFiles ? { overwriteExistingFiles } : {}),
179
+ ...(publishAllLocales !== undefined ? { publishAllLocales } : {}),
163
180
  ...(locale ? { locale } : {}),
164
181
  ...(fallbackLocale ? { fallbackLocale } : {}),
165
182
  ...(select ? { select: select as SelectType } : {}),
@@ -0,0 +1,64 @@
1
+ import { getUploadInstructions as getPayloadUploadInstructions } from 'payload/internal'
2
+ import { z } from 'zod'
3
+
4
+ import { defaultAccess } from '../../../defaultAccess.js'
5
+ import { defineCollectionTool } from '../../../defineTool.js'
6
+
7
+ export const getUploadInstructionsTool = defineCollectionTool({
8
+ access: (args) =>
9
+ defaultAccess(args) &&
10
+ Boolean(
11
+ args.permissions?.collections?.[args.collectionSlug]?.create ||
12
+ args.permissions?.collections?.[args.collectionSlug]?.update,
13
+ ),
14
+ annotations: {
15
+ destructiveHint: false,
16
+ idempotentHint: false,
17
+ openWorldHint: true,
18
+ readOnlyHint: false,
19
+ title: 'Get Upload Instructions',
20
+ },
21
+ description:
22
+ 'Prepare a file upload before createDocument or updateDocument. Pass file metadata only, without base64 or file contents.',
23
+ input: z.object({
24
+ docPrefix: z.string().describe('Optional document folder or prefix').optional(),
25
+ filename: z.string().describe('The original file name'),
26
+ filesize: z.number().int().nonnegative().describe('The file size in bytes'),
27
+ mimeType: z.string().describe('The file MIME type'),
28
+ }),
29
+ }).handler(async ({ authorizedMCP, collectionSlug, input, req }) => {
30
+ try {
31
+ const instructions = await getPayloadUploadInstructions({
32
+ ...input,
33
+ collectionSlug,
34
+ overrideAccess: authorizedMCP.overrideAccess,
35
+ req,
36
+ })
37
+
38
+ const nextStep =
39
+ instructions.type === 'http'
40
+ ? 'Send the exact file bytes using request, then pass { source: "uploadReference", file } to createDocument or updateDocument.'
41
+ : `Call the local MCP tool named "${instructions.name}" with the file and data, then pass { source: "uploadReference", file } to createDocument or updateDocument.`
42
+
43
+ return {
44
+ content: [
45
+ {
46
+ type: 'text',
47
+ text: `Upload instructions for collection "${collectionSlug}":\n\`\`\`json\n${JSON.stringify(instructions)}\n\`\`\`\n${nextStep}`,
48
+ },
49
+ ],
50
+ structuredContent: { instructions },
51
+ }
52
+ } catch (error) {
53
+ const message = error instanceof Error ? error.message : 'Unknown error'
54
+ return {
55
+ content: [
56
+ {
57
+ type: 'text',
58
+ text: `Error getting upload instructions for collection "${collectionSlug}": ${message}`,
59
+ },
60
+ ],
61
+ isError: true,
62
+ }
63
+ }
64
+ })
@@ -20,6 +20,7 @@ import { findVersionsTool } from './builtin/collections/findVersionsTool.js'
20
20
  import { getCollectionSchemaTool } from './builtin/collections/getCollectionSchemaTool.js'
21
21
  import { restoreVersionTool } from './builtin/collections/restoreVersionTool.js'
22
22
  import { updateDocumentTool } from './builtin/collections/updateTool.js'
23
+ import { getUploadInstructionsTool } from './builtin/collections/uploadInstructionsTool.js'
23
24
  import { getConfigInfoTool } from './builtin/getConfigInfoTool.js'
24
25
  import { countGlobalVersionsTool } from './builtin/globals/countVersionsTool.js'
25
26
  import { findGlobalTool } from './builtin/globals/findTool.js'
@@ -32,6 +33,7 @@ import { updateGlobalTool } from './builtin/globals/updateTool.js'
32
33
  type CollectionBuiltin = {
33
34
  mcpName: string
34
35
  requiresDuplicateEnabled?: boolean
36
+ requiresUpload?: boolean
35
37
  requiresVersions?: boolean
36
38
  tool: CollectionTool
37
39
  }
@@ -70,6 +72,11 @@ export const COLLECTION_BUILTINS = {
70
72
  },
71
73
  findVersions: { mcpName: 'findVersions', requiresVersions: true, tool: findVersionsTool },
72
74
  getCollectionSchema: { mcpName: 'getCollectionSchema', tool: getCollectionSchemaTool },
75
+ getUploadInstructions: {
76
+ mcpName: 'getUploadInstructions',
77
+ requiresUpload: true,
78
+ tool: getUploadInstructionsTool,
79
+ },
73
80
  restoreVersion: { mcpName: 'restoreVersion', requiresVersions: true, tool: restoreVersionTool },
74
81
  update: { mcpName: 'updateDocument', tool: updateDocumentTool },
75
82
  } satisfies Record<string, CollectionBuiltin>
@@ -127,7 +127,7 @@ const sanitizeCollectionConfig = ({
127
127
 
128
128
  for (const [
129
129
  toolKey,
130
- { mcpName, requiresDuplicateEnabled, requiresVersions, tool },
130
+ { mcpName, requiresDuplicateEnabled, requiresUpload, requiresVersions, tool },
131
131
  ] of COLLECTION_BUILTIN_ENTRIES) {
132
132
  if (requiresVersions && !collection.versions) {
133
133
  continue
@@ -135,6 +135,9 @@ const sanitizeCollectionConfig = ({
135
135
  if (requiresDuplicateEnabled && isDuplicateDisabled) {
136
136
  continue
137
137
  }
138
+ if (requiresUpload && !collection.upload) {
139
+ continue
140
+ }
138
141
  const matchedConfigEntry = collectionPluginConfig?.tools?.[toolKey]
139
142
  if (matchedConfigEntry === false) {
140
143
  continue
@@ -76,8 +76,8 @@ describe('sanitizeEntitySchema', () => {
76
76
  },
77
77
  },
78
78
  properties: {
79
- // Managed fields (createdAt/updatedAt/_status) are excluded upstream by the `input` variant;
80
- // `id` stays because it's a valid optional input (a client may supply a custom ID).
79
+ // Managed timestamps are excluded upstream by the `input` variant. `id` stays because it's
80
+ // a valid optional input (a client may supply a custom ID).
81
81
  id: { type: 'string' },
82
82
  content: {
83
83
  type: 'object',