@payloadcms/plugin-mcp 4.0.0-internal.293e026 → 4.0.0-internal.2fddfc0

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 (201) hide show
  1. package/dist/defaultAccess.d.ts +3 -0
  2. package/dist/defaultAccess.d.ts.map +1 -0
  3. package/dist/defaultAccess.js +3 -0
  4. package/dist/defaultAccess.js.map +1 -0
  5. package/dist/endpoint/access.d.ts +17 -5
  6. package/dist/endpoint/access.d.ts.map +1 -1
  7. package/dist/endpoint/access.js +82 -88
  8. package/dist/endpoint/access.js.map +1 -1
  9. package/dist/endpoint/index.d.ts.map +1 -1
  10. package/dist/endpoint/index.js +11 -0
  11. package/dist/endpoint/index.js.map +1 -1
  12. package/dist/exports/client.d.ts +1 -1
  13. package/dist/exports/client.d.ts.map +1 -1
  14. package/dist/exports/client.js +1 -1
  15. package/dist/exports/client.js.map +1 -1
  16. package/dist/exports/internal.d.ts +2 -0
  17. package/dist/exports/internal.d.ts.map +1 -0
  18. package/dist/exports/internal.js +3 -0
  19. package/dist/exports/internal.js.map +1 -0
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +13 -18
  22. package/dist/index.js.map +1 -1
  23. package/dist/mcp/buildMcpServer.d.ts.map +1 -1
  24. package/dist/mcp/buildMcpServer.js +102 -71
  25. package/dist/mcp/buildMcpServer.js.map +1 -1
  26. package/dist/mcp/builtin/collections/authTools.d.ts.map +1 -1
  27. package/dist/mcp/builtin/collections/authTools.js +44 -6
  28. package/dist/mcp/builtin/collections/authTools.js.map +1 -1
  29. package/dist/mcp/builtin/collections/countTool.d.ts +2 -0
  30. package/dist/mcp/builtin/collections/countTool.d.ts.map +1 -0
  31. package/dist/mcp/builtin/collections/countTool.js +69 -0
  32. package/dist/mcp/builtin/collections/countTool.js.map +1 -0
  33. package/dist/mcp/builtin/collections/countVersionsTool.d.ts +2 -0
  34. package/dist/mcp/builtin/collections/countVersionsTool.d.ts.map +1 -0
  35. package/dist/mcp/builtin/collections/countVersionsTool.js +65 -0
  36. package/dist/mcp/builtin/collections/countVersionsTool.js.map +1 -0
  37. package/dist/mcp/builtin/collections/createTool.d.ts +1 -1
  38. package/dist/mcp/builtin/collections/createTool.d.ts.map +1 -1
  39. package/dist/mcp/builtin/collections/createTool.js +38 -42
  40. package/dist/mcp/builtin/collections/createTool.js.map +1 -1
  41. package/dist/mcp/builtin/collections/deleteTool.d.ts +1 -1
  42. package/dist/mcp/builtin/collections/deleteTool.d.ts.map +1 -1
  43. package/dist/mcp/builtin/collections/deleteTool.js +14 -20
  44. package/dist/mcp/builtin/collections/deleteTool.js.map +1 -1
  45. package/dist/mcp/builtin/collections/duplicateTool.d.ts +2 -0
  46. package/dist/mcp/builtin/collections/duplicateTool.d.ts.map +1 -0
  47. package/dist/mcp/builtin/collections/duplicateTool.js +97 -0
  48. package/dist/mcp/builtin/collections/duplicateTool.js.map +1 -0
  49. package/dist/mcp/builtin/collections/findDistinctTool.d.ts +2 -0
  50. package/dist/mcp/builtin/collections/findDistinctTool.d.ts.map +1 -0
  51. package/dist/mcp/builtin/collections/findDistinctTool.js +93 -0
  52. package/dist/mcp/builtin/collections/findDistinctTool.js.map +1 -0
  53. package/dist/mcp/builtin/collections/findTool.d.ts +1 -1
  54. package/dist/mcp/builtin/collections/findTool.d.ts.map +1 -1
  55. package/dist/mcp/builtin/collections/findTool.js +49 -43
  56. package/dist/mcp/builtin/collections/findTool.js.map +1 -1
  57. package/dist/mcp/builtin/collections/findVersionByIDTool.d.ts +2 -0
  58. package/dist/mcp/builtin/collections/findVersionByIDTool.d.ts.map +1 -0
  59. package/dist/mcp/builtin/collections/findVersionByIDTool.js +84 -0
  60. package/dist/mcp/builtin/collections/findVersionByIDTool.js.map +1 -0
  61. package/dist/mcp/builtin/collections/findVersionsTool.d.ts +2 -0
  62. package/dist/mcp/builtin/collections/findVersionsTool.d.ts.map +1 -0
  63. package/dist/mcp/builtin/collections/findVersionsTool.js +99 -0
  64. package/dist/mcp/builtin/collections/findVersionsTool.js.map +1 -0
  65. package/dist/mcp/builtin/collections/formatCollectionError.d.ts +9 -0
  66. package/dist/mcp/builtin/collections/formatCollectionError.d.ts.map +1 -0
  67. package/dist/mcp/builtin/collections/formatCollectionError.js +60 -0
  68. package/dist/mcp/builtin/collections/formatCollectionError.js.map +1 -0
  69. package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts +2 -0
  70. package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -0
  71. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +47 -0
  72. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -0
  73. package/dist/mcp/builtin/collections/restoreVersionTool.d.ts +2 -0
  74. package/dist/mcp/builtin/collections/restoreVersionTool.d.ts.map +1 -0
  75. package/dist/mcp/builtin/collections/restoreVersionTool.js +82 -0
  76. package/dist/mcp/builtin/collections/restoreVersionTool.js.map +1 -0
  77. package/dist/mcp/builtin/collections/updateTool.d.ts +1 -1
  78. package/dist/mcp/builtin/collections/updateTool.d.ts.map +1 -1
  79. package/dist/mcp/builtin/collections/updateTool.js +87 -86
  80. package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
  81. package/dist/mcp/builtin/getConfigInfoTool.d.ts +2 -0
  82. package/dist/mcp/builtin/getConfigInfoTool.d.ts.map +1 -0
  83. package/dist/mcp/builtin/getConfigInfoTool.js +71 -0
  84. package/dist/mcp/builtin/getConfigInfoTool.js.map +1 -0
  85. package/dist/mcp/builtin/globals/countVersionsTool.d.ts +2 -0
  86. package/dist/mcp/builtin/globals/countVersionsTool.d.ts.map +1 -0
  87. package/dist/mcp/builtin/globals/countVersionsTool.js +65 -0
  88. package/dist/mcp/builtin/globals/countVersionsTool.js.map +1 -0
  89. package/dist/mcp/builtin/globals/findTool.d.ts.map +1 -1
  90. package/dist/mcp/builtin/globals/findTool.js +18 -21
  91. package/dist/mcp/builtin/globals/findTool.js.map +1 -1
  92. package/dist/mcp/builtin/globals/findVersionByIDTool.d.ts +2 -0
  93. package/dist/mcp/builtin/globals/findVersionByIDTool.d.ts.map +1 -0
  94. package/dist/mcp/builtin/globals/findVersionByIDTool.js +80 -0
  95. package/dist/mcp/builtin/globals/findVersionByIDTool.js.map +1 -0
  96. package/dist/mcp/builtin/globals/findVersionsTool.d.ts +2 -0
  97. package/dist/mcp/builtin/globals/findVersionsTool.d.ts.map +1 -0
  98. package/dist/mcp/builtin/globals/findVersionsTool.js +95 -0
  99. package/dist/mcp/builtin/globals/findVersionsTool.js.map +1 -0
  100. package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts +2 -0
  101. package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts.map +1 -0
  102. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js +47 -0
  103. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js.map +1 -0
  104. package/dist/mcp/builtin/globals/restoreVersionTool.d.ts +2 -0
  105. package/dist/mcp/builtin/globals/restoreVersionTool.d.ts.map +1 -0
  106. package/dist/mcp/builtin/globals/restoreVersionTool.js +78 -0
  107. package/dist/mcp/builtin/globals/restoreVersionTool.js.map +1 -0
  108. package/dist/mcp/builtin/globals/updateTool.d.ts.map +1 -1
  109. package/dist/mcp/builtin/globals/updateTool.js +31 -40
  110. package/dist/mcp/builtin/globals/updateTool.js.map +1 -1
  111. package/dist/mcp/builtin/validateEntityData.d.ts +14 -0
  112. package/dist/mcp/builtin/validateEntityData.d.ts.map +1 -0
  113. package/dist/mcp/builtin/validateEntityData.js +82 -0
  114. package/dist/mcp/builtin/validateEntityData.js.map +1 -0
  115. package/dist/mcp/builtinTools.d.ts +144 -19
  116. package/dist/mcp/builtinTools.d.ts.map +1 -1
  117. package/dist/mcp/builtinTools.js +119 -20
  118. package/dist/mcp/builtinTools.js.map +1 -1
  119. package/dist/mcp/sanitizeMCPConfig.d.ts +0 -1
  120. package/dist/mcp/sanitizeMCPConfig.d.ts.map +1 -1
  121. package/dist/mcp/sanitizeMCPConfig.js +120 -58
  122. package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
  123. package/dist/stdio.d.ts +3 -2
  124. package/dist/stdio.d.ts.map +1 -1
  125. package/dist/stdio.js +27 -8
  126. package/dist/stdio.js.map +1 -1
  127. package/dist/types.d.ts +62 -108
  128. package/dist/types.d.ts.map +1 -1
  129. package/dist/types.js +4 -4
  130. package/dist/types.js.map +1 -1
  131. package/dist/utils/getPluginConfig.d.ts +1 -1
  132. package/dist/utils/getPluginConfig.js +1 -1
  133. package/dist/utils/getPluginConfig.js.map +1 -1
  134. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts +11 -0
  135. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts.map +1 -0
  136. package/dist/utils/schemaConversion/getEntityInputSchema.js +34 -0
  137. package/dist/utils/schemaConversion/getEntityInputSchema.js.map +1 -0
  138. package/dist/utils/whereSchema.d.ts +9 -0
  139. package/dist/utils/whereSchema.d.ts.map +1 -0
  140. package/dist/utils/whereSchema.js +13 -0
  141. package/dist/utils/whereSchema.js.map +1 -0
  142. package/package.json +8 -11
  143. package/src/defaultAccess.ts +3 -0
  144. package/src/endpoint/access.ts +88 -101
  145. package/src/endpoint/index.ts +14 -1
  146. package/src/exports/client.ts +2 -1
  147. package/src/exports/internal.ts +1 -0
  148. package/src/index.ts +8 -16
  149. package/src/mcp/buildMcpServer.ts +131 -96
  150. package/src/mcp/builtin/collections/authTools.ts +45 -9
  151. package/src/mcp/builtin/collections/countTool.ts +74 -0
  152. package/src/mcp/builtin/collections/countVersionsTool.ts +70 -0
  153. package/src/mcp/builtin/collections/createTool.ts +55 -59
  154. package/src/mcp/builtin/collections/deleteTool.ts +19 -16
  155. package/src/mcp/builtin/collections/duplicateTool.ts +135 -0
  156. package/src/mcp/builtin/collections/findDistinctTool.ts +120 -0
  157. package/src/mcp/builtin/collections/findTool.ts +63 -33
  158. package/src/mcp/builtin/collections/findVersionByIDTool.ts +110 -0
  159. package/src/mcp/builtin/collections/findVersionsTool.ts +155 -0
  160. package/src/mcp/builtin/collections/formatCollectionError.ts +84 -0
  161. package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +46 -0
  162. package/src/mcp/builtin/collections/restoreVersionTool.ts +108 -0
  163. package/src/mcp/builtin/collections/updateTool.ts +111 -110
  164. package/src/mcp/builtin/getConfigInfoTool.ts +69 -0
  165. package/src/mcp/builtin/globals/countVersionsTool.ts +69 -0
  166. package/src/mcp/builtin/globals/findTool.ts +26 -17
  167. package/src/mcp/builtin/globals/findVersionByIDTool.ts +104 -0
  168. package/src/mcp/builtin/globals/findVersionsTool.ts +148 -0
  169. package/src/mcp/builtin/globals/getGlobalSchemaTool.ts +41 -0
  170. package/src/mcp/builtin/globals/restoreVersionTool.ts +100 -0
  171. package/src/mcp/builtin/globals/updateTool.ts +50 -55
  172. package/src/mcp/builtin/validateEntityData.ts +132 -0
  173. package/src/mcp/builtinTools.ts +111 -41
  174. package/src/mcp/sanitizeMCPConfig.ts +116 -78
  175. package/src/stdio.ts +23 -8
  176. package/src/types.ts +77 -112
  177. package/src/utils/getPluginConfig.ts +1 -1
  178. package/src/utils/schemaConversion/getEntityInputSchema.ts +78 -0
  179. package/src/utils/whereSchema.ts +24 -0
  180. package/dist/collection/getAccessField.d.ts +0 -12
  181. package/dist/collection/getAccessField.d.ts.map +0 -1
  182. package/dist/collection/getAccessField.js +0 -57
  183. package/dist/collection/getAccessField.js.map +0 -1
  184. package/dist/collection/index.d.ts +0 -6
  185. package/dist/collection/index.d.ts.map +0 -1
  186. package/dist/collection/index.js +0 -60
  187. package/dist/collection/index.js.map +0 -1
  188. package/dist/components/AccessField/index.client.d.ts +0 -10
  189. package/dist/components/AccessField/index.client.d.ts.map +0 -1
  190. package/dist/components/AccessField/index.client.js +0 -305
  191. package/dist/components/AccessField/index.client.js.map +0 -1
  192. package/dist/components/AccessField/index.css +0 -93
  193. package/dist/utils/schemaConversion/buildToolInput.d.ts +0 -29
  194. package/dist/utils/schemaConversion/buildToolInput.d.ts.map +0 -1
  195. package/dist/utils/schemaConversion/buildToolInput.js +0 -51
  196. package/dist/utils/schemaConversion/buildToolInput.js.map +0 -1
  197. package/src/collection/getAccessField.ts +0 -64
  198. package/src/collection/index.ts +0 -64
  199. package/src/components/AccessField/index.client.tsx +0 -344
  200. package/src/components/AccessField/index.css +0 -93
  201. package/src/utils/schemaConversion/buildToolInput.ts +0 -68
@@ -1,14 +1,8 @@
1
1
  import { McpServer } from '@modelcontextprotocol/server';
2
- import { APIError, entityToStandaloneJSONSchema } from 'payload';
3
- import { toCamelCase } from '../utils/camelCase.js';
2
+ import { APIError } from 'payload';
3
+ import { z } from 'zod';
4
4
  import { getLogger } from '../utils/getLogger.js';
5
- import { getCollectionVirtualFieldNames, getGlobalVirtualFieldNames } from '../utils/getVirtualFieldNames.js';
6
- import { removeVirtualFieldsFromSchema } from '../utils/schemaConversion/removeVirtualFieldsFromSchema.js';
7
5
  import { toStandardSchema } from '../utils/toStandardSchema.js';
8
- /** `findPosts`, `updateSiteSettings` — auto-prefixed wire name for collection/global tools. */ const wireName = (key, slug)=>{
9
- const camel = toCamelCase(slug);
10
- return `${key}${camel.charAt(0).toUpperCase()}${camel.slice(1)}`;
11
- };
12
6
  /**
13
7
  * Transport-agnostic core: registers every authorized MCP item onto a fresh
14
8
  * `McpServer` and returns it. The caller is responsible for picking a transport
@@ -36,79 +30,85 @@ import { toStandardSchema } from '../utils/toStandardSchema.js';
36
30
  const { doc: _doc, ...rest } = overridden;
37
31
  return rest;
38
32
  };
33
+ /**
34
+ * Runs a collection/global tool call:
35
+ * - reads `collectionSlug` / `globalSlug` from the input
36
+ * - runs access control: errors if `authorizedMCP.items` has no entry for this tool + slug
37
+ * - runs the tool handler and finalizes its response
38
+ */ const callEntityTool = async ({ input, item, serverContext })=>{
39
+ const entity = item.type === 'collectionTool' ? 'collection' : 'global';
40
+ const slugKey = item.type === 'collectionTool' ? 'collectionSlug' : 'globalSlug';
41
+ const toolInput = input ?? {};
42
+ const slug = toolInput[slugKey];
43
+ if (!slug) {
44
+ return {
45
+ content: [
46
+ {
47
+ type: 'text',
48
+ text: `Error: "${item.mcpName}" requires ${slugKey}. Use getConfigInfo to inspect ${entity} slugs.`
49
+ }
50
+ ],
51
+ isError: true
52
+ };
53
+ }
54
+ const match = authorizedMCP.items.find((candidate)=>candidate.type === item.type && candidate.mcpName === item.mcpName && (candidate.type === 'collectionTool' ? candidate.collectionSlug === slug : candidate.type === 'globalTool' && candidate.globalSlug === slug));
55
+ if (!match) {
56
+ return {
57
+ content: [
58
+ {
59
+ type: 'text',
60
+ text: `Error: MCP access to "${item.mcpName}" is not enabled for ${entity} "${slug}"`
61
+ }
62
+ ],
63
+ isError: true
64
+ };
65
+ }
66
+ const handlerArgs = {
67
+ authorizedMCP,
68
+ input: toolInput,
69
+ req,
70
+ serverContext
71
+ };
72
+ const response = await (match.type === 'collectionTool' ? match.tool.handler({
73
+ ...handlerArgs,
74
+ collectionSlug: slug
75
+ }) : match.tool.handler({
76
+ ...handlerArgs,
77
+ globalSlug: slug
78
+ }));
79
+ return finalizeToolResponse(response, match.tool.overrideResponse);
80
+ };
39
81
  try {
82
+ const registeredEntityTools = new Set();
40
83
  for (const item of authorizedMCP.items){
41
84
  switch(item.type){
42
85
  case 'collectionTool':
43
- {
44
- const tool = item.tool;
45
- const name = wireName(item.key, item.collectionSlug);
46
- let inputSchema = tool.input;
47
- if (typeof inputSchema === 'function') {
48
- const collection = req.payload.collections[item.collectionSlug]?.config;
49
- if (!collection) {
50
- throw new APIError(`Collection schema not found for slug: ${item.collectionSlug}`, 500);
51
- }
52
- const collectionSchema = removeVirtualFieldsFromSchema(entityToStandaloneJSONSchema({
53
- config: req.payload.config,
54
- defaultIDType: req.payload.db.defaultIDType,
55
- entity: collection,
56
- i18n: req.i18n
57
- }), getCollectionVirtualFieldNames(req.payload.config, item.collectionSlug));
58
- inputSchema = inputSchema({
59
- collectionSchema
60
- });
61
- }
62
- server.registerTool(name, {
63
- description: tool.description,
64
- inputSchema: inputSchema ? toStandardSchema(inputSchema) : undefined
65
- }, async (input, ctx)=>finalizeToolResponse(await tool.handler({
66
- authorizedMCP,
67
- collectionSlug: item.collectionSlug,
68
- input: input ?? {},
69
- req,
70
- serverContext: ctx
71
- }), tool.overrideResponse));
72
- logger.info(`✅ Tool: ${name} Registered.`);
73
- break;
74
- }
75
86
  case 'globalTool':
76
87
  {
77
- const tool = item.tool;
78
- const name = wireName(item.key, item.globalSlug);
79
- let inputSchema = tool.input;
80
- if (typeof inputSchema === 'function') {
81
- const globalEntity = req.payload.config.globals.find((globalConfig)=>globalConfig.slug === item.globalSlug);
82
- if (!globalEntity) {
83
- throw new APIError(`Global schema not found for slug: ${item.globalSlug}`, 500);
84
- }
85
- const globalSchema = removeVirtualFieldsFromSchema(entityToStandaloneJSONSchema({
86
- config: req.payload.config,
87
- defaultIDType: req.payload.db.defaultIDType,
88
- entity: globalEntity,
89
- i18n: req.i18n
90
- }), getGlobalVirtualFieldNames(req.payload.config, item.globalSlug));
91
- inputSchema = inputSchema({
92
- globalSchema
93
- });
88
+ if (registeredEntityTools.has(item.mcpName)) {
89
+ break;
94
90
  }
95
- server.registerTool(name, {
96
- description: tool.description,
97
- inputSchema: inputSchema ? toStandardSchema(inputSchema) : undefined
98
- }, async (input, ctx)=>finalizeToolResponse(await tool.handler({
99
- authorizedMCP,
100
- globalSlug: item.globalSlug,
101
- input: input ?? {},
102
- req,
91
+ registeredEntityTools.add(item.mcpName);
92
+ const inputSchema = withSlugInput({
93
+ name: item.type === 'collectionTool' ? 'collectionSlug' : 'globalSlug',
94
+ input: item.tool.input
95
+ });
96
+ server.registerTool(item.mcpName, {
97
+ annotations: item.tool.annotations,
98
+ description: item.tool.description,
99
+ inputSchema: toStandardSchema(inputSchema)
100
+ }, async (input, ctx)=>callEntityTool({
101
+ input,
102
+ item,
103
103
  serverContext: ctx
104
- }), tool.overrideResponse));
105
- logger.info(`✅ Tool: ${name} Registered.`);
104
+ }));
105
+ logger.info(`✅ Tool: ${item.mcpName} Registered.`);
106
106
  break;
107
107
  }
108
108
  case 'prompt':
109
109
  {
110
110
  const prompt = item.prompt;
111
- server.registerPrompt(item.key, {
111
+ server.registerPrompt(item.mcpName, {
112
112
  argsSchema: prompt.argsSchema ? toStandardSchema(prompt.argsSchema) : undefined,
113
113
  description: prompt.description,
114
114
  title: prompt.title
@@ -123,7 +123,7 @@ import { toStandardSchema } from '../utils/toStandardSchema.js';
123
123
  case 'resource':
124
124
  {
125
125
  const resource = item.resource;
126
- server.registerResource(item.key, // @ts-expect-error - Overload type ambiguity (string OR ResourceTemplate is valid)
126
+ server.registerResource(item.mcpName, // @ts-expect-error - Overload type ambiguity (string OR ResourceTemplate is valid)
127
127
  resource.uri, {
128
128
  description: resource.description,
129
129
  mimeType: resource.mimeType,
@@ -147,7 +147,8 @@ import { toStandardSchema } from '../utils/toStandardSchema.js';
147
147
  case 'tool':
148
148
  {
149
149
  const tool = item.tool;
150
- server.registerTool(item.key, {
150
+ server.registerTool(item.mcpName, {
151
+ annotations: tool.annotations,
151
152
  description: tool.description,
152
153
  inputSchema: tool.input ? toStandardSchema(tool.input) : undefined
153
154
  }, async (input, ctx)=>finalizeToolResponse(await tool.handler({
@@ -156,7 +157,7 @@ import { toStandardSchema } from '../utils/toStandardSchema.js';
156
157
  req,
157
158
  serverContext: ctx
158
159
  }), tool.overrideResponse));
159
- logger.info(`✅ Tool: ${item.key} Registered.`);
160
+ logger.info(`✅ Tool: ${item.mcpName} Registered.`);
160
161
  break;
161
162
  }
162
163
  }
@@ -166,5 +167,35 @@ import { toStandardSchema } from '../utils/toStandardSchema.js';
166
167
  }
167
168
  return server;
168
169
  };
170
+ const withSlugInput = ({ name, input })=>{
171
+ const description = name === 'collectionSlug' ? 'The collection slug' : 'The global slug';
172
+ const slugSchema = z.string().describe(description);
173
+ if (!input) {
174
+ return z.object({
175
+ [name]: slugSchema
176
+ });
177
+ }
178
+ if (input instanceof z.ZodObject) {
179
+ return input.extend({
180
+ [name]: slugSchema
181
+ });
182
+ }
183
+ const schema = input;
184
+ return {
185
+ ...schema,
186
+ type: 'object',
187
+ properties: {
188
+ ...schema.properties,
189
+ [name]: {
190
+ type: 'string',
191
+ description
192
+ }
193
+ },
194
+ required: Array.from(new Set([
195
+ name,
196
+ ...schema.required ?? []
197
+ ]))
198
+ };
199
+ };
169
200
 
170
201
  //# sourceMappingURL=buildMcpServer.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/mcp/buildMcpServer.ts"],"sourcesContent":["import { McpServer, type ServerContext } from '@modelcontextprotocol/server'\nimport { APIError, entityToStandaloneJSONSchema, type PayloadRequest } from 'payload'\n\nimport type {\n AuthorizedMCP,\n JsonSchemaType,\n MCPResponseOverride,\n MCPToolResponse,\n SanitizedMCPPluginConfig,\n} from '../types.js'\n\nimport { toCamelCase } from '../utils/camelCase.js'\nimport { getLogger } from '../utils/getLogger.js'\nimport {\n getCollectionVirtualFieldNames,\n getGlobalVirtualFieldNames,\n} from '../utils/getVirtualFieldNames.js'\nimport { removeVirtualFieldsFromSchema } from '../utils/schemaConversion/removeVirtualFieldsFromSchema.js'\nimport { toStandardSchema } from '../utils/toStandardSchema.js'\n\n/** `findPosts`, `updateSiteSettings` — auto-prefixed wire name for collection/global tools. */\nconst wireName = (key: string, slug: string): string => {\n const camel = toCamelCase(slug)\n return `${key}${camel.charAt(0).toUpperCase()}${camel.slice(1)}`\n}\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 try {\n for (const item of authorizedMCP.items) {\n switch (item.type) {\n case 'collectionTool': {\n const tool = item.tool\n const name = wireName(item.key, item.collectionSlug)\n let inputSchema = tool.input\n if (typeof inputSchema === 'function') {\n const collection = req.payload.collections[item.collectionSlug]?.config\n if (!collection) {\n throw new APIError(\n `Collection schema not found for slug: ${item.collectionSlug}`,\n 500,\n )\n }\n const collectionSchema = removeVirtualFieldsFromSchema(\n entityToStandaloneJSONSchema({\n config: req.payload.config,\n defaultIDType: req.payload.db.defaultIDType,\n entity: collection,\n i18n: req.i18n,\n }) as unknown as JsonSchemaType,\n getCollectionVirtualFieldNames(req.payload.config, item.collectionSlug),\n )\n inputSchema = inputSchema({ collectionSchema })\n }\n server.registerTool(\n name,\n {\n description: tool.description,\n inputSchema: inputSchema ? toStandardSchema(inputSchema) : undefined,\n },\n async (input: unknown, ctx: ServerContext) =>\n finalizeToolResponse(\n await tool.handler({\n authorizedMCP,\n collectionSlug: item.collectionSlug,\n input: (input ?? {}) as Record<string, unknown>,\n req,\n serverContext: ctx,\n }),\n tool.overrideResponse,\n ),\n )\n logger.info(`✅ Tool: ${name} Registered.`)\n break\n }\n case 'globalTool': {\n const tool = item.tool\n const name = wireName(item.key, item.globalSlug)\n let inputSchema = tool.input\n if (typeof inputSchema === 'function') {\n const globalEntity = req.payload.config.globals.find(\n (globalConfig) => globalConfig.slug === item.globalSlug,\n )\n if (!globalEntity) {\n throw new APIError(`Global schema not found for slug: ${item.globalSlug}`, 500)\n }\n const globalSchema = removeVirtualFieldsFromSchema(\n entityToStandaloneJSONSchema({\n config: req.payload.config,\n defaultIDType: req.payload.db.defaultIDType,\n entity: globalEntity,\n i18n: req.i18n,\n }) as unknown as JsonSchemaType,\n getGlobalVirtualFieldNames(req.payload.config, item.globalSlug),\n )\n\n inputSchema = inputSchema({ globalSchema })\n }\n server.registerTool(\n name,\n {\n description: tool.description,\n inputSchema: inputSchema ? toStandardSchema(inputSchema) : undefined,\n },\n async (input: unknown, ctx: ServerContext) =>\n finalizeToolResponse(\n await tool.handler({\n authorizedMCP,\n globalSlug: item.globalSlug,\n input: (input ?? {}) as Record<string, unknown>,\n req,\n serverContext: ctx,\n }),\n tool.overrideResponse,\n ),\n )\n logger.info(`✅ Tool: ${name} Registered.`)\n break\n }\n case 'prompt': {\n const prompt = item.prompt\n server.registerPrompt(\n item.key,\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.key,\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.key,\n {\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.key} 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"],"names":["McpServer","APIError","entityToStandaloneJSONSchema","toCamelCase","getLogger","getCollectionVirtualFieldNames","getGlobalVirtualFieldNames","removeVirtualFieldsFromSchema","toStandardSchema","wireName","key","slug","camel","charAt","toUpperCase","slice","buildMcpServer","authorizedMCP","pluginConfig","req","serverOptions","mcp","server","name","version","serverInfo","options","logger","payload","finalizeToolResponse","response","overrideResponse","overridden","doc","_doc","rest","item","items","type","tool","collectionSlug","inputSchema","input","collection","collections","config","collectionSchema","defaultIDType","db","entity","i18n","registerTool","description","undefined","ctx","handler","serverContext","info","globalSlug","globalEntity","globals","find","globalConfig","globalSchema","prompt","registerPrompt","argsSchema","title","resource","registerResource","uri","mimeType","sdkArgs","length","params","error","String"],"mappings":"AAAA,SAASA,SAAS,QAA4B,+BAA8B;AAC5E,SAASC,QAAQ,EAAEC,4BAA4B,QAA6B,UAAS;AAUrF,SAASC,WAAW,QAAQ,wBAAuB;AACnD,SAASC,SAAS,QAAQ,wBAAuB;AACjD,SACEC,8BAA8B,EAC9BC,0BAA0B,QACrB,mCAAkC;AACzC,SAASC,6BAA6B,QAAQ,6DAA4D;AAC1G,SAASC,gBAAgB,QAAQ,+BAA8B;AAE/D,6FAA6F,GAC7F,MAAMC,WAAW,CAACC,KAAaC;IAC7B,MAAMC,QAAQT,YAAYQ;IAC1B,OAAO,GAAGD,MAAME,MAAMC,MAAM,CAAC,GAAGC,WAAW,KAAKF,MAAMG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E;4BACtB,MAAME,SAAUF,QAAQC,MAAM,GAAG,IAAID,OAAO,CAAC,EAAE,GAAG,CAAC;4BACnD,OAAOJ,SAASb,OAAO,CAAC;gCAAEmB;gCAAQvD;gCAAKqC,eAAeF;gCAAKgB;4BAAI;wBACjE;wBAEF3C,OAAO8B,IAAI,CAAC,CAAC,YAAY,EAAEW,SAASD,KAAK,CAAC,YAAY,CAAC;wBACvD;oBACF;gBACA,KAAK;oBAAQ;wBACX,MAAM5B,OAAOH,KAAKG,IAAI;wBACtBjB,OAAO6B,YAAY,CACjBf,KAAK1B,GAAG,EACR;4BACE0C,aAAab,KAAKa,WAAW;4BAC7BX,aAAaF,KAAKG,KAAK,GAAGlC,iBAAiB+B,KAAKG,KAAK,IAAIW;wBAC3D,GACA,OAAOX,OAAgBY,MACrBzB,qBACE,MAAMU,KAAKgB,OAAO,CAAC;gCACjBtC;gCACAyB,OAAQA,SAAS,CAAC;gCAClBvB;gCACAqC,eAAeF;4BACjB,IACAf,KAAKR,gBAAgB;wBAG3BJ,OAAO8B,IAAI,CAAC,CAAC,QAAQ,EAAErB,KAAK1B,GAAG,CAAC,YAAY,CAAC;wBAC7C;oBACF;YACF;QACF;IACF,EAAE,OAAOiE,OAAO;QACd,MAAM,IAAI1E,SAAS,CAAC,gCAAgC,EAAE2E,OAAOD,QAAQ,EAAE;IACzE;IAEA,OAAOrD;AACT,EAAC"}
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","Array","from"],"mappings":"AAAA,SAASA,SAAS,QAA4B,+BAA8B;AAC5E,SAASC,QAAQ,QAA6B,UAAS;AACvD,SAASC,CAAC,QAAQ,MAAK;AAavB,SAASC,SAAS,QAAQ,wBAAuB;AACjD,SAASC,gBAAgB,QAAQ,+BAA8B;AAE/D;;;;;;;;;CASC,GACD,OAAO,MAAMC,iBAAiB,CAAC,EAC7BC,aAAa,EACbC,YAAY,EACZC,GAAG,EAKJ;IACC,MAAMC,gBAAgBF,aAAaG,GAAG,EAAED,iBAAiB,CAAC;IAC1D,MAAME,SAAS,IAAIX,UACjB;QAAEY,MAAM;QAAsBC,SAAS;QAAS,GAAGJ,cAAcK,UAAU;IAAC,GAC5EL,cAAcM,OAAO;IAGvB,MAAMC,SAASb,UAAU;QAAEc,SAAST,IAAIS,OAAO;IAAC;IAEhD;;;GAGC,GACD,MAAMC,uBAAuB,CAC3BC,UACAC;QAEA,MAAMC,aAAaD,mBAAmBD,UAAUA,SAASG,GAAG,IAAI,CAAC,GAAGd,QAAQW;QAC5E,MAAM,EAAEG,KAAKC,IAAI,EAAE,GAAGC,MAAM,GAAGH;QAC/B,OAAOG;IACT;IAEA;;;;;GAKC,GACD,MAAMC,iBAAiB,OAAO,EAC5BC,KAAK,EACLC,IAAI,EACJC,aAAa,EAKd;QACC,MAAMC,SAASF,KAAKG,IAAI,KAAK,mBAAmB,eAAe;QAC/D,MAAMC,UAAUJ,KAAKG,IAAI,KAAK,mBAAmB,mBAAmB;QACpE,M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BAAwB;IACxE,MAAM4D,aAAatE,EAAEuE,MAAM,GAAGC,QAAQ,CAACnB;IAEvC,IAAI,CAAC7B,OAAO;QACV,OAAOxB,EAAEyE,MAAM,CAAC;YAAE,CAAC/D,KAAK,EAAE4D;QAAW;IACvC;IAEA,IAAI9C,iBAAiBxB,EAAE0E,SAAS,EAAE;QAChC,OAAOlD,MAAMmD,MAAM,CAAC;YAAE,CAACjE,KAAK,EAAE4D;QAAW;IAC3C;IAEA,MAAMM,SAASpD;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 +1 @@
1
- {"version":3,"file":"authTools.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/authTools.ts"],"names":[],"mappings":"AAiCA,eAAO,MAAM,kBAAkB,4CAoC7B,CAAA;AAEF,eAAO,MAAM,4BAA4B,4CAgCvC,CAAA;AAEF,eAAO,MAAM,mBAAmB,4CA0C9B,CAAA;AAEF,eAAO,MAAM,2BAA2B,4CA4BtC,CAAA;AAEF,eAAO,MAAM,oBAAoB,4CAyB/B,CAAA;AAEF,eAAO,MAAM,oBAAoB,4CA0B/B,CAAA"}
1
+ {"version":3,"file":"authTools.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/authTools.ts"],"names":[],"mappings":"AAiCA,eAAO,MAAM,kBAAkB,4CAqC7B,CAAA;AAEF,eAAO,MAAM,4BAA4B,4CAuCvC,CAAA;AAEF,eAAO,MAAM,mBAAmB,4CAiD9B,CAAA;AAEF,eAAO,MAAM,2BAA2B,4CAmCtC,CAAA;AAEF,eAAO,MAAM,oBAAoB,4CAgC/B,CAAA;AAEF,eAAO,MAAM,oBAAoB,4CAiC/B,CAAA"}
@@ -22,9 +22,16 @@ const wrapError = (name)=>({ collectionSlug, message })=>{
22
22
  };
23
23
  };
24
24
  export const authCollectionTool = defineCollectionTool({
25
+ annotations: {
26
+ destructiveHint: false,
27
+ idempotentHint: true,
28
+ openWorldHint: false,
29
+ readOnlyHint: true,
30
+ title: 'Check Auth Status'
31
+ },
25
32
  description: 'Checks authentication status for the current user.',
26
33
  input: z.object({
27
- headers: z.string().describe('Optional JSON string containing custom headers to send with the authentication request').optional()
34
+ headers: z.record(z.string(), z.string()).describe('Optional custom headers to send with the authentication request').optional()
28
35
  })
29
36
  }).handler(async ({ collectionSlug, input, req })=>{
30
37
  const logger = getLogger({
@@ -33,11 +40,7 @@ export const authCollectionTool = defineCollectionTool({
33
40
  try {
34
41
  let authHeaders = new Headers();
35
42
  if (input.headers) {
36
- try {
37
- authHeaders = new Headers(JSON.parse(input.headers));
38
- } catch {
39
- logger.warn(`Invalid headers JSON for auth: ${input.headers}, using empty headers`);
40
- }
43
+ authHeaders = new Headers(input.headers);
41
44
  }
42
45
  const result = await req.payload.auth({
43
46
  headers: authHeaders
@@ -61,6 +64,13 @@ export const authCollectionTool = defineCollectionTool({
61
64
  }
62
65
  });
63
66
  export const forgotPasswordCollectionTool = defineCollectionTool({
67
+ annotations: {
68
+ destructiveHint: false,
69
+ idempotentHint: false,
70
+ openWorldHint: true,
71
+ readOnlyHint: false,
72
+ title: 'Forgot Password'
73
+ },
64
74
  description: 'Sends a password reset email to a user.',
65
75
  input: z.object({
66
76
  disableEmail: z.boolean().describe('Whether to disable sending the email (for testing)').optional().default(false),
@@ -99,6 +109,13 @@ export const forgotPasswordCollectionTool = defineCollectionTool({
99
109
  }
100
110
  });
101
111
  export const loginCollectionTool = defineCollectionTool({
112
+ annotations: {
113
+ destructiveHint: false,
114
+ idempotentHint: false,
115
+ openWorldHint: false,
116
+ readOnlyHint: false,
117
+ title: 'User Login'
118
+ },
102
119
  description: 'Authenticates a user with email and password.',
103
120
  input: z.object({
104
121
  depth: z.number().int().min(0).max(10).describe('Depth of population for relationships').optional().default(0),
@@ -139,6 +156,13 @@ export const loginCollectionTool = defineCollectionTool({
139
156
  }
140
157
  });
141
158
  export const resetPasswordCollectionTool = defineCollectionTool({
159
+ annotations: {
160
+ destructiveHint: false,
161
+ idempotentHint: false,
162
+ openWorldHint: false,
163
+ readOnlyHint: false,
164
+ title: 'Reset Password'
165
+ },
142
166
  description: 'Resets a user password with a reset token.',
143
167
  input: z.object({
144
168
  password: z.string().describe('The new password for the user'),
@@ -176,6 +200,13 @@ export const resetPasswordCollectionTool = defineCollectionTool({
176
200
  }
177
201
  });
178
202
  export const unlockCollectionTool = defineCollectionTool({
203
+ annotations: {
204
+ destructiveHint: false,
205
+ idempotentHint: true,
206
+ openWorldHint: false,
207
+ readOnlyHint: false,
208
+ title: 'Unlock Account'
209
+ },
179
210
  description: 'Unlocks a user account that has been locked due to failed login attempts.',
180
211
  input: z.object({
181
212
  email: emailSchema
@@ -213,6 +244,13 @@ export const unlockCollectionTool = defineCollectionTool({
213
244
  }
214
245
  });
215
246
  export const verifyCollectionTool = defineCollectionTool({
247
+ annotations: {
248
+ destructiveHint: false,
249
+ idempotentHint: false,
250
+ openWorldHint: false,
251
+ readOnlyHint: false,
252
+ title: 'Email Verification'
253
+ },
216
254
  description: 'Verifies a user email with a verification token.',
217
255
  input: z.object({
218
256
  token: z.string().describe('The verification token sent to the user email')
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/mcp/builtin/collections/authTools.ts"],"sourcesContent":["import { z } from 'zod'\n\nimport type { MCPToolResponse } from '../../../types.js'\n\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\n\n/**\n * Auth tools surfaced under `collections.<auth-collection>.tools`. Opt-in: they\n * default off (an LLM with `login` access can probe passwords; not something\n * to expose by default). Enable in plugin config via `tools: { login: true }`\n * (or `{ description: '...' }`).\n *\n * `auth` (check current token) doesn't actually depend on the collection at\n * runtime — `payload.auth({ headers })` is global — but it's grouped under the\n * users collection so all auth-shaped tools live in one place.\n */\n\nconst emailSchema = z.string().email().describe('The user email address')\n\nconst wrapError =\n (name: string) =>\n ({ collectionSlug, message }: { collectionSlug: string; message: string }): MCPToolResponse => {\n return {\n content: [\n {\n type: 'text',\n text: `❌ **Error in ${name}** on ${collectionSlug}: ${message}`,\n },\n ],\n }\n }\n\nexport const authCollectionTool = defineCollectionTool({\n description: 'Checks authentication status for the current user.',\n input: z.object({\n headers: z\n .string()\n .describe(\n 'Optional JSON string containing custom headers to send with the authentication request',\n )\n .optional(),\n }),\n}).handler(async ({ collectionSlug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n let authHeaders = new Headers()\n if (input.headers) {\n try {\n authHeaders = new Headers(JSON.parse(input.headers) as Record<string, string>)\n } catch {\n logger.warn(`Invalid headers JSON for auth: ${input.headers}, using empty headers`)\n }\n }\n const result = await req.payload.auth({ headers: authHeaders })\n return {\n content: [\n {\n type: 'text',\n text: `# Authentication Status\\n\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as unknown as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error in auth tool on ${collectionSlug}: ${errorMessage}`)\n return wrapError('auth')({ collectionSlug, message: errorMessage })\n }\n})\n\nexport const forgotPasswordCollectionTool = defineCollectionTool({\n description: 'Sends a password reset email to a user.',\n input: z.object({\n disableEmail: z\n .boolean()\n .describe('Whether to disable sending the email (for testing)')\n .optional()\n .default(false),\n email: emailSchema,\n }),\n}).handler(async ({ collectionSlug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.forgotPassword({\n collection: collectionSlug,\n data: { email: input.email },\n disableEmail: input.disableEmail,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Forgot Password Email Sent\\n\\n**Collection:** ${collectionSlug}\\n**Email:** ${input.email}\\n\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: { result } as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error in forgotPassword tool on ${collectionSlug}: ${errorMessage}`)\n return wrapError('forgotPassword')({ collectionSlug, message: errorMessage })\n }\n})\n\nexport const loginCollectionTool = defineCollectionTool({\n description: 'Authenticates a user with email and password.',\n input: z.object({\n depth: z\n .number()\n .int()\n .min(0)\n .max(10)\n .describe('Depth of population for relationships')\n .optional()\n .default(0),\n email: emailSchema,\n password: z.string().describe('The user password'),\n showHiddenFields: z\n .boolean()\n .describe('Whether to show hidden fields in the response')\n .optional()\n .default(false),\n }),\n}).handler(async ({ collectionSlug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.login({\n collection: collectionSlug,\n data: { email: input.email, password: input.password },\n depth: input.depth,\n showHiddenFields: input.showHiddenFields,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Login Successful\\n\\n**User:** ${input.email}\\n**Collection:** ${collectionSlug}\\n\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as unknown as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error in login tool on ${collectionSlug}: ${errorMessage}`)\n return wrapError('login')({ collectionSlug, message: errorMessage })\n }\n})\n\nexport const resetPasswordCollectionTool = defineCollectionTool({\n description: 'Resets a user password with a reset token.',\n input: z.object({\n password: z.string().describe('The new password for the user'),\n token: z.string().describe('The password reset token sent to the user email'),\n }),\n}).handler(async ({ collectionSlug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.resetPassword({\n collection: collectionSlug,\n data: { password: input.password, token: input.token },\n overrideAccess: true,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Password Reset Successful\\n\\n**Collection:** ${collectionSlug}\\n\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as unknown as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error in resetPassword tool on ${collectionSlug}: ${errorMessage}`)\n return wrapError('resetPassword')({ collectionSlug, message: errorMessage })\n }\n})\n\nexport const unlockCollectionTool = defineCollectionTool({\n description: 'Unlocks a user account that has been locked due to failed login attempts.',\n input: z.object({ email: emailSchema }),\n}).handler(async ({ collectionSlug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.unlock({\n collection: collectionSlug,\n data: { email: input.email },\n overrideAccess: true,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Account Unlocked\\n\\n**Collection:** ${collectionSlug}\\n**Email:** ${input.email}\\n**Result:** ${result ? 'Success' : 'Failed'}`,\n },\n ],\n doc: { result } as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error in unlock tool on ${collectionSlug}: ${errorMessage}`)\n return wrapError('unlock')({ collectionSlug, message: errorMessage })\n }\n})\n\nexport const verifyCollectionTool = defineCollectionTool({\n description: 'Verifies a user email with a verification token.',\n input: z.object({\n token: z.string().describe('The verification token sent to the user email'),\n }),\n}).handler(async ({ collectionSlug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.verifyEmail({\n collection: collectionSlug,\n token: input.token,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Email Verification Successful\\n\\n**Collection:** ${collectionSlug}\\n**Result:** ${result ? 'Success' : 'Failed'}`,\n },\n ],\n doc: { result } as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error in verify tool on ${collectionSlug}: ${errorMessage}`)\n return wrapError('verify')({ collectionSlug, message: errorMessage })\n }\n})\n"],"names":["z","defineCollectionTool","getLogger","emailSchema","string","email","describe","wrapError","name","collectionSlug","message","content","type","text","authCollectionTool","description","input","object","headers","optional","handler","req","logger","payload","authHeaders","Headers","JSON","parse","warn","result","auth","stringify","doc","error","errorMessage","Error","forgotPasswordCollectionTool","disableEmail","boolean","default","forgotPassword","collection","data","loginCollectionTool","depth","number","int","min","max","password","showHiddenFields","login","resetPasswordCollectionTool","token","resetPassword","overrideAccess","unlockCollectionTool","unlock","verifyCollectionTool","verifyEmail"],"mappings":"AAAA,SAASA,CAAC,QAAQ,MAAK;AAIvB,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AAEvD;;;;;;;;;CASC,GAED,MAAMC,cAAcH,EAAEI,MAAM,GAAGC,KAAK,GAAGC,QAAQ,CAAC;AAEhD,MAAMC,YACJ,CAACC,OACD,CAAC,EAAEC,cAAc,EAAEC,OAAO,EAA+C;QACvE,OAAO;YACLC,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,aAAa,EAAEL,KAAK,MAAM,EAAEC,eAAe,EAAE,EAAEC,SAAS;gBACjE;aACD;QACH;IACF;AAEF,OAAO,MAAMI,qBAAqBb,qBAAqB;IACrDc,aAAa;IACbC,OAAOhB,EAAEiB,MAAM,CAAC;QACdC,SAASlB,EACNI,MAAM,GACNE,QAAQ,CACP,0FAEDa,QAAQ;IACb;AACF,GAAGC,OAAO,CAAC,OAAO,EAAEX,cAAc,EAAEO,KAAK,EAAEK,GAAG,EAAE;IAC9C,MAAMC,SAASpB,UAAU;QAAEqB,SAASF,IAAIE,OAAO;IAAC;IAChD,IAAI;QACF,IAAIC,cAAc,IAAIC;QACtB,IAAIT,MAAME,OAAO,EAAE;YACjB,IAAI;gBACFM,cAAc,IAAIC,QAAQC,KAAKC,KAAK,CAACX,MAAME,OAAO;YACpD,EAAE,OAAM;gBACNI,OAAOM,IAAI,CAAC,CAAC,+BAA+B,EAAEZ,MAAME,OAAO,CAAC,qBAAqB,CAAC;YACpF;QACF;QACA,MAAMW,SAAS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AE,OAAOI,OAAO;QACd,MAAMC,eAAeD,iBAAiBE,QAAQF,MAAMvB,OAAO,GAAG;QAC9DY,OAAOW,KAAK,CAAC,CAAC,wBAAwB,EAAExB,eAAe,EAAE,EAAEyB,cAAc;QACzE,OAAO3B,UAAU,UAAU;YAAEE;YAAgBC,SAASwB;QAAa;IACrE;AACF,GAAE"}
1
+ {"version":3,"sources":["../../../../src/mcp/builtin/collections/authTools.ts"],"sourcesContent":["import { z } from 'zod'\n\nimport type { MCPToolResponse } from '../../../types.js'\n\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\n\n/**\n * Auth tools surfaced under `collections.<auth-collection>.tools`. Opt-in: they\n * default off (an LLM with `login` access can probe passwords; not something\n * to expose by default). Enable in plugin config via `tools: { login: true }`\n * (or `{ description: '...' }`).\n *\n * `auth` (check current token) doesn't actually depend on the collection at\n * runtime — `payload.auth({ headers })` is global — but it's grouped under the\n * users collection so all auth-shaped tools live in one place.\n */\n\nconst emailSchema = z.string().email().describe('The user email address')\n\nconst wrapError =\n (name: string) =>\n ({ collectionSlug, message }: { collectionSlug: string; message: string }): MCPToolResponse => {\n return {\n content: [\n {\n type: 'text',\n text: `❌ **Error in ${name}** on ${collectionSlug}: ${message}`,\n },\n ],\n }\n }\n\nexport const authCollectionTool = defineCollectionTool({\n annotations: {\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n readOnlyHint: true,\n title: 'Check Auth Status',\n },\n description: 'Checks authentication status for the current user.',\n input: z.object({\n headers: z\n .record(z.string(), z.string())\n .describe('Optional custom headers to send with the authentication request')\n .optional(),\n }),\n}).handler(async ({ collectionSlug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n let authHeaders = new Headers()\n if (input.headers) {\n authHeaders = new Headers(input.headers)\n }\n const result = await req.payload.auth({ headers: authHeaders })\n return {\n content: [\n {\n type: 'text',\n text: `# Authentication Status\\n\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as unknown as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error in auth tool on ${collectionSlug}: ${errorMessage}`)\n return wrapError('auth')({ collectionSlug, message: errorMessage })\n }\n})\n\nexport const forgotPasswordCollectionTool = defineCollectionTool({\n annotations: {\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: true,\n readOnlyHint: false,\n title: 'Forgot Password',\n },\n description: 'Sends a password reset email to a user.',\n input: z.object({\n disableEmail: z\n .boolean()\n .describe('Whether to disable sending the email (for testing)')\n .optional()\n .default(false),\n email: emailSchema,\n }),\n}).handler(async ({ collectionSlug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.forgotPassword({\n collection: collectionSlug,\n data: { email: input.email },\n disableEmail: input.disableEmail,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Forgot Password Email Sent\\n\\n**Collection:** ${collectionSlug}\\n**Email:** ${input.email}\\n\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: { result } as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error in forgotPassword tool on ${collectionSlug}: ${errorMessage}`)\n return wrapError('forgotPassword')({ collectionSlug, message: errorMessage })\n }\n})\n\nexport const loginCollectionTool = defineCollectionTool({\n annotations: {\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'User Login',\n },\n description: 'Authenticates a user with email and password.',\n input: z.object({\n depth: z\n .number()\n .int()\n .min(0)\n .max(10)\n .describe('Depth of population for relationships')\n .optional()\n .default(0),\n email: emailSchema,\n password: z.string().describe('The user password'),\n showHiddenFields: z\n .boolean()\n .describe('Whether to show hidden fields in the response')\n .optional()\n .default(false),\n }),\n}).handler(async ({ collectionSlug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.login({\n collection: collectionSlug,\n data: { email: input.email, password: input.password },\n depth: input.depth,\n showHiddenFields: input.showHiddenFields,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Login Successful\\n\\n**User:** ${input.email}\\n**Collection:** ${collectionSlug}\\n\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as unknown as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error in login tool on ${collectionSlug}: ${errorMessage}`)\n return wrapError('login')({ collectionSlug, message: errorMessage })\n }\n})\n\nexport const resetPasswordCollectionTool = defineCollectionTool({\n annotations: {\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'Reset Password',\n },\n description: 'Resets a user password with a reset token.',\n input: z.object({\n password: z.string().describe('The new password for the user'),\n token: z.string().describe('The password reset token sent to the user email'),\n }),\n}).handler(async ({ collectionSlug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.resetPassword({\n collection: collectionSlug,\n data: { password: input.password, token: input.token },\n overrideAccess: true,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Password Reset Successful\\n\\n**Collection:** ${collectionSlug}\\n\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as unknown as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error in resetPassword tool on ${collectionSlug}: ${errorMessage}`)\n return wrapError('resetPassword')({ collectionSlug, message: errorMessage })\n }\n})\n\nexport const unlockCollectionTool = defineCollectionTool({\n annotations: {\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'Unlock Account',\n },\n description: 'Unlocks a user account that has been locked due to failed login attempts.',\n input: z.object({ email: emailSchema }),\n}).handler(async ({ collectionSlug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.unlock({\n collection: collectionSlug,\n data: { email: input.email },\n overrideAccess: true,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Account Unlocked\\n\\n**Collection:** ${collectionSlug}\\n**Email:** ${input.email}\\n**Result:** ${result ? 'Success' : 'Failed'}`,\n },\n ],\n doc: { result } as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error in unlock tool on ${collectionSlug}: ${errorMessage}`)\n return wrapError('unlock')({ collectionSlug, message: errorMessage })\n }\n})\n\nexport const verifyCollectionTool = defineCollectionTool({\n annotations: {\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'Email Verification',\n },\n description: 'Verifies a user email with a verification token.',\n input: z.object({\n token: z.string().describe('The verification token sent to the user email'),\n }),\n}).handler(async ({ collectionSlug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.verifyEmail({\n collection: collectionSlug,\n token: input.token,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Email Verification Successful\\n\\n**Collection:** ${collectionSlug}\\n**Result:** ${result ? 'Success' : 'Failed'}`,\n },\n ],\n doc: { result } as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error in verify tool on ${collectionSlug}: ${errorMessage}`)\n return wrapError('verify')({ collectionSlug, message: errorMessage })\n }\n})\n"],"names":["z","defineCollectionTool","getLogger","emailSchema","string","email","describe","wrapError","name","collectionSlug","message","content","type","text","authCollectionTool","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","object","headers","record","optional","handler","req","logger","payload","authHeaders","Headers","result","auth","JSON","stringify","doc","error","errorMessage","Error","forgotPasswordCollectionTool","disableEmail","boolean","default","forgotPassword","collection","data","loginCollectionTool","depth","number","int","min","max","password","showHiddenFields","login","resetPasswordCollectionTool","token","resetPassword","overrideAccess","unlockCollectionT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AYrC;YACZiD,OAAOpC,MAAMoC,KAAK;QACpB;QACA,OAAO;YACL/C,SAAS;gBACP;oBACEC,MAAM;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"}
@@ -0,0 +1,2 @@
1
+ export declare const countDocumentsTool: import("../../../types.js").CollectionTool;
2
+ //# sourceMappingURL=countTool.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"countTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/countTool.ts"],"names":[],"mappings":"AAWA,eAAO,MAAM,kBAAkB,4CA8D7B,CAAA"}
@@ -0,0 +1,69 @@
1
+ import { z } from 'zod';
2
+ import { defaultAccess } from '../../../defaultAccess.js';
3
+ import { defineCollectionTool } from '../../../defineTool.js';
4
+ import { getLogger } from '../../../utils/getLogger.js';
5
+ import { localAPIDefaults } from '../../../utils/localAPIDefaults.js';
6
+ import { whereSchema } from '../../../utils/whereSchema.js';
7
+ const DEFAULT_DESCRIPTION = 'Count documents in any collection by passing the collection slug and optional where clause.';
8
+ export const countDocumentsTool = defineCollectionTool({
9
+ access: (args)=>defaultAccess(args) && Boolean(args.permissions?.collections?.[args.collectionSlug]?.read),
10
+ annotations: {
11
+ destructiveHint: false,
12
+ idempotentHint: true,
13
+ openWorldHint: false,
14
+ readOnlyHint: true,
15
+ title: 'Count Documents'
16
+ },
17
+ 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 })=>{
24
+ const payload = req.payload;
25
+ const logger = getLogger({
26
+ payload
27
+ });
28
+ const { locale, trash, where } = input;
29
+ logger.info(`Counting documents in collection: ${collectionSlug}`);
30
+ try {
31
+ const result = await payload.count({
32
+ collection: collectionSlug,
33
+ req,
34
+ ...localAPIDefaults(authorizedMCP),
35
+ ...locale ? {
36
+ locale
37
+ } : {},
38
+ ...trash !== undefined ? {
39
+ trash
40
+ } : {},
41
+ ...where ? {
42
+ where
43
+ } : {}
44
+ });
45
+ return {
46
+ content: [
47
+ {
48
+ type: 'text',
49
+ text: `Collection "${collectionSlug}" contains ${result.totalDocs} matching documents.\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``
50
+ }
51
+ ],
52
+ doc: result
53
+ };
54
+ } catch (error) {
55
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';
56
+ logger.error(`Error counting documents in ${collectionSlug}: ${errorMessage}`);
57
+ return {
58
+ content: [
59
+ {
60
+ type: 'text',
61
+ text: `❌ **Error counting documents in collection "${collectionSlug}":** ${errorMessage}`
62
+ }
63
+ ],
64
+ isError: true
65
+ };
66
+ }
67
+ });
68
+
69
+ //# sourceMappingURL=countTool.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/mcp/builtin/collections/countTool.ts"],"sourcesContent":["import { z } from 'zod'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\nimport { 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","tot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AM,IAAI,CAAC,CAAC;YACxC,GAAIE,QAAQ;gBAAEA;YAAM,IAAI,CAAC,CAAC;QAC5B;QAEA,OAAO;YACLW,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,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"}
@@ -0,0 +1,2 @@
1
+ export declare const countVersionsTool: import("../../../types.js").CollectionTool;
2
+ //# sourceMappingURL=countVersionsTool.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"countVersionsTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/countVersionsTool.ts"],"names":[],"mappings":"AAWA,eAAO,MAAM,iBAAiB,4CA0D5B,CAAA"}