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

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 (151) hide show
  1. package/dist/endpoint/access.js +2 -2
  2. package/dist/endpoint/access.js.map +1 -1
  3. package/dist/mcp/buildMcpServer.d.ts +1 -1
  4. package/dist/mcp/buildMcpServer.d.ts.map +1 -1
  5. package/dist/mcp/buildMcpServer.js +35 -23
  6. package/dist/mcp/buildMcpServer.js.map +1 -1
  7. package/dist/mcp/builtin/collections/authTools.d.ts.map +1 -1
  8. package/dist/mcp/builtin/collections/authTools.js +79 -56
  9. package/dist/mcp/builtin/collections/authTools.js.map +1 -1
  10. package/dist/mcp/builtin/collections/countTool.d.ts.map +1 -1
  11. package/dist/mcp/builtin/collections/countTool.js +9 -14
  12. package/dist/mcp/builtin/collections/countTool.js.map +1 -1
  13. package/dist/mcp/builtin/collections/countVersionsTool.d.ts.map +1 -1
  14. package/dist/mcp/builtin/collections/countVersionsTool.js +9 -13
  15. package/dist/mcp/builtin/collections/countVersionsTool.js.map +1 -1
  16. package/dist/mcp/builtin/collections/createTool.d.ts.map +1 -1
  17. package/dist/mcp/builtin/collections/createTool.js +20 -28
  18. package/dist/mcp/builtin/collections/createTool.js.map +1 -1
  19. package/dist/mcp/builtin/collections/deleteTool.d.ts.map +1 -1
  20. package/dist/mcp/builtin/collections/deleteTool.js +40 -43
  21. package/dist/mcp/builtin/collections/deleteTool.js.map +1 -1
  22. package/dist/mcp/builtin/collections/duplicateTool.d.ts.map +1 -1
  23. package/dist/mcp/builtin/collections/duplicateTool.js +15 -34
  24. package/dist/mcp/builtin/collections/duplicateTool.js.map +1 -1
  25. package/dist/mcp/builtin/collections/fileInput.d.ts +21 -21
  26. package/dist/mcp/builtin/collections/fileInput.d.ts.map +1 -1
  27. package/dist/mcp/builtin/collections/fileInput.js +19 -20
  28. package/dist/mcp/builtin/collections/fileInput.js.map +1 -1
  29. package/dist/mcp/builtin/collections/fileInput.spec.js +2 -2
  30. package/dist/mcp/builtin/collections/fileInput.spec.js.map +1 -1
  31. package/dist/mcp/builtin/collections/findDistinctTool.d.ts.map +1 -1
  32. package/dist/mcp/builtin/collections/findDistinctTool.js +11 -26
  33. package/dist/mcp/builtin/collections/findDistinctTool.js.map +1 -1
  34. package/dist/mcp/builtin/collections/findTool.d.ts.map +1 -1
  35. package/dist/mcp/builtin/collections/findTool.js +21 -43
  36. package/dist/mcp/builtin/collections/findTool.js.map +1 -1
  37. package/dist/mcp/builtin/collections/findVersionByIDTool.d.ts.map +1 -1
  38. package/dist/mcp/builtin/collections/findVersionByIDTool.js +17 -26
  39. package/dist/mcp/builtin/collections/findVersionByIDTool.js.map +1 -1
  40. package/dist/mcp/builtin/collections/findVersionsTool.d.ts.map +1 -1
  41. package/dist/mcp/builtin/collections/findVersionsTool.js +16 -30
  42. package/dist/mcp/builtin/collections/findVersionsTool.js.map +1 -1
  43. package/dist/mcp/builtin/collections/formatCollectionError.d.ts +2 -2
  44. package/dist/mcp/builtin/collections/formatCollectionError.d.ts.map +1 -1
  45. package/dist/mcp/builtin/collections/formatCollectionError.js +6 -6
  46. package/dist/mcp/builtin/collections/formatCollectionError.js.map +1 -1
  47. package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -1
  48. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +12 -12
  49. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -1
  50. package/dist/mcp/builtin/collections/restoreVersionTool.d.ts.map +1 -1
  51. package/dist/mcp/builtin/collections/restoreVersionTool.js +14 -26
  52. package/dist/mcp/builtin/collections/restoreVersionTool.js.map +1 -1
  53. package/dist/mcp/builtin/collections/updateTool.d.ts.map +1 -1
  54. package/dist/mcp/builtin/collections/updateTool.js +35 -77
  55. package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
  56. package/dist/mcp/builtin/collections/uploadInstructionsTool.js +11 -11
  57. package/dist/mcp/builtin/collections/uploadInstructionsTool.js.map +1 -1
  58. package/dist/mcp/builtin/getConfigInfoTool.d.ts.map +1 -1
  59. package/dist/mcp/builtin/getConfigInfoTool.js +3 -2
  60. package/dist/mcp/builtin/getConfigInfoTool.js.map +1 -1
  61. package/dist/mcp/builtin/globals/countVersionsTool.d.ts.map +1 -1
  62. package/dist/mcp/builtin/globals/countVersionsTool.js +9 -13
  63. package/dist/mcp/builtin/globals/countVersionsTool.js.map +1 -1
  64. package/dist/mcp/builtin/globals/findTool.d.ts.map +1 -1
  65. package/dist/mcp/builtin/globals/findTool.js +10 -16
  66. package/dist/mcp/builtin/globals/findTool.js.map +1 -1
  67. package/dist/mcp/builtin/globals/findVersionByIDTool.d.ts.map +1 -1
  68. package/dist/mcp/builtin/globals/findVersionByIDTool.js +13 -24
  69. package/dist/mcp/builtin/globals/findVersionByIDTool.js.map +1 -1
  70. package/dist/mcp/builtin/globals/findVersionsTool.d.ts.map +1 -1
  71. package/dist/mcp/builtin/globals/findVersionsTool.js +13 -29
  72. package/dist/mcp/builtin/globals/findVersionsTool.js.map +1 -1
  73. package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts.map +1 -1
  74. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js +11 -11
  75. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js.map +1 -1
  76. package/dist/mcp/builtin/globals/restoreVersionTool.d.ts.map +1 -1
  77. package/dist/mcp/builtin/globals/restoreVersionTool.js +15 -22
  78. package/dist/mcp/builtin/globals/restoreVersionTool.js.map +1 -1
  79. package/dist/mcp/builtin/globals/updateTool.d.ts.map +1 -1
  80. package/dist/mcp/builtin/globals/updateTool.js +18 -23
  81. package/dist/mcp/builtin/globals/updateTool.js.map +1 -1
  82. package/dist/mcp/builtin/validateEntityData.d.ts +4 -4
  83. package/dist/mcp/builtin/validateEntityData.d.ts.map +1 -1
  84. package/dist/mcp/builtin/validateEntityData.js +7 -7
  85. package/dist/mcp/builtin/validateEntityData.js.map +1 -1
  86. package/dist/types.d.ts +4 -4
  87. package/dist/types.d.ts.map +1 -1
  88. package/dist/types.js.map +1 -1
  89. package/package.json +4 -6
  90. package/src/endpoint/access.ts +2 -3
  91. package/src/mcp/buildMcpServer.ts +39 -29
  92. package/src/mcp/builtin/collections/authTools.ts +77 -69
  93. package/src/mcp/builtin/collections/countTool.ts +9 -21
  94. package/src/mcp/builtin/collections/countVersionsTool.ts +9 -18
  95. package/src/mcp/builtin/collections/createTool.ts +25 -69
  96. package/src/mcp/builtin/collections/deleteTool.ts +36 -64
  97. package/src/mcp/builtin/collections/duplicateTool.ts +21 -83
  98. package/src/mcp/builtin/collections/fileInput.spec.ts +2 -2
  99. package/src/mcp/builtin/collections/fileInput.ts +30 -25
  100. package/src/mcp/builtin/collections/findDistinctTool.ts +11 -63
  101. package/src/mcp/builtin/collections/findTool.ts +21 -103
  102. package/src/mcp/builtin/collections/findVersionByIDTool.ts +15 -58
  103. package/src/mcp/builtin/collections/findVersionsTool.ts +14 -85
  104. package/src/mcp/builtin/collections/formatCollectionError.ts +8 -8
  105. package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +11 -11
  106. package/src/mcp/builtin/collections/restoreVersionTool.ts +14 -56
  107. package/src/mcp/builtin/collections/updateTool.ts +45 -99
  108. package/src/mcp/builtin/collections/uploadInstructionsTool.ts +12 -12
  109. package/src/mcp/builtin/getConfigInfoTool.ts +2 -1
  110. package/src/mcp/builtin/globals/countVersionsTool.ts +9 -17
  111. package/src/mcp/builtin/globals/findTool.ts +12 -51
  112. package/src/mcp/builtin/globals/findVersionByIDTool.ts +13 -52
  113. package/src/mcp/builtin/globals/findVersionsTool.ts +14 -92
  114. package/src/mcp/builtin/globals/getGlobalSchemaTool.ts +10 -10
  115. package/src/mcp/builtin/globals/restoreVersionTool.ts +14 -45
  116. package/src/mcp/builtin/globals/updateTool.ts +34 -52
  117. package/src/mcp/builtin/validateEntityData.ts +10 -13
  118. package/src/types.ts +4 -4
  119. package/dist/utils/getVirtualFieldNames.d.ts +0 -14
  120. package/dist/utils/getVirtualFieldNames.d.ts.map +0 -1
  121. package/dist/utils/getVirtualFieldNames.js +0 -35
  122. package/dist/utils/getVirtualFieldNames.js.map +0 -1
  123. package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts +0 -28
  124. package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts.map +0 -1
  125. package/dist/utils/schemaConversion/filterFieldsByAccess.js +0 -71
  126. package/dist/utils/schemaConversion/filterFieldsByAccess.js.map +0 -1
  127. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts +0 -13
  128. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts.map +0 -1
  129. package/dist/utils/schemaConversion/getEntityInputSchema.js +0 -66
  130. package/dist/utils/schemaConversion/getEntityInputSchema.js.map +0 -1
  131. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts +0 -10
  132. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts.map +0 -1
  133. package/dist/utils/schemaConversion/sanitizeEntitySchema.js +0 -384
  134. package/dist/utils/schemaConversion/sanitizeEntitySchema.js.map +0 -1
  135. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js +0 -133
  136. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js.map +0 -1
  137. package/dist/utils/transformPointDataToPayload.d.ts +0 -7
  138. package/dist/utils/transformPointDataToPayload.d.ts.map +0 -1
  139. package/dist/utils/transformPointDataToPayload.js +0 -28
  140. package/dist/utils/transformPointDataToPayload.js.map +0 -1
  141. package/dist/utils/whereSchema.d.ts +0 -9
  142. package/dist/utils/whereSchema.d.ts.map +0 -1
  143. package/dist/utils/whereSchema.js +0 -13
  144. package/dist/utils/whereSchema.js.map +0 -1
  145. package/src/utils/getVirtualFieldNames.ts +0 -53
  146. package/src/utils/schemaConversion/filterFieldsByAccess.ts +0 -123
  147. package/src/utils/schemaConversion/getEntityInputSchema.ts +0 -96
  148. package/src/utils/schemaConversion/sanitizeEntitySchema.spec.ts +0 -96
  149. package/src/utils/schemaConversion/sanitizeEntitySchema.ts +0 -432
  150. package/src/utils/transformPointDataToPayload.ts +0 -40
  151. package/src/utils/whereSchema.ts +0 -24
@@ -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 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,oBAA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oBACNC,MAAM,CAAC,mDAAmD,EAAEJ,eAAe,cAAc,EAAEwB,SAAS,YAAY,UAAU;gBAC5H;aACD;YACDI,KAAK;gBAAEJ;YAAO;QAChB;IACF,EAAE,OAAOK,OAAO;QACd,MAAMC,eAAeD,iBAAiBE,QAAQF,MAAM5B,OAAO,GAAG;QAC9DmB,OAAOS,KAAK,CAAC,CAAC,wBAAwB,EAAE7B,eAAe,EAAE,EAAE8B,cAAc;QACzE,OAAOhC,UAAU,UAAU;YAAEE;YAAgBC,SAAS6B;QAAa;IACrE;AACF,GAAE"}
1
+ {"version":3,"sources":["../../../../src/mcp/builtin/collections/authTools.ts"],"sourcesContent":["import { createLocalReq, strictObject, z } from 'payload'\n\nimport type { MCPToolResponse } from '../../../types.js'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\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.email().check(z.describe('The user email address.'))\n\nconst wrapError =\n (name: string) =>\n ({ slug, message }: { message: string; slug: string }): MCPToolResponse => {\n return {\n content: [\n {\n type: 'text',\n text: `❌ **Error in ${name}** on ${slug}: ${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: strictObject({\n headers: z\n .optional(z.record(z.string(), z.string()))\n .check(z.describe('Custom headers to send with the authentication request.')),\n }),\n}).handler(async ({ slug, authorizedMCP, 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 authReq = await createLocalReq({ req: { headers: authHeaders } }, req.payload)\n const result = await req.payload.auth({ headers: authHeaders, req: authReq })\n\n if (result.user) {\n const authenticatedUser = result.user\n // Auth strategies read users with trusted Local API access. Re-read the user with the MCP\n // caller's access level before returning it to the client.\n const user = await req.payload.findByID({\n id: authenticatedUser.id,\n collection: authenticatedUser.collection,\n overrideAccess: authorizedMCP.overrideAccess,\n req: authReq,\n })\n result.user = {\n ...user,\n _sid: authenticatedUser._sid,\n _strategy: authenticatedUser._strategy,\n collection: authenticatedUser.collection,\n }\n }\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 ${slug}: ${errorMessage}`)\n return wrapError('auth')({ slug, 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: strictObject({\n email: emailSchema,\n }),\n}).handler(async ({ slug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n await req.payload.forgotPassword({\n collection: slug,\n data: { email: input.email },\n disableEmail: false,\n overrideAccess: false,\n req,\n })\n return {\n content: [\n {\n type: 'text',\n text: 'If an account matches that email, password reset instructions have been sent.',\n },\n ],\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error in forgotPassword tool on ${slug}: ${errorMessage}`)\n return wrapError('forgotPassword')({ slug, 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: strictObject({\n depth: z\n ._default(z.int().check(z.minimum(0), z.maximum(10)), 0)\n .check(z.describe('Depth of population for relationships.')),\n email: emailSchema,\n password: z.string().check(z.describe('The user password.')),\n }),\n}).handler(async ({ slug, authorizedMCP, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.login({\n collection: slug,\n data: { email: input.email, password: input.password },\n depth: input.depth,\n overrideAccess: authorizedMCP.overrideAccess,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Login Successful\\n\\n**User:** ${input.email}\\n**Collection:** ${slug}\\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 ${slug}: ${errorMessage}`)\n return wrapError('login')({ slug, 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: strictObject({\n password: z.string().check(z.describe('The new password for the user.')),\n token: z.string().check(z.describe('The password reset token sent to the user email.')),\n }),\n}).handler(async ({ slug, authorizedMCP, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.resetPassword({\n collection: slug,\n data: { password: input.password, token: input.token },\n overrideAccess: authorizedMCP.overrideAccess,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Password Reset Successful\\n\\n**Collection:** ${slug}\\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 ${slug}: ${errorMessage}`)\n return wrapError('resetPassword')({ slug, message: errorMessage })\n }\n})\n\nexport const unlockCollectionTool = defineCollectionTool({\n access: (args) =>\n defaultAccess(args) && Boolean(args.permissions?.collections?.[args.slug]?.unlock),\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: strictObject({ email: emailSchema }),\n}).handler(async ({ slug, authorizedMCP, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.unlock({\n collection: slug,\n data: { email: input.email },\n overrideAccess: authorizedMCP.overrideAccess,\n req,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Account Unlocked\\n\\n**Collection:** ${slug}\\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 ${slug}: ${errorMessage}`)\n return wrapError('unlock')({ slug, 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: strictObject({\n token: z.string().check(z.describe('The verification token sent to the user email.')),\n }),\n}).handler(async ({ slug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.verifyEmail({\n collection: slug,\n token: input.token,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Email Verification Successful\\n\\n**Collection:** ${slug}\\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 ${slug}: ${errorMessage}`)\n return wrapError('verify')({ slug, message: errorMessage })\n }\n})\n"],"names":["createLocalReq","strictObject","z","defaultAccess","defineCollectionTool","getLogger","emailSchema","email","check","describe","wrapError","name","slug","message","content","type","text","authCollectionTool","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","headers","optional","record","string","handler","authorizedMCP","req","logger","payload","authHeaders","Headers","authReq","result","auth","user","authenticatedUser","findByID","id","collection","overrideAccess","_sid","_strategy","JSON","stringify","doc","error","errorMessage","Error","forgotPasswordCollectionTool","forgotPassword","data","disableEmail","loginCollectionTool","depth","_default","int","minimum","maximum","password","login","resetPasswordCollectionTool","token","resetPassword","unlockCollectionTool","access","args","Boolean","permissions","collections","unlock","verifyCollectionTool","verifyEmail"],"mappings":"AAAA,SAASA,cAAc,EAAEC,YAAY,EAAEC,CAAC,QAAQ,UAAS;AAIzD,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AAEvD;;;;;;;;;CASC,GAED,MAAMC,cAAcJ,EAAEK,KAAK,GAAGC,KAAK,CAACN,EAAEO,QAAQ,CAAC;AAE/C,MAAMC,YACJ,CAACC,OACD,CAAC,EAAEC,IAAI,EAAEC,OAAO,EAAqC;QACnD,OAAO;YACLC,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,aAAa,EAAEL,KAAK,MAAM,EAAEC,KAAK,EAAE,EAAEC,SAAS;gBACvD;aACD;QACH;IACF;AAEF,OAAO,MAAMI,qBAAqBb,qBAAqB;IACrDc,aAAa;QACXC,iBAAiB;QACjBC,gBAAgB;QAChBC,eAAe;QACfC,cAAc;QACdC,OAAO;IACT;IACAC,aAAa;IACbC,OAAOxB,aAAa;QAClByB,SAASxB,EACNyB,QAAQ,CAACzB,EAAE0B,MAAM,CAAC1B,EAAE2B,MAAM,IAAI3B,EAAE2B,MAAM,KACtCrB,KAAK,CAACN,EAAEO,QAAQ,CAAC;IACtB;AACF,GAAGqB,OAAO,CAAC,OAAO,EAAElB,IAAI,EA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DoB,OAAOkB,KAAK,CAAC,CAAC,wBAAwB,EAAEvC,KAAK,EAAE,EAAEwC,cAAc;QAC/D,OAAO1C,UAAU,UAAU;YAAEE;YAAMC,SAASuC;QAAa;IAC3D;AACF,GAAE"}
@@ -1 +1 @@
1
- {"version":3,"file":"countTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/countTool.ts"],"names":[],"mappings":"AAUA,eAAO,MAAM,kBAAkB,4CA8D7B,CAAA"}
1
+ {"version":3,"file":"countTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/countTool.ts"],"names":[],"mappings":"AASA,eAAO,MAAM,kBAAkB,4CAmD7B,CAAA"}
@@ -1,11 +1,10 @@
1
- import { z } from 'zod';
1
+ import { countDocumentsInputSchema } from 'payload';
2
2
  import { defaultAccess } from '../../../defaultAccess.js';
3
3
  import { defineCollectionTool } from '../../../defineTool.js';
4
4
  import { getLogger } from '../../../utils/getLogger.js';
5
- import { whereSchema } from '../../../utils/whereSchema.js';
6
5
  const DEFAULT_DESCRIPTION = 'Count documents in any collection by passing the collection slug and optional where clause.';
7
6
  export const countDocumentsTool = defineCollectionTool({
8
- access: (args)=>defaultAccess(args) && Boolean(args.permissions?.collections?.[args.collectionSlug]?.read),
7
+ access: (args)=>defaultAccess(args) && Boolean(args.permissions?.collections?.[args.slug]?.read),
9
8
  annotations: {
10
9
  destructiveHint: false,
11
10
  idempotentHint: true,
@@ -14,21 +13,17 @@ export const countDocumentsTool = defineCollectionTool({
14
13
  title: 'Count Documents'
15
14
  },
16
15
  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 })=>{
16
+ input: countDocumentsInputSchema
17
+ }).handler(async ({ slug, authorizedMCP, input, req })=>{
23
18
  const payload = req.payload;
24
19
  const logger = getLogger({
25
20
  payload
26
21
  });
27
22
  const { locale, trash, where } = input;
28
- logger.info(`Counting documents in collection: ${collectionSlug}`);
23
+ logger.info(`Counting documents in collection: ${slug}`);
29
24
  try {
30
25
  const result = await payload.count({
31
- collection: collectionSlug,
26
+ collection: slug,
32
27
  overrideAccess: authorizedMCP.overrideAccess,
33
28
  req,
34
29
  ...locale ? {
@@ -45,19 +40,19 @@ export const countDocumentsTool = defineCollectionTool({
45
40
  content: [
46
41
  {
47
42
  type: 'text',
48
- text: `Collection "${collectionSlug}" contains ${result.totalDocs} matching documents.\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``
43
+ text: `Collection "${slug}" contains ${result.totalDocs} matching documents.\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``
49
44
  }
50
45
  ],
51
46
  doc: result
52
47
  };
53
48
  } catch (error) {
54
49
  const errorMessage = error instanceof Error ? error.message : 'Unknown error';
55
- logger.error(`Error counting documents in ${collectionSlug}: ${errorMessage}`);
50
+ logger.error(`Error counting documents in ${slug}: ${errorMessage}`);
56
51
  return {
57
52
  content: [
58
53
  {
59
54
  type: 'text',
60
- text: `❌ **Error counting documents in collection "${collectionSlug}":** ${errorMessage}`
55
+ text: `❌ **Error counting documents in collection "${slug}":** ${errorMessage}`
61
56
  }
62
57
  ],
63
58
  isError: true
@@ -1 +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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O;YACLY,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,YAAY,EAAE/B,eAAe,WAAW,EAAEwB,OAAOQ,SAAS,CAAC,kCAAkC,EAAEC,KAAKC,SAAS,CAACV,QAAQ,QAAQ,CAAC;gBACxI;aACD;YACDW,KAAKX;QACP;IACF,EAAE,OAAOY,OAAO;QACd,MAAMC,eAAeD,iBAAiBE,QAAQF,MAAMG,OAAO,GAAG;QAC9DjB,OAAOc,KAAK,CAAC,CAAC,4BAA4B,EAAEpC,eAAe,EAAE,EAAEqC,cAAc;QAC7E,OAAO;YACLR,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,4CAA4C,EAAE/B,eAAe,KAAK,EAAEqC,cAAc;gBAC3F;aACD;YACDG,SAAS;QACX;IACF;AACF,GAAE"}
1
+ {"version":3,"sources":["../../../../src/mcp/builtin/collections/countTool.ts"],"sourcesContent":["import { countDocumentsInputSchema } from 'payload'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.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.slug]?.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: countDocumentsInputSchema,\n}).handler(async ({ slug, authorizedMCP, 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: ${slug}`)\n\n try {\n const result = await payload.count({\n collection: slug,\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 \"${slug}\" 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 ${slug}: ${errorMessage}`)\n return {\n content: [\n {\n type: 'text',\n text: `❌ **Error counting documents in collection \"${slug}\":** ${errorMessage}`,\n },\n ],\n isError: true,\n }\n }\n})\n"],"names":["countDocumentsInputSchema","defaultAccess","defineCollectionTool","getLogger","DEFAULT_DESCRIPTION","countDocumentsTool","access","args","Boolean","permissions","collections","slug","read","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","handler","authorizedMCP","req","payload","logger","locale","trash","where","info","result","count","collection","overrideAccess","undefined","content","type","text","totalDocs","JSON","stringify","doc","error","errorMessage","Error","message","isError"],"mappings":"AAAA,SAASA,yBAAyB,QAAQ,UAAS;AAEnD,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AAEvD,MAAMC,sBACJ;AAEF,OAAO,MAAMC,qBAAqBH,qBAAqB;IACrDI,QAAQ,CAACC,OACPN,cAAcM,SAASC,QAAQD,KAAKE,WAAW,EAAEC,aAAa,CAACH,KAAKI,IAAI,CAAC,EAAEC;IAC7EC,aAAa;QACXC,iBAAiB;QACjBC,gBAAgB;QAChBC,eAAe;QACfC,cAAc;QACdC,OAAO;IACT;IACAC,aAAaf;IACbgB,OAAOpB;AACT,GAAGqB,OAAO,CAAC,OAAO,EAAEV,IAAI,EAAEW,aAAa,EAAEF,KAAK,EAAEG,GAAG,EAAE;IACnD,MAAMC,UAAUD,IAAIC,OAAO;IAC3B,MAAMC,SAAStB,UAAU;QAAEqB;IAAQ;IACnC,MAAM,EAAEE,MAAM,EAAEC,KAAK,EAAEC,KAAK,EAAE,GAAGR;IAEjCK,OAAOI,IAAI,CAAC,CAAC,kCAAkC,EAAElB,MAAM;IAEvD,IAAI;QACF,MAAMmB,SAAS,MAAMN,QAAQO,KAAK,CAAC;YACjCC,YAAYrB;YACZsB,gBAAgBX,cAAcW,cAAc;YAC5CV;YACA,GAAIG,SAAS;gBAAEA;YAAO,IAAI,CAAC,CAAC;YAC5B,GAAIC,UAAUO,YAAY;gBAAEP;YAAM,IAAI,CAAC,CAAC;YACxC,GAAIC,QAAQ;gBAAEA;YAAM,IAAI,CAAC,CAAC;QAC5B;QAEA,OAAO;YACLO,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,YAAY,EAAE1B,KAAK,WAAW,EAAEmB,OAAOQ,SAAS,CAAC,kCAAkC,EAAEC,KAAKC,SAAS,CAACV,QAAQ,QAAQ,CAAC;gBAC9H;aACD;YACDW,KAAKX;QACP;IACF,EAAE,OAAOY,OAAO;QACd,MAAMC,eAAeD,iBAAiBE,QAAQF,MAAMG,OAAO,GAAG;QAC9DpB,OAAOiB,KAAK,CAAC,CAAC,4BAA4B,EAAE/B,KAAK,EAAE,EAAEgC,cAAc;QACnE,OAAO;YACLR,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,4CAA4C,EAAE1B,KAAK,KAAK,EAAEgC,cAAc;gBACjF;aACD;YACDG,SAAS;QACX;IACF;AACF,GAAE"}
@@ -1 +1 @@
1
- {"version":3,"file":"countVersionsTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/countVersionsTool.ts"],"names":[],"mappings":"AAUA,eAAO,MAAM,iBAAiB,4CA0D5B,CAAA"}
1
+ {"version":3,"file":"countVersionsTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/countVersionsTool.ts"],"names":[],"mappings":"AASA,eAAO,MAAM,iBAAiB,4CAkD5B,CAAA"}
@@ -1,11 +1,10 @@
1
- import { z } from 'zod';
1
+ import { countVersionsInputSchema } from 'payload';
2
2
  import { defaultAccess } from '../../../defaultAccess.js';
3
3
  import { defineCollectionTool } from '../../../defineTool.js';
4
4
  import { getLogger } from '../../../utils/getLogger.js';
5
- import { whereSchema } from '../../../utils/whereSchema.js';
6
5
  const DEFAULT_DESCRIPTION = 'Count document versions in any version-enabled collection by passing the collection slug and optional where clause.';
7
6
  export const countVersionsTool = defineCollectionTool({
8
- access: (args)=>defaultAccess(args) && Boolean(args.permissions?.collections?.[args.collectionSlug]?.readVersions),
7
+ access: (args)=>defaultAccess(args) && Boolean(args.permissions?.collections?.[args.slug]?.readVersions),
9
8
  annotations: {
10
9
  destructiveHint: false,
11
10
  idempotentHint: true,
@@ -14,20 +13,17 @@ export const countVersionsTool = defineCollectionTool({
14
13
  title: 'Count Versions'
15
14
  },
16
15
  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 })=>{
16
+ input: countVersionsInputSchema
17
+ }).handler(async ({ slug, authorizedMCP, input, req })=>{
22
18
  const payload = req.payload;
23
19
  const logger = getLogger({
24
20
  payload
25
21
  });
26
22
  const { locale, where } = input;
27
- logger.info(`Counting versions in collection: ${collectionSlug}`);
23
+ logger.info(`Counting versions in collection: ${slug}`);
28
24
  try {
29
25
  const result = await payload.countVersions({
30
- collection: collectionSlug,
26
+ collection: slug,
31
27
  overrideAccess: authorizedMCP.overrideAccess,
32
28
  req,
33
29
  ...locale ? {
@@ -41,19 +37,19 @@ export const countVersionsTool = defineCollectionTool({
41
37
  content: [
42
38
  {
43
39
  type: 'text',
44
- text: `Collection "${collectionSlug}" contains ${result.totalDocs} matching versions.\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``
40
+ text: `Collection "${slug}" contains ${result.totalDocs} matching versions.\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``
45
41
  }
46
42
  ],
47
43
  doc: result
48
44
  };
49
45
  } catch (error) {
50
46
  const errorMessage = error instanceof Error ? error.message : 'Unknown error';
51
- logger.error(`Error counting versions in ${collectionSlug}: ${errorMessage}`);
47
+ logger.error(`Error counting versions in ${slug}: ${errorMessage}`);
52
48
  return {
53
49
  content: [
54
50
  {
55
51
  type: 'text',
56
- text: `❌ **Error counting versions in collection "${collectionSlug}":** ${errorMessage}`
52
+ text: `❌ **Error counting versions in collection "${slug}":** ${errorMessage}`
57
53
  }
58
54
  ],
59
55
  isError: true
@@ -1 +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
+ {"version":3,"sources":["../../../../src/mcp/builtin/collections/countVersionsTool.ts"],"sourcesContent":["import { countVersionsInputSchema } from 'payload'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.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) && Boolean(args.permissions?.collections?.[args.slug]?.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: countVersionsInputSchema,\n}).handler(async ({ slug, authorizedMCP, 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: ${slug}`)\n\n try {\n const result = await payload.countVersions({\n collection: slug,\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 \"${slug}\" 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 ${slug}: ${errorMessage}`)\n return {\n content: [\n {\n type: 'text',\n text: `❌ **Error counting versions in collection \"${slug}\":** ${errorMessage}`,\n },\n ],\n isError: true,\n }\n }\n})\n"],"names":["countVersionsInputSchema","defaultAccess","defineCollectionTool","getLogger","DEFAULT_DESCRIPTION","countVersionsTool","access","args","Boolean","permissions","collections","slug","readVersions","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","handler","authorizedMCP","req","payload","logger","locale","where","info","result","countVersions","collection","overrideAccess","content","type","text","totalDocs","JSON","stringify","doc","error","errorMessage","Error","message","isError"],"mappings":"AAAA,SAASA,wBAAwB,QAAQ,UAAS;AAElD,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AAEvD,MAAMC,sBACJ;AAEF,OAAO,MAAMC,oBAAoBH,qBAAqB;IACpDI,QAAQ,CAACC,OACPN,cAAcM,SAASC,QAAQD,KAAKE,WAAW,EAAEC,aAAa,CAACH,KAAKI,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"names":[],"mappings":"AAmBA,eAAO,MAAM,mBAAmB,4CAoJ9B,CAAA"}
1
+ {"version":3,"file":"createTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/createTool.ts"],"names":[],"mappings":"AAiBA,eAAO,MAAM,mBAAmB,4CA0G9B,CAAA"}
@@ -1,15 +1,13 @@
1
- import { z } from 'zod';
1
+ import { createDocumentsInputSchema, getCollectionVirtualFieldNames, stripVirtualFields, transformPointDataToPayload } from 'payload';
2
2
  import { defaultAccess } from '../../../defaultAccess.js';
3
3
  import { defineCollectionTool } from '../../../defineTool.js';
4
4
  import { getLogger } from '../../../utils/getLogger.js';
5
- import { getCollectionVirtualFieldNames, stripVirtualFields } from '../../../utils/getVirtualFieldNames.js';
6
- import { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js';
7
5
  import { validateCollectionData } from '../validateEntityData.js';
8
6
  import { fileInputSchema, resolveFile } from './fileInput.js';
9
7
  import { formatCollectionError } from './formatCollectionError.js';
10
8
  const DEFAULT_DESCRIPTION = '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.';
11
9
  export const createDocumentsTool = defineCollectionTool({
12
- access: (args)=>defaultAccess(args) && Boolean(args.permissions?.collections?.[args.collectionSlug]?.create),
10
+ access: (args)=>defaultAccess(args) && Boolean(args.permissions?.collections?.[args.slug]?.create),
13
11
  annotations: {
14
12
  destructiveHint: false,
15
13
  idempotentHint: false,
@@ -18,26 +16,18 @@ export const createDocumentsTool = defineCollectionTool({
18
16
  title: 'Create Documents'
19
17
  },
20
18
  description: DEFAULT_DESCRIPTION,
21
- input: z.object({
22
- depth: z.number().int().min(0).max(10).describe('How many levels deep to populate relationships in response').optional().default(0),
23
- documents: z.array(z.object({
24
- data: z.record(z.string(), z.unknown()).describe('The document fields to create. Only include fields permitted by the schema returned by getCollectionSchema.'),
25
- file: fileInputSchema.optional()
26
- })).min(1).describe('The documents to create, in order'),
27
- 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),
28
- fallbackLocale: z.string().describe('Optional: fallback locale code to use when requested locale is not available').optional(),
29
- locale: z.string().describe('Optional: locale code to create the documents in (e.g., "en", "es"). Defaults to the default locale').optional(),
30
- select: z.record(z.string(), z.unknown()).describe('Optional: define exactly which fields you\'d like to return, e.g., {"title": true}').optional()
19
+ input: createDocumentsInputSchema({
20
+ file: fileInputSchema
31
21
  })
32
- }).handler(async ({ authorizedMCP, collectionSlug, input, req })=>{
22
+ }).handler(async ({ slug, authorizedMCP, input, req })=>{
33
23
  const payload = req.payload;
34
24
  const logger = getLogger({
35
25
  payload
36
26
  });
37
- const { depth, documents, draft, fallbackLocale, locale, select } = input;
38
- logger.info(`Creating ${documents.length} documents in collection: ${collectionSlug}`);
27
+ const { depth, documents, draft, fallbackLocale, locale, populate, publishAllLocales, select } = input;
28
+ logger.info(`Creating ${documents.length} documents in collection: ${slug}`);
39
29
  try {
40
- const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, collectionSlug);
30
+ const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, slug);
41
31
  const docs = [];
42
32
  const errors = [];
43
33
  let validationSchema;
@@ -45,7 +35,7 @@ export const createDocumentsTool = defineCollectionTool({
45
35
  try {
46
36
  const inputData = stripVirtualFields(document.data, virtualFieldNames);
47
37
  const validationError = validateCollectionData({
48
- collectionSlug,
38
+ slug,
49
39
  data: inputData,
50
40
  req
51
41
  });
@@ -64,16 +54,18 @@ export const createDocumentsTool = defineCollectionTool({
64
54
  }
65
55
  const parsedData = transformPointDataToPayload(inputData);
66
56
  const file = await resolveFile({
67
- collectionSlug,
57
+ slug,
68
58
  input: document.file,
69
59
  req
70
60
  });
71
61
  const result = await payload.create({
72
- collection: collectionSlug,
62
+ collection: slug,
73
63
  data: parsedData,
74
64
  depth,
75
65
  draft,
76
66
  overrideAccess: authorizedMCP.overrideAccess,
67
+ populate,
68
+ publishAllLocales,
77
69
  req,
78
70
  ...file ? {
79
71
  file
@@ -81,11 +73,11 @@ export const createDocumentsTool = defineCollectionTool({
81
73
  ...locale ? {
82
74
  locale
83
75
  } : {},
84
- ...fallbackLocale ? {
76
+ ...fallbackLocale !== undefined ? {
85
77
  fallbackLocale
86
78
  } : {},
87
79
  ...select ? {
88
- select: select
80
+ select
89
81
  } : {}
90
82
  });
91
83
  docs.push({
@@ -94,7 +86,7 @@ export const createDocumentsTool = defineCollectionTool({
94
86
  });
95
87
  } catch (error) {
96
88
  const message = error instanceof Error ? error.message : 'Unknown error';
97
- logger.error(`Error creating document at index ${index} in ${collectionSlug}: ${message}`);
89
+ logger.error(`Error creating document at index ${index} in ${slug}: ${message}`);
98
90
  errors.push({
99
91
  index,
100
92
  message
@@ -111,12 +103,12 @@ export const createDocumentsTool = defineCollectionTool({
111
103
  ...batchResult,
112
104
  schema: validationSchema
113
105
  } : batchResult;
114
- logger.info(`Created ${docs.length} of ${documents.length} documents in ${collectionSlug}`);
106
+ logger.info(`Created ${docs.length} of ${documents.length} documents in ${slug}`);
115
107
  return {
116
108
  content: [
117
109
  {
118
110
  type: 'text',
119
- text: `Created ${docs.length} of ${documents.length} documents in collection "${collectionSlug}".${retryMessage}\nResults:\n\`\`\`json\n${JSON.stringify(batchResult)}\n\`\`\`${schemaMessage}`
111
+ text: `Created ${docs.length} of ${documents.length} documents in collection "${slug}".${retryMessage}\nResults:\n\`\`\`json\n${JSON.stringify(batchResult)}\n\`\`\`${schemaMessage}`
120
112
  }
121
113
  ],
122
114
  doc: structuredContent,
@@ -125,10 +117,10 @@ export const createDocumentsTool = defineCollectionTool({
125
117
  };
126
118
  } catch (error) {
127
119
  const message = error instanceof Error ? error.message : 'Unknown error';
128
- logger.error(`Error creating documents in ${collectionSlug}: ${message}`);
120
+ logger.error(`Error creating documents in ${slug}: ${message}`);
129
121
  return formatCollectionError({
122
+ slug,
130
123
  action: 'creating',
131
- collectionSlug,
132
124
  error,
133
125
  req
134
126
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/mcp/builtin/collections/createTool.ts"],"sourcesContent":["import type { SelectType } from 'payload'\n\nimport { z } from 'zod'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\nimport {\n getCollectionVirtualFieldNames,\n stripVirtualFields,\n} from '../../../utils/getVirtualFieldNames.js'\nimport { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'\nimport { validateCollectionData } from '../validateEntityData.js'\nimport { fileInputSchema, resolveFile } from './fileInput.js'\nimport { formatCollectionError } from './formatCollectionError.js'\n\nconst DEFAULT_DESCRIPTION =\n '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.'\n\nexport const createDocumentsTool = 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 Documents',\n },\n description: DEFAULT_DESCRIPTION,\n input: z.object({\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 documents: z\n .array(\n 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 file: fileInputSchema.optional(),\n }),\n )\n .min(1)\n .describe('The documents to create, in order'),\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 documents 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 const { depth, documents, draft, fallbackLocale, locale, select } = input\n\n logger.info(`Creating ${documents.length} documents in collection: ${collectionSlug}`)\n\n try {\n const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, collectionSlug)\n const docs: Array<{ doc: Record<string, unknown>; index: number }> = []\n const errors: Array<{ index: number; message: string }> = []\n let validationSchema: Record<string, unknown> | undefined\n\n for (const [index, document] of documents.entries()) {\n try {\n const inputData = stripVirtualFields(document.data, virtualFieldNames)\n const validationError = validateCollectionData({ collectionSlug, data: inputData, req })\n\n if (validationError) {\n const firstContent = validationError.content[0]\n const validationContent = validationError.structuredContent as\n | Record<string, unknown>\n | undefined\n const schema = validationContent?.schema\n\n if (!validationSchema && schema && typeof schema === 'object') {\n validationSchema = schema as Record<string, unknown>\n }\n\n errors.push({\n index,\n message:\n firstContent?.type === 'text'\n ? (firstContent.text.split('\\n\\nUse this schema')[0] ?? 'Invalid document data')\n : 'Invalid document data',\n })\n continue\n }\n\n const parsedData = transformPointDataToPayload(inputData)\n const file = await resolveFile({ collectionSlug, input: document.file, req })\n const result = await payload.create({\n collection: collectionSlug,\n data: parsedData,\n depth,\n draft,\n overrideAccess: authorizedMCP.overrideAccess,\n req,\n ...(file ? { file } : {}),\n ...(locale ? { locale } : {}),\n ...(fallbackLocale ? { fallbackLocale } : {}),\n ...(select ? { select: select as SelectType } : {}),\n })\n\n docs.push({ doc: result as Record<string, unknown>, index })\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error'\n\n logger.error(`Error creating document at index ${index} in ${collectionSlug}: ${message}`)\n errors.push({ index, message })\n }\n }\n\n const batchResult = { docs, errors }\n const retryMessage = errors.length > 0 ? '\\nRetry failed indexes only.' : ''\n const schemaMessage = validationSchema\n ? `\\n\\nUse this schema for data:\\n\\`\\`\\`json\\n${JSON.stringify(validationSchema)}\\n\\`\\`\\``\n : ''\n const structuredContent = validationSchema\n ? { ...batchResult, schema: validationSchema }\n : batchResult\n\n logger.info(`Created ${docs.length} of ${documents.length} documents in ${collectionSlug}`)\n\n return {\n content: [\n {\n type: 'text',\n text: `Created ${docs.length} of ${documents.length} documents in collection \"${collectionSlug}\".${retryMessage}\\nResults:\\n\\`\\`\\`json\\n${JSON.stringify(batchResult)}\\n\\`\\`\\`${schemaMessage}`,\n },\n ],\n doc: structuredContent as unknown as Record<string, unknown>,\n isError: docs.length === 0 && errors.length > 0,\n structuredContent,\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error'\n\n logger.error(`Error creating documents in ${collectionSlug}: ${message}`)\n return formatCollectionError({ action: 'creating', collectionSlug, error, req })\n }\n})\n"],"names":["z","defaultAccess","defineCollectionTool","getLogger","getCollectionVirtualFieldNames","stripVirtualFields","transformPointDataToPayload","validateCollectionData","fileInputSchema","resolveFile","formatCollectionError","DEFAULT_DESCRIPTION","createDocumentsTool","access","args","Boolean","permissions","collections","collectionSlug","create","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","object","depth","number","int","min","max","describe","optional","default","documents","array","data","record","string","unknown","file","draft","boolean","fallbackLocale","locale","select","handler","authorizedMCP","req","payload","logger","info","length","virtualFieldNames","config","docs","errors","validationSchema","index","document","entries","inputData","validationError","firstContent","content","validationContent","structuredContent","schema","push","message","type","text","split","parsedData","result","collection","overrideAccess","doc","error","Error","batchResult","retryMessage","schemaMessage","JSON","stringify","isError","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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AOJ,MAAM,GAAG;YAC9Cc;QACF;IACF,EAAE,OAAOY,OAAO;QACd,MAAMT,UAAUS,iBAAiBC,QAAQD,MAAMT,OAAO,GAAG;QAEzDnB,OAAO4B,KAAK,CAAC,CAAC,4BAA4B,EAAE/D,eAAe,EAAE,EAAEsD,SAAS;QACxE,OAAO9D,sBAAsB;YAAE+E,QAAQ;YAAYvE;YAAgB+D;YAAO9B;QAAI;IAChF;AACF,GAAE"}
1
+ {"version":3,"sources":["../../../../src/mcp/builtin/collections/createTool.ts"],"sourcesContent":["import {\n createDocumentsInputSchema,\n getCollectionVirtualFieldNames,\n stripVirtualFields,\n transformPointDataToPayload,\n} from 'payload'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\nimport { validateCollectionData } from '../validateEntityData.js'\nimport { fileInputSchema, resolveFile } from './fileInput.js'\nimport { formatCollectionError } from './formatCollectionError.js'\n\nconst DEFAULT_DESCRIPTION =\n '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.'\n\nexport const createDocumentsTool = defineCollectionTool({\n access: (args) =>\n defaultAccess(args) && Boolean(args.permissions?.collections?.[args.slug]?.create),\n annotations: {\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'Create Documents',\n },\n description: DEFAULT_DESCRIPTION,\n input: createDocumentsInputSchema({ file: fileInputSchema }),\n}).handler(async ({ slug, authorizedMCP, input, req }) => {\n const payload = req.payload\n const logger = getLogger({ payload })\n const { depth, documents, draft, fallbackLocale, locale, populate, publishAllLocales, select } =\n input\n\n logger.info(`Creating ${documents.length} documents in collection: ${slug}`)\n\n try {\n const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, slug)\n const docs: Array<{ doc: Record<string, unknown>; index: number }> = []\n const errors: Array<{ index: number; message: string }> = []\n let validationSchema: Record<string, unknown> | undefined\n\n for (const [index, document] of documents.entries()) {\n try {\n const inputData = stripVirtualFields(document.data, virtualFieldNames)\n const validationError = validateCollectionData({ slug, data: inputData, req })\n\n if (validationError) {\n const firstContent = validationError.content[0]\n const validationContent = validationError.structuredContent as\n | Record<string, unknown>\n | undefined\n const schema = validationContent?.schema\n\n if (!validationSchema && schema && typeof schema === 'object') {\n validationSchema = schema as Record<string, unknown>\n }\n\n errors.push({\n index,\n message:\n firstContent?.type === 'text'\n ? (firstContent.text.split('\\n\\nUse this schema')[0] ?? 'Invalid document data')\n : 'Invalid document data',\n })\n continue\n }\n\n const parsedData = transformPointDataToPayload(inputData)\n const file = await resolveFile({ slug, input: document.file, req })\n const result = await payload.create({\n collection: slug,\n data: parsedData,\n depth,\n draft,\n overrideAccess: authorizedMCP.overrideAccess,\n populate,\n publishAllLocales,\n req,\n ...(file ? { file } : {}),\n ...(locale ? { locale } : {}),\n ...(fallbackLocale !== undefined ? { fallbackLocale } : {}),\n ...(select ? { select } : {}),\n })\n\n docs.push({ doc: result as Record<string, unknown>, index })\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error'\n\n logger.error(`Error creating document at index ${index} in ${slug}: ${message}`)\n errors.push({ index, message })\n }\n }\n\n const batchResult = { docs, errors }\n const retryMessage = errors.length > 0 ? '\\nRetry failed indexes only.' : ''\n const schemaMessage = validationSchema\n ? `\\n\\nUse this schema for data:\\n\\`\\`\\`json\\n${JSON.stringify(validationSchema)}\\n\\`\\`\\``\n : ''\n const structuredContent = validationSchema\n ? { ...batchResult, schema: validationSchema }\n : batchResult\n\n logger.info(`Created ${docs.length} of ${documents.length} documents in ${slug}`)\n\n return {\n content: [\n {\n type: 'text',\n text: `Created ${docs.length} of ${documents.length} documents in collection \"${slug}\".${retryMessage}\\nResults:\\n\\`\\`\\`json\\n${JSON.stringify(batchResult)}\\n\\`\\`\\`${schemaMessage}`,\n },\n ],\n doc: structuredContent as unknown as Record<string, unknown>,\n isError: docs.length === 0 && errors.length > 0,\n structuredContent,\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error'\n\n logger.error(`Error creating documents in ${slug}: ${message}`)\n return formatCollectionError({ slug, action: 'creating', error, req })\n }\n})\n"],"names":["createDocumentsInputSchema","getCollectionVirtualFieldNames","stripVirtualFields","transformPointDataToPayload","defaultAccess","defineCollectionTool","getLogger","validateCollectionData","fileInputSchema","resolveFile","formatCollectionError","DEFAULT_DESCRIPTION","createDocumentsTool","access","args","Boolean","permissions","collections","slug","create","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","file","handler","authorizedMCP","req","payload","logger","depth","documents","draft","fallbackLocale","locale","populate","publishAllLocales","select","info","length","virtualFieldNames","config","docs","errors","validationSchema","index","document","entries","inputData","data","validationError","firstContent","content","validationContent","structuredContent","schema","push","message","type","text","split","parsedData","result","collection","overrideAccess","undefined","doc","error","Error","batchResult","retryMessage","schemaMessage","JSON","stringify","isError","action"],"mappings":"AAAA,SACEA,0BAA0B,EAC1BC,8BAA8B,EAC9BC,kBAAkB,EAClBC,2BAA2B,QACtB,UAAS;AAEhB,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AACvD,SAASC,sBAAsB,QAAQ,2BAA0B;AACjE,SAASC,eAAe,EAAEC,WAAW,QAAQ,iBAAgB;AAC7D,SAASC,qBAAqB,QAAQ,6BAA4B;AAElE,MAAMC,sBACJ;AAEF,OAAO,MAAMC,sBAAsBP,qBAAqB;IACtDQ,QAAQ,CAACC,OACPV,cAAcU,SAASC,QAAQD,KAAKE,WAAW,EAAEC,aAAa,CAACH,KAAKI,IAAI,CAAC,EAAEC;IAC7EC,aAAa;QACXC,iBAAiB;QACjBC,gBAAgB;QAChBC,eAAe;QACfC,cAAc;QACdC,OAAO;IACT;IACAC,aAAaf;IACbgB,OAAO3B,2BAA2B;QAAE4B,MAAMpB;IAAgB;AAC5D,GAAGqB,OAAO,CAAC,OAAO,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AA0B,EAAEzB,KAAK,EAAE,EAAEwD,aAAa,wBAAwB,EAAEE,KAAKC,SAAS,CAACJ,aAAa,QAAQ,EAAEE,eAAe;gBACvL;aACD;YACDL,KAAKZ;YACLoB,SAAShC,KAAKH,MAAM,KAAK,KAAKI,OAAOJ,MAAM,GAAG;YAC9Ce;QACF;IACF,EAAE,OAAOa,OAAO;QACd,MAAMV,UAAUU,iBAAiBC,QAAQD,MAAMV,OAAO,GAAG;QAEzD5B,OAAOsC,KAAK,CAAC,CAAC,4BAA4B,EAAErD,KAAK,EAAE,EAAE2C,SAAS;QAC9D,OAAOnD,sBAAsB;YAAEQ;YAAM6D,QAAQ;YAAYR;YAAOxC;QAAI;IACtE;AACF,GAAE"}
@@ -1 +1 @@
1
- {"version":3,"file":"deleteTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/deleteTool.ts"],"names":[],"mappings":"AAUA,eAAO,MAAM,mBAAmB,4CAkH9B,CAAA"}
1
+ {"version":3,"file":"deleteTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/deleteTool.ts"],"names":[],"mappings":"AASA,eAAO,MAAM,mBAAmB,4CAuF9B,CAAA"}
@@ -1,11 +1,10 @@
1
- import { z } from 'zod';
1
+ import { deleteDocumentsInputSchema } from 'payload';
2
2
  import { defaultAccess } from '../../../defaultAccess.js';
3
3
  import { defineCollectionTool } from '../../../defineTool.js';
4
4
  import { getLogger } from '../../../utils/getLogger.js';
5
- import { whereSchema } from '../../../utils/whereSchema.js';
6
5
  const DEFAULT_DESCRIPTION = 'Delete documents in any collection by passing the collection slug and ID or where clause.';
7
6
  export const deleteDocumentsTool = defineCollectionTool({
8
- access: (args)=>defaultAccess(args) && Boolean(args.permissions?.collections?.[args.collectionSlug]?.delete),
7
+ access: (args)=>defaultAccess(args) && Boolean(args.permissions?.collections?.[args.slug]?.delete),
9
8
  annotations: {
10
9
  destructiveHint: true,
11
10
  idempotentHint: false,
@@ -14,25 +13,40 @@ export const deleteDocumentsTool = defineCollectionTool({
14
13
  title: 'Delete Documents'
15
14
  },
16
15
  description: DEFAULT_DESCRIPTION,
17
- input: z.object({
18
- id: z.union([
19
- z.string(),
20
- z.number()
21
- ]).describe('Optional: specific document ID to delete').optional(),
22
- depth: z.number().int().min(0).max(10).describe('Depth of population for relationships in response').optional().default(0),
23
- fallbackLocale: z.string().describe('Optional: fallback locale code to use when requested locale is not available').optional(),
24
- locale: z.string().describe('Optional: locale code for the operation (e.g., "en", "es"). Defaults to the default locale').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()
26
- })
27
- }).handler(async ({ authorizedMCP, collectionSlug, input, req })=>{
16
+ input: deleteDocumentsInputSchema
17
+ }).handler(async ({ slug, authorizedMCP, input, req })=>{
28
18
  const payload = req.payload;
29
19
  const logger = getLogger({
30
20
  payload
31
21
  });
32
22
  const { id, depth, fallbackLocale, locale, where } = input;
33
- logger.info(`Deleting document from collection: ${collectionSlug}${id ? ` with ID: ${id}` : ' with where clause'}${locale ? `, locale: ${locale}` : ''}`);
23
+ logger.info(`Deleting document from collection: ${slug}${id ? ` with ID: ${id}` : ' with where clause'}${locale ? `, locale: ${locale}` : ''}`);
34
24
  try {
35
- if (!id && !where) {
25
+ if (id !== undefined) {
26
+ const result = await payload.delete({
27
+ id,
28
+ collection: slug,
29
+ depth,
30
+ overrideAccess: authorizedMCP.overrideAccess,
31
+ req,
32
+ ...locale && {
33
+ locale
34
+ },
35
+ ...fallbackLocale !== undefined && {
36
+ fallbackLocale
37
+ }
38
+ });
39
+ return {
40
+ content: [
41
+ {
42
+ type: 'text',
43
+ text: `Document deleted successfully from collection "${slug}"!\nDeleted document:\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``
44
+ }
45
+ ],
46
+ doc: result
47
+ };
48
+ }
49
+ if (where === undefined) {
36
50
  return {
37
51
  content: [
38
52
  {
@@ -42,39 +56,22 @@ export const deleteDocumentsTool = defineCollectionTool({
42
56
  ]
43
57
  };
44
58
  }
45
- const deleteOptions = {
46
- collection: collectionSlug,
59
+ const result = await payload.delete({
60
+ collection: slug,
47
61
  depth,
48
62
  overrideAccess: authorizedMCP.overrideAccess,
49
63
  req,
64
+ where,
50
65
  ...locale && {
51
66
  locale
52
67
  },
53
- ...fallbackLocale && {
68
+ ...fallbackLocale !== undefined && {
54
69
  fallbackLocale
55
70
  }
56
- };
57
- if (id) {
58
- deleteOptions.id = id;
59
- } else {
60
- deleteOptions.where = where;
61
- }
62
- const result = await payload.delete(deleteOptions);
63
- if (id) {
64
- return {
65
- content: [
66
- {
67
- type: 'text',
68
- text: `Document deleted successfully from collection "${collectionSlug}"!\nDeleted document:\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``
69
- }
70
- ],
71
- doc: result
72
- };
73
- }
74
- const bulkResult = result;
75
- const docs = bulkResult.docs || [];
76
- const errors = bulkResult.errors || [];
77
- let responseText = `Document deleted successfully from collection "${collectionSlug}"!\nDeleted: ${docs.length} documents\nErrors: ${errors.length}\n---`;
71
+ });
72
+ const docs = result.docs || [];
73
+ const errors = result.errors || [];
74
+ let responseText = `Document deleted successfully from collection "${slug}"!\nDeleted: ${docs.length} documents\nErrors: ${errors.length}\n---`;
78
75
  if (docs.length > 0) {
79
76
  responseText += `\n\nDeleted documents:\n\`\`\`json\n${JSON.stringify(docs)}\n\`\`\``;
80
77
  }
@@ -95,12 +92,12 @@ export const deleteDocumentsTool = defineCollectionTool({
95
92
  };
96
93
  } catch (error) {
97
94
  const errorMessage = error instanceof Error ? error.message : 'Unknown error';
98
- logger.error(`Error deleting document from ${collectionSlug}: ${errorMessage}`);
95
+ logger.error(`Error deleting document from ${slug}: ${errorMessage}`);
99
96
  return {
100
97
  content: [
101
98
  {
102
99
  type: 'text',
103
- text: `Error deleting document from collection "${collectionSlug}": ${errorMessage}`
100
+ text: `Error deleting document from collection "${slug}": ${errorMessage}`
104
101
  }
105
102
  ]
106
103
  };