@payloadcms/plugin-mcp 4.0.0-internal.a0ef1b8 → 4.0.0-internal.bc5cf8c

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
@@ -0,0 +1,104 @@
1
+ import type { PopulateType, SelectType } from 'payload'
2
+
3
+ import { z } from 'zod'
4
+
5
+ import { defaultAccess } from '../../../defaultAccess.js'
6
+ import { defineGlobalTool } from '../../../defineTool.js'
7
+ import { getLogger } from '../../../utils/getLogger.js'
8
+ import { localAPIDefaults } from '../../../utils/localAPIDefaults.js'
9
+
10
+ const DEFAULT_DESCRIPTION =
11
+ 'Find a specific global version in any version-enabled global by passing the global slug and version ID.'
12
+
13
+ export const findGlobalVersionByIDTool = defineGlobalTool({
14
+ access: (args) =>
15
+ defaultAccess(args) && Boolean(args.permissions?.globals?.[args.globalSlug]?.readVersions),
16
+ annotations: {
17
+ destructiveHint: false,
18
+ idempotentHint: true,
19
+ openWorldHint: false,
20
+ readOnlyHint: true,
21
+ title: 'Find Global Version By ID',
22
+ },
23
+ description: DEFAULT_DESCRIPTION,
24
+ input: z.object({
25
+ id: z.string().describe('The ID of the global version to retrieve'),
26
+ depth: z
27
+ .number()
28
+ .int()
29
+ .min(0)
30
+ .max(10)
31
+ .describe('How many levels deep to populate relationships in the global version document')
32
+ .optional()
33
+ .default(0),
34
+ fallbackLocale: z
35
+ .string()
36
+ .describe('Optional: fallback locale code to use when requested locale is not available')
37
+ .optional(),
38
+ locale: z
39
+ .string()
40
+ .describe(
41
+ 'Optional: locale code to retrieve data in (e.g., "en", "es"). Use "all" to retrieve all locales for localized fields',
42
+ )
43
+ .optional(),
44
+ populate: z
45
+ .record(z.string(), z.unknown())
46
+ .describe(
47
+ 'Optional: control which fields to include from populated relationship or upload documents.',
48
+ )
49
+ .optional(),
50
+ select: z
51
+ .record(z.string(), z.unknown())
52
+ .describe(
53
+ 'Optional: define exactly which fields you\'d like to return in the response, e.g., {"version.siteName": true}',
54
+ )
55
+ .optional(),
56
+ showHiddenFields: z
57
+ .boolean()
58
+ .describe('Optional: include hidden fields in the returned global version document')
59
+ .optional(),
60
+ }),
61
+ }).handler(async ({ authorizedMCP, globalSlug, input, req }) => {
62
+ const payload = req.payload
63
+ const logger = getLogger({ payload })
64
+ const { id, depth, fallbackLocale, locale, populate, select, showHiddenFields } = input
65
+
66
+ logger.info(`Finding version for global: ${globalSlug} with ID: ${id}`)
67
+
68
+ try {
69
+ const result = await payload.findGlobalVersionByID({
70
+ id,
71
+ slug: globalSlug,
72
+ depth,
73
+ req,
74
+ ...localAPIDefaults(authorizedMCP),
75
+ ...(fallbackLocale ? { fallbackLocale } : {}),
76
+ ...(locale ? { locale } : {}),
77
+ ...(populate ? { populate: populate as PopulateType } : {}),
78
+ ...(select ? { select: select as SelectType } : {}),
79
+ ...(showHiddenFields !== undefined ? { showHiddenFields } : {}),
80
+ })
81
+
82
+ return {
83
+ content: [
84
+ {
85
+ type: 'text',
86
+ text: `Version "${id}" from global "${globalSlug}":\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``,
87
+ },
88
+ ],
89
+ doc: result as unknown as Record<string, unknown>,
90
+ }
91
+ } catch (error) {
92
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error'
93
+ logger.error(`Error finding version ${id} for global ${globalSlug}: ${errorMessage}`)
94
+ return {
95
+ content: [
96
+ {
97
+ type: 'text',
98
+ text: `❌ **Error finding version "${id}" for global "${globalSlug}":** ${errorMessage}`,
99
+ },
100
+ ],
101
+ isError: true,
102
+ }
103
+ }
104
+ })
@@ -0,0 +1,148 @@
1
+ import type { PopulateType, SelectType } from 'payload'
2
+
3
+ import { z } from 'zod'
4
+
5
+ import { defaultAccess } from '../../../defaultAccess.js'
6
+ import { defineGlobalTool } from '../../../defineTool.js'
7
+ import { getLogger } from '../../../utils/getLogger.js'
8
+ import { localAPIDefaults } from '../../../utils/localAPIDefaults.js'
9
+ import { whereSchema } from '../../../utils/whereSchema.js'
10
+
11
+ const DEFAULT_DESCRIPTION =
12
+ 'Find global versions in any version-enabled global by passing the global slug and optional where clause.'
13
+
14
+ export const findGlobalVersionsTool = defineGlobalTool({
15
+ access: (args) =>
16
+ defaultAccess(args) && Boolean(args.permissions?.globals?.[args.globalSlug]?.readVersions),
17
+ annotations: {
18
+ destructiveHint: false,
19
+ idempotentHint: true,
20
+ openWorldHint: false,
21
+ readOnlyHint: true,
22
+ title: 'Find Global Versions',
23
+ },
24
+ description: DEFAULT_DESCRIPTION,
25
+ input: z.object({
26
+ depth: z
27
+ .number()
28
+ .int()
29
+ .min(0)
30
+ .max(10)
31
+ .describe('How many levels deep to populate relationships in global version documents')
32
+ .optional()
33
+ .default(0),
34
+ fallbackLocale: z
35
+ .string()
36
+ .describe('Optional: fallback locale code to use when requested locale is not available')
37
+ .optional(),
38
+ limit: z
39
+ .number()
40
+ .int()
41
+ .min(1)
42
+ .max(100)
43
+ .describe('Maximum number of versions to return (default: 10, max: 100)')
44
+ .optional()
45
+ .default(10),
46
+ locale: z
47
+ .string()
48
+ .describe(
49
+ 'Optional: locale code to retrieve data in (e.g., "en", "es"). Use "all" to retrieve all locales for localized fields',
50
+ )
51
+ .optional(),
52
+ page: z
53
+ .number()
54
+ .int()
55
+ .min(1)
56
+ .describe('Page number for pagination (default: 1)')
57
+ .optional()
58
+ .default(1),
59
+ pagination: z
60
+ .boolean()
61
+ .describe('Optional: set to false to skip the count query overhead')
62
+ .optional(),
63
+ populate: z
64
+ .record(z.string(), z.unknown())
65
+ .describe(
66
+ 'Optional: control which fields to include from populated relationship or upload documents.',
67
+ )
68
+ .optional(),
69
+ select: z
70
+ .record(z.string(), z.unknown())
71
+ .describe(
72
+ 'Optional: define exactly which fields you\'d like to return in the response, e.g., {"version.siteName": true}',
73
+ )
74
+ .optional(),
75
+ showHiddenFields: z
76
+ .boolean()
77
+ .describe('Optional: include hidden fields in returned global version documents')
78
+ .optional(),
79
+ sort: z
80
+ .string()
81
+ .describe('Field to sort by (e.g., "-updatedAt", "-version.updatedAt" for descending)')
82
+ .optional(),
83
+ where: whereSchema
84
+ .describe(
85
+ 'Optional: where clause for filtering versions. Version document fields are usually under "version". Example: {"version.siteName":{"contains":"test"}}',
86
+ )
87
+ .optional(),
88
+ }),
89
+ }).handler(async ({ authorizedMCP, globalSlug, input, req }) => {
90
+ const payload = req.payload
91
+ const logger = getLogger({ payload })
92
+ const {
93
+ depth,
94
+ fallbackLocale,
95
+ limit,
96
+ locale,
97
+ page,
98
+ pagination,
99
+ populate,
100
+ select,
101
+ showHiddenFields,
102
+ sort,
103
+ where,
104
+ } = input
105
+
106
+ logger.info(`Finding versions for global: ${globalSlug}, limit: ${limit}, page: ${page}`)
107
+
108
+ try {
109
+ const result = await payload.findGlobalVersions({
110
+ slug: globalSlug,
111
+ depth,
112
+ limit,
113
+ page,
114
+ req,
115
+ ...localAPIDefaults(authorizedMCP),
116
+ ...(fallbackLocale ? { fallbackLocale } : {}),
117
+ ...(locale ? { locale } : {}),
118
+ ...(pagination !== undefined ? { pagination } : {}),
119
+ ...(populate ? { populate: populate as PopulateType } : {}),
120
+ ...(select ? { select: select as SelectType } : {}),
121
+ ...(showHiddenFields !== undefined ? { showHiddenFields } : {}),
122
+ ...(sort ? { sort } : {}),
123
+ ...(where ? { where } : {}),
124
+ })
125
+
126
+ return {
127
+ content: [
128
+ {
129
+ type: 'text',
130
+ text: `Versions for global "${globalSlug}":\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``,
131
+ },
132
+ ],
133
+ doc: result as unknown as Record<string, unknown>,
134
+ }
135
+ } catch (error) {
136
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error'
137
+ logger.error(`Error finding versions for global ${globalSlug}: ${errorMessage}`)
138
+ return {
139
+ content: [
140
+ {
141
+ type: 'text',
142
+ text: `❌ **Error finding versions for global "${globalSlug}":** ${errorMessage}`,
143
+ },
144
+ ],
145
+ isError: true,
146
+ }
147
+ }
148
+ })
@@ -0,0 +1,41 @@
1
+ import { defaultAccess } from '../../../defaultAccess.js'
2
+ import { defineGlobalTool } from '../../../defineTool.js'
3
+ import { getGlobalInputSchema } from '../../../utils/schemaConversion/getEntityInputSchema.js'
4
+
5
+ export const getGlobalSchemaTool = defineGlobalTool({
6
+ access: (args) => {
7
+ const permissions = args.permissions?.globals?.[args.globalSlug]
8
+
9
+ return defaultAccess(args) && Boolean(permissions?.read || permissions?.update)
10
+ },
11
+ annotations: {
12
+ destructiveHint: false,
13
+ idempotentHint: true,
14
+ openWorldHint: false,
15
+ readOnlyHint: true,
16
+ title: 'Get Global Schema',
17
+ },
18
+ description: 'Get the input schema for updating a global.',
19
+ }).handler(({ globalSlug, req }) => {
20
+ const inputSchema = getGlobalInputSchema({ globalSlug, req })
21
+
22
+ if (!inputSchema) {
23
+ return {
24
+ content: [{ type: 'text', text: `Error: Global "${globalSlug}" not found` }],
25
+ isError: true,
26
+ }
27
+ }
28
+
29
+ return {
30
+ content: [
31
+ {
32
+ type: 'text',
33
+ text: `Schema for global "${globalSlug}":\n\`\`\`json\n${JSON.stringify(inputSchema)}\n\`\`\``,
34
+ },
35
+ ],
36
+ structuredContent: {
37
+ globalSlug,
38
+ schema: inputSchema,
39
+ },
40
+ }
41
+ })
@@ -0,0 +1,100 @@
1
+ import type { PopulateType } from 'payload'
2
+
3
+ import { z } from 'zod'
4
+
5
+ import { defaultAccess } from '../../../defaultAccess.js'
6
+ import { defineGlobalTool } from '../../../defineTool.js'
7
+ import { getLogger } from '../../../utils/getLogger.js'
8
+ import { localAPIDefaults } from '../../../utils/localAPIDefaults.js'
9
+
10
+ const DEFAULT_DESCRIPTION =
11
+ 'Restore a global from a previous version in any version-enabled global.'
12
+
13
+ export const restoreGlobalVersionTool = defineGlobalTool({
14
+ access: (args) =>
15
+ defaultAccess(args) && Boolean(args.permissions?.globals?.[args.globalSlug]?.update),
16
+ annotations: {
17
+ destructiveHint: true,
18
+ idempotentHint: false,
19
+ openWorldHint: false,
20
+ readOnlyHint: false,
21
+ title: 'Restore Global Version',
22
+ },
23
+ description: DEFAULT_DESCRIPTION,
24
+ input: z.object({
25
+ id: z.string().describe('The ID of the global version to restore'),
26
+ depth: z
27
+ .number()
28
+ .int()
29
+ .min(0)
30
+ .max(10)
31
+ .describe('How many levels deep to populate relationships in response')
32
+ .optional()
33
+ .default(0),
34
+ fallbackLocale: z
35
+ .string()
36
+ .describe('Optional: fallback locale code to use when requested locale is not available')
37
+ .optional(),
38
+ locale: z
39
+ .string()
40
+ .describe('Optional: locale code to restore in (e.g., "en", "es")')
41
+ .optional(),
42
+ populate: z
43
+ .record(z.string(), z.unknown())
44
+ .describe(
45
+ 'Optional: control which fields to include from populated relationship or upload documents.',
46
+ )
47
+ .optional(),
48
+ showHiddenFields: z
49
+ .boolean()
50
+ .describe('Optional: include hidden fields in the restored global response')
51
+ .optional(),
52
+ }),
53
+ }).handler(async ({ authorizedMCP, globalSlug, input, req }) => {
54
+ const payload = req.payload
55
+ const logger = getLogger({ payload })
56
+ const { id, depth, fallbackLocale, locale, populate, showHiddenFields } = input
57
+
58
+ logger.info(`Restoring version for global: ${globalSlug} with ID: ${id}`)
59
+
60
+ try {
61
+ const result = await payload.restoreGlobalVersion({
62
+ id,
63
+ slug: globalSlug,
64
+ depth,
65
+ req,
66
+ ...localAPIDefaults(authorizedMCP),
67
+ ...(fallbackLocale ? { fallbackLocale } : {}),
68
+ ...(locale ? { locale } : {}),
69
+ ...(populate ? { populate: populate as PopulateType } : {}),
70
+ ...(showHiddenFields !== undefined ? { showHiddenFields } : {}),
71
+ })
72
+ const resultObject = result as Record<string, unknown>
73
+ const restoredGlobal =
74
+ resultObject.version && typeof resultObject.version === 'object'
75
+ ? (resultObject.version as Record<string, unknown>)
76
+ : resultObject
77
+
78
+ return {
79
+ content: [
80
+ {
81
+ type: 'text',
82
+ text: `Version "${id}" restored successfully for global "${globalSlug}"!\nRestored global:\n\`\`\`json\n${JSON.stringify(restoredGlobal)}\n\`\`\``,
83
+ },
84
+ ],
85
+ doc: restoredGlobal,
86
+ }
87
+ } catch (error) {
88
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error'
89
+ logger.error(`Error restoring version ${id} for global ${globalSlug}: ${errorMessage}`)
90
+ return {
91
+ content: [
92
+ {
93
+ type: 'text',
94
+ text: `❌ **Error restoring version "${id}" for global "${globalSlug}":** ${errorMessage}`,
95
+ },
96
+ ],
97
+ isError: true,
98
+ }
99
+ }
100
+ })
@@ -2,6 +2,7 @@ import type { SelectType } from 'payload'
2
2
 
3
3
  import { z } from 'zod'
4
4
 
5
+ import { defaultAccess } from '../../../defaultAccess.js'
5
6
  import { defineGlobalTool } from '../../../defineTool.js'
6
7
  import { getLogger } from '../../../utils/getLogger.js'
7
8
  import {
@@ -9,54 +10,51 @@ import {
9
10
  stripVirtualFields,
10
11
  } from '../../../utils/getVirtualFieldNames.js'
11
12
  import { localAPIDefaults } from '../../../utils/localAPIDefaults.js'
12
- import { buildToolInput } from '../../../utils/schemaConversion/buildToolInput.js'
13
- import { sanitizeEntitySchema } from '../../../utils/schemaConversion/sanitizeEntitySchema.js'
13
+ import { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'
14
+ import { validateGlobalData } from '../validateEntityData.js'
14
15
 
15
- const DEFAULT_DESCRIPTION = 'Update a Payload global singleton configuration.'
16
+ const DEFAULT_DESCRIPTION = 'Update any Payload global by passing the global slug and data.'
16
17
 
17
18
  export const updateGlobalTool = defineGlobalTool({
18
- description: DEFAULT_DESCRIPTION,
19
- input: ({ globalSchema }) => {
20
- const partialSchema = sanitizeEntitySchema(globalSchema)
21
- // Global updates do not require all required fields to be passed => delete .required.
22
- //
23
- // Local API equivalent: packages/payload/src/global/operations/local/update.ts#BaseOptions#data:
24
- // data: DeepPartial<Omit<DataFromGlobalSlug<TSlug>, 'id'>>
25
- delete partialSchema.required
26
-
27
- return buildToolInput({
28
- controls: {
29
- depth: z
30
- .number()
31
- .describe('Optional: Depth of relationships to populate')
32
- .optional()
33
- .default(0),
34
- draft: z
35
- .boolean()
36
- .describe('Optional: Whether to save as draft (default: false)')
37
- .optional()
38
- .default(false),
39
- fallbackLocale: z
40
- .string()
41
- .describe('Optional: fallback locale code to use when requested locale is not available')
42
- .optional(),
43
- locale: z
44
- .string()
45
- .describe(
46
- 'Optional: locale code to update data in (e.g., "en", "es"). Use "all" to update all locales for localized fields',
47
- )
48
- .optional(),
49
- select: z
50
- .string()
51
- .describe(
52
- 'Optional: define exactly which fields you\'d like to return in the response (JSON), e.g., \'{"siteName": "My Site"}\'',
53
- )
54
- .optional(),
55
- },
56
- dataDescription: 'The fields to update',
57
- dataSchema: partialSchema,
58
- })
19
+ access: (args) =>
20
+ defaultAccess(args) && Boolean(args.permissions?.globals?.[args.globalSlug]?.update),
21
+ annotations: {
22
+ destructiveHint: true,
23
+ idempotentHint: false,
24
+ openWorldHint: false,
25
+ readOnlyHint: false,
26
+ title: 'Update Global',
59
27
  },
28
+ description: DEFAULT_DESCRIPTION,
29
+ input: z.object({
30
+ data: z.record(z.string(), z.unknown()).describe('The global fields to update'),
31
+ depth: z
32
+ .number()
33
+ .describe('Optional: Depth of relationships to populate')
34
+ .optional()
35
+ .default(0),
36
+ draft: z
37
+ .boolean()
38
+ .describe('Optional: Whether to save as draft (default: false)')
39
+ .optional()
40
+ .default(false),
41
+ fallbackLocale: z
42
+ .string()
43
+ .describe('Optional: fallback locale code to use when requested locale is not available')
44
+ .optional(),
45
+ locale: z
46
+ .string()
47
+ .describe(
48
+ 'Optional: locale code to update data in (e.g., "en", "es"). Use "all" to update all locales for localized fields',
49
+ )
50
+ .optional(),
51
+ select: z
52
+ .record(z.string(), z.unknown())
53
+ .describe(
54
+ 'Optional: define exactly which fields you\'d like to return in the response, e.g., {"siteName": true}',
55
+ )
56
+ .optional(),
57
+ }),
60
58
  }).handler(async ({ authorizedMCP, globalSlug, input, req }) => {
61
59
  const payload = req.payload
62
60
  const logger = getLogger({ payload })
@@ -69,18 +67,15 @@ export const updateGlobalTool = defineGlobalTool({
69
67
 
70
68
  try {
71
69
  const virtualFieldNames = getGlobalVirtualFieldNames(payload.config, globalSlug)
72
- const parsedData = stripVirtualFields(data, virtualFieldNames)
70
+ const inputData = stripVirtualFields(data, virtualFieldNames)
71
+ const validationError = validateGlobalData({ data: inputData, globalSlug, req })
73
72
 
74
- let selectClause: SelectType | undefined
75
- if (select) {
76
- try {
77
- selectClause = JSON.parse(select) as SelectType
78
- } catch {
79
- logger.warn(`Invalid select clause JSON for global: ${select}`)
80
- return { content: [{ type: 'text', text: 'Error: Invalid JSON in select clause' }] }
81
- }
73
+ if (validationError) {
74
+ return validationError
82
75
  }
83
76
 
77
+ const parsedData = transformPointDataToPayload(inputData)
78
+
84
79
  const updateOptions: Parameters<typeof payload.updateGlobal>[0] = {
85
80
  slug: globalSlug,
86
81
  data: parsedData,
@@ -95,8 +90,8 @@ export const updateGlobalTool = defineGlobalTool({
95
90
  if (fallbackLocale) {
96
91
  updateOptions.fallbackLocale = fallbackLocale
97
92
  }
98
- if (selectClause) {
99
- updateOptions.select = selectClause
93
+ if (select) {
94
+ updateOptions.select = select as SelectType
100
95
  }
101
96
 
102
97
  const result = await payload.updateGlobal(updateOptions)
@@ -0,0 +1,132 @@
1
+ import type { CollectionSlug, GlobalSlug, PayloadRequest, SanitizedConfig } from 'payload'
2
+
3
+ import { CfWorkerJsonSchemaValidator } from '@modelcontextprotocol/server'
4
+
5
+ import type { JsonSchemaType, MCPToolResponse } from '../../types.js'
6
+
7
+ import {
8
+ getCollectionInputSchema,
9
+ getGlobalInputSchema,
10
+ } from '../../utils/schemaConversion/getEntityInputSchema.js'
11
+
12
+ /**
13
+ * Keep the default `shortcircuit: true` - `false` makes validating nested rich text exponentially slow.
14
+ */
15
+ const validator = new CfWorkerJsonSchemaValidator({ shortcircuit: true })
16
+
17
+ type EntityValidator = {
18
+ schema: JsonSchemaType
19
+ validate: ReturnType<(typeof validator)['getValidator']>
20
+ }
21
+
22
+ /**
23
+ * - Caches each entity's schema and validator, so both are only built on the first request.
24
+ * - Keyed by payload config, then by entity type, slug, partial and language.
25
+ */
26
+ const validatorCache = new WeakMap<SanitizedConfig, Map<string, EntityValidator>>()
27
+
28
+ export const validateCollectionData = ({
29
+ collectionSlug,
30
+ data,
31
+ partial,
32
+ req,
33
+ }: {
34
+ collectionSlug: CollectionSlug
35
+ data: Record<string, unknown>
36
+ partial?: boolean
37
+ req: PayloadRequest
38
+ }): MCPToolResponse | null =>
39
+ validateData({
40
+ slug: collectionSlug,
41
+ buildSchema: () => getCollectionInputSchema({ collectionSlug, req }),
42
+ data,
43
+ entity: 'collection',
44
+ partial,
45
+ req,
46
+ })
47
+
48
+ export const validateGlobalData = ({
49
+ data,
50
+ globalSlug,
51
+ req,
52
+ }: {
53
+ data: Record<string, unknown>
54
+ globalSlug: GlobalSlug
55
+ req: PayloadRequest
56
+ }): MCPToolResponse | null =>
57
+ validateData({
58
+ slug: globalSlug,
59
+ buildSchema: () => getGlobalInputSchema({ globalSlug, req }),
60
+ data,
61
+ entity: 'global',
62
+ partial: true,
63
+ req,
64
+ })
65
+
66
+ const validateData = ({
67
+ slug,
68
+ buildSchema,
69
+ data,
70
+ entity,
71
+ partial,
72
+ req,
73
+ }: {
74
+ buildSchema: () => JsonSchemaType | null
75
+ data: Record<string, unknown>
76
+ entity: 'collection' | 'global'
77
+ partial?: boolean
78
+ req: PayloadRequest
79
+ slug: string
80
+ }): MCPToolResponse | null => {
81
+ let cache = validatorCache.get(req.payload.config)
82
+ if (!cache) {
83
+ cache = new Map()
84
+ validatorCache.set(req.payload.config, cache)
85
+ }
86
+
87
+ const cacheKey = `${entity}:${slug}:${partial ? 'partial' : 'full'}:${req.i18n.language}`
88
+ let entityValidator = cache.get(cacheKey)
89
+
90
+ if (!entityValidator) {
91
+ const schema = buildSchema()
92
+
93
+ if (!schema) {
94
+ return null
95
+ }
96
+
97
+ entityValidator = {
98
+ schema,
99
+ validate: validator.getValidator(partial ? withoutRequired(schema) : schema),
100
+ }
101
+ cache.set(cacheKey, entityValidator)
102
+ }
103
+
104
+ const result = entityValidator.validate(data)
105
+
106
+ if (result.valid) {
107
+ return null
108
+ }
109
+
110
+ const { schema } = entityValidator
111
+
112
+ return {
113
+ content: [
114
+ {
115
+ type: 'text',
116
+ text: `Invalid data for ${entity} "${slug}": ${result.errorMessage}\n\nUse this schema for data:\n\`\`\`json\n${JSON.stringify(schema)}\n\`\`\``,
117
+ },
118
+ ],
119
+ isError: true,
120
+ structuredContent: {
121
+ [`${entity}Slug`]: slug,
122
+ errors: [{ message: result.errorMessage }],
123
+ schema,
124
+ },
125
+ }
126
+ }
127
+
128
+ /** Updates are partial — drop the schema's top-level `required` before validating. */
129
+ const withoutRequired = (schema: JsonSchemaType): JsonSchemaType => {
130
+ const { required: _required, ...rest } = schema
131
+ return rest
132
+ }