@payloadcms/plugin-mcp 4.0.0-internal.e387174 → 4.0.0-internal.e7d4ebc

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 (53) hide show
  1. package/dist/defaultAccess.d.ts.map +1 -1
  2. package/dist/defineTool.d.ts +8 -8
  3. package/dist/defineTool.d.ts.map +1 -1
  4. package/dist/endpoint/access.d.ts.map +1 -1
  5. package/dist/mcp/buildMcpServer.d.ts.map +1 -1
  6. package/dist/mcp/builtin/collections/createTool.d.ts.map +1 -1
  7. package/dist/mcp/builtin/collections/createTool.js +12 -2
  8. package/dist/mcp/builtin/collections/createTool.js.map +1 -1
  9. package/dist/mcp/builtin/collections/fileInput.d.ts +28 -0
  10. package/dist/mcp/builtin/collections/fileInput.d.ts.map +1 -0
  11. package/dist/mcp/builtin/collections/fileInput.js +117 -0
  12. package/dist/mcp/builtin/collections/fileInput.js.map +1 -0
  13. package/dist/mcp/builtin/collections/fileInput.spec.js +86 -0
  14. package/dist/mcp/builtin/collections/fileInput.spec.js.map +1 -0
  15. package/dist/mcp/builtin/collections/formatCollectionError.d.ts +1 -1
  16. package/dist/mcp/builtin/collections/formatCollectionError.d.ts.map +1 -1
  17. package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -1
  18. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +24 -2
  19. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -1
  20. package/dist/mcp/builtin/collections/updateTool.d.ts.map +1 -1
  21. package/dist/mcp/builtin/collections/updateTool.js +13 -7
  22. package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
  23. package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts +2 -0
  24. package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts.map +1 -0
  25. package/dist/mcp/builtin/collections/uploadInstructionsTool.js +55 -0
  26. package/dist/mcp/builtin/collections/uploadInstructionsTool.js.map +1 -0
  27. package/dist/mcp/builtin/validateEntityData.d.ts.map +1 -1
  28. package/dist/mcp/builtinTools.d.ts +6 -0
  29. package/dist/mcp/builtinTools.d.ts.map +1 -1
  30. package/dist/mcp/builtinTools.js +6 -0
  31. package/dist/mcp/builtinTools.js.map +1 -1
  32. package/dist/mcp/sanitizeMCPConfig.d.ts.map +1 -1
  33. package/dist/mcp/sanitizeMCPConfig.js +4 -1
  34. package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
  35. package/dist/stdio.d.ts.map +1 -1
  36. package/dist/stdio.js +2 -1
  37. package/dist/stdio.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/toStandardSchema.d.ts.map +1 -1
  44. package/package.json +3 -3
  45. package/src/mcp/builtin/collections/createTool.ts +6 -2
  46. package/src/mcp/builtin/collections/fileInput.spec.ts +93 -0
  47. package/src/mcp/builtin/collections/fileInput.ts +154 -0
  48. package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +18 -1
  49. package/src/mcp/builtin/collections/updateTool.ts +7 -5
  50. package/src/mcp/builtin/collections/uploadInstructionsTool.ts +64 -0
  51. package/src/mcp/builtinTools.ts +7 -0
  52. package/src/mcp/sanitizeMCPConfig.ts +4 -1
  53. package/src/stdio.ts +2 -1
@@ -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
+ }
@@ -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) =>
@@ -52,7 +53,7 @@ export const updateDocumentTool = defineCollectionTool({
52
53
  .string()
53
54
  .describe('Optional: fallback locale code to use when requested locale is not available')
54
55
  .optional(),
55
- filePath: z.string().describe('File path for file uploads').optional(),
56
+ file: fileInputSchema.optional(),
56
57
  locale: z
57
58
  .string()
58
59
  .describe(
@@ -97,7 +98,7 @@ export const updateDocumentTool = defineCollectionTool({
97
98
  depth,
98
99
  draft,
99
100
  fallbackLocale,
100
- filePath,
101
+ file: fileInput,
101
102
  locale,
102
103
  overrideLock,
103
104
  overwriteExistingFiles,
@@ -131,6 +132,7 @@ export const updateDocumentTool = defineCollectionTool({
131
132
  }
132
133
 
133
134
  const parsedData = transformPointDataToPayload(inputData)
135
+ const file = await resolveFile({ collectionSlug, input: fileInput, req })
134
136
 
135
137
  const whereClause: Where = where ?? {}
136
138
 
@@ -144,7 +146,7 @@ export const updateDocumentTool = defineCollectionTool({
144
146
  overrideAccess: authorizedMCP.overrideAccess,
145
147
  overrideLock,
146
148
  req,
147
- ...(filePath ? { filePath } : {}),
149
+ ...(file ? { file } : {}),
148
150
  ...(overwriteExistingFiles ? { overwriteExistingFiles } : {}),
149
151
  ...(publishAllLocales !== undefined ? { publishAllLocales } : {}),
150
152
  ...(locale ? { locale } : {}),
@@ -172,7 +174,7 @@ export const updateDocumentTool = defineCollectionTool({
172
174
  overrideLock,
173
175
  req,
174
176
  where: whereClause,
175
- ...(filePath ? { filePath } : {}),
177
+ ...(file ? { file } : {}),
176
178
  ...(overwriteExistingFiles ? { overwriteExistingFiles } : {}),
177
179
  ...(publishAllLocales !== undefined ? { publishAllLocales } : {}),
178
180
  ...(locale ? { locale } : {}),
@@ -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
package/src/stdio.ts CHANGED
@@ -4,7 +4,7 @@ import type { Config, Plugin, SanitizedConfig } from 'payload'
4
4
  import { serveStdio } from '@modelcontextprotocol/server/stdio'
5
5
  import { fileURLToPath, pathToFileURL } from 'node:url'
6
6
  import { createLocalReq, getPayload } from 'payload'
7
- import { findConfig } from 'payload/node'
7
+ import { findConfig, loadEnv } from 'payload/node'
8
8
 
9
9
  import type { SanitizedMCPPluginConfig } from './types.js'
10
10
 
@@ -28,6 +28,7 @@ export const runMcpStdio = async (): Promise<void> => {
28
28
  process.chdir(projectRoot)
29
29
  }
30
30
 
31
+ loadEnv()
31
32
  const configPath = findConfig()
32
33
  const configModule = await import(pathToFileURL(configPath).toString())
33
34
  const config = (await (configModule.default ?? configModule)) as SanitizedConfig