@payloadcms/plugin-mcp 4.0.0-internal.cc18726 → 4.0.0-internal.cd47d20

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 (57) hide show
  1. package/dist/mcp/buildMcpServer.d.ts +1 -1
  2. package/dist/mcp/buildMcpServer.d.ts.map +1 -1
  3. package/dist/mcp/buildMcpServer.js +2 -2
  4. package/dist/mcp/buildMcpServer.js.map +1 -1
  5. package/dist/mcp/builtin/collections/authTools.d.ts.map +1 -1
  6. package/dist/mcp/builtin/collections/authTools.js +4 -3
  7. package/dist/mcp/builtin/collections/authTools.js.map +1 -1
  8. package/dist/mcp/builtin/collections/createTool.d.ts.map +1 -1
  9. package/dist/mcp/builtin/collections/createTool.js +31 -24
  10. package/dist/mcp/builtin/collections/createTool.js.map +1 -1
  11. package/dist/mcp/builtin/collections/deleteTool.js +6 -2
  12. package/dist/mcp/builtin/collections/deleteTool.js.map +1 -1
  13. package/dist/mcp/builtin/collections/duplicateTool.d.ts.map +1 -1
  14. package/dist/mcp/builtin/collections/duplicateTool.js +17 -4
  15. package/dist/mcp/builtin/collections/duplicateTool.js.map +1 -1
  16. package/dist/mcp/builtin/collections/fileInput.d.ts +1 -1
  17. package/dist/mcp/builtin/collections/fileInput.d.ts.map +1 -1
  18. package/dist/mcp/builtin/collections/fileInput.js +19 -54
  19. package/dist/mcp/builtin/collections/fileInput.js.map +1 -1
  20. package/dist/mcp/builtin/collections/findTool.js +7 -3
  21. package/dist/mcp/builtin/collections/findTool.js.map +1 -1
  22. package/dist/mcp/builtin/collections/updateTool.d.ts.map +1 -1
  23. package/dist/mcp/builtin/collections/updateTool.js +25 -15
  24. package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
  25. package/dist/mcp/builtin/formatEntityError.d.ts +16 -0
  26. package/dist/mcp/builtin/formatEntityError.d.ts.map +1 -0
  27. package/dist/mcp/builtin/formatEntityError.js +55 -0
  28. package/dist/mcp/builtin/formatEntityError.js.map +1 -0
  29. package/dist/mcp/builtin/globals/updateTool.d.ts.map +1 -1
  30. package/dist/mcp/builtin/globals/updateTool.js +12 -16
  31. package/dist/mcp/builtin/globals/updateTool.js.map +1 -1
  32. package/dist/stdio.js +4 -3
  33. package/dist/stdio.js.map +1 -1
  34. package/package.json +4 -4
  35. package/src/mcp/buildMcpServer.ts +3 -3
  36. package/src/mcp/builtin/collections/authTools.ts +5 -2
  37. package/src/mcp/builtin/collections/createTool.ts +52 -31
  38. package/src/mcp/builtin/collections/deleteTool.ts +2 -2
  39. package/src/mcp/builtin/collections/duplicateTool.ts +15 -3
  40. package/src/mcp/builtin/collections/fileInput.ts +17 -59
  41. package/src/mcp/builtin/collections/findTool.ts +3 -3
  42. package/src/mcp/builtin/collections/updateTool.ts +14 -14
  43. package/src/mcp/builtin/formatEntityError.ts +77 -0
  44. package/src/mcp/builtin/globals/updateTool.ts +6 -11
  45. package/src/stdio.ts +2 -2
  46. package/dist/mcp/builtin/collections/fileInput.spec.js +0 -86
  47. package/dist/mcp/builtin/collections/fileInput.spec.js.map +0 -1
  48. package/dist/mcp/builtin/collections/formatCollectionError.d.ts +0 -9
  49. package/dist/mcp/builtin/collections/formatCollectionError.d.ts.map +0 -1
  50. package/dist/mcp/builtin/collections/formatCollectionError.js +0 -60
  51. package/dist/mcp/builtin/collections/formatCollectionError.js.map +0 -1
  52. package/dist/mcp/builtin/validateEntityData.d.ts +0 -14
  53. package/dist/mcp/builtin/validateEntityData.d.ts.map +0 -1
  54. package/dist/mcp/builtin/validateEntityData.js +0 -82
  55. package/dist/mcp/builtin/validateEntityData.js.map +0 -1
  56. package/src/mcp/builtin/collections/formatCollectionError.ts +0 -84
  57. package/src/mcp/builtin/validateEntityData.ts +0 -129
@@ -1,5 +1,5 @@
1
1
  import { APIError, z } from 'payload';
2
- import { getExternalFile, getFileFromUploadInstructions, isURLAllowed } from 'payload/internal';
2
+ import { externalURLInputSchema, getFileFromUploadInstructions, resolveURLUploadInput } from 'payload/internal';
3
3
  import { sanitizeFilename } from 'payload/shared';
4
4
  const mimeTypeSchema = z.string().check(z.regex(/^[!#$%&'*+.^`|~\w-]+\/[!#$%&'*+.^`|~\w-]+$/, 'MIME type must use the type/subtype format'));
5
5
  const uploadFileSchema = z.strictObject({
@@ -15,11 +15,7 @@ export const fileInputSchema = z.discriminatedUnion('source', [
15
15
  mimeType: mimeTypeSchema.check(z.describe('The file MIME type, for example image/png.')),
16
16
  source: z.literal('base64')
17
17
  }),
18
- z.strictObject({
19
- name: z.optional(z.string().check(z.minLength(1))).check(z.describe('File name override.')),
20
- source: z.literal('externalURL'),
21
- url: z.url().check(z.describe('The http or https URL to download.'))
22
- }),
18
+ externalURLInputSchema,
23
19
  z.strictObject({
24
20
  file: uploadFileSchema.check(z.describe('getUploadInstructions file field post-upload.')),
25
21
  source: z.literal('uploadReference')
@@ -43,51 +39,28 @@ export async function resolveFile({ slug, input, req }) {
43
39
  throw error;
44
40
  }
45
41
  }
42
+ if (input.source === 'externalURL') {
43
+ return resolveURLUploadInput({
44
+ slug,
45
+ input,
46
+ req
47
+ });
48
+ }
46
49
  const uploadConfig = req.payload.collections[slug]?.config.upload;
47
50
  if (!uploadConfig) {
48
51
  throw new APIError(`Collection "${slug}" does not support file uploads.`, 400);
49
52
  }
50
53
  const maxFileSize = req.payload.config.upload.limits?.fileSize;
51
- let file;
52
- if (input.source === 'base64') {
53
- const data = decodeBase64({
54
- maxFileSize,
55
- value: input.data
56
- });
57
- file = {
58
- name: sanitizeFilename(input.name),
59
- data,
60
- mimetype: input.mimeType,
61
- size: data.length
62
- };
63
- } else {
64
- if (uploadConfig.pasteURL === false) {
65
- throw new APIError(`Uploading files from URLs is disabled for collection "${slug}".`, 400);
66
- }
67
- const url = new URL(input.url);
68
- if (![
69
- 'http:',
70
- 'https:'
71
- ].includes(url.protocol)) {
72
- throw new APIError('File URLs must use http or https.', 400);
73
- }
74
- if (typeof uploadConfig.pasteURL === 'object' && !isURLAllowed(input.url, uploadConfig.pasteURL.allowList)) {
75
- throw new APIError('The provided file URL is not allowed.', 400);
76
- }
77
- file = await getExternalFile({
78
- data: {
79
- filename: sanitizeFilename(input.name || getURLFilename(url)),
80
- url: input.url
81
- },
82
- req,
83
- uploadConfig: {
84
- ...uploadConfig,
85
- externalFileHeaderFilter: uploadConfig.externalFileHeaderFilter ?? (()=>({}))
86
- }
87
- });
88
- file.mimetype = file.mimetype?.split(';')[0] || 'application/octet-stream';
89
- file.size = file.data.length;
90
- }
54
+ const data = decodeBase64({
55
+ maxFileSize,
56
+ value: input.data
57
+ });
58
+ const file = {
59
+ name: sanitizeFilename(input.name),
60
+ data,
61
+ mimetype: input.mimeType,
62
+ size: data.length
63
+ };
91
64
  if (maxFileSize !== undefined && Number.isFinite(maxFileSize) && file.size > maxFileSize) {
92
65
  throw new APIError(`File exceeds the ${maxFileSize} byte upload limit.`, 400);
93
66
  }
@@ -111,13 +84,5 @@ function decodeBase64({ maxFileSize, value }) {
111
84
  }
112
85
  return data;
113
86
  }
114
- function getURLFilename(url) {
115
- const pathSegment = url.pathname.split('/').pop() || 'upload';
116
- try {
117
- return decodeURIComponent(pathSegment);
118
- } catch {
119
- return pathSegment;
120
- }
121
- }
122
87
 
123
88
  //# sourceMappingURL=fileInput.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/mcp/builtin/collections/fileInput.ts"],"sourcesContent":["import type { CollectionSlug, File, FileData, PayloadRequest } from 'payload'\n\nimport { APIError, z } from 'payload'\nimport { getExternalFile, getFileFromUploadInstructions, isURLAllowed } from 'payload/internal'\nimport { sanitizeFilename } from 'payload/shared'\n\nconst mimeTypeSchema = z\n .string()\n .check(\n z.regex(\n /^[!#$%&'*+.^`|~\\w-]+\\/[!#$%&'*+.^`|~\\w-]+$/,\n 'MIME type must use the type/subtype format',\n ),\n )\n\nconst uploadFileSchema = z.strictObject({\n filename: z.string(),\n mimeType: z.string(),\n size: z.int().check(z.nonnegative()),\n uploadReference: z.record(z.string(), z.unknown()),\n})\n\nexport const fileInputSchema = z\n .discriminatedUnion('source', [\n z.strictObject({\n name: z.string().check(z.minLength(1), z.describe('The file name, including its extension.')),\n data: z\n .string()\n .check(z.describe('The base64-encoded file bytes, without a data URL prefix.')),\n mimeType: mimeTypeSchema.check(z.describe('The file MIME type, for example image/png.')),\n source: z.literal('base64'),\n }),\n z.strictObject({\n name: z.optional(z.string().check(z.minLength(1))).check(z.describe('File name override.')),\n source: z.literal('externalURL'),\n url: z.url().check(z.describe('The http or https URL to download.')),\n }),\n z.strictObject({\n file: uploadFileSchema.check(z.describe('getUploadInstructions file field post-upload.')),\n source: z.literal('uploadReference'),\n }),\n ])\n .check(\n z.describe(\n 'A file for an upload collection. Prefer uploadReference after its upload succeeds; use base64 only for small local files or externalURL for an online file.',\n ),\n )\n\ntype FileInput = z.infer<typeof fileInputSchema>\n\nexport async function resolveFile({\n slug,\n input,\n req,\n}: {\n input?: FileInput\n req: PayloadRequest\n slug: CollectionSlug\n}): Promise<File | undefined> {\n if (!input) {\n return undefined\n }\n\n if (input.source === 'uploadReference') {\n try {\n return await getFileFromUploadInstructions({ collectionSlug: slug, file: input.file, req })\n } catch (error) {\n if (error instanceof Error && error.message === 'Staged upload was not found.') {\n throw new APIError(\n 'Staged upload not found. Complete the upload action first, or use base64 for small local files.',\n 400,\n )\n }\n throw error\n }\n }\n\n const uploadConfig = req.payload.collections[slug]?.config.upload\n\n if (!uploadConfig) {\n throw new APIError(`Collection \"${slug}\" 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(`Uploading files from URLs is disabled for collection \"${slug}\".`, 400)\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","z","getExternalFile","getFileFromUploadInstructions","isURLAllowed","sanitizeFilename","mimeTypeSchema","string","check","regex","uploadFileSchema","strictObject","filename","mimeType","size","int","nonnegative","uploadReference","record","unknown","fileInputSchema","discriminatedUnion","name","minLength","describe","data","source","literal","optional","url","file","resolveFile","slug","input","req","undefined","collectionSlug","error","Error","message","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,EAAEC,CAAC,QAAQ,UAAS;AACrC,SAASC,eAAe,EAAEC,6BAA6B,EAAEC,YAAY,QAAQ,mBAAkB;AAC/F,SAASC,gBAAgB,QAAQ,iBAAgB;AAEjD,MAAMC,iBAAiBL,EACpBM,MAAM,GACNC,KAAK,CACJP,EAAEQ,KAAK,CACL,8CACA;AAIN,MAAMC,mBAAmBT,EAAEU,YAAY,CAAC;IACtCC,UAAUX,EAAEM,MAAM;IAClBM,UAAUZ,EAAEM,MAAM;IAClBO,MAAMb,EAAEc,GAAG,GAAGP,KAAK,CAACP,EAAEe,WAAW;IACjCC,iBAAiBhB,EAAEiB,MAAM,CAACjB,EAAEM,MAAM,IAAIN,EAAEkB,OAAO;AACjD;AAEA,OAAO,MAAMC,kBAAkBnB,EAC5BoB,kBAAkB,CAAC,UAAU;IAC5BpB,EAAEU,YAAY,CAAC;QACbW,MAAMrB,EAAEM,MAAM,GAAGC,KAAK,CAACP,EAAEsB,SAAS,CAAC,IAAItB,EAAEuB,QAAQ,CAAC;QAClDC,MAAMxB,EACHM,MAAM,GACNC,KAAK,CAACP,EAAEuB,QAAQ,CAAC;QACpBX,UAAUP,eAAeE,KAAK,CAACP,EAAEuB,QAAQ,CAAC;QAC1CE,QAAQzB,EAAE0B,OAAO,CAAC;IACpB;IACA1B,EAAEU,YAAY,CAAC;QACbW,MAAMrB,EAAE2B,QAAQ,CAAC3B,EAAEM,MAAM,GAAGC,KAAK,CAACP,EAAEsB,SAAS,CAAC,KAAKf,KAAK,CAACP,EA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E,MAAM,IAAInD,SAAS,mCAAmC;IACxD;IAEA,IAAI6C,gBAAgBV,aAAayB,OAAOC,QAAQ,CAAChB,cAAc;QAC7D,MAAMoB,gBAAgBH,WAAWI,QAAQ,CAAC,QAAQ,IAAIJ,WAAWI,QAAQ,CAAC,OAAO,IAAI;QACrF,MAAMC,cAAcC,KAAKC,KAAK,CAAC,AAACP,WAAWX,MAAM,GAAG,IAAK,KAAKc;QAE9D,IAAIE,cAActB,aAAa;YAC7B,MAAM,IAAI7C,SAAS,CAAC,iBAAiB,EAAE6C,YAAY,mBAAmB,CAAC,EAAE;QAC3E;IACF;IAEA,MAAMpB,OAAO6C,OAAOC,IAAI,CAACT,YAAY;IAErC,IAAIrC,KAAK+C,QAAQ,CAAC,UAAUT,OAAO,CAAC,OAAO,QAAQD,WAAWC,OAAO,CAAC,OAAO,KAAK;QAChF,MAAM,IAAI/D,SAAS,mCAAmC;IACxD;IAEA,OAAOyB;AACT;AAEA,SAASgC,eAAe5B,GAAQ;IAC9B,MAAM4C,cAAc5C,IAAI6C,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, PayloadRequest } from 'payload'\n\nimport { APIError, z } from 'payload'\nimport {\n externalURLInputSchema,\n getFileFromUploadInstructions,\n resolveURLUploadInput,\n} from 'payload/internal'\nimport { sanitizeFilename } from 'payload/shared'\n\nconst mimeTypeSchema = z\n .string()\n .check(\n z.regex(\n /^[!#$%&'*+.^`|~\\w-]+\\/[!#$%&'*+.^`|~\\w-]+$/,\n 'MIME type must use the type/subtype format',\n ),\n )\n\nconst uploadFileSchema = z.strictObject({\n filename: z.string(),\n mimeType: z.string(),\n size: z.int().check(z.nonnegative()),\n uploadReference: z.record(z.string(), z.unknown()),\n})\n\nexport const fileInputSchema = z\n .discriminatedUnion('source', [\n z.strictObject({\n name: z.string().check(z.minLength(1), z.describe('The file name, including its extension.')),\n data: z\n .string()\n .check(z.describe('The base64-encoded file bytes, without a data URL prefix.')),\n mimeType: mimeTypeSchema.check(z.describe('The file MIME type, for example image/png.')),\n source: z.literal('base64'),\n }),\n externalURLInputSchema,\n z.strictObject({\n file: uploadFileSchema.check(z.describe('getUploadInstructions file field post-upload.')),\n source: z.literal('uploadReference'),\n }),\n ])\n .check(\n z.describe(\n 'A file for an upload collection. Prefer uploadReference after its upload succeeds; use base64 only for small local files or externalURL for an online file.',\n ),\n )\n\ntype FileInput = z.infer<typeof fileInputSchema>\n\nexport async function resolveFile({\n slug,\n input,\n req,\n}: {\n input?: FileInput\n req: PayloadRequest\n slug: CollectionSlug\n}): Promise<File | undefined> {\n if (!input) {\n return undefined\n }\n\n if (input.source === 'uploadReference') {\n try {\n return await getFileFromUploadInstructions({ collectionSlug: slug, file: input.file, req })\n } catch (error) {\n if (error instanceof Error && error.message === 'Staged upload was not found.') {\n throw new APIError(\n 'Staged upload not found. Complete the upload action first, or use base64 for small local files.',\n 400,\n )\n }\n throw error\n }\n }\n\n if (input.source === 'externalURL') {\n return resolveURLUploadInput({ slug, input, req })\n }\n\n const uploadConfig = req.payload.collections[slug]?.config.upload\n\n if (!uploadConfig) {\n throw new APIError(`Collection \"${slug}\" does not support file uploads.`, 400)\n }\n\n const maxFileSize = req.payload.config.upload.limits?.fileSize\n const data = decodeBase64({ maxFileSize, value: input.data })\n const file: File = {\n name: sanitizeFilename(input.name),\n data,\n mimetype: input.mimeType,\n size: 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"],"names":["APIError","z","externalURLInputSchema","getFileFromUploadInstructions","resolveURLUploadInput","sanitizeFilename","mimeTypeSchema","string","check","regex","uploadFileSchema","strictObject","filename","mimeType","size","int","nonnegative","uploadReference","record","unknown","fileInputSchema","discriminatedUnion","name","minLength","describe","data","source","literal","file","resolveFile","slug","input","req","undefined","collectionSlug","error","Error","message","uploadConfig","payload","collections","config","upload","maxFileSize","limits","fileSize","decodeBase64","value","mimetype","length","Number","isFinite","normalized","replace","test","paddingLength","endsWith","decodedSize","Math","floor","Buffer","from","toString"],"mappings":"AAEA,SAASA,QAAQ,EAAEC,CAAC,QAAQ,UAAS;AACrC,SACEC,sBAAsB,EACtBC,6BAA6B,EAC7BC,qBAAqB,QAChB,mBAAkB;AACzB,SAASC,gBAAgB,QAAQ,iBAAgB;AAEjD,MAAMC,iBAAiBL,EACpBM,MAAM,GACNC,KAAK,CACJP,EAAEQ,KAAK,CACL,8CACA;AAIN,MAAMC,mBAAmBT,EAAEU,YAAY,CAAC;IACtCC,UAAUX,EAAEM,MAAM;IAClBM,UAAUZ,EAAEM,MAAM;IAClBO,MAAMb,EAAEc,GAAG,GAAGP,KAAK,CAACP,EAAEe,WAAW;IACjCC,iBAAiBhB,EAAEiB,MAAM,CAACjB,EAAEM,MAAM,IAAIN,EAAEkB,OAAO;AACjD;AAEA,OAAO,MAAMC,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ocumentsInputSchema } from 'payload';
1
+ import { findDocumentsInputSchema, parseDocumentID } from 'payload';
2
2
  import { defaultAccess } from '../../../defaultAccess.js';
3
3
  import { defineCollectionTool } from '../../../defineTool.js';
4
4
  import { getLogger } from '../../../utils/getLogger.js';
@@ -22,10 +22,14 @@ export const findDocumentsTool = defineCollectionTool({
22
22
  const { id, depth, draft, fallbackLocale, joins, limit, locale, page, pagination, populate, select, sort, trash, where } = input;
23
23
  logger.info(`Reading document from collection: ${slug}${id ? ` with ID: ${id}` : ''}, limit: ${limit}, page: ${page}${locale ? `, locale: ${locale}` : ''}`);
24
24
  try {
25
- if (id) {
25
+ if (id !== undefined) {
26
26
  try {
27
27
  const doc = await payload.findByID({
28
- id,
28
+ id: parseDocumentID({
29
+ id,
30
+ collectionSlug: slug,
31
+ payload
32
+ }),
29
33
  collection: slug,
30
34
  depth,
31
35
  overrideAccess: authorizedMCP.overrideAccess,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/mcp/builtin/collections/findTool.ts"],"sourcesContent":["import { findDocumentsInputSchema } from 'payload'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\n\nconst DEFAULT_DESCRIPTION =\n 'Find documents in any collection by passing the collection slug and optional ID or where clause.'\n\nexport const findDocumentsTool = defineCollectionTool({\n access: (args) =>\n defaultAccess(args) && Boolean(args.permissions?.collections?.[args.slug]?.read),\n annotations: {\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n readOnlyHint: true,\n title: 'Find Documents',\n },\n description: DEFAULT_DESCRIPTION,\n input: findDocumentsInputSchema,\n}).handler(async ({ slug, authorizedMCP, input, req }) => {\n const payload = req.payload\n const logger = getLogger({ payload })\n\n const {\n id,\n depth,\n draft,\n fallbackLocale,\n joins,\n limit,\n locale,\n page,\n pagination,\n populate,\n select,\n sort,\n trash,\n where,\n } = input\n\n logger.info(\n `Reading document from collection: ${slug}${id ? ` with ID: ${id}` : ''}, limit: ${limit}, page: ${page}${locale ? `, locale: ${locale}` : ''}`,\n )\n\n try {\n if (id) {\n try {\n const doc = await payload.findByID({\n id,\n collection: slug,\n depth,\n overrideAccess: authorizedMCP.overrideAccess,\n req,\n ...(select && { select }),\n ...(populate && { populate }),\n ...(joins !== undefined && { joins }),\n ...(locale && { locale }),\n ...(fallbackLocale !== undefined && { fallbackLocale }),\n ...(draft !== undefined && { draft }),\n ...(trash !== undefined && { trash }),\n })\n\n return {\n content: [\n {\n type: 'text',\n text: `Document from collection \"${slug}\":\\n${JSON.stringify(doc)}`,\n },\n ],\n doc: doc as Record<string, unknown>,\n }\n } catch {\n logger.warn(`Document not found with ID: ${id} in collection: ${slug}`)\n return {\n content: [\n {\n type: 'text',\n text: `Error: Document with ID \"${id}\" not found in collection \"${slug}\"`,\n },\n ],\n }\n }\n }\n\n const findOptions: Parameters<typeof payload.find>[0] = {\n collection: slug,\n depth,\n limit,\n overrideAccess: authorizedMCP.overrideAccess,\n page,\n req,\n ...(select && { select }),\n ...(populate && { populate }),\n ...(joins !== undefined && { joins }),\n ...(locale && { locale }),\n ...(fallbackLocale !== undefined && { fallbackLocale }),\n ...(draft !== undefined && { draft }),\n ...(pagination !== undefined && { pagination }),\n ...(trash !== undefined && { trash }),\n }\n\n if (sort) {\n findOptions.sort = sort\n }\n if (where) {\n findOptions.where = where\n }\n\n const result = await payload.find(findOptions)\n\n let responseText = `Collection: \"${slug}\"\\nTotal: ${result.totalDocs} documents\\nPage: ${result.page} of ${result.totalPages}\\n`\n for (const doc of result.docs) {\n responseText += `\\n\\`\\`\\`json\\n${JSON.stringify(doc)}\\n\\`\\`\\``\n }\n\n return {\n content: [{ type: 'text', text: responseText }],\n doc: result as unknown as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error reading documents from collection ${slug}: ${errorMessage}`)\n return {\n content: [\n {\n type: 'text',\n text: `❌ **Error reading documents from collection \"${slug}\":** ${errorMessage}`,\n },\n ],\n }\n }\n})\n"],"names":["findDocumentsInputSchema","defaultAccess","defineCollectionTool","getLogger","DEFAULT_DESCRIPTION","findDocumentsTool","access","args","Boolean","permissions","collections","slug","read","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","handler","authorizedMCP","req","payload","logger","id","depth","draft","fallbackLocale","joins","limit","locale","page","pagination","populate","select","sort","trash","where","info","doc","findByID","collection","overrideAccess","undefined","content","type","text","JSON","stringify","warn","findOptions","result","find","responseText","totalDocs","totalPages","docs","error","errorMessage","Error","message"],"mappings":"AAAA,SAASA,wBAAwB,QAAQ,UAAS;AAElD,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AAEvD,MAAMC,sBACJ;AAEF,OAAO,MAAMC,oBAAoBH,qBAAqB;IACpDI,QAAQ,CAACC,OACPN,cAAcM,SAASC,QAAQD,KAAKE,WAAW,EAAEC,aAAa,CAACH,KAAKI,IAAI,CAAC,EAAEC;IAC7EC,aAAa;QACXC,iBAAiB;QACjBC,gBAAgB;QAChBC,eAAe;QACfC,cAAc;QACdC,OAAO;IACT;IACAC,aAAaf;IACbgB,OAAOpB;AACT,GAAGqB,OAAO,CAAC,OAAO,EAAEV,IAAI,EAAEW,aAAa,EAAEF,KAAK,EAAEG,GAAG,EAAE;IACnD,MAAMC,UAAUD,IAAIC,OAAO;IAC3B,MAAMC,SAAStB,UAAU;QAAEqB;IAAQ;IAEnC,MAAM,EACJE,EAAE,EACFC,KAAK,EACLC,KAAK,EACLC,cAAc,EACdC,KAAK,EACLC,KAAK,EACLC,MAAM,EACNC,IAAI,EACJC,UAAU,EACVC,QAAQ,EACRC,MAAM,EACNC,IAAI,EACJC,KAAK,EACLC,KAAK,EACN,GAAGnB;IAEJK,OAAOe,IAAI,CACT,CAAC,kCAAkC,EAAE7B,OAAOe,KAAK,CAAC,UAAU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AAEf;YAAM,CAAC;YACpC,GAAIE,UAAU;gBAAEA;YAAO,CAAC;YACxB,GAAIH,mBAAmBgB,aAAa;gBAAEhB;YAAe,CAAC;YACtD,GAAID,UAAUiB,aAAa;gBAAEjB;YAAM,CAAC;YACpC,GAAIM,eAAeW,aAAa;gBAAEX;YAAW,CAAC;YAC9C,GAAII,UAAUO,aAAa;gBAAEP;YAAM,CAAC;QACtC;QAEA,IAAID,MAAM;YACRe,YAAYf,IAAI,GAAGA;QACrB;QACA,IAAIE,OAAO;YACTa,YAAYb,KAAK,GAAGA;QACtB;QAEA,MAAMc,SAAS,MAAM7B,QAAQ8B,IAAI,CAACF;QAElC,IAAIG,eAAe,CAAC,aAAa,EAAE5C,KAAK,UAAU,EAAE0C,OAAOG,SAAS,CAAC,kBAAkB,EAAEH,OAAOpB,IAAI,CAAC,IAAI,EAAEoB,OAAOI,UAAU,CAAC,EAAE,CAAC;QAChI,KAAK,MAAMhB,OAAOY,OAAOK,IAAI,CAAE;YAC7BH,gBAAgB,CAAC,cAAc,EAAEN,KAAKC,SAAS,CAACT,KAAK,QAAQ,CAAC;QAChE;QAEA,OAAO;YACLK,SAAS;gBAAC;oBAAEC,MAAM;oBAAQC,MAAMO;gBAAa;aAAE;YAC/Cd,KAAKY;QACP;IACF,EAAE,OAAOM,OAAO;QACd,MAAMC,eAAeD,iBAAiBE,QAAQF,MAAMG,OAAO,GAAG;QAC9DrC,OAAOkC,KAAK,CAAC,CAAC,wCAAwC,EAAEhD,KAAK,EAAE,EAAEiD,cAAc;QAC/E,OAAO;YACLd,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,6CAA6C,EAAErC,KAAK,KAAK,EAAEiD,cAAc;gBAClF;aACD;QACH;IACF;AACF,GAAE"}
1
+ {"version":3,"sources":["../../../../src/mcp/builtin/collections/findTool.ts"],"sourcesContent":["import { findDocumentsInputSchema, parseDocumentID } from 'payload'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\n\nconst DEFAULT_DESCRIPTION =\n 'Find documents in any collection by passing the collection slug and optional ID or where clause.'\n\nexport const findDocumentsTool = defineCollectionTool({\n access: (args) =>\n defaultAccess(args) && Boolean(args.permissions?.collections?.[args.slug]?.read),\n annotations: {\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n readOnlyHint: true,\n title: 'Find Documents',\n },\n description: DEFAULT_DESCRIPTION,\n input: findDocumentsInputSchema,\n}).handler(async ({ slug, authorizedMCP, input, req }) => {\n const payload = req.payload\n const logger = getLogger({ payload })\n\n const {\n id,\n depth,\n draft,\n fallbackLocale,\n joins,\n limit,\n locale,\n page,\n pagination,\n populate,\n select,\n sort,\n trash,\n where,\n } = input\n\n logger.info(\n `Reading document from collection: ${slug}${id ? ` with ID: ${id}` : ''}, limit: ${limit}, page: ${page}${locale ? `, locale: ${locale}` : ''}`,\n )\n\n try {\n if (id !== undefined) {\n try {\n const doc = await payload.findByID({\n id: parseDocumentID({ id, collectionSlug: slug, payload }),\n collection: slug,\n depth,\n overrideAccess: authorizedMCP.overrideAccess,\n req,\n ...(select && { select }),\n ...(populate && { populate }),\n ...(joins !== undefined && { joins }),\n ...(locale && { locale }),\n ...(fallbackLocale !== undefined && { fallbackLocale }),\n ...(draft !== undefined && { draft }),\n ...(trash !== undefined && { trash }),\n })\n\n return {\n content: [\n {\n type: 'text',\n text: `Document from collection \"${slug}\":\\n${JSON.stringify(doc)}`,\n },\n ],\n doc: doc as Record<string, unknown>,\n }\n } catch {\n logger.warn(`Document not found with ID: ${id} in collection: ${slug}`)\n return {\n content: [\n {\n type: 'text',\n text: `Error: Document with ID \"${id}\" not found in collection \"${slug}\"`,\n },\n ],\n }\n }\n }\n\n const findOptions: Parameters<typeof payload.find>[0] = {\n collection: slug,\n depth,\n limit,\n overrideAccess: authorizedMCP.overrideAccess,\n page,\n req,\n ...(select && { select }),\n ...(populate && { populate }),\n ...(joins !== undefined && { joins }),\n ...(locale && { locale }),\n ...(fallbackLocale !== undefined && { fallbackLocale }),\n ...(draft !== undefined && { draft }),\n ...(pagination !== undefined && { pagination }),\n ...(trash !== undefined && { trash }),\n }\n\n if (sort) {\n findOptions.sort = sort\n }\n if (where) {\n findOptions.where = where\n }\n\n const result = await payload.find(findOptions)\n\n let responseText = `Collection: \"${slug}\"\\nTotal: ${result.totalDocs} documents\\nPage: ${result.page} of ${result.totalPages}\\n`\n for (const doc of result.docs) {\n responseText += `\\n\\`\\`\\`json\\n${JSON.stringify(doc)}\\n\\`\\`\\``\n }\n\n return {\n content: [{ type: 'text', text: responseText }],\n doc: result as unknown as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error reading documents from collection ${slug}: ${errorMessage}`)\n return {\n content: [\n {\n type: 'text',\n text: `❌ **Error reading documents from collection \"${slug}\":** ${errorMessage}`,\n },\n ],\n }\n }\n})\n"],"names":["findDocumentsInputSchema","parseDocumentID","defaultAccess","defineCollectionTool","getLogger","DEFAULT_DESCRIPTION","findDocumentsTool","access","args","Boolean","permissions","collections","slug","read","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","handler","authorizedMCP","req","payload","logger","id","depth","draft","fallbackLocale","joins","limit","locale","page","pagination","populate","select","sort","trash","where","info","undefined","doc","findByID","collectionSlug","collection","overrideAccess","content","type","text","JSON","stringify","warn","findOptions","result","find","responseText","totalDocs","totalPages","docs","error","errorMessage","Error","message"],"mappings":"AAAA,SAASA,wBAAwB,EAAEC,eAAe,QAAQ,UAAS;AAEnE,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AAEvD,MAAMC,sBACJ;AAEF,OAAO,MAAMC,oBAAoBH,qBAAqB;IACpDI,QAAQ,CAACC,OACPN,cAAcM,SAASC,QAAQD,KAAKE,WAAW,EAAEC,aA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,KAAK,MAAMhB,OAAOY,OAAOK,IAAI,CAAE;YAC7BH,gBAAgB,CAAC,cAAc,EAAEN,KAAKC,SAAS,CAACT,KAAK,QAAQ,CAAC;QAChE;QAEA,OAAO;YACLK,SAAS;gBAAC;oBAAEC,MAAM;oBAAQC,MAAMO;gBAAa;aAAE;YAC/Cd,KAAKY;QACP;IACF,EAAE,OAAOM,OAAO;QACd,MAAMC,eAAeD,iBAAiBE,QAAQF,MAAMG,OAAO,GAAG;QAC9DtC,OAAOmC,KAAK,CAAC,CAAC,wCAAwC,EAAEjD,KAAK,EAAE,EAAEkD,cAAc;QAC/E,OAAO;YACLd,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,6CAA6C,EAAEtC,KAAK,KAAK,EAAEkD,cAAc;gBAClF;aACD;QACH;IACF;AACF,GAAE"}
@@ -1 +1 @@
1
- {"version":3,"file":"updateTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/updateTool.ts"],"names":[],"mappings":"AAoBA,eAAO,MAAM,kBAAkB,4CAwJ7B,CAAA"}
1
+ {"version":3,"file":"updateTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/updateTool.ts"],"names":[],"mappings":"AAqBA,eAAO,MAAM,kBAAkB,4CAuJ7B,CAAA"}
@@ -1,10 +1,9 @@
1
- import { getCollectionInputSchema, getCollectionVirtualFieldNames, stripVirtualFields, transformPointDataToPayload, updateDocumentInputSchema } from 'payload';
1
+ import { getCollectionInputSchema, getCollectionVirtualFieldNames, parseDocumentID, stripVirtualFields, transformPointDataToPayload, updateDocumentInputSchema, validateCollectionData } from 'payload';
2
2
  import { defaultAccess } from '../../../defaultAccess.js';
3
3
  import { defineCollectionTool } from '../../../defineTool.js';
4
4
  import { getLogger } from '../../../utils/getLogger.js';
5
- import { validateCollectionData } from '../validateEntityData.js';
5
+ import { formatEntityError } from '../formatEntityError.js';
6
6
  import { fileInputSchema, resolveFile } from './fileInput.js';
7
- import { formatCollectionError } from './formatCollectionError.js';
8
7
  const DEFAULT_DESCRIPTION = 'Update documents. Prefer uploadReference after upload, externalURL for URLs, or base64 for small local files.';
9
8
  export const updateDocumentTool = defineCollectionTool({
10
9
  access: (args)=>defaultAccess(args) && Boolean(args.permissions?.collections?.[args.slug]?.update),
@@ -24,20 +23,17 @@ export const updateDocumentTool = defineCollectionTool({
24
23
  const logger = getLogger({
25
24
  payload
26
25
  });
27
- const { id, data, depth, draft, fallbackLocale, file: fileInput, limit, locale, overrideLock, populate, publishAllLocales, select, sort, trash, unpublishAllLocales, where } = input;
26
+ const { id, data, depth, draft, fallbackLocale, file: fileInput, limit, locale, overrideLock, populate, publishAllLocales, returning, select, sort, trash, unpublishAllLocales, where } = input;
28
27
  logger.info(`Updating document in collection: ${slug}${id ? ` with ID: ${id}` : ' with where clause'}, draft: ${draft}${locale ? `, locale: ${locale}` : ''}`);
29
28
  try {
30
29
  const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, slug);
31
30
  const inputData = stripVirtualFields(data, virtualFieldNames);
32
- const validationError = validateCollectionData({
31
+ validateCollectionData({
33
32
  slug,
34
33
  data: inputData,
35
34
  partial: true,
36
35
  req
37
36
  });
38
- if (validationError) {
39
- return validationError;
40
- }
41
37
  const parsedData = transformPointDataToPayload(inputData);
42
38
  const file = await resolveFile({
43
39
  slug,
@@ -47,7 +43,11 @@ export const updateDocumentTool = defineCollectionTool({
47
43
  const whereClause = where ?? {};
48
44
  if (id !== undefined) {
49
45
  const result = await payload.update({
50
- id,
46
+ id: parseDocumentID({
47
+ id,
48
+ collectionSlug: slug,
49
+ payload
50
+ }),
51
51
  collection: slug,
52
52
  data: parsedData,
53
53
  depth,
@@ -59,21 +59,26 @@ export const updateDocumentTool = defineCollectionTool({
59
59
  populate,
60
60
  publishAllLocales,
61
61
  req,
62
- select,
62
+ select: returning ? select : {
63
+ id: true
64
+ },
63
65
  trash,
64
66
  unpublishAllLocales,
65
67
  ...file ? {
66
68
  file
67
69
  } : {}
68
70
  });
71
+ const responseResult = returning ? result : {
72
+ id: result.id
73
+ };
69
74
  return {
70
75
  content: [
71
76
  {
72
77
  type: 'text',
73
- text: `Document updated successfully in collection "${slug}"!\nUpdated document:\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``
78
+ text: `Document updated successfully in collection "${slug}"!\nResult:\n\`\`\`json\n${JSON.stringify(responseResult)}\n\`\`\``
74
79
  }
75
80
  ],
76
- doc: result
81
+ doc: responseResult
77
82
  };
78
83
  }
79
84
  const result = await payload.update({
@@ -89,7 +94,9 @@ export const updateDocumentTool = defineCollectionTool({
89
94
  populate,
90
95
  publishAllLocales,
91
96
  req,
92
- select,
97
+ select: returning ? select : {
98
+ id: true
99
+ },
93
100
  sort,
94
101
  trash,
95
102
  unpublishAllLocales,
@@ -98,7 +105,9 @@ export const updateDocumentTool = defineCollectionTool({
98
105
  file
99
106
  } : {}
100
107
  });
101
- const docs = result.docs || [];
108
+ const docs = returning ? result.docs : result.docs.map(({ id })=>({
109
+ id
110
+ }));
102
111
  const errors = result.errors || [];
103
112
  let responseText = `Multiple documents updated in collection "${slug}"!\nUpdated: ${docs.length} documents\nErrors: ${errors.length}\n---`;
104
113
  if (docs.length > 0) {
@@ -150,9 +159,10 @@ export const updateDocumentTool = defineCollectionTool({
150
159
  } catch (error) {
151
160
  const errorMessage = error instanceof Error ? error.message : 'Unknown error';
152
161
  logger.error(`Error updating document in ${slug}: ${errorMessage}`);
153
- return formatCollectionError({
162
+ return formatEntityError({
154
163
  slug,
155
164
  action: 'updating',
165
+ entity: 'collection',
156
166
  error,
157
167
  req
158
168
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/mcp/builtin/collections/updateTool.ts"],"sourcesContent":["import type { Where } from 'payload'\n\nimport {\n getCollectionInputSchema,\n getCollectionVirtualFieldNames,\n stripVirtualFields,\n transformPointDataToPayload,\n updateDocumentInputSchema,\n} from 'payload'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\nimport { validateCollectionData } from '../validateEntityData.js'\nimport { fileInputSchema, resolveFile } from './fileInput.js'\nimport { formatCollectionError } from './formatCollectionError.js'\n\nconst DEFAULT_DESCRIPTION =\n 'Update documents. Prefer uploadReference after upload, externalURL for URLs, or base64 for small local files.'\n\nexport const updateDocumentTool = defineCollectionTool({\n access: (args) =>\n defaultAccess(args) && Boolean(args.permissions?.collections?.[args.slug]?.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: updateDocumentInputSchema({ file: fileInputSchema }),\n}).handler(async ({ slug, authorizedMCP, 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 limit,\n locale,\n overrideLock,\n populate,\n publishAllLocales,\n select,\n sort,\n trash,\n unpublishAllLocales,\n where,\n } = input\n\n logger.info(\n `Updating document in collection: ${slug}${id ? ` with ID: ${id}` : ' with where clause'}, draft: ${draft}${locale ? `, locale: ${locale}` : ''}`,\n )\n\n try {\n const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, slug)\n const inputData = stripVirtualFields(data, virtualFieldNames)\n const validationError = validateCollectionData({\n slug,\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({ slug, input: fileInput, req })\n\n const whereClause: Where = where ?? {}\n\n if (id !== undefined) {\n const result = await payload.update({\n id,\n collection: slug,\n data: parsedData,\n depth,\n draft,\n fallbackLocale,\n locale,\n overrideAccess: authorizedMCP.overrideAccess,\n overrideLock,\n populate,\n publishAllLocales,\n req,\n select,\n trash,\n unpublishAllLocales,\n ...(file ? { file } : {}),\n })\n\n return {\n content: [\n {\n type: 'text',\n text: `Document updated successfully in collection \"${slug}\"!\\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: slug,\n data: parsedData,\n depth,\n draft,\n fallbackLocale,\n limit,\n locale,\n overrideAccess: authorizedMCP.overrideAccess,\n overrideLock,\n populate,\n publishAllLocales,\n req,\n select,\n sort,\n trash,\n unpublishAllLocales,\n where: whereClause,\n ...(file ? { file } : {}),\n })\n\n const docs = result.docs || []\n const errors = result.errors || []\n\n let responseText = `Multiple documents updated in collection \"${slug}\"!\\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: slug, 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 slug,\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 ${slug}: ${errorMessage}`)\n return formatCollectionError({ slug, action: 'updating', error, req })\n }\n})\n"],"names":["getCollectionInputSchema","getCollectionVirtualFieldNames","stripVirtualFields","transformPointDataToPayload","updateDocumentInputSchema","defaultAccess","defineCollectionTool","getLogger","validateCollectionData","fileInputSchema","resolveFile","formatCollectionError","DEFAULT_DESCRIPTION","updateDocumentTool","access","args","Boolean","permissions","collections","slug","update","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","file","handler","authorizedMCP","req","payload","logger","id","data","depth","draft","fallbackLocale","fileInput","limit","locale","overrideLock","populate","publishAllLocales","select","sort","trash","unpublishAllLocales","where","info","virtualFieldNames","config","inputData","validationError","partial","parsedData","whereClause","undefined","result","collection","overrideAccess","content","type","text","JSON","stringify","doc","docs","errors","responseText","length","errorSchema","collectionSlug","isError","structuredContent","schema","error","errorMessage","Error","message","action"],"mappings":"AAEA,SACEA,wBAAwB,EACxBC,8BAA8B,EAC9BC,kBAAkB,EAClBC,2BAA2B,EAC3BC,yBAAyB,QACpB,UAAS;AAEhB,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AACvD,SAASC,sBAAsB,QAAQ,2BAA0B;AACjE,SAASC,eAAe,EAAEC,WAAW,QAAQ,iBAAgB;AAC7D,SAASC,qBAAqB,QAAQ,6BAA4B;AAElE,MAAMC,sBACJ;AAEF,OAAO,MAAMC,qBAAqBP,qBAAqB;IACrDQ,QAAQ,CAACC,OACPV,cAAcU,SAASC,QAAQD,KAAKE,WAAW,EAAEC,aAAa,CAACH,KAAKI,IAAI,CAAC,EAAEC;IAC7EC,aAAa;QACXC,iBAAiB;QACjBC,gBAAgB;QAChBC,eAAe;QACfC,cAAc;QACdC,OAAO;IACT;IACAC,aAAaf;IACbgB,OAAOxB,0BAA0B;QAAEyB,MAAMpB;IAAgB;AAC3D,GAAGqB,OAAO,CAAC,OAAO,EAAEX,IAAI,EAAEY,aAAa,EAAEH,KAAK,EAAEI,GAAG,EAAE;IACnD,MAAMC,UAAUD,IAAIC,OAAO;IAC3B,MAAMC,SAAS3B,UAAU;QAAE0B;IAAQ;IAEnC,MAAM,EACJE,EAAE,EACFC,IAAI,EACJC,KAAK,EACLC,KAAK,EACLC,cAAc,EACdV,MAAMW,SAAS,EACfC,KAAK,EAC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AAMG,OAAO,GAAG;QAC9D/C,OAAO4C,KAAK,CAAC,CAAC,2BAA2B,EAAE3D,KAAK,EAAE,EAAE4D,cAAc;QAClE,OAAOpE,sBAAsB;YAAEQ;YAAM+D,QAAQ;YAAYJ;YAAO9C;QAAI;IACtE;AACF,GAAE"}
1
+ {"version":3,"sources":["../../../../src/mcp/builtin/collections/updateTool.ts"],"sourcesContent":["import type { Where } from 'payload'\n\nimport {\n getCollectionInputSchema,\n getCollectionVirtualFieldNames,\n parseDocumentID,\n stripVirtualFields,\n transformPointDataToPayload,\n updateDocumentInputSchema,\n validateCollectionData,\n} from 'payload'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\nimport { formatEntityError } from '../formatEntityError.js'\nimport { fileInputSchema, resolveFile } from './fileInput.js'\n\nconst DEFAULT_DESCRIPTION =\n 'Update documents. Prefer uploadReference after upload, externalURL for URLs, or base64 for small local files.'\n\nexport const updateDocumentTool = defineCollectionTool({\n access: (args) =>\n defaultAccess(args) && Boolean(args.permissions?.collections?.[args.slug]?.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: updateDocumentInputSchema({ file: fileInputSchema }),\n}).handler(async ({ slug, authorizedMCP, 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 limit,\n locale,\n overrideLock,\n populate,\n publishAllLocales,\n returning,\n select,\n sort,\n trash,\n unpublishAllLocales,\n where,\n } = input\n\n logger.info(\n `Updating document in collection: ${slug}${id ? ` with ID: ${id}` : ' with where clause'}, draft: ${draft}${locale ? `, locale: ${locale}` : ''}`,\n )\n\n try {\n const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, slug)\n const inputData = stripVirtualFields(data, virtualFieldNames)\n validateCollectionData({\n slug,\n data: inputData,\n partial: true,\n req,\n })\n\n const parsedData = transformPointDataToPayload(inputData)\n const file = await resolveFile({ slug, input: fileInput, req })\n\n const whereClause: Where = where ?? {}\n\n if (id !== undefined) {\n const result = await payload.update({\n id: parseDocumentID({ id, collectionSlug: slug, payload }),\n collection: slug,\n data: parsedData,\n depth,\n draft,\n fallbackLocale,\n locale,\n overrideAccess: authorizedMCP.overrideAccess,\n overrideLock,\n populate,\n publishAllLocales,\n req,\n select: returning ? select : { id: true },\n trash,\n unpublishAllLocales,\n ...(file ? { file } : {}),\n })\n\n const responseResult = returning ? result : { id: result.id }\n\n return {\n content: [\n {\n type: 'text',\n text: `Document updated successfully in collection \"${slug}\"!\\nResult:\\n\\`\\`\\`json\\n${JSON.stringify(responseResult)}\\n\\`\\`\\``,\n },\n ],\n doc: responseResult as Record<string, unknown>,\n }\n }\n\n const result = await payload.update({\n collection: slug,\n data: parsedData,\n depth,\n draft,\n fallbackLocale,\n limit,\n locale,\n overrideAccess: authorizedMCP.overrideAccess,\n overrideLock,\n populate,\n publishAllLocales,\n req,\n select: returning ? select : { id: true },\n sort,\n trash,\n unpublishAllLocales,\n where: whereClause,\n ...(file ? { file } : {}),\n })\n\n const docs = returning ? result.docs : result.docs.map(({ id }) => ({ id }))\n const errors = result.errors || []\n\n let responseText = `Multiple documents updated in collection \"${slug}\"!\\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: slug, 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 slug,\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 ${slug}: ${errorMessage}`)\n return formatEntityError({ slug, action: 'updating', entity: 'collection', error, req })\n }\n})\n"],"names":["getCollectionInputSchema","getCollectionVirtualFieldNames","parseDocumentID","stripVirtualFields","transformPointDataToPayload","updateDocumentInputSchema","validateCollectionData","defaultAccess","defineCollectionTool","getLogger","formatEntityError","fileInputSchema","resolveFile","DEFAULT_DESCRIPTION","updateDocumentTool","access","args","Boolean","permissions","collections","slug","update","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","file","handler","authorizedMCP","req","payload","logger","id","data","depth","draft","fallbackLocale","fileInput","limit","locale","overrideLock","populate","publishAllLocales","returning","select","sort","trash","unpublishAllLocales","where","info","virtualFieldNames","config","inputData","partial","parsedData","whereClause","undefined","result","collectionSlug","collection","overrideAccess","responseResult","content","type","text","JSON","stringify","doc","docs","map","errors","responseText","length","errorSchema","isError","structuredContent","schema","error","errorMessage","Error","message","action","entity"],"mappings":"AAEA,SACEA,wBAAwB,EACxBC,8BAA8B,EAC9BC,eAAe,EACfC,kBAAkB,EAClBC,2BAA2B,EAC3BC,yBAAyB,EACzBC,sBAAsB,QACjB,UAAS;AAEhB,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AACvD,SAASC,iBAAiB,QAAQ,0BAAyB;AAC3D,SAASC,eAAe,EAAEC,WAAW,QAAQ,iBAAgB;AAE7D,MAAMC,sBACJ;AAEF,OAAO,MAAMC,qBAAqBN,qBAAqB;IACrDO,QA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,MAAM,GAAG,GAAG;YACnBD,gBAAgB,CAAC,oCAAoC,EAAEN,KAAKC,SAAS,CAACE,MAAM,QAAQ,CAAC;QACvF;QACA,IAAIE,OAAOE,MAAM,GAAG,GAAG;YACrBD,gBAAgB,CAAC,yBAAyB,EAAEN,KAAKC,SAAS,CAACI,QAAQ,QAAQ,CAAC;YAE5E,MAAMG,cAAc7E,yBAAyB;gBAAE8D,gBAAgB1C;gBAAMa;YAAI;YAEzE,IAAI4C,aAAa;gBACfF,gBAAgB,CAAC,2CAA2C,EAAEN,KAAKC,SAAS,CAACO,aAAa,QAAQ,CAAC;YACrG;YAEA,OAAO;gBACLX,SAAS;oBAAC;wBAAEC,MAAM;wBAAQC,MAAMO;oBAAa;iBAAE;gBAC/CJ,KAAK;oBAAEC;oBAAME;gBAAO;gBACpBI,SAAS;gBACT,GAAID,cACA;oBACEE,mBAAmB;wBACjB3D;wBACAoD;wBACAE;wBACAM,QAAQH;oBACV;gBACF,IACA,CAAC,CAAC;YACR;QACF;QAEA,OAAO;YACLX,SAAS;gBAAC;oBAAEC,MAAM;oBAAQC,MAAMO;gBAAa;aAAE;YAC/CJ,KAAK;gBAAEC;gBAAME;YAAO;QACtB;IACF,EAAE,OAAOO,OAAO;QACd,MAAMC,eAAeD,iBAAiBE,QAAQF,MAAMG,OAAO,GAAG;QAC9DjD,OAAO8C,KAAK,CAAC,CAAC,2BAA2B,EAAE7D,KAAK,EAAE,EAAE8D,cAAc;QAClE,OAAOxE,kBAAkB;YAAEU;YAAMiE,QAAQ;YAAYC,QAAQ;YAAcL;YAAOhD;QAAI;IACxF;AACF,GAAE"}
@@ -0,0 +1,16 @@
1
+ import type { CollectionSlug, GlobalSlug, PayloadRequest } from 'payload';
2
+ import type { MCPToolResponse } from '../../types.js';
3
+ export declare const formatEntityError: ({ slug, action, entity, error, req, }: {
4
+ action: 'creating' | 'duplicating' | 'updating';
5
+ entity: 'collection';
6
+ error: unknown;
7
+ req: PayloadRequest;
8
+ slug: CollectionSlug;
9
+ } | {
10
+ action: 'updating';
11
+ entity: 'global';
12
+ error: unknown;
13
+ req: PayloadRequest;
14
+ slug: GlobalSlug;
15
+ }) => MCPToolResponse;
16
+ //# sourceMappingURL=formatEntityError.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"formatEntityError.d.ts","sourceRoot":"","sources":["../../../src/mcp/builtin/formatEntityError.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAIzE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAA;AAErD,eAAO,MAAM,iBAAiB,0CAO1B;IACE,MAAM,EAAE,UAAU,GAAG,aAAa,GAAG,UAAU,CAAA;IAC/C,MAAM,EAAE,YAAY,CAAA;IACpB,KAAK,EAAE,OAAO,CAAA;IACd,GAAG,EAAE,cAAc,CAAA;IACnB,IAAI,EAAE,cAAc,CAAA;CACrB,GACD;IACE,MAAM,EAAE,UAAU,CAAA;IAClB,MAAM,EAAE,QAAQ,CAAA;IAChB,KAAK,EAAE,OAAO,CAAA;IACd,GAAG,EAAE,cAAc,CAAA;IACnB,IAAI,EAAE,UAAU,CAAA;CACjB,KAAG,eAsCP,CAAA"}
@@ -0,0 +1,55 @@
1
+ import { getCollectionInputSchema, getGlobalInputSchema, ValidationError } from 'payload';
2
+ export const formatEntityError = ({ slug, action, entity, error, req })=>{
3
+ const message = error instanceof Error ? error.message : 'Unknown error';
4
+ const target = entity === 'collection' ? `document in collection "${slug}"` : `global "${slug}"`;
5
+ if (!isValidationError(error, message)) {
6
+ return {
7
+ content: [
8
+ {
9
+ type: 'text',
10
+ text: `Error ${action} ${target}: ${message}`
11
+ }
12
+ ],
13
+ isError: true
14
+ };
15
+ }
16
+ const schema = entity === 'collection' ? getCollectionInputSchema({
17
+ collectionSlug: slug,
18
+ req
19
+ }) : getGlobalInputSchema({
20
+ globalSlug: slug,
21
+ req
22
+ });
23
+ const errors = error instanceof ValidationError ? error.data.errors : [
24
+ {
25
+ message
26
+ }
27
+ ];
28
+ const validationMessage = errors.map((issue)=>`${'path' in issue ? `${issue.path}: ` : ''}${issue.message}`).join('\n');
29
+ const schemaText = schema ? `\n\nUse this schema for data:\n\`\`\`json\n${JSON.stringify(schema)}\n\`\`\`` : '';
30
+ return {
31
+ content: [
32
+ {
33
+ type: 'text',
34
+ text: `Error ${action} ${target}: ${validationMessage}${schemaText}`
35
+ }
36
+ ],
37
+ isError: true,
38
+ ...schema ? {
39
+ structuredContent: {
40
+ slug,
41
+ errors,
42
+ schema
43
+ }
44
+ } : {}
45
+ };
46
+ };
47
+ const isValidationError = (error, message)=>{
48
+ if (error instanceof ValidationError) {
49
+ return true;
50
+ }
51
+ const name = error && typeof error === 'object' && 'name' in error ? error.name : undefined;
52
+ return name === 'CastError' || message.includes('Cast to ') || message.includes('validation failed');
53
+ };
54
+
55
+ //# sourceMappingURL=formatEntityError.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/mcp/builtin/formatEntityError.ts"],"sourcesContent":["import type { CollectionSlug, GlobalSlug, PayloadRequest } from 'payload'\n\nimport { getCollectionInputSchema, getGlobalInputSchema, ValidationError } from 'payload'\n\nimport type { MCPToolResponse } from '../../types.js'\n\nexport const formatEntityError = ({\n slug,\n action,\n entity,\n error,\n req,\n}:\n | {\n action: 'creating' | 'duplicating' | 'updating'\n entity: 'collection'\n error: unknown\n req: PayloadRequest\n slug: CollectionSlug\n }\n | {\n action: 'updating'\n entity: 'global'\n error: unknown\n req: PayloadRequest\n slug: GlobalSlug\n }): MCPToolResponse => {\n const message = error instanceof Error ? error.message : 'Unknown error'\n const target = entity === 'collection' ? `document in collection \"${slug}\"` : `global \"${slug}\"`\n\n if (!isValidationError(error, message)) {\n return {\n content: [{ type: 'text', text: `Error ${action} ${target}: ${message}` }],\n isError: true,\n }\n }\n\n const schema =\n entity === 'collection'\n ? getCollectionInputSchema({ collectionSlug: slug, req })\n : getGlobalInputSchema({ globalSlug: slug, req })\n const errors = error instanceof ValidationError ? error.data.errors : [{ message }]\n const validationMessage = errors\n .map((issue) => `${'path' in issue ? `${issue.path}: ` : ''}${issue.message}`)\n .join('\\n')\n const schemaText = schema\n ? `\\n\\nUse this schema for data:\\n\\`\\`\\`json\\n${JSON.stringify(schema)}\\n\\`\\`\\``\n : ''\n\n return {\n content: [\n { type: 'text', text: `Error ${action} ${target}: ${validationMessage}${schemaText}` },\n ],\n isError: true,\n ...(schema\n ? {\n structuredContent: {\n slug,\n errors,\n schema,\n },\n }\n : {}),\n }\n}\n\nconst isValidationError = (error: unknown, message: string): boolean => {\n if (error instanceof ValidationError) {\n return true\n }\n\n const name = error && typeof error === 'object' && 'name' in error ? error.name : undefined\n\n return (\n name === 'CastError' || message.includes('Cast to ') || message.includes('validation failed')\n )\n}\n"],"names":["getCollectionInputSchema","getGlobalInputSchema","ValidationError","formatEntityError","slug","action","entity","error","req","message","Error","target","isValidationError","content","type","text","isError","schema","collectionSlug","globalSlug","errors","data","validationMessage","map","issue","path","join","schemaText","JSON","stringify","structuredContent","name","undefined","includes"],"mappings":"AAEA,SAASA,wBAAwB,EAAEC,oBAAoB,EAAEC,eAAe,QAAQ,UAAS;AAIzF,OAAO,MAAMC,oBAAoB,CAAC,EAChCC,IAAI,EACJC,MAAM,EACNC,MAAM,EACNC,KAAK,EACLC,GAAG,EAeA;IACH,MAAMC,UAAUF,iBAAiBG,QAAQH,MAAME,OAAO,GAAG;IACzD,MAAME,SAASL,WAAW,eAAe,CAAC,wBAAwB,EAAEF,KAAK,CAAC,CAAC,GAAG,CAAC,QAAQ,EAAEA,KAAK,CAAC,CAAC;IAEhG,IAAI,CAACQ,kBAAkBL,OAAOE,UAAU;QACtC,OAAO;YACLI,SAAS;gBAAC;oBAAEC,MAAM;oBAAQC,MAAM,CAAC,MAAM,EAAEV,OAAO,CAAC,EAAEM,OAAO,EAAE,EAAEF,SAAS;gBAAC;aAAE;YAC1EO,SAAS;QACX;IACF;IAEA,MAAMC,SACJX,WAAW,eACPN,yBAAyB;QAAEkB,gBAAgBd;QAAMI;IAAI,KACrDP,qBAAqB;QAAEkB,YAAYf;QAAMI;IAAI;IACnD,MAAMY,SAASb,iBAAiBL,kBAAkBK,MAAMc,IAAI,CAACD,MAAM,GAAG;QAAC;YAAEX;QAAQ;KAAE;IACnF,MAAMa,oBAAoBF,OACvBG,GAAG,CAAC,CAACC,QAAU,GAAG,UAAUA,QAAQ,GAAGA,MAAMC,IAAI,CAAC,EAAE,CAAC,GAAG,KAAKD,MAAMf,OAAO,EAAE,EAC5EiB,IAAI,CAAC;IACR,MAAMC,aAAaV,SACf,CAAC,2CAA2C,EAAEW,KAAKC,SAAS,CAACZ,QAAQ,QAAQ,CAAC,GAC9E;IAEJ,OAAO;QACLJ,SAAS;YACP;gBAAEC,MAAM;gBAAQC,MAAM,CAAC,MAAM,EAAEV,OAAO,CAAC,EAAEM,OAAO,EAAE,EAAEW,oBAAoBK,YAAY;YAAC;SACtF;QACDX,SAAS;QACT,GAAIC,SACA;YACEa,mBAAmB;gBACjB1B;gBACAgB;gBACAH;YACF;QACF,IACA,CAAC,CAAC;IACR;AACF,EAAC;AAED,MAAML,oBAAoB,CAACL,OAAgBE;IACzC,IAAIF,iBAAiBL,iBAAiB;QACpC,OAAO;IACT;IAEA,MAAM6B,OAAOxB,SAAS,OAAOA,UAAU,YAAY,UAAUA,QAAQA,MAAMwB,IAAI,GAAGC;IAElF,OACED,SAAS,eAAetB,QAAQwB,QAAQ,CAAC,eAAexB,QAAQwB,QAAQ,CAAC;AAE7E"}
@@ -1 +1 @@
1
- {"version":3,"file":"updateTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/globals/updateTool.ts"],"names":[],"mappings":"AAcA,eAAO,MAAM,gBAAgB,wCAkF3B,CAAA"}
1
+ {"version":3,"file":"updateTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/globals/updateTool.ts"],"names":[],"mappings":"AAeA,eAAO,MAAM,gBAAgB,wCA4E3B,CAAA"}
@@ -1,8 +1,8 @@
1
- import { getGlobalVirtualFieldNames, stripVirtualFields, transformPointDataToPayload, updateGlobalInputSchema } from 'payload';
1
+ import { getGlobalVirtualFieldNames, stripVirtualFields, transformPointDataToPayload, updateGlobalInputSchema, validateGlobalData } from 'payload';
2
2
  import { defaultAccess } from '../../../defaultAccess.js';
3
3
  import { defineGlobalTool } from '../../../defineTool.js';
4
4
  import { getLogger } from '../../../utils/getLogger.js';
5
- import { validateGlobalData } from '../validateEntityData.js';
5
+ import { formatEntityError } from '../formatEntityError.js';
6
6
  const DEFAULT_DESCRIPTION = 'Update any Payload global by passing the global slug and data.';
7
7
  export const updateGlobalTool = defineGlobalTool({
8
8
  access: (args)=>defaultAccess(args) && Boolean(args.permissions?.globals?.[args.slug]?.update),
@@ -25,14 +25,11 @@ export const updateGlobalTool = defineGlobalTool({
25
25
  try {
26
26
  const virtualFieldNames = getGlobalVirtualFieldNames(payload.config, slug);
27
27
  const inputData = stripVirtualFields(data, virtualFieldNames);
28
- const validationError = validateGlobalData({
28
+ validateGlobalData({
29
29
  slug,
30
30
  data: inputData,
31
31
  req
32
32
  });
33
- if (validationError) {
34
- return validationError;
35
- }
36
33
  const parsedData = transformPointDataToPayload(inputData);
37
34
  const updateOptions = {
38
35
  slug,
@@ -66,16 +63,15 @@ export const updateGlobalTool = defineGlobalTool({
66
63
  doc: result
67
64
  };
68
65
  } catch (error) {
69
- const errorMessage = error instanceof Error ? error.message : 'Unknown error';
70
- logger.error(`Error updating global ${slug}: ${errorMessage}`);
71
- return {
72
- content: [
73
- {
74
- type: 'text',
75
- text: `Error updating global "${slug}": ${errorMessage}`
76
- }
77
- ]
78
- };
66
+ const message = error instanceof Error ? error.message : 'Unknown error';
67
+ logger.error(`Error updating global ${slug}: ${message}`);
68
+ return formatEntityError({
69
+ slug,
70
+ action: 'updating',
71
+ entity: 'global',
72
+ error,
73
+ req
74
+ });
79
75
  }
80
76
  });
81
77
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/mcp/builtin/globals/updateTool.ts"],"sourcesContent":["import {\n getGlobalVirtualFieldNames,\n stripVirtualFields,\n transformPointDataToPayload,\n updateGlobalInputSchema,\n} from 'payload'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineGlobalTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\nimport { validateGlobalData } from '../validateEntityData.js'\n\nconst DEFAULT_DESCRIPTION = 'Update any Payload global by passing the global slug and data.'\n\nexport const updateGlobalTool = defineGlobalTool({\n access: (args) => defaultAccess(args) && Boolean(args.permissions?.globals?.[args.slug]?.update),\n annotations: {\n destructiveHint: true,\n idempotentHint: false,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'Update Global',\n },\n description: DEFAULT_DESCRIPTION,\n input: updateGlobalInputSchema,\n}).handler(async ({ slug, authorizedMCP, input, req }) => {\n const payload = req.payload\n const logger = getLogger({ payload })\n\n const {\n data,\n depth,\n draft,\n fallbackLocale,\n locale,\n overrideLock,\n populate,\n publishAllLocales,\n select,\n unpublishAllLocales,\n } = input\n\n logger.info(`Updating global: ${slug}, draft: ${draft}${locale ? `, locale: ${locale}` : ''}`)\n\n try {\n const virtualFieldNames = getGlobalVirtualFieldNames(payload.config, slug)\n const inputData = stripVirtualFields(data, virtualFieldNames)\n const validationError = validateGlobalData({ slug, data: inputData, req })\n\n if (validationError) {\n return validationError\n }\n\n const parsedData = transformPointDataToPayload(inputData)\n\n const updateOptions: Parameters<typeof payload.updateGlobal>[0] = {\n slug,\n data: parsedData,\n depth,\n draft,\n overrideAccess: authorizedMCP.overrideAccess,\n overrideLock,\n populate,\n publishAllLocales,\n req,\n unpublishAllLocales,\n }\n\n if (locale) {\n updateOptions.locale = locale\n }\n if (fallbackLocale !== undefined) {\n updateOptions.fallbackLocale = fallbackLocale\n }\n if (select) {\n updateOptions.select = select\n }\n\n const result = await payload.updateGlobal(updateOptions)\n\n return {\n content: [\n {\n type: 'text',\n text: `Global \"${slug}\" updated successfully!\\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 updating global ${slug}: ${errorMessage}`)\n return {\n content: [{ type: 'text', text: `Error updating global \"${slug}\": ${errorMessage}` }],\n }\n }\n})\n"],"names":["getGlobalVirtualFieldNames","stripVirtualFields","transformPointDataToPayload","updateGlobalInputSchema","defaultAccess","defineGlobalTool","getLogger","validateGlobalData","DEFAULT_DESCRIPTION","updateGlobalTool","access","args","Boolean","permissions","globals","slug","update","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","handler","authorizedMCP","req","payload","logger","data","depth","draft","fallbackLocale","locale","overrideLock","populate","publishAllLocales","select","unpublishAllLocales","info","virtualFieldNames","config","inputData","validationError","parsedData","updateOptions","overrideAccess","undefined","result","updateGlobal","content","type","text","JSON","stringify","doc","error","errorMessage","Error","message"],"mappings":"AAAA,SACEA,0BAA0B,EAC1BC,kBAAkB,EAClBC,2BAA2B,EAC3BC,uBAAuB,QAClB,UAAS;AAEhB,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,gBAAgB,QAAQ,yBAAwB;AACzD,SAASC,SAAS,QAAQ,8BAA6B;AACvD,SAASC,kBAAkB,QAAQ,2BAA0B;AAE7D,MAAMC,sBAAsB;AAE5B,OAAO,MAAMC,mBAAmBJ,iBAAiB;IAC/CK,QAAQ,CAACC,OAASP,cAAcO,SAASC,QAAQD,KAAKE,WAAW,EAAEC,SAAS,CAACH,KAAKI,IAAI,CAAC,EAAEC;IACzFC,aAAa;QACXC,iBAAiB;QACjBC,gBAAgB;QAChBC,eAAe;QACfC,cAAc;QACdC,OAAO;IACT;IACAC,aAAaf;IACbgB,OAAOrB;AACT,GAAGsB,OAAO,CAAC,OAAO,EAAEV,IAAI,EAAEW,aAAa,EAAEF,KAAK,EAAE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4B,KAAK,CAAC,CAAC,sBAAsB,EAAE1C,KAAK,EAAE,EAAE2C,cAAc;QAC7D,OAAO;YACLP,SAAS;gBAAC;oBAAEC,MAAM;oBAAQC,MAAM,CAAC,uBAAuB,EAAEtC,KAAK,GAAG,EAAE2C,cAAc;gBAAC;aAAE;QACvF;IACF;AACF,GAAE"}
1
+ {"version":3,"sources":["../../../../src/mcp/builtin/globals/updateTool.ts"],"sourcesContent":["import {\n getGlobalVirtualFieldNames,\n stripVirtualFields,\n transformPointDataToPayload,\n updateGlobalInputSchema,\n validateGlobalData,\n} from 'payload'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineGlobalTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\nimport { formatEntityError } from '../formatEntityError.js'\n\nconst DEFAULT_DESCRIPTION = 'Update any Payload global by passing the global slug and data.'\n\nexport const updateGlobalTool = defineGlobalTool({\n access: (args) => defaultAccess(args) && Boolean(args.permissions?.globals?.[args.slug]?.update),\n annotations: {\n destructiveHint: true,\n idempotentHint: false,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'Update Global',\n },\n description: DEFAULT_DESCRIPTION,\n input: updateGlobalInputSchema,\n}).handler(async ({ slug, authorizedMCP, input, req }) => {\n const payload = req.payload\n const logger = getLogger({ payload })\n\n const {\n data,\n depth,\n draft,\n fallbackLocale,\n locale,\n overrideLock,\n populate,\n publishAllLocales,\n select,\n unpublishAllLocales,\n } = input\n\n logger.info(`Updating global: ${slug}, draft: ${draft}${locale ? `, locale: ${locale}` : ''}`)\n\n try {\n const virtualFieldNames = getGlobalVirtualFieldNames(payload.config, slug)\n const inputData = stripVirtualFields(data, virtualFieldNames)\n validateGlobalData({ slug, data: inputData, req })\n\n const parsedData = transformPointDataToPayload(inputData)\n\n const updateOptions: Parameters<typeof payload.updateGlobal>[0] = {\n slug,\n data: parsedData,\n depth,\n draft,\n overrideAccess: authorizedMCP.overrideAccess,\n overrideLock,\n populate,\n publishAllLocales,\n req,\n unpublishAllLocales,\n }\n\n if (locale) {\n updateOptions.locale = locale\n }\n if (fallbackLocale !== undefined) {\n updateOptions.fallbackLocale = fallbackLocale\n }\n if (select) {\n updateOptions.select = select\n }\n\n const result = await payload.updateGlobal(updateOptions)\n\n return {\n content: [\n {\n type: 'text',\n text: `Global \"${slug}\" updated successfully!\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as Record<string, unknown>,\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error updating global ${slug}: ${message}`)\n return formatEntityError({ slug, action: 'updating', entity: 'global', error, req })\n }\n})\n"],"names":["getGlobalVirtualFieldNames","stripVirtualFields","transformPointDataToPayload","updateGlobalInputSchema","validateGlobalData","defaultAccess","defineGlobalTool","getLogger","formatEntityError","DEFAULT_DESCRIPTION","updateGlobalTool","access","args","Boolean","permissions","globals","slug","update","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","handler","authorizedMCP","req","payload","logger","data","depth","draft","fallbackLocale","locale","overrideLock","populate","publishAllLocales","select","unpublishAllLocales","info","virtualFieldNames","config","inputData","parsedData","updateOptions","overrideAccess","undefined","result","updateGlobal","content","type","text","JSON","stringify","doc","error","message","Error","action","entity"],"mappings":"AAAA,SACEA,0BAA0B,EAC1BC,kBAAkB,EAClBC,2BAA2B,EAC3BC,uBAAuB,EACvBC,kBAAkB,QACb,UAAS;AAEhB,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,gBAAgB,QAAQ,yBAAwB;AACzD,SAASC,SAAS,QAAQ,8BAA6B;AACvD,SAASC,iBAAiB,QAAQ,0BAAyB;AAE3D,MAAMC,sBAAsB;AAE5B,OAAO,MAAMC,mBAAmBJ,iBAAiB;IAC/CK,QAAQ,CAACC,OAASP,cAAcO,SAASC,QAAQD,KAAKE,WAAW,EAAEC,SAAS,CAACH,KAAKI,IAAI,CAAC,EAAEC;IACzFC,aAAa;QACXC,i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O,KAAKP;QACP;IACF,EAAE,OAAOQ,OAAO;QACd,MAAMC,UAAUD,iBAAiBE,QAAQF,MAAMC,OAAO,GAAG;QACzD5B,OAAO2B,KAAK,CAAC,CAAC,sBAAsB,EAAEzC,KAAK,EAAE,EAAE0C,SAAS;QACxD,OAAOlD,kBAAkB;YAAEQ;YAAM4C,QAAQ;YAAYC,QAAQ;YAAUJ;YAAO7B;QAAI;IACpF;AACF,GAAE"}
package/dist/stdio.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /* eslint-disable no-console */ import { serveStdio } from '@modelcontextprotocol/server/stdio';
2
2
  import { fileURLToPath, pathToFileURL } from 'node:url';
3
- import { createLocalReq, getPayload } from 'payload';
3
+ import { createPayloadRequest, getPayload } from 'payload';
4
4
  import { findConfig, loadEnv } from 'payload/node';
5
5
  import { getAuthorizedMCP } from './endpoint/access.js';
6
6
  import { buildMcpServer } from './mcp/buildMcpServer.js';
@@ -80,11 +80,12 @@ import { resolveProjectRoot } from './utils/resolveProjectRoot.js';
80
80
  if (process.env.PAYLOAD_MCP_AUTHORIZATION) {
81
81
  headers.set('Authorization', process.env.PAYLOAD_MCP_AUTHORIZATION);
82
82
  }
83
- const req = await createLocalReq({
83
+ const req = await createPayloadRequest({
84
+ payload,
84
85
  req: {
85
86
  headers
86
87
  }
87
- }, payload);
88
+ });
88
89
  req.payloadAPI = 'MCP';
89
90
  const authorizedMCP = await getAuthorizedMCP({
90
91
  overrideAccess,