@payloadcms/plugin-mcp 4.0.0-internal.21664f3 → 4.0.0-internal.22d1431
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.map +1 -1
- package/dist/endpoint/access.js +25 -5
- package/dist/endpoint/access.js.map +1 -1
- package/dist/endpoint/index.d.ts.map +1 -1
- package/dist/endpoint/index.js +46 -4
- package/dist/endpoint/index.js.map +1 -1
- package/dist/endpoint/oauth.d.ts +39 -0
- package/dist/endpoint/oauth.d.ts.map +1 -0
- package/dist/endpoint/oauth.js +94 -0
- package/dist/endpoint/oauth.js.map +1 -0
- package/dist/endpoint/oauthLoginToken.d.ts +21 -0
- package/dist/endpoint/oauthLoginToken.d.ts.map +1 -0
- package/dist/endpoint/oauthLoginToken.js +79 -0
- package/dist/endpoint/oauthLoginToken.js.map +1 -0
- package/dist/endpoint/oauthServer.d.ts +12 -0
- package/dist/endpoint/oauthServer.d.ts.map +1 -0
- package/dist/endpoint/oauthServer.js +362 -0
- package/dist/endpoint/oauthServer.js.map +1 -0
- package/dist/index.d.ts +10 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +15 -2
- 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 +1 -1
- package/dist/mcp/builtin/collections/createTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/createTool.js +104 -63
- 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 +44 -43
- 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 -13
- package/dist/mcp/builtin/collections/fileInput.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/fileInput.js +52 -64
- 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 +33 -16
- 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 +58 -90
- package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
- package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts +2 -0
- package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts.map +1 -0
- package/dist/mcp/builtin/collections/uploadInstructionsTool.js +55 -0
- package/dist/mcp/builtin/collections/uploadInstructionsTool.js.map +1 -0
- 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/builtinTools.d.ts +6 -0
- package/dist/mcp/builtinTools.d.ts.map +1 -1
- package/dist/mcp/builtinTools.js +9 -3
- package/dist/mcp/builtinTools.js.map +1 -1
- package/dist/mcp/sanitizeMCPConfig.d.ts.map +1 -1
- package/dist/mcp/sanitizeMCPConfig.js +7 -1
- package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
- package/dist/stdio.d.ts.map +1 -1
- package/dist/stdio.js +6 -4
- package/dist/stdio.js.map +1 -1
- package/dist/types.d.ts +96 -7
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/utils/seal.d.ts +18 -0
- package/dist/utils/seal.d.ts.map +1 -0
- package/dist/utils/seal.js +27 -0
- package/dist/utils/seal.js.map +1 -0
- package/dist/utils/toStandardSchema.js.map +1 -1
- package/package.json +23 -28
- package/src/endpoint/access.ts +24 -6
- package/src/endpoint/index.ts +41 -3
- package/src/endpoint/oauth.ts +92 -0
- package/src/endpoint/oauthLoginToken.ts +91 -0
- package/src/endpoint/oauthServer.ts +396 -0
- package/src/index.ts +40 -5
- 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 +108 -86
- package/src/mcp/builtin/collections/deleteTool.ts +37 -65
- package/src/mcp/builtin/collections/duplicateTool.ts +36 -86
- package/src/mcp/builtin/collections/fileInput.spec.ts +20 -6
- package/src/mcp/builtin/collections/fileInput.ts +64 -76
- 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 +28 -13
- package/src/mcp/builtin/collections/restoreVersionTool.ts +15 -57
- package/src/mcp/builtin/collections/updateTool.ts +57 -111
- package/src/mcp/builtin/collections/uploadInstructionsTool.ts +64 -0
- 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/builtinTools.ts +9 -2
- package/src/mcp/sanitizeMCPConfig.ts +5 -1
- package/src/stdio.ts +4 -3
- package/src/types.ts +98 -7
- package/src/utils/seal.ts +46 -0
- package/src/utils/toStandardSchema.ts +1 -1
- package/dist/mcp/builtin/collections/fileInput.spec.js +0 -72
- 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
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
OAuthClientInformationFull,
|
|
3
|
+
OAuthTokens,
|
|
4
|
+
OpenIdProviderDiscoveryMetadata,
|
|
5
|
+
} from '@modelcontextprotocol/server'
|
|
6
|
+
import type { Endpoint, PayloadHandler, PayloadRequest } from 'payload'
|
|
7
|
+
|
|
8
|
+
import { OAuthErrorCode } from '@modelcontextprotocol/server'
|
|
9
|
+
import { createHash } from 'crypto'
|
|
10
|
+
import { formatAdminURL } from 'payload/shared'
|
|
11
|
+
|
|
12
|
+
import type { MCPBuiltinOAuthConfig, MCPOAuthTokens } from '../types.js'
|
|
13
|
+
|
|
14
|
+
import { getPluginConfig } from '../utils/getPluginConfig.js'
|
|
15
|
+
import { seal, unseal } from '../utils/seal.js'
|
|
16
|
+
import { getMCPURL } from './oauth.js'
|
|
17
|
+
import { issueLoginToken, refreshLoginToken } from './oauthLoginToken.js'
|
|
18
|
+
|
|
19
|
+
type Client = { name: string; redirectURIs: string[] }
|
|
20
|
+
|
|
21
|
+
type Consent = {
|
|
22
|
+
clientID: string
|
|
23
|
+
codeChallenge: string
|
|
24
|
+
collection: string
|
|
25
|
+
redirectURI: string
|
|
26
|
+
state: null | string
|
|
27
|
+
userID: number | string
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
type Code = {
|
|
31
|
+
clientID: string
|
|
32
|
+
codeChallenge: string
|
|
33
|
+
redirectURI: string
|
|
34
|
+
tokens: MCPOAuthTokens
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
type RefreshToken = {
|
|
38
|
+
clientID: string
|
|
39
|
+
refreshToken: string
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Turns Payload into the OAuth authorization server for MCP clients when `oauth.type` is
|
|
44
|
+
* `'builtin'`. Clients register, the user allows them after logging in to the admin panel, and
|
|
45
|
+
* the client receives the tokens `issueToken` creates.
|
|
46
|
+
*
|
|
47
|
+
* Clients, consent forms, authorization codes, and refresh tokens are encrypted and handed to the
|
|
48
|
+
* client instead of being stored. Only the default tokens write to the database, to the user's
|
|
49
|
+
* login sessions.
|
|
50
|
+
*/
|
|
51
|
+
export const oauthServerEndpoints: Endpoint[] = [
|
|
52
|
+
{
|
|
53
|
+
disableAuth: true,
|
|
54
|
+
handler: (req) => withIssuer(req, (issuer) => metadataResponse(issuer)),
|
|
55
|
+
method: 'get',
|
|
56
|
+
// OpenID discovery is the only metadata location MCP clients check below the issuer's path,
|
|
57
|
+
// which lets this work under /api without a route at the site root
|
|
58
|
+
path: '/mcp/oauth/.well-known/openid-configuration',
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
disableAuth: true,
|
|
62
|
+
handler: (req) => withIssuer(req, () => Response.json({ keys: [] })),
|
|
63
|
+
method: 'get',
|
|
64
|
+
path: '/mcp/oauth/jwks',
|
|
65
|
+
},
|
|
66
|
+
{
|
|
67
|
+
disableAuth: true,
|
|
68
|
+
handler: (req) => withIssuer(req, () => register(req)),
|
|
69
|
+
method: 'post',
|
|
70
|
+
path: '/mcp/oauth/register',
|
|
71
|
+
},
|
|
72
|
+
{
|
|
73
|
+
handler: (req) => withIssuer(req, () => authorize(req)),
|
|
74
|
+
method: 'get',
|
|
75
|
+
path: '/mcp/oauth/authorize',
|
|
76
|
+
},
|
|
77
|
+
{
|
|
78
|
+
handler: (req) => withIssuer(req, () => approve(req)),
|
|
79
|
+
method: 'post',
|
|
80
|
+
path: '/mcp/oauth/authorize',
|
|
81
|
+
},
|
|
82
|
+
{
|
|
83
|
+
disableAuth: true,
|
|
84
|
+
handler: (req) => withIssuer(req, () => token(req)),
|
|
85
|
+
method: 'post',
|
|
86
|
+
path: '/mcp/oauth/token',
|
|
87
|
+
},
|
|
88
|
+
]
|
|
89
|
+
|
|
90
|
+
/** The authorization server URL, or `undefined` when Payload isn't the authorization server. */
|
|
91
|
+
const getIssuer = (req: PayloadRequest): string | undefined =>
|
|
92
|
+
getPluginConfig({ config: req.payload.config }).oauth?.type === 'builtin'
|
|
93
|
+
? `${getMCPURL({ config: req.payload.config, url: req.url! })}/oauth`
|
|
94
|
+
: undefined
|
|
95
|
+
|
|
96
|
+
const withIssuer = (
|
|
97
|
+
req: PayloadRequest,
|
|
98
|
+
handler: (issuer: string) => Promise<Response> | Response,
|
|
99
|
+
): Promise<Response> | Response => {
|
|
100
|
+
const issuer = getIssuer(req)
|
|
101
|
+
return issuer ? handler(issuer) : new Response(null, { status: 404 })
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* The user logged in to this browser, who can allow MCP clients. Tokens and API keys in the
|
|
106
|
+
* `Authorization` header can't, or an MCP client could use its access token to approve itself a
|
|
107
|
+
* new, separate login.
|
|
108
|
+
*/
|
|
109
|
+
const getBrowserUser = (req: PayloadRequest): PayloadRequest['user'] =>
|
|
110
|
+
req.headers.has('Authorization') ? null : req.user
|
|
111
|
+
|
|
112
|
+
const metadataResponse = (issuer: string): Response =>
|
|
113
|
+
Response.json(
|
|
114
|
+
{
|
|
115
|
+
authorization_endpoint: `${issuer}/authorize`,
|
|
116
|
+
code_challenge_methods_supported: ['S256'],
|
|
117
|
+
grant_types_supported: ['authorization_code', 'refresh_token'],
|
|
118
|
+
// Required by OpenID discovery. No ID tokens are issued.
|
|
119
|
+
id_token_signing_alg_values_supported: ['RS256'],
|
|
120
|
+
issuer,
|
|
121
|
+
jwks_uri: `${issuer}/jwks`,
|
|
122
|
+
registration_endpoint: `${issuer}/register`,
|
|
123
|
+
response_types_supported: ['code'],
|
|
124
|
+
subject_types_supported: ['public'],
|
|
125
|
+
token_endpoint: `${issuer}/token`,
|
|
126
|
+
token_endpoint_auth_methods_supported: ['none'],
|
|
127
|
+
} satisfies OpenIdProviderDiscoveryMetadata,
|
|
128
|
+
// Not cached, since without `serverURL` its URLs come from the request
|
|
129
|
+
{ headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'no-store' } },
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
const register: PayloadHandler = async (req) => {
|
|
133
|
+
const { client_name, redirect_uris } = await req.json!().catch(() => ({}))
|
|
134
|
+
|
|
135
|
+
if (
|
|
136
|
+
!Array.isArray(redirect_uris) ||
|
|
137
|
+
!redirect_uris.length ||
|
|
138
|
+
!redirect_uris.every(
|
|
139
|
+
(uri) => typeof uri === 'string' && URL.canParse(uri) && !uri.includes('#'),
|
|
140
|
+
)
|
|
141
|
+
) {
|
|
142
|
+
return Response.json({ error: OAuthErrorCode.InvalidRedirectUri }, { status: 400 })
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const client: Client = {
|
|
146
|
+
name: typeof client_name === 'string' ? client_name : 'An MCP client',
|
|
147
|
+
redirectURIs: redirect_uris,
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
return Response.json(
|
|
151
|
+
{
|
|
152
|
+
client_id: seal({ type: 'client', data: client, req }),
|
|
153
|
+
client_name: client.name,
|
|
154
|
+
grant_types: ['authorization_code', 'refresh_token'],
|
|
155
|
+
redirect_uris: client.redirectURIs,
|
|
156
|
+
response_types: ['code'],
|
|
157
|
+
token_endpoint_auth_method: 'none',
|
|
158
|
+
} satisfies OAuthClientInformationFull,
|
|
159
|
+
{ status: 201 },
|
|
160
|
+
)
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const authorize: PayloadHandler = (req) => {
|
|
164
|
+
const url = new URL(req.url!)
|
|
165
|
+
const params = url.searchParams
|
|
166
|
+
const clientID = params.get('client_id')
|
|
167
|
+
const client = unseal<Client>({ type: 'client', req, value: clientID })
|
|
168
|
+
const redirectURI = params.get('redirect_uri')
|
|
169
|
+
|
|
170
|
+
// Never redirect to an address the client didn't register
|
|
171
|
+
if (!client || !redirectURI || !client.redirectURIs.includes(redirectURI)) {
|
|
172
|
+
return page({
|
|
173
|
+
content: '<p>Start the sign-in again from your MCP client.</p>',
|
|
174
|
+
status: 400,
|
|
175
|
+
title: 'This sign-in link is invalid',
|
|
176
|
+
})
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const state = params.get('state')
|
|
180
|
+
const codeChallenge = params.get('code_challenge')
|
|
181
|
+
|
|
182
|
+
if (
|
|
183
|
+
params.get('response_type') !== 'code' ||
|
|
184
|
+
params.get('code_challenge_method') !== 'S256' ||
|
|
185
|
+
!codeChallenge
|
|
186
|
+
) {
|
|
187
|
+
return redirect({ params: { error: OAuthErrorCode.InvalidRequest, state }, redirectURI })
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const user = getBrowserUser(req)
|
|
191
|
+
|
|
192
|
+
if (!user) {
|
|
193
|
+
const loginURL = formatAdminURL({ adminRoute: req.payload.config.routes.admin, path: '/login' })
|
|
194
|
+
|
|
195
|
+
return new Response(null, {
|
|
196
|
+
headers: {
|
|
197
|
+
Location: `${loginURL}?redirect=${encodeURIComponent(url.pathname + url.search)}`,
|
|
198
|
+
},
|
|
199
|
+
status: 302,
|
|
200
|
+
})
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const consent: Consent = {
|
|
204
|
+
clientID: clientID!,
|
|
205
|
+
codeChallenge,
|
|
206
|
+
collection: user.collection,
|
|
207
|
+
redirectURI,
|
|
208
|
+
state,
|
|
209
|
+
userID: user.id,
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
return page({
|
|
213
|
+
content: `<p>It will be able to use this app's MCP tools as ${escapeHTML(String(user.email ?? user.id))}, and you will return to ${escapeHTML(new URL(redirectURI).host || redirectURI)}.</p>
|
|
214
|
+
<form method="post">
|
|
215
|
+
<input name="consent" type="hidden" value="${seal({ type: 'consent', data: consent, expiresIn: 20 * 60 * 60, req })}">
|
|
216
|
+
<button name="decision" type="submit" value="allow">Allow</button>
|
|
217
|
+
<button name="decision" type="submit" value="deny">Deny</button>
|
|
218
|
+
</form>`,
|
|
219
|
+
status: 200,
|
|
220
|
+
title: `Allow ${client.name} to use your account?`,
|
|
221
|
+
})
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const approve: PayloadHandler = async (req) => {
|
|
225
|
+
const form = new URLSearchParams(await req.text!())
|
|
226
|
+
const consent = unseal<Consent>({ type: 'consent', req, value: form.get('consent') })
|
|
227
|
+
const user = getBrowserUser(req)
|
|
228
|
+
|
|
229
|
+
// The form is only valid for the user it was shown to
|
|
230
|
+
if (!consent || user?.id !== consent.userID || user.collection !== consent.collection) {
|
|
231
|
+
return page({
|
|
232
|
+
content: '<p>Start the sign-in again from your MCP client.</p>',
|
|
233
|
+
status: 400,
|
|
234
|
+
title: 'This sign-in request expired',
|
|
235
|
+
})
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const { clientID, codeChallenge, redirectURI, state } = consent
|
|
239
|
+
|
|
240
|
+
if (form.get('decision') !== 'allow') {
|
|
241
|
+
return redirect({ params: { error: OAuthErrorCode.AccessDenied, state }, redirectURI })
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
const code: Code = {
|
|
245
|
+
clientID,
|
|
246
|
+
codeChallenge,
|
|
247
|
+
redirectURI,
|
|
248
|
+
tokens: await getTokenHooks(req).issueToken({ req }),
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
return redirect({
|
|
252
|
+
params: { code: seal({ type: 'code', data: code, expiresIn: 60, req }), state },
|
|
253
|
+
redirectURI,
|
|
254
|
+
})
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
const token: PayloadHandler = async (req) => {
|
|
258
|
+
const form = new URLSearchParams(await req.text!())
|
|
259
|
+
const clientID = form.get('client_id')
|
|
260
|
+
const tokens =
|
|
261
|
+
clientID &&
|
|
262
|
+
(form.get('grant_type') === 'refresh_token'
|
|
263
|
+
? await refresh({ clientID, form, req })
|
|
264
|
+
: redeemCode({ clientID, form, req }))
|
|
265
|
+
|
|
266
|
+
if (!clientID || !tokens) {
|
|
267
|
+
return Response.json({ error: OAuthErrorCode.InvalidGrant }, { status: 400 })
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
return Response.json(
|
|
271
|
+
{
|
|
272
|
+
access_token: tokens.accessToken,
|
|
273
|
+
expires_in: tokens.expiresIn,
|
|
274
|
+
refresh_token:
|
|
275
|
+
tokens.refreshToken &&
|
|
276
|
+
seal({
|
|
277
|
+
type: 'refresh',
|
|
278
|
+
data: { clientID, refreshToken: tokens.refreshToken } satisfies RefreshToken,
|
|
279
|
+
req,
|
|
280
|
+
}),
|
|
281
|
+
token_type: 'Bearer',
|
|
282
|
+
} satisfies OAuthTokens,
|
|
283
|
+
{ headers: { 'Cache-Control': 'no-store' } },
|
|
284
|
+
)
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
const redeemCode = ({
|
|
288
|
+
clientID,
|
|
289
|
+
form,
|
|
290
|
+
req,
|
|
291
|
+
}: {
|
|
292
|
+
clientID: string
|
|
293
|
+
form: URLSearchParams
|
|
294
|
+
req: PayloadRequest
|
|
295
|
+
}): MCPOAuthTokens | undefined => {
|
|
296
|
+
const code = unseal<Code>({ type: 'code', req, value: form.get('code') })
|
|
297
|
+
|
|
298
|
+
if (
|
|
299
|
+
form.get('grant_type') === 'authorization_code' &&
|
|
300
|
+
code?.clientID === clientID &&
|
|
301
|
+
code.redirectURI === form.get('redirect_uri') &&
|
|
302
|
+
// PKCE: only the client that started the sign-in knows the verifier
|
|
303
|
+
createHash('sha256')
|
|
304
|
+
.update(form.get('code_verifier') ?? '')
|
|
305
|
+
.digest('base64url') === code.codeChallenge
|
|
306
|
+
) {
|
|
307
|
+
return code.tokens
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
const refresh = async ({
|
|
312
|
+
clientID,
|
|
313
|
+
form,
|
|
314
|
+
req,
|
|
315
|
+
}: {
|
|
316
|
+
clientID: string
|
|
317
|
+
form: URLSearchParams
|
|
318
|
+
req: PayloadRequest
|
|
319
|
+
}): Promise<MCPOAuthTokens | null | undefined> => {
|
|
320
|
+
const refreshToken = unseal<RefreshToken>({
|
|
321
|
+
type: 'refresh',
|
|
322
|
+
req,
|
|
323
|
+
value: form.get('refresh_token'),
|
|
324
|
+
})
|
|
325
|
+
|
|
326
|
+
// Only the client a refresh token was issued to can use it
|
|
327
|
+
if (refreshToken?.clientID === clientID) {
|
|
328
|
+
return await getTokenHooks(req).refreshToken?.({
|
|
329
|
+
refreshToken: refreshToken.refreshToken,
|
|
330
|
+
req,
|
|
331
|
+
})
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** `issueToken` and `refreshToken`, or the defaults for Payload login tokens. */
|
|
336
|
+
const getTokenHooks = (req: PayloadRequest) => {
|
|
337
|
+
const oauth = getPluginConfig({ config: req.payload.config }).oauth as MCPBuiltinOAuthConfig
|
|
338
|
+
|
|
339
|
+
return oauth.issueToken
|
|
340
|
+
? { issueToken: oauth.issueToken, refreshToken: oauth.refreshToken }
|
|
341
|
+
: { issueToken: issueLoginToken, refreshToken: refreshLoginToken }
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
const redirect = ({
|
|
345
|
+
params,
|
|
346
|
+
redirectURI,
|
|
347
|
+
}: {
|
|
348
|
+
params: Record<string, null | string>
|
|
349
|
+
redirectURI: string
|
|
350
|
+
}): Response => {
|
|
351
|
+
const location = new URL(redirectURI)
|
|
352
|
+
|
|
353
|
+
for (const [key, value] of Object.entries(params)) {
|
|
354
|
+
if (value) {
|
|
355
|
+
location.searchParams.set(key, value)
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
return new Response(null, { headers: { Location: location.href }, status: 302 })
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
const page = ({
|
|
363
|
+
content,
|
|
364
|
+
status,
|
|
365
|
+
title,
|
|
366
|
+
}: {
|
|
367
|
+
content: string
|
|
368
|
+
status: number
|
|
369
|
+
title: string
|
|
370
|
+
}): Response =>
|
|
371
|
+
new Response(
|
|
372
|
+
`<!doctype html>
|
|
373
|
+
<html lang="en">
|
|
374
|
+
<head>
|
|
375
|
+
<meta charset="utf-8">
|
|
376
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
377
|
+
<title>${escapeHTML(title)}</title>
|
|
378
|
+
<style>
|
|
379
|
+
body { font-family: system-ui, sans-serif; margin: 4rem auto; max-width: 32rem; overflow-wrap: anywhere; padding: 0 1rem }
|
|
380
|
+
button { font: inherit; margin-inline-end: 0.5rem; padding: 0.5rem 1rem }
|
|
381
|
+
</style>
|
|
382
|
+
</head>
|
|
383
|
+
<body><h1>${escapeHTML(title)}</h1>${content}</body>
|
|
384
|
+
</html>`,
|
|
385
|
+
{
|
|
386
|
+
headers: {
|
|
387
|
+
// Stop other sites from framing the page to trick users into clicking Allow
|
|
388
|
+
'Content-Security-Policy': "frame-ancestors 'none'",
|
|
389
|
+
'Content-Type': 'text/html; charset=utf-8',
|
|
390
|
+
},
|
|
391
|
+
status,
|
|
392
|
+
},
|
|
393
|
+
)
|
|
394
|
+
|
|
395
|
+
const escapeHTML = (value: string): string =>
|
|
396
|
+
value.replace(/[&<>"']/g, (character) => `&#${character.charCodeAt(0)};`)
|
package/src/index.ts
CHANGED
|
@@ -1,8 +1,18 @@
|
|
|
1
1
|
import { definePlugin } from 'payload'
|
|
2
2
|
|
|
3
|
-
import type {
|
|
3
|
+
import type {
|
|
4
|
+
AuthorizedMCP,
|
|
5
|
+
MCPBuiltinOAuthConfig,
|
|
6
|
+
MCPExternalOAuthConfig,
|
|
7
|
+
MCPOAuthConfig,
|
|
8
|
+
MCPOAuthTokens,
|
|
9
|
+
MCPPluginConfig,
|
|
10
|
+
SanitizedMCPPluginConfig,
|
|
11
|
+
} from './types.js'
|
|
4
12
|
|
|
5
13
|
import { mcpEndpoint } from './endpoint/index.js'
|
|
14
|
+
import { oauthProtectedResourceEndpoint } from './endpoint/oauth.js'
|
|
15
|
+
import { oauthServerEndpoints } from './endpoint/oauthServer.js'
|
|
6
16
|
import { sanitizeMCPConfig } from './mcp/sanitizeMCPConfig.js'
|
|
7
17
|
|
|
8
18
|
declare module 'payload' {
|
|
@@ -13,11 +23,27 @@ declare module 'payload' {
|
|
|
13
23
|
/** After the plugin's `plugin` callback runs, `options` holds the sanitized config. */
|
|
14
24
|
'@payloadcms/plugin-mcp': MCPPluginConfig
|
|
15
25
|
}
|
|
26
|
+
export interface RequestContext {
|
|
27
|
+
/** Set on MCP requests before they're authenticated. */
|
|
28
|
+
mcp?: {
|
|
29
|
+
/** The MCP endpoint's address, which OAuth access tokens for MCP are issued for. */
|
|
30
|
+
resource: string
|
|
31
|
+
}
|
|
32
|
+
}
|
|
16
33
|
}
|
|
17
34
|
|
|
18
|
-
export type {
|
|
35
|
+
export type {
|
|
36
|
+
AuthorizedMCP,
|
|
37
|
+
MCPBuiltinOAuthConfig,
|
|
38
|
+
MCPExternalOAuthConfig,
|
|
39
|
+
MCPOAuthConfig,
|
|
40
|
+
MCPOAuthTokens,
|
|
41
|
+
MCPPluginConfig,
|
|
42
|
+
SanitizedMCPPluginConfig,
|
|
43
|
+
}
|
|
19
44
|
|
|
20
45
|
export { defineCollectionTool, defineGlobalTool, definePrompt, defineTool } from './defineTool.js'
|
|
46
|
+
export { oauthProtectedResourceHandler } from './endpoint/oauth.js'
|
|
21
47
|
|
|
22
48
|
export const mcpPlugin = definePlugin<MCPPluginConfig>({
|
|
23
49
|
slug: '@payloadcms/plugin-mcp',
|
|
@@ -29,7 +55,7 @@ export const mcpPlugin = definePlugin<MCPPluginConfig>({
|
|
|
29
55
|
const registered = plugins['@payloadcms/plugin-mcp']
|
|
30
56
|
if (registered) {
|
|
31
57
|
// @ts-expect-error
|
|
32
|
-
registered.sanitizedOptions = pluginConfig
|
|
58
|
+
registered.sanitizedOptions = pluginConfig
|
|
33
59
|
}
|
|
34
60
|
|
|
35
61
|
if (pluginConfig.disabled) {
|
|
@@ -40,15 +66,24 @@ export const mcpPlugin = definePlugin<MCPPluginConfig>({
|
|
|
40
66
|
...config,
|
|
41
67
|
endpoints: [
|
|
42
68
|
...(config.endpoints ?? []),
|
|
43
|
-
// Payload prefixes /api, so the full path is /api/mcp.
|
|
44
|
-
|
|
69
|
+
// Payload prefixes /api, so the full path is /api/mcp. getAuthorizedMCP authenticates the
|
|
70
|
+
// request with dev auto-login turned off, so Payload doesn't authenticate it first.
|
|
71
|
+
{ disableAuth: true, handler: mcpEndpoint, method: 'post', path: '/mcp' },
|
|
45
72
|
// Streamable HTTP's optional server=>client GET stream. We don't offer
|
|
46
73
|
// one, so answer 405 per spec-— clients then skip it cleanly
|
|
47
74
|
{
|
|
75
|
+
disableAuth: true,
|
|
48
76
|
handler: () => new Response(null, { headers: { Allow: 'POST' }, status: 405 }),
|
|
49
77
|
method: 'get',
|
|
50
78
|
path: '/mcp',
|
|
51
79
|
},
|
|
80
|
+
{
|
|
81
|
+
disableAuth: true,
|
|
82
|
+
handler: oauthProtectedResourceEndpoint,
|
|
83
|
+
method: 'get',
|
|
84
|
+
path: '/mcp/oauth-protected-resource',
|
|
85
|
+
},
|
|
86
|
+
...oauthServerEndpoints,
|
|
52
87
|
],
|
|
53
88
|
}
|
|
54
89
|
},
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
+
import type { PayloadRequest } from 'payload'
|
|
2
|
+
|
|
1
3
|
import { McpServer, type ServerContext } from '@modelcontextprotocol/server'
|
|
2
|
-
import { APIError,
|
|
3
|
-
import { z } from 'zod'
|
|
4
|
+
import { APIError, strictObject, z } from 'payload'
|
|
4
5
|
|
|
5
6
|
import type {
|
|
6
7
|
AuthorizedMCP,
|
|
@@ -24,7 +25,7 @@ import { toStandardSchema } from '../utils/toStandardSchema.js'
|
|
|
24
25
|
*
|
|
25
26
|
* `req` is the request context handlers see. For HTTP it's the live
|
|
26
27
|
* `PayloadRequest` derived from the incoming HTTP request; for stdio it's a
|
|
27
|
-
* synthesized one built via `
|
|
28
|
+
* synthesized one built via `createPayloadRequest`.
|
|
28
29
|
*/
|
|
29
30
|
export const buildMcpServer = ({
|
|
30
31
|
authorizedMCP,
|
|
@@ -35,6 +36,8 @@ export const buildMcpServer = ({
|
|
|
35
36
|
pluginConfig: SanitizedMCPPluginConfig
|
|
36
37
|
req: PayloadRequest
|
|
37
38
|
}): McpServer => {
|
|
39
|
+
z.config(z.locales.en())
|
|
40
|
+
|
|
38
41
|
const serverOptions = pluginConfig.mcp?.serverOptions || {}
|
|
39
42
|
const server = new McpServer(
|
|
40
43
|
{ name: 'Payload MCP Server', version: '1.0.0', ...serverOptions.serverInfo },
|
|
@@ -68,7 +71,7 @@ export const buildMcpServer = ({
|
|
|
68
71
|
|
|
69
72
|
/**
|
|
70
73
|
* Runs a collection/global tool call:
|
|
71
|
-
* - reads `
|
|
74
|
+
* - reads `slug` from the input
|
|
72
75
|
* - runs access control: errors if `authorizedMCP.items` has no entry for this tool + slug
|
|
73
76
|
* - runs the tool handler and finalizes its response
|
|
74
77
|
*/
|
|
@@ -82,16 +85,15 @@ export const buildMcpServer = ({
|
|
|
82
85
|
serverContext: ServerContext
|
|
83
86
|
}): Promise<MCPToolResponse> => {
|
|
84
87
|
const entity = item.type === 'collectionTool' ? 'collection' : 'global'
|
|
85
|
-
const slugKey = item.type === 'collectionTool' ? 'collectionSlug' : 'globalSlug'
|
|
86
88
|
const toolInput = (input ?? {}) as Record<string, unknown>
|
|
87
|
-
const slug = toolInput
|
|
89
|
+
const slug = toolInput.slug as string | undefined
|
|
88
90
|
|
|
89
91
|
if (!slug) {
|
|
90
92
|
return {
|
|
91
93
|
content: [
|
|
92
94
|
{
|
|
93
95
|
type: 'text',
|
|
94
|
-
text: `Error: "${item.mcpName}" requires
|
|
96
|
+
text: `Error: "${item.mcpName}" requires slug. Use getConfigInfo to inspect ${entity} slugs.`,
|
|
95
97
|
},
|
|
96
98
|
],
|
|
97
99
|
isError: true,
|
|
@@ -126,8 +128,8 @@ export const buildMcpServer = ({
|
|
|
126
128
|
serverContext,
|
|
127
129
|
}
|
|
128
130
|
const response = await (match.type === 'collectionTool'
|
|
129
|
-
? match.tool.handler({ ...handlerArgs,
|
|
130
|
-
: match.tool.handler({ ...handlerArgs,
|
|
131
|
+
? match.tool.handler({ ...handlerArgs, slug })
|
|
132
|
+
: match.tool.handler({ ...handlerArgs, slug }))
|
|
131
133
|
|
|
132
134
|
return finalizeToolResponse({
|
|
133
135
|
input: toolInput,
|
|
@@ -149,10 +151,7 @@ export const buildMcpServer = ({
|
|
|
149
151
|
}
|
|
150
152
|
registeredEntityTools.add(item.mcpName)
|
|
151
153
|
|
|
152
|
-
const inputSchema = withSlugInput({
|
|
153
|
-
name: item.type === 'collectionTool' ? 'collectionSlug' : 'globalSlug',
|
|
154
|
-
input: item.tool.input,
|
|
155
|
-
})
|
|
154
|
+
const inputSchema = withSlugInput({ input: item.tool.input })
|
|
156
155
|
|
|
157
156
|
server.registerTool(
|
|
158
157
|
item.mcpName,
|
|
@@ -246,39 +245,50 @@ export const buildMcpServer = ({
|
|
|
246
245
|
return server
|
|
247
246
|
}
|
|
248
247
|
|
|
249
|
-
const withSlugInput = ({
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
}: {
|
|
253
|
-
input?: ToolInputSchema
|
|
254
|
-
name: 'collectionSlug' | 'globalSlug'
|
|
255
|
-
}): ToolInputSchema => {
|
|
256
|
-
const description = name === 'collectionSlug' ? 'The collection slug' : 'The global slug'
|
|
257
|
-
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))
|
|
258
251
|
|
|
259
252
|
if (!input) {
|
|
260
|
-
return
|
|
253
|
+
return strictObject({ slug: slugSchema })
|
|
261
254
|
}
|
|
262
255
|
|
|
263
|
-
if (input
|
|
264
|
-
|
|
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 })
|
|
265
265
|
}
|
|
266
266
|
|
|
267
|
-
|
|
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 {
|
|
268
278
|
properties?: Record<string, JsonSchemaType>
|
|
269
279
|
required?: string[]
|
|
270
280
|
} & JsonSchemaType
|
|
271
281
|
|
|
272
282
|
return {
|
|
273
|
-
...
|
|
283
|
+
...objectSchema,
|
|
274
284
|
type: 'object',
|
|
275
285
|
properties: {
|
|
276
|
-
...
|
|
277
|
-
|
|
286
|
+
...objectSchema.properties,
|
|
287
|
+
slug: {
|
|
278
288
|
type: 'string',
|
|
279
289
|
description,
|
|
280
290
|
},
|
|
281
291
|
},
|
|
282
|
-
required: Array.from(new Set([
|
|
292
|
+
required: Array.from(new Set(['slug', ...(objectSchema.required ?? [])])),
|
|
283
293
|
}
|
|
284
294
|
}
|