@payloadcms/plugin-mcp 4.0.0-internal.40de3ec → 4.0.0-internal.41055b1

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 (247) hide show
  1. package/LICENSE.md +1 -1
  2. package/bin.js +15 -6
  3. package/dist/bin/index.d.ts +2 -0
  4. package/dist/bin/index.d.ts.map +1 -0
  5. package/dist/bin/index.js +12 -0
  6. package/dist/bin/index.js.map +1 -0
  7. package/dist/bin/initializeViteHMR.d.ts +8 -0
  8. package/dist/bin/initializeViteHMR.d.ts.map +1 -0
  9. package/dist/bin/initializeViteHMR.js +75 -0
  10. package/dist/bin/initializeViteHMR.js.map +1 -0
  11. package/dist/bin/viteConfigBoundary.d.ts +6 -0
  12. package/dist/bin/viteConfigBoundary.d.ts.map +1 -0
  13. package/dist/bin/viteConfigBoundary.js +25 -0
  14. package/dist/bin/viteConfigBoundary.js.map +1 -0
  15. package/dist/defaultAccess.d.ts +3 -0
  16. package/dist/defaultAccess.d.ts.map +1 -0
  17. package/dist/defaultAccess.js +3 -0
  18. package/dist/defaultAccess.js.map +1 -0
  19. package/dist/endpoint/access.d.ts +12 -5
  20. package/dist/endpoint/access.d.ts.map +1 -1
  21. package/dist/endpoint/access.js +75 -88
  22. package/dist/endpoint/access.js.map +1 -1
  23. package/dist/endpoint/index.d.ts +1 -1
  24. package/dist/endpoint/index.d.ts.map +1 -1
  25. package/dist/endpoint/index.js +68 -17
  26. package/dist/endpoint/index.js.map +1 -1
  27. package/dist/exports/client.d.ts +1 -1
  28. package/dist/exports/client.d.ts.map +1 -1
  29. package/dist/exports/client.js +1 -1
  30. package/dist/exports/client.js.map +1 -1
  31. package/dist/exports/internal.d.ts +2 -0
  32. package/dist/exports/internal.d.ts.map +1 -0
  33. package/dist/exports/internal.js +3 -0
  34. package/dist/exports/internal.js.map +1 -0
  35. package/dist/index.d.ts +2 -2
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +15 -20
  38. package/dist/index.js.map +1 -1
  39. package/dist/mcp/buildMcpServer.d.ts +4 -4
  40. package/dist/mcp/buildMcpServer.d.ts.map +1 -1
  41. package/dist/mcp/buildMcpServer.js +133 -80
  42. package/dist/mcp/buildMcpServer.js.map +1 -1
  43. package/dist/mcp/builtin/collections/authTools.d.ts.map +1 -1
  44. package/dist/mcp/builtin/collections/authTools.js +44 -6
  45. package/dist/mcp/builtin/collections/authTools.js.map +1 -1
  46. package/dist/mcp/builtin/collections/countTool.d.ts +2 -0
  47. package/dist/mcp/builtin/collections/countTool.d.ts.map +1 -0
  48. package/dist/mcp/builtin/collections/countTool.js +68 -0
  49. package/dist/mcp/builtin/collections/countTool.js.map +1 -0
  50. package/dist/mcp/builtin/collections/countVersionsTool.d.ts +2 -0
  51. package/dist/mcp/builtin/collections/countVersionsTool.d.ts.map +1 -0
  52. package/dist/mcp/builtin/collections/countVersionsTool.js +64 -0
  53. package/dist/mcp/builtin/collections/countVersionsTool.js.map +1 -0
  54. package/dist/mcp/builtin/collections/createTool.d.ts +1 -1
  55. package/dist/mcp/builtin/collections/createTool.d.ts.map +1 -1
  56. package/dist/mcp/builtin/collections/createTool.js +39 -44
  57. package/dist/mcp/builtin/collections/createTool.js.map +1 -1
  58. package/dist/mcp/builtin/collections/deleteTool.d.ts +1 -1
  59. package/dist/mcp/builtin/collections/deleteTool.d.ts.map +1 -1
  60. package/dist/mcp/builtin/collections/deleteTool.js +15 -22
  61. package/dist/mcp/builtin/collections/deleteTool.js.map +1 -1
  62. package/dist/mcp/builtin/collections/duplicateTool.d.ts +2 -0
  63. package/dist/mcp/builtin/collections/duplicateTool.d.ts.map +1 -0
  64. package/dist/mcp/builtin/collections/duplicateTool.js +96 -0
  65. package/dist/mcp/builtin/collections/duplicateTool.js.map +1 -0
  66. package/dist/mcp/builtin/collections/findDistinctTool.d.ts +2 -0
  67. package/dist/mcp/builtin/collections/findDistinctTool.d.ts.map +1 -0
  68. package/dist/mcp/builtin/collections/findDistinctTool.js +92 -0
  69. package/dist/mcp/builtin/collections/findDistinctTool.js.map +1 -0
  70. package/dist/mcp/builtin/collections/findTool.d.ts +1 -1
  71. package/dist/mcp/builtin/collections/findTool.d.ts.map +1 -1
  72. package/dist/mcp/builtin/collections/findTool.js +52 -47
  73. package/dist/mcp/builtin/collections/findTool.js.map +1 -1
  74. package/dist/mcp/builtin/collections/findVersionByIDTool.d.ts +2 -0
  75. package/dist/mcp/builtin/collections/findVersionByIDTool.d.ts.map +1 -0
  76. package/dist/mcp/builtin/collections/findVersionByIDTool.js +83 -0
  77. package/dist/mcp/builtin/collections/findVersionByIDTool.js.map +1 -0
  78. package/dist/mcp/builtin/collections/findVersionsTool.d.ts +2 -0
  79. package/dist/mcp/builtin/collections/findVersionsTool.d.ts.map +1 -0
  80. package/dist/mcp/builtin/collections/findVersionsTool.js +98 -0
  81. package/dist/mcp/builtin/collections/findVersionsTool.js.map +1 -0
  82. package/dist/mcp/builtin/collections/formatCollectionError.d.ts +9 -0
  83. package/dist/mcp/builtin/collections/formatCollectionError.d.ts.map +1 -0
  84. package/dist/mcp/builtin/collections/formatCollectionError.js +60 -0
  85. package/dist/mcp/builtin/collections/formatCollectionError.js.map +1 -0
  86. package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts +2 -0
  87. package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -0
  88. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +65 -0
  89. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -0
  90. package/dist/mcp/builtin/collections/restoreVersionTool.d.ts +2 -0
  91. package/dist/mcp/builtin/collections/restoreVersionTool.d.ts.map +1 -0
  92. package/dist/mcp/builtin/collections/restoreVersionTool.js +81 -0
  93. package/dist/mcp/builtin/collections/restoreVersionTool.js.map +1 -0
  94. package/dist/mcp/builtin/collections/updateTool.d.ts +1 -1
  95. package/dist/mcp/builtin/collections/updateTool.d.ts.map +1 -1
  96. package/dist/mcp/builtin/collections/updateTool.js +96 -89
  97. package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
  98. package/dist/mcp/builtin/getConfigInfoTool.d.ts +2 -0
  99. package/dist/mcp/builtin/getConfigInfoTool.d.ts.map +1 -0
  100. package/dist/mcp/builtin/getConfigInfoTool.js +68 -0
  101. package/dist/mcp/builtin/getConfigInfoTool.js.map +1 -0
  102. package/dist/mcp/builtin/globals/countVersionsTool.d.ts +2 -0
  103. package/dist/mcp/builtin/globals/countVersionsTool.d.ts.map +1 -0
  104. package/dist/mcp/builtin/globals/countVersionsTool.js +64 -0
  105. package/dist/mcp/builtin/globals/countVersionsTool.js.map +1 -0
  106. package/dist/mcp/builtin/globals/findTool.d.ts.map +1 -1
  107. package/dist/mcp/builtin/globals/findTool.js +20 -23
  108. package/dist/mcp/builtin/globals/findTool.js.map +1 -1
  109. package/dist/mcp/builtin/globals/findVersionByIDTool.d.ts +2 -0
  110. package/dist/mcp/builtin/globals/findVersionByIDTool.d.ts.map +1 -0
  111. package/dist/mcp/builtin/globals/findVersionByIDTool.js +79 -0
  112. package/dist/mcp/builtin/globals/findVersionByIDTool.js.map +1 -0
  113. package/dist/mcp/builtin/globals/findVersionsTool.d.ts +2 -0
  114. package/dist/mcp/builtin/globals/findVersionsTool.d.ts.map +1 -0
  115. package/dist/mcp/builtin/globals/findVersionsTool.js +94 -0
  116. package/dist/mcp/builtin/globals/findVersionsTool.js.map +1 -0
  117. package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts +2 -0
  118. package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts.map +1 -0
  119. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js +65 -0
  120. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js.map +1 -0
  121. package/dist/mcp/builtin/globals/restoreVersionTool.d.ts +2 -0
  122. package/dist/mcp/builtin/globals/restoreVersionTool.d.ts.map +1 -0
  123. package/dist/mcp/builtin/globals/restoreVersionTool.js +77 -0
  124. package/dist/mcp/builtin/globals/restoreVersionTool.js.map +1 -0
  125. package/dist/mcp/builtin/globals/updateTool.d.ts.map +1 -1
  126. package/dist/mcp/builtin/globals/updateTool.js +33 -42
  127. package/dist/mcp/builtin/globals/updateTool.js.map +1 -1
  128. package/dist/mcp/builtin/validateEntityData.d.ts +14 -0
  129. package/dist/mcp/builtin/validateEntityData.d.ts.map +1 -0
  130. package/dist/mcp/builtin/validateEntityData.js +82 -0
  131. package/dist/mcp/builtin/validateEntityData.js.map +1 -0
  132. package/dist/mcp/builtinTools.d.ts +144 -19
  133. package/dist/mcp/builtinTools.d.ts.map +1 -1
  134. package/dist/mcp/builtinTools.js +119 -20
  135. package/dist/mcp/builtinTools.js.map +1 -1
  136. package/dist/mcp/sanitizeMCPConfig.d.ts +0 -1
  137. package/dist/mcp/sanitizeMCPConfig.d.ts.map +1 -1
  138. package/dist/mcp/sanitizeMCPConfig.js +121 -58
  139. package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
  140. package/dist/stdio.d.ts +5 -4
  141. package/dist/stdio.d.ts.map +1 -1
  142. package/dist/stdio.js +88 -49
  143. package/dist/stdio.js.map +1 -1
  144. package/dist/types.d.ts +112 -110
  145. package/dist/types.d.ts.map +1 -1
  146. package/dist/types.js +2 -4
  147. package/dist/types.js.map +1 -1
  148. package/dist/utils/getPluginConfig.d.ts +1 -1
  149. package/dist/utils/getPluginConfig.js +1 -1
  150. package/dist/utils/getPluginConfig.js.map +1 -1
  151. package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts +28 -0
  152. package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts.map +1 -0
  153. package/dist/utils/schemaConversion/filterFieldsByAccess.js +71 -0
  154. package/dist/utils/schemaConversion/filterFieldsByAccess.js.map +1 -0
  155. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts +13 -0
  156. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts.map +1 -0
  157. package/dist/utils/schemaConversion/getEntityInputSchema.js +66 -0
  158. package/dist/utils/schemaConversion/getEntityInputSchema.js.map +1 -0
  159. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts +5 -10
  160. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts.map +1 -1
  161. package/dist/utils/schemaConversion/sanitizeEntitySchema.js +15 -95
  162. package/dist/utils/schemaConversion/sanitizeEntitySchema.js.map +1 -1
  163. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js +15 -40
  164. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js.map +1 -1
  165. package/dist/utils/whereSchema.d.ts +9 -0
  166. package/dist/utils/whereSchema.d.ts.map +1 -0
  167. package/dist/utils/whereSchema.js +13 -0
  168. package/dist/utils/whereSchema.js.map +1 -0
  169. package/package.json +25 -17
  170. package/src/bin/index.ts +16 -0
  171. package/src/bin/initializeViteHMR.ts +76 -0
  172. package/src/bin/viteConfigBoundary.ts +39 -0
  173. package/src/defaultAccess.ts +3 -0
  174. package/src/endpoint/access.ts +81 -101
  175. package/src/endpoint/index.ts +58 -16
  176. package/src/exports/client.ts +2 -1
  177. package/src/exports/internal.ts +1 -0
  178. package/src/index.ts +12 -20
  179. package/src/mcp/buildMcpServer.ts +170 -115
  180. package/src/mcp/builtin/collections/authTools.ts +45 -9
  181. package/src/mcp/builtin/collections/countTool.ts +73 -0
  182. package/src/mcp/builtin/collections/countVersionsTool.ts +69 -0
  183. package/src/mcp/builtin/collections/createTool.ts +62 -61
  184. package/src/mcp/builtin/collections/deleteTool.ts +20 -18
  185. package/src/mcp/builtin/collections/duplicateTool.ts +134 -0
  186. package/src/mcp/builtin/collections/findDistinctTool.ts +119 -0
  187. package/src/mcp/builtin/collections/findTool.ts +66 -37
  188. package/src/mcp/builtin/collections/findVersionByIDTool.ts +109 -0
  189. package/src/mcp/builtin/collections/findVersionsTool.ts +154 -0
  190. package/src/mcp/builtin/collections/formatCollectionError.ts +84 -0
  191. package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +63 -0
  192. package/src/mcp/builtin/collections/restoreVersionTool.ts +107 -0
  193. package/src/mcp/builtin/collections/updateTool.ts +127 -112
  194. package/src/mcp/builtin/getConfigInfoTool.ts +67 -0
  195. package/src/mcp/builtin/globals/countVersionsTool.ts +68 -0
  196. package/src/mcp/builtin/globals/findTool.ts +28 -19
  197. package/src/mcp/builtin/globals/findVersionByIDTool.ts +103 -0
  198. package/src/mcp/builtin/globals/findVersionsTool.ts +147 -0
  199. package/src/mcp/builtin/globals/getGlobalSchemaTool.ts +63 -0
  200. package/src/mcp/builtin/globals/restoreVersionTool.ts +99 -0
  201. package/src/mcp/builtin/globals/updateTool.ts +52 -57
  202. package/src/mcp/builtin/validateEntityData.ts +132 -0
  203. package/src/mcp/builtinTools.ts +111 -41
  204. package/src/mcp/sanitizeMCPConfig.ts +117 -78
  205. package/src/stdio.ts +82 -48
  206. package/src/types.ts +128 -115
  207. package/src/utils/getPluginConfig.ts +1 -1
  208. package/src/utils/schemaConversion/filterFieldsByAccess.ts +123 -0
  209. package/src/utils/schemaConversion/getEntityInputSchema.ts +96 -0
  210. package/src/utils/schemaConversion/sanitizeEntitySchema.spec.ts +12 -19
  211. package/src/utils/schemaConversion/sanitizeEntitySchema.ts +17 -114
  212. package/src/utils/whereSchema.ts +24 -0
  213. package/dist/@types/assets.d.js +0 -2
  214. package/dist/@types/assets.d.js.map +0 -1
  215. package/dist/collection/getAccessField.d.ts +0 -12
  216. package/dist/collection/getAccessField.d.ts.map +0 -1
  217. package/dist/collection/getAccessField.js +0 -57
  218. package/dist/collection/getAccessField.js.map +0 -1
  219. package/dist/collection/index.d.ts +0 -6
  220. package/dist/collection/index.d.ts.map +0 -1
  221. package/dist/collection/index.js +0 -60
  222. package/dist/collection/index.js.map +0 -1
  223. package/dist/components/AccessField/index.client.d.ts +0 -10
  224. package/dist/components/AccessField/index.client.d.ts.map +0 -1
  225. package/dist/components/AccessField/index.client.js +0 -305
  226. package/dist/components/AccessField/index.client.js.map +0 -1
  227. package/dist/components/AccessField/index.css +0 -93
  228. package/dist/utils/localAPIDefaults.d.ts +0 -20
  229. package/dist/utils/localAPIDefaults.d.ts.map +0 -1
  230. package/dist/utils/localAPIDefaults.js +0 -19
  231. package/dist/utils/localAPIDefaults.js.map +0 -1
  232. package/dist/utils/schemaConversion/buildToolInput.d.ts +0 -29
  233. package/dist/utils/schemaConversion/buildToolInput.d.ts.map +0 -1
  234. package/dist/utils/schemaConversion/buildToolInput.js +0 -51
  235. package/dist/utils/schemaConversion/buildToolInput.js.map +0 -1
  236. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.d.ts +0 -7
  237. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.d.ts.map +0 -1
  238. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.js +0 -20
  239. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.js.map +0 -1
  240. package/src/@types/assets.d.ts +0 -3
  241. package/src/collection/getAccessField.ts +0 -64
  242. package/src/collection/index.ts +0 -64
  243. package/src/components/AccessField/index.client.tsx +0 -344
  244. package/src/components/AccessField/index.css +0 -93
  245. package/src/utils/localAPIDefaults.ts +0 -22
  246. package/src/utils/schemaConversion/buildToolInput.ts +0 -68
  247. package/src/utils/schemaConversion/removeVirtualFieldsFromSchema.ts +0 -27
@@ -22,9 +22,16 @@ const wrapError = (name)=>({ collectionSlug, message })=>{
22
22
  };
23
23
  };
24
24
  export const authCollectionTool = defineCollectionTool({
25
+ annotations: {
26
+ destructiveHint: false,
27
+ idempotentHint: true,
28
+ openWorldHint: false,
29
+ readOnlyHint: true,
30
+ title: 'Check Auth Status'
31
+ },
25
32
  description: 'Checks authentication status for the current user.',
26
33
  input: z.object({
27
- headers: z.string().describe('Optional JSON string containing custom headers to send with the authentication request').optional()
34
+ headers: z.record(z.string(), z.string()).describe('Optional custom headers to send with the authentication request').optional()
28
35
  })
29
36
  }).handler(async ({ collectionSlug, input, req })=>{
30
37
  const logger = getLogger({
@@ -33,11 +40,7 @@ export const authCollectionTool = defineCollectionTool({
33
40
  try {
34
41
  let authHeaders = new Headers();
35
42
  if (input.headers) {
36
- try {
37
- authHeaders = new Headers(JSON.parse(input.headers));
38
- } catch {
39
- logger.warn(`Invalid headers JSON for auth: ${input.headers}, using empty headers`);
40
- }
43
+ authHeaders = new Headers(input.headers);
41
44
  }
42
45
  const result = await req.payload.auth({
43
46
  headers: authHeaders
@@ -61,6 +64,13 @@ export const authCollectionTool = defineCollectionTool({
61
64
  }
62
65
  });
63
66
  export const forgotPasswordCollectionTool = defineCollectionTool({
67
+ annotations: {
68
+ destructiveHint: false,
69
+ idempotentHint: false,
70
+ openWorldHint: true,
71
+ readOnlyHint: false,
72
+ title: 'Forgot Password'
73
+ },
64
74
  description: 'Sends a password reset email to a user.',
65
75
  input: z.object({
66
76
  disableEmail: z.boolean().describe('Whether to disable sending the email (for testing)').optional().default(false),
@@ -99,6 +109,13 @@ export const forgotPasswordCollectionTool = defineCollectionTool({
99
109
  }
100
110
  });
101
111
  export const loginCollectionTool = defineCollectionTool({
112
+ annotations: {
113
+ destructiveHint: false,
114
+ idempotentHint: false,
115
+ openWorldHint: false,
116
+ readOnlyHint: false,
117
+ title: 'User Login'
118
+ },
102
119
  description: 'Authenticates a user with email and password.',
103
120
  input: z.object({
104
121
  depth: z.number().int().min(0).max(10).describe('Depth of population for relationships').optional().default(0),
@@ -139,6 +156,13 @@ export const loginCollectionTool = defineCollectionTool({
139
156
  }
140
157
  });
141
158
  export const resetPasswordCollectionTool = defineCollectionTool({
159
+ annotations: {
160
+ destructiveHint: false,
161
+ idempotentHint: false,
162
+ openWorldHint: false,
163
+ readOnlyHint: false,
164
+ title: 'Reset Password'
165
+ },
142
166
  description: 'Resets a user password with a reset token.',
143
167
  input: z.object({
144
168
  password: z.string().describe('The new password for the user'),
@@ -176,6 +200,13 @@ export const resetPasswordCollectionTool = defineCollectionTool({
176
200
  }
177
201
  });
178
202
  export const unlockCollectionTool = defineCollectionTool({
203
+ annotations: {
204
+ destructiveHint: false,
205
+ idempotentHint: true,
206
+ openWorldHint: false,
207
+ readOnlyHint: false,
208
+ title: 'Unlock Account'
209
+ },
179
210
  description: 'Unlocks a user account that has been locked due to failed login attempts.',
180
211
  input: z.object({
181
212
  email: emailSchema
@@ -213,6 +244,13 @@ export const unlockCollectionTool = defineCollectionTool({
213
244
  }
214
245
  });
215
246
  export const verifyCollectionTool = defineCollectionTool({
247
+ annotations: {
248
+ destructiveHint: false,
249
+ idempotentHint: false,
250
+ openWorldHint: false,
251
+ readOnlyHint: false,
252
+ title: 'Email Verification'
253
+ },
216
254
  description: 'Verifies a user email with a verification token.',
217
255
  input: z.object({
218
256
  token: z.string().describe('The verification token sent to the user email')
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/mcp/builtin/collections/authTools.ts"],"sourcesContent":["import { z } from 'zod'\n\nimport type { MCPToolResponse } from '../../../types.js'\n\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\n\n/**\n * Auth tools surfaced under `collections.<auth-collection>.tools`. Opt-in: they\n * default off (an LLM with `login` access can probe passwords; not something\n * to expose by default). Enable in plugin config via `tools: { login: true }`\n * (or `{ description: '...' }`).\n *\n * `auth` (check current token) doesn't actually depend on the collection at\n * runtime — `payload.auth({ headers })` is global — but it's grouped under the\n * users collection so all auth-shaped tools live in one place.\n */\n\nconst emailSchema = z.string().email().describe('The user email address')\n\nconst wrapError =\n (name: string) =>\n ({ collectionSlug, message }: { collectionSlug: string; message: string }): MCPToolResponse => {\n return {\n content: [\n {\n type: 'text',\n text: `❌ **Error in ${name}** on ${collectionSlug}: ${message}`,\n },\n ],\n }\n }\n\nexport const authCollectionTool = defineCollectionTool({\n description: 'Checks authentication status for the current user.',\n input: z.object({\n headers: z\n .string()\n .describe(\n 'Optional JSON string containing custom headers to send with the authentication request',\n )\n .optional(),\n }),\n}).handler(async ({ collectionSlug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n let authHeaders = new Headers()\n if (input.headers) {\n try {\n authHeaders = new Headers(JSON.parse(input.headers) as Record<string, string>)\n } catch {\n logger.warn(`Invalid headers JSON for auth: ${input.headers}, using empty headers`)\n }\n }\n const result = await req.payload.auth({ headers: authHeaders })\n return {\n content: [\n {\n type: 'text',\n text: `# Authentication Status\\n\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\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 in auth tool on ${collectionSlug}: ${errorMessage}`)\n return wrapError('auth')({ collectionSlug, message: errorMessage })\n }\n})\n\nexport const forgotPasswordCollectionTool = defineCollectionTool({\n description: 'Sends a password reset email to a user.',\n input: z.object({\n disableEmail: z\n .boolean()\n .describe('Whether to disable sending the email (for testing)')\n .optional()\n .default(false),\n email: emailSchema,\n }),\n}).handler(async ({ collectionSlug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.forgotPassword({\n collection: collectionSlug,\n data: { email: input.email },\n disableEmail: input.disableEmail,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Forgot Password Email Sent\\n\\n**Collection:** ${collectionSlug}\\n**Email:** ${input.email}\\n\\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 in forgotPassword tool on ${collectionSlug}: ${errorMessage}`)\n return wrapError('forgotPassword')({ collectionSlug, message: errorMessage })\n }\n})\n\nexport const loginCollectionTool = defineCollectionTool({\n description: 'Authenticates a user with email and password.',\n input: z.object({\n depth: z\n .number()\n .int()\n .min(0)\n .max(10)\n .describe('Depth of population for relationships')\n .optional()\n .default(0),\n email: emailSchema,\n password: z.string().describe('The user password'),\n showHiddenFields: z\n .boolean()\n .describe('Whether to show hidden fields in the response')\n .optional()\n .default(false),\n }),\n}).handler(async ({ collectionSlug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.login({\n collection: collectionSlug,\n data: { email: input.email, password: input.password },\n depth: input.depth,\n showHiddenFields: input.showHiddenFields,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Login Successful\\n\\n**User:** ${input.email}\\n**Collection:** ${collectionSlug}\\n\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\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 in login tool on ${collectionSlug}: ${errorMessage}`)\n return wrapError('login')({ collectionSlug, message: errorMessage })\n }\n})\n\nexport const resetPasswordCollectionTool = defineCollectionTool({\n description: 'Resets a user password with a reset token.',\n input: z.object({\n password: z.string().describe('The new password for the user'),\n token: z.string().describe('The password reset token sent to the user email'),\n }),\n}).handler(async ({ collectionSlug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.resetPassword({\n collection: collectionSlug,\n data: { password: input.password, token: input.token },\n overrideAccess: true,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Password Reset Successful\\n\\n**Collection:** ${collectionSlug}\\n\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\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 in resetPassword tool on ${collectionSlug}: ${errorMessage}`)\n return wrapError('resetPassword')({ collectionSlug, message: errorMessage })\n }\n})\n\nexport const unlockCollectionTool = defineCollectionTool({\n description: 'Unlocks a user account that has been locked due to failed login attempts.',\n input: z.object({ email: emailSchema }),\n}).handler(async ({ collectionSlug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.unlock({\n collection: collectionSlug,\n data: { email: input.email },\n overrideAccess: true,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Account Unlocked\\n\\n**Collection:** ${collectionSlug}\\n**Email:** ${input.email}\\n**Result:** ${result ? 'Success' : 'Failed'}`,\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 in unlock tool on ${collectionSlug}: ${errorMessage}`)\n return wrapError('unlock')({ collectionSlug, message: errorMessage })\n }\n})\n\nexport const verifyCollectionTool = defineCollectionTool({\n description: 'Verifies a user email with a verification token.',\n input: z.object({\n token: z.string().describe('The verification token sent to the user email'),\n }),\n}).handler(async ({ collectionSlug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.verifyEmail({\n collection: collectionSlug,\n token: input.token,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Email Verification Successful\\n\\n**Collection:** ${collectionSlug}\\n**Result:** ${result ? 'Success' : 'Failed'}`,\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 in verify tool on ${collectionSlug}: ${errorMessage}`)\n return wrapError('verify')({ collectionSlug, message: errorMessage })\n }\n})\n"],"names":["z","defineCollectionTool","getLogger","emailSchema","string","email","describe","wrapError","name","collectionSlug","message","content","type","text","authCollectionTool","description","input","object","headers","optional","handler","req","logger","payload","authHeaders","Headers","JSON","parse","warn","result","auth","stringify","doc","error","errorMessage","Error","forgotPasswordCollectionTool","disableEmail","boolean","default","forgotPassword","collection","data","loginCollectionTool","depth","number","int","min","max","password","showHiddenFields","login","resetPasswordCollectionTool","token","resetPassword","overrideAccess","unlockCollectionTool","unlock","verifyCollectionTool","verifyEmail"],"mappings":"AAAA,SAASA,CAAC,QAAQ,MAAK;AAIvB,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AAEvD;;;;;;;;;CASC,GAED,MAAMC,cAAcH,EAAEI,MAAM,GAAGC,KAAK,GAAGC,QAAQ,CAAC;AAEhD,MAAMC,YACJ,CAACC,OAC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OAAO,GAAG;QAC9DY,OAAOW,KAAK,CAAC,CAAC,wBAAwB,EAAExB,eAAe,EAAE,EAAEyB,cAAc;QACzE,OAAO3B,UAAU,UAAU;YAAEE;YAAgBC,SAASwB;QAAa;IACrE;AACF,GAAE;AAEF,OAAO,MAAMwB,uBAAuBzD,qBAAqB;IACvDc,aAAa;IACbC,OAAOhB,EAAEiB,MAAM,CAAC;QACdoC,OAAOrD,EAAEI,MAAM,GAAGE,QAAQ,CAAC;IAC7B;AACF,GAAGc,OAAO,CAAC,OAAO,EAAEX,cAAc,EAAEO,KAAK,EAAEK,GAAG,EAAE;IAC9C,MAAMC,SAASpB,UAAU;QAAEqB,SAASF,IAAIE,OAAO;IAAC;IAChD,IAAI;QACF,MAAMM,SAAS,MAAMR,IAAIE,OAAO,CAACoC,WAAW,CAAC;YAC3ClB,YAAYhC;YACZ4C,OAAOrC,MAAMqC,KAAK;QACpB;QACA,OAAO;YACL1C,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,mDAAmD,EAAEJ,eAAe,cAAc,EAAEoB,SAAS,YAAY,UAAU;gBAC5H;aACD;YACDG,KAAK;gBAAEH;YAAO;QAChB;IACF,EAAE,OAAOI,OAAO;QACd,MAAMC,eAAeD,iBAAiBE,QAAQF,MAAMvB,OAAO,GAAG;QAC9DY,OAAOW,KAAK,CAAC,CAAC,wBAAwB,EAAExB,eAAe,EAAE,EAAEyB,cAAc;QACzE,OAAO3B,UAAU,UAAU;YAAEE;YAAgBC,SAASwB;QAAa;IACrE;AACF,GAAE"}
1
+ {"version":3,"sources":["../../../../src/mcp/builtin/collections/authTools.ts"],"sourcesContent":["import { z } from 'zod'\n\nimport type { MCPToolResponse } from '../../../types.js'\n\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\n\n/**\n * Auth tools surfaced under `collections.<auth-collection>.tools`. Opt-in: they\n * default off (an LLM with `login` access can probe passwords; not something\n * to expose by default). Enable in plugin config via `tools: { login: true }`\n * (or `{ description: '...' }`).\n *\n * `auth` (check current token) doesn't actually depend on the collection at\n * runtime — `payload.auth({ headers })` is global — but it's grouped under the\n * users collection so all auth-shaped tools live in one place.\n */\n\nconst emailSchema = z.string().email().describe('The user email address')\n\nconst wrapError =\n (name: string) =>\n ({ collectionSlug, message }: { collectionSlug: string; message: string }): MCPToolResponse => {\n return {\n content: [\n {\n type: 'text',\n text: `❌ **Error in ${name}** on ${collectionSlug}: ${message}`,\n },\n ],\n }\n }\n\nexport const authCollectionTool = defineCollectionTool({\n annotations: {\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n readOnlyHint: true,\n title: 'Check Auth Status',\n },\n description: 'Checks authentication status for the current user.',\n input: z.object({\n headers: z\n .record(z.string(), z.string())\n .describe('Optional custom headers to send with the authentication request')\n .optional(),\n }),\n}).handler(async ({ collectionSlug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n let authHeaders = new Headers()\n if (input.headers) {\n authHeaders = new Headers(input.headers)\n }\n const result = await req.payload.auth({ headers: authHeaders })\n return {\n content: [\n {\n type: 'text',\n text: `# Authentication Status\\n\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\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 in auth tool on ${collectionSlug}: ${errorMessage}`)\n return wrapError('auth')({ collectionSlug, message: errorMessage })\n }\n})\n\nexport const forgotPasswordCollectionTool = defineCollectionTool({\n annotations: {\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: true,\n readOnlyHint: false,\n title: 'Forgot Password',\n },\n description: 'Sends a password reset email to a user.',\n input: z.object({\n disableEmail: z\n .boolean()\n .describe('Whether to disable sending the email (for testing)')\n .optional()\n .default(false),\n email: emailSchema,\n }),\n}).handler(async ({ collectionSlug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.forgotPassword({\n collection: collectionSlug,\n data: { email: input.email },\n disableEmail: input.disableEmail,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Forgot Password Email Sent\\n\\n**Collection:** ${collectionSlug}\\n**Email:** ${input.email}\\n\\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 in forgotPassword tool on ${collectionSlug}: ${errorMessage}`)\n return wrapError('forgotPassword')({ collectionSlug, message: errorMessage })\n }\n})\n\nexport const loginCollectionTool = defineCollectionTool({\n annotations: {\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'User Login',\n },\n description: 'Authenticates a user with email and password.',\n input: z.object({\n depth: z\n .number()\n .int()\n .min(0)\n .max(10)\n .describe('Depth of population for relationships')\n .optional()\n .default(0),\n email: emailSchema,\n password: z.string().describe('The user password'),\n showHiddenFields: z\n .boolean()\n .describe('Whether to show hidden fields in the response')\n .optional()\n .default(false),\n }),\n}).handler(async ({ collectionSlug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.login({\n collection: collectionSlug,\n data: { email: input.email, password: input.password },\n depth: input.depth,\n showHiddenFields: input.showHiddenFields,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Login Successful\\n\\n**User:** ${input.email}\\n**Collection:** ${collectionSlug}\\n\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\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 in login tool on ${collectionSlug}: ${errorMessage}`)\n return wrapError('login')({ collectionSlug, message: errorMessage })\n }\n})\n\nexport const resetPasswordCollectionTool = defineCollectionTool({\n annotations: {\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'Reset Password',\n },\n description: 'Resets a user password with a reset token.',\n input: z.object({\n password: z.string().describe('The new password for the user'),\n token: z.string().describe('The password reset token sent to the user email'),\n }),\n}).handler(async ({ collectionSlug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.resetPassword({\n collection: collectionSlug,\n data: { password: input.password, token: input.token },\n overrideAccess: true,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Password Reset Successful\\n\\n**Collection:** ${collectionSlug}\\n\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\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 in resetPassword tool on ${collectionSlug}: ${errorMessage}`)\n return wrapError('resetPassword')({ collectionSlug, message: errorMessage })\n }\n})\n\nexport const unlockCollectionTool = defineCollectionTool({\n annotations: {\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'Unlock Account',\n },\n description: 'Unlocks a user account that has been locked due to failed login attempts.',\n input: z.object({ email: emailSchema }),\n}).handler(async ({ collectionSlug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.unlock({\n collection: collectionSlug,\n data: { email: input.email },\n overrideAccess: true,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Account Unlocked\\n\\n**Collection:** ${collectionSlug}\\n**Email:** ${input.email}\\n**Result:** ${result ? 'Success' : 'Failed'}`,\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 in unlock tool on ${collectionSlug}: ${errorMessage}`)\n return wrapError('unlock')({ collectionSlug, message: errorMessage })\n }\n})\n\nexport const verifyCollectionTool = defineCollectionTool({\n annotations: {\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'Email Verification',\n },\n description: 'Verifies a user email with a verification token.',\n input: z.object({\n token: z.string().describe('The verification token sent to the user email'),\n }),\n}).handler(async ({ collectionSlug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.verifyEmail({\n collection: collectionSlug,\n token: input.token,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Email Verification Successful\\n\\n**Collection:** ${collectionSlug}\\n**Result:** ${result ? 'Success' : 'Failed'}`,\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 in verify tool on ${collectionSlug}: ${errorMessage}`)\n return wrapError('verify')({ collectionSlug, message: errorMessage })\n }\n})\n"],"names":["z","defineCollectionTool","getLogger","emailSchema","string","email","describe","wrapError","name","collectionSlug","message","content","type","text","authCollectionTool","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","object","headers","record","optional","handler","req","logger","payload","authHeaders","Headers","result","auth","JSON","stringify","doc","error","errorMessage","Error","forgotPasswordCollectionTool","disableEmail","boolean","default","forgotPassword","collection","data","loginCollectionTool","depth","number","int","min","max","password","showHiddenFields","login","resetPasswordCollectionTool","token","resetPassword","overrideAccess","unlockCollectionTool","unlock","verifyCollectionTool","verifyEmail"],"mappings":"AAAA,SAASA,CAAC,QAAQ,MAAK;AAIvB,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AAEvD;;;;;;;;;CASC,GAED,MAAMC,cAAcH,EAAEI,MAAM,GAAGC,KAAK,GAAGC,QAAQ,CAAC;AAEhD,MAAMC,YACJ,CAACC,OACD,CAAC,EAAEC,cAAc,EAAEC,OAAO,EAA+C;QACvE,OAAO;YACLC,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,aAAa,EAAEL,KAAK,MAAM,EAAEC,eAAe,EAAE,EAAEC,SAAS;gBACjE;aACD;QACH;IACF;AAEF,OAAO,MAAMI,qBAAqBb,qBAAqB;IACrDc,aAAa;QACX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ectionTool;
2
+ //# sourceMappingURL=countTool.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"countTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/countTool.ts"],"names":[],"mappings":"AAUA,eAAO,MAAM,kBAAkB,4CA8D7B,CAAA"}
@@ -0,0 +1,68 @@
1
+ import { z } from 'zod';
2
+ import { defaultAccess } from '../../../defaultAccess.js';
3
+ import { defineCollectionTool } from '../../../defineTool.js';
4
+ import { getLogger } from '../../../utils/getLogger.js';
5
+ import { whereSchema } from '../../../utils/whereSchema.js';
6
+ const DEFAULT_DESCRIPTION = 'Count documents in any collection by passing the collection slug and optional where clause.';
7
+ export const countDocumentsTool = defineCollectionTool({
8
+ access: (args)=>defaultAccess(args) && Boolean(args.permissions?.collections?.[args.collectionSlug]?.read),
9
+ annotations: {
10
+ destructiveHint: false,
11
+ idempotentHint: true,
12
+ openWorldHint: false,
13
+ readOnlyHint: true,
14
+ title: 'Count Documents'
15
+ },
16
+ description: DEFAULT_DESCRIPTION,
17
+ input: z.object({
18
+ locale: z.string().describe('Optional: locale code to count documents in').optional(),
19
+ trash: z.boolean().describe('Optional: include soft-deleted documents when trash is enabled on the collection').optional(),
20
+ where: whereSchema.describe('Optional: where clause for filtering. Use field names with Payload operators, and/or arrays for grouping. Example: {"title":{"contains":"test"}}').optional()
21
+ })
22
+ }).handler(async ({ authorizedMCP, collectionSlug, input, req })=>{
23
+ const payload = req.payload;
24
+ const logger = getLogger({
25
+ payload
26
+ });
27
+ const { locale, trash, where } = input;
28
+ logger.info(`Counting documents in collection: ${collectionSlug}`);
29
+ try {
30
+ const result = await payload.count({
31
+ collection: collectionSlug,
32
+ overrideAccess: authorizedMCP.overrideAccess,
33
+ req,
34
+ ...locale ? {
35
+ locale
36
+ } : {},
37
+ ...trash !== undefined ? {
38
+ trash
39
+ } : {},
40
+ ...where ? {
41
+ where
42
+ } : {}
43
+ });
44
+ return {
45
+ content: [
46
+ {
47
+ type: 'text',
48
+ text: `Collection "${collectionSlug}" contains ${result.totalDocs} matching documents.\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``
49
+ }
50
+ ],
51
+ doc: result
52
+ };
53
+ } catch (error) {
54
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';
55
+ logger.error(`Error counting documents in ${collectionSlug}: ${errorMessage}`);
56
+ return {
57
+ content: [
58
+ {
59
+ type: 'text',
60
+ text: `❌ **Error counting documents in collection "${collectionSlug}":** ${errorMessage}`
61
+ }
62
+ ],
63
+ isError: true
64
+ };
65
+ }
66
+ });
67
+
68
+ //# sourceMappingURL=countTool.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/mcp/builtin/collections/countTool.ts"],"sourcesContent":["import { z } from 'zod'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\nimport { whereSchema } from '../../../utils/whereSchema.js'\n\nconst DEFAULT_DESCRIPTION =\n 'Count documents in any collection by passing the collection slug and optional where clause.'\n\nexport const countDocumentsTool = defineCollectionTool({\n access: (args) =>\n defaultAccess(args) && Boolean(args.permissions?.collections?.[args.collectionSlug]?.read),\n annotations: {\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n readOnlyHint: true,\n title: 'Count Documents',\n },\n description: DEFAULT_DESCRIPTION,\n input: z.object({\n locale: z.string().describe('Optional: locale code to count documents in').optional(),\n trash: z\n .boolean()\n .describe('Optional: include soft-deleted documents when trash is enabled on the collection')\n .optional(),\n where: whereSchema\n .describe(\n 'Optional: where clause for filtering. Use field names with Payload operators, and/or arrays for grouping. Example: {\"title\":{\"contains\":\"test\"}}',\n )\n .optional(),\n }),\n}).handler(async ({ authorizedMCP, collectionSlug, input, req }) => {\n const payload = req.payload\n const logger = getLogger({ payload })\n const { locale, trash, where } = input\n\n logger.info(`Counting documents in collection: ${collectionSlug}`)\n\n try {\n const result = await payload.count({\n collection: collectionSlug,\n overrideAccess: authorizedMCP.overrideAccess,\n req,\n ...(locale ? { locale } : {}),\n ...(trash !== undefined ? { trash } : {}),\n ...(where ? { where } : {}),\n })\n\n return {\n content: [\n {\n type: 'text',\n text: `Collection \"${collectionSlug}\" contains ${result.totalDocs} matching documents.\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error counting documents in ${collectionSlug}: ${errorMessage}`)\n return {\n content: [\n {\n type: 'text',\n text: `❌ **Error counting documents in collection \"${collectionSlug}\":** ${errorMessage}`,\n },\n ],\n isError: true,\n }\n }\n})\n"],"names":["z","defaultAccess","defineCollectionTool","getLogger","whereSchema","DEFAULT_DESCRIPTION","countDocumentsTool","access","args","Boolean","permissions","collections","collectionSlug","read","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","object","locale","string","describe","optional","trash","boolean","where","handler","authorizedMCP","req","payload","logger","info","result","count","collection","overrideAccess","undefined","content","type","text","totalDocs","JSON","stringify","doc","error","errorMessage","Error","message","isError"],"mappings":"AAAA,SAASA,CAAC,QAAQ,MAAK;AAEvB,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AACvD,SAASC,WAAW,QAAQ,gCAA+B;AAE3D,MAAMC,sBACJ;AAEF,OAAO,MAAMC,qBAAqBJ,qBAAqB;IACrDK,QAAQ,CAACC,OACPP,cAAcO,SAASC,QAAQD,KAAKE,WAAW,EAAEC,aAAa,CAACH,KAAKI,cAAc,CAAC,EAAEC;IACvFC,aAAa;QACXC,iBAAiB;QACjBC,gBAAgB;QAChBC,eAAe;QACfC,cAAc;QACdC,OAAO;IACT;IACAC,aAAaf;IACbgB,OAAOrB,EAAEsB,MAAM,CAAC;QACdC,QAAQvB,EAAEwB,MAAM,GAAGC,QAAQ,CAAC,+CA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0 +1,2 @@
1
+ export declare const countVersionsTool: import("../../../types.js").CollectionTool;
2
+ //# sourceMappingURL=countVersionsTool.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"countVersionsTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/countVersionsTool.ts"],"names":[],"mappings":"AAUA,eAAO,MAAM,iBAAiB,4CA0D5B,CAAA"}
@@ -0,0 +1,64 @@
1
+ import { z } from 'zod';
2
+ import { defaultAccess } from '../../../defaultAccess.js';
3
+ import { defineCollectionTool } from '../../../defineTool.js';
4
+ import { getLogger } from '../../../utils/getLogger.js';
5
+ import { whereSchema } from '../../../utils/whereSchema.js';
6
+ const DEFAULT_DESCRIPTION = 'Count document versions in any version-enabled collection by passing the collection slug and optional where clause.';
7
+ export const countVersionsTool = defineCollectionTool({
8
+ access: (args)=>defaultAccess(args) && Boolean(args.permissions?.collections?.[args.collectionSlug]?.readVersions),
9
+ annotations: {
10
+ destructiveHint: false,
11
+ idempotentHint: true,
12
+ openWorldHint: false,
13
+ readOnlyHint: true,
14
+ title: 'Count Versions'
15
+ },
16
+ description: DEFAULT_DESCRIPTION,
17
+ input: z.object({
18
+ locale: z.string().describe('Optional: locale code to count versions in').optional(),
19
+ where: whereSchema.describe('Optional: where clause for filtering versions. Version document fields are usually under "version". Example: {"version.title":{"contains":"test"}}').optional()
20
+ })
21
+ }).handler(async ({ authorizedMCP, collectionSlug, input, req })=>{
22
+ const payload = req.payload;
23
+ const logger = getLogger({
24
+ payload
25
+ });
26
+ const { locale, where } = input;
27
+ logger.info(`Counting versions in collection: ${collectionSlug}`);
28
+ try {
29
+ const result = await payload.countVersions({
30
+ collection: collectionSlug,
31
+ overrideAccess: authorizedMCP.overrideAccess,
32
+ req,
33
+ ...locale ? {
34
+ locale
35
+ } : {},
36
+ ...where ? {
37
+ where
38
+ } : {}
39
+ });
40
+ return {
41
+ content: [
42
+ {
43
+ type: 'text',
44
+ text: `Collection "${collectionSlug}" contains ${result.totalDocs} matching versions.\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``
45
+ }
46
+ ],
47
+ doc: result
48
+ };
49
+ } catch (error) {
50
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';
51
+ logger.error(`Error counting versions in ${collectionSlug}: ${errorMessage}`);
52
+ return {
53
+ content: [
54
+ {
55
+ type: 'text',
56
+ text: `❌ **Error counting versions in collection "${collectionSlug}":** ${errorMessage}`
57
+ }
58
+ ],
59
+ isError: true
60
+ };
61
+ }
62
+ });
63
+
64
+ //# sourceMappingURL=countVersionsTool.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/mcp/builtin/collections/countVersionsTool.ts"],"sourcesContent":["import { z } from 'zod'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\nimport { whereSchema } from '../../../utils/whereSchema.js'\n\nconst DEFAULT_DESCRIPTION =\n 'Count document versions in any version-enabled collection by passing the collection slug and optional where clause.'\n\nexport const countVersionsTool = defineCollectionTool({\n access: (args) =>\n defaultAccess(args) &&\n Boolean(args.permissions?.collections?.[args.collectionSlug]?.readVersions),\n annotations: {\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n readOnlyHint: true,\n title: 'Count Versions',\n },\n description: DEFAULT_DESCRIPTION,\n input: z.object({\n locale: z.string().describe('Optional: locale code to count versions in').optional(),\n where: whereSchema\n .describe(\n 'Optional: where clause for filtering versions. Version document fields are usually under \"version\". Example: {\"version.title\":{\"contains\":\"test\"}}',\n )\n .optional(),\n }),\n}).handler(async ({ authorizedMCP, collectionSlug, input, req }) => {\n const payload = req.payload\n const logger = getLogger({ payload })\n const { locale, where } = input\n\n logger.info(`Counting versions in collection: ${collectionSlug}`)\n\n try {\n const result = await payload.countVersions({\n collection: collectionSlug,\n overrideAccess: authorizedMCP.overrideAccess,\n req,\n ...(locale ? { locale } : {}),\n ...(where ? { where } : {}),\n })\n\n return {\n content: [\n {\n type: 'text',\n text: `Collection \"${collectionSlug}\" contains ${result.totalDocs} matching versions.\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error counting versions in ${collectionSlug}: ${errorMessage}`)\n return {\n content: [\n {\n type: 'text',\n text: `❌ **Error counting versions in collection \"${collectionSlug}\":** ${errorMessage}`,\n },\n ],\n isError: true,\n }\n }\n})\n"],"names":["z","defaultAccess","defineCollectionTool","getLogger","whereSchema","DEFAULT_DESCRIPTION","countVersionsTool","access","args","Boolean","permissions","collections","collectionSlug","readVersions","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","object","locale","string","describe","optional","where","handler","authorizedMCP","req","payload","logger","info","result","countVersions","collection","overrideAccess","content","type","text","totalDocs","JSON","stringify","doc","error","errorMessage","Error","message","isError"],"mappings":"AAAA,SAASA,CAAC,QAAQ,MAAK;AAEvB,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AACvD,SAASC,WAAW,QAAQ,gCAA+B;AAE3D,MAAMC,sBACJ;AAEF,OAAO,MAAMC,oBAAoBJ,qBAAqB;IACpDK,QAAQ,CAACC,OACPP,cAAcO,SACdC,QAAQD,KAAKE,WAAW,EAAEC,aAAa,CAACH,KAAKI,cAAc,CAAC,EAAEC;IAChEC,aAAa;QACXC,iBAAiB;QACjBC,gBAAgB;QAChBC,eAAe;QACfC,cAAc;QACdC,OAAO;IACT;IACAC,aAAaf;IACbgB,OAAOrB,EAAEsB,MAAM,CAAC;QACdC,QAAQvB,EAAEwB,MAAM,GAAGC,QAAQ,CAAC,8CAA8CC,QAAQ;QAClFC,OAAOvB,YACJqB,QAAQ,CACP,sJAEDC,QAAQ;IACb;AACF,GAAGE,OAAO,CAAC,OAAO,EAAEC,aAAa,EAAEjB,cAAc,EAAES,KAAK,EAAES,GAAG,EAAE;IAC7D,MAAMC,UAAUD,IAAIC,OAAO;IAC3B,MAAMC,SAAS7B,UAAU;QAAE4B;IAAQ;IACnC,MAAM,EAAER,MAAM,EAAEI,KAAK,EAAE,GAAGN;IAE1BW,OAAOC,IAAI,CAAC,CAAC,iCAAiC,EAAErB,gBAAgB;IAEhE,IAAI;QACF,MAAMsB,SAAS,MAAMH,QAAQI,aAAa,CAAC;YACzCC,YAAYxB;YACZyB,gBAAgBR,cAAcQ,cAAc;YAC5CP;YACA,GAAIP,SAAS;gBAAEA;YAAO,IAAI,CAAC,CAAC;YAC5B,GAAII,QAAQ;gBAAEA;YAAM,IAAI,CAAC,CAAC;QAC5B;QAEA,OAAO;YACLW,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,YAAY,EAAE5B,eAAe,WAAW,EAAEsB,OAAOO,SAAS,CAAC,iCAAiC,EAAEC,KAAKC,SAAS,CAACT,QAAQ,QAAQ,CAAC;gBACvI;aACD;YACDU,KAAKV;QACP;IACF,EAAE,OAAOW,OAAO;QACd,MAAMC,eAAeD,iBAAiBE,QAAQF,MAAMG,OAAO,GAAG;QAC9DhB,OAAOa,KAAK,CAAC,CAAC,2BAA2B,EAAEjC,eAAe,EAAE,EAAEkC,cAAc;QAC5E,OAAO;YACLR,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,2CAA2C,EAAE5B,eAAe,KAAK,EAAEkC,cAAc;gBAC1F;aACD;YACDG,SAAS;QACX;IACF;AACF,GAAE"}
@@ -1,2 +1,2 @@
1
- export declare const createCollectionTool: import("../../../types.js").CollectionTool;
1
+ export declare const createDocumentTool: import("../../../types.js").CollectionTool;
2
2
  //# sourceMappingURL=createTool.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"createTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/createTool.ts"],"names":[],"mappings":"AAiBA,eAAO,MAAM,oBAAoB,4CAkG/B,CAAA"}
1
+ {"version":3,"file":"createTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/createTool.ts"],"names":[],"mappings":"AAkBA,eAAO,MAAM,kBAAkB,4CAkG7B,CAAA"}
@@ -1,25 +1,30 @@
1
1
  import { z } from 'zod';
2
+ import { defaultAccess } from '../../../defaultAccess.js';
2
3
  import { defineCollectionTool } from '../../../defineTool.js';
3
4
  import { getLogger } from '../../../utils/getLogger.js';
4
5
  import { getCollectionVirtualFieldNames, stripVirtualFields } from '../../../utils/getVirtualFieldNames.js';
5
- import { localAPIDefaults } from '../../../utils/localAPIDefaults.js';
6
- import { buildToolInput } from '../../../utils/schemaConversion/buildToolInput.js';
7
- import { sanitizeEntitySchema } from '../../../utils/schemaConversion/sanitizeEntitySchema.js';
8
6
  import { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js';
9
- const DEFAULT_DESCRIPTION = 'Create a document in a collection.';
10
- export const createCollectionTool = defineCollectionTool({
7
+ import { validateCollectionData } from '../validateEntityData.js';
8
+ import { formatCollectionError } from './formatCollectionError.js';
9
+ const DEFAULT_DESCRIPTION = 'Create a document in any collection by passing the collection slug and data.';
10
+ export const createDocumentTool = defineCollectionTool({
11
+ access: (args)=>defaultAccess(args) && Boolean(args.permissions?.collections?.[args.collectionSlug]?.create),
12
+ annotations: {
13
+ destructiveHint: false,
14
+ idempotentHint: false,
15
+ openWorldHint: false,
16
+ readOnlyHint: false,
17
+ title: 'Create Document'
18
+ },
11
19
  description: DEFAULT_DESCRIPTION,
12
- input: ({ collectionSchema })=>buildToolInput({
13
- controls: {
14
- depth: z.number().int().min(0).max(10).describe('How many levels deep to populate relationships in response').optional().default(0),
15
- draft: z.boolean().describe('Whether to create the document as a draft').optional().default(false),
16
- fallbackLocale: z.string().describe('Optional: fallback locale code to use when requested locale is not available').optional(),
17
- locale: z.string().describe('Optional: locale code to create the document in (e.g., "en", "es"). Defaults to the default locale').optional(),
18
- select: z.string().describe('Optional: define exactly which fields you\'d like to create (JSON), e.g., \'{"title": "My Post"}\'').optional()
19
- },
20
- dataDescription: 'The document fields to create',
21
- dataSchema: sanitizeEntitySchema(collectionSchema)
22
- })
20
+ input: z.object({
21
+ data: z.record(z.string(), z.unknown()).describe('The document fields to create. Only include fields permitted by the schema returned by getCollectionSchema.'),
22
+ depth: z.number().int().min(0).max(10).describe('How many levels deep to populate relationships in response').optional().default(0),
23
+ draft: z.boolean().describe('Only if getCollectionSchema includes _status; otherwise _status does not exist. true forces data._status to "draft"; with false, data._status controls draft or published.').optional().default(false),
24
+ fallbackLocale: z.string().describe('Optional: fallback locale code to use when requested locale is not available').optional(),
25
+ locale: z.string().describe('Optional: locale code to create the document in (e.g., "en", "es"). Defaults to the default locale').optional(),
26
+ select: z.record(z.string(), z.unknown()).describe('Optional: define exactly which fields you\'d like to return, e.g., {"title": true}').optional()
27
+ })
23
28
  }).handler(async ({ authorizedMCP, collectionSlug, input, req })=>{
24
29
  const payload = req.payload;
25
30
  const logger = getLogger({
@@ -28,40 +33,32 @@ export const createCollectionTool = defineCollectionTool({
28
33
  const { data, depth, draft, fallbackLocale, locale, select } = input;
29
34
  logger.info(`Creating document in collection: ${collectionSlug}${locale ? ` with locale: ${locale}` : ''}`);
30
35
  try {
31
- let parsedData = transformPointDataToPayload(data);
32
36
  const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, collectionSlug);
33
- parsedData = stripVirtualFields(parsedData, virtualFieldNames);
34
- let selectClause;
35
- if (select) {
36
- try {
37
- selectClause = JSON.parse(select);
38
- } catch {
39
- logger.warn(`Invalid select clause JSON: ${select}`);
40
- return {
41
- content: [
42
- {
43
- type: 'text',
44
- text: 'Error: Invalid JSON in select clause'
45
- }
46
- ]
47
- };
48
- }
37
+ const inputData = stripVirtualFields(data, virtualFieldNames);
38
+ const validationError = validateCollectionData({
39
+ collectionSlug,
40
+ data: inputData,
41
+ req
42
+ });
43
+ if (validationError) {
44
+ return validationError;
49
45
  }
46
+ const parsedData = transformPointDataToPayload(inputData);
50
47
  const result = await payload.create({
51
48
  collection: collectionSlug,
52
49
  data: parsedData,
53
50
  depth,
54
51
  draft,
52
+ overrideAccess: authorizedMCP.overrideAccess,
55
53
  req,
56
- ...localAPIDefaults(authorizedMCP),
57
54
  ...locale ? {
58
55
  locale
59
56
  } : {},
60
57
  ...fallbackLocale ? {
61
58
  fallbackLocale
62
59
  } : {},
63
- ...selectClause ? {
64
- select: selectClause
60
+ ...select ? {
61
+ select: select
65
62
  } : {}
66
63
  });
67
64
  logger.info(`Successfully created document in ${collectionSlug} with ID: ${result.id}`);
@@ -77,14 +74,12 @@ export const createCollectionTool = defineCollectionTool({
77
74
  } catch (error) {
78
75
  const errorMessage = error instanceof Error ? error.message : 'Unknown error';
79
76
  logger.error(`Error creating document in ${collectionSlug}: ${errorMessage}`);
80
- return {
81
- content: [
82
- {
83
- type: 'text',
84
- text: `Error creating document in collection "${collectionSlug}": ${errorMessage}`
85
- }
86
- ]
87
- };
77
+ return formatCollectionError({
78
+ action: 'creating',
79
+ collectionSlug,
80
+ error,
81
+ req
82
+ });
88
83
  }
89
84
  });
90
85
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/mcp/builtin/collections/createTool.ts"],"sourcesContent":["import type { SelectType } from 'payload'\n\nimport { z } from 'zod'\n\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\nimport {\n getCollectionVirtualFieldNames,\n stripVirtualFields,\n} from '../../../utils/getVirtualFieldNames.js'\nimport { localAPIDefaults } from '../../../utils/localAPIDefaults.js'\nimport { buildToolInput } from '../../../utils/schemaConversion/buildToolInput.js'\nimport { sanitizeEntitySchema } from '../../../utils/schemaConversion/sanitizeEntitySchema.js'\nimport { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'\n\nconst DEFAULT_DESCRIPTION = 'Create a document in a collection.'\n\nexport const createCollectionTool = defineCollectionTool({\n description: DEFAULT_DESCRIPTION,\n input: ({ collectionSchema }) =>\n buildToolInput({\n controls: {\n depth: z\n .number()\n .int()\n .min(0)\n .max(10)\n .describe('How many levels deep to populate relationships in response')\n .optional()\n .default(0),\n draft: z\n .boolean()\n .describe('Whether to create the document as a draft')\n .optional()\n .default(false),\n fallbackLocale: z\n .string()\n .describe('Optional: fallback locale code to use when requested locale is not available')\n .optional(),\n locale: z\n .string()\n .describe(\n 'Optional: locale code to create the document in (e.g., \"en\", \"es\"). Defaults to the default locale',\n )\n .optional(),\n select: z\n .string()\n .describe(\n 'Optional: define exactly which fields you\\'d like to create (JSON), e.g., \\'{\"title\": \"My Post\"}\\'',\n )\n .optional(),\n },\n dataDescription: 'The document fields to create',\n dataSchema: sanitizeEntitySchema(collectionSchema),\n }),\n}).handler(async ({ authorizedMCP, collectionSlug, input, req }) => {\n const payload = req.payload\n const logger = getLogger({ payload })\n\n const { data, depth, draft, fallbackLocale, locale, select } = input\n\n logger.info(\n `Creating document in collection: ${collectionSlug}${locale ? ` with locale: ${locale}` : ''}`,\n )\n\n try {\n let parsedData = transformPointDataToPayload(data)\n const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, collectionSlug)\n parsedData = stripVirtualFields(parsedData, virtualFieldNames)\n\n let selectClause: SelectType | undefined\n if (select) {\n try {\n selectClause = JSON.parse(select) as SelectType\n } catch {\n logger.warn(`Invalid select clause JSON: ${select}`)\n return { content: [{ type: 'text', text: 'Error: Invalid JSON in select clause' }] }\n }\n }\n\n const result = await payload.create({\n collection: collectionSlug,\n data: parsedData,\n depth,\n draft,\n req,\n ...localAPIDefaults(authorizedMCP),\n ...(locale ? { locale } : {}),\n ...(fallbackLocale ? { fallbackLocale } : {}),\n ...(selectClause ? { select: selectClause } : {}),\n })\n\n logger.info(`Successfully created document in ${collectionSlug} with ID: ${result.id}`)\n\n return {\n content: [\n {\n type: 'text',\n text: `Document created successfully in collection \"${collectionSlug}\"!\\nCreated document:\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error creating document in ${collectionSlug}: ${errorMessage}`)\n return {\n content: [\n {\n type: 'text',\n text: `Error creating document in collection \"${collectionSlug}\": ${errorMessage}`,\n },\n ],\n }\n }\n})\n"],"names":["z","defineCollectionTool","getLogger","getCollectionVirtualFieldNames","stripVirtualFields","localAPIDefaults","buildToolInput","sanitizeEntitySchema","transformPointDataToPayload","DEFAULT_DESCRIPTION","createCollectionTool","description","input","collectionSchema","controls","depth","number","int","min","max","describe","optional","default","draft","boolean","fallbackLocale","string","locale","select","dataDescription","dataSchema","handler","authorizedMCP","collectionSlug","req","payload","logger","data","info","parsedData","virtualFieldNames","config","selectClause","JSON","parse","warn","content","type","text","result","create","collection","id","stringify","doc","error","errorMessage","Error","message"],"mappings":"AAEA,SAASA,CAAC,QAAQ,MAAK;AAEvB,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AACvD,SACEC,8BAA8B,EAC9BC,kBAAkB,QACb,yCAAwC;AAC/C,SAASC,gBAAgB,QAAQ,qCAAoC;AACrE,SAASC,cAAc,QAAQ,oDAAmD;AAClF,SAASC,oBAAoB,QAAQ,0DAAyD;AAC9F,SAASC,2BAA2B,QAAQ,gDAA+C;AAE3F,MAAMC,sBAAsB;AAE5B,OAAO,MAAMC,uBAAuBT,qBAAqB;IACvDU,aAAaF;IACbG,OAAO,CAAC,EAAEC,gBAAgB,EAAE,GAC1BP,eAAe;YACbQ,UAAU;gBACRC,OAAOf,EACJgB,MAAM,GACNC,GAAG,GACHC,GAAG,CAAC,GACJC,GAAG,CAAC,IACJC,QAAQ,CAAC,8DACTC,QAAQ,GACRC,OAAO,CAAC;gBACXC,OAAOvB,EACJwB,OAAO,GACPJ,QAAQ,CAAC,6CACTC,QAAQ,GACRC,OAAO,CAAC;gBACXG,gBAAgBzB,EACb0B,MAAM,GACNN,QAAQ,CAAC,gFACT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a,IAAI,CAAC,CAAC;QAClD;QAEAN,OAAOE,IAAI,CAAC,CAAC,iCAAiC,EAAEL,eAAe,UAAU,EAAEgB,OAAOG,EAAE,EAAE;QAEtF,OAAO;YACLN,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,6CAA6C,EAAEf,eAAe,mCAAmC,EAAEU,KAAKU,SAAS,CAACJ,QAAQ,QAAQ,CAAC;gBAC5I;aACD;YACDK,KAAKL;QACP;IACF,EAAE,OAAOM,OAAO;QACd,MAAMC,eAAeD,iBAAiBE,QAAQF,MAAMG,OAAO,GAAG;QAC9DtB,OAAOmB,KAAK,CAAC,CAAC,2BAA2B,EAAEtB,eAAe,EAAE,EAAEuB,cAAc;QAC5E,OAAO;YACLV,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,uCAAuC,EAAEf,eAAe,GAAG,EAAEuB,cAAc;gBACpF;aACD;QACH;IACF;AACF,GAAE"}
1
+ {"version":3,"sources":["../../../../src/mcp/builtin/collections/createTool.ts"],"sourcesContent":["import type { SelectType } from 'payload'\n\nimport { z } from 'zod'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\nimport {\n getCollectionVirtualFieldNames,\n stripVirtualFields,\n} from '../../../utils/getVirtualFieldNames.js'\nimport { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'\nimport { validateCollectionData } from '../validateEntityData.js'\nimport { formatCollectionError } from './formatCollectionError.js'\n\nconst DEFAULT_DESCRIPTION =\n 'Create a document in any collection by passing the collection slug and data.'\n\nexport const createDocumentTool = defineCollectionTool({\n access: (args) =>\n defaultAccess(args) && Boolean(args.permissions?.collections?.[args.collectionSlug]?.create),\n annotations: {\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'Create Document',\n },\n description: DEFAULT_DESCRIPTION,\n input: z.object({\n data: z\n .record(z.string(), z.unknown())\n .describe(\n 'The document fields to create. Only include fields permitted by the schema returned by getCollectionSchema.',\n ),\n depth: z\n .number()\n .int()\n .min(0)\n .max(10)\n .describe('How many levels deep to populate relationships in response')\n .optional()\n .default(0),\n draft: z\n .boolean()\n .describe(\n 'Only if getCollectionSchema includes _status; otherwise _status does not exist. true forces data._status to \"draft\"; with false, data._status controls draft or published.',\n )\n .optional()\n .default(false),\n fallbackLocale: z\n .string()\n .describe('Optional: fallback locale code to use when requested locale is not available')\n .optional(),\n locale: z\n .string()\n .describe(\n 'Optional: locale code to create the document in (e.g., \"en\", \"es\"). Defaults to the default locale',\n )\n .optional(),\n select: z\n .record(z.string(), z.unknown())\n .describe(\n 'Optional: define exactly which fields you\\'d like to return, e.g., {\"title\": true}',\n )\n .optional(),\n }),\n}).handler(async ({ authorizedMCP, collectionSlug, input, req }) => {\n const payload = req.payload\n const logger = getLogger({ payload })\n\n const { data, depth, draft, fallbackLocale, locale, select } = input\n\n logger.info(\n `Creating document in collection: ${collectionSlug}${locale ? ` with locale: ${locale}` : ''}`,\n )\n\n try {\n const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, collectionSlug)\n const inputData = stripVirtualFields(data, virtualFieldNames)\n const validationError = validateCollectionData({ collectionSlug, data: inputData, req })\n\n if (validationError) {\n return validationError\n }\n\n const parsedData = transformPointDataToPayload(inputData)\n\n const result = await payload.create({\n collection: collectionSlug,\n data: parsedData,\n depth,\n draft,\n overrideAccess: authorizedMCP.overrideAccess,\n req,\n ...(locale ? { locale } : {}),\n ...(fallbackLocale ? { fallbackLocale } : {}),\n ...(select ? { select: select as SelectType } : {}),\n })\n\n logger.info(`Successfully created document in ${collectionSlug} with ID: ${result.id}`)\n\n return {\n content: [\n {\n type: 'text',\n text: `Document created successfully in collection \"${collectionSlug}\"!\\nCreated document:\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error creating document in ${collectionSlug}: ${errorMessage}`)\n return formatCollectionError({ action: 'creating', collectionSlug, error, req })\n }\n})\n"],"names":["z","defaultAccess","defineCollectionTool","getLogger","getCollectionVirtualFieldNames","stripVirtualFields","transformPointDataToPayload","validateCollectionData","formatCollectionError","DEFAULT_DESCRIPTION","createDocumentTool","access","args","Boolean","permissions","collections","collectionSlug","create","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","object","data","record","string","unknown","describe","depth","number","int","min","max","optional","default","draft","boolean","fallbackLocale","locale","select","handler","authorizedMCP","req","payload","logger","info","virtualFieldNames","config","inputData","validationError","parsedData","result","collection","overrideAccess","id","content","type","text","JSON","stringify","doc","error","errorMessage","Error","message","action"],"mappings":"AAEA,SAASA,CAAC,QAAQ,MAAK;AAEvB,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AACvD,SACEC,8BAA8B,EAC9BC,kBAAkB,QACb,yCAAwC;AAC/C,SAASC,2BAA2B,QAAQ,gDAA+C;AAC3F,SAASC,sBAAsB,QAAQ,2BAA0B;AACjE,SAASC,qBAAqB,QAAQ,6BAA4B;AAElE,MAAMC,sBACJ;AAEF,OAAO,MAAMC,qBAAqBR,qBAAqB;IACrDS,QAAQ,CAACC,OACPX,cAAcW,SAASC,QAAQD,KAAKE,WAAW,EAAEC,aAAa,CAACH,KAAKI,cAAc,CAAC,EAAEC;IACvFC,aAAa;QACXC,iBAAiB;QACjBC,gBAAgB;QAChBC,eAAe;QACfC,cAAc;QACdC,OAAO;IACT;IACAC,aAAaf;IACbgB,OAAOzB,EAAE0B,MAAM,CAAC;QACdC,MAAM3B,EACH4B,MAAM,CAAC5B,EAAE6B,MAAM,IAAI7B,EAAE8B,OAAO,IAC5BC,QAAQ,CACP;QAEJC,OAAOhC,EACJiC,MAAM,GACNC,GAAG,GACHC,GAAG,CAAC,G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B;gBAAEA;YAAe,IAAI,CAAC,CAAC;YAC5C,GAAIE,SAAS;gBAAEA,QAAQA;YAAqB,IAAI,CAAC,CAAC;QACpD;QAEAK,OAAOC,IAAI,CAAC,CAAC,iCAAiC,EAAEjC,eAAe,UAAU,EAAEuC,OAAOG,EAAE,EAAE;QAEtF,OAAO;YACLC,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,6CAA6C,EAAE7C,eAAe,mCAAmC,EAAE8C,KAAKC,SAAS,CAACR,QAAQ,QAAQ,CAAC;gBAC5I;aACD;YACDS,KAAKT;QACP;IACF,EAAE,OAAOU,OAAO;QACd,MAAMC,eAAeD,iBAAiBE,QAAQF,MAAMG,OAAO,GAAG;QAC9DpB,OAAOiB,KAAK,CAAC,CAAC,2BAA2B,EAAEjD,eAAe,EAAE,EAAEkD,cAAc;QAC5E,OAAO1D,sBAAsB;YAAE6D,QAAQ;YAAYrD;YAAgBiD;YAAOnB;QAAI;IAChF;AACF,GAAE"}
@@ -1,2 +1,2 @@
1
- export declare const deleteCollectionTool: import("../../../types.js").CollectionTool;
1
+ export declare const deleteDocumentsTool: import("../../../types.js").CollectionTool;
2
2
  //# sourceMappingURL=deleteTool.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"deleteTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/deleteTool.ts"],"names":[],"mappings":"AAQA,eAAO,MAAM,oBAAoB,4CAkH/B,CAAA"}
1
+ {"version":3,"file":"deleteTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/deleteTool.ts"],"names":[],"mappings":"AAUA,eAAO,MAAM,mBAAmB,4CAkH9B,CAAA"}
@@ -1,9 +1,18 @@
1
1
  import { z } from 'zod';
2
+ import { defaultAccess } from '../../../defaultAccess.js';
2
3
  import { defineCollectionTool } from '../../../defineTool.js';
3
4
  import { getLogger } from '../../../utils/getLogger.js';
4
- import { localAPIDefaults } from '../../../utils/localAPIDefaults.js';
5
- const DEFAULT_DESCRIPTION = 'Delete documents in a collection by ID or where clause.';
6
- export const deleteCollectionTool = defineCollectionTool({
5
+ import { whereSchema } from '../../../utils/whereSchema.js';
6
+ const DEFAULT_DESCRIPTION = 'Delete documents in any collection by passing the collection slug and ID or where clause.';
7
+ export const deleteDocumentsTool = defineCollectionTool({
8
+ access: (args)=>defaultAccess(args) && Boolean(args.permissions?.collections?.[args.collectionSlug]?.delete),
9
+ annotations: {
10
+ destructiveHint: true,
11
+ idempotentHint: false,
12
+ openWorldHint: false,
13
+ readOnlyHint: false,
14
+ title: 'Delete Documents'
15
+ },
7
16
  description: DEFAULT_DESCRIPTION,
8
17
  input: z.object({
9
18
  id: z.union([
@@ -13,7 +22,7 @@ export const deleteCollectionTool = defineCollectionTool({
13
22
  depth: z.number().int().min(0).max(10).describe('Depth of population for relationships in response').optional().default(0),
14
23
  fallbackLocale: z.string().describe('Optional: fallback locale code to use when requested locale is not available').optional(),
15
24
  locale: z.string().describe('Optional: locale code for the operation (e.g., "en", "es"). Defaults to the default locale').optional(),
16
- where: z.string().describe('Optional: JSON string for where clause to delete multiple documents').optional()
25
+ where: whereSchema.describe('Optional: where clause to delete multiple documents. Use field names with Payload operators, and/or arrays for grouping. Example: {"title":{"contains":"test"}}').optional()
17
26
  })
18
27
  }).handler(async ({ authorizedMCP, collectionSlug, input, req })=>{
19
28
  const payload = req.payload;
@@ -33,27 +42,11 @@ export const deleteCollectionTool = defineCollectionTool({
33
42
  ]
34
43
  };
35
44
  }
36
- let whereClause = {};
37
- if (where) {
38
- try {
39
- whereClause = JSON.parse(where);
40
- } catch {
41
- logger.warn(`Invalid where clause JSON: ${where}`);
42
- return {
43
- content: [
44
- {
45
- type: 'text',
46
- text: 'Error: Invalid JSON in where clause'
47
- }
48
- ]
49
- };
50
- }
51
- }
52
45
  const deleteOptions = {
53
46
  collection: collectionSlug,
54
47
  depth,
48
+ overrideAccess: authorizedMCP.overrideAccess,
55
49
  req,
56
- ...localAPIDefaults(authorizedMCP),
57
50
  ...locale && {
58
51
  locale
59
52
  },
@@ -64,7 +57,7 @@ export const deleteCollectionTool = defineCollectionTool({
64
57
  if (id) {
65
58
  deleteOptions.id = id;
66
59
  } else {
67
- deleteOptions.where = whereClause;
60
+ deleteOptions.where = where;
68
61
  }
69
62
  const result = await payload.delete(deleteOptions);
70
63
  if (id) {