@payloadcms/plugin-mcp 4.0.0-internal.a0ef1b8 → 4.0.0-internal.a2d053c

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 (259) hide show
  1. package/LICENSE.md +1 -1
  2. package/dist/defaultAccess.d.ts +3 -0
  3. package/dist/defaultAccess.d.ts.map +1 -0
  4. package/dist/defaultAccess.js +3 -0
  5. package/dist/defaultAccess.js.map +1 -0
  6. package/dist/defineTool.d.ts +8 -8
  7. package/dist/defineTool.d.ts.map +1 -1
  8. package/dist/endpoint/access.d.ts +12 -5
  9. package/dist/endpoint/access.d.ts.map +1 -1
  10. package/dist/endpoint/access.js +95 -88
  11. package/dist/endpoint/access.js.map +1 -1
  12. package/dist/endpoint/index.d.ts +1 -1
  13. package/dist/endpoint/index.d.ts.map +1 -1
  14. package/dist/endpoint/index.js +109 -16
  15. package/dist/endpoint/index.js.map +1 -1
  16. package/dist/endpoint/oauth.d.ts +39 -0
  17. package/dist/endpoint/oauth.d.ts.map +1 -0
  18. package/dist/endpoint/oauth.js +94 -0
  19. package/dist/endpoint/oauth.js.map +1 -0
  20. package/dist/endpoint/oauthLoginToken.d.ts +21 -0
  21. package/dist/endpoint/oauthLoginToken.d.ts.map +1 -0
  22. package/dist/endpoint/oauthLoginToken.js +79 -0
  23. package/dist/endpoint/oauthLoginToken.js.map +1 -0
  24. package/dist/endpoint/oauthServer.d.ts +12 -0
  25. package/dist/endpoint/oauthServer.d.ts.map +1 -0
  26. package/dist/endpoint/oauthServer.js +362 -0
  27. package/dist/endpoint/oauthServer.js.map +1 -0
  28. package/dist/exports/client.d.ts +1 -1
  29. package/dist/exports/client.d.ts.map +1 -1
  30. package/dist/exports/client.js +1 -1
  31. package/dist/exports/client.js.map +1 -1
  32. package/dist/exports/internal.d.ts +2 -0
  33. package/dist/exports/internal.d.ts.map +1 -0
  34. package/dist/exports/internal.js +3 -0
  35. package/dist/exports/internal.js.map +1 -0
  36. package/dist/index.d.ts +12 -4
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +30 -22
  39. package/dist/index.js.map +1 -1
  40. package/dist/mcp/buildMcpServer.d.ts +6 -6
  41. package/dist/mcp/buildMcpServer.d.ts.map +1 -1
  42. package/dist/mcp/buildMcpServer.js +146 -81
  43. package/dist/mcp/buildMcpServer.js.map +1 -1
  44. package/dist/mcp/builtin/collections/authTools.d.ts.map +1 -1
  45. package/dist/mcp/builtin/collections/authTools.js +123 -61
  46. package/dist/mcp/builtin/collections/authTools.js.map +1 -1
  47. package/dist/mcp/builtin/collections/countTool.d.ts +2 -0
  48. package/dist/mcp/builtin/collections/countTool.d.ts.map +1 -0
  49. package/dist/mcp/builtin/collections/countTool.js +63 -0
  50. package/dist/mcp/builtin/collections/countTool.js.map +1 -0
  51. package/dist/mcp/builtin/collections/countVersionsTool.d.ts +2 -0
  52. package/dist/mcp/builtin/collections/countVersionsTool.d.ts.map +1 -0
  53. package/dist/mcp/builtin/collections/countVersionsTool.js +60 -0
  54. package/dist/mcp/builtin/collections/countVersionsTool.js.map +1 -0
  55. package/dist/mcp/builtin/collections/createTool.d.ts +1 -1
  56. package/dist/mcp/builtin/collections/createTool.d.ts.map +1 -1
  57. package/dist/mcp/builtin/collections/createTool.js +114 -68
  58. package/dist/mcp/builtin/collections/createTool.js.map +1 -1
  59. package/dist/mcp/builtin/collections/deleteTool.d.ts +1 -1
  60. package/dist/mcp/builtin/collections/deleteTool.d.ts.map +1 -1
  61. package/dist/mcp/builtin/collections/deleteTool.js +55 -61
  62. package/dist/mcp/builtin/collections/deleteTool.js.map +1 -1
  63. package/dist/mcp/builtin/collections/duplicateTool.d.ts +2 -0
  64. package/dist/mcp/builtin/collections/duplicateTool.d.ts.map +1 -0
  65. package/dist/mcp/builtin/collections/duplicateTool.js +90 -0
  66. package/dist/mcp/builtin/collections/duplicateTool.js.map +1 -0
  67. package/dist/mcp/builtin/collections/fileInput.d.ts +28 -0
  68. package/dist/mcp/builtin/collections/fileInput.d.ts.map +1 -0
  69. package/dist/mcp/builtin/collections/fileInput.js +88 -0
  70. package/dist/mcp/builtin/collections/fileInput.js.map +1 -0
  71. package/dist/mcp/builtin/collections/findDistinctTool.d.ts +2 -0
  72. package/dist/mcp/builtin/collections/findDistinctTool.d.ts.map +1 -0
  73. package/dist/mcp/builtin/collections/findDistinctTool.js +77 -0
  74. package/dist/mcp/builtin/collections/findDistinctTool.js.map +1 -0
  75. package/dist/mcp/builtin/collections/findTool.d.ts +1 -1
  76. package/dist/mcp/builtin/collections/findTool.d.ts.map +1 -1
  77. package/dist/mcp/builtin/collections/findTool.js +62 -75
  78. package/dist/mcp/builtin/collections/findTool.js.map +1 -1
  79. package/dist/mcp/builtin/collections/findVersionByIDTool.d.ts +2 -0
  80. package/dist/mcp/builtin/collections/findVersionByIDTool.d.ts.map +1 -0
  81. package/dist/mcp/builtin/collections/findVersionByIDTool.js +74 -0
  82. package/dist/mcp/builtin/collections/findVersionByIDTool.js.map +1 -0
  83. package/dist/mcp/builtin/collections/findVersionsTool.d.ts +2 -0
  84. package/dist/mcp/builtin/collections/findVersionsTool.d.ts.map +1 -0
  85. package/dist/mcp/builtin/collections/findVersionsTool.js +84 -0
  86. package/dist/mcp/builtin/collections/findVersionsTool.js.map +1 -0
  87. package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts +2 -0
  88. package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -0
  89. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +103 -0
  90. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -0
  91. package/dist/mcp/builtin/collections/restoreVersionTool.d.ts +2 -0
  92. package/dist/mcp/builtin/collections/restoreVersionTool.d.ts.map +1 -0
  93. package/dist/mcp/builtin/collections/restoreVersionTool.js +69 -0
  94. package/dist/mcp/builtin/collections/restoreVersionTool.js.map +1 -0
  95. package/dist/mcp/builtin/collections/updateTool.d.ts +1 -1
  96. package/dist/mcp/builtin/collections/updateTool.d.ts.map +1 -1
  97. package/dist/mcp/builtin/collections/updateTool.js +118 -137
  98. package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
  99. package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts +2 -0
  100. package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts.map +1 -0
  101. package/dist/mcp/builtin/collections/uploadInstructionsTool.js +55 -0
  102. package/dist/mcp/builtin/collections/uploadInstructionsTool.js.map +1 -0
  103. package/dist/mcp/builtin/formatEntityError.d.ts +16 -0
  104. package/dist/mcp/builtin/formatEntityError.d.ts.map +1 -0
  105. package/dist/mcp/builtin/formatEntityError.js +55 -0
  106. package/dist/mcp/builtin/formatEntityError.js.map +1 -0
  107. package/dist/mcp/builtin/getConfigInfoTool.d.ts +2 -0
  108. package/dist/mcp/builtin/getConfigInfoTool.d.ts.map +1 -0
  109. package/dist/mcp/builtin/getConfigInfoTool.js +69 -0
  110. package/dist/mcp/builtin/getConfigInfoTool.js.map +1 -0
  111. package/dist/mcp/builtin/globals/countVersionsTool.d.ts +2 -0
  112. package/dist/mcp/builtin/globals/countVersionsTool.d.ts.map +1 -0
  113. package/dist/mcp/builtin/globals/countVersionsTool.js +60 -0
  114. package/dist/mcp/builtin/globals/countVersionsTool.js.map +1 -0
  115. package/dist/mcp/builtin/globals/findTool.d.ts.map +1 -1
  116. package/dist/mcp/builtin/globals/findTool.js +27 -36
  117. package/dist/mcp/builtin/globals/findTool.js.map +1 -1
  118. package/dist/mcp/builtin/globals/findVersionByIDTool.d.ts +2 -0
  119. package/dist/mcp/builtin/globals/findVersionByIDTool.d.ts.map +1 -0
  120. package/dist/mcp/builtin/globals/findVersionByIDTool.js +68 -0
  121. package/dist/mcp/builtin/globals/findVersionByIDTool.js.map +1 -0
  122. package/dist/mcp/builtin/globals/findVersionsTool.d.ts +2 -0
  123. package/dist/mcp/builtin/globals/findVersionsTool.d.ts.map +1 -0
  124. package/dist/mcp/builtin/globals/findVersionsTool.js +78 -0
  125. package/dist/mcp/builtin/globals/findVersionsTool.js.map +1 -0
  126. package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts +2 -0
  127. package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts.map +1 -0
  128. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js +81 -0
  129. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js.map +1 -0
  130. package/dist/mcp/builtin/globals/restoreVersionTool.d.ts +2 -0
  131. package/dist/mcp/builtin/globals/restoreVersionTool.d.ts.map +1 -0
  132. package/dist/mcp/builtin/globals/restoreVersionTool.js +70 -0
  133. package/dist/mcp/builtin/globals/restoreVersionTool.js.map +1 -0
  134. package/dist/mcp/builtin/globals/updateTool.d.ts.map +1 -1
  135. package/dist/mcp/builtin/globals/updateTool.js +44 -62
  136. package/dist/mcp/builtin/globals/updateTool.js.map +1 -1
  137. package/dist/mcp/builtinTools.d.ts +150 -19
  138. package/dist/mcp/builtinTools.d.ts.map +1 -1
  139. package/dist/mcp/builtinTools.js +125 -20
  140. package/dist/mcp/builtinTools.js.map +1 -1
  141. package/dist/mcp/sanitizeMCPConfig.d.ts +0 -1
  142. package/dist/mcp/sanitizeMCPConfig.d.ts.map +1 -1
  143. package/dist/mcp/sanitizeMCPConfig.js +127 -58
  144. package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
  145. package/dist/stdio.d.ts +3 -3
  146. package/dist/stdio.d.ts.map +1 -1
  147. package/dist/stdio.js +86 -47
  148. package/dist/stdio.js.map +1 -1
  149. package/dist/types.d.ts +205 -114
  150. package/dist/types.d.ts.map +1 -1
  151. package/dist/types.js +2 -4
  152. package/dist/types.js.map +1 -1
  153. package/dist/utils/camelCase.d.ts.map +1 -1
  154. package/dist/utils/getPluginConfig.d.ts +1 -1
  155. package/dist/utils/getPluginConfig.js +1 -1
  156. package/dist/utils/getPluginConfig.js.map +1 -1
  157. package/dist/utils/resolveProjectRoot.d.ts.map +1 -1
  158. package/dist/utils/seal.d.ts +18 -0
  159. package/dist/utils/seal.d.ts.map +1 -0
  160. package/dist/utils/seal.js +27 -0
  161. package/dist/utils/seal.js.map +1 -0
  162. package/dist/utils/toStandardSchema.d.ts.map +1 -1
  163. package/dist/utils/toStandardSchema.js.map +1 -1
  164. package/package.json +27 -37
  165. package/src/defaultAccess.ts +3 -0
  166. package/src/endpoint/access.ts +99 -101
  167. package/src/endpoint/index.ts +95 -15
  168. package/src/endpoint/oauth.ts +92 -0
  169. package/src/endpoint/oauthLoginToken.ts +91 -0
  170. package/src/endpoint/oauthServer.ts +396 -0
  171. package/src/exports/client.ts +2 -1
  172. package/src/exports/internal.ts +1 -0
  173. package/src/index.ts +52 -25
  174. package/src/mcp/buildMcpServer.ts +181 -116
  175. package/src/mcp/builtin/collections/authTools.ts +124 -77
  176. package/src/mcp/builtin/collections/countTool.ts +61 -0
  177. package/src/mcp/builtin/collections/countVersionsTool.ts +60 -0
  178. package/src/mcp/builtin/collections/createTool.ts +115 -88
  179. package/src/mcp/builtin/collections/deleteTool.ts +49 -75
  180. package/src/mcp/builtin/collections/duplicateTool.ts +84 -0
  181. package/src/mcp/builtin/collections/fileInput.spec.ts +93 -0
  182. package/src/mcp/builtin/collections/fileInput.ts +127 -0
  183. package/src/mcp/builtin/collections/findDistinctTool.ts +67 -0
  184. package/src/mcp/builtin/collections/findTool.ts +58 -111
  185. package/src/mcp/builtin/collections/findVersionByIDTool.ts +66 -0
  186. package/src/mcp/builtin/collections/findVersionsTool.ts +83 -0
  187. package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +91 -0
  188. package/src/mcp/builtin/collections/restoreVersionTool.ts +65 -0
  189. package/src/mcp/builtin/collections/updateTool.ts +106 -143
  190. package/src/mcp/builtin/collections/uploadInstructionsTool.ts +64 -0
  191. package/src/mcp/builtin/formatEntityError.ts +77 -0
  192. package/src/mcp/builtin/getConfigInfoTool.ts +68 -0
  193. package/src/mcp/builtin/globals/countVersionsTool.ts +60 -0
  194. package/src/mcp/builtin/globals/findTool.ts +28 -58
  195. package/src/mcp/builtin/globals/findVersionByIDTool.ts +64 -0
  196. package/src/mcp/builtin/globals/findVersionsTool.ts +69 -0
  197. package/src/mcp/builtin/globals/getGlobalSchemaTool.ts +73 -0
  198. package/src/mcp/builtin/globals/restoreVersionTool.ts +68 -0
  199. package/src/mcp/builtin/globals/updateTool.ts +52 -80
  200. package/src/mcp/builtinTools.ts +118 -41
  201. package/src/mcp/sanitizeMCPConfig.ts +121 -78
  202. package/src/stdio.ts +80 -47
  203. package/src/types.ts +223 -119
  204. package/src/utils/getPluginConfig.ts +1 -1
  205. package/src/utils/seal.ts +46 -0
  206. package/src/utils/toStandardSchema.ts +1 -1
  207. package/dist/@types/assets.d.js +0 -2
  208. package/dist/@types/assets.d.js.map +0 -1
  209. package/dist/collection/getAccessField.d.ts +0 -12
  210. package/dist/collection/getAccessField.d.ts.map +0 -1
  211. package/dist/collection/getAccessField.js +0 -57
  212. package/dist/collection/getAccessField.js.map +0 -1
  213. package/dist/collection/index.d.ts +0 -6
  214. package/dist/collection/index.d.ts.map +0 -1
  215. package/dist/collection/index.js +0 -60
  216. package/dist/collection/index.js.map +0 -1
  217. package/dist/components/AccessField/index.client.d.ts +0 -10
  218. package/dist/components/AccessField/index.client.d.ts.map +0 -1
  219. package/dist/components/AccessField/index.client.js +0 -305
  220. package/dist/components/AccessField/index.client.js.map +0 -1
  221. package/dist/components/AccessField/index.css +0 -93
  222. package/dist/utils/getVirtualFieldNames.d.ts +0 -14
  223. package/dist/utils/getVirtualFieldNames.d.ts.map +0 -1
  224. package/dist/utils/getVirtualFieldNames.js +0 -35
  225. package/dist/utils/getVirtualFieldNames.js.map +0 -1
  226. package/dist/utils/localAPIDefaults.d.ts +0 -20
  227. package/dist/utils/localAPIDefaults.d.ts.map +0 -1
  228. package/dist/utils/localAPIDefaults.js +0 -19
  229. package/dist/utils/localAPIDefaults.js.map +0 -1
  230. package/dist/utils/schemaConversion/buildToolInput.d.ts +0 -29
  231. package/dist/utils/schemaConversion/buildToolInput.d.ts.map +0 -1
  232. package/dist/utils/schemaConversion/buildToolInput.js +0 -51
  233. package/dist/utils/schemaConversion/buildToolInput.js.map +0 -1
  234. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.d.ts +0 -7
  235. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.d.ts.map +0 -1
  236. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.js +0 -20
  237. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.js.map +0 -1
  238. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts +0 -15
  239. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts.map +0 -1
  240. package/dist/utils/schemaConversion/sanitizeEntitySchema.js +0 -464
  241. package/dist/utils/schemaConversion/sanitizeEntitySchema.js.map +0 -1
  242. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js +0 -158
  243. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js.map +0 -1
  244. package/dist/utils/transformPointDataToPayload.d.ts +0 -7
  245. package/dist/utils/transformPointDataToPayload.d.ts.map +0 -1
  246. package/dist/utils/transformPointDataToPayload.js +0 -28
  247. package/dist/utils/transformPointDataToPayload.js.map +0 -1
  248. package/src/@types/assets.d.ts +0 -3
  249. package/src/collection/getAccessField.ts +0 -64
  250. package/src/collection/index.ts +0 -64
  251. package/src/components/AccessField/index.client.tsx +0 -344
  252. package/src/components/AccessField/index.css +0 -93
  253. package/src/utils/getVirtualFieldNames.ts +0 -53
  254. package/src/utils/localAPIDefaults.ts +0 -22
  255. package/src/utils/schemaConversion/buildToolInput.ts +0 -68
  256. package/src/utils/schemaConversion/removeVirtualFieldsFromSchema.ts +0 -27
  257. package/src/utils/schemaConversion/sanitizeEntitySchema.spec.ts +0 -103
  258. package/src/utils/schemaConversion/sanitizeEntitySchema.ts +0 -529
  259. package/src/utils/transformPointDataToPayload.ts +0 -40
@@ -1,116 +1,143 @@
1
- import type { SelectType } from 'payload'
2
-
3
- import { z } from 'zod'
4
-
5
- import { defineCollectionTool } from '../../../defineTool.js'
6
- import { getLogger } from '../../../utils/getLogger.js'
7
1
  import {
2
+ createDocumentsInputSchema,
8
3
  getCollectionVirtualFieldNames,
4
+ hasDraftValidationEnabled,
9
5
  stripVirtualFields,
10
- } from '../../../utils/getVirtualFieldNames.js'
11
- import { localAPIDefaults } from '../../../utils/localAPIDefaults.js'
12
- import { buildToolInput } from '../../../utils/schemaConversion/buildToolInput.js'
13
- import { sanitizeEntitySchema } from '../../../utils/schemaConversion/sanitizeEntitySchema.js'
14
- import { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'
6
+ transformPointDataToPayload,
7
+ validateCollectionData,
8
+ } from 'payload'
9
+
10
+ import { defaultAccess } from '../../../defaultAccess.js'
11
+ import { defineCollectionTool } from '../../../defineTool.js'
12
+ import { getLogger } from '../../../utils/getLogger.js'
13
+ import { formatEntityError } from '../formatEntityError.js'
14
+ import { fileInputSchema, resolveFile } from './fileInput.js'
15
15
 
16
- const DEFAULT_DESCRIPTION = 'Create a document in a collection.'
16
+ const DEFAULT_DESCRIPTION =
17
+ 'Create one or more documents. Each can have different data or a file. Prefer uploadReference after upload, externalURL for URLs, or base64 for small local files.'
17
18
 
18
- export const createCollectionTool = defineCollectionTool({
19
+ export const createDocumentsTool = defineCollectionTool({
20
+ access: (args) =>
21
+ defaultAccess(args) && Boolean(args.permissions?.collections?.[args.slug]?.create),
22
+ annotations: {
23
+ destructiveHint: false,
24
+ idempotentHint: false,
25
+ openWorldHint: false,
26
+ readOnlyHint: false,
27
+ title: 'Create Documents',
28
+ },
19
29
  description: DEFAULT_DESCRIPTION,
20
- input: ({ collectionSchema }) =>
21
- buildToolInput({
22
- controls: {
23
- depth: z
24
- .number()
25
- .int()
26
- .min(0)
27
- .max(10)
28
- .describe('How many levels deep to populate relationships in response')
29
- .optional()
30
- .default(0),
31
- draft: z
32
- .boolean()
33
- .describe('Whether to create the document as a draft')
34
- .optional()
35
- .default(false),
36
- fallbackLocale: z
37
- .string()
38
- .describe('Optional: fallback locale code to use when requested locale is not available')
39
- .optional(),
40
- locale: z
41
- .string()
42
- .describe(
43
- 'Optional: locale code to create the document in (e.g., "en", "es"). Defaults to the default locale',
44
- )
45
- .optional(),
46
- select: z
47
- .string()
48
- .describe(
49
- 'Optional: define exactly which fields you\'d like to create (JSON), e.g., \'{"title": "My Post"}\'',
50
- )
51
- .optional(),
52
- },
53
- dataDescription: 'The document fields to create',
54
- dataSchema: sanitizeEntitySchema(collectionSchema),
55
- }),
56
- }).handler(async ({ authorizedMCP, collectionSlug, input, req }) => {
30
+ input: createDocumentsInputSchema({ file: fileInputSchema }),
31
+ }).handler(async ({ slug, authorizedMCP, input, req }) => {
57
32
  const payload = req.payload
33
+ const collectionConfig = payload.collections[slug]?.config
58
34
  const logger = getLogger({ payload })
35
+ const {
36
+ depth,
37
+ documents,
38
+ draft,
39
+ fallbackLocale,
40
+ locale,
41
+ populate,
42
+ publishAllLocales,
43
+ returning,
44
+ select,
45
+ } = input
46
+ const shouldUsePartialSchema =
47
+ draft === true && collectionConfig !== undefined && !hasDraftValidationEnabled(collectionConfig)
59
48
 
60
- const { data, depth, draft, fallbackLocale, locale, select } = input
61
-
62
- logger.info(
63
- `Creating document in collection: ${collectionSlug}${locale ? ` with locale: ${locale}` : ''}`,
64
- )
49
+ logger.info(`Creating ${documents.length} documents in collection: ${slug}`)
65
50
 
66
51
  try {
67
- let parsedData = transformPointDataToPayload(data)
68
- const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, collectionSlug)
69
- parsedData = stripVirtualFields(parsedData, virtualFieldNames)
52
+ const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, slug)
53
+ const docs: Array<
54
+ { doc: Record<string, unknown>; index: number } | { id: number | string; index: number }
55
+ > = []
56
+ const errors: Array<{ index: number; message: string }> = []
57
+ let validationSchema: Record<string, unknown> | undefined
70
58
 
71
- let selectClause: SelectType | undefined
72
- if (select) {
59
+ for (const [index, document] of documents.entries()) {
73
60
  try {
74
- selectClause = JSON.parse(select) as SelectType
75
- } catch {
76
- logger.warn(`Invalid select clause JSON: ${select}`)
77
- return { content: [{ type: 'text', text: 'Error: Invalid JSON in select clause' }] }
61
+ const inputData = stripVirtualFields(document.data, virtualFieldNames)
62
+ validateCollectionData({
63
+ slug,
64
+ data: inputData,
65
+ partial: shouldUsePartialSchema,
66
+ req,
67
+ })
68
+
69
+ const parsedData = transformPointDataToPayload(inputData)
70
+ const file = await resolveFile({ slug, input: document.file, req })
71
+ const result = await payload.create({
72
+ collection: slug,
73
+ data: parsedData,
74
+ depth,
75
+ draft,
76
+ overrideAccess: authorizedMCP.overrideAccess,
77
+ populate,
78
+ publishAllLocales,
79
+ req,
80
+ ...(file ? { file } : {}),
81
+ ...(locale ? { locale } : {}),
82
+ ...(fallbackLocale !== undefined ? { fallbackLocale } : {}),
83
+ select: returning ? select : { id: true },
84
+ })
85
+
86
+ docs.push(returning ? { doc: result, index } : { id: result.id, index })
87
+ } catch (error) {
88
+ const message = error instanceof Error ? error.message : 'Unknown error'
89
+ const formattedError = formatEntityError({
90
+ slug,
91
+ action: 'creating',
92
+ entity: 'collection',
93
+ error,
94
+ req,
95
+ })
96
+ const structuredContent = formattedError.structuredContent as
97
+ | { schema?: unknown }
98
+ | undefined
99
+ const schema = structuredContent?.schema
100
+ const errorContent = formattedError.content[0]
101
+ const formattedMessage =
102
+ errorContent?.type === 'text'
103
+ ? (errorContent.text.split('\n\nUse this schema')[0] ?? message)
104
+ : message
105
+
106
+ if (!validationSchema && schema && typeof schema === 'object') {
107
+ validationSchema = schema as Record<string, unknown>
108
+ }
109
+
110
+ logger.error(`Error creating document at index ${index} in ${slug}: ${message}`)
111
+ errors.push({ index, message: formattedMessage })
78
112
  }
79
113
  }
80
114
 
81
- const result = await payload.create({
82
- collection: collectionSlug,
83
- data: parsedData,
84
- depth,
85
- draft,
86
- req,
87
- ...localAPIDefaults(authorizedMCP),
88
- ...(locale ? { locale } : {}),
89
- ...(fallbackLocale ? { fallbackLocale } : {}),
90
- ...(selectClause ? { select: selectClause } : {}),
91
- })
115
+ const batchResult = { docs, errors }
116
+ const retryMessage = errors.length > 0 ? '\nRetry failed indexes only.' : ''
117
+ const schemaMessage = validationSchema
118
+ ? `\n\nUse this schema for data:\n\`\`\`json\n${JSON.stringify(validationSchema)}\n\`\`\``
119
+ : ''
120
+ const structuredContent = validationSchema
121
+ ? { ...batchResult, schema: validationSchema }
122
+ : batchResult
92
123
 
93
- logger.info(`Successfully created document in ${collectionSlug} with ID: ${result.id}`)
124
+ logger.info(`Created ${docs.length} of ${documents.length} documents in ${slug}`)
94
125
 
95
126
  return {
96
127
  content: [
97
128
  {
98
129
  type: 'text',
99
- text: `Document created successfully in collection "${collectionSlug}"!\nCreated document:\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``,
130
+ text: `Created ${docs.length} of ${documents.length} documents in collection "${slug}".${retryMessage}\nResults:\n\`\`\`json\n${JSON.stringify(batchResult)}\n\`\`\`${schemaMessage}`,
100
131
  },
101
132
  ],
102
- doc: result as Record<string, unknown>,
133
+ doc: structuredContent as unknown as Record<string, unknown>,
134
+ isError: docs.length === 0 && errors.length > 0,
135
+ structuredContent,
103
136
  }
104
137
  } catch (error) {
105
- const errorMessage = error instanceof Error ? error.message : 'Unknown error'
106
- logger.error(`Error creating document in ${collectionSlug}: ${errorMessage}`)
107
- return {
108
- content: [
109
- {
110
- type: 'text',
111
- text: `Error creating document in collection "${collectionSlug}": ${errorMessage}`,
112
- },
113
- ],
114
- }
138
+ const message = error instanceof Error ? error.message : 'Unknown error'
139
+
140
+ logger.error(`Error creating documents in ${slug}: ${message}`)
141
+ return formatEntityError({ slug, action: 'creating', entity: 'collection', error, req })
115
142
  }
116
143
  })
@@ -1,102 +1,76 @@
1
- import { z } from 'zod'
1
+ import { deleteDocumentsInputSchema, parseDocumentID } from 'payload'
2
2
 
3
+ import { defaultAccess } from '../../../defaultAccess.js'
3
4
  import { defineCollectionTool } from '../../../defineTool.js'
4
5
  import { getLogger } from '../../../utils/getLogger.js'
5
- import { localAPIDefaults } from '../../../utils/localAPIDefaults.js'
6
6
 
7
- const DEFAULT_DESCRIPTION = 'Delete documents in a collection by ID or where clause.'
7
+ const DEFAULT_DESCRIPTION =
8
+ 'Delete documents in any collection by passing the collection slug and ID or where clause.'
8
9
 
9
- export const deleteCollectionTool = defineCollectionTool({
10
+ export const deleteDocumentsTool = defineCollectionTool({
11
+ access: (args) =>
12
+ defaultAccess(args) && Boolean(args.permissions?.collections?.[args.slug]?.delete),
13
+ annotations: {
14
+ destructiveHint: true,
15
+ idempotentHint: false,
16
+ openWorldHint: false,
17
+ readOnlyHint: false,
18
+ title: 'Delete Documents',
19
+ },
10
20
  description: DEFAULT_DESCRIPTION,
11
- input: z.object({
12
- id: z
13
- .union([z.string(), z.number()])
14
- .describe('Optional: specific document ID to delete')
15
- .optional(),
16
- depth: z
17
- .number()
18
- .int()
19
- .min(0)
20
- .max(10)
21
- .describe('Depth of population for relationships in response')
22
- .optional()
23
- .default(0),
24
- fallbackLocale: z
25
- .string()
26
- .describe('Optional: fallback locale code to use when requested locale is not available')
27
- .optional(),
28
- locale: z
29
- .string()
30
- .describe(
31
- 'Optional: locale code for the operation (e.g., "en", "es"). Defaults to the default locale',
32
- )
33
- .optional(),
34
- where: z
35
- .string()
36
- .describe('Optional: JSON string for where clause to delete multiple documents')
37
- .optional(),
38
- }),
39
- }).handler(async ({ authorizedMCP, collectionSlug, input, req }) => {
21
+ input: deleteDocumentsInputSchema,
22
+ }).handler(async ({ slug, authorizedMCP, input, req }) => {
40
23
  const payload = req.payload
41
24
  const logger = getLogger({ payload })
42
25
 
43
26
  const { id, depth, fallbackLocale, locale, where } = input
44
27
 
45
28
  logger.info(
46
- `Deleting document from collection: ${collectionSlug}${id ? ` with ID: ${id}` : ' with where clause'}${locale ? `, locale: ${locale}` : ''}`,
29
+ `Deleting document from collection: ${slug}${id ? ` with ID: ${id}` : ' with where clause'}${locale ? `, locale: ${locale}` : ''}`,
47
30
  )
48
31
 
49
32
  try {
50
- if (!id && !where) {
51
- return {
52
- content: [{ type: 'text', text: 'Error: Either id or where clause must be provided' }],
53
- }
54
- }
55
-
56
- let whereClause: Record<string, unknown> = {}
57
- if (where) {
58
- try {
59
- whereClause = JSON.parse(where) as Record<string, unknown>
60
- } catch {
61
- logger.warn(`Invalid where clause JSON: ${where}`)
62
- return { content: [{ type: 'text', text: 'Error: Invalid JSON in where clause' }] }
63
- }
64
- }
65
-
66
- const deleteOptions: Record<string, unknown> = {
67
- collection: collectionSlug,
68
- depth,
69
- req,
70
- ...localAPIDefaults(authorizedMCP),
71
- ...(locale && { locale }),
72
- ...(fallbackLocale && { fallbackLocale }),
73
- }
33
+ if (id !== undefined) {
34
+ const result = await payload.delete({
35
+ id: parseDocumentID({ id, collectionSlug: slug, payload }),
36
+ collection: slug,
37
+ depth,
38
+ overrideAccess: authorizedMCP.overrideAccess,
39
+ req,
40
+ ...(locale && { locale }),
41
+ ...(fallbackLocale !== undefined && { fallbackLocale }),
42
+ })
74
43
 
75
- if (id) {
76
- deleteOptions.id = id
77
- } else {
78
- deleteOptions.where = whereClause
79
- }
80
-
81
- const result = await payload.delete(deleteOptions as Parameters<typeof payload.delete>[0])
82
-
83
- if (id) {
84
44
  return {
85
45
  content: [
86
46
  {
87
47
  type: 'text',
88
- text: `Document deleted successfully from collection "${collectionSlug}"!\nDeleted document:\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``,
48
+ text: `Document deleted successfully from collection "${slug}"!\nDeleted document:\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``,
89
49
  },
90
50
  ],
91
- doc: result as Record<string, unknown>,
51
+ doc: result,
92
52
  }
93
53
  }
94
54
 
95
- const bulkResult = result as { docs?: unknown[]; errors?: unknown[] }
96
- const docs = bulkResult.docs || []
97
- const errors = bulkResult.errors || []
55
+ if (where === undefined) {
56
+ return {
57
+ content: [{ type: 'text', text: 'Error: Either id or where clause must be provided' }],
58
+ }
59
+ }
60
+
61
+ const result = await payload.delete({
62
+ collection: slug,
63
+ depth,
64
+ overrideAccess: authorizedMCP.overrideAccess,
65
+ req,
66
+ where,
67
+ ...(locale && { locale }),
68
+ ...(fallbackLocale !== undefined && { fallbackLocale }),
69
+ })
70
+ const docs = result.docs || []
71
+ const errors = result.errors || []
98
72
 
99
- let responseText = `Document deleted successfully from collection "${collectionSlug}"!\nDeleted: ${docs.length} documents\nErrors: ${errors.length}\n---`
73
+ let responseText = `Document deleted successfully from collection "${slug}"!\nDeleted: ${docs.length} documents\nErrors: ${errors.length}\n---`
100
74
  if (docs.length > 0) {
101
75
  responseText += `\n\nDeleted documents:\n\`\`\`json\n${JSON.stringify(docs)}\n\`\`\``
102
76
  }
@@ -110,12 +84,12 @@ export const deleteCollectionTool = defineCollectionTool({
110
84
  }
111
85
  } catch (error) {
112
86
  const errorMessage = error instanceof Error ? error.message : 'Unknown error'
113
- logger.error(`Error deleting document from ${collectionSlug}: ${errorMessage}`)
87
+ logger.error(`Error deleting document from ${slug}: ${errorMessage}`)
114
88
  return {
115
89
  content: [
116
90
  {
117
91
  type: 'text',
118
- text: `Error deleting document from collection "${collectionSlug}": ${errorMessage}`,
92
+ text: `Error deleting document from collection "${slug}": ${errorMessage}`,
119
93
  },
120
94
  ],
121
95
  }
@@ -0,0 +1,84 @@
1
+ import {
2
+ duplicateDocumentInputSchema,
3
+ getCollectionVirtualFieldNames,
4
+ parseDocumentID,
5
+ stripVirtualFields,
6
+ transformPointDataToPayload,
7
+ validateCollectionData,
8
+ } from 'payload'
9
+
10
+ import { defaultAccess } from '../../../defaultAccess.js'
11
+ import { defineCollectionTool } from '../../../defineTool.js'
12
+ import { getLogger } from '../../../utils/getLogger.js'
13
+ import { formatEntityError } from '../formatEntityError.js'
14
+
15
+ const DEFAULT_DESCRIPTION =
16
+ 'Duplicate a document in any collection by passing the collection slug and source document ID.'
17
+
18
+ export const duplicateDocumentTool = defineCollectionTool({
19
+ access: (args) =>
20
+ defaultAccess(args) && Boolean(args.permissions?.collections?.[args.slug]?.create),
21
+ annotations: {
22
+ destructiveHint: false,
23
+ idempotentHint: false,
24
+ openWorldHint: false,
25
+ readOnlyHint: false,
26
+ title: 'Duplicate Document',
27
+ },
28
+ description: DEFAULT_DESCRIPTION,
29
+ input: duplicateDocumentInputSchema,
30
+ }).handler(async ({ slug, authorizedMCP, input, req }) => {
31
+ const payload = req.payload
32
+ const logger = getLogger({ payload })
33
+ const { id, data, depth, draft, fallbackLocale, locale, populate, select, selectedLocales } =
34
+ input
35
+
36
+ logger.info(`Duplicating document in collection: ${slug} with ID: ${id}`)
37
+
38
+ try {
39
+ const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, slug)
40
+ const inputData = data ? stripVirtualFields(data, virtualFieldNames) : undefined
41
+
42
+ if (inputData) {
43
+ validateCollectionData({
44
+ slug,
45
+ data: inputData,
46
+ partial: true,
47
+ req,
48
+ })
49
+ }
50
+
51
+ const parsedData = inputData ? transformPointDataToPayload(inputData) : undefined
52
+
53
+ const result = await payload.duplicate({
54
+ id: parseDocumentID({ id, collectionSlug: slug, payload }),
55
+ collection: slug,
56
+ depth,
57
+ draft,
58
+ overrideAccess: authorizedMCP.overrideAccess,
59
+ req,
60
+ ...(parsedData ? { data: parsedData } : {}),
61
+ ...(locale ? { locale } : {}),
62
+ ...(fallbackLocale !== undefined ? { fallbackLocale } : {}),
63
+ ...(populate ? { populate } : {}),
64
+ ...(select ? { select } : {}),
65
+ ...(selectedLocales ? { selectedLocales } : {}),
66
+ })
67
+
68
+ logger.info(`Successfully duplicated document in ${slug} from ID: ${id}`)
69
+
70
+ return {
71
+ content: [
72
+ {
73
+ type: 'text',
74
+ text: `Document duplicated successfully in collection "${slug}"!\nDuplicated document:\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``,
75
+ },
76
+ ],
77
+ doc: result,
78
+ }
79
+ } catch (error) {
80
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error'
81
+ logger.error(`Error duplicating document in ${slug}: ${errorMessage}`)
82
+ return formatEntityError({ slug, action: 'duplicating', entity: 'collection', error, req })
83
+ }
84
+ })
@@ -0,0 +1,93 @@
1
+ import type { PayloadRequest } from 'payload'
2
+
3
+ import { describe, expect, it } from 'vitest'
4
+
5
+ import { fileInputSchema, resolveFile } from './fileInput.js'
6
+
7
+ describe('MCP file input', () => {
8
+ it('should reject malformed MIME types', () => {
9
+ const result = fileInputSchema.safeParse({
10
+ data: 'aGVsbG8=',
11
+ mimeType: 'text/plain\r\nx-test: value',
12
+ name: 'hello.txt',
13
+ source: 'base64',
14
+ })
15
+
16
+ expect(result.success).toBe(false)
17
+ })
18
+
19
+ it('should accept a prepared upload', () => {
20
+ const result = fileInputSchema.safeParse({
21
+ file: {
22
+ filename: 'image.png',
23
+ mimeType: 'image/png',
24
+ size: 123,
25
+ uploadReference: { uploadId: 'upload-id' },
26
+ },
27
+ source: 'uploadReference',
28
+ })
29
+
30
+ expect(result.success).toBe(true)
31
+ })
32
+
33
+ it('should reject oversized base64 files', async () => {
34
+ const req = createRequest({ maxFileSize: 4 })
35
+
36
+ await expect(
37
+ resolveFile({
38
+ slug: 'media',
39
+ input: {
40
+ data: Buffer.from('hello').toString('base64'),
41
+ mimeType: 'text/plain',
42
+ name: 'hello.txt',
43
+ source: 'base64',
44
+ },
45
+ req,
46
+ }),
47
+ ).rejects.toThrow('File exceeds the 4 byte upload limit.')
48
+ })
49
+
50
+ it('should reject URLs outside the collection allowlist', async () => {
51
+ const req = createRequest({
52
+ allowList: [{ hostname: 'assets.example.com', protocol: 'https' }],
53
+ })
54
+
55
+ await expect(
56
+ resolveFile({
57
+ slug: 'media',
58
+ input: {
59
+ source: 'externalURL',
60
+ url: 'https://example.com/image.png',
61
+ },
62
+ req,
63
+ }),
64
+ ).rejects.toThrow('The provided file URL is not allowed.')
65
+ })
66
+ })
67
+
68
+ function createRequest({
69
+ allowList,
70
+ maxFileSize,
71
+ }: {
72
+ allowList?: Array<{ hostname: string; protocol: 'http' | 'https' }>
73
+ maxFileSize?: number
74
+ }): PayloadRequest {
75
+ return {
76
+ payload: {
77
+ collections: {
78
+ media: {
79
+ config: {
80
+ upload: allowList ? { pasteURL: { allowList } } : {},
81
+ },
82
+ },
83
+ },
84
+ config: {
85
+ upload: {
86
+ limits: {
87
+ fileSize: maxFileSize,
88
+ },
89
+ },
90
+ },
91
+ },
92
+ } as unknown as PayloadRequest
93
+ }