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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (202) hide show
  1. package/LICENSE.md +1 -1
  2. package/bin.js +7 -0
  3. package/dist/defaultAccess.d.ts.map +1 -1
  4. package/dist/defineTool.d.ts +8 -8
  5. package/dist/defineTool.d.ts.map +1 -1
  6. package/dist/endpoint/access.d.ts +2 -7
  7. package/dist/endpoint/access.d.ts.map +1 -1
  8. package/dist/endpoint/access.js +6 -13
  9. package/dist/endpoint/access.js.map +1 -1
  10. package/dist/endpoint/index.d.ts +1 -1
  11. package/dist/endpoint/index.d.ts.map +1 -1
  12. package/dist/endpoint/index.js +57 -17
  13. package/dist/endpoint/index.js.map +1 -1
  14. package/dist/index.d.ts +2 -2
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +2 -2
  17. package/dist/index.js.map +1 -1
  18. package/dist/mcp/buildMcpServer.d.ts +5 -5
  19. package/dist/mcp/buildMcpServer.d.ts.map +1 -1
  20. package/dist/mcp/buildMcpServer.js +67 -33
  21. package/dist/mcp/buildMcpServer.js.map +1 -1
  22. package/dist/mcp/builtin/collections/authTools.d.ts.map +1 -1
  23. package/dist/mcp/builtin/collections/authTools.js +79 -56
  24. package/dist/mcp/builtin/collections/authTools.js.map +1 -1
  25. package/dist/mcp/builtin/collections/countTool.d.ts.map +1 -1
  26. package/dist/mcp/builtin/collections/countTool.js +10 -16
  27. package/dist/mcp/builtin/collections/countTool.js.map +1 -1
  28. package/dist/mcp/builtin/collections/countVersionsTool.d.ts.map +1 -1
  29. package/dist/mcp/builtin/collections/countVersionsTool.js +10 -15
  30. package/dist/mcp/builtin/collections/countVersionsTool.js.map +1 -1
  31. package/dist/mcp/builtin/collections/createTool.d.ts +1 -1
  32. package/dist/mcp/builtin/collections/createTool.d.ts.map +1 -1
  33. package/dist/mcp/builtin/collections/createTool.js +104 -54
  34. package/dist/mcp/builtin/collections/createTool.js.map +1 -1
  35. package/dist/mcp/builtin/collections/deleteTool.d.ts.map +1 -1
  36. package/dist/mcp/builtin/collections/deleteTool.js +41 -45
  37. package/dist/mcp/builtin/collections/deleteTool.js.map +1 -1
  38. package/dist/mcp/builtin/collections/duplicateTool.d.ts.map +1 -1
  39. package/dist/mcp/builtin/collections/duplicateTool.js +27 -38
  40. package/dist/mcp/builtin/collections/duplicateTool.js.map +1 -1
  41. package/dist/mcp/builtin/collections/fileInput.d.ts +28 -0
  42. package/dist/mcp/builtin/collections/fileInput.d.ts.map +1 -0
  43. package/dist/mcp/builtin/collections/fileInput.js +123 -0
  44. package/dist/mcp/builtin/collections/fileInput.js.map +1 -0
  45. package/dist/mcp/builtin/collections/fileInput.spec.js +86 -0
  46. package/dist/mcp/builtin/collections/fileInput.spec.js.map +1 -0
  47. package/dist/mcp/builtin/collections/findDistinctTool.d.ts.map +1 -1
  48. package/dist/mcp/builtin/collections/findDistinctTool.js +12 -28
  49. package/dist/mcp/builtin/collections/findDistinctTool.js.map +1 -1
  50. package/dist/mcp/builtin/collections/findTool.d.ts.map +1 -1
  51. package/dist/mcp/builtin/collections/findTool.js +23 -46
  52. package/dist/mcp/builtin/collections/findTool.js.map +1 -1
  53. package/dist/mcp/builtin/collections/findVersionByIDTool.d.ts.map +1 -1
  54. package/dist/mcp/builtin/collections/findVersionByIDTool.js +18 -28
  55. package/dist/mcp/builtin/collections/findVersionByIDTool.js.map +1 -1
  56. package/dist/mcp/builtin/collections/findVersionsTool.d.ts.map +1 -1
  57. package/dist/mcp/builtin/collections/findVersionsTool.js +17 -32
  58. package/dist/mcp/builtin/collections/findVersionsTool.js.map +1 -1
  59. package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -1
  60. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +51 -11
  61. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -1
  62. package/dist/mcp/builtin/collections/restoreVersionTool.d.ts.map +1 -1
  63. package/dist/mcp/builtin/collections/restoreVersionTool.js +15 -28
  64. package/dist/mcp/builtin/collections/restoreVersionTool.js.map +1 -1
  65. package/dist/mcp/builtin/collections/updateTool.d.ts.map +1 -1
  66. package/dist/mcp/builtin/collections/updateTool.js +62 -86
  67. package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
  68. package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts +2 -0
  69. package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts.map +1 -0
  70. package/dist/mcp/builtin/collections/uploadInstructionsTool.js +55 -0
  71. package/dist/mcp/builtin/collections/uploadInstructionsTool.js.map +1 -0
  72. package/dist/mcp/builtin/formatEntityError.d.ts +16 -0
  73. package/dist/mcp/builtin/formatEntityError.d.ts.map +1 -0
  74. package/dist/mcp/builtin/formatEntityError.js +55 -0
  75. package/dist/mcp/builtin/formatEntityError.js.map +1 -0
  76. package/dist/mcp/builtin/getConfigInfoTool.d.ts.map +1 -1
  77. package/dist/mcp/builtin/getConfigInfoTool.js +5 -7
  78. package/dist/mcp/builtin/getConfigInfoTool.js.map +1 -1
  79. package/dist/mcp/builtin/globals/countVersionsTool.d.ts.map +1 -1
  80. package/dist/mcp/builtin/globals/countVersionsTool.js +10 -15
  81. package/dist/mcp/builtin/globals/countVersionsTool.js.map +1 -1
  82. package/dist/mcp/builtin/globals/findTool.d.ts.map +1 -1
  83. package/dist/mcp/builtin/globals/findTool.js +12 -18
  84. package/dist/mcp/builtin/globals/findTool.js.map +1 -1
  85. package/dist/mcp/builtin/globals/findVersionByIDTool.d.ts.map +1 -1
  86. package/dist/mcp/builtin/globals/findVersionByIDTool.js +14 -26
  87. package/dist/mcp/builtin/globals/findVersionByIDTool.js.map +1 -1
  88. package/dist/mcp/builtin/globals/findVersionsTool.d.ts.map +1 -1
  89. package/dist/mcp/builtin/globals/findVersionsTool.js +14 -31
  90. package/dist/mcp/builtin/globals/findVersionsTool.js.map +1 -1
  91. package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts.map +1 -1
  92. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js +28 -10
  93. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js.map +1 -1
  94. package/dist/mcp/builtin/globals/restoreVersionTool.d.ts.map +1 -1
  95. package/dist/mcp/builtin/globals/restoreVersionTool.js +16 -24
  96. package/dist/mcp/builtin/globals/restoreVersionTool.js.map +1 -1
  97. package/dist/mcp/builtin/globals/updateTool.d.ts.map +1 -1
  98. package/dist/mcp/builtin/globals/updateTool.js +28 -37
  99. package/dist/mcp/builtin/globals/updateTool.js.map +1 -1
  100. package/dist/mcp/builtinTools.d.ts +6 -0
  101. package/dist/mcp/builtinTools.d.ts.map +1 -1
  102. package/dist/mcp/builtinTools.js +9 -3
  103. package/dist/mcp/builtinTools.js.map +1 -1
  104. package/dist/mcp/sanitizeMCPConfig.d.ts.map +1 -1
  105. package/dist/mcp/sanitizeMCPConfig.js +5 -1
  106. package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
  107. package/dist/stdio.d.ts +3 -4
  108. package/dist/stdio.d.ts.map +1 -1
  109. package/dist/stdio.js +61 -42
  110. package/dist/stdio.js.map +1 -1
  111. package/dist/types.d.ts +61 -13
  112. package/dist/types.d.ts.map +1 -1
  113. package/dist/types.js +2 -4
  114. package/dist/types.js.map +1 -1
  115. package/dist/utils/camelCase.d.ts.map +1 -1
  116. package/dist/utils/resolveProjectRoot.d.ts.map +1 -1
  117. package/dist/utils/toStandardSchema.d.ts.map +1 -1
  118. package/package.json +8 -12
  119. package/src/endpoint/access.ts +5 -13
  120. package/src/endpoint/index.ts +45 -16
  121. package/src/index.ts +4 -4
  122. package/src/mcp/buildMcpServer.ts +79 -49
  123. package/src/mcp/builtin/collections/authTools.ts +77 -69
  124. package/src/mcp/builtin/collections/countTool.ts +10 -23
  125. package/src/mcp/builtin/collections/countVersionsTool.ts +10 -20
  126. package/src/mcp/builtin/collections/createTool.ts +110 -77
  127. package/src/mcp/builtin/collections/deleteTool.ts +36 -65
  128. package/src/mcp/builtin/collections/duplicateTool.ts +34 -86
  129. package/src/mcp/builtin/collections/fileInput.spec.ts +93 -0
  130. package/src/mcp/builtin/collections/fileInput.ts +169 -0
  131. package/src/mcp/builtin/collections/findDistinctTool.ts +12 -65
  132. package/src/mcp/builtin/collections/findTool.ts +23 -106
  133. package/src/mcp/builtin/collections/findVersionByIDTool.ts +16 -60
  134. package/src/mcp/builtin/collections/findVersionsTool.ts +15 -87
  135. package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +48 -14
  136. package/src/mcp/builtin/collections/restoreVersionTool.ts +15 -58
  137. package/src/mcp/builtin/collections/updateTool.ts +61 -100
  138. package/src/mcp/builtin/collections/uploadInstructionsTool.ts +64 -0
  139. package/src/mcp/builtin/formatEntityError.ts +77 -0
  140. package/src/mcp/builtin/getConfigInfoTool.ts +4 -5
  141. package/src/mcp/builtin/globals/countVersionsTool.ts +10 -19
  142. package/src/mcp/builtin/globals/findTool.ts +14 -53
  143. package/src/mcp/builtin/globals/findVersionByIDTool.ts +14 -54
  144. package/src/mcp/builtin/globals/findVersionsTool.ts +15 -94
  145. package/src/mcp/builtin/globals/getGlobalSchemaTool.ts +30 -8
  146. package/src/mcp/builtin/globals/restoreVersionTool.ts +15 -47
  147. package/src/mcp/builtin/globals/updateTool.ts +39 -62
  148. package/src/mcp/builtinTools.ts +9 -2
  149. package/src/mcp/sanitizeMCPConfig.ts +5 -1
  150. package/src/stdio.ts +61 -43
  151. package/src/types.ts +61 -13
  152. package/dist/@types/assets.d.js +0 -2
  153. package/dist/@types/assets.d.js.map +0 -1
  154. package/dist/mcp/builtin/collections/formatCollectionError.d.ts +0 -9
  155. package/dist/mcp/builtin/collections/formatCollectionError.d.ts.map +0 -1
  156. package/dist/mcp/builtin/collections/formatCollectionError.js +0 -60
  157. package/dist/mcp/builtin/collections/formatCollectionError.js.map +0 -1
  158. package/dist/mcp/builtin/validateEntityData.d.ts +0 -14
  159. package/dist/mcp/builtin/validateEntityData.d.ts.map +0 -1
  160. package/dist/mcp/builtin/validateEntityData.js +0 -82
  161. package/dist/mcp/builtin/validateEntityData.js.map +0 -1
  162. package/dist/utils/getVirtualFieldNames.d.ts +0 -14
  163. package/dist/utils/getVirtualFieldNames.d.ts.map +0 -1
  164. package/dist/utils/getVirtualFieldNames.js +0 -35
  165. package/dist/utils/getVirtualFieldNames.js.map +0 -1
  166. package/dist/utils/localAPIDefaults.d.ts +0 -20
  167. package/dist/utils/localAPIDefaults.d.ts.map +0 -1
  168. package/dist/utils/localAPIDefaults.js +0 -19
  169. package/dist/utils/localAPIDefaults.js.map +0 -1
  170. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts +0 -11
  171. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts.map +0 -1
  172. package/dist/utils/schemaConversion/getEntityInputSchema.js +0 -34
  173. package/dist/utils/schemaConversion/getEntityInputSchema.js.map +0 -1
  174. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.d.ts +0 -7
  175. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.d.ts.map +0 -1
  176. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.js +0 -20
  177. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.js.map +0 -1
  178. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts +0 -15
  179. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts.map +0 -1
  180. package/dist/utils/schemaConversion/sanitizeEntitySchema.js +0 -464
  181. package/dist/utils/schemaConversion/sanitizeEntitySchema.js.map +0 -1
  182. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js +0 -158
  183. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js.map +0 -1
  184. package/dist/utils/transformPointDataToPayload.d.ts +0 -7
  185. package/dist/utils/transformPointDataToPayload.d.ts.map +0 -1
  186. package/dist/utils/transformPointDataToPayload.js +0 -28
  187. package/dist/utils/transformPointDataToPayload.js.map +0 -1
  188. package/dist/utils/whereSchema.d.ts +0 -9
  189. package/dist/utils/whereSchema.d.ts.map +0 -1
  190. package/dist/utils/whereSchema.js +0 -13
  191. package/dist/utils/whereSchema.js.map +0 -1
  192. package/src/@types/assets.d.ts +0 -3
  193. package/src/mcp/builtin/collections/formatCollectionError.ts +0 -84
  194. package/src/mcp/builtin/validateEntityData.ts +0 -132
  195. package/src/utils/getVirtualFieldNames.ts +0 -53
  196. package/src/utils/localAPIDefaults.ts +0 -22
  197. package/src/utils/schemaConversion/getEntityInputSchema.ts +0 -78
  198. package/src/utils/schemaConversion/removeVirtualFieldsFromSchema.ts +0 -27
  199. package/src/utils/schemaConversion/sanitizeEntitySchema.spec.ts +0 -103
  200. package/src/utils/schemaConversion/sanitizeEntitySchema.ts +0 -529
  201. package/src/utils/transformPointDataToPayload.ts +0 -40
  202. package/src/utils/whereSchema.ts +0 -24
@@ -1,5 +1,11 @@
1
- import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/server'
2
- import { APIError, type PayloadHandler } from 'payload'
1
+ import type { PayloadHandler, PayloadRequest } from 'payload'
2
+
3
+ import {
4
+ createMcpHandler,
5
+ isLegacyRequest,
6
+ WebStandardStreamableHTTPServerTransport,
7
+ } from '@modelcontextprotocol/server'
8
+ import { APIError } from 'payload'
3
9
 
4
10
  import { buildMcpServer } from '../mcp/buildMcpServer.js'
5
11
  import { getPluginConfig } from '../utils/getPluginConfig.js'
@@ -27,22 +33,45 @@ export const mcpEndpoint: PayloadHandler = async (req) => {
27
33
  }
28
34
 
29
35
  const authorizedMCP = await getAuthorizedMCP({ overrideAccess, req })
36
+ // Payload augments the original web-standard Request in place.
37
+ const mcpRequest = req as PayloadRequest & Request
30
38
 
31
- const server = buildMcpServer({ authorizedMCP, pluginConfig, req })
32
-
33
- const transport = new WebStandardStreamableHTTPServerTransport({
34
- enableJsonResponse: true,
35
- sessionIdGenerator: undefined, // stateless mode
36
- })
39
+ // Keep the old JSON-only, stateless behavior because the SDK's 2025 fallback uses SSE.
40
+ if (await isLegacyRequest(mcpRequest)) {
41
+ const server = buildMcpServer({ authorizedMCP, pluginConfig, req })
42
+ const transport = new WebStandardStreamableHTTPServerTransport({
43
+ enableJsonResponse: true,
44
+ sessionIdGenerator: undefined, // stateless mode
45
+ })
46
+ transport.onerror = (err) => {
47
+ req.payload.logger.error({ err, msg: 'Error serving legacy MCP request' })
48
+ }
37
49
 
38
- await server.connect(transport)
50
+ try {
51
+ await server.connect(transport)
52
+ return await transport.handleRequest(mcpRequest)
53
+ } finally {
54
+ await server.close().catch((err) => {
55
+ req.payload.logger.error({ err, msg: 'Error closing MCP server' })
56
+ })
57
+ }
58
+ }
39
59
 
40
- const mcpRequest = new Request(req.url, {
41
- body: req.body,
42
- duplex: 'half',
43
- headers: req.headers,
44
- method: req.method,
45
- } as { duplex: 'half' } & RequestInit)
60
+ const handler = createMcpHandler(() => buildMcpServer({ authorizedMCP, pluginConfig, req }), {
61
+ legacy: 'reject',
62
+ // SDK subscriptions always use SSE, so disable them to keep every response JSON-only.
63
+ maxSubscriptions: 0,
64
+ onerror: (err) => {
65
+ req.payload.logger.error({ err, msg: 'Error serving modern MCP request' })
66
+ },
67
+ responseMode: 'json',
68
+ })
46
69
 
47
- return await transport.handleRequest(mcpRequest)
70
+ try {
71
+ return await handler.fetch(mcpRequest)
72
+ } finally {
73
+ await handler.close().catch((err) => {
74
+ req.payload.logger.error({ err, msg: 'Error closing modern MCP handler' })
75
+ })
76
+ }
48
77
  }
package/src/index.ts CHANGED
@@ -6,8 +6,8 @@ import { mcpEndpoint } from './endpoint/index.js'
6
6
  import { sanitizeMCPConfig } from './mcp/sanitizeMCPConfig.js'
7
7
 
8
8
  declare module 'payload' {
9
- export interface PayloadRequest {
10
- payloadAPI: 'GraphQL' | 'local' | 'MCP' | 'REST'
9
+ export interface PayloadRequestAPI {
10
+ MCP: true
11
11
  }
12
12
  interface RegisteredPlugins {
13
13
  /** After the plugin's `plugin` callback runs, `options` holds the sanitized config. */
@@ -22,8 +22,8 @@ export { defineCollectionTool, defineGlobalTool, definePrompt, defineTool } from
22
22
  export const mcpPlugin = definePlugin<MCPPluginConfig>({
23
23
  slug: '@payloadcms/plugin-mcp',
24
24
  order: 10,
25
- plugin: ({ config, plugins, ...rawConfig }) => {
26
- const pluginConfig = sanitizeMCPConfig({ config, pluginConfig: rawConfig })
25
+ plugin: ({ config, options, plugins }) => {
26
+ const pluginConfig = sanitizeMCPConfig({ config, pluginConfig: options })
27
27
 
28
28
  // Stash the sanitized config on plugin options so `getPluginConfig()` reads it.
29
29
  const registered = plugins['@payloadcms/plugin-mcp']
@@ -1,6 +1,7 @@
1
+ import type { PayloadRequest } from 'payload'
2
+
1
3
  import { McpServer, type ServerContext } from '@modelcontextprotocol/server'
2
- import { APIError, type PayloadRequest } from 'payload'
3
- import { z } from 'zod'
4
+ import { APIError, strictObject, z } from 'payload'
4
5
 
5
6
  import type {
6
7
  AuthorizedMCP,
@@ -16,11 +17,13 @@ import type {
16
17
  import { getLogger } from '../utils/getLogger.js'
17
18
  import { toStandardSchema } from '../utils/toStandardSchema.js'
18
19
 
20
+ z.config(z.locales.en())
21
+
19
22
  /**
20
- * Transport-agnostic core: registers every authorized MCP item onto a fresh
21
- * `McpServer` and returns it. The caller is responsible for picking a transport
22
- * (`WebStandardStreamableHTTPServerTransport`, `StdioServerTransport`, …) and
23
- * calling `server.connect(transport)`.
23
+ * Serving-entry-agnostic core: registers every authorized MCP item onto a fresh
24
+ * `McpServer` and returns it. The HTTP and stdio entry point callers provide fresh
25
+ * instances from this builder while they own the transport and protocol-era
26
+ * decision.
24
27
  *
25
28
  * `req` is the request context handlers see. For HTTP it's the live
26
29
  * `PayloadRequest` derived from the incoming HTTP request; for stdio it's a
@@ -47,18 +50,28 @@ export const buildMcpServer = ({
47
50
  * Wrap a tool handler's response with the tool's `overrideResponse`, then
48
51
  * strip the internal `doc` field so it doesn't leak onto the wire.
49
52
  */
50
- const finalizeToolResponse = (
51
- response: MCPToolResponse,
52
- overrideResponse?: MCPResponseOverride,
53
- ): MCPToolResponse => {
54
- const overridden = overrideResponse?.(response, response.doc ?? {}, req) ?? response
53
+ const finalizeToolResponse = async ({
54
+ input,
55
+ overrideResponse,
56
+ response,
57
+ toolName,
58
+ }: {
59
+ input: unknown
60
+ overrideResponse?: MCPResponseOverride
61
+ response: MCPToolResponse
62
+ toolName: string
63
+ }): Promise<MCPToolResponse> => {
64
+ let overridden = overrideResponse?.(response, response.doc ?? {}, req) ?? response
65
+ for (const hook of pluginConfig.hooks?.afterToolCall ?? []) {
66
+ overridden = await hook({ input, req, response: overridden, toolName })
67
+ }
55
68
  const { doc: _doc, ...rest } = overridden
56
69
  return rest
57
70
  }
58
71
 
59
72
  /**
60
73
  * Runs a collection/global tool call:
61
- * - reads `collectionSlug` / `globalSlug` from the input
74
+ * - reads `slug` from the input
62
75
  * - runs access control: errors if `authorizedMCP.items` has no entry for this tool + slug
63
76
  * - runs the tool handler and finalizes its response
64
77
  */
@@ -72,16 +85,15 @@ export const buildMcpServer = ({
72
85
  serverContext: ServerContext
73
86
  }): Promise<MCPToolResponse> => {
74
87
  const entity = item.type === 'collectionTool' ? 'collection' : 'global'
75
- const slugKey = item.type === 'collectionTool' ? 'collectionSlug' : 'globalSlug'
76
88
  const toolInput = (input ?? {}) as Record<string, unknown>
77
- const slug = toolInput[slugKey] as string | undefined
89
+ const slug = toolInput.slug as string | undefined
78
90
 
79
91
  if (!slug) {
80
92
  return {
81
93
  content: [
82
94
  {
83
95
  type: 'text',
84
- text: `Error: "${item.mcpName}" requires ${slugKey}. Use getConfigInfo to inspect ${entity} slugs.`,
96
+ text: `Error: "${item.mcpName}" requires slug. Use getConfigInfo to inspect ${entity} slugs.`,
85
97
  },
86
98
  ],
87
99
  isError: true,
@@ -116,10 +128,15 @@ export const buildMcpServer = ({
116
128
  serverContext,
117
129
  }
118
130
  const response = await (match.type === 'collectionTool'
119
- ? match.tool.handler({ ...handlerArgs, collectionSlug: slug })
120
- : match.tool.handler({ ...handlerArgs, globalSlug: slug }))
131
+ ? match.tool.handler({ ...handlerArgs, slug })
132
+ : match.tool.handler({ ...handlerArgs, slug }))
121
133
 
122
- return finalizeToolResponse(response, match.tool.overrideResponse)
134
+ return finalizeToolResponse({
135
+ input: toolInput,
136
+ overrideResponse: match.tool.overrideResponse,
137
+ response,
138
+ toolName: match.mcpName,
139
+ })
123
140
  }
124
141
 
125
142
  try {
@@ -134,10 +151,7 @@ export const buildMcpServer = ({
134
151
  }
135
152
  registeredEntityTools.add(item.mcpName)
136
153
 
137
- const inputSchema = withSlugInput({
138
- name: item.type === 'collectionTool' ? 'collectionSlug' : 'globalSlug',
139
- input: item.tool.input,
140
- })
154
+ const inputSchema = withSlugInput({ input: item.tool.input })
141
155
 
142
156
  server.registerTool(
143
157
  item.mcpName,
@@ -203,16 +217,21 @@ export const buildMcpServer = ({
203
217
  description: tool.description,
204
218
  inputSchema: tool.input ? toStandardSchema(tool.input) : undefined,
205
219
  },
206
- async (input: unknown, ctx: ServerContext) =>
207
- finalizeToolResponse(
208
- await tool.handler({
209
- authorizedMCP,
210
- input: (input ?? {}) as Record<string, unknown>,
211
- req,
212
- serverContext: ctx,
213
- }),
214
- tool.overrideResponse,
215
- ),
220
+ async (input: unknown, ctx: ServerContext) => {
221
+ const toolInput = (input ?? {}) as Record<string, unknown>
222
+ const response = await tool.handler({
223
+ authorizedMCP,
224
+ input: toolInput,
225
+ req,
226
+ serverContext: ctx,
227
+ })
228
+ return finalizeToolResponse({
229
+ input: toolInput,
230
+ overrideResponse: tool.overrideResponse,
231
+ response,
232
+ toolName: item.mcpName,
233
+ })
234
+ },
216
235
  )
217
236
  logger.info(`✅ Tool: ${item.mcpName} Registered.`)
218
237
  break
@@ -226,39 +245,50 @@ export const buildMcpServer = ({
226
245
  return server
227
246
  }
228
247
 
229
- const withSlugInput = ({
230
- name,
231
- input,
232
- }: {
233
- input?: ToolInputSchema
234
- name: 'collectionSlug' | 'globalSlug'
235
- }): ToolInputSchema => {
236
- const description = name === 'collectionSlug' ? 'The collection slug' : 'The global slug'
237
- const slugSchema = z.string().describe(description)
248
+ const withSlugInput = ({ input }: { input?: ToolInputSchema }): ToolInputSchema => {
249
+ const description = 'The target slug.'
250
+ const slugSchema = z.string().check(z.describe(description))
238
251
 
239
252
  if (!input) {
240
- return z.object({ [name]: slugSchema })
253
+ return strictObject({ slug: slugSchema }) as unknown as ToolInputSchema
241
254
  }
242
255
 
243
- if (input instanceof z.ZodObject) {
244
- return input.extend({ [name]: slugSchema })
256
+ if (typeof input === 'object' && input !== null && '~standard' in input) {
257
+ const schema = input['~standard'].jsonSchema.input({ target: 'draft-2020-12' })
258
+ const properties = schema.properties as Record<string, unknown> | undefined
259
+
260
+ if (properties?.slug) {
261
+ return input
262
+ }
263
+
264
+ return addSlugToJSONSchema({ description, schema: schema as JsonSchemaType })
245
265
  }
246
266
 
247
- const schema = input as {
267
+ return addSlugToJSONSchema({ description, schema: input })
268
+ }
269
+
270
+ const addSlugToJSONSchema = ({
271
+ description,
272
+ schema,
273
+ }: {
274
+ description: string
275
+ schema: JsonSchemaType
276
+ }): JsonSchemaType => {
277
+ const objectSchema = schema as {
248
278
  properties?: Record<string, JsonSchemaType>
249
279
  required?: string[]
250
280
  } & JsonSchemaType
251
281
 
252
282
  return {
253
- ...schema,
283
+ ...objectSchema,
254
284
  type: 'object',
255
285
  properties: {
256
- ...schema.properties,
257
- [name]: {
286
+ ...objectSchema.properties,
287
+ slug: {
258
288
  type: 'string',
259
289
  description,
260
290
  },
261
291
  },
262
- required: Array.from(new Set([name, ...(schema.required ?? [])])),
292
+ required: Array.from(new Set(['slug', ...(objectSchema.required ?? [])])),
263
293
  }
264
294
  }
@@ -1,7 +1,8 @@
1
- import { z } from 'zod'
1
+ import { createLocalReq, strictObject, z } from 'payload'
2
2
 
3
3
  import type { MCPToolResponse } from '../../../types.js'
4
4
 
5
+ import { defaultAccess } from '../../../defaultAccess.js'
5
6
  import { defineCollectionTool } from '../../../defineTool.js'
6
7
  import { getLogger } from '../../../utils/getLogger.js'
7
8
 
@@ -16,16 +17,16 @@ import { getLogger } from '../../../utils/getLogger.js'
16
17
  * users collection so all auth-shaped tools live in one place.
17
18
  */
18
19
 
19
- const emailSchema = z.string().email().describe('The user email address')
20
+ const emailSchema = z.email().check(z.describe('The user email address.'))
20
21
 
21
22
  const wrapError =
22
23
  (name: string) =>
23
- ({ collectionSlug, message }: { collectionSlug: string; message: string }): MCPToolResponse => {
24
+ ({ slug, message }: { message: string; slug: string }): MCPToolResponse => {
24
25
  return {
25
26
  content: [
26
27
  {
27
28
  type: 'text',
28
- text: `❌ **Error in ${name}** on ${collectionSlug}: ${message}`,
29
+ text: `❌ **Error in ${name}** on ${slug}: ${message}`,
29
30
  },
30
31
  ],
31
32
  }
@@ -40,20 +41,38 @@ export const authCollectionTool = defineCollectionTool({
40
41
  title: 'Check Auth Status',
41
42
  },
42
43
  description: 'Checks authentication status for the current user.',
43
- input: z.object({
44
+ input: strictObject({
44
45
  headers: z
45
- .record(z.string(), z.string())
46
- .describe('Optional custom headers to send with the authentication request')
47
- .optional(),
46
+ .optional(z.record(z.string(), z.string()))
47
+ .check(z.describe('Custom headers to send with the authentication request.')),
48
48
  }),
49
- }).handler(async ({ collectionSlug, input, req }) => {
49
+ }).handler(async ({ slug, authorizedMCP, input, req }) => {
50
50
  const logger = getLogger({ payload: req.payload })
51
51
  try {
52
52
  let authHeaders = new Headers()
53
53
  if (input.headers) {
54
54
  authHeaders = new Headers(input.headers)
55
55
  }
56
- const result = await req.payload.auth({ headers: authHeaders })
56
+ const authReq = await createLocalReq({ req: { headers: authHeaders } }, req.payload)
57
+ const result = await req.payload.auth({ headers: authHeaders, req: authReq })
58
+
59
+ if (result.user) {
60
+ const authenticatedUser = result.user
61
+ // Auth strategies read users with trusted Local API access. Re-read the user with the MCP
62
+ // caller's access level before returning it to the client.
63
+ const user = await req.payload.findByID({
64
+ id: authenticatedUser.id,
65
+ collection: authenticatedUser.collection,
66
+ overrideAccess: authorizedMCP.overrideAccess,
67
+ req: authReq,
68
+ })
69
+ result.user = {
70
+ ...user,
71
+ _sid: authenticatedUser._sid,
72
+ _strategy: authenticatedUser._strategy,
73
+ collection: authenticatedUser.collection,
74
+ }
75
+ }
57
76
  return {
58
77
  content: [
59
78
  {
@@ -65,8 +84,8 @@ export const authCollectionTool = defineCollectionTool({
65
84
  }
66
85
  } catch (error) {
67
86
  const errorMessage = error instanceof Error ? error.message : 'Unknown error'
68
- logger.error(`Error in auth tool on ${collectionSlug}: ${errorMessage}`)
69
- return wrapError('auth')({ collectionSlug, message: errorMessage })
87
+ logger.error(`Error in auth tool on ${slug}: ${errorMessage}`)
88
+ return wrapError('auth')({ slug, message: errorMessage })
70
89
  }
71
90
  })
72
91
 
@@ -79,35 +98,31 @@ export const forgotPasswordCollectionTool = defineCollectionTool({
79
98
  title: 'Forgot Password',
80
99
  },
81
100
  description: 'Sends a password reset email to a user.',
82
- input: z.object({
83
- disableEmail: z
84
- .boolean()
85
- .describe('Whether to disable sending the email (for testing)')
86
- .optional()
87
- .default(false),
101
+ input: strictObject({
88
102
  email: emailSchema,
89
103
  }),
90
- }).handler(async ({ collectionSlug, input, req }) => {
104
+ }).handler(async ({ slug, input, req }) => {
91
105
  const logger = getLogger({ payload: req.payload })
92
106
  try {
93
- const result = await req.payload.forgotPassword({
94
- collection: collectionSlug,
107
+ await req.payload.forgotPassword({
108
+ collection: slug,
95
109
  data: { email: input.email },
96
- disableEmail: input.disableEmail,
110
+ disableEmail: false,
111
+ overrideAccess: false,
112
+ req,
97
113
  })
98
114
  return {
99
115
  content: [
100
116
  {
101
117
  type: 'text',
102
- text: `# Forgot Password Email Sent\n\n**Collection:** ${collectionSlug}\n**Email:** ${input.email}\n\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``,
118
+ text: 'If an account matches that email, password reset instructions have been sent.',
103
119
  },
104
120
  ],
105
- doc: { result } as Record<string, unknown>,
106
121
  }
107
122
  } catch (error) {
108
123
  const errorMessage = error instanceof Error ? error.message : 'Unknown error'
109
- logger.error(`Error in forgotPassword tool on ${collectionSlug}: ${errorMessage}`)
110
- return wrapError('forgotPassword')({ collectionSlug, message: errorMessage })
124
+ logger.error(`Error in forgotPassword tool on ${slug}: ${errorMessage}`)
125
+ return wrapError('forgotPassword')({ slug, message: errorMessage })
111
126
  }
112
127
  })
113
128
 
@@ -120,45 +135,35 @@ export const loginCollectionTool = defineCollectionTool({
120
135
  title: 'User Login',
121
136
  },
122
137
  description: 'Authenticates a user with email and password.',
123
- input: z.object({
138
+ input: strictObject({
124
139
  depth: z
125
- .number()
126
- .int()
127
- .min(0)
128
- .max(10)
129
- .describe('Depth of population for relationships')
130
- .optional()
131
- .default(0),
140
+ ._default(z.int().check(z.minimum(0), z.maximum(10)), 0)
141
+ .check(z.describe('Depth of population for relationships.')),
132
142
  email: emailSchema,
133
- password: z.string().describe('The user password'),
134
- showHiddenFields: z
135
- .boolean()
136
- .describe('Whether to show hidden fields in the response')
137
- .optional()
138
- .default(false),
143
+ password: z.string().check(z.describe('The user password.')),
139
144
  }),
140
- }).handler(async ({ collectionSlug, input, req }) => {
145
+ }).handler(async ({ slug, authorizedMCP, input, req }) => {
141
146
  const logger = getLogger({ payload: req.payload })
142
147
  try {
143
148
  const result = await req.payload.login({
144
- collection: collectionSlug,
149
+ collection: slug,
145
150
  data: { email: input.email, password: input.password },
146
151
  depth: input.depth,
147
- showHiddenFields: input.showHiddenFields,
152
+ overrideAccess: authorizedMCP.overrideAccess,
148
153
  })
149
154
  return {
150
155
  content: [
151
156
  {
152
157
  type: 'text',
153
- text: `# Login Successful\n\n**User:** ${input.email}\n**Collection:** ${collectionSlug}\n\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``,
158
+ text: `# Login Successful\n\n**User:** ${input.email}\n**Collection:** ${slug}\n\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``,
154
159
  },
155
160
  ],
156
161
  doc: result as unknown as Record<string, unknown>,
157
162
  }
158
163
  } catch (error) {
159
164
  const errorMessage = error instanceof Error ? error.message : 'Unknown error'
160
- logger.error(`Error in login tool on ${collectionSlug}: ${errorMessage}`)
161
- return wrapError('login')({ collectionSlug, message: errorMessage })
165
+ logger.error(`Error in login tool on ${slug}: ${errorMessage}`)
166
+ return wrapError('login')({ slug, message: errorMessage })
162
167
  }
163
168
  })
164
169
 
@@ -171,35 +176,37 @@ export const resetPasswordCollectionTool = defineCollectionTool({
171
176
  title: 'Reset Password',
172
177
  },
173
178
  description: 'Resets a user password with a reset token.',
174
- input: z.object({
175
- password: z.string().describe('The new password for the user'),
176
- token: z.string().describe('The password reset token sent to the user email'),
179
+ input: strictObject({
180
+ password: z.string().check(z.describe('The new password for the user.')),
181
+ token: z.string().check(z.describe('The password reset token sent to the user email.')),
177
182
  }),
178
- }).handler(async ({ collectionSlug, input, req }) => {
183
+ }).handler(async ({ slug, authorizedMCP, input, req }) => {
179
184
  const logger = getLogger({ payload: req.payload })
180
185
  try {
181
186
  const result = await req.payload.resetPassword({
182
- collection: collectionSlug,
187
+ collection: slug,
183
188
  data: { password: input.password, token: input.token },
184
- overrideAccess: true,
189
+ overrideAccess: authorizedMCP.overrideAccess,
185
190
  })
186
191
  return {
187
192
  content: [
188
193
  {
189
194
  type: 'text',
190
- text: `# Password Reset Successful\n\n**Collection:** ${collectionSlug}\n\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``,
195
+ text: `# Password Reset Successful\n\n**Collection:** ${slug}\n\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``,
191
196
  },
192
197
  ],
193
198
  doc: result as unknown as Record<string, unknown>,
194
199
  }
195
200
  } catch (error) {
196
201
  const errorMessage = error instanceof Error ? error.message : 'Unknown error'
197
- logger.error(`Error in resetPassword tool on ${collectionSlug}: ${errorMessage}`)
198
- return wrapError('resetPassword')({ collectionSlug, message: errorMessage })
202
+ logger.error(`Error in resetPassword tool on ${slug}: ${errorMessage}`)
203
+ return wrapError('resetPassword')({ slug, message: errorMessage })
199
204
  }
200
205
  })
201
206
 
202
207
  export const unlockCollectionTool = defineCollectionTool({
208
+ access: (args) =>
209
+ defaultAccess(args) && Boolean(args.permissions?.collections?.[args.slug]?.unlock),
203
210
  annotations: {
204
211
  destructiveHint: false,
205
212
  idempotentHint: true,
@@ -208,28 +215,29 @@ export const unlockCollectionTool = defineCollectionTool({
208
215
  title: 'Unlock Account',
209
216
  },
210
217
  description: 'Unlocks a user account that has been locked due to failed login attempts.',
211
- input: z.object({ email: emailSchema }),
212
- }).handler(async ({ collectionSlug, input, req }) => {
218
+ input: strictObject({ email: emailSchema }),
219
+ }).handler(async ({ slug, authorizedMCP, input, req }) => {
213
220
  const logger = getLogger({ payload: req.payload })
214
221
  try {
215
222
  const result = await req.payload.unlock({
216
- collection: collectionSlug,
223
+ collection: slug,
217
224
  data: { email: input.email },
218
- overrideAccess: true,
225
+ overrideAccess: authorizedMCP.overrideAccess,
226
+ req,
219
227
  })
220
228
  return {
221
229
  content: [
222
230
  {
223
231
  type: 'text',
224
- text: `# Account Unlocked\n\n**Collection:** ${collectionSlug}\n**Email:** ${input.email}\n**Result:** ${result ? 'Success' : 'Failed'}`,
232
+ text: `# Account Unlocked\n\n**Collection:** ${slug}\n**Email:** ${input.email}\n**Result:** ${result ? 'Success' : 'Failed'}`,
225
233
  },
226
234
  ],
227
235
  doc: { result } as Record<string, unknown>,
228
236
  }
229
237
  } catch (error) {
230
238
  const errorMessage = error instanceof Error ? error.message : 'Unknown error'
231
- logger.error(`Error in unlock tool on ${collectionSlug}: ${errorMessage}`)
232
- return wrapError('unlock')({ collectionSlug, message: errorMessage })
239
+ logger.error(`Error in unlock tool on ${slug}: ${errorMessage}`)
240
+ return wrapError('unlock')({ slug, message: errorMessage })
233
241
  }
234
242
  })
235
243
 
@@ -242,28 +250,28 @@ export const verifyCollectionTool = defineCollectionTool({
242
250
  title: 'Email Verification',
243
251
  },
244
252
  description: 'Verifies a user email with a verification token.',
245
- input: z.object({
246
- token: z.string().describe('The verification token sent to the user email'),
253
+ input: strictObject({
254
+ token: z.string().check(z.describe('The verification token sent to the user email.')),
247
255
  }),
248
- }).handler(async ({ collectionSlug, input, req }) => {
256
+ }).handler(async ({ slug, input, req }) => {
249
257
  const logger = getLogger({ payload: req.payload })
250
258
  try {
251
259
  const result = await req.payload.verifyEmail({
252
- collection: collectionSlug,
260
+ collection: slug,
253
261
  token: input.token,
254
262
  })
255
263
  return {
256
264
  content: [
257
265
  {
258
266
  type: 'text',
259
- text: `# Email Verification Successful\n\n**Collection:** ${collectionSlug}\n**Result:** ${result ? 'Success' : 'Failed'}`,
267
+ text: `# Email Verification Successful\n\n**Collection:** ${slug}\n**Result:** ${result ? 'Success' : 'Failed'}`,
260
268
  },
261
269
  ],
262
270
  doc: { result } as Record<string, unknown>,
263
271
  }
264
272
  } catch (error) {
265
273
  const errorMessage = error instanceof Error ? error.message : 'Unknown error'
266
- logger.error(`Error in verify tool on ${collectionSlug}: ${errorMessage}`)
267
- return wrapError('verify')({ collectionSlug, message: errorMessage })
274
+ logger.error(`Error in verify tool on ${slug}: ${errorMessage}`)
275
+ return wrapError('verify')({ slug, message: errorMessage })
268
276
  }
269
277
  })