@payloadcms/plugin-mcp 4.0.0-internal.811e0a4 → 4.0.0-internal.8867dba

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 (142) hide show
  1. package/bin.js +7 -0
  2. package/dist/defaultAccess.d.ts.map +1 -1
  3. package/dist/defineTool.d.ts +8 -8
  4. package/dist/defineTool.d.ts.map +1 -1
  5. package/dist/endpoint/access.d.ts +2 -7
  6. package/dist/endpoint/access.d.ts.map +1 -1
  7. package/dist/endpoint/access.js +4 -11
  8. package/dist/endpoint/access.js.map +1 -1
  9. package/dist/mcp/buildMcpServer.d.ts.map +1 -1
  10. package/dist/mcp/builtin/collections/countTool.d.ts.map +1 -1
  11. package/dist/mcp/builtin/collections/countTool.js +1 -2
  12. package/dist/mcp/builtin/collections/countTool.js.map +1 -1
  13. package/dist/mcp/builtin/collections/countVersionsTool.d.ts.map +1 -1
  14. package/dist/mcp/builtin/collections/countVersionsTool.js +1 -2
  15. package/dist/mcp/builtin/collections/countVersionsTool.js.map +1 -1
  16. package/dist/mcp/builtin/collections/createTool.d.ts.map +1 -1
  17. package/dist/mcp/builtin/collections/createTool.js +15 -6
  18. package/dist/mcp/builtin/collections/createTool.js.map +1 -1
  19. package/dist/mcp/builtin/collections/deleteTool.d.ts.map +1 -1
  20. package/dist/mcp/builtin/collections/deleteTool.js +1 -2
  21. package/dist/mcp/builtin/collections/deleteTool.js.map +1 -1
  22. package/dist/mcp/builtin/collections/duplicateTool.d.ts.map +1 -1
  23. package/dist/mcp/builtin/collections/duplicateTool.js +1 -2
  24. package/dist/mcp/builtin/collections/duplicateTool.js.map +1 -1
  25. package/dist/mcp/builtin/collections/fileInput.d.ts +28 -0
  26. package/dist/mcp/builtin/collections/fileInput.d.ts.map +1 -0
  27. package/dist/mcp/builtin/collections/fileInput.js +117 -0
  28. package/dist/mcp/builtin/collections/fileInput.js.map +1 -0
  29. package/dist/mcp/builtin/collections/fileInput.spec.js +86 -0
  30. package/dist/mcp/builtin/collections/fileInput.spec.js.map +1 -0
  31. package/dist/mcp/builtin/collections/findDistinctTool.d.ts.map +1 -1
  32. package/dist/mcp/builtin/collections/findDistinctTool.js +1 -2
  33. package/dist/mcp/builtin/collections/findDistinctTool.js.map +1 -1
  34. package/dist/mcp/builtin/collections/findTool.d.ts.map +1 -1
  35. package/dist/mcp/builtin/collections/findTool.js +3 -4
  36. package/dist/mcp/builtin/collections/findTool.js.map +1 -1
  37. package/dist/mcp/builtin/collections/findVersionByIDTool.d.ts.map +1 -1
  38. package/dist/mcp/builtin/collections/findVersionByIDTool.js +1 -2
  39. package/dist/mcp/builtin/collections/findVersionByIDTool.js.map +1 -1
  40. package/dist/mcp/builtin/collections/findVersionsTool.d.ts.map +1 -1
  41. package/dist/mcp/builtin/collections/findVersionsTool.js +1 -2
  42. package/dist/mcp/builtin/collections/findVersionsTool.js.map +1 -1
  43. package/dist/mcp/builtin/collections/formatCollectionError.d.ts +1 -1
  44. package/dist/mcp/builtin/collections/formatCollectionError.d.ts.map +1 -1
  45. package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -1
  46. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +45 -5
  47. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -1
  48. package/dist/mcp/builtin/collections/restoreVersionTool.d.ts.map +1 -1
  49. package/dist/mcp/builtin/collections/restoreVersionTool.js +1 -2
  50. package/dist/mcp/builtin/collections/restoreVersionTool.js.map +1 -1
  51. package/dist/mcp/builtin/collections/updateTool.d.ts.map +1 -1
  52. package/dist/mcp/builtin/collections/updateTool.js +24 -12
  53. package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
  54. package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts +2 -0
  55. package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts.map +1 -0
  56. package/dist/mcp/builtin/collections/uploadInstructionsTool.js +55 -0
  57. package/dist/mcp/builtin/collections/uploadInstructionsTool.js.map +1 -0
  58. package/dist/mcp/builtin/getConfigInfoTool.d.ts.map +1 -1
  59. package/dist/mcp/builtin/getConfigInfoTool.js +2 -5
  60. package/dist/mcp/builtin/getConfigInfoTool.js.map +1 -1
  61. package/dist/mcp/builtin/globals/countVersionsTool.d.ts.map +1 -1
  62. package/dist/mcp/builtin/globals/countVersionsTool.js +1 -2
  63. package/dist/mcp/builtin/globals/countVersionsTool.js.map +1 -1
  64. package/dist/mcp/builtin/globals/findTool.d.ts.map +1 -1
  65. package/dist/mcp/builtin/globals/findTool.js +2 -2
  66. package/dist/mcp/builtin/globals/findTool.js.map +1 -1
  67. package/dist/mcp/builtin/globals/findVersionByIDTool.d.ts.map +1 -1
  68. package/dist/mcp/builtin/globals/findVersionByIDTool.js +1 -2
  69. package/dist/mcp/builtin/globals/findVersionByIDTool.js.map +1 -1
  70. package/dist/mcp/builtin/globals/findVersionsTool.d.ts.map +1 -1
  71. package/dist/mcp/builtin/globals/findVersionsTool.js +1 -2
  72. package/dist/mcp/builtin/globals/findVersionsTool.js.map +1 -1
  73. package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts.map +1 -1
  74. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js +21 -3
  75. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js.map +1 -1
  76. package/dist/mcp/builtin/globals/restoreVersionTool.js +1 -2
  77. package/dist/mcp/builtin/globals/restoreVersionTool.js.map +1 -1
  78. package/dist/mcp/builtin/globals/updateTool.d.ts.map +1 -1
  79. package/dist/mcp/builtin/globals/updateTool.js +2 -2
  80. package/dist/mcp/builtin/globals/updateTool.js.map +1 -1
  81. package/dist/mcp/builtin/validateEntityData.d.ts.map +1 -1
  82. package/dist/mcp/builtinTools.d.ts +6 -0
  83. package/dist/mcp/builtinTools.d.ts.map +1 -1
  84. package/dist/mcp/builtinTools.js +6 -0
  85. package/dist/mcp/builtinTools.js.map +1 -1
  86. package/dist/mcp/sanitizeMCPConfig.d.ts.map +1 -1
  87. package/dist/mcp/sanitizeMCPConfig.js +4 -1
  88. package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
  89. package/dist/types.d.ts +44 -7
  90. package/dist/types.d.ts.map +1 -1
  91. package/dist/types.js +2 -4
  92. package/dist/types.js.map +1 -1
  93. package/dist/utils/camelCase.d.ts.map +1 -1
  94. package/dist/utils/resolveProjectRoot.d.ts.map +1 -1
  95. package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts +28 -0
  96. package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts.map +1 -0
  97. package/dist/utils/schemaConversion/filterFieldsByAccess.js +71 -0
  98. package/dist/utils/schemaConversion/filterFieldsByAccess.js.map +1 -0
  99. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts +5 -3
  100. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts.map +1 -1
  101. package/dist/utils/schemaConversion/getEntityInputSchema.js +40 -6
  102. package/dist/utils/schemaConversion/getEntityInputSchema.js.map +1 -1
  103. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts.map +1 -1
  104. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js +2 -2
  105. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js.map +1 -1
  106. package/dist/utils/toStandardSchema.d.ts.map +1 -1
  107. package/package.json +4 -4
  108. package/src/endpoint/access.ts +3 -10
  109. package/src/mcp/builtin/collections/countTool.ts +1 -2
  110. package/src/mcp/builtin/collections/countVersionsTool.ts +2 -6
  111. package/src/mcp/builtin/collections/createTool.ts +15 -6
  112. package/src/mcp/builtin/collections/deleteTool.ts +1 -2
  113. package/src/mcp/builtin/collections/duplicateTool.ts +1 -2
  114. package/src/mcp/builtin/collections/fileInput.spec.ts +93 -0
  115. package/src/mcp/builtin/collections/fileInput.ts +154 -0
  116. package/src/mcp/builtin/collections/findDistinctTool.ts +3 -3
  117. package/src/mcp/builtin/collections/findTool.ts +3 -4
  118. package/src/mcp/builtin/collections/findVersionByIDTool.ts +1 -2
  119. package/src/mcp/builtin/collections/findVersionsTool.ts +1 -2
  120. package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +43 -9
  121. package/src/mcp/builtin/collections/restoreVersionTool.ts +1 -2
  122. package/src/mcp/builtin/collections/updateTool.ts +26 -10
  123. package/src/mcp/builtin/collections/uploadInstructionsTool.ts +64 -0
  124. package/src/mcp/builtin/getConfigInfoTool.ts +2 -4
  125. package/src/mcp/builtin/globals/countVersionsTool.ts +2 -6
  126. package/src/mcp/builtin/globals/findTool.ts +2 -2
  127. package/src/mcp/builtin/globals/findVersionByIDTool.ts +1 -2
  128. package/src/mcp/builtin/globals/findVersionsTool.ts +1 -2
  129. package/src/mcp/builtin/globals/getGlobalSchemaTool.ts +25 -3
  130. package/src/mcp/builtin/globals/restoreVersionTool.ts +3 -3
  131. package/src/mcp/builtin/globals/updateTool.ts +2 -2
  132. package/src/mcp/builtinTools.ts +7 -0
  133. package/src/mcp/sanitizeMCPConfig.ts +4 -1
  134. package/src/types.ts +43 -7
  135. package/src/utils/schemaConversion/filterFieldsByAccess.ts +123 -0
  136. package/src/utils/schemaConversion/getEntityInputSchema.ts +47 -13
  137. package/src/utils/schemaConversion/sanitizeEntitySchema.spec.ts +2 -2
  138. package/dist/utils/localAPIDefaults.d.ts +0 -20
  139. package/dist/utils/localAPIDefaults.d.ts.map +0 -1
  140. package/dist/utils/localAPIDefaults.js +0 -19
  141. package/dist/utils/localAPIDefaults.js.map +0 -1
  142. package/src/utils/localAPIDefaults.ts +0 -22
@@ -3,7 +3,6 @@ import { z } from 'zod'
3
3
  import { defaultAccess } from '../../../defaultAccess.js'
4
4
  import { defineCollectionTool } from '../../../defineTool.js'
5
5
  import { getLogger } from '../../../utils/getLogger.js'
6
- import { localAPIDefaults } from '../../../utils/localAPIDefaults.js'
7
6
  import { whereSchema } from '../../../utils/whereSchema.js'
8
7
 
9
8
  const DEFAULT_DESCRIPTION =
@@ -22,10 +21,7 @@ export const countVersionsTool = defineCollectionTool({
22
21
  },
23
22
  description: DEFAULT_DESCRIPTION,
24
23
  input: z.object({
25
- locale: z
26
- .string()
27
- .describe('Optional: locale code to count versions in')
28
- .optional(),
24
+ locale: z.string().describe('Optional: locale code to count versions in').optional(),
29
25
  where: whereSchema
30
26
  .describe(
31
27
  'Optional: where clause for filtering versions. Version document fields are usually under "version". Example: {"version.title":{"contains":"test"}}',
@@ -42,8 +38,8 @@ export const countVersionsTool = defineCollectionTool({
42
38
  try {
43
39
  const result = await payload.countVersions({
44
40
  collection: collectionSlug,
41
+ overrideAccess: authorizedMCP.overrideAccess,
45
42
  req,
46
- ...localAPIDefaults(authorizedMCP),
47
43
  ...(locale ? { locale } : {}),
48
44
  ...(where ? { where } : {}),
49
45
  })
@@ -9,13 +9,13 @@ import {
9
9
  getCollectionVirtualFieldNames,
10
10
  stripVirtualFields,
11
11
  } from '../../../utils/getVirtualFieldNames.js'
12
- import { localAPIDefaults } from '../../../utils/localAPIDefaults.js'
13
12
  import { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'
14
13
  import { validateCollectionData } from '../validateEntityData.js'
14
+ import { fileInputSchema, resolveFile } from './fileInput.js'
15
15
  import { formatCollectionError } from './formatCollectionError.js'
16
16
 
17
17
  const DEFAULT_DESCRIPTION =
18
- '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.'
19
19
 
20
20
  export const createDocumentTool = defineCollectionTool({
21
21
  access: (args) =>
@@ -29,7 +29,11 @@ export const createDocumentTool = defineCollectionTool({
29
29
  },
30
30
  description: DEFAULT_DESCRIPTION,
31
31
  input: z.object({
32
- 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
+ ),
33
37
  depth: z
34
38
  .number()
35
39
  .int()
@@ -40,13 +44,16 @@ export const createDocumentTool = defineCollectionTool({
40
44
  .default(0),
41
45
  draft: z
42
46
  .boolean()
43
- .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
+ )
44
50
  .optional()
45
51
  .default(false),
46
52
  fallbackLocale: z
47
53
  .string()
48
54
  .describe('Optional: fallback locale code to use when requested locale is not available')
49
55
  .optional(),
56
+ file: fileInputSchema.optional(),
50
57
  locale: z
51
58
  .string()
52
59
  .describe(
@@ -64,7 +71,7 @@ export const createDocumentTool = defineCollectionTool({
64
71
  const payload = req.payload
65
72
  const logger = getLogger({ payload })
66
73
 
67
- const { data, depth, draft, fallbackLocale, locale, select } = input
74
+ const { data, depth, draft, fallbackLocale, file: fileInput, locale, select } = input
68
75
 
69
76
  logger.info(
70
77
  `Creating document in collection: ${collectionSlug}${locale ? ` with locale: ${locale}` : ''}`,
@@ -80,14 +87,16 @@ export const createDocumentTool = defineCollectionTool({
80
87
  }
81
88
 
82
89
  const parsedData = transformPointDataToPayload(inputData)
90
+ const file = await resolveFile({ collectionSlug, input: fileInput, req })
83
91
 
84
92
  const result = await payload.create({
85
93
  collection: collectionSlug,
86
94
  data: parsedData,
87
95
  depth,
88
96
  draft,
97
+ overrideAccess: authorizedMCP.overrideAccess,
89
98
  req,
90
- ...localAPIDefaults(authorizedMCP),
99
+ ...(file ? { file } : {}),
91
100
  ...(locale ? { locale } : {}),
92
101
  ...(fallbackLocale ? { fallbackLocale } : {}),
93
102
  ...(select ? { select: select as SelectType } : {}),
@@ -3,7 +3,6 @@ import { z } from 'zod'
3
3
  import { defaultAccess } from '../../../defaultAccess.js'
4
4
  import { defineCollectionTool } from '../../../defineTool.js'
5
5
  import { getLogger } from '../../../utils/getLogger.js'
6
- import { localAPIDefaults } from '../../../utils/localAPIDefaults.js'
7
6
  import { whereSchema } from '../../../utils/whereSchema.js'
8
7
 
9
8
  const DEFAULT_DESCRIPTION =
@@ -69,8 +68,8 @@ export const deleteDocumentsTool = defineCollectionTool({
69
68
  const deleteOptions: Record<string, unknown> = {
70
69
  collection: collectionSlug,
71
70
  depth,
71
+ overrideAccess: authorizedMCP.overrideAccess,
72
72
  req,
73
- ...localAPIDefaults(authorizedMCP),
74
73
  ...(locale && { locale }),
75
74
  ...(fallbackLocale && { fallbackLocale }),
76
75
  }
@@ -9,7 +9,6 @@ import {
9
9
  getCollectionVirtualFieldNames,
10
10
  stripVirtualFields,
11
11
  } from '../../../utils/getVirtualFieldNames.js'
12
- import { localAPIDefaults } from '../../../utils/localAPIDefaults.js'
13
12
  import { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'
14
13
  import { formatCollectionError } from './formatCollectionError.js'
15
14
 
@@ -105,8 +104,8 @@ export const duplicateDocumentTool = defineCollectionTool({
105
104
  collection: collectionSlug,
106
105
  depth,
107
106
  draft,
107
+ overrideAccess: authorizedMCP.overrideAccess,
108
108
  req,
109
- ...localAPIDefaults(authorizedMCP),
110
109
  ...(parsedData ? { data: parsedData } : {}),
111
110
  ...(locale ? { locale } : {}),
112
111
  ...(fallbackLocale ? { fallbackLocale } : {}),
@@ -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
+ }
@@ -5,7 +5,6 @@ import { z } from 'zod'
5
5
  import { defaultAccess } from '../../../defaultAccess.js'
6
6
  import { defineCollectionTool } from '../../../defineTool.js'
7
7
  import { getLogger } from '../../../utils/getLogger.js'
8
- import { localAPIDefaults } from '../../../utils/localAPIDefaults.js'
9
8
  import { whereSchema } from '../../../utils/whereSchema.js'
10
9
 
11
10
  const DEFAULT_DESCRIPTION =
@@ -73,7 +72,8 @@ export const findDistinctTool = defineCollectionTool({
73
72
  }).handler(async ({ authorizedMCP, collectionSlug, input, req }) => {
74
73
  const payload = req.payload
75
74
  const logger = getLogger({ payload })
76
- const { depth, field, limit, locale, page, populate, showHiddenFields, sort, trash, where } = input
75
+ const { depth, field, limit, locale, page, populate, showHiddenFields, sort, trash, where } =
76
+ input
77
77
 
78
78
  logger.info(`Finding distinct values in collection: ${collectionSlug}, field: ${field}`)
79
79
 
@@ -82,8 +82,8 @@ export const findDistinctTool = defineCollectionTool({
82
82
  collection: collectionSlug,
83
83
  depth,
84
84
  field,
85
+ overrideAccess: authorizedMCP.overrideAccess,
85
86
  req,
86
- ...localAPIDefaults(authorizedMCP),
87
87
  ...(limit ? { limit } : {}),
88
88
  ...(locale ? { locale } : {}),
89
89
  ...(page ? { page } : {}),
@@ -5,7 +5,6 @@ import { z } from 'zod'
5
5
  import { defaultAccess } from '../../../defaultAccess.js'
6
6
  import { defineCollectionTool } from '../../../defineTool.js'
7
7
  import { getLogger } from '../../../utils/getLogger.js'
8
- import { localAPIDefaults } from '../../../utils/localAPIDefaults.js'
9
8
  import { whereSchema } from '../../../utils/whereSchema.js'
10
9
 
11
10
  const DEFAULT_DESCRIPTION =
@@ -40,7 +39,7 @@ export const findDocumentsTool = defineCollectionTool({
40
39
  draft: z
41
40
  .boolean()
42
41
  .describe(
43
- '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.',
44
43
  )
45
44
  .optional(),
46
45
  fallbackLocale: z
@@ -134,8 +133,8 @@ export const findDocumentsTool = defineCollectionTool({
134
133
  id,
135
134
  collection: collectionSlug,
136
135
  depth,
136
+ overrideAccess: authorizedMCP.overrideAccess,
137
137
  req,
138
- ...localAPIDefaults(authorizedMCP),
139
138
  ...(select && { select: select as SelectType }),
140
139
  ...(populate && { populate: populate as PopulateType }),
141
140
  ...(joins !== undefined && { joins: joins as JoinQuery }),
@@ -171,9 +170,9 @@ export const findDocumentsTool = defineCollectionTool({
171
170
  collection: collectionSlug,
172
171
  depth,
173
172
  limit,
173
+ overrideAccess: authorizedMCP.overrideAccess,
174
174
  page,
175
175
  req,
176
- ...localAPIDefaults(authorizedMCP),
177
176
  ...(select && { select: select as SelectType }),
178
177
  ...(populate && { populate: populate as PopulateType }),
179
178
  ...(joins !== undefined && { joins: joins as JoinQuery }),
@@ -5,7 +5,6 @@ import { z } from 'zod'
5
5
  import { defaultAccess } from '../../../defaultAccess.js'
6
6
  import { defineCollectionTool } from '../../../defineTool.js'
7
7
  import { getLogger } from '../../../utils/getLogger.js'
8
- import { localAPIDefaults } from '../../../utils/localAPIDefaults.js'
9
8
 
10
9
  const DEFAULT_DESCRIPTION =
11
10
  'Find a specific document version in any version-enabled collection by passing the collection slug and version ID.'
@@ -75,8 +74,8 @@ export const findVersionByIDTool = defineCollectionTool({
75
74
  id,
76
75
  collection: collectionSlug,
77
76
  depth,
77
+ overrideAccess: authorizedMCP.overrideAccess,
78
78
  req,
79
- ...localAPIDefaults(authorizedMCP),
80
79
  ...(fallbackLocale ? { fallbackLocale } : {}),
81
80
  ...(locale ? { locale } : {}),
82
81
  ...(populate ? { populate: populate as PopulateType } : {}),
@@ -5,7 +5,6 @@ import { z } from 'zod'
5
5
  import { defaultAccess } from '../../../defaultAccess.js'
6
6
  import { defineCollectionTool } from '../../../defineTool.js'
7
7
  import { getLogger } from '../../../utils/getLogger.js'
8
- import { localAPIDefaults } from '../../../utils/localAPIDefaults.js'
9
8
  import { whereSchema } from '../../../utils/whereSchema.js'
10
9
 
11
10
  const DEFAULT_DESCRIPTION =
@@ -116,9 +115,9 @@ export const findVersionsTool = defineCollectionTool({
116
115
  collection: collectionSlug,
117
116
  depth,
118
117
  limit,
118
+ overrideAccess: authorizedMCP.overrideAccess,
119
119
  page,
120
120
  req,
121
- ...localAPIDefaults(authorizedMCP),
122
121
  ...(fallbackLocale ? { fallbackLocale } : {}),
123
122
  ...(locale ? { locale } : {}),
124
123
  ...(pagination !== undefined ? { pagination } : {}),
@@ -1,3 +1,5 @@
1
+ import { getAccessResults } from 'payload'
2
+
1
3
  import { defaultAccess } from '../../../defaultAccess.js'
2
4
  import { defineCollectionTool } from '../../../defineTool.js'
3
5
  import { getCollectionInputSchema } from '../../../utils/schemaConversion/getEntityInputSchema.js'
@@ -6,12 +8,7 @@ export const getCollectionSchemaTool = defineCollectionTool({
6
8
  access: (args) => {
7
9
  const permissions = args.permissions?.collections?.[args.collectionSlug]
8
10
 
9
- return (
10
- defaultAccess(args) &&
11
- Boolean(
12
- permissions?.create || permissions?.delete || permissions?.read || permissions?.update,
13
- )
14
- )
11
+ return defaultAccess(args) && Boolean(permissions?.create || permissions?.update)
15
12
  },
16
13
  annotations: {
17
14
  destructiveHint: false,
@@ -21,8 +18,28 @@ export const getCollectionSchemaTool = defineCollectionTool({
21
18
  title: 'Get Collection Schema',
22
19
  },
23
20
  description: 'Get the input schema for creating or updating documents in a collection.',
24
- }).handler(({ collectionSlug, req }) => {
25
- const inputSchema = getCollectionInputSchema({ collectionSlug, req })
21
+ }).handler(async ({ authorizedMCP, collectionSlug, req }) => {
22
+ const permissions = authorizedMCP.overrideAccess
23
+ ? null
24
+ : (await getAccessResults({ req })).collections?.[collectionSlug]
25
+
26
+ if (!authorizedMCP.overrideAccess && !permissions?.create && !permissions?.update) {
27
+ return {
28
+ content: [
29
+ {
30
+ type: 'text',
31
+ text: `Error: MCP access to "getCollectionSchema" is not enabled for collection "${collectionSlug}"`,
32
+ },
33
+ ],
34
+ isError: true,
35
+ }
36
+ }
37
+
38
+ const inputSchema = getCollectionInputSchema({
39
+ collectionSlug,
40
+ req,
41
+ ...(permissions ? { permissions } : {}),
42
+ })
26
43
 
27
44
  if (!inputSchema) {
28
45
  return {
@@ -31,16 +48,33 @@ export const getCollectionSchemaTool = defineCollectionTool({
31
48
  }
32
49
  }
33
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
+
34
67
  return {
35
68
  content: [
36
69
  {
37
70
  type: 'text',
38
- 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\`\`\``,
39
72
  },
40
73
  ],
41
74
  structuredContent: {
42
75
  collectionSlug,
43
76
  schema: inputSchema,
77
+ upload,
44
78
  },
45
79
  }
46
80
  })
@@ -5,7 +5,6 @@ import { z } from 'zod'
5
5
  import { defaultAccess } from '../../../defaultAccess.js'
6
6
  import { defineCollectionTool } from '../../../defineTool.js'
7
7
  import { getLogger } from '../../../utils/getLogger.js'
8
- import { localAPIDefaults } from '../../../utils/localAPIDefaults.js'
9
8
 
10
9
  const DEFAULT_DESCRIPTION =
11
10
  'Restore a document from a previous version in any version-enabled collection.'
@@ -74,8 +73,8 @@ export const restoreVersionTool = defineCollectionTool({
74
73
  collection: collectionSlug,
75
74
  depth,
76
75
  draft,
76
+ overrideAccess: authorizedMCP.overrideAccess,
77
77
  req,
78
- ...localAPIDefaults(authorizedMCP),
79
78
  ...(fallbackLocale ? { fallbackLocale } : {}),
80
79
  ...(locale ? { locale } : {}),
81
80
  ...(populate ? { populate: populate as PopulateType } : {}),