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

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 (169) hide show
  1. package/LICENSE.md +1 -1
  2. package/bin.js +7 -0
  3. package/dist/defaultAccess.d.ts.map +1 -1
  4. package/dist/defineTool.d.ts +8 -8
  5. package/dist/defineTool.d.ts.map +1 -1
  6. package/dist/endpoint/access.d.ts +2 -7
  7. package/dist/endpoint/access.d.ts.map +1 -1
  8. package/dist/endpoint/access.js +4 -11
  9. package/dist/endpoint/access.js.map +1 -1
  10. package/dist/endpoint/index.d.ts +1 -1
  11. package/dist/endpoint/index.d.ts.map +1 -1
  12. package/dist/endpoint/index.js +57 -17
  13. package/dist/endpoint/index.js.map +1 -1
  14. package/dist/index.d.ts +2 -2
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +2 -2
  17. package/dist/index.js.map +1 -1
  18. package/dist/mcp/buildMcpServer.d.ts +4 -4
  19. package/dist/mcp/buildMcpServer.d.ts.map +1 -1
  20. package/dist/mcp/buildMcpServer.js +32 -10
  21. package/dist/mcp/buildMcpServer.js.map +1 -1
  22. package/dist/mcp/builtin/collections/countTool.d.ts.map +1 -1
  23. package/dist/mcp/builtin/collections/countTool.js +1 -2
  24. package/dist/mcp/builtin/collections/countTool.js.map +1 -1
  25. package/dist/mcp/builtin/collections/countVersionsTool.d.ts.map +1 -1
  26. package/dist/mcp/builtin/collections/countVersionsTool.js +1 -2
  27. package/dist/mcp/builtin/collections/countVersionsTool.js.map +1 -1
  28. package/dist/mcp/builtin/collections/createTool.d.ts.map +1 -1
  29. package/dist/mcp/builtin/collections/createTool.js +14 -5
  30. package/dist/mcp/builtin/collections/createTool.js.map +1 -1
  31. package/dist/mcp/builtin/collections/deleteTool.d.ts.map +1 -1
  32. package/dist/mcp/builtin/collections/deleteTool.js +1 -2
  33. package/dist/mcp/builtin/collections/deleteTool.js.map +1 -1
  34. package/dist/mcp/builtin/collections/duplicateTool.d.ts.map +1 -1
  35. package/dist/mcp/builtin/collections/duplicateTool.js +1 -2
  36. package/dist/mcp/builtin/collections/duplicateTool.js.map +1 -1
  37. package/dist/mcp/builtin/collections/fileInput.d.ts +20 -0
  38. package/dist/mcp/builtin/collections/fileInput.d.ts.map +1 -0
  39. package/dist/mcp/builtin/collections/fileInput.js +100 -0
  40. package/dist/mcp/builtin/collections/fileInput.js.map +1 -0
  41. package/dist/mcp/builtin/collections/fileInput.spec.js +72 -0
  42. package/dist/mcp/builtin/collections/fileInput.spec.js.map +1 -0
  43. package/dist/mcp/builtin/collections/findDistinctTool.d.ts.map +1 -1
  44. package/dist/mcp/builtin/collections/findDistinctTool.js +1 -2
  45. package/dist/mcp/builtin/collections/findDistinctTool.js.map +1 -1
  46. package/dist/mcp/builtin/collections/findTool.d.ts.map +1 -1
  47. package/dist/mcp/builtin/collections/findTool.js +3 -4
  48. package/dist/mcp/builtin/collections/findTool.js.map +1 -1
  49. package/dist/mcp/builtin/collections/findVersionByIDTool.d.ts.map +1 -1
  50. package/dist/mcp/builtin/collections/findVersionByIDTool.js +1 -2
  51. package/dist/mcp/builtin/collections/findVersionByIDTool.js.map +1 -1
  52. package/dist/mcp/builtin/collections/findVersionsTool.d.ts.map +1 -1
  53. package/dist/mcp/builtin/collections/findVersionsTool.js +1 -2
  54. package/dist/mcp/builtin/collections/findVersionsTool.js.map +1 -1
  55. package/dist/mcp/builtin/collections/formatCollectionError.d.ts +1 -1
  56. package/dist/mcp/builtin/collections/formatCollectionError.d.ts.map +1 -1
  57. package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -1
  58. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +44 -5
  59. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -1
  60. package/dist/mcp/builtin/collections/restoreVersionTool.d.ts.map +1 -1
  61. package/dist/mcp/builtin/collections/restoreVersionTool.js +1 -2
  62. package/dist/mcp/builtin/collections/restoreVersionTool.js.map +1 -1
  63. package/dist/mcp/builtin/collections/updateTool.d.ts.map +1 -1
  64. package/dist/mcp/builtin/collections/updateTool.js +23 -11
  65. package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
  66. package/dist/mcp/builtin/getConfigInfoTool.d.ts.map +1 -1
  67. package/dist/mcp/builtin/getConfigInfoTool.js +2 -5
  68. package/dist/mcp/builtin/getConfigInfoTool.js.map +1 -1
  69. package/dist/mcp/builtin/globals/countVersionsTool.d.ts.map +1 -1
  70. package/dist/mcp/builtin/globals/countVersionsTool.js +1 -2
  71. package/dist/mcp/builtin/globals/countVersionsTool.js.map +1 -1
  72. package/dist/mcp/builtin/globals/findTool.d.ts.map +1 -1
  73. package/dist/mcp/builtin/globals/findTool.js +2 -2
  74. package/dist/mcp/builtin/globals/findTool.js.map +1 -1
  75. package/dist/mcp/builtin/globals/findVersionByIDTool.d.ts.map +1 -1
  76. package/dist/mcp/builtin/globals/findVersionByIDTool.js +1 -2
  77. package/dist/mcp/builtin/globals/findVersionByIDTool.js.map +1 -1
  78. package/dist/mcp/builtin/globals/findVersionsTool.d.ts.map +1 -1
  79. package/dist/mcp/builtin/globals/findVersionsTool.js +1 -2
  80. package/dist/mcp/builtin/globals/findVersionsTool.js.map +1 -1
  81. package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts.map +1 -1
  82. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js +21 -3
  83. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js.map +1 -1
  84. package/dist/mcp/builtin/globals/restoreVersionTool.d.ts.map +1 -1
  85. package/dist/mcp/builtin/globals/restoreVersionTool.js +1 -2
  86. package/dist/mcp/builtin/globals/restoreVersionTool.js.map +1 -1
  87. package/dist/mcp/builtin/globals/updateTool.d.ts.map +1 -1
  88. package/dist/mcp/builtin/globals/updateTool.js +2 -2
  89. package/dist/mcp/builtin/globals/updateTool.js.map +1 -1
  90. package/dist/mcp/builtin/validateEntityData.d.ts.map +1 -1
  91. package/dist/mcp/builtin/validateEntityData.js +1 -1
  92. package/dist/mcp/builtin/validateEntityData.js.map +1 -1
  93. package/dist/mcp/builtinTools.d.ts.map +1 -1
  94. package/dist/mcp/sanitizeMCPConfig.d.ts.map +1 -1
  95. package/dist/mcp/sanitizeMCPConfig.js +1 -0
  96. package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
  97. package/dist/stdio.d.ts +3 -4
  98. package/dist/stdio.d.ts.map +1 -1
  99. package/dist/stdio.js +59 -41
  100. package/dist/stdio.js.map +1 -1
  101. package/dist/types.d.ts +57 -9
  102. package/dist/types.d.ts.map +1 -1
  103. package/dist/types.js +2 -4
  104. package/dist/types.js.map +1 -1
  105. package/dist/utils/camelCase.d.ts.map +1 -1
  106. package/dist/utils/resolveProjectRoot.d.ts.map +1 -1
  107. package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts +28 -0
  108. package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts.map +1 -0
  109. package/dist/utils/schemaConversion/filterFieldsByAccess.js +71 -0
  110. package/dist/utils/schemaConversion/filterFieldsByAccess.js.map +1 -0
  111. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts +5 -3
  112. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts.map +1 -1
  113. package/dist/utils/schemaConversion/getEntityInputSchema.js +44 -12
  114. package/dist/utils/schemaConversion/getEntityInputSchema.js.map +1 -1
  115. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts +5 -10
  116. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts.map +1 -1
  117. package/dist/utils/schemaConversion/sanitizeEntitySchema.js +15 -95
  118. package/dist/utils/schemaConversion/sanitizeEntitySchema.js.map +1 -1
  119. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js +15 -40
  120. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js.map +1 -1
  121. package/dist/utils/toStandardSchema.d.ts.map +1 -1
  122. package/package.json +9 -11
  123. package/src/endpoint/access.ts +3 -10
  124. package/src/endpoint/index.ts +45 -16
  125. package/src/index.ts +4 -4
  126. package/src/mcp/buildMcpServer.ts +40 -20
  127. package/src/mcp/builtin/collections/countTool.ts +1 -2
  128. package/src/mcp/builtin/collections/countVersionsTool.ts +1 -2
  129. package/src/mcp/builtin/collections/createTool.ts +14 -5
  130. package/src/mcp/builtin/collections/deleteTool.ts +1 -2
  131. package/src/mcp/builtin/collections/duplicateTool.ts +1 -2
  132. package/src/mcp/builtin/collections/fileInput.spec.ts +79 -0
  133. package/src/mcp/builtin/collections/fileInput.ts +139 -0
  134. package/src/mcp/builtin/collections/findDistinctTool.ts +1 -2
  135. package/src/mcp/builtin/collections/findTool.ts +3 -4
  136. package/src/mcp/builtin/collections/findVersionByIDTool.ts +1 -2
  137. package/src/mcp/builtin/collections/findVersionsTool.ts +1 -2
  138. package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +39 -9
  139. package/src/mcp/builtin/collections/restoreVersionTool.ts +1 -2
  140. package/src/mcp/builtin/collections/updateTool.ts +25 -9
  141. package/src/mcp/builtin/getConfigInfoTool.ts +2 -4
  142. package/src/mcp/builtin/globals/countVersionsTool.ts +1 -2
  143. package/src/mcp/builtin/globals/findTool.ts +2 -2
  144. package/src/mcp/builtin/globals/findVersionByIDTool.ts +1 -2
  145. package/src/mcp/builtin/globals/findVersionsTool.ts +1 -2
  146. package/src/mcp/builtin/globals/getGlobalSchemaTool.ts +25 -3
  147. package/src/mcp/builtin/globals/restoreVersionTool.ts +1 -2
  148. package/src/mcp/builtin/globals/updateTool.ts +2 -2
  149. package/src/mcp/builtin/validateEntityData.ts +1 -1
  150. package/src/mcp/sanitizeMCPConfig.ts +1 -0
  151. package/src/stdio.ts +59 -42
  152. package/src/types.ts +57 -9
  153. package/src/utils/schemaConversion/filterFieldsByAccess.ts +123 -0
  154. package/src/utils/schemaConversion/getEntityInputSchema.ts +45 -27
  155. package/src/utils/schemaConversion/sanitizeEntitySchema.spec.ts +12 -19
  156. package/src/utils/schemaConversion/sanitizeEntitySchema.ts +17 -114
  157. package/dist/@types/assets.d.js +0 -2
  158. package/dist/@types/assets.d.js.map +0 -1
  159. package/dist/utils/localAPIDefaults.d.ts +0 -20
  160. package/dist/utils/localAPIDefaults.d.ts.map +0 -1
  161. package/dist/utils/localAPIDefaults.js +0 -19
  162. package/dist/utils/localAPIDefaults.js.map +0 -1
  163. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.d.ts +0 -7
  164. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.d.ts.map +0 -1
  165. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.js +0 -20
  166. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.js.map +0 -1
  167. package/src/@types/assets.d.ts +0 -3
  168. package/src/utils/localAPIDefaults.ts +0 -22
  169. package/src/utils/schemaConversion/removeVirtualFieldsFromSchema.ts +0 -27
package/src/stdio.ts CHANGED
@@ -1,7 +1,7 @@
1
- import type { MaybePromise, Plugin, SanitizedConfig } from 'payload'
1
+ import type { Config, Plugin, SanitizedConfig } from 'payload'
2
2
 
3
3
  /* eslint-disable no-console */
4
- import { StdioServerTransport } from '@modelcontextprotocol/server'
4
+ import { serveStdio } from '@modelcontextprotocol/server/stdio'
5
5
  import { fileURLToPath, pathToFileURL } from 'node:url'
6
6
  import { createLocalReq, getPayload } from 'payload'
7
7
  import { findConfig } from 'payload/node'
@@ -15,23 +15,14 @@ import { getPluginConfig } from './utils/getPluginConfig.js'
15
15
  import { resolveProjectRoot } from './utils/resolveProjectRoot.js'
16
16
 
17
17
  /**
18
- * Stdio adapter for the Payload MCP server.
18
+ * Starts Payload's MCP server over stdin and stdout.
19
19
  *
20
- * Pass PAYLOAD_MCP_AUTHORIZATION when stdio should authenticate with the same
21
- * Payload auth header as HTTP. In development, PAYLOAD_MCP_OVERRIDE_ACCESS=true
22
- * skips access control for local setup.
20
+ * Set `PAYLOAD_MCP_AUTHORIZATION` to authenticate. In development,
21
+ * `PAYLOAD_MCP_OVERRIDE_ACCESS=true` skips access checks.
23
22
  */
24
23
  export const runMcpStdio = async (): Promise<void> => {
25
- /**
26
- * If MCP clients spawn stdio servers from an arbitrary working directory,
27
- * Payload's cwd-anchored `findConfig()` can't locate the project on
28
- * its own. This module always lives inside the project's `node_modules`, so
29
- * we derive the project root from its own path and `chdir` into it.
30
- *
31
- * An absolute `PAYLOAD_CONFIG_PATH` still overrides everything; unusual
32
- * layouts (e.g. a monorepo where the package is hoisted above the app) can
33
- * fall back to it. See the implementation of findConfig for details.
34
- */
24
+ // MCP clients may start this command from another folder. Move to the Payload
25
+ // project so findConfig() can find the config.
35
26
  const projectRoot = resolveProjectRoot(fileURLToPath(import.meta.url))
36
27
  if (projectRoot) {
37
28
  process.chdir(projectRoot)
@@ -39,29 +30,46 @@ export const runMcpStdio = async (): Promise<void> => {
39
30
 
40
31
  const configPath = findConfig()
41
32
  const configModule = await import(pathToFileURL(configPath).toString())
42
- const config = (await (configModule.default ?? configModule)) as MaybePromise<SanitizedConfig>
43
-
44
- const payload = await getPayload({ config })
33
+ const config = (await (configModule.default ?? configModule)) as SanitizedConfig
45
34
 
46
35
  /**
47
- * If the user added `mcpPlugin({...})` to their `plugins` array, read the
48
- * sanitized config they registered. Otherwise fall back to the defaults. That way,
49
- * the mcp works on any project that has `@payloadcms/plugin-mcp` installed,
50
- * even if the plugin is not added to the plugins array.
36
+ * stdout is only for MCP messages. The spec says the server must not write
37
+ * logs there and may write them to stderr instead.
38
+ *
39
+ * The 2.0 client library recovers from stray stdout logs, but that behavior is not
40
+ * guaranteed. Move Payload logs to stderr so Payload does not add invalid data
41
+ * to stdout. Keep options from configurable loggers. Replace pre-built loggers
42
+ * because their output cannot be redirected.
43
+ *
44
+ * @see https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#stdio
51
45
  */
46
+ const loggerConfig: { logger?: Config['logger'] } = config
47
+ if (
48
+ loggerConfig.logger &&
49
+ typeof loggerConfig.logger === 'object' &&
50
+ 'options' in loggerConfig.logger
51
+ ) {
52
+ loggerConfig.logger.destination = process.stderr
53
+ } else {
54
+ loggerConfig.logger = { destination: process.stderr, options: {} }
55
+ }
56
+
57
+ const payload = await getPayload({ config, cron: false, disableOnInit: true })
58
+
52
59
  let pluginConfig: SanitizedMCPPluginConfig
53
60
  try {
54
61
  pluginConfig = getPluginConfig({ config: payload.config })
55
62
  } catch {
63
+ // The command also works when mcpPlugin() is not in the Payload config.
56
64
  pluginConfig = sanitizeMCPConfig({ config: payload.config, pluginConfig: {} })
57
65
 
58
- const fakePluginFn: Plugin = (config) => config
59
- fakePluginFn.slug = '@payloadcms/plugin-mcp'
60
- // @ts-expect-error
61
- fakePluginFn.sanitizedOptions = pluginConfig
62
-
63
- // Push to payload config, to ensure consecutive calls to `getPluginConfig()` work
64
- ;(payload.config.plugins ??= []).push(fakePluginFn)
66
+ const fallbackPlugin: Plugin = (config) => config
67
+ Object.assign(fallbackPlugin, {
68
+ slug: '@payloadcms/plugin-mcp',
69
+ sanitizedOptions: pluginConfig,
70
+ })
71
+ payload.config.plugins ??= []
72
+ payload.config.plugins.push(fallbackPlugin)
65
73
  }
66
74
 
67
75
  const overrideAccessEnv = process.env.PAYLOAD_MCP_OVERRIDE_ACCESS
@@ -86,28 +94,37 @@ export const runMcpStdio = async (): Promise<void> => {
86
94
  req.payloadAPI = 'MCP' as const
87
95
  const authorizedMCP = await getAuthorizedMCP({ overrideAccess, req })
88
96
 
89
- const server = buildMcpServer({ authorizedMCP, pluginConfig, req })
90
-
91
- const transport = new StdioServerTransport()
92
- await server.connect(transport)
97
+ const stdioServer = serveStdio(() => buildMcpServer({ authorizedMCP, pluginConfig, req }), {
98
+ onerror: (err) => {
99
+ // MCP messages use stdout, so write SDK errors to stderr.
100
+ console.error('[payload-mcp] error serving MCP over stdio:', err)
101
+ },
102
+ })
103
+
104
+ // Close the MCP server and Payload when the client disconnects or the process stops.
105
+ let isShuttingDown = false
106
+ const shutdown = async () => {
107
+ if (isShuttingDown) {
108
+ return
109
+ }
110
+ isShuttingDown = true
93
111
 
94
- // Process now lives until stdin closes. Wire graceful shutdown so DB
95
- // connections (and any other Payload-managed resources) get released.
96
- const shutdown = async (code = 0) => {
97
112
  try {
98
- await server.close()
113
+ await stdioServer.close()
99
114
  } catch (err) {
100
115
  console.error('[payload-mcp] error closing server:', err)
101
116
  }
117
+
102
118
  try {
103
119
  await payload.destroy()
104
120
  } catch (err) {
105
121
  console.error('[payload-mcp] error destroying payload:', err)
106
122
  }
107
- process.exit(code)
123
+
124
+ process.exit(0)
108
125
  }
109
126
 
110
- process.on('SIGINT', () => void shutdown(0))
111
- process.on('SIGTERM', () => void shutdown(0))
112
- process.stdin.on('close', () => void shutdown(0))
127
+ process.once('SIGINT', () => void shutdown())
128
+ process.once('SIGTERM', () => void shutdown())
129
+ process.stdin.once('close', () => void shutdown())
113
130
  }
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 timestamps are excluded upstream by the `input` variant. `id` stays because it's
80
+ // 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: {