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

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 (150) hide show
  1. package/LICENSE.md +1 -1
  2. package/dist/endpoint/access.d.ts +2 -7
  3. package/dist/endpoint/access.d.ts.map +1 -1
  4. package/dist/endpoint/access.js +4 -11
  5. package/dist/endpoint/access.js.map +1 -1
  6. package/dist/endpoint/index.d.ts +1 -1
  7. package/dist/endpoint/index.d.ts.map +1 -1
  8. package/dist/endpoint/index.js +57 -17
  9. package/dist/endpoint/index.js.map +1 -1
  10. package/dist/index.d.ts +2 -2
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +2 -2
  13. package/dist/index.js.map +1 -1
  14. package/dist/mcp/buildMcpServer.d.ts +4 -4
  15. package/dist/mcp/buildMcpServer.d.ts.map +1 -1
  16. package/dist/mcp/buildMcpServer.js +32 -10
  17. package/dist/mcp/buildMcpServer.js.map +1 -1
  18. package/dist/mcp/builtin/collections/countTool.d.ts.map +1 -1
  19. package/dist/mcp/builtin/collections/countTool.js +1 -2
  20. package/dist/mcp/builtin/collections/countTool.js.map +1 -1
  21. package/dist/mcp/builtin/collections/countVersionsTool.d.ts.map +1 -1
  22. package/dist/mcp/builtin/collections/countVersionsTool.js +1 -2
  23. package/dist/mcp/builtin/collections/countVersionsTool.js.map +1 -1
  24. package/dist/mcp/builtin/collections/createTool.d.ts.map +1 -1
  25. package/dist/mcp/builtin/collections/createTool.js +1 -2
  26. package/dist/mcp/builtin/collections/createTool.js.map +1 -1
  27. package/dist/mcp/builtin/collections/deleteTool.d.ts.map +1 -1
  28. package/dist/mcp/builtin/collections/deleteTool.js +1 -2
  29. package/dist/mcp/builtin/collections/deleteTool.js.map +1 -1
  30. package/dist/mcp/builtin/collections/duplicateTool.d.ts.map +1 -1
  31. package/dist/mcp/builtin/collections/duplicateTool.js +1 -2
  32. package/dist/mcp/builtin/collections/duplicateTool.js.map +1 -1
  33. package/dist/mcp/builtin/collections/findDistinctTool.d.ts.map +1 -1
  34. package/dist/mcp/builtin/collections/findDistinctTool.js +1 -2
  35. package/dist/mcp/builtin/collections/findDistinctTool.js.map +1 -1
  36. package/dist/mcp/builtin/collections/findTool.d.ts.map +1 -1
  37. package/dist/mcp/builtin/collections/findTool.js +2 -3
  38. package/dist/mcp/builtin/collections/findTool.js.map +1 -1
  39. package/dist/mcp/builtin/collections/findVersionByIDTool.d.ts.map +1 -1
  40. package/dist/mcp/builtin/collections/findVersionByIDTool.js +1 -2
  41. package/dist/mcp/builtin/collections/findVersionByIDTool.js.map +1 -1
  42. package/dist/mcp/builtin/collections/findVersionsTool.d.ts.map +1 -1
  43. package/dist/mcp/builtin/collections/findVersionsTool.js +1 -2
  44. package/dist/mcp/builtin/collections/findVersionsTool.js.map +1 -1
  45. package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -1
  46. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +21 -3
  47. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -1
  48. package/dist/mcp/builtin/collections/restoreVersionTool.d.ts.map +1 -1
  49. package/dist/mcp/builtin/collections/restoreVersionTool.js +1 -2
  50. package/dist/mcp/builtin/collections/restoreVersionTool.js.map +1 -1
  51. package/dist/mcp/builtin/collections/updateTool.d.ts.map +1 -1
  52. package/dist/mcp/builtin/collections/updateTool.js +2 -3
  53. package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
  54. package/dist/mcp/builtin/getConfigInfoTool.d.ts.map +1 -1
  55. package/dist/mcp/builtin/getConfigInfoTool.js +2 -5
  56. package/dist/mcp/builtin/getConfigInfoTool.js.map +1 -1
  57. package/dist/mcp/builtin/globals/countVersionsTool.d.ts.map +1 -1
  58. package/dist/mcp/builtin/globals/countVersionsTool.js +1 -2
  59. package/dist/mcp/builtin/globals/countVersionsTool.js.map +1 -1
  60. package/dist/mcp/builtin/globals/findTool.d.ts.map +1 -1
  61. package/dist/mcp/builtin/globals/findTool.js +2 -2
  62. package/dist/mcp/builtin/globals/findTool.js.map +1 -1
  63. package/dist/mcp/builtin/globals/findVersionByIDTool.d.ts.map +1 -1
  64. package/dist/mcp/builtin/globals/findVersionByIDTool.js +1 -2
  65. package/dist/mcp/builtin/globals/findVersionByIDTool.js.map +1 -1
  66. package/dist/mcp/builtin/globals/findVersionsTool.d.ts.map +1 -1
  67. package/dist/mcp/builtin/globals/findVersionsTool.js +1 -2
  68. package/dist/mcp/builtin/globals/findVersionsTool.js.map +1 -1
  69. package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts.map +1 -1
  70. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js +21 -3
  71. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js.map +1 -1
  72. package/dist/mcp/builtin/globals/restoreVersionTool.d.ts.map +1 -1
  73. package/dist/mcp/builtin/globals/restoreVersionTool.js +1 -2
  74. package/dist/mcp/builtin/globals/restoreVersionTool.js.map +1 -1
  75. package/dist/mcp/builtin/globals/updateTool.d.ts.map +1 -1
  76. package/dist/mcp/builtin/globals/updateTool.js +2 -2
  77. package/dist/mcp/builtin/globals/updateTool.js.map +1 -1
  78. package/dist/mcp/builtin/validateEntityData.js +1 -1
  79. package/dist/mcp/builtin/validateEntityData.js.map +1 -1
  80. package/dist/mcp/sanitizeMCPConfig.d.ts.map +1 -1
  81. package/dist/mcp/sanitizeMCPConfig.js +1 -0
  82. package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
  83. package/dist/stdio.d.ts +3 -4
  84. package/dist/stdio.d.ts.map +1 -1
  85. package/dist/stdio.js +59 -41
  86. package/dist/stdio.js.map +1 -1
  87. package/dist/types.d.ts +57 -9
  88. package/dist/types.d.ts.map +1 -1
  89. package/dist/types.js +2 -4
  90. package/dist/types.js.map +1 -1
  91. package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts +28 -0
  92. package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts.map +1 -0
  93. package/dist/utils/schemaConversion/filterFieldsByAccess.js +71 -0
  94. package/dist/utils/schemaConversion/filterFieldsByAccess.js.map +1 -0
  95. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts +5 -3
  96. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts.map +1 -1
  97. package/dist/utils/schemaConversion/getEntityInputSchema.js +44 -12
  98. package/dist/utils/schemaConversion/getEntityInputSchema.js.map +1 -1
  99. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts +5 -10
  100. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts.map +1 -1
  101. package/dist/utils/schemaConversion/sanitizeEntitySchema.js +15 -95
  102. package/dist/utils/schemaConversion/sanitizeEntitySchema.js.map +1 -1
  103. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js +15 -40
  104. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js.map +1 -1
  105. package/package.json +8 -10
  106. package/src/endpoint/access.ts +3 -10
  107. package/src/endpoint/index.ts +45 -16
  108. package/src/index.ts +4 -4
  109. package/src/mcp/buildMcpServer.ts +40 -20
  110. package/src/mcp/builtin/collections/countTool.ts +1 -2
  111. package/src/mcp/builtin/collections/countVersionsTool.ts +1 -2
  112. package/src/mcp/builtin/collections/createTool.ts +1 -2
  113. package/src/mcp/builtin/collections/deleteTool.ts +1 -2
  114. package/src/mcp/builtin/collections/duplicateTool.ts +1 -2
  115. package/src/mcp/builtin/collections/findDistinctTool.ts +1 -2
  116. package/src/mcp/builtin/collections/findTool.ts +2 -3
  117. package/src/mcp/builtin/collections/findVersionByIDTool.ts +1 -2
  118. package/src/mcp/builtin/collections/findVersionsTool.ts +1 -2
  119. package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +25 -8
  120. package/src/mcp/builtin/collections/restoreVersionTool.ts +1 -2
  121. package/src/mcp/builtin/collections/updateTool.ts +2 -3
  122. package/src/mcp/builtin/getConfigInfoTool.ts +2 -4
  123. package/src/mcp/builtin/globals/countVersionsTool.ts +1 -2
  124. package/src/mcp/builtin/globals/findTool.ts +2 -2
  125. package/src/mcp/builtin/globals/findVersionByIDTool.ts +1 -2
  126. package/src/mcp/builtin/globals/findVersionsTool.ts +1 -2
  127. package/src/mcp/builtin/globals/getGlobalSchemaTool.ts +25 -3
  128. package/src/mcp/builtin/globals/restoreVersionTool.ts +1 -2
  129. package/src/mcp/builtin/globals/updateTool.ts +2 -2
  130. package/src/mcp/builtin/validateEntityData.ts +1 -1
  131. package/src/mcp/sanitizeMCPConfig.ts +1 -0
  132. package/src/stdio.ts +59 -42
  133. package/src/types.ts +57 -9
  134. package/src/utils/schemaConversion/filterFieldsByAccess.ts +123 -0
  135. package/src/utils/schemaConversion/getEntityInputSchema.ts +45 -27
  136. package/src/utils/schemaConversion/sanitizeEntitySchema.spec.ts +12 -19
  137. package/src/utils/schemaConversion/sanitizeEntitySchema.ts +17 -114
  138. package/dist/@types/assets.d.js +0 -2
  139. package/dist/@types/assets.d.js.map +0 -1
  140. package/dist/utils/localAPIDefaults.d.ts +0 -20
  141. package/dist/utils/localAPIDefaults.d.ts.map +0 -1
  142. package/dist/utils/localAPIDefaults.js +0 -19
  143. package/dist/utils/localAPIDefaults.js.map +0 -1
  144. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.d.ts +0 -7
  145. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.d.ts.map +0 -1
  146. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.js +0 -20
  147. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.js.map +0 -1
  148. package/src/@types/assets.d.ts +0 -3
  149. package/src/utils/localAPIDefaults.ts +0 -22
  150. package/src/utils/schemaConversion/removeVirtualFieldsFromSchema.ts +0 -27
package/src/types.ts CHANGED
@@ -15,7 +15,6 @@ import type {
15
15
  MaybePromise,
16
16
  PayloadRequest,
17
17
  SanitizedPermissions,
18
- TypedUser,
19
18
  } from 'payload'
20
19
 
21
20
  import type { GetAuthorizedMCPArgs } from './endpoint/access.js'
@@ -32,7 +31,8 @@ export type { JsonSchemaType, StandardSchemaWithJSON, ToolAnnotations }
32
31
 
33
32
  /**
34
33
  * What a tool's `input` (or a prompt's `argsSchema`) can be — either a raw
35
- * JSON Schema literal, or a Standard Schema instance (Zod, Valibot, …).
34
+ * JSON Schema 2020-12 literal, or a Standard Schema instance (Zod, Valibot, …).
35
+ * Raw schemas may omit `$schema`; when present it must declare the 2020-12 dialect.
36
36
  */
37
37
  export type ToolInputSchema = JsonSchemaType | StandardSchemaWithJSON
38
38
 
@@ -52,6 +52,13 @@ export type MCPResponseOverride = (
52
52
  req: PayloadRequest,
53
53
  ) => MCPToolResponse
54
54
 
55
+ export type MCPAfterToolCallHook = (args: {
56
+ input: unknown
57
+ req: PayloadRequest
58
+ response: MCPToolResponse
59
+ toolName: string
60
+ }) => MaybePromise<MCPToolResponse>
61
+
55
62
  /**
56
63
  * The handler's `input` type. A specific Standard Schema (Zod, Valibot, …) gets
57
64
  * its inferred output; anything else falls back to `Record<string, unknown>`.
@@ -91,6 +98,11 @@ export type GlobalToolHandlerArgs<TSchema = undefined> = {
91
98
  } & ToolHandlerArgs<TSchema>
92
99
 
93
100
  export type Tool<TSchema extends ToolInputSchema | undefined = ToolInputSchema | undefined> = {
101
+ /**
102
+ * Runs while authorizing each MCP request, before the tool is advertised or called. Return
103
+ * `false` to make the tool unavailable for that request. This is skipped when `overrideAccess`
104
+ * is enabled.
105
+ */
94
106
  access?: (args: MCPAccessArgs) => MaybePromise<boolean>
95
107
  annotations?: ToolAnnotations
96
108
  description: string
@@ -105,6 +117,12 @@ export type Tool<TSchema extends ToolInputSchema | undefined = ToolInputSchema |
105
117
  export type CollectionTool<
106
118
  TSchema extends ToolInputSchema | undefined = ToolInputSchema | undefined,
107
119
  > = {
120
+ /**
121
+ * Runs while authorizing each MCP request for this collection. Return `false` to reject calls
122
+ * to this tool for the collection. The shared tool is not advertised when no collections allow
123
+ * it, but can remain advertised when it is available for another collection. This is skipped
124
+ * when `overrideAccess` is enabled.
125
+ */
108
126
  access?: (args: CollectionMCPAccessArgs) => MaybePromise<boolean>
109
127
  handler: (args: CollectionToolHandlerArgs<TSchema>) => MaybePromise<MCPToolResponse>
110
128
  input?: TSchema
@@ -112,6 +130,12 @@ export type CollectionTool<
112
130
 
113
131
  export type GlobalTool<TSchema extends ToolInputSchema | undefined = ToolInputSchema | undefined> =
114
132
  {
133
+ /**
134
+ * Runs while authorizing each MCP request for this global. Return `false` to reject calls to
135
+ * this tool for the global. The shared tool is not advertised when no globals allow it, but
136
+ * can remain advertised when it is available for another global. This is skipped when
137
+ * `overrideAccess` is enabled.
138
+ */
115
139
  access?: (args: GlobalMCPAccessArgs) => MaybePromise<boolean>
116
140
  handler: (args: GlobalToolHandlerArgs<TSchema>) => MaybePromise<MCPToolResponse>
117
141
  input?: TSchema
@@ -123,6 +147,10 @@ export type GlobalTool<TSchema extends ToolInputSchema | undefined = ToolInputSc
123
147
  * required handler) from being silently accepted at a built-in key slot.
124
148
  */
125
149
  export type MCPBuiltInCollectionToolOverride = {
150
+ /**
151
+ * Replaces the built-in tool's access check. Return `false` to make the tool unavailable for
152
+ * this collection. This is skipped when `overrideAccess` is enabled.
153
+ */
126
154
  access?: (args: CollectionMCPAccessArgs) => MaybePromise<boolean>
127
155
  annotations?: ToolAnnotations
128
156
  description?: string
@@ -131,6 +159,10 @@ export type MCPBuiltInCollectionToolOverride = {
131
159
  }
132
160
 
133
161
  export type MCPBuiltInGlobalToolOverride = {
162
+ /**
163
+ * Replaces the built-in tool's access check. Return `false` to make the tool unavailable for
164
+ * this global. This is skipped when `overrideAccess` is enabled.
165
+ */
134
166
  access?: (args: GlobalMCPAccessArgs) => MaybePromise<boolean>
135
167
  annotations?: ToolAnnotations
136
168
  description?: string
@@ -175,6 +207,11 @@ export type PromptHandlerArgs<TSchema = undefined> = {
175
207
  }
176
208
 
177
209
  export type Prompt<TSchema extends ToolInputSchema = ToolInputSchema> = {
210
+ /**
211
+ * Runs while authorizing each MCP request, before the prompt is advertised or used. Return
212
+ * `false` to make the prompt unavailable for that request. This is skipped when
213
+ * `overrideAccess` is enabled.
214
+ */
178
215
  access?: (args: MCPAccessArgs) => MaybePromise<boolean>
179
216
  argsSchema: TSchema
180
217
  description: string
@@ -193,6 +230,11 @@ export type ResourceHandlerArgs = {
193
230
  }
194
231
 
195
232
  export type Resource = {
233
+ /**
234
+ * Runs while authorizing each MCP request, before the resource is advertised or read. Return
235
+ * `false` to make the resource unavailable for that request. This is skipped when
236
+ * `overrideAccess` is enabled.
237
+ */
196
238
  access?: (args: MCPAccessArgs) => MaybePromise<boolean>
197
239
  description: string
198
240
  handler: (args: ResourceHandlerArgs) => MaybePromise<{
@@ -232,11 +274,20 @@ export type MCPPluginConfig = {
232
274
  globals?: {
233
275
  [Slug in GlobalSlug]?: MCPPluginGlobalConfig
234
276
  }
277
+ hooks?: {
278
+ /** Transform a tool response after its handler returns */
279
+ afterToolCall?: MCPAfterToolCallHook[]
280
+ }
235
281
  mcp?: {
236
282
  serverOptions?: MCPServerOptions
237
283
  verboseLogs?: boolean
238
284
  }
239
- /** Replace the default MCP authorization resolver. */
285
+ /**
286
+ * Replace the default MCP authorization resolver.
287
+ *
288
+ * This hook replaces the default authentication flow. It must set `req.user` to the
289
+ * authenticated Payload user, or to `null` for an anonymous caller, before returning.
290
+ */
240
291
  overrideGetAuthorizedMCP?: (
241
292
  args: {
242
293
  pluginConfig: SanitizedMCPPluginConfig
@@ -250,7 +301,7 @@ export type MCPPluginConfig = {
250
301
 
251
302
  export type SanitizedMCPPluginConfig = {
252
303
  items: MCPItem[]
253
- } & Pick<MCPPluginConfig, 'disabled' | 'mcp' | 'overrideGetAuthorizedMCP'>
304
+ } & Pick<MCPPluginConfig, 'disabled' | 'hooks' | 'mcp' | 'overrideGetAuthorizedMCP'>
254
305
 
255
306
  export type MCPServerOptions = {
256
307
  options?: ConstructorParameters<typeof McpServer>[1]
@@ -300,13 +351,10 @@ export type MCPItem =
300
351
  | GlobalMCPItem
301
352
 
302
353
  /**
303
- * The caller's identity + the MCP items authorized for this request. Disabled
304
- * items and items blocked by access callbacks or Payload operation access are
305
- * absent from `items`. Tool handlers receive this via `args.authorizedMCP` so
306
- * they can spread `localAPIDefaults(authorizedMCP)` into every local API call.
354
+ * The MCP items and access mode authorized for this request. The authenticated user is available
355
+ * as `req.user`.
307
356
  */
308
357
  export type AuthorizedMCP = {
309
358
  items: MCPItem[]
310
359
  overrideAccess: boolean
311
- user: null | TypedUser
312
360
  }
@@ -0,0 +1,123 @@
1
+ import type {
2
+ FlattenedBlock,
3
+ FlattenedField,
4
+ Operation,
5
+ SanitizedDocumentPermissions,
6
+ SanitizedFieldsPermissions,
7
+ } from 'payload'
8
+
9
+ type FieldOperation = Exclude<Operation, 'delete'>
10
+ type AllowedFieldOperations = Record<FieldOperation, boolean>
11
+
12
+ /**
13
+ * Filters fields using the access results in `permissions`. `shouldExcludeField` receives the
14
+ * operations allowed by the entity, field, and its parents and decides whether to remove the
15
+ * field.
16
+ *
17
+ * Arrays, groups, named tabs, and blocks are filtered recursively. Rows and unnamed tabs are
18
+ * flattened by Payload, so their children are filtered at the containing level.
19
+ *
20
+ * @example Include fields writable through any collection operation the user can perform.
21
+ * ```ts
22
+ * filterFieldsByAccess({
23
+ * fields,
24
+ * permissions: collectionPermissions,
25
+ * shouldExcludeField: ({ create, update }) => !create && !update,
26
+ * })
27
+ * ```
28
+ */
29
+ export const filterFieldsByAccess = ({
30
+ blocks,
31
+ fields,
32
+ permissions,
33
+ shouldExcludeField,
34
+ }: {
35
+ blocks?: FlattenedBlock[]
36
+ fields: FlattenedField[]
37
+ permissions: SanitizedDocumentPermissions
38
+ shouldExcludeField: (allowedOperations: AllowedFieldOperations) => boolean
39
+ }): FlattenedField[] => {
40
+ const filterFields = (
41
+ nestedFields: FlattenedField[],
42
+ nestedPermissions: SanitizedFieldsPermissions | undefined,
43
+ parentAllowedOperations: AllowedFieldOperations,
44
+ ): FlattenedField[] => {
45
+ const accessibleFields: FlattenedField[] = []
46
+
47
+ for (const field of nestedFields) {
48
+ const fieldPermissions = nestedPermissions === true ? true : nestedPermissions?.[field.name]
49
+ const isOperationAllowed = (operation: FieldOperation): boolean =>
50
+ parentAllowedOperations[operation] &&
51
+ (fieldPermissions === true || fieldPermissions?.[operation] === true)
52
+ const allowedOperations: AllowedFieldOperations = {
53
+ create: isOperationAllowed('create'),
54
+ read: isOperationAllowed('read'),
55
+ update: isOperationAllowed('update'),
56
+ }
57
+
58
+ if (shouldExcludeField(allowedOperations)) {
59
+ continue
60
+ }
61
+
62
+ if (field.type === 'blocks') {
63
+ const accessibleBlocks: (FlattenedBlock | string)[] = []
64
+
65
+ for (const blockOrReference of field.blocks) {
66
+ const block =
67
+ typeof blockOrReference === 'string'
68
+ ? blocks?.find(({ slug }) => slug === blockOrReference)
69
+ : blockOrReference
70
+
71
+ if (!block) {
72
+ continue
73
+ }
74
+
75
+ const blockPermissions =
76
+ fieldPermissions === true
77
+ ? true
78
+ : fieldPermissions?.blocks === true
79
+ ? true
80
+ : fieldPermissions?.blocks?.[block.slug]
81
+
82
+ accessibleBlocks.push({
83
+ ...block,
84
+ flattenedFields: filterFields(
85
+ block.flattenedFields,
86
+ blockPermissions === true ? true : blockPermissions?.fields,
87
+ allowedOperations,
88
+ ),
89
+ })
90
+ }
91
+
92
+ if (accessibleBlocks.length === 0) {
93
+ continue
94
+ }
95
+
96
+ accessibleFields.push({ ...field, blocks: accessibleBlocks })
97
+ continue
98
+ }
99
+
100
+ if (field.type === 'array' || field.type === 'group' || field.type === 'tab') {
101
+ accessibleFields.push({
102
+ ...field,
103
+ flattenedFields: filterFields(
104
+ field.flattenedFields,
105
+ fieldPermissions === true ? true : fieldPermissions?.fields,
106
+ allowedOperations,
107
+ ),
108
+ })
109
+ continue
110
+ }
111
+
112
+ accessibleFields.push(field)
113
+ }
114
+
115
+ return accessibleFields
116
+ }
117
+
118
+ return filterFields(fields, permissions.fields, {
119
+ create: 'create' in permissions && permissions.create === true,
120
+ read: permissions.read === true,
121
+ update: permissions.update === true,
122
+ })
123
+ }
@@ -1,26 +1,27 @@
1
1
  import {
2
2
  type CollectionSlug,
3
3
  entityToStandaloneJSONSchema,
4
+ type FlattenedField,
4
5
  type GlobalSlug,
5
6
  type PayloadRequest,
6
7
  type SanitizedCollectionConfig,
8
+ type SanitizedCollectionPermission,
7
9
  type SanitizedGlobalConfig,
10
+ type SanitizedGlobalPermission,
8
11
  } from 'payload'
9
12
 
10
13
  import type { JsonSchemaType } from '../../types.js'
11
14
 
12
- import {
13
- getCollectionVirtualFieldNames,
14
- getGlobalVirtualFieldNames,
15
- } from '../getVirtualFieldNames.js'
16
- import { removeVirtualFieldsFromSchema } from './removeVirtualFieldsFromSchema.js'
15
+ import { filterFieldsByAccess } from './filterFieldsByAccess.js'
17
16
  import { sanitizeEntitySchema } from './sanitizeEntitySchema.js'
18
17
 
19
18
  export const getCollectionInputSchema = ({
20
19
  collectionSlug,
20
+ permissions,
21
21
  req,
22
22
  }: {
23
23
  collectionSlug: CollectionSlug
24
+ permissions?: SanitizedCollectionPermission
24
25
  req: PayloadRequest
25
26
  }): JsonSchemaType | null => {
26
27
  const collection = req.payload.collections[collectionSlug]?.config
@@ -29,18 +30,27 @@ export const getCollectionInputSchema = ({
29
30
  return null
30
31
  }
31
32
 
32
- return buildEntityInputSchema({
33
- entity: collection,
34
- req,
35
- virtualFieldNames: getCollectionVirtualFieldNames(req.payload.config, collectionSlug),
33
+ if (!permissions) {
34
+ return buildEntityInputSchema({ entity: collection, req })
35
+ }
36
+
37
+ const fieldsAllowedByAccess = filterFieldsByAccess({
38
+ blocks: req.payload.config.blocks,
39
+ fields: collection.flattenedFields,
40
+ permissions,
41
+ shouldExcludeField: ({ create, update }) => !create && !update,
36
42
  })
43
+
44
+ return buildEntityInputSchema({ entity: collection, fields: fieldsAllowedByAccess, req })
37
45
  }
38
46
 
39
47
  export const getGlobalInputSchema = ({
40
48
  globalSlug,
49
+ permissions,
41
50
  req,
42
51
  }: {
43
52
  globalSlug: GlobalSlug
53
+ permissions?: SanitizedGlobalPermission
44
54
  req: PayloadRequest
45
55
  }): JsonSchemaType | null => {
46
56
  const global = req.payload.config.globals.find((globalConfig) => globalConfig.slug === globalSlug)
@@ -49,30 +59,38 @@ export const getGlobalInputSchema = ({
49
59
  return null
50
60
  }
51
61
 
52
- return buildEntityInputSchema({
53
- entity: global,
54
- req,
55
- virtualFieldNames: getGlobalVirtualFieldNames(req.payload.config, globalSlug),
62
+ if (!permissions) {
63
+ return buildEntityInputSchema({ entity: global, req })
64
+ }
65
+
66
+ const fieldsAllowedByAccess = filterFieldsByAccess({
67
+ blocks: req.payload.config.blocks,
68
+ fields: global.flattenedFields,
69
+ permissions,
70
+ shouldExcludeField: ({ create, update }) => !create && !update,
56
71
  })
72
+
73
+ return buildEntityInputSchema({ entity: global, fields: fieldsAllowedByAccess, req })
57
74
  }
58
75
 
59
76
  const buildEntityInputSchema = ({
60
77
  entity,
78
+ fields = entity.flattenedFields,
61
79
  req,
62
- virtualFieldNames,
63
80
  }: {
64
81
  entity: SanitizedCollectionConfig | SanitizedGlobalConfig
82
+ fields?: FlattenedField[]
65
83
  req: PayloadRequest
66
- virtualFieldNames: string[]
67
- }): JsonSchemaType =>
68
- sanitizeEntitySchema(
69
- removeVirtualFieldsFromSchema(
70
- entityToStandaloneJSONSchema({
71
- config: req.payload.config,
72
- defaultIDType: req.payload.db.defaultIDType,
73
- entity,
74
- i18n: req.i18n,
75
- }) as unknown as JsonSchemaType,
76
- virtualFieldNames,
77
- ),
78
- )
84
+ }): JsonSchemaType => {
85
+ // The core schema generator reads flattenedFields from the entity and has no fields argument.
86
+ const entityForSchema = { ...entity, flattenedFields: fields }
87
+ const schema = entityToStandaloneJSONSchema({
88
+ config: req.payload.config,
89
+ defaultIDType: req.payload.db.defaultIDType,
90
+ entity: entityForSchema,
91
+ i18n: req.i18n,
92
+ variant: 'input',
93
+ }) as unknown as JsonSchemaType
94
+
95
+ return sanitizeEntitySchema(schema)
96
+ }
@@ -5,10 +5,11 @@ import type { JsonSchemaType } from '../../types.js'
5
5
  import { sanitizeEntitySchema } from './sanitizeEntitySchema.js'
6
6
 
7
7
  describe('sanitizeEntitySchema', () => {
8
- it('keeps a Lexical node union strict (oneOf) while simplifying relationship values to IDs', () => {
9
- // Shaped like the schema the MCP server prepares for a collection with a Lexical richText field:
10
- // a `$defs` node union (a `oneOf` of node shapes) where a relationship node's `value` is either
11
- // an ID or a `$ref` to the populated related collection.
8
+ it('renames the Lexical node-union definition to a short name and keeps it a strict oneOf', () => {
9
+ // Shaped like the schema the MCP server prepares for a collection with a Lexical richText field
10
+ // (Payload's `input` variant): a `$defs` node union (a `oneOf` of node shapes). The input variant
11
+ // already types the relationship node's `value` as a bare ID - there is no populated-doc `$ref` to
12
+ // reduce here (the variant did that upstream), so sanitize leaves the value untouched.
12
13
  const standalone: JsonSchemaType = {
13
14
  type: 'object',
14
15
  $defs: {
@@ -25,17 +26,12 @@ describe('sanitizeEntitySchema', () => {
25
26
  additionalProperties: false,
26
27
  properties: {
27
28
  type: { const: 'relationship' },
28
- value: { oneOf: [{ type: 'string' }, { $ref: '#/$defs/posts' }] },
29
+ value: { type: 'string', description: 'The related document ID.' },
29
30
  },
30
31
  required: ['type'],
31
32
  },
32
33
  ],
33
34
  },
34
- posts: {
35
- type: 'object',
36
- additionalProperties: false,
37
- properties: { id: { type: 'string' }, title: { type: 'string' } },
38
- },
39
35
  },
40
36
  properties: {
41
37
  id: { type: 'string' },
@@ -57,7 +53,7 @@ describe('sanitizeEntitySchema', () => {
57
53
  type: 'object',
58
54
  $defs: {
59
55
  // The node union is renamed to a short, readable `node`, and stays a strict discriminated
60
- // `oneOf` - not loosened to `anyOf`...
56
+ // `oneOf` - not loosened to `anyOf`.
61
57
  node: {
62
58
  oneOf: [
63
59
  {
@@ -71,21 +67,18 @@ describe('sanitizeEntitySchema', () => {
71
67
  additionalProperties: false,
72
68
  properties: {
73
69
  type: { const: 'relationship' },
74
- // ...while the relationship `value` is simplified to a bare ID (the populated-doc `$ref` is dropped).
75
- value: { type: 'string', description: 'The ID of the related "posts" document.' },
70
+ // The value is already ID-only from the input variant - left as-is.
71
+ value: { type: 'string', description: 'The related document ID.' },
76
72
  },
77
73
  required: ['type'],
78
74
  },
79
75
  ],
80
76
  },
81
- posts: {
82
- type: 'object',
83
- additionalProperties: false,
84
- properties: { id: { type: 'string' }, title: { type: 'string' } },
85
- },
86
77
  },
87
78
  properties: {
88
- // `id` is dropped - it's a Payload-managed field MCP clients never set.
79
+ // Managed fields (createdAt/updatedAt/_status) are excluded upstream by the `input` variant;
80
+ // `id` stays because it's a valid optional input (a client may supply a custom ID).
81
+ id: { type: 'string' },
89
82
  content: {
90
83
  type: 'object',
91
84
  properties: {
@@ -1,30 +1,22 @@
1
1
  import type { JsonSchemaType } from '../../types.js'
2
2
 
3
3
  /**
4
- * Turns the JSON Schema that Payload generates for a collection or global into the input schema for
5
- * an MCP create/update tool. In short, it:
6
- *
7
- * - drops fields a client can't set (`id`, `createdAt`, the draft `_status`, …),
8
- * - rewrites Payload-specific field shapes (points, relationships) into plain JSON the model can fill,
9
- * - and shrinks the result so it's cheaper for the model to read,
10
- *
11
- * while keeping every node valid JSON Schema draft 2020-12. Each step below is tagged with why it runs -
12
- * **Correctness** (valid input the API accepts), **Size** (equivalence-preserving shrink), or **LLM
13
- * ergonomics** (easier for the model to read/fill) - and carries a before/after example on its definition.
4
+ * Refines Payload's `input`-variant JSON Schema into an MCP create/update tool's input schema. The
5
+ * variant already covers correctness (ID-only relationships, no managed/virtual/join fields); the
6
+ * passes here are MCP-specific - reshaping fields for the model and shrinking the result - and keep
7
+ * every node valid JSON Schema draft 2020-12. Each is tagged **Correctness**, **Size**, or **LLM
8
+ * ergonomics**, with a before/after example on its definition.
14
9
  */
15
10
  export const sanitizeEntitySchema = (schema: JsonSchemaType): JsonSchemaType => {
16
11
  // Work on a copy — the caller reuses the original schema elsewhere (e.g. when listing tools).
17
12
  let result = structuredClone(schema)
18
13
 
19
- // Correctness — drop the fields a client can't set (id, createdAt, updatedAt, draft _status) + collapse nullable types.
20
- result = removeManagedFields(result)
14
+ // LLM ergonomics — drop the redundant `'null'` from optional arrays/objects (`['array','null']` `'array'`).
15
+ result = collapseOptionalContainerTypes(result)
21
16
 
22
17
  // LLM ergonomics — rewrite point fields from a `[number, number]` tuple into a `{ longitude, latitude }` object.
23
18
  result = pointFieldsToObjects(result)
24
19
 
25
- // Correctness — a relationship value can be an ID or a populated doc; on input only the ID is valid, so keep that.
26
- result = relationshipsToIds(result)
27
-
28
20
  // Size — strip inert type-gen leftovers that only bloat the schema (`tsType`, block-collision notes).
29
21
  result = removeTypeGenArtifacts(result)
30
22
 
@@ -58,26 +50,20 @@ const mapNodes = (node: unknown, visit: (node: JsonSchemaType) => JsonSchemaType
58
50
  for (const [key, value] of Object.entries(node)) {
59
51
  out[key] = mapNodes(value, visit)
60
52
  }
61
- return visit(out as JsonSchemaType)
53
+ return visit(out)
62
54
  }
63
55
 
64
- // Payload sets these on every document, so an MCP client never provides them when creating/updating.
65
- const PAYLOAD_MANAGED_FIELDS = new Set(['_status', 'createdAt', 'id', 'updatedAt'])
66
-
67
56
  /**
68
- * **Correctness.** Removes the fields a client can't set on create/update - `id`, `createdAt`, `updatedAt`, and the draft
69
- * `_status` - from every field object's `properties` and `required` (recursing into nested objects and
70
- * array items). Along the way it also collapses optional array/object types via {@link collapseNullableType}.
57
+ * **LLM ergonomics.** Collapses optional array/object types (`['array', 'null']` `'array'`) via
58
+ * {@link collapseNullableType}, recursing through `properties` and array items. The `required` list
59
+ * already conveys optionality, so the `'null'` is redundant noise for the model.
71
60
  *
72
61
  * @example
73
- * { properties: { id: { type: 'string' }, tags: { type: ['array', 'null'], items: {} } }, required: ['id', 'tags'] }
74
- * → { properties: { tags: { type: 'array', items: {} } }, required: ['tags'] }
62
+ * { properties: { tags: { type: ['array', 'null'], items: {} } }, required: [] }
63
+ * → { properties: { tags: { type: 'array', items: {} } }, required: [] }
75
64
  */
76
- const removeManagedFields = (schema: JsonSchemaType): JsonSchemaType => {
65
+ const collapseOptionalContainerTypes = (schema: JsonSchemaType): JsonSchemaType => {
77
66
  if (schema.properties && typeof schema.properties === 'object') {
78
- for (const field of PAYLOAD_MANAGED_FIELDS) {
79
- delete schema.properties[field]
80
- }
81
67
  for (const key of Object.keys(schema.properties)) {
82
68
  const prop = schema.properties[key] as JsonSchemaType
83
69
  if (!prop || typeof prop !== 'object') {
@@ -86,21 +72,14 @@ const removeManagedFields = (schema: JsonSchemaType): JsonSchemaType => {
86
72
  const isRequired = Array.isArray(schema.required) && schema.required.includes(key)
87
73
  collapseNullableType(prop, isRequired)
88
74
  if (prop.properties) {
89
- removeManagedFields(prop)
75
+ collapseOptionalContainerTypes(prop)
90
76
  }
91
77
  if (prop.items && typeof prop.items === 'object' && !Array.isArray(prop.items)) {
92
- removeManagedFields(prop.items)
78
+ collapseOptionalContainerTypes(prop.items)
93
79
  }
94
80
  }
95
81
  }
96
82
 
97
- if (Array.isArray(schema.required)) {
98
- schema.required = schema.required.filter((name) => !PAYLOAD_MANAGED_FIELDS.has(name))
99
- if (schema.required.length === 0) {
100
- delete schema.required
101
- }
102
- }
103
-
104
83
  return schema
105
84
  }
106
85
 
@@ -193,82 +172,6 @@ const pointFieldsToObjects = (schema: JsonSchemaType): JsonSchemaType => {
193
172
  return transformed
194
173
  }
195
174
 
196
- /**
197
- * **Correctness.** Reduces relationship/upload fields to the IDs a client actually sends. Payload types the value as
198
- * "an ID or the full related document" - but the populated-document form only appears in read responses;
199
- * on create/update you always reference a relationship by its ID. So we drop that `$ref` option, leaving
200
- * the bare ID. A single remaining target collapses inline (with a description naming the target
201
- * collection); several targets become an `anyOf` of IDs.
202
- *
203
- * @example
204
- * { oneOf: [{ type: 'string' }, { $ref: '#/$defs/posts' }] }
205
- * → { type: 'string', description: 'The ID of the related "posts" document.' }
206
- */
207
- const relationshipsToIds = (schema: JsonSchemaType): JsonSchemaType => {
208
- if (!schema || typeof schema !== 'object') {
209
- return schema
210
- }
211
-
212
- const processed = { ...schema }
213
-
214
- if (Array.isArray(processed.oneOf)) {
215
- const isRelatedDocRef = (option: unknown): option is { $ref: string } =>
216
- !!option && typeof option === 'object' && '$ref' in option
217
-
218
- if (processed.oneOf.some(isRelatedDocRef)) {
219
- // A relationship value is "an ID, or the populated related document". Keep the ID option(s) and
220
- // drop the `$ref`s to the related collections, since a client only ever sends the ID.
221
- const idOptions = processed.oneOf
222
- .filter((option) => !isRelatedDocRef(option))
223
- .map((option) => (typeof option === 'object' ? relationshipsToIds(option) : option))
224
- const targetCollections = processed.oneOf
225
- .filter(isRelatedDocRef)
226
- .map((option) => option.$ref.replace('#/$defs/', ''))
227
-
228
- if (idOptions.length === 1) {
229
- delete processed.oneOf
230
- Object.assign(processed, idOptions[0])
231
- if (targetCollections.length > 0 && !processed.description) {
232
- processed.description = `The ID of the related "${targetCollections.join('" or "')}" document.`
233
- }
234
- } else if (idOptions.length > 1) {
235
- delete processed.oneOf
236
- processed.anyOf = idOptions
237
- }
238
- } else {
239
- processed.oneOf = processed.oneOf.map((option) =>
240
- typeof option === 'object' ? relationshipsToIds(option) : option,
241
- )
242
- }
243
- }
244
-
245
- if (processed.properties && typeof processed.properties === 'object') {
246
- processed.properties = Object.fromEntries(
247
- Object.entries(processed.properties).map(([key, value]) => [
248
- key,
249
- typeof value === 'object' ? relationshipsToIds(value) : value,
250
- ]),
251
- )
252
- }
253
-
254
- if (processed.items && typeof processed.items === 'object' && !Array.isArray(processed.items)) {
255
- processed.items = relationshipsToIds(processed.items)
256
- }
257
-
258
- // Lexical node unions and blocks live under `$defs` and have their own relationship fields, so walk
259
- // those too — otherwise their `$ref`s would dangle once we don't bundle the related collections.
260
- if (processed.$defs && typeof processed.$defs === 'object') {
261
- processed.$defs = Object.fromEntries(
262
- Object.entries(processed.$defs).map(([key, value]) => [
263
- key,
264
- typeof value === 'object' ? relationshipsToIds(value) : value,
265
- ]),
266
- )
267
- }
268
-
269
- return processed
270
- }
271
-
272
175
  /**
273
176
  * **Size.** Strips type-generation leftovers that bloat the schema without helping the model: the `tsType`
274
177
  * hint (a `json-schema-to-typescript` extension; JSON Schema validators just ignore it, they don't reject it)
@@ -448,7 +351,7 @@ const deduplicateIntoDefinitions = (schema: JsonSchemaType): JsonSchemaType => {
448
351
  if (!name) {
449
352
  name = `shared_${nameByKey.size}`
450
353
  nameByKey.set(key, name)
451
- sharedEntries[name] = node as JsonSchemaType
354
+ sharedEntries[name] = node
452
355
  }
453
356
  return { $ref: `#/$defs/${name}` }
454
357
  }
@@ -1,2 +0,0 @@
1
-
2
- //# sourceMappingURL=assets.d.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/@types/assets.d.ts"],"names":[],"mappings":""}