@payloadcms/plugin-mcp 4.0.0-internal.4cbdd50 → 4.0.0-internal.4e1f822

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 (202) hide show
  1. package/LICENSE.md +1 -1
  2. package/bin.js +7 -0
  3. package/dist/defaultAccess.d.ts.map +1 -1
  4. package/dist/defineTool.d.ts +8 -8
  5. package/dist/defineTool.d.ts.map +1 -1
  6. package/dist/endpoint/access.d.ts +2 -7
  7. package/dist/endpoint/access.d.ts.map +1 -1
  8. package/dist/endpoint/access.js +6 -13
  9. package/dist/endpoint/access.js.map +1 -1
  10. package/dist/endpoint/index.d.ts +1 -1
  11. package/dist/endpoint/index.d.ts.map +1 -1
  12. package/dist/endpoint/index.js +57 -17
  13. package/dist/endpoint/index.js.map +1 -1
  14. package/dist/index.d.ts +2 -2
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +2 -2
  17. package/dist/index.js.map +1 -1
  18. package/dist/mcp/buildMcpServer.d.ts +5 -5
  19. package/dist/mcp/buildMcpServer.d.ts.map +1 -1
  20. package/dist/mcp/buildMcpServer.js +67 -33
  21. package/dist/mcp/buildMcpServer.js.map +1 -1
  22. package/dist/mcp/builtin/collections/authTools.d.ts.map +1 -1
  23. package/dist/mcp/builtin/collections/authTools.js +79 -56
  24. package/dist/mcp/builtin/collections/authTools.js.map +1 -1
  25. package/dist/mcp/builtin/collections/countTool.d.ts.map +1 -1
  26. package/dist/mcp/builtin/collections/countTool.js +10 -16
  27. package/dist/mcp/builtin/collections/countTool.js.map +1 -1
  28. package/dist/mcp/builtin/collections/countVersionsTool.d.ts.map +1 -1
  29. package/dist/mcp/builtin/collections/countVersionsTool.js +10 -15
  30. package/dist/mcp/builtin/collections/countVersionsTool.js.map +1 -1
  31. package/dist/mcp/builtin/collections/createTool.d.ts +1 -1
  32. package/dist/mcp/builtin/collections/createTool.d.ts.map +1 -1
  33. package/dist/mcp/builtin/collections/createTool.js +104 -54
  34. package/dist/mcp/builtin/collections/createTool.js.map +1 -1
  35. package/dist/mcp/builtin/collections/deleteTool.d.ts.map +1 -1
  36. package/dist/mcp/builtin/collections/deleteTool.js +41 -45
  37. package/dist/mcp/builtin/collections/deleteTool.js.map +1 -1
  38. package/dist/mcp/builtin/collections/duplicateTool.d.ts.map +1 -1
  39. package/dist/mcp/builtin/collections/duplicateTool.js +27 -38
  40. package/dist/mcp/builtin/collections/duplicateTool.js.map +1 -1
  41. package/dist/mcp/builtin/collections/fileInput.d.ts +28 -0
  42. package/dist/mcp/builtin/collections/fileInput.d.ts.map +1 -0
  43. package/dist/mcp/builtin/collections/fileInput.js +123 -0
  44. package/dist/mcp/builtin/collections/fileInput.js.map +1 -0
  45. package/dist/mcp/builtin/collections/fileInput.spec.js +86 -0
  46. package/dist/mcp/builtin/collections/fileInput.spec.js.map +1 -0
  47. package/dist/mcp/builtin/collections/findDistinctTool.d.ts.map +1 -1
  48. package/dist/mcp/builtin/collections/findDistinctTool.js +12 -28
  49. package/dist/mcp/builtin/collections/findDistinctTool.js.map +1 -1
  50. package/dist/mcp/builtin/collections/findTool.d.ts.map +1 -1
  51. package/dist/mcp/builtin/collections/findTool.js +23 -46
  52. package/dist/mcp/builtin/collections/findTool.js.map +1 -1
  53. package/dist/mcp/builtin/collections/findVersionByIDTool.d.ts.map +1 -1
  54. package/dist/mcp/builtin/collections/findVersionByIDTool.js +18 -28
  55. package/dist/mcp/builtin/collections/findVersionByIDTool.js.map +1 -1
  56. package/dist/mcp/builtin/collections/findVersionsTool.d.ts.map +1 -1
  57. package/dist/mcp/builtin/collections/findVersionsTool.js +17 -32
  58. package/dist/mcp/builtin/collections/findVersionsTool.js.map +1 -1
  59. package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -1
  60. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +51 -11
  61. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -1
  62. package/dist/mcp/builtin/collections/restoreVersionTool.d.ts.map +1 -1
  63. package/dist/mcp/builtin/collections/restoreVersionTool.js +15 -28
  64. package/dist/mcp/builtin/collections/restoreVersionTool.js.map +1 -1
  65. package/dist/mcp/builtin/collections/updateTool.d.ts.map +1 -1
  66. package/dist/mcp/builtin/collections/updateTool.js +62 -86
  67. package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
  68. package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts +2 -0
  69. package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts.map +1 -0
  70. package/dist/mcp/builtin/collections/uploadInstructionsTool.js +55 -0
  71. package/dist/mcp/builtin/collections/uploadInstructionsTool.js.map +1 -0
  72. package/dist/mcp/builtin/formatEntityError.d.ts +16 -0
  73. package/dist/mcp/builtin/formatEntityError.d.ts.map +1 -0
  74. package/dist/mcp/builtin/formatEntityError.js +55 -0
  75. package/dist/mcp/builtin/formatEntityError.js.map +1 -0
  76. package/dist/mcp/builtin/getConfigInfoTool.d.ts.map +1 -1
  77. package/dist/mcp/builtin/getConfigInfoTool.js +5 -7
  78. package/dist/mcp/builtin/getConfigInfoTool.js.map +1 -1
  79. package/dist/mcp/builtin/globals/countVersionsTool.d.ts.map +1 -1
  80. package/dist/mcp/builtin/globals/countVersionsTool.js +10 -15
  81. package/dist/mcp/builtin/globals/countVersionsTool.js.map +1 -1
  82. package/dist/mcp/builtin/globals/findTool.d.ts.map +1 -1
  83. package/dist/mcp/builtin/globals/findTool.js +12 -18
  84. package/dist/mcp/builtin/globals/findTool.js.map +1 -1
  85. package/dist/mcp/builtin/globals/findVersionByIDTool.d.ts.map +1 -1
  86. package/dist/mcp/builtin/globals/findVersionByIDTool.js +14 -26
  87. package/dist/mcp/builtin/globals/findVersionByIDTool.js.map +1 -1
  88. package/dist/mcp/builtin/globals/findVersionsTool.d.ts.map +1 -1
  89. package/dist/mcp/builtin/globals/findVersionsTool.js +14 -31
  90. package/dist/mcp/builtin/globals/findVersionsTool.js.map +1 -1
  91. package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts.map +1 -1
  92. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js +28 -10
  93. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js.map +1 -1
  94. package/dist/mcp/builtin/globals/restoreVersionTool.d.ts.map +1 -1
  95. package/dist/mcp/builtin/globals/restoreVersionTool.js +16 -24
  96. package/dist/mcp/builtin/globals/restoreVersionTool.js.map +1 -1
  97. package/dist/mcp/builtin/globals/updateTool.d.ts.map +1 -1
  98. package/dist/mcp/builtin/globals/updateTool.js +28 -37
  99. package/dist/mcp/builtin/globals/updateTool.js.map +1 -1
  100. package/dist/mcp/builtinTools.d.ts +6 -0
  101. package/dist/mcp/builtinTools.d.ts.map +1 -1
  102. package/dist/mcp/builtinTools.js +9 -3
  103. package/dist/mcp/builtinTools.js.map +1 -1
  104. package/dist/mcp/sanitizeMCPConfig.d.ts.map +1 -1
  105. package/dist/mcp/sanitizeMCPConfig.js +5 -1
  106. package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
  107. package/dist/stdio.d.ts +3 -4
  108. package/dist/stdio.d.ts.map +1 -1
  109. package/dist/stdio.js +61 -42
  110. package/dist/stdio.js.map +1 -1
  111. package/dist/types.d.ts +61 -13
  112. package/dist/types.d.ts.map +1 -1
  113. package/dist/types.js +2 -4
  114. package/dist/types.js.map +1 -1
  115. package/dist/utils/camelCase.d.ts.map +1 -1
  116. package/dist/utils/resolveProjectRoot.d.ts.map +1 -1
  117. package/dist/utils/toStandardSchema.d.ts.map +1 -1
  118. package/package.json +8 -12
  119. package/src/endpoint/access.ts +5 -13
  120. package/src/endpoint/index.ts +45 -16
  121. package/src/index.ts +4 -4
  122. package/src/mcp/buildMcpServer.ts +79 -49
  123. package/src/mcp/builtin/collections/authTools.ts +77 -69
  124. package/src/mcp/builtin/collections/countTool.ts +10 -23
  125. package/src/mcp/builtin/collections/countVersionsTool.ts +10 -20
  126. package/src/mcp/builtin/collections/createTool.ts +110 -77
  127. package/src/mcp/builtin/collections/deleteTool.ts +36 -65
  128. package/src/mcp/builtin/collections/duplicateTool.ts +34 -86
  129. package/src/mcp/builtin/collections/fileInput.spec.ts +93 -0
  130. package/src/mcp/builtin/collections/fileInput.ts +169 -0
  131. package/src/mcp/builtin/collections/findDistinctTool.ts +12 -65
  132. package/src/mcp/builtin/collections/findTool.ts +23 -106
  133. package/src/mcp/builtin/collections/findVersionByIDTool.ts +16 -60
  134. package/src/mcp/builtin/collections/findVersionsTool.ts +15 -87
  135. package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +48 -14
  136. package/src/mcp/builtin/collections/restoreVersionTool.ts +15 -58
  137. package/src/mcp/builtin/collections/updateTool.ts +61 -100
  138. package/src/mcp/builtin/collections/uploadInstructionsTool.ts +64 -0
  139. package/src/mcp/builtin/formatEntityError.ts +77 -0
  140. package/src/mcp/builtin/getConfigInfoTool.ts +4 -5
  141. package/src/mcp/builtin/globals/countVersionsTool.ts +10 -19
  142. package/src/mcp/builtin/globals/findTool.ts +14 -53
  143. package/src/mcp/builtin/globals/findVersionByIDTool.ts +14 -54
  144. package/src/mcp/builtin/globals/findVersionsTool.ts +15 -94
  145. package/src/mcp/builtin/globals/getGlobalSchemaTool.ts +30 -8
  146. package/src/mcp/builtin/globals/restoreVersionTool.ts +15 -47
  147. package/src/mcp/builtin/globals/updateTool.ts +39 -62
  148. package/src/mcp/builtinTools.ts +9 -2
  149. package/src/mcp/sanitizeMCPConfig.ts +5 -1
  150. package/src/stdio.ts +61 -43
  151. package/src/types.ts +61 -13
  152. package/dist/@types/assets.d.js +0 -2
  153. package/dist/@types/assets.d.js.map +0 -1
  154. package/dist/mcp/builtin/collections/formatCollectionError.d.ts +0 -9
  155. package/dist/mcp/builtin/collections/formatCollectionError.d.ts.map +0 -1
  156. package/dist/mcp/builtin/collections/formatCollectionError.js +0 -60
  157. package/dist/mcp/builtin/collections/formatCollectionError.js.map +0 -1
  158. package/dist/mcp/builtin/validateEntityData.d.ts +0 -14
  159. package/dist/mcp/builtin/validateEntityData.d.ts.map +0 -1
  160. package/dist/mcp/builtin/validateEntityData.js +0 -82
  161. package/dist/mcp/builtin/validateEntityData.js.map +0 -1
  162. package/dist/utils/getVirtualFieldNames.d.ts +0 -14
  163. package/dist/utils/getVirtualFieldNames.d.ts.map +0 -1
  164. package/dist/utils/getVirtualFieldNames.js +0 -35
  165. package/dist/utils/getVirtualFieldNames.js.map +0 -1
  166. package/dist/utils/localAPIDefaults.d.ts +0 -20
  167. package/dist/utils/localAPIDefaults.d.ts.map +0 -1
  168. package/dist/utils/localAPIDefaults.js +0 -19
  169. package/dist/utils/localAPIDefaults.js.map +0 -1
  170. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts +0 -11
  171. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts.map +0 -1
  172. package/dist/utils/schemaConversion/getEntityInputSchema.js +0 -34
  173. package/dist/utils/schemaConversion/getEntityInputSchema.js.map +0 -1
  174. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.d.ts +0 -7
  175. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.d.ts.map +0 -1
  176. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.js +0 -20
  177. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.js.map +0 -1
  178. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts +0 -15
  179. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts.map +0 -1
  180. package/dist/utils/schemaConversion/sanitizeEntitySchema.js +0 -464
  181. package/dist/utils/schemaConversion/sanitizeEntitySchema.js.map +0 -1
  182. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js +0 -158
  183. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js.map +0 -1
  184. package/dist/utils/transformPointDataToPayload.d.ts +0 -7
  185. package/dist/utils/transformPointDataToPayload.d.ts.map +0 -1
  186. package/dist/utils/transformPointDataToPayload.js +0 -28
  187. package/dist/utils/transformPointDataToPayload.js.map +0 -1
  188. package/dist/utils/whereSchema.d.ts +0 -9
  189. package/dist/utils/whereSchema.d.ts.map +0 -1
  190. package/dist/utils/whereSchema.js +0 -13
  191. package/dist/utils/whereSchema.js.map +0 -1
  192. package/src/@types/assets.d.ts +0 -3
  193. package/src/mcp/builtin/collections/formatCollectionError.ts +0 -84
  194. package/src/mcp/builtin/validateEntityData.ts +0 -132
  195. package/src/utils/getVirtualFieldNames.ts +0 -53
  196. package/src/utils/localAPIDefaults.ts +0 -22
  197. package/src/utils/schemaConversion/getEntityInputSchema.ts +0 -78
  198. package/src/utils/schemaConversion/removeVirtualFieldsFromSchema.ts +0 -27
  199. package/src/utils/schemaConversion/sanitizeEntitySchema.spec.ts +0 -103
  200. package/src/utils/schemaConversion/sanitizeEntitySchema.ts +0 -529
  201. package/src/utils/transformPointDataToPayload.ts +0 -40
  202. package/src/utils/whereSchema.ts +0 -24
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/mcp/buildMcpServer.ts"],"sourcesContent":["import { McpServer, type ServerContext } from '@modelcontextprotocol/server'\nimport { APIError, type PayloadRequest } from 'payload'\nimport { z } from 'zod'\n\nimport type {\n AuthorizedMCP,\n CollectionMCPItem,\n GlobalMCPItem,\n JsonSchemaType,\n MCPResponseOverride,\n MCPToolResponse,\n SanitizedMCPPluginConfig,\n ToolInputSchema,\n} from '../types.js'\n\nimport { getLogger } from '../utils/getLogger.js'\nimport { toStandardSchema } from '../utils/toStandardSchema.js'\n\n/**\n * Transport-agnostic core: registers every authorized MCP item onto a fresh\n * `McpServer` and returns it. The caller is responsible for picking a transport\n * (`WebStandardStreamableHTTPServerTransport`, `StdioServerTransport`, …) and\n * calling `server.connect(transport)`.\n *\n * `req` is the request context handlers see. For HTTP it's the live\n * `PayloadRequest` derived from the incoming HTTP request; for stdio it's a\n * synthesized one built via `createLocalReq`.\n */\nexport const buildMcpServer = ({\n authorizedMCP,\n pluginConfig,\n req,\n}: {\n authorizedMCP: AuthorizedMCP\n pluginConfig: SanitizedMCPPluginConfig\n req: PayloadRequest\n}): McpServer => {\n const serverOptions = pluginConfig.mcp?.serverOptions || {}\n const server = new McpServer(\n { name: 'Payload MCP Server', version: '1.0.0', ...serverOptions.serverInfo },\n serverOptions.options,\n )\n\n const logger = getLogger({ payload: req.payload })\n\n /**\n * Wrap a tool handler's response with the tool's `overrideResponse`, then\n * strip the internal `doc` field so it doesn't leak onto the wire.\n */\n const finalizeToolResponse = (\n response: MCPToolResponse,\n overrideResponse?: MCPResponseOverride,\n ): MCPToolResponse => {\n const overridden = overrideResponse?.(response, response.doc ?? {}, req) ?? response\n const { doc: _doc, ...rest } = overridden\n return rest\n }\n\n /**\n * Runs a collection/global tool call:\n * - reads `collectionSlug` / `globalSlug` from the input\n * - runs access control: errors if `authorizedMCP.items` has no entry for this tool + slug\n * - runs the tool handler and finalizes its response\n */\n const callEntityTool = async ({\n input,\n item,\n serverContext,\n }: {\n input: unknown\n item: CollectionMCPItem | GlobalMCPItem\n serverContext: ServerContext\n }): Promise<MCPToolResponse> => {\n const entity = item.type === 'collectionTool' ? 'collection' : 'global'\n const slugKey = item.type === 'collectionTool' ? 'collectionSlug' : 'globalSlug'\n const toolInput = (input ?? {}) as Record<string, unknown>\n const slug = toolInput[slugKey] as string | undefined\n\n if (!slug) {\n return {\n content: [\n {\n type: 'text',\n text: `Error: \"${item.mcpName}\" requires ${slugKey}. Use getConfigInfo to inspect ${entity} slugs.`,\n },\n ],\n isError: true,\n }\n }\n\n const match = authorizedMCP.items.find(\n (candidate): candidate is CollectionMCPItem | GlobalMCPItem =>\n candidate.type === item.type &&\n candidate.mcpName === item.mcpName &&\n (candidate.type === 'collectionTool'\n ? candidate.collectionSlug === slug\n : candidate.type === 'globalTool' && candidate.globalSlug === slug),\n )\n\n if (!match) {\n return {\n content: [\n {\n type: 'text',\n text: `Error: MCP access to \"${item.mcpName}\" is not enabled for ${entity} \"${slug}\"`,\n },\n ],\n isError: true,\n }\n }\n\n const handlerArgs = {\n authorizedMCP,\n input: toolInput,\n req,\n serverContext,\n }\n const response = await (match.type === 'collectionTool'\n ? match.tool.handler({ ...handlerArgs, collectionSlug: slug })\n : match.tool.handler({ ...handlerArgs, globalSlug: slug }))\n\n return finalizeToolResponse(response, match.tool.overrideResponse)\n }\n\n try {\n const registeredEntityTools = new Set<string>()\n\n for (const item of authorizedMCP.items) {\n switch (item.type) {\n case 'collectionTool':\n case 'globalTool': {\n if (registeredEntityTools.has(item.mcpName)) {\n break\n }\n registeredEntityTools.add(item.mcpName)\n\n const inputSchema = withSlugInput({\n name: item.type === 'collectionTool' ? 'collectionSlug' : 'globalSlug',\n input: item.tool.input,\n })\n\n server.registerTool(\n item.mcpName,\n {\n annotations: item.tool.annotations,\n description: item.tool.description,\n inputSchema: toStandardSchema(inputSchema),\n },\n async (input: unknown, ctx: ServerContext) =>\n callEntityTool({ input, item, serverContext: ctx }),\n )\n logger.info(`✅ Tool: ${item.mcpName} Registered.`)\n break\n }\n case 'prompt': {\n const prompt = item.prompt\n server.registerPrompt(\n item.mcpName,\n {\n argsSchema: prompt.argsSchema ? toStandardSchema(prompt.argsSchema) : undefined,\n description: prompt.description,\n title: prompt.title,\n },\n async (input: unknown, ctx: ServerContext) =>\n prompt.handler({\n input: (input ?? {}) as Record<string, unknown>,\n req,\n serverContext: ctx,\n }),\n )\n logger.info(`✅ Prompt: ${prompt.title} Registered.`)\n break\n }\n case 'resource': {\n const resource = item.resource\n server.registerResource(\n item.mcpName,\n // @ts-expect-error - Overload type ambiguity (string OR ResourceTemplate is valid)\n resource.uri,\n {\n description: resource.description,\n mimeType: resource.mimeType,\n title: resource.title,\n },\n // Static URIs call (uri, ctx); ResourceTemplates call (uri, params, ctx).\n // The rest-params shape lets us collect either signature uniformly.\n async (...sdkArgs: unknown[]) => {\n const ctx = sdkArgs[sdkArgs.length - 1] as ServerContext\n const uri = sdkArgs[0] as URL\n const params = (sdkArgs.length > 2 ? sdkArgs[1] : {}) as Record<string, string>\n return resource.handler({ params, req, serverContext: ctx, uri })\n },\n )\n logger.info(`✅ Resource: ${resource.title} Registered.`)\n break\n }\n case 'tool': {\n const tool = item.tool\n server.registerTool(\n item.mcpName,\n {\n annotations: tool.annotations,\n description: tool.description,\n inputSchema: tool.input ? toStandardSchema(tool.input) : undefined,\n },\n async (input: unknown, ctx: ServerContext) =>\n finalizeToolResponse(\n await tool.handler({\n authorizedMCP,\n input: (input ?? {}) as Record<string, unknown>,\n req,\n serverContext: ctx,\n }),\n tool.overrideResponse,\n ),\n )\n logger.info(`✅ Tool: ${item.mcpName} Registered.`)\n break\n }\n }\n }\n } catch (error) {\n throw new APIError(`Error initializing MCP handler: ${String(error)}`, 500)\n }\n\n return server\n}\n\nconst withSlugInput = ({\n name,\n input,\n}: {\n input?: ToolInputSchema\n name: 'collectionSlug' | 'globalSlug'\n}): ToolInputSchema => {\n const description = name === 'collectionSlug' ? 'The collection slug' : 'The global slug'\n const slugSchema = z.string().describe(description)\n\n if (!input) {\n return z.object({ [name]: slugSchema })\n }\n\n if (input instanceof z.ZodObject) {\n return input.extend({ [name]: slugSchema })\n }\n\n const schema = input as {\n properties?: Record<string, JsonSchemaType>\n required?: string[]\n } & JsonSchemaType\n\n return {\n ...schema,\n type: 'object',\n properties: {\n ...schema.properties,\n [name]: {\n type: 'string',\n description,\n },\n },\n required: Array.from(new Set([name, ...(schema.required ?? [])])),\n }\n}\n"],"names":["McpServer","APIError","z","getLogger","toStandardSchema","buildMcpServer","authorizedMCP","pluginConfig","req","serverOptions","mcp","server","name","version","serverInfo","options","logger","payload","finalizeToolResponse","response","overrideResponse","overridden","doc","_doc","rest","callEntityTool","input","item","serverContext","entity","type","slugKey","toolInput","slug","content","text","mcpName","isError","match","items","find","candidate","collectionSlug","globalSlug","handlerArgs","tool","handler","registeredEntityTools","Set","has","add","inputSchema","withSlugInput","registerTool","annotations","description","ctx","info","prompt","registerPrompt","argsSchema","undefined","title","resource","registerResource","uri","mimeType","sdkArgs","length","params","error","String","slugSchema","string","describe","object","ZodObject","extend","schema","properties","required","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;IAKf,OAAO;QACL,GAAGoD,MAAM;QACThD,MAAM;QACNiD,YAAY;YACV,GAAGD,OAAOC,UAAU;YACpB,CAACnE,KAAK,EAAE;gBACNkB,MAAM;gBACNyB;YACF;QACF;QACAyB,UAAUC,MAAMC,IAAI,CAAC,IAAIlC,IAAI;YAACpC;eAAUkE,OAAOE,QAAQ,IAAI,EAAE;SAAE;IACjE;AACF"}
1
+ {"version":3,"sources":["../../src/mcp/buildMcpServer.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\n\nimport { McpServer, type ServerContext } from '@modelcontextprotocol/server'\nimport { APIError, strictObject, z } from 'payload'\n\nimport type {\n AuthorizedMCP,\n CollectionMCPItem,\n GlobalMCPItem,\n JsonSchemaType,\n MCPResponseOverride,\n MCPToolResponse,\n SanitizedMCPPluginConfig,\n ToolInputSchema,\n} from '../types.js'\n\nimport { getLogger } from '../utils/getLogger.js'\nimport { toStandardSchema } from '../utils/toStandardSchema.js'\n\nz.config(z.locales.en())\n\n/**\n * Serving-entry-agnostic core: registers every authorized MCP item onto a fresh\n * `McpServer` and returns it. The HTTP and stdio entry point callers provide fresh\n * instances from this builder while they own the transport and protocol-era\n * decision.\n *\n * `req` is the request context handlers see. For HTTP it's the live\n * `PayloadRequest` derived from the incoming HTTP request; for stdio it's a\n * synthesized one built via `createLocalReq`.\n */\nexport const buildMcpServer = ({\n authorizedMCP,\n pluginConfig,\n req,\n}: {\n authorizedMCP: AuthorizedMCP\n pluginConfig: SanitizedMCPPluginConfig\n req: PayloadRequest\n}): McpServer => {\n const serverOptions = pluginConfig.mcp?.serverOptions || {}\n const server = new McpServer(\n { name: 'Payload MCP Server', version: '1.0.0', ...serverOptions.serverInfo },\n serverOptions.options,\n )\n\n const logger = getLogger({ payload: req.payload })\n\n /**\n * Wrap a tool handler's response with the tool's `overrideResponse`, then\n * strip the internal `doc` field so it doesn't leak onto the wire.\n */\n const finalizeToolResponse = async ({\n input,\n overrideResponse,\n response,\n toolName,\n }: {\n input: unknown\n overrideResponse?: MCPResponseOverride\n response: MCPToolResponse\n toolName: string\n }): Promise<MCPToolResponse> => {\n let overridden = overrideResponse?.(response, response.doc ?? {}, req) ?? response\n for (const hook of pluginConfig.hooks?.afterToolCall ?? []) {\n overridden = await hook({ input, req, response: overridden, toolName })\n }\n const { doc: _doc, ...rest } = overridden\n return rest\n }\n\n /**\n * Runs a collection/global tool call:\n * - reads `slug` from the input\n * - runs access control: errors if `authorizedMCP.items` has no entry for this tool + slug\n * - runs the tool handler and finalizes its response\n */\n const callEntityTool = async ({\n input,\n item,\n serverContext,\n }: {\n input: unknown\n item: CollectionMCPItem | GlobalMCPItem\n serverContext: ServerContext\n }): Promise<MCPToolResponse> => {\n const entity = item.type === 'collectionTool' ? 'collection' : 'global'\n const toolInput = (input ?? {}) as Record<string, unknown>\n const slug = toolInput.slug as string | undefined\n\n if (!slug) {\n return {\n content: [\n {\n type: 'text',\n text: `Error: \"${item.mcpName}\" requires slug. Use getConfigInfo to inspect ${entity} slugs.`,\n },\n ],\n isError: true,\n }\n }\n\n const match = authorizedMCP.items.find(\n (candidate): candidate is CollectionMCPItem | GlobalMCPItem =>\n candidate.type === item.type &&\n candidate.mcpName === item.mcpName &&\n (candidate.type === 'collectionTool'\n ? candidate.collectionSlug === slug\n : candidate.type === 'globalTool' && candidate.globalSlug === slug),\n )\n\n if (!match) {\n return {\n content: [\n {\n type: 'text',\n text: `Error: MCP access to \"${item.mcpName}\" is not enabled for ${entity} \"${slug}\"`,\n },\n ],\n isError: true,\n }\n }\n\n const handlerArgs = {\n authorizedMCP,\n input: toolInput,\n req,\n serverContext,\n }\n const response = await (match.type === 'collectionTool'\n ? match.tool.handler({ ...handlerArgs, slug })\n : match.tool.handler({ ...handlerArgs, slug }))\n\n return finalizeToolResponse({\n input: toolInput,\n overrideResponse: match.tool.overrideResponse,\n response,\n toolName: match.mcpName,\n })\n }\n\n try {\n const registeredEntityTools = new Set<string>()\n\n for (const item of authorizedMCP.items) {\n switch (item.type) {\n case 'collectionTool':\n case 'globalTool': {\n if (registeredEntityTools.has(item.mcpName)) {\n break\n }\n registeredEntityTools.add(item.mcpName)\n\n const inputSchema = withSlugInput({ input: item.tool.input })\n\n server.registerTool(\n item.mcpName,\n {\n annotations: item.tool.annotations,\n description: item.tool.description,\n inputSchema: toStandardSchema(inputSchema),\n },\n async (input: unknown, ctx: ServerContext) =>\n callEntityTool({ input, item, serverContext: ctx }),\n )\n logger.info(`✅ Tool: ${item.mcpName} Registered.`)\n break\n }\n case 'prompt': {\n const prompt = item.prompt\n server.registerPrompt(\n item.mcpName,\n {\n argsSchema: prompt.argsSchema ? toStandardSchema(prompt.argsSchema) : undefined,\n description: prompt.description,\n title: prompt.title,\n },\n async (input: unknown, ctx: ServerContext) =>\n prompt.handler({\n input: (input ?? {}) as Record<string, unknown>,\n req,\n serverContext: ctx,\n }),\n )\n logger.info(`✅ Prompt: ${prompt.title} Registered.`)\n break\n }\n case 'resource': {\n const resource = item.resource\n server.registerResource(\n item.mcpName,\n // @ts-expect-error - Overload type ambiguity (string OR ResourceTemplate is valid)\n resource.uri,\n {\n description: resource.description,\n mimeType: resource.mimeType,\n title: resource.title,\n },\n // Static URIs call (uri, ctx); ResourceTemplates call (uri, params, ctx).\n // The rest-params shape lets us collect either signature uniformly.\n async (...sdkArgs: unknown[]) => {\n const ctx = sdkArgs[sdkArgs.length - 1] as ServerContext\n const uri = sdkArgs[0] as URL\n const params = (sdkArgs.length > 2 ? sdkArgs[1] : {}) as Record<string, string>\n return resource.handler({ params, req, serverContext: ctx, uri })\n },\n )\n logger.info(`✅ Resource: ${resource.title} Registered.`)\n break\n }\n case 'tool': {\n const tool = item.tool\n server.registerTool(\n item.mcpName,\n {\n annotations: tool.annotations,\n description: tool.description,\n inputSchema: tool.input ? toStandardSchema(tool.input) : undefined,\n },\n async (input: unknown, ctx: ServerContext) => {\n const toolInput = (input ?? {}) as Record<string, unknown>\n const response = await tool.handler({\n authorizedMCP,\n input: toolInput,\n req,\n serverContext: ctx,\n })\n return finalizeToolResponse({\n input: toolInput,\n overrideResponse: tool.overrideResponse,\n response,\n toolName: item.mcpName,\n })\n },\n )\n logger.info(`✅ Tool: ${item.mcpName} Registered.`)\n break\n }\n }\n }\n } catch (error) {\n throw new APIError(`Error initializing MCP handler: ${String(error)}`, 500)\n }\n\n return server\n}\n\nconst withSlugInput = ({ input }: { input?: ToolInputSchema }): ToolInputSchema => {\n const description = 'The target slug.'\n const slugSchema = z.string().check(z.describe(description))\n\n if (!input) {\n return strictObject({ slug: slugSchema }) as unknown as ToolInputSchema\n }\n\n if (typeof input === 'object' && input !== null && '~standard' in input) {\n const schema = input['~standard'].jsonSchema.input({ target: 'draft-2020-12' })\n const properties = schema.properties as Record<string, unknown> | undefined\n\n if (properties?.slug) {\n return input\n }\n\n return addSlugToJSONSchema({ description, schema: schema as JsonSchemaType })\n }\n\n return addSlugToJSONSchema({ description, schema: input })\n}\n\nconst addSlugToJSONSchema = ({\n description,\n schema,\n}: {\n description: string\n schema: JsonSchemaType\n}): JsonSchemaType => {\n const objectSchema = schema as {\n properties?: Record<string, JsonSchemaType>\n required?: string[]\n } & JsonSchemaType\n\n return {\n ...objectSchema,\n type: 'object',\n properties: {\n ...objectSchema.properties,\n slug: {\n type: 'string',\n description,\n },\n },\n required: Array.from(new Set(['slug', ...(objectSchema.required ?? [])])),\n }\n}\n"],"names":["McpServer","APIError","strictObject","z","getLogger","toStandardSchema","config","locales","en","buildMcpServer","authorizedMCP","pluginConfig","req","serverOptions","mcp","server","name","version","serverInfo","options","logger","payload","finalizeToolResponse","input","overrideResponse","response","toolName","overridden","doc","hook","hooks","afterToolCall","_doc","rest","callEntityTool","item","serverContext","entity","type","toolInput","slug","content","text","mcpName","isError","match","items","find","candidate","collectionSlug","globalSlug","handlerArgs","tool","handler","registeredEntityTools","Set","has","add","inputSchema","withSlugInput","registerTool","annotations","description","ctx","info","prompt","registerPrompt","argsSchema","undefined","title","resource","registerResource","uri","mimeType","sdkArgs","length","params","error","String","slugSchema","string","check","describe","schema","jsonSchema","target","properties","addSlugToJSONSchema","objectSchema","required","Array","from"],"mappings":"AAEA,SAASA,SAAS,QAA4B,+BAA8B;AAC5E,SAASC,QAAQ,EAAEC,YAAY,EAAEC,CAAC,QAAQ,UAAS;AAanD,SAASC,SAAS,QAAQ,wBAAuB;AACjD,SAASC,gBAAgB,QAAQ,+BAA8B;AAE/DF,EAAEG,MAAM,CAACH,EAAEI,OAAO,CAACC,EAAE;AAErB;;;;;;;;;CASC,GACD,OAAO,MAAMC,iBAAiB,CAAC,EAC7BC,aAAa,EACbC,YAAY,EACZC,GAAG,EAKJ;IACC,MAAMC,gBAAgBF,aAAaG,GAAG,EAAED,iBAAiB,CAAC;IAC1D,MAAME,SAAS,IAAIf,UACjB;QAAEgB,MAAM;QAAsBC,SAAS;QAAS,GAAGJ,cAAcK,UAAU;IAAC,GAC5EL,cAAcM,OAAO;IAGvB,MAAMC,SAAShB,UAAU;QAAEiB,SAAST,IAAIS,OAAO;IAAC;IAEhD;;;GAGC,GACD,MAAMC,uBAAuB,OAAO,EAClCC,KAAK,EACLC,gBAAgB,EAChBC,QAAQ,EACRC,QAAQ,EAMT;QACC,IAAIC,aAAaH,mBAAmBC,UAAUA,SAASG,GAAG,IAAI,CAAC,GAAGhB,QAAQa;QAC1E,KAAK,MAAMI,QAAQlB,aAAamB,KAAK,EAAEC,iBAAiB,EAAE,CAAE;YAC1DJ,aAAa,MAAME,KAAK;gBAAEN;gBAAOX;gBAAKa,UAAUE;gBAAYD;YAAS;QACvE;QACA,MAAM,EAAEE,KAAKI,IAAI,EAAE,GAAGC,MAAM,GAAGN;QAC/B,OAAOM;IACT;IAEA;;;;;GAKC,GACD,MAAMC,iBAAiB,OAAO,EAC5BX,KAAK,EACLY,IAAI,EACJC,aAAa,EAKd;QACC,MAAMC,SAASF,KAAKG,IAAI,KAAK,mBAAmB,eAAe;QAC/D,MAAMC,YAAahB,SAAS,CAAC;QAC7B,MAAMiB,OAAOD,UAAUC,IA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
+ {"version":3,"file":"authTools.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/authTools.ts"],"names":[],"mappings":"AAkCA,eAAO,MAAM,kBAAkB,4CAuD7B,CAAA;AAEF,eAAO,MAAM,4BAA4B,4CAmCvC,CAAA;AAEF,eAAO,MAAM,mBAAmB,4CAuC9B,CAAA;AAEF,eAAO,MAAM,2BAA2B,4CAmCtC,CAAA;AAEF,eAAO,MAAM,oBAAoB,4CAmC/B,CAAA;AAEF,eAAO,MAAM,oBAAoB,4CAiC/B,CAAA"}
@@ -1,4 +1,5 @@
1
- import { z } from 'zod';
1
+ import { createLocalReq, strictObject, z } from 'payload';
2
+ import { defaultAccess } from '../../../defaultAccess.js';
2
3
  import { defineCollectionTool } from '../../../defineTool.js';
3
4
  import { getLogger } from '../../../utils/getLogger.js';
4
5
  /**
@@ -10,13 +11,13 @@ import { getLogger } from '../../../utils/getLogger.js';
10
11
  * `auth` (check current token) doesn't actually depend on the collection at
11
12
  * runtime — `payload.auth({ headers })` is global — but it's grouped under the
12
13
  * users collection so all auth-shaped tools live in one place.
13
- */ const emailSchema = z.string().email().describe('The user email address');
14
- const wrapError = (name)=>({ collectionSlug, message })=>{
14
+ */ const emailSchema = z.email().check(z.describe('The user email address.'));
15
+ const wrapError = (name)=>({ slug, message })=>{
15
16
  return {
16
17
  content: [
17
18
  {
18
19
  type: 'text',
19
- text: `❌ **Error in ${name}** on ${collectionSlug}: ${message}`
20
+ text: `❌ **Error in ${name}** on ${slug}: ${message}`
20
21
  }
21
22
  ]
22
23
  };
@@ -30,10 +31,10 @@ export const authCollectionTool = defineCollectionTool({
30
31
  title: 'Check Auth Status'
31
32
  },
32
33
  description: 'Checks authentication status for the current user.',
33
- input: z.object({
34
- headers: z.record(z.string(), z.string()).describe('Optional custom headers to send with the authentication request').optional()
34
+ input: strictObject({
35
+ headers: z.optional(z.record(z.string(), z.string())).check(z.describe('Custom headers to send with the authentication request.'))
35
36
  })
36
- }).handler(async ({ collectionSlug, input, req })=>{
37
+ }).handler(async ({ slug, authorizedMCP, input, req })=>{
37
38
  const logger = getLogger({
38
39
  payload: req.payload
39
40
  });
@@ -42,9 +43,32 @@ export const authCollectionTool = defineCollectionTool({
42
43
  if (input.headers) {
43
44
  authHeaders = new Headers(input.headers);
44
45
  }
46
+ const authReq = await createLocalReq({
47
+ req: {
48
+ headers: authHeaders
49
+ }
50
+ }, req.payload);
45
51
  const result = await req.payload.auth({
46
- headers: authHeaders
52
+ headers: authHeaders,
53
+ req: authReq
47
54
  });
55
+ if (result.user) {
56
+ const authenticatedUser = result.user;
57
+ // Auth strategies read users with trusted Local API access. Re-read the user with the MCP
58
+ // caller's access level before returning it to the client.
59
+ const user = await req.payload.findByID({
60
+ id: authenticatedUser.id,
61
+ collection: authenticatedUser.collection,
62
+ overrideAccess: authorizedMCP.overrideAccess,
63
+ req: authReq
64
+ });
65
+ result.user = {
66
+ ...user,
67
+ _sid: authenticatedUser._sid,
68
+ _strategy: authenticatedUser._strategy,
69
+ collection: authenticatedUser.collection
70
+ };
71
+ }
48
72
  return {
49
73
  content: [
50
74
  {
@@ -56,9 +80,9 @@ export const authCollectionTool = defineCollectionTool({
56
80
  };
57
81
  } catch (error) {
58
82
  const errorMessage = error instanceof Error ? error.message : 'Unknown error';
59
- logger.error(`Error in auth tool on ${collectionSlug}: ${errorMessage}`);
83
+ logger.error(`Error in auth tool on ${slug}: ${errorMessage}`);
60
84
  return wrapError('auth')({
61
- collectionSlug,
85
+ slug,
62
86
  message: errorMessage
63
87
  });
64
88
  }
@@ -72,38 +96,36 @@ export const forgotPasswordCollectionTool = defineCollectionTool({
72
96
  title: 'Forgot Password'
73
97
  },
74
98
  description: 'Sends a password reset email to a user.',
75
- input: z.object({
76
- disableEmail: z.boolean().describe('Whether to disable sending the email (for testing)').optional().default(false),
99
+ input: strictObject({
77
100
  email: emailSchema
78
101
  })
79
- }).handler(async ({ collectionSlug, input, req })=>{
102
+ }).handler(async ({ slug, input, req })=>{
80
103
  const logger = getLogger({
81
104
  payload: req.payload
82
105
  });
83
106
  try {
84
- const result = await req.payload.forgotPassword({
85
- collection: collectionSlug,
107
+ await req.payload.forgotPassword({
108
+ collection: slug,
86
109
  data: {
87
110
  email: input.email
88
111
  },
89
- disableEmail: input.disableEmail
112
+ disableEmail: false,
113
+ overrideAccess: false,
114
+ req
90
115
  });
91
116
  return {
92
117
  content: [
93
118
  {
94
119
  type: 'text',
95
- text: `# Forgot Password Email Sent\n\n**Collection:** ${collectionSlug}\n**Email:** ${input.email}\n\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``
120
+ text: 'If an account matches that email, password reset instructions have been sent.'
96
121
  }
97
- ],
98
- doc: {
99
- result
100
- }
122
+ ]
101
123
  };
102
124
  } catch (error) {
103
125
  const errorMessage = error instanceof Error ? error.message : 'Unknown error';
104
- logger.error(`Error in forgotPassword tool on ${collectionSlug}: ${errorMessage}`);
126
+ logger.error(`Error in forgotPassword tool on ${slug}: ${errorMessage}`);
105
127
  return wrapError('forgotPassword')({
106
- collectionSlug,
128
+ slug,
107
129
  message: errorMessage
108
130
  });
109
131
  }
@@ -117,40 +139,39 @@ export const loginCollectionTool = defineCollectionTool({
117
139
  title: 'User Login'
118
140
  },
119
141
  description: 'Authenticates a user with email and password.',
120
- input: z.object({
121
- depth: z.number().int().min(0).max(10).describe('Depth of population for relationships').optional().default(0),
142
+ input: strictObject({
143
+ depth: z._default(z.int().check(z.minimum(0), z.maximum(10)), 0).check(z.describe('Depth of population for relationships.')),
122
144
  email: emailSchema,
123
- password: z.string().describe('The user password'),
124
- showHiddenFields: z.boolean().describe('Whether to show hidden fields in the response').optional().default(false)
145
+ password: z.string().check(z.describe('The user password.'))
125
146
  })
126
- }).handler(async ({ collectionSlug, input, req })=>{
147
+ }).handler(async ({ slug, authorizedMCP, input, req })=>{
127
148
  const logger = getLogger({
128
149
  payload: req.payload
129
150
  });
130
151
  try {
131
152
  const result = await req.payload.login({
132
- collection: collectionSlug,
153
+ collection: slug,
133
154
  data: {
134
155
  email: input.email,
135
156
  password: input.password
136
157
  },
137
158
  depth: input.depth,
138
- showHiddenFields: input.showHiddenFields
159
+ overrideAccess: authorizedMCP.overrideAccess
139
160
  });
140
161
  return {
141
162
  content: [
142
163
  {
143
164
  type: 'text',
144
- text: `# Login Successful\n\n**User:** ${input.email}\n**Collection:** ${collectionSlug}\n\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``
165
+ text: `# Login Successful\n\n**User:** ${input.email}\n**Collection:** ${slug}\n\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``
145
166
  }
146
167
  ],
147
168
  doc: result
148
169
  };
149
170
  } catch (error) {
150
171
  const errorMessage = error instanceof Error ? error.message : 'Unknown error';
151
- logger.error(`Error in login tool on ${collectionSlug}: ${errorMessage}`);
172
+ logger.error(`Error in login tool on ${slug}: ${errorMessage}`);
152
173
  return wrapError('login')({
153
- collectionSlug,
174
+ slug,
154
175
  message: errorMessage
155
176
  });
156
177
  }
@@ -164,42 +185,43 @@ export const resetPasswordCollectionTool = defineCollectionTool({
164
185
  title: 'Reset Password'
165
186
  },
166
187
  description: 'Resets a user password with a reset token.',
167
- input: z.object({
168
- password: z.string().describe('The new password for the user'),
169
- token: z.string().describe('The password reset token sent to the user email')
188
+ input: strictObject({
189
+ password: z.string().check(z.describe('The new password for the user.')),
190
+ token: z.string().check(z.describe('The password reset token sent to the user email.'))
170
191
  })
171
- }).handler(async ({ collectionSlug, input, req })=>{
192
+ }).handler(async ({ slug, authorizedMCP, input, req })=>{
172
193
  const logger = getLogger({
173
194
  payload: req.payload
174
195
  });
175
196
  try {
176
197
  const result = await req.payload.resetPassword({
177
- collection: collectionSlug,
198
+ collection: slug,
178
199
  data: {
179
200
  password: input.password,
180
201
  token: input.token
181
202
  },
182
- overrideAccess: true
203
+ overrideAccess: authorizedMCP.overrideAccess
183
204
  });
184
205
  return {
185
206
  content: [
186
207
  {
187
208
  type: 'text',
188
- text: `# Password Reset Successful\n\n**Collection:** ${collectionSlug}\n\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``
209
+ text: `# Password Reset Successful\n\n**Collection:** ${slug}\n\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``
189
210
  }
190
211
  ],
191
212
  doc: result
192
213
  };
193
214
  } catch (error) {
194
215
  const errorMessage = error instanceof Error ? error.message : 'Unknown error';
195
- logger.error(`Error in resetPassword tool on ${collectionSlug}: ${errorMessage}`);
216
+ logger.error(`Error in resetPassword tool on ${slug}: ${errorMessage}`);
196
217
  return wrapError('resetPassword')({
197
- collectionSlug,
218
+ slug,
198
219
  message: errorMessage
199
220
  });
200
221
  }
201
222
  });
202
223
  export const unlockCollectionTool = defineCollectionTool({
224
+ access: (args)=>defaultAccess(args) && Boolean(args.permissions?.collections?.[args.slug]?.unlock),
203
225
  annotations: {
204
226
  destructiveHint: false,
205
227
  idempotentHint: true,
@@ -208,26 +230,27 @@ export const unlockCollectionTool = defineCollectionTool({
208
230
  title: 'Unlock Account'
209
231
  },
210
232
  description: 'Unlocks a user account that has been locked due to failed login attempts.',
211
- input: z.object({
233
+ input: strictObject({
212
234
  email: emailSchema
213
235
  })
214
- }).handler(async ({ collectionSlug, input, req })=>{
236
+ }).handler(async ({ slug, authorizedMCP, input, req })=>{
215
237
  const logger = getLogger({
216
238
  payload: req.payload
217
239
  });
218
240
  try {
219
241
  const result = await req.payload.unlock({
220
- collection: collectionSlug,
242
+ collection: slug,
221
243
  data: {
222
244
  email: input.email
223
245
  },
224
- overrideAccess: true
246
+ overrideAccess: authorizedMCP.overrideAccess,
247
+ req
225
248
  });
226
249
  return {
227
250
  content: [
228
251
  {
229
252
  type: 'text',
230
- text: `# Account Unlocked\n\n**Collection:** ${collectionSlug}\n**Email:** ${input.email}\n**Result:** ${result ? 'Success' : 'Failed'}`
253
+ text: `# Account Unlocked\n\n**Collection:** ${slug}\n**Email:** ${input.email}\n**Result:** ${result ? 'Success' : 'Failed'}`
231
254
  }
232
255
  ],
233
256
  doc: {
@@ -236,9 +259,9 @@ export const unlockCollectionTool = defineCollectionTool({
236
259
  };
237
260
  } catch (error) {
238
261
  const errorMessage = error instanceof Error ? error.message : 'Unknown error';
239
- logger.error(`Error in unlock tool on ${collectionSlug}: ${errorMessage}`);
262
+ logger.error(`Error in unlock tool on ${slug}: ${errorMessage}`);
240
263
  return wrapError('unlock')({
241
- collectionSlug,
264
+ slug,
242
265
  message: errorMessage
243
266
  });
244
267
  }
@@ -252,23 +275,23 @@ export const verifyCollectionTool = defineCollectionTool({
252
275
  title: 'Email Verification'
253
276
  },
254
277
  description: 'Verifies a user email with a verification token.',
255
- input: z.object({
256
- token: z.string().describe('The verification token sent to the user email')
278
+ input: strictObject({
279
+ token: z.string().check(z.describe('The verification token sent to the user email.'))
257
280
  })
258
- }).handler(async ({ collectionSlug, input, req })=>{
281
+ }).handler(async ({ slug, input, req })=>{
259
282
  const logger = getLogger({
260
283
  payload: req.payload
261
284
  });
262
285
  try {
263
286
  const result = await req.payload.verifyEmail({
264
- collection: collectionSlug,
287
+ collection: slug,
265
288
  token: input.token
266
289
  });
267
290
  return {
268
291
  content: [
269
292
  {
270
293
  type: 'text',
271
- text: `# Email Verification Successful\n\n**Collection:** ${collectionSlug}\n**Result:** ${result ? 'Success' : 'Failed'}`
294
+ text: `# Email Verification Successful\n\n**Collection:** ${slug}\n**Result:** ${result ? 'Success' : 'Failed'}`
272
295
  }
273
296
  ],
274
297
  doc: {
@@ -277,9 +300,9 @@ export const verifyCollectionTool = defineCollectionTool({
277
300
  };
278
301
  } catch (error) {
279
302
  const errorMessage = error instanceof Error ? error.message : 'Unknown error';
280
- logger.error(`Error in verify tool on ${collectionSlug}: ${errorMessage}`);
303
+ logger.error(`Error in verify tool on ${slug}: ${errorMessage}`);
281
304
  return wrapError('verify')({
282
- collectionSlug,
305
+ slug,
283
306
  message: errorMessage
284
307
  });
285
308
  }
@@ -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,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,EA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mB,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,EAAEmB,aAAa,EAAEN,KAAK,EAAEO,GAAG,EAAE;IACnD,MAAMC,SAAS5B,UAAU;QAAE6B,SAASF,IAAIE,OAAO;IAAC;IAChD,IAAI;QACF,IAAIC,cAAc,IAAIC;QACtB,IAAIX,MAAMC,OAAO,EAAE;YACjBS,cAAc,IAAIC,QAAQX,MAAM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../../../src/mcp/builtin/collections/countTool.ts"],"names":[],"mappings":"AAWA,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,12 +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 { localAPIDefaults } from '../../../utils/localAPIDefaults.js';
6
- import { whereSchema } from '../../../utils/whereSchema.js';
7
5
  const DEFAULT_DESCRIPTION = 'Count documents in any collection by passing the collection slug and optional where clause.';
8
6
  export const countDocumentsTool = defineCollectionTool({
9
- access: (args)=>defaultAccess(args) && Boolean(args.permissions?.collections?.[args.collectionSlug]?.read),
7
+ access: (args)=>defaultAccess(args) && Boolean(args.permissions?.collections?.[args.slug]?.read),
10
8
  annotations: {
11
9
  destructiveHint: false,
12
10
  idempotentHint: true,
@@ -15,23 +13,19 @@ export const countDocumentsTool = defineCollectionTool({
15
13
  title: 'Count Documents'
16
14
  },
17
15
  description: DEFAULT_DESCRIPTION,
18
- input: z.object({
19
- locale: z.string().describe('Optional: locale code to count documents in').optional(),
20
- trash: z.boolean().describe('Optional: include soft-deleted documents when trash is enabled on the collection').optional(),
21
- where: whereSchema.describe('Optional: where clause for filtering. Use field names with Payload operators, and/or arrays for grouping. Example: {"title":{"contains":"test"}}').optional()
22
- })
23
- }).handler(async ({ authorizedMCP, collectionSlug, input, req })=>{
16
+ input: countDocumentsInputSchema
17
+ }).handler(async ({ slug, authorizedMCP, input, req })=>{
24
18
  const payload = req.payload;
25
19
  const logger = getLogger({
26
20
  payload
27
21
  });
28
22
  const { locale, trash, where } = input;
29
- logger.info(`Counting documents in collection: ${collectionSlug}`);
23
+ logger.info(`Counting documents in collection: ${slug}`);
30
24
  try {
31
25
  const result = await payload.count({
32
- collection: collectionSlug,
26
+ collection: slug,
27
+ overrideAccess: authorizedMCP.overrideAccess,
33
28
  req,
34
- ...localAPIDefaults(authorizedMCP),
35
29
  ...locale ? {
36
30
  locale
37
31
  } : {},
@@ -46,19 +40,19 @@ export const countDocumentsTool = defineCollectionTool({
46
40
  content: [
47
41
  {
48
42
  type: 'text',
49
- 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\`\`\``
50
44
  }
51
45
  ],
52
46
  doc: result
53
47
  };
54
48
  } catch (error) {
55
49
  const errorMessage = error instanceof Error ? error.message : 'Unknown error';
56
- logger.error(`Error counting documents in ${collectionSlug}: ${errorMessage}`);
50
+ logger.error(`Error counting documents in ${slug}: ${errorMessage}`);
57
51
  return {
58
52
  content: [
59
53
  {
60
54
  type: 'text',
61
- text: `❌ **Error counting documents in collection "${collectionSlug}":** ${errorMessage}`
55
+ text: `❌ **Error counting documents in collection "${slug}":** ${errorMessage}`
62
56
  }
63
57
  ],
64
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 { localAPIDefaults } from '../../../utils/localAPIDefaults.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 req,\n ...localAPIDefaults(authorizedMCP),\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","localAPIDefaults","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","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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CAAC,YAAY,EAAE9B,eAAe,WAAW,EAAEwB,OAAOO,SAAS,CAAC,kCAAkC,EAAEC,KAAKC,SAAS,CAACT,QAAQ,QAAQ,CAAC;gBACxI;aACD;YACDU,KAAKV;QACP;IACF,EAAE,OAAOW,OAAO;QACd,MAAMC,eAAeD,iBAAiBE,QAAQF,MAAMG,OAAO,GAAG;QAC9DhB,OAAOa,KAAK,CAAC,CAAC,4BAA4B,EAAEnC,eAAe,EAAE,EAAEoC,cAAc;QAC7E,OAAO;YACLR,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,4CAA4C,EAAE9B,eAAe,KAAK,EAAEoC,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":"AAWA,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"}