@payloadcms/plugin-mcp 4.0.0-internal.2fddfc0 → 4.0.0-internal.314c594

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 (179) hide show
  1. package/LICENSE.md +1 -1
  2. package/bin.js +7 -0
  3. package/dist/defaultAccess.d.ts.map +1 -1
  4. package/dist/defineTool.d.ts +8 -8
  5. package/dist/defineTool.d.ts.map +1 -1
  6. package/dist/endpoint/access.d.ts +2 -7
  7. package/dist/endpoint/access.d.ts.map +1 -1
  8. package/dist/endpoint/access.js +4 -11
  9. package/dist/endpoint/access.js.map +1 -1
  10. package/dist/endpoint/index.d.ts +1 -1
  11. package/dist/endpoint/index.d.ts.map +1 -1
  12. package/dist/endpoint/index.js +57 -17
  13. package/dist/endpoint/index.js.map +1 -1
  14. package/dist/index.d.ts +2 -2
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +2 -2
  17. package/dist/index.js.map +1 -1
  18. package/dist/mcp/buildMcpServer.d.ts +4 -4
  19. package/dist/mcp/buildMcpServer.d.ts.map +1 -1
  20. package/dist/mcp/buildMcpServer.js +32 -10
  21. package/dist/mcp/buildMcpServer.js.map +1 -1
  22. package/dist/mcp/builtin/collections/countTool.d.ts.map +1 -1
  23. package/dist/mcp/builtin/collections/countTool.js +1 -2
  24. package/dist/mcp/builtin/collections/countTool.js.map +1 -1
  25. package/dist/mcp/builtin/collections/countVersionsTool.d.ts.map +1 -1
  26. package/dist/mcp/builtin/collections/countVersionsTool.js +1 -2
  27. package/dist/mcp/builtin/collections/countVersionsTool.js.map +1 -1
  28. package/dist/mcp/builtin/collections/createTool.d.ts +1 -1
  29. package/dist/mcp/builtin/collections/createTool.d.ts.map +1 -1
  30. package/dist/mcp/builtin/collections/createTool.js +91 -40
  31. package/dist/mcp/builtin/collections/createTool.js.map +1 -1
  32. package/dist/mcp/builtin/collections/deleteTool.d.ts.map +1 -1
  33. package/dist/mcp/builtin/collections/deleteTool.js +1 -2
  34. package/dist/mcp/builtin/collections/deleteTool.js.map +1 -1
  35. package/dist/mcp/builtin/collections/duplicateTool.d.ts.map +1 -1
  36. package/dist/mcp/builtin/collections/duplicateTool.js +1 -2
  37. package/dist/mcp/builtin/collections/duplicateTool.js.map +1 -1
  38. package/dist/mcp/builtin/collections/fileInput.d.ts +28 -0
  39. package/dist/mcp/builtin/collections/fileInput.d.ts.map +1 -0
  40. package/dist/mcp/builtin/collections/fileInput.js +124 -0
  41. package/dist/mcp/builtin/collections/fileInput.js.map +1 -0
  42. package/dist/mcp/builtin/collections/fileInput.spec.js +86 -0
  43. package/dist/mcp/builtin/collections/fileInput.spec.js.map +1 -0
  44. package/dist/mcp/builtin/collections/findDistinctTool.d.ts.map +1 -1
  45. package/dist/mcp/builtin/collections/findDistinctTool.js +1 -2
  46. package/dist/mcp/builtin/collections/findDistinctTool.js.map +1 -1
  47. package/dist/mcp/builtin/collections/findTool.d.ts.map +1 -1
  48. package/dist/mcp/builtin/collections/findTool.js +3 -4
  49. package/dist/mcp/builtin/collections/findTool.js.map +1 -1
  50. package/dist/mcp/builtin/collections/findVersionByIDTool.d.ts.map +1 -1
  51. package/dist/mcp/builtin/collections/findVersionByIDTool.js +1 -2
  52. package/dist/mcp/builtin/collections/findVersionByIDTool.js.map +1 -1
  53. package/dist/mcp/builtin/collections/findVersionsTool.d.ts.map +1 -1
  54. package/dist/mcp/builtin/collections/findVersionsTool.js +1 -2
  55. package/dist/mcp/builtin/collections/findVersionsTool.js.map +1 -1
  56. package/dist/mcp/builtin/collections/formatCollectionError.d.ts +1 -1
  57. package/dist/mcp/builtin/collections/formatCollectionError.d.ts.map +1 -1
  58. package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -1
  59. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +45 -5
  60. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -1
  61. package/dist/mcp/builtin/collections/restoreVersionTool.d.ts.map +1 -1
  62. package/dist/mcp/builtin/collections/restoreVersionTool.js +1 -2
  63. package/dist/mcp/builtin/collections/restoreVersionTool.js.map +1 -1
  64. package/dist/mcp/builtin/collections/updateTool.d.ts.map +1 -1
  65. package/dist/mcp/builtin/collections/updateTool.js +24 -12
  66. package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
  67. package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts +2 -0
  68. package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts.map +1 -0
  69. package/dist/mcp/builtin/collections/uploadInstructionsTool.js +55 -0
  70. package/dist/mcp/builtin/collections/uploadInstructionsTool.js.map +1 -0
  71. package/dist/mcp/builtin/getConfigInfoTool.d.ts.map +1 -1
  72. package/dist/mcp/builtin/getConfigInfoTool.js +2 -5
  73. package/dist/mcp/builtin/getConfigInfoTool.js.map +1 -1
  74. package/dist/mcp/builtin/globals/countVersionsTool.d.ts.map +1 -1
  75. package/dist/mcp/builtin/globals/countVersionsTool.js +1 -2
  76. package/dist/mcp/builtin/globals/countVersionsTool.js.map +1 -1
  77. package/dist/mcp/builtin/globals/findTool.d.ts.map +1 -1
  78. package/dist/mcp/builtin/globals/findTool.js +2 -2
  79. package/dist/mcp/builtin/globals/findTool.js.map +1 -1
  80. package/dist/mcp/builtin/globals/findVersionByIDTool.d.ts.map +1 -1
  81. package/dist/mcp/builtin/globals/findVersionByIDTool.js +1 -2
  82. package/dist/mcp/builtin/globals/findVersionByIDTool.js.map +1 -1
  83. package/dist/mcp/builtin/globals/findVersionsTool.d.ts.map +1 -1
  84. package/dist/mcp/builtin/globals/findVersionsTool.js +1 -2
  85. package/dist/mcp/builtin/globals/findVersionsTool.js.map +1 -1
  86. package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts.map +1 -1
  87. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js +21 -3
  88. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js.map +1 -1
  89. package/dist/mcp/builtin/globals/restoreVersionTool.d.ts.map +1 -1
  90. package/dist/mcp/builtin/globals/restoreVersionTool.js +1 -2
  91. package/dist/mcp/builtin/globals/restoreVersionTool.js.map +1 -1
  92. package/dist/mcp/builtin/globals/updateTool.d.ts.map +1 -1
  93. package/dist/mcp/builtin/globals/updateTool.js +2 -2
  94. package/dist/mcp/builtin/globals/updateTool.js.map +1 -1
  95. package/dist/mcp/builtin/validateEntityData.d.ts.map +1 -1
  96. package/dist/mcp/builtin/validateEntityData.js +1 -1
  97. package/dist/mcp/builtin/validateEntityData.js.map +1 -1
  98. package/dist/mcp/builtinTools.d.ts +6 -0
  99. package/dist/mcp/builtinTools.d.ts.map +1 -1
  100. package/dist/mcp/builtinTools.js +9 -3
  101. package/dist/mcp/builtinTools.js.map +1 -1
  102. package/dist/mcp/sanitizeMCPConfig.d.ts.map +1 -1
  103. package/dist/mcp/sanitizeMCPConfig.js +5 -1
  104. package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
  105. package/dist/stdio.d.ts +3 -4
  106. package/dist/stdio.d.ts.map +1 -1
  107. package/dist/stdio.js +61 -42
  108. package/dist/stdio.js.map +1 -1
  109. package/dist/types.d.ts +57 -9
  110. package/dist/types.d.ts.map +1 -1
  111. package/dist/types.js +2 -4
  112. package/dist/types.js.map +1 -1
  113. package/dist/utils/camelCase.d.ts.map +1 -1
  114. package/dist/utils/resolveProjectRoot.d.ts.map +1 -1
  115. package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts +28 -0
  116. package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts.map +1 -0
  117. package/dist/utils/schemaConversion/filterFieldsByAccess.js +71 -0
  118. package/dist/utils/schemaConversion/filterFieldsByAccess.js.map +1 -0
  119. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts +5 -3
  120. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts.map +1 -1
  121. package/dist/utils/schemaConversion/getEntityInputSchema.js +44 -12
  122. package/dist/utils/schemaConversion/getEntityInputSchema.js.map +1 -1
  123. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts +5 -10
  124. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts.map +1 -1
  125. package/dist/utils/schemaConversion/sanitizeEntitySchema.js +15 -95
  126. package/dist/utils/schemaConversion/sanitizeEntitySchema.js.map +1 -1
  127. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js +15 -40
  128. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js.map +1 -1
  129. package/dist/utils/toStandardSchema.d.ts.map +1 -1
  130. package/package.json +8 -10
  131. package/src/endpoint/access.ts +3 -10
  132. package/src/endpoint/index.ts +45 -16
  133. package/src/index.ts +4 -4
  134. package/src/mcp/buildMcpServer.ts +40 -20
  135. package/src/mcp/builtin/collections/countTool.ts +1 -2
  136. package/src/mcp/builtin/collections/countVersionsTool.ts +1 -2
  137. package/src/mcp/builtin/collections/createTool.ts +90 -34
  138. package/src/mcp/builtin/collections/deleteTool.ts +1 -2
  139. package/src/mcp/builtin/collections/duplicateTool.ts +1 -2
  140. package/src/mcp/builtin/collections/fileInput.spec.ts +93 -0
  141. package/src/mcp/builtin/collections/fileInput.ts +164 -0
  142. package/src/mcp/builtin/collections/findDistinctTool.ts +1 -2
  143. package/src/mcp/builtin/collections/findTool.ts +3 -4
  144. package/src/mcp/builtin/collections/findVersionByIDTool.ts +1 -2
  145. package/src/mcp/builtin/collections/findVersionsTool.ts +1 -2
  146. package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +43 -9
  147. package/src/mcp/builtin/collections/restoreVersionTool.ts +1 -2
  148. package/src/mcp/builtin/collections/updateTool.ts +26 -10
  149. package/src/mcp/builtin/collections/uploadInstructionsTool.ts +64 -0
  150. package/src/mcp/builtin/getConfigInfoTool.ts +2 -4
  151. package/src/mcp/builtin/globals/countVersionsTool.ts +1 -2
  152. package/src/mcp/builtin/globals/findTool.ts +2 -2
  153. package/src/mcp/builtin/globals/findVersionByIDTool.ts +1 -2
  154. package/src/mcp/builtin/globals/findVersionsTool.ts +1 -2
  155. package/src/mcp/builtin/globals/getGlobalSchemaTool.ts +25 -3
  156. package/src/mcp/builtin/globals/restoreVersionTool.ts +1 -2
  157. package/src/mcp/builtin/globals/updateTool.ts +2 -2
  158. package/src/mcp/builtin/validateEntityData.ts +1 -1
  159. package/src/mcp/builtinTools.ts +9 -2
  160. package/src/mcp/sanitizeMCPConfig.ts +5 -1
  161. package/src/stdio.ts +61 -43
  162. package/src/types.ts +57 -9
  163. package/src/utils/schemaConversion/filterFieldsByAccess.ts +123 -0
  164. package/src/utils/schemaConversion/getEntityInputSchema.ts +45 -27
  165. package/src/utils/schemaConversion/sanitizeEntitySchema.spec.ts +12 -19
  166. package/src/utils/schemaConversion/sanitizeEntitySchema.ts +17 -114
  167. package/dist/@types/assets.d.js +0 -2
  168. package/dist/@types/assets.d.js.map +0 -1
  169. package/dist/utils/localAPIDefaults.d.ts +0 -20
  170. package/dist/utils/localAPIDefaults.d.ts.map +0 -1
  171. package/dist/utils/localAPIDefaults.js +0 -19
  172. package/dist/utils/localAPIDefaults.js.map +0 -1
  173. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.d.ts +0 -7
  174. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.d.ts.map +0 -1
  175. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.js +0 -20
  176. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.js.map +0 -1
  177. package/src/@types/assets.d.ts +0 -3
  178. package/src/utils/localAPIDefaults.ts +0 -22
  179. package/src/utils/schemaConversion/removeVirtualFieldsFromSchema.ts +0 -27
package/src/index.ts CHANGED
@@ -6,8 +6,8 @@ import { mcpEndpoint } from './endpoint/index.js'
6
6
  import { sanitizeMCPConfig } from './mcp/sanitizeMCPConfig.js'
7
7
 
8
8
  declare module 'payload' {
9
- export interface PayloadRequest {
10
- payloadAPI: 'GraphQL' | 'local' | 'MCP' | 'REST'
9
+ export interface PayloadRequestAPI {
10
+ MCP: true
11
11
  }
12
12
  interface RegisteredPlugins {
13
13
  /** After the plugin's `plugin` callback runs, `options` holds the sanitized config. */
@@ -22,8 +22,8 @@ export { defineCollectionTool, defineGlobalTool, definePrompt, defineTool } from
22
22
  export const mcpPlugin = definePlugin<MCPPluginConfig>({
23
23
  slug: '@payloadcms/plugin-mcp',
24
24
  order: 10,
25
- plugin: ({ config, plugins, ...rawConfig }) => {
26
- const pluginConfig = sanitizeMCPConfig({ config, pluginConfig: rawConfig })
25
+ plugin: ({ config, options, plugins }) => {
26
+ const pluginConfig = sanitizeMCPConfig({ config, pluginConfig: options })
27
27
 
28
28
  // Stash the sanitized config on plugin options so `getPluginConfig()` reads it.
29
29
  const registered = plugins['@payloadcms/plugin-mcp']
@@ -17,10 +17,10 @@ import { getLogger } from '../utils/getLogger.js'
17
17
  import { toStandardSchema } from '../utils/toStandardSchema.js'
18
18
 
19
19
  /**
20
- * Transport-agnostic core: registers every authorized MCP item onto a fresh
21
- * `McpServer` and returns it. The caller is responsible for picking a transport
22
- * (`WebStandardStreamableHTTPServerTransport`, `StdioServerTransport`, …) and
23
- * calling `server.connect(transport)`.
20
+ * Serving-entry-agnostic core: registers every authorized MCP item onto a fresh
21
+ * `McpServer` and returns it. The HTTP and stdio entry point callers provide fresh
22
+ * instances from this builder while they own the transport and protocol-era
23
+ * decision.
24
24
  *
25
25
  * `req` is the request context handlers see. For HTTP it's the live
26
26
  * `PayloadRequest` derived from the incoming HTTP request; for stdio it's a
@@ -47,11 +47,21 @@ export const buildMcpServer = ({
47
47
  * Wrap a tool handler's response with the tool's `overrideResponse`, then
48
48
  * strip the internal `doc` field so it doesn't leak onto the wire.
49
49
  */
50
- const finalizeToolResponse = (
51
- response: MCPToolResponse,
52
- overrideResponse?: MCPResponseOverride,
53
- ): MCPToolResponse => {
54
- const overridden = overrideResponse?.(response, response.doc ?? {}, req) ?? response
50
+ const finalizeToolResponse = async ({
51
+ input,
52
+ overrideResponse,
53
+ response,
54
+ toolName,
55
+ }: {
56
+ input: unknown
57
+ overrideResponse?: MCPResponseOverride
58
+ response: MCPToolResponse
59
+ toolName: string
60
+ }): Promise<MCPToolResponse> => {
61
+ let overridden = overrideResponse?.(response, response.doc ?? {}, req) ?? response
62
+ for (const hook of pluginConfig.hooks?.afterToolCall ?? []) {
63
+ overridden = await hook({ input, req, response: overridden, toolName })
64
+ }
55
65
  const { doc: _doc, ...rest } = overridden
56
66
  return rest
57
67
  }
@@ -119,7 +129,12 @@ export const buildMcpServer = ({
119
129
  ? match.tool.handler({ ...handlerArgs, collectionSlug: slug })
120
130
  : match.tool.handler({ ...handlerArgs, globalSlug: slug }))
121
131
 
122
- return finalizeToolResponse(response, match.tool.overrideResponse)
132
+ return finalizeToolResponse({
133
+ input: toolInput,
134
+ overrideResponse: match.tool.overrideResponse,
135
+ response,
136
+ toolName: match.mcpName,
137
+ })
123
138
  }
124
139
 
125
140
  try {
@@ -203,16 +218,21 @@ export const buildMcpServer = ({
203
218
  description: tool.description,
204
219
  inputSchema: tool.input ? toStandardSchema(tool.input) : undefined,
205
220
  },
206
- async (input: unknown, ctx: ServerContext) =>
207
- finalizeToolResponse(
208
- await tool.handler({
209
- authorizedMCP,
210
- input: (input ?? {}) as Record<string, unknown>,
211
- req,
212
- serverContext: ctx,
213
- }),
214
- tool.overrideResponse,
215
- ),
221
+ async (input: unknown, ctx: ServerContext) => {
222
+ const toolInput = (input ?? {}) as Record<string, unknown>
223
+ const response = await tool.handler({
224
+ authorizedMCP,
225
+ input: toolInput,
226
+ req,
227
+ serverContext: ctx,
228
+ })
229
+ return finalizeToolResponse({
230
+ input: toolInput,
231
+ overrideResponse: tool.overrideResponse,
232
+ response,
233
+ toolName: item.mcpName,
234
+ })
235
+ },
216
236
  )
217
237
  logger.info(`✅ Tool: ${item.mcpName} Registered.`)
218
238
  break
@@ -3,7 +3,6 @@ import { z } from 'zod'
3
3
  import { defaultAccess } from '../../../defaultAccess.js'
4
4
  import { defineCollectionTool } from '../../../defineTool.js'
5
5
  import { getLogger } from '../../../utils/getLogger.js'
6
- import { localAPIDefaults } from '../../../utils/localAPIDefaults.js'
7
6
  import { whereSchema } from '../../../utils/whereSchema.js'
8
7
 
9
8
  const DEFAULT_DESCRIPTION =
@@ -42,8 +41,8 @@ export const countDocumentsTool = defineCollectionTool({
42
41
  try {
43
42
  const result = await payload.count({
44
43
  collection: collectionSlug,
44
+ overrideAccess: authorizedMCP.overrideAccess,
45
45
  req,
46
- ...localAPIDefaults(authorizedMCP),
47
46
  ...(locale ? { locale } : {}),
48
47
  ...(trash !== undefined ? { trash } : {}),
49
48
  ...(where ? { where } : {}),
@@ -3,7 +3,6 @@ import { z } from 'zod'
3
3
  import { defaultAccess } from '../../../defaultAccess.js'
4
4
  import { defineCollectionTool } from '../../../defineTool.js'
5
5
  import { getLogger } from '../../../utils/getLogger.js'
6
- import { localAPIDefaults } from '../../../utils/localAPIDefaults.js'
7
6
  import { whereSchema } from '../../../utils/whereSchema.js'
8
7
 
9
8
  const DEFAULT_DESCRIPTION =
@@ -39,8 +38,8 @@ export const countVersionsTool = defineCollectionTool({
39
38
  try {
40
39
  const result = await payload.countVersions({
41
40
  collection: collectionSlug,
41
+ overrideAccess: authorizedMCP.overrideAccess,
42
42
  req,
43
- ...localAPIDefaults(authorizedMCP),
44
43
  ...(locale ? { locale } : {}),
45
44
  ...(where ? { where } : {}),
46
45
  })
@@ -9,15 +9,15 @@ import {
9
9
  getCollectionVirtualFieldNames,
10
10
  stripVirtualFields,
11
11
  } from '../../../utils/getVirtualFieldNames.js'
12
- import { localAPIDefaults } from '../../../utils/localAPIDefaults.js'
13
12
  import { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'
14
13
  import { validateCollectionData } from '../validateEntityData.js'
14
+ import { fileInputSchema, resolveFile } from './fileInput.js'
15
15
  import { formatCollectionError } from './formatCollectionError.js'
16
16
 
17
17
  const DEFAULT_DESCRIPTION =
18
- 'Create a document in any collection by passing the collection slug and data.'
18
+ 'Create 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.'
19
19
 
20
- export const createDocumentTool = defineCollectionTool({
20
+ export const createDocumentsTool = defineCollectionTool({
21
21
  access: (args) =>
22
22
  defaultAccess(args) && Boolean(args.permissions?.collections?.[args.collectionSlug]?.create),
23
23
  annotations: {
@@ -25,11 +25,10 @@ export const createDocumentTool = defineCollectionTool({
25
25
  idempotentHint: false,
26
26
  openWorldHint: false,
27
27
  readOnlyHint: false,
28
- title: 'Create Document',
28
+ title: 'Create Documents',
29
29
  },
30
30
  description: DEFAULT_DESCRIPTION,
31
31
  input: z.object({
32
- data: z.record(z.string(), z.unknown()).describe('The document fields to create'),
33
32
  depth: z
34
33
  .number()
35
34
  .int()
@@ -38,9 +37,24 @@ export const createDocumentTool = defineCollectionTool({
38
37
  .describe('How many levels deep to populate relationships in response')
39
38
  .optional()
40
39
  .default(0),
40
+ documents: z
41
+ .array(
42
+ z.object({
43
+ data: z
44
+ .record(z.string(), z.unknown())
45
+ .describe(
46
+ 'The document fields to create. Only include fields permitted by the schema returned by getCollectionSchema.',
47
+ ),
48
+ file: fileInputSchema.optional(),
49
+ }),
50
+ )
51
+ .min(1)
52
+ .describe('The documents to create, in order'),
41
53
  draft: z
42
54
  .boolean()
43
- .describe('Whether to create the document as a draft')
55
+ .describe(
56
+ 'Only if getCollectionSchema includes _status; otherwise _status does not exist. true forces data._status to "draft"; with false, data._status controls draft or published.',
57
+ )
44
58
  .optional()
45
59
  .default(false),
46
60
  fallbackLocale: z
@@ -50,7 +64,7 @@ export const createDocumentTool = defineCollectionTool({
50
64
  locale: z
51
65
  .string()
52
66
  .describe(
53
- 'Optional: locale code to create the document in (e.g., "en", "es"). Defaults to the default locale',
67
+ 'Optional: locale code to create the documents in (e.g., "en", "es"). Defaults to the default locale',
54
68
  )
55
69
  .optional(),
56
70
  select: z
@@ -63,50 +77,92 @@ export const createDocumentTool = defineCollectionTool({
63
77
  }).handler(async ({ authorizedMCP, collectionSlug, input, req }) => {
64
78
  const payload = req.payload
65
79
  const logger = getLogger({ payload })
80
+ const { depth, documents, draft, fallbackLocale, locale, select } = input
66
81
 
67
- const { data, depth, draft, fallbackLocale, locale, select } = input
68
-
69
- logger.info(
70
- `Creating document in collection: ${collectionSlug}${locale ? ` with locale: ${locale}` : ''}`,
71
- )
82
+ logger.info(`Creating ${documents.length} documents in collection: ${collectionSlug}`)
72
83
 
73
84
  try {
74
85
  const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, collectionSlug)
75
- const inputData = stripVirtualFields(data, virtualFieldNames)
76
- const validationError = validateCollectionData({ collectionSlug, data: inputData, req })
86
+ const docs: Array<{ doc: Record<string, unknown>; index: number }> = []
87
+ const errors: Array<{ index: number; message: string }> = []
88
+ let validationSchema: Record<string, unknown> | undefined
77
89
 
78
- if (validationError) {
79
- return validationError
80
- }
90
+ for (const [index, document] of documents.entries()) {
91
+ try {
92
+ const inputData = stripVirtualFields(document.data, virtualFieldNames)
93
+ const validationError = validateCollectionData({ collectionSlug, data: inputData, req })
94
+
95
+ if (validationError) {
96
+ const firstContent = validationError.content[0]
97
+ const validationContent = validationError.structuredContent as
98
+ | Record<string, unknown>
99
+ | undefined
100
+ const schema = validationContent?.schema
81
101
 
82
- const parsedData = transformPointDataToPayload(inputData)
102
+ if (!validationSchema && schema && typeof schema === 'object') {
103
+ validationSchema = schema as Record<string, unknown>
104
+ }
83
105
 
84
- const result = await payload.create({
85
- collection: collectionSlug,
86
- data: parsedData,
87
- depth,
88
- draft,
89
- req,
90
- ...localAPIDefaults(authorizedMCP),
91
- ...(locale ? { locale } : {}),
92
- ...(fallbackLocale ? { fallbackLocale } : {}),
93
- ...(select ? { select: select as SelectType } : {}),
94
- })
106
+ errors.push({
107
+ index,
108
+ message:
109
+ firstContent?.type === 'text'
110
+ ? (firstContent.text.split('\n\nUse this schema')[0] ?? 'Invalid document data')
111
+ : 'Invalid document data',
112
+ })
113
+ continue
114
+ }
95
115
 
96
- logger.info(`Successfully created document in ${collectionSlug} with ID: ${result.id}`)
116
+ const parsedData = transformPointDataToPayload(inputData)
117
+ const file = await resolveFile({ collectionSlug, input: document.file, req })
118
+ const result = await payload.create({
119
+ collection: collectionSlug,
120
+ data: parsedData,
121
+ depth,
122
+ draft,
123
+ overrideAccess: authorizedMCP.overrideAccess,
124
+ req,
125
+ ...(file ? { file } : {}),
126
+ ...(locale ? { locale } : {}),
127
+ ...(fallbackLocale ? { fallbackLocale } : {}),
128
+ ...(select ? { select: select as SelectType } : {}),
129
+ })
130
+
131
+ docs.push({ doc: result as Record<string, unknown>, index })
132
+ } catch (error) {
133
+ const message = error instanceof Error ? error.message : 'Unknown error'
134
+
135
+ logger.error(`Error creating document at index ${index} in ${collectionSlug}: ${message}`)
136
+ errors.push({ index, message })
137
+ }
138
+ }
139
+
140
+ const batchResult = { docs, errors }
141
+ const retryMessage = errors.length > 0 ? '\nRetry failed indexes only.' : ''
142
+ const schemaMessage = validationSchema
143
+ ? `\n\nUse this schema for data:\n\`\`\`json\n${JSON.stringify(validationSchema)}\n\`\`\``
144
+ : ''
145
+ const structuredContent = validationSchema
146
+ ? { ...batchResult, schema: validationSchema }
147
+ : batchResult
148
+
149
+ logger.info(`Created ${docs.length} of ${documents.length} documents in ${collectionSlug}`)
97
150
 
98
151
  return {
99
152
  content: [
100
153
  {
101
154
  type: 'text',
102
- text: `Document created successfully in collection "${collectionSlug}"!\nCreated document:\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``,
155
+ text: `Created ${docs.length} of ${documents.length} documents in collection "${collectionSlug}".${retryMessage}\nResults:\n\`\`\`json\n${JSON.stringify(batchResult)}\n\`\`\`${schemaMessage}`,
103
156
  },
104
157
  ],
105
- doc: result as Record<string, unknown>,
158
+ doc: structuredContent as unknown as Record<string, unknown>,
159
+ isError: docs.length === 0 && errors.length > 0,
160
+ structuredContent,
106
161
  }
107
162
  } catch (error) {
108
- const errorMessage = error instanceof Error ? error.message : 'Unknown error'
109
- logger.error(`Error creating document in ${collectionSlug}: ${errorMessage}`)
163
+ const message = error instanceof Error ? error.message : 'Unknown error'
164
+
165
+ logger.error(`Error creating documents in ${collectionSlug}: ${message}`)
110
166
  return formatCollectionError({ action: 'creating', collectionSlug, error, req })
111
167
  }
112
168
  })
@@ -3,7 +3,6 @@ import { z } from 'zod'
3
3
  import { defaultAccess } from '../../../defaultAccess.js'
4
4
  import { defineCollectionTool } from '../../../defineTool.js'
5
5
  import { getLogger } from '../../../utils/getLogger.js'
6
- import { localAPIDefaults } from '../../../utils/localAPIDefaults.js'
7
6
  import { whereSchema } from '../../../utils/whereSchema.js'
8
7
 
9
8
  const DEFAULT_DESCRIPTION =
@@ -69,8 +68,8 @@ export const deleteDocumentsTool = defineCollectionTool({
69
68
  const deleteOptions: Record<string, unknown> = {
70
69
  collection: collectionSlug,
71
70
  depth,
71
+ overrideAccess: authorizedMCP.overrideAccess,
72
72
  req,
73
- ...localAPIDefaults(authorizedMCP),
74
73
  ...(locale && { locale }),
75
74
  ...(fallbackLocale && { fallbackLocale }),
76
75
  }
@@ -9,7 +9,6 @@ import {
9
9
  getCollectionVirtualFieldNames,
10
10
  stripVirtualFields,
11
11
  } from '../../../utils/getVirtualFieldNames.js'
12
- import { localAPIDefaults } from '../../../utils/localAPIDefaults.js'
13
12
  import { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'
14
13
  import { formatCollectionError } from './formatCollectionError.js'
15
14
 
@@ -105,8 +104,8 @@ export const duplicateDocumentTool = defineCollectionTool({
105
104
  collection: collectionSlug,
106
105
  depth,
107
106
  draft,
107
+ overrideAccess: authorizedMCP.overrideAccess,
108
108
  req,
109
- ...localAPIDefaults(authorizedMCP),
110
109
  ...(parsedData ? { data: parsedData } : {}),
111
110
  ...(locale ? { locale } : {}),
112
111
  ...(fallbackLocale ? { fallbackLocale } : {}),
@@ -0,0 +1,93 @@
1
+ import type { PayloadRequest } from 'payload'
2
+
3
+ import { describe, expect, it } from 'vitest'
4
+
5
+ import { fileInputSchema, resolveFile } from './fileInput.js'
6
+
7
+ describe('MCP file input', () => {
8
+ it('should reject malformed MIME types', () => {
9
+ const result = fileInputSchema.safeParse({
10
+ data: 'aGVsbG8=',
11
+ mimeType: 'text/plain\r\nx-test: value',
12
+ name: 'hello.txt',
13
+ source: 'base64',
14
+ })
15
+
16
+ expect(result.success).toBe(false)
17
+ })
18
+
19
+ it('should accept a prepared upload', () => {
20
+ const result = fileInputSchema.safeParse({
21
+ file: {
22
+ filename: 'image.png',
23
+ mimeType: 'image/png',
24
+ size: 123,
25
+ uploadReference: { uploadId: 'upload-id' },
26
+ },
27
+ source: 'uploadReference',
28
+ })
29
+
30
+ expect(result.success).toBe(true)
31
+ })
32
+
33
+ it('should reject oversized base64 files', async () => {
34
+ const req = createRequest({ maxFileSize: 4 })
35
+
36
+ await expect(
37
+ resolveFile({
38
+ collectionSlug: 'media',
39
+ input: {
40
+ data: Buffer.from('hello').toString('base64'),
41
+ mimeType: 'text/plain',
42
+ name: 'hello.txt',
43
+ source: 'base64',
44
+ },
45
+ req,
46
+ }),
47
+ ).rejects.toThrow('File exceeds the 4 byte upload limit.')
48
+ })
49
+
50
+ it('should reject URLs outside the collection allowlist', async () => {
51
+ const req = createRequest({
52
+ allowList: [{ hostname: 'assets.example.com', protocol: 'https' }],
53
+ })
54
+
55
+ await expect(
56
+ resolveFile({
57
+ collectionSlug: 'media',
58
+ input: {
59
+ source: 'externalURL',
60
+ url: 'https://example.com/image.png',
61
+ },
62
+ req,
63
+ }),
64
+ ).rejects.toThrow('The provided file URL is not allowed.')
65
+ })
66
+ })
67
+
68
+ function createRequest({
69
+ allowList,
70
+ maxFileSize,
71
+ }: {
72
+ allowList?: Array<{ hostname: string; protocol: 'http' | 'https' }>
73
+ maxFileSize?: number
74
+ }): PayloadRequest {
75
+ return {
76
+ payload: {
77
+ collections: {
78
+ media: {
79
+ config: {
80
+ upload: allowList ? { pasteURL: { allowList } } : {},
81
+ },
82
+ },
83
+ },
84
+ config: {
85
+ upload: {
86
+ limits: {
87
+ fileSize: maxFileSize,
88
+ },
89
+ },
90
+ },
91
+ },
92
+ } as unknown as PayloadRequest
93
+ }
@@ -0,0 +1,164 @@
1
+ import type { CollectionSlug, File, FileData, PayloadRequest } from 'payload'
2
+
3
+ import { APIError } from 'payload'
4
+ import { getExternalFile, getFileFromUploadInstructions, isURLAllowed } from 'payload/internal'
5
+ import { sanitizeFilename } from 'payload/shared'
6
+ import { z } from 'zod'
7
+
8
+ const mimeTypeSchema = z
9
+ .string()
10
+ .regex(/^[!#$%&'*+.^`|~\w-]+\/[!#$%&'*+.^`|~\w-]+$/, 'MIME type must use the type/subtype format')
11
+
12
+ const uploadFileSchema = z.object({
13
+ filename: z.string(),
14
+ mimeType: z.string(),
15
+ size: z.number().int().nonnegative(),
16
+ uploadReference: z.record(z.string(), z.unknown()),
17
+ })
18
+
19
+ export const fileInputSchema = z
20
+ .discriminatedUnion('source', [
21
+ z.object({
22
+ name: z.string().min(1).describe('The file name, including its extension'),
23
+ data: z.string().describe('The base64-encoded file bytes, without a data URL prefix'),
24
+ mimeType: mimeTypeSchema.describe('The file MIME type, for example image/png'),
25
+ source: z.literal('base64'),
26
+ }),
27
+ z.object({
28
+ name: z.string().min(1).describe('Optional file name override').optional(),
29
+ source: z.literal('externalURL'),
30
+ url: z.url().describe('The http or https URL to download'),
31
+ }),
32
+ z.object({
33
+ file: uploadFileSchema.describe('getUploadInstructions file field post-upload'),
34
+ source: z.literal('uploadReference'),
35
+ }),
36
+ ])
37
+ .describe(
38
+ '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.',
39
+ )
40
+
41
+ type FileInput = z.infer<typeof fileInputSchema>
42
+
43
+ export async function resolveFile({
44
+ collectionSlug,
45
+ input,
46
+ req,
47
+ }: {
48
+ collectionSlug: CollectionSlug
49
+ input?: FileInput
50
+ req: PayloadRequest
51
+ }): Promise<File | undefined> {
52
+ if (!input) {
53
+ return undefined
54
+ }
55
+
56
+ if (input.source === 'uploadReference') {
57
+ try {
58
+ return await getFileFromUploadInstructions({ collectionSlug, file: input.file, req })
59
+ } catch (error) {
60
+ if (error instanceof Error && error.message === 'Staged upload was not found.') {
61
+ throw new APIError(
62
+ 'Staged upload not found. Complete the upload action first, or use base64 for small local files.',
63
+ 400,
64
+ )
65
+ }
66
+ throw error
67
+ }
68
+ }
69
+
70
+ const uploadConfig = req.payload.collections[collectionSlug]?.config.upload
71
+
72
+ if (!uploadConfig) {
73
+ throw new APIError(`Collection "${collectionSlug}" does not support file uploads.`, 400)
74
+ }
75
+
76
+ const maxFileSize = req.payload.config.upload.limits?.fileSize
77
+ let file: File
78
+
79
+ if (input.source === 'base64') {
80
+ const data = decodeBase64({ maxFileSize, value: input.data })
81
+
82
+ file = {
83
+ name: sanitizeFilename(input.name),
84
+ data,
85
+ mimetype: input.mimeType,
86
+ size: data.length,
87
+ }
88
+ } else {
89
+ if (uploadConfig.pasteURL === false) {
90
+ throw new APIError(
91
+ `Uploading files from URLs is disabled for collection "${collectionSlug}".`,
92
+ 400,
93
+ )
94
+ }
95
+
96
+ const url = new URL(input.url)
97
+
98
+ if (!['http:', 'https:'].includes(url.protocol)) {
99
+ throw new APIError('File URLs must use http or https.', 400)
100
+ }
101
+
102
+ if (
103
+ typeof uploadConfig.pasteURL === 'object' &&
104
+ !isURLAllowed(input.url, uploadConfig.pasteURL.allowList)
105
+ ) {
106
+ throw new APIError('The provided file URL is not allowed.', 400)
107
+ }
108
+
109
+ file = await getExternalFile({
110
+ data: {
111
+ filename: sanitizeFilename(input.name || getURLFilename(url)),
112
+ url: input.url,
113
+ } as FileData,
114
+ req,
115
+ uploadConfig: {
116
+ ...uploadConfig,
117
+ externalFileHeaderFilter: uploadConfig.externalFileHeaderFilter ?? (() => ({})),
118
+ },
119
+ })
120
+ file.mimetype = file.mimetype?.split(';')[0] || 'application/octet-stream'
121
+ file.size = file.data.length
122
+ }
123
+
124
+ if (maxFileSize !== undefined && Number.isFinite(maxFileSize) && file.size > maxFileSize) {
125
+ throw new APIError(`File exceeds the ${maxFileSize} byte upload limit.`, 400)
126
+ }
127
+
128
+ return file
129
+ }
130
+
131
+ function decodeBase64({ maxFileSize, value }: { maxFileSize?: number; value: string }): Buffer {
132
+ const normalized = value.replace(/\s/g, '')
133
+
134
+ if (!/^[a-z0-9+/]*={0,2}$/i.test(normalized) || normalized.length % 4 === 1) {
135
+ throw new APIError('File data must be valid base64.', 400)
136
+ }
137
+
138
+ if (maxFileSize !== undefined && Number.isFinite(maxFileSize)) {
139
+ const paddingLength = normalized.endsWith('==') ? 2 : normalized.endsWith('=') ? 1 : 0
140
+ const decodedSize = Math.floor((normalized.length * 3) / 4) - paddingLength
141
+
142
+ if (decodedSize > maxFileSize) {
143
+ throw new APIError(`File exceeds the ${maxFileSize} byte upload limit.`, 400)
144
+ }
145
+ }
146
+
147
+ const data = Buffer.from(normalized, 'base64')
148
+
149
+ if (data.toString('base64').replace(/=+$/, '') !== normalized.replace(/=+$/, '')) {
150
+ throw new APIError('File data must be valid base64.', 400)
151
+ }
152
+
153
+ return data
154
+ }
155
+
156
+ function getURLFilename(url: URL): string {
157
+ const pathSegment = url.pathname.split('/').pop() || 'upload'
158
+
159
+ try {
160
+ return decodeURIComponent(pathSegment)
161
+ } catch {
162
+ return pathSegment
163
+ }
164
+ }
@@ -5,7 +5,6 @@ import { z } from 'zod'
5
5
  import { defaultAccess } from '../../../defaultAccess.js'
6
6
  import { defineCollectionTool } from '../../../defineTool.js'
7
7
  import { getLogger } from '../../../utils/getLogger.js'
8
- import { localAPIDefaults } from '../../../utils/localAPIDefaults.js'
9
8
  import { whereSchema } from '../../../utils/whereSchema.js'
10
9
 
11
10
  const DEFAULT_DESCRIPTION =
@@ -83,8 +82,8 @@ export const findDistinctTool = defineCollectionTool({
83
82
  collection: collectionSlug,
84
83
  depth,
85
84
  field,
85
+ overrideAccess: authorizedMCP.overrideAccess,
86
86
  req,
87
- ...localAPIDefaults(authorizedMCP),
88
87
  ...(limit ? { limit } : {}),
89
88
  ...(locale ? { locale } : {}),
90
89
  ...(page ? { page } : {}),