@payloadcms/plugin-mcp 4.0.0-internal.e55ccef → 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 (36) hide show
  1. package/dist/mcp/builtin/collections/createTool.js +3 -3
  2. package/dist/mcp/builtin/collections/createTool.js.map +1 -1
  3. package/dist/mcp/builtin/collections/fileInput.d.ts +10 -2
  4. package/dist/mcp/builtin/collections/fileInput.d.ts.map +1 -1
  5. package/dist/mcp/builtin/collections/fileInput.js +21 -4
  6. package/dist/mcp/builtin/collections/fileInput.js.map +1 -1
  7. package/dist/mcp/builtin/collections/fileInput.spec.js +18 -4
  8. package/dist/mcp/builtin/collections/fileInput.spec.js.map +1 -1
  9. package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -1
  10. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +3 -2
  11. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -1
  12. package/dist/mcp/builtin/collections/updateTool.js +3 -3
  13. package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
  14. package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts +2 -0
  15. package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts.map +1 -0
  16. package/dist/mcp/builtin/collections/uploadInstructionsTool.js +55 -0
  17. package/dist/mcp/builtin/collections/uploadInstructionsTool.js.map +1 -0
  18. package/dist/mcp/builtinTools.d.ts +6 -0
  19. package/dist/mcp/builtinTools.d.ts.map +1 -1
  20. package/dist/mcp/builtinTools.js +6 -0
  21. package/dist/mcp/builtinTools.js.map +1 -1
  22. package/dist/mcp/sanitizeMCPConfig.js +4 -1
  23. package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
  24. package/dist/stdio.d.ts.map +1 -1
  25. package/dist/stdio.js +2 -1
  26. package/dist/stdio.js.map +1 -1
  27. package/package.json +3 -3
  28. package/src/mcp/builtin/collections/createTool.ts +3 -3
  29. package/src/mcp/builtin/collections/fileInput.spec.ts +18 -4
  30. package/src/mcp/builtin/collections/fileInput.ts +19 -4
  31. package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +5 -1
  32. package/src/mcp/builtin/collections/updateTool.ts +3 -3
  33. package/src/mcp/builtin/collections/uploadInstructionsTool.ts +64 -0
  34. package/src/mcp/builtinTools.ts +7 -0
  35. package/src/mcp/sanitizeMCPConfig.ts +4 -1
  36. package/src/stdio.ts +2 -1
@@ -5,9 +5,9 @@ import { getLogger } from '../../../utils/getLogger.js';
5
5
  import { getCollectionVirtualFieldNames, stripVirtualFields } from '../../../utils/getVirtualFieldNames.js';
6
6
  import { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js';
7
7
  import { validateCollectionData } from '../validateEntityData.js';
8
- import { fileInputSchema, resolveFileInput } from './fileInput.js';
8
+ import { fileInputSchema, resolveFile } from './fileInput.js';
9
9
  import { formatCollectionError } from './formatCollectionError.js';
10
- const DEFAULT_DESCRIPTION = 'Create a document in any collection by passing the collection slug and data.';
10
+ const DEFAULT_DESCRIPTION = 'Create a document in any collection. Files can use a URL, base64, or an upload prepared by getUploadInstructions.';
11
11
  export const createDocumentTool = defineCollectionTool({
12
12
  access: (args)=>defaultAccess(args) && Boolean(args.permissions?.collections?.[args.collectionSlug]?.create),
13
13
  annotations: {
@@ -46,7 +46,7 @@ export const createDocumentTool = defineCollectionTool({
46
46
  return validationError;
47
47
  }
48
48
  const parsedData = transformPointDataToPayload(inputData);
49
- const file = await resolveFileInput({
49
+ const file = await resolveFile({
50
50
  collectionSlug,
51
51
  input: fileInput,
52
52
  req
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/mcp/builtin/collections/createTool.ts"],"sourcesContent":["import type { SelectType } from 'payload'\n\nimport { z } from 'zod'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\nimport {\n getCollectionVirtualFieldNames,\n stripVirtualFields,\n} from '../../../utils/getVirtualFieldNames.js'\nimport { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'\nimport { validateCollectionData } from '../validateEntityData.js'\nimport { fileInputSchema, resolveFileInput } from './fileInput.js'\nimport { formatCollectionError } from './formatCollectionError.js'\n\nconst DEFAULT_DESCRIPTION =\n 'Create a document in any collection by passing the collection slug and data.'\n\nexport const createDocumentTool = defineCollectionTool({\n access: (args) =>\n defaultAccess(args) && Boolean(args.permissions?.collections?.[args.collectionSlug]?.create),\n annotations: {\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'Create Document',\n },\n description: DEFAULT_DESCRIPTION,\n input: z.object({\n data: z\n .record(z.string(), z.unknown())\n .describe(\n 'The document fields to create. Only include fields permitted by the schema returned by getCollectionSchema.',\n ),\n depth: z\n .number()\n .int()\n .min(0)\n .max(10)\n .describe('How many levels deep to populate relationships in response')\n .optional()\n .default(0),\n draft: z\n .boolean()\n .describe(\n 'Only if getCollectionSchema includes _status; otherwise _status does not exist. true forces data._status to \"draft\"; with false, data._status controls draft or published.',\n )\n .optional()\n .default(false),\n fallbackLocale: z\n .string()\n .describe('Optional: fallback locale code to use when requested locale is not available')\n .optional(),\n file: fileInputSchema.optional(),\n locale: z\n .string()\n .describe(\n 'Optional: locale code to create the document in (e.g., \"en\", \"es\"). Defaults to the default locale',\n )\n .optional(),\n select: z\n .record(z.string(), z.unknown())\n .describe(\n 'Optional: define exactly which fields you\\'d like to return, e.g., {\"title\": true}',\n )\n .optional(),\n }),\n}).handler(async ({ authorizedMCP, collectionSlug, input, req }) => {\n const payload = req.payload\n const logger = getLogger({ payload })\n\n const { data, depth, draft, fallbackLocale, file: fileInput, locale, select } = input\n\n logger.info(\n `Creating document in collection: ${collectionSlug}${locale ? ` with locale: ${locale}` : ''}`,\n )\n\n try {\n const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, collectionSlug)\n const inputData = stripVirtualFields(data, virtualFieldNames)\n const validationError = validateCollectionData({ collectionSlug, data: inputData, req })\n\n if (validationError) {\n return validationError\n }\n\n const parsedData = transformPointDataToPayload(inputData)\n const file = await resolveFileInput({ collectionSlug, input: fileInput, req })\n\n const result = await payload.create({\n collection: collectionSlug,\n data: parsedData,\n depth,\n draft,\n overrideAccess: authorizedMCP.overrideAccess,\n req,\n ...(file ? { file } : {}),\n ...(locale ? { locale } : {}),\n ...(fallbackLocale ? { fallbackLocale } : {}),\n ...(select ? { select: select as SelectType } : {}),\n })\n\n logger.info(`Successfully created document in ${collectionSlug} with ID: ${result.id}`)\n\n return {\n content: [\n {\n type: 'text',\n text: `Document created successfully in collection \"${collectionSlug}\"!\\nCreated document:\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error creating document in ${collectionSlug}: ${errorMessage}`)\n return formatCollectionError({ action: 'creating', collectionSlug, error, req })\n }\n})\n"],"names":["z","defaultAccess","defineCollectionTool","getLogger","getCollectionVirtualFieldNames","stripVirtualFields","transformPointDataToPayload","validateCollectionData","fileInputSchema","resolveFileInput","formatCollectionError","DEFAULT_DESCRIPTION","createDocumentTool","access","args","Boolean","permissions","collections","collectionSlug","create","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","object","data","record","string","unknown","describe","depth","number","int","min","max","optional","default","draft","boolean","fallbackLocale","file","locale","select","handler","authorizedMCP","req","payload","logger","fileInput","info","virtualFieldNames","config","inputData","validationError","parsedData","result","collection","overrideAccess","id","content","type","text","JSON","stringify","doc","error","errorMessage","Error","message","action"],"mappings":"AAEA,SAASA,CAAC,QAAQ,MAAK;AAEvB,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AACvD,SACEC,8BAA8B,EAC9BC,kBAAkB,QACb,y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,OAAO,GAAG;QAC9DrB,OAAOkB,KAAK,CAAC,CAAC,2BAA2B,EAAEnD,eAAe,EAAE,EAAEoD,cAAc;QAC5E,OAAO5D,sBAAsB;YAAE+D,QAAQ;YAAYvD;YAAgBmD;YAAOpB;QAAI;IAChF;AACF,GAAE"}
1
+ {"version":3,"sources":["../../../../src/mcp/builtin/collections/createTool.ts"],"sourcesContent":["import type { SelectType } from 'payload'\n\nimport { z } from 'zod'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\nimport {\n getCollectionVirtualFieldNames,\n stripVirtualFields,\n} from '../../../utils/getVirtualFieldNames.js'\nimport { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'\nimport { validateCollectionData } from '../validateEntityData.js'\nimport { fileInputSchema, resolveFile } from './fileInput.js'\nimport { formatCollectionError } from './formatCollectionError.js'\n\nconst DEFAULT_DESCRIPTION =\n 'Create a document in any collection. Files can use a URL, base64, or an upload prepared by getUploadInstructions.'\n\nexport const createDocumentTool = defineCollectionTool({\n access: (args) =>\n defaultAccess(args) && Boolean(args.permissions?.collections?.[args.collectionSlug]?.create),\n annotations: {\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'Create Document',\n },\n description: DEFAULT_DESCRIPTION,\n input: z.object({\n data: z\n .record(z.string(), z.unknown())\n .describe(\n 'The document fields to create. Only include fields permitted by the schema returned by getCollectionSchema.',\n ),\n depth: z\n .number()\n .int()\n .min(0)\n .max(10)\n .describe('How many levels deep to populate relationships in response')\n .optional()\n .default(0),\n draft: z\n .boolean()\n .describe(\n 'Only if getCollectionSchema includes _status; otherwise _status does not exist. true forces data._status to \"draft\"; with false, data._status controls draft or published.',\n )\n .optional()\n .default(false),\n fallbackLocale: z\n .string()\n .describe('Optional: fallback locale code to use when requested locale is not available')\n .optional(),\n file: fileInputSchema.optional(),\n locale: z\n .string()\n .describe(\n 'Optional: locale code to create the document in (e.g., \"en\", \"es\"). Defaults to the default locale',\n )\n .optional(),\n select: z\n .record(z.string(), z.unknown())\n .describe(\n 'Optional: define exactly which fields you\\'d like to return, e.g., {\"title\": true}',\n )\n .optional(),\n }),\n}).handler(async ({ authorizedMCP, collectionSlug, input, req }) => {\n const payload = req.payload\n const logger = getLogger({ payload })\n\n const { data, depth, draft, fallbackLocale, file: fileInput, locale, select } = input\n\n logger.info(\n `Creating document in collection: ${collectionSlug}${locale ? ` with locale: ${locale}` : ''}`,\n )\n\n try {\n const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, collectionSlug)\n const inputData = stripVirtualFields(data, virtualFieldNames)\n const validationError = validateCollectionData({ collectionSlug, data: inputData, req })\n\n if (validationError) {\n return validationError\n }\n\n const parsedData = transformPointDataToPayload(inputData)\n const file = await resolveFile({ collectionSlug, input: fileInput, req })\n\n const result = await payload.create({\n collection: collectionSlug,\n data: parsedData,\n depth,\n draft,\n overrideAccess: authorizedMCP.overrideAccess,\n req,\n ...(file ? { file } : {}),\n ...(locale ? { locale } : {}),\n ...(fallbackLocale ? { fallbackLocale } : {}),\n ...(select ? { select: select as SelectType } : {}),\n })\n\n logger.info(`Successfully created document in ${collectionSlug} with ID: ${result.id}`)\n\n return {\n content: [\n {\n type: 'text',\n text: `Document created successfully in collection \"${collectionSlug}\"!\\nCreated document:\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error creating document in ${collectionSlug}: ${errorMessage}`)\n return formatCollectionError({ action: 'creating', collectionSlug, error, req })\n }\n})\n"],"names":["z","defaultAccess","defineCollectionTool","getLogger","getCollectionVirtualFieldNames","stripVirtualFields","transformPointDataToPayload","validateCollectionData","fileInputSchema","resolveFile","formatCollectionError","DEFAULT_DESCRIPTION","createDocumentTool","access","args","Boolean","permissions","collections","collectionSlug","create","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","object","data","record","string","unknown","describe","depth","number","int","min","max","optional","default","draft","boolean","fallbackLocale","file","locale","select","handler","authorizedMCP","req","payload","logger","fileInput","info","virtualFieldNames","config","inputData","validationError","parsedData","result","collection","overrideAccess","id","content","type","text","JSON","stringify","doc","error","errorMessage","Error","message","action"],"mappings":"AAEA,SAASA,CAAC,QAAQ,MAAK;AAEvB,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AACvD,SACEC,8BAA8B,EAC9BC,kBAAkB,QACb,yCAAwC;AAC/C,SAASC,2BAA2B,QAAQ,gDAA+C;AAC3F,SAASC,sBAAsB,QAAQ,2BAA0B;AACjE,SAASC,eAAe,EAAEC,WAAW,QAAQ,iBAAgB;AAC7D,SAASC,qBAAqB,QAAQ,6BAA4B;AAElE,MAAMC,sBACJ;AAEF,OAAO,MAAMC,qBAAqBV,qBAAqB;IACrDW,QAAQ,CAACC,OACPb,cAAca,SAASC,QAAQD,KAAKE,WAAW,EAAEC,aAAa,CAACH,KAAKI,cAAc,CAAC,EAAEC;IACvFC,aAAa;QACXC,iBAAiB;QACjBC,gBAAgB;QAChBC,eAAe;QACfC,cAAc;QACdC,OAAO;IACT;IACAC,aAAaf;IACbgB,OAAO3B,EAAE4B,MAAM,CAAC;QACdC,MAAM7B,EACH8B,MAAM,CAAC9B,EAAE+B,MAAM,IAAI/B,EAAEgC,OAAO,IAC5BC,QAAQ,CACP;QAEJC,OAAOlC,EACJmC,MAAM,GACNC,GAAG,GACHC,GAAG,CAAC,GACJC,GAAG,CAAC,IACJL,QAAQ,CAAC,8DACTM,QAAQ,GACRC,OAAO,CAAC;QACXC,OAAOzC,EACJ0C,OAAO,GACPT,QAAQ,CACP,8KAEDM,QAAQ,GACRC,OAAO,CAAC;QACXG,gBAAgB3C,EACb+B,MAAM,GACNE,QAAQ,CA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,IAAI,CAAC,CAAC;YAC5C,GAAIG,SAAS;gBAAEA,QAAQA;YAAqB,IAAI,CAAC,CAAC;QACpD;QAEAK,OAAOE,IAAI,CAAC,CAAC,iCAAiC,EAAEnC,eAAe,UAAU,EAAEyC,OAAOG,EAAE,EAAE;QAEtF,OAAO;YACLC,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,6CAA6C,EAAE/C,eAAe,mCAAmC,EAAEgD,KAAKC,SAAS,CAACR,QAAQ,QAAQ,CAAC;gBAC5I;aACD;YACDS,KAAKT;QACP;IACF,EAAE,OAAOU,OAAO;QACd,MAAMC,eAAeD,iBAAiBE,QAAQF,MAAMG,OAAO,GAAG;QAC9DrB,OAAOkB,KAAK,CAAC,CAAC,2BAA2B,EAAEnD,eAAe,EAAE,EAAEoD,cAAc;QAC5E,OAAO5D,sBAAsB;YAAE+D,QAAQ;YAAYvD;YAAgBmD;YAAOpB;QAAI;IAChF;AACF,GAAE"}
@@ -7,11 +7,19 @@ export declare const fileInputSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
7
7
  source: z.ZodLiteral<"base64">;
8
8
  }, z.core.$strip>, z.ZodObject<{
9
9
  name: z.ZodOptional<z.ZodString>;
10
- source: z.ZodLiteral<"url">;
10
+ source: z.ZodLiteral<"externalURL">;
11
11
  url: z.ZodURL;
12
+ }, z.core.$strip>, z.ZodObject<{
13
+ file: z.ZodObject<{
14
+ filename: z.ZodString;
15
+ mimeType: z.ZodString;
16
+ size: z.ZodNumber;
17
+ uploadReference: z.ZodRecord<z.ZodString, z.ZodUnknown>;
18
+ }, z.core.$strip>;
19
+ source: z.ZodLiteral<"uploadReference">;
12
20
  }, z.core.$strip>], "source">;
13
21
  type FileInput = z.infer<typeof fileInputSchema>;
14
- export declare function resolveFileInput({ collectionSlug, input, req, }: {
22
+ export declare function resolveFile({ collectionSlug, input, req, }: {
15
23
  collectionSlug: CollectionSlug;
16
24
  input?: FileInput;
17
25
  req: PayloadRequest;
@@ -1 +1 @@
1
- {"version":3,"file":"fileInput.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/fileInput.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,IAAI,EAAY,cAAc,EAAE,MAAM,SAAS,CAAA;AAK7E,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;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
+ {"version":3,"file":"fileInput.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/fileInput.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,IAAI,EAAY,cAAc,EAAE,MAAM,SAAS,CAAA;AAK7E,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAavB,eAAO,MAAM,eAAe;;;;;;;;;;;;;;;;;6BAoBzB,CAAA;AAEH,KAAK,SAAS,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,eAAe,CAAC,CAAA;AAEhD,wBAAsB,WAAW,CAAC,EAChC,cAAc,EACd,KAAK,EACL,GAAG,GACJ,EAAE;IACD,cAAc,EAAE,cAAc,CAAA;IAC9B,KAAK,CAAC,EAAE,SAAS,CAAA;IACjB,GAAG,EAAE,cAAc,CAAA;CACpB,GAAG,OAAO,CAAC,IAAI,GAAG,SAAS,CAAC,CAoE5B"}
@@ -1,8 +1,14 @@
1
1
  import { APIError } from 'payload';
2
- import { getExternalFile, isURLAllowed } from 'payload/internal';
2
+ import { getExternalFile, getFileFromUploadInstructions, isURLAllowed } from 'payload/internal';
3
3
  import { sanitizeFilename } from 'payload/shared';
4
4
  import { z } from 'zod';
5
5
  const mimeTypeSchema = z.string().regex(/^[!#$%&'*+.^`|~\w-]+\/[!#$%&'*+.^`|~\w-]+$/, 'MIME type must use the type/subtype format');
6
+ const uploadFileSchema = z.object({
7
+ filename: z.string(),
8
+ mimeType: z.string(),
9
+ size: z.number().int().nonnegative(),
10
+ uploadReference: z.record(z.string(), z.unknown())
11
+ });
6
12
  export const fileInputSchema = z.discriminatedUnion('source', [
7
13
  z.object({
8
14
  name: z.string().min(1).describe('The file name, including its extension'),
@@ -12,14 +18,25 @@ export const fileInputSchema = z.discriminatedUnion('source', [
12
18
  }),
13
19
  z.object({
14
20
  name: z.string().min(1).describe('Optional file name override').optional(),
15
- source: z.literal('url'),
21
+ source: z.literal('externalURL'),
16
22
  url: z.url().describe('The http or https URL to download')
23
+ }),
24
+ z.object({
25
+ file: uploadFileSchema.describe('The file value returned by getUploadInstructions'),
26
+ source: z.literal('uploadReference')
17
27
  })
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 }) {
28
+ ]).describe('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.');
29
+ export async function resolveFile({ collectionSlug, input, req }) {
20
30
  if (!input) {
21
31
  return undefined;
22
32
  }
33
+ if (input.source === 'uploadReference') {
34
+ return getFileFromUploadInstructions({
35
+ collectionSlug,
36
+ file: input.file,
37
+ req
38
+ });
39
+ }
23
40
  const uploadConfig = req.payload.collections[collectionSlug]?.config.upload;
24
41
  if (!uploadConfig) {
25
42
  throw new APIError(`Collection "${collectionSlug}" does not support file uploads.`, 400);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/mcp/builtin/collections/fileInput.ts"],"sourcesContent":["import type { CollectionSlug, File, FileData, PayloadRequest } from 'payload'\n\nimport { APIError } from 'payload'\nimport { getExternalFile, 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,EAAEa,OAAO,CAAC;QAClBE,KAAKf,EAAEe,GAAG,GAAGN,QAAQ,CAAC;IACxB;CACD,EACAA,QAAQ,CACP,wIACD;AAIH,OAAO,eAAeO,iBAAiB,EACrCC,cAAc,EACdC,KAAK,EACLC,GAAG,EAKJ;IACC,IAAI,CAACD,OAAO;QACV,OAAOE;IACT;IAEA,MAAMC,eAAeF,IAAIG,OAAO,CAACC,WAAW,CAACN,eAAe,EAAEO,OAAOC;IAErE,IAAI,CAACJ,cAAc;QACjB,MAAM,IAAIzB,SAAS,CAAC,YAAY,EAAEqB,eAAe,gCAAgC,CAAC,EAAE;IACtF;IAEA,MAAMS,cAAcP,IAAIG,OAAO,CAACE,MAAM,CAACC,MAAM,CAACE,MAAM,EAAEC;IACtD,IAAIC;IAEJ,IAAIX,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Y,mBAAmB,CAAC,EAAE;IAC3E;IAEA,OAAOG;AACT;AAEA,SAASC,aAAa,EAAEJ,WAAW,EAAEK,KAAK,EAA2C;IACnF,MAAMe,aAAaf,MAAMgB,OAAO,CAAC,OAAO;IAExC,IAAI,CAAC,uBAAuBC,IAAI,CAACF,eAAeA,WAAWZ,MAAM,GAAG,MAAM,GAAG;QAC3E,MAAM,IAAItC,SAAS,mCAAmC;IACxD;IAEA,IAAI8B,gBAAgBN,aAAawB,OAAOC,QAAQ,CAACnB,cAAc;QAC7D,MAAMuB,gBAAgBH,WAAWI,QAAQ,CAAC,QAAQ,IAAIJ,WAAWI,QAAQ,CAAC,OAAO,IAAI;QACrF,MAAMC,cAAcC,KAAKC,KAAK,CAAC,AAACP,WAAWZ,MAAM,GAAG,IAAK,KAAKe;QAE9D,IAAIE,cAAczB,aAAa;YAC7B,MAAM,IAAI9B,SAAS,CAAC,iBAAiB,EAAE8B,YAAY,mBAAmB,CAAC,EAAE;QAC3E;IACF;IAEA,MAAMhB,OAAO4C,OAAOC,IAAI,CAACT,YAAY;IAErC,IAAIpC,KAAK8C,QAAQ,CAAC,UAAUT,OAAO,CAAC,OAAO,QAAQD,WAAWC,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
+ {"version":3,"sources":["../../../../src/mcp/builtin/collections/fileInput.ts"],"sourcesContent":["import type { CollectionSlug, File, FileData, PayloadRequest } from 'payload'\n\nimport { APIError } from 'payload'\nimport { getExternalFile, getFileFromUploadInstructions, isURLAllowed } from 'payload/internal'\nimport { sanitizeFilename } from 'payload/shared'\nimport { z } from 'zod'\n\nconst mimeTypeSchema = z\n .string()\n .regex(/^[!#$%&'*+.^`|~\\w-]+\\/[!#$%&'*+.^`|~\\w-]+$/, 'MIME type must use the type/subtype format')\n\nconst uploadFileSchema = z.object({\n filename: z.string(),\n mimeType: z.string(),\n size: z.number().int().nonnegative(),\n uploadReference: z.record(z.string(), z.unknown()),\n})\n\nexport const fileInputSchema = z\n .discriminatedUnion('source', [\n z.object({\n name: z.string().min(1).describe('The file name, including its extension'),\n data: z.string().describe('The base64-encoded file bytes, without a data URL prefix'),\n mimeType: mimeTypeSchema.describe('The file MIME type, for example image/png'),\n source: z.literal('base64'),\n }),\n z.object({\n name: z.string().min(1).describe('Optional file name override').optional(),\n source: z.literal('externalURL'),\n url: z.url().describe('The http or https URL to download'),\n }),\n z.object({\n file: uploadFileSchema.describe('The file value returned by getUploadInstructions'),\n source: z.literal('uploadReference'),\n }),\n ])\n .describe(\n '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.',\n )\n\ntype FileInput = z.infer<typeof fileInputSchema>\n\nexport async function resolveFile({\n collectionSlug,\n input,\n req,\n}: {\n collectionSlug: CollectionSlug\n input?: FileInput\n req: PayloadRequest\n}): Promise<File | undefined> {\n if (!input) {\n return undefined\n }\n\n if (input.source === 'uploadReference') {\n return getFileFromUploadInstructions({ collectionSlug, file: input.file, req })\n }\n\n const uploadConfig = req.payload.collections[collectionSlug]?.config.upload\n\n if (!uploadConfig) {\n throw new APIError(`Collection \"${collectionSlug}\" does not support file uploads.`, 400)\n }\n\n const maxFileSize = req.payload.config.upload.limits?.fileSize\n let file: File\n\n if (input.source === 'base64') {\n const data = decodeBase64({ maxFileSize, value: input.data })\n\n file = {\n name: sanitizeFilename(input.name),\n data,\n mimetype: input.mimeType,\n size: data.length,\n }\n } else {\n if (uploadConfig.pasteURL === false) {\n throw new APIError(\n `Uploading files from URLs is disabled for collection \"${collectionSlug}\".`,\n 400,\n )\n }\n\n const url = new URL(input.url)\n\n if (!['http:', 'https:'].includes(url.protocol)) {\n throw new APIError('File URLs must use http or https.', 400)\n }\n\n if (\n typeof uploadConfig.pasteURL === 'object' &&\n !isURLAllowed(input.url, uploadConfig.pasteURL.allowList)\n ) {\n throw new APIError('The provided file URL is not allowed.', 400)\n }\n\n file = await getExternalFile({\n data: {\n filename: sanitizeFilename(input.name || getURLFilename(url)),\n url: input.url,\n } as FileData,\n req,\n uploadConfig: {\n ...uploadConfig,\n externalFileHeaderFilter: uploadConfig.externalFileHeaderFilter ?? (() => ({})),\n },\n })\n file.mimetype = file.mimetype?.split(';')[0] || 'application/octet-stream'\n file.size = file.data.length\n }\n\n if (maxFileSize !== undefined && Number.isFinite(maxFileSize) && file.size > maxFileSize) {\n throw new APIError(`File exceeds the ${maxFileSize} byte upload limit.`, 400)\n }\n\n return file\n}\n\nfunction decodeBase64({ maxFileSize, value }: { maxFileSize?: number; value: string }): Buffer {\n const normalized = value.replace(/\\s/g, '')\n\n if (!/^[a-z0-9+/]*={0,2}$/i.test(normalized) || normalized.length % 4 === 1) {\n throw new APIError('File data must be valid base64.', 400)\n }\n\n if (maxFileSize !== undefined && Number.isFinite(maxFileSize)) {\n const paddingLength = normalized.endsWith('==') ? 2 : normalized.endsWith('=') ? 1 : 0\n const decodedSize = Math.floor((normalized.length * 3) / 4) - paddingLength\n\n if (decodedSize > maxFileSize) {\n throw new APIError(`File exceeds the ${maxFileSize} byte upload limit.`, 400)\n }\n }\n\n const data = Buffer.from(normalized, 'base64')\n\n if (data.toString('base64').replace(/=+$/, '') !== normalized.replace(/=+$/, '')) {\n throw new APIError('File data must be valid base64.', 400)\n }\n\n return data\n}\n\nfunction getURLFilename(url: URL): string {\n const pathSegment = url.pathname.split('/').pop() || 'upload'\n\n try {\n return decodeURIComponent(pathSegment)\n } catch {\n return pathSegment\n }\n}\n"],"names":["APIError","getExternalFile","getFileFromUploadInstructions","isURLAllowed","sanitizeFilename","z","mimeTypeSchema","string","regex","uploadFileSchema","object","filename","mimeType","size","number","int","nonnegative","uploadReference","record","unknown","fileInputSchema","discriminatedUnion","name","min","describe","data","source","literal","optional","url","file","resolveFile","collectionSlug","input","req","undefined","uploadConfig","payload","collections","config","upload","maxFileSize","limits","fileSize","decodeBase64","value","mimetype","length","pasteURL","URL","includes","protocol","allowList","getURLFilename","externalFileHeaderFilter","split","Number","isFinite","normalized","replace","test","paddingLength","endsWith","decodedSize","Math","floor","Buffer","from","toString","pathSegment","pathname","pop","decodeURIComponent"],"mappings":"AAEA,SAASA,QAAQ,QAAQ,UAAS;AAClC,SAASC,eAAe,EAAEC,6BAA6B,EAAEC,YAAY,QAAQ,mBAAkB;AAC/F,SAASC,gBAAgB,QAAQ,iBAAgB;AACjD,SAASC,CAAC,QAAQ,MAAK;AAEvB,MAAMC,iBAAiBD,EACpBE,MAAM,GACNC,KAAK,CAAC,8CAA8C;AAEvD,MAAMC,mBAAmBJ,EAAEK,MAAM,CAAC;IAChCC,UAAUN,EAAEE,MAAM;IAClBK,UAAUP,EAAEE,MAAM;IAClBM,MAAMR,EAAES,MAAM,GAAGC,GAAG,GAAGC,WAAW;IAClCC,iBAAiBZ,EAAEa,MAAM,CAACb,EAAEE,MAAM,IAAIF,EAAEc,OAAO;AACjD;AAEA,OAAO,MAAMC,kBAAkBf,EAC5BgB,kBAAkB,CAAC,UAAU;IAC5BhB,EAAEK,MAAM,CAAC;QACPY,MAAMjB,EAAEE,MAAM,GAAGgB,GAAG,CAAC,GAAGC,QAAQ,CAAC;QACjCC,MAAMpB,EAAEE,MAAM,GAAGiB,QAAQ,CAAC;QAC1BZ,UAAUN,eAAekB,QAAQ,CAAC;QAClCE,QAAQrB,EAAEsB,OAAO,CAAC;IACpB;IACAtB,EAAEK,MAAM,CAAC;QACPY,MAAMjB,EAAEE,MAAM,GAAGgB,GAAG,CAAC,GAAGC,QAAQ,CAAC,+BAA+BI,QAAQ;QACxEF,QAAQrB,EAAEsB,OAAO,CAAC;QAClBE,KAAKxB,EAAEwB,GAA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S,CAAC,iBAAiB,EAAEyC,YAAY,mBAAmB,CAAC,EAAE;QAC3E;IACF;IAEA,MAAMhB,OAAOyC,OAAOC,IAAI,CAACT,YAAY;IAErC,IAAIjC,KAAK2C,QAAQ,CAAC,UAAUT,OAAO,CAAC,OAAO,QAAQD,WAAWC,OAAO,CAAC,OAAO,KAAK;QAChF,MAAM,IAAI3D,SAAS,mCAAmC;IACxD;IAEA,OAAOyB;AACT;AAEA,SAAS4B,eAAexB,GAAQ;IAC9B,MAAMwC,cAAcxC,IAAIyC,QAAQ,CAACf,KAAK,CAAC,KAAKgB,GAAG,MAAM;IAErD,IAAI;QACF,OAAOC,mBAAmBH;IAC5B,EAAE,OAAM;QACN,OAAOA;IACT;AACF"}
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, it } from 'vitest';
2
- import { fileInputSchema, resolveFileInput } from './fileInput.js';
2
+ import { fileInputSchema, resolveFile } from './fileInput.js';
3
3
  describe('MCP file input', ()=>{
4
4
  it('should reject malformed MIME types', ()=>{
5
5
  const result = fileInputSchema.safeParse({
@@ -10,11 +10,25 @@ describe('MCP file input', ()=>{
10
10
  });
11
11
  expect(result.success).toBe(false);
12
12
  });
13
+ it('should accept a prepared upload', ()=>{
14
+ const result = fileInputSchema.safeParse({
15
+ file: {
16
+ filename: 'image.png',
17
+ mimeType: 'image/png',
18
+ size: 123,
19
+ uploadReference: {
20
+ uploadId: 'upload-id'
21
+ }
22
+ },
23
+ source: 'uploadReference'
24
+ });
25
+ expect(result.success).toBe(true);
26
+ });
13
27
  it('should reject oversized base64 files', async ()=>{
14
28
  const req = createRequest({
15
29
  maxFileSize: 4
16
30
  });
17
- await expect(resolveFileInput({
31
+ await expect(resolveFile({
18
32
  collectionSlug: 'media',
19
33
  input: {
20
34
  data: Buffer.from('hello').toString('base64'),
@@ -34,10 +48,10 @@ describe('MCP file input', ()=>{
34
48
  }
35
49
  ]
36
50
  });
37
- await expect(resolveFileInput({
51
+ await expect(resolveFile({
38
52
  collectionSlug: 'media',
39
53
  input: {
40
- source: 'url',
54
+ source: 'externalURL',
41
55
  url: 'https://example.com/image.png'
42
56
  },
43
57
  req
@@ -1 +1 @@
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
+ {"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, resolveFile } 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 accept a prepared upload', () => {\n const result = fileInputSchema.safeParse({\n file: {\n filename: 'image.png',\n mimeType: 'image/png',\n size: 123,\n uploadReference: { uploadId: 'upload-id' },\n },\n source: 'uploadReference',\n })\n\n expect(result.success).toBe(true)\n })\n\n it('should reject oversized base64 files', async () => {\n const req = createRequest({ maxFileSize: 4 })\n\n await expect(\n resolveFile({\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 resolveFile({\n collectionSlug: 'media',\n input: {\n source: 'externalURL',\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","resolveFile","result","safeParse","data","mimeType","name","source","success","toBe","file","filename","size","uploadReference","uploadId","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,WAAW,QAAQ,iBAAgB;AAE7DJ,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,mCAAmC;QACpC,MAAMG,SAASF,gBAAgBG,SAAS,CAAC;YACvCO,MAAM;gBACJC,UAAU;gBACVN,UAAU;gBACVO,MAAM;gBACNC,iBAAiB;oBAAEC,UAAU;gBAAY;YAC3C;YACAP,QAAQ;QACV;QAEAT,OAAOI,OAAOM,OAAO,EAAEC,IAAI,CAAC;IAC9B;IAEAV,GAAG,wCAAwC;QACzC,MAAMgB,MAAMC,cAAc;YAAEC,aAAa;QAAE;QAE3C,MAAMnB,OACJG,YAAY;YACViB,gBAAgB;YAChBC,OAAO;gBACLf,MAAMgB,OAAOC,IAAI,CAAC,SAASC,QAAQ,CAAC;gBACpCjB,UAAU;gBACVC,MAAM;gBACNC,QAAQ;YACV;YACAQ;QACF,IACAQ,OAAO,CAACC,OAAO,CAAC;IACpB;IAEAzB,GAAG,uDAAuD;QACxD,MAAMgB,MAAMC,cAAc;YACxBS,WAAW;gBAAC;oBAAEC,UAAU;oBAAsBC,UAAU;gBAAQ;aAAE;QACpE;QAEA,MAAM7B,OACJG,YAAY;YACViB,gBAAgB;YAChBC,OAAO;gBACLZ,QAAQ;gBACRqB,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 +1 @@
1
- {"version":3,"file":"getCollectionSchemaTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/getCollectionSchemaTool.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,uBAAuB,4CAqElC,CAAA"}
1
+ {"version":3,"file":"getCollectionSchemaTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/getCollectionSchemaTool.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,uBAAuB,4CAyElC,CAAA"}
@@ -58,9 +58,10 @@ export const getCollectionSchemaTool = defineCollectionTool({
58
58
  ],
59
59
  sources: [
60
60
  ...uploadConfig.pasteURL !== false ? [
61
- 'url'
61
+ 'externalURL'
62
62
  ] : [],
63
- 'base64'
63
+ 'base64',
64
+ 'uploadReference'
64
65
  ],
65
66
  ...typeof maxFileSize === 'number' && Number.isFinite(maxFileSize) ? {
66
67
  maxFileSize
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/mcp/builtin/collections/getCollectionSchemaTool.ts"],"sourcesContent":["import { getAccessResults } from 'payload'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getCollectionInputSchema } from '../../../utils/schemaConversion/getEntityInputSchema.js'\n\nexport const getCollectionSchemaTool = defineCollectionTool({\n access: (args) => {\n const permissions = args.permissions?.collections?.[args.collectionSlug]\n\n return defaultAccess(args) && Boolean(permissions?.create || permissions?.update)\n },\n annotations: {\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n readOnlyHint: true,\n title: 'Get Collection Schema',\n },\n description: 'Get the input schema for creating or updating documents in a collection.',\n}).handler(async ({ authorizedMCP, collectionSlug, req }) => {\n const permissions = authorizedMCP.overrideAccess\n ? null\n : (await getAccessResults({ req })).collections?.[collectionSlug]\n\n if (!authorizedMCP.overrideAccess && !permissions?.create && !permissions?.update) {\n return {\n content: [\n {\n type: 'text',\n text: `Error: MCP access to \"getCollectionSchema\" is not enabled for collection \"${collectionSlug}\"`,\n },\n ],\n isError: true,\n }\n }\n\n const inputSchema = getCollectionInputSchema({\n collectionSlug,\n req,\n ...(permissions ? { permissions } : {}),\n })\n\n if (!inputSchema) {\n return {\n content: [{ type: 'text', text: `Error: Collection \"${collectionSlug}\" not found` }],\n isError: true,\n }\n }\n\n const uploadConfig = req.payload.collections[collectionSlug]?.config.upload\n const maxFileSize = req.payload.config.upload.limits?.fileSize\n const upload = uploadConfig\n ? {\n enabled: true,\n filesRequiredOnCreate: uploadConfig.filesRequiredOnCreate !== false,\n mimeTypes: uploadConfig.mimeTypes ?? ['*/*'],\n sources: [...(uploadConfig.pasteURL !== false ? ['url'] : []), 'base64'],\n ...(typeof maxFileSize === 'number' && Number.isFinite(maxFileSize) ? { maxFileSize } : {}),\n }\n : { enabled: false }\n\n return {\n content: [\n {\n type: 'text',\n text: `Schema for collection \"${collectionSlug}\":\\n\\`\\`\\`json\\n${JSON.stringify(inputSchema)}\\n\\`\\`\\`\\nUpload configuration:\\n\\`\\`\\`json\\n${JSON.stringify(upload)}\\n\\`\\`\\``,\n },\n ],\n structuredContent: {\n collectionSlug,\n schema: inputSchema,\n upload,\n },\n }\n})\n"],"names":["getAccessResults","defaultAccess","defineCollectionTool","getCollectionInputSchema","getCollectionSchemaTool","access","args","permissions","collections","collectionSlug","Boolean","create","update","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","handler","authorizedMCP","req","overrideAccess","content","type","text","isError","inputSchema","uploadConfig","payload","config","upload","maxFileSize","limits","fileSize","enabled","filesRequiredOnCreate","mimeTypes","sources","pasteURL","Number","isFinite","JSON","stringify","structuredContent","schema"],"mappings":"AAAA,SAASA,gBAAgB,QA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M,EAAEC;IACtD,MAAMH,SAASH,eACX;QACEO,SAAS;QACTC,uBAAuBR,aAAaQ,qBAAqB,KAAK;QAC9DC,WAAWT,aAAaS,SAAS,IAAI;YAAC;SAAM;QAC5CC,SAAS;eAAKV,aAAaW,QAAQ,KAAK,QAAQ;gBAAC;aAAM,GAAG,EAAE;YAAG;SAAS;QACxE,GAAI,OAAOP,gBAAgB,YAAYQ,OAAOC,QAAQ,CAACT,eAAe;YAAEA;QAAY,IAAI,CAAC,CAAC;IAC5F,IACA;QAAEG,SAAS;IAAM;IAErB,OAAO;QACLZ,SAAS;YACP;gBACEC,MAAM;gBACNC,MAAM,CAAC,uBAAuB,EAAEjB,eAAe,gBAAgB,EAAEkC,KAAKC,SAAS,CAAChB,aAAa,6CAA6C,EAAEe,KAAKC,SAAS,CAACZ,QAAQ,QAAQ,CAAC;YAC9K;SACD;QACDa,mBAAmB;YACjBpC;YACAqC,QAAQlB;YACRI;QACF;IACF;AACF,GAAE"}
1
+ {"version":3,"sources":["../../../../src/mcp/builtin/collections/getCollectionSchemaTool.ts"],"sourcesContent":["import { getAccessResults } from 'payload'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getCollectionInputSchema } from '../../../utils/schemaConversion/getEntityInputSchema.js'\n\nexport const getCollectionSchemaTool = defineCollectionTool({\n access: (args) => {\n const permissions = args.permissions?.collections?.[args.collectionSlug]\n\n return defaultAccess(args) && Boolean(permissions?.create || permissions?.update)\n },\n annotations: {\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n readOnlyHint: true,\n title: 'Get Collection Schema',\n },\n description: 'Get the input schema for creating or updating documents in a collection.',\n}).handler(async ({ authorizedMCP, collectionSlug, req }) => {\n const permissions = authorizedMCP.overrideAccess\n ? null\n : (await getAccessResults({ req })).collections?.[collectionSlug]\n\n if (!authorizedMCP.overrideAccess && !permissions?.create && !permissions?.update) {\n return {\n content: [\n {\n type: 'text',\n text: `Error: MCP access to \"getCollectionSchema\" is not enabled for collection \"${collectionSlug}\"`,\n },\n ],\n isError: true,\n }\n }\n\n const inputSchema = getCollectionInputSchema({\n collectionSlug,\n req,\n ...(permissions ? { permissions } : {}),\n })\n\n if (!inputSchema) {\n return {\n content: [{ type: 'text', text: `Error: Collection \"${collectionSlug}\" not found` }],\n isError: true,\n }\n }\n\n const uploadConfig = req.payload.collections[collectionSlug]?.config.upload\n const maxFileSize = req.payload.config.upload.limits?.fileSize\n const upload = uploadConfig\n ? {\n enabled: true,\n filesRequiredOnCreate: uploadConfig.filesRequiredOnCreate !== false,\n mimeTypes: uploadConfig.mimeTypes ?? ['*/*'],\n sources: [\n ...(uploadConfig.pasteURL !== false ? ['externalURL'] : []),\n 'base64',\n 'uploadReference',\n ],\n ...(typeof maxFileSize === 'number' && Number.isFinite(maxFileSize) ? { maxFileSize } : {}),\n }\n : { enabled: false }\n\n return {\n content: [\n {\n type: 'text',\n text: `Schema for collection \"${collectionSlug}\":\\n\\`\\`\\`json\\n${JSON.stringify(inputSchema)}\\n\\`\\`\\`\\nUpload configuration:\\n\\`\\`\\`json\\n${JSON.stringify(upload)}\\n\\`\\`\\``,\n },\n ],\n structuredContent: {\n collectionSlug,\n schema: inputSchema,\n upload,\n },\n }\n})\n"],"names":["getAccessResults","defaultAccess","defineCollectionTool","getCollectionInputSchema","getCollectionSchemaTool","access","args","permissions","collections","collectionSlug","Boolean","create","update","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","handler","authorizedMCP","req","overrideAccess","content","type","text","isError","inputSchema","uploadConfig","payload","config","upload","maxFileSize","limits","fileSize","enabled","filesRequiredOnCreate","mimeTypes","sources","pasteURL","Number","isFinite","JSON","stringify","structuredContent","schema"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,UAAS;AAE1C,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,wBAAwB,QAAQ,0DAAyD;AAElG,O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AAM;QAC5CC,SAAS;eACHV,aAAaW,QAAQ,KAAK,QAAQ;gBAAC;aAAc,GAAG,EAAE;YAC1D;YACA;SACD;QACD,GAAI,OAAOP,gBAAgB,YAAYQ,OAAOC,QAAQ,CAACT,eAAe;YAAEA;QAAY,IAAI,CAAC,CAAC;IAC5F,IACA;QAAEG,SAAS;IAAM;IAErB,OAAO;QACLZ,SAAS;YACP;gBACEC,MAAM;gBACNC,MAAM,CAAC,uBAAuB,EAAEjB,eAAe,gBAAgB,EAAEkC,KAAKC,SAAS,CAAChB,aAAa,6CAA6C,EAAEe,KAAKC,SAAS,CAACZ,QAAQ,QAAQ,CAAC;YAC9K;SACD;QACDa,mBAAmB;YACjBpC;YACAqC,QAAQlB;YACRI;QACF;IACF;AACF,GAAE"}
@@ -7,9 +7,9 @@ import { getCollectionInputSchema } from '../../../utils/schemaConversion/getEnt
7
7
  import { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js';
8
8
  import { whereSchema } from '../../../utils/whereSchema.js';
9
9
  import { validateCollectionData } from '../validateEntityData.js';
10
- import { fileInputSchema, resolveFileInput } from './fileInput.js';
10
+ import { fileInputSchema, resolveFile } from './fileInput.js';
11
11
  import { formatCollectionError } from './formatCollectionError.js';
12
- const DEFAULT_DESCRIPTION = 'Update documents in any collection by passing the collection slug and data.';
12
+ const DEFAULT_DESCRIPTION = 'Update documents in any collection. Files can use a URL, base64, or an upload prepared by getUploadInstructions.';
13
13
  export const updateDocumentTool = defineCollectionTool({
14
14
  access: (args)=>defaultAccess(args) && Boolean(args.permissions?.collections?.[args.collectionSlug]?.update),
15
15
  annotations: {
@@ -67,7 +67,7 @@ export const updateDocumentTool = defineCollectionTool({
67
67
  return validationError;
68
68
  }
69
69
  const parsedData = transformPointDataToPayload(inputData);
70
- const file = await resolveFileInput({
70
+ const file = await resolveFile({
71
71
  collectionSlug,
72
72
  input: fileInput,
73
73
  req
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/mcp/builtin/collections/updateTool.ts"],"sourcesContent":["import type { SelectType, Where } from 'payload'\n\nimport { z } from 'zod'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\nimport {\n getCollectionVirtualFieldNames,\n stripVirtualFields,\n} from '../../../utils/getVirtualFieldNames.js'\nimport { getCollectionInputSchema } from '../../../utils/schemaConversion/getEntityInputSchema.js'\nimport { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'\nimport { whereSchema } from '../../../utils/whereSchema.js'\nimport { validateCollectionData } from '../validateEntityData.js'\nimport { fileInputSchema, resolveFileInput } from './fileInput.js'\nimport { formatCollectionError } from './formatCollectionError.js'\n\nconst DEFAULT_DESCRIPTION =\n 'Update documents in any collection by passing the collection slug and data.'\n\nexport const updateDocumentTool = defineCollectionTool({\n access: (args) =>\n defaultAccess(args) && Boolean(args.permissions?.collections?.[args.collectionSlug]?.update),\n annotations: {\n destructiveHint: true,\n idempotentHint: false,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'Update Document',\n },\n description: DEFAULT_DESCRIPTION,\n input: z.object({\n id: z.union([z.string(), z.number()]).describe('The ID of the document to update').optional(),\n data: z\n .record(z.string(), z.unknown())\n .describe(\n 'The fields to update. Only include fields permitted by the schema returned by getCollectionSchema.',\n ),\n depth: z\n .number()\n .describe('How many levels deep to populate relationships')\n .optional()\n .default(0),\n draft: z\n .boolean()\n .describe(\n '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.',\n )\n .optional()\n .default(false),\n fallbackLocale: z\n .string()\n .describe('Optional: fallback locale code to use when requested locale is not available')\n .optional(),\n file: fileInputSchema.optional(),\n locale: z\n .string()\n .describe(\n 'Optional: locale code to update the document in (e.g., \"en\", \"es\"). Defaults to the default locale',\n )\n .optional(),\n overrideLock: z\n .boolean()\n .describe('Whether to override document locks')\n .optional()\n .default(true),\n overwriteExistingFiles: z\n .boolean()\n .describe('Whether to overwrite existing files')\n .optional()\n .default(false),\n publishAllLocales: z\n .boolean()\n .describe(\n 'For collections with localized publishing status, whether publishing should affect every locale. Set false with locale to publish only that locale.',\n )\n .optional(),\n select: z\n .record(z.string(), z.unknown())\n .describe(\n 'Optional: define exactly which fields you\\'d like to return in the response, e.g., {\"title\": true}',\n )\n .optional(),\n where: whereSchema\n .describe(\n 'Where clause to update multiple documents. Use field names with Payload operators, and/or arrays for grouping. Example: {\"title\":{\"contains\":\"test\"}}',\n )\n .optional(),\n }),\n}).handler(async ({ authorizedMCP, collectionSlug, input, req }) => {\n const payload = req.payload\n const logger = getLogger({ payload })\n\n const {\n id,\n data,\n depth,\n draft,\n fallbackLocale,\n file: fileInput,\n locale,\n overrideLock,\n overwriteExistingFiles,\n publishAllLocales,\n select,\n where,\n } = input\n\n logger.info(\n `Updating document in collection: ${collectionSlug}${id ? ` with ID: ${id}` : ' with where clause'}, draft: ${draft}${locale ? `, locale: ${locale}` : ''}`,\n )\n\n try {\n if (!id && !where) {\n return {\n content: [{ type: 'text', text: 'Error: Either id or where clause must be provided' }],\n }\n }\n\n const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, collectionSlug)\n const inputData = stripVirtualFields(data, virtualFieldNames)\n const validationError = validateCollectionData({\n collectionSlug,\n data: inputData,\n partial: true,\n req,\n })\n\n if (validationError) {\n return validationError\n }\n\n const parsedData = transformPointDataToPayload(inputData)\n const file = await resolveFileInput({ collectionSlug, input: fileInput, req })\n\n const whereClause: Where = where ?? {}\n\n if (id) {\n const result = await payload.update({\n id,\n collection: collectionSlug,\n data: parsedData,\n depth,\n draft,\n overrideAccess: authorizedMCP.overrideAccess,\n overrideLock,\n req,\n ...(file ? { file } : {}),\n ...(overwriteExistingFiles ? { overwriteExistingFiles } : {}),\n ...(publishAllLocales !== undefined ? { publishAllLocales } : {}),\n ...(locale ? { locale } : {}),\n ...(fallbackLocale ? { fallbackLocale } : {}),\n ...(select ? { select: select as SelectType } : {}),\n })\n\n return {\n content: [\n {\n type: 'text',\n text: `Document updated successfully in collection \"${collectionSlug}\"!\\nUpdated document:\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as Record<string, unknown>,\n }\n }\n\n const result = await payload.update({\n collection: collectionSlug,\n data: parsedData,\n depth,\n draft,\n overrideAccess: authorizedMCP.overrideAccess,\n overrideLock,\n req,\n where: whereClause,\n ...(file ? { file } : {}),\n ...(overwriteExistingFiles ? { overwriteExistingFiles } : {}),\n ...(publishAllLocales !== undefined ? { publishAllLocales } : {}),\n ...(locale ? { locale } : {}),\n ...(fallbackLocale ? { fallbackLocale } : {}),\n ...(select ? { select: select as SelectType } : {}),\n })\n\n const docs = result.docs || []\n const errors = result.errors || []\n\n let responseText = `Multiple documents updated in collection \"${collectionSlug}\"!\\nUpdated: ${docs.length} documents\\nErrors: ${errors.length}\\n---`\n if (docs.length > 0) {\n responseText += `\\n\\nUpdated documents:\\n\\`\\`\\`json\\n${JSON.stringify(docs)}\\n\\`\\`\\``\n }\n if (errors.length > 0) {\n responseText += `\\n\\nErrors:\\n\\`\\`\\`json\\n${JSON.stringify(errors)}\\n\\`\\`\\``\n\n const errorSchema = getCollectionInputSchema({ collectionSlug, req })\n\n if (errorSchema) {\n responseText += `\\n\\nUse this schema for data:\\n\\`\\`\\`json\\n${JSON.stringify(errorSchema)}\\n\\`\\`\\``\n }\n\n return {\n content: [{ type: 'text', text: responseText }],\n doc: { docs, errors } as unknown as Record<string, unknown>,\n isError: true,\n ...(errorSchema\n ? {\n structuredContent: {\n collectionSlug,\n docs,\n errors,\n schema: errorSchema,\n },\n }\n : {}),\n }\n }\n\n return {\n content: [{ type: 'text', text: responseText }],\n doc: { docs, errors } as unknown as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error updating document in ${collectionSlug}: ${errorMessage}`)\n return formatCollectionError({ action: 'updating', collectionSlug, error, req })\n }\n})\n"],"names":["z","defaultAccess","defineCollectionTool","getLogger","getCollectionVirtualFieldNames","stripVirtualFields","getCollectionInputSchema","transformPointDataToPayload","whereSchema","validateCollectionData","fileInputSchema","resolveFileInput","formatCollectionError","DEFAULT_DESCRIPTION","updateDocumentTool","access","args","Boolean","permissions","collections","collectionSlug","update","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","object","id","union","string","number","describe","optional","data","record","unknown","depth","default","draft","boolean","fallbackLocale","file","locale","overrideLock","overwriteExistingFiles","publishAllLocales","select","where","handler","authorizedMCP","req","payload","logger","fileInput","info","content","type","text","virtualFieldNames","config","inputData","validationError","partial","parsedData","whereClause","result","collection","overrideAccess","undefined","JSON","stringify","doc","docs","errors","responseText","length","errorSchema","isError","structuredContent","schema","error","errorMessage","Error","message","action"],"mappings":"AAEA,SAASA,CAAC,QAAQ,MAAK;AAEvB,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AACvD,SACEC,8BAA8B,EAC9BC,kBAAkB,QACb,yCAAwC;AAC/C,SAASC,wBAAwB,QAAQ,0DAAyD;AAClG,SAASC,2BAA2B,QAAQ,gDAA+C;AAC3F,SAASC,WAAW,QAAQ,gCAA+B;AAC3D,SAASC,sBAAsB,QAAQ,2BAA0B;AACjE,SAASC,eAAe,EAAEC,gBAAgB,QAAQ,iBAAgB;AAClE,SAASC,qBAAqB,QAAQ,6BAA4B;AAElE,MAAMC,sBACJ;AAEF,OAAO,MAAMC,qBAAqBZ,qBAAqB;IACrDa,QAAQ,CAACC,OACPf,cAAce,SAASC,QAAQD,KAAKE,WAAW,EAAEC,aAAa,CAACH,KAAKI,cAAc,CAAC,EAAEC;IACvFC,aAAa;QACXC,iBAAiB;QACjBC,gBAAgB;QAChBC,eAAe;QACfC,cAAc;QACdC,OAAO;IACT;IACAC,aAAaf;IACbgB,OAAO7B,EAAE8B,MAAM,CAAC;QAC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YAEnE,IAAI0B,aAAa;gBACfF,gBAAgB,CAAC,2CAA2C,EAAEL,KAAKC,SAAS,CAACM,aAAa,QAAQ,CAAC;YACrG;YAEA,OAAO;gBACLrB,SAAS;oBAAC;wBAAEC,MAAM;wBAAQC,MAAMiB;oBAAa;iBAAE;gBAC/CH,KAAK;oBAAEC;oBAAMC;gBAAO;gBACpBI,SAAS;gBACT,GAAID,cACA;oBACEE,mBAAmB;wBACjB9D;wBACAwD;wBACAC;wBACAM,QAAQH;oBACV;gBACF,IACA,CAAC,CAAC;YACR;QACF;QAEA,OAAO;YACLrB,SAAS;gBAAC;oBAAEC,MAAM;oBAAQC,MAAMiB;gBAAa;aAAE;YAC/CH,KAAK;gBAAEC;gBAAMC;YAAO;QACtB;IACF,EAAE,OAAOO,OAAO;QACd,MAAMC,eAAeD,iBAAiBE,QAAQF,MAAMG,OAAO,GAAG;QAC9D/B,OAAO4B,KAAK,CAAC,CAAC,2BAA2B,EAAEhE,eAAe,EAAE,EAAEiE,cAAc;QAC5E,OAAOzE,sBAAsB;YAAE4E,QAAQ;YAAYpE;YAAgBgE;YAAO9B;QAAI;IAChF;AACF,GAAE"}
1
+ {"version":3,"sources":["../../../../src/mcp/builtin/collections/updateTool.ts"],"sourcesContent":["import type { SelectType, Where } from 'payload'\n\nimport { z } from 'zod'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\nimport {\n getCollectionVirtualFieldNames,\n stripVirtualFields,\n} from '../../../utils/getVirtualFieldNames.js'\nimport { getCollectionInputSchema } from '../../../utils/schemaConversion/getEntityInputSchema.js'\nimport { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'\nimport { whereSchema } from '../../../utils/whereSchema.js'\nimport { validateCollectionData } from '../validateEntityData.js'\nimport { fileInputSchema, resolveFile } from './fileInput.js'\nimport { formatCollectionError } from './formatCollectionError.js'\n\nconst DEFAULT_DESCRIPTION =\n 'Update documents in any collection. Files can use a URL, base64, or an upload prepared by getUploadInstructions.'\n\nexport const updateDocumentTool = defineCollectionTool({\n access: (args) =>\n defaultAccess(args) && Boolean(args.permissions?.collections?.[args.collectionSlug]?.update),\n annotations: {\n destructiveHint: true,\n idempotentHint: false,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'Update Document',\n },\n description: DEFAULT_DESCRIPTION,\n input: z.object({\n id: z.union([z.string(), z.number()]).describe('The ID of the document to update').optional(),\n data: z\n .record(z.string(), z.unknown())\n .describe(\n 'The fields to update. Only include fields permitted by the schema returned by getCollectionSchema.',\n ),\n depth: z\n .number()\n .describe('How many levels deep to populate relationships')\n .optional()\n .default(0),\n draft: z\n .boolean()\n .describe(\n '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.',\n )\n .optional()\n .default(false),\n fallbackLocale: z\n .string()\n .describe('Optional: fallback locale code to use when requested locale is not available')\n .optional(),\n file: fileInputSchema.optional(),\n locale: z\n .string()\n .describe(\n 'Optional: locale code to update the document in (e.g., \"en\", \"es\"). Defaults to the default locale',\n )\n .optional(),\n overrideLock: z\n .boolean()\n .describe('Whether to override document locks')\n .optional()\n .default(true),\n overwriteExistingFiles: z\n .boolean()\n .describe('Whether to overwrite existing files')\n .optional()\n .default(false),\n publishAllLocales: z\n .boolean()\n .describe(\n 'For collections with localized publishing status, whether publishing should affect every locale. Set false with locale to publish only that locale.',\n )\n .optional(),\n select: z\n .record(z.string(), z.unknown())\n .describe(\n 'Optional: define exactly which fields you\\'d like to return in the response, e.g., {\"title\": true}',\n )\n .optional(),\n where: whereSchema\n .describe(\n 'Where clause to update multiple documents. Use field names with Payload operators, and/or arrays for grouping. Example: {\"title\":{\"contains\":\"test\"}}',\n )\n .optional(),\n }),\n}).handler(async ({ authorizedMCP, collectionSlug, input, req }) => {\n const payload = req.payload\n const logger = getLogger({ payload })\n\n const {\n id,\n data,\n depth,\n draft,\n fallbackLocale,\n file: fileInput,\n locale,\n overrideLock,\n overwriteExistingFiles,\n publishAllLocales,\n select,\n where,\n } = input\n\n logger.info(\n `Updating document in collection: ${collectionSlug}${id ? ` with ID: ${id}` : ' with where clause'}, draft: ${draft}${locale ? `, locale: ${locale}` : ''}`,\n )\n\n try {\n if (!id && !where) {\n return {\n content: [{ type: 'text', text: 'Error: Either id or where clause must be provided' }],\n }\n }\n\n const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, collectionSlug)\n const inputData = stripVirtualFields(data, virtualFieldNames)\n const validationError = validateCollectionData({\n collectionSlug,\n data: inputData,\n partial: true,\n req,\n })\n\n if (validationError) {\n return validationError\n }\n\n const parsedData = transformPointDataToPayload(inputData)\n const file = await resolveFile({ collectionSlug, input: fileInput, req })\n\n const whereClause: Where = where ?? {}\n\n if (id) {\n const result = await payload.update({\n id,\n collection: collectionSlug,\n data: parsedData,\n depth,\n draft,\n overrideAccess: authorizedMCP.overrideAccess,\n overrideLock,\n req,\n ...(file ? { file } : {}),\n ...(overwriteExistingFiles ? { overwriteExistingFiles } : {}),\n ...(publishAllLocales !== undefined ? { publishAllLocales } : {}),\n ...(locale ? { locale } : {}),\n ...(fallbackLocale ? { fallbackLocale } : {}),\n ...(select ? { select: select as SelectType } : {}),\n })\n\n return {\n content: [\n {\n type: 'text',\n text: `Document updated successfully in collection \"${collectionSlug}\"!\\nUpdated document:\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as Record<string, unknown>,\n }\n }\n\n const result = await payload.update({\n collection: collectionSlug,\n data: parsedData,\n depth,\n draft,\n overrideAccess: authorizedMCP.overrideAccess,\n overrideLock,\n req,\n where: whereClause,\n ...(file ? { file } : {}),\n ...(overwriteExistingFiles ? { overwriteExistingFiles } : {}),\n ...(publishAllLocales !== undefined ? { publishAllLocales } : {}),\n ...(locale ? { locale } : {}),\n ...(fallbackLocale ? { fallbackLocale } : {}),\n ...(select ? { select: select as SelectType } : {}),\n })\n\n const docs = result.docs || []\n const errors = result.errors || []\n\n let responseText = `Multiple documents updated in collection \"${collectionSlug}\"!\\nUpdated: ${docs.length} documents\\nErrors: ${errors.length}\\n---`\n if (docs.length > 0) {\n responseText += `\\n\\nUpdated documents:\\n\\`\\`\\`json\\n${JSON.stringify(docs)}\\n\\`\\`\\``\n }\n if (errors.length > 0) {\n responseText += `\\n\\nErrors:\\n\\`\\`\\`json\\n${JSON.stringify(errors)}\\n\\`\\`\\``\n\n const errorSchema = getCollectionInputSchema({ collectionSlug, req })\n\n if (errorSchema) {\n responseText += `\\n\\nUse this schema for data:\\n\\`\\`\\`json\\n${JSON.stringify(errorSchema)}\\n\\`\\`\\``\n }\n\n return {\n content: [{ type: 'text', text: responseText }],\n doc: { docs, errors } as unknown as Record<string, unknown>,\n isError: true,\n ...(errorSchema\n ? {\n structuredContent: {\n collectionSlug,\n docs,\n errors,\n schema: errorSchema,\n },\n }\n : {}),\n }\n }\n\n return {\n content: [{ type: 'text', text: responseText }],\n doc: { docs, errors } as unknown as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error updating document in ${collectionSlug}: ${errorMessage}`)\n return formatCollectionError({ action: 'updating', collectionSlug, error, req })\n }\n})\n"],"names":["z","defaultAccess","defineCollectionTool","getLogger","getCollectionVirtualFieldNames","stripVirtualFields","getCollectionInputSchema","transformPointDataToPayload","whereSchema","validateCollectionData","fileInputSchema","resolveFile","formatCollectionError","DEFAULT_DESCRIPTION","updateDocumentTool","access","args","Boolean","permissions","collections","collectionSlug","update","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","object","id","union","string","number","describe","optional","data","record","unknown","depth","default","draft","boolean","fallbackLocale","file","locale","overrideLock","overwriteExistingFiles","publishAllLocales","select","where","handler","authorizedMCP","req","payload","logger","fileInput","info","content","type","text","virtualFieldNames","config","inputData","validationError","partial","parsedData","whereClause","result","collection","overrideAccess","undefined","JSON","stringify","doc","docs","errors","responseText","length","errorSchema","isError","structuredContent","schema","error","errorMessage","Error","message","action"],"mappings":"AAEA,SAASA,CAAC,QAAQ,MAAK;AAEvB,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AACvD,SACEC,8BAA8B,EAC9BC,kBAAkB,QACb,yCAAwC;AAC/C,SAASC,wBAAwB,QAAQ,0DAAyD;AAClG,SAASC,2BAA2B,QAAQ,gDAA+C;AAC3F,SAASC,WAAW,QAAQ,gCAA+B;AAC3D,SAASC,sBAAsB,QAAQ,2BAA0B;AACjE,SAASC,eAAe,EAAEC,WAAW,QAAQ,iBAAgB;AAC7D,SAASC,qBAAqB,QAAQ,6BAA4B;AAElE,MAAMC,sBACJ;AAEF,OAAO,MAAMC,qBAAqBZ,qBAAqB;IACrDa,QAAQ,CAACC,OACPf,cAAce,SAASC,QAAQD,KAAKE,WAAW,EAAEC,aAAa,CAACH,KAAKI,cAAc,CAAC,EAAEC;IACvFC,aAAa;QACXC,iBAAiB;QACjBC,gBAAgB;QAChBC,eAAe;QACfC,cAAc;QACdC,OAAO;IACT;IACAC,aAAaf;IACbgB,OAAO7B,EAAE8B,MAAM,CAAC;QACdC,IAAI/B,EAAEgC,KAAK,CAAC;YAAChC,EAAEiC,MAAM;YAAIjC,EAAEkC,MAAM;SAAG,EAAEC,QAAQ,CAAC,oCAAoCC,QAAQ;QAC3FC,MAAMrC,EACHsC,MAAM,CAACtC,EAAEiC,MAAM,IAAIjC,EAAEuC,OAAO,IAC5BJ,QAAQ,CACP;QAEJK,OAAOxC,EACJkC,MAAM,GACNC,QAAQ,CAAC,kDACTC,QAAQ,GACRK,OAAO,CAAC;QACXC,OAAO1C,EACJ2C,OAAO,GACPR,QAAQ,CACP,+LAEDC,QAAQ,GACRK,OAAO,CAAC;QACXG,gBAAgB5C,EACbiC,MAAM,GACNE,QAAQ,CAAC,gFACTC,QAAQ;QACXS,MAAMnC,gBA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QACtB;IACF,EAAE,OAAOO,OAAO;QACd,MAAMC,eAAeD,iBAAiBE,QAAQF,MAAMG,OAAO,GAAG;QAC9D/B,OAAO4B,KAAK,CAAC,CAAC,2BAA2B,EAAEhE,eAAe,EAAE,EAAEiE,cAAc;QAC5E,OAAOzE,sBAAsB;YAAE4E,QAAQ;YAAYpE;YAAgBgE;YAAO9B;QAAI;IAChF;AACF,GAAE"}
@@ -0,0 +1,2 @@
1
+ export declare const getUploadInstructionsTool: import("../../../types.js").CollectionTool;
2
+ //# sourceMappingURL=uploadInstructionsTool.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"uploadInstructionsTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/uploadInstructionsTool.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,yBAAyB,4CAyDpC,CAAA"}
@@ -0,0 +1,55 @@
1
+ import { getUploadInstructions as getPayloadUploadInstructions } from 'payload/internal';
2
+ import { z } from 'zod';
3
+ import { defaultAccess } from '../../../defaultAccess.js';
4
+ import { defineCollectionTool } from '../../../defineTool.js';
5
+ export const getUploadInstructionsTool = defineCollectionTool({
6
+ access: (args)=>defaultAccess(args) && Boolean(args.permissions?.collections?.[args.collectionSlug]?.create || args.permissions?.collections?.[args.collectionSlug]?.update),
7
+ annotations: {
8
+ destructiveHint: false,
9
+ idempotentHint: false,
10
+ openWorldHint: true,
11
+ readOnlyHint: false,
12
+ title: 'Get Upload Instructions'
13
+ },
14
+ description: 'Prepare a file upload before createDocument or updateDocument. Pass file metadata only, without base64 or file contents.',
15
+ input: z.object({
16
+ docPrefix: z.string().describe('Optional document folder or prefix').optional(),
17
+ filename: z.string().describe('The original file name'),
18
+ filesize: z.number().int().nonnegative().describe('The file size in bytes'),
19
+ mimeType: z.string().describe('The file MIME type')
20
+ })
21
+ }).handler(async ({ authorizedMCP, collectionSlug, input, req })=>{
22
+ try {
23
+ const instructions = await getPayloadUploadInstructions({
24
+ ...input,
25
+ collectionSlug,
26
+ overrideAccess: authorizedMCP.overrideAccess,
27
+ req
28
+ });
29
+ const nextStep = instructions.type === 'http' ? 'Send the exact file bytes using request, then pass { source: "uploadReference", file } to createDocument or updateDocument.' : `Call the local MCP tool named "${instructions.name}" with the file and data, then pass { source: "uploadReference", file } to createDocument or updateDocument.`;
30
+ return {
31
+ content: [
32
+ {
33
+ type: 'text',
34
+ text: `Upload instructions for collection "${collectionSlug}":\n\`\`\`json\n${JSON.stringify(instructions)}\n\`\`\`\n${nextStep}`
35
+ }
36
+ ],
37
+ structuredContent: {
38
+ instructions
39
+ }
40
+ };
41
+ } catch (error) {
42
+ const message = error instanceof Error ? error.message : 'Unknown error';
43
+ return {
44
+ content: [
45
+ {
46
+ type: 'text',
47
+ text: `Error getting upload instructions for collection "${collectionSlug}": ${message}`
48
+ }
49
+ ],
50
+ isError: true
51
+ };
52
+ }
53
+ });
54
+
55
+ //# sourceMappingURL=uploadInstructionsTool.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/mcp/builtin/collections/uploadInstructionsTool.ts"],"sourcesContent":["import { getUploadInstructions as getPayloadUploadInstructions } from 'payload/internal'\nimport { z } from 'zod'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\n\nexport const getUploadInstructionsTool = defineCollectionTool({\n access: (args) =>\n defaultAccess(args) &&\n Boolean(\n args.permissions?.collections?.[args.collectionSlug]?.create ||\n args.permissions?.collections?.[args.collectionSlug]?.update,\n ),\n annotations: {\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: true,\n readOnlyHint: false,\n title: 'Get Upload Instructions',\n },\n description:\n 'Prepare a file upload before createDocument or updateDocument. Pass file metadata only, without base64 or file contents.',\n input: z.object({\n docPrefix: z.string().describe('Optional document folder or prefix').optional(),\n filename: z.string().describe('The original file name'),\n filesize: z.number().int().nonnegative().describe('The file size in bytes'),\n mimeType: z.string().describe('The file MIME type'),\n }),\n}).handler(async ({ authorizedMCP, collectionSlug, input, req }) => {\n try {\n const instructions = await getPayloadUploadInstructions({\n ...input,\n collectionSlug,\n overrideAccess: authorizedMCP.overrideAccess,\n req,\n })\n\n const nextStep =\n instructions.type === 'http'\n ? 'Send the exact file bytes using request, then pass { source: \"uploadReference\", file } to createDocument or updateDocument.'\n : `Call the local MCP tool named \"${instructions.name}\" with the file and data, then pass { source: \"uploadReference\", file } to createDocument or updateDocument.`\n\n return {\n content: [\n {\n type: 'text',\n text: `Upload instructions for collection \"${collectionSlug}\":\\n\\`\\`\\`json\\n${JSON.stringify(instructions)}\\n\\`\\`\\`\\n${nextStep}`,\n },\n ],\n structuredContent: { instructions },\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error'\n return {\n content: [\n {\n type: 'text',\n text: `Error getting upload instructions for collection \"${collectionSlug}\": ${message}`,\n },\n ],\n isError: true,\n }\n }\n})\n"],"names":["getUploadInstructions","getPayloadUploadInstructions","z","defaultAccess","defineCollectionTool","getUploadInstructionsTool","access","args","Boolean","permissions","collections","collectionSlug","create","update","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","object","docPrefix","string","describe","optional","filename","filesize","number","int","nonnegative","mimeType","handler","authorizedMCP","req","instructions","overrideAccess","nextStep","type","name","content","text","JSON","stringify","structuredContent","error","message","Error","isError"],"mappings":"AAAA,SAASA,yBAAyBC,4BAA4B,QAAQ,mBAAkB;AACxF,SAASC,CAAC,QAAQ,MAAK;AAEvB,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAE7D,OAAO,MAAMC,4BAA4BD,qBAAqB;IAC5DE,QAAQ,CAACC,OACPJ,cAAcI,SACdC,QACED,KAAKE,WAAW,EAAEC,aAAa,CAACH,KAAKI,cAAc,CAAC,EAAEC,UACpDL,KAAKE,WAAW,EAAEC,aAAa,CAACH,KAAKI,cAAc,CAAC,EAAEE;IAE5DC,aAAa;QACXC,iBAAiB;QACjBC,gBAAgB;QAChBC,eAAe;QACfC,cAAc;QACdC,OAAO;IACT;IACAC,aACE;IACFC,OAAOnB,EAAEoB,MAAM,CAAC;QACdC,WAAWrB,EAAEsB,MAAM,GAAGC,QAAQ,CAAC,sCAAsCC,QAAQ;QAC7EC,UAAUzB,EAAEsB,MAAM,GAAGC,QAAQ,CAAC;QAC9BG,UAAU1B,EAAE2B,MAAM,GAAGC,GAAG,GAAGC,WAAW,GAAGN,QAAQ,CAAC;QAClDO,UAAU9B,EAAEsB,MAAM,GAAGC,QAAQ,CAAC;IAChC;AACF,GAAGQ,OAAO,CAAC,OAAO,EAAEC,aAAa,EAAEvB,cAAc,EAAEU,KAAK,EAAEc,GAAG,EAAE;IAC7D,IAAI;QACF,MAAMC,eAAe,MAAMnC,6BAA6B;YACtD,GAAGoB,KAAK;YACRV;YACA0B,gBAAgBH,cAAcG,cAAc;YAC5CF;QACF;QAEA,MAAMG,WACJF,aAAaG,IAAI,KAAK,SAClB,gIACA,CAAC,+BAA+B,EAAEH,aAAaI,IAAI,CAAC,4GAA4G,CAAC;QAEvK,OAAO;YACLC,SAAS;gBACP;oBACEF,MAAM;oBACNG,MAAM,CAAC,oCAAoC,EAAE/B,eAAe,gBAAgB,EAAEgC,KAAKC,SAAS,CAACR,cAAc,UAAU,EAAEE,UAAU;gBACnI;aACD;YACDO,mBAAmB;gBAAET;YAAa;QACpC;IACF,EAAE,OAAOU,OAAO;QACd,MAAMC,UAAUD,iBAAiBE,QAAQF,MAAMC,OAAO,GAAG;QACzD,OAAO;YACLN,SAAS;gBACP;oBACEF,MAAM;oBACNG,MAAM,CAAC,kDAAkD,EAAE/B,eAAe,GAAG,EAAEoC,SAAS;gBAC1F;aACD;YACDE,SAAS;QACX;IACF;AACF,GAAE"}
@@ -2,6 +2,7 @@ import type { CollectionTool, GlobalTool, Tool } from '../types.js';
2
2
  type CollectionBuiltin = {
3
3
  mcpName: string;
4
4
  requiresDuplicateEnabled?: boolean;
5
+ requiresUpload?: boolean;
5
6
  requiresVersions?: boolean;
6
7
  tool: CollectionTool;
7
8
  };
@@ -66,6 +67,11 @@ export declare const COLLECTION_BUILTINS: {
66
67
  mcpName: string;
67
68
  tool: CollectionTool;
68
69
  };
70
+ getUploadInstructions: {
71
+ mcpName: string;
72
+ requiresUpload: true;
73
+ tool: CollectionTool;
74
+ };
69
75
  restoreVersion: {
70
76
  mcpName: string;
71
77
  requiresVersions: true;
@@ -1 +1 @@
1
- {"version":3,"file":"builtinTools.d.ts","sourceRoot":"","sources":["../../src/mcp/builtinTools.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AA+BnE,KAAK,iBAAiB,GAAG;IACvB,OAAO,EAAE,MAAM,CAAA;IACf,wBAAwB,CAAC,EAAE,OAAO,CAAA;IAClC,gBAAgB,CAAC,EAAE,OAAO,CAAA;IAC1B,IAAI,EAAE,cAAc,CAAA;CACrB,CAAA;AAED,KAAK,aAAa,GAAG;IACnB,OAAO,EAAE,MAAM,CAAA;IACf,gBAAgB,CAAC,EAAE,OAAO,CAAA;IAC1B,IAAI,EAAE,UAAU,CAAA;CACjB,CAAA;AAED,eAAO,MAAM,aAAa;;QACP,OAAO;QAAmB,IAAI;;CACU,CAAA;AAE3D;;;;GAIG;AACH,eAAO,MAAM,mBAAmB;;QACrB,OAAO;QAAoB,IAAI;;;;;;;;QAE9B,OAAO;QAAoB,IAAI;;;QAC/B,OAAO;QAAqB,IAAI;;;;;;;;QAMlC,OAAO;QAAmB,IAAI;;;QACtB,OAAO;QAAkB,IAAI;;;;;;;;;;;;;QAOtB,OAAO;QAAyB,IAAI;;;;;;;;QAEjD,OAAO;QAAoB,IAAI;;CACE,CAAA;AAE7C;;;GAGG;AACH,eAAO,MAAM,wBAAwB;;QAC3B,OAAO;QAAU,IAAI;;;QAE3B,OAAO;QACP,IAAI;;;QAEG,OAAO;QAAW,IAAI;;;QAE7B,OAAO;QACP,IAAI;;;QAEI,OAAO;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AO,aAAa,CAAC,CAAC,sBAAsB,CAAC,CAAC,CACzE,CAAA;AAED,eAAO,MAAM,0BAA0B,EAA0C,KAAK,CACpF,CAAC,wBAAwB,EAAE,iBAAiB,CAAC,CAC9C,CAAA;AAED,eAAO,MAAM,+BAA+B,EAA+C,KAAK,CAC9F,CAAC,yBAAyB,EAAE,CAAC,OAAO,wBAAwB,CAAC,CAAC,yBAAyB,CAAC,CAAC,CAC1F,CAAA;AAED,eAAO,MAAM,sBAAsB,EAAsC,KAAK,CAC5E,CAAC,oBAAoB,EAAE,aAAa,CAAC,CACtC,CAAA"}
@@ -11,6 +11,7 @@ import { findVersionsTool } from './builtin/collections/findVersionsTool.js';
11
11
  import { getCollectionSchemaTool } from './builtin/collections/getCollectionSchemaTool.js';
12
12
  import { restoreVersionTool } from './builtin/collections/restoreVersionTool.js';
13
13
  import { updateDocumentTool } from './builtin/collections/updateTool.js';
14
+ import { getUploadInstructionsTool } from './builtin/collections/uploadInstructionsTool.js';
14
15
  import { getConfigInfoTool } from './builtin/getConfigInfoTool.js';
15
16
  import { countGlobalVersionsTool } from './builtin/globals/countVersionsTool.js';
16
17
  import { findGlobalTool } from './builtin/globals/findTool.js';
@@ -74,6 +75,11 @@ export const TOOL_BUILTINS = {
74
75
  mcpName: 'getCollectionSchema',
75
76
  tool: getCollectionSchemaTool
76
77
  },
78
+ getUploadInstructions: {
79
+ mcpName: 'getUploadInstructions',
80
+ requiresUpload: true,
81
+ tool: getUploadInstructionsTool
82
+ },
77
83
  restoreVersion: {
78
84
  mcpName: 'restoreVersion',
79
85
  requiresVersions: true,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/mcp/builtinTools.ts"],"sourcesContent":["import type { CollectionTool, GlobalTool, Tool } from '../types.js'\n\nimport {\n authCollectionTool,\n forgotPasswordCollectionTool,\n loginCollectionTool,\n resetPasswordCollectionTool,\n unlockCollectionTool,\n verifyCollectionTool,\n} from './builtin/collections/authTools.js'\nimport { countDocumentsTool } from './builtin/collections/countTool.js'\nimport { countVersionsTool } from './builtin/collections/countVersionsTool.js'\nimport { createDocumentTool } from './builtin/collections/createTool.js'\nimport { deleteDocumentsTool } from './builtin/collections/deleteTool.js'\nimport { duplicateDocumentTool } from './builtin/collections/duplicateTool.js'\nimport { findDistinctTool } from './builtin/collections/findDistinctTool.js'\nimport { findDocumentsTool } from './builtin/collections/findTool.js'\nimport { findVersionByIDTool } from './builtin/collections/findVersionByIDTool.js'\nimport { findVersionsTool } from './builtin/collections/findVersionsTool.js'\nimport { getCollectionSchemaTool } from './builtin/collections/getCollectionSchemaTool.js'\nimport { restoreVersionTool } from './builtin/collections/restoreVersionTool.js'\nimport { updateDocumentTool } from './builtin/collections/updateTool.js'\nimport { getConfigInfoTool } from './builtin/getConfigInfoTool.js'\nimport { countGlobalVersionsTool } from './builtin/globals/countVersionsTool.js'\nimport { findGlobalTool } from './builtin/globals/findTool.js'\nimport { findGlobalVersionByIDTool } from './builtin/globals/findVersionByIDTool.js'\nimport { findGlobalVersionsTool } from './builtin/globals/findVersionsTool.js'\nimport { getGlobalSchemaTool } from './builtin/globals/getGlobalSchemaTool.js'\nimport { restoreGlobalVersionTool } from './builtin/globals/restoreVersionTool.js'\nimport { updateGlobalTool } from './builtin/globals/updateTool.js'\n\ntype CollectionBuiltin = {\n mcpName: string\n requiresDuplicateEnabled?: boolean\n requiresVersions?: boolean\n tool: CollectionTool\n}\n\ntype GlobalBuiltin = {\n mcpName: string\n requiresVersions?: boolean\n tool: GlobalTool\n}\n\nexport const TOOL_BUILTINS = {\n getConfigInfo: { mcpName: 'getConfigInfo', tool: getConfigInfoTool },\n} satisfies Record<string, { mcpName: string; tool: Tool }>\n\n/**\n * The static built-in collection CRUD tools. Keys here are the source of truth\n * for `MCPCollectionBuiltinName` — adding/removing an entry updates the type\n * automatically.\n */\nexport const COLLECTION_BUILTINS = {\n count: { mcpName: 'countDocuments', tool: countDocumentsTool },\n countVersions: { mcpName: 'countVersions', requiresVersions: true, tool: countVersionsTool },\n create: { mcpName: 'createDocument', tool: createDocumentTool },\n delete: { mcpName: 'deleteDocuments', tool: deleteDocumentsTool },\n duplicate: {\n mcpName: 'duplicateDocument',\n requiresDuplicateEnabled: true,\n tool: duplicateDocumentTool,\n },\n find: { mcpName: 'findDocuments', tool: findDocumentsTool },\n findDistinct: { mcpName: 'findDistinct', tool: findDistinctTool },\n findVersionByID: {\n mcpName: 'findVersionByID',\n requiresVersions: true,\n tool: findVersionByIDTool,\n },\n findVersions: { mcpName: 'findVersions', requiresVersions: true, tool: findVersionsTool },\n getCollectionSchema: { mcpName: 'getCollectionSchema', tool: getCollectionSchemaTool },\n restoreVersion: { mcpName: 'restoreVersion', requiresVersions: true, tool: restoreVersionTool },\n update: { mcpName: 'updateDocument', tool: updateDocumentTool },\n} satisfies Record<string, CollectionBuiltin>\n\n/**\n * The static auth tools surfaced under auth-enabled collections. Keys are the\n * source of truth for `MCPCollectionAuthToolName`.\n */\nexport const COLLECTION_AUTH_BUILTINS = {\n auth: { mcpName: 'auth', tool: authCollectionTool },\n forgotPassword: {\n mcpName: 'forgotPassword',\n tool: forgotPasswordCollectionTool,\n },\n login: { mcpName: 'login', tool: loginCollectionTool },\n resetPassword: {\n mcpName: 'resetPassword',\n tool: resetPasswordCollectionTool,\n },\n unlock: { mcpName: 'unlock', tool: unlockCollectionTool },\n verify: { mcpName: 'verify', tool: verifyCollectionTool },\n} satisfies Record<string, { mcpName: string; tool: CollectionTool }>\n\n/**\n * The static built-in global tools. Keys are the source of truth for\n * `MCPGlobalBuiltinName`.\n */\nexport const GLOBAL_BUILTINS = {\n countGlobalVersions: {\n mcpName: 'countGlobalVersions',\n requiresVersions: true,\n tool: countGlobalVersionsTool,\n },\n find: { mcpName: 'findGlobal', tool: findGlobalTool },\n findGlobalVersionByID: {\n mcpName: 'findGlobalVersionByID',\n requiresVersions: true,\n tool: findGlobalVersionByIDTool,\n },\n findGlobalVersions: {\n mcpName: 'findGlobalVersions',\n requiresVersions: true,\n tool: findGlobalVersionsTool,\n },\n getGlobalSchema: { mcpName: 'getGlobalSchema', tool: getGlobalSchemaTool },\n restoreGlobalVersion: {\n mcpName: 'restoreGlobalVersion',\n requiresVersions: true,\n tool: restoreGlobalVersionTool,\n },\n update: { mcpName: 'updateGlobal', tool: updateGlobalTool },\n} satisfies Record<string, GlobalBuiltin>\n\nexport type MCPCollectionBuiltinName = keyof typeof COLLECTION_BUILTINS\n\nexport type MCPCollectionAuthToolName = keyof typeof COLLECTION_AUTH_BUILTINS\n\nexport type MCPGlobalBuiltinName = keyof typeof GLOBAL_BUILTINS\n\nexport type MCPTopLevelBuiltinName = keyof typeof TOOL_BUILTINS\n\n/**\n * Pre-typed `Object.entries` for each registry. The cast from `string` to the\n * literal key union lives here once so consumers can iterate without their own\n * cast — TypeScript's `Object.entries` always widens keys to `string`, which\n * defeats the narrow type lookups on `MCPCollectionToolsMap`.\n */\nexport const TOOL_BUILTIN_ENTRIES = Object.entries(TOOL_BUILTINS) as Array<\n [MCPTopLevelBuiltinName, (typeof TOOL_BUILTINS)[MCPTopLevelBuiltinName]]\n>\n\nexport const COLLECTION_BUILTIN_ENTRIES = Object.entries(COLLECTION_BUILTINS) as Array<\n [MCPCollectionBuiltinName, CollectionBuiltin]\n>\n\nexport const COLLECTION_AUTH_BUILTIN_ENTRIES = Object.entries(COLLECTION_AUTH_BUILTINS) as Array<\n [MCPCollectionAuthToolName, (typeof COLLECTION_AUTH_BUILTINS)[MCPCollectionAuthToolName]]\n>\n\nexport const GLOBAL_BUILTIN_ENTRIES = Object.entries(GLOBAL_BUILTINS) as Array<\n [MCPGlobalBuiltinName, GlobalBuiltin]\n>\n"],"names":["authCollectionTool","forgotPasswordCollectionTool","loginCollectionTool","resetPasswordCollectionTool","unlockCollectionTool","verifyCollectionTool","countDocumentsTool","countVersionsTool","createDocumentTool","deleteDocumentsTool","duplicateDocumentTool","findDistinctTool","findDocumentsTool","findVersionByIDTool","findVersionsTool","getCollectionSchemaTool","restoreVersionTool","updateDocumentTool","getConfigInfoTool","countGlobalVersionsTool","findGlobalTool","findGlobalVersionByIDTool","findGlobalVersionsTool","getGlobalSchemaTool","restoreGlobalVersionTool","updateGlobalTool","TOOL_BUILTINS","getConfigInfo","mcpName","tool","COLLECTION_BUILTINS","count","countVersions","requiresVersions","create","delete","duplicate","requiresDuplicateEnabled","find","findDistinct","findVersionByID","findVersions","getCollectionSchema","restoreVersion","update","COLLECTION_AUTH_BUILTINS","auth","forgotPassword","login","resetPassword","unlock","verify","GLOBAL_BUILTINS","countGlobalVersions","findGlobalVersionByID","findGlobalVersions","getGlobalSchema","restoreGlobalVersion","TOOL_BUILTIN_ENTRIES","Object","entries","COLLECTION_BUILTIN_ENTRIES","COLLECTION_AUTH_BUILTIN_ENTRIES","GLOBAL_BUILTIN_ENTRIES"],"mappings":"AAEA,SACEA,kBAAkB,EAClBC,4BAA4B,EAC5BC,mBAAmB,EACnBC,2BAA2B,EAC3BC,oBAAoB,EACpBC,oBAAoB,QACf,qCAAoC;AAC3C,SAASC,kBAAkB,QAAQ,qCAAoC;AACvE,SAASC,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,kBAAkB,QAAQ,sCAAqC;AACxE,SAASC,mBAAmB,QAAQ,sCAAqC;AACzE,SAASC,qBAAqB,QAAQ,yCAAwC;AAC9E,SAASC,gBAAgB,QAAQ,4CAA2C;AAC5E,SAASC,iBAAiB,QAAQ,oCAAmC;AACrE,SAASC,mBAAmB,QAAQ,+CAA8C;AAClF,SAASC,gBAAgB,QAAQ,4CAA2C;AAC5E,SAASC,uBAAuB,QAAQ,mDAAkD;AAC1F,SAASC,kBAAkB,QAAQ,8CAA6C;AAChF,SAASC,kBAAkB,QAAQ,sCAAqC;AACxE,SAASC,iBAAiB,QAAQ,iCAAgC;AAClE,SAASC,uBAAuB,QAAQ,yCAAwC;AAChF,SAASC,cAAc,QAAQ,gCAA+B;AAC9D,SAASC,yBAAyB,QAAQ,2CAA0C;AACpF,SAASC,sBAAsB,QAAQ,wCAAuC;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QAAUC,MAAMzB;IAAqB;IACxD+C,QAAQ;QAAEvB,SAAS;QAAUC,MAAMxB;IAAqB;AAC1D,EAAqE;AAErE;;;CAGC,GACD,OAAO,MAAM+C,kBAAkB;IAC7BC,qBAAqB;QACnBzB,SAAS;QACTK,kBAAkB;QAClBJ,MAAMV;IACR;IACAmB,MAAM;QAAEV,SAAS;QAAcC,MAAMT;IAAe;IACpDkC,uBAAuB;QACrB1B,SAAS;QACTK,kBAAkB;QAClBJ,MAAMR;IACR;IACAkC,oBAAoB;QAClB3B,SAAS;QACTK,kBAAkB;QAClBJ,MAAMP;IACR;IACAkC,iBAAiB;QAAE5B,SAAS;QAAmBC,MAAMN;IAAoB;IACzEkC,sBAAsB;QACpB7B,SAAS;QACTK,kBAAkB;QAClBJ,MAAML;IACR;IACAoB,QAAQ;QAAEhB,SAAS;QAAgBC,MAAMJ;IAAiB;AAC5D,EAAyC;AAUzC;;;;;CAKC,GACD,OAAO,MAAMiC,uBAAuBC,OAAOC,OAAO,CAAClC,eAElD;AAED,OAAO,MAAMmC,6BAA6BF,OAAOC,OAAO,CAAC9B,qBAExD;AAED,OAAO,MAAMgC,kCAAkCH,OAAOC,OAAO,CAACf,0BAE7D;AAED,OAAO,MAAMkB,yBAAyBJ,OAAOC,OAAO,CAACR,iBAEpD"}
1
+ {"version":3,"sources":["../../src/mcp/builtinTools.ts"],"sourcesContent":["import type { CollectionTool, GlobalTool, Tool } from '../types.js'\n\nimport {\n authCollectionTool,\n forgotPasswordCollectionTool,\n loginCollectionTool,\n resetPasswordCollectionTool,\n unlockCollectionTool,\n verifyCollectionTool,\n} from './builtin/collections/authTools.js'\nimport { countDocumentsTool } from './builtin/collections/countTool.js'\nimport { countVersionsTool } from './builtin/collections/countVersionsTool.js'\nimport { createDocumentTool } from './builtin/collections/createTool.js'\nimport { deleteDocumentsTool } from './builtin/collections/deleteTool.js'\nimport { duplicateDocumentTool } from './builtin/collections/duplicateTool.js'\nimport { findDistinctTool } from './builtin/collections/findDistinctTool.js'\nimport { findDocumentsTool } from './builtin/collections/findTool.js'\nimport { findVersionByIDTool } from './builtin/collections/findVersionByIDTool.js'\nimport { findVersionsTool } from './builtin/collections/findVersionsTool.js'\nimport { getCollectionSchemaTool } from './builtin/collections/getCollectionSchemaTool.js'\nimport { restoreVersionTool } from './builtin/collections/restoreVersionTool.js'\nimport { updateDocumentTool } from './builtin/collections/updateTool.js'\nimport { getUploadInstructionsTool } from './builtin/collections/uploadInstructionsTool.js'\nimport { getConfigInfoTool } from './builtin/getConfigInfoTool.js'\nimport { countGlobalVersionsTool } from './builtin/globals/countVersionsTool.js'\nimport { findGlobalTool } from './builtin/globals/findTool.js'\nimport { findGlobalVersionByIDTool } from './builtin/globals/findVersionByIDTool.js'\nimport { findGlobalVersionsTool } from './builtin/globals/findVersionsTool.js'\nimport { getGlobalSchemaTool } from './builtin/globals/getGlobalSchemaTool.js'\nimport { restoreGlobalVersionTool } from './builtin/globals/restoreVersionTool.js'\nimport { updateGlobalTool } from './builtin/globals/updateTool.js'\n\ntype CollectionBuiltin = {\n mcpName: string\n requiresDuplicateEnabled?: boolean\n requiresUpload?: boolean\n requiresVersions?: boolean\n tool: CollectionTool\n}\n\ntype GlobalBuiltin = {\n mcpName: string\n requiresVersions?: boolean\n tool: GlobalTool\n}\n\nexport const TOOL_BUILTINS = {\n getConfigInfo: { mcpName: 'getConfigInfo', tool: getConfigInfoTool },\n} satisfies Record<string, { mcpName: string; tool: Tool }>\n\n/**\n * The static built-in collection CRUD tools. Keys here are the source of truth\n * for `MCPCollectionBuiltinName` — adding/removing an entry updates the type\n * automatically.\n */\nexport const COLLECTION_BUILTINS = {\n count: { mcpName: 'countDocuments', tool: countDocumentsTool },\n countVersions: { mcpName: 'countVersions', requiresVersions: true, tool: countVersionsTool },\n create: { mcpName: 'createDocument', tool: createDocumentTool },\n delete: { mcpName: 'deleteDocuments', tool: deleteDocumentsTool },\n duplicate: {\n mcpName: 'duplicateDocument',\n requiresDuplicateEnabled: true,\n tool: duplicateDocumentTool,\n },\n find: { mcpName: 'findDocuments', tool: findDocumentsTool },\n findDistinct: { mcpName: 'findDistinct', tool: findDistinctTool },\n findVersionByID: {\n mcpName: 'findVersionByID',\n requiresVersions: true,\n tool: findVersionByIDTool,\n },\n findVersions: { mcpName: 'findVersions', requiresVersions: true, tool: findVersionsTool },\n getCollectionSchema: { mcpName: 'getCollectionSchema', tool: getCollectionSchemaTool },\n getUploadInstructions: {\n mcpName: 'getUploadInstructions',\n requiresUpload: true,\n tool: getUploadInstructionsTool,\n },\n restoreVersion: { mcpName: 'restoreVersion', requiresVersions: true, tool: restoreVersionTool },\n update: { mcpName: 'updateDocument', tool: updateDocumentTool },\n} satisfies Record<string, CollectionBuiltin>\n\n/**\n * The static auth tools surfaced under auth-enabled collections. Keys are the\n * source of truth for `MCPCollectionAuthToolName`.\n */\nexport const COLLECTION_AUTH_BUILTINS = {\n auth: { mcpName: 'auth', tool: authCollectionTool },\n forgotPassword: {\n mcpName: 'forgotPassword',\n tool: forgotPasswordCollectionTool,\n },\n login: { mcpName: 'login', tool: loginCollectionTool },\n resetPassword: {\n mcpName: 'resetPassword',\n tool: resetPasswordCollectionTool,\n },\n unlock: { mcpName: 'unlock', tool: unlockCollectionTool },\n verify: { mcpName: 'verify', tool: verifyCollectionTool },\n} satisfies Record<string, { mcpName: string; tool: CollectionTool }>\n\n/**\n * The static built-in global tools. Keys are the source of truth for\n * `MCPGlobalBuiltinName`.\n */\nexport const GLOBAL_BUILTINS = {\n countGlobalVersions: {\n mcpName: 'countGlobalVersions',\n requiresVersions: true,\n tool: countGlobalVersionsTool,\n },\n find: { mcpName: 'findGlobal', tool: findGlobalTool },\n findGlobalVersionByID: {\n mcpName: 'findGlobalVersionByID',\n requiresVersions: true,\n tool: findGlobalVersionByIDTool,\n },\n findGlobalVersions: {\n mcpName: 'findGlobalVersions',\n requiresVersions: true,\n tool: findGlobalVersionsTool,\n },\n getGlobalSchema: { mcpName: 'getGlobalSchema', tool: getGlobalSchemaTool },\n restoreGlobalVersion: {\n mcpName: 'restoreGlobalVersion',\n requiresVersions: true,\n tool: restoreGlobalVersionTool,\n },\n update: { mcpName: 'updateGlobal', tool: updateGlobalTool },\n} satisfies Record<string, GlobalBuiltin>\n\nexport type MCPCollectionBuiltinName = keyof typeof COLLECTION_BUILTINS\n\nexport type MCPCollectionAuthToolName = keyof typeof COLLECTION_AUTH_BUILTINS\n\nexport type MCPGlobalBuiltinName = keyof typeof GLOBAL_BUILTINS\n\nexport type MCPTopLevelBuiltinName = keyof typeof TOOL_BUILTINS\n\n/**\n * Pre-typed `Object.entries` for each registry. The cast from `string` to the\n * literal key union lives here once so consumers can iterate without their own\n * cast — TypeScript's `Object.entries` always widens keys to `string`, which\n * defeats the narrow type lookups on `MCPCollectionToolsMap`.\n */\nexport const TOOL_BUILTIN_ENTRIES = Object.entries(TOOL_BUILTINS) as Array<\n [MCPTopLevelBuiltinName, (typeof TOOL_BUILTINS)[MCPTopLevelBuiltinName]]\n>\n\nexport const COLLECTION_BUILTIN_ENTRIES = Object.entries(COLLECTION_BUILTINS) as Array<\n [MCPCollectionBuiltinName, CollectionBuiltin]\n>\n\nexport const COLLECTION_AUTH_BUILTIN_ENTRIES = Object.entries(COLLECTION_AUTH_BUILTINS) as Array<\n [MCPCollectionAuthToolName, (typeof COLLECTION_AUTH_BUILTINS)[MCPCollectionAuthToolName]]\n>\n\nexport const GLOBAL_BUILTIN_ENTRIES = Object.entries(GLOBAL_BUILTINS) as Array<\n [MCPGlobalBuiltinName, GlobalBuiltin]\n>\n"],"names":["authCollectionTool","forgotPasswordCollectionTool","loginCollectionTool","resetPasswordCollectionTool","unlockCollectionTool","verifyCollectionTool","countDocumentsTool","countVersionsTool","createDocumentTool","deleteDocumentsTool","duplicateDocumentTool","findDistinctTool","findDocumentsTool","findVersionByIDTool","findVersionsTool","getCollectionSchemaTool","restoreVersionTool","updateDocumentTool","getUploadInstructionsTool","getConfigInfoTool","countGlobalVersionsTool","findGlobalTool","findGlobalVersionByIDTool","findGlobalVersionsTool","getGlobalSchemaTool","restoreGlobalVersionTool","updateGlobalTool","TOOL_BUILTINS","getConfigInfo","mcpName","tool","COLLECTION_BUILTINS","count","countVersions","requiresVersions","create","delete","duplicate","requiresDuplicateEnabled","find","findDistinct","findVersionByID","findVersions","getCollectionSchema","getUploadInstructions","requiresUpload","restoreVersion","update","COLLECTION_AUTH_BUILTINS","auth","forgotPassword","login","resetPassword","unlock","verify","GLOBAL_BUILTINS","countGlobalVersions","findGlobalVersionByID","findGlobalVersions","getGlobalSchema","restoreGlobalVersion","TOOL_BUILTIN_ENTRIES","Object","entries","COLLECTION_BUILTIN_ENTRIES","COLLECTION_AUTH_BUILTIN_ENTRIES","GLOBAL_BUILTIN_ENTRIES"],"mappings":"AAEA,SACEA,kBAAkB,EAClBC,4BAA4B,EAC5BC,mBAAmB,EACnBC,2BAA2B,EAC3BC,oBAAoB,EACpBC,oBAAoB,QACf,qCAAoC;AAC3C,SAASC,kBAAkB,QAAQ,qCAAoC;AACvE,SAASC,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,kBAAkB,QAAQ,sCAAqC;AACxE,SAASC,mBAAmB,QAAQ,sCAAqC;AACzE,SAASC,qBAAqB,QAAQ,yCAAwC;AAC9E,SAASC,gBAAgB,QAAQ,4CAA2C;AAC5E,SAASC,iBAAiB,QAAQ,oCAAmC;AACrE,SAASC,mBAAmB,QAAQ,+CAA8C;AAClF,SAASC,gBAAgB,QAAQ,4CAA2C;AAC5E,SAASC,uBAAuB,QAAQ,mDAAkD;AAC1F,SAASC,kBAAkB,QAAQ,8CAA6C;AAChF,SAASC,kBAAkB,QAAQ,sCAAqC;AACxE,SAASC,yBAAyB,QAAQ,kDAAiD;AAC3F,SAASC,iBAAiB,QAAQ,iCAAgC;AAClE,SAASC,uBAAuB,QAAQ,yCAAwC;AAChF,SAASC,cAAc,QAAQ,gCAA+B;AAC9D,SAASC,yBAAyB,QAAQ,2CAA0C;AACpF,SAASC,sBAAsB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B;IAAoB;IACrDkD,eAAe;QACbvB,SAAS;QACTC,MAAM3B;IACR;IACAkD,QAAQ;QAAExB,SAAS;QAAUC,MAAM1B;IAAqB;IACxDkD,QAAQ;QAAEzB,SAAS;QAAUC,MAAMzB;IAAqB;AAC1D,EAAqE;AAErE;;;CAGC,GACD,OAAO,MAAMkD,kBAAkB;IAC7BC,qBAAqB;QACnB3B,SAAS;QACTK,kBAAkB;QAClBJ,MAAMV;IACR;IACAmB,MAAM;QAAEV,SAAS;QAAcC,MAAMT;IAAe;IACpDoC,uBAAuB;QACrB5B,SAAS;QACTK,kBAAkB;QAClBJ,MAAMR;IACR;IACAoC,oBAAoB;QAClB7B,SAAS;QACTK,kBAAkB;QAClBJ,MAAMP;IACR;IACAoC,iBAAiB;QAAE9B,SAAS;QAAmBC,MAAMN;IAAoB;IACzEoC,sBAAsB;QACpB/B,SAAS;QACTK,kBAAkB;QAClBJ,MAAML;IACR;IACAsB,QAAQ;QAAElB,SAAS;QAAgBC,MAAMJ;IAAiB;AAC5D,EAAyC;AAUzC;;;;;CAKC,GACD,OAAO,MAAMmC,uBAAuBC,OAAOC,OAAO,CAACpC,eAElD;AAED,OAAO,MAAMqC,6BAA6BF,OAAOC,OAAO,CAAChC,qBAExD;AAED,OAAO,MAAMkC,kCAAkCH,OAAOC,OAAO,CAACf,0BAE7D;AAED,OAAO,MAAMkB,yBAAyBJ,OAAOC,OAAO,CAACR,iBAEpD"}
@@ -89,13 +89,16 @@ const sanitizeCollectionConfig = ({ collection, pluginConfig })=>{
89
89
  * Payload disables duplicate for auth collections by default unless the
90
90
  * collection explicitly opts back in with `disableDuplicate: false`.
91
91
  */ const isDuplicateDisabled = collection.disableDuplicate === true || Boolean(collection.auth) && collection.disableDuplicate !== false;
92
- for (const [toolKey, { mcpName, requiresDuplicateEnabled, requiresVersions, tool }] of COLLECTION_BUILTIN_ENTRIES){
92
+ for (const [toolKey, { mcpName, requiresDuplicateEnabled, requiresUpload, requiresVersions, tool }] of COLLECTION_BUILTIN_ENTRIES){
93
93
  if (requiresVersions && !collection.versions) {
94
94
  continue;
95
95
  }
96
96
  if (requiresDuplicateEnabled && isDuplicateDisabled) {
97
97
  continue;
98
98
  }
99
+ if (requiresUpload && !collection.upload) {
100
+ continue;
101
+ }
99
102
  const matchedConfigEntry = collectionPluginConfig?.tools?.[toolKey];
100
103
  if (matchedConfigEntry === false) {
101
104
  continue;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/mcp/sanitizeMCPConfig.ts"],"sourcesContent":["import type {\n CollectionConfig,\n Config,\n GlobalConfig,\n SanitizedCollectionConfig,\n SanitizedConfig,\n SanitizedGlobalConfig,\n} from 'payload'\n\nimport type {\n CollectionMCPItem,\n CollectionTool,\n GlobalMCPItem,\n GlobalTool,\n MCPItem,\n MCPPluginConfig,\n SanitizedMCPPluginConfig,\n} from '../types.js'\n\nimport { defaultAccess } from '../defaultAccess.js'\nimport {\n COLLECTION_AUTH_BUILTIN_ENTRIES,\n COLLECTION_AUTH_BUILTINS,\n COLLECTION_BUILTIN_ENTRIES,\n COLLECTION_BUILTINS,\n GLOBAL_BUILTIN_ENTRIES,\n GLOBAL_BUILTINS,\n TOOL_BUILTIN_ENTRIES,\n TOOL_BUILTINS,\n} from './builtinTools.js'\n\n/**\n * Converts the user-configured `MCPPluginConfig` into a `SanitizedMCPPluginConfig`:\n * - Flattens `tools` / `prompts` / `resources` / per-collection / per-global\n * tool maps into a single `items` array.\n * - Applies built-in tools for collections and globals, respecting opt-out user overrides.\n *\n * Called once during plugin init. After that, `plugins['@payloadcms/plugin-mcp']\n * ?.options` holds the sanitized result\n */\nexport const sanitizeMCPConfig = ({\n config,\n pluginConfig,\n}: {\n config: Config | SanitizedConfig\n pluginConfig: MCPPluginConfig\n}): SanitizedMCPPluginConfig => {\n const items: MCPItem[] = []\n\n for (const collection of config.collections ?? []) {\n items.push(...sanitizeCollectionConfig({ collection, pluginConfig }))\n }\n\n for (const global of config.globals ?? []) {\n items.push(...sanitizeGlobalConfig({ global, pluginConfig }))\n }\n\n for (const [configKey, { mcpName, tool }] of TOOL_BUILTIN_ENTRIES) {\n items.push({\n type: 'tool',\n configKey,\n label: tool.annotations?.title ?? configKey,\n mcpName,\n tool: { ...tool, access: tool.access ?? defaultAccess },\n })\n }\n\n for (const [configKey, tool] of Object.entries(pluginConfig.tools ?? {})) {\n if (configKey in TOOL_BUILTINS) {\n continue\n }\n items.push({\n type: 'tool',\n configKey,\n label: tool.annotations?.title ?? configKey,\n mcpName: configKey,\n tool: { ...tool, access: tool.access ?? defaultAccess },\n })\n }\n\n for (const [configKey, prompt] of Object.entries(pluginConfig.prompts ?? {})) {\n items.push({\n type: 'prompt',\n configKey,\n label: prompt.title ?? configKey,\n mcpName: configKey,\n prompt: { ...prompt, access: prompt.access ?? defaultAccess },\n })\n }\n\n for (const [configKey, resource] of Object.entries(pluginConfig.resources ?? {})) {\n items.push({\n type: 'resource',\n configKey,\n label: resource.title ?? configKey,\n mcpName: configKey,\n resource: { ...resource, access: resource.access ?? defaultAccess },\n })\n }\n\n return {\n disabled: pluginConfig.disabled,\n hooks: pluginConfig.hooks,\n items,\n mcp: pluginConfig.mcp,\n overrideGetAuthorizedMCP: pluginConfig.overrideGetAuthorizedMCP,\n }\n}\n\nconst sanitizeCollectionConfig = ({\n collection,\n pluginConfig,\n}: {\n collection: CollectionConfig | SanitizedCollectionConfig\n pluginConfig: MCPPluginConfig\n}): CollectionMCPItem[] => {\n const slug = collection.slug\n const collectionPluginConfig = pluginConfig.collections?.[slug]\n const items: CollectionMCPItem[] = []\n /**\n * Payload disables duplicate for auth collections by default unless the\n * collection explicitly opts back in with `disableDuplicate: false`.\n */\n const isDuplicateDisabled =\n collection.disableDuplicate === true ||\n (Boolean(collection.auth) && collection.disableDuplicate !== false)\n\n for (const [\n toolKey,\n { mcpName, requiresDuplicateEnabled, requiresVersions, tool },\n ] of COLLECTION_BUILTIN_ENTRIES) {\n if (requiresVersions && !collection.versions) {\n continue\n }\n if (requiresDuplicateEnabled && isDuplicateDisabled) {\n continue\n }\n const matchedConfigEntry = collectionPluginConfig?.tools?.[toolKey]\n if (matchedConfigEntry === false) {\n continue\n }\n const override = typeof matchedConfigEntry === 'object' ? matchedConfigEntry : undefined\n const annotations = { ...tool.annotations, ...override?.annotations }\n items.push({\n type: 'collectionTool',\n collectionSlug: slug,\n configKey: toolKey,\n label: annotations.title ?? toolKey,\n mcpName,\n tool: {\n ...tool,\n access: override?.access ?? tool.access ?? defaultAccess,\n annotations,\n description: override?.description ?? tool.description,\n overrideResponse:\n override?.overrideResponse ??\n collectionPluginConfig?.overrideResponse ??\n tool.overrideResponse,\n },\n })\n }\n\n if (collection.auth) {\n for (const [authToolKey, { mcpName, tool }] of COLLECTION_AUTH_BUILTIN_ENTRIES) {\n const matchedConfigEntry = collectionPluginConfig?.tools?.[authToolKey]\n if (!matchedConfigEntry) {\n continue\n }\n // `true` means \"enable, no override\"; only the object form carries fields.\n const override = typeof matchedConfigEntry === 'object' ? matchedConfigEntry : undefined\n const annotations = { ...tool.annotations, ...override?.annotations }\n items.push({\n type: 'collectionTool',\n collectionSlug: slug,\n configKey: authToolKey,\n label: annotations.title ?? authToolKey,\n mcpName,\n tool: {\n ...tool,\n access: override?.access ?? tool.access ?? defaultAccess,\n annotations,\n description: override?.description ?? tool.description,\n overrideResponse:\n override?.overrideResponse ??\n collectionPluginConfig?.overrideResponse ??\n tool.overrideResponse,\n },\n })\n }\n }\n\n // Cast: builtin keys are filtered out below, so the remaining values are\n // always custom tools (`CollectionTool`) or undefined\n const customEntries = Object.entries(collectionPluginConfig?.tools ?? {}) as Array<\n [string, CollectionTool | undefined]\n >\n for (const [configKey, customTool] of customEntries) {\n if (configKey in COLLECTION_BUILTINS || configKey in COLLECTION_AUTH_BUILTINS) {\n continue\n }\n if (!customTool) {\n continue\n }\n items.push({\n type: 'collectionTool',\n collectionSlug: slug,\n configKey,\n label: customTool.annotations?.title ?? configKey,\n mcpName: configKey,\n tool: { ...customTool, access: customTool.access ?? defaultAccess },\n })\n }\n\n return items\n}\n\nconst sanitizeGlobalConfig = ({\n global,\n pluginConfig,\n}: {\n global: GlobalConfig | SanitizedGlobalConfig\n pluginConfig: MCPPluginConfig\n}): GlobalMCPItem[] => {\n const slug = global.slug\n const globalPluginConfig = pluginConfig.globals?.[slug]\n const items: GlobalMCPItem[] = []\n\n for (const [toolKey, { mcpName, requiresVersions, tool }] of GLOBAL_BUILTIN_ENTRIES) {\n if (requiresVersions && !global.versions) {\n continue\n }\n const matchedConfigEntry = globalPluginConfig?.tools?.[toolKey]\n if (matchedConfigEntry === false) {\n continue\n }\n const override = typeof matchedConfigEntry === 'object' ? matchedConfigEntry : undefined\n const annotations = { ...tool.annotations, ...override?.annotations }\n items.push({\n type: 'globalTool',\n configKey: toolKey,\n globalSlug: slug,\n label: annotations.title ?? toolKey,\n mcpName,\n tool: {\n ...tool,\n access: override?.access ?? tool.access ?? defaultAccess,\n annotations,\n description: override?.description ?? tool.description,\n overrideResponse:\n override?.overrideResponse ??\n globalPluginConfig?.overrideResponse ??\n tool.overrideResponse,\n },\n })\n }\n\n const customEntries = Object.entries(globalPluginConfig?.tools ?? {}) as Array<\n [string, GlobalTool | undefined]\n >\n for (const [configKey, customTool] of customEntries) {\n if (configKey in GLOBAL_BUILTINS) {\n continue\n }\n if (!customTool) {\n continue\n }\n items.push({\n type: 'globalTool',\n configKey,\n globalSlug: slug,\n label: customTool.annotations?.title ?? configKey,\n mcpName: configKey,\n tool: { ...customTool, access: customTool.access ?? defaultAccess },\n })\n }\n\n return items\n}\n"],"names":["defaultAccess","COLLECTION_AUTH_BUILTIN_ENTRIES","COLLECTION_AUTH_BUILTINS","COLLECTION_BUILTIN_ENTRIES","COLLECTION_BUILTINS","GLOBAL_BUILTIN_ENTRIES","GLOBAL_BUILTINS","TOOL_BUILTIN_ENTRIES","TOOL_BUILTINS","sanitizeMCPConfig","config","pluginConfig","items","collection","collections","push","sanitizeCollectionConfig","global","globals","sanitizeGlobalConfig","configKey","mcpName","tool","type","label","annotations","title","access","Object","entries","tools","prompt","prompts","resource","resources","disabled","hooks","mcp","overrideGetAuthorizedMCP","slug","collectionPluginConfig","isDuplicateDisabled","disableDuplicate","Boolean","auth","toolKey","requiresDuplicateEnabled","requiresVersions","versions","matchedConfigEntry","override","undefined","collectionSlug","description","overrideResponse","authToolKey","customEntries","customTool","globalPluginConfig","globalSlug"],"mappings":"AAmBA,SAASA,aAAa,QAAQ,sBAAqB;AACnD,SACEC,+BAA+B,EAC/BC,wBAAwB,EACxBC,0BAA0B,EAC1BC,mBAAmB,EACnBC,sBAAsB,EACtBC,eAAe,EACfC,oBAAoB,EACpBC,aAAa,QACR,oBAAmB;AAE1B;;;;;;;;CAQC,GACD,OAAO,MAAMC,oBAAoB,CAAC,EAChCC,MAAM,EACNC,YAAY,EAIb;IACC,MAAMC,QAAmB,EAAE;IAE3B,KAAK,MAAMC,cAAcH,OAAOI,WAAW,IAAI,EAAE,CAAE;QACjDF,MAAMG,IAAI,IAAIC,yBAAyB;YAAEH;YAAYF;QAAa;IACpE;IAEA,KAAK,MAAMM,UAAUP,OAAOQ,OAAO,IAAI,EAAE,CAAE;QACzCN,MAAMG,IAAI,IAAII,qBAAqB;YAAEF;YAAQN;QAAa;IAC5D;IAEA,KAAK,MAAM,CAACS,WAAW,EAAEC,OAAO,EAAEC,IAAI,EAAE,CAAC,IAAIf,qBAAsB;QACjEK,MAAMG,IAAI,CAAC;YACTQ,MAAM;YACNH;YACAI,OAAOF,KAAKG,WAAW,EAAEC,SAASN;YAClCC;YACAC,MAAM;gBAAE,GAAGA,IAAI;gBAAEK,QAAQL,KAAKK,MAAM,IAAI3B;YAAc;QACxD;IACF;IAEA,KAAK,MAAM,CAACoB,WAAWE,KAAK,IAAIM,OAAOC,OAAO,CAAClB,aAAamB,KAAK,IAAI,CAAC,GAAI;QACxE,IAAIV,aAAaZ,eAAe;YAC9B;QACF;QACAI,MAAMG,IAAI,CAAC;YACTQ,MAAM;YACNH;YACAI,OAAO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AAUzB,WAAW;QAAC;QACpEb,MAAMG,IAAI,CAAC;YACTQ,MAAM;YACNH,WAAWyB;YACXc,YAAYpB;YACZf,OAAOC,YAAYC,KAAK,IAAImB;YAC5BxB;YACAC,MAAM;gBACJ,GAAGA,IAAI;gBACPK,QAAQuB,UAAUvB,UAAUL,KAAKK,MAAM,IAAI3B;gBAC3CyB;gBACA4B,aAAaH,UAAUG,eAAe/B,KAAK+B,WAAW;gBACtDC,kBACEJ,UAAUI,oBACVI,oBAAoBJ,oBACpBhC,KAAKgC,gBAAgB;YACzB;QACF;IACF;IAEA,MAAME,gBAAgB5B,OAAOC,OAAO,CAAC6B,oBAAoB5B,SAAS,CAAC;IAGnE,KAAK,MAAM,CAACV,WAAWqC,WAAW,IAAID,cAAe;QACnD,IAAIpC,aAAad,iBAAiB;YAChC;QACF;QACA,IAAI,CAACmD,YAAY;YACf;QACF;QACA7C,MAAMG,IAAI,CAAC;YACTQ,MAAM;YACNH;YACAuC,YAAYpB;YACZf,OAAOiC,WAAWhC,WAAW,EAAEC,SAASN;YACxCC,SAASD;YACTE,MAAM;gBAAE,GAAGmC,UAAU;gBAAE9B,QAAQ8B,WAAW9B,MAAM,IAAI3B;YAAc;QACpE;IACF;IAEA,OAAOY;AACT"}
1
+ {"version":3,"sources":["../../src/mcp/sanitizeMCPConfig.ts"],"sourcesContent":["import type {\n CollectionConfig,\n Config,\n GlobalConfig,\n SanitizedCollectionConfig,\n SanitizedConfig,\n SanitizedGlobalConfig,\n} from 'payload'\n\nimport type {\n CollectionMCPItem,\n CollectionTool,\n GlobalMCPItem,\n GlobalTool,\n MCPItem,\n MCPPluginConfig,\n SanitizedMCPPluginConfig,\n} from '../types.js'\n\nimport { defaultAccess } from '../defaultAccess.js'\nimport {\n COLLECTION_AUTH_BUILTIN_ENTRIES,\n COLLECTION_AUTH_BUILTINS,\n COLLECTION_BUILTIN_ENTRIES,\n COLLECTION_BUILTINS,\n GLOBAL_BUILTIN_ENTRIES,\n GLOBAL_BUILTINS,\n TOOL_BUILTIN_ENTRIES,\n TOOL_BUILTINS,\n} from './builtinTools.js'\n\n/**\n * Converts the user-configured `MCPPluginConfig` into a `SanitizedMCPPluginConfig`:\n * - Flattens `tools` / `prompts` / `resources` / per-collection / per-global\n * tool maps into a single `items` array.\n * - Applies built-in tools for collections and globals, respecting opt-out user overrides.\n *\n * Called once during plugin init. After that, `plugins['@payloadcms/plugin-mcp']\n * ?.options` holds the sanitized result\n */\nexport const sanitizeMCPConfig = ({\n config,\n pluginConfig,\n}: {\n config: Config | SanitizedConfig\n pluginConfig: MCPPluginConfig\n}): SanitizedMCPPluginConfig => {\n const items: MCPItem[] = []\n\n for (const collection of config.collections ?? []) {\n items.push(...sanitizeCollectionConfig({ collection, pluginConfig }))\n }\n\n for (const global of config.globals ?? []) {\n items.push(...sanitizeGlobalConfig({ global, pluginConfig }))\n }\n\n for (const [configKey, { mcpName, tool }] of TOOL_BUILTIN_ENTRIES) {\n items.push({\n type: 'tool',\n configKey,\n label: tool.annotations?.title ?? configKey,\n mcpName,\n tool: { ...tool, access: tool.access ?? defaultAccess },\n })\n }\n\n for (const [configKey, tool] of Object.entries(pluginConfig.tools ?? {})) {\n if (configKey in TOOL_BUILTINS) {\n continue\n }\n items.push({\n type: 'tool',\n configKey,\n label: tool.annotations?.title ?? configKey,\n mcpName: configKey,\n tool: { ...tool, access: tool.access ?? defaultAccess },\n })\n }\n\n for (const [configKey, prompt] of Object.entries(pluginConfig.prompts ?? {})) {\n items.push({\n type: 'prompt',\n configKey,\n label: prompt.title ?? configKey,\n mcpName: configKey,\n prompt: { ...prompt, access: prompt.access ?? defaultAccess },\n })\n }\n\n for (const [configKey, resource] of Object.entries(pluginConfig.resources ?? {})) {\n items.push({\n type: 'resource',\n configKey,\n label: resource.title ?? configKey,\n mcpName: configKey,\n resource: { ...resource, access: resource.access ?? defaultAccess },\n })\n }\n\n return {\n disabled: pluginConfig.disabled,\n hooks: pluginConfig.hooks,\n items,\n mcp: pluginConfig.mcp,\n overrideGetAuthorizedMCP: pluginConfig.overrideGetAuthorizedMCP,\n }\n}\n\nconst sanitizeCollectionConfig = ({\n collection,\n pluginConfig,\n}: {\n collection: CollectionConfig | SanitizedCollectionConfig\n pluginConfig: MCPPluginConfig\n}): CollectionMCPItem[] => {\n const slug = collection.slug\n const collectionPluginConfig = pluginConfig.collections?.[slug]\n const items: CollectionMCPItem[] = []\n /**\n * Payload disables duplicate for auth collections by default unless the\n * collection explicitly opts back in with `disableDuplicate: false`.\n */\n const isDuplicateDisabled =\n collection.disableDuplicate === true ||\n (Boolean(collection.auth) && collection.disableDuplicate !== false)\n\n for (const [\n toolKey,\n { mcpName, requiresDuplicateEnabled, requiresUpload, requiresVersions, tool },\n ] of COLLECTION_BUILTIN_ENTRIES) {\n if (requiresVersions && !collection.versions) {\n continue\n }\n if (requiresDuplicateEnabled && isDuplicateDisabled) {\n continue\n }\n if (requiresUpload && !collection.upload) {\n continue\n }\n const matchedConfigEntry = collectionPluginConfig?.tools?.[toolKey]\n if (matchedConfigEntry === false) {\n continue\n }\n const override = typeof matchedConfigEntry === 'object' ? matchedConfigEntry : undefined\n const annotations = { ...tool.annotations, ...override?.annotations }\n items.push({\n type: 'collectionTool',\n collectionSlug: slug,\n configKey: toolKey,\n label: annotations.title ?? toolKey,\n mcpName,\n tool: {\n ...tool,\n access: override?.access ?? tool.access ?? defaultAccess,\n annotations,\n description: override?.description ?? tool.description,\n overrideResponse:\n override?.overrideResponse ??\n collectionPluginConfig?.overrideResponse ??\n tool.overrideResponse,\n },\n })\n }\n\n if (collection.auth) {\n for (const [authToolKey, { mcpName, tool }] of COLLECTION_AUTH_BUILTIN_ENTRIES) {\n const matchedConfigEntry = collectionPluginConfig?.tools?.[authToolKey]\n if (!matchedConfigEntry) {\n continue\n }\n // `true` means \"enable, no override\"; only the object form carries fields.\n const override = typeof matchedConfigEntry === 'object' ? matchedConfigEntry : undefined\n const annotations = { ...tool.annotations, ...override?.annotations }\n items.push({\n type: 'collectionTool',\n collectionSlug: slug,\n configKey: authToolKey,\n label: annotations.title ?? authToolKey,\n mcpName,\n tool: {\n ...tool,\n access: override?.access ?? tool.access ?? defaultAccess,\n annotations,\n description: override?.description ?? tool.description,\n overrideResponse:\n override?.overrideResponse ??\n collectionPluginConfig?.overrideResponse ??\n tool.overrideResponse,\n },\n })\n }\n }\n\n // Cast: builtin keys are filtered out below, so the remaining values are\n // always custom tools (`CollectionTool`) or undefined\n const customEntries = Object.entries(collectionPluginConfig?.tools ?? {}) as Array<\n [string, CollectionTool | undefined]\n >\n for (const [configKey, customTool] of customEntries) {\n if (configKey in COLLECTION_BUILTINS || configKey in COLLECTION_AUTH_BUILTINS) {\n continue\n }\n if (!customTool) {\n continue\n }\n items.push({\n type: 'collectionTool',\n collectionSlug: slug,\n configKey,\n label: customTool.annotations?.title ?? configKey,\n mcpName: configKey,\n tool: { ...customTool, access: customTool.access ?? defaultAccess },\n })\n }\n\n return items\n}\n\nconst sanitizeGlobalConfig = ({\n global,\n pluginConfig,\n}: {\n global: GlobalConfig | SanitizedGlobalConfig\n pluginConfig: MCPPluginConfig\n}): GlobalMCPItem[] => {\n const slug = global.slug\n const globalPluginConfig = pluginConfig.globals?.[slug]\n const items: GlobalMCPItem[] = []\n\n for (const [toolKey, { mcpName, requiresVersions, tool }] of GLOBAL_BUILTIN_ENTRIES) {\n if (requiresVersions && !global.versions) {\n continue\n }\n const matchedConfigEntry = globalPluginConfig?.tools?.[toolKey]\n if (matchedConfigEntry === false) {\n continue\n }\n const override = typeof matchedConfigEntry === 'object' ? matchedConfigEntry : undefined\n const annotations = { ...tool.annotations, ...override?.annotations }\n items.push({\n type: 'globalTool',\n configKey: toolKey,\n globalSlug: slug,\n label: annotations.title ?? toolKey,\n mcpName,\n tool: {\n ...tool,\n access: override?.access ?? tool.access ?? defaultAccess,\n annotations,\n description: override?.description ?? tool.description,\n overrideResponse:\n override?.overrideResponse ??\n globalPluginConfig?.overrideResponse ??\n tool.overrideResponse,\n },\n })\n }\n\n const customEntries = Object.entries(globalPluginConfig?.tools ?? {}) as Array<\n [string, GlobalTool | undefined]\n >\n for (const [configKey, customTool] of customEntries) {\n if (configKey in GLOBAL_BUILTINS) {\n continue\n }\n if (!customTool) {\n continue\n }\n items.push({\n type: 'globalTool',\n configKey,\n globalSlug: slug,\n label: customTool.annotations?.title ?? configKey,\n mcpName: configKey,\n tool: { ...customTool, access: customTool.access ?? defaultAccess },\n })\n }\n\n return items\n}\n"],"names":["defaultAccess","COLLECTION_AUTH_BUILTIN_ENTRIES","COLLECTION_AUTH_BUILTINS","COLLECTION_BUILTIN_ENTRIES","COLLECTION_BUILTINS","GLOBAL_BUILTIN_ENTRIES","GLOBAL_BUILTINS","TOOL_BUILTIN_ENTRIES","TOOL_BUILTINS","sanitizeMCPConfig","config","pluginConfig","items","collection","collections","push","sanitizeCollectionConfig","global","globals","sanitizeGlobalConfig","configKey","mcpName","tool","type","label","annotations","title","access","Object","entries","tools","prompt","prompts","resource","resources","disabled","hooks","mcp","overrideGetAuthorizedMCP","slug","collectionPluginConfig","isDuplicateDisabled","disableDuplicate","Boolean","auth","toolKey","requiresDuplicateEnabled","requiresUpload","requiresVersions","versions","upload","matchedConfigEntry","override","undefined","collectionSlug","description","overrideResponse","authToolKey","customEntries","customTool","globalPluginConfig","globalSlug"],"mappings":"AAmBA,SAASA,aAAa,QAAQ,sBAAqB;AACnD,SACEC,+BAA+B,EAC/BC,wBAAwB,EACxBC,0BAA0B,EAC1BC,mBAAmB,EACnBC,sBAAsB,EACtBC,eAAe,EACfC,oBAAoB,EACpBC,aAAa,QACR,oBAAmB;AAE1B;;;;;;;;CAQC,GACD,OAAO,MAAMC,oBAAoB,CAAC,EAChCC,MAAM,EACNC,YAAY,EAIb;IACC,MAAMC,QAAmB,EAAE;IAE3B,KAAK,MAAMC,cAAcH,OAAOI,WAAW,IAAI,EAAE,CAAE;QACjDF,MAAMG,IAAI,IAAIC,yBAAyB;YAAEH;YAAYF;QAAa;IACpE;IAEA,KAAK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NH;YACAyC,YAAYtB;YACZf,OAAOmC,WAAWlC,WAAW,EAAEC,SAASN;YACxCC,SAASD;YACTE,MAAM;gBAAE,GAAGqC,UAAU;gBAAEhC,QAAQgC,WAAWhC,MAAM,IAAI3B;YAAc;QACpE;IACF;IAEA,OAAOY;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"stdio.d.ts","sourceRoot":"","sources":["../src/stdio.ts"],"names":[],"mappings":"AAgBA;;;;;GAKG;AACH,eAAO,MAAM,WAAW,QAAa,OAAO,CAAC,IAAI,CA2GhD,CAAA"}
1
+ {"version":3,"file":"stdio.d.ts","sourceRoot":"","sources":["../src/stdio.ts"],"names":[],"mappings":"AAgBA;;;;;GAKG;AACH,eAAO,MAAM,WAAW,QAAa,OAAO,CAAC,IAAI,CA4GhD,CAAA"}
package/dist/stdio.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /* eslint-disable no-console */ import { serveStdio } from '@modelcontextprotocol/server/stdio';
2
2
  import { fileURLToPath, pathToFileURL } from 'node:url';
3
3
  import { createLocalReq, getPayload } from 'payload';
4
- import { findConfig } from 'payload/node';
4
+ import { findConfig, loadEnv } from 'payload/node';
5
5
  import { getAuthorizedMCP } from './endpoint/access.js';
6
6
  import { buildMcpServer } from './mcp/buildMcpServer.js';
7
7
  import { sanitizeMCPConfig } from './mcp/sanitizeMCPConfig.js';
@@ -19,6 +19,7 @@ import { resolveProjectRoot } from './utils/resolveProjectRoot.js';
19
19
  if (projectRoot) {
20
20
  process.chdir(projectRoot);
21
21
  }
22
+ loadEnv();
22
23
  const configPath = findConfig();
23
24
  const configModule = await import(pathToFileURL(configPath).toString());
24
25
  const config = await (configModule.default ?? configModule);
package/dist/stdio.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/stdio.ts"],"sourcesContent":["import type { Config, Plugin, SanitizedConfig } from 'payload'\n\n/* eslint-disable no-console */\nimport { serveStdio } from '@modelcontextprotocol/server/stdio'\nimport { fileURLToPath, pathToFileURL } from 'node:url'\nimport { createLocalReq, getPayload } from 'payload'\nimport { findConfig } from 'payload/node'\n\nimport type { SanitizedMCPPluginConfig } from './types.js'\n\nimport { getAuthorizedMCP } from './endpoint/access.js'\nimport { buildMcpServer } from './mcp/buildMcpServer.js'\nimport { sanitizeMCPConfig } from './mcp/sanitizeMCPConfig.js'\nimport { getPluginConfig } from './utils/getPluginConfig.js'\nimport { resolveProjectRoot } from './utils/resolveProjectRoot.js'\n\n/**\n * Starts Payload's MCP server over stdin and stdout.\n *\n * Set `PAYLOAD_MCP_AUTHORIZATION` to authenticate. In development,\n * `PAYLOAD_MCP_OVERRIDE_ACCESS=true` skips access checks.\n */\nexport const runMcpStdio = async (): Promise<void> => {\n // MCP clients may start this command from another folder. Move to the Payload\n // project so findConfig() can find the config.\n const projectRoot = resolveProjectRoot(fileURLToPath(import.meta.url))\n if (projectRoot) {\n process.chdir(projectRoot)\n }\n\n const configPath = findConfig()\n const configModule = await import(pathToFileURL(configPath).toString())\n const config = (await (configModule.default ?? configModule)) as SanitizedConfig\n\n /**\n * stdout is only for MCP messages. The spec says the server must not write\n * logs there and may write them to stderr instead.\n *\n * The 2.0 client library recovers from stray stdout logs, but that behavior is not\n * guaranteed. Move Payload logs to stderr so Payload does not add invalid data\n * to stdout. Keep options from configurable loggers. Replace pre-built loggers\n * because their output cannot be redirected.\n *\n * @see https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#stdio\n */\n const loggerConfig: { logger?: Config['logger'] } = config\n if (\n loggerConfig.logger &&\n typeof loggerConfig.logger === 'object' &&\n 'options' in loggerConfig.logger\n ) {\n loggerConfig.logger.destination = process.stderr\n } else {\n loggerConfig.logger = { destination: process.stderr, options: {} }\n }\n\n const payload = await getPayload({ config, cron: false, disableOnInit: true })\n\n let pluginConfig: SanitizedMCPPluginConfig\n try {\n pluginConfig = getPluginConfig({ config: payload.config })\n } catch {\n // The command also works when mcpPlugin() is not in the Payload config.\n pluginConfig = sanitizeMCPConfig({ config: payload.config, pluginConfig: {} })\n\n const fallbackPlugin: Plugin = (config) => config\n Object.assign(fallbackPlugin, {\n slug: '@payloadcms/plugin-mcp',\n sanitizedOptions: pluginConfig,\n })\n payload.config.plugins ??= []\n payload.config.plugins.push(fallbackPlugin)\n }\n\n const overrideAccessEnv = process.env.PAYLOAD_MCP_OVERRIDE_ACCESS\n let overrideAccess = false\n\n if (overrideAccessEnv === 'true') {\n overrideAccess = true\n } else if (overrideAccessEnv && overrideAccessEnv !== 'false') {\n throw new Error('PAYLOAD_MCP_OVERRIDE_ACCESS must be \"true\" or \"false\".')\n }\n\n if (overrideAccess && process.env.NODE_ENV !== 'development') {\n throw new Error('PAYLOAD_MCP_OVERRIDE_ACCESS is only available in development.')\n }\n\n const headers = new Headers()\n if (process.env.PAYLOAD_MCP_AUTHORIZATION) {\n headers.set('Authorization', process.env.PAYLOAD_MCP_AUTHORIZATION)\n }\n\n const req = await createLocalReq({ req: { headers } }, payload)\n req.payloadAPI = 'MCP' as const\n const authorizedMCP = await getAuthorizedMCP({ overrideAccess, req })\n\n const stdioServer = serveStdio(() => buildMcpServer({ authorizedMCP, pluginConfig, req }), {\n onerror: (err) => {\n // MCP messages use stdout, so write SDK errors to stderr.\n console.error('[payload-mcp] error serving MCP over stdio:', err)\n },\n })\n\n // Close the MCP server and Payload when the client disconnects or the process stops.\n let isShuttingDown = false\n const shutdown = async () => {\n if (isShuttingDown) {\n return\n }\n isShuttingDown = true\n\n try {\n await stdioServer.close()\n } catch (err) {\n console.error('[payload-mcp] error closing server:', err)\n }\n\n try {\n await payload.destroy()\n } catch (err) {\n console.error('[payload-mcp] error destroying payload:', err)\n }\n\n process.exit(0)\n }\n\n process.once('SIGINT', () => void shutdown())\n process.once('SIGTERM', () => void shutdown())\n process.stdin.once('close', () => void shutdown())\n}\n"],"names":["serveStdio","fileURLToPath","pathToFileURL","createLocalReq","getPayload","findConfig","getAuthorizedMCP","buildMcpServer","sanitizeMCPConfig","getPluginConfig","resolveProjectRoot","runMcpStdio","projectRoot","url","process","chdir","configPath","configModule","toString","config","default","loggerConfig","logger","destination","stderr","options","payload","cron","disableOnInit","pluginConfig","fallbackPlugin","Object","assign","slug","sanitizedOptions","plugins","push","overrideAccessEnv","env","PAYLOAD_MCP_OVERRIDE_ACCESS","overrideAccess","Error","NODE_ENV","headers","Headers","PAYLOAD_MCP_AUTHORIZATION","set","req","payloadAPI","authorizedMCP","stdioServer","onerror","err","console","error","isShuttingDown","shutdown","close","destroy","exit","once","stdin"],"mappings":"AAEA,6BAA6B,GAC7B,SAASA,UAAU,QAAQ,qCAAoC;AAC/D,SAASC,aAAa,EAAEC,aAAa,QAAQ,WAAU;AACvD,SAASC,cAAc,EAAEC,UAAU,QAAQ,UAAS;AACpD,SAASC,UAAU,QAAQ,eAAc;AAIzC,SAASC,gBAAgB,QAAQ,uBAAsB;AACvD,SAASC,cAAc,QAAQ,0BAAyB;AACxD,SAASC,iBAAiB,QAAQ,6BAA4B;AAC9D,SAASC,eAAe,QAAQ,6BAA4B;AAC5D,SAASC,kBAAkB,QAAQ,gCAA+B;AAElE;;;;;CAKC,GACD,OAAO,MAAMC,cAAc;IACzB,8EAA8E;IAC9E,+CAA+C;IAC/C,MAAMC,cAAcF,mBAAmBT,cAAc,YAAYY,GAAG;IACpE,IAAID,aAAa;QACfE,QAAQC,KAAK,CAACH;IAChB;IAEA,MAAMI,aAAaX;IACnB,MAAMY,eAAe,MAAM,MAAM,CAACf,cAAcc,YAAYE,QAAQ;IACpE,MAAMC,SAAU,MAAOF,CAAAA,aAAaG,OAAO,IAAIH,YAAW;IAE1D;;;;;;;;;;GAUC,GACD,MAAMI,eAA8CF;IACpD,IACEE,aAAaC,MAAM,IACnB,OAAOD,aAAaC,MAAM,KAAK,YAC/B,aAAaD,aAAaC,MAAM,EAChC;QACAD,aAAaC,MAAM,CAACC,WAAW,GAAGT,QAAQU,MAAM;IAClD,OAAO;QACLH,aAAaC,MAAM,GAAG;YAAEC,aAAaT,QAAQU,MAAM;YAAEC,SAAS,CA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AA+CF;QAC/D;IACF;IAEA,qFAAqF;IACrF,IAAIG,iBAAiB;IACrB,MAAMC,WAAW;QACf,IAAID,gBAAgB;YAClB;QACF;QACAA,iBAAiB;QAEjB,IAAI;YACF,MAAML,YAAYO,KAAK;QACzB,EAAE,OAAOL,KAAK;YACZC,QAAQC,KAAK,CAAC,uCAAuCF;QACvD;QAEA,IAAI;YACF,MAAM1B,QAAQgC,OAAO;QACvB,EAAE,OAAON,KAAK;YACZC,QAAQC,KAAK,CAAC,2CAA2CF;QAC3D;QAEAtC,QAAQ6C,IAAI,CAAC;IACf;IAEA7C,QAAQ8C,IAAI,CAAC,UAAU,IAAM,KAAKJ;IAClC1C,QAAQ8C,IAAI,CAAC,WAAW,IAAM,KAAKJ;IACnC1C,QAAQ+C,KAAK,CAACD,IAAI,CAAC,SAAS,IAAM,KAAKJ;AACzC,EAAC"}
1
+ {"version":3,"sources":["../src/stdio.ts"],"sourcesContent":["import type { Config, Plugin, SanitizedConfig } from 'payload'\n\n/* eslint-disable no-console */\nimport { serveStdio } from '@modelcontextprotocol/server/stdio'\nimport { fileURLToPath, pathToFileURL } from 'node:url'\nimport { createLocalReq, getPayload } from 'payload'\nimport { findConfig, loadEnv } from 'payload/node'\n\nimport type { SanitizedMCPPluginConfig } from './types.js'\n\nimport { getAuthorizedMCP } from './endpoint/access.js'\nimport { buildMcpServer } from './mcp/buildMcpServer.js'\nimport { sanitizeMCPConfig } from './mcp/sanitizeMCPConfig.js'\nimport { getPluginConfig } from './utils/getPluginConfig.js'\nimport { resolveProjectRoot } from './utils/resolveProjectRoot.js'\n\n/**\n * Starts Payload's MCP server over stdin and stdout.\n *\n * Set `PAYLOAD_MCP_AUTHORIZATION` to authenticate. In development,\n * `PAYLOAD_MCP_OVERRIDE_ACCESS=true` skips access checks.\n */\nexport const runMcpStdio = async (): Promise<void> => {\n // MCP clients may start this command from another folder. Move to the Payload\n // project so findConfig() can find the config.\n const projectRoot = resolveProjectRoot(fileURLToPath(import.meta.url))\n if (projectRoot) {\n process.chdir(projectRoot)\n }\n\n loadEnv()\n const configPath = findConfig()\n const configModule = await import(pathToFileURL(configPath).toString())\n const config = (await (configModule.default ?? configModule)) as SanitizedConfig\n\n /**\n * stdout is only for MCP messages. The spec says the server must not write\n * logs there and may write them to stderr instead.\n *\n * The 2.0 client library recovers from stray stdout logs, but that behavior is not\n * guaranteed. Move Payload logs to stderr so Payload does not add invalid data\n * to stdout. Keep options from configurable loggers. Replace pre-built loggers\n * because their output cannot be redirected.\n *\n * @see https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#stdio\n */\n const loggerConfig: { logger?: Config['logger'] } = config\n if (\n loggerConfig.logger &&\n typeof loggerConfig.logger === 'object' &&\n 'options' in loggerConfig.logger\n ) {\n loggerConfig.logger.destination = process.stderr\n } else {\n loggerConfig.logger = { destination: process.stderr, options: {} }\n }\n\n const payload = await getPayload({ config, cron: false, disableOnInit: true })\n\n let pluginConfig: SanitizedMCPPluginConfig\n try {\n pluginConfig = getPluginConfig({ config: payload.config })\n } catch {\n // The command also works when mcpPlugin() is not in the Payload config.\n pluginConfig = sanitizeMCPConfig({ config: payload.config, pluginConfig: {} })\n\n const fallbackPlugin: Plugin = (config) => config\n Object.assign(fallbackPlugin, {\n slug: '@payloadcms/plugin-mcp',\n sanitizedOptions: pluginConfig,\n })\n payload.config.plugins ??= []\n payload.config.plugins.push(fallbackPlugin)\n }\n\n const overrideAccessEnv = process.env.PAYLOAD_MCP_OVERRIDE_ACCESS\n let overrideAccess = false\n\n if (overrideAccessEnv === 'true') {\n overrideAccess = true\n } else if (overrideAccessEnv && overrideAccessEnv !== 'false') {\n throw new Error('PAYLOAD_MCP_OVERRIDE_ACCESS must be \"true\" or \"false\".')\n }\n\n if (overrideAccess && process.env.NODE_ENV !== 'development') {\n throw new Error('PAYLOAD_MCP_OVERRIDE_ACCESS is only available in development.')\n }\n\n const headers = new Headers()\n if (process.env.PAYLOAD_MCP_AUTHORIZATION) {\n headers.set('Authorization', process.env.PAYLOAD_MCP_AUTHORIZATION)\n }\n\n const req = await createLocalReq({ req: { headers } }, payload)\n req.payloadAPI = 'MCP' as const\n const authorizedMCP = await getAuthorizedMCP({ overrideAccess, req })\n\n const stdioServer = serveStdio(() => buildMcpServer({ authorizedMCP, pluginConfig, req }), {\n onerror: (err) => {\n // MCP messages use stdout, so write SDK errors to stderr.\n console.error('[payload-mcp] error serving MCP over stdio:', err)\n },\n })\n\n // Close the MCP server and Payload when the client disconnects or the process stops.\n let isShuttingDown = false\n const shutdown = async () => {\n if (isShuttingDown) {\n return\n }\n isShuttingDown = true\n\n try {\n await stdioServer.close()\n } catch (err) {\n console.error('[payload-mcp] error closing server:', err)\n }\n\n try {\n await payload.destroy()\n } catch (err) {\n console.error('[payload-mcp] error destroying payload:', err)\n }\n\n process.exit(0)\n }\n\n process.once('SIGINT', () => void shutdown())\n process.once('SIGTERM', () => void shutdown())\n process.stdin.once('close', () => void shutdown())\n}\n"],"names":["serveStdio","fileURLToPath","pathToFileURL","createLocalReq","getPayload","findConfig","loadEnv","getAuthorizedMCP","buildMcpServer","sanitizeMCPConfig","getPluginConfig","resolveProjectRoot","runMcpStdio","projectRoot","url","process","chdir","configPath","configModule","toString","config","default","loggerConfig","logger","destination","stderr","options","payload","cron","disableOnInit","pluginConfig","fallbackPlugin","Object","assign","slug","sanitizedOptions","plugins","push","overrideAccessEnv","env","PAYLOAD_MCP_OVERRIDE_ACCESS","overrideAccess","Error","NODE_ENV","headers","Headers","PAYLOAD_MCP_AUTHORIZATION","set","req","payloadAPI","authorizedMCP","stdioServer","onerror","err","console","error","isShuttingDown","shutdown","close","destroy","exit","once","stdin"],"mappings":"AAEA,6BAA6B,GAC7B,SAASA,UAAU,QAAQ,qCAAoC;AAC/D,SAASC,aAAa,EAAEC,aAAa,QAAQ,WAAU;AACvD,SAASC,cAAc,EAAEC,UAAU,QAAQ,UAAS;AACpD,SAASC,UAAU,EAAEC,OAAO,QAAQ,eAAc;AAIlD,SAASC,gBAAgB,Q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K,CAACD,IAAI,CAAC,SAAS,IAAM,KAAKJ;AACzC,EAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@payloadcms/plugin-mcp",
3
- "version": "4.0.0-internal.e55ccef",
3
+ "version": "4.0.0-internal.e7d4ebc",
4
4
  "description": "MCP (Model Context Protocol) capabilities with Payload",
5
5
  "keywords": [
6
6
  "plugin",
@@ -61,10 +61,10 @@
61
61
  },
62
62
  "devDependencies": {
63
63
  "@payloadcms/eslint-config": "3.28.0",
64
- "payload": "4.0.0-internal.e55ccef"
64
+ "payload": "4.0.0-internal.e7d4ebc"
65
65
  },
66
66
  "peerDependencies": {
67
- "payload": "4.0.0-internal.e55ccef"
67
+ "payload": "4.0.0-internal.e7d4ebc"
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,11 +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, resolveFileInput } from './fileInput.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) =>
@@ -87,7 +87,7 @@ export const createDocumentTool = defineCollectionTool({
87
87
  }
88
88
 
89
89
  const parsedData = transformPointDataToPayload(inputData)
90
- const file = await resolveFileInput({ collectionSlug, input: fileInput, req })
90
+ const file = await resolveFile({ collectionSlug, input: fileInput, req })
91
91
 
92
92
  const result = await payload.create({
93
93
  collection: collectionSlug,
@@ -2,7 +2,7 @@ import type { PayloadRequest } from 'payload'
2
2
 
3
3
  import { describe, expect, it } from 'vitest'
4
4
 
5
- import { fileInputSchema, resolveFileInput } from './fileInput.js'
5
+ import { fileInputSchema, resolveFile } from './fileInput.js'
6
6
 
7
7
  describe('MCP file input', () => {
8
8
  it('should reject malformed MIME types', () => {
@@ -16,11 +16,25 @@ describe('MCP file input', () => {
16
16
  expect(result.success).toBe(false)
17
17
  })
18
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
+
19
33
  it('should reject oversized base64 files', async () => {
20
34
  const req = createRequest({ maxFileSize: 4 })
21
35
 
22
36
  await expect(
23
- resolveFileInput({
37
+ resolveFile({
24
38
  collectionSlug: 'media',
25
39
  input: {
26
40
  data: Buffer.from('hello').toString('base64'),
@@ -39,10 +53,10 @@ describe('MCP file input', () => {
39
53
  })
40
54
 
41
55
  await expect(
42
- resolveFileInput({
56
+ resolveFile({
43
57
  collectionSlug: 'media',
44
58
  input: {
45
- source: 'url',
59
+ source: 'externalURL',
46
60
  url: 'https://example.com/image.png',
47
61
  },
48
62
  req,
@@ -1,7 +1,7 @@
1
1
  import type { CollectionSlug, File, FileData, PayloadRequest } from 'payload'
2
2
 
3
3
  import { APIError } from 'payload'
4
- import { getExternalFile, isURLAllowed } from 'payload/internal'
4
+ import { getExternalFile, getFileFromUploadInstructions, isURLAllowed } from 'payload/internal'
5
5
  import { sanitizeFilename } from 'payload/shared'
6
6
  import { z } from 'zod'
7
7
 
@@ -9,6 +9,13 @@ const mimeTypeSchema = z
9
9
  .string()
10
10
  .regex(/^[!#$%&'*+.^`|~\w-]+\/[!#$%&'*+.^`|~\w-]+$/, 'MIME type must use the type/subtype format')
11
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
+
12
19
  export const fileInputSchema = z
13
20
  .discriminatedUnion('source', [
14
21
  z.object({
@@ -19,17 +26,21 @@ export const fileInputSchema = z
19
26
  }),
20
27
  z.object({
21
28
  name: z.string().min(1).describe('Optional file name override').optional(),
22
- source: z.literal('url'),
29
+ source: z.literal('externalURL'),
23
30
  url: z.url().describe('The http or https URL to download'),
24
31
  }),
32
+ z.object({
33
+ file: uploadFileSchema.describe('The file value returned by getUploadInstructions'),
34
+ source: z.literal('uploadReference'),
35
+ }),
25
36
  ])
26
37
  .describe(
27
- 'A file for an upload collection. Use only a source listed by getCollectionSchema: url for an online file or base64 for a local file.',
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.',
28
39
  )
29
40
 
30
41
  type FileInput = z.infer<typeof fileInputSchema>
31
42
 
32
- export async function resolveFileInput({
43
+ export async function resolveFile({
33
44
  collectionSlug,
34
45
  input,
35
46
  req,
@@ -42,6 +53,10 @@ export async function resolveFileInput({
42
53
  return undefined
43
54
  }
44
55
 
56
+ if (input.source === 'uploadReference') {
57
+ return getFileFromUploadInstructions({ collectionSlug, file: input.file, req })
58
+ }
59
+
45
60
  const uploadConfig = req.payload.collections[collectionSlug]?.config.upload
46
61
 
47
62
  if (!uploadConfig) {
@@ -55,7 +55,11 @@ export const getCollectionSchemaTool = defineCollectionTool({
55
55
  enabled: true,
56
56
  filesRequiredOnCreate: uploadConfig.filesRequiredOnCreate !== false,
57
57
  mimeTypes: uploadConfig.mimeTypes ?? ['*/*'],
58
- sources: [...(uploadConfig.pasteURL !== false ? ['url'] : []), 'base64'],
58
+ sources: [
59
+ ...(uploadConfig.pasteURL !== false ? ['externalURL'] : []),
60
+ 'base64',
61
+ 'uploadReference',
62
+ ],
59
63
  ...(typeof maxFileSize === 'number' && Number.isFinite(maxFileSize) ? { maxFileSize } : {}),
60
64
  }
61
65
  : { enabled: false }
@@ -13,11 +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, resolveFileInput } from './fileInput.js'
16
+ import { fileInputSchema, resolveFile } from './fileInput.js'
17
17
  import { formatCollectionError } from './formatCollectionError.js'
18
18
 
19
19
  const DEFAULT_DESCRIPTION =
20
- '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.'
21
21
 
22
22
  export const updateDocumentTool = defineCollectionTool({
23
23
  access: (args) =>
@@ -132,7 +132,7 @@ export const updateDocumentTool = defineCollectionTool({
132
132
  }
133
133
 
134
134
  const parsedData = transformPointDataToPayload(inputData)
135
- const file = await resolveFileInput({ collectionSlug, input: fileInput, req })
135
+ const file = await resolveFile({ collectionSlug, input: fileInput, req })
136
136
 
137
137
  const whereClause: Where = where ?? {}
138
138
 
@@ -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