@payloadcms/plugin-mcp 4.0.0-canary.20 → 4.0.0-canary.20261117
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.
- package/bin.js +0 -7
- package/dist/endpoint/access.d.ts +20 -4
- package/dist/endpoint/access.d.ts.map +1 -1
- package/dist/endpoint/access.js +73 -11
- package/dist/endpoint/access.js.map +1 -1
- package/dist/endpoint/index.d.ts.map +1 -1
- package/dist/endpoint/index.js +58 -4
- package/dist/endpoint/index.js.map +1 -1
- package/dist/endpoint/oauth.d.ts +37 -0
- package/dist/endpoint/oauth.d.ts.map +1 -0
- package/dist/endpoint/oauth.js +105 -0
- package/dist/endpoint/oauth.js.map +1 -0
- package/dist/endpoint/oauthLoginToken.d.ts +27 -0
- package/dist/endpoint/oauthLoginToken.d.ts.map +1 -0
- package/dist/endpoint/oauthLoginToken.js +86 -0
- package/dist/endpoint/oauthLoginToken.js.map +1 -0
- package/dist/endpoint/oauthServer.d.ts +28 -0
- package/dist/endpoint/oauthServer.d.ts.map +1 -0
- package/dist/endpoint/oauthServer.js +455 -0
- package/dist/endpoint/oauthServer.js.map +1 -0
- package/dist/exports/client.d.ts +1 -1
- package/dist/exports/client.d.ts.map +1 -1
- package/dist/exports/client.js +1 -1
- package/dist/exports/client.js.map +1 -1
- package/dist/exports/rsc.d.ts +2 -0
- package/dist/exports/rsc.d.ts.map +1 -0
- package/dist/exports/rsc.js +3 -0
- package/dist/exports/rsc.js.map +1 -0
- package/dist/index.d.ts +10 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +34 -10
- package/dist/index.js.map +1 -1
- package/dist/mcp/buildMcpServer.d.ts +2 -2
- package/dist/mcp/buildMcpServer.d.ts.map +1 -1
- package/dist/mcp/buildMcpServer.js +36 -24
- package/dist/mcp/buildMcpServer.js.map +1 -1
- package/dist/mcp/builtin/collections/authTools.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/authTools.js +80 -56
- package/dist/mcp/builtin/collections/authTools.js.map +1 -1
- package/dist/mcp/builtin/collections/countTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/countTool.js +9 -14
- package/dist/mcp/builtin/collections/countTool.js.map +1 -1
- package/dist/mcp/builtin/collections/countVersionsTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/countVersionsTool.js +9 -13
- package/dist/mcp/builtin/collections/countVersionsTool.js.map +1 -1
- package/dist/mcp/builtin/collections/createTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/createTool.js +48 -49
- package/dist/mcp/builtin/collections/createTool.js.map +1 -1
- package/dist/mcp/builtin/collections/deleteTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/deleteTool.js +47 -44
- package/dist/mcp/builtin/collections/deleteTool.js.map +1 -1
- package/dist/mcp/builtin/collections/duplicateTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/duplicateTool.js +31 -37
- package/dist/mcp/builtin/collections/duplicateTool.js.map +1 -1
- package/dist/mcp/builtin/collections/fileInput.d.ts +21 -21
- package/dist/mcp/builtin/collections/fileInput.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/fileInput.js +34 -70
- package/dist/mcp/builtin/collections/fileInput.js.map +1 -1
- package/dist/mcp/builtin/collections/findDistinctTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/findDistinctTool.js +11 -26
- package/dist/mcp/builtin/collections/findDistinctTool.js.map +1 -1
- package/dist/mcp/builtin/collections/findTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/findTool.js +28 -46
- package/dist/mcp/builtin/collections/findTool.js.map +1 -1
- package/dist/mcp/builtin/collections/findVersionByIDTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/findVersionByIDTool.js +17 -26
- package/dist/mcp/builtin/collections/findVersionByIDTool.js.map +1 -1
- package/dist/mcp/builtin/collections/findVersionsTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/findVersionsTool.js +16 -30
- package/dist/mcp/builtin/collections/findVersionsTool.js.map +1 -1
- package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +30 -14
- package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -1
- package/dist/mcp/builtin/collections/restoreVersionTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/restoreVersionTool.js +14 -26
- package/dist/mcp/builtin/collections/restoreVersionTool.js.map +1 -1
- package/dist/mcp/builtin/collections/updateTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/updateTool.js +55 -87
- package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
- package/dist/mcp/builtin/collections/uploadInstructionsTool.js +11 -11
- package/dist/mcp/builtin/collections/uploadInstructionsTool.js.map +1 -1
- package/dist/mcp/builtin/formatEntityError.d.ts +16 -0
- package/dist/mcp/builtin/formatEntityError.d.ts.map +1 -0
- package/dist/mcp/builtin/formatEntityError.js +55 -0
- package/dist/mcp/builtin/formatEntityError.js.map +1 -0
- package/dist/mcp/builtin/getConfigInfoTool.d.ts.map +1 -1
- package/dist/mcp/builtin/getConfigInfoTool.js +3 -2
- package/dist/mcp/builtin/getConfigInfoTool.js.map +1 -1
- package/dist/mcp/builtin/globals/countVersionsTool.d.ts.map +1 -1
- package/dist/mcp/builtin/globals/countVersionsTool.js +9 -13
- package/dist/mcp/builtin/globals/countVersionsTool.js.map +1 -1
- package/dist/mcp/builtin/globals/findTool.d.ts.map +1 -1
- package/dist/mcp/builtin/globals/findTool.js +10 -16
- package/dist/mcp/builtin/globals/findTool.js.map +1 -1
- package/dist/mcp/builtin/globals/findVersionByIDTool.d.ts.map +1 -1
- package/dist/mcp/builtin/globals/findVersionByIDTool.js +13 -24
- package/dist/mcp/builtin/globals/findVersionByIDTool.js.map +1 -1
- package/dist/mcp/builtin/globals/findVersionsTool.d.ts.map +1 -1
- package/dist/mcp/builtin/globals/findVersionsTool.js +13 -29
- package/dist/mcp/builtin/globals/findVersionsTool.js.map +1 -1
- package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts.map +1 -1
- package/dist/mcp/builtin/globals/getGlobalSchemaTool.js +29 -13
- package/dist/mcp/builtin/globals/getGlobalSchemaTool.js.map +1 -1
- package/dist/mcp/builtin/globals/restoreVersionTool.d.ts.map +1 -1
- package/dist/mcp/builtin/globals/restoreVersionTool.js +15 -22
- package/dist/mcp/builtin/globals/restoreVersionTool.js.map +1 -1
- package/dist/mcp/builtin/globals/updateTool.d.ts.map +1 -1
- package/dist/mcp/builtin/globals/updateTool.js +27 -36
- package/dist/mcp/builtin/globals/updateTool.js.map +1 -1
- package/dist/mcp/sanitizeMCPConfig.d.ts.map +1 -1
- package/dist/mcp/sanitizeMCPConfig.js +4 -0
- package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
- package/dist/stdio.js +4 -3
- package/dist/stdio.js.map +1 -1
- package/dist/types.d.ts +131 -10
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/utils/seal.d.ts +17 -0
- package/dist/utils/seal.d.ts.map +1 -0
- package/dist/utils/seal.js +24 -0
- package/dist/utils/seal.js.map +1 -0
- package/dist/utils/toStandardSchema.js.map +1 -1
- package/dist/views/Authorize/AllowButtons/index.d.ts +18 -0
- package/dist/views/Authorize/AllowButtons/index.d.ts.map +1 -0
- package/dist/views/Authorize/AllowButtons/index.js +88 -0
- package/dist/views/Authorize/AllowButtons/index.js.map +1 -0
- package/dist/views/Authorize/index.css +19 -0
- package/dist/views/Authorize/index.d.ts +9 -0
- package/dist/views/Authorize/index.d.ts.map +1 -0
- package/dist/views/Authorize/index.js +98 -0
- package/dist/views/Authorize/index.js.map +1 -0
- package/package.json +30 -28
- package/src/endpoint/access.ts +81 -9
- package/src/endpoint/index.ts +50 -4
- package/src/endpoint/oauth.ts +108 -0
- package/src/endpoint/oauthLoginToken.ts +100 -0
- package/src/endpoint/oauthServer.ts +472 -0
- package/src/exports/client.ts +1 -1
- package/src/exports/rsc.ts +1 -0
- package/src/index.ts +53 -9
- package/src/mcp/buildMcpServer.ts +40 -30
- package/src/mcp/builtin/collections/authTools.ts +82 -71
- package/src/mcp/builtin/collections/countTool.ts +9 -21
- package/src/mcp/builtin/collections/countVersionsTool.ts +9 -18
- package/src/mcp/builtin/collections/createTool.ts +71 -96
- package/src/mcp/builtin/collections/deleteTool.ts +40 -66
- package/src/mcp/builtin/collections/duplicateTool.ts +36 -86
- package/src/mcp/builtin/collections/fileInput.spec.ts +2 -2
- package/src/mcp/builtin/collections/fileInput.ts +44 -81
- package/src/mcp/builtin/collections/findDistinctTool.ts +11 -63
- package/src/mcp/builtin/collections/findTool.ts +24 -106
- package/src/mcp/builtin/collections/findVersionByIDTool.ts +15 -58
- package/src/mcp/builtin/collections/findVersionsTool.ts +14 -85
- package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +23 -12
- package/src/mcp/builtin/collections/restoreVersionTool.ts +15 -57
- package/src/mcp/builtin/collections/updateTool.ts +55 -109
- package/src/mcp/builtin/collections/uploadInstructionsTool.ts +12 -12
- package/src/mcp/builtin/formatEntityError.ts +77 -0
- package/src/mcp/builtin/getConfigInfoTool.ts +2 -1
- package/src/mcp/builtin/globals/countVersionsTool.ts +9 -17
- package/src/mcp/builtin/globals/findTool.ts +13 -52
- package/src/mcp/builtin/globals/findVersionByIDTool.ts +13 -52
- package/src/mcp/builtin/globals/findVersionsTool.ts +14 -92
- package/src/mcp/builtin/globals/getGlobalSchemaTool.ts +21 -11
- package/src/mcp/builtin/globals/restoreVersionTool.ts +14 -45
- package/src/mcp/builtin/globals/updateTool.ts +38 -61
- package/src/mcp/sanitizeMCPConfig.ts +2 -0
- package/src/stdio.ts +2 -2
- package/src/types.ts +130 -10
- package/src/utils/seal.ts +46 -0
- package/src/utils/toStandardSchema.ts +1 -1
- package/src/views/Authorize/AllowButtons/index.tsx +97 -0
- package/src/views/Authorize/index.css +19 -0
- package/src/views/Authorize/index.tsx +100 -0
- package/dist/mcp/builtin/collections/fileInput.spec.js +0 -86
- package/dist/mcp/builtin/collections/fileInput.spec.js.map +0 -1
- package/dist/mcp/builtin/collections/formatCollectionError.d.ts +0 -9
- package/dist/mcp/builtin/collections/formatCollectionError.d.ts.map +0 -1
- package/dist/mcp/builtin/collections/formatCollectionError.js +0 -60
- package/dist/mcp/builtin/collections/formatCollectionError.js.map +0 -1
- package/dist/mcp/builtin/validateEntityData.d.ts +0 -14
- package/dist/mcp/builtin/validateEntityData.d.ts.map +0 -1
- package/dist/mcp/builtin/validateEntityData.js +0 -82
- package/dist/mcp/builtin/validateEntityData.js.map +0 -1
- package/dist/utils/getVirtualFieldNames.d.ts +0 -14
- package/dist/utils/getVirtualFieldNames.d.ts.map +0 -1
- package/dist/utils/getVirtualFieldNames.js +0 -35
- package/dist/utils/getVirtualFieldNames.js.map +0 -1
- package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts +0 -28
- package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts.map +0 -1
- package/dist/utils/schemaConversion/filterFieldsByAccess.js +0 -71
- package/dist/utils/schemaConversion/filterFieldsByAccess.js.map +0 -1
- package/dist/utils/schemaConversion/getEntityInputSchema.d.ts +0 -13
- package/dist/utils/schemaConversion/getEntityInputSchema.d.ts.map +0 -1
- package/dist/utils/schemaConversion/getEntityInputSchema.js +0 -66
- package/dist/utils/schemaConversion/getEntityInputSchema.js.map +0 -1
- package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts +0 -10
- package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts.map +0 -1
- package/dist/utils/schemaConversion/sanitizeEntitySchema.js +0 -384
- package/dist/utils/schemaConversion/sanitizeEntitySchema.js.map +0 -1
- package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js +0 -133
- package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js.map +0 -1
- package/dist/utils/transformPointDataToPayload.d.ts +0 -7
- package/dist/utils/transformPointDataToPayload.d.ts.map +0 -1
- package/dist/utils/transformPointDataToPayload.js +0 -28
- package/dist/utils/transformPointDataToPayload.js.map +0 -1
- package/dist/utils/whereSchema.d.ts +0 -9
- package/dist/utils/whereSchema.d.ts.map +0 -1
- package/dist/utils/whereSchema.js +0 -13
- package/dist/utils/whereSchema.js.map +0 -1
- package/src/mcp/builtin/collections/formatCollectionError.ts +0 -84
- package/src/mcp/builtin/validateEntityData.ts +0 -132
- package/src/utils/getVirtualFieldNames.ts +0 -53
- package/src/utils/schemaConversion/filterFieldsByAccess.ts +0 -123
- package/src/utils/schemaConversion/getEntityInputSchema.ts +0 -96
- package/src/utils/schemaConversion/sanitizeEntitySchema.spec.ts +0 -96
- package/src/utils/schemaConversion/sanitizeEntitySchema.ts +0 -432
- package/src/utils/transformPointDataToPayload.ts +0 -40
- package/src/utils/whereSchema.ts +0 -24
package/src/endpoint/access.ts
CHANGED
|
@@ -1,25 +1,34 @@
|
|
|
1
1
|
import type { PayloadRequest, SanitizedPermissions } from 'payload'
|
|
2
2
|
|
|
3
|
-
import { getAccessResults, UnauthorizedError } from 'payload'
|
|
3
|
+
import { executeAuthStrategies, Forbidden, getAccessResults, UnauthorizedError } from 'payload'
|
|
4
|
+
import { extractBearerToken } from 'payload/shared'
|
|
4
5
|
|
|
5
6
|
import type { AuthorizedMCP, MCPItem } from '../types.js'
|
|
6
7
|
|
|
7
8
|
import { getPluginConfig } from '../utils/getPluginConfig.js'
|
|
9
|
+
import { authenticateLoginToken } from './oauthLoginToken.js'
|
|
8
10
|
|
|
9
11
|
export type GetAuthorizedMCPArgs = {
|
|
12
|
+
/**
|
|
13
|
+
* Whether the request came through the HTTP endpoint, whose response can carry the OAuth
|
|
14
|
+
* challenge and headers from auth strategies. stdio has no response to carry them.
|
|
15
|
+
*/
|
|
16
|
+
isHTTP?: boolean
|
|
10
17
|
overrideAccess: boolean
|
|
11
18
|
req: PayloadRequest
|
|
12
19
|
}
|
|
13
20
|
|
|
14
21
|
/**
|
|
15
|
-
* Authenticates an MCP request and removes items the
|
|
16
|
-
* `overrideAccess` skips Payload and MCP
|
|
22
|
+
* Authenticates an MCP request, rejects users the plugin's `access` denies, and removes items the
|
|
23
|
+
* user cannot access. `overrideAccess` skips Payload and MCP access checks.
|
|
17
24
|
*/
|
|
18
25
|
export const getAuthorizedMCP: (args: GetAuthorizedMCPArgs) => Promise<AuthorizedMCP> = async ({
|
|
26
|
+
isHTTP = false,
|
|
19
27
|
overrideAccess,
|
|
20
28
|
req,
|
|
21
29
|
}) => {
|
|
22
30
|
const pluginConfig = getPluginConfig({ config: req.payload.config })
|
|
31
|
+
const isChallengedWhenSignedOut = isHTTP && Boolean(pluginConfig.oauth)
|
|
23
32
|
|
|
24
33
|
if (pluginConfig.overrideGetAuthorizedMCP) {
|
|
25
34
|
return await pluginConfig.overrideGetAuthorizedMCP({
|
|
@@ -34,30 +43,94 @@ export const getAuthorizedMCP: (args: GetAuthorizedMCPArgs) => Promise<Authorize
|
|
|
34
43
|
const hasAuthorization = headers.has('Authorization')
|
|
35
44
|
|
|
36
45
|
headers.set('DisableAutologin', 'true')
|
|
37
|
-
|
|
46
|
+
// Not `payload.auth()`, which also computes permissions that filterMCPItems computes anyway
|
|
47
|
+
const { responseHeaders, user } = await executeAuthStrategies({
|
|
48
|
+
canSetHeaders: isHTTP,
|
|
49
|
+
headers,
|
|
50
|
+
payload: req.payload,
|
|
51
|
+
req,
|
|
52
|
+
})
|
|
53
|
+
req.user = user
|
|
54
|
+
if (responseHeaders) {
|
|
55
|
+
req.responseHeaders = responseHeaders
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Only bearer tokens that no auth strategy accepted get here, e.g. an OAuth access token.
|
|
59
|
+
// API keys use the `<collection> API-Key <key>` scheme instead of `Bearer`, so they never do.
|
|
60
|
+
const bearerToken = extractBearerToken({ headers })
|
|
61
|
+
// Sealed Payload login tokens from the built-in OAuth server
|
|
62
|
+
if (
|
|
63
|
+
!req.user &&
|
|
64
|
+
bearerToken &&
|
|
65
|
+
pluginConfig.oauth?.type === 'builtin' &&
|
|
66
|
+
!pluginConfig.oauth.issueToken
|
|
67
|
+
) {
|
|
68
|
+
req.user = await authenticateLoginToken({ req, token: bearerToken })
|
|
69
|
+
}
|
|
70
|
+
if (!req.user && bearerToken && pluginConfig.oauth?.authenticate) {
|
|
71
|
+
req.user = await pluginConfig.oauth.authenticate({ req, token: bearerToken })
|
|
72
|
+
}
|
|
38
73
|
|
|
39
|
-
|
|
74
|
+
// With OAuth, the endpoint answers with a challenge that starts the client's sign-in
|
|
75
|
+
if (hasAuthorization && !req.user && !isChallengedWhenSignedOut) {
|
|
40
76
|
throw new UnauthorizedError(req.t)
|
|
41
77
|
}
|
|
42
78
|
}
|
|
43
79
|
|
|
80
|
+
// Signed-out users only get the challenge, so they can't use any MCP items. Skipping the access
|
|
81
|
+
// checks saves work, and access callbacks only see signed-in users.
|
|
82
|
+
if (isChallengedWhenSignedOut && !req.user) {
|
|
83
|
+
return { items: [], overrideAccess }
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// Computed once for the plugin's `access` and every item's
|
|
87
|
+
const permissions = overrideAccess ? undefined : await getAccessResults({ req })
|
|
88
|
+
|
|
89
|
+
if (!overrideAccess && !(await canUseMCP({ permissions, req }))) {
|
|
90
|
+
throw new Forbidden(req.t)
|
|
91
|
+
}
|
|
92
|
+
|
|
44
93
|
return {
|
|
45
94
|
items: await filterMCPItems({
|
|
46
95
|
items: pluginConfig.items,
|
|
47
96
|
overrideAccess,
|
|
97
|
+
permissions,
|
|
48
98
|
req,
|
|
49
99
|
}),
|
|
50
100
|
overrideAccess,
|
|
51
101
|
}
|
|
52
102
|
}
|
|
53
103
|
|
|
104
|
+
/**
|
|
105
|
+
* Runs the plugin's top-level `access`, which decides whether the user can use MCP at all. Doesn't
|
|
106
|
+
* check `overrideAccess`, so callers skip it themselves.
|
|
107
|
+
*/
|
|
108
|
+
export const canUseMCP = async ({
|
|
109
|
+
permissions,
|
|
110
|
+
req,
|
|
111
|
+
}: {
|
|
112
|
+
/** Computed when missing and `access` is set. */
|
|
113
|
+
permissions?: SanitizedPermissions
|
|
114
|
+
req: PayloadRequest
|
|
115
|
+
}): Promise<boolean> => {
|
|
116
|
+
const { access } = getPluginConfig({ config: req.payload.config })
|
|
117
|
+
|
|
118
|
+
return (
|
|
119
|
+
!access ||
|
|
120
|
+
(await access({ permissions: permissions ?? (await getAccessResults({ req })), req }))
|
|
121
|
+
)
|
|
122
|
+
}
|
|
123
|
+
|
|
54
124
|
export const filterMCPItems = async ({
|
|
55
125
|
items,
|
|
56
126
|
overrideAccess,
|
|
127
|
+
permissions: providedPermissions,
|
|
57
128
|
req,
|
|
58
129
|
}: {
|
|
59
130
|
items: MCPItem[]
|
|
60
131
|
overrideAccess: boolean
|
|
132
|
+
/** Computed when missing. */
|
|
133
|
+
permissions?: SanitizedPermissions
|
|
61
134
|
req: PayloadRequest
|
|
62
135
|
}): Promise<MCPItem[]> => {
|
|
63
136
|
// Match Payload core: overrideAccess bypasses access evaluation
|
|
@@ -67,7 +140,7 @@ export const filterMCPItems = async ({
|
|
|
67
140
|
|
|
68
141
|
const authorizedItems: MCPItem[] = []
|
|
69
142
|
|
|
70
|
-
const permissions = await getAccessResults({ req })
|
|
143
|
+
const permissions = providedPermissions ?? (await getAccessResults({ req }))
|
|
71
144
|
|
|
72
145
|
for (const item of items) {
|
|
73
146
|
if (!(await checkItemAccess({ item, permissions, req }))) {
|
|
@@ -95,12 +168,11 @@ const checkItemAccess = async ({
|
|
|
95
168
|
case 'collectionTool':
|
|
96
169
|
return (
|
|
97
170
|
!item.tool.access ||
|
|
98
|
-
(await item.tool.access({
|
|
171
|
+
(await item.tool.access({ slug: item.collectionSlug, permissions, req }))
|
|
99
172
|
)
|
|
100
173
|
case 'globalTool':
|
|
101
174
|
return (
|
|
102
|
-
!item.tool.access ||
|
|
103
|
-
(await item.tool.access({ globalSlug: item.globalSlug, permissions, req }))
|
|
175
|
+
!item.tool.access || (await item.tool.access({ slug: item.globalSlug, permissions, req }))
|
|
104
176
|
)
|
|
105
177
|
case 'prompt':
|
|
106
178
|
return !item.prompt.access || (await item.prompt.access({ permissions, req }))
|
package/src/endpoint/index.ts
CHANGED
|
@@ -3,6 +3,7 @@ import type { PayloadHandler, PayloadRequest } from 'payload'
|
|
|
3
3
|
import {
|
|
4
4
|
createMcpHandler,
|
|
5
5
|
isLegacyRequest,
|
|
6
|
+
readRequestBody,
|
|
6
7
|
WebStandardStreamableHTTPServerTransport,
|
|
7
8
|
} from '@modelcontextprotocol/server'
|
|
8
9
|
import { APIError } from 'payload'
|
|
@@ -10,6 +11,7 @@ import { APIError } from 'payload'
|
|
|
10
11
|
import { buildMcpServer } from '../mcp/buildMcpServer.js'
|
|
11
12
|
import { getPluginConfig } from '../utils/getPluginConfig.js'
|
|
12
13
|
import { getAuthorizedMCP } from './access.js'
|
|
14
|
+
import { getMCPResource, oauthChallenge } from './oauth.js'
|
|
13
15
|
|
|
14
16
|
export const mcpEndpoint: PayloadHandler = async (req) => {
|
|
15
17
|
if (!req.url) {
|
|
@@ -17,6 +19,8 @@ export const mcpEndpoint: PayloadHandler = async (req) => {
|
|
|
17
19
|
}
|
|
18
20
|
|
|
19
21
|
req.payloadAPI = 'MCP' as const
|
|
22
|
+
// Lets auth strategies check that an OAuth access token was issued for this MCP server
|
|
23
|
+
req.context.mcp = { resource: getMCPResource({ req }) }
|
|
20
24
|
|
|
21
25
|
const pluginConfig = getPluginConfig({ config: req.payload.config })
|
|
22
26
|
const overrideAccessParam = new URL(req.url).searchParams.get('overrideAccess')
|
|
@@ -32,15 +36,31 @@ export const mcpEndpoint: PayloadHandler = async (req) => {
|
|
|
32
36
|
throw new APIError('MCP overrideAccess must be "true" or "false".', 400)
|
|
33
37
|
}
|
|
34
38
|
|
|
35
|
-
const authorizedMCP = await getAuthorizedMCP({ overrideAccess, req })
|
|
39
|
+
const authorizedMCP = await getAuthorizedMCP({ isHTTP: true, overrideAccess, req })
|
|
40
|
+
|
|
41
|
+
// Clients like Codex send a GET first to find out where to sign in, so this comes before the
|
|
42
|
+
// GET check
|
|
43
|
+
if (pluginConfig.oauth && !req.user) {
|
|
44
|
+
return oauthChallenge({ req })
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Streamable HTTP's optional server-to-client stream. We don't offer one, so answer 405 per
|
|
48
|
+
// spec, and clients skip it
|
|
49
|
+
if (req.method === 'GET') {
|
|
50
|
+
return new Response(null, { headers: { Allow: 'POST' }, status: 405 })
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const maxRequestBodySize = pluginConfig.mcp?.maxRequestBodySize
|
|
36
54
|
// Payload augments the original web-standard Request in place.
|
|
37
55
|
const mcpRequest = req as PayloadRequest & Request
|
|
56
|
+
const parsedBody = await parseRequestBody({ maxRequestBodySize, request: mcpRequest })
|
|
38
57
|
|
|
39
58
|
// Keep the old JSON-only, stateless behavior because the SDK's 2025 fallback uses SSE.
|
|
40
|
-
if (await isLegacyRequest(mcpRequest)) {
|
|
59
|
+
if (await isLegacyRequest(mcpRequest, parsedBody, { maxRequestBodySize })) {
|
|
41
60
|
const server = buildMcpServer({ authorizedMCP, pluginConfig, req })
|
|
42
61
|
const transport = new WebStandardStreamableHTTPServerTransport({
|
|
43
62
|
enableJsonResponse: true,
|
|
63
|
+
maxRequestBodySize,
|
|
44
64
|
sessionIdGenerator: undefined, // stateless mode
|
|
45
65
|
})
|
|
46
66
|
transport.onerror = (err) => {
|
|
@@ -49,7 +69,7 @@ export const mcpEndpoint: PayloadHandler = async (req) => {
|
|
|
49
69
|
|
|
50
70
|
try {
|
|
51
71
|
await server.connect(transport)
|
|
52
|
-
return await transport.handleRequest(mcpRequest)
|
|
72
|
+
return await transport.handleRequest(mcpRequest, { parsedBody })
|
|
53
73
|
} finally {
|
|
54
74
|
await server.close().catch((err) => {
|
|
55
75
|
req.payload.logger.error({ err, msg: 'Error closing MCP server' })
|
|
@@ -59,6 +79,7 @@ export const mcpEndpoint: PayloadHandler = async (req) => {
|
|
|
59
79
|
|
|
60
80
|
const handler = createMcpHandler(() => buildMcpServer({ authorizedMCP, pluginConfig, req }), {
|
|
61
81
|
legacy: 'reject',
|
|
82
|
+
maxRequestBodySize,
|
|
62
83
|
// SDK subscriptions always use SSE, so disable them to keep every response JSON-only.
|
|
63
84
|
maxSubscriptions: 0,
|
|
64
85
|
onerror: (err) => {
|
|
@@ -68,10 +89,35 @@ export const mcpEndpoint: PayloadHandler = async (req) => {
|
|
|
68
89
|
})
|
|
69
90
|
|
|
70
91
|
try {
|
|
71
|
-
return await handler.fetch(mcpRequest)
|
|
92
|
+
return await handler.fetch(mcpRequest, { parsedBody })
|
|
72
93
|
} finally {
|
|
73
94
|
await handler.close().catch((err) => {
|
|
74
95
|
req.payload.logger.error({ err, msg: 'Error closing modern MCP handler' })
|
|
75
96
|
})
|
|
76
97
|
}
|
|
77
98
|
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Parses a POST body once so the era check and the SDK handler can share it. The SDK
|
|
102
|
+
* skips its size limit for a pre-parsed body, so this reads with the same limit. It reads
|
|
103
|
+
* a clone and returns `undefined` for any body the SDK should reject (too large, unreadable,
|
|
104
|
+
* or not JSON), leaving the original request for the SDK to read and answer.
|
|
105
|
+
*/
|
|
106
|
+
const parseRequestBody = async ({
|
|
107
|
+
maxRequestBodySize,
|
|
108
|
+
request,
|
|
109
|
+
}: {
|
|
110
|
+
maxRequestBodySize?: number
|
|
111
|
+
request: Request
|
|
112
|
+
}): Promise<unknown> => {
|
|
113
|
+
if (request.method.toUpperCase() !== 'POST') {
|
|
114
|
+
return undefined
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
try {
|
|
118
|
+
const body = await readRequestBody(request.clone(), maxRequestBodySize)
|
|
119
|
+
return body.tooLarge ? undefined : JSON.parse(body.text)
|
|
120
|
+
} catch {
|
|
121
|
+
return undefined
|
|
122
|
+
}
|
|
123
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import type { OAuthProtectedResourceMetadata } from '@modelcontextprotocol/server'
|
|
2
|
+
import type { PayloadHandler, PayloadRequest, SanitizedConfig } from 'payload'
|
|
3
|
+
|
|
4
|
+
import {
|
|
5
|
+
bearerAuthChallengeResponse,
|
|
6
|
+
OAuthError,
|
|
7
|
+
OAuthErrorCode,
|
|
8
|
+
} from '@modelcontextprotocol/server'
|
|
9
|
+
import { createPayloadRequest, getPayload } from 'payload'
|
|
10
|
+
import { formatAdminURL, stripTrailingSlash } from 'payload/shared'
|
|
11
|
+
|
|
12
|
+
import { getPluginConfig } from '../utils/getPluginConfig.js'
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Serves the OAuth protected resource metadata (RFC 9728) at `/api/mcp/oauth-protected-resource`.
|
|
16
|
+
* The OAuth challenge links here, so MCP clients find the authorization server without setup.
|
|
17
|
+
*/
|
|
18
|
+
export const oauthProtectedResourceEndpoint: PayloadHandler = (req) => getMetadataResponse({ req })
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Serves the same metadata for clients that ignore the challenge's link and only look at
|
|
22
|
+
* `/.well-known/oauth-protected-resource`. Mount it at the site root, e.g. in Next.js at
|
|
23
|
+
* `app/.well-known/oauth-protected-resource/[[...path]]/route.ts`:
|
|
24
|
+
*
|
|
25
|
+
* ```ts
|
|
26
|
+
* import config from '@payload-config'
|
|
27
|
+
* import { oauthProtectedResourceHandler } from '@payloadcms/plugin-mcp'
|
|
28
|
+
*
|
|
29
|
+
* export const GET = oauthProtectedResourceHandler({ config })
|
|
30
|
+
* ```
|
|
31
|
+
*/
|
|
32
|
+
export const oauthProtectedResourceHandler =
|
|
33
|
+
({ config }: { config: Promise<SanitizedConfig> | SanitizedConfig }) =>
|
|
34
|
+
async (request: Request): Promise<Response> =>
|
|
35
|
+
getMetadataResponse({
|
|
36
|
+
req: await createPayloadRequest({ payload: await getPayload({ config }), req: request }),
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Answers an unauthenticated MCP request with a challenge linking to the protected resource
|
|
41
|
+
* metadata, which starts the client's OAuth flow.
|
|
42
|
+
*/
|
|
43
|
+
export const oauthChallenge = ({ req }: { req: PayloadRequest }): Response => {
|
|
44
|
+
const { oauth } = getPluginConfig({ config: req.payload.config })
|
|
45
|
+
const response = bearerAuthChallengeResponse(
|
|
46
|
+
new OAuthError(OAuthErrorCode.InvalidToken, req.t('error:unauthorized')),
|
|
47
|
+
{
|
|
48
|
+
requiredScopes: oauth?.type === 'external' ? oauth.scopes : undefined,
|
|
49
|
+
resourceMetadataUrl: `${getMCPResource({ req })}/oauth-protected-resource`,
|
|
50
|
+
},
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
// Lets browser-based MCP clients read the challenge, when Payload's `cors` setting allows them
|
|
54
|
+
response.headers.set('Access-Control-Expose-Headers', 'WWW-Authenticate')
|
|
55
|
+
|
|
56
|
+
return response
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* The MCP endpoint's address, as advertised in the metadata's `resource`. The metadata link and
|
|
61
|
+
* the built-in authorization server's issuer are based on it. Clients send it when they sign in,
|
|
62
|
+
* and authorization servers that support it put it in the access token's audience.
|
|
63
|
+
*/
|
|
64
|
+
export const getMCPResource = ({ req }: { req: PayloadRequest }): string => {
|
|
65
|
+
const { config } = req.payload
|
|
66
|
+
const resource = getPluginConfig({ config }).oauth?.resource
|
|
67
|
+
|
|
68
|
+
if (typeof resource === 'function') {
|
|
69
|
+
return resource({ req })
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
if (resource) {
|
|
73
|
+
return resource
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// Without the slash Next.js's `trailingSlash` would add, since the metadata link appends to it
|
|
77
|
+
const path = stripTrailingSlash(formatAdminURL({ apiRoute: config.routes.api, path: '/mcp' }))
|
|
78
|
+
|
|
79
|
+
return new URL(path, config.serverURL || req.url).href
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const getMetadataResponse = async ({ req }: { req: PayloadRequest }): Promise<Response> => {
|
|
83
|
+
const { config } = req.payload
|
|
84
|
+
const { oauth } = getPluginConfig({ config })
|
|
85
|
+
|
|
86
|
+
if (!oauth) {
|
|
87
|
+
return new Response(null, { status: 404 })
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const resource = getMCPResource({ req })
|
|
91
|
+
|
|
92
|
+
return Response.json(
|
|
93
|
+
{
|
|
94
|
+
authorization_servers:
|
|
95
|
+
oauth.type === 'builtin'
|
|
96
|
+
? [`${resource}/oauth`]
|
|
97
|
+
: typeof oauth.authorizationServers === 'function'
|
|
98
|
+
? await oauth.authorizationServers({ req })
|
|
99
|
+
: oauth.authorizationServers,
|
|
100
|
+
bearer_methods_supported: ['header'],
|
|
101
|
+
resource,
|
|
102
|
+
scopes_supported: oauth.type === 'external' ? oauth.scopes : undefined,
|
|
103
|
+
} satisfies OAuthProtectedResourceMetadata,
|
|
104
|
+
// Public document, readable by browser-based MCP clients on any origin. Not cached, since its
|
|
105
|
+
// URLs can depend on the request.
|
|
106
|
+
{ headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'no-store' } },
|
|
107
|
+
)
|
|
108
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import type { PayloadRequest } from 'payload'
|
|
2
|
+
|
|
3
|
+
import { APIError, createAuthToken, executeAuthStrategies, redeemRefreshToken } from 'payload'
|
|
4
|
+
|
|
5
|
+
import type { MCPOAuthTokens } from '../types.js'
|
|
6
|
+
|
|
7
|
+
import { seal, unseal } from '../utils/seal.js'
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The default `issueToken`: a Payload login token, sealed so it only works for MCP, where
|
|
11
|
+
* `authenticateLoginToken` unseals it. Otherwise an MCP client could use it as the user's admin
|
|
12
|
+
* panel login. When the collection uses sessions, the client also gets a refresh token.
|
|
13
|
+
*/
|
|
14
|
+
export const issueLoginToken = async ({
|
|
15
|
+
client,
|
|
16
|
+
req,
|
|
17
|
+
}: {
|
|
18
|
+
client: { name: string; redirectURI: string }
|
|
19
|
+
req: PayloadRequest
|
|
20
|
+
}): Promise<MCPOAuthTokens> => {
|
|
21
|
+
const collectionConfig = req.payload.collections[req.user!.collection]!.config
|
|
22
|
+
|
|
23
|
+
if (collectionConfig.auth.disableLocalStrategy) {
|
|
24
|
+
throw new APIError(
|
|
25
|
+
`MCP clients can't get Payload login tokens for the "${collectionConfig.slug}" collection because its local strategy is disabled. Pass oauth.issueToken to the MCP plugin.`,
|
|
26
|
+
)
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// The full document, like the one a password login starts its session on
|
|
30
|
+
const user = (await req.payload.db.findOne<NonNullable<PayloadRequest['user']>>({
|
|
31
|
+
collection: collectionConfig.slug,
|
|
32
|
+
req,
|
|
33
|
+
where: { id: { equals: req.user!.id } },
|
|
34
|
+
}))!
|
|
35
|
+
|
|
36
|
+
const { refreshToken, token } = await createAuthToken({
|
|
37
|
+
type: 'mcp',
|
|
38
|
+
collectionConfig,
|
|
39
|
+
// App schemes like `com.example.app:/callback` have no host
|
|
40
|
+
email: user.email!,
|
|
41
|
+
label: client.name,
|
|
42
|
+
metadata: { redirectHost: new URL(client.redirectURI).host || client.redirectURI },
|
|
43
|
+
req,
|
|
44
|
+
shouldCreateRefreshToken: true,
|
|
45
|
+
user,
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
return {
|
|
49
|
+
accessToken: sealLoginToken({ req, token }),
|
|
50
|
+
expiresIn: collectionConfig.auth.tokenExpiration,
|
|
51
|
+
refreshToken,
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** The default `refreshToken`. Payload logs out the session when a refresh token is reused. */
|
|
56
|
+
export const refreshLoginToken = async ({
|
|
57
|
+
refreshToken,
|
|
58
|
+
req,
|
|
59
|
+
reuseInterval,
|
|
60
|
+
}: {
|
|
61
|
+
refreshToken: string
|
|
62
|
+
req: PayloadRequest
|
|
63
|
+
/** See `redeemRefreshToken`. */
|
|
64
|
+
reuseInterval?: number
|
|
65
|
+
}): Promise<MCPOAuthTokens | null> => {
|
|
66
|
+
const refreshed = await redeemRefreshToken({ refreshToken, req, reuseInterval })
|
|
67
|
+
|
|
68
|
+
return (
|
|
69
|
+
refreshed && {
|
|
70
|
+
accessToken: sealLoginToken({ req, token: refreshed.token }),
|
|
71
|
+
expiresIn: refreshed.collectionConfig.auth.tokenExpiration,
|
|
72
|
+
refreshToken: refreshed.refreshToken,
|
|
73
|
+
}
|
|
74
|
+
)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Finds the user of an MCP request's access token from `issueLoginToken`. */
|
|
78
|
+
export const authenticateLoginToken = async ({
|
|
79
|
+
req,
|
|
80
|
+
token,
|
|
81
|
+
}: {
|
|
82
|
+
req: PayloadRequest
|
|
83
|
+
token: string
|
|
84
|
+
}): Promise<PayloadRequest['user']> => {
|
|
85
|
+
const loginToken = unseal<{ token: string }>({ type: 'access', req, value: token })
|
|
86
|
+
|
|
87
|
+
if (!loginToken) {
|
|
88
|
+
return null
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const headers = new Headers({
|
|
92
|
+
Authorization: `JWT ${loginToken.token}`,
|
|
93
|
+
DisableAutologin: 'true',
|
|
94
|
+
})
|
|
95
|
+
|
|
96
|
+
return (await executeAuthStrategies({ headers, payload: req.payload, req })).user
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const sealLoginToken = ({ req, token }: { req: PayloadRequest; token: string }): string =>
|
|
100
|
+
seal({ type: 'access', data: { token }, req })
|