@payloadcms/plugin-mcp 4.0.0-internal.656159a → 4.0.0-internal.697830c

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 (44) hide show
  1. package/bin.js +0 -7
  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 +3 -13
  9. package/dist/mcp/builtin/collections/createTool.js.map +1 -1
  10. package/dist/mcp/builtin/collections/findTool.js +1 -1
  11. package/dist/mcp/builtin/collections/findTool.js.map +1 -1
  12. package/dist/mcp/builtin/collections/formatCollectionError.d.ts +1 -1
  13. package/dist/mcp/builtin/collections/formatCollectionError.d.ts.map +1 -1
  14. package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -1
  15. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +2 -23
  16. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -1
  17. package/dist/mcp/builtin/collections/updateTool.d.ts.map +1 -1
  18. package/dist/mcp/builtin/collections/updateTool.js +8 -21
  19. package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
  20. package/dist/mcp/builtin/validateEntityData.d.ts.map +1 -1
  21. package/dist/mcp/builtinTools.d.ts.map +1 -1
  22. package/dist/mcp/sanitizeMCPConfig.d.ts.map +1 -1
  23. package/dist/utils/camelCase.d.ts.map +1 -1
  24. package/dist/utils/resolveProjectRoot.d.ts.map +1 -1
  25. package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts.map +1 -1
  26. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts.map +1 -1
  27. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts.map +1 -1
  28. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js +2 -2
  29. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js.map +1 -1
  30. package/dist/utils/toStandardSchema.d.ts.map +1 -1
  31. package/package.json +4 -4
  32. package/src/mcp/builtin/collections/createTool.ts +3 -13
  33. package/src/mcp/builtin/collections/findTool.ts +1 -1
  34. package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +1 -14
  35. package/src/mcp/builtin/collections/updateTool.ts +6 -23
  36. package/src/utils/schemaConversion/sanitizeEntitySchema.spec.ts +2 -2
  37. package/dist/mcp/builtin/collections/fileInput.d.ts +0 -20
  38. package/dist/mcp/builtin/collections/fileInput.d.ts.map +0 -1
  39. package/dist/mcp/builtin/collections/fileInput.js +0 -100
  40. package/dist/mcp/builtin/collections/fileInput.js.map +0 -1
  41. package/dist/mcp/builtin/collections/fileInput.spec.js +0 -72
  42. package/dist/mcp/builtin/collections/fileInput.spec.js.map +0 -1
  43. package/src/mcp/builtin/collections/fileInput.spec.ts +0 -79
  44. package/src/mcp/builtin/collections/fileInput.ts +0 -139
@@ -1 +1 @@
1
- {"version":3,"file":"toStandardSchema.d.ts","sourceRoot":"","sources":["../../src/utils/toStandardSchema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,KAAK,sBAAsB,EAAE,MAAM,8BAA8B,CAAA;AAE1F,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAElD,gIAAgI;AAChI,eAAO,MAAM,gBAAgB,WAAY,eAAe,KAAG,sBAG/B,CAAA"}
1
+ {"version":3,"file":"toStandardSchema.d.ts","sourceRoot":"","sources":["../../src/utils/toStandardSchema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,KAAK,sBAAsB,EAAE,MAAM,8BAA8B,CAAA;AAE1F,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAElD,gIAAgI;AAChI,eAAO,MAAM,gBAAgB,GAAI,QAAQ,eAAe,KAAG,sBAG/B,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@payloadcms/plugin-mcp",
3
- "version": "4.0.0-internal.656159a",
3
+ "version": "4.0.0-internal.697830c",
4
4
  "description": "MCP (Model Context Protocol) capabilities with Payload",
5
5
  "keywords": [
6
6
  "plugin",
@@ -55,16 +55,16 @@
55
55
  "bin.js"
56
56
  ],
57
57
  "dependencies": {
58
- "@modelcontextprotocol/server": "2.0.0-beta.3",
58
+ "@modelcontextprotocol/server": "2.0.0-beta.2",
59
59
  "tsx": "4.22.4",
60
60
  "zod": "^4.2.0"
61
61
  },
62
62
  "devDependencies": {
63
63
  "@payloadcms/eslint-config": "3.28.0",
64
- "payload": "4.0.0-internal.656159a"
64
+ "payload": "4.0.0-internal.697830c"
65
65
  },
66
66
  "peerDependencies": {
67
- "payload": "4.0.0-internal.656159a"
67
+ "payload": "4.0.0-internal.697830c"
68
68
  },
69
69
  "//deps_notes": {
70
70
  "zod": "zod is a hard dependency of @modelcontextprotocol/server, thus we can safely use it without it impacting bundle size. Make extra sure the zod version here matches exactly what's defined in the dependencies of @modelcontextprotocol/server to avoid duplicate versions being installed.",
@@ -11,7 +11,6 @@ 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, resolveFileInput } from './fileInput.js'
15
14
  import { formatCollectionError } from './formatCollectionError.js'
16
15
 
17
16
  const DEFAULT_DESCRIPTION =
@@ -29,11 +28,7 @@ export const createDocumentTool = defineCollectionTool({
29
28
  },
30
29
  description: DEFAULT_DESCRIPTION,
31
30
  input: z.object({
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
- ),
31
+ data: z.record(z.string(), z.unknown()).describe('The document fields to create'),
37
32
  depth: z
38
33
  .number()
39
34
  .int()
@@ -44,16 +39,13 @@ export const createDocumentTool = defineCollectionTool({
44
39
  .default(0),
45
40
  draft: z
46
41
  .boolean()
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
- )
42
+ .describe('Whether to create the document as a draft')
50
43
  .optional()
51
44
  .default(false),
52
45
  fallbackLocale: z
53
46
  .string()
54
47
  .describe('Optional: fallback locale code to use when requested locale is not available')
55
48
  .optional(),
56
- file: fileInputSchema.optional(),
57
49
  locale: z
58
50
  .string()
59
51
  .describe(
@@ -71,7 +63,7 @@ export const createDocumentTool = defineCollectionTool({
71
63
  const payload = req.payload
72
64
  const logger = getLogger({ payload })
73
65
 
74
- const { data, depth, draft, fallbackLocale, file: fileInput, locale, select } = input
66
+ const { data, depth, draft, fallbackLocale, locale, select } = input
75
67
 
76
68
  logger.info(
77
69
  `Creating document in collection: ${collectionSlug}${locale ? ` with locale: ${locale}` : ''}`,
@@ -87,7 +79,6 @@ export const createDocumentTool = defineCollectionTool({
87
79
  }
88
80
 
89
81
  const parsedData = transformPointDataToPayload(inputData)
90
- const file = await resolveFileInput({ collectionSlug, input: fileInput, req })
91
82
 
92
83
  const result = await payload.create({
93
84
  collection: collectionSlug,
@@ -96,7 +87,6 @@ export const createDocumentTool = defineCollectionTool({
96
87
  draft,
97
88
  overrideAccess: authorizedMCP.overrideAccess,
98
89
  req,
99
- ...(file ? { file } : {}),
100
90
  ...(locale ? { locale } : {}),
101
91
  ...(fallbackLocale ? { fallbackLocale } : {}),
102
92
  ...(select ? { select: select as SelectType } : {}),
@@ -39,7 +39,7 @@ export const findDocumentsTool = defineCollectionTool({
39
39
  draft: z
40
40
  .boolean()
41
41
  .describe(
42
- 'For versioned collections, true returns the latest draft version when available. False reads the main document.',
42
+ 'Optional: whether the document should be queried from the versions table/collection or not.',
43
43
  )
44
44
  .optional(),
45
45
  fallbackLocale: z
@@ -48,29 +48,16 @@ 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: [...(uploadConfig.pasteURL !== false ? ['url'] : []), 'base64'],
59
- ...(typeof maxFileSize === 'number' && Number.isFinite(maxFileSize) ? { maxFileSize } : {}),
60
- }
61
- : { enabled: false }
62
-
63
51
  return {
64
52
  content: [
65
53
  {
66
54
  type: 'text',
67
- text: `Schema for collection "${collectionSlug}":\n\`\`\`json\n${JSON.stringify(inputSchema)}\n\`\`\`\nUpload configuration:\n\`\`\`json\n${JSON.stringify(upload)}\n\`\`\``,
55
+ text: `Schema for collection "${collectionSlug}":\n\`\`\`json\n${JSON.stringify(inputSchema)}\n\`\`\``,
68
56
  },
69
57
  ],
70
58
  structuredContent: {
71
59
  collectionSlug,
72
60
  schema: inputSchema,
73
- upload,
74
61
  },
75
62
  }
76
63
  })
@@ -13,7 +13,6 @@ 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, resolveFileInput } from './fileInput.js'
17
16
  import { formatCollectionError } from './formatCollectionError.js'
18
17
 
19
18
  const DEFAULT_DESCRIPTION =
@@ -32,11 +31,7 @@ export const updateDocumentTool = defineCollectionTool({
32
31
  description: DEFAULT_DESCRIPTION,
33
32
  input: z.object({
34
33
  id: z.union([z.string(), z.number()]).describe('The ID of the document to update').optional(),
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
- ),
34
+ data: z.record(z.string(), z.unknown()).describe('The fields to update'),
40
35
  depth: z
41
36
  .number()
42
37
  .describe('How many levels deep to populate relationships')
@@ -44,16 +39,14 @@ export const updateDocumentTool = defineCollectionTool({
44
39
  .default(0),
45
40
  draft: z
46
41
  .boolean()
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
- )
42
+ .describe('Whether to update the document as a draft')
50
43
  .optional()
51
44
  .default(false),
52
45
  fallbackLocale: z
53
46
  .string()
54
47
  .describe('Optional: fallback locale code to use when requested locale is not available')
55
48
  .optional(),
56
- file: fileInputSchema.optional(),
49
+ filePath: z.string().describe('File path for file uploads').optional(),
57
50
  locale: z
58
51
  .string()
59
52
  .describe(
@@ -70,12 +63,6 @@ export const updateDocumentTool = defineCollectionTool({
70
63
  .describe('Whether to overwrite existing files')
71
64
  .optional()
72
65
  .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(),
79
66
  select: z
80
67
  .record(z.string(), z.unknown())
81
68
  .describe(
@@ -98,11 +85,10 @@ export const updateDocumentTool = defineCollectionTool({
98
85
  depth,
99
86
  draft,
100
87
  fallbackLocale,
101
- file: fileInput,
88
+ filePath,
102
89
  locale,
103
90
  overrideLock,
104
91
  overwriteExistingFiles,
105
- publishAllLocales,
106
92
  select,
107
93
  where,
108
94
  } = input
@@ -132,7 +118,6 @@ export const updateDocumentTool = defineCollectionTool({
132
118
  }
133
119
 
134
120
  const parsedData = transformPointDataToPayload(inputData)
135
- const file = await resolveFileInput({ collectionSlug, input: fileInput, req })
136
121
 
137
122
  const whereClause: Where = where ?? {}
138
123
 
@@ -146,9 +131,8 @@ export const updateDocumentTool = defineCollectionTool({
146
131
  overrideAccess: authorizedMCP.overrideAccess,
147
132
  overrideLock,
148
133
  req,
149
- ...(file ? { file } : {}),
134
+ ...(filePath ? { filePath } : {}),
150
135
  ...(overwriteExistingFiles ? { overwriteExistingFiles } : {}),
151
- ...(publishAllLocales !== undefined ? { publishAllLocales } : {}),
152
136
  ...(locale ? { locale } : {}),
153
137
  ...(fallbackLocale ? { fallbackLocale } : {}),
154
138
  ...(select ? { select: select as SelectType } : {}),
@@ -174,9 +158,8 @@ export const updateDocumentTool = defineCollectionTool({
174
158
  overrideLock,
175
159
  req,
176
160
  where: whereClause,
177
- ...(file ? { file } : {}),
161
+ ...(filePath ? { filePath } : {}),
178
162
  ...(overwriteExistingFiles ? { overwriteExistingFiles } : {}),
179
- ...(publishAllLocales !== undefined ? { publishAllLocales } : {}),
180
163
  ...(locale ? { locale } : {}),
181
164
  ...(fallbackLocale ? { fallbackLocale } : {}),
182
165
  ...(select ? { select: select as SelectType } : {}),
@@ -76,8 +76,8 @@ describe('sanitizeEntitySchema', () => {
76
76
  },
77
77
  },
78
78
  properties: {
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).
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).
81
81
  id: { type: 'string' },
82
82
  content: {
83
83
  type: 'object',
@@ -1,20 +0,0 @@
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<"url">;
11
- url: z.ZodURL;
12
- }, z.core.$strip>], "source">;
13
- type FileInput = z.infer<typeof fileInputSchema>;
14
- export declare function resolveFileInput({ collectionSlug, input, req, }: {
15
- collectionSlug: CollectionSlug;
16
- input?: FileInput;
17
- req: PayloadRequest;
18
- }): Promise<File | undefined>;
19
- export {};
20
- //# sourceMappingURL=fileInput.d.ts.map
@@ -1 +0,0 @@
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;AAMvB,eAAO,MAAM,eAAe;;;;;;;;;6BAgBzB,CAAA;AAEH,KAAK,SAAS,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,eAAe,CAAC,CAAA;AAEhD,wBAAsB,gBAAgB,CAAC,EACrC,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,CAgE5B"}
@@ -1,100 +0,0 @@
1
- import { APIError } from 'payload';
2
- import { getExternalFile, 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
- export const fileInputSchema = z.discriminatedUnion('source', [
7
- z.object({
8
- name: z.string().min(1).describe('The file name, including its extension'),
9
- data: z.string().describe('The base64-encoded file bytes, without a data URL prefix'),
10
- mimeType: mimeTypeSchema.describe('The file MIME type, for example image/png'),
11
- source: z.literal('base64')
12
- }),
13
- z.object({
14
- name: z.string().min(1).describe('Optional file name override').optional(),
15
- source: z.literal('url'),
16
- url: z.url().describe('The http or https URL to download')
17
- })
18
- ]).describe('A file for an upload collection. Use only a source listed by getCollectionSchema: url for an online file or base64 for a local file.');
19
- export async function resolveFileInput({ collectionSlug, input, req }) {
20
- if (!input) {
21
- return undefined;
22
- }
23
- const uploadConfig = req.payload.collections[collectionSlug]?.config.upload;
24
- if (!uploadConfig) {
25
- throw new APIError(`Collection "${collectionSlug}" does not support file uploads.`, 400);
26
- }
27
- const maxFileSize = req.payload.config.upload.limits?.fileSize;
28
- let file;
29
- if (input.source === 'base64') {
30
- const data = decodeBase64({
31
- maxFileSize,
32
- value: input.data
33
- });
34
- file = {
35
- name: sanitizeFilename(input.name),
36
- data,
37
- mimetype: input.mimeType,
38
- size: data.length
39
- };
40
- } else {
41
- if (uploadConfig.pasteURL === false) {
42
- throw new APIError(`Uploading files from URLs is disabled for collection "${collectionSlug}".`, 400);
43
- }
44
- const url = new URL(input.url);
45
- if (![
46
- 'http:',
47
- 'https:'
48
- ].includes(url.protocol)) {
49
- throw new APIError('File URLs must use http or https.', 400);
50
- }
51
- if (typeof uploadConfig.pasteURL === 'object' && !isURLAllowed(input.url, uploadConfig.pasteURL.allowList)) {
52
- throw new APIError('The provided file URL is not allowed.', 400);
53
- }
54
- file = await getExternalFile({
55
- data: {
56
- filename: sanitizeFilename(input.name || getURLFilename(url)),
57
- url: input.url
58
- },
59
- req,
60
- uploadConfig: {
61
- ...uploadConfig,
62
- externalFileHeaderFilter: uploadConfig.externalFileHeaderFilter ?? (()=>({}))
63
- }
64
- });
65
- file.mimetype = file.mimetype?.split(';')[0] || 'application/octet-stream';
66
- file.size = file.data.length;
67
- }
68
- if (maxFileSize !== undefined && Number.isFinite(maxFileSize) && file.size > maxFileSize) {
69
- throw new APIError(`File exceeds the ${maxFileSize} byte upload limit.`, 400);
70
- }
71
- return file;
72
- }
73
- function decodeBase64({ maxFileSize, value }) {
74
- const normalized = value.replace(/\s/g, '');
75
- if (!/^[a-z0-9+/]*={0,2}$/i.test(normalized) || normalized.length % 4 === 1) {
76
- throw new APIError('File data must be valid base64.', 400);
77
- }
78
- if (maxFileSize !== undefined && Number.isFinite(maxFileSize)) {
79
- const paddingLength = normalized.endsWith('==') ? 2 : normalized.endsWith('=') ? 1 : 0;
80
- const decodedSize = Math.floor(normalized.length * 3 / 4) - paddingLength;
81
- if (decodedSize > maxFileSize) {
82
- throw new APIError(`File exceeds the ${maxFileSize} byte upload limit.`, 400);
83
- }
84
- }
85
- const data = Buffer.from(normalized, 'base64');
86
- if (data.toString('base64').replace(/=+$/, '') !== normalized.replace(/=+$/, '')) {
87
- throw new APIError('File data must be valid base64.', 400);
88
- }
89
- return data;
90
- }
91
- function getURLFilename(url) {
92
- const pathSegment = url.pathname.split('/').pop() || 'upload';
93
- try {
94
- return decodeURIComponent(pathSegment);
95
- } catch {
96
- return pathSegment;
97
- }
98
- }
99
-
100
- //# sourceMappingURL=fileInput.js.map
@@ -1 +0,0 @@
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, 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\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('url'),\n url: z.url().describe('The http or https URL to download'),\n }),\n ])\n .describe(\n 'A file for an upload collection. Use only a source listed by getCollectionSchema: url for an online file or base64 for a local file.',\n )\n\ntype FileInput = z.infer<typeof fileInputSchema>\n\nexport async function resolveFileInput({\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 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","isURLAllowed","sanitizeFilename","z","mimeTypeSchema","string","regex","fileInputSchema","discriminatedUnion","object","name","min","describe","data","mimeType","source","literal","optional","url","resolveFileInput","collectionSlug","input","req","undefined","uploadConfig","payload","collections","config","upload","maxFileSize","limits","fileSize","file","decodeBase64","value","mimetype","size","length","pasteURL","URL","includes","protocol","allowList","filename","getURLFilename","externalFileHeaderFilter","split","Number","isFinite","normalized","replace","test","paddingLength","endsWith","decodedSize","Math","floor","Buffer","from","toString","pathSegment","pathname","pop","decodeURIComponent"],"mappings":"AAEA,SAASA,QAAQ,QAAQ,UAAS;AAClC,SAASC,eAAe,EAAEC,YAAY,QAAQ,mBAAkB;AAChE,SAASC,gBAAgB,QAAQ,iBAAgB;AACjD,SAASC,CAAC,QAAQ,MAAK;AAEvB,MAAMC,iBAAiBD,EACpBE,MAAM,GACNC,KAAK,CAAC,8CAA8C;AAEvD,OAAO,MAAMC,kBAAkBJ,EAC5BK,kBAAkB,CAAC,UAAU;IAC5BL,EAAEM,MAAM,CAAC;QACPC,MAAMP,EAAEE,MAAM,GAAGM,GAAG,CAAC,GAAGC,QAAQ,CAAC;QACjCC,MAAMV,EAAEE,MAAM,GAAGO,QAAQ,CAAC;QAC1BE,UAAUV,eAAeQ,QAAQ,CAAC;QAClCG,QAAQZ,EAAEa,OAAO,CAAC;IACpB;IACAb,EAAEM,MAAM,CAAC;QACPC,MAAMP,EAAEE,MAAM,GAAGM,GAAG,CAAC,GAAGC,QAAQ,CAAC,+BAA+BK,QAAQ;QACxEF,QAAQZ,EA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C,OAAO,CAAC,OAAO,KAAK;QAChF,MAAM,IAAInD,SAAS,mCAAmC;IACxD;IAEA,OAAOc;AACT;AAEA,SAAS+B,eAAe1B,GAAQ;IAC9B,MAAM0C,cAAc1C,IAAI2C,QAAQ,CAACf,KAAK,CAAC,KAAKgB,GAAG,MAAM;IAErD,IAAI;QACF,OAAOC,mBAAmBH;IAC5B,EAAE,OAAM;QACN,OAAOA;IACT;AACF"}
@@ -1,72 +0,0 @@
1
- import { describe, expect, it } from 'vitest';
2
- import { fileInputSchema, resolveFileInput } from './fileInput.js';
3
- describe('MCP file input', ()=>{
4
- it('should reject malformed MIME types', ()=>{
5
- const result = fileInputSchema.safeParse({
6
- data: 'aGVsbG8=',
7
- mimeType: 'text/plain\r\nx-test: value',
8
- name: 'hello.txt',
9
- source: 'base64'
10
- });
11
- expect(result.success).toBe(false);
12
- });
13
- it('should reject oversized base64 files', async ()=>{
14
- const req = createRequest({
15
- maxFileSize: 4
16
- });
17
- await expect(resolveFileInput({
18
- collectionSlug: 'media',
19
- input: {
20
- data: Buffer.from('hello').toString('base64'),
21
- mimeType: 'text/plain',
22
- name: 'hello.txt',
23
- source: 'base64'
24
- },
25
- req
26
- })).rejects.toThrow('File exceeds the 4 byte upload limit.');
27
- });
28
- it('should reject URLs outside the collection allowlist', async ()=>{
29
- const req = createRequest({
30
- allowList: [
31
- {
32
- hostname: 'assets.example.com',
33
- protocol: 'https'
34
- }
35
- ]
36
- });
37
- await expect(resolveFileInput({
38
- collectionSlug: 'media',
39
- input: {
40
- source: 'url',
41
- url: 'https://example.com/image.png'
42
- },
43
- req
44
- })).rejects.toThrow('The provided file URL is not allowed.');
45
- });
46
- });
47
- function createRequest({ allowList, maxFileSize }) {
48
- return {
49
- payload: {
50
- collections: {
51
- media: {
52
- config: {
53
- upload: allowList ? {
54
- pasteURL: {
55
- allowList
56
- }
57
- } : {}
58
- }
59
- }
60
- },
61
- config: {
62
- upload: {
63
- limits: {
64
- fileSize: maxFileSize
65
- }
66
- }
67
- }
68
- }
69
- };
70
- }
71
-
72
- //# sourceMappingURL=fileInput.spec.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../../src/mcp/builtin/collections/fileInput.spec.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\n\nimport { describe, expect, it } from 'vitest'\n\nimport { fileInputSchema, resolveFileInput } from './fileInput.js'\n\ndescribe('MCP file input', () => {\n it('should reject malformed MIME types', () => {\n const result = fileInputSchema.safeParse({\n data: 'aGVsbG8=',\n mimeType: 'text/plain\\r\\nx-test: value',\n name: 'hello.txt',\n source: 'base64',\n })\n\n expect(result.success).toBe(false)\n })\n\n it('should reject oversized base64 files', async () => {\n const req = createRequest({ maxFileSize: 4 })\n\n await expect(\n resolveFileInput({\n collectionSlug: 'media',\n input: {\n data: Buffer.from('hello').toString('base64'),\n mimeType: 'text/plain',\n name: 'hello.txt',\n source: 'base64',\n },\n req,\n }),\n ).rejects.toThrow('File exceeds the 4 byte upload limit.')\n })\n\n it('should reject URLs outside the collection allowlist', async () => {\n const req = createRequest({\n allowList: [{ hostname: 'assets.example.com', protocol: 'https' }],\n })\n\n await expect(\n resolveFileInput({\n collectionSlug: 'media',\n input: {\n source: 'url',\n url: 'https://example.com/image.png',\n },\n req,\n }),\n ).rejects.toThrow('The provided file URL is not allowed.')\n })\n})\n\nfunction createRequest({\n allowList,\n maxFileSize,\n}: {\n allowList?: Array<{ hostname: string; protocol: 'http' | 'https' }>\n maxFileSize?: number\n}): PayloadRequest {\n return {\n payload: {\n collections: {\n media: {\n config: {\n upload: allowList ? { pasteURL: { allowList } } : {},\n },\n },\n },\n config: {\n upload: {\n limits: {\n fileSize: maxFileSize,\n },\n },\n },\n },\n } as unknown as PayloadRequest\n}\n"],"names":["describe","expect","it","fileInputSchema","resolveFileInput","result","safeParse","data","mimeType","name","source","success","toBe","req","createRequest","maxFileSize","collectionSlug","input","Buffer","from","toString","rejects","toThrow","allowList","hostname","protocol","url","payload","collections","media","config","upload","pasteURL","limits","fileSize"],"mappings":"AAEA,SAASA,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAQ;AAE7C,SAASC,eAAe,EAAEC,gBAAgB,QAAQ,iBAAgB;AAElEJ,SAAS,kBAAkB;IACzBE,GAAG,sCAAsC;QACvC,MAAMG,SAASF,gBAAgBG,SAAS,CAAC;YACvCC,MAAM;YACNC,UAAU;YACVC,MAAM;YACNC,QAAQ;QACV;QAEAT,OAAOI,OAAOM,OAAO,EAAEC,IAAI,CAAC;IAC9B;IAEAV,GAAG,wCAAwC;QACzC,MAAMW,MAAMC,cAAc;YAAEC,aAAa;QAAE;QAE3C,MAAMd,OACJG,iBAAiB;YACfY,gBAAgB;YAChBC,OAAO;gBACLV,MAAMW,OAAOC,IAAI,CAAC,SAASC,QAAQ,CAAC;gBACpCZ,UAAU;gBACVC,MAAM;gBACNC,QAAQ;YACV;YACAG;QACF,IACAQ,OAAO,CAACC,OAAO,CAAC;IACpB;IAEApB,GAAG,uDAAuD;QACxD,MAAMW,MAAMC,cAAc;YACxBS,WAAW;gBAAC;oBAAEC,UAAU;oBAAsBC,UAAU;gBAAQ;aAAE;QACpE;QAEA,MAAMxB,OACJG,iBAAiB;YACfY,gBAAgB;YAChBC,OAAO;gBACLP,QAAQ;gBACRgB,KAAK;YACP;YACAb;QACF,IACAQ,OAAO,CAACC,OAAO,CAAC;IACpB;AACF;AAEA,SAASR,cAAc,EACrBS,SAAS,EACTR,WAAW,EAIZ;IACC,OAAO;QACLY,SAAS;YACPC,aAAa;gBACXC,OAAO;oBACLC,QAAQ;wBACNC,QAAQR,YAAY;4BAAES,UAAU;gCAAET;4BAAU;wBAAE,IAAI,CAAC;oBACrD;gBACF;YACF;YACAO,QAAQ;gBACNC,QAAQ;oBACNE,QAAQ;wBACNC,UAAUnB;oBACZ;gBACF;YACF;QACF;IACF;AACF"}
@@ -1,79 +0,0 @@
1
- import type { PayloadRequest } from 'payload'
2
-
3
- import { describe, expect, it } from 'vitest'
4
-
5
- import { fileInputSchema, resolveFileInput } 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 reject oversized base64 files', async () => {
20
- const req = createRequest({ maxFileSize: 4 })
21
-
22
- await expect(
23
- resolveFileInput({
24
- collectionSlug: 'media',
25
- input: {
26
- data: Buffer.from('hello').toString('base64'),
27
- mimeType: 'text/plain',
28
- name: 'hello.txt',
29
- source: 'base64',
30
- },
31
- req,
32
- }),
33
- ).rejects.toThrow('File exceeds the 4 byte upload limit.')
34
- })
35
-
36
- it('should reject URLs outside the collection allowlist', async () => {
37
- const req = createRequest({
38
- allowList: [{ hostname: 'assets.example.com', protocol: 'https' }],
39
- })
40
-
41
- await expect(
42
- resolveFileInput({
43
- collectionSlug: 'media',
44
- input: {
45
- source: 'url',
46
- url: 'https://example.com/image.png',
47
- },
48
- req,
49
- }),
50
- ).rejects.toThrow('The provided file URL is not allowed.')
51
- })
52
- })
53
-
54
- function createRequest({
55
- allowList,
56
- maxFileSize,
57
- }: {
58
- allowList?: Array<{ hostname: string; protocol: 'http' | 'https' }>
59
- maxFileSize?: number
60
- }): PayloadRequest {
61
- return {
62
- payload: {
63
- collections: {
64
- media: {
65
- config: {
66
- upload: allowList ? { pasteURL: { allowList } } : {},
67
- },
68
- },
69
- },
70
- config: {
71
- upload: {
72
- limits: {
73
- fileSize: maxFileSize,
74
- },
75
- },
76
- },
77
- },
78
- } as unknown as PayloadRequest
79
- }